path
stringlengths
14
112
content
stringlengths
0
6.32M
size
int64
0
6.32M
max_lines
int64
1
100k
repo_name
stringclasses
2 values
autogenerated
bool
1 class
cosmopolitan/third_party/python/Lib/test/SHIFT_JISX0213.TXT
00 0000 01 0001 02 0002 03 0003 04 0004 05 0005 06 0006 07 0007 08 0008 09 0009 0A 000A 0B 000B 0C 000C 0D 000D 0E 000E 0F 000F 10 0010 11 0011 12 0012 13 0013 14 0014 15 0015 16 0016 17 0017 18 0018 19 0019 1A 001A 1B 001B 1C 001C 1D 001D 1E 001E 1F 001F 20 0020 21 0021 22 0022 23 0023 24 0024 25 0025 26 0026 27 0027 28 0028 29 0029 2A 002A 2B 002B 2C 002C 2D 002D 2E 002E 2F 002F 30 0030 31 0031 32 0032 33 0033 34 0034 35 0035 36 0036 37 0037 38 0038 39 0039 3A 003A 3B 003B 3C 003C 3D 003D 3E 003E 3F 003F 40 0040 41 0041 42 0042 43 0043 44 0044 45 0045 46 0046 47 0047 48 0048 49 0049 4A 004A 4B 004B 4C 004C 4D 004D 4E 004E 4F 004F 50 0050 51 0051 52 0052 53 0053 54 0054 55 0055 56 0056 57 0057 58 0058 59 0059 5A 005A 5B 005B 5C 00A5 5D 005D 5E 005E 5F 005F 60 0060 61 0061 62 0062 63 0063 64 0064 65 0065 66 0066 67 0067 68 0068 69 0069 6A 006A 6B 006B 6C 006C 6D 006D 6E 006E 6F 006F 70 0070 71 0071 72 0072 73 0073 74 0074 75 0075 76 0076 77 0077 78 0078 79 0079 7A 007A 7B 007B 7C 007C 7D 007D 7E 203E 7F 007F 8140 3000 8141 3001 8142 3002 8143 FF0C 8144 FF0E 8145 30FB 8146 FF1A 8147 FF1B 8148 FF1F 8149 FF01 814A 309B 814B 309C 814C 00B4 814D FF40 814E 00A8 814F FF3E 8150 FFE3 8151 FF3F 8152 30FD 8153 30FE 8154 309D 8155 309E 8156 3003 8157 4EDD 8158 3005 8159 3006 815A 3007 815B 30FC 815C 2015 815D 2010 815E FF0F 8160 301C 8161 2016 8162 FF5C 8163 2026 8164 2025 8165 2018 8166 2019 8167 201C 8168 201D 8169 FF08 816A FF09 816B 3014 816C 3015 816D FF3B 816E FF3D 816F FF5B 8170 FF5D 8171 3008 8172 3009 8173 300A 8174 300B 8175 300C 8176 300D 8177 300E 8178 300F 8179 3010 817A 3011 817B FF0B 817C 2212 817D 00B1 817E 00D7 8180 00F7 8181 FF1D 8182 2260 8183 FF1C 8184 FF1E 8185 2266 8186 2267 8187 221E 8188 2234 8189 2642 818A 2640 818B 00B0 818C 2032 818D 2033 818E 2103 818F FFE5 8190 FF04 8191 00A2 8192 00A3 8193 FF05 8194 FF03 8195 FF06 8196 FF0A 8197 FF20 8198 00A7 8199 2606 819A 2605 819B 25CB 819C 25CF 819D 25CE 819E 25C7 819F 25C6 81A0 25A1 81A1 25A0 81A2 25B3 81A3 25B2 81A4 25BD 81A5 25BC 81A6 203B 81A7 3012 81A8 2192 81A9 2190 81AA 2191 81AB 2193 81AC 3013 81AD FF07 81AE FF02 81AF FF0D 81B1 3033 81B2 3034 81B3 3035 81B4 303B 81B5 303C 81B6 30FF 81B7 309F 81B8 2208 81B9 220B 81BA 2286 81BB 2287 81BC 2282 81BD 2283 81BE 222A 81BF 2229 81C0 2284 81C1 2285 81C2 228A 81C3 228B 81C4 2209 81C5 2205 81C6 2305 81C7 2306 81C8 2227 81C9 2228 81CA 00AC 81CB 21D2 81CC 21D4 81CD 2200 81CE 2203 81CF 2295 81D0 2296 81D1 2297 81D2 2225 81D3 2226 81D6 3018 81D7 3019 81D8 3016 81D9 3017 81DA 2220 81DB 22A5 81DC 2312 81DD 2202 81DE 2207 81DF 2261 81E0 2252 81E1 226A 81E2 226B 81E3 221A 81E4 223D 81E5 221D 81E6 2235 81E7 222B 81E8 222C 81E9 2262 81EA 2243 81EB 2245 81EC 2248 81ED 2276 81EE 2277 81EF 2194 81F0 212B 81F1 2030 81F2 266F 81F3 266D 81F4 266A 81F5 2020 81F6 2021 81F7 00B6 81F8 266E 81F9 266B 81FA 266C 81FB 2669 81FC 25EF 8240 25B7 8241 25B6 8242 25C1 8243 25C0 8244 2197 8245 2198 8246 2196 8247 2199 8248 21C4 8249 21E8 824A 21E6 824B 21E7 824C 21E9 824D 2934 824E 2935 824F FF10 8250 FF11 8251 FF12 8252 FF13 8253 FF14 8254 FF15 8255 FF16 8256 FF17 8257 FF18 8258 FF19 825A 25C9 825B 303D 825C FE46 825D FE45 825E 25E6 825F 2022 8260 FF21 8261 FF22 8262 FF23 8263 FF24 8264 FF25 8265 FF26 8266 FF27 8267 FF28 8268 FF29 8269 FF2A 826A FF2B 826B FF2C 826C FF2D 826D FF2E 826E FF2F 826F FF30 8270 FF31 8271 FF32 8272 FF33 8273 FF34 8274 FF35 8275 FF36 8276 FF37 8277 FF38 8278 FF39 8279 FF3A 827A 2213 827B 2135 827C 210F 827D 33CB 827E 2113 8280 2127 8281 FF41 8282 FF42 8283 FF43 8284 FF44 8285 FF45 8286 FF46 8287 FF47 8288 FF48 8289 FF49 828A FF4A 828B FF4B 828C FF4C 828D FF4D 828E FF4E 828F FF4F 8290 FF50 8291 FF51 8292 FF52 8293 FF53 8294 FF54 8295 FF55 8296 FF56 8297 FF57 8298 FF58 8299 FF59 829A FF5A 829B 30A0 829C 2013 829D 29FA 829E 29FB 829F 3041 82A0 3042 82A1 3043 82A2 3044 82A3 3045 82A4 3046 82A5 3047 82A6 3048 82A7 3049 82A8 304A 82A9 304B 82AA 304C 82AB 304D 82AC 304E 82AD 304F 82AE 3050 82AF 3051 82B0 3052 82B1 3053 82B2 3054 82B3 3055 82B4 3056 82B5 3057 82B6 3058 82B7 3059 82B8 305A 82B9 305B 82BA 305C 82BB 305D 82BC 305E 82BD 305F 82BE 3060 82BF 3061 82C0 3062 82C1 3063 82C2 3064 82C3 3065 82C4 3066 82C5 3067 82C6 3068 82C7 3069 82C8 306A 82C9 306B 82CA 306C 82CB 306D 82CC 306E 82CD 306F 82CE 3070 82CF 3071 82D0 3072 82D1 3073 82D2 3074 82D3 3075 82D4 3076 82D5 3077 82D6 3078 82D7 3079 82D8 307A 82D9 307B 82DA 307C 82DB 307D 82DC 307E 82DD 307F 82DE 3080 82DF 3081 82E0 3082 82E1 3083 82E2 3084 82E3 3085 82E4 3086 82E5 3087 82E6 3088 82E7 3089 82E8 308A 82E9 308B 82EA 308C 82EB 308D 82EC 308E 82ED 308F 82EE 3090 82EF 3091 82F0 3092 82F1 3093 82F2 3094 82F3 3095 82F4 3096 82F5 304B 309A 82F6 304D 309A 82F7 304F 309A 82F8 3051 309A 82F9 3053 309A 8340 30A1 8341 30A2 8342 30A3 8343 30A4 8344 30A5 8345 30A6 8346 30A7 8347 30A8 8348 30A9 8349 30AA 834A 30AB 834B 30AC 834C 30AD 834D 30AE 834E 30AF 834F 30B0 8350 30B1 8351 30B2 8352 30B3 8353 30B4 8354 30B5 8355 30B6 8356 30B7 8357 30B8 8358 30B9 8359 30BA 835A 30BB 835B 30BC 835C 30BD 835D 30BE 835E 30BF 835F 30C0 8360 30C1 8361 30C2 8362 30C3 8363 30C4 8364 30C5 8365 30C6 8366 30C7 8367 30C8 8368 30C9 8369 30CA 836A 30CB 836B 30CC 836C 30CD 836D 30CE 836E 30CF 836F 30D0 8370 30D1 8371 30D2 8372 30D3 8373 30D4 8374 30D5 8375 30D6 8376 30D7 8377 30D8 8378 30D9 8379 30DA 837A 30DB 837B 30DC 837C 30DD 837D 30DE 837E 30DF 8380 30E0 8381 30E1 8382 30E2 8383 30E3 8384 30E4 8385 30E5 8386 30E6 8387 30E7 8388 30E8 8389 30E9 838A 30EA 838B 30EB 838C 30EC 838D 30ED 838E 30EE 838F 30EF 8390 30F0 8391 30F1 8392 30F2 8393 30F3 8394 30F4 8395 30F5 8396 30F6 8397 30AB 309A 8398 30AD 309A 8399 30AF 309A 839A 30B1 309A 839B 30B3 309A 839C 30BB 309A 839D 30C4 309A 839E 30C8 309A 839F 0391 83A0 0392 83A1 0393 83A2 0394 83A3 0395 83A4 0396 83A5 0397 83A6 0398 83A7 0399 83A8 039A 83A9 039B 83AA 039C 83AB 039D 83AC 039E 83AD 039F 83AE 03A0 83AF 03A1 83B0 03A3 83B1 03A4 83B2 03A5 83B3 03A6 83B4 03A7 83B5 03A8 83B6 03A9 83B7 2664 83B8 2660 83B9 2662 83BA 2666 83BB 2661 83BC 2665 83BD 2667 83BE 2663 83BF 03B1 83C0 03B2 83C1 03B3 83C2 03B4 83C3 03B5 83C4 03B6 83C5 03B7 83C6 03B8 83C7 03B9 83C8 03BA 83C9 03BB 83CA 03BC 83CB 03BD 83CC 03BE 83CD 03BF 83CE 03C0 83CF 03C1 83D0 03C3 83D1 03C4 83D2 03C5 83D3 03C6 83D4 03C7 83D5 03C8 83D6 03C9 83D7 03C2 83D8 24F5 83D9 24F6 83DA 24F7 83DB 24F8 83DC 24F9 83DD 24FA 83DE 24FB 83DF 24FC 83E0 24FD 83E1 24FE 83E2 2616 83E3 2617 83E4 3020 83E5 260E 83E6 2600 83E7 2601 83E8 2602 83E9 2603 83EA 2668 83EB 25B1 83EC 31F0 83ED 31F1 83EE 31F2 83EF 31F3 83F0 31F4 83F1 31F5 83F2 31F6 83F3 31F7 83F4 31F8 83F5 31F9 83F6 31F7 309A 83F7 31FA 83F8 31FB 83F9 31FC 83FA 31FD 83FB 31FE 83FC 31FF 8440 0410 8441 0411 8442 0412 8443 0413 8444 0414 8445 0415 8446 0401 8447 0416 8448 0417 8449 0418 844A 0419 844B 041A 844C 041B 844D 041C 844E 041D 844F 041E 8450 041F 8451 0420 8452 0421 8453 0422 8454 0423 8455 0424 8456 0425 8457 0426 8458 0427 8459 0428 845A 0429 845B 042A 845C 042B 845D 042C 845E 042D 845F 042E 8460 042F 8461 23BE 8462 23BF 8463 23C0 8464 23C1 8465 23C2 8466 23C3 8467 23C4 8468 23C5 8469 23C6 846A 23C7 846B 23C8 846C 23C9 846D 23CA 846E 23CB 846F 23CC 8470 0430 8471 0431 8472 0432 8473 0433 8474 0434 8475 0435 8476 0451 8477 0436 8478 0437 8479 0438 847A 0439 847B 043A 847C 043B 847D 043C 847E 043D 8480 043E 8481 043F 8482 0440 8483 0441 8484 0442 8485 0443 8486 0444 8487 0445 8488 0446 8489 0447 848A 0448 848B 0449 848C 044A 848D 044B 848E 044C 848F 044D 8490 044E 8491 044F 8492 30F7 8493 30F8 8494 30F9 8495 30FA 8496 22DA 8497 22DB 8498 2153 8499 2154 849A 2155 849B 2713 849C 2318 849D 2423 849E 23CE 849F 2500 84A0 2502 84A1 250C 84A2 2510 84A3 2518 84A4 2514 84A5 251C 84A6 252C 84A7 2524 84A8 2534 84A9 253C 84AA 2501 84AB 2503 84AC 250F 84AD 2513 84AE 251B 84AF 2517 84B0 2523 84B1 2533 84B2 252B 84B3 253B 84B4 254B 84B5 2520 84B6 252F 84B7 2528 84B8 2537 84B9 253F 84BA 251D 84BB 2530 84BC 2525 84BD 2538 84BE 2542 84BF 3251 84C0 3252 84C1 3253 84C2 3254 84C3 3255 84C4 3256 84C5 3257 84C6 3258 84C7 3259 84C8 325A 84C9 325B 84CA 325C 84CB 325D 84CC 325E 84CD 325F 84CE 32B1 84CF 32B2 84D0 32B3 84D1 32B4 84D2 32B5 84D3 32B6 84D4 32B7 84D5 32B8 84D6 32B9 84D7 32BA 84D8 32BB 84D9 32BC 84DA 32BD 84DB 32BE 84DC 32BF 84E5 25D0 84E6 25D1 84E7 25D2 84E8 25D3 84E9 203C 84EA 2047 84EB 2048 84EC 2049 84ED 01CD 84EE 01CE 84EF 01D0 84F0 1E3E 84F1 1E3F 84F2 01F8 84F3 01F9 84F4 01D1 84F5 01D2 84F6 01D4 84F7 01D6 84F8 01D8 84F9 01DA 84FA 01DC 8540 20AC 8541 00A0 8542 00A1 8543 00A4 8544 00A6 8545 00A9 8546 00AA 8547 00AB 8548 00AD 8549 00AE 854A 00AF 854B 00B2 854C 00B3 854D 00B7 854E 00B8 854F 00B9 8550 00BA 8551 00BB 8552 00BC 8553 00BD 8554 00BE 8555 00BF 8556 00C0 8557 00C1 8558 00C2 8559 00C3 855A 00C4 855B 00C5 855C 00C6 855D 00C7 855E 00C8 855F 00C9 8560 00CA 8561 00CB 8562 00CC 8563 00CD 8564 00CE 8565 00CF 8566 00D0 8567 00D1 8568 00D2 8569 00D3 856A 00D4 856B 00D5 856C 00D6 856D 00D8 856E 00D9 856F 00DA 8570 00DB 8571 00DC 8572 00DD 8573 00DE 8574 00DF 8575 00E0 8576 00E1 8577 00E2 8578 00E3 8579 00E4 857A 00E5 857B 00E6 857C 00E7 857D 00E8 857E 00E9 8580 00EA 8581 00EB 8582 00EC 8583 00ED 8584 00EE 8585 00EF 8586 00F0 8587 00F1 8588 00F2 8589 00F3 858A 00F4 858B 00F5 858C 00F6 858D 00F8 858E 00F9 858F 00FA 8590 00FB 8591 00FC 8592 00FD 8593 00FE 8594 00FF 8595 0100 8596 012A 8597 016A 8598 0112 8599 014C 859A 0101 859B 012B 859C 016B 859D 0113 859E 014D 859F 0104 85A0 02D8 85A1 0141 85A2 013D 85A3 015A 85A4 0160 85A5 015E 85A6 0164 85A7 0179 85A8 017D 85A9 017B 85AA 0105 85AB 02DB 85AC 0142 85AD 013E 85AE 015B 85AF 02C7 85B0 0161 85B1 015F 85B2 0165 85B3 017A 85B4 02DD 85B5 017E 85B6 017C 85B7 0154 85B8 0102 85B9 0139 85BA 0106 85BB 010C 85BC 0118 85BD 011A 85BE 010E 85BF 0143 85C0 0147 85C1 0150 85C2 0158 85C3 016E 85C4 0170 85C5 0162 85C6 0155 85C7 0103 85C8 013A 85C9 0107 85CA 010D 85CB 0119 85CC 011B 85CD 010F 85CE 0111 85CF 0144 85D0 0148 85D1 0151 85D2 0159 85D3 016F 85D4 0171 85D5 0163 85D6 02D9 85D7 0108 85D8 011C 85D9 0124 85DA 0134 85DB 015C 85DC 016C 85DD 0109 85DE 011D 85DF 0125 85E0 0135 85E1 015D 85E2 016D 85E3 0271 85E4 028B 85E5 027E 85E6 0283 85E7 0292 85E8 026C 85E9 026E 85EA 0279 85EB 0288 85EC 0256 85ED 0273 85EE 027D 85EF 0282 85F0 0290 85F1 027B 85F2 026D 85F3 025F 85F4 0272 85F5 029D 85F6 028E 85F7 0261 85F8 014B 85F9 0270 85FA 0281 85FB 0127 85FC 0295 8640 0294 8641 0266 8642 0298 8643 01C2 8644 0253 8645 0257 8646 0284 8647 0260 8648 0193 8649 0153 864A 0152 864B 0268 864C 0289 864D 0258 864E 0275 864F 0259 8650 025C 8651 025E 8652 0250 8653 026F 8654 028A 8655 0264 8656 028C 8657 0254 8658 0251 8659 0252 865A 028D 865B 0265 865C 02A2 865D 02A1 865E 0255 865F 0291 8660 027A 8661 0267 8662 025A 8663 00E6 0300 8664 01FD 8665 1F70 8666 1F71 8667 0254 0300 8668 0254 0301 8669 028C 0300 866A 028C 0301 866B 0259 0300 866C 0259 0301 866D 025A 0300 866E 025A 0301 866F 1F72 8670 1F73 8671 0361 8672 02C8 8673 02CC 8674 02D0 8675 02D1 8676 0306 8677 203F 8678 030B 8679 0301 867A 0304 867B 0300 867C 030F 867D 030C 867E 0302 8680 02E5 8681 02E6 8682 02E7 8683 02E8 8684 02E9 8685 02E9 02E5 8686 02E5 02E9 8687 0325 8688 032C 8689 0339 868A 031C 868B 031F 868C 0320 868D 0308 868E 033D 868F 0329 8690 032F 8691 02DE 8692 0324 8693 0330 8694 033C 8695 0334 8696 031D 8697 031E 8698 0318 8699 0319 869A 032A 869B 033A 869C 033B 869D 0303 869E 031A 869F 2776 86A0 2777 86A1 2778 86A2 2779 86A3 277A 86A4 277B 86A5 277C 86A6 277D 86A7 277E 86A8 277F 86A9 24EB 86AA 24EC 86AB 24ED 86AC 24EE 86AD 24EF 86AE 24F0 86AF 24F1 86B0 24F2 86B1 24F3 86B2 24F4 86B3 2170 86B4 2171 86B5 2172 86B6 2173 86B7 2174 86B8 2175 86B9 2176 86BA 2177 86BB 2178 86BC 2179 86BD 217A 86BE 217B 86BF 24D0 86C0 24D1 86C1 24D2 86C2 24D3 86C3 24D4 86C4 24D5 86C5 24D6 86C6 24D7 86C7 24D8 86C8 24D9 86C9 24DA 86CA 24DB 86CB 24DC 86CC 24DD 86CD 24DE 86CE 24DF 86CF 24E0 86D0 24E1 86D1 24E2 86D2 24E3 86D3 24E4 86D4 24E5 86D5 24E6 86D6 24E7 86D7 24E8 86D8 24E9 86D9 32D0 86DA 32D1 86DB 32D2 86DC 32D3 86DD 32D4 86DE 32D5 86DF 32D6 86E0 32D7 86E1 32D8 86E2 32D9 86E3 32DA 86E4 32DB 86E5 32DC 86E6 32DD 86E7 32DE 86E8 32DF 86E9 32E0 86EA 32E1 86EB 32E2 86EC 32E3 86ED 32FA 86EE 32E9 86EF 32E5 86F0 32ED 86F1 32EC 86FB 2051 86FC 2042 8740 2460 8741 2461 8742 2462 8743 2463 8744 2464 8745 2465 8746 2466 8747 2467 8748 2468 8749 2469 874A 246A 874B 246B 874C 246C 874D 246D 874E 246E 874F 246F 8750 2470 8751 2471 8752 2472 8753 2473 8754 2160 8755 2161 8756 2162 8757 2163 8758 2164 8759 2165 875A 2166 875B 2167 875C 2168 875D 2169 875E 216A 875F 3349 8760 3314 8761 3322 8762 334D 8763 3318 8764 3327 8765 3303 8766 3336 8767 3351 8768 3357 8769 330D 876A 3326 876B 3323 876C 332B 876D 334A 876E 333B 876F 339C 8770 339D 8771 339E 8772 338E 8773 338F 8774 33C4 8775 33A1 8776 216B 877E 337B 8780 301D 8781 301F 8782 2116 8783 33CD 8784 2121 8785 32A4 8786 32A5 8787 32A6 8788 32A7 8789 32A8 878A 3231 878B 3232 878C 3239 878D 337E 878E 337D 878F 337C 8793 222E 8798 221F 8799 22BF 879D 2756 879E 261E 87A0 2000B 87A1 3402 87A2 4E28 87A3 4E2F 87A4 4E30 87A5 4E8D 87A6 4EE1 87A7 4EFD 87A8 4EFF 87A9 4F03 87AA 4F0B 87AB 4F60 87AC 4F48 87AD 4F49 87AE 4F56 87AF 4F5F 87B0 4F6A 87B1 4F6C 87B2 4F7E 87B3 4F8A 87B4 4F94 87B5 4F97 87B6 FA30 87B7 4FC9 87B8 4FE0 87B9 5001 87BA 5002 87BB 500E 87BC 5018 87BD 5027 87BE 502E 87BF 5040 87C0 503B 87C1 5041 87C2 5094 87C3 50CC 87C4 50F2 87C5 50D0 87C6 50E6 87C7 FA31 87C8 5106 87C9 5103 87CA 510B 87CB 511E 87CC 5135 87CD 514A 87CE FA32 87CF 5155 87D0 5157 87D1 34B5 87D2 519D 87D3 51C3 87D4 51CA 87D5 51DE 87D6 51E2 87D7 51EE 87D8 5201 87D9 34DB 87DA 5213 87DB 5215 87DC 5249 87DD 5257 87DE 5261 87DF 5293 87E0 52C8 87E1 FA33 87E2 52CC 87E3 52D0 87E4 52D6 87E5 52DB 87E6 FA34 87E7 52F0 87E8 52FB 87E9 5300 87EA 5307 87EB 531C 87EC FA35 87ED 5361 87EE 5363 87EF 537D 87F0 5393 87F1 539D 87F2 53B2 87F3 5412 87F4 5427 87F5 544D 87F6 549C 87F7 546B 87F8 5474 87F9 547F 87FA 5488 87FB 5496 87FC 54A1 8840 54A9 8841 54C6 8842 54FF 8843 550E 8844 552B 8845 5535 8846 5550 8847 555E 8848 5581 8849 5586 884A 558E 884B FA36 884C 55AD 884D 55CE 884E FA37 884F 5608 8850 560E 8851 563B 8852 5649 8853 5676 8854 5666 8855 FA38 8856 566F 8857 5671 8858 5672 8859 5699 885A 569E 885B 56A9 885C 56AC 885D 56B3 885E 56C9 885F 56CA 8860 570A 8861 2123D 8862 5721 8863 572F 8864 5733 8865 5734 8866 5770 8867 5777 8868 577C 8869 579C 886A FA0F 886B 2131B 886C 57B8 886D 57C7 886E 57C8 886F 57CF 8870 57E4 8871 57ED 8872 57F5 8873 57F6 8874 57FF 8875 5809 8876 FA10 8877 5861 8878 5864 8879 FA39 887A 587C 887B 5889 887C 589E 887D FA3A 887E 58A9 8880 2146E 8881 58D2 8882 58CE 8883 58D4 8884 58DA 8885 58E0 8886 58E9 8887 590C 8888 8641 8889 595D 888A 596D 888B 598B 888C 5992 888D 59A4 888E 59C3 888F 59D2 8890 59DD 8891 5A13 8892 5A23 8893 5A67 8894 5A6D 8895 5A77 8896 5A7E 8897 5A84 8898 5A9E 8899 5AA7 889A 5AC4 889B 218BD 889C 5B19 889D 5B25 889F 4E9C 88A0 5516 88A1 5A03 88A2 963F 88A3 54C0 88A4 611B 88A5 6328 88A6 59F6 88A7 9022 88A8 8475 88A9 831C 88AA 7A50 88AB 60AA 88AC 63E1 88AD 6E25 88AE 65ED 88AF 8466 88B0 82A6 88B1 9BF5 88B2 6893 88B3 5727 88B4 65A1 88B5 6271 88B6 5B9B 88B7 59D0 88B8 867B 88B9 98F4 88BA 7D62 88BB 7DBE 88BC 9B8E 88BD 6216 88BE 7C9F 88BF 88B7 88C0 5B89 88C1 5EB5 88C2 6309 88C3 6697 88C4 6848 88C5 95C7 88C6 978D 88C7 674F 88C8 4EE5 88C9 4F0A 88CA 4F4D 88CB 4F9D 88CC 5049 88CD 56F2 88CE 5937 88CF 59D4 88D0 5A01 88D1 5C09 88D2 60DF 88D3 610F 88D4 6170 88D5 6613 88D6 6905 88D7 70BA 88D8 754F 88D9 7570 88DA 79FB 88DB 7DAD 88DC 7DEF 88DD 80C3 88DE 840E 88DF 8863 88E0 8B02 88E1 9055 88E2 907A 88E3 533B 88E4 4E95 88E5 4EA5 88E6 57DF 88E7 80B2 88E8 90C1 88E9 78EF 88EA 4E00 88EB 58F1 88EC 6EA2 88ED 9038 88EE 7A32 88EF 8328 88F0 828B 88F1 9C2F 88F2 5141 88F3 5370 88F4 54BD 88F5 54E1 88F6 56E0 88F7 59FB 88F8 5F15 88F9 98F2 88FA 6DEB 88FB 80E4 88FC 852D 8940 9662 8941 9670 8942 96A0 8943 97FB 8944 540B 8945 53F3 8946 5B87 8947 70CF 8948 7FBD 8949 8FC2 894A 96E8 894B 536F 894C 9D5C 894D 7ABA 894E 4E11 894F 7893 8950 81FC 8951 6E26 8952 5618 8953 5504 8954 6B1D 8955 851A 8956 9C3B 8957 59E5 8958 53A9 8959 6D66 895A 74DC 895B 958F 895C 5642 895D 4E91 895E 904B 895F 96F2 8960 834F 8961 990C 8962 53E1 8963 55B6 8964 5B30 8965 5F71 8966 6620 8967 66F3 8968 6804 8969 6C38 896A 6CF3 896B 6D29 896C 745B 896D 76C8 896E 7A4E 896F 9834 8970 82F1 8971 885B 8972 8A60 8973 92ED 8974 6DB2 8975 75AB 8976 76CA 8977 99C5 8978 60A6 8979 8B01 897A 8D8A 897B 95B2 897C 698E 897D 53AD 897E 5186 8980 5712 8981 5830 8982 5944 8983 5BB4 8984 5EF6 8985 6028 8986 63A9 8987 63F4 8988 6CBF 8989 6F14 898A 708E 898B 7114 898C 7159 898D 71D5 898E 733F 898F 7E01 8990 8276 8991 82D1 8992 8597 8993 9060 8994 925B 8995 9D1B 8996 5869 8997 65BC 8998 6C5A 8999 7525 899A 51F9 899B 592E 899C 5965 899D 5F80 899E 5FDC 899F 62BC 89A0 65FA 89A1 6A2A 89A2 6B27 89A3 6BB4 89A4 738B 89A5 7FC1 89A6 8956 89A7 9D2C 89A8 9D0E 89A9 9EC4 89AA 5CA1 89AB 6C96 89AC 837B 89AD 5104 89AE 5C4B 89AF 61B6 89B0 81C6 89B1 6876 89B2 7261 89B3 4E59 89B4 4FFA 89B5 5378 89B6 6069 89B7 6E29 89B8 7A4F 89B9 97F3 89BA 4E0B 89BB 5316 89BC 4EEE 89BD 4F55 89BE 4F3D 89BF 4FA1 89C0 4F73 89C1 52A0 89C2 53EF 89C3 5609 89C4 590F 89C5 5AC1 89C6 5BB6 89C7 5BE1 89C8 79D1 89C9 6687 89CA 679C 89CB 67B6 89CC 6B4C 89CD 6CB3 89CE 706B 89CF 73C2 89D0 798D 89D1 79BE 89D2 7A3C 89D3 7B87 89D4 82B1 89D5 82DB 89D6 8304 89D7 8377 89D8 83EF 89D9 83D3 89DA 8766 89DB 8AB2 89DC 5629 89DD 8CA8 89DE 8FE6 89DF 904E 89E0 971E 89E1 868A 89E2 4FC4 89E3 5CE8 89E4 6211 89E5 7259 89E6 753B 89E7 81E5 89E8 82BD 89E9 86FE 89EA 8CC0 89EB 96C5 89EC 9913 89ED 99D5 89EE 4ECB 89EF 4F1A 89F0 89E3 89F1 56DE 89F2 584A 89F3 58CA 89F4 5EFB 89F5 5FEB 89F6 602A 89F7 6094 89F8 6062 89F9 61D0 89FA 6212 89FB 62D0 89FC 6539 8A40 9B41 8A41 6666 8A42 68B0 8A43 6D77 8A44 7070 8A45 754C 8A46 7686 8A47 7D75 8A48 82A5 8A49 87F9 8A4A 958B 8A4B 968E 8A4C 8C9D 8A4D 51F1 8A4E 52BE 8A4F 5916 8A50 54B3 8A51 5BB3 8A52 5D16 8A53 6168 8A54 6982 8A55 6DAF 8A56 788D 8A57 84CB 8A58 8857 8A59 8A72 8A5A 93A7 8A5B 9AB8 8A5C 6D6C 8A5D 99A8 8A5E 86D9 8A5F 57A3 8A60 67FF 8A61 86CE 8A62 920E 8A63 5283 8A64 5687 8A65 5404 8A66 5ED3 8A67 62E1 8A68 64B9 8A69 683C 8A6A 6838 8A6B 6BBB 8A6C 7372 8A6D 78BA 8A6E 7A6B 8A6F 899A 8A70 89D2 8A71 8D6B 8A72 8F03 8A73 90ED 8A74 95A3 8A75 9694 8A76 9769 8A77 5B66 8A78 5CB3 8A79 697D 8A7A 984D 8A7B 984E 8A7C 639B 8A7D 7B20 8A7E 6A2B 8A80 6A7F 8A81 68B6 8A82 9C0D 8A83 6F5F 8A84 5272 8A85 559D 8A86 6070 8A87 62EC 8A88 6D3B 8A89 6E07 8A8A 6ED1 8A8B 845B 8A8C 8910 8A8D 8F44 8A8E 4E14 8A8F 9C39 8A90 53F6 8A91 691B 8A92 6A3A 8A93 9784 8A94 682A 8A95 515C 8A96 7AC3 8A97 84B2 8A98 91DC 8A99 938C 8A9A 565B 8A9B 9D28 8A9C 6822 8A9D 8305 8A9E 8431 8A9F 7CA5 8AA0 5208 8AA1 82C5 8AA2 74E6 8AA3 4E7E 8AA4 4F83 8AA5 51A0 8AA6 5BD2 8AA7 520A 8AA8 52D8 8AA9 52E7 8AAA 5DFB 8AAB 559A 8AAC 582A 8AAD 59E6 8AAE 5B8C 8AAF 5B98 8AB0 5BDB 8AB1 5E72 8AB2 5E79 8AB3 60A3 8AB4 611F 8AB5 6163 8AB6 61BE 8AB7 63DB 8AB8 6562 8AB9 67D1 8ABA 6853 8ABB 68FA 8ABC 6B3E 8ABD 6B53 8ABE 6C57 8ABF 6F22 8AC0 6F97 8AC1 6F45 8AC2 74B0 8AC3 7518 8AC4 76E3 8AC5 770B 8AC6 7AFF 8AC7 7BA1 8AC8 7C21 8AC9 7DE9 8ACA 7F36 8ACB 7FF0 8ACC 809D 8ACD 8266 8ACE 839E 8ACF 89B3 8AD0 8ACC 8AD1 8CAB 8AD2 9084 8AD3 9451 8AD4 9593 8AD5 9591 8AD6 95A2 8AD7 9665 8AD8 97D3 8AD9 9928 8ADA 8218 8ADB 4E38 8ADC 542B 8ADD 5CB8 8ADE 5DCC 8ADF 73A9 8AE0 764C 8AE1 773C 8AE2 5CA9 8AE3 7FEB 8AE4 8D0B 8AE5 96C1 8AE6 9811 8AE7 9854 8AE8 9858 8AE9 4F01 8AEA 4F0E 8AEB 5371 8AEC 559C 8AED 5668 8AEE 57FA 8AEF 5947 8AF0 5B09 8AF1 5BC4 8AF2 5C90 8AF3 5E0C 8AF4 5E7E 8AF5 5FCC 8AF6 63EE 8AF7 673A 8AF8 65D7 8AF9 65E2 8AFA 671F 8AFB 68CB 8AFC 68C4 8B40 6A5F 8B41 5E30 8B42 6BC5 8B43 6C17 8B44 6C7D 8B45 757F 8B46 7948 8B47 5B63 8B48 7A00 8B49 7D00 8B4A 5FBD 8B4B 898F 8B4C 8A18 8B4D 8CB4 8B4E 8D77 8B4F 8ECC 8B50 8F1D 8B51 98E2 8B52 9A0E 8B53 9B3C 8B54 4E80 8B55 507D 8B56 5100 8B57 5993 8B58 5B9C 8B59 622F 8B5A 6280 8B5B 64EC 8B5C 6B3A 8B5D 72A0 8B5E 7591 8B5F 7947 8B60 7FA9 8B61 87FB 8B62 8ABC 8B63 8B70 8B64 63AC 8B65 83CA 8B66 97A0 8B67 5409 8B68 5403 8B69 55AB 8B6A 6854 8B6B 6A58 8B6C 8A70 8B6D 7827 8B6E 6775 8B6F 9ECD 8B70 5374 8B71 5BA2 8B72 811A 8B73 8650 8B74 9006 8B75 4E18 8B76 4E45 8B77 4EC7 8B78 4F11 8B79 53CA 8B7A 5438 8B7B 5BAE 8B7C 5F13 8B7D 6025 8B7E 6551 8B80 673D 8B81 6C42 8B82 6C72 8B83 6CE3 8B84 7078 8B85 7403 8B86 7A76 8B87 7AAE 8B88 7B08 8B89 7D1A 8B8A 7CFE 8B8B 7D66 8B8C 65E7 8B8D 725B 8B8E 53BB 8B8F 5C45 8B90 5DE8 8B91 62D2 8B92 62E0 8B93 6319 8B94 6E20 8B95 865A 8B96 8A31 8B97 8DDD 8B98 92F8 8B99 6F01 8B9A 79A6 8B9B 9B5A 8B9C 4EA8 8B9D 4EAB 8B9E 4EAC 8B9F 4F9B 8BA0 4FA0 8BA1 50D1 8BA2 5147 8BA3 7AF6 8BA4 5171 8BA5 51F6 8BA6 5354 8BA7 5321 8BA8 537F 8BA9 53EB 8BAA 55AC 8BAB 5883 8BAC 5CE1 8BAD 5F37 8BAE 5F4A 8BAF 602F 8BB0 6050 8BB1 606D 8BB2 631F 8BB3 6559 8BB4 6A4B 8BB5 6CC1 8BB6 72C2 8BB7 72ED 8BB8 77EF 8BB9 80F8 8BBA 8105 8BBB 8208 8BBC 854E 8BBD 90F7 8BBE 93E1 8BBF 97FF 8BC0 9957 8BC1 9A5A 8BC2 4EF0 8BC3 51DD 8BC4 5C2D 8BC5 6681 8BC6 696D 8BC7 5C40 8BC8 66F2 8BC9 6975 8BCA 7389 8BCB 6850 8BCC 7C81 8BCD 50C5 8BCE 52E4 8BCF 5747 8BD0 5DFE 8BD1 9326 8BD2 65A4 8BD3 6B23 8BD4 6B3D 8BD5 7434 8BD6 7981 8BD7 79BD 8BD8 7B4B 8BD9 7DCA 8BDA 82B9 8BDB 83CC 8BDC 887F 8BDD 895F 8BDE 8B39 8BDF 8FD1 8BE0 91D1 8BE1 541F 8BE2 9280 8BE3 4E5D 8BE4 5036 8BE5 53E5 8BE6 533A 8BE7 72D7 8BE8 7396 8BE9 77E9 8BEA 82E6 8BEB 8EAF 8BEC 99C6 8BED 99C8 8BEE 99D2 8BEF 5177 8BF0 611A 8BF1 865E 8BF2 55B0 8BF3 7A7A 8BF4 5076 8BF5 5BD3 8BF6 9047 8BF7 9685 8BF8 4E32 8BF9 6ADB 8BFA 91E7 8BFB 5C51 8BFC 5C48 8C40 6398 8C41 7A9F 8C42 6C93 8C43 9774 8C44 8F61 8C45 7AAA 8C46 718A 8C47 9688 8C48 7C82 8C49 6817 8C4A 7E70 8C4B 6851 8C4C 936C 8C4D 52F2 8C4E 541B 8C4F 85AB 8C50 8A13 8C51 7FA4 8C52 8ECD 8C53 90E1 8C54 5366 8C55 8888 8C56 7941 8C57 4FC2 8C58 50BE 8C59 5211 8C5A 5144 8C5B 5553 8C5C 572D 8C5D 73EA 8C5E 578B 8C5F 5951 8C60 5F62 8C61 5F84 8C62 6075 8C63 6176 8C64 6167 8C65 61A9 8C66 63B2 8C67 643A 8C68 656C 8C69 666F 8C6A 6842 8C6B 6E13 8C6C 7566 8C6D 7A3D 8C6E 7CFB 8C6F 7D4C 8C70 7D99 8C71 7E4B 8C72 7F6B 8C73 830E 8C74 834A 8C75 86CD 8C76 8A08 8C77 8A63 8C78 8B66 8C79 8EFD 8C7A 981A 8C7B 9D8F 8C7C 82B8 8C7D 8FCE 8C7E 9BE8 8C80 5287 8C81 621F 8C82 6483 8C83 6FC0 8C84 9699 8C85 6841 8C86 5091 8C87 6B20 8C88 6C7A 8C89 6F54 8C8A 7A74 8C8B 7D50 8C8C 8840 8C8D 8A23 8C8E 6708 8C8F 4EF6 8C90 5039 8C91 5026 8C92 5065 8C93 517C 8C94 5238 8C95 5263 8C96 55A7 8C97 570F 8C98 5805 8C99 5ACC 8C9A 5EFA 8C9B 61B2 8C9C 61F8 8C9D 62F3 8C9E 6372 8C9F 691C 8CA0 6A29 8CA1 727D 8CA2 72AC 8CA3 732E 8CA4 7814 8CA5 786F 8CA6 7D79 8CA7 770C 8CA8 80A9 8CA9 898B 8CAA 8B19 8CAB 8CE2 8CAC 8ED2 8CAD 9063 8CAE 9375 8CAF 967A 8CB0 9855 8CB1 9A13 8CB2 9E78 8CB3 5143 8CB4 539F 8CB5 53B3 8CB6 5E7B 8CB7 5F26 8CB8 6E1B 8CB9 6E90 8CBA 7384 8CBB 73FE 8CBC 7D43 8CBD 8237 8CBE 8A00 8CBF 8AFA 8CC0 9650 8CC1 4E4E 8CC2 500B 8CC3 53E4 8CC4 547C 8CC5 56FA 8CC6 59D1 8CC7 5B64 8CC8 5DF1 8CC9 5EAB 8CCA 5F27 8CCB 6238 8CCC 6545 8CCD 67AF 8CCE 6E56 8CCF 72D0 8CD0 7CCA 8CD1 88B4 8CD2 80A1 8CD3 80E1 8CD4 83F0 8CD5 864E 8CD6 8A87 8CD7 8DE8 8CD8 9237 8CD9 96C7 8CDA 9867 8CDB 9F13 8CDC 4E94 8CDD 4E92 8CDE 4F0D 8CDF 5348 8CE0 5449 8CE1 543E 8CE2 5A2F 8CE3 5F8C 8CE4 5FA1 8CE5 609F 8CE6 68A7 8CE7 6A8E 8CE8 745A 8CE9 7881 8CEA 8A9E 8CEB 8AA4 8CEC 8B77 8CED 9190 8CEE 4E5E 8CEF 9BC9 8CF0 4EA4 8CF1 4F7C 8CF2 4FAF 8CF3 5019 8CF4 5016 8CF5 5149 8CF6 516C 8CF7 529F 8CF8 52B9 8CF9 52FE 8CFA 539A 8CFB 53E3 8CFC 5411 8D40 540E 8D41 5589 8D42 5751 8D43 57A2 8D44 597D 8D45 5B54 8D46 5B5D 8D47 5B8F 8D48 5DE5 8D49 5DE7 8D4A 5DF7 8D4B 5E78 8D4C 5E83 8D4D 5E9A 8D4E 5EB7 8D4F 5F18 8D50 6052 8D51 614C 8D52 6297 8D53 62D8 8D54 63A7 8D55 653B 8D56 6602 8D57 6643 8D58 66F4 8D59 676D 8D5A 6821 8D5B 6897 8D5C 69CB 8D5D 6C5F 8D5E 6D2A 8D5F 6D69 8D60 6E2F 8D61 6E9D 8D62 7532 8D63 7687 8D64 786C 8D65 7A3F 8D66 7CE0 8D67 7D05 8D68 7D18 8D69 7D5E 8D6A 7DB1 8D6B 8015 8D6C 8003 8D6D 80AF 8D6E 80B1 8D6F 8154 8D70 818F 8D71 822A 8D72 8352 8D73 884C 8D74 8861 8D75 8B1B 8D76 8CA2 8D77 8CFC 8D78 90CA 8D79 9175 8D7A 9271 8D7B 783F 8D7C 92FC 8D7D 95A4 8D7E 964D 8D80 9805 8D81 9999 8D82 9AD8 8D83 9D3B 8D84 525B 8D85 52AB 8D86 53F7 8D87 5408 8D88 58D5 8D89 62F7 8D8A 6FE0 8D8B 8C6A 8D8C 8F5F 8D8D 9EB9 8D8E 514B 8D8F 523B 8D90 544A 8D91 56FD 8D92 7A40 8D93 9177 8D94 9D60 8D95 9ED2 8D96 7344 8D97 6F09 8D98 8170 8D99 7511 8D9A 5FFD 8D9B 60DA 8D9C 9AA8 8D9D 72DB 8D9E 8FBC 8D9F 6B64 8DA0 9803 8DA1 4ECA 8DA2 56F0 8DA3 5764 8DA4 58BE 8DA5 5A5A 8DA6 6068 8DA7 61C7 8DA8 660F 8DA9 6606 8DAA 6839 8DAB 68B1 8DAC 6DF7 8DAD 75D5 8DAE 7D3A 8DAF 826E 8DB0 9B42 8DB1 4E9B 8DB2 4F50 8DB3 53C9 8DB4 5506 8DB5 5D6F 8DB6 5DE6 8DB7 5DEE 8DB8 67FB 8DB9 6C99 8DBA 7473 8DBB 7802 8DBC 8A50 8DBD 9396 8DBE 88DF 8DBF 5750 8DC0 5EA7 8DC1 632B 8DC2 50B5 8DC3 50AC 8DC4 518D 8DC5 6700 8DC6 54C9 8DC7 585E 8DC8 59BB 8DC9 5BB0 8DCA 5F69 8DCB 624D 8DCC 63A1 8DCD 683D 8DCE 6B73 8DCF 6E08 8DD0 707D 8DD1 91C7 8DD2 7280 8DD3 7815 8DD4 7826 8DD5 796D 8DD6 658E 8DD7 7D30 8DD8 83DC 8DD9 88C1 8DDA 8F09 8DDB 969B 8DDC 5264 8DDD 5728 8DDE 6750 8DDF 7F6A 8DE0 8CA1 8DE1 51B4 8DE2 5742 8DE3 962A 8DE4 583A 8DE5 698A 8DE6 80B4 8DE7 54B2 8DE8 5D0E 8DE9 57FC 8DEA 7895 8DEB 9DFA 8DEC 4F5C 8DED 524A 8DEE 548B 8DEF 643E 8DF0 6628 8DF1 6714 8DF2 67F5 8DF3 7A84 8DF4 7B56 8DF5 7D22 8DF6 932F 8DF7 685C 8DF8 9BAD 8DF9 7B39 8DFA 5319 8DFB 518A 8DFC 5237 8E40 5BDF 8E41 62F6 8E42 64AE 8E43 64E6 8E44 672D 8E45 6BBA 8E46 85A9 8E47 96D1 8E48 7690 8E49 9BD6 8E4A 634C 8E4B 9306 8E4C 9BAB 8E4D 76BF 8E4E 6652 8E4F 4E09 8E50 5098 8E51 53C2 8E52 5C71 8E53 60E8 8E54 6492 8E55 6563 8E56 685F 8E57 71E6 8E58 73CA 8E59 7523 8E5A 7B97 8E5B 7E82 8E5C 8695 8E5D 8B83 8E5E 8CDB 8E5F 9178 8E60 9910 8E61 65AC 8E62 66AB 8E63 6B8B 8E64 4ED5 8E65 4ED4 8E66 4F3A 8E67 4F7F 8E68 523A 8E69 53F8 8E6A 53F2 8E6B 55E3 8E6C 56DB 8E6D 58EB 8E6E 59CB 8E6F 59C9 8E70 59FF 8E71 5B50 8E72 5C4D 8E73 5E02 8E74 5E2B 8E75 5FD7 8E76 601D 8E77 6307 8E78 652F 8E79 5B5C 8E7A 65AF 8E7B 65BD 8E7C 65E8 8E7D 679D 8E7E 6B62 8E80 6B7B 8E81 6C0F 8E82 7345 8E83 7949 8E84 79C1 8E85 7CF8 8E86 7D19 8E87 7D2B 8E88 80A2 8E89 8102 8E8A 81F3 8E8B 8996 8E8C 8A5E 8E8D 8A69 8E8E 8A66 8E8F 8A8C 8E90 8AEE 8E91 8CC7 8E92 8CDC 8E93 96CC 8E94 98FC 8E95 6B6F 8E96 4E8B 8E97 4F3C 8E98 4F8D 8E99 5150 8E9A 5B57 8E9B 5BFA 8E9C 6148 8E9D 6301 8E9E 6642 8E9F 6B21 8EA0 6ECB 8EA1 6CBB 8EA2 723E 8EA3 74BD 8EA4 75D4 8EA5 78C1 8EA6 793A 8EA7 800C 8EA8 8033 8EA9 81EA 8EAA 8494 8EAB 8F9E 8EAC 6C50 8EAD 9E7F 8EAE 5F0F 8EAF 8B58 8EB0 9D2B 8EB1 7AFA 8EB2 8EF8 8EB3 5B8D 8EB4 96EB 8EB5 4E03 8EB6 53F1 8EB7 57F7 8EB8 5931 8EB9 5AC9 8EBA 5BA4 8EBB 6089 8EBC 6E7F 8EBD 6F06 8EBE 75BE 8EBF 8CEA 8EC0 5B9F 8EC1 8500 8EC2 7BE0 8EC3 5072 8EC4 67F4 8EC5 829D 8EC6 5C61 8EC7 854A 8EC8 7E1E 8EC9 820E 8ECA 5199 8ECB 5C04 8ECC 6368 8ECD 8D66 8ECE 659C 8ECF 716E 8ED0 793E 8ED1 7D17 8ED2 8005 8ED3 8B1D 8ED4 8ECA 8ED5 906E 8ED6 86C7 8ED7 90AA 8ED8 501F 8ED9 52FA 8EDA 5C3A 8EDB 6753 8EDC 707C 8EDD 7235 8EDE 914C 8EDF 91C8 8EE0 932B 8EE1 82E5 8EE2 5BC2 8EE3 5F31 8EE4 60F9 8EE5 4E3B 8EE6 53D6 8EE7 5B88 8EE8 624B 8EE9 6731 8EEA 6B8A 8EEB 72E9 8EEC 73E0 8EED 7A2E 8EEE 816B 8EEF 8DA3 8EF0 9152 8EF1 9996 8EF2 5112 8EF3 53D7 8EF4 546A 8EF5 5BFF 8EF6 6388 8EF7 6A39 8EF8 7DAC 8EF9 9700 8EFA 56DA 8EFB 53CE 8EFC 5468 8F40 5B97 8F41 5C31 8F42 5DDE 8F43 4FEE 8F44 6101 8F45 62FE 8F46 6D32 8F47 79C0 8F48 79CB 8F49 7D42 8F4A 7E4D 8F4B 7FD2 8F4C 81ED 8F4D 821F 8F4E 8490 8F4F 8846 8F50 8972 8F51 8B90 8F52 8E74 8F53 8F2F 8F54 9031 8F55 914B 8F56 916C 8F57 96C6 8F58 919C 8F59 4EC0 8F5A 4F4F 8F5B 5145 8F5C 5341 8F5D 5F93 8F5E 620E 8F5F 67D4 8F60 6C41 8F61 6E0B 8F62 7363 8F63 7E26 8F64 91CD 8F65 9283 8F66 53D4 8F67 5919 8F68 5BBF 8F69 6DD1 8F6A 795D 8F6B 7E2E 8F6C 7C9B 8F6D 587E 8F6E 719F 8F6F 51FA 8F70 8853 8F71 8FF0 8F72 4FCA 8F73 5CFB 8F74 6625 8F75 77AC 8F76 7AE3 8F77 821C 8F78 99FF 8F79 51C6 8F7A 5FAA 8F7B 65EC 8F7C 696F 8F7D 6B89 8F7E 6DF3 8F80 6E96 8F81 6F64 8F82 76FE 8F83 7D14 8F84 5DE1 8F85 9075 8F86 9187 8F87 9806 8F88 51E6 8F89 521D 8F8A 6240 8F8B 6691 8F8C 66D9 8F8D 6E1A 8F8E 5EB6 8F8F 7DD2 8F90 7F72 8F91 66F8 8F92 85AF 8F93 85F7 8F94 8AF8 8F95 52A9 8F96 53D9 8F97 5973 8F98 5E8F 8F99 5F90 8F9A 6055 8F9B 92E4 8F9C 9664 8F9D 50B7 8F9E 511F 8F9F 52DD 8FA0 5320 8FA1 5347 8FA2 53EC 8FA3 54E8 8FA4 5546 8FA5 5531 8FA6 5617 8FA7 5968 8FA8 59BE 8FA9 5A3C 8FAA 5BB5 8FAB 5C06 8FAC 5C0F 8FAD 5C11 8FAE 5C1A 8FAF 5E84 8FB0 5E8A 8FB1 5EE0 8FB2 5F70 8FB3 627F 8FB4 6284 8FB5 62DB 8FB6 638C 8FB7 6377 8FB8 6607 8FB9 660C 8FBA 662D 8FBB 6676 8FBC 677E 8FBD 68A2 8FBE 6A1F 8FBF 6A35 8FC0 6CBC 8FC1 6D88 8FC2 6E09 8FC3 6E58 8FC4 713C 8FC5 7126 8FC6 7167 8FC7 75C7 8FC8 7701 8FC9 785D 8FCA 7901 8FCB 7965 8FCC 79F0 8FCD 7AE0 8FCE 7B11 8FCF 7CA7 8FD0 7D39 8FD1 8096 8FD2 83D6 8FD3 848B 8FD4 8549 8FD5 885D 8FD6 88F3 8FD7 8A1F 8FD8 8A3C 8FD9 8A54 8FDA 8A73 8FDB 8C61 8FDC 8CDE 8FDD 91A4 8FDE 9266 8FDF 937E 8FE0 9418 8FE1 969C 8FE2 9798 8FE3 4E0A 8FE4 4E08 8FE5 4E1E 8FE6 4E57 8FE7 5197 8FE8 5270 8FE9 57CE 8FEA 5834 8FEB 58CC 8FEC 5B22 8FED 5E38 8FEE 60C5 8FEF 64FE 8FF0 6761 8FF1 6756 8FF2 6D44 8FF3 72B6 8FF4 7573 8FF5 7A63 8FF6 84B8 8FF7 8B72 8FF8 91B8 8FF9 9320 8FFA 5631 8FFB 57F4 8FFC 98FE 9040 62ED 9041 690D 9042 6B96 9043 71ED 9044 7E54 9045 8077 9046 8272 9047 89E6 9048 98DF 9049 8755 904A 8FB1 904B 5C3B 904C 4F38 904D 4FE1 904E 4FB5 904F 5507 9050 5A20 9051 5BDD 9052 5BE9 9053 5FC3 9054 614E 9055 632F 9056 65B0 9057 664B 9058 68EE 9059 699B 905A 6D78 905B 6DF1 905C 7533 905D 75B9 905E 771F 905F 795E 9060 79E6 9061 7D33 9062 81E3 9063 82AF 9064 85AA 9065 89AA 9066 8A3A 9067 8EAB 9068 8F9B 9069 9032 906A 91DD 906B 9707 906C 4EBA 906D 4EC1 906E 5203 906F 5875 9070 58EC 9071 5C0B 9072 751A 9073 5C3D 9074 814E 9075 8A0A 9076 8FC5 9077 9663 9078 976D 9079 7B25 907A 8ACF 907B 9808 907C 9162 907D 56F3 907E 53A8 9080 9017 9081 5439 9082 5782 9083 5E25 9084 63A8 9085 6C34 9086 708A 9087 7761 9088 7C8B 9089 7FE0 908A 8870 908B 9042 908C 9154 908D 9310 908E 9318 908F 968F 9090 745E 9091 9AC4 9092 5D07 9093 5D69 9094 6570 9095 67A2 9096 8DA8 9097 96DB 9098 636E 9099 6749 909A 6919 909B 83C5 909C 9817 909D 96C0 909E 88FE 909F 6F84 90A0 647A 90A1 5BF8 90A2 4E16 90A3 702C 90A4 755D 90A5 662F 90A6 51C4 90A7 5236 90A8 52E2 90A9 59D3 90AA 5F81 90AB 6027 90AC 6210 90AD 653F 90AE 6574 90AF 661F 90B0 6674 90B1 68F2 90B2 6816 90B3 6B63 90B4 6E05 90B5 7272 90B6 751F 90B7 76DB 90B8 7CBE 90B9 8056 90BA 58F0 90BB 88FD 90BC 897F 90BD 8AA0 90BE 8A93 90BF 8ACB 90C0 901D 90C1 9192 90C2 9752 90C3 9759 90C4 6589 90C5 7A0E 90C6 8106 90C7 96BB 90C8 5E2D 90C9 60DC 90CA 621A 90CB 65A5 90CC 6614 90CD 6790 90CE 77F3 90CF 7A4D 90D0 7C4D 90D1 7E3E 90D2 810A 90D3 8CAC 90D4 8D64 90D5 8DE1 90D6 8E5F 90D7 78A9 90D8 5207 90D9 62D9 90DA 63A5 90DB 6442 90DC 6298 90DD 8A2D 90DE 7A83 90DF 7BC0 90E0 8AAC 90E1 96EA 90E2 7D76 90E3 820C 90E4 8749 90E5 4ED9 90E6 5148 90E7 5343 90E8 5360 90E9 5BA3 90EA 5C02 90EB 5C16 90EC 5DDD 90ED 6226 90EE 6247 90EF 64B0 90F0 6813 90F1 6834 90F2 6CC9 90F3 6D45 90F4 6D17 90F5 67D3 90F6 6F5C 90F7 714E 90F8 717D 90F9 65CB 90FA 7A7F 90FB 7BAD 90FC 7DDA 9140 7E4A 9141 7FA8 9142 817A 9143 821B 9144 8239 9145 85A6 9146 8A6E 9147 8CCE 9148 8DF5 9149 9078 914A 9077 914B 92AD 914C 9291 914D 9583 914E 9BAE 914F 524D 9150 5584 9151 6F38 9152 7136 9153 5168 9154 7985 9155 7E55 9156 81B3 9157 7CCE 9158 564C 9159 5851 915A 5CA8 915B 63AA 915C 66FE 915D 66FD 915E 695A 915F 72D9 9160 758F 9161 758E 9162 790E 9163 7956 9164 79DF 9165 7C97 9166 7D20 9167 7D44 9168 8607 9169 8A34 916A 963B 916B 9061 916C 9F20 916D 50E7 916E 5275 916F 53CC 9170 53E2 9171 5009 9172 55AA 9173 58EE 9174 594F 9175 723D 9176 5B8B 9177 5C64 9178 531D 9179 60E3 917A 60F3 917B 635C 917C 6383 917D 633F 917E 63BB 9180 64CD 9181 65E9 9182 66F9 9183 5DE3 9184 69CD 9185 69FD 9186 6F15 9187 71E5 9188 4E89 9189 75E9 918A 76F8 918B 7A93 918C 7CDF 918D 7DCF 918E 7D9C 918F 8061 9190 8349 9191 8358 9192 846C 9193 84BC 9194 85FB 9195 88C5 9196 8D70 9197 9001 9198 906D 9199 9397 919A 971C 919B 9A12 919C 50CF 919D 5897 919E 618E 919F 81D3 91A0 8535 91A1 8D08 91A2 9020 91A3 4FC3 91A4 5074 91A5 5247 91A6 5373 91A7 606F 91A8 6349 91A9 675F 91AA 6E2C 91AB 8DB3 91AC 901F 91AD 4FD7 91AE 5C5E 91AF 8CCA 91B0 65CF 91B1 7D9A 91B2 5352 91B3 8896 91B4 5176 91B5 63C3 91B6 5B58 91B7 5B6B 91B8 5C0A 91B9 640D 91BA 6751 91BB 905C 91BC 4ED6 91BD 591A 91BE 592A 91BF 6C70 91C0 8A51 91C1 553E 91C2 5815 91C3 59A5 91C4 60F0 91C5 6253 91C6 67C1 91C7 8235 91C8 6955 91C9 9640 91CA 99C4 91CB 9A28 91CC 4F53 91CD 5806 91CE 5BFE 91CF 8010 91D0 5CB1 91D1 5E2F 91D2 5F85 91D3 6020 91D4 614B 91D5 6234 91D6 66FF 91D7 6CF0 91D8 6EDE 91D9 80CE 91DA 817F 91DB 82D4 91DC 888B 91DD 8CB8 91DE 9000 91DF 902E 91E0 968A 91E1 9EDB 91E2 9BDB 91E3 4EE3 91E4 53F0 91E5 5927 91E6 7B2C 91E7 918D 91E8 984C 91E9 9DF9 91EA 6EDD 91EB 7027 91EC 5353 91ED 5544 91EE 5B85 91EF 6258 91F0 629E 91F1 62D3 91F2 6CA2 91F3 6FEF 91F4 7422 91F5 8A17 91F6 9438 91F7 6FC1 91F8 8AFE 91F9 8338 91FA 51E7 91FB 86F8 91FC 53EA 9240 53E9 9241 4F46 9242 9054 9243 8FB0 9244 596A 9245 8131 9246 5DFD 9247 7AEA 9248 8FBF 9249 68DA 924A 8C37 924B 72F8 924C 9C48 924D 6A3D 924E 8AB0 924F 4E39 9250 5358 9251 5606 9252 5766 9253 62C5 9254 63A2 9255 65E6 9256 6B4E 9257 6DE1 9258 6E5B 9259 70AD 925A 77ED 925B 7AEF 925C 7BAA 925D 7DBB 925E 803D 925F 80C6 9260 86CB 9261 8A95 9262 935B 9263 56E3 9264 58C7 9265 5F3E 9266 65AD 9267 6696 9268 6A80 9269 6BB5 926A 7537 926B 8AC7 926C 5024 926D 77E5 926E 5730 926F 5F1B 9270 6065 9271 667A 9272 6C60 9273 75F4 9274 7A1A 9275 7F6E 9276 81F4 9277 8718 9278 9045 9279 99B3 927A 7BC9 927B 755C 927C 7AF9 927D 7B51 927E 84C4 9280 9010 9281 79E9 9282 7A92 9283 8336 9284 5AE1 9285 7740 9286 4E2D 9287 4EF2 9288 5B99 9289 5FE0 928A 62BD 928B 663C 928C 67F1 928D 6CE8 928E 866B 928F 8877 9290 8A3B 9291 914E 9292 92F3 9293 99D0 9294 6A17 9295 7026 9296 732A 9297 82E7 9298 8457 9299 8CAF 929A 4E01 929B 5146 929C 51CB 929D 558B 929E 5BF5 929F 5E16 92A0 5E33 92A1 5E81 92A2 5F14 92A3 5F35 92A4 5F6B 92A5 5FB4 92A6 61F2 92A7 6311 92A8 66A2 92A9 671D 92AA 6F6E 92AB 7252 92AC 753A 92AD 773A 92AE 8074 92AF 8139 92B0 8178 92B1 8776 92B2 8ABF 92B3 8ADC 92B4 8D85 92B5 8DF3 92B6 929A 92B7 9577 92B8 9802 92B9 9CE5 92BA 52C5 92BB 6357 92BC 76F4 92BD 6715 92BE 6C88 92BF 73CD 92C0 8CC3 92C1 93AE 92C2 9673 92C3 6D25 92C4 589C 92C5 690E 92C6 69CC 92C7 8FFD 92C8 939A 92C9 75DB 92CA 901A 92CB 585A 92CC 6802 92CD 63B4 92CE 69FB 92CF 4F43 92D0 6F2C 92D1 67D8 92D2 8FBB 92D3 8526 92D4 7DB4 92D5 9354 92D6 693F 92D7 6F70 92D8 576A 92D9 58F7 92DA 5B2C 92DB 7D2C 92DC 722A 92DD 540A 92DE 91E3 92DF 9DB4 92E0 4EAD 92E1 4F4E 92E2 505C 92E3 5075 92E4 5243 92E5 8C9E 92E6 5448 92E7 5824 92E8 5B9A 92E9 5E1D 92EA 5E95 92EB 5EAD 92EC 5EF7 92ED 5F1F 92EE 608C 92EF 62B5 92F0 633A 92F1 63D0 92F2 68AF 92F3 6C40 92F4 7887 92F5 798E 92F6 7A0B 92F7 7DE0 92F8 8247 92F9 8A02 92FA 8AE6 92FB 8E44 92FC 9013 9340 90B8 9341 912D 9342 91D8 9343 9F0E 9344 6CE5 9345 6458 9346 64E2 9347 6575 9348 6EF4 9349 7684 934A 7B1B 934B 9069 934C 93D1 934D 6EBA 934E 54F2 934F 5FB9 9350 64A4 9351 8F4D 9352 8FED 9353 9244 9354 5178 9355 586B 9356 5929 9357 5C55 9358 5E97 9359 6DFB 935A 7E8F 935B 751C 935C 8CBC 935D 8EE2 935E 985B 935F 70B9 9360 4F1D 9361 6BBF 9362 6FB1 9363 7530 9364 96FB 9365 514E 9366 5410 9367 5835 9368 5857 9369 59AC 936A 5C60 936B 5F92 936C 6597 936D 675C 936E 6E21 936F 767B 9370 83DF 9371 8CED 9372 9014 9373 90FD 9374 934D 9375 7825 9376 783A 9377 52AA 9378 5EA6 9379 571F 937A 5974 937B 6012 937C 5012 937D 515A 937E 51AC 9380 51CD 9381 5200 9382 5510 9383 5854 9384 5858 9385 5957 9386 5B95 9387 5CF6 9388 5D8B 9389 60BC 938A 6295 938B 642D 938C 6771 938D 6843 938E 68BC 938F 68DF 9390 76D7 9391 6DD8 9392 6E6F 9393 6D9B 9394 706F 9395 71C8 9396 5F53 9397 75D8 9398 7977 9399 7B49 939A 7B54 939B 7B52 939C 7CD6 939D 7D71 939E 5230 939F 8463 93A0 8569 93A1 85E4 93A2 8A0E 93A3 8B04 93A4 8C46 93A5 8E0F 93A6 9003 93A7 900F 93A8 9419 93A9 9676 93AA 982D 93AB 9A30 93AC 95D8 93AD 50CD 93AE 52D5 93AF 540C 93B0 5802 93B1 5C0E 93B2 61A7 93B3 649E 93B4 6D1E 93B5 77B3 93B6 7AE5 93B7 80F4 93B8 8404 93B9 9053 93BA 9285 93BB 5CE0 93BC 9D07 93BD 533F 93BE 5F97 93BF 5FB3 93C0 6D9C 93C1 7279 93C2 7763 93C3 79BF 93C4 7BE4 93C5 6BD2 93C6 72EC 93C7 8AAD 93C8 6803 93C9 6A61 93CA 51F8 93CB 7A81 93CC 6934 93CD 5C4A 93CE 9CF6 93CF 82EB 93D0 5BC5 93D1 9149 93D2 701E 93D3 5678 93D4 5C6F 93D5 60C7 93D6 6566 93D7 6C8C 93D8 8C5A 93D9 9041 93DA 9813 93DB 5451 93DC 66C7 93DD 920D 93DE 5948 93DF 90A3 93E0 5185 93E1 4E4D 93E2 51EA 93E3 8599 93E4 8B0E 93E5 7058 93E6 637A 93E7 934B 93E8 6962 93E9 99B4 93EA 7E04 93EB 7577 93EC 5357 93ED 6960 93EE 8EDF 93EF 96E3 93F0 6C5D 93F1 4E8C 93F2 5C3C 93F3 5F10 93F4 8FE9 93F5 5302 93F6 8CD1 93F7 8089 93F8 8679 93F9 5EFF 93FA 65E5 93FB 4E73 93FC 5165 9440 5982 9441 5C3F 9442 97EE 9443 4EFB 9444 598A 9445 5FCD 9446 8A8D 9447 6FE1 9448 79B0 9449 7962 944A 5BE7 944B 8471 944C 732B 944D 71B1 944E 5E74 944F 5FF5 9450 637B 9451 649A 9452 71C3 9453 7C98 9454 4E43 9455 5EFC 9456 4E4B 9457 57DC 9458 56A2 9459 60A9 945A 6FC3 945B 7D0D 945C 80FD 945D 8133 945E 81BF 945F 8FB2 9460 8997 9461 86A4 9462 5DF4 9463 628A 9464 64AD 9465 8987 9466 6777 9467 6CE2 9468 6D3E 9469 7436 946A 7834 946B 5A46 946C 7F75 946D 82AD 946E 99AC 946F 4FF3 9470 5EC3 9471 62DD 9472 6392 9473 6557 9474 676F 9475 76C3 9476 724C 9477 80CC 9478 80BA 9479 8F29 947A 914D 947B 500D 947C 57F9 947D 5A92 947E 6885 9480 6973 9481 7164 9482 72FD 9483 8CB7 9484 58F2 9485 8CE0 9486 966A 9487 9019 9488 877F 9489 79E4 948A 77E7 948B 8429 948C 4F2F 948D 5265 948E 535A 948F 62CD 9490 67CF 9491 6CCA 9492 767D 9493 7B94 9494 7C95 9495 8236 9496 8584 9497 8FEB 9498 66DD 9499 6F20 949A 7206 949B 7E1B 949C 83AB 949D 99C1 949E 9EA6 949F 51FD 94A0 7BB1 94A1 7872 94A2 7BB8 94A3 8087 94A4 7B48 94A5 6AE8 94A6 5E61 94A7 808C 94A8 7551 94A9 7560 94AA 516B 94AB 9262 94AC 6E8C 94AD 767A 94AE 9197 94AF 9AEA 94B0 4F10 94B1 7F70 94B2 629C 94B3 7B4F 94B4 95A5 94B5 9CE9 94B6 567A 94B7 5859 94B8 86E4 94B9 96BC 94BA 4F34 94BB 5224 94BC 534A 94BD 53CD 94BE 53DB 94BF 5E06 94C0 642C 94C1 6591 94C2 677F 94C3 6C3E 94C4 6C4E 94C5 7248 94C6 72AF 94C7 73ED 94C8 7554 94C9 7E41 94CA 822C 94CB 85E9 94CC 8CA9 94CD 7BC4 94CE 91C6 94CF 7169 94D0 9812 94D1 98EF 94D2 633D 94D3 6669 94D4 756A 94D5 76E4 94D6 78D0 94D7 8543 94D8 86EE 94D9 532A 94DA 5351 94DB 5426 94DC 5983 94DD 5E87 94DE 5F7C 94DF 60B2 94E0 6249 94E1 6279 94E2 62AB 94E3 6590 94E4 6BD4 94E5 6CCC 94E6 75B2 94E7 76AE 94E8 7891 94E9 79D8 94EA 7DCB 94EB 7F77 94EC 80A5 94ED 88AB 94EE 8AB9 94EF 8CBB 94F0 907F 94F1 975E 94F2 98DB 94F3 6A0B 94F4 7C38 94F5 5099 94F6 5C3E 94F7 5FAE 94F8 6787 94F9 6BD8 94FA 7435 94FB 7709 94FC 7F8E 9540 9F3B 9541 67CA 9542 7A17 9543 5339 9544 758B 9545 9AED 9546 5F66 9547 819D 9548 83F1 9549 8098 954A 5F3C 954B 5FC5 954C 7562 954D 7B46 954E 903C 954F 6867 9550 59EB 9551 5A9B 9552 7D10 9553 767E 9554 8B2C 9555 4FF5 9556 5F6A 9557 6A19 9558 6C37 9559 6F02 955A 74E2 955B 7968 955C 8868 955D 8A55 955E 8C79 955F 5EDF 9560 63CF 9561 75C5 9562 79D2 9563 82D7 9564 9328 9565 92F2 9566 849C 9567 86ED 9568 9C2D 9569 54C1 956A 5F6C 956B 658C 956C 6D5C 956D 7015 956E 8CA7 956F 8CD3 9570 983B 9571 654F 9572 74F6 9573 4E0D 9574 4ED8 9575 57E0 9576 592B 9577 5A66 9578 5BCC 9579 51A8 957A 5E03 957B 5E9C 957C 6016 957D 6276 957E 6577 9580 65A7 9581 666E 9582 6D6E 9583 7236 9584 7B26 9585 8150 9586 819A 9587 8299 9588 8B5C 9589 8CA0 958A 8CE6 958B 8D74 958C 961C 958D 9644 958E 4FAE 958F 64AB 9590 6B66 9591 821E 9592 8461 9593 856A 9594 90E8 9595 5C01 9596 6953 9597 98A8 9598 847A 9599 8557 959A 4F0F 959B 526F 959C 5FA9 959D 5E45 959E 670D 959F 798F 95A0 8179 95A1 8907 95A2 8986 95A3 6DF5 95A4 5F17 95A5 6255 95A6 6CB8 95A7 4ECF 95A8 7269 95A9 9B92 95AA 5206 95AB 543B 95AC 5674 95AD 58B3 95AE 61A4 95AF 626E 95B0 711A 95B1 596E 95B2 7C89 95B3 7CDE 95B4 7D1B 95B5 96F0 95B6 6587 95B7 805E 95B8 4E19 95B9 4F75 95BA 5175 95BB 5840 95BC 5E63 95BD 5E73 95BE 5F0A 95BF 67C4 95C0 4E26 95C1 853D 95C2 9589 95C3 965B 95C4 7C73 95C5 9801 95C6 50FB 95C7 58C1 95C8 7656 95C9 78A7 95CA 5225 95CB 77A5 95CC 8511 95CD 7B86 95CE 504F 95CF 5909 95D0 7247 95D1 7BC7 95D2 7DE8 95D3 8FBA 95D4 8FD4 95D5 904D 95D6 4FBF 95D7 52C9 95D8 5A29 95D9 5F01 95DA 97AD 95DB 4FDD 95DC 8217 95DD 92EA 95DE 5703 95DF 6355 95E0 6B69 95E1 752B 95E2 88DC 95E3 8F14 95E4 7A42 95E5 52DF 95E6 5893 95E7 6155 95E8 620A 95E9 66AE 95EA 6BCD 95EB 7C3F 95EC 83E9 95ED 5023 95EE 4FF8 95EF 5305 95F0 5446 95F1 5831 95F2 5949 95F3 5B9D 95F4 5CF0 95F5 5CEF 95F6 5D29 95F7 5E96 95F8 62B1 95F9 6367 95FA 653E 95FB 65B9 95FC 670B 9640 6CD5 9641 6CE1 9642 70F9 9643 7832 9644 7E2B 9645 80DE 9646 82B3 9647 840C 9648 84EC 9649 8702 964A 8912 964B 8A2A 964C 8C4A 964D 90A6 964E 92D2 964F 98FD 9650 9CF3 9651 9D6C 9652 4E4F 9653 4EA1 9654 508D 9655 5256 9656 574A 9657 59A8 9658 5E3D 9659 5FD8 965A 5FD9 965B 623F 965C 66B4 965D 671B 965E 67D0 965F 68D2 9660 5192 9661 7D21 9662 80AA 9663 81A8 9664 8B00 9665 8C8C 9666 8CBF 9667 927E 9668 9632 9669 5420 966A 982C 966B 5317 966C 50D5 966D 535C 966E 58A8 966F 64B2 9670 6734 9671 7267 9672 7766 9673 7A46 9674 91E6 9675 52C3 9676 6CA1 9677 6B86 9678 5800 9679 5E4C 967A 5954 967B 672C 967C 7FFB 967D 51E1 967E 76C6 9680 6469 9681 78E8 9682 9B54 9683 9EBB 9684 57CB 9685 59B9 9686 6627 9687 679A 9688 6BCE 9689 54E9 968A 69D9 968B 5E55 968C 819C 968D 6795 968E 9BAA 968F 67FE 9690 9C52 9691 685D 9692 4EA6 9693 4FE3 9694 53C8 9695 62B9 9696 672B 9697 6CAB 9698 8FC4 9699 4FAD 969A 7E6D 969B 9EBF 969C 4E07 969D 6162 969E 6E80 969F 6F2B 96A0 8513 96A1 5473 96A2 672A 96A3 9B45 96A4 5DF3 96A5 7B95 96A6 5CAC 96A7 5BC6 96A8 871C 96A9 6E4A 96AA 84D1 96AB 7A14 96AC 8108 96AD 5999 96AE 7C8D 96AF 6C11 96B0 7720 96B1 52D9 96B2 5922 96B3 7121 96B4 725F 96B5 77DB 96B6 9727 96B7 9D61 96B8 690B 96B9 5A7F 96BA 5A18 96BB 51A5 96BC 540D 96BD 547D 96BE 660E 96BF 76DF 96C0 8FF7 96C1 9298 96C2 9CF4 96C3 59EA 96C4 725D 96C5 6EC5 96C6 514D 96C7 68C9 96C8 7DBF 96C9 7DEC 96CA 9762 96CB 9EBA 96CC 6478 96CD 6A21 96CE 8302 96CF 5984 96D0 5B5F 96D1 6BDB 96D2 731B 96D3 76F2 96D4 7DB2 96D5 8017 96D6 8499 96D7 5132 96D8 6728 96D9 9ED9 96DA 76EE 96DB 6762 96DC 52FF 96DD 9905 96DE 5C24 96DF 623B 96E0 7C7E 96E1 8CB0 96E2 554F 96E3 60B6 96E4 7D0B 96E5 9580 96E6 5301 96E7 4E5F 96E8 51B6 96E9 591C 96EA 723A 96EB 8036 96EC 91CE 96ED 5F25 96EE 77E2 96EF 5384 96F0 5F79 96F1 7D04 96F2 85AC 96F3 8A33 96F4 8E8D 96F5 9756 96F6 67F3 96F7 85AE 96F8 9453 96F9 6109 96FA 6108 96FB 6CB9 96FC 7652 9740 8AED 9741 8F38 9742 552F 9743 4F51 9744 512A 9745 52C7 9746 53CB 9747 5BA5 9748 5E7D 9749 60A0 974A 6182 974B 63D6 974C 6709 974D 67DA 974E 6E67 974F 6D8C 9750 7336 9751 7337 9752 7531 9753 7950 9754 88D5 9755 8A98 9756 904A 9757 9091 9758 90F5 9759 96C4 975A 878D 975B 5915 975C 4E88 975D 4F59 975E 4E0E 975F 8A89 9760 8F3F 9761 9810 9762 50AD 9763 5E7C 9764 5996 9765 5BB9 9766 5EB8 9767 63DA 9768 63FA 9769 64C1 976A 66DC 976B 694A 976C 69D8 976D 6D0B 976E 6EB6 976F 7194 9770 7528 9771 7AAF 9772 7F8A 9773 8000 9774 8449 9775 84C9 9776 8981 9777 8B21 9778 8E0A 9779 9065 977A 967D 977B 990A 977C 617E 977D 6291 977E 6B32 9780 6C83 9781 6D74 9782 7FCC 9783 7FFC 9784 6DC0 9785 7F85 9786 87BA 9787 88F8 9788 6765 9789 83B1 978A 983C 978B 96F7 978C 6D1B 978D 7D61 978E 843D 978F 916A 9790 4E71 9791 5375 9792 5D50 9793 6B04 9794 6FEB 9795 85CD 9796 862D 9797 89A7 9798 5229 9799 540F 979A 5C65 979B 674E 979C 68A8 979D 7406 979E 7483 979F 75E2 97A0 88CF 97A1 88E1 97A2 91CC 97A3 96E2 97A4 9678 97A5 5F8B 97A6 7387 97A7 7ACB 97A8 844E 97A9 63A0 97AA 7565 97AB 5289 97AC 6D41 97AD 6E9C 97AE 7409 97AF 7559 97B0 786B 97B1 7C92 97B2 9686 97B3 7ADC 97B4 9F8D 97B5 4FB6 97B6 616E 97B7 65C5 97B8 865C 97B9 4E86 97BA 4EAE 97BB 50DA 97BC 4E21 97BD 51CC 97BE 5BEE 97BF 6599 97C0 6881 97C1 6DBC 97C2 731F 97C3 7642 97C4 77AD 97C5 7A1C 97C6 7CE7 97C7 826F 97C8 8AD2 97C9 907C 97CA 91CF 97CB 9675 97CC 9818 97CD 529B 97CE 7DD1 97CF 502B 97D0 5398 97D1 6797 97D2 6DCB 97D3 71D0 97D4 7433 97D5 81E8 97D6 8F2A 97D7 96A3 97D8 9C57 97D9 9E9F 97DA 7460 97DB 5841 97DC 6D99 97DD 7D2F 97DE 985E 97DF 4EE4 97E0 4F36 97E1 4F8B 97E2 51B7 97E3 52B1 97E4 5DBA 97E5 601C 97E6 73B2 97E7 793C 97E8 82D3 97E9 9234 97EA 96B7 97EB 96F6 97EC 970A 97ED 9E97 97EE 9F62 97EF 66A6 97F0 6B74 97F1 5217 97F2 52A3 97F3 70C8 97F4 88C2 97F5 5EC9 97F6 604B 97F7 6190 97F8 6F23 97F9 7149 97FA 7C3E 97FB 7DF4 97FC 806F 9840 84EE 9841 9023 9842 932C 9843 5442 9844 9B6F 9845 6AD3 9846 7089 9847 8CC2 9848 8DEF 9849 9732 984A 52B4 984B 5A41 984C 5ECA 984D 5F04 984E 6717 984F 697C 9850 6994 9851 6D6A 9852 6F0F 9853 7262 9854 72FC 9855 7BED 9856 8001 9857 807E 9858 874B 9859 90CE 985A 516D 985B 9E93 985C 7984 985D 808B 985E 9332 985F 8AD6 9860 502D 9861 548C 9862 8A71 9863 6B6A 9864 8CC4 9865 8107 9866 60D1 9867 67A0 9868 9DF2 9869 4E99 986A 4E98 986B 9C10 986C 8A6B 986D 85C1 986E 8568 986F 6900 9870 6E7E 9871 7897 9872 8155 9874 5B41 9875 5B56 9876 5B7D 9877 5B93 9878 5BD8 9879 5BEC 987A 5C12 987B 5C1E 987C 5C23 987D 5C2B 987E 378D 9880 5C62 9881 FA3B 9882 FA3C 9883 216B4 9884 5C7A 9885 5C8F 9886 5C9F 9887 5CA3 9888 5CAA 9889 5CBA 988A 5CCB 988B 5CD0 988C 5CD2 988D 5CF4 988E 21E34 988F 37E2 9890 5D0D 9891 5D27 9892 FA11 9893 5D46 9894 5D47 9895 5D53 9896 5D4A 9897 5D6D 9898 5D81 9899 5DA0 989A 5DA4 989B 5DA7 989C 5DB8 989D 5DCB 989F 5F0C 98A0 4E10 98A1 4E15 98A2 4E2A 98A3 4E31 98A4 4E36 98A5 4E3C 98A6 4E3F 98A7 4E42 98A8 4E56 98A9 4E58 98AA 4E82 98AB 4E85 98AC 8C6B 98AD 4E8A 98AE 8212 98AF 5F0D 98B0 4E8E 98B1 4E9E 98B2 4E9F 98B3 4EA0 98B4 4EA2 98B5 4EB0 98B6 4EB3 98B7 4EB6 98B8 4ECE 98B9 4ECD 98BA 4EC4 98BB 4EC6 98BC 4EC2 98BD 4ED7 98BE 4EDE 98BF 4EED 98C0 4EDF 98C1 4EF7 98C2 4F09 98C3 4F5A 98C4 4F30 98C5 4F5B 98C6 4F5D 98C7 4F57 98C8 4F47 98C9 4F76 98CA 4F88 98CB 4F8F 98CC 4F98 98CD 4F7B 98CE 4F69 98CF 4F70 98D0 4F91 98D1 4F6F 98D2 4F86 98D3 4F96 98D4 5118 98D5 4FD4 98D6 4FDF 98D7 4FCE 98D8 4FD8 98D9 4FDB 98DA 4FD1 98DB 4FDA 98DC 4FD0 98DD 4FE4 98DE 4FE5 98DF 501A 98E0 5028 98E1 5014 98E2 502A 98E3 5025 98E4 5005 98E5 4F1C 98E6 4FF6 98E7 5021 98E8 5029 98E9 502C 98EA 4FFE 98EB 4FEF 98EC 5011 98ED 5006 98EE 5043 98EF 5047 98F0 6703 98F1 5055 98F2 5050 98F3 5048 98F4 505A 98F5 5056 98F6 506C 98F7 5078 98F8 5080 98F9 509A 98FA 5085 98FB 50B4 98FC 50B2 9940 50C9 9941 50CA 9942 50B3 9943 50C2 9944 50D6 9945 50DE 9946 50E5 9947 50ED 9948 50E3 9949 50EE 994A 50F9 994B 50F5 994C 5109 994D 5101 994E 5102 994F 5116 9950 5115 9951 5114 9952 511A 9953 5121 9954 513A 9955 5137 9956 513C 9957 513B 9958 513F 9959 5140 995A 5152 995B 514C 995C 5154 995D 5162 995E 7AF8 995F 5169 9960 516A 9961 516E 9962 5180 9963 5182 9964 56D8 9965 518C 9966 5189 9967 518F 9968 5191 9969 5193 996A 5195 996B 5196 996C 51A4 996D 51A6 996E 51A2 996F 51A9 9970 51AA 9971 51AB 9972 51B3 9973 51B1 9974 51B2 9975 51B0 9976 51B5 9977 51BD 9978 51C5 9979 51C9 997A 51DB 997B 51E0 997C 8655 997D 51E9 997E 51ED 9980 51F0 9981 51F5 9982 51FE 9983 5204 9984 520B 9985 5214 9986 520E 9987 5227 9988 522A 9989 522E 998A 5233 998B 5239 998C 524F 998D 5244 998E 524B 998F 524C 9990 525E 9991 5254 9992 526A 9993 5274 9994 5269 9995 5273 9996 527F 9997 527D 9998 528D 9999 5294 999A 5292 999B 5271 999C 5288 999D 5291 999E 8FA8 999F 8FA7 99A0 52AC 99A1 52AD 99A2 52BC 99A3 52B5 99A4 52C1 99A5 52CD 99A6 52D7 99A7 52DE 99A8 52E3 99A9 52E6 99AA 98ED 99AB 52E0 99AC 52F3 99AD 52F5 99AE 52F8 99AF 52F9 99B0 5306 99B1 5308 99B2 7538 99B3 530D 99B4 5310 99B5 530F 99B6 5315 99B7 531A 99B8 5323 99B9 532F 99BA 5331 99BB 5333 99BC 5338 99BD 5340 99BE 5346 99BF 5345 99C0 4E17 99C1 5349 99C2 534D 99C3 51D6 99C4 535E 99C5 5369 99C6 536E 99C7 5918 99C8 537B 99C9 5377 99CA 5382 99CB 5396 99CC 53A0 99CD 53A6 99CE 53A5 99CF 53AE 99D0 53B0 99D1 53B6 99D2 53C3 99D3 7C12 99D4 96D9 99D5 53DF 99D6 66FC 99D7 71EE 99D8 53EE 99D9 53E8 99DA 53ED 99DB 53FA 99DC 5401 99DD 543D 99DE 5440 99DF 542C 99E0 542D 99E1 543C 99E2 542E 99E3 5436 99E4 5429 99E5 541D 99E6 544E 99E7 548F 99E8 5475 99E9 548E 99EA 545F 99EB 5471 99EC 5477 99ED 5470 99EE 5492 99EF 547B 99F0 5480 99F1 5476 99F2 5484 99F3 5490 99F4 5486 99F5 54C7 99F6 54A2 99F7 54B8 99F8 54A5 99F9 54AC 99FA 54C4 99FB 54C8 99FC 54A8 9A40 54AB 9A41 54C2 9A42 54A4 9A43 54BE 9A44 54BC 9A45 54D8 9A46 54E5 9A47 54E6 9A48 550F 9A49 5514 9A4A 54FD 9A4B 54EE 9A4C 54ED 9A4D 54FA 9A4E 54E2 9A4F 5539 9A50 5540 9A51 5563 9A52 554C 9A53 552E 9A54 555C 9A55 5545 9A56 5556 9A57 5557 9A58 5538 9A59 5533 9A5A 555D 9A5B 5599 9A5C 5580 9A5D 54AF 9A5E 558A 9A5F 559F 9A60 557B 9A61 557E 9A62 5598 9A63 559E 9A64 55AE 9A65 557C 9A66 5583 9A67 55A9 9A68 5587 9A69 55A8 9A6A 55DA 9A6B 55C5 9A6C 55DF 9A6D 55C4 9A6E 55DC 9A6F 55E4 9A70 55D4 9A71 5614 9A72 55F7 9A73 5616 9A74 55FE 9A75 55FD 9A76 561B 9A77 55F9 9A78 564E 9A79 5650 9A7A 71DF 9A7B 5634 9A7C 5636 9A7D 5632 9A7E 5638 9A80 566B 9A81 5664 9A82 562F 9A83 566C 9A84 566A 9A85 5686 9A86 5680 9A87 568A 9A88 56A0 9A89 5694 9A8A 568F 9A8B 56A5 9A8C 56AE 9A8D 56B6 9A8E 56B4 9A8F 56C2 9A90 56BC 9A91 56C1 9A92 56C3 9A93 56C0 9A94 56C8 9A95 56CE 9A96 56D1 9A97 56D3 9A98 56D7 9A99 56EE 9A9A 56F9 9A9B 5700 9A9C 56FF 9A9D 5704 9A9E 5709 9A9F 5708 9AA0 570B 9AA1 570D 9AA2 5713 9AA3 5718 9AA4 5716 9AA5 55C7 9AA6 571C 9AA7 5726 9AA8 5737 9AA9 5738 9AAA 574E 9AAB 573B 9AAC 5740 9AAD 574F 9AAE 5769 9AAF 57C0 9AB0 5788 9AB1 5761 9AB2 577F 9AB3 5789 9AB4 5793 9AB5 57A0 9AB6 57B3 9AB7 57A4 9AB8 57AA 9AB9 57B0 9ABA 57C3 9ABB 57C6 9ABC 57D4 9ABD 57D2 9ABE 57D3 9ABF 580A 9AC0 57D6 9AC1 57E3 9AC2 580B 9AC3 5819 9AC4 581D 9AC5 5872 9AC6 5821 9AC7 5862 9AC8 584B 9AC9 5870 9ACA 6BC0 9ACB 5852 9ACC 583D 9ACD 5879 9ACE 5885 9ACF 58B9 9AD0 589F 9AD1 58AB 9AD2 58BA 9AD3 58DE 9AD4 58BB 9AD5 58B8 9AD6 58AE 9AD7 58C5 9AD8 58D3 9AD9 58D1 9ADA 58D7 9ADB 58D9 9ADC 58D8 9ADD 58E5 9ADE 58DC 9ADF 58E4 9AE0 58DF 9AE1 58EF 9AE2 58FA 9AE3 58F9 9AE4 58FB 9AE5 58FC 9AE6 58FD 9AE7 5902 9AE8 590A 9AE9 5910 9AEA 591B 9AEB 68A6 9AEC 5925 9AED 592C 9AEE 592D 9AEF 5932 9AF0 5938 9AF1 593E 9AF2 7AD2 9AF3 5955 9AF4 5950 9AF5 594E 9AF6 595A 9AF7 5958 9AF8 5962 9AF9 5960 9AFA 5967 9AFB 596C 9AFC 5969 9B40 5978 9B41 5981 9B42 599D 9B43 4F5E 9B44 4FAB 9B45 59A3 9B46 59B2 9B47 59C6 9B48 59E8 9B49 59DC 9B4A 598D 9B4B 59D9 9B4C 59DA 9B4D 5A25 9B4E 5A1F 9B4F 5A11 9B50 5A1C 9B51 5A09 9B52 5A1A 9B53 5A40 9B54 5A6C 9B55 5A49 9B56 5A35 9B57 5A36 9B58 5A62 9B59 5A6A 9B5A 5A9A 9B5B 5ABC 9B5C 5ABE 9B5D 5ACB 9B5E 5AC2 9B5F 5ABD 9B60 5AE3 9B61 5AD7 9B62 5AE6 9B63 5AE9 9B64 5AD6 9B65 5AFA 9B66 5AFB 9B67 5B0C 9B68 5B0B 9B69 5B16 9B6A 5B32 9B6B 5AD0 9B6C 5B2A 9B6D 5B36 9B6E 5B3E 9B6F 5B43 9B70 5B45 9B71 5B40 9B72 5B51 9B73 5B55 9B74 5B5A 9B75 5B5B 9B76 5B65 9B77 5B69 9B78 5B70 9B79 5B73 9B7A 5B75 9B7B 5B78 9B7C 6588 9B7D 5B7A 9B7E 5B80 9B80 5B83 9B81 5BA6 9B82 5BB8 9B83 5BC3 9B84 5BC7 9B85 5BC9 9B86 5BD4 9B87 5BD0 9B88 5BE4 9B89 5BE6 9B8A 5BE2 9B8B 5BDE 9B8C 5BE5 9B8D 5BEB 9B8E 5BF0 9B8F 5BF6 9B90 5BF3 9B91 5C05 9B92 5C07 9B93 5C08 9B94 5C0D 9B95 5C13 9B96 5C20 9B97 5C22 9B98 5C28 9B99 5C38 9B9A 5C39 9B9B 5C41 9B9C 5C46 9B9D 5C4E 9B9E 5C53 9B9F 5C50 9BA0 5C4F 9BA1 5B71 9BA2 5C6C 9BA3 5C6E 9BA4 4E62 9BA5 5C76 9BA6 5C79 9BA7 5C8C 9BA8 5C91 9BA9 5C94 9BAA 599B 9BAB 5CAB 9BAC 5CBB 9BAD 5CB6 9BAE 5CBC 9BAF 5CB7 9BB0 5CC5 9BB1 5CBE 9BB2 5CC7 9BB3 5CD9 9BB4 5CE9 9BB5 5CFD 9BB6 5CFA 9BB7 5CED 9BB8 5D8C 9BB9 5CEA 9BBA 5D0B 9BBB 5D15 9BBC 5D17 9BBD 5D5C 9BBE 5D1F 9BBF 5D1B 9BC0 5D11 9BC1 5D14 9BC2 5D22 9BC3 5D1A 9BC4 5D19 9BC5 5D18 9BC6 5D4C 9BC7 5D52 9BC8 5D4E 9BC9 5D4B 9BCA 5D6C 9BCB 5D73 9BCC 5D76 9BCD 5D87 9BCE 5D84 9BCF 5D82 9BD0 5DA2 9BD1 5D9D 9BD2 5DAC 9BD3 5DAE 9BD4 5DBD 9BD5 5D90 9BD6 5DB7 9BD7 5DBC 9BD8 5DC9 9BD9 5DCD 9BDA 5DD3 9BDB 5DD2 9BDC 5DD6 9BDD 5DDB 9BDE 5DEB 9BDF 5DF2 9BE0 5DF5 9BE1 5E0B 9BE2 5E1A 9BE3 5E19 9BE4 5E11 9BE5 5E1B 9BE6 5E36 9BE7 5E37 9BE8 5E44 9BE9 5E43 9BEA 5E40 9BEB 5E4E 9BEC 5E57 9BED 5E54 9BEE 5E5F 9BEF 5E62 9BF0 5E64 9BF1 5E47 9BF2 5E75 9BF3 5E76 9BF4 5E7A 9BF5 9EBC 9BF6 5E7F 9BF7 5EA0 9BF8 5EC1 9BF9 5EC2 9BFA 5EC8 9BFB 5ED0 9BFC 5ECF 9C40 5ED6 9C41 5EE3 9C42 5EDD 9C43 5EDA 9C44 5EDB 9C45 5EE2 9C46 5EE1 9C47 5EE8 9C48 5EE9 9C49 5EEC 9C4A 5EF1 9C4B 5EF3 9C4C 5EF0 9C4D 5EF4 9C4E 5EF8 9C4F 5EFE 9C50 5F03 9C51 5F09 9C52 5F5D 9C53 5F5C 9C54 5F0B 9C55 5F11 9C56 5F16 9C57 5F29 9C58 5F2D 9C59 5F38 9C5A 5F41 9C5B 5F48 9C5C 5F4C 9C5D 5F4E 9C5E 5F2F 9C5F 5F51 9C60 5F56 9C61 5F57 9C62 5F59 9C63 5F61 9C64 5F6D 9C65 5F73 9C66 5F77 9C67 5F83 9C68 5F82 9C69 5F7F 9C6A 5F8A 9C6B 5F88 9C6C 5F91 9C6D 5F87 9C6E 5F9E 9C6F 5F99 9C70 5F98 9C71 5FA0 9C72 5FA8 9C73 5FAD 9C74 5FBC 9C75 5FD6 9C76 5FFB 9C77 5FE4 9C78 5FF8 9C79 5FF1 9C7A 5FDD 9C7B 60B3 9C7C 5FFF 9C7D 6021 9C7E 6060 9C80 6019 9C81 6010 9C82 6029 9C83 600E 9C84 6031 9C85 601B 9C86 6015 9C87 602B 9C88 6026 9C89 600F 9C8A 603A 9C8B 605A 9C8C 6041 9C8D 606A 9C8E 6077 9C8F 605F 9C90 604A 9C91 6046 9C92 604D 9C93 6063 9C94 6043 9C95 6064 9C96 6042 9C97 606C 9C98 606B 9C99 6059 9C9A 6081 9C9B 608D 9C9C 60E7 9C9D 6083 9C9E 609A 9C9F 6084 9CA0 609B 9CA1 6096 9CA2 6097 9CA3 6092 9CA4 60A7 9CA5 608B 9CA6 60E1 9CA7 60B8 9CA8 60E0 9CA9 60D3 9CAA 60B4 9CAB 5FF0 9CAC 60BD 9CAD 60C6 9CAE 60B5 9CAF 60D8 9CB0 614D 9CB1 6115 9CB2 6106 9CB3 60F6 9CB4 60F7 9CB5 6100 9CB6 60F4 9CB7 60FA 9CB8 6103 9CB9 6121 9CBA 60FB 9CBB 60F1 9CBC 610D 9CBD 610E 9CBE 6147 9CBF 613E 9CC0 6128 9CC1 6127 9CC2 614A 9CC3 613F 9CC4 613C 9CC5 612C 9CC6 6134 9CC7 613D 9CC8 6142 9CC9 6144 9CCA 6173 9CCB 6177 9CCC 6158 9CCD 6159 9CCE 615A 9CCF 616B 9CD0 6174 9CD1 616F 9CD2 6165 9CD3 6171 9CD4 615F 9CD5 615D 9CD6 6153 9CD7 6175 9CD8 6199 9CD9 6196 9CDA 6187 9CDB 61AC 9CDC 6194 9CDD 619A 9CDE 618A 9CDF 6191 9CE0 61AB 9CE1 61AE 9CE2 61CC 9CE3 61CA 9CE4 61C9 9CE5 61F7 9CE6 61C8 9CE7 61C3 9CE8 61C6 9CE9 61BA 9CEA 61CB 9CEB 7F79 9CEC 61CD 9CED 61E6 9CEE 61E3 9CEF 61F6 9CF0 61FA 9CF1 61F4 9CF2 61FF 9CF3 61FD 9CF4 61FC 9CF5 61FE 9CF6 6200 9CF7 6208 9CF8 6209 9CF9 620D 9CFA 620C 9CFB 6214 9CFC 621B 9D40 621E 9D41 6221 9D42 622A 9D43 622E 9D44 6230 9D45 6232 9D46 6233 9D47 6241 9D48 624E 9D49 625E 9D4A 6263 9D4B 625B 9D4C 6260 9D4D 6268 9D4E 627C 9D4F 6282 9D50 6289 9D51 627E 9D52 6292 9D53 6293 9D54 6296 9D55 62D4 9D56 6283 9D57 6294 9D58 62D7 9D59 62D1 9D5A 62BB 9D5B 62CF 9D5C 62FF 9D5D 62C6 9D5E 64D4 9D5F 62C8 9D60 62DC 9D61 62CC 9D62 62CA 9D63 62C2 9D64 62C7 9D65 629B 9D66 62C9 9D67 630C 9D68 62EE 9D69 62F1 9D6A 6327 9D6B 6302 9D6C 6308 9D6D 62EF 9D6E 62F5 9D6F 6350 9D70 633E 9D71 634D 9D72 641C 9D73 634F 9D74 6396 9D75 638E 9D76 6380 9D77 63AB 9D78 6376 9D79 63A3 9D7A 638F 9D7B 6389 9D7C 639F 9D7D 63B5 9D7E 636B 9D80 6369 9D81 63BE 9D82 63E9 9D83 63C0 9D84 63C6 9D85 63E3 9D86 63C9 9D87 63D2 9D88 63F6 9D89 63C4 9D8A 6416 9D8B 6434 9D8C 6406 9D8D 6413 9D8E 6426 9D8F 6436 9D90 651D 9D91 6417 9D92 6428 9D93 640F 9D94 6467 9D95 646F 9D96 6476 9D97 644E 9D98 652A 9D99 6495 9D9A 6493 9D9B 64A5 9D9C 64A9 9D9D 6488 9D9E 64BC 9D9F 64DA 9DA0 64D2 9DA1 64C5 9DA2 64C7 9DA3 64BB 9DA4 64D8 9DA5 64C2 9DA6 64F1 9DA7 64E7 9DA8 8209 9DA9 64E0 9DAA 64E1 9DAB 62AC 9DAC 64E3 9DAD 64EF 9DAE 652C 9DAF 64F6 9DB0 64F4 9DB1 64F2 9DB2 64FA 9DB3 6500 9DB4 64FD 9DB5 6518 9DB6 651C 9DB7 6505 9DB8 6524 9DB9 6523 9DBA 652B 9DBB 6534 9DBC 6535 9DBD 6537 9DBE 6536 9DBF 6538 9DC0 754B 9DC1 6548 9DC2 6556 9DC3 6555 9DC4 654D 9DC5 6558 9DC6 655E 9DC7 655D 9DC8 6572 9DC9 6578 9DCA 6582 9DCB 6583 9DCC 8B8A 9DCD 659B 9DCE 659F 9DCF 65AB 9DD0 65B7 9DD1 65C3 9DD2 65C6 9DD3 65C1 9DD4 65C4 9DD5 65CC 9DD6 65D2 9DD7 65DB 9DD8 65D9 9DD9 65E0 9DDA 65E1 9DDB 65F1 9DDC 6772 9DDD 660A 9DDE 6603 9DDF 65FB 9DE0 6773 9DE1 6635 9DE2 6636 9DE3 6634 9DE4 661C 9DE5 664F 9DE6 6644 9DE7 6649 9DE8 6641 9DE9 665E 9DEA 665D 9DEB 6664 9DEC 6667 9DED 6668 9DEE 665F 9DEF 6662 9DF0 6670 9DF1 6683 9DF2 6688 9DF3 668E 9DF4 6689 9DF5 6684 9DF6 6698 9DF7 669D 9DF8 66C1 9DF9 66B9 9DFA 66C9 9DFB 66BE 9DFC 66BC 9E40 66C4 9E41 66B8 9E42 66D6 9E43 66DA 9E44 66E0 9E45 663F 9E46 66E6 9E47 66E9 9E48 66F0 9E49 66F5 9E4A 66F7 9E4B 670F 9E4C 6716 9E4D 671E 9E4E 6726 9E4F 6727 9E50 9738 9E51 672E 9E52 673F 9E53 6736 9E54 6741 9E55 6738 9E56 6737 9E57 6746 9E58 675E 9E59 6760 9E5A 6759 9E5B 6763 9E5C 6764 9E5D 6789 9E5E 6770 9E5F 67A9 9E60 677C 9E61 676A 9E62 678C 9E63 678B 9E64 67A6 9E65 67A1 9E66 6785 9E67 67B7 9E68 67EF 9E69 67B4 9E6A 67EC 9E6B 67B3 9E6C 67E9 9E6D 67B8 9E6E 67E4 9E6F 67DE 9E70 67DD 9E71 67E2 9E72 67EE 9E73 67B9 9E74 67CE 9E75 67C6 9E76 67E7 9E77 6A9C 9E78 681E 9E79 6846 9E7A 6829 9E7B 6840 9E7C 684D 9E7D 6832 9E7E 684E 9E80 68B3 9E81 682B 9E82 6859 9E83 6863 9E84 6877 9E85 687F 9E86 689F 9E87 688F 9E88 68AD 9E89 6894 9E8A 689D 9E8B 689B 9E8C 6883 9E8D 6AAE 9E8E 68B9 9E8F 6874 9E90 68B5 9E91 68A0 9E92 68BA 9E93 690F 9E94 688D 9E95 687E 9E96 6901 9E97 68CA 9E98 6908 9E99 68D8 9E9A 6922 9E9B 6926 9E9C 68E1 9E9D 690C 9E9E 68CD 9E9F 68D4 9EA0 68E7 9EA1 68D5 9EA2 6936 9EA3 6912 9EA4 6904 9EA5 68D7 9EA6 68E3 9EA7 6925 9EA8 68F9 9EA9 68E0 9EAA 68EF 9EAB 6928 9EAC 692A 9EAD 691A 9EAE 6923 9EAF 6921 9EB0 68C6 9EB1 6979 9EB2 6977 9EB3 695C 9EB4 6978 9EB5 696B 9EB6 6954 9EB7 697E 9EB8 696E 9EB9 6939 9EBA 6974 9EBB 693D 9EBC 6959 9EBD 6930 9EBE 6961 9EBF 695E 9EC0 695D 9EC1 6981 9EC2 696A 9EC3 69B2 9EC4 69AE 9EC5 69D0 9EC6 69BF 9EC7 69C1 9EC8 69D3 9EC9 69BE 9ECA 69CE 9ECB 5BE8 9ECC 69CA 9ECD 69DD 9ECE 69BB 9ECF 69C3 9ED0 69A7 9ED1 6A2E 9ED2 6991 9ED3 69A0 9ED4 699C 9ED5 6995 9ED6 69B4 9ED7 69DE 9ED8 69E8 9ED9 6A02 9EDA 6A1B 9EDB 69FF 9EDC 6B0A 9EDD 69F9 9EDE 69F2 9EDF 69E7 9EE0 6A05 9EE1 69B1 9EE2 6A1E 9EE3 69ED 9EE4 6A14 9EE5 69EB 9EE6 6A0A 9EE7 6A12 9EE8 6AC1 9EE9 6A23 9EEA 6A13 9EEB 6A44 9EEC 6A0C 9EED 6A72 9EEE 6A36 9EEF 6A78 9EF0 6A47 9EF1 6A62 9EF2 6A59 9EF3 6A66 9EF4 6A48 9EF5 6A38 9EF6 6A22 9EF7 6A90 9EF8 6A8D 9EF9 6AA0 9EFA 6A84 9EFB 6AA2 9EFC 6AA3 9F40 6A97 9F41 8617 9F42 6ABB 9F43 6AC3 9F44 6AC2 9F45 6AB8 9F46 6AB3 9F47 6AAC 9F48 6ADE 9F49 6AD1 9F4A 6ADF 9F4B 6AAA 9F4C 6ADA 9F4D 6AEA 9F4E 6AFB 9F4F 6B05 9F50 8616 9F51 6AFA 9F52 6B12 9F53 6B16 9F54 9B31 9F55 6B1F 9F56 6B38 9F57 6B37 9F58 76DC 9F59 6B39 9F5A 98EE 9F5B 6B47 9F5C 6B43 9F5D 6B49 9F5E 6B50 9F5F 6B59 9F60 6B54 9F61 6B5B 9F62 6B5F 9F63 6B61 9F64 6B78 9F65 6B79 9F66 6B7F 9F67 6B80 9F68 6B84 9F69 6B83 9F6A 6B8D 9F6B 6B98 9F6C 6B95 9F6D 6B9E 9F6E 6BA4 9F6F 6BAA 9F70 6BAB 9F71 6BAF 9F72 6BB2 9F73 6BB1 9F74 6BB3 9F75 6BB7 9F76 6BBC 9F77 6BC6 9F78 6BCB 9F79 6BD3 9F7A 6BDF 9F7B 6BEC 9F7C 6BEB 9F7D 6BF3 9F7E 6BEF 9F80 9EBE 9F81 6C08 9F82 6C13 9F83 6C14 9F84 6C1B 9F85 6C24 9F86 6C23 9F87 6C5E 9F88 6C55 9F89 6C62 9F8A 6C6A 9F8B 6C82 9F8C 6C8D 9F8D 6C9A 9F8E 6C81 9F8F 6C9B 9F90 6C7E 9F91 6C68 9F92 6C73 9F93 6C92 9F94 6C90 9F95 6CC4 9F96 6CF1 9F97 6CD3 9F98 6CBD 9F99 6CD7 9F9A 6CC5 9F9B 6CDD 9F9C 6CAE 9F9D 6CB1 9F9E 6CBE 9F9F 6CBA 9FA0 6CDB 9FA1 6CEF 9FA2 6CD9 9FA3 6CEA 9FA4 6D1F 9FA5 884D 9FA6 6D36 9FA7 6D2B 9FA8 6D3D 9FA9 6D38 9FAA 6D19 9FAB 6D35 9FAC 6D33 9FAD 6D12 9FAE 6D0C 9FAF 6D63 9FB0 6D93 9FB1 6D64 9FB2 6D5A 9FB3 6D79 9FB4 6D59 9FB5 6D8E 9FB6 6D95 9FB7 6FE4 9FB8 6D85 9FB9 6DF9 9FBA 6E15 9FBB 6E0A 9FBC 6DB5 9FBD 6DC7 9FBE 6DE6 9FBF 6DB8 9FC0 6DC6 9FC1 6DEC 9FC2 6DDE 9FC3 6DCC 9FC4 6DE8 9FC5 6DD2 9FC6 6DC5 9FC7 6DFA 9FC8 6DD9 9FC9 6DE4 9FCA 6DD5 9FCB 6DEA 9FCC 6DEE 9FCD 6E2D 9FCE 6E6E 9FCF 6E2E 9FD0 6E19 9FD1 6E72 9FD2 6E5F 9FD3 6E3E 9FD4 6E23 9FD5 6E6B 9FD6 6E2B 9FD7 6E76 9FD8 6E4D 9FD9 6E1F 9FDA 6E43 9FDB 6E3A 9FDC 6E4E 9FDD 6E24 9FDE 6EFF 9FDF 6E1D 9FE0 6E38 9FE1 6E82 9FE2 6EAA 9FE3 6E98 9FE4 6EC9 9FE5 6EB7 9FE6 6ED3 9FE7 6EBD 9FE8 6EAF 9FE9 6EC4 9FEA 6EB2 9FEB 6ED4 9FEC 6ED5 9FED 6E8F 9FEE 6EA5 9FEF 6EC2 9FF0 6E9F 9FF1 6F41 9FF2 6F11 9FF3 704C 9FF4 6EEC 9FF5 6EF8 9FF6 6EFE 9FF7 6F3F 9FF8 6EF2 9FF9 6F31 9FFA 6EEF 9FFB 6F32 9FFC 6ECC A1 FF61 A2 FF62 A3 FF63 A4 FF64 A5 FF65 A6 FF66 A7 FF67 A8 FF68 A9 FF69 AA FF6A AB FF6B AC FF6C AD FF6D AE FF6E AF FF6F B0 FF70 B1 FF71 B2 FF72 B3 FF73 B4 FF74 B5 FF75 B6 FF76 B7 FF77 B8 FF78 B9 FF79 BA FF7A BB FF7B BC FF7C BD FF7D BE FF7E BF FF7F C0 FF80 C1 FF81 C2 FF82 C3 FF83 C4 FF84 C5 FF85 C6 FF86 C7 FF87 C8 FF88 C9 FF89 CA FF8A CB FF8B CC FF8C CD FF8D CE FF8E CF FF8F D0 FF90 D1 FF91 D2 FF92 D3 FF93 D4 FF94 D5 FF95 D6 FF96 D7 FF97 D8 FF98 D9 FF99 DA FF9A DB FF9B DC FF9C DD FF9D DE FF9E DF FF9F E040 6F3E E041 6F13 E042 6EF7 E043 6F86 E044 6F7A E045 6F78 E046 6F81 E047 6F80 E048 6F6F E049 6F5B E04A 6FF3 E04B 6F6D E04C 6F82 E04D 6F7C E04E 6F58 E04F 6F8E E050 6F91 E051 6FC2 E052 6F66 E053 6FB3 E054 6FA3 E055 6FA1 E056 6FA4 E057 6FB9 E058 6FC6 E059 6FAA E05A 6FDF E05B 6FD5 E05C 6FEC E05D 6FD4 E05E 6FD8 E05F 6FF1 E060 6FEE E061 6FDB E062 7009 E063 700B E064 6FFA E065 7011 E066 7001 E067 700F E068 6FFE E069 701B E06A 701A E06B 6F74 E06C 701D E06D 7018 E06E 701F E06F 7030 E070 703E E071 7032 E072 7051 E073 7063 E074 7099 E075 7092 E076 70AF E077 70F1 E078 70AC E079 70B8 E07A 70B3 E07B 70AE E07C 70DF E07D 70CB E07E 70DD E080 70D9 E081 7109 E082 70FD E083 711C E084 7119 E085 7165 E086 7155 E087 7188 E088 7166 E089 7162 E08A 714C E08B 7156 E08C 716C E08D 718F E08E 71FB E08F 7184 E090 7195 E091 71A8 E092 71AC E093 71D7 E094 71B9 E095 71BE E096 71D2 E097 71C9 E098 71D4 E099 71CE E09A 71E0 E09B 71EC E09C 71E7 E09D 71F5 E09E 71FC E09F 71F9 E0A0 71FF E0A1 720D E0A2 7210 E0A3 721B E0A4 7228 E0A5 722D E0A6 722C E0A7 7230 E0A8 7232 E0A9 723B E0AA 723C E0AB 723F E0AC 7240 E0AD 7246 E0AE 724B E0AF 7258 E0B0 7274 E0B1 727E E0B2 7282 E0B3 7281 E0B4 7287 E0B5 7292 E0B6 7296 E0B7 72A2 E0B8 72A7 E0B9 72B9 E0BA 72B2 E0BB 72C3 E0BC 72C6 E0BD 72C4 E0BE 72CE E0BF 72D2 E0C0 72E2 E0C1 72E0 E0C2 72E1 E0C3 72F9 E0C4 72F7 E0C5 500F E0C6 7317 E0C7 730A E0C8 731C E0C9 7316 E0CA 731D E0CB 7334 E0CC 732F E0CD 7329 E0CE 7325 E0CF 733E E0D0 734E E0D1 734F E0D2 9ED8 E0D3 7357 E0D4 736A E0D5 7368 E0D6 7370 E0D7 7378 E0D8 7375 E0D9 737B E0DA 737A E0DB 73C8 E0DC 73B3 E0DD 73CE E0DE 73BB E0DF 73C0 E0E0 73E5 E0E1 73EE E0E2 73DE E0E3 74A2 E0E4 7405 E0E5 746F E0E6 7425 E0E7 73F8 E0E8 7432 E0E9 743A E0EA 7455 E0EB 743F E0EC 745F E0ED 7459 E0EE 7441 E0EF 745C E0F0 7469 E0F1 7470 E0F2 7463 E0F3 746A E0F4 7476 E0F5 747E E0F6 748B E0F7 749E E0F8 74A7 E0F9 74CA E0FA 74CF E0FB 74D4 E0FC 73F1 E140 74E0 E141 74E3 E142 74E7 E143 74E9 E144 74EE E145 74F2 E146 74F0 E147 74F1 E148 74F8 E149 74F7 E14A 7504 E14B 7503 E14C 7505 E14D 750C E14E 750E E14F 750D E150 7515 E151 7513 E152 751E E153 7526 E154 752C E155 753C E156 7544 E157 754D E158 754A E159 7549 E15A 755B E15B 7546 E15C 755A E15D 7569 E15E 7564 E15F 7567 E160 756B E161 756D E162 7578 E163 7576 E164 7586 E165 7587 E166 7574 E167 758A E168 7589 E169 7582 E16A 7594 E16B 759A E16C 759D E16D 75A5 E16E 75A3 E16F 75C2 E170 75B3 E171 75C3 E172 75B5 E173 75BD E174 75B8 E175 75BC E176 75B1 E177 75CD E178 75CA E179 75D2 E17A 75D9 E17B 75E3 E17C 75DE E17D 75FE E17E 75FF E180 75FC E181 7601 E182 75F0 E183 75FA E184 75F2 E185 75F3 E186 760B E187 760D E188 7609 E189 761F E18A 7627 E18B 7620 E18C 7621 E18D 7622 E18E 7624 E18F 7634 E190 7630 E191 763B E192 7647 E193 7648 E194 7646 E195 765C E196 7658 E197 7661 E198 7662 E199 7668 E19A 7669 E19B 766A E19C 7667 E19D 766C E19E 7670 E19F 7672 E1A0 7676 E1A1 7678 E1A2 767C E1A3 7680 E1A4 7683 E1A5 7688 E1A6 768B E1A7 768E E1A8 7696 E1A9 7693 E1AA 7699 E1AB 769A E1AC 76B0 E1AD 76B4 E1AE 76B8 E1AF 76B9 E1B0 76BA E1B1 76C2 E1B2 76CD E1B3 76D6 E1B4 76D2 E1B5 76DE E1B6 76E1 E1B7 76E5 E1B8 76E7 E1B9 76EA E1BA 862F E1BB 76FB E1BC 7708 E1BD 7707 E1BE 7704 E1BF 7729 E1C0 7724 E1C1 771E E1C2 7725 E1C3 7726 E1C4 771B E1C5 7737 E1C6 7738 E1C7 7747 E1C8 775A E1C9 7768 E1CA 776B E1CB 775B E1CC 7765 E1CD 777F E1CE 777E E1CF 7779 E1D0 778E E1D1 778B E1D2 7791 E1D3 77A0 E1D4 779E E1D5 77B0 E1D6 77B6 E1D7 77B9 E1D8 77BF E1D9 77BC E1DA 77BD E1DB 77BB E1DC 77C7 E1DD 77CD E1DE 77D7 E1DF 77DA E1E0 77DC E1E1 77E3 E1E2 77EE E1E3 77FC E1E4 780C E1E5 7812 E1E6 7926 E1E7 7820 E1E8 792A E1E9 7845 E1EA 788E E1EB 7874 E1EC 7886 E1ED 787C E1EE 789A E1EF 788C E1F0 78A3 E1F1 78B5 E1F2 78AA E1F3 78AF E1F4 78D1 E1F5 78C6 E1F6 78CB E1F7 78D4 E1F8 78BE E1F9 78BC E1FA 78C5 E1FB 78CA E1FC 78EC E240 78E7 E241 78DA E242 78FD E243 78F4 E244 7907 E245 7912 E246 7911 E247 7919 E248 792C E249 792B E24A 7940 E24B 7960 E24C 7957 E24D 795F E24E 795A E24F 7955 E250 7953 E251 797A E252 797F E253 798A E254 799D E255 79A7 E256 9F4B E257 79AA E258 79AE E259 79B3 E25A 79B9 E25B 79BA E25C 79C9 E25D 79D5 E25E 79E7 E25F 79EC E260 79E1 E261 79E3 E262 7A08 E263 7A0D E264 7A18 E265 7A19 E266 7A20 E267 7A1F E268 7980 E269 7A31 E26A 7A3B E26B 7A3E E26C 7A37 E26D 7A43 E26E 7A57 E26F 7A49 E270 7A61 E271 7A62 E272 7A69 E273 9F9D E274 7A70 E275 7A79 E276 7A7D E277 7A88 E278 7A97 E279 7A95 E27A 7A98 E27B 7A96 E27C 7AA9 E27D 7AC8 E27E 7AB0 E280 7AB6 E281 7AC5 E282 7AC4 E283 7ABF E284 9083 E285 7AC7 E286 7ACA E287 7ACD E288 7ACF E289 7AD5 E28A 7AD3 E28B 7AD9 E28C 7ADA E28D 7ADD E28E 7AE1 E28F 7AE2 E290 7AE6 E291 7AED E292 7AF0 E293 7B02 E294 7B0F E295 7B0A E296 7B06 E297 7B33 E298 7B18 E299 7B19 E29A 7B1E E29B 7B35 E29C 7B28 E29D 7B36 E29E 7B50 E29F 7B7A E2A0 7B04 E2A1 7B4D E2A2 7B0B E2A3 7B4C E2A4 7B45 E2A5 7B75 E2A6 7B65 E2A7 7B74 E2A8 7B67 E2A9 7B70 E2AA 7B71 E2AB 7B6C E2AC 7B6E E2AD 7B9D E2AE 7B98 E2AF 7B9F E2B0 7B8D E2B1 7B9C E2B2 7B9A E2B3 7B8B E2B4 7B92 E2B5 7B8F E2B6 7B5D E2B7 7B99 E2B8 7BCB E2B9 7BC1 E2BA 7BCC E2BB 7BCF E2BC 7BB4 E2BD 7BC6 E2BE 7BDD E2BF 7BE9 E2C0 7C11 E2C1 7C14 E2C2 7BE6 E2C3 7BE5 E2C4 7C60 E2C5 7C00 E2C6 7C07 E2C7 7C13 E2C8 7BF3 E2C9 7BF7 E2CA 7C17 E2CB 7C0D E2CC 7BF6 E2CD 7C23 E2CE 7C27 E2CF 7C2A E2D0 7C1F E2D1 7C37 E2D2 7C2B E2D3 7C3D E2D4 7C4C E2D5 7C43 E2D6 7C54 E2D7 7C4F E2D8 7C40 E2D9 7C50 E2DA 7C58 E2DB 7C5F E2DC 7C64 E2DD 7C56 E2DE 7C65 E2DF 7C6C E2E0 7C75 E2E1 7C83 E2E2 7C90 E2E3 7CA4 E2E4 7CAD E2E5 7CA2 E2E6 7CAB E2E7 7CA1 E2E8 7CA8 E2E9 7CB3 E2EA 7CB2 E2EB 7CB1 E2EC 7CAE E2ED 7CB9 E2EE 7CBD E2EF 7CC0 E2F0 7CC5 E2F1 7CC2 E2F2 7CD8 E2F3 7CD2 E2F4 7CDC E2F5 7CE2 E2F6 9B3B E2F7 7CEF E2F8 7CF2 E2F9 7CF4 E2FA 7CF6 E2FB 7CFA E2FC 7D06 E340 7D02 E341 7D1C E342 7D15 E343 7D0A E344 7D45 E345 7D4B E346 7D2E E347 7D32 E348 7D3F E349 7D35 E34A 7D46 E34B 7D73 E34C 7D56 E34D 7D4E E34E 7D72 E34F 7D68 E350 7D6E E351 7D4F E352 7D63 E353 7D93 E354 7D89 E355 7D5B E356 7D8F E357 7D7D E358 7D9B E359 7DBA E35A 7DAE E35B 7DA3 E35C 7DB5 E35D 7DC7 E35E 7DBD E35F 7DAB E360 7E3D E361 7DA2 E362 7DAF E363 7DDC E364 7DB8 E365 7D9F E366 7DB0 E367 7DD8 E368 7DDD E369 7DE4 E36A 7DDE E36B 7DFB E36C 7DF2 E36D 7DE1 E36E 7E05 E36F 7E0A E370 7E23 E371 7E21 E372 7E12 E373 7E31 E374 7E1F E375 7E09 E376 7E0B E377 7E22 E378 7E46 E379 7E66 E37A 7E3B E37B 7E35 E37C 7E39 E37D 7E43 E37E 7E37 E380 7E32 E381 7E3A E382 7E67 E383 7E5D E384 7E56 E385 7E5E E386 7E59 E387 7E5A E388 7E79 E389 7E6A E38A 7E69 E38B 7E7C E38C 7E7B E38D 7E83 E38E 7DD5 E38F 7E7D E390 8FAE E391 7E7F E392 7E88 E393 7E89 E394 7E8C E395 7E92 E396 7E90 E397 7E93 E398 7E94 E399 7E96 E39A 7E8E E39B 7E9B E39C 7E9C E39D 7F38 E39E 7F3A E39F 7F45 E3A0 7F4C E3A1 7F4D E3A2 7F4E E3A3 7F50 E3A4 7F51 E3A5 7F55 E3A6 7F54 E3A7 7F58 E3A8 7F5F E3A9 7F60 E3AA 7F68 E3AB 7F69 E3AC 7F67 E3AD 7F78 E3AE 7F82 E3AF 7F86 E3B0 7F83 E3B1 7F88 E3B2 7F87 E3B3 7F8C E3B4 7F94 E3B5 7F9E E3B6 7F9D E3B7 7F9A E3B8 7FA3 E3B9 7FAF E3BA 7FB2 E3BB 7FB9 E3BC 7FAE E3BD 7FB6 E3BE 7FB8 E3BF 8B71 E3C0 7FC5 E3C1 7FC6 E3C2 7FCA E3C3 7FD5 E3C4 7FD4 E3C5 7FE1 E3C6 7FE6 E3C7 7FE9 E3C8 7FF3 E3C9 7FF9 E3CA 98DC E3CB 8006 E3CC 8004 E3CD 800B E3CE 8012 E3CF 8018 E3D0 8019 E3D1 801C E3D2 8021 E3D3 8028 E3D4 803F E3D5 803B E3D6 804A E3D7 8046 E3D8 8052 E3D9 8058 E3DA 805A E3DB 805F E3DC 8062 E3DD 8068 E3DE 8073 E3DF 8072 E3E0 8070 E3E1 8076 E3E2 8079 E3E3 807D E3E4 807F E3E5 8084 E3E6 8086 E3E7 8085 E3E8 809B E3E9 8093 E3EA 809A E3EB 80AD E3EC 5190 E3ED 80AC E3EE 80DB E3EF 80E5 E3F0 80D9 E3F1 80DD E3F2 80C4 E3F3 80DA E3F4 80D6 E3F5 8109 E3F6 80EF E3F7 80F1 E3F8 811B E3F9 8129 E3FA 8123 E3FB 812F E3FC 814B E440 968B E441 8146 E442 813E E443 8153 E444 8151 E445 80FC E446 8171 E447 816E E448 8165 E449 8166 E44A 8174 E44B 8183 E44C 8188 E44D 818A E44E 8180 E44F 8182 E450 81A0 E451 8195 E452 81A4 E453 81A3 E454 815F E455 8193 E456 81A9 E457 81B0 E458 81B5 E459 81BE E45A 81B8 E45B 81BD E45C 81C0 E45D 81C2 E45E 81BA E45F 81C9 E460 81CD E461 81D1 E462 81D9 E463 81D8 E464 81C8 E465 81DA E466 81DF E467 81E0 E468 81E7 E469 81FA E46A 81FB E46B 81FE E46C 8201 E46D 8202 E46E 8205 E46F 8207 E470 820A E471 820D E472 8210 E473 8216 E474 8229 E475 822B E476 8238 E477 8233 E478 8240 E479 8259 E47A 8258 E47B 825D E47C 825A E47D 825F E47E 8264 E480 8262 E481 8268 E482 826A E483 826B E484 822E E485 8271 E486 8277 E487 8278 E488 827E E489 828D E48A 8292 E48B 82AB E48C 829F E48D 82BB E48E 82AC E48F 82E1 E490 82E3 E491 82DF E492 82D2 E493 82F4 E494 82F3 E495 82FA E496 8393 E497 8303 E498 82FB E499 82F9 E49A 82DE E49B 8306 E49C 82DC E49D 8309 E49E 82D9 E49F 8335 E4A0 8334 E4A1 8316 E4A2 8332 E4A3 8331 E4A4 8340 E4A5 8339 E4A6 8350 E4A7 8345 E4A8 832F E4A9 832B E4AA 8317 E4AB 8318 E4AC 8385 E4AD 839A E4AE 83AA E4AF 839F E4B0 83A2 E4B1 8396 E4B2 8323 E4B3 838E E4B4 8387 E4B5 838A E4B6 837C E4B7 83B5 E4B8 8373 E4B9 8375 E4BA 83A0 E4BB 8389 E4BC 83A8 E4BD 83F4 E4BE 8413 E4BF 83EB E4C0 83CE E4C1 83FD E4C2 8403 E4C3 83D8 E4C4 840B E4C5 83C1 E4C6 83F7 E4C7 8407 E4C8 83E0 E4C9 83F2 E4CA 840D E4CB 8422 E4CC 8420 E4CD 83BD E4CE 8438 E4CF 8506 E4D0 83FB E4D1 846D E4D2 842A E4D3 843C E4D4 855A E4D5 8484 E4D6 8477 E4D7 846B E4D8 84AD E4D9 846E E4DA 8482 E4DB 8469 E4DC 8446 E4DD 842C E4DE 846F E4DF 8479 E4E0 8435 E4E1 84CA E4E2 8462 E4E3 84B9 E4E4 84BF E4E5 849F E4E6 84D9 E4E7 84CD E4E8 84BB E4E9 84DA E4EA 84D0 E4EB 84C1 E4EC 84C6 E4ED 84D6 E4EE 84A1 E4EF 8521 E4F0 84FF E4F1 84F4 E4F2 8517 E4F3 8518 E4F4 852C E4F5 851F E4F6 8515 E4F7 8514 E4F8 84FC E4F9 8540 E4FA 8563 E4FB 8558 E4FC 8548 E540 8541 E541 8602 E542 854B E543 8555 E544 8580 E545 85A4 E546 8588 E547 8591 E548 858A E549 85A8 E54A 856D E54B 8594 E54C 859B E54D 85EA E54E 8587 E54F 859C E550 8577 E551 857E E552 8590 E553 85C9 E554 85BA E555 85CF E556 85B9 E557 85D0 E558 85D5 E559 85DD E55A 85E5 E55B 85DC E55C 85F9 E55D 860A E55E 8613 E55F 860B E560 85FE E561 85FA E562 8606 E563 8622 E564 861A E565 8630 E566 863F E567 864D E568 4E55 E569 8654 E56A 865F E56B 8667 E56C 8671 E56D 8693 E56E 86A3 E56F 86A9 E570 86AA E571 868B E572 868C E573 86B6 E574 86AF E575 86C4 E576 86C6 E577 86B0 E578 86C9 E579 8823 E57A 86AB E57B 86D4 E57C 86DE E57D 86E9 E57E 86EC E580 86DF E581 86DB E582 86EF E583 8712 E584 8706 E585 8708 E586 8700 E587 8703 E588 86FB E589 8711 E58A 8709 E58B 870D E58C 86F9 E58D 870A E58E 8734 E58F 873F E590 8737 E591 873B E592 8725 E593 8729 E594 871A E595 8760 E596 875F E597 8778 E598 874C E599 874E E59A 8774 E59B 8757 E59C 8768 E59D 876E E59E 8759 E59F 8753 E5A0 8763 E5A1 876A E5A2 8805 E5A3 87A2 E5A4 879F E5A5 8782 E5A6 87AF E5A7 87CB E5A8 87BD E5A9 87C0 E5AA 87D0 E5AB 96D6 E5AC 87AB E5AD 87C4 E5AE 87B3 E5AF 87C7 E5B0 87C6 E5B1 87BB E5B2 87EF E5B3 87F2 E5B4 87E0 E5B5 880F E5B6 880D E5B7 87FE E5B8 87F6 E5B9 87F7 E5BA 880E E5BB 87D2 E5BC 8811 E5BD 8816 E5BE 8815 E5BF 8822 E5C0 8821 E5C1 8831 E5C2 8836 E5C3 8839 E5C4 8827 E5C5 883B E5C6 8844 E5C7 8842 E5C8 8852 E5C9 8859 E5CA 885E E5CB 8862 E5CC 886B E5CD 8881 E5CE 887E E5CF 889E E5D0 8875 E5D1 887D E5D2 88B5 E5D3 8872 E5D4 8882 E5D5 8897 E5D6 8892 E5D7 88AE E5D8 8899 E5D9 88A2 E5DA 888D E5DB 88A4 E5DC 88B0 E5DD 88BF E5DE 88B1 E5DF 88C3 E5E0 88C4 E5E1 88D4 E5E2 88D8 E5E3 88D9 E5E4 88DD E5E5 88F9 E5E6 8902 E5E7 88FC E5E8 88F4 E5E9 88E8 E5EA 88F2 E5EB 8904 E5EC 890C E5ED 890A E5EE 8913 E5EF 8943 E5F0 891E E5F1 8925 E5F2 892A E5F3 892B E5F4 8941 E5F5 8944 E5F6 893B E5F7 8936 E5F8 8938 E5F9 894C E5FA 891D E5FB 8960 E5FC 895E E640 8966 E641 8964 E642 896D E643 896A E644 896F E645 8974 E646 8977 E647 897E E648 8983 E649 8988 E64A 898A E64B 8993 E64C 8998 E64D 89A1 E64E 89A9 E64F 89A6 E650 89AC E651 89AF E652 89B2 E653 89BA E654 89BD E655 89BF E656 89C0 E657 89DA E658 89DC E659 89DD E65A 89E7 E65B 89F4 E65C 89F8 E65D 8A03 E65E 8A16 E65F 8A10 E660 8A0C E661 8A1B E662 8A1D E663 8A25 E664 8A36 E665 8A41 E666 8A5B E667 8A52 E668 8A46 E669 8A48 E66A 8A7C E66B 8A6D E66C 8A6C E66D 8A62 E66E 8A85 E66F 8A82 E670 8A84 E671 8AA8 E672 8AA1 E673 8A91 E674 8AA5 E675 8AA6 E676 8A9A E677 8AA3 E678 8AC4 E679 8ACD E67A 8AC2 E67B 8ADA E67C 8AEB E67D 8AF3 E67E 8AE7 E680 8AE4 E681 8AF1 E682 8B14 E683 8AE0 E684 8AE2 E685 8AF7 E686 8ADE E687 8ADB E688 8B0C E689 8B07 E68A 8B1A E68B 8AE1 E68C 8B16 E68D 8B10 E68E 8B17 E68F 8B20 E690 8B33 E691 97AB E692 8B26 E693 8B2B E694 8B3E E695 8B28 E696 8B41 E697 8B4C E698 8B4F E699 8B4E E69A 8B49 E69B 8B56 E69C 8B5B E69D 8B5A E69E 8B6B E69F 8B5F E6A0 8B6C E6A1 8B6F E6A2 8B74 E6A3 8B7D E6A4 8B80 E6A5 8B8C E6A6 8B8E E6A7 8B92 E6A8 8B93 E6A9 8B96 E6AA 8B99 E6AB 8B9A E6AC 8C3A E6AD 8C41 E6AE 8C3F E6AF 8C48 E6B0 8C4C E6B1 8C4E E6B2 8C50 E6B3 8C55 E6B4 8C62 E6B5 8C6C E6B6 8C78 E6B7 8C7A E6B8 8C82 E6B9 8C89 E6BA 8C85 E6BB 8C8A E6BC 8C8D E6BD 8C8E E6BE 8C94 E6BF 8C7C E6C0 8C98 E6C1 621D E6C2 8CAD E6C3 8CAA E6C4 8CBD E6C5 8CB2 E6C6 8CB3 E6C7 8CAE E6C8 8CB6 E6C9 8CC8 E6CA 8CC1 E6CB 8CE4 E6CC 8CE3 E6CD 8CDA E6CE 8CFD E6CF 8CFA E6D0 8CFB E6D1 8D04 E6D2 8D05 E6D3 8D0A E6D4 8D07 E6D5 8D0F E6D6 8D0D E6D7 8D10 E6D8 9F4E E6D9 8D13 E6DA 8CCD E6DB 8D14 E6DC 8D16 E6DD 8D67 E6DE 8D6D E6DF 8D71 E6E0 8D73 E6E1 8D81 E6E2 8D99 E6E3 8DC2 E6E4 8DBE E6E5 8DBA E6E6 8DCF E6E7 8DDA E6E8 8DD6 E6E9 8DCC E6EA 8DDB E6EB 8DCB E6EC 8DEA E6ED 8DEB E6EE 8DDF E6EF 8DE3 E6F0 8DFC E6F1 8E08 E6F2 8E09 E6F3 8DFF E6F4 8E1D E6F5 8E1E E6F6 8E10 E6F7 8E1F E6F8 8E42 E6F9 8E35 E6FA 8E30 E6FB 8E34 E6FC 8E4A E740 8E47 E741 8E49 E742 8E4C E743 8E50 E744 8E48 E745 8E59 E746 8E64 E747 8E60 E748 8E2A E749 8E63 E74A 8E55 E74B 8E76 E74C 8E72 E74D 8E7C E74E 8E81 E74F 8E87 E750 8E85 E751 8E84 E752 8E8B E753 8E8A E754 8E93 E755 8E91 E756 8E94 E757 8E99 E758 8EAA E759 8EA1 E75A 8EAC E75B 8EB0 E75C 8EC6 E75D 8EB1 E75E 8EBE E75F 8EC5 E760 8EC8 E761 8ECB E762 8EDB E763 8EE3 E764 8EFC E765 8EFB E766 8EEB E767 8EFE E768 8F0A E769 8F05 E76A 8F15 E76B 8F12 E76C 8F19 E76D 8F13 E76E 8F1C E76F 8F1F E770 8F1B E771 8F0C E772 8F26 E773 8F33 E774 8F3B E775 8F39 E776 8F45 E777 8F42 E778 8F3E E779 8F4C E77A 8F49 E77B 8F46 E77C 8F4E E77D 8F57 E77E 8F5C E780 8F62 E781 8F63 E782 8F64 E783 8F9C E784 8F9F E785 8FA3 E786 8FAD E787 8FAF E788 8FB7 E789 8FDA E78A 8FE5 E78B 8FE2 E78C 8FEA E78D 8FEF E78E 9087 E78F 8FF4 E790 9005 E791 8FF9 E792 8FFA E793 9011 E794 9015 E795 9021 E796 900D E797 901E E798 9016 E799 900B E79A 9027 E79B 9036 E79C 9035 E79D 9039 E79E 8FF8 E79F 904F E7A0 9050 E7A1 9051 E7A2 9052 E7A3 900E E7A4 9049 E7A5 903E E7A6 9056 E7A7 9058 E7A8 905E E7A9 9068 E7AA 906F E7AB 9076 E7AC 96A8 E7AD 9072 E7AE 9082 E7AF 907D E7B0 9081 E7B1 9080 E7B2 908A E7B3 9089 E7B4 908F E7B5 90A8 E7B6 90AF E7B7 90B1 E7B8 90B5 E7B9 90E2 E7BA 90E4 E7BB 6248 E7BC 90DB E7BD 9102 E7BE 9112 E7BF 9119 E7C0 9132 E7C1 9130 E7C2 914A E7C3 9156 E7C4 9158 E7C5 9163 E7C6 9165 E7C7 9169 E7C8 9173 E7C9 9172 E7CA 918B E7CB 9189 E7CC 9182 E7CD 91A2 E7CE 91AB E7CF 91AF E7D0 91AA E7D1 91B5 E7D2 91B4 E7D3 91BA E7D4 91C0 E7D5 91C1 E7D6 91C9 E7D7 91CB E7D8 91D0 E7D9 91D6 E7DA 91DF E7DB 91E1 E7DC 91DB E7DD 91FC E7DE 91F5 E7DF 91F6 E7E0 921E E7E1 91FF E7E2 9214 E7E3 922C E7E4 9215 E7E5 9211 E7E6 925E E7E7 9257 E7E8 9245 E7E9 9249 E7EA 9264 E7EB 9248 E7EC 9295 E7ED 923F E7EE 924B E7EF 9250 E7F0 929C E7F1 9296 E7F2 9293 E7F3 929B E7F4 925A E7F5 92CF E7F6 92B9 E7F7 92B7 E7F8 92E9 E7F9 930F E7FA 92FA E7FB 9344 E7FC 932E E840 9319 E841 9322 E842 931A E843 9323 E844 933A E845 9335 E846 933B E847 935C E848 9360 E849 937C E84A 936E E84B 9356 E84C 93B0 E84D 93AC E84E 93AD E84F 9394 E850 93B9 E851 93D6 E852 93D7 E853 93E8 E854 93E5 E855 93D8 E856 93C3 E857 93DD E858 93D0 E859 93C8 E85A 93E4 E85B 941A E85C 9414 E85D 9413 E85E 9403 E85F 9407 E860 9410 E861 9436 E862 942B E863 9435 E864 9421 E865 943A E866 9441 E867 9452 E868 9444 E869 945B E86A 9460 E86B 9462 E86C 945E E86D 946A E86E 9229 E86F 9470 E870 9475 E871 9477 E872 947D E873 945A E874 947C E875 947E E876 9481 E877 947F E878 9582 E879 9587 E87A 958A E87B 9594 E87C 9596 E87D 9598 E87E 9599 E880 95A0 E881 95A8 E882 95A7 E883 95AD E884 95BC E885 95BB E886 95B9 E887 95BE E888 95CA E889 6FF6 E88A 95C3 E88B 95CD E88C 95CC E88D 95D5 E88E 95D4 E88F 95D6 E890 95DC E891 95E1 E892 95E5 E893 95E2 E894 9621 E895 9628 E896 962E E897 962F E898 9642 E899 964C E89A 964F E89B 964B E89C 9677 E89D 965C E89E 965E E89F 965D E8A0 965F E8A1 9666 E8A2 9672 E8A3 966C E8A4 968D E8A5 9698 E8A6 9695 E8A7 9697 E8A8 96AA E8A9 96A7 E8AA 96B1 E8AB 96B2 E8AC 96B0 E8AD 96B4 E8AE 96B6 E8AF 96B8 E8B0 96B9 E8B1 96CE E8B2 96CB E8B3 96C9 E8B4 96CD E8B5 894D E8B6 96DC E8B7 970D E8B8 96D5 E8B9 96F9 E8BA 9704 E8BB 9706 E8BC 9708 E8BD 9713 E8BE 970E E8BF 9711 E8C0 970F E8C1 9716 E8C2 9719 E8C3 9724 E8C4 972A E8C5 9730 E8C6 9739 E8C7 973D E8C8 973E E8C9 9744 E8CA 9746 E8CB 9748 E8CC 9742 E8CD 9749 E8CE 975C E8CF 9760 E8D0 9764 E8D1 9766 E8D2 9768 E8D3 52D2 E8D4 976B E8D5 9771 E8D6 9779 E8D7 9785 E8D8 977C E8D9 9781 E8DA 977A E8DB 9786 E8DC 978B E8DD 978F E8DE 9790 E8DF 979C E8E0 97A8 E8E1 97A6 E8E2 97A3 E8E3 97B3 E8E4 97B4 E8E5 97C3 E8E6 97C6 E8E7 97C8 E8E8 97CB E8E9 97DC E8EA 97ED E8EB 9F4F E8EC 97F2 E8ED 7ADF E8EE 97F6 E8EF 97F5 E8F0 980F E8F1 980C E8F2 9838 E8F3 9824 E8F4 9821 E8F5 9837 E8F6 983D E8F7 9846 E8F8 984F E8F9 984B E8FA 986B E8FB 986F E8FC 9870 E940 9871 E941 9874 E942 9873 E943 98AA E944 98AF E945 98B1 E946 98B6 E947 98C4 E948 98C3 E949 98C6 E94A 98E9 E94B 98EB E94C 9903 E94D 9909 E94E 9912 E94F 9914 E950 9918 E951 9921 E952 991D E953 991E E954 9924 E955 9920 E956 992C E957 992E E958 993D E959 993E E95A 9942 E95B 9949 E95C 9945 E95D 9950 E95E 994B E95F 9951 E960 9952 E961 994C E962 9955 E963 9997 E964 9998 E965 99A5 E966 99AD E967 99AE E968 99BC E969 99DF E96A 99DB E96B 99DD E96C 99D8 E96D 99D1 E96E 99ED E96F 99EE E970 99F1 E971 99F2 E972 99FB E973 99F8 E974 9A01 E975 9A0F E976 9A05 E977 99E2 E978 9A19 E979 9A2B E97A 9A37 E97B 9A45 E97C 9A42 E97D 9A40 E97E 9A43 E980 9A3E E981 9A55 E982 9A4D E983 9A5B E984 9A57 E985 9A5F E986 9A62 E987 9A65 E988 9A64 E989 9A69 E98A 9A6B E98B 9A6A E98C 9AAD E98D 9AB0 E98E 9ABC E98F 9AC0 E990 9ACF E991 9AD1 E992 9AD3 E993 9AD4 E994 9ADE E995 9ADF E996 9AE2 E997 9AE3 E998 9AE6 E999 9AEF E99A 9AEB E99B 9AEE E99C 9AF4 E99D 9AF1 E99E 9AF7 E99F 9AFB E9A0 9B06 E9A1 9B18 E9A2 9B1A E9A3 9B1F E9A4 9B22 E9A5 9B23 E9A6 9B25 E9A7 9B27 E9A8 9B28 E9A9 9B29 E9AA 9B2A E9AB 9B2E E9AC 9B2F E9AD 9B32 E9AE 9B44 E9AF 9B43 E9B0 9B4F E9B1 9B4D E9B2 9B4E E9B3 9B51 E9B4 9B58 E9B5 9B74 E9B6 9B93 E9B7 9B83 E9B8 9B91 E9B9 9B96 E9BA 9B97 E9BB 9B9F E9BC 9BA0 E9BD 9BA8 E9BE 9BB4 E9BF 9BC0 E9C0 9BCA E9C1 9BB9 E9C2 9BC6 E9C3 9BCF E9C4 9BD1 E9C5 9BD2 E9C6 9BE3 E9C7 9BE2 E9C8 9BE4 E9C9 9BD4 E9CA 9BE1 E9CB 9C3A E9CC 9BF2 E9CD 9BF1 E9CE 9BF0 E9CF 9C15 E9D0 9C14 E9D1 9C09 E9D2 9C13 E9D3 9C0C E9D4 9C06 E9D5 9C08 E9D6 9C12 E9D7 9C0A E9D8 9C04 E9D9 9C2E E9DA 9C1B E9DB 9C25 E9DC 9C24 E9DD 9C21 E9DE 9C30 E9DF 9C47 E9E0 9C32 E9E1 9C46 E9E2 9C3E E9E3 9C5A E9E4 9C60 E9E5 9C67 E9E6 9C76 E9E7 9C78 E9E8 9CE7 E9E9 9CEC E9EA 9CF0 E9EB 9D09 E9EC 9D08 E9ED 9CEB E9EE 9D03 E9EF 9D06 E9F0 9D2A E9F1 9D26 E9F2 9DAF E9F3 9D23 E9F4 9D1F E9F5 9D44 E9F6 9D15 E9F7 9D12 E9F8 9D41 E9F9 9D3F E9FA 9D3E E9FB 9D46 E9FC 9D48 EA40 9D5D EA41 9D5E EA42 9D64 EA43 9D51 EA44 9D50 EA45 9D59 EA46 9D72 EA47 9D89 EA48 9D87 EA49 9DAB EA4A 9D6F EA4B 9D7A EA4C 9D9A EA4D 9DA4 EA4E 9DA9 EA4F 9DB2 EA50 9DC4 EA51 9DC1 EA52 9DBB EA53 9DB8 EA54 9DBA EA55 9DC6 EA56 9DCF EA57 9DC2 EA58 9DD9 EA59 9DD3 EA5A 9DF8 EA5B 9DE6 EA5C 9DED EA5D 9DEF EA5E 9DFD EA5F 9E1A EA60 9E1B EA61 9E1E EA62 9E75 EA63 9E79 EA64 9E7D EA65 9E81 EA66 9E88 EA67 9E8B EA68 9E8C EA69 9E92 EA6A 9E95 EA6B 9E91 EA6C 9E9D EA6D 9EA5 EA6E 9EA9 EA6F 9EB8 EA70 9EAA EA71 9EAD EA72 9761 EA73 9ECC EA74 9ECE EA75 9ECF EA76 9ED0 EA77 9ED4 EA78 9EDC EA79 9EDE EA7A 9EDD EA7B 9EE0 EA7C 9EE5 EA7D 9EE8 EA7E 9EEF EA80 9EF4 EA81 9EF6 EA82 9EF7 EA83 9EF9 EA84 9EFB EA85 9EFC EA86 9EFD EA87 9F07 EA88 9F08 EA89 76B7 EA8A 9F15 EA8B 9F21 EA8C 9F2C EA8D 9F3E EA8E 9F4A EA8F 9F52 EA90 9F54 EA91 9F63 EA92 9F5F EA93 9F60 EA94 9F61 EA95 9F66 EA96 9F67 EA97 9F6C EA98 9F6A EA99 9F77 EA9A 9F72 EA9B 9F76 EA9C 9F95 EA9D 9F9C EA9E 9FA0 EA9F 582F EAA0 69C7 EAA1 9059 EAA2 7464 EAA3 51DC EAA4 7199 EAA6 5DE2 EAA7 5E14 EAA8 5E18 EAA9 5E58 EAAA 5E5E EAAB 5EBE EAAC F928 EAAD 5ECB EAAE 5EF9 EAAF 5F00 EAB0 5F02 EAB1 5F07 EAB2 5F1D EAB3 5F23 EAB4 5F34 EAB5 5F36 EAB6 5F3D EAB7 5F40 EAB8 5F45 EAB9 5F54 EABA 5F58 EABB 5F64 EABC 5F67 EABD 5F7D EABE 5F89 EABF 5F9C EAC0 5FA7 EAC1 5FAF EAC2 5FB5 EAC3 5FB7 EAC4 5FC9 EAC5 5FDE EAC6 5FE1 EAC7 5FE9 EAC8 600D EAC9 6014 EACA 6018 EACB 6033 EACC 6035 EACD 6047 EACE FA3D EACF 609D EAD0 609E EAD1 60CB EAD2 60D4 EAD3 60D5 EAD4 60DD EAD5 60F8 EAD6 611C EAD7 612B EAD8 6130 EAD9 6137 EADA FA3E EADB 618D EADC FA3F EADD 61BC EADE 61B9 EADF FA40 EAE0 6222 EAE1 623E EAE2 6243 EAE3 6256 EAE4 625A EAE5 626F EAE6 6285 EAE7 62C4 EAE8 62D6 EAE9 62FC EAEA 630A EAEB 6318 EAEC 6339 EAED 6343 EAEE 6365 EAEF 637C EAF0 63E5 EAF1 63ED EAF2 63F5 EAF3 6410 EAF4 6414 EAF5 6422 EAF6 6479 EAF7 6451 EAF8 6460 EAF9 646D EAFA 64CE EAFB 64BE EAFC 64BF EB40 64C4 EB41 64CA EB42 64D0 EB43 64F7 EB44 64FB EB45 6522 EB46 6529 EB47 FA41 EB48 6567 EB49 659D EB4A FA42 EB4B 6600 EB4C 6609 EB4D 6615 EB4E 661E EB4F 663A EB50 6622 EB51 6624 EB52 662B EB53 6630 EB54 6631 EB55 6633 EB56 66FB EB57 6648 EB58 664C EB59 231C4 EB5A 6659 EB5B 665A EB5C 6661 EB5D 6665 EB5E 6673 EB5F 6677 EB60 6678 EB61 668D EB62 FA43 EB63 66A0 EB64 66B2 EB65 66BB EB66 66C6 EB67 66C8 EB68 3B22 EB69 66DB EB6A 66E8 EB6B 66FA EB6C 6713 EB6D F929 EB6E 6733 EB6F 6766 EB70 6747 EB71 6748 EB72 677B EB73 6781 EB74 6793 EB75 6798 EB76 679B EB77 67BB EB78 67F9 EB79 67C0 EB7A 67D7 EB7B 67FC EB7C 6801 EB7D 6852 EB7E 681D EB80 682C EB81 6831 EB82 685B EB83 6872 EB84 6875 EB85 FA44 EB86 68A3 EB87 68A5 EB88 68B2 EB89 68C8 EB8A 68D0 EB8B 68E8 EB8C 68ED EB8D 68F0 EB8E 68F1 EB8F 68FC EB90 690A EB91 6949 EB92 235C4 EB93 6935 EB94 6942 EB95 6957 EB96 6963 EB97 6964 EB98 6968 EB99 6980 EB9A FA14 EB9B 69A5 EB9C 69AD EB9D 69CF EB9E 3BB6 EB9F 3BC3 EBA0 69E2 EBA1 69E9 EBA2 69EA EBA3 69F5 EBA4 69F6 EBA5 6A0F EBA6 6A15 EBA7 2373F EBA8 6A3B EBA9 6A3E EBAA 6A45 EBAB 6A50 EBAC 6A56 EBAD 6A5B EBAE 6A6B EBAF 6A73 EBB0 23763 EBB1 6A89 EBB2 6A94 EBB3 6A9D EBB4 6A9E EBB5 6AA5 EBB6 6AE4 EBB7 6AE7 EBB8 3C0F EBB9 F91D EBBA 6B1B EBBB 6B1E EBBC 6B2C EBBD 6B35 EBBE 6B46 EBBF 6B56 EBC0 6B60 EBC1 6B65 EBC2 6B67 EBC3 6B77 EBC4 6B82 EBC5 6BA9 EBC6 6BAD EBC7 F970 EBC8 6BCF EBC9 6BD6 EBCA 6BD7 EBCB 6BFF EBCC 6C05 EBCD 6C10 EBCE 6C33 EBCF 6C59 EBD0 6C5C EBD1 6CAA EBD2 6C74 EBD3 6C76 EBD4 6C85 EBD5 6C86 EBD6 6C98 EBD7 6C9C EBD8 6CFB EBD9 6CC6 EBDA 6CD4 EBDB 6CE0 EBDC 6CEB EBDD 6CEE EBDE 23CFE EBDF 6D04 EBE0 6D0E EBE1 6D2E EBE2 6D31 EBE3 6D39 EBE4 6D3F EBE5 6D58 EBE6 6D65 EBE7 FA45 EBE8 6D82 EBE9 6D87 EBEA 6D89 EBEB 6D94 EBEC 6DAA EBED 6DAC EBEE 6DBF EBEF 6DC4 EBF0 6DD6 EBF1 6DDA EBF2 6DDB EBF3 6DDD EBF4 6DFC EBF5 FA46 EBF6 6E34 EBF7 6E44 EBF8 6E5C EBF9 6E5E EBFA 6EAB EBFB 6EB1 EBFC 6EC1 EC40 6EC7 EC41 6ECE EC42 6F10 EC43 6F1A EC44 FA47 EC45 6F2A EC46 6F2F EC47 6F33 EC48 6F51 EC49 6F59 EC4A 6F5E EC4B 6F61 EC4C 6F62 EC4D 6F7E EC4E 6F88 EC4F 6F8C EC50 6F8D EC51 6F94 EC52 6FA0 EC53 6FA7 EC54 6FB6 EC55 6FBC EC56 6FC7 EC57 6FCA EC58 6FF9 EC59 6FF0 EC5A 6FF5 EC5B 7005 EC5C 7006 EC5D 7028 EC5E 704A EC5F 705D EC60 705E EC61 704E EC62 7064 EC63 7075 EC64 7085 EC65 70A4 EC66 70AB EC67 70B7 EC68 70D4 EC69 70D8 EC6A 70E4 EC6B 710F EC6C 712B EC6D 711E EC6E 7120 EC6F 712E EC70 7130 EC71 7146 EC72 7147 EC73 7151 EC74 FA48 EC75 7152 EC76 715C EC77 7160 EC78 7168 EC79 FA15 EC7A 7185 EC7B 7187 EC7C 7192 EC7D 71C1 EC7E 71BA EC80 71C4 EC81 71FE EC82 7200 EC83 7215 EC84 7255 EC85 7256 EC86 3E3F EC87 728D EC88 729B EC89 72BE EC8A 72C0 EC8B 72FB EC8C 247F1 EC8D 7327 EC8E 7328 EC8F FA16 EC90 7350 EC91 7366 EC92 737C EC93 7395 EC94 739F EC95 73A0 EC96 73A2 EC97 73A6 EC98 73AB EC99 73C9 EC9A 73CF EC9B 73D6 EC9C 73D9 EC9D 73E3 EC9E 73E9 EC9F 7407 ECA0 740A ECA1 741A ECA2 741B ECA3 FA4A ECA4 7426 ECA5 7428 ECA6 742A ECA7 742B ECA8 742C ECA9 742E ECAA 742F ECAB 7430 ECAC 7444 ECAD 7446 ECAE 7447 ECAF 744B ECB0 7457 ECB1 7462 ECB2 746B ECB3 746D ECB4 7486 ECB5 7487 ECB6 7489 ECB7 7498 ECB8 749C ECB9 749F ECBA 74A3 ECBB 7490 ECBC 74A6 ECBD 74A8 ECBE 74A9 ECBF 74B5 ECC0 74BF ECC1 74C8 ECC2 74C9 ECC3 74DA ECC4 74FF ECC5 7501 ECC6 7517 ECC7 752F ECC8 756F ECC9 7579 ECCA 7592 ECCB 3F72 ECCC 75CE ECCD 75E4 ECCE 7600 ECCF 7602 ECD0 7608 ECD1 7615 ECD2 7616 ECD3 7619 ECD4 761E ECD5 762D ECD6 7635 ECD7 7643 ECD8 764B ECD9 7664 ECDA 7665 ECDB 766D ECDC 766F ECDD 7671 ECDE 7681 ECDF 769B ECE0 769D ECE1 769E ECE2 76A6 ECE3 76AA ECE4 76B6 ECE5 76C5 ECE6 76CC ECE7 76CE ECE8 76D4 ECE9 76E6 ECEA 76F1 ECEB 76FC ECEC 770A ECED 7719 ECEE 7734 ECEF 7736 ECF0 7746 ECF1 774D ECF2 774E ECF3 775C ECF4 775F ECF5 7762 ECF6 777A ECF7 7780 ECF8 7794 ECF9 77AA ECFA 77E0 ECFB 782D ECFC 2548E ED40 7843 ED41 784E ED42 784F ED43 7851 ED44 7868 ED45 786E ED46 FA4B ED47 78B0 ED48 2550E ED49 78AD ED4A 78E4 ED4B 78F2 ED4C 7900 ED4D 78F7 ED4E 791C ED4F 792E ED50 7931 ED51 7934 ED52 FA4C ED53 FA4D ED54 7945 ED55 7946 ED56 FA4E ED57 FA4F ED58 FA50 ED59 795C ED5A FA51 ED5B FA19 ED5C FA1A ED5D 7979 ED5E FA52 ED5F FA53 ED60 FA1B ED61 7998 ED62 79B1 ED63 79B8 ED64 79C8 ED65 79CA ED66 25771 ED67 79D4 ED68 79DE ED69 79EB ED6A 79ED ED6B 7A03 ED6C FA54 ED6D 7A39 ED6E 7A5D ED6F 7A6D ED70 FA55 ED71 7A85 ED72 7AA0 ED73 259C4 ED74 7AB3 ED75 7ABB ED76 7ACE ED77 7AEB ED78 7AFD ED79 7B12 ED7A 7B2D ED7B 7B3B ED7C 7B47 ED7D 7B4E ED7E 7B60 ED80 7B6D ED81 7B6F ED82 7B72 ED83 7B9E ED84 FA56 ED85 7BD7 ED86 7BD9 ED87 7C01 ED88 7C31 ED89 7C1E ED8A 7C20 ED8B 7C33 ED8C 7C36 ED8D 4264 ED8E 25DA1 ED8F 7C59 ED90 7C6D ED91 7C79 ED92 7C8F ED93 7C94 ED94 7CA0 ED95 7CBC ED96 7CD5 ED97 7CD9 ED98 7CDD ED99 7D07 ED9A 7D08 ED9B 7D13 ED9C 7D1D ED9D 7D23 ED9E 7D31 ED9F 7D41 EDA0 7D48 EDA1 7D53 EDA2 7D5C EDA3 7D7A EDA4 7D83 EDA5 7D8B EDA6 7DA0 EDA7 7DA6 EDA8 7DC2 EDA9 7DCC EDAA 7DD6 EDAB 7DE3 EDAC FA57 EDAD 7E28 EDAE 7E08 EDAF 7E11 EDB0 7E15 EDB1 FA59 EDB2 7E47 EDB3 7E52 EDB4 7E61 EDB5 7E8A EDB6 7E8D EDB7 7F47 EDB8 FA5A EDB9 7F91 EDBA 7F97 EDBB 7FBF EDBC 7FCE EDBD 7FDB EDBE 7FDF EDBF 7FEC EDC0 7FEE EDC1 7FFA EDC2 FA5B EDC3 8014 EDC4 8026 EDC5 8035 EDC6 8037 EDC7 803C EDC8 80CA EDC9 80D7 EDCA 80E0 EDCB 80F3 EDCC 8118 EDCD 814A EDCE 8160 EDCF 8167 EDD0 8168 EDD1 816D EDD2 81BB EDD3 81CA EDD4 81CF EDD5 81D7 EDD6 FA5C EDD7 4453 EDD8 445B EDD9 8260 EDDA 8274 EDDB 26AFF EDDC 828E EDDD 82A1 EDDE 82A3 EDDF 82A4 EDE0 82A9 EDE1 82AE EDE2 82B7 EDE3 82BE EDE4 82BF EDE5 82C6 EDE6 82D5 EDE7 82FD EDE8 82FE EDE9 8300 EDEA 8301 EDEB 8362 EDEC 8322 EDED 832D EDEE 833A EDEF 8343 EDF0 8347 EDF1 8351 EDF2 8355 EDF3 837D EDF4 8386 EDF5 8392 EDF6 8398 EDF7 83A7 EDF8 83A9 EDF9 83BF EDFA 83C0 EDFB 83C7 EDFC 83CF EE40 83D1 EE41 83E1 EE42 83EA EE43 8401 EE44 8406 EE45 840A EE46 FA5F EE47 8448 EE48 845F EE49 8470 EE4A 8473 EE4B 8485 EE4C 849E EE4D 84AF EE4E 84B4 EE4F 84BA EE50 84C0 EE51 84C2 EE52 26E40 EE53 8532 EE54 851E EE55 8523 EE56 852F EE57 8559 EE58 8564 EE59 FA1F EE5A 85AD EE5B 857A EE5C 858C EE5D 858F EE5E 85A2 EE5F 85B0 EE60 85CB EE61 85CE EE62 85ED EE63 8612 EE64 85FF EE65 8604 EE66 8605 EE67 8610 EE68 270F4 EE69 8618 EE6A 8629 EE6B 8638 EE6C 8657 EE6D 865B EE6E F936 EE6F 8662 EE70 459D EE71 866C EE72 8675 EE73 8698 EE74 86B8 EE75 86FA EE76 86FC EE77 86FD EE78 870B EE79 8771 EE7A 8787 EE7B 8788 EE7C 87AC EE7D 87AD EE7E 87B5 EE80 45EA EE81 87D6 EE82 87EC EE83 8806 EE84 880A EE85 8810 EE86 8814 EE87 881F EE88 8898 EE89 88AA EE8A 88CA EE8B 88CE EE8C 27684 EE8D 88F5 EE8E 891C EE8F FA60 EE90 8918 EE91 8919 EE92 891A EE93 8927 EE94 8930 EE95 8932 EE96 8939 EE97 8940 EE98 8994 EE99 FA61 EE9A 89D4 EE9B 89E5 EE9C 89F6 EE9D 8A12 EE9E 8A15 EE9F 8A22 EEA0 8A37 EEA1 8A47 EEA2 8A4E EEA3 8A5D EEA4 8A61 EEA5 8A75 EEA6 8A79 EEA7 8AA7 EEA8 8AD0 EEA9 8ADF EEAA 8AF4 EEAB 8AF6 EEAC FA22 EEAD FA62 EEAE FA63 EEAF 8B46 EEB0 8B54 EEB1 8B59 EEB2 8B69 EEB3 8B9D EEB4 8C49 EEB5 8C68 EEB6 FA64 EEB7 8CE1 EEB8 8CF4 EEB9 8CF8 EEBA 8CFE EEBB FA65 EEBC 8D12 EEBD 8D1B EEBE 8DAF EEBF 8DCE EEC0 8DD1 EEC1 8DD7 EEC2 8E20 EEC3 8E23 EEC4 8E3D EEC5 8E70 EEC6 8E7B EEC7 28277 EEC8 8EC0 EEC9 4844 EECA 8EFA EECB 8F1E EECC 8F2D EECD 8F36 EECE 8F54 EECF 283CD EED0 8FA6 EED1 8FB5 EED2 8FE4 EED3 8FE8 EED4 8FEE EED5 9008 EED6 902D EED7 FA67 EED8 9088 EED9 9095 EEDA 9097 EEDB 9099 EEDC 909B EEDD 90A2 EEDE 90B3 EEDF 90BE EEE0 90C4 EEE1 90C5 EEE2 90C7 EEE3 90D7 EEE4 90DD EEE5 90DE EEE6 90EF EEE7 90F4 EEE8 FA26 EEE9 9114 EEEA 9115 EEEB 9116 EEEC 9122 EEED 9123 EEEE 9127 EEEF 912F EEF0 9131 EEF1 9134 EEF2 913D EEF3 9148 EEF4 915B EEF5 9183 EEF6 919E EEF7 91AC EEF8 91B1 EEF9 91BC EEFA 91D7 EEFB 91FB EEFC 91E4 EF40 91E5 EF41 91ED EF42 91F1 EF43 9207 EF44 9210 EF45 9238 EF46 9239 EF47 923A EF48 923C EF49 9240 EF4A 9243 EF4B 924F EF4C 9278 EF4D 9288 EF4E 92C2 EF4F 92CB EF50 92CC EF51 92D3 EF52 92E0 EF53 92FF EF54 9304 EF55 931F EF56 9321 EF57 9325 EF58 9348 EF59 9349 EF5A 934A EF5B 9364 EF5C 9365 EF5D 936A EF5E 9370 EF5F 939B EF60 93A3 EF61 93BA EF62 93C6 EF63 93DE EF64 93DF EF65 9404 EF66 93FD EF67 9433 EF68 944A EF69 9463 EF6A 946B EF6B 9471 EF6C 9472 EF6D 958E EF6E 959F EF6F 95A6 EF70 95A9 EF71 95AC EF72 95B6 EF73 95BD EF74 95CB EF75 95D0 EF76 95D3 EF77 49B0 EF78 95DA EF79 95DE EF7A 9658 EF7B 9684 EF7C F9DC EF7D 969D EF7E 96A4 EF80 96A5 EF81 96D2 EF82 96DE EF83 FA68 EF84 96E9 EF85 96EF EF86 9733 EF87 973B EF88 974D EF89 974E EF8A 974F EF8B 975A EF8C 976E EF8D 9773 EF8E 9795 EF8F 97AE EF90 97BA EF91 97C1 EF92 97C9 EF93 97DE EF94 97DB EF95 97F4 EF96 FA69 EF97 980A EF98 981E EF99 982B EF9A 9830 EF9B FA6A EF9C 9852 EF9D 9853 EF9E 9856 EF9F 9857 EFA0 9859 EFA1 985A EFA2 F9D0 EFA3 9865 EFA4 986C EFA5 98BA EFA6 98C8 EFA7 98E7 EFA8 9958 EFA9 999E EFAA 9A02 EFAB 9A03 EFAC 9A24 EFAD 9A2D EFAE 9A2E EFAF 9A38 EFB0 9A4A EFB1 9A4E EFB2 9A52 EFB3 9AB6 EFB4 9AC1 EFB5 9AC3 EFB6 9ACE EFB7 9AD6 EFB8 9AF9 EFB9 9B02 EFBA 9B08 EFBB 9B20 EFBC 4C17 EFBD 9B2D EFBE 9B5E EFBF 9B79 EFC0 9B66 EFC1 9B72 EFC2 9B75 EFC3 9B84 EFC4 9B8A EFC5 9B8F EFC6 9B9E EFC7 9BA7 EFC8 9BC1 EFC9 9BCE EFCA 9BE5 EFCB 9BF8 EFCC 9BFD EFCD 9C00 EFCE 9C23 EFCF 9C41 EFD0 9C4F EFD1 9C50 EFD2 9C53 EFD3 9C63 EFD4 9C65 EFD5 9C77 EFD6 9D1D EFD7 9D1E EFD8 9D43 EFD9 9D47 EFDA 9D52 EFDB 9D63 EFDC 9D70 EFDD 9D7C EFDE 9D8A EFDF 9D96 EFE0 9DC0 EFE1 9DAC EFE2 9DBC EFE3 9DD7 EFE4 2A190 EFE5 9DE7 EFE6 9E07 EFE7 9E15 EFE8 9E7C EFE9 9E9E EFEA 9EA4 EFEB 9EAC EFEC 9EAF EFED 9EB4 EFEE 9EB5 EFEF 9EC3 EFF0 9ED1 EFF1 9F10 EFF2 9F39 EFF3 9F57 EFF4 9F90 EFF5 9F94 EFF6 9F97 EFF7 9FA2 F040 20089 F041 4E02 F042 4E0F F043 4E12 F044 4E29 F045 4E2B F046 4E2E F047 4E40 F048 4E47 F049 4E48 F04A 200A2 F04B 4E51 F04C 3406 F04D 200A4 F04E 4E5A F04F 4E69 F050 4E9D F051 342C F052 342E F053 4EB9 F054 4EBB F055 201A2 F056 4EBC F057 4EC3 F058 4EC8 F059 4ED0 F05A 4EEB F05B 4EDA F05C 4EF1 F05D 4EF5 F05E 4F00 F05F 4F16 F060 4F64 F061 4F37 F062 4F3E F063 4F54 F064 4F58 F065 20213 F066 4F77 F067 4F78 F068 4F7A F069 4F7D F06A 4F82 F06B 4F85 F06C 4F92 F06D 4F9A F06E 4FE6 F06F 4FB2 F070 4FBE F071 4FC5 F072 4FCB F073 4FCF F074 4FD2 F075 346A F076 4FF2 F077 5000 F078 5010 F079 5013 F07A 501C F07B 501E F07C 5022 F07D 3468 F07E 5042 F080 5046 F081 504E F082 5053 F083 5057 F084 5063 F085 5066 F086 506A F087 5070 F088 50A3 F089 5088 F08A 5092 F08B 5093 F08C 5095 F08D 5096 F08E 509C F08F 50AA F090 2032B F091 50B1 F092 50BA F093 50BB F094 50C4 F095 50C7 F096 50F3 F097 20381 F098 50CE F099 20371 F09A 50D4 F09B 50D9 F09C 50E1 F09D 50E9 F09E 3492 F09F 5B96 F0A0 5BAC F0A1 3761 F0A2 5BC0 F0A3 3762 F0A4 5BCE F0A5 5BD6 F0A6 376C F0A7 376B F0A8 5BF1 F0A9 5BFD F0AA 3775 F0AB 5C03 F0AC 5C29 F0AD 5C30 F0AE 21C56 F0AF 5C5F F0B0 5C63 F0B1 5C67 F0B2 5C68 F0B3 5C69 F0B4 5C70 F0B5 21D2D F0B6 21D45 F0B7 5C7C F0B8 21D78 F0B9 21D62 F0BA 5C88 F0BB 5C8A F0BC 37C1 F0BD 21DA1 F0BE 21D9C F0BF 5CA0 F0C0 5CA2 F0C1 5CA6 F0C2 5CA7 F0C3 21D92 F0C4 5CAD F0C5 5CB5 F0C6 21DB7 F0C7 5CC9 F0C8 21DE0 F0C9 21E33 F0CA 5D06 F0CB 5D10 F0CC 5D2B F0CD 5D1D F0CE 5D20 F0CF 5D24 F0D0 5D26 F0D1 5D31 F0D2 5D39 F0D3 5D42 F0D4 37E8 F0D5 5D61 F0D6 5D6A F0D7 37F4 F0D8 5D70 F0D9 21F1E F0DA 37FD F0DB 5D88 F0DC 3800 F0DD 5D92 F0DE 5D94 F0DF 5D97 F0E0 5D99 F0E1 5DB0 F0E2 5DB2 F0E3 5DB4 F0E4 21F76 F0E5 5DB9 F0E6 5DD1 F0E7 5DD7 F0E8 5DD8 F0E9 5DE0 F0EA 21FFA F0EB 5DE4 F0EC 5DE9 F0ED 382F F0EE 5E00 F0EF 3836 F0F0 5E12 F0F1 5E15 F0F2 3840 F0F3 5E1F F0F4 5E2E F0F5 5E3E F0F6 5E49 F0F7 385C F0F8 5E56 F0F9 3861 F0FA 5E6B F0FB 5E6C F0FC 5E6D F140 5108 F141 203F9 F142 5117 F143 511B F144 2044A F145 5160 F146 20509 F147 5173 F148 5183 F149 518B F14A 34BC F14B 5198 F14C 51A3 F14D 51AD F14E 34C7 F14F 51BC F150 205D6 F151 20628 F152 51F3 F153 51F4 F154 5202 F155 5212 F156 5216 F157 2074F F158 5255 F159 525C F15A 526C F15B 5277 F15C 5284 F15D 5282 F15E 20807 F15F 5298 F160 2083A F161 52A4 F162 52A6 F163 52AF F164 52BA F165 52BB F166 52CA F167 351F F168 52D1 F169 208B9 F16A 52F7 F16B 530A F16C 530B F16D 5324 F16E 5335 F16F 533E F170 5342 F171 2097C F172 2099D F173 5367 F174 536C F175 537A F176 53A4 F177 53B4 F178 20AD3 F179 53B7 F17A 53C0 F17B 20B1D F17C 355D F17D 355E F17E 53D5 F180 53DA F181 3563 F182 53F4 F183 53F5 F184 5455 F185 5424 F186 5428 F187 356E F188 5443 F189 5462 F18A 5466 F18B 546C F18C 548A F18D 548D F18E 5495 F18F 54A0 F190 54A6 F191 54AD F192 54AE F193 54B7 F194 54BA F195 54BF F196 54C3 F197 20D45 F198 54EC F199 54EF F19A 54F1 F19B 54F3 F19C 5500 F19D 5501 F19E 5509 F19F 553C F1A0 5541 F1A1 35A6 F1A2 5547 F1A3 554A F1A4 35A8 F1A5 5560 F1A6 5561 F1A7 5564 F1A8 20DE1 F1A9 557D F1AA 5582 F1AB 5588 F1AC 5591 F1AD 35C5 F1AE 55D2 F1AF 20E95 F1B0 20E6D F1B1 55BF F1B2 55C9 F1B3 55CC F1B4 55D1 F1B5 55DD F1B6 35DA F1B7 55E2 F1B8 20E64 F1B9 55E9 F1BA 5628 F1BB 20F5F F1BC 5607 F1BD 5610 F1BE 5630 F1BF 5637 F1C0 35F4 F1C1 563D F1C2 563F F1C3 5640 F1C4 5647 F1C5 565E F1C6 5660 F1C7 566D F1C8 3605 F1C9 5688 F1CA 568C F1CB 5695 F1CC 569A F1CD 569D F1CE 56A8 F1CF 56AD F1D0 56B2 F1D1 56C5 F1D2 56CD F1D3 56DF F1D4 56E8 F1D5 56F6 F1D6 56F7 F1D7 21201 F1D8 5715 F1D9 5723 F1DA 21255 F1DB 5729 F1DC 2127B F1DD 5745 F1DE 5746 F1DF 574C F1E0 574D F1E1 21274 F1E2 5768 F1E3 576F F1E4 5773 F1E5 5774 F1E6 5775 F1E7 577B F1E8 212E4 F1E9 212D7 F1EA 57AC F1EB 579A F1EC 579D F1ED 579E F1EE 57A8 F1EF 57D7 F1F0 212FD F1F1 57CC F1F2 21336 F1F3 21344 F1F4 57DE F1F5 57E6 F1F6 57F0 F1F7 364A F1F8 57F8 F1F9 57FB F1FA 57FD F1FB 5804 F1FC 581E F240 5820 F241 5827 F242 5832 F243 5839 F244 213C4 F245 5849 F246 584C F247 5867 F248 588A F249 588B F24A 588D F24B 588F F24C 5890 F24D 5894 F24E 589D F24F 58AA F250 58B1 F251 2146D F252 58C3 F253 58CD F254 58E2 F255 58F3 F256 58F4 F257 5905 F258 5906 F259 590B F25A 590D F25B 5914 F25C 5924 F25D 215D7 F25E 3691 F25F 593D F260 3699 F261 5946 F262 3696 F263 26C29 F264 595B F265 595F F266 21647 F267 5975 F268 5976 F269 597C F26A 599F F26B 59AE F26C 59BC F26D 59C8 F26E 59CD F26F 59DE F270 59E3 F271 59E4 F272 59E7 F273 59EE F274 21706 F275 21742 F276 36CF F277 5A0C F278 5A0D F279 5A17 F27A 5A27 F27B 5A2D F27C 5A55 F27D 5A65 F27E 5A7A F280 5A8B F281 5A9C F282 5A9F F283 5AA0 F284 5AA2 F285 5AB1 F286 5AB3 F287 5AB5 F288 5ABA F289 5ABF F28A 5ADA F28B 5ADC F28C 5AE0 F28D 5AE5 F28E 5AF0 F28F 5AEE F290 5AF5 F291 5B00 F292 5B08 F293 5B17 F294 5B34 F295 5B2D F296 5B4C F297 5B52 F298 5B68 F299 5B6F F29A 5B7C F29B 5B7F F29C 5B81 F29D 5B84 F29E 219C3 F29F 5E6E F2A0 2217B F2A1 5EA5 F2A2 5EAA F2A3 5EAC F2A4 5EB9 F2A5 5EBF F2A6 5EC6 F2A7 5ED2 F2A8 5ED9 F2A9 2231E F2AA 5EFD F2AB 5F08 F2AC 5F0E F2AD 5F1C F2AE 223AD F2AF 5F1E F2B0 5F47 F2B1 5F63 F2B2 5F72 F2B3 5F7E F2B4 5F8F F2B5 5FA2 F2B6 5FA4 F2B7 5FB8 F2B8 5FC4 F2B9 38FA F2BA 5FC7 F2BB 5FCB F2BC 5FD2 F2BD 5FD3 F2BE 5FD4 F2BF 5FE2 F2C0 5FEE F2C1 5FEF F2C2 5FF3 F2C3 5FFC F2C4 3917 F2C5 6017 F2C6 6022 F2C7 6024 F2C8 391A F2C9 604C F2CA 607F F2CB 608A F2CC 6095 F2CD 60A8 F2CE 226F3 F2CF 60B0 F2D0 60B1 F2D1 60BE F2D2 60C8 F2D3 60D9 F2D4 60DB F2D5 60EE F2D6 60F2 F2D7 60F5 F2D8 6110 F2D9 6112 F2DA 6113 F2DB 6119 F2DC 611E F2DD 613A F2DE 396F F2DF 6141 F2E0 6146 F2E1 6160 F2E2 617C F2E3 2285B F2E4 6192 F2E5 6193 F2E6 6197 F2E7 6198 F2E8 61A5 F2E9 61A8 F2EA 61AD F2EB 228AB F2EC 61D5 F2ED 61DD F2EE 61DF F2EF 61F5 F2F0 2298F F2F1 6215 F2F2 6223 F2F3 6229 F2F4 6246 F2F5 624C F2F6 6251 F2F7 6252 F2F8 6261 F2F9 6264 F2FA 627B F2FB 626D F2FC 6273 F340 6299 F341 62A6 F342 62D5 F343 22AB8 F344 62FD F345 6303 F346 630D F347 6310 F348 22B4F F349 22B50 F34A 6332 F34B 6335 F34C 633B F34D 633C F34E 6341 F34F 6344 F350 634E F351 22B46 F352 6359 F353 22C1D F354 22BA6 F355 636C F356 6384 F357 6399 F358 22C24 F359 6394 F35A 63BD F35B 63F7 F35C 63D4 F35D 63D5 F35E 63DC F35F 63E0 F360 63EB F361 63EC F362 63F2 F363 6409 F364 641E F365 6425 F366 6429 F367 642F F368 645A F369 645B F36A 645D F36B 6473 F36C 647D F36D 6487 F36E 6491 F36F 649D F370 649F F371 64CB F372 64CC F373 64D5 F374 64D7 F375 22DE1 F376 64E4 F377 64E5 F378 64FF F379 6504 F37A 3A6E F37B 650F F37C 6514 F37D 6516 F37E 3A73 F380 651E F381 6532 F382 6544 F383 6554 F384 656B F385 657A F386 6581 F387 6584 F388 6585 F389 658A F38A 65B2 F38B 65B5 F38C 65B8 F38D 65BF F38E 65C2 F38F 65C9 F390 65D4 F391 3AD6 F392 65F2 F393 65F9 F394 65FC F395 6604 F396 6608 F397 6621 F398 662A F399 6645 F39A 6651 F39B 664E F39C 3AEA F39D 231C3 F39E 6657 F39F 665B F3A0 6663 F3A1 231F5 F3A2 231B6 F3A3 666A F3A4 666B F3A5 666C F3A6 666D F3A7 667B F3A8 6680 F3A9 6690 F3AA 6692 F3AB 6699 F3AC 3B0E F3AD 66AD F3AE 66B1 F3AF 66B5 F3B0 3B1A F3B1 66BF F3B2 3B1C F3B3 66EC F3B4 3AD7 F3B5 6701 F3B6 6705 F3B7 6712 F3B8 23372 F3B9 6719 F3BA 233D3 F3BB 233D2 F3BC 674C F3BD 674D F3BE 6754 F3BF 675D F3C0 233D0 F3C1 233E4 F3C2 233D5 F3C3 6774 F3C4 6776 F3C5 233DA F3C6 6792 F3C7 233DF F3C8 8363 F3C9 6810 F3CA 67B0 F3CB 67B2 F3CC 67C3 F3CD 67C8 F3CE 67D2 F3CF 67D9 F3D0 67DB F3D1 67F0 F3D2 67F7 F3D3 2344A F3D4 23451 F3D5 2344B F3D6 6818 F3D7 681F F3D8 682D F3D9 23465 F3DA 6833 F3DB 683B F3DC 683E F3DD 6844 F3DE 6845 F3DF 6849 F3E0 684C F3E1 6855 F3E2 6857 F3E3 3B77 F3E4 686B F3E5 686E F3E6 687A F3E7 687C F3E8 6882 F3E9 6890 F3EA 6896 F3EB 3B6D F3EC 6898 F3ED 6899 F3EE 689A F3EF 689C F3F0 68AA F3F1 68AB F3F2 68B4 F3F3 68BB F3F4 68FB F3F5 234E4 F3F6 2355A F3F7 FA13 F3F8 68C3 F3F9 68C5 F3FA 68CC F3FB 68CF F3FC 68D6 F440 68D9 F441 68E4 F442 68E5 F443 68EC F444 68F7 F445 6903 F446 6907 F447 3B87 F448 3B88 F449 23594 F44A 693B F44B 3B8D F44C 6946 F44D 6969 F44E 696C F44F 6972 F450 697A F451 697F F452 6992 F453 3BA4 F454 6996 F455 6998 F456 69A6 F457 69B0 F458 69B7 F459 69BA F45A 69BC F45B 69C0 F45C 69D1 F45D 69D6 F45E 23639 F45F 23647 F460 6A30 F461 23638 F462 2363A F463 69E3 F464 69EE F465 69EF F466 69F3 F467 3BCD F468 69F4 F469 69FE F46A 6A11 F46B 6A1A F46C 6A1D F46D 2371C F46E 6A32 F46F 6A33 F470 6A34 F471 6A3F F472 6A46 F473 6A49 F474 6A7A F475 6A4E F476 6A52 F477 6A64 F478 2370C F479 6A7E F47A 6A83 F47B 6A8B F47C 3BF0 F47D 6A91 F47E 6A9F F480 6AA1 F481 23764 F482 6AAB F483 6ABD F484 6AC6 F485 6AD4 F486 6AD0 F487 6ADC F488 6ADD F489 237FF F48A 237E7 F48B 6AEC F48C 6AF1 F48D 6AF2 F48E 6AF3 F48F 6AFD F490 23824 F491 6B0B F492 6B0F F493 6B10 F494 6B11 F495 2383D F496 6B17 F497 3C26 F498 6B2F F499 6B4A F49A 6B58 F49B 6B6C F49C 6B75 F49D 6B7A F49E 6B81 F49F 6B9B F4A0 6BAE F4A1 23A98 F4A2 6BBD F4A3 6BBE F4A4 6BC7 F4A5 6BC8 F4A6 6BC9 F4A7 6BDA F4A8 6BE6 F4A9 6BE7 F4AA 6BEE F4AB 6BF1 F4AC 6C02 F4AD 6C0A F4AE 6C0E F4AF 6C35 F4B0 6C36 F4B1 6C3A F4B2 23C7F F4B3 6C3F F4B4 6C4D F4B5 6C5B F4B6 6C6D F4B7 6C84 F4B8 6C89 F4B9 3CC3 F4BA 6C94 F4BB 6C95 F4BC 6C97 F4BD 6CAD F4BE 6CC2 F4BF 6CD0 F4C0 3CD2 F4C1 6CD6 F4C2 6CDA F4C3 6CDC F4C4 6CE9 F4C5 6CEC F4C6 6CED F4C7 23D00 F4C8 6D00 F4C9 6D0A F4CA 6D24 F4CB 6D26 F4CC 6D27 F4CD 6C67 F4CE 6D2F F4CF 6D3C F4D0 6D5B F4D1 6D5E F4D2 6D60 F4D3 6D70 F4D4 6D80 F4D5 6D81 F4D6 6D8A F4D7 6D8D F4D8 6D91 F4D9 6D98 F4DA 23D40 F4DB 6E17 F4DC 23DFA F4DD 23DF9 F4DE 23DD3 F4DF 6DAB F4E0 6DAE F4E1 6DB4 F4E2 6DC2 F4E3 6D34 F4E4 6DC8 F4E5 6DCE F4E6 6DCF F4E7 6DD0 F4E8 6DDF F4E9 6DE9 F4EA 6DF6 F4EB 6E36 F4EC 6E1E F4ED 6E22 F4EE 6E27 F4EF 3D11 F4F0 6E32 F4F1 6E3C F4F2 6E48 F4F3 6E49 F4F4 6E4B F4F5 6E4C F4F6 6E4F F4F7 6E51 F4F8 6E53 F4F9 6E54 F4FA 6E57 F4FB 6E63 F4FC 3D1E F540 6E93 F541 6EA7 F542 6EB4 F543 6EBF F544 6EC3 F545 6ECA F546 6ED9 F547 6F35 F548 6EEB F549 6EF9 F54A 6EFB F54B 6F0A F54C 6F0C F54D 6F18 F54E 6F25 F54F 6F36 F550 6F3C F551 23F7E F552 6F52 F553 6F57 F554 6F5A F555 6F60 F556 6F68 F557 6F98 F558 6F7D F559 6F90 F55A 6F96 F55B 6FBE F55C 6F9F F55D 6FA5 F55E 6FAF F55F 3D64 F560 6FB5 F561 6FC8 F562 6FC9 F563 6FDA F564 6FDE F565 6FE9 F566 24096 F567 6FFC F568 7000 F569 7007 F56A 700A F56B 7023 F56C 24103 F56D 7039 F56E 703A F56F 703C F570 7043 F571 7047 F572 704B F573 3D9A F574 7054 F575 7065 F576 7069 F577 706C F578 706E F579 7076 F57A 707E F57B 7081 F57C 7086 F57D 7095 F57E 7097 F580 70BB F581 241C6 F582 709F F583 70B1 F584 241FE F585 70EC F586 70CA F587 70D1 F588 70D3 F589 70DC F58A 7103 F58B 7104 F58C 7106 F58D 7107 F58E 7108 F58F 710C F590 3DC0 F591 712F F592 7131 F593 7150 F594 714A F595 7153 F596 715E F597 3DD4 F598 7196 F599 7180 F59A 719B F59B 71A0 F59C 71A2 F59D 71AE F59E 71AF F59F 71B3 F5A0 243BC F5A1 71CB F5A2 71D3 F5A3 71D9 F5A4 71DC F5A5 7207 F5A6 3E05 F5A7 FA49 F5A8 722B F5A9 7234 F5AA 7238 F5AB 7239 F5AC 4E2C F5AD 7242 F5AE 7253 F5AF 7257 F5B0 7263 F5B1 24629 F5B2 726E F5B3 726F F5B4 7278 F5B5 727F F5B6 728E F5B7 246A5 F5B8 72AD F5B9 72AE F5BA 72B0 F5BB 72B1 F5BC 72C1 F5BD 3E60 F5BE 72CC F5BF 3E66 F5C0 3E68 F5C1 72F3 F5C2 72FA F5C3 7307 F5C4 7312 F5C5 7318 F5C6 7319 F5C7 3E83 F5C8 7339 F5C9 732C F5CA 7331 F5CB 7333 F5CC 733D F5CD 7352 F5CE 3E94 F5CF 736B F5D0 736C F5D1 24896 F5D2 736E F5D3 736F F5D4 7371 F5D5 7377 F5D6 7381 F5D7 7385 F5D8 738A F5D9 7394 F5DA 7398 F5DB 739C F5DC 739E F5DD 73A5 F5DE 73A8 F5DF 73B5 F5E0 73B7 F5E1 73B9 F5E2 73BC F5E3 73BF F5E4 73C5 F5E5 73CB F5E6 73E1 F5E7 73E7 F5E8 73F9 F5E9 7413 F5EA 73FA F5EB 7401 F5EC 7424 F5ED 7431 F5EE 7439 F5EF 7453 F5F0 7440 F5F1 7443 F5F2 744D F5F3 7452 F5F4 745D F5F5 7471 F5F6 7481 F5F7 7485 F5F8 7488 F5F9 24A4D F5FA 7492 F5FB 7497 F5FC 7499 F640 74A0 F641 74A1 F642 74A5 F643 74AA F644 74AB F645 74B9 F646 74BB F647 74BA F648 74D6 F649 74D8 F64A 74DE F64B 74EF F64C 74EB F64D 24B56 F64E 74FA F64F 24B6F F650 7520 F651 7524 F652 752A F653 3F57 F654 24C16 F655 753D F656 753E F657 7540 F658 7548 F659 754E F65A 7550 F65B 7552 F65C 756C F65D 7572 F65E 7571 F65F 757A F660 757D F661 757E F662 7581 F663 24D14 F664 758C F665 3F75 F666 75A2 F667 3F77 F668 75B0 F669 75B7 F66A 75BF F66B 75C0 F66C 75C6 F66D 75CF F66E 75D3 F66F 75DD F670 75DF F671 75E0 F672 75E7 F673 75EC F674 75EE F675 75F1 F676 75F9 F677 7603 F678 7618 F679 7607 F67A 760F F67B 3FAE F67C 24E0E F67D 7613 F67E 761B F680 761C F681 24E37 F682 7625 F683 7628 F684 763C F685 7633 F686 24E6A F687 3FC9 F688 7641 F689 24E8B F68A 7649 F68B 7655 F68C 3FD7 F68D 766E F68E 7695 F68F 769C F690 76A1 F691 76A0 F692 76A7 F693 76A8 F694 76AF F695 2504A F696 76C9 F697 25055 F698 76E8 F699 76EC F69A 25122 F69B 7717 F69C 771A F69D 772D F69E 7735 F69F 251A9 F6A0 4039 F6A1 251E5 F6A2 251CD F6A3 7758 F6A4 7760 F6A5 776A F6A6 2521E F6A7 7772 F6A8 777C F6A9 777D F6AA 2524C F6AB 4058 F6AC 779A F6AD 779F F6AE 77A2 F6AF 77A4 F6B0 77A9 F6B1 77DE F6B2 77DF F6B3 77E4 F6B4 77E6 F6B5 77EA F6B6 77EC F6B7 4093 F6B8 77F0 F6B9 77F4 F6BA 77FB F6BB 2542E F6BC 7805 F6BD 7806 F6BE 7809 F6BF 780D F6C0 7819 F6C1 7821 F6C2 782C F6C3 7847 F6C4 7864 F6C5 786A F6C6 254D9 F6C7 788A F6C8 7894 F6C9 78A4 F6CA 789D F6CB 789E F6CC 789F F6CD 78BB F6CE 78C8 F6CF 78CC F6D0 78CE F6D1 78D5 F6D2 78E0 F6D3 78E1 F6D4 78E6 F6D5 78F9 F6D6 78FA F6D7 78FB F6D8 78FE F6D9 255A7 F6DA 7910 F6DB 791B F6DC 7930 F6DD 7925 F6DE 793B F6DF 794A F6E0 7958 F6E1 795B F6E2 4105 F6E3 7967 F6E4 7972 F6E5 7994 F6E6 7995 F6E7 7996 F6E8 799B F6E9 79A1 F6EA 79A9 F6EB 79B4 F6EC 79BB F6ED 79C2 F6EE 79C7 F6EF 79CC F6F0 79CD F6F1 79D6 F6F2 4148 F6F3 257A9 F6F4 257B4 F6F5 414F F6F6 7A0A F6F7 7A11 F6F8 7A15 F6F9 7A1B F6FA 7A1E F6FB 4163 F6FC 7A2D F740 7A38 F741 7A47 F742 7A4C F743 7A56 F744 7A59 F745 7A5C F746 7A5F F747 7A60 F748 7A67 F749 7A6A F74A 7A75 F74B 7A78 F74C 7A82 F74D 7A8A F74E 7A90 F74F 7AA3 F750 7AAC F751 259D4 F752 41B4 F753 7AB9 F754 7ABC F755 7ABE F756 41BF F757 7ACC F758 7AD1 F759 7AE7 F75A 7AE8 F75B 7AF4 F75C 25AE4 F75D 25AE3 F75E 7B07 F75F 25AF1 F760 7B3D F761 7B27 F762 7B2A F763 7B2E F764 7B2F F765 7B31 F766 41E6 F767 41F3 F768 7B7F F769 7B41 F76A 41EE F76B 7B55 F76C 7B79 F76D 7B64 F76E 7B66 F76F 7B69 F770 7B73 F771 25BB2 F772 4207 F773 7B90 F774 7B91 F775 7B9B F776 420E F777 7BAF F778 7BB5 F779 7BBC F77A 7BC5 F77B 7BCA F77C 25C4B F77D 25C64 F77E 7BD4 F780 7BD6 F781 7BDA F782 7BEA F783 7BF0 F784 7C03 F785 7C0B F786 7C0E F787 7C0F F788 7C26 F789 7C45 F78A 7C4A F78B 7C51 F78C 7C57 F78D 7C5E F78E 7C61 F78F 7C69 F790 7C6E F791 7C6F F792 7C70 F793 25E2E F794 25E56 F795 25E65 F796 7CA6 F797 25E62 F798 7CB6 F799 7CB7 F79A 7CBF F79B 25ED8 F79C 7CC4 F79D 25EC2 F79E 7CC8 F79F 7CCD F7A0 25EE8 F7A1 7CD7 F7A2 25F23 F7A3 7CE6 F7A4 7CEB F7A5 25F5C F7A6 7CF5 F7A7 7D03 F7A8 7D09 F7A9 42C6 F7AA 7D12 F7AB 7D1E F7AC 25FE0 F7AD 25FD4 F7AE 7D3D F7AF 7D3E F7B0 7D40 F7B1 7D47 F7B2 2600C F7B3 25FFB F7B4 42D6 F7B5 7D59 F7B6 7D5A F7B7 7D6A F7B8 7D70 F7B9 42DD F7BA 7D7F F7BB 26017 F7BC 7D86 F7BD 7D88 F7BE 7D8C F7BF 7D97 F7C0 26060 F7C1 7D9D F7C2 7DA7 F7C3 7DAA F7C4 7DB6 F7C5 7DB7 F7C6 7DC0 F7C7 7DD7 F7C8 7DD9 F7C9 7DE6 F7CA 7DF1 F7CB 7DF9 F7CC 4302 F7CD 260ED F7CE FA58 F7CF 7E10 F7D0 7E17 F7D1 7E1D F7D2 7E20 F7D3 7E27 F7D4 7E2C F7D5 7E45 F7D6 7E73 F7D7 7E75 F7D8 7E7E F7D9 7E86 F7DA 7E87 F7DB 432B F7DC 7E91 F7DD 7E98 F7DE 7E9A F7DF 4343 F7E0 7F3C F7E1 7F3B F7E2 7F3E F7E3 7F43 F7E4 7F44 F7E5 7F4F F7E6 34C1 F7E7 26270 F7E8 7F52 F7E9 26286 F7EA 7F61 F7EB 7F63 F7EC 7F64 F7ED 7F6D F7EE 7F7D F7EF 7F7E F7F0 2634C F7F1 7F90 F7F2 517B F7F3 23D0E F7F4 7F96 F7F5 7F9C F7F6 7FAD F7F7 26402 F7F8 7FC3 F7F9 7FCF F7FA 7FE3 F7FB 7FE5 F7FC 7FEF F840 7FF2 F841 8002 F842 800A F843 8008 F844 800E F845 8011 F846 8016 F847 8024 F848 802C F849 8030 F84A 8043 F84B 8066 F84C 8071 F84D 8075 F84E 807B F84F 8099 F850 809C F851 80A4 F852 80A7 F853 80B8 F854 2667E F855 80C5 F856 80D5 F857 80D8 F858 80E6 F859 266B0 F85A 810D F85B 80F5 F85C 80FB F85D 43EE F85E 8135 F85F 8116 F860 811E F861 43F0 F862 8124 F863 8127 F864 812C F865 2671D F866 813D F867 4408 F868 8169 F869 4417 F86A 8181 F86B 441C F86C 8184 F86D 8185 F86E 4422 F86F 8198 F870 81B2 F871 81C1 F872 81C3 F873 81D6 F874 81DB F875 268DD F876 81E4 F877 268EA F878 81EC F879 26951 F87A 81FD F87B 81FF F87C 2696F F87D 8204 F87E 269DD F880 8219 F881 8221 F882 8222 F883 26A1E F884 8232 F885 8234 F886 823C F887 8246 F888 8249 F889 8245 F88A 26A58 F88B 824B F88C 4476 F88D 824F F88E 447A F88F 8257 F890 26A8C F891 825C F892 8263 F893 26AB7 F894 FA5D F895 FA5E F896 8279 F897 4491 F898 827D F899 827F F89A 8283 F89B 828A F89C 8293 F89D 82A7 F89E 82A8 F89F 82B2 F8A0 82B4 F8A1 82BA F8A2 82BC F8A3 82E2 F8A4 82E8 F8A5 82F7 F8A6 8307 F8A7 8308 F8A8 830C F8A9 8354 F8AA 831B F8AB 831D F8AC 8330 F8AD 833C F8AE 8344 F8AF 8357 F8B0 44BE F8B1 837F F8B2 44D4 F8B3 44B3 F8B4 838D F8B5 8394 F8B6 8395 F8B7 839B F8B8 839D F8B9 83C9 F8BA 83D0 F8BB 83D4 F8BC 83DD F8BD 83E5 F8BE 83F9 F8BF 840F F8C0 8411 F8C1 8415 F8C2 26C73 F8C3 8417 F8C4 8439 F8C5 844A F8C6 844F F8C7 8451 F8C8 8452 F8C9 8459 F8CA 845A F8CB 845C F8CC 26CDD F8CD 8465 F8CE 8476 F8CF 8478 F8D0 847C F8D1 8481 F8D2 450D F8D3 84DC F8D4 8497 F8D5 84A6 F8D6 84BE F8D7 4508 F8D8 84CE F8D9 84CF F8DA 84D3 F8DB 26E65 F8DC 84E7 F8DD 84EA F8DE 84EF F8DF 84F0 F8E0 84F1 F8E1 84FA F8E2 84FD F8E3 850C F8E4 851B F8E5 8524 F8E6 8525 F8E7 852B F8E8 8534 F8E9 854F F8EA 856F F8EB 4525 F8EC 4543 F8ED 853E F8EE 8551 F8EF 8553 F8F0 855E F8F1 8561 F8F2 8562 F8F3 26F94 F8F4 857B F8F5 857D F8F6 857F F8F7 8581 F8F8 8586 F8F9 8593 F8FA 859D F8FB 859F F8FC 26FF8 F940 26FF6 F941 26FF7 F942 85B7 F943 85BC F944 85C7 F945 85CA F946 85D8 F947 85D9 F948 85DF F949 85E1 F94A 85E6 F94B 85F6 F94C 8600 F94D 8611 F94E 861E F94F 8621 F950 8624 F951 8627 F952 2710D F953 8639 F954 863C F955 27139 F956 8640 F957 FA20 F958 8653 F959 8656 F95A 866F F95B 8677 F95C 867A F95D 8687 F95E 8689 F95F 868D F960 8691 F961 869C F962 869D F963 86A8 F964 FA21 F965 86B1 F966 86B3 F967 86C1 F968 86C3 F969 86D1 F96A 86D5 F96B 86D7 F96C 86E3 F96D 86E6 F96E 45B8 F96F 8705 F970 8707 F971 870E F972 8710 F973 8713 F974 8719 F975 871F F976 8721 F977 8723 F978 8731 F979 873A F97A 873E F97B 8740 F97C 8743 F97D 8751 F97E 8758 F980 8764 F981 8765 F982 8772 F983 877C F984 273DB F985 273DA F986 87A7 F987 8789 F988 878B F989 8793 F98A 87A0 F98B 273FE F98C 45E5 F98D 87BE F98E 27410 F98F 87C1 F990 87CE F991 87F5 F992 87DF F993 27449 F994 87E3 F995 87E5 F996 87E6 F997 87EA F998 87EB F999 87ED F99A 8801 F99B 8803 F99C 880B F99D 8813 F99E 8828 F99F 882E F9A0 8832 F9A1 883C F9A2 460F F9A3 884A F9A4 8858 F9A5 885F F9A6 8864 F9A7 27615 F9A8 27614 F9A9 8869 F9AA 27631 F9AB 886F F9AC 88A0 F9AD 88BC F9AE 88BD F9AF 88BE F9B0 88C0 F9B1 88D2 F9B2 27693 F9B3 88D1 F9B4 88D3 F9B5 88DB F9B6 88F0 F9B7 88F1 F9B8 4641 F9B9 8901 F9BA 2770E F9BB 8937 F9BC 27723 F9BD 8942 F9BE 8945 F9BF 8949 F9C0 27752 F9C1 4665 F9C2 8962 F9C3 8980 F9C4 8989 F9C5 8990 F9C6 899F F9C7 89B0 F9C8 89B7 F9C9 89D6 F9CA 89D8 F9CB 89EB F9CC 46A1 F9CD 89F1 F9CE 89F3 F9CF 89FD F9D0 89FF F9D1 46AF F9D2 8A11 F9D3 8A14 F9D4 27985 F9D5 8A21 F9D6 8A35 F9D7 8A3E F9D8 8A45 F9D9 8A4D F9DA 8A58 F9DB 8AAE F9DC 8A90 F9DD 8AB7 F9DE 8ABE F9DF 8AD7 F9E0 8AFC F9E1 27A84 F9E2 8B0A F9E3 8B05 F9E4 8B0D F9E5 8B1C F9E6 8B1F F9E7 8B2D F9E8 8B43 F9E9 470C F9EA 8B51 F9EB 8B5E F9EC 8B76 F9ED 8B7F F9EE 8B81 F9EF 8B8B F9F0 8B94 F9F1 8B95 F9F2 8B9C F9F3 8B9E F9F4 8C39 F9F5 27BB3 F9F6 8C3D F9F7 27BBE F9F8 27BC7 F9F9 8C45 F9FA 8C47 F9FB 8C4F F9FC 8C54 FA40 8C57 FA41 8C69 FA42 8C6D FA43 8C73 FA44 27CB8 FA45 8C93 FA46 8C92 FA47 8C99 FA48 4764 FA49 8C9B FA4A 8CA4 FA4B 8CD6 FA4C 8CD5 FA4D 8CD9 FA4E 27DA0 FA4F 8CF0 FA50 8CF1 FA51 27E10 FA52 8D09 FA53 8D0E FA54 8D6C FA55 8D84 FA56 8D95 FA57 8DA6 FA58 27FB7 FA59 8DC6 FA5A 8DC8 FA5B 8DD9 FA5C 8DEC FA5D 8E0C FA5E 47FD FA5F 8DFD FA60 8E06 FA61 2808A FA62 8E14 FA63 8E16 FA64 8E21 FA65 8E22 FA66 8E27 FA67 280BB FA68 4816 FA69 8E36 FA6A 8E39 FA6B 8E4B FA6C 8E54 FA6D 8E62 FA6E 8E6C FA6F 8E6D FA70 8E6F FA71 8E98 FA72 8E9E FA73 8EAE FA74 8EB3 FA75 8EB5 FA76 8EB6 FA77 8EBB FA78 28282 FA79 8ED1 FA7A 8ED4 FA7B 484E FA7C 8EF9 FA7D 282F3 FA7E 8F00 FA80 8F08 FA81 8F17 FA82 8F2B FA83 8F40 FA84 8F4A FA85 8F58 FA86 2840C FA87 8FA4 FA88 8FB4 FA89 FA66 FA8A 8FB6 FA8B 28455 FA8C 8FC1 FA8D 8FC6 FA8E FA24 FA8F 8FCA FA90 8FCD FA91 8FD3 FA92 8FD5 FA93 8FE0 FA94 8FF1 FA95 8FF5 FA96 8FFB FA97 9002 FA98 900C FA99 9037 FA9A 2856B FA9B 9043 FA9C 9044 FA9D 905D FA9E 285C8 FA9F 285C9 FAA0 9085 FAA1 908C FAA2 9090 FAA3 961D FAA4 90A1 FAA5 48B5 FAA6 90B0 FAA7 90B6 FAA8 90C3 FAA9 90C8 FAAA 286D7 FAAB 90DC FAAC 90DF FAAD 286FA FAAE 90F6 FAAF 90F2 FAB0 9100 FAB1 90EB FAB2 90FE FAB3 90FF FAB4 9104 FAB5 9106 FAB6 9118 FAB7 911C FAB8 911E FAB9 9137 FABA 9139 FABB 913A FABC 9146 FABD 9147 FABE 9157 FABF 9159 FAC0 9161 FAC1 9164 FAC2 9174 FAC3 9179 FAC4 9185 FAC5 918E FAC6 91A8 FAC7 91AE FAC8 91B3 FAC9 91B6 FACA 91C3 FACB 91C4 FACC 91DA FACD 28949 FACE 28946 FACF 91EC FAD0 91EE FAD1 9201 FAD2 920A FAD3 9216 FAD4 9217 FAD5 2896B FAD6 9233 FAD7 9242 FAD8 9247 FAD9 924A FADA 924E FADB 9251 FADC 9256 FADD 9259 FADE 9260 FADF 9261 FAE0 9265 FAE1 9267 FAE2 9268 FAE3 28987 FAE4 28988 FAE5 927C FAE6 927D FAE7 927F FAE8 9289 FAE9 928D FAEA 9297 FAEB 9299 FAEC 929F FAED 92A7 FAEE 92AB FAEF 289BA FAF0 289BB FAF1 92B2 FAF2 92BF FAF3 92C0 FAF4 92C6 FAF5 92CE FAF6 92D0 FAF7 92D7 FAF8 92D9 FAF9 92E5 FAFA 92E7 FAFB 9311 FAFC 28A1E FB40 28A29 FB41 92F7 FB42 92F9 FB43 92FB FB44 9302 FB45 930D FB46 9315 FB47 931D FB48 931E FB49 9327 FB4A 9329 FB4B 28A71 FB4C 28A43 FB4D 9347 FB4E 9351 FB4F 9357 FB50 935A FB51 936B FB52 9371 FB53 9373 FB54 93A1 FB55 28A99 FB56 28ACD FB57 9388 FB58 938B FB59 938F FB5A 939E FB5B 93F5 FB5C 28AE4 FB5D 28ADD FB5E 93F1 FB5F 93C1 FB60 93C7 FB61 93DC FB62 93E2 FB63 93E7 FB64 9409 FB65 940F FB66 9416 FB67 9417 FB68 93FB FB69 9432 FB6A 9434 FB6B 943B FB6C 9445 FB6D 28BC1 FB6E 28BEF FB6F 946D FB70 946F FB71 9578 FB72 9579 FB73 9586 FB74 958C FB75 958D FB76 28D10 FB77 95AB FB78 95B4 FB79 28D71 FB7A 95C8 FB7B 28DFB FB7C 28E1F FB7D 962C FB7E 9633 FB80 9634 FB81 28E36 FB82 963C FB83 9641 FB84 9661 FB85 28E89 FB86 9682 FB87 28EEB FB88 969A FB89 28F32 FB8A 49E7 FB8B 96A9 FB8C 96AF FB8D 96B3 FB8E 96BA FB8F 96BD FB90 49FA FB91 28FF8 FB92 96D8 FB93 96DA FB94 96DD FB95 4A04 FB96 9714 FB97 9723 FB98 4A29 FB99 9736 FB9A 9741 FB9B 9747 FB9C 9755 FB9D 9757 FB9E 975B FB9F 976A FBA0 292A0 FBA1 292B1 FBA2 9796 FBA3 979A FBA4 979E FBA5 97A2 FBA6 97B1 FBA7 97B2 FBA8 97BE FBA9 97CC FBAA 97D1 FBAB 97D4 FBAC 97D8 FBAD 97D9 FBAE 97E1 FBAF 97F1 FBB0 9804 FBB1 980D FBB2 980E FBB3 9814 FBB4 9816 FBB5 4ABC FBB6 29490 FBB7 9823 FBB8 9832 FBB9 9833 FBBA 9825 FBBB 9847 FBBC 9866 FBBD 98AB FBBE 98AD FBBF 98B0 FBC0 295CF FBC1 98B7 FBC2 98B8 FBC3 98BB FBC4 98BC FBC5 98BF FBC6 98C2 FBC7 98C7 FBC8 98CB FBC9 98E0 FBCA 2967F FBCB 98E1 FBCC 98E3 FBCD 98E5 FBCE 98EA FBCF 98F0 FBD0 98F1 FBD1 98F3 FBD2 9908 FBD3 4B3B FBD4 296F0 FBD5 9916 FBD6 9917 FBD7 29719 FBD8 991A FBD9 991B FBDA 991C FBDB 29750 FBDC 9931 FBDD 9932 FBDE 9933 FBDF 993A FBE0 993B FBE1 993C FBE2 9940 FBE3 9941 FBE4 9946 FBE5 994D FBE6 994E FBE7 995C FBE8 995F FBE9 9960 FBEA 99A3 FBEB 99A6 FBEC 99B9 FBED 99BD FBEE 99BF FBEF 99C3 FBF0 99C9 FBF1 99D4 FBF2 99D9 FBF3 99DE FBF4 298C6 FBF5 99F0 FBF6 99F9 FBF7 99FC FBF8 9A0A FBF9 9A11 FBFA 9A16 FBFB 9A1A FBFC 9A20 FC40 9A31 FC41 9A36 FC42 9A44 FC43 9A4C FC44 9A58 FC45 4BC2 FC46 9AAF FC47 4BCA FC48 9AB7 FC49 4BD2 FC4A 9AB9 FC4B 29A72 FC4C 9AC6 FC4D 9AD0 FC4E 9AD2 FC4F 9AD5 FC50 4BE8 FC51 9ADC FC52 9AE0 FC53 9AE5 FC54 9AE9 FC55 9B03 FC56 9B0C FC57 9B10 FC58 9B12 FC59 9B16 FC5A 9B1D FC5B 9B2B FC5C 9B33 FC5D 9B3D FC5E 4C20 FC5F 9B4B FC60 9B63 FC61 9B65 FC62 9B6B FC63 9B6C FC64 9B73 FC65 9B76 FC66 9B77 FC67 9BA6 FC68 9BAC FC69 9BB1 FC6A 29DDB FC6B 29E3D FC6C 9BB2 FC6D 9BB8 FC6E 9BBE FC6F 9BC7 FC70 9BF3 FC71 9BD8 FC72 9BDD FC73 9BE7 FC74 9BEA FC75 9BEB FC76 9BEF FC77 9BEE FC78 29E15 FC79 9BFA FC7A 29E8A FC7B 9BF7 FC7C 29E49 FC7D 9C16 FC7E 9C18 FC80 9C19 FC81 9C1A FC82 9C1D FC83 9C22 FC84 9C27 FC85 9C29 FC86 9C2A FC87 29EC4 FC88 9C31 FC89 9C36 FC8A 9C37 FC8B 9C45 FC8C 9C5C FC8D 29EE9 FC8E 9C49 FC8F 9C4A FC90 29EDB FC91 9C54 FC92 9C58 FC93 9C5B FC94 9C5D FC95 9C5F FC96 9C69 FC97 9C6A FC98 9C6B FC99 9C6D FC9A 9C6E FC9B 9C70 FC9C 9C72 FC9D 9C75 FC9E 9C7A FC9F 9CE6 FCA0 9CF2 FCA1 9D0B FCA2 9D02 FCA3 29FCE FCA4 9D11 FCA5 9D17 FCA6 9D18 FCA7 2A02F FCA8 4CC4 FCA9 2A01A FCAA 9D32 FCAB 4CD1 FCAC 9D42 FCAD 9D4A FCAE 9D5F FCAF 9D62 FCB0 2A0F9 FCB1 9D69 FCB2 9D6B FCB3 2A082 FCB4 9D73 FCB5 9D76 FCB6 9D77 FCB7 9D7E FCB8 9D84 FCB9 9D8D FCBA 9D99 FCBB 9DA1 FCBC 9DBF FCBD 9DB5 FCBE 9DB9 FCBF 9DBD FCC0 9DC3 FCC1 9DC7 FCC2 9DC9 FCC3 9DD6 FCC4 9DDA FCC5 9DDF FCC6 9DE0 FCC7 9DE3 FCC8 9DF4 FCC9 4D07 FCCA 9E0A FCCB 9E02 FCCC 9E0D FCCD 9E19 FCCE 9E1C FCCF 9E1D FCD0 9E7B FCD1 22218 FCD2 9E80 FCD3 9E85 FCD4 9E9B FCD5 9EA8 FCD6 2A38C FCD7 9EBD FCD8 2A437 FCD9 9EDF FCDA 9EE7 FCDB 9EEE FCDC 9EFF FCDD 9F02 FCDE 4D77 FCDF 9F03 FCE0 9F17 FCE1 9F19 FCE2 9F2F FCE3 9F37 FCE4 9F3A FCE5 9F3D FCE6 9F41 FCE7 9F45 FCE8 9F46 FCE9 9F53 FCEA 9F55 FCEB 9F58 FCEC 2A5F1 FCED 9F5D FCEE 2A602 FCEF 9F69 FCF0 2A61A FCF1 9F6D FCF2 9F70 FCF3 9F75 FCF4 2A6B2
114,135
11,410
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/reperf.py
import re import time def main(): s = "\13hello\14 \13world\14 " * 1000 p = re.compile(r"([\13\14])") timefunc(10, p.sub, "", s) timefunc(10, p.split, s) timefunc(10, p.findall, s) def timefunc(n, func, *args, **kw): t0 = time.perf_counter() try: for i in range(n): result = func(*args, **kw) return result finally: t1 = time.perf_counter() if n > 1: print(n, "times", end=' ') print(func.__name__, "%.3f" % (t1-t0), "CPU seconds") main()
538
24
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_range.py
# Python test set -- built-in functions import unittest import sys import pickle import itertools import test.support # pure Python implementations (3 args only), for comparison def pyrange(start, stop, step): if (start - stop) // step < 0: # replace stop with next element in the sequence of integers # that are congruent to start modulo step. stop += (start - stop) % step while start != stop: yield start start += step def pyrange_reversed(start, stop, step): stop += (start - stop) % step return pyrange(stop - step, start - step, -step) class RangeTest(unittest.TestCase): def assert_iterators_equal(self, xs, ys, test_id, limit=None): # check that an iterator xs matches the expected results ys, # up to a given limit. if limit is not None: xs = itertools.islice(xs, limit) ys = itertools.islice(ys, limit) sentinel = object() pairs = itertools.zip_longest(xs, ys, fillvalue=sentinel) for i, (x, y) in enumerate(pairs): if x == y: continue elif x == sentinel: self.fail('{}: iterator ended unexpectedly ' 'at position {}; expected {}'.format(test_id, i, y)) elif y == sentinel: self.fail('{}: unexpected excess element {} at ' 'position {}'.format(test_id, x, i)) else: self.fail('{}: wrong element at position {}; ' 'expected {}, got {}'.format(test_id, i, y, x)) def test_range(self): self.assertEqual(list(range(3)), [0, 1, 2]) self.assertEqual(list(range(1, 5)), [1, 2, 3, 4]) self.assertEqual(list(range(0)), []) self.assertEqual(list(range(-3)), []) self.assertEqual(list(range(1, 10, 3)), [1, 4, 7]) self.assertEqual(list(range(5, -5, -3)), [5, 2, -1, -4]) a = 10 b = 100 c = 50 self.assertEqual(list(range(a, a+2)), [a, a+1]) self.assertEqual(list(range(a+2, a, -1)), [a+2, a+1]) self.assertEqual(list(range(a+4, a, -2)), [a+4, a+2]) seq = list(range(a, b, c)) self.assertIn(a, seq) self.assertNotIn(b, seq) self.assertEqual(len(seq), 2) seq = list(range(b, a, -c)) self.assertIn(b, seq) self.assertNotIn(a, seq) self.assertEqual(len(seq), 2) seq = list(range(-a, -b, -c)) self.assertIn(-a, seq) self.assertNotIn(-b, seq) self.assertEqual(len(seq), 2) self.assertRaises(TypeError, range) self.assertRaises(TypeError, range, 1, 2, 3, 4) self.assertRaises(ValueError, range, 1, 2, 0) self.assertRaises(TypeError, range, 0.0, 2, 1) self.assertRaises(TypeError, range, 1, 2.0, 1) self.assertRaises(TypeError, range, 1, 2, 1.0) self.assertRaises(TypeError, range, 1e100, 1e101, 1e101) self.assertRaises(TypeError, range, 0, "spam") self.assertRaises(TypeError, range, 0, 42, "spam") self.assertEqual(len(range(0, sys.maxsize, sys.maxsize-1)), 2) r = range(-sys.maxsize, sys.maxsize, 2) self.assertEqual(len(r), sys.maxsize) def test_large_operands(self): x = range(10**20, 10**20+10, 3) self.assertEqual(len(x), 4) self.assertEqual(len(list(x)), 4) x = range(10**20+10, 10**20, 3) self.assertEqual(len(x), 0) self.assertEqual(len(list(x)), 0) self.assertFalse(x) x = range(10**20, 10**20+10, -3) self.assertEqual(len(x), 0) self.assertEqual(len(list(x)), 0) self.assertFalse(x) x = range(10**20+10, 10**20, -3) self.assertEqual(len(x), 4) self.assertEqual(len(list(x)), 4) self.assertTrue(x) # Now test range() with longs for x in [range(-2**100), range(0, -2**100), range(0, 2**100, -1)]: self.assertEqual(list(x), []) self.assertFalse(x) a = int(10 * sys.maxsize) b = int(100 * sys.maxsize) c = int(50 * sys.maxsize) self.assertEqual(list(range(a, a+2)), [a, a+1]) self.assertEqual(list(range(a+2, a, -1)), [a+2, a+1]) self.assertEqual(list(range(a+4, a, -2)), [a+4, a+2]) seq = list(range(a, b, c)) self.assertIn(a, seq) self.assertNotIn(b, seq) self.assertEqual(len(seq), 2) self.assertEqual(seq[0], a) self.assertEqual(seq[-1], a+c) seq = list(range(b, a, -c)) self.assertIn(b, seq) self.assertNotIn(a, seq) self.assertEqual(len(seq), 2) self.assertEqual(seq[0], b) self.assertEqual(seq[-1], b-c) seq = list(range(-a, -b, -c)) self.assertIn(-a, seq) self.assertNotIn(-b, seq) self.assertEqual(len(seq), 2) self.assertEqual(seq[0], -a) self.assertEqual(seq[-1], -a-c) def test_large_range(self): # Check long ranges (len > sys.maxsize) # len() is expected to fail due to limitations of the __len__ protocol def _range_len(x): try: length = len(x) except OverflowError: step = x[1] - x[0] length = 1 + ((x[-1] - x[0]) // step) return length a = -sys.maxsize b = sys.maxsize expected_len = b - a x = range(a, b) self.assertIn(a, x) self.assertNotIn(b, x) self.assertRaises(OverflowError, len, x) self.assertTrue(x) self.assertEqual(_range_len(x), expected_len) self.assertEqual(x[0], a) idx = sys.maxsize+1 self.assertEqual(x[idx], a+idx) self.assertEqual(x[idx:idx+1][0], a+idx) with self.assertRaises(IndexError): x[-expected_len-1] with self.assertRaises(IndexError): x[expected_len] a = 0 b = 2 * sys.maxsize expected_len = b - a x = range(a, b) self.assertIn(a, x) self.assertNotIn(b, x) self.assertRaises(OverflowError, len, x) self.assertTrue(x) self.assertEqual(_range_len(x), expected_len) self.assertEqual(x[0], a) idx = sys.maxsize+1 self.assertEqual(x[idx], a+idx) self.assertEqual(x[idx:idx+1][0], a+idx) with self.assertRaises(IndexError): x[-expected_len-1] with self.assertRaises(IndexError): x[expected_len] a = 0 b = sys.maxsize**10 c = 2*sys.maxsize expected_len = 1 + (b - a) // c x = range(a, b, c) self.assertIn(a, x) self.assertNotIn(b, x) self.assertRaises(OverflowError, len, x) self.assertTrue(x) self.assertEqual(_range_len(x), expected_len) self.assertEqual(x[0], a) idx = sys.maxsize+1 self.assertEqual(x[idx], a+(idx*c)) self.assertEqual(x[idx:idx+1][0], a+(idx*c)) with self.assertRaises(IndexError): x[-expected_len-1] with self.assertRaises(IndexError): x[expected_len] a = sys.maxsize**10 b = 0 c = -2*sys.maxsize expected_len = 1 + (b - a) // c x = range(a, b, c) self.assertIn(a, x) self.assertNotIn(b, x) self.assertRaises(OverflowError, len, x) self.assertTrue(x) self.assertEqual(_range_len(x), expected_len) self.assertEqual(x[0], a) idx = sys.maxsize+1 self.assertEqual(x[idx], a+(idx*c)) self.assertEqual(x[idx:idx+1][0], a+(idx*c)) with self.assertRaises(IndexError): x[-expected_len-1] with self.assertRaises(IndexError): x[expected_len] def test_invalid_invocation(self): self.assertRaises(TypeError, range) self.assertRaises(TypeError, range, 1, 2, 3, 4) self.assertRaises(ValueError, range, 1, 2, 0) a = int(10 * sys.maxsize) self.assertRaises(ValueError, range, a, a + 1, int(0)) self.assertRaises(TypeError, range, 1., 1., 1.) self.assertRaises(TypeError, range, 1e100, 1e101, 1e101) self.assertRaises(TypeError, range, 0, "spam") self.assertRaises(TypeError, range, 0, 42, "spam") # Exercise various combinations of bad arguments, to check # refcounting logic self.assertRaises(TypeError, range, 0.0) self.assertRaises(TypeError, range, 0, 0.0) self.assertRaises(TypeError, range, 0.0, 0) self.assertRaises(TypeError, range, 0.0, 0.0) self.assertRaises(TypeError, range, 0, 0, 1.0) self.assertRaises(TypeError, range, 0, 0.0, 1) self.assertRaises(TypeError, range, 0, 0.0, 1.0) self.assertRaises(TypeError, range, 0.0, 0, 1) self.assertRaises(TypeError, range, 0.0, 0, 1.0) self.assertRaises(TypeError, range, 0.0, 0.0, 1) self.assertRaises(TypeError, range, 0.0, 0.0, 1.0) def test_index(self): u = range(2) self.assertEqual(u.index(0), 0) self.assertEqual(u.index(1), 1) self.assertRaises(ValueError, u.index, 2) u = range(-2, 3) self.assertEqual(u.count(0), 1) self.assertEqual(u.index(0), 2) self.assertRaises(TypeError, u.index) class BadExc(Exception): pass class BadCmp: def __eq__(self, other): if other == 2: raise BadExc() return False a = range(4) self.assertRaises(BadExc, a.index, BadCmp()) a = range(-2, 3) self.assertEqual(a.index(0), 2) self.assertEqual(range(1, 10, 3).index(4), 1) self.assertEqual(range(1, -10, -3).index(-5), 2) self.assertEqual(range(10**20).index(1), 1) self.assertEqual(range(10**20).index(10**20 - 1), 10**20 - 1) self.assertRaises(ValueError, range(1, 2**100, 2).index, 2**87) self.assertEqual(range(1, 2**100, 2).index(2**87+1), 2**86) class AlwaysEqual(object): def __eq__(self, other): return True always_equal = AlwaysEqual() self.assertEqual(range(10).index(always_equal), 0) def test_user_index_method(self): bignum = 2*sys.maxsize smallnum = 42 # User-defined class with an __index__ method class I: def __init__(self, n): self.n = int(n) def __index__(self): return self.n self.assertEqual(list(range(I(bignum), I(bignum + 1))), [bignum]) self.assertEqual(list(range(I(smallnum), I(smallnum + 1))), [smallnum]) # User-defined class with a failing __index__ method class IX: def __index__(self): raise RuntimeError self.assertRaises(RuntimeError, range, IX()) # User-defined class with an invalid __index__ method class IN: def __index__(self): return "not a number" self.assertRaises(TypeError, range, IN()) # Test use of user-defined classes in slice indices. self.assertEqual(range(10)[:I(5)], range(5)) with self.assertRaises(RuntimeError): range(0, 10)[:IX()] with self.assertRaises(TypeError): range(0, 10)[:IN()] def test_count(self): self.assertEqual(range(3).count(-1), 0) self.assertEqual(range(3).count(0), 1) self.assertEqual(range(3).count(1), 1) self.assertEqual(range(3).count(2), 1) self.assertEqual(range(3).count(3), 0) self.assertIs(type(range(3).count(-1)), int) self.assertIs(type(range(3).count(1)), int) self.assertEqual(range(10**20).count(1), 1) self.assertEqual(range(10**20).count(10**20), 0) self.assertEqual(range(3).index(1), 1) self.assertEqual(range(1, 2**100, 2).count(2**87), 0) self.assertEqual(range(1, 2**100, 2).count(2**87+1), 1) class AlwaysEqual(object): def __eq__(self, other): return True always_equal = AlwaysEqual() self.assertEqual(range(10).count(always_equal), 10) self.assertEqual(len(range(sys.maxsize, sys.maxsize+10)), 10) def test_repr(self): self.assertEqual(repr(range(1)), 'range(0, 1)') self.assertEqual(repr(range(1, 2)), 'range(1, 2)') self.assertEqual(repr(range(1, 2, 3)), 'range(1, 2, 3)') def test_pickling(self): testcases = [(13,), (0, 11), (-22, 10), (20, 3, -1), (13, 21, 3), (-2, 2, 2), (2**65, 2**65+2)] for proto in range(pickle.HIGHEST_PROTOCOL + 1): for t in testcases: with self.subTest(proto=proto, test=t): r = range(*t) self.assertEqual(list(pickle.loads(pickle.dumps(r, proto))), list(r)) def test_iterator_pickling(self): testcases = [(13,), (0, 11), (-22, 10), (20, 3, -1), (13, 21, 3), (-2, 2, 2), (2**65, 2**65+2)] for proto in range(pickle.HIGHEST_PROTOCOL + 1): for t in testcases: it = itorg = iter(range(*t)) data = list(range(*t)) d = pickle.dumps(it, proto) it = pickle.loads(d) self.assertEqual(type(itorg), type(it)) self.assertEqual(list(it), data) it = pickle.loads(d) try: next(it) except StopIteration: continue d = pickle.dumps(it, proto) it = pickle.loads(d) self.assertEqual(list(it), data[1:]) def test_exhausted_iterator_pickling(self): for proto in range(pickle.HIGHEST_PROTOCOL + 1): r = range(2**65, 2**65+2) i = iter(r) while True: r = next(i) if r == 2**65+1: break d = pickle.dumps(i, proto) i2 = pickle.loads(d) self.assertEqual(list(i), []) self.assertEqual(list(i2), []) def test_large_exhausted_iterator_pickling(self): for proto in range(pickle.HIGHEST_PROTOCOL + 1): r = range(20) i = iter(r) while True: r = next(i) if r == 19: break d = pickle.dumps(i, proto) i2 = pickle.loads(d) self.assertEqual(list(i), []) self.assertEqual(list(i2), []) def test_odd_bug(self): # This used to raise a "SystemError: NULL result without error" # because the range validation step was eating the exception # before NULL was returned. with self.assertRaises(TypeError): range([], 1, -1) def test_types(self): # Non-integer objects *equal* to any of the range's items are supposed # to be contained in the range. self.assertIn(1.0, range(3)) self.assertIn(True, range(3)) self.assertIn(1+0j, range(3)) class C1: def __eq__(self, other): return True self.assertIn(C1(), range(3)) # Objects are never coerced into other types for comparison. class C2: def __int__(self): return 1 def __index__(self): return 1 self.assertNotIn(C2(), range(3)) # ..except if explicitly told so. self.assertIn(int(C2()), range(3)) # Check that the range.__contains__ optimization is only # used for ints, not for instances of subclasses of int. class C3(int): def __eq__(self, other): return True self.assertIn(C3(11), range(10)) self.assertIn(C3(11), list(range(10))) def test_strided_limits(self): r = range(0, 101, 2) self.assertIn(0, r) self.assertNotIn(1, r) self.assertIn(2, r) self.assertNotIn(99, r) self.assertIn(100, r) self.assertNotIn(101, r) r = range(0, -20, -1) self.assertIn(0, r) self.assertIn(-1, r) self.assertIn(-19, r) self.assertNotIn(-20, r) r = range(0, -20, -2) self.assertIn(-18, r) self.assertNotIn(-19, r) self.assertNotIn(-20, r) def test_empty(self): r = range(0) self.assertNotIn(0, r) self.assertNotIn(1, r) r = range(0, -10) self.assertNotIn(0, r) self.assertNotIn(-1, r) self.assertNotIn(1, r) def test_range_iterators(self): # exercise 'fast' iterators, that use a rangeiterobject internally. # see issue 7298 limits = [base + jiggle for M in (2**32, 2**64) for base in (-M, -M//2, 0, M//2, M) for jiggle in (-2, -1, 0, 1, 2)] test_ranges = [(start, end, step) for start in limits for end in limits for step in (-2**63, -2**31, -2, -1, 1, 2)] for start, end, step in test_ranges: iter1 = range(start, end, step) iter2 = pyrange(start, end, step) test_id = "range({}, {}, {})".format(start, end, step) # check first 100 entries self.assert_iterators_equal(iter1, iter2, test_id, limit=100) iter1 = reversed(range(start, end, step)) iter2 = pyrange_reversed(start, end, step) test_id = "reversed(range({}, {}, {}))".format(start, end, step) self.assert_iterators_equal(iter1, iter2, test_id, limit=100) @test.support.cpython_only def test_range_iterator_invocation(self): import _testcapi rangeiter_type = type(iter(range(0))) self.assertWarns(DeprecationWarning, rangeiter_type, 1, 3, 1) with test.support.check_warnings(('', DeprecationWarning)): # rangeiter_new doesn't take keyword arguments with self.assertRaises(TypeError): rangeiter_type(a=1) # rangeiter_new takes exactly 3 arguments self.assertRaises(TypeError, rangeiter_type) self.assertRaises(TypeError, rangeiter_type, 1) self.assertRaises(TypeError, rangeiter_type, 1, 1) self.assertRaises(TypeError, rangeiter_type, 1, 1, 1, 1) # start, stop and stop must fit in C long for good_val in [_testcapi.LONG_MAX, _testcapi.LONG_MIN]: rangeiter_type(good_val, good_val, good_val) for bad_val in [_testcapi.LONG_MAX + 1, _testcapi.LONG_MIN - 1]: self.assertRaises(OverflowError, rangeiter_type, bad_val, 1, 1) self.assertRaises(OverflowError, rangeiter_type, 1, bad_val, 1) self.assertRaises(OverflowError, rangeiter_type, 1, 1, bad_val) # step mustn't be zero self.assertRaises(ValueError, rangeiter_type, 1, 1, 0) def test_slice(self): def check(start, stop, step=None): i = slice(start, stop, step) self.assertEqual(list(r[i]), list(r)[i]) self.assertEqual(len(r[i]), len(list(r)[i])) for r in [range(10), range(0), range(1, 9, 3), range(8, 0, -3), range(sys.maxsize+1, sys.maxsize+10), ]: check(0, 2) check(0, 20) check(1, 2) check(20, 30) check(-30, -20) check(-1, 100, 2) check(0, -1) check(-1, -3, -1) def test_contains(self): r = range(10) self.assertIn(0, r) self.assertIn(1, r) self.assertIn(5.0, r) self.assertNotIn(5.1, r) self.assertNotIn(-1, r) self.assertNotIn(10, r) self.assertNotIn("", r) r = range(9, -1, -1) self.assertIn(0, r) self.assertIn(1, r) self.assertIn(5.0, r) self.assertNotIn(5.1, r) self.assertNotIn(-1, r) self.assertNotIn(10, r) self.assertNotIn("", r) r = range(0, 10, 2) self.assertIn(0, r) self.assertNotIn(1, r) self.assertNotIn(5.0, r) self.assertNotIn(5.1, r) self.assertNotIn(-1, r) self.assertNotIn(10, r) self.assertNotIn("", r) r = range(9, -1, -2) self.assertNotIn(0, r) self.assertIn(1, r) self.assertIn(5.0, r) self.assertNotIn(5.1, r) self.assertNotIn(-1, r) self.assertNotIn(10, r) self.assertNotIn("", r) def test_reverse_iteration(self): for r in [range(10), range(0), range(1, 9, 3), range(8, 0, -3), range(sys.maxsize+1, sys.maxsize+10), ]: self.assertEqual(list(reversed(r)), list(r)[::-1]) def test_issue11845(self): r = range(*slice(1, 18, 2).indices(20)) values = {None, 0, 1, -1, 2, -2, 5, -5, 19, -19, 20, -20, 21, -21, 30, -30, 99, -99} for i in values: for j in values: for k in values - {0}: r[i:j:k] def test_comparison(self): test_ranges = [range(0), range(0, -1), range(1, 1, 3), range(1), range(5, 6), range(5, 6, 2), range(5, 7, 2), range(2), range(0, 4, 2), range(0, 5, 2), range(0, 6, 2)] test_tuples = list(map(tuple, test_ranges)) # Check that equality of ranges matches equality of the corresponding # tuples for each pair from the test lists above. ranges_eq = [a == b for a in test_ranges for b in test_ranges] tuples_eq = [a == b for a in test_tuples for b in test_tuples] self.assertEqual(ranges_eq, tuples_eq) # Check that != correctly gives the logical negation of == ranges_ne = [a != b for a in test_ranges for b in test_ranges] self.assertEqual(ranges_ne, [not x for x in ranges_eq]) # Equal ranges should have equal hashes. for a in test_ranges: for b in test_ranges: if a == b: self.assertEqual(hash(a), hash(b)) # Ranges are unequal to other types (even sequence types) self.assertIs(range(0) == (), False) self.assertIs(() == range(0), False) self.assertIs(range(2) == [0, 1], False) # Huge integers aren't a problem. self.assertEqual(range(0, 2**100 - 1, 2), range(0, 2**100, 2)) self.assertEqual(hash(range(0, 2**100 - 1, 2)), hash(range(0, 2**100, 2))) self.assertNotEqual(range(0, 2**100, 2), range(0, 2**100 + 1, 2)) self.assertEqual(range(2**200, 2**201 - 2**99, 2**100), range(2**200, 2**201, 2**100)) self.assertEqual(hash(range(2**200, 2**201 - 2**99, 2**100)), hash(range(2**200, 2**201, 2**100))) self.assertNotEqual(range(2**200, 2**201, 2**100), range(2**200, 2**201 + 1, 2**100)) # Order comparisons are not implemented for ranges. with self.assertRaises(TypeError): range(0) < range(0) with self.assertRaises(TypeError): range(0) > range(0) with self.assertRaises(TypeError): range(0) <= range(0) with self.assertRaises(TypeError): range(0) >= range(0) def test_attributes(self): # test the start, stop and step attributes of range objects self.assert_attrs(range(0), 0, 0, 1) self.assert_attrs(range(10), 0, 10, 1) self.assert_attrs(range(-10), 0, -10, 1) self.assert_attrs(range(0, 10, 1), 0, 10, 1) self.assert_attrs(range(0, 10, 3), 0, 10, 3) self.assert_attrs(range(10, 0, -1), 10, 0, -1) self.assert_attrs(range(10, 0, -3), 10, 0, -3) def assert_attrs(self, rangeobj, start, stop, step): self.assertEqual(rangeobj.start, start) self.assertEqual(rangeobj.stop, stop) self.assertEqual(rangeobj.step, step) with self.assertRaises(AttributeError): rangeobj.start = 0 with self.assertRaises(AttributeError): rangeobj.stop = 10 with self.assertRaises(AttributeError): rangeobj.step = 1 with self.assertRaises(AttributeError): del rangeobj.start with self.assertRaises(AttributeError): del rangeobj.stop with self.assertRaises(AttributeError): del rangeobj.step if __name__ == "__main__": unittest.main()
24,999
694
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_complex.py
import unittest from test import support from test.test_grammar import (VALID_UNDERSCORE_LITERALS, INVALID_UNDERSCORE_LITERALS) from random import random from math import atan2, isnan, copysign import operator INF = float("inf") NAN = float("nan") # These tests ensure that complex math does the right thing class ComplexTest(unittest.TestCase): def assertAlmostEqual(self, a, b): if isinstance(a, complex): if isinstance(b, complex): unittest.TestCase.assertAlmostEqual(self, a.real, b.real) unittest.TestCase.assertAlmostEqual(self, a.imag, b.imag) else: unittest.TestCase.assertAlmostEqual(self, a.real, b) unittest.TestCase.assertAlmostEqual(self, a.imag, 0.) else: if isinstance(b, complex): unittest.TestCase.assertAlmostEqual(self, a, b.real) unittest.TestCase.assertAlmostEqual(self, 0., b.imag) else: unittest.TestCase.assertAlmostEqual(self, a, b) def assertCloseAbs(self, x, y, eps=1e-9): """Return true iff floats x and y "are close".""" # put the one with larger magnitude second if abs(x) > abs(y): x, y = y, x if y == 0: return abs(x) < eps if x == 0: return abs(y) < eps # check that relative difference < eps self.assertTrue(abs((x-y)/y) < eps) def assertFloatsAreIdentical(self, x, y): """assert that floats x and y are identical, in the sense that: (1) both x and y are nans, or (2) both x and y are infinities, with the same sign, or (3) both x and y are zeros, with the same sign, or (4) x and y are both finite and nonzero, and x == y """ msg = 'floats {!r} and {!r} are not identical' if isnan(x) or isnan(y): if isnan(x) and isnan(y): return elif x == y: if x != 0.0: return # both zero; check that signs match elif copysign(1.0, x) == copysign(1.0, y): return else: msg += ': zeros have different signs' self.fail(msg.format(x, y)) def assertClose(self, x, y, eps=1e-9): """Return true iff complexes x and y "are close".""" self.assertCloseAbs(x.real, y.real, eps) self.assertCloseAbs(x.imag, y.imag, eps) def check_div(self, x, y): """Compute complex z=x*y, and check that z/x==y and z/y==x.""" z = x * y if x != 0: q = z / x self.assertClose(q, y) q = z.__truediv__(x) self.assertClose(q, y) if y != 0: q = z / y self.assertClose(q, x) q = z.__truediv__(y) self.assertClose(q, x) def test_truediv(self): simple_real = [float(i) for i in range(-5, 6)] simple_complex = [complex(x, y) for x in simple_real for y in simple_real] for x in simple_complex: for y in simple_complex: self.check_div(x, y) # A naive complex division algorithm (such as in 2.0) is very prone to # nonsense errors for these (overflows and underflows). self.check_div(complex(1e200, 1e200), 1+0j) self.check_div(complex(1e-200, 1e-200), 1+0j) # Just for fun. for i in range(100): self.check_div(complex(random(), random()), complex(random(), random())) self.assertRaises(ZeroDivisionError, complex.__truediv__, 1+1j, 0+0j) # FIXME: The following currently crashes on Alpha # self.assertRaises(OverflowError, pow, 1e200+1j, 1e200+1j) self.assertAlmostEqual(complex.__truediv__(2+0j, 1+1j), 1-1j) self.assertRaises(ZeroDivisionError, complex.__truediv__, 1+1j, 0+0j) for denom_real, denom_imag in [(0, NAN), (NAN, 0), (NAN, NAN)]: z = complex(0, 0) / complex(denom_real, denom_imag) self.assertTrue(isnan(z.real)) self.assertTrue(isnan(z.imag)) def test_floordiv(self): self.assertRaises(TypeError, complex.__floordiv__, 3+0j, 1.5+0j) self.assertRaises(TypeError, complex.__floordiv__, 3+0j, 0+0j) def test_richcompare(self): self.assertIs(complex.__eq__(1+1j, 1<<10000), False) self.assertIs(complex.__lt__(1+1j, None), NotImplemented) self.assertIs(complex.__eq__(1+1j, 1+1j), True) self.assertIs(complex.__eq__(1+1j, 2+2j), False) self.assertIs(complex.__ne__(1+1j, 1+1j), False) self.assertIs(complex.__ne__(1+1j, 2+2j), True) for i in range(1, 100): f = i / 100.0 self.assertIs(complex.__eq__(f+0j, f), True) self.assertIs(complex.__ne__(f+0j, f), False) self.assertIs(complex.__eq__(complex(f, f), f), False) self.assertIs(complex.__ne__(complex(f, f), f), True) self.assertIs(complex.__lt__(1+1j, 2+2j), NotImplemented) self.assertIs(complex.__le__(1+1j, 2+2j), NotImplemented) self.assertIs(complex.__gt__(1+1j, 2+2j), NotImplemented) self.assertIs(complex.__ge__(1+1j, 2+2j), NotImplemented) self.assertRaises(TypeError, operator.lt, 1+1j, 2+2j) self.assertRaises(TypeError, operator.le, 1+1j, 2+2j) self.assertRaises(TypeError, operator.gt, 1+1j, 2+2j) self.assertRaises(TypeError, operator.ge, 1+1j, 2+2j) self.assertIs(operator.eq(1+1j, 1+1j), True) self.assertIs(operator.eq(1+1j, 2+2j), False) self.assertIs(operator.ne(1+1j, 1+1j), False) self.assertIs(operator.ne(1+1j, 2+2j), True) def test_richcompare_boundaries(self): def check(n, deltas, is_equal, imag = 0.0): for delta in deltas: i = n + delta z = complex(i, imag) self.assertIs(complex.__eq__(z, i), is_equal(delta)) self.assertIs(complex.__ne__(z, i), not is_equal(delta)) # For IEEE-754 doubles the following should hold: # x in [2 ** (52 + i), 2 ** (53 + i + 1)] -> x mod 2 ** i == 0 # where the interval is representable, of course. for i in range(1, 10): pow = 52 + i mult = 2 ** i check(2 ** pow, range(1, 101), lambda delta: delta % mult == 0) check(2 ** pow, range(1, 101), lambda delta: False, float(i)) check(2 ** 53, range(-100, 0), lambda delta: True) def test_mod(self): # % is no longer supported on complex numbers self.assertRaises(TypeError, (1+1j).__mod__, 0+0j) self.assertRaises(TypeError, lambda: (3.33+4.43j) % 0) self.assertRaises(TypeError, (1+1j).__mod__, 4.3j) def test_divmod(self): self.assertRaises(TypeError, divmod, 1+1j, 1+0j) self.assertRaises(TypeError, divmod, 1+1j, 0+0j) def test_pow(self): self.assertAlmostEqual(pow(1+1j, 0+0j), 1.0) self.assertAlmostEqual(pow(0+0j, 2+0j), 0.0) self.assertRaises(ZeroDivisionError, pow, 0+0j, 1j) self.assertAlmostEqual(pow(1j, -1), 1/1j) self.assertAlmostEqual(pow(1j, 200), 1) self.assertRaises(ValueError, pow, 1+1j, 1+1j, 1+1j) a = 3.33+4.43j self.assertEqual(a ** 0j, 1) self.assertEqual(a ** 0.+0.j, 1) self.assertEqual(3j ** 0j, 1) self.assertEqual(3j ** 0, 1) try: 0j ** a except ZeroDivisionError: pass else: self.fail("should fail 0.0 to negative or complex power") try: 0j ** (3-2j) except ZeroDivisionError: pass else: self.fail("should fail 0.0 to negative or complex power") # The following is used to exercise certain code paths self.assertEqual(a ** 105, a ** 105) self.assertEqual(a ** -105, a ** -105) self.assertEqual(a ** -30, a ** -30) self.assertEqual(0.0j ** 0, 1) b = 5.1+2.3j self.assertRaises(ValueError, pow, a, b, 0) def test_boolcontext(self): for i in range(100): self.assertTrue(complex(random() + 1e-6, random() + 1e-6)) self.assertTrue(not complex(0.0, 0.0)) def test_conjugate(self): self.assertClose(complex(5.3, 9.8).conjugate(), 5.3-9.8j) def test_constructor(self): class OS: def __init__(self, value): self.value = value def __complex__(self): return self.value class NS(object): def __init__(self, value): self.value = value def __complex__(self): return self.value self.assertEqual(complex(OS(1+10j)), 1+10j) self.assertEqual(complex(NS(1+10j)), 1+10j) self.assertRaises(TypeError, complex, OS(None)) self.assertRaises(TypeError, complex, NS(None)) self.assertRaises(TypeError, complex, {}) self.assertRaises(TypeError, complex, NS(1.5)) self.assertRaises(TypeError, complex, NS(1)) self.assertAlmostEqual(complex("1+10j"), 1+10j) self.assertAlmostEqual(complex(10), 10+0j) self.assertAlmostEqual(complex(10.0), 10+0j) self.assertAlmostEqual(complex(10), 10+0j) self.assertAlmostEqual(complex(10+0j), 10+0j) self.assertAlmostEqual(complex(1,10), 1+10j) self.assertAlmostEqual(complex(1,10), 1+10j) self.assertAlmostEqual(complex(1,10.0), 1+10j) self.assertAlmostEqual(complex(1,10), 1+10j) self.assertAlmostEqual(complex(1,10), 1+10j) self.assertAlmostEqual(complex(1,10.0), 1+10j) self.assertAlmostEqual(complex(1.0,10), 1+10j) self.assertAlmostEqual(complex(1.0,10), 1+10j) self.assertAlmostEqual(complex(1.0,10.0), 1+10j) self.assertAlmostEqual(complex(3.14+0j), 3.14+0j) self.assertAlmostEqual(complex(3.14), 3.14+0j) self.assertAlmostEqual(complex(314), 314.0+0j) self.assertAlmostEqual(complex(314), 314.0+0j) self.assertAlmostEqual(complex(3.14+0j, 0j), 3.14+0j) self.assertAlmostEqual(complex(3.14, 0.0), 3.14+0j) self.assertAlmostEqual(complex(314, 0), 314.0+0j) self.assertAlmostEqual(complex(314, 0), 314.0+0j) self.assertAlmostEqual(complex(0j, 3.14j), -3.14+0j) self.assertAlmostEqual(complex(0.0, 3.14j), -3.14+0j) self.assertAlmostEqual(complex(0j, 3.14), 3.14j) self.assertAlmostEqual(complex(0.0, 3.14), 3.14j) self.assertAlmostEqual(complex("1"), 1+0j) self.assertAlmostEqual(complex("1j"), 1j) self.assertAlmostEqual(complex(), 0) self.assertAlmostEqual(complex("-1"), -1) self.assertAlmostEqual(complex("+1"), +1) self.assertAlmostEqual(complex("(1+2j)"), 1+2j) self.assertAlmostEqual(complex("(1.3+2.2j)"), 1.3+2.2j) self.assertAlmostEqual(complex("3.14+1J"), 3.14+1j) self.assertAlmostEqual(complex(" ( +3.14-6J )"), 3.14-6j) self.assertAlmostEqual(complex(" ( +3.14-J )"), 3.14-1j) self.assertAlmostEqual(complex(" ( +3.14+j )"), 3.14+1j) self.assertAlmostEqual(complex("J"), 1j) self.assertAlmostEqual(complex("( j )"), 1j) self.assertAlmostEqual(complex("+J"), 1j) self.assertAlmostEqual(complex("( -j)"), -1j) self.assertAlmostEqual(complex('1e-500'), 0.0 + 0.0j) self.assertAlmostEqual(complex('-1e-500j'), 0.0 - 0.0j) self.assertAlmostEqual(complex('-1e-500+1e-500j'), -0.0 + 0.0j) class complex2(complex): pass self.assertAlmostEqual(complex(complex2(1+1j)), 1+1j) self.assertAlmostEqual(complex(real=17, imag=23), 17+23j) self.assertAlmostEqual(complex(real=17+23j), 17+23j) self.assertAlmostEqual(complex(real=17+23j, imag=23), 17+46j) self.assertAlmostEqual(complex(real=1+2j, imag=3+4j), -3+5j) # check that the sign of a zero in the real or imaginary part # is preserved when constructing from two floats. (These checks # are harmless on systems without support for signed zeros.) def split_zeros(x): """Function that produces different results for 0. and -0.""" return atan2(x, -1.) self.assertEqual(split_zeros(complex(1., 0.).imag), split_zeros(0.)) self.assertEqual(split_zeros(complex(1., -0.).imag), split_zeros(-0.)) self.assertEqual(split_zeros(complex(0., 1.).real), split_zeros(0.)) self.assertEqual(split_zeros(complex(-0., 1.).real), split_zeros(-0.)) c = 3.14 + 1j self.assertTrue(complex(c) is c) del c self.assertRaises(TypeError, complex, "1", "1") self.assertRaises(TypeError, complex, 1, "1") # SF bug 543840: complex(string) accepts strings with \0 # Fixed in 2.3. self.assertRaises(ValueError, complex, '1+1j\0j') self.assertRaises(TypeError, int, 5+3j) self.assertRaises(TypeError, int, 5+3j) self.assertRaises(TypeError, float, 5+3j) self.assertRaises(ValueError, complex, "") self.assertRaises(TypeError, complex, None) self.assertRaisesRegex(TypeError, "not 'NoneType'", complex, None) self.assertRaises(ValueError, complex, "\0") self.assertRaises(ValueError, complex, "3\09") self.assertRaises(TypeError, complex, "1", "2") self.assertRaises(TypeError, complex, "1", 42) self.assertRaises(TypeError, complex, 1, "2") self.assertRaises(ValueError, complex, "1+") self.assertRaises(ValueError, complex, "1+1j+1j") self.assertRaises(ValueError, complex, "--") self.assertRaises(ValueError, complex, "(1+2j") self.assertRaises(ValueError, complex, "1+2j)") self.assertRaises(ValueError, complex, "1+(2j)") self.assertRaises(ValueError, complex, "(1+2j)123") self.assertRaises(ValueError, complex, "x") self.assertRaises(ValueError, complex, "1j+2") self.assertRaises(ValueError, complex, "1e1ej") self.assertRaises(ValueError, complex, "1e++1ej") self.assertRaises(ValueError, complex, ")1+2j(") self.assertRaisesRegex( TypeError, "first argument must be a string or a number, not 'dict'", complex, {1:2}, 1) self.assertRaisesRegex( TypeError, "second argument must be a number, not 'dict'", complex, 1, {1:2}) # the following three are accepted by Python 2.6 self.assertRaises(ValueError, complex, "1..1j") self.assertRaises(ValueError, complex, "1.11.1j") self.assertRaises(ValueError, complex, "1e1.1j") # check that complex accepts long unicode strings self.assertEqual(type(complex("1"*500)), complex) # check whitespace processing self.assertEqual(complex('\N{EM SPACE}(\N{EN SPACE}1+1j ) '), 1+1j) # Invalid unicode string # See bpo-34087 self.assertRaises(ValueError, complex, '\u3053\u3093\u306b\u3061\u306f') class EvilExc(Exception): pass class evilcomplex: def __complex__(self): raise EvilExc self.assertRaises(EvilExc, complex, evilcomplex()) class float2: def __init__(self, value): self.value = value def __float__(self): return self.value self.assertAlmostEqual(complex(float2(42.)), 42) self.assertAlmostEqual(complex(real=float2(17.), imag=float2(23.)), 17+23j) self.assertRaises(TypeError, complex, float2(None)) class complex0(complex): """Test usage of __complex__() when inheriting from 'complex'""" def __complex__(self): return 42j class complex1(complex): """Test usage of __complex__() with a __new__() method""" def __new__(self, value=0j): return complex.__new__(self, 2*value) def __complex__(self): return self class complex2(complex): """Make sure that __complex__() calls fail if anything other than a complex is returned""" def __complex__(self): return None self.assertAlmostEqual(complex(complex0(1j)), 42j) self.assertAlmostEqual(complex(complex1(1j)), 2j) self.assertRaises(TypeError, complex, complex2(1j)) @support.requires_IEEE_754 def test_constructor_special_numbers(self): class complex2(complex): pass for x in 0.0, -0.0, INF, -INF, NAN: for y in 0.0, -0.0, INF, -INF, NAN: with self.subTest(x=x, y=y): z = complex(x, y) self.assertFloatsAreIdentical(z.real, x) self.assertFloatsAreIdentical(z.imag, y) z = complex2(x, y) self.assertIs(type(z), complex2) self.assertFloatsAreIdentical(z.real, x) self.assertFloatsAreIdentical(z.imag, y) z = complex(complex2(x, y)) self.assertIs(type(z), complex) self.assertFloatsAreIdentical(z.real, x) self.assertFloatsAreIdentical(z.imag, y) z = complex2(complex(x, y)) self.assertIs(type(z), complex2) self.assertFloatsAreIdentical(z.real, x) self.assertFloatsAreIdentical(z.imag, y) def test_underscores(self): # check underscores for lit in VALID_UNDERSCORE_LITERALS: if not any(ch in lit for ch in 'xXoObB'): self.assertEqual(complex(lit), eval(lit)) self.assertEqual(complex(lit), complex(lit.replace('_', ''))) for lit in INVALID_UNDERSCORE_LITERALS: if lit in ('0_7', '09_99'): # octals are not recognized here continue if not any(ch in lit for ch in 'xXoObB'): self.assertRaises(ValueError, complex, lit) def test_hash(self): for x in range(-30, 30): self.assertEqual(hash(x), hash(complex(x, 0))) x /= 3.0 # now check against floating point self.assertEqual(hash(x), hash(complex(x, 0.))) def test_abs(self): nums = [complex(x/3., y/7.) for x in range(-9,9) for y in range(-9,9)] for num in nums: self.assertAlmostEqual((num.real**2 + num.imag**2) ** 0.5, abs(num)) def test_repr_str(self): def test(v, expected, test_fn=self.assertEqual): test_fn(repr(v), expected) test_fn(str(v), expected) test(1+6j, '(1+6j)') test(1-6j, '(1-6j)') test(-(1+0j), '(-1+-0j)', test_fn=self.assertNotEqual) test(complex(1., INF), "(1+infj)") test(complex(1., -INF), "(1-infj)") test(complex(INF, 1), "(inf+1j)") test(complex(-INF, INF), "(-inf+infj)") test(complex(NAN, 1), "(nan+1j)") test(complex(1, NAN), "(1+nanj)") test(complex(NAN, NAN), "(nan+nanj)") test(complex(0, INF), "infj") test(complex(0, -INF), "-infj") test(complex(0, NAN), "nanj") self.assertEqual(1-6j,complex(repr(1-6j))) self.assertEqual(1+6j,complex(repr(1+6j))) self.assertEqual(-6j,complex(repr(-6j))) self.assertEqual(6j,complex(repr(6j))) @support.requires_IEEE_754 def test_negative_zero_repr_str(self): def test(v, expected, test_fn=self.assertEqual): test_fn(repr(v), expected) test_fn(str(v), expected) test(complex(0., 1.), "1j") test(complex(-0., 1.), "(-0+1j)") test(complex(0., -1.), "-1j") test(complex(-0., -1.), "(-0-1j)") test(complex(0., 0.), "0j") test(complex(0., -0.), "-0j") test(complex(-0., 0.), "(-0+0j)") test(complex(-0., -0.), "(-0-0j)") def test_neg(self): self.assertEqual(-(1+6j), -1-6j) def test_file(self): a = 3.33+4.43j b = 5.1+2.3j fo = None try: fo = open(support.TESTFN, "w") print(a, b, file=fo) fo.close() fo = open(support.TESTFN, "r") self.assertEqual(fo.read(), ("%s %s\n" % (a, b))) finally: if (fo is not None) and (not fo.closed): fo.close() support.unlink(support.TESTFN) def test_getnewargs(self): self.assertEqual((1+2j).__getnewargs__(), (1.0, 2.0)) self.assertEqual((1-2j).__getnewargs__(), (1.0, -2.0)) self.assertEqual((2j).__getnewargs__(), (0.0, 2.0)) self.assertEqual((-0j).__getnewargs__(), (0.0, -0.0)) self.assertEqual(complex(0, INF).__getnewargs__(), (0.0, INF)) self.assertEqual(complex(INF, 0).__getnewargs__(), (INF, 0.0)) @support.requires_IEEE_754 def test_plus_minus_0j(self): # test that -0j and 0j literals are not identified z1, z2 = 0j, -0j self.assertEqual(atan2(z1.imag, -1.), atan2(0., -1.)) self.assertEqual(atan2(z2.imag, -1.), atan2(-0., -1.)) @support.requires_IEEE_754 def test_negated_imaginary_literal(self): z0 = -0j z1 = -7j z2 = -1e1000j # Note: In versions of Python < 3.2, a negated imaginary literal # accidentally ended up with real part 0.0 instead of -0.0, thanks to a # modification during CST -> AST translation (see issue #9011). That's # fixed in Python 3.2. self.assertFloatsAreIdentical(z0.real, -0.0) self.assertFloatsAreIdentical(z0.imag, -0.0) self.assertFloatsAreIdentical(z1.real, -0.0) self.assertFloatsAreIdentical(z1.imag, -7.0) self.assertFloatsAreIdentical(z2.real, -0.0) self.assertFloatsAreIdentical(z2.imag, -INF) @support.requires_IEEE_754 def test_overflow(self): self.assertEqual(complex("1e500"), complex(INF, 0.0)) self.assertEqual(complex("-1e500j"), complex(0.0, -INF)) self.assertEqual(complex("-1e500+1.8e308j"), complex(-INF, INF)) @support.requires_IEEE_754 def test_repr_roundtrip(self): vals = [0.0, 1e-500, 1e-315, 1e-200, 0.0123, 3.1415, 1e50, INF, NAN] vals += [-v for v in vals] # complex(repr(z)) should recover z exactly, even for complex # numbers involving an infinity, nan, or negative zero for x in vals: for y in vals: z = complex(x, y) roundtrip = complex(repr(z)) self.assertFloatsAreIdentical(z.real, roundtrip.real) self.assertFloatsAreIdentical(z.imag, roundtrip.imag) # if we predefine some constants, then eval(repr(z)) should # also work, except that it might change the sign of zeros inf, nan = float('inf'), float('nan') infj, nanj = complex(0.0, inf), complex(0.0, nan) for x in vals: for y in vals: z = complex(x, y) roundtrip = eval(repr(z)) # adding 0.0 has no effect beside changing -0.0 to 0.0 self.assertFloatsAreIdentical(0.0 + z.real, 0.0 + roundtrip.real) self.assertFloatsAreIdentical(0.0 + z.imag, 0.0 + roundtrip.imag) def test_format(self): # empty format string is same as str() self.assertEqual(format(1+3j, ''), str(1+3j)) self.assertEqual(format(1.5+3.5j, ''), str(1.5+3.5j)) self.assertEqual(format(3j, ''), str(3j)) self.assertEqual(format(3.2j, ''), str(3.2j)) self.assertEqual(format(3+0j, ''), str(3+0j)) self.assertEqual(format(3.2+0j, ''), str(3.2+0j)) # empty presentation type should still be analogous to str, # even when format string is nonempty (issue #5920). self.assertEqual(format(3.2+0j, '-'), str(3.2+0j)) self.assertEqual(format(3.2+0j, '<'), str(3.2+0j)) z = 4/7. - 100j/7. self.assertEqual(format(z, ''), str(z)) self.assertEqual(format(z, '-'), str(z)) self.assertEqual(format(z, '<'), str(z)) self.assertEqual(format(z, '10'), str(z)) z = complex(0.0, 3.0) self.assertEqual(format(z, ''), str(z)) self.assertEqual(format(z, '-'), str(z)) self.assertEqual(format(z, '<'), str(z)) self.assertEqual(format(z, '2'), str(z)) z = complex(-0.0, 2.0) self.assertEqual(format(z, ''), str(z)) self.assertEqual(format(z, '-'), str(z)) self.assertEqual(format(z, '<'), str(z)) self.assertEqual(format(z, '3'), str(z)) self.assertEqual(format(1+3j, 'g'), '1+3j') self.assertEqual(format(3j, 'g'), '0+3j') self.assertEqual(format(1.5+3.5j, 'g'), '1.5+3.5j') self.assertEqual(format(1.5+3.5j, '+g'), '+1.5+3.5j') self.assertEqual(format(1.5-3.5j, '+g'), '+1.5-3.5j') self.assertEqual(format(1.5-3.5j, '-g'), '1.5-3.5j') self.assertEqual(format(1.5+3.5j, ' g'), ' 1.5+3.5j') self.assertEqual(format(1.5-3.5j, ' g'), ' 1.5-3.5j') self.assertEqual(format(-1.5+3.5j, ' g'), '-1.5+3.5j') self.assertEqual(format(-1.5-3.5j, ' g'), '-1.5-3.5j') self.assertEqual(format(-1.5-3.5e-20j, 'g'), '-1.5-3.5e-20j') self.assertEqual(format(-1.5-3.5j, 'f'), '-1.500000-3.500000j') self.assertEqual(format(-1.5-3.5j, 'F'), '-1.500000-3.500000j') self.assertEqual(format(-1.5-3.5j, 'e'), '-1.500000e+00-3.500000e+00j') self.assertEqual(format(-1.5-3.5j, '.2e'), '-1.50e+00-3.50e+00j') self.assertEqual(format(-1.5-3.5j, '.2E'), '-1.50E+00-3.50E+00j') self.assertEqual(format(-1.5e10-3.5e5j, '.2G'), '-1.5E+10-3.5E+05j') self.assertEqual(format(1.5+3j, '<20g'), '1.5+3j ') self.assertEqual(format(1.5+3j, '*<20g'), '1.5+3j**************') self.assertEqual(format(1.5+3j, '>20g'), ' 1.5+3j') self.assertEqual(format(1.5+3j, '^20g'), ' 1.5+3j ') self.assertEqual(format(1.5+3j, '<20'), '(1.5+3j) ') self.assertEqual(format(1.5+3j, '>20'), ' (1.5+3j)') self.assertEqual(format(1.5+3j, '^20'), ' (1.5+3j) ') self.assertEqual(format(1.123-3.123j, '^20.2'), ' (1.1-3.1j) ') self.assertEqual(format(1.5+3j, '20.2f'), ' 1.50+3.00j') self.assertEqual(format(1.5+3j, '>20.2f'), ' 1.50+3.00j') self.assertEqual(format(1.5+3j, '<20.2f'), '1.50+3.00j ') self.assertEqual(format(1.5e20+3j, '<20.2f'), '150000000000000000000.00+3.00j') self.assertEqual(format(1.5e20+3j, '>40.2f'), ' 150000000000000000000.00+3.00j') self.assertEqual(format(1.5e20+3j, '^40,.2f'), ' 150,000,000,000,000,000,000.00+3.00j ') self.assertEqual(format(1.5e21+3j, '^40,.2f'), ' 1,500,000,000,000,000,000,000.00+3.00j ') self.assertEqual(format(1.5e21+3000j, ',.2f'), '1,500,000,000,000,000,000,000.00+3,000.00j') # Issue 7094: Alternate formatting (specified by #) self.assertEqual(format(1+1j, '.0e'), '1e+00+1e+00j') self.assertEqual(format(1+1j, '#.0e'), '1.e+00+1.e+00j') self.assertEqual(format(1+1j, '.0f'), '1+1j') self.assertEqual(format(1+1j, '#.0f'), '1.+1.j') self.assertEqual(format(1.1+1.1j, 'g'), '1.1+1.1j') self.assertEqual(format(1.1+1.1j, '#g'), '1.10000+1.10000j') # Alternate doesn't make a difference for these, they format the same with or without it self.assertEqual(format(1+1j, '.1e'), '1.0e+00+1.0e+00j') self.assertEqual(format(1+1j, '#.1e'), '1.0e+00+1.0e+00j') self.assertEqual(format(1+1j, '.1f'), '1.0+1.0j') self.assertEqual(format(1+1j, '#.1f'), '1.0+1.0j') # Misc. other alternate tests self.assertEqual(format((-1.5+0.5j), '#f'), '-1.500000+0.500000j') self.assertEqual(format((-1.5+0.5j), '#.0f'), '-2.+0.j') self.assertEqual(format((-1.5+0.5j), '#e'), '-1.500000e+00+5.000000e-01j') self.assertEqual(format((-1.5+0.5j), '#.0e'), '-2.e+00+5.e-01j') self.assertEqual(format((-1.5+0.5j), '#g'), '-1.50000+0.500000j') self.assertEqual(format((-1.5+0.5j), '.0g'), '-2+0.5j') self.assertEqual(format((-1.5+0.5j), '#.0g'), '-2.+0.5j') # zero padding is invalid self.assertRaises(ValueError, (1.5+0.5j).__format__, '010f') # '=' alignment is invalid self.assertRaises(ValueError, (1.5+3j).__format__, '=20') # integer presentation types are an error for t in 'bcdoxX': self.assertRaises(ValueError, (1.5+0.5j).__format__, t) # make sure everything works in ''.format() self.assertEqual('*{0:.3f}*'.format(3.14159+2.71828j), '*3.142+2.718j*') # issue 3382 self.assertEqual(format(complex(NAN, NAN), 'f'), 'nan+nanj') self.assertEqual(format(complex(1, NAN), 'f'), '1.000000+nanj') self.assertEqual(format(complex(NAN, 1), 'f'), 'nan+1.000000j') self.assertEqual(format(complex(NAN, -1), 'f'), 'nan-1.000000j') self.assertEqual(format(complex(NAN, NAN), 'F'), 'NAN+NANj') self.assertEqual(format(complex(1, NAN), 'F'), '1.000000+NANj') self.assertEqual(format(complex(NAN, 1), 'F'), 'NAN+1.000000j') self.assertEqual(format(complex(NAN, -1), 'F'), 'NAN-1.000000j') self.assertEqual(format(complex(INF, INF), 'f'), 'inf+infj') self.assertEqual(format(complex(1, INF), 'f'), '1.000000+infj') self.assertEqual(format(complex(INF, 1), 'f'), 'inf+1.000000j') self.assertEqual(format(complex(INF, -1), 'f'), 'inf-1.000000j') self.assertEqual(format(complex(INF, INF), 'F'), 'INF+INFj') self.assertEqual(format(complex(1, INF), 'F'), '1.000000+INFj') self.assertEqual(format(complex(INF, 1), 'F'), 'INF+1.000000j') self.assertEqual(format(complex(INF, -1), 'F'), 'INF-1.000000j') def test_main(): support.run_unittest(ComplexTest) if __name__ == "__main__": test_main()
30,346
692
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/inspect_fodder2.py
# line 1 def wrap(foo=None): def wrapper(func): return func return wrapper # line 7 def replace(func): def insteadfunc(): print('hello') return insteadfunc # line 13 @wrap() @wrap(wrap) def wrapped(): pass # line 19 @replace def gone(): pass # line 24 oll = lambda m: m # line 27 tll = lambda g: g and \ g and \ g # line 32 tlli = lambda d: d and \ d # line 36 def onelinefunc(): pass # line 39 def manyargs(arg1, arg2, arg3, arg4): pass # line 43 def twolinefunc(m): return m and \ m # line 47 a = [None, lambda x: x, None] # line 52 def setfunc(func): globals()["anonymous"] = func setfunc(lambda x, y: x*y) # line 57 def with_comment(): # hello world # line 61 multiline_sig = [ lambda x, \ y: x+y, None, ] # line 68 def func69(): class cls70: def func71(): pass return cls70 extra74 = 74 # line 76 def func77(): pass (extra78, stuff78) = 'xy' extra79 = 'stop' # line 81 class cls82: def func83(): pass (extra84, stuff84) = 'xy' extra85 = 'stop' # line 87 def func88(): # comment return 90 # line 92 def f(): class X: def g(): "doc" return 42 return X method_in_dynamic_class = f().g #line 101 def keyworded(*arg1, arg2=1): pass #line 105 def annotated(arg1: list): pass #line 109 def keyword_only_arg(*, arg): pass @wrap(lambda: None) def func114(): return 115 class ClassWithMethod: def method(self): pass from functools import wraps def decorator(func): @wraps(func) def fake(): return 42 return fake #line 129 @decorator def real(): return 20 #line 134 class cls135: def func136(): def func137(): never_reached1 never_reached2
1,816
140
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_marshal.py
from test import support import array import io import marshal import sys import unittest import os import types try: import _testcapi except ImportError: _testcapi = None if __name__ == 'PYOBJ.COM': import _testcapi class HelperMixin: def helper(self, sample, *extra): new = marshal.loads(marshal.dumps(sample, *extra)) self.assertEqual(sample, new) try: with open(support.TESTFN, "wb") as f: marshal.dump(sample, f, *extra) with open(support.TESTFN, "rb") as f: new = marshal.load(f) self.assertEqual(sample, new) finally: support.unlink(support.TESTFN) class IntTestCase(unittest.TestCase, HelperMixin): def test_ints(self): # Test a range of Python ints larger than the machine word size. n = sys.maxsize ** 2 while n: for expected in (-n, n): self.helper(expected) n = n >> 1 def test_int64(self): # Simulate int marshaling with TYPE_INT64. maxint64 = (1 << 63) - 1 minint64 = -maxint64-1 for base in maxint64, minint64, -maxint64, -(minint64 >> 1): while base: s = b'I' + int.to_bytes(base, 8, 'little', signed=True) got = marshal.loads(s) self.assertEqual(base, got) if base == -1: # a fixed-point for shifting right 1 base = 0 else: base >>= 1 got = marshal.loads(b'I\xfe\xdc\xba\x98\x76\x54\x32\x10') self.assertEqual(got, 0x1032547698badcfe) got = marshal.loads(b'I\x01\x23\x45\x67\x89\xab\xcd\xef') self.assertEqual(got, -0x1032547698badcff) got = marshal.loads(b'I\x08\x19\x2a\x3b\x4c\x5d\x6e\x7f') self.assertEqual(got, 0x7f6e5d4c3b2a1908) got = marshal.loads(b'I\xf7\xe6\xd5\xc4\xb3\xa2\x91\x80') self.assertEqual(got, -0x7f6e5d4c3b2a1909) def test_bool(self): for b in (True, False): self.helper(b) class FloatTestCase(unittest.TestCase, HelperMixin): def test_floats(self): # Test a few floats small = 1e-25 n = sys.maxsize * 3.7e250 while n > small: for expected in (-n, n): self.helper(float(expected)) n /= 123.4567 f = 0.0 s = marshal.dumps(f, 2) got = marshal.loads(s) self.assertEqual(f, got) # and with version <= 1 (floats marshalled differently then) s = marshal.dumps(f, 1) got = marshal.loads(s) self.assertEqual(f, got) n = sys.maxsize * 3.7e-250 while n < small: for expected in (-n, n): f = float(expected) self.helper(f) self.helper(f, 1) n *= 123.4567 class StringTestCase(unittest.TestCase, HelperMixin): def test_unicode(self): for s in ["", "Andr\xe8 Previn", "abc", " "*10000]: self.helper(marshal.loads(marshal.dumps(s))) def test_string(self): for s in ["", "Andr\xe8 Previn", "abc", " "*10000]: self.helper(s) def test_bytes(self): for s in [b"", b"Andr\xe8 Previn", b"abc", b" "*10000]: self.helper(s) class ExceptionTestCase(unittest.TestCase): def test_exceptions(self): new = marshal.loads(marshal.dumps(StopIteration)) self.assertEqual(StopIteration, new) class CodeTestCase(unittest.TestCase): def test_code(self): co = ExceptionTestCase.test_exceptions.__code__ new = marshal.loads(marshal.dumps(co)) self.assertEqual(co, new) def test_many_codeobjects(self): # Issue2957: bad recursion count on code objects count = 5000 # more than MAX_MARSHAL_STACK_DEPTH codes = (ExceptionTestCase.test_exceptions.__code__,) * count marshal.loads(marshal.dumps(codes)) def test_different_filenames(self): co1 = compile("x", "f1", "exec") co2 = compile("y", "f2", "exec") co1, co2 = marshal.loads(marshal.dumps((co1, co2))) self.assertEqual(co1.co_filename, "f1") self.assertEqual(co2.co_filename, "f2") @support.cpython_only def test_same_filename_used(self): s = """def f(): pass\ndef g(): pass""" co = compile(s, "myfile", "exec") co = marshal.loads(marshal.dumps(co)) for obj in co.co_consts: if isinstance(obj, types.CodeType): self.assertIs(co.co_filename, obj.co_filename) class ContainerTestCase(unittest.TestCase, HelperMixin): d = {'astring': '[email protected]', 'afloat': 7283.43, 'anint': 2**20, 'ashortlong': 2, 'alist': ['.zyx.41'], 'atuple': ('.zyx.41',)*10, 'aboolean': False, 'aunicode': "Andr\xe8 Previn" } def test_dict(self): self.helper(self.d) def test_list(self): self.helper(list(self.d.items())) def test_tuple(self): self.helper(tuple(self.d.keys())) def test_sets(self): for constructor in (set, frozenset): self.helper(constructor(self.d.keys())) @support.cpython_only def test_empty_frozenset_singleton(self): # marshal.loads() must reuse the empty frozenset singleton obj = frozenset() obj2 = marshal.loads(marshal.dumps(obj)) self.assertIs(obj2, obj) class BufferTestCase(unittest.TestCase, HelperMixin): def test_bytearray(self): b = bytearray(b"abc") self.helper(b) new = marshal.loads(marshal.dumps(b)) self.assertEqual(type(new), bytes) def test_memoryview(self): b = memoryview(b"abc") self.helper(b) new = marshal.loads(marshal.dumps(b)) self.assertEqual(type(new), bytes) def test_array(self): a = array.array('B', b"abc") new = marshal.loads(marshal.dumps(a)) self.assertEqual(new, b"abc") class BugsTestCase(unittest.TestCase): def test_bug_5888452(self): # Simple-minded check for SF 588452: Debug build crashes marshal.dumps([128] * 1000) def test_patch_873224(self): self.assertRaises(Exception, marshal.loads, b'0') self.assertRaises(Exception, marshal.loads, b'f') self.assertRaises(Exception, marshal.loads, marshal.dumps(2**65)[:-1]) def test_version_argument(self): # Python 2.4.0 crashes for any call to marshal.dumps(x, y) self.assertEqual(marshal.loads(marshal.dumps(5, 0)), 5) self.assertEqual(marshal.loads(marshal.dumps(5, 1)), 5) def test_fuzz(self): # simple test that it's at least not *totally* trivial to # crash from bad marshal data for i in range(256): c = bytes([i]) try: marshal.loads(c) except Exception: pass def test_loads_recursion(self): def run_tests(N, check): # (((...None...),),) check(b')\x01' * N + b'N') check(b'(\x01\x00\x00\x00' * N + b'N') # [[[...None...]]] check(b'[\x01\x00\x00\x00' * N + b'N') # {None: {None: {None: ...None...}}} check(b'{N' * N + b'N' + b'0' * N) # frozenset([frozenset([frozenset([...None...])])]) check(b'>\x01\x00\x00\x00' * N + b'N') # Check that the generated marshal data is valid and marshal.loads() # works for moderately deep nesting run_tests(100, marshal.loads) # Very deeply nested structure shouldn't blow the stack def check(s): self.assertRaises(ValueError, marshal.loads, s) run_tests(2**20, check) def test_recursion_limit(self): # Create a deeply nested structure. head = last = [] # The max stack depth should match the value in Python/marshal.c. if os.name == 'nt' and hasattr(sys, 'gettotalrefcount'): MAX_MARSHAL_STACK_DEPTH = 1000 else: MAX_MARSHAL_STACK_DEPTH = 2000 for i in range(MAX_MARSHAL_STACK_DEPTH - 2): last.append([0]) last = last[-1] # Verify we don't blow out the stack with dumps/load. data = marshal.dumps(head) new_head = marshal.loads(data) # Don't use == to compare objects, it can exceed the recursion limit. self.assertEqual(len(new_head), len(head)) self.assertEqual(len(new_head[0]), len(head[0])) self.assertEqual(len(new_head[-1]), len(head[-1])) last.append([0]) self.assertRaises(ValueError, marshal.dumps, head) def test_exact_type_match(self): # Former bug: # >>> class Int(int): pass # >>> type(loads(dumps(Int()))) # <type 'int'> for typ in (int, float, complex, tuple, list, dict, set, frozenset): # Note: str subclasses are not tested because they get handled # by marshal's routines for objects supporting the buffer API. subtyp = type('subtyp', (typ,), {}) self.assertRaises(ValueError, marshal.dumps, subtyp()) # Issue #1792 introduced a change in how marshal increases the size of its # internal buffer; this test ensures that the new code is exercised. def test_large_marshal(self): size = int(1e6) testString = 'abc' * size marshal.dumps(testString) def test_invalid_longs(self): # Issue #7019: marshal.loads shouldn't produce unnormalized PyLongs invalid_string = b'l\x02\x00\x00\x00\x00\x00\x00\x00' self.assertRaises(ValueError, marshal.loads, invalid_string) def test_multiple_dumps_and_loads(self): # Issue 12291: marshal.load() should be callable multiple times # with interleaved data written by non-marshal code # Adapted from a patch by Engelbert Gruber. data = (1, 'abc', b'def', 1.0, (2, 'a', ['b', b'c'])) for interleaved in (b'', b'0123'): ilen = len(interleaved) positions = [] try: with open(support.TESTFN, 'wb') as f: for d in data: marshal.dump(d, f) if ilen: f.write(interleaved) positions.append(f.tell()) with open(support.TESTFN, 'rb') as f: for i, d in enumerate(data): self.assertEqual(d, marshal.load(f)) if ilen: f.read(ilen) self.assertEqual(positions[i], f.tell()) finally: support.unlink(support.TESTFN) def test_loads_reject_unicode_strings(self): # Issue #14177: marshal.loads() should not accept unicode strings unicode_string = 'T' self.assertRaises(TypeError, marshal.loads, unicode_string) def test_bad_reader(self): class BadReader(io.BytesIO): def readinto(self, buf): n = super().readinto(buf) if n is not None and n > 4: n += 10**6 return n for value in (1.0, 1j, b'0123456789', '0123456789'): self.assertRaises(ValueError, marshal.load, BadReader(marshal.dumps(value))) def test_eof(self): data = marshal.dumps(("hello", "dolly", None)) for i in range(len(data)): self.assertRaises(EOFError, marshal.loads, data[0: i]) LARGE_SIZE = 2**31 pointer_size = 8 if sys.maxsize > 0xFFFFFFFF else 4 class NullWriter: def write(self, s): pass @unittest.skipIf(LARGE_SIZE > sys.maxsize, "test cannot run on 32-bit systems") class LargeValuesTestCase(unittest.TestCase): def check_unmarshallable(self, data): self.assertRaises(ValueError, marshal.dump, data, NullWriter()) @support.bigmemtest(size=LARGE_SIZE, memuse=2, dry_run=False) def test_bytes(self, size): self.check_unmarshallable(b'x' * size) @support.bigmemtest(size=LARGE_SIZE, memuse=2, dry_run=False) def test_str(self, size): self.check_unmarshallable('x' * size) @support.bigmemtest(size=LARGE_SIZE, memuse=pointer_size + 1, dry_run=False) def test_tuple(self, size): self.check_unmarshallable((None,) * size) @support.bigmemtest(size=LARGE_SIZE, memuse=pointer_size + 1, dry_run=False) def test_list(self, size): self.check_unmarshallable([None] * size) @support.bigmemtest(size=LARGE_SIZE, memuse=pointer_size*12 + sys.getsizeof(LARGE_SIZE-1), dry_run=False) def test_set(self, size): self.check_unmarshallable(set(range(size))) @support.bigmemtest(size=LARGE_SIZE, memuse=pointer_size*12 + sys.getsizeof(LARGE_SIZE-1), dry_run=False) def test_frozenset(self, size): self.check_unmarshallable(frozenset(range(size))) @support.bigmemtest(size=LARGE_SIZE, memuse=2, dry_run=False) def test_bytearray(self, size): self.check_unmarshallable(bytearray(size)) def CollectObjectIDs(ids, obj): """Collect object ids seen in a structure""" if id(obj) in ids: return ids.add(id(obj)) if isinstance(obj, (list, tuple, set, frozenset)): for e in obj: CollectObjectIDs(ids, e) elif isinstance(obj, dict): for k, v in obj.items(): CollectObjectIDs(ids, k) CollectObjectIDs(ids, v) return len(ids) class InstancingTestCase(unittest.TestCase, HelperMixin): intobj = 123321 floatobj = 1.2345 strobj = "abcde"*3 dictobj = {"hello":floatobj, "goodbye":floatobj, floatobj:"hello"} def helper3(self, rsample, recursive=False, simple=False): #we have two instances sample = (rsample, rsample) n0 = CollectObjectIDs(set(), sample) s3 = marshal.dumps(sample, 3) n3 = CollectObjectIDs(set(), marshal.loads(s3)) #same number of instances generated self.assertEqual(n3, n0) if not recursive: #can compare with version 2 s2 = marshal.dumps(sample, 2) n2 = CollectObjectIDs(set(), marshal.loads(s2)) #old format generated more instances self.assertGreater(n2, n0) #if complex objects are in there, old format is larger if not simple: self.assertGreater(len(s2), len(s3)) else: self.assertGreaterEqual(len(s2), len(s3)) def testInt(self): self.helper(self.intobj) self.helper3(self.intobj, simple=True) def testFloat(self): self.helper(self.floatobj) self.helper3(self.floatobj) def testStr(self): self.helper(self.strobj) self.helper3(self.strobj) def testDict(self): self.helper(self.dictobj) self.helper3(self.dictobj) def testModule(self): with open(__file__, "rb") as f: code = f.read() if __file__.endswith(".py"): code = compile(code, __file__, "exec") self.helper(code) self.helper3(code) def testRecursion(self): d = dict(self.dictobj) d["self"] = d self.helper3(d, recursive=True) l = [self.dictobj] l.append(l) self.helper3(l, recursive=True) class CompatibilityTestCase(unittest.TestCase): def _test(self, version): with open(__file__, "rb") as f: code = f.read() if __file__.endswith(".py"): code = compile(code, __file__, "exec") data = marshal.dumps(code, version) marshal.loads(data) def test0To3(self): self._test(0) def test1To3(self): self._test(1) def test2To3(self): self._test(2) def test3To3(self): self._test(3) class InterningTestCase(unittest.TestCase, HelperMixin): strobj = "this is an interned string" strobj = sys.intern(strobj) def testIntern(self): s = marshal.loads(marshal.dumps(self.strobj)) self.assertEqual(s, self.strobj) self.assertEqual(id(s), id(self.strobj)) s2 = sys.intern(s) self.assertEqual(id(s2), id(s)) def testNoIntern(self): s = marshal.loads(marshal.dumps(self.strobj, 2)) self.assertEqual(s, self.strobj) self.assertNotEqual(id(s), id(self.strobj)) s2 = sys.intern(s) self.assertNotEqual(id(s2), id(s)) @support.cpython_only @unittest.skipUnless(_testcapi, 'requires _testcapi') class CAPI_TestCase(unittest.TestCase, HelperMixin): def test_write_long_to_file(self): for v in range(marshal.version + 1): _testcapi.pymarshal_write_long_to_file(0x12345678, support.TESTFN, v) with open(support.TESTFN, 'rb') as f: data = f.read() support.unlink(support.TESTFN) self.assertEqual(data, b'\x78\x56\x34\x12') def test_write_object_to_file(self): obj = ('\u20ac', b'abc', 123, 45.6, 7+8j, 'long line '*1000) for v in range(marshal.version + 1): _testcapi.pymarshal_write_object_to_file(obj, support.TESTFN, v) with open(support.TESTFN, 'rb') as f: data = f.read() support.unlink(support.TESTFN) self.assertEqual(marshal.loads(data), obj) def test_read_short_from_file(self): with open(support.TESTFN, 'wb') as f: f.write(b'\x34\x12xxxx') r, p = _testcapi.pymarshal_read_short_from_file(support.TESTFN) support.unlink(support.TESTFN) self.assertEqual(r, 0x1234) self.assertEqual(p, 2) with open(support.TESTFN, 'wb') as f: f.write(b'\x12') with self.assertRaises(EOFError): _testcapi.pymarshal_read_short_from_file(support.TESTFN) support.unlink(support.TESTFN) def test_read_long_from_file(self): with open(support.TESTFN, 'wb') as f: f.write(b'\x78\x56\x34\x12xxxx') r, p = _testcapi.pymarshal_read_long_from_file(support.TESTFN) support.unlink(support.TESTFN) self.assertEqual(r, 0x12345678) self.assertEqual(p, 4) with open(support.TESTFN, 'wb') as f: f.write(b'\x56\x34\x12') with self.assertRaises(EOFError): _testcapi.pymarshal_read_long_from_file(support.TESTFN) support.unlink(support.TESTFN) def test_read_last_object_from_file(self): obj = ('\u20ac', b'abc', 123, 45.6, 7+8j) for v in range(marshal.version + 1): data = marshal.dumps(obj, v) with open(support.TESTFN, 'wb') as f: f.write(data + b'xxxx') r, p = _testcapi.pymarshal_read_last_object_from_file(support.TESTFN) support.unlink(support.TESTFN) self.assertEqual(r, obj) with open(support.TESTFN, 'wb') as f: f.write(data[:1]) with self.assertRaises(EOFError): _testcapi.pymarshal_read_last_object_from_file(support.TESTFN) support.unlink(support.TESTFN) def test_read_object_from_file(self): obj = ('\u20ac', b'abc', 123, 45.6, 7+8j) for v in range(marshal.version + 1): data = marshal.dumps(obj, v) with open(support.TESTFN, 'wb') as f: f.write(data + b'xxxx') r, p = _testcapi.pymarshal_read_object_from_file(support.TESTFN) support.unlink(support.TESTFN) self.assertEqual(r, obj) self.assertEqual(p, len(data)) with open(support.TESTFN, 'wb') as f: f.write(data[:1]) with self.assertRaises(EOFError): _testcapi.pymarshal_read_object_from_file(support.TESTFN) support.unlink(support.TESTFN) if __name__ == "__main__": unittest.main()
19,986
572
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_site.py
"""Tests for 'site'. Tests assume the initial paths in sys.path once the interpreter has begun executing have not been removed. """ import unittest import test.support from test import support from test.support import (captured_stderr, TESTFN, EnvironmentVarGuard, change_cwd) import builtins import os import sys import re import encodings import urllib.request import urllib.error import shutil import subprocess import sysconfig from unittest import mock from copy import copy # These tests are not particularly useful if Python was invoked with -S. # If you add tests that are useful under -S, this skip should be moved # to the class level. if sys.flags.no_site: raise unittest.SkipTest("Python was invoked with -S") import site OLD_SYS_PATH = None def setUpModule(): global OLD_SYS_PATH OLD_SYS_PATH = sys.path[:] if site.ENABLE_USER_SITE and not os.path.isdir(site.USER_SITE): # need to add user site directory for tests try: os.makedirs(site.USER_SITE) # modify sys.path: will be restored by tearDownModule() site.addsitedir(site.USER_SITE) except PermissionError as exc: raise unittest.SkipTest('unable to create user site directory (%r): %s' % (site.USER_SITE, exc)) def tearDownModule(): sys.path[:] = OLD_SYS_PATH class HelperFunctionsTests(unittest.TestCase): """Tests for helper functions. """ def setUp(self): """Save a copy of sys.path""" self.sys_path = sys.path[:] self.old_base = site.USER_BASE self.old_site = site.USER_SITE self.old_prefixes = site.PREFIXES self.original_vars = sysconfig._CONFIG_VARS self.old_vars = copy(sysconfig._CONFIG_VARS) def tearDown(self): """Restore sys.path""" sys.path[:] = self.sys_path site.USER_BASE = self.old_base site.USER_SITE = self.old_site site.PREFIXES = self.old_prefixes sysconfig._CONFIG_VARS = self.original_vars sysconfig._CONFIG_VARS.clear() sysconfig._CONFIG_VARS.update(self.old_vars) def test_makepath(self): # Test makepath() have an absolute path for its first return value # and a case-normalized version of the absolute path for its # second value. path_parts = ("Beginning", "End") original_dir = os.path.join(*path_parts) abs_dir, norm_dir = site.makepath(*path_parts) self.assertEqual(os.path.abspath(original_dir), abs_dir) if original_dir == os.path.normcase(original_dir): self.assertEqual(abs_dir, norm_dir) else: self.assertEqual(os.path.normcase(abs_dir), norm_dir) def test_init_pathinfo(self): dir_set = site._init_pathinfo() for entry in [site.makepath(path)[1] for path in sys.path if path and os.path.exists(path)]: self.assertIn(entry, dir_set, "%s from sys.path not found in set returned " "by _init_pathinfo(): %s" % (entry, dir_set)) @unittest.skipIf(True, "pth files modify import paths, nasty") def pth_file_tests(self, pth_file): """Contain common code for testing results of reading a .pth file""" self.assertIn(pth_file.imported, sys.modules, "%s not in sys.modules" % pth_file.imported) self.assertIn(site.makepath(pth_file.good_dir_path)[0], sys.path) self.assertFalse(os.path.exists(pth_file.bad_dir_path)) def test_addpackage(self): # Make sure addpackage() imports if the line starts with 'import', # adds directories to sys.path for any line in the file that is not a # comment or import that is a valid directory name for where the .pth # file resides; invalid directories are not added pth_file = PthFile() pth_file.cleanup(prep=True) # to make sure that nothing is # pre-existing that shouldn't be try: pth_file.create() site.addpackage(pth_file.base_dir, pth_file.filename, set()) self.pth_file_tests(pth_file) finally: pth_file.cleanup() def make_pth(self, contents, pth_dir='.', pth_name=TESTFN): # Create a .pth file and return its (abspath, basename). pth_dir = os.path.abspath(pth_dir) pth_basename = pth_name + '.pth' pth_fn = os.path.join(pth_dir, pth_basename) pth_file = open(pth_fn, 'w', encoding='utf-8') self.addCleanup(lambda: os.remove(pth_fn)) pth_file.write(contents) pth_file.close() return pth_dir, pth_basename def test_addpackage_import_bad_syntax(self): # Issue 10642 pth_dir, pth_fn = self.make_pth("import bad)syntax\n") with captured_stderr() as err_out: site.addpackage(pth_dir, pth_fn, set()) self.assertRegex(err_out.getvalue(), "line 1") self.assertRegex(err_out.getvalue(), re.escape(os.path.join(pth_dir, pth_fn))) # XXX: the previous two should be independent checks so that the # order doesn't matter. The next three could be a single check # but my regex foo isn't good enough to write it. self.assertRegex(err_out.getvalue(), 'Traceback') self.assertRegex(err_out.getvalue(), r'import bad\)syntax') self.assertRegex(err_out.getvalue(), 'SyntaxError') def test_addpackage_import_bad_exec(self): # Issue 10642 pth_dir, pth_fn = self.make_pth("randompath\nimport nosuchmodule\n") with captured_stderr() as err_out: site.addpackage(pth_dir, pth_fn, set()) self.assertRegex(err_out.getvalue(), "line 2") self.assertRegex(err_out.getvalue(), re.escape(os.path.join(pth_dir, pth_fn))) # XXX: ditto previous XXX comment. self.assertRegex(err_out.getvalue(), 'Traceback') self.assertRegex(err_out.getvalue(), 'ModuleNotFoundError') def test_addpackage_import_bad_pth_file(self): # Issue 5258 pth_dir, pth_fn = self.make_pth("abc\x00def\n") with captured_stderr() as err_out: site.addpackage(pth_dir, pth_fn, set()) self.assertRegex(err_out.getvalue(), "line 1") self.assertRegex(err_out.getvalue(), re.escape(os.path.join(pth_dir, pth_fn))) # XXX: ditto previous XXX comment. self.assertRegex(err_out.getvalue(), 'Traceback') self.assertRegex(err_out.getvalue(), 'ValueError') def test_addsitedir(self): # Same tests for test_addpackage since addsitedir() essentially just # calls addpackage() for every .pth file in the directory pth_file = PthFile() pth_file.cleanup(prep=True) # Make sure that nothing is pre-existing # that is tested for try: pth_file.create() site.addsitedir(pth_file.base_dir, set()) self.pth_file_tests(pth_file) finally: pth_file.cleanup() @unittest.skipUnless(site.ENABLE_USER_SITE, "requires access to PEP 370 " "user-site (site.ENABLE_USER_SITE)") def test_s_option(self): usersite = site.USER_SITE self.assertIn(usersite, sys.path) env = os.environ.copy() rc = subprocess.call([sys.executable, '-c', 'import sys; sys.exit(%r in sys.path)' % usersite], env=env) self.assertEqual(rc, 1) env = os.environ.copy() rc = subprocess.call([sys.executable, '-s', '-c', 'import sys; sys.exit(%r in sys.path)' % usersite], env=env) if usersite == site.getsitepackages()[0]: self.assertEqual(rc, 1) else: self.assertEqual(rc, 0) env = os.environ.copy() env["PYTHONNOUSERSITE"] = "1" rc = subprocess.call([sys.executable, '-c', 'import sys; sys.exit(%r in sys.path)' % usersite], env=env) if usersite == site.getsitepackages()[0]: self.assertEqual(rc, 1) else: self.assertEqual(rc, 0) env = os.environ.copy() env["PYTHONUSERBASE"] = "/tmp" rc = subprocess.call([sys.executable, '-c', 'import sys, site; sys.exit(site.USER_BASE.startswith("/tmp"))'], env=env) self.assertEqual(rc, 1) def test_getuserbase(self): site.USER_BASE = None user_base = site.getuserbase() # the call sets site.USER_BASE self.assertEqual(site.USER_BASE, user_base) # let's set PYTHONUSERBASE and see if it uses it site.USER_BASE = None import sysconfig sysconfig._CONFIG_VARS = None with EnvironmentVarGuard() as environ: environ['PYTHONUSERBASE'] = 'xoxo' self.assertTrue(site.getuserbase().startswith('xoxo'), site.getuserbase()) def test_getusersitepackages(self): site.USER_SITE = None site.USER_BASE = None user_site = site.getusersitepackages() # the call sets USER_BASE *and* USER_SITE self.assertEqual(site.USER_SITE, user_site) self.assertTrue(user_site.startswith(site.USER_BASE), user_site) self.assertEqual(site.USER_BASE, site.getuserbase()) def test_getsitepackages(self): site.PREFIXES = ['xoxo'] dirs = site.getsitepackages() if (sys.platform == "darwin" and sysconfig.get_config_var("PYTHONFRAMEWORK")): # OS X framework builds site.PREFIXES = ['Python.framework'] dirs = site.getsitepackages() self.assertEqual(len(dirs), 2) wanted = os.path.join('/Library', sysconfig.get_config_var("PYTHONFRAMEWORK"), '%d.%d' % sys.version_info[:2], 'site-packages') self.assertEqual(dirs[1], wanted) elif os.sep == '/': # OS X non-framework builds, Linux, FreeBSD, etc self.assertEqual(len(dirs), 1) wanted = os.path.join('xoxo', 'lib', 'python%d.%d' % sys.version_info[:2], 'site-packages') self.assertEqual(dirs[0], wanted) else: # other platforms self.assertEqual(len(dirs), 2) self.assertEqual(dirs[0], 'xoxo') wanted = os.path.join('xoxo', 'lib', 'site-packages') self.assertEqual(dirs[1], wanted) def test_no_home_directory(self): # bpo-10496: getuserbase() and getusersitepackages() must not fail if # the current user has no home directory (if expanduser() returns the # path unchanged). site.USER_SITE = None site.USER_BASE = None sysconfig._CONFIG_VARS = None with EnvironmentVarGuard() as environ, \ mock.patch('os.path.expanduser', lambda path: path): del environ['PYTHONUSERBASE'] del environ['APPDATA'] user_base = site.getuserbase() self.assertTrue(user_base.startswith('~' + os.sep), user_base) user_site = site.getusersitepackages() self.assertTrue(user_site.startswith(user_base), user_site) with mock.patch('os.path.isdir', return_value=False) as mock_isdir, \ mock.patch.object(site, 'addsitedir') as mock_addsitedir, \ support.swap_attr(site, 'ENABLE_USER_SITE', True): # addusersitepackages() must not add user_site to sys.path # if it is not an existing directory known_paths = set() site.addusersitepackages(known_paths) mock_isdir.assert_called_once_with(user_site) mock_addsitedir.assert_not_called() self.assertFalse(known_paths) class PthFile(object): """Helper class for handling testing of .pth files""" def __init__(self, filename_base=TESTFN, imported="time", good_dirname="__testdir__", bad_dirname="__bad"): """Initialize instance variables""" self.filename = filename_base + ".pth" self.base_dir = os.path.abspath('') self.file_path = os.path.join(self.base_dir, self.filename) self.imported = imported self.good_dirname = good_dirname self.bad_dirname = bad_dirname self.good_dir_path = os.path.join(self.base_dir, self.good_dirname) self.bad_dir_path = os.path.join(self.base_dir, self.bad_dirname) def create(self): """Create a .pth file with a comment, blank lines, an ``import <self.imported>``, a line with self.good_dirname, and a line with self.bad_dirname. Creation of the directory for self.good_dir_path (based off of self.good_dirname) is also performed. Make sure to call self.cleanup() to undo anything done by this method. """ FILE = open(self.file_path, 'w') try: print("#import @bad module name", file=FILE) print("\n", file=FILE) print("import %s" % self.imported, file=FILE) print(self.good_dirname, file=FILE) print(self.bad_dirname, file=FILE) finally: FILE.close() os.mkdir(self.good_dir_path) def cleanup(self, prep=False): """Make sure that the .pth file is deleted, self.imported is not in sys.modules, and that both self.good_dirname and self.bad_dirname are not existing directories.""" if os.path.exists(self.file_path): os.remove(self.file_path) if prep: self.imported_module = sys.modules.get(self.imported) if self.imported_module: del sys.modules[self.imported] else: if self.imported_module: sys.modules[self.imported] = self.imported_module if os.path.exists(self.good_dir_path): os.rmdir(self.good_dir_path) if os.path.exists(self.bad_dir_path): os.rmdir(self.bad_dir_path) class ImportSideEffectTests(unittest.TestCase): """Test side-effects from importing 'site'.""" def setUp(self): """Make a copy of sys.path""" self.sys_path = sys.path[:] def tearDown(self): """Restore sys.path""" sys.path[:] = self.sys_path def test_abs_paths(self): # Make sure all imported modules have their __file__ and __cached__ # attributes as absolute paths. Arranging to put the Lib directory on # PYTHONPATH would cause the os module to have a relative path for # __file__ if abs_paths() does not get run. sys and builtins (the # only other modules imported before site.py runs) do not have # __file__ or __cached__ because they are built-in. # abspath stuff clashes with APE ZIP store imports return try: parent = os.path.relpath(os.path.dirname(os.__file__)) cwd = os.getcwd() except ValueError: # Failure to get relpath probably means we need to chdir # to the same drive. cwd, parent = os.path.split(os.path.dirname(os.__file__)) with change_cwd(cwd): env = os.environ.copy() env['PYTHONPATH'] = parent code = ('import os, sys', # use ASCII to avoid locale issues with non-ASCII directories 'os_file = os.__file__.encode("ascii", "backslashreplace")', r'sys.stdout.buffer.write(os_file + b"\n")', 'os_cached = os.__cached__.encode("ascii", "backslashreplace")', r'sys.stdout.buffer.write(os_cached + b"\n")') command = '\n'.join(code) # First, prove that with -S (no 'import site'), the paths are # relative. proc = subprocess.Popen([sys.executable, '-S', '-c', command], env=env, stdout=subprocess.PIPE) stdout, stderr = proc.communicate() self.assertEqual(proc.returncode, 0) os__file__, os__cached__ = stdout.splitlines()[:2] self.assertFalse(os.path.isabs(os__file__)) self.assertFalse(os.path.isabs(os__cached__)) # Now, with 'import site', it works. proc = subprocess.Popen([sys.executable, '-c', command], env=env, stdout=subprocess.PIPE) stdout, stderr = proc.communicate() self.assertEqual(proc.returncode, 0) os__file__, os__cached__ = stdout.splitlines()[:2] self.assertTrue(os.path.isabs(os__file__), "expected absolute path, got {}" .format(os__file__.decode('ascii'))) self.assertTrue(os.path.isabs(os__cached__), "expected absolute path, got {}" .format(os__cached__.decode('ascii'))) def test_no_duplicate_paths(self): # No duplicate paths should exist in sys.path # Handled by removeduppaths() site.removeduppaths() seen_paths = set() for path in sys.path: self.assertNotIn(path, seen_paths) seen_paths.add(path) @unittest.skip('test not implemented') def test_add_build_dir(self): # Test that the build directory's Modules directory is used when it # should be. # XXX: implement pass def test_setting_quit(self): # 'quit' and 'exit' should be injected into builtins self.assertTrue(hasattr(builtins, "quit")) self.assertTrue(hasattr(builtins, "exit")) def test_setting_copyright(self): # 'copyright', 'credits', and 'license' should be in builtins self.assertTrue(hasattr(builtins, "copyright")) self.assertTrue(hasattr(builtins, "credits")) self.assertTrue(hasattr(builtins, "license")) def test_setting_help(self): # 'help' should be set in builtins self.assertTrue(hasattr(builtins, "help")) def test_aliasing_mbcs(self): if sys.platform == "win32": import locale if locale.getdefaultlocale()[1].startswith('cp'): for value in encodings.aliases.aliases.values(): if value == "mbcs": break else: self.fail("did not alias mbcs") def test_sitecustomize_executed(self): # If sitecustomize is available, it should have been imported. if "sitecustomize" not in sys.modules: try: import sitecustomize except ImportError: pass else: self.fail("sitecustomize not imported automatically") @unittest.skipIf(True, "internet not allowed") @test.support.requires_resource('network') @test.support.system_must_validate_cert @unittest.skipUnless(sys.version_info[3] == 'final', 'only for released versions') @unittest.skipUnless(hasattr(urllib.request, "HTTPSHandler"), 'need SSL support to download license') def test_license_exists_at_url(self): # This test is a bit fragile since it depends on the format of the # string displayed by license in the absence of a LICENSE file. url = license._Printer__data.split()[1] req = urllib.request.Request(url, method='HEAD') try: with test.support.transient_internet(url): with urllib.request.urlopen(req) as data: code = data.getcode() except urllib.error.HTTPError as e: code = e.code self.assertEqual(code, 200, msg="Can't find " + url) class StartupImportTests(unittest.TestCase): def test_startup_imports(self): # This tests checks which modules are loaded by Python when it # initially starts upon startup. popen = subprocess.Popen([sys.executable, '-I', '-v', '-c', 'import sys; print(set(sys.modules))'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf-8') stdout, stderr = popen.communicate() modules = eval(stdout) self.assertIn('site', modules) return # interferes with ZIP store # http://bugs.python.org/issue19205 re_mods = {'re', '_sre', 'sre_compile', 'sre_constants', 'sre_parse'} # _osx_support uses the re module in many placs if False and sys.platform != 'darwin': self.assertFalse(modules.intersection(re_mods), stderr) # http://bugs.python.org/issue9548 self.assertNotIn('locale', modules, stderr) if sys.platform != 'darwin': # http://bugs.python.org/issue19209 self.assertNotIn('copyreg', modules, stderr) # http://bugs.python.org/issue19218> collection_mods = {'_collections', 'collections', 'functools', 'heapq', 'itertools', 'keyword', 'operator', 'reprlib', 'types', 'weakref' }.difference(sys.builtin_module_names) # http://bugs.python.org/issue28095 if sys.platform != 'darwin': self.assertFalse(modules.intersection(collection_mods), stderr) def test_startup_interactivehook(self): r = subprocess.Popen([sys.executable, '-c', 'import sys; sys.exit(hasattr(sys, "__interactivehook__"))']).wait() self.assertTrue(r, "'__interactivehook__' not added by site") def test_startup_interactivehook_isolated(self): # issue28192 readline is not automatically enabled in isolated mode r = subprocess.Popen([sys.executable, '-I', '-c', 'import sys; sys.exit(hasattr(sys, "__interactivehook__"))']).wait() self.assertFalse(r, "'__interactivehook__' added in isolated mode") def test_startup_interactivehook_isolated_explicit(self): # issue28192 readline can be explicitly enabled in isolated mode r = subprocess.Popen([sys.executable, '-I', '-c', 'import site, sys; site.enablerlcompleter(); sys.exit(hasattr(sys, "__interactivehook__"))']).wait() self.assertTrue(r, "'__interactivehook__' not added by enablerlcompleter()") @classmethod def _create_underpth_exe(self, lines): exe_file = os.path.join(os.getenv('TEMP'), os.path.split(sys.executable)[1]) shutil.copy(sys.executable, exe_file) _pth_file = os.path.splitext(exe_file)[0] + '._pth' try: with open(_pth_file, 'w') as f: for line in lines: print(line, file=f) return exe_file except: test.support.unlink(_pth_file) test.support.unlink(exe_file) raise @classmethod def _cleanup_underpth_exe(self, exe_file): _pth_file = os.path.splitext(exe_file)[0] + '._pth' test.support.unlink(_pth_file) test.support.unlink(exe_file) @classmethod def _calc_sys_path_for_underpth_nosite(self, sys_prefix, lines): sys_path = [] for line in lines: if not line or line[0] == '#': continue abs_path = os.path.abspath(os.path.join(sys_prefix, line)) sys_path.append(abs_path) return sys_path @unittest.skipUnless(sys.platform == 'win32', "only supported on Windows") def test_underpth_nosite_file(self): libpath = os.path.dirname(os.path.dirname(encodings.__file__)) exe_prefix = os.path.dirname(sys.executable) pth_lines = [ 'fake-path-name', *[libpath for _ in range(200)], '', '# comment', ] exe_file = self._create_underpth_exe(pth_lines) sys_path = self._calc_sys_path_for_underpth_nosite( os.path.dirname(exe_file), pth_lines) try: env = os.environ.copy() env['PYTHONPATH'] = 'from-env' env['PATH'] = '{};{}'.format(exe_prefix, os.getenv('PATH')) rc = subprocess.call([exe_file, '-c', 'import sys; sys.exit(sys.flags.no_site and ' 'len(sys.path) > 200 and ' 'sys.path == %r)' % sys_path, ], env=env) finally: self._cleanup_underpth_exe(exe_file) self.assertTrue(rc, "sys.path is incorrect") @unittest.skipUnless(sys.platform == 'win32', "only supported on Windows") def test_underpth_file(self): libpath = os.path.dirname(os.path.dirname(encodings.__file__)) exe_prefix = os.path.dirname(sys.executable) exe_file = self._create_underpth_exe([ 'fake-path-name', *[libpath for _ in range(200)], '', '# comment', 'import site' ]) sys_prefix = os.path.dirname(exe_file) try: env = os.environ.copy() env['PYTHONPATH'] = 'from-env' env['PATH'] = '{};{}'.format(exe_prefix, os.getenv('PATH')) rc = subprocess.call([exe_file, '-c', 'import sys; sys.exit(not sys.flags.no_site and ' '%r in sys.path and %r in sys.path and %r not in sys.path and ' 'all("\\r" not in p and "\\n" not in p for p in sys.path))' % ( os.path.join(sys_prefix, 'fake-path-name'), libpath, os.path.join(sys_prefix, 'from-env'), )], env=env) finally: self._cleanup_underpth_exe(exe_file) self.assertTrue(rc, "sys.path is incorrect") if __name__ == "__main__": unittest.main()
26,162
648
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_typing.py
import contextlib import collections import pickle import re import sys from unittest import TestCase, main, skipUnless, SkipTest, expectedFailure from copy import copy, deepcopy from typing import Any, NoReturn from typing import TypeVar, AnyStr from typing import T, KT, VT # Not in __all__. from typing import Union, Optional from typing import Tuple, List, MutableMapping from typing import Callable from typing import Generic, ClassVar, GenericMeta from typing import cast from typing import get_type_hints from typing import no_type_check, no_type_check_decorator from typing import Type from typing import NewType from typing import NamedTuple from typing import IO, TextIO, BinaryIO from typing import Pattern, Match import abc import typing import weakref try: import collections.abc as collections_abc except ImportError: import collections as collections_abc # Fallback for PY3.2. if __name__ == 'PYOBJ.COM': import test.ann_module import test.ann_module2 import test.ann_module3 try: import mod_generics_cache except ImportError: # try to use the builtin one, Python 3.5+ from test import mod_generics_cache PY36 = sys.version_info[:2] >= (3, 6) class BaseTestCase(TestCase): def assertIsSubclass(self, cls, class_or_tuple, msg=None): if not issubclass(cls, class_or_tuple): message = '%r is not a subclass of %r' % (cls, class_or_tuple) if msg is not None: message += ' : %s' % msg raise self.failureException(message) def assertNotIsSubclass(self, cls, class_or_tuple, msg=None): if issubclass(cls, class_or_tuple): message = '%r is a subclass of %r' % (cls, class_or_tuple) if msg is not None: message += ' : %s' % msg raise self.failureException(message) def clear_caches(self): for f in typing._cleanups: f() class Employee: pass class Manager(Employee): pass class Founder(Employee): pass class ManagingFounder(Manager, Founder): pass class AnyTests(BaseTestCase): def test_any_instance_type_error(self): with self.assertRaises(TypeError): isinstance(42, Any) def test_any_subclass_type_error(self): with self.assertRaises(TypeError): issubclass(Employee, Any) with self.assertRaises(TypeError): issubclass(Any, Employee) def test_repr(self): self.assertEqual(repr(Any), 'typing.Any') def test_errors(self): with self.assertRaises(TypeError): issubclass(42, Any) with self.assertRaises(TypeError): Any[int] # Any is not a generic type. def test_cannot_subclass(self): with self.assertRaises(TypeError): class A(Any): pass with self.assertRaises(TypeError): class A(type(Any)): pass def test_cannot_instantiate(self): with self.assertRaises(TypeError): Any() with self.assertRaises(TypeError): type(Any)() def test_any_works_with_alias(self): # These expressions must simply not fail. typing.Match[Any] typing.Pattern[Any] typing.IO[Any] class NoReturnTests(BaseTestCase): def test_noreturn_instance_type_error(self): with self.assertRaises(TypeError): isinstance(42, NoReturn) def test_noreturn_subclass_type_error(self): with self.assertRaises(TypeError): issubclass(Employee, NoReturn) with self.assertRaises(TypeError): issubclass(NoReturn, Employee) def test_repr(self): self.assertEqual(repr(NoReturn), 'typing.NoReturn') def test_not_generic(self): with self.assertRaises(TypeError): NoReturn[int] def test_cannot_subclass(self): with self.assertRaises(TypeError): class A(NoReturn): pass with self.assertRaises(TypeError): class A(type(NoReturn)): pass def test_cannot_instantiate(self): with self.assertRaises(TypeError): NoReturn() with self.assertRaises(TypeError): type(NoReturn)() class TypeVarTests(BaseTestCase): def test_basic_plain(self): T = TypeVar('T') # T equals itself. self.assertEqual(T, T) # T is an instance of TypeVar self.assertIsInstance(T, TypeVar) def test_typevar_instance_type_error(self): T = TypeVar('T') with self.assertRaises(TypeError): isinstance(42, T) def test_typevar_subclass_type_error(self): T = TypeVar('T') with self.assertRaises(TypeError): issubclass(int, T) with self.assertRaises(TypeError): issubclass(T, int) def test_constrained_error(self): with self.assertRaises(TypeError): X = TypeVar('X', int) X def test_union_unique(self): X = TypeVar('X') Y = TypeVar('Y') self.assertNotEqual(X, Y) self.assertEqual(Union[X], X) self.assertNotEqual(Union[X], Union[X, Y]) self.assertEqual(Union[X, X], X) self.assertNotEqual(Union[X, int], Union[X]) self.assertNotEqual(Union[X, int], Union[int]) self.assertEqual(Union[X, int].__args__, (X, int)) self.assertEqual(Union[X, int].__parameters__, (X,)) self.assertIs(Union[X, int].__origin__, Union) def test_union_constrained(self): A = TypeVar('A', str, bytes) self.assertNotEqual(Union[A, str], Union[A]) def test_repr(self): self.assertEqual(repr(T), '~T') self.assertEqual(repr(KT), '~KT') self.assertEqual(repr(VT), '~VT') self.assertEqual(repr(AnyStr), '~AnyStr') T_co = TypeVar('T_co', covariant=True) self.assertEqual(repr(T_co), '+T_co') T_contra = TypeVar('T_contra', contravariant=True) self.assertEqual(repr(T_contra), '-T_contra') def test_no_redefinition(self): self.assertNotEqual(TypeVar('T'), TypeVar('T')) self.assertNotEqual(TypeVar('T', int, str), TypeVar('T', int, str)) def test_cannot_subclass_vars(self): with self.assertRaises(TypeError): class V(TypeVar('T')): pass def test_cannot_subclass_var_itself(self): with self.assertRaises(TypeError): class V(TypeVar): pass def test_cannot_instantiate_vars(self): with self.assertRaises(TypeError): TypeVar('A')() def test_bound_errors(self): with self.assertRaises(TypeError): TypeVar('X', bound=42) with self.assertRaises(TypeError): TypeVar('X', str, float, bound=Employee) def test_no_bivariant(self): with self.assertRaises(ValueError): TypeVar('T', covariant=True, contravariant=True) class UnionTests(BaseTestCase): def test_basics(self): u = Union[int, float] self.assertNotEqual(u, Union) def test_subclass_error(self): with self.assertRaises(TypeError): issubclass(int, Union) with self.assertRaises(TypeError): issubclass(Union, int) with self.assertRaises(TypeError): issubclass(int, Union[int, str]) with self.assertRaises(TypeError): issubclass(Union[int, str], int) def test_union_any(self): u = Union[Any] self.assertEqual(u, Any) u1 = Union[int, Any] u2 = Union[Any, int] u3 = Union[Any, object] self.assertEqual(u1, u2) self.assertNotEqual(u1, Any) self.assertNotEqual(u2, Any) self.assertNotEqual(u3, Any) def test_union_object(self): u = Union[object] self.assertEqual(u, object) u = Union[int, object] self.assertEqual(u, object) u = Union[object, int] self.assertEqual(u, object) def test_unordered(self): u1 = Union[int, float] u2 = Union[float, int] self.assertEqual(u1, u2) def test_single_class_disappears(self): t = Union[Employee] self.assertIs(t, Employee) def test_base_class_disappears(self): u = Union[Employee, Manager, int] self.assertEqual(u, Union[int, Employee]) u = Union[Manager, int, Employee] self.assertEqual(u, Union[int, Employee]) u = Union[Employee, Manager] self.assertIs(u, Employee) def test_union_union(self): u = Union[int, float] v = Union[u, Employee] self.assertEqual(v, Union[int, float, Employee]) def test_repr(self): self.assertEqual(repr(Union), 'typing.Union') u = Union[Employee, int] self.assertEqual(repr(u), 'typing.Union[%s.Employee, int]' % __name__) u = Union[int, Employee] self.assertEqual(repr(u), 'typing.Union[int, %s.Employee]' % __name__) T = TypeVar('T') u = Union[T, int][int] self.assertEqual(repr(u), repr(int)) u = Union[List[int], int] self.assertEqual(repr(u), 'typing.Union[typing.List[int], int]') def test_cannot_subclass(self): with self.assertRaises(TypeError): class C(Union): pass with self.assertRaises(TypeError): class C(type(Union)): pass with self.assertRaises(TypeError): class C(Union[int, str]): pass def test_cannot_instantiate(self): with self.assertRaises(TypeError): Union() with self.assertRaises(TypeError): type(Union)() u = Union[int, float] with self.assertRaises(TypeError): u() with self.assertRaises(TypeError): type(u)() def test_union_generalization(self): self.assertFalse(Union[str, typing.Iterable[int]] == str) self.assertFalse(Union[str, typing.Iterable[int]] == typing.Iterable[int]) self.assertTrue(Union[str, typing.Iterable] == typing.Iterable) def test_union_compare_other(self): self.assertNotEqual(Union, object) self.assertNotEqual(Union, Any) self.assertNotEqual(ClassVar, Union) self.assertNotEqual(Optional, Union) self.assertNotEqual([None], Optional) self.assertNotEqual(Optional, typing.Mapping) self.assertNotEqual(Optional[typing.MutableMapping], Union) def test_optional(self): o = Optional[int] u = Union[int, None] self.assertEqual(o, u) def test_empty(self): with self.assertRaises(TypeError): Union[()] def test_union_instance_type_error(self): with self.assertRaises(TypeError): isinstance(42, Union[int, str]) def test_no_eval_union(self): u = Union[int, str] def f(x: u): ... self.assertIs(get_type_hints(f)['x'], u) def test_function_repr_union(self): def fun() -> int: ... self.assertEqual(repr(Union[fun, int]), 'typing.Union[fun, int]') def test_union_str_pattern(self): # Shouldn't crash; see http://bugs.python.org/issue25390 A = Union[str, Pattern] A def test_etree(self): # See https://github.com/python/typing/issues/229 # (Only relevant for Python 2.) try: from xml.etree.cElementTree import Element except ImportError: raise SkipTest("cElementTree not found") Union[Element, str] # Shouldn't crash def Elem(*args): return Element(*args) Union[Elem, str] # Nor should this class TupleTests(BaseTestCase): def test_basics(self): with self.assertRaises(TypeError): issubclass(Tuple, Tuple[int, str]) with self.assertRaises(TypeError): issubclass(tuple, Tuple[int, str]) class TP(tuple): ... self.assertTrue(issubclass(tuple, Tuple)) self.assertTrue(issubclass(TP, Tuple)) def test_equality(self): self.assertEqual(Tuple[int], Tuple[int]) self.assertEqual(Tuple[int, ...], Tuple[int, ...]) self.assertNotEqual(Tuple[int], Tuple[int, int]) self.assertNotEqual(Tuple[int], Tuple[int, ...]) def test_tuple_subclass(self): class MyTuple(tuple): pass self.assertTrue(issubclass(MyTuple, Tuple)) def test_tuple_instance_type_error(self): with self.assertRaises(TypeError): isinstance((0, 0), Tuple[int, int]) self.assertIsInstance((0, 0), Tuple) def test_repr(self): self.assertEqual(repr(Tuple), 'typing.Tuple') self.assertEqual(repr(Tuple[()]), 'typing.Tuple[()]') self.assertEqual(repr(Tuple[int, float]), 'typing.Tuple[int, float]') self.assertEqual(repr(Tuple[int, ...]), 'typing.Tuple[int, ...]') def test_errors(self): with self.assertRaises(TypeError): issubclass(42, Tuple) with self.assertRaises(TypeError): issubclass(42, Tuple[int]) class CallableTests(BaseTestCase): def test_self_subclass(self): with self.assertRaises(TypeError): self.assertTrue(issubclass(type(lambda x: x), Callable[[int], int])) self.assertTrue(issubclass(type(lambda x: x), Callable)) def test_eq_hash(self): self.assertEqual(Callable[[int], int], Callable[[int], int]) self.assertEqual(len({Callable[[int], int], Callable[[int], int]}), 1) self.assertNotEqual(Callable[[int], int], Callable[[int], str]) self.assertNotEqual(Callable[[int], int], Callable[[str], int]) self.assertNotEqual(Callable[[int], int], Callable[[int, int], int]) self.assertNotEqual(Callable[[int], int], Callable[[], int]) self.assertNotEqual(Callable[[int], int], Callable) def test_cannot_instantiate(self): with self.assertRaises(TypeError): Callable() with self.assertRaises(TypeError): type(Callable)() c = Callable[[int], str] with self.assertRaises(TypeError): c() with self.assertRaises(TypeError): type(c)() def test_callable_wrong_forms(self): with self.assertRaises(TypeError): Callable[[...], int] with self.assertRaises(TypeError): Callable[(), int] with self.assertRaises(TypeError): Callable[[()], int] with self.assertRaises(TypeError): Callable[[int, 1], 2] with self.assertRaises(TypeError): Callable[int] def test_callable_instance_works(self): def f(): pass self.assertIsInstance(f, Callable) self.assertNotIsInstance(None, Callable) def test_callable_instance_type_error(self): def f(): pass with self.assertRaises(TypeError): self.assertIsInstance(f, Callable[[], None]) with self.assertRaises(TypeError): self.assertIsInstance(f, Callable[[], Any]) with self.assertRaises(TypeError): self.assertNotIsInstance(None, Callable[[], None]) with self.assertRaises(TypeError): self.assertNotIsInstance(None, Callable[[], Any]) def test_repr(self): ct0 = Callable[[], bool] self.assertEqual(repr(ct0), 'typing.Callable[[], bool]') ct2 = Callable[[str, float], int] self.assertEqual(repr(ct2), 'typing.Callable[[str, float], int]') ctv = Callable[..., str] self.assertEqual(repr(ctv), 'typing.Callable[..., str]') def test_callable_with_ellipsis(self): def foo(a: Callable[..., T]): pass self.assertEqual(get_type_hints(foo, globals(), locals()), {'a': Callable[..., T]}) def test_ellipsis_in_generic(self): # Shouldn't crash; see https://github.com/python/typing/issues/259 typing.List[Callable[..., str]] XK = TypeVar('XK', str, bytes) XV = TypeVar('XV') class SimpleMapping(Generic[XK, XV]): def __getitem__(self, key: XK) -> XV: ... def __setitem__(self, key: XK, value: XV): ... def get(self, key: XK, default: XV = None) -> XV: ... class MySimpleMapping(SimpleMapping[XK, XV]): def __init__(self): self.store = {} def __getitem__(self, key: str): return self.store[key] def __setitem__(self, key: str, value): self.store[key] = value def get(self, key: str, default=None): try: return self.store[key] except KeyError: return default class ProtocolTests(BaseTestCase): def test_supports_int(self): self.assertIsSubclass(int, typing.SupportsInt) self.assertNotIsSubclass(str, typing.SupportsInt) def test_supports_float(self): self.assertIsSubclass(float, typing.SupportsFloat) self.assertNotIsSubclass(str, typing.SupportsFloat) def test_supports_complex(self): # Note: complex itself doesn't have __complex__. class C: def __complex__(self): return 0j self.assertIsSubclass(C, typing.SupportsComplex) self.assertNotIsSubclass(str, typing.SupportsComplex) def test_supports_bytes(self): # Note: bytes itself doesn't have __bytes__. class B: def __bytes__(self): return b'' self.assertIsSubclass(B, typing.SupportsBytes) self.assertNotIsSubclass(str, typing.SupportsBytes) def test_supports_abs(self): self.assertIsSubclass(float, typing.SupportsAbs) self.assertIsSubclass(int, typing.SupportsAbs) self.assertNotIsSubclass(str, typing.SupportsAbs) def test_supports_round(self): issubclass(float, typing.SupportsRound) self.assertIsSubclass(float, typing.SupportsRound) self.assertIsSubclass(int, typing.SupportsRound) self.assertNotIsSubclass(str, typing.SupportsRound) def test_reversible(self): self.assertIsSubclass(list, typing.Reversible) self.assertNotIsSubclass(int, typing.Reversible) def test_protocol_instance_type_error(self): with self.assertRaises(TypeError): isinstance(0, typing.SupportsAbs) class C1(typing.SupportsInt): def __int__(self) -> int: return 42 class C2(C1): pass c = C2() self.assertIsInstance(c, C1) class GenericTests(BaseTestCase): def test_basics(self): X = SimpleMapping[str, Any] self.assertEqual(X.__parameters__, ()) with self.assertRaises(TypeError): X[str] with self.assertRaises(TypeError): X[str, str] Y = SimpleMapping[XK, str] self.assertEqual(Y.__parameters__, (XK,)) Y[str] with self.assertRaises(TypeError): Y[str, str] self.assertIsSubclass(SimpleMapping[str, int], SimpleMapping) def test_generic_errors(self): T = TypeVar('T') S = TypeVar('S') with self.assertRaises(TypeError): Generic[T]() with self.assertRaises(TypeError): Generic[T][T] with self.assertRaises(TypeError): Generic[T][S] with self.assertRaises(TypeError): isinstance([], List[int]) with self.assertRaises(TypeError): issubclass(list, List[int]) with self.assertRaises(TypeError): class NewGeneric(Generic): ... with self.assertRaises(TypeError): class MyGeneric(Generic[T], Generic[S]): ... with self.assertRaises(TypeError): class MyGeneric(List[T], Generic[S]): ... def test_init(self): T = TypeVar('T') S = TypeVar('S') with self.assertRaises(TypeError): Generic[T, T] with self.assertRaises(TypeError): Generic[T, S, T] @skipUnless(PY36, "__init_subclass__ support required") def test_init_subclass(self): class X(typing.Generic[T]): def __init_subclass__(cls, **kwargs): super().__init_subclass__(**kwargs) cls.attr = 42 class Y(X): pass self.assertEqual(Y.attr, 42) with self.assertRaises(AttributeError): X.attr X.attr = 1 Y.attr = 2 class Z(Y): pass class W(X[int]): pass self.assertEqual(Y.attr, 2) self.assertEqual(Z.attr, 42) self.assertEqual(W.attr, 42) def test_repr(self): self.assertEqual(repr(SimpleMapping), __name__ + '.' + 'SimpleMapping') self.assertEqual(repr(MySimpleMapping), __name__ + '.' + 'MySimpleMapping') def test_chain_repr(self): T = TypeVar('T') S = TypeVar('S') class C(Generic[T]): pass X = C[Tuple[S, T]] self.assertEqual(X, C[Tuple[S, T]]) self.assertNotEqual(X, C[Tuple[T, S]]) Y = X[T, int] self.assertEqual(Y, X[T, int]) self.assertNotEqual(Y, X[S, int]) self.assertNotEqual(Y, X[T, str]) Z = Y[str] self.assertEqual(Z, Y[str]) self.assertNotEqual(Z, Y[int]) self.assertNotEqual(Z, Y[T]) self.assertTrue(str(Z).endswith( '.C[typing.Tuple[str, int]]')) def test_new_repr(self): T = TypeVar('T') U = TypeVar('U', covariant=True) S = TypeVar('S') self.assertEqual(repr(List), 'typing.List') self.assertEqual(repr(List[T]), 'typing.List[~T]') self.assertEqual(repr(List[U]), 'typing.List[+U]') self.assertEqual(repr(List[S][T][int]), 'typing.List[int]') self.assertEqual(repr(List[int]), 'typing.List[int]') def test_new_repr_complex(self): T = TypeVar('T') TS = TypeVar('TS') self.assertEqual(repr(typing.Mapping[T, TS][TS, T]), 'typing.Mapping[~TS, ~T]') self.assertEqual(repr(List[Tuple[T, TS]][int, T]), 'typing.List[typing.Tuple[int, ~T]]') self.assertEqual( repr(List[Tuple[T, T]][List[int]]), 'typing.List[typing.Tuple[typing.List[int], typing.List[int]]]' ) def test_new_repr_bare(self): T = TypeVar('T') self.assertEqual(repr(Generic[T]), 'typing.Generic[~T]') self.assertEqual(repr(typing._Protocol[T]), 'typing.Protocol[~T]') class C(typing.Dict[Any, Any]): ... # this line should just work repr(C.__mro__) def test_dict(self): T = TypeVar('T') class B(Generic[T]): pass b = B() b.foo = 42 self.assertEqual(b.__dict__, {'foo': 42}) class C(B[int]): pass c = C() c.bar = 'abc' self.assertEqual(c.__dict__, {'bar': 'abc'}) def test_subscripted_generics_as_proxies(self): T = TypeVar('T') class C(Generic[T]): x = 'def' self.assertEqual(C[int].x, 'def') self.assertEqual(C[C[int]].x, 'def') C[C[int]].x = 'changed' self.assertEqual(C.x, 'changed') self.assertEqual(C[str].x, 'changed') C[List[str]].z = 'new' self.assertEqual(C.z, 'new') self.assertEqual(C[Tuple[int]].z, 'new') self.assertEqual(C().x, 'changed') self.assertEqual(C[Tuple[str]]().z, 'new') class D(C[T]): pass self.assertEqual(D[int].x, 'changed') self.assertEqual(D.z, 'new') D.z = 'from derived z' D[int].x = 'from derived x' self.assertEqual(C.x, 'changed') self.assertEqual(C[int].z, 'new') self.assertEqual(D.x, 'from derived x') self.assertEqual(D[str].z, 'from derived z') def test_abc_registry_kept(self): T = TypeVar('T') class C(Generic[T]): ... C.register(int) self.assertIsInstance(1, C) C[int] self.assertIsInstance(1, C) def test_false_subclasses(self): class MyMapping(MutableMapping[str, str]): pass self.assertNotIsInstance({}, MyMapping) self.assertNotIsSubclass(dict, MyMapping) def test_abc_bases(self): class MM(MutableMapping[str, str]): def __getitem__(self, k): return None def __setitem__(self, k, v): pass def __delitem__(self, k): pass def __iter__(self): return iter(()) def __len__(self): return 0 # this should just work MM().update() self.assertIsInstance(MM(), collections_abc.MutableMapping) self.assertIsInstance(MM(), MutableMapping) self.assertNotIsInstance(MM(), List) self.assertNotIsInstance({}, MM) def test_multiple_bases(self): class MM1(MutableMapping[str, str], collections_abc.MutableMapping): pass with self.assertRaises(TypeError): # consistent MRO not possible class MM2(collections_abc.MutableMapping, MutableMapping[str, str]): pass def test_orig_bases(self): T = TypeVar('T') class C(typing.Dict[str, T]): ... self.assertEqual(C.__orig_bases__, (typing.Dict[str, T],)) def test_naive_runtime_checks(self): def naive_dict_check(obj, tp): # Check if a dictionary conforms to Dict type if len(tp.__parameters__) > 0: raise NotImplementedError if tp.__args__: KT, VT = tp.__args__ return all( isinstance(k, KT) and isinstance(v, VT) for k, v in obj.items() ) self.assertTrue(naive_dict_check({'x': 1}, typing.Dict[str, int])) self.assertFalse(naive_dict_check({1: 'x'}, typing.Dict[str, int])) with self.assertRaises(NotImplementedError): naive_dict_check({1: 'x'}, typing.Dict[str, T]) def naive_generic_check(obj, tp): # Check if an instance conforms to the generic class if not hasattr(obj, '__orig_class__'): raise NotImplementedError return obj.__orig_class__ == tp class Node(Generic[T]): ... self.assertTrue(naive_generic_check(Node[int](), Node[int])) self.assertFalse(naive_generic_check(Node[str](), Node[int])) self.assertFalse(naive_generic_check(Node[str](), List)) with self.assertRaises(NotImplementedError): naive_generic_check([1, 2, 3], Node[int]) def naive_list_base_check(obj, tp): # Check if list conforms to a List subclass return all(isinstance(x, tp.__orig_bases__[0].__args__[0]) for x in obj) class C(List[int]): ... self.assertTrue(naive_list_base_check([1, 2, 3], C)) self.assertFalse(naive_list_base_check(['a', 'b'], C)) def test_multi_subscr_base(self): T = TypeVar('T') U = TypeVar('U') V = TypeVar('V') class C(List[T][U][V]): ... class D(C, List[T][U][V]): ... self.assertEqual(C.__parameters__, (V,)) self.assertEqual(D.__parameters__, (V,)) self.assertEqual(C[int].__parameters__, ()) self.assertEqual(D[int].__parameters__, ()) self.assertEqual(C[int].__args__, (int,)) self.assertEqual(D[int].__args__, (int,)) self.assertEqual(C.__bases__, (List,)) self.assertEqual(D.__bases__, (C, List)) self.assertEqual(C.__orig_bases__, (List[T][U][V],)) self.assertEqual(D.__orig_bases__, (C, List[T][U][V])) def test_subscript_meta(self): T = TypeVar('T') self.assertEqual(Type[GenericMeta], Type[GenericMeta]) self.assertEqual(Union[T, int][GenericMeta], Union[GenericMeta, int]) self.assertEqual(Callable[..., GenericMeta].__args__, (Ellipsis, GenericMeta)) def test_generic_hashes(self): class A(Generic[T]): ... class B(Generic[T]): class A(Generic[T]): ... self.assertEqual(A, A) self.assertEqual(mod_generics_cache.A[str], mod_generics_cache.A[str]) self.assertEqual(B.A, B.A) self.assertEqual(mod_generics_cache.B.A[B.A[str]], mod_generics_cache.B.A[B.A[str]]) self.assertNotEqual(A, B.A) self.assertNotEqual(A, mod_generics_cache.A) self.assertNotEqual(A, mod_generics_cache.B.A) self.assertNotEqual(B.A, mod_generics_cache.A) self.assertNotEqual(B.A, mod_generics_cache.B.A) self.assertNotEqual(A[str], B.A[str]) self.assertNotEqual(A[List[Any]], B.A[List[Any]]) self.assertNotEqual(A[str], mod_generics_cache.A[str]) self.assertNotEqual(A[str], mod_generics_cache.B.A[str]) self.assertNotEqual(B.A[int], mod_generics_cache.A[int]) self.assertNotEqual(B.A[List[Any]], mod_generics_cache.B.A[List[Any]]) self.assertNotEqual(Tuple[A[str]], Tuple[B.A[str]]) self.assertNotEqual(Tuple[A[List[Any]]], Tuple[B.A[List[Any]]]) self.assertNotEqual(Union[str, A[str]], Union[str, mod_generics_cache.A[str]]) self.assertNotEqual(Union[A[str], A[str]], Union[A[str], mod_generics_cache.A[str]]) self.assertNotEqual(typing.FrozenSet[A[str]], typing.FrozenSet[mod_generics_cache.B.A[str]]) if sys.version_info[:2] > (3, 2): self.assertTrue(repr(Tuple[A[str]]).endswith('<locals>.A[str]]')) self.assertTrue(repr(Tuple[B.A[str]]).endswith('<locals>.B.A[str]]')) self.assertTrue(repr(Tuple[mod_generics_cache.A[str]]) .endswith('mod_generics_cache.A[str]]')) self.assertTrue(repr(Tuple[mod_generics_cache.B.A[str]]) .endswith('mod_generics_cache.B.A[str]]')) def test_extended_generic_rules_eq(self): T = TypeVar('T') U = TypeVar('U') self.assertEqual(Tuple[T, T][int], Tuple[int, int]) self.assertEqual(typing.Iterable[Tuple[T, T]][T], typing.Iterable[Tuple[T, T]]) with self.assertRaises(TypeError): Tuple[T, int][()] with self.assertRaises(TypeError): Tuple[T, U][T, ...] self.assertEqual(Union[T, int][int], int) self.assertEqual(Union[T, U][int, Union[int, str]], Union[int, str]) class Base: ... class Derived(Base): ... self.assertEqual(Union[T, Base][Derived], Base) with self.assertRaises(TypeError): Union[T, int][1] self.assertEqual(Callable[[T], T][KT], Callable[[KT], KT]) self.assertEqual(Callable[..., List[T]][int], Callable[..., List[int]]) with self.assertRaises(TypeError): Callable[[T], U][..., int] with self.assertRaises(TypeError): Callable[[T], U][[], int] def test_extended_generic_rules_repr(self): T = TypeVar('T') self.assertEqual(repr(Union[Tuple, Callable]).replace('typing.', ''), 'Union[Tuple, Callable]') self.assertEqual(repr(Union[Tuple, Tuple[int]]).replace('typing.', ''), 'Tuple') self.assertEqual(repr(Callable[..., Optional[T]][int]).replace('typing.', ''), 'Callable[..., Union[int, NoneType]]') self.assertEqual(repr(Callable[[], List[T]][int]).replace('typing.', ''), 'Callable[[], List[int]]') def test_generic_forward_ref(self): def foobar(x: List[List['CC']]): ... class CC: ... self.assertEqual( get_type_hints(foobar, globals(), locals()), {'x': List[List[CC]]} ) T = TypeVar('T') AT = Tuple[T, ...] def barfoo(x: AT): ... self.assertIs(get_type_hints(barfoo, globals(), locals())['x'], AT) CT = Callable[..., List[T]] def barfoo2(x: CT): ... self.assertIs(get_type_hints(barfoo2, globals(), locals())['x'], CT) def test_extended_generic_rules_subclassing(self): class T1(Tuple[T, KT]): ... class T2(Tuple[T, ...]): ... class C1(Callable[[T], T]): ... class C2(Callable[..., int]): def __call__(self): return None self.assertEqual(T1.__parameters__, (T, KT)) self.assertEqual(T1[int, str].__args__, (int, str)) self.assertEqual(T1[int, T].__origin__, T1) self.assertEqual(T2.__parameters__, (T,)) with self.assertRaises(TypeError): T1[int] with self.assertRaises(TypeError): T2[int, str] self.assertEqual(repr(C1[int]).split('.')[-1], 'C1[int]') self.assertEqual(C2.__parameters__, ()) self.assertIsInstance(C2(), collections_abc.Callable) self.assertIsSubclass(C2, collections_abc.Callable) self.assertIsSubclass(C1, collections_abc.Callable) self.assertIsInstance(T1(), tuple) self.assertIsSubclass(T2, tuple) self.assertIsSubclass(Tuple[int, ...], typing.Sequence) self.assertIsSubclass(Tuple[int, ...], typing.Iterable) def test_fail_with_bare_union(self): with self.assertRaises(TypeError): List[Union] with self.assertRaises(TypeError): Tuple[Optional] with self.assertRaises(TypeError): ClassVar[ClassVar] with self.assertRaises(TypeError): List[ClassVar[int]] def test_fail_with_bare_generic(self): T = TypeVar('T') with self.assertRaises(TypeError): List[Generic] with self.assertRaises(TypeError): Tuple[Generic[T]] with self.assertRaises(TypeError): List[typing._Protocol] with self.assertRaises(TypeError): isinstance(1, Generic) def test_type_erasure_special(self): T = TypeVar('T') # this is the only test that checks type caching self.clear_caches() class MyTup(Tuple[T, T]): ... self.assertIs(MyTup[int]().__class__, MyTup) self.assertIs(MyTup[int]().__orig_class__, MyTup[int]) class MyCall(Callable[..., T]): def __call__(self): return None self.assertIs(MyCall[T]().__class__, MyCall) self.assertIs(MyCall[T]().__orig_class__, MyCall[T]) class MyDict(typing.Dict[T, T]): ... self.assertIs(MyDict[int]().__class__, MyDict) self.assertIs(MyDict[int]().__orig_class__, MyDict[int]) class MyDef(typing.DefaultDict[str, T]): ... self.assertIs(MyDef[int]().__class__, MyDef) self.assertIs(MyDef[int]().__orig_class__, MyDef[int]) # ChainMap was added in 3.3 if sys.version_info >= (3, 3): class MyChain(typing.ChainMap[str, T]): ... self.assertIs(MyChain[int]().__class__, MyChain) self.assertIs(MyChain[int]().__orig_class__, MyChain[int]) def test_all_repr_eq_any(self): objs = (getattr(typing, el) for el in typing.__all__) for obj in objs: self.assertNotEqual(repr(obj), '') self.assertEqual(obj, obj) if getattr(obj, '__parameters__', None) and len(obj.__parameters__) == 1: self.assertEqual(obj[Any].__args__, (Any,)) if isinstance(obj, type): for base in obj.__mro__: self.assertNotEqual(repr(base), '') self.assertEqual(base, base) def test_substitution_helper(self): T = TypeVar('T') KT = TypeVar('KT') VT = TypeVar('VT') class Map(Generic[KT, VT]): def meth(self, k: KT, v: VT): ... StrMap = Map[str, T] obj = StrMap[int]() new_args = typing._subs_tree(obj.__orig_class__) new_annots = {k: typing._replace_arg(v, type(obj).__parameters__, new_args) for k, v in obj.meth.__annotations__.items()} self.assertEqual(new_annots, {'k': str, 'v': int}) def test_pickle(self): global C # pickle wants to reference the class by name T = TypeVar('T') class B(Generic[T]): pass class C(B[int]): pass c = C() c.foo = 42 c.bar = 'abc' for proto in range(pickle.HIGHEST_PROTOCOL + 1): z = pickle.dumps(c, proto) x = pickle.loads(z) self.assertEqual(x.foo, 42) self.assertEqual(x.bar, 'abc') self.assertEqual(x.__dict__, {'foo': 42, 'bar': 'abc'}) simples = [Any, Union, Tuple, Callable, ClassVar, List, typing.Iterable] for s in simples: for proto in range(pickle.HIGHEST_PROTOCOL + 1): z = pickle.dumps(s, proto) x = pickle.loads(z) self.assertEqual(s, x) def test_copy_and_deepcopy(self): T = TypeVar('T') class Node(Generic[T]): ... things = [Union[T, int], Tuple[T, int], Callable[..., T], Callable[[int], int], Tuple[Any, Any], Node[T], Node[int], Node[Any], typing.Iterable[T], typing.Iterable[Any], typing.Iterable[int], typing.Dict[int, str], typing.Dict[T, Any], ClassVar[int], ClassVar[List[T]], Tuple['T', 'T'], Union['T', int], List['T'], typing.Mapping['T', int]] for t in things + [Any]: self.assertEqual(t, copy(t)) self.assertEqual(t, deepcopy(t)) if sys.version_info >= (3, 3): # From copy module documentation: # It does "copy" functions and classes (shallow and deeply), by returning # the original object unchanged; this is compatible with the way these # are treated by the pickle module. self.assertTrue(t is copy(t)) self.assertTrue(t is deepcopy(t)) def test_copy_generic_instances(self): T = TypeVar('T') class C(Generic[T]): def __init__(self, attr: T) -> None: self.attr = attr c = C(42) self.assertEqual(copy(c).attr, 42) self.assertEqual(deepcopy(c).attr, 42) self.assertIsNot(copy(c), c) self.assertIsNot(deepcopy(c), c) c.attr = 1 self.assertEqual(copy(c).attr, 1) self.assertEqual(deepcopy(c).attr, 1) ci = C[int](42) self.assertEqual(copy(ci).attr, 42) self.assertEqual(deepcopy(ci).attr, 42) self.assertIsNot(copy(ci), ci) self.assertIsNot(deepcopy(ci), ci) ci.attr = 1 self.assertEqual(copy(ci).attr, 1) self.assertEqual(deepcopy(ci).attr, 1) self.assertEqual(ci.__orig_class__, C[int]) def test_weakref_all(self): T = TypeVar('T') things = [Any, Union[T, int], Callable[..., T], Tuple[Any, Any], Optional[List[int]], typing.Mapping[int, str], typing.re.Match[bytes], typing.Iterable['whatever']] for t in things: self.assertEqual(weakref.ref(t)(), t) def test_parameterized_slots(self): T = TypeVar('T') class C(Generic[T]): __slots__ = ('potato',) c = C() c_int = C[int]() self.assertEqual(C.__slots__, C[str].__slots__) c.potato = 0 c_int.potato = 0 with self.assertRaises(AttributeError): c.tomato = 0 with self.assertRaises(AttributeError): c_int.tomato = 0 def foo(x: C['C']): ... self.assertEqual(get_type_hints(foo, globals(), locals())['x'], C[C]) self.assertEqual(get_type_hints(foo, globals(), locals())['x'].__slots__, C.__slots__) self.assertEqual(copy(C[int]), deepcopy(C[int])) def test_parameterized_slots_dict(self): T = TypeVar('T') class D(Generic[T]): __slots__ = {'banana': 42} d = D() d_int = D[int]() self.assertEqual(D.__slots__, D[str].__slots__) d.banana = 'yes' d_int.banana = 'yes' with self.assertRaises(AttributeError): d.foobar = 'no' with self.assertRaises(AttributeError): d_int.foobar = 'no' def test_errors(self): with self.assertRaises(TypeError): B = SimpleMapping[XK, Any] class C(Generic[B]): pass def test_repr_2(self): PY32 = sys.version_info[:2] < (3, 3) class C(Generic[T]): pass self.assertEqual(C.__module__, __name__) if not PY32: self.assertEqual(C.__qualname__, 'GenericTests.test_repr_2.<locals>.C') self.assertEqual(repr(C).split('.')[-1], 'C') X = C[int] self.assertEqual(X.__module__, __name__) if not PY32: self.assertTrue(X.__qualname__.endswith('.<locals>.C')) self.assertEqual(repr(X).split('.')[-1], 'C[int]') class Y(C[int]): pass self.assertEqual(Y.__module__, __name__) if not PY32: self.assertEqual(Y.__qualname__, 'GenericTests.test_repr_2.<locals>.Y') self.assertEqual(repr(Y).split('.')[-1], 'Y') def test_eq_1(self): self.assertEqual(Generic, Generic) self.assertEqual(Generic[T], Generic[T]) self.assertNotEqual(Generic[KT], Generic[VT]) def test_eq_2(self): class A(Generic[T]): pass class B(Generic[T]): pass self.assertEqual(A, A) self.assertNotEqual(A, B) self.assertEqual(A[T], A[T]) self.assertNotEqual(A[T], B[T]) def test_multiple_inheritance(self): class A(Generic[T, VT]): pass class B(Generic[KT, T]): pass class C(A[T, VT], Generic[VT, T, KT], B[KT, T]): pass self.assertEqual(C.__parameters__, (VT, T, KT)) def test_nested(self): G = Generic class Visitor(G[T]): a = None def set(self, a: T): self.a = a def get(self): return self.a def visit(self) -> T: return self.a V = Visitor[typing.List[int]] class IntListVisitor(V): def append(self, x: int): self.a.append(x) a = IntListVisitor() a.set([]) a.append(1) a.append(42) self.assertEqual(a.get(), [1, 42]) def test_type_erasure(self): T = TypeVar('T') class Node(Generic[T]): def __init__(self, label: T, left: 'Node[T]' = None, right: 'Node[T]' = None): self.label = label # type: T self.left = left # type: Optional[Node[T]] self.right = right # type: Optional[Node[T]] def foo(x: T): a = Node(x) b = Node[T](x) c = Node[Any](x) self.assertIs(type(a), Node) self.assertIs(type(b), Node) self.assertIs(type(c), Node) self.assertEqual(a.label, x) self.assertEqual(b.label, x) self.assertEqual(c.label, x) foo(42) def test_implicit_any(self): T = TypeVar('T') class C(Generic[T]): pass class D(C): pass self.assertEqual(D.__parameters__, ()) with self.assertRaises(Exception): D[int] with self.assertRaises(Exception): D[Any] with self.assertRaises(Exception): D[T] def test_new_with_args(self): class A(Generic[T]): pass class B: def __new__(cls, arg): # call object obj = super().__new__(cls) obj.arg = arg return obj # mro: C, A, Generic, B, object class C(A, B): pass c = C('foo') self.assertEqual(c.arg, 'foo') def test_new_with_args2(self): class A: def __init__(self, arg): self.from_a = arg # call object super().__init__() # mro: C, Generic, A, object class C(Generic[T], A): def __init__(self, arg): self.from_c = arg # call Generic super().__init__(arg) c = C('foo') self.assertEqual(c.from_a, 'foo') self.assertEqual(c.from_c, 'foo') def test_new_no_args(self): class A(Generic[T]): pass with self.assertRaises(TypeError): A('foo') class B: def __new__(cls): # call object obj = super().__new__(cls) obj.from_b = 'b' return obj # mro: C, A, Generic, B, object class C(A, B): def __init__(self, arg): self.arg = arg def __new__(cls, arg): # call A obj = super().__new__(cls) obj.from_c = 'c' return obj c = C('foo') self.assertEqual(c.arg, 'foo') self.assertEqual(c.from_b, 'b') self.assertEqual(c.from_c, 'c') class ClassVarTests(BaseTestCase): def test_basics(self): with self.assertRaises(TypeError): ClassVar[1] with self.assertRaises(TypeError): ClassVar[int, str] with self.assertRaises(TypeError): ClassVar[int][str] def test_repr(self): self.assertEqual(repr(ClassVar), 'typing.ClassVar') cv = ClassVar[int] self.assertEqual(repr(cv), 'typing.ClassVar[int]') cv = ClassVar[Employee] self.assertEqual(repr(cv), 'typing.ClassVar[%s.Employee]' % __name__) def test_cannot_subclass(self): with self.assertRaises(TypeError): class C(type(ClassVar)): pass with self.assertRaises(TypeError): class C(type(ClassVar[int])): pass def test_cannot_init(self): with self.assertRaises(TypeError): ClassVar() with self.assertRaises(TypeError): type(ClassVar)() with self.assertRaises(TypeError): type(ClassVar[Optional[int]])() def test_no_isinstance(self): with self.assertRaises(TypeError): isinstance(1, ClassVar[int]) with self.assertRaises(TypeError): issubclass(int, ClassVar) class CastTests(BaseTestCase): def test_basics(self): self.assertEqual(cast(int, 42), 42) self.assertEqual(cast(float, 42), 42) self.assertIs(type(cast(float, 42)), int) self.assertEqual(cast(Any, 42), 42) self.assertEqual(cast(list, 42), 42) self.assertEqual(cast(Union[str, float], 42), 42) self.assertEqual(cast(AnyStr, 42), 42) self.assertEqual(cast(None, 42), 42) def test_errors(self): # Bogus calls are not expected to fail. cast(42, 42) cast('hello', 42) class ForwardRefTests(BaseTestCase): def test_basics(self): class Node(Generic[T]): def __init__(self, label: T): self.label = label self.left = self.right = None def add_both(self, left: 'Optional[Node[T]]', right: 'Node[T]' = None, stuff: int = None, blah=None): self.left = left self.right = right def add_left(self, node: Optional['Node[T]']): self.add_both(node, None) def add_right(self, node: 'Node[T]' = None): self.add_both(None, node) t = Node[int] both_hints = get_type_hints(t.add_both, globals(), locals()) self.assertEqual(both_hints['left'], Optional[Node[T]]) self.assertEqual(both_hints['right'], Optional[Node[T]]) self.assertEqual(both_hints['left'], both_hints['right']) self.assertEqual(both_hints['stuff'], Optional[int]) self.assertNotIn('blah', both_hints) left_hints = get_type_hints(t.add_left, globals(), locals()) self.assertEqual(left_hints['node'], Optional[Node[T]]) right_hints = get_type_hints(t.add_right, globals(), locals()) self.assertEqual(right_hints['node'], Optional[Node[T]]) def test_forwardref_instance_type_error(self): fr = typing._ForwardRef('int') with self.assertRaises(TypeError): isinstance(42, fr) def test_forwardref_subclass_type_error(self): fr = typing._ForwardRef('int') with self.assertRaises(TypeError): issubclass(int, fr) def test_forward_equality(self): fr = typing._ForwardRef('int') self.assertEqual(fr, typing._ForwardRef('int')) self.assertNotEqual(List['int'], List[int]) def test_forward_repr(self): self.assertEqual(repr(List['int']), "typing.List[_ForwardRef('int')]") def test_union_forward(self): def foo(a: Union['T']): pass self.assertEqual(get_type_hints(foo, globals(), locals()), {'a': Union[T]}) def test_tuple_forward(self): def foo(a: Tuple['T']): pass self.assertEqual(get_type_hints(foo, globals(), locals()), {'a': Tuple[T]}) def test_callable_forward(self): def foo(a: Callable[['T'], 'T']): pass self.assertEqual(get_type_hints(foo, globals(), locals()), {'a': Callable[[T], T]}) def test_callable_with_ellipsis_forward(self): def foo(a: 'Callable[..., T]'): pass self.assertEqual(get_type_hints(foo, globals(), locals()), {'a': Callable[..., T]}) def test_syntax_error(self): with self.assertRaises(SyntaxError): Generic['/T'] def test_delayed_syntax_error(self): def foo(a: 'Node[T'): pass with self.assertRaises(SyntaxError): get_type_hints(foo) def test_type_error(self): def foo(a: Tuple['42']): pass with self.assertRaises(TypeError): get_type_hints(foo) def test_name_error(self): def foo(a: 'Noode[T]'): pass with self.assertRaises(NameError): get_type_hints(foo, locals()) def test_no_type_check(self): @no_type_check def foo(a: 'whatevers') -> {}: pass th = get_type_hints(foo) self.assertEqual(th, {}) def test_no_type_check_class(self): @no_type_check class C: def foo(a: 'whatevers') -> {}: pass cth = get_type_hints(C.foo) self.assertEqual(cth, {}) ith = get_type_hints(C().foo) self.assertEqual(ith, {}) def test_no_type_check_no_bases(self): class C: def meth(self, x: int): ... @no_type_check class D(C): c = C # verify that @no_type_check never affects bases self.assertEqual(get_type_hints(C.meth), {'x': int}) def test_meta_no_type_check(self): @no_type_check_decorator def magic_decorator(func): return func self.assertEqual(magic_decorator.__name__, 'magic_decorator') @magic_decorator def foo(a: 'whatevers') -> {}: pass @magic_decorator class C: def foo(a: 'whatevers') -> {}: pass self.assertEqual(foo.__name__, 'foo') th = get_type_hints(foo) self.assertEqual(th, {}) cth = get_type_hints(C.foo) self.assertEqual(cth, {}) ith = get_type_hints(C().foo) self.assertEqual(ith, {}) def test_default_globals(self): code = ("class C:\n" " def foo(self, a: 'C') -> 'D': pass\n" "class D:\n" " def bar(self, b: 'D') -> C: pass\n" ) ns = {} exec(code, ns) hints = get_type_hints(ns['C'].foo) self.assertEqual(hints, {'a': ns['C'], 'return': ns['D']}) class OverloadTests(BaseTestCase): def test_overload_fails(self): from typing import overload with self.assertRaises(RuntimeError): @overload def blah(): pass blah() def test_overload_succeeds(self): from typing import overload @overload def blah(): pass def blah(): pass blah() ASYNCIO = sys.version_info[:2] >= (3, 5) ASYNCIO_TESTS = """ import asyncio T_a = TypeVar('T_a') class AwaitableWrapper(typing.Awaitable[T_a]): def __init__(self, value): self.value = value def __await__(self) -> typing.Iterator[T_a]: yield return self.value class AsyncIteratorWrapper(typing.AsyncIterator[T_a]): def __init__(self, value: typing.Iterable[T_a]): self.value = value def __aiter__(self) -> typing.AsyncIterator[T_a]: return self @asyncio.coroutine def __anext__(self) -> T_a: data = yield from self.value if data: return data else: raise StopAsyncIteration class ACM: async def __aenter__(self) -> int: return 42 async def __aexit__(self, etype, eval, tb): return None """ if ASYNCIO: try: exec(ASYNCIO_TESTS) except ImportError: ASYNCIO = False else: # fake names for the sake of static analysis asyncio = None AwaitableWrapper = AsyncIteratorWrapper = ACM = object PY36_TESTS = """ from test import ann_module, ann_module2, ann_module3 from typing import AsyncContextManager class A: y: float class B(A): x: ClassVar[Optional['B']] = None y: int b: int class CSub(B): z: ClassVar['CSub'] = B() class G(Generic[T]): lst: ClassVar[List[T]] = [] class NoneAndForward: parent: 'NoneAndForward' meaning: None class CoolEmployee(NamedTuple): name: str cool: int class CoolEmployeeWithDefault(NamedTuple): name: str cool: int = 0 class XMeth(NamedTuple): x: int def double(self): return 2 * self.x class XRepr(NamedTuple): x: int y: int = 1 def __str__(self): return f'{self.x} -> {self.y}' def __add__(self, other): return 0 class HasForeignBaseClass(mod_generics_cache.A): some_xrepr: 'XRepr' other_a: 'mod_generics_cache.A' """ ASYNC_PART = """ async def g_with(am: AsyncContextManager[int]): x: int async with am as x: return x try: g_with(ACM()).send(None) except StopIteration as e: assert e.args[0] == 42 """ if PY36: exec(PY36_TESTS) else: # fake names for the sake of static analysis ann_module = ann_module2 = ann_module3 = None A = B = CSub = G = CoolEmployee = CoolEmployeeWithDefault = object XMeth = XRepr = NoneAndForward = object gth = get_type_hints class GetTypeHintTests(BaseTestCase): def test_get_type_hints_from_various_objects(self): # For invalid objects should fail with TypeError (not AttributeError etc). with self.assertRaises(TypeError): gth(123) with self.assertRaises(TypeError): gth('abc') with self.assertRaises(TypeError): gth(None) @skipUnless(PY36, 'Python 3.6 required') def test_get_type_hints_modules(self): ann_module_type_hints = {1: 2, 'f': Tuple[int, int], 'x': int, 'y': str} self.assertEqual(gth(ann_module), ann_module_type_hints) self.assertEqual(gth(ann_module2), {}) self.assertEqual(gth(ann_module3), {}) @skipUnless(PY36, 'Python 3.6 required') @expectedFailure def test_get_type_hints_modules_forwardref(self): # FIXME: This currently exposes a bug in typing. Cached forward references # don't account for the case where there are multiple types of the same # name coming from different modules in the same program. mgc_hints = {'default_a': Optional[mod_generics_cache.A], 'default_b': Optional[mod_generics_cache.B]} self.assertEqual(gth(mod_generics_cache), mgc_hints) @skipUnless(PY36, 'Python 3.6 required') def test_get_type_hints_classes(self): self.assertEqual(gth(ann_module.C), # gth will find the right globalns {'y': Optional[ann_module.C]}) self.assertIsInstance(gth(ann_module.j_class), dict) self.assertEqual(gth(ann_module.M), {'123': 123, 'o': type}) self.assertEqual(gth(ann_module.D), {'j': str, 'k': str, 'y': Optional[ann_module.C]}) self.assertEqual(gth(ann_module.Y), {'z': int}) self.assertEqual(gth(ann_module.h_class), {'y': Optional[ann_module.C]}) self.assertEqual(gth(ann_module.S), {'x': str, 'y': str}) self.assertEqual(gth(ann_module.foo), {'x': int}) self.assertEqual(gth(NoneAndForward), {'parent': NoneAndForward, 'meaning': type(None)}) self.assertEqual(gth(HasForeignBaseClass), {'some_xrepr': XRepr, 'other_a': mod_generics_cache.A, 'some_b': mod_generics_cache.B}) self.assertEqual(gth(XRepr.__new__), {'x': int, 'y': int}) self.assertEqual(gth(mod_generics_cache.B), {'my_inner_a1': mod_generics_cache.B.A, 'my_inner_a2': mod_generics_cache.B.A, 'my_outer_a': mod_generics_cache.A}) @skipUnless(PY36, 'Python 3.6 required') def test_respect_no_type_check(self): @no_type_check class NoTpCheck: class Inn: def __init__(self, x: 'not a type'): ... self.assertTrue(NoTpCheck.__no_type_check__) self.assertTrue(NoTpCheck.Inn.__init__.__no_type_check__) self.assertEqual(gth(ann_module2.NTC.meth), {}) class ABase(Generic[T]): def meth(x: int): ... @no_type_check class Der(ABase): ... self.assertEqual(gth(ABase.meth), {'x': int}) def test_get_type_hints_for_builtins(self): # Should not fail for built-in classes and functions. self.assertEqual(gth(int), {}) self.assertEqual(gth(type), {}) self.assertEqual(gth(dir), {}) self.assertEqual(gth(len), {}) self.assertEqual(gth(object.__str__), {}) self.assertEqual(gth(object().__str__), {}) self.assertEqual(gth(str.join), {}) def test_previous_behavior(self): def testf(x, y): ... testf.__annotations__['x'] = 'int' self.assertEqual(gth(testf), {'x': int}) def testg(x: None): ... self.assertEqual(gth(testg), {'x': type(None)}) def test_get_type_hints_for_object_with_annotations(self): class A: ... class B: ... b = B() b.__annotations__ = {'x': 'A'} self.assertEqual(gth(b, locals()), {'x': A}) @skipUnless(PY36, 'Python 3.6 required') def test_get_type_hints_ClassVar(self): self.assertEqual(gth(ann_module2.CV, ann_module2.__dict__), {'var': typing.ClassVar[ann_module2.CV]}) self.assertEqual(gth(B, globals()), {'y': int, 'x': ClassVar[Optional[B]], 'b': int}) self.assertEqual(gth(CSub, globals()), {'z': ClassVar[CSub], 'y': int, 'b': int, 'x': ClassVar[Optional[B]]}) self.assertEqual(gth(G), {'lst': ClassVar[List[T]]}) class CollectionsAbcTests(BaseTestCase): def test_hashable(self): self.assertIsInstance(42, typing.Hashable) self.assertNotIsInstance([], typing.Hashable) def test_iterable(self): self.assertIsInstance([], typing.Iterable) # Due to ABC caching, the second time takes a separate code # path and could fail. So call this a few times. self.assertIsInstance([], typing.Iterable) self.assertIsInstance([], typing.Iterable) self.assertNotIsInstance(42, typing.Iterable) # Just in case, also test issubclass() a few times. self.assertIsSubclass(list, typing.Iterable) self.assertIsSubclass(list, typing.Iterable) def test_iterator(self): it = iter([]) self.assertIsInstance(it, typing.Iterator) self.assertNotIsInstance(42, typing.Iterator) @skipUnless(ASYNCIO, 'Python 3.5 and multithreading required') def test_awaitable(self): ns = {} exec( "async def foo() -> typing.Awaitable[int]:\n" " return await AwaitableWrapper(42)\n", globals(), ns) foo = ns['foo'] g = foo() self.assertIsInstance(g, typing.Awaitable) self.assertNotIsInstance(foo, typing.Awaitable) g.send(None) # Run foo() till completion, to avoid warning. @skipUnless(ASYNCIO, 'Python 3.5 and multithreading required') def test_coroutine(self): ns = {} exec( "async def foo():\n" " return\n", globals(), ns) foo = ns['foo'] g = foo() self.assertIsInstance(g, typing.Coroutine) with self.assertRaises(TypeError): isinstance(g, typing.Coroutine[int]) self.assertNotIsInstance(foo, typing.Coroutine) try: g.send(None) except StopIteration: pass @skipUnless(ASYNCIO, 'Python 3.5 and multithreading required') def test_async_iterable(self): base_it = range(10) # type: Iterator[int] it = AsyncIteratorWrapper(base_it) self.assertIsInstance(it, typing.AsyncIterable) self.assertIsInstance(it, typing.AsyncIterable) self.assertNotIsInstance(42, typing.AsyncIterable) @skipUnless(ASYNCIO, 'Python 3.5 and multithreading required') def test_async_iterator(self): base_it = range(10) # type: Iterator[int] it = AsyncIteratorWrapper(base_it) self.assertIsInstance(it, typing.AsyncIterator) self.assertNotIsInstance(42, typing.AsyncIterator) def test_sized(self): self.assertIsInstance([], typing.Sized) self.assertNotIsInstance(42, typing.Sized) def test_container(self): self.assertIsInstance([], typing.Container) self.assertNotIsInstance(42, typing.Container) def test_collection(self): if hasattr(typing, 'Collection'): self.assertIsInstance(tuple(), typing.Collection) self.assertIsInstance(frozenset(), typing.Collection) self.assertIsSubclass(dict, typing.Collection) self.assertNotIsInstance(42, typing.Collection) def test_abstractset(self): self.assertIsInstance(set(), typing.AbstractSet) self.assertNotIsInstance(42, typing.AbstractSet) def test_mutableset(self): self.assertIsInstance(set(), typing.MutableSet) self.assertNotIsInstance(frozenset(), typing.MutableSet) def test_mapping(self): self.assertIsInstance({}, typing.Mapping) self.assertNotIsInstance(42, typing.Mapping) def test_mutablemapping(self): self.assertIsInstance({}, typing.MutableMapping) self.assertNotIsInstance(42, typing.MutableMapping) def test_sequence(self): self.assertIsInstance([], typing.Sequence) self.assertNotIsInstance(42, typing.Sequence) def test_mutablesequence(self): self.assertIsInstance([], typing.MutableSequence) self.assertNotIsInstance((), typing.MutableSequence) def test_bytestring(self): self.assertIsInstance(b'', typing.ByteString) self.assertIsInstance(bytearray(b''), typing.ByteString) def test_list(self): self.assertIsSubclass(list, typing.List) def test_deque(self): self.assertIsSubclass(collections.deque, typing.Deque) class MyDeque(typing.Deque[int]): ... self.assertIsInstance(MyDeque(), collections.deque) def test_counter(self): self.assertIsSubclass(collections.Counter, typing.Counter) def test_set(self): self.assertIsSubclass(set, typing.Set) self.assertNotIsSubclass(frozenset, typing.Set) def test_frozenset(self): self.assertIsSubclass(frozenset, typing.FrozenSet) self.assertNotIsSubclass(set, typing.FrozenSet) def test_dict(self): self.assertIsSubclass(dict, typing.Dict) def test_no_list_instantiation(self): with self.assertRaises(TypeError): typing.List() with self.assertRaises(TypeError): typing.List[T]() with self.assertRaises(TypeError): typing.List[int]() def test_list_subclass(self): class MyList(typing.List[int]): pass a = MyList() self.assertIsInstance(a, MyList) self.assertIsInstance(a, typing.Sequence) self.assertIsSubclass(MyList, list) self.assertNotIsSubclass(list, MyList) def test_no_dict_instantiation(self): with self.assertRaises(TypeError): typing.Dict() with self.assertRaises(TypeError): typing.Dict[KT, VT]() with self.assertRaises(TypeError): typing.Dict[str, int]() def test_dict_subclass(self): class MyDict(typing.Dict[str, int]): pass d = MyDict() self.assertIsInstance(d, MyDict) self.assertIsInstance(d, typing.MutableMapping) self.assertIsSubclass(MyDict, dict) self.assertNotIsSubclass(dict, MyDict) def test_defaultdict_instantiation(self): self.assertIs(type(typing.DefaultDict()), collections.defaultdict) self.assertIs(type(typing.DefaultDict[KT, VT]()), collections.defaultdict) self.assertIs(type(typing.DefaultDict[str, int]()), collections.defaultdict) def test_defaultdict_subclass(self): class MyDefDict(typing.DefaultDict[str, int]): pass dd = MyDefDict() self.assertIsInstance(dd, MyDefDict) self.assertIsSubclass(MyDefDict, collections.defaultdict) self.assertNotIsSubclass(collections.defaultdict, MyDefDict) @skipUnless(sys.version_info >= (3, 3), 'ChainMap was added in 3.3') def test_chainmap_instantiation(self): self.assertIs(type(typing.ChainMap()), collections.ChainMap) self.assertIs(type(typing.ChainMap[KT, VT]()), collections.ChainMap) self.assertIs(type(typing.ChainMap[str, int]()), collections.ChainMap) class CM(typing.ChainMap[KT, VT]): ... self.assertIs(type(CM[int, str]()), CM) @skipUnless(sys.version_info >= (3, 3), 'ChainMap was added in 3.3') def test_chainmap_subclass(self): class MyChainMap(typing.ChainMap[str, int]): pass cm = MyChainMap() self.assertIsInstance(cm, MyChainMap) self.assertIsSubclass(MyChainMap, collections.ChainMap) self.assertNotIsSubclass(collections.ChainMap, MyChainMap) def test_deque_instantiation(self): self.assertIs(type(typing.Deque()), collections.deque) self.assertIs(type(typing.Deque[T]()), collections.deque) self.assertIs(type(typing.Deque[int]()), collections.deque) class D(typing.Deque[T]): ... self.assertIs(type(D[int]()), D) def test_counter_instantiation(self): self.assertIs(type(typing.Counter()), collections.Counter) self.assertIs(type(typing.Counter[T]()), collections.Counter) self.assertIs(type(typing.Counter[int]()), collections.Counter) class C(typing.Counter[T]): ... self.assertIs(type(C[int]()), C) def test_counter_subclass_instantiation(self): class MyCounter(typing.Counter[int]): pass d = MyCounter() self.assertIsInstance(d, MyCounter) self.assertIsInstance(d, typing.Counter) self.assertIsInstance(d, collections.Counter) def test_no_set_instantiation(self): with self.assertRaises(TypeError): typing.Set() with self.assertRaises(TypeError): typing.Set[T]() with self.assertRaises(TypeError): typing.Set[int]() def test_set_subclass_instantiation(self): class MySet(typing.Set[int]): pass d = MySet() self.assertIsInstance(d, MySet) def test_no_frozenset_instantiation(self): with self.assertRaises(TypeError): typing.FrozenSet() with self.assertRaises(TypeError): typing.FrozenSet[T]() with self.assertRaises(TypeError): typing.FrozenSet[int]() def test_frozenset_subclass_instantiation(self): class MyFrozenSet(typing.FrozenSet[int]): pass d = MyFrozenSet() self.assertIsInstance(d, MyFrozenSet) def test_no_tuple_instantiation(self): with self.assertRaises(TypeError): Tuple() with self.assertRaises(TypeError): Tuple[T]() with self.assertRaises(TypeError): Tuple[int]() def test_generator(self): def foo(): yield 42 g = foo() self.assertIsSubclass(type(g), typing.Generator) def test_no_generator_instantiation(self): with self.assertRaises(TypeError): typing.Generator() with self.assertRaises(TypeError): typing.Generator[T, T, T]() with self.assertRaises(TypeError): typing.Generator[int, int, int]() @skipUnless(PY36, 'Python 3.6 required') def test_async_generator(self): ns = {} exec("async def f():\n" " yield 42\n", globals(), ns) g = ns['f']() self.assertIsSubclass(type(g), typing.AsyncGenerator) @skipUnless(PY36, 'Python 3.6 required') def test_no_async_generator_instantiation(self): with self.assertRaises(TypeError): typing.AsyncGenerator() with self.assertRaises(TypeError): typing.AsyncGenerator[T, T]() with self.assertRaises(TypeError): typing.AsyncGenerator[int, int]() def test_subclassing(self): class MMA(typing.MutableMapping): pass with self.assertRaises(TypeError): # It's abstract MMA() class MMC(MMA): def __getitem__(self, k): return None def __setitem__(self, k, v): pass def __delitem__(self, k): pass def __iter__(self): return iter(()) def __len__(self): return 0 self.assertEqual(len(MMC()), 0) assert callable(MMC.update) self.assertIsInstance(MMC(), typing.Mapping) class MMB(typing.MutableMapping[KT, VT]): def __getitem__(self, k): return None def __setitem__(self, k, v): pass def __delitem__(self, k): pass def __iter__(self): return iter(()) def __len__(self): return 0 self.assertEqual(len(MMB()), 0) self.assertEqual(len(MMB[str, str]()), 0) self.assertEqual(len(MMB[KT, VT]()), 0) self.assertNotIsSubclass(dict, MMA) self.assertNotIsSubclass(dict, MMB) self.assertIsSubclass(MMA, typing.Mapping) self.assertIsSubclass(MMB, typing.Mapping) self.assertIsSubclass(MMC, typing.Mapping) self.assertIsInstance(MMB[KT, VT](), typing.Mapping) self.assertIsInstance(MMB[KT, VT](), collections.Mapping) self.assertIsSubclass(MMA, collections.Mapping) self.assertIsSubclass(MMB, collections.Mapping) self.assertIsSubclass(MMC, collections.Mapping) self.assertIsSubclass(MMB[str, str], typing.Mapping) self.assertIsSubclass(MMC, MMA) class I(typing.Iterable): ... self.assertNotIsSubclass(list, I) class G(typing.Generator[int, int, int]): ... def g(): yield 0 self.assertIsSubclass(G, typing.Generator) self.assertIsSubclass(G, typing.Iterable) if hasattr(collections, 'Generator'): self.assertIsSubclass(G, collections.Generator) self.assertIsSubclass(G, collections.Iterable) self.assertNotIsSubclass(type(g), G) @skipUnless(PY36, 'Python 3.6 required') def test_subclassing_async_generator(self): class G(typing.AsyncGenerator[int, int]): def asend(self, value): pass def athrow(self, typ, val=None, tb=None): pass ns = {} exec('async def g(): yield 0', globals(), ns) g = ns['g'] self.assertIsSubclass(G, typing.AsyncGenerator) self.assertIsSubclass(G, typing.AsyncIterable) self.assertIsSubclass(G, collections.AsyncGenerator) self.assertIsSubclass(G, collections.AsyncIterable) self.assertNotIsSubclass(type(g), G) instance = G() self.assertIsInstance(instance, typing.AsyncGenerator) self.assertIsInstance(instance, typing.AsyncIterable) self.assertIsInstance(instance, collections.AsyncGenerator) self.assertIsInstance(instance, collections.AsyncIterable) self.assertNotIsInstance(type(g), G) self.assertNotIsInstance(g, G) def test_subclassing_subclasshook(self): class Base(typing.Iterable): @classmethod def __subclasshook__(cls, other): if other.__name__ == 'Foo': return True else: return False class C(Base): ... class Foo: ... class Bar: ... self.assertIsSubclass(Foo, Base) self.assertIsSubclass(Foo, C) self.assertNotIsSubclass(Bar, C) def test_subclassing_register(self): class A(typing.Container): ... class B(A): ... class C: ... A.register(C) self.assertIsSubclass(C, A) self.assertNotIsSubclass(C, B) class D: ... B.register(D) self.assertIsSubclass(D, A) self.assertIsSubclass(D, B) class M(): ... collections.MutableMapping.register(M) self.assertIsSubclass(M, typing.Mapping) def test_collections_as_base(self): class M(collections.Mapping): ... self.assertIsSubclass(M, typing.Mapping) self.assertIsSubclass(M, typing.Iterable) class S(collections.MutableSequence): ... self.assertIsSubclass(S, typing.MutableSequence) self.assertIsSubclass(S, typing.Iterable) class I(collections.Iterable): ... self.assertIsSubclass(I, typing.Iterable) class A(collections.Mapping, metaclass=abc.ABCMeta): ... class B: ... A.register(B) self.assertIsSubclass(B, typing.Mapping) class OtherABCTests(BaseTestCase): def test_contextmanager(self): @contextlib.contextmanager def manager(): yield 42 cm = manager() self.assertIsInstance(cm, typing.ContextManager) self.assertNotIsInstance(42, typing.ContextManager) @skipUnless(ASYNCIO, 'Python 3.5 required') def test_async_contextmanager(self): class NotACM: pass self.assertIsInstance(ACM(), typing.AsyncContextManager) self.assertNotIsInstance(NotACM(), typing.AsyncContextManager) @contextlib.contextmanager def manager(): yield 42 cm = manager() self.assertNotIsInstance(cm, typing.AsyncContextManager) self.assertEqual(typing.AsyncContextManager[int].__args__, (int,)) with self.assertRaises(TypeError): isinstance(42, typing.AsyncContextManager[int]) with self.assertRaises(TypeError): typing.AsyncContextManager[int, str] class TypeTests(BaseTestCase): def test_type_basic(self): class User: pass class BasicUser(User): pass class ProUser(User): pass def new_user(user_class: Type[User]) -> User: return user_class() new_user(BasicUser) def test_type_typevar(self): class User: pass class BasicUser(User): pass class ProUser(User): pass U = TypeVar('U', bound=User) def new_user(user_class: Type[U]) -> U: return user_class() new_user(BasicUser) def test_type_optional(self): A = Optional[Type[BaseException]] def foo(a: A) -> Optional[BaseException]: if a is None: return None else: return a() assert isinstance(foo(KeyboardInterrupt), KeyboardInterrupt) assert foo(None) is None class NewTypeTests(BaseTestCase): def test_basic(self): UserId = NewType('UserId', int) UserName = NewType('UserName', str) self.assertIsInstance(UserId(5), int) self.assertIsInstance(UserName('Joe'), str) self.assertEqual(UserId(5) + 1, 6) def test_errors(self): UserId = NewType('UserId', int) UserName = NewType('UserName', str) with self.assertRaises(TypeError): issubclass(UserId, int) with self.assertRaises(TypeError): class D(UserName): pass class NamedTupleTests(BaseTestCase): def test_basics(self): Emp = NamedTuple('Emp', [('name', str), ('id', int)]) self.assertIsSubclass(Emp, tuple) joe = Emp('Joe', 42) jim = Emp(name='Jim', id=1) self.assertIsInstance(joe, Emp) self.assertIsInstance(joe, tuple) self.assertEqual(joe.name, 'Joe') self.assertEqual(joe.id, 42) self.assertEqual(jim.name, 'Jim') self.assertEqual(jim.id, 1) self.assertEqual(Emp.__name__, 'Emp') self.assertEqual(Emp._fields, ('name', 'id')) self.assertEqual(Emp.__annotations__, collections.OrderedDict([('name', str), ('id', int)])) self.assertIs(Emp._field_types, Emp.__annotations__) def test_namedtuple_pyversion(self): if sys.version_info[:2] < (3, 6): with self.assertRaises(TypeError): NamedTuple('Name', one=int, other=str) with self.assertRaises(TypeError): class NotYet(NamedTuple): whatever = 0 @skipUnless(PY36, 'Python 3.6 required') def test_annotation_usage(self): tim = CoolEmployee('Tim', 9000) self.assertIsInstance(tim, CoolEmployee) self.assertIsInstance(tim, tuple) self.assertEqual(tim.name, 'Tim') self.assertEqual(tim.cool, 9000) self.assertEqual(CoolEmployee.__name__, 'CoolEmployee') self.assertEqual(CoolEmployee._fields, ('name', 'cool')) self.assertEqual(CoolEmployee.__annotations__, collections.OrderedDict(name=str, cool=int)) self.assertIs(CoolEmployee._field_types, CoolEmployee.__annotations__) @skipUnless(PY36, 'Python 3.6 required') def test_annotation_usage_with_default(self): jelle = CoolEmployeeWithDefault('Jelle') self.assertIsInstance(jelle, CoolEmployeeWithDefault) self.assertIsInstance(jelle, tuple) self.assertEqual(jelle.name, 'Jelle') self.assertEqual(jelle.cool, 0) cooler_employee = CoolEmployeeWithDefault('Sjoerd', 1) self.assertEqual(cooler_employee.cool, 1) self.assertEqual(CoolEmployeeWithDefault.__name__, 'CoolEmployeeWithDefault') self.assertEqual(CoolEmployeeWithDefault._fields, ('name', 'cool')) self.assertEqual(CoolEmployeeWithDefault._field_types, dict(name=str, cool=int)) self.assertEqual(CoolEmployeeWithDefault._field_defaults, dict(cool=0)) with self.assertRaises(TypeError): exec(""" class NonDefaultAfterDefault(NamedTuple): x: int = 3 y: int """) @skipUnless(PY36, 'Python 3.6 required') def test_annotation_usage_with_methods(self): self.assertEqual(XMeth(1).double(), 2) self.assertEqual(XMeth(42).x, XMeth(42)[0]) self.assertEqual(str(XRepr(42)), '42 -> 1') self.assertEqual(XRepr(1, 2) + XRepr(3), 0) with self.assertRaises(AttributeError): exec(""" class XMethBad(NamedTuple): x: int def _fields(self): return 'no chance for this' """) with self.assertRaises(AttributeError): exec(""" class XMethBad2(NamedTuple): x: int def _source(self): return 'no chance for this as well' """) @skipUnless(PY36, 'Python 3.6 required') def test_namedtuple_keyword_usage(self): LocalEmployee = NamedTuple("LocalEmployee", name=str, age=int) nick = LocalEmployee('Nick', 25) self.assertIsInstance(nick, tuple) self.assertEqual(nick.name, 'Nick') self.assertEqual(LocalEmployee.__name__, 'LocalEmployee') self.assertEqual(LocalEmployee._fields, ('name', 'age')) self.assertEqual(LocalEmployee.__annotations__, dict(name=str, age=int)) self.assertIs(LocalEmployee._field_types, LocalEmployee.__annotations__) with self.assertRaises(TypeError): NamedTuple('Name', [('x', int)], y=str) with self.assertRaises(TypeError): NamedTuple('Name', x=1, y='a') def test_pickle(self): global Emp # pickle wants to reference the class by name Emp = NamedTuple('Emp', [('name', str), ('id', int)]) jane = Emp('jane', 37) for proto in range(pickle.HIGHEST_PROTOCOL + 1): z = pickle.dumps(jane, proto) jane2 = pickle.loads(z) self.assertEqual(jane2, jane) class IOTests(BaseTestCase): def test_io(self): def stuff(a: IO) -> AnyStr: return a.readline() a = stuff.__annotations__['a'] self.assertEqual(a.__parameters__, (AnyStr,)) def test_textio(self): def stuff(a: TextIO) -> str: return a.readline() a = stuff.__annotations__['a'] self.assertEqual(a.__parameters__, ()) def test_binaryio(self): def stuff(a: BinaryIO) -> bytes: return a.readline() a = stuff.__annotations__['a'] self.assertEqual(a.__parameters__, ()) # def test_io_submodule(self): # from typing.io import IO, TextIO, BinaryIO, __all__, __name__ # self.assertIs(IO, typing.IO) # self.assertIs(TextIO, typing.TextIO) # self.assertIs(BinaryIO, typing.BinaryIO) # self.assertEqual(set(__all__), set(['IO', 'TextIO', 'BinaryIO'])) # self.assertEqual(__name__, 'typing.io') class RETests(BaseTestCase): # Much of this is really testing _TypeAlias. def test_basics(self): pat = re.compile('[a-z]+', re.I) self.assertIsSubclass(pat.__class__, Pattern) self.assertIsSubclass(type(pat), Pattern) self.assertIsInstance(pat, Pattern) mat = pat.search('12345abcde.....') self.assertIsSubclass(mat.__class__, Match) self.assertIsSubclass(type(mat), Match) self.assertIsInstance(mat, Match) # these should just work Pattern[Union[str, bytes]] Match[Union[bytes, str]] def test_alias_equality(self): self.assertEqual(Pattern[str], Pattern[str]) self.assertNotEqual(Pattern[str], Pattern[bytes]) self.assertNotEqual(Pattern[str], Match[str]) self.assertNotEqual(Pattern[str], str) def test_errors(self): with self.assertRaises(TypeError): # Doesn't fit AnyStr. Pattern[int] with self.assertRaises(TypeError): # Can't change type vars? Match[T] m = Match[Union[str, bytes]] with self.assertRaises(TypeError): # Too complicated? m[str] with self.assertRaises(TypeError): # We don't support isinstance(). isinstance(42, Pattern[str]) with self.assertRaises(TypeError): # We don't support issubclass(). issubclass(Pattern[bytes], Pattern[str]) def test_repr(self): self.assertEqual(repr(Pattern), 'Pattern[~AnyStr]') self.assertEqual(repr(Pattern[str]), 'Pattern[str]') self.assertEqual(repr(Pattern[bytes]), 'Pattern[bytes]') self.assertEqual(repr(Match), 'Match[~AnyStr]') self.assertEqual(repr(Match[str]), 'Match[str]') self.assertEqual(repr(Match[bytes]), 'Match[bytes]') # def test_re_submodule(self): # from typing.re import Match, Pattern, __all__, __name__ # self.assertIs(Match, typing.Match) # self.assertIs(Pattern, typing.Pattern) # self.assertEqual(set(__all__), set(['Match', 'Pattern'])) # self.assertEqual(__name__, 'typing.re') def test_cannot_subclass(self): with self.assertRaises(TypeError) as ex: class A(typing.Match): pass self.assertEqual(str(ex.exception), "Cannot subclass typing._TypeAlias") class AllTests(BaseTestCase): """Tests for __all__.""" def test_all(self): from typing import __all__ as a # Just spot-check the first and last of every category. self.assertIn('AbstractSet', a) self.assertIn('ValuesView', a) self.assertIn('cast', a) self.assertIn('overload', a) if hasattr(contextlib, 'AbstractContextManager'): self.assertIn('ContextManager', a) # Check that io and re are not exported. self.assertNotIn('io', a) self.assertNotIn('re', a) # Spot-check that stdlib modules aren't exported. self.assertNotIn('os', a) self.assertNotIn('sys', a) # Check that Text is defined. self.assertIn('Text', a) # Check previously missing classes. self.assertIn('SupportsBytes', a) self.assertIn('SupportsComplex', a) if __name__ == '__main__': main()
86,730
2,654
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_threadedtempfile.py
""" Create and delete FILES_PER_THREAD temp files (via tempfile.TemporaryFile) in each of NUM_THREADS threads, recording the number of successes and failures. A failure is a bug in tempfile, and may be due to: + Trying to create more than one tempfile with the same name. + Trying to delete a tempfile that doesn't still exist. + Something we've never seen before. By default, NUM_THREADS == 20 and FILES_PER_THREAD == 50. This is enough to create about 150 failures per run under Win98SE in 2.0, and runs pretty quickly. Guido reports needing to boost FILES_PER_THREAD to 500 before provoking a 2.0 failure under Linux. """ NUM_THREADS = 20 FILES_PER_THREAD = 50 import tempfile from test.support import start_threads, import_module threading = import_module('threading') import unittest import io from traceback import print_exc startEvent = threading.Event() class TempFileGreedy(threading.Thread): error_count = 0 ok_count = 0 def run(self): self.errors = io.StringIO() startEvent.wait() for i in range(FILES_PER_THREAD): try: f = tempfile.TemporaryFile("w+b") f.close() except: self.error_count += 1 print_exc(file=self.errors) else: self.ok_count += 1 class ThreadedTempFileTest(unittest.TestCase): def test_main(self): threads = [TempFileGreedy() for i in range(NUM_THREADS)] with start_threads(threads, startEvent.set): pass ok = sum(t.ok_count for t in threads) errors = [str(t.name) + str(t.errors.getvalue()) for t in threads if t.error_count] msg = "Errors: errors %d ok %d\n%s" % (len(errors), ok, '\n'.join(errors)) self.assertEqual(errors, [], msg) self.assertEqual(ok, NUM_THREADS * FILES_PER_THREAD) if __name__ == "__main__": unittest.main()
1,932
63
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/eintrdata/eintr_tester.py
""" This test suite exercises some system calls subject to interruption with EINTR, to check that it is actually handled transparently. It is intended to be run by the main test suite within a child process, to ensure there is no background thread running (so that signals are delivered to the correct thread). Signals are generated in-process using setitimer(ITIMER_REAL), which allows sub-second periodicity (contrarily to signal()). """ import contextlib import faulthandler import fcntl import os import select import signal import socket import subprocess import sys import time import unittest from test import support @contextlib.contextmanager def kill_on_error(proc): """Context manager killing the subprocess if a Python exception is raised.""" with proc: try: yield proc except: proc.kill() raise @unittest.skipUnless(hasattr(signal, "setitimer"), "requires setitimer()") class EINTRBaseTest(unittest.TestCase): """ Base class for EINTR tests. """ # delay for initial signal delivery signal_delay = 0.1 # signal delivery periodicity signal_period = 0.1 # default sleep time for tests - should obviously have: # sleep_time > signal_period sleep_time = 0.2 def sighandler(self, signum, frame): self.signals += 1 def setUp(self): self.signals = 0 self.orig_handler = signal.signal(signal.SIGALRM, self.sighandler) signal.setitimer(signal.ITIMER_REAL, self.signal_delay, self.signal_period) # Use faulthandler as watchdog to debug when a test hangs # (timeout of 10 minutes) if hasattr(faulthandler, 'dump_traceback_later'): faulthandler.dump_traceback_later(10 * 60, exit=True, file=sys.__stderr__) @staticmethod def stop_alarm(): signal.setitimer(signal.ITIMER_REAL, 0, 0) def tearDown(self): self.stop_alarm() signal.signal(signal.SIGALRM, self.orig_handler) if hasattr(faulthandler, 'cancel_dump_traceback_later'): faulthandler.cancel_dump_traceback_later() def subprocess(self, *args, **kw): cmd_args = (sys.executable, '-c') + args return subprocess.Popen(cmd_args, **kw) @unittest.skipUnless(hasattr(signal, "setitimer"), "requires setitimer()") class OSEINTRTest(EINTRBaseTest): """ EINTR tests for the os module. """ def new_sleep_process(self): code = 'import time; time.sleep(%r)' % self.sleep_time return self.subprocess(code) def _test_wait_multiple(self, wait_func): num = 3 processes = [self.new_sleep_process() for _ in range(num)] for _ in range(num): wait_func() # Call the Popen method to avoid a ResourceWarning for proc in processes: proc.wait() def test_wait(self): self._test_wait_multiple(os.wait) @unittest.skipUnless(hasattr(os, 'wait3'), 'requires wait3()') def test_wait3(self): self._test_wait_multiple(lambda: os.wait3(0)) def _test_wait_single(self, wait_func): proc = self.new_sleep_process() wait_func(proc.pid) # Call the Popen method to avoid a ResourceWarning proc.wait() def test_waitpid(self): self._test_wait_single(lambda pid: os.waitpid(pid, 0)) @unittest.skipUnless(hasattr(os, 'wait4'), 'requires wait4()') def test_wait4(self): self._test_wait_single(lambda pid: os.wait4(pid, 0)) def test_read(self): rd, wr = os.pipe() self.addCleanup(os.close, rd) # wr closed explicitly by parent # the payload below are smaller than PIPE_BUF, hence the writes will be # atomic datas = [b"hello", b"world", b"spam"] code = '\n'.join(( 'import os, sys, time', '', 'wr = int(sys.argv[1])', 'datas = %r' % datas, 'sleep_time = %r' % self.sleep_time, '', 'for data in datas:', ' # let the parent block on read()', ' time.sleep(sleep_time)', ' os.write(wr, data)', )) proc = self.subprocess(code, str(wr), pass_fds=[wr]) with kill_on_error(proc): os.close(wr) for data in datas: self.assertEqual(data, os.read(rd, len(data))) self.assertEqual(proc.wait(), 0) def test_write(self): rd, wr = os.pipe() self.addCleanup(os.close, wr) # rd closed explicitly by parent # we must write enough data for the write() to block data = b"x" * support.PIPE_MAX_SIZE code = '\n'.join(( 'import io, os, sys, time', '', 'rd = int(sys.argv[1])', 'sleep_time = %r' % self.sleep_time, 'data = b"x" * %s' % support.PIPE_MAX_SIZE, 'data_len = len(data)', '', '# let the parent block on write()', 'time.sleep(sleep_time)', '', 'read_data = io.BytesIO()', 'while len(read_data.getvalue()) < data_len:', ' chunk = os.read(rd, 2 * data_len)', ' read_data.write(chunk)', '', 'value = read_data.getvalue()', 'if value != data:', ' raise Exception("read error: %s vs %s bytes"', ' % (len(value), data_len))', )) proc = self.subprocess(code, str(rd), pass_fds=[rd]) with kill_on_error(proc): os.close(rd) written = 0 while written < len(data): written += os.write(wr, memoryview(data)[written:]) self.assertEqual(proc.wait(), 0) @unittest.skipUnless(hasattr(signal, "setitimer"), "requires setitimer()") class SocketEINTRTest(EINTRBaseTest): """ EINTR tests for the socket module. """ @unittest.skipUnless(hasattr(socket, 'socketpair'), 'needs socketpair()') def _test_recv(self, recv_func): rd, wr = socket.socketpair() self.addCleanup(rd.close) # wr closed explicitly by parent # single-byte payload guard us against partial recv datas = [b"x", b"y", b"z"] code = '\n'.join(( 'import os, socket, sys, time', '', 'fd = int(sys.argv[1])', 'family = %s' % int(wr.family), 'sock_type = %s' % int(wr.type), 'datas = %r' % datas, 'sleep_time = %r' % self.sleep_time, '', 'wr = socket.fromfd(fd, family, sock_type)', 'os.close(fd)', '', 'with wr:', ' for data in datas:', ' # let the parent block on recv()', ' time.sleep(sleep_time)', ' wr.sendall(data)', )) fd = wr.fileno() proc = self.subprocess(code, str(fd), pass_fds=[fd]) with kill_on_error(proc): wr.close() for data in datas: self.assertEqual(data, recv_func(rd, len(data))) self.assertEqual(proc.wait(), 0) def test_recv(self): self._test_recv(socket.socket.recv) @unittest.skipUnless(hasattr(socket.socket, 'recvmsg'), 'needs recvmsg()') def test_recvmsg(self): self._test_recv(lambda sock, data: sock.recvmsg(data)[0]) def _test_send(self, send_func): rd, wr = socket.socketpair() self.addCleanup(wr.close) # rd closed explicitly by parent # we must send enough data for the send() to block data = b"xyz" * (support.SOCK_MAX_SIZE // 3) code = '\n'.join(( 'import os, socket, sys, time', '', 'fd = int(sys.argv[1])', 'family = %s' % int(rd.family), 'sock_type = %s' % int(rd.type), 'sleep_time = %r' % self.sleep_time, 'data = b"xyz" * %s' % (support.SOCK_MAX_SIZE // 3), 'data_len = len(data)', '', 'rd = socket.fromfd(fd, family, sock_type)', 'os.close(fd)', '', 'with rd:', ' # let the parent block on send()', ' time.sleep(sleep_time)', '', ' received_data = bytearray(data_len)', ' n = 0', ' while n < data_len:', ' n += rd.recv_into(memoryview(received_data)[n:])', '', 'if received_data != data:', ' raise Exception("recv error: %s vs %s bytes"', ' % (len(received_data), data_len))', )) fd = rd.fileno() proc = self.subprocess(code, str(fd), pass_fds=[fd]) with kill_on_error(proc): rd.close() written = 0 while written < len(data): sent = send_func(wr, memoryview(data)[written:]) # sendall() returns None written += len(data) if sent is None else sent self.assertEqual(proc.wait(), 0) def test_send(self): self._test_send(socket.socket.send) def test_sendall(self): self._test_send(socket.socket.sendall) @unittest.skipUnless(hasattr(socket.socket, 'sendmsg'), 'needs sendmsg()') def test_sendmsg(self): self._test_send(lambda sock, data: sock.sendmsg([data])) def test_accept(self): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.addCleanup(sock.close) sock.bind((support.HOST, 0)) port = sock.getsockname()[1] sock.listen() code = '\n'.join(( 'import socket, time', '', 'host = %r' % support.HOST, 'port = %s' % port, 'sleep_time = %r' % self.sleep_time, '', '# let parent block on accept()', 'time.sleep(sleep_time)', 'with socket.create_connection((host, port)):', ' time.sleep(sleep_time)', )) proc = self.subprocess(code) with kill_on_error(proc): client_sock, _ = sock.accept() client_sock.close() self.assertEqual(proc.wait(), 0) # Issue #25122: There is a race condition in the FreeBSD kernel on # handling signals in the FIFO device. Skip the test until the bug is # fixed in the kernel. # https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=203162 @support.requires_freebsd_version(10, 3) @unittest.skipUnless(hasattr(os, 'mkfifo'), 'needs mkfifo()') def _test_open(self, do_open_close_reader, do_open_close_writer): filename = support.TESTFN # Use a fifo: until the child opens it for reading, the parent will # block when trying to open it for writing. support.unlink(filename) try: os.mkfifo(filename) except PermissionError as e: self.skipTest('os.mkfifo(): %s' % e) self.addCleanup(support.unlink, filename) code = '\n'.join(( 'import os, time', '', 'path = %a' % filename, 'sleep_time = %r' % self.sleep_time, '', '# let the parent block', 'time.sleep(sleep_time)', '', do_open_close_reader, )) proc = self.subprocess(code) with kill_on_error(proc): do_open_close_writer(filename) self.assertEqual(proc.wait(), 0) def python_open(self, path): fp = open(path, 'w') fp.close() @unittest.skipIf(sys.platform == "darwin", "hangs under macOS; see bpo-25234, bpo-35363") def test_open(self): self._test_open("fp = open(path, 'r')\nfp.close()", self.python_open) def os_open(self, path): fd = os.open(path, os.O_WRONLY) os.close(fd) @unittest.skipIf(sys.platform == "darwin", "hangs under macOS; see bpo-25234, bpo-35363") def test_os_open(self): self._test_open("fd = os.open(path, os.O_RDONLY)\nos.close(fd)", self.os_open) @unittest.skipUnless(hasattr(signal, "setitimer"), "requires setitimer()") class TimeEINTRTest(EINTRBaseTest): """ EINTR tests for the time module. """ def test_sleep(self): t0 = time.monotonic() time.sleep(self.sleep_time) self.stop_alarm() dt = time.monotonic() - t0 self.assertGreaterEqual(dt, self.sleep_time) @unittest.skipUnless(hasattr(signal, "setitimer"), "requires setitimer()") # bpo-30320: Need pthread_sigmask() to block the signal, otherwise the test # is vulnerable to a race condition between the child and the parent processes. @unittest.skipUnless(hasattr(signal, 'pthread_sigmask'), 'need signal.pthread_sigmask()') class SignalEINTRTest(EINTRBaseTest): """ EINTR tests for the signal module. """ def check_sigwait(self, wait_func): signum = signal.SIGUSR1 pid = os.getpid() old_handler = signal.signal(signum, lambda *args: None) self.addCleanup(signal.signal, signum, old_handler) code = '\n'.join(( 'import os, time', 'pid = %s' % os.getpid(), 'signum = %s' % int(signum), 'sleep_time = %r' % self.sleep_time, 'time.sleep(sleep_time)', 'os.kill(pid, signum)', )) old_mask = signal.pthread_sigmask(signal.SIG_BLOCK, [signum]) self.addCleanup(signal.pthread_sigmask, signal.SIG_UNBLOCK, [signum]) t0 = time.monotonic() proc = self.subprocess(code) with kill_on_error(proc): wait_func(signum) dt = time.monotonic() - t0 self.assertEqual(proc.wait(), 0) @unittest.skipUnless(hasattr(signal, 'sigwaitinfo'), 'need signal.sigwaitinfo()') def test_sigwaitinfo(self): def wait_func(signum): signal.sigwaitinfo([signum]) self.check_sigwait(wait_func) @unittest.skipUnless(hasattr(signal, 'sigtimedwait'), 'need signal.sigwaitinfo()') def test_sigtimedwait(self): def wait_func(signum): signal.sigtimedwait([signum], 120.0) self.check_sigwait(wait_func) @unittest.skipUnless(hasattr(signal, "setitimer"), "requires setitimer()") class SelectEINTRTest(EINTRBaseTest): """ EINTR tests for the select module. """ def test_select(self): t0 = time.monotonic() select.select([], [], [], self.sleep_time) dt = time.monotonic() - t0 self.stop_alarm() self.assertGreaterEqual(dt, self.sleep_time) @unittest.skipIf(sys.platform == "darwin", "poll may fail on macOS; see issue #28087") @unittest.skipUnless(hasattr(select, 'poll'), 'need select.poll') def test_poll(self): poller = select.poll() t0 = time.monotonic() poller.poll(self.sleep_time * 1e3) dt = time.monotonic() - t0 self.stop_alarm() self.assertGreaterEqual(dt, self.sleep_time) @unittest.skipUnless(hasattr(select, 'epoll'), 'need select.epoll') def test_epoll(self): poller = select.epoll() self.addCleanup(poller.close) t0 = time.monotonic() poller.poll(self.sleep_time) dt = time.monotonic() - t0 self.stop_alarm() self.assertGreaterEqual(dt, self.sleep_time) @unittest.skipUnless(hasattr(select, 'kqueue'), 'need select.kqueue') def test_kqueue(self): kqueue = select.kqueue() self.addCleanup(kqueue.close) t0 = time.monotonic() kqueue.control(None, 1, self.sleep_time) dt = time.monotonic() - t0 self.stop_alarm() self.assertGreaterEqual(dt, self.sleep_time) @unittest.skipUnless(hasattr(select, 'devpoll'), 'need select.devpoll') def test_devpoll(self): poller = select.devpoll() self.addCleanup(poller.close) t0 = time.monotonic() poller.poll(self.sleep_time * 1e3) dt = time.monotonic() - t0 self.stop_alarm() self.assertGreaterEqual(dt, self.sleep_time) class FNTLEINTRTest(EINTRBaseTest): def _lock(self, lock_func, lock_name): self.addCleanup(support.unlink, support.TESTFN) code = '\n'.join(( "import fcntl, time", "with open('%s', 'wb') as f:" % support.TESTFN, " fcntl.%s(f, fcntl.LOCK_EX)" % lock_name, " time.sleep(%s)" % self.sleep_time)) start_time = time.monotonic() proc = self.subprocess(code) with kill_on_error(proc): with open(support.TESTFN, 'wb') as f: while True: # synchronize the subprocess dt = time.monotonic() - start_time if dt > 60.0: raise Exception("failed to sync child in %.1f sec" % dt) try: lock_func(f, fcntl.LOCK_EX | fcntl.LOCK_NB) lock_func(f, fcntl.LOCK_UN) time.sleep(0.01) except BlockingIOError: break # the child locked the file just a moment ago for 'sleep_time' seconds # that means that the lock below will block for 'sleep_time' minus some # potential context switch delay lock_func(f, fcntl.LOCK_EX) dt = time.monotonic() - start_time self.assertGreaterEqual(dt, self.sleep_time) self.stop_alarm() proc.wait() def test_lockf(self): self._lock(fcntl.lockf, "lockf") def test_flock(self): self._lock(fcntl.flock, "flock") if __name__ == "__main__": unittest.main()
17,948
530
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/capath/5ed36f99.0
-----BEGIN CERTIFICATE----- MIIHPTCCBSWgAwIBAgIBADANBgkqhkiG9w0BAQQFADB5MRAwDgYDVQQKEwdSb290 IENBMR4wHAYDVQQLExVodHRwOi8vd3d3LmNhY2VydC5vcmcxIjAgBgNVBAMTGUNB IENlcnQgU2lnbmluZyBBdXRob3JpdHkxITAfBgkqhkiG9w0BCQEWEnN1cHBvcnRA Y2FjZXJ0Lm9yZzAeFw0wMzAzMzAxMjI5NDlaFw0zMzAzMjkxMjI5NDlaMHkxEDAO BgNVBAoTB1Jvb3QgQ0ExHjAcBgNVBAsTFWh0dHA6Ly93d3cuY2FjZXJ0Lm9yZzEi MCAGA1UEAxMZQ0EgQ2VydCBTaWduaW5nIEF1dGhvcml0eTEhMB8GCSqGSIb3DQEJ ARYSc3VwcG9ydEBjYWNlcnQub3JnMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIIC CgKCAgEAziLA4kZ97DYoB1CW8qAzQIxL8TtmPzHlawI229Z89vGIj053NgVBlfkJ 8BLPRoZzYLdufujAWGSuzbCtRRcMY/pnCujW0r8+55jE8Ez64AO7NV1sId6eINm6 zWYyN3L69wj1x81YyY7nDl7qPv4coRQKFWyGhFtkZip6qUtTefWIonvuLwphK42y fk1WpRPs6tqSnqxEQR5YYGUFZvjARL3LlPdCfgv3ZWiYUQXw8wWRBB0bF4LsyFe7 w2t6iPGwcswlWyCR7BYCEo8y6RcYSNDHBS4CMEK4JZwFaz+qOqfrU0j36NK2B5jc G8Y0f3/JHIJ6BVgrCFvzOKKrF11myZjXnhCLotLddJr3cQxyYN/Nb5gznZY0dj4k epKwDpUeb+agRThHqtdB7Uq3EvbXG4OKDy7YCbZZ16oE/9KTfWgu3YtLq1i6L43q laegw1SJpfvbi1EinbLDvhG+LJGGi5Z4rSDTii8aP8bQUWWHIbEZAWV/RRyH9XzQ QUxPKZgh/TMfdQwEUfoZd9vUFBzugcMd9Zi3aQaRIt0AUMyBMawSB3s42mhb5ivU fslfrejrckzzAeVLIL+aplfKkQABi6F1ITe1Yw1nPkZPcCBnzsXWWdsC4PDSy826 YreQQejdIOQpvGQpQsgi3Hia/0PsmBsJUUtaWsJx8cTLc6nloQsCAwEAAaOCAc4w ggHKMB0GA1UdDgQWBBQWtTIb1Mfz4OaO873SsDrusjkY0TCBowYDVR0jBIGbMIGY gBQWtTIb1Mfz4OaO873SsDrusjkY0aF9pHsweTEQMA4GA1UEChMHUm9vdCBDQTEe MBwGA1UECxMVaHR0cDovL3d3dy5jYWNlcnQub3JnMSIwIAYDVQQDExlDQSBDZXJ0 IFNpZ25pbmcgQXV0aG9yaXR5MSEwHwYJKoZIhvcNAQkBFhJzdXBwb3J0QGNhY2Vy dC5vcmeCAQAwDwYDVR0TAQH/BAUwAwEB/zAyBgNVHR8EKzApMCegJaAjhiFodHRw czovL3d3dy5jYWNlcnQub3JnL3Jldm9rZS5jcmwwMAYJYIZIAYb4QgEEBCMWIWh0 dHBzOi8vd3d3LmNhY2VydC5vcmcvcmV2b2tlLmNybDA0BglghkgBhvhCAQgEJxYl aHR0cDovL3d3dy5jYWNlcnQub3JnL2luZGV4LnBocD9pZD0xMDBWBglghkgBhvhC AQ0ESRZHVG8gZ2V0IHlvdXIgb3duIGNlcnRpZmljYXRlIGZvciBGUkVFIGhlYWQg b3ZlciB0byBodHRwOi8vd3d3LmNhY2VydC5vcmcwDQYJKoZIhvcNAQEEBQADggIB ACjH7pyCArpcgBLKNQodgW+JapnM8mgPf6fhjViVPr3yBsOQWqy1YPaZQwGjiHCc nWKdpIevZ1gNMDY75q1I08t0AoZxPuIrA2jxNGJARjtT6ij0rPtmlVOKTV39O9lg 18p5aTuxZZKmxoGCXJzN600BiqXfEVWqFcofN8CCmHBh22p8lqOOLlQ+TyGpkO/c gr/c6EWtTZBzCDyUZbAEmXZ/4rzCahWqlwQ3JNgelE5tDlG+1sSPypZt90Pf6DBl Jzt7u0NDY8RD97LsaMzhGY4i+5jhe1o+ATc7iwiwovOVThrLm82asduycPAtStvY sONvRUgzEv/+PDIqVPfE94rwiCPCR/5kenHA0R6mY7AHfqQv0wGP3J8rtsYIqQ+T SCX8Ev2fQtzzxD72V7DX3WnRBnc0CkvSyqD/HMaMyRa+xMwyN2hzXwj7UfdJUzYF CpUCTPJ5GhD22Dp1nPMd8aINcGeGG7MW9S/lpOt5hvk9C8JzC6WZrG/8Z7jlLwum GCSNe9FINSkYQKyTYOGWhlC0elnYjyELn8+CkcY7v2vcB5G5l1YjqrZslMZIBjzk zk6q5PYvCdxTby78dOs6Y5nCpqyJvKeyRKANihDjbPIky/qbn3BHLt4Ui9SyIAmW omTxJBzcoTWcFbLUvFUufQb1nA5V9FrWk9p2rSVzTMVD -----END CERTIFICATE-----
2,569
42
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/capath/6e88d7b8.0
-----BEGIN CERTIFICATE----- MIICLDCCAdYCAQAwDQYJKoZIhvcNAQEEBQAwgaAxCzAJBgNVBAYTAlBUMRMwEQYD VQQIEwpRdWVlbnNsYW5kMQ8wDQYDVQQHEwZMaXNib2ExFzAVBgNVBAoTDk5ldXJv bmlvLCBMZGEuMRgwFgYDVQQLEw9EZXNlbnZvbHZpbWVudG8xGzAZBgNVBAMTEmJy dXR1cy5uZXVyb25pby5wdDEbMBkGCSqGSIb3DQEJARYMc2FtcG9AaWtpLmZpMB4X DTk2MDkwNTAzNDI0M1oXDTk2MTAwNTAzNDI0M1owgaAxCzAJBgNVBAYTAlBUMRMw EQYDVQQIEwpRdWVlbnNsYW5kMQ8wDQYDVQQHEwZMaXNib2ExFzAVBgNVBAoTDk5l dXJvbmlvLCBMZGEuMRgwFgYDVQQLEw9EZXNlbnZvbHZpbWVudG8xGzAZBgNVBAMT EmJydXR1cy5uZXVyb25pby5wdDEbMBkGCSqGSIb3DQEJARYMc2FtcG9AaWtpLmZp MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAL7+aty3S1iBA/+yxjxv4q1MUTd1kjNw L4lYKbpzzlmC5beaQXeQ2RmGMTXU+mDvuqItjVHOK3DvPK7lTcSGftUCAwEAATAN BgkqhkiG9w0BAQQFAANBAFqPEKFjk6T6CKTHvaQeEAsX0/8YHPHqH/9AnhSjrwuX 9EBc0n6bVGhN7XaXd6sJ7dym9sbsWxb+pJdurnkxjx4= -----END CERTIFICATE-----
814
15
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/capath/99d0fa06.0
-----BEGIN CERTIFICATE----- MIIHPTCCBSWgAwIBAgIBADANBgkqhkiG9w0BAQQFADB5MRAwDgYDVQQKEwdSb290 IENBMR4wHAYDVQQLExVodHRwOi8vd3d3LmNhY2VydC5vcmcxIjAgBgNVBAMTGUNB IENlcnQgU2lnbmluZyBBdXRob3JpdHkxITAfBgkqhkiG9w0BCQEWEnN1cHBvcnRA Y2FjZXJ0Lm9yZzAeFw0wMzAzMzAxMjI5NDlaFw0zMzAzMjkxMjI5NDlaMHkxEDAO BgNVBAoTB1Jvb3QgQ0ExHjAcBgNVBAsTFWh0dHA6Ly93d3cuY2FjZXJ0Lm9yZzEi MCAGA1UEAxMZQ0EgQ2VydCBTaWduaW5nIEF1dGhvcml0eTEhMB8GCSqGSIb3DQEJ ARYSc3VwcG9ydEBjYWNlcnQub3JnMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIIC CgKCAgEAziLA4kZ97DYoB1CW8qAzQIxL8TtmPzHlawI229Z89vGIj053NgVBlfkJ 8BLPRoZzYLdufujAWGSuzbCtRRcMY/pnCujW0r8+55jE8Ez64AO7NV1sId6eINm6 zWYyN3L69wj1x81YyY7nDl7qPv4coRQKFWyGhFtkZip6qUtTefWIonvuLwphK42y fk1WpRPs6tqSnqxEQR5YYGUFZvjARL3LlPdCfgv3ZWiYUQXw8wWRBB0bF4LsyFe7 w2t6iPGwcswlWyCR7BYCEo8y6RcYSNDHBS4CMEK4JZwFaz+qOqfrU0j36NK2B5jc G8Y0f3/JHIJ6BVgrCFvzOKKrF11myZjXnhCLotLddJr3cQxyYN/Nb5gznZY0dj4k epKwDpUeb+agRThHqtdB7Uq3EvbXG4OKDy7YCbZZ16oE/9KTfWgu3YtLq1i6L43q laegw1SJpfvbi1EinbLDvhG+LJGGi5Z4rSDTii8aP8bQUWWHIbEZAWV/RRyH9XzQ QUxPKZgh/TMfdQwEUfoZd9vUFBzugcMd9Zi3aQaRIt0AUMyBMawSB3s42mhb5ivU fslfrejrckzzAeVLIL+aplfKkQABi6F1ITe1Yw1nPkZPcCBnzsXWWdsC4PDSy826 YreQQejdIOQpvGQpQsgi3Hia/0PsmBsJUUtaWsJx8cTLc6nloQsCAwEAAaOCAc4w ggHKMB0GA1UdDgQWBBQWtTIb1Mfz4OaO873SsDrusjkY0TCBowYDVR0jBIGbMIGY gBQWtTIb1Mfz4OaO873SsDrusjkY0aF9pHsweTEQMA4GA1UEChMHUm9vdCBDQTEe MBwGA1UECxMVaHR0cDovL3d3dy5jYWNlcnQub3JnMSIwIAYDVQQDExlDQSBDZXJ0 IFNpZ25pbmcgQXV0aG9yaXR5MSEwHwYJKoZIhvcNAQkBFhJzdXBwb3J0QGNhY2Vy dC5vcmeCAQAwDwYDVR0TAQH/BAUwAwEB/zAyBgNVHR8EKzApMCegJaAjhiFodHRw czovL3d3dy5jYWNlcnQub3JnL3Jldm9rZS5jcmwwMAYJYIZIAYb4QgEEBCMWIWh0 dHBzOi8vd3d3LmNhY2VydC5vcmcvcmV2b2tlLmNybDA0BglghkgBhvhCAQgEJxYl aHR0cDovL3d3dy5jYWNlcnQub3JnL2luZGV4LnBocD9pZD0xMDBWBglghkgBhvhC AQ0ESRZHVG8gZ2V0IHlvdXIgb3duIGNlcnRpZmljYXRlIGZvciBGUkVFIGhlYWQg b3ZlciB0byBodHRwOi8vd3d3LmNhY2VydC5vcmcwDQYJKoZIhvcNAQEEBQADggIB ACjH7pyCArpcgBLKNQodgW+JapnM8mgPf6fhjViVPr3yBsOQWqy1YPaZQwGjiHCc nWKdpIevZ1gNMDY75q1I08t0AoZxPuIrA2jxNGJARjtT6ij0rPtmlVOKTV39O9lg 18p5aTuxZZKmxoGCXJzN600BiqXfEVWqFcofN8CCmHBh22p8lqOOLlQ+TyGpkO/c gr/c6EWtTZBzCDyUZbAEmXZ/4rzCahWqlwQ3JNgelE5tDlG+1sSPypZt90Pf6DBl Jzt7u0NDY8RD97LsaMzhGY4i+5jhe1o+ATc7iwiwovOVThrLm82asduycPAtStvY sONvRUgzEv/+PDIqVPfE94rwiCPCR/5kenHA0R6mY7AHfqQv0wGP3J8rtsYIqQ+T SCX8Ev2fQtzzxD72V7DX3WnRBnc0CkvSyqD/HMaMyRa+xMwyN2hzXwj7UfdJUzYF CpUCTPJ5GhD22Dp1nPMd8aINcGeGG7MW9S/lpOt5hvk9C8JzC6WZrG/8Z7jlLwum GCSNe9FINSkYQKyTYOGWhlC0elnYjyELn8+CkcY7v2vcB5G5l1YjqrZslMZIBjzk zk6q5PYvCdxTby78dOs6Y5nCpqyJvKeyRKANihDjbPIky/qbn3BHLt4Ui9SyIAmW omTxJBzcoTWcFbLUvFUufQb1nA5V9FrWk9p2rSVzTMVD -----END CERTIFICATE-----
2,569
42
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/capath/4e1295a3.0
-----BEGIN CERTIFICATE----- MIICLDCCAdYCAQAwDQYJKoZIhvcNAQEEBQAwgaAxCzAJBgNVBAYTAlBUMRMwEQYD VQQIEwpRdWVlbnNsYW5kMQ8wDQYDVQQHEwZMaXNib2ExFzAVBgNVBAoTDk5ldXJv bmlvLCBMZGEuMRgwFgYDVQQLEw9EZXNlbnZvbHZpbWVudG8xGzAZBgNVBAMTEmJy dXR1cy5uZXVyb25pby5wdDEbMBkGCSqGSIb3DQEJARYMc2FtcG9AaWtpLmZpMB4X DTk2MDkwNTAzNDI0M1oXDTk2MTAwNTAzNDI0M1owgaAxCzAJBgNVBAYTAlBUMRMw EQYDVQQIEwpRdWVlbnNsYW5kMQ8wDQYDVQQHEwZMaXNib2ExFzAVBgNVBAoTDk5l dXJvbmlvLCBMZGEuMRgwFgYDVQQLEw9EZXNlbnZvbHZpbWVudG8xGzAZBgNVBAMT EmJydXR1cy5uZXVyb25pby5wdDEbMBkGCSqGSIb3DQEJARYMc2FtcG9AaWtpLmZp MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAL7+aty3S1iBA/+yxjxv4q1MUTd1kjNw L4lYKbpzzlmC5beaQXeQ2RmGMTXU+mDvuqItjVHOK3DvPK7lTcSGftUCAwEAATAN BgkqhkiG9w0BAQQFAANBAFqPEKFjk6T6CKTHvaQeEAsX0/8YHPHqH/9AnhSjrwuX 9EBc0n6bVGhN7XaXd6sJ7dym9sbsWxb+pJdurnkxjx4= -----END CERTIFICATE-----
814
15
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/capath/ceff1710.0
-----BEGIN CERTIFICATE----- MIIEbTCCAtWgAwIBAgIJAMstgJlaaVJbMA0GCSqGSIb3DQEBCwUAME0xCzAJBgNV BAYTAlhZMSYwJAYDVQQKDB1QeXRob24gU29mdHdhcmUgRm91bmRhdGlvbiBDQTEW MBQGA1UEAwwNb3VyLWNhLXNlcnZlcjAeFw0xODA4MjkxNDIzMTZaFw0yODA4MjYx NDIzMTZaME0xCzAJBgNVBAYTAlhZMSYwJAYDVQQKDB1QeXRob24gU29mdHdhcmUg Rm91bmRhdGlvbiBDQTEWMBQGA1UEAwwNb3VyLWNhLXNlcnZlcjCCAaIwDQYJKoZI hvcNAQEBBQADggGPADCCAYoCggGBAJftVUG6NheV23Ec0+FhrFhz48aWzysfuAj1 nUtLxzD2uAuzUnKgu8lNO47fIo4BV4HJknPMAMbscLA6F0DB3/KMNkzEp4HntiRo 4qB+NQcvoFv5RUb3HvBGEf7KGjxQ8SapX5winPhB4d9PEpUZL1yQARdufj59z+kJ ryX4+EJ3LW1fNvJ4Hn1Kh2hjbAZxG436Jf7U0/WlF7Hv6hfLVMgnmYDLPEXxLFIc 3R9RRSBQHl6rV3MbQXiW3oSket2PMIU2WHl2oNJhyBuplJljxu74FL+0UlYxl/rr rFOelc5MxFpKt8oDJ1s1V84C3OzKafiKWjnLFiAVAyRhbPR6/LZI5VkQXEnQI5/7 cV466WifNHKAJ7Y/TLHZ22N/Z2hKbhH46MD0WhY5Uwto3nf6Ref4kc14zSiUl3FU +8/wN97JJsXcG56JbQmsyERxy23xlzHVTCAzv3VKoODcaRHtKrRkEBEwiw6wpxDY isWqG8gmiiXnZp+lahovfF+DxnhPHwIDAQABo1AwTjAdBgNVHQ4EFgQU3b/K2ubR NLo3dSHKb5oIKPI1tkgwHwYDVR0jBBgwFoAU3b/K2ubRNLo3dSHKb5oIKPI1tkgw DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAYEAM2pU02vA1wFfnfQFwZNm kFDQtxjpsB5KoLbadpOvhNutFVQxFRPk3n5ODNUJHDQ1tuVM1m9lfTJf6/ypawf3 SYLlgX4HgJpj+CzDQLyP1CraPtHuCLdNp4TK9D+hmEW+sQVp59/Xmasb7oswzPf8 59QLF66Xv+R7/Q+ntIV541niFoe/HylFLCOTdr7Ahx3e7CtCauW7yPQKSggKjFzY fU3RuL/V9yntktGUBOg1Bld/LCOXh6U1jSbTGkfyFtfZxtQfI0PTJpk5yiD0cSNv DEp2dvd2H7P+v0ew/CpWgeHS3e4I2PT/WtwlYYqRArmGHPJQc3YlNfy2JSYVy+vE K2EMHOfuLxeb7PDUoYTn0q/e5BskFKcBh+OrKVhGoNnACuCN11nTG/hUID54paXI T4sDxJaf7PtHz3YtjWU0J7/6rgEFivOSCt2JbJehx+dgUees60t9LLhlyf5dakhV juTH+WpA4bhkRem1WSmlX899WH1keeWkCawedmU9lMRo -----END CERTIFICATE-----
1,594
27
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/capath/b1930218.0
-----BEGIN CERTIFICATE----- MIIEbTCCAtWgAwIBAgIJAMstgJlaaVJbMA0GCSqGSIb3DQEBCwUAME0xCzAJBgNV BAYTAlhZMSYwJAYDVQQKDB1QeXRob24gU29mdHdhcmUgRm91bmRhdGlvbiBDQTEW MBQGA1UEAwwNb3VyLWNhLXNlcnZlcjAeFw0xODA4MjkxNDIzMTZaFw0yODA4MjYx NDIzMTZaME0xCzAJBgNVBAYTAlhZMSYwJAYDVQQKDB1QeXRob24gU29mdHdhcmUg Rm91bmRhdGlvbiBDQTEWMBQGA1UEAwwNb3VyLWNhLXNlcnZlcjCCAaIwDQYJKoZI hvcNAQEBBQADggGPADCCAYoCggGBAJftVUG6NheV23Ec0+FhrFhz48aWzysfuAj1 nUtLxzD2uAuzUnKgu8lNO47fIo4BV4HJknPMAMbscLA6F0DB3/KMNkzEp4HntiRo 4qB+NQcvoFv5RUb3HvBGEf7KGjxQ8SapX5winPhB4d9PEpUZL1yQARdufj59z+kJ ryX4+EJ3LW1fNvJ4Hn1Kh2hjbAZxG436Jf7U0/WlF7Hv6hfLVMgnmYDLPEXxLFIc 3R9RRSBQHl6rV3MbQXiW3oSket2PMIU2WHl2oNJhyBuplJljxu74FL+0UlYxl/rr rFOelc5MxFpKt8oDJ1s1V84C3OzKafiKWjnLFiAVAyRhbPR6/LZI5VkQXEnQI5/7 cV466WifNHKAJ7Y/TLHZ22N/Z2hKbhH46MD0WhY5Uwto3nf6Ref4kc14zSiUl3FU +8/wN97JJsXcG56JbQmsyERxy23xlzHVTCAzv3VKoODcaRHtKrRkEBEwiw6wpxDY isWqG8gmiiXnZp+lahovfF+DxnhPHwIDAQABo1AwTjAdBgNVHQ4EFgQU3b/K2ubR NLo3dSHKb5oIKPI1tkgwHwYDVR0jBBgwFoAU3b/K2ubRNLo3dSHKb5oIKPI1tkgw DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAYEAM2pU02vA1wFfnfQFwZNm kFDQtxjpsB5KoLbadpOvhNutFVQxFRPk3n5ODNUJHDQ1tuVM1m9lfTJf6/ypawf3 SYLlgX4HgJpj+CzDQLyP1CraPtHuCLdNp4TK9D+hmEW+sQVp59/Xmasb7oswzPf8 59QLF66Xv+R7/Q+ntIV541niFoe/HylFLCOTdr7Ahx3e7CtCauW7yPQKSggKjFzY fU3RuL/V9yntktGUBOg1Bld/LCOXh6U1jSbTGkfyFtfZxtQfI0PTJpk5yiD0cSNv DEp2dvd2H7P+v0ew/CpWgeHS3e4I2PT/WtwlYYqRArmGHPJQc3YlNfy2JSYVy+vE K2EMHOfuLxeb7PDUoYTn0q/e5BskFKcBh+OrKVhGoNnACuCN11nTG/hUID54paXI T4sDxJaf7PtHz3YtjWU0J7/6rgEFivOSCt2JbJehx+dgUees60t9LLhlyf5dakhV juTH+WpA4bhkRem1WSmlX899WH1keeWkCawedmU9lMRo -----END CERTIFICATE-----
1,594
27
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/sndhdrdata/sndhdr.8svx
FORMf8SVXVHDR¬DANNO File created by Sound Exchange CHANBODY ÿÿ
110
2
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/sndhdrdata/sndhdr.wav
RIFF8WAVEfmt D±data
64
1
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/sndhdrdata/README
Sound file samples used by Lib/test/test_sndhdr.py and generated using the following commands: dd if=/dev/zero of=sndhdr.raw bs=20 count=1 sox -s -2 -c 2 -r 44100 sndhdr.raw sndhdr.<format>
197
6
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/sndhdrdata/sndhdr.aiff
FORMdAIFFCOMTÈb7ÍProcessed by SoXCOMM@¬DSSND
108
1
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/sndhdrdata/sndhdr.sndt
SOUNDD¬ Processed by SoX€€€
129
2
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/sndhdrdata/sndhdr.hcom
AFSSDHCOMÿÿ€
256
1
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/sndhdrdata/sndhdr.au
.snd,¬DProcessed by SoX
64
1
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/sndhdrdata/sndhdr.voc
Creative Voice File ) D¬
63
2
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/sndhdrdata/sndhdr.aifc
FORMbAIFCFVER¢€Q@COMM&@¬DNONEnot compressedSSND
106
1
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_asyncio/test_queues.py
"""Tests for queues.py""" import unittest from unittest import mock import asyncio from asyncio import test_utils class _QueueTestBase(test_utils.TestCase): def setUp(self): super().setUp() self.loop = self.new_test_loop() class QueueBasicTests(_QueueTestBase): def _test_repr_or_str(self, fn, expect_id): """Test Queue's repr or str. fn is repr or str. expect_id is True if we expect the Queue's id to appear in fn(Queue()). """ def gen(): when = yield self.assertAlmostEqual(0.1, when) when = yield 0.1 self.assertAlmostEqual(0.2, when) yield 0.1 loop = self.new_test_loop(gen) q = asyncio.Queue(loop=loop) self.assertTrue(fn(q).startswith('<Queue'), fn(q)) id_is_present = hex(id(q)) in fn(q) self.assertEqual(expect_id, id_is_present) @asyncio.coroutine def add_getter(): q = asyncio.Queue(loop=loop) # Start a task that waits to get. asyncio.Task(q.get(), loop=loop) # Let it start waiting. yield from asyncio.sleep(0.1, loop=loop) self.assertTrue('_getters[1]' in fn(q)) # resume q.get coroutine to finish generator q.put_nowait(0) loop.run_until_complete(add_getter()) @asyncio.coroutine def add_putter(): q = asyncio.Queue(maxsize=1, loop=loop) q.put_nowait(1) # Start a task that waits to put. asyncio.Task(q.put(2), loop=loop) # Let it start waiting. yield from asyncio.sleep(0.1, loop=loop) self.assertTrue('_putters[1]' in fn(q)) # resume q.put coroutine to finish generator q.get_nowait() loop.run_until_complete(add_putter()) q = asyncio.Queue(loop=loop) q.put_nowait(1) self.assertTrue('_queue=[1]' in fn(q)) def test_ctor_loop(self): loop = mock.Mock() q = asyncio.Queue(loop=loop) self.assertIs(q._loop, loop) q = asyncio.Queue(loop=self.loop) self.assertIs(q._loop, self.loop) def test_ctor_noloop(self): asyncio.set_event_loop(self.loop) q = asyncio.Queue() self.assertIs(q._loop, self.loop) def test_repr(self): self._test_repr_or_str(repr, True) def test_str(self): self._test_repr_or_str(str, False) def test_empty(self): q = asyncio.Queue(loop=self.loop) self.assertTrue(q.empty()) q.put_nowait(1) self.assertFalse(q.empty()) self.assertEqual(1, q.get_nowait()) self.assertTrue(q.empty()) def test_full(self): q = asyncio.Queue(loop=self.loop) self.assertFalse(q.full()) q = asyncio.Queue(maxsize=1, loop=self.loop) q.put_nowait(1) self.assertTrue(q.full()) def test_order(self): q = asyncio.Queue(loop=self.loop) for i in [1, 3, 2]: q.put_nowait(i) items = [q.get_nowait() for _ in range(3)] self.assertEqual([1, 3, 2], items) def test_maxsize(self): def gen(): when = yield self.assertAlmostEqual(0.01, when) when = yield 0.01 self.assertAlmostEqual(0.02, when) yield 0.01 loop = self.new_test_loop(gen) q = asyncio.Queue(maxsize=2, loop=loop) self.assertEqual(2, q.maxsize) have_been_put = [] @asyncio.coroutine def putter(): for i in range(3): yield from q.put(i) have_been_put.append(i) return True @asyncio.coroutine def test(): t = asyncio.Task(putter(), loop=loop) yield from asyncio.sleep(0.01, loop=loop) # The putter is blocked after putting two items. self.assertEqual([0, 1], have_been_put) self.assertEqual(0, q.get_nowait()) # Let the putter resume and put last item. yield from asyncio.sleep(0.01, loop=loop) self.assertEqual([0, 1, 2], have_been_put) self.assertEqual(1, q.get_nowait()) self.assertEqual(2, q.get_nowait()) self.assertTrue(t.done()) self.assertTrue(t.result()) loop.run_until_complete(test()) self.assertAlmostEqual(0.02, loop.time()) class QueueGetTests(_QueueTestBase): def test_blocking_get(self): q = asyncio.Queue(loop=self.loop) q.put_nowait(1) @asyncio.coroutine def queue_get(): return (yield from q.get()) res = self.loop.run_until_complete(queue_get()) self.assertEqual(1, res) def test_get_with_putters(self): q = asyncio.Queue(1, loop=self.loop) q.put_nowait(1) waiter = asyncio.Future(loop=self.loop) q._putters.append(waiter) res = self.loop.run_until_complete(q.get()) self.assertEqual(1, res) self.assertTrue(waiter.done()) self.assertIsNone(waiter.result()) def test_blocking_get_wait(self): def gen(): when = yield self.assertAlmostEqual(0.01, when) yield 0.01 loop = self.new_test_loop(gen) q = asyncio.Queue(loop=loop) started = asyncio.Event(loop=loop) finished = False @asyncio.coroutine def queue_get(): nonlocal finished started.set() res = yield from q.get() finished = True return res @asyncio.coroutine def queue_put(): loop.call_later(0.01, q.put_nowait, 1) queue_get_task = asyncio.Task(queue_get(), loop=loop) yield from started.wait() self.assertFalse(finished) res = yield from queue_get_task self.assertTrue(finished) return res res = loop.run_until_complete(queue_put()) self.assertEqual(1, res) self.assertAlmostEqual(0.01, loop.time()) def test_nonblocking_get(self): q = asyncio.Queue(loop=self.loop) q.put_nowait(1) self.assertEqual(1, q.get_nowait()) def test_nonblocking_get_exception(self): q = asyncio.Queue(loop=self.loop) self.assertRaises(asyncio.QueueEmpty, q.get_nowait) def test_get_cancelled(self): def gen(): when = yield self.assertAlmostEqual(0.01, when) when = yield 0.01 self.assertAlmostEqual(0.061, when) yield 0.05 loop = self.new_test_loop(gen) q = asyncio.Queue(loop=loop) @asyncio.coroutine def queue_get(): return (yield from asyncio.wait_for(q.get(), 0.051, loop=loop)) @asyncio.coroutine def test(): get_task = asyncio.Task(queue_get(), loop=loop) yield from asyncio.sleep(0.01, loop=loop) # let the task start q.put_nowait(1) return (yield from get_task) self.assertEqual(1, loop.run_until_complete(test())) self.assertAlmostEqual(0.06, loop.time()) def test_get_cancelled_race(self): q = asyncio.Queue(loop=self.loop) t1 = asyncio.Task(q.get(), loop=self.loop) t2 = asyncio.Task(q.get(), loop=self.loop) test_utils.run_briefly(self.loop) t1.cancel() test_utils.run_briefly(self.loop) self.assertTrue(t1.done()) q.put_nowait('a') test_utils.run_briefly(self.loop) self.assertEqual(t2.result(), 'a') def test_get_with_waiting_putters(self): q = asyncio.Queue(loop=self.loop, maxsize=1) asyncio.Task(q.put('a'), loop=self.loop) asyncio.Task(q.put('b'), loop=self.loop) test_utils.run_briefly(self.loop) self.assertEqual(self.loop.run_until_complete(q.get()), 'a') self.assertEqual(self.loop.run_until_complete(q.get()), 'b') def test_why_are_getters_waiting(self): # From issue #268. @asyncio.coroutine def consumer(queue, num_expected): for _ in range(num_expected): yield from queue.get() @asyncio.coroutine def producer(queue, num_items): for i in range(num_items): yield from queue.put(i) queue_size = 1 producer_num_items = 5 q = asyncio.Queue(queue_size, loop=self.loop) self.loop.run_until_complete( asyncio.gather(producer(q, producer_num_items), consumer(q, producer_num_items), loop=self.loop), ) def test_cancelled_getters_not_being_held_in_self_getters(self): def a_generator(): yield 0.1 yield 0.2 self.loop = self.new_test_loop(a_generator) @asyncio.coroutine def consumer(queue): try: item = yield from asyncio.wait_for(queue.get(), 0.1, loop=self.loop) except asyncio.TimeoutError: pass queue = asyncio.Queue(loop=self.loop, maxsize=5) self.loop.run_until_complete(self.loop.create_task(consumer(queue))) self.assertEqual(len(queue._getters), 0) class QueuePutTests(_QueueTestBase): def test_blocking_put(self): q = asyncio.Queue(loop=self.loop) @asyncio.coroutine def queue_put(): # No maxsize, won't block. yield from q.put(1) self.loop.run_until_complete(queue_put()) def test_blocking_put_wait(self): def gen(): when = yield self.assertAlmostEqual(0.01, when) yield 0.01 loop = self.new_test_loop(gen) q = asyncio.Queue(maxsize=1, loop=loop) started = asyncio.Event(loop=loop) finished = False @asyncio.coroutine def queue_put(): nonlocal finished started.set() yield from q.put(1) yield from q.put(2) finished = True @asyncio.coroutine def queue_get(): loop.call_later(0.01, q.get_nowait) queue_put_task = asyncio.Task(queue_put(), loop=loop) yield from started.wait() self.assertFalse(finished) yield from queue_put_task self.assertTrue(finished) loop.run_until_complete(queue_get()) self.assertAlmostEqual(0.01, loop.time()) def test_nonblocking_put(self): q = asyncio.Queue(loop=self.loop) q.put_nowait(1) self.assertEqual(1, q.get_nowait()) def test_get_cancel_drop_one_pending_reader(self): def gen(): yield 0.01 yield 0.1 loop = self.new_test_loop(gen) q = asyncio.Queue(loop=loop) reader = loop.create_task(q.get()) loop.run_until_complete(asyncio.sleep(0.01, loop=loop)) q.put_nowait(1) q.put_nowait(2) reader.cancel() try: loop.run_until_complete(reader) except asyncio.CancelledError: # try again reader = loop.create_task(q.get()) loop.run_until_complete(reader) result = reader.result() # if we get 2, it means 1 got dropped! self.assertEqual(1, result) def test_get_cancel_drop_many_pending_readers(self): def gen(): yield 0.01 yield 0.1 loop = self.new_test_loop(gen) loop.set_debug(True) q = asyncio.Queue(loop=loop) reader1 = loop.create_task(q.get()) reader2 = loop.create_task(q.get()) reader3 = loop.create_task(q.get()) loop.run_until_complete(asyncio.sleep(0.01, loop=loop)) q.put_nowait(1) q.put_nowait(2) reader1.cancel() try: loop.run_until_complete(reader1) except asyncio.CancelledError: pass loop.run_until_complete(reader3) # It is undefined in which order concurrent readers receive results. self.assertEqual({reader2.result(), reader3.result()}, {1, 2}) def test_put_cancel_drop(self): def gen(): yield 0.01 yield 0.1 loop = self.new_test_loop(gen) q = asyncio.Queue(1, loop=loop) q.put_nowait(1) # putting a second item in the queue has to block (qsize=1) writer = loop.create_task(q.put(2)) loop.run_until_complete(asyncio.sleep(0.01, loop=loop)) value1 = q.get_nowait() self.assertEqual(value1, 1) writer.cancel() try: loop.run_until_complete(writer) except asyncio.CancelledError: # try again writer = loop.create_task(q.put(2)) loop.run_until_complete(writer) value2 = q.get_nowait() self.assertEqual(value2, 2) self.assertEqual(q.qsize(), 0) def test_nonblocking_put_exception(self): q = asyncio.Queue(maxsize=1, loop=self.loop) q.put_nowait(1) self.assertRaises(asyncio.QueueFull, q.put_nowait, 2) def test_float_maxsize(self): q = asyncio.Queue(maxsize=1.3, loop=self.loop) q.put_nowait(1) q.put_nowait(2) self.assertTrue(q.full()) self.assertRaises(asyncio.QueueFull, q.put_nowait, 3) q = asyncio.Queue(maxsize=1.3, loop=self.loop) @asyncio.coroutine def queue_put(): yield from q.put(1) yield from q.put(2) self.assertTrue(q.full()) self.loop.run_until_complete(queue_put()) def test_put_cancelled(self): q = asyncio.Queue(loop=self.loop) @asyncio.coroutine def queue_put(): yield from q.put(1) return True @asyncio.coroutine def test(): return (yield from q.get()) t = asyncio.Task(queue_put(), loop=self.loop) self.assertEqual(1, self.loop.run_until_complete(test())) self.assertTrue(t.done()) self.assertTrue(t.result()) def test_put_cancelled_race(self): q = asyncio.Queue(loop=self.loop, maxsize=1) put_a = asyncio.Task(q.put('a'), loop=self.loop) put_b = asyncio.Task(q.put('b'), loop=self.loop) put_c = asyncio.Task(q.put('X'), loop=self.loop) test_utils.run_briefly(self.loop) self.assertTrue(put_a.done()) self.assertFalse(put_b.done()) put_c.cancel() test_utils.run_briefly(self.loop) self.assertTrue(put_c.done()) self.assertEqual(q.get_nowait(), 'a') test_utils.run_briefly(self.loop) self.assertEqual(q.get_nowait(), 'b') self.loop.run_until_complete(put_b) def test_put_with_waiting_getters(self): q = asyncio.Queue(loop=self.loop) t = asyncio.Task(q.get(), loop=self.loop) test_utils.run_briefly(self.loop) self.loop.run_until_complete(q.put('a')) self.assertEqual(self.loop.run_until_complete(t), 'a') def test_why_are_putters_waiting(self): # From issue #265. queue = asyncio.Queue(2, loop=self.loop) @asyncio.coroutine def putter(item): yield from queue.put(item) @asyncio.coroutine def getter(): yield num = queue.qsize() for _ in range(num): item = queue.get_nowait() t0 = putter(0) t1 = putter(1) t2 = putter(2) t3 = putter(3) self.loop.run_until_complete( asyncio.gather(getter(), t0, t1, t2, t3, loop=self.loop)) class LifoQueueTests(_QueueTestBase): def test_order(self): q = asyncio.LifoQueue(loop=self.loop) for i in [1, 3, 2]: q.put_nowait(i) items = [q.get_nowait() for _ in range(3)] self.assertEqual([2, 3, 1], items) class PriorityQueueTests(_QueueTestBase): def test_order(self): q = asyncio.PriorityQueue(loop=self.loop) for i in [1, 3, 2]: q.put_nowait(i) items = [q.get_nowait() for _ in range(3)] self.assertEqual([1, 2, 3], items) class _QueueJoinTestMixin: q_class = None def test_task_done_underflow(self): q = self.q_class(loop=self.loop) self.assertRaises(ValueError, q.task_done) def test_task_done(self): q = self.q_class(loop=self.loop) for i in range(100): q.put_nowait(i) accumulator = 0 # Two workers get items from the queue and call task_done after each. # Join the queue and assert all items have been processed. running = True @asyncio.coroutine def worker(): nonlocal accumulator while running: item = yield from q.get() accumulator += item q.task_done() @asyncio.coroutine def test(): tasks = [asyncio.Task(worker(), loop=self.loop) for index in range(2)] yield from q.join() return tasks tasks = self.loop.run_until_complete(test()) self.assertEqual(sum(range(100)), accumulator) # close running generators running = False for i in range(len(tasks)): q.put_nowait(0) self.loop.run_until_complete(asyncio.wait(tasks, loop=self.loop)) def test_join_empty_queue(self): q = self.q_class(loop=self.loop) # Test that a queue join()s successfully, and before anything else # (done twice for insurance). @asyncio.coroutine def join(): yield from q.join() yield from q.join() self.loop.run_until_complete(join()) def test_format(self): q = self.q_class(loop=self.loop) self.assertEqual(q._format(), 'maxsize=0') q._unfinished_tasks = 2 self.assertEqual(q._format(), 'maxsize=0 tasks=2') class QueueJoinTests(_QueueJoinTestMixin, _QueueTestBase): q_class = asyncio.Queue class LifoQueueJoinTests(_QueueJoinTestMixin, _QueueTestBase): q_class = asyncio.LifoQueue class PriorityQueueJoinTests(_QueueJoinTestMixin, _QueueTestBase): q_class = asyncio.PriorityQueue if __name__ == '__main__': unittest.main()
18,382
644
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_asyncio/echo.py
import os if __name__ == '__main__': while True: buf = os.read(0, 1024) if not buf: break os.write(1, buf)
148
9
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_asyncio/test_transports.py
"""Tests for transports.py.""" import unittest from unittest import mock import asyncio from asyncio import transports class TransportTests(unittest.TestCase): def test_ctor_extra_is_none(self): transport = asyncio.Transport() self.assertEqual(transport._extra, {}) def test_get_extra_info(self): transport = asyncio.Transport({'extra': 'info'}) self.assertEqual('info', transport.get_extra_info('extra')) self.assertIsNone(transport.get_extra_info('unknown')) default = object() self.assertIs(default, transport.get_extra_info('unknown', default)) def test_writelines(self): transport = asyncio.Transport() transport.write = mock.Mock() transport.writelines([b'line1', bytearray(b'line2'), memoryview(b'line3')]) self.assertEqual(1, transport.write.call_count) transport.write.assert_called_with(b'line1line2line3') def test_not_implemented(self): transport = asyncio.Transport() self.assertRaises(NotImplementedError, transport.set_write_buffer_limits) self.assertRaises(NotImplementedError, transport.get_write_buffer_size) self.assertRaises(NotImplementedError, transport.write, 'data') self.assertRaises(NotImplementedError, transport.write_eof) self.assertRaises(NotImplementedError, transport.can_write_eof) self.assertRaises(NotImplementedError, transport.pause_reading) self.assertRaises(NotImplementedError, transport.resume_reading) self.assertRaises(NotImplementedError, transport.close) self.assertRaises(NotImplementedError, transport.abort) def test_dgram_not_implemented(self): transport = asyncio.DatagramTransport() self.assertRaises(NotImplementedError, transport.sendto, 'data') self.assertRaises(NotImplementedError, transport.abort) def test_subprocess_transport_not_implemented(self): transport = asyncio.SubprocessTransport() self.assertRaises(NotImplementedError, transport.get_pid) self.assertRaises(NotImplementedError, transport.get_returncode) self.assertRaises(NotImplementedError, transport.get_pipe_transport, 1) self.assertRaises(NotImplementedError, transport.send_signal, 1) self.assertRaises(NotImplementedError, transport.terminate) self.assertRaises(NotImplementedError, transport.kill) def test_flowcontrol_mixin_set_write_limits(self): class MyTransport(transports._FlowControlMixin, transports.Transport): def get_write_buffer_size(self): return 512 loop = mock.Mock() transport = MyTransport(loop=loop) transport._protocol = mock.Mock() self.assertFalse(transport._protocol_paused) with self.assertRaisesRegex(ValueError, 'high.*must be >= low'): transport.set_write_buffer_limits(high=0, low=1) transport.set_write_buffer_limits(high=1024, low=128) self.assertFalse(transport._protocol_paused) self.assertEqual(transport.get_write_buffer_limits(), (128, 1024)) transport.set_write_buffer_limits(high=256, low=128) self.assertTrue(transport._protocol_paused) self.assertEqual(transport.get_write_buffer_limits(), (128, 256)) if __name__ == '__main__': unittest.main()
3,471
92
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_asyncio/test_windows_utils.py
"""Tests for window_utils""" import socket import sys import unittest import warnings from unittest import mock if sys.platform != 'win32': raise unittest.SkipTest('Windows only') import _winapi from asyncio import _overlapped from asyncio import windows_utils try: from test import support except ImportError: from asyncio import test_support as support class WinsocketpairTests(unittest.TestCase): def check_winsocketpair(self, ssock, csock): csock.send(b'xxx') self.assertEqual(b'xxx', ssock.recv(1024)) csock.close() ssock.close() def test_winsocketpair(self): ssock, csock = windows_utils.socketpair() self.check_winsocketpair(ssock, csock) @unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 not supported or enabled') def test_winsocketpair_ipv6(self): ssock, csock = windows_utils.socketpair(family=socket.AF_INET6) self.check_winsocketpair(ssock, csock) @unittest.skipIf(hasattr(socket, 'socketpair'), 'socket.socketpair is available') @mock.patch('asyncio.windows_utils.socket') def test_winsocketpair_exc(self, m_socket): m_socket.AF_INET = socket.AF_INET m_socket.SOCK_STREAM = socket.SOCK_STREAM m_socket.socket.return_value.getsockname.return_value = ('', 12345) m_socket.socket.return_value.accept.return_value = object(), object() m_socket.socket.return_value.connect.side_effect = OSError() self.assertRaises(OSError, windows_utils.socketpair) def test_winsocketpair_invalid_args(self): self.assertRaises(ValueError, windows_utils.socketpair, family=socket.AF_UNSPEC) self.assertRaises(ValueError, windows_utils.socketpair, type=socket.SOCK_DGRAM) self.assertRaises(ValueError, windows_utils.socketpair, proto=1) @unittest.skipIf(hasattr(socket, 'socketpair'), 'socket.socketpair is available') @mock.patch('asyncio.windows_utils.socket') def test_winsocketpair_close(self, m_socket): m_socket.AF_INET = socket.AF_INET m_socket.SOCK_STREAM = socket.SOCK_STREAM sock = mock.Mock() m_socket.socket.return_value = sock sock.bind.side_effect = OSError self.assertRaises(OSError, windows_utils.socketpair) self.assertTrue(sock.close.called) class PipeTests(unittest.TestCase): def test_pipe_overlapped(self): h1, h2 = windows_utils.pipe(overlapped=(True, True)) try: ov1 = _overlapped.Overlapped() self.assertFalse(ov1.pending) self.assertEqual(ov1.error, 0) ov1.ReadFile(h1, 100) self.assertTrue(ov1.pending) self.assertEqual(ov1.error, _winapi.ERROR_IO_PENDING) ERROR_IO_INCOMPLETE = 996 try: ov1.getresult() except OSError as e: self.assertEqual(e.winerror, ERROR_IO_INCOMPLETE) else: raise RuntimeError('expected ERROR_IO_INCOMPLETE') ov2 = _overlapped.Overlapped() self.assertFalse(ov2.pending) self.assertEqual(ov2.error, 0) ov2.WriteFile(h2, b"hello") self.assertIn(ov2.error, {0, _winapi.ERROR_IO_PENDING}) res = _winapi.WaitForMultipleObjects([ov2.event], False, 100) self.assertEqual(res, _winapi.WAIT_OBJECT_0) self.assertFalse(ov1.pending) self.assertEqual(ov1.error, ERROR_IO_INCOMPLETE) self.assertFalse(ov2.pending) self.assertIn(ov2.error, {0, _winapi.ERROR_IO_PENDING}) self.assertEqual(ov1.getresult(), b"hello") finally: _winapi.CloseHandle(h1) _winapi.CloseHandle(h2) def test_pipe_handle(self): h, _ = windows_utils.pipe(overlapped=(True, True)) _winapi.CloseHandle(_) p = windows_utils.PipeHandle(h) self.assertEqual(p.fileno(), h) self.assertEqual(p.handle, h) # check garbage collection of p closes handle with warnings.catch_warnings(): warnings.filterwarnings("ignore", "", ResourceWarning) del p support.gc_collect() try: _winapi.CloseHandle(h) except OSError as e: self.assertEqual(e.winerror, 6) # ERROR_INVALID_HANDLE else: raise RuntimeError('expected ERROR_INVALID_HANDLE') class PopenTests(unittest.TestCase): def test_popen(self): command = r"""if 1: import sys s = sys.stdin.readline() sys.stdout.write(s.upper()) sys.stderr.write('stderr') """ msg = b"blah\n" p = windows_utils.Popen([sys.executable, '-c', command], stdin=windows_utils.PIPE, stdout=windows_utils.PIPE, stderr=windows_utils.PIPE) for f in [p.stdin, p.stdout, p.stderr]: self.assertIsInstance(f, windows_utils.PipeHandle) ovin = _overlapped.Overlapped() ovout = _overlapped.Overlapped() overr = _overlapped.Overlapped() ovin.WriteFile(p.stdin.handle, msg) ovout.ReadFile(p.stdout.handle, 100) overr.ReadFile(p.stderr.handle, 100) events = [ovin.event, ovout.event, overr.event] # Super-long timeout for slow buildbots. res = _winapi.WaitForMultipleObjects(events, True, 10000) self.assertEqual(res, _winapi.WAIT_OBJECT_0) self.assertFalse(ovout.pending) self.assertFalse(overr.pending) self.assertFalse(ovin.pending) self.assertEqual(ovin.getresult(), len(msg)) out = ovout.getresult().rstrip() err = overr.getresult().rstrip() self.assertGreater(len(out), 0) self.assertGreater(len(err), 0) # allow for partial reads... self.assertTrue(msg.upper().rstrip().startswith(out)) self.assertTrue(b"stderr".startswith(err)) # The context manager calls wait() and closes resources with p: pass if __name__ == '__main__': unittest.main()
6,274
183
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_asyncio/test_pep492.py
"""Tests support for new syntax introduced by PEP 492.""" import collections.abc import types import unittest try: from test import support except ImportError: from asyncio import test_support as support from unittest import mock import asyncio from asyncio import test_utils class BaseTest(test_utils.TestCase): def setUp(self): super().setUp() self.loop = asyncio.BaseEventLoop() self.loop._process_events = mock.Mock() self.loop._selector = mock.Mock() self.loop._selector.select.return_value = () self.set_event_loop(self.loop) class LockTests(BaseTest): def test_context_manager_async_with(self): primitives = [ asyncio.Lock(loop=self.loop), asyncio.Condition(loop=self.loop), asyncio.Semaphore(loop=self.loop), asyncio.BoundedSemaphore(loop=self.loop), ] async def test(lock): await asyncio.sleep(0.01, loop=self.loop) self.assertFalse(lock.locked()) async with lock as _lock: self.assertIs(_lock, None) self.assertTrue(lock.locked()) await asyncio.sleep(0.01, loop=self.loop) self.assertTrue(lock.locked()) self.assertFalse(lock.locked()) for primitive in primitives: self.loop.run_until_complete(test(primitive)) self.assertFalse(primitive.locked()) def test_context_manager_with_await(self): primitives = [ asyncio.Lock(loop=self.loop), asyncio.Condition(loop=self.loop), asyncio.Semaphore(loop=self.loop), asyncio.BoundedSemaphore(loop=self.loop), ] async def test(lock): await asyncio.sleep(0.01, loop=self.loop) self.assertFalse(lock.locked()) with await lock as _lock: self.assertIs(_lock, None) self.assertTrue(lock.locked()) await asyncio.sleep(0.01, loop=self.loop) self.assertTrue(lock.locked()) self.assertFalse(lock.locked()) for primitive in primitives: self.loop.run_until_complete(test(primitive)) self.assertFalse(primitive.locked()) class StreamReaderTests(BaseTest): def test_readline(self): DATA = b'line1\nline2\nline3' stream = asyncio.StreamReader(loop=self.loop) stream.feed_data(DATA) stream.feed_eof() async def reader(): data = [] async for line in stream: data.append(line) return data data = self.loop.run_until_complete(reader()) self.assertEqual(data, [b'line1\n', b'line2\n', b'line3']) class CoroutineTests(BaseTest): def test_iscoroutine(self): async def foo(): pass f = foo() try: self.assertTrue(asyncio.iscoroutine(f)) finally: f.close() # silence warning # Test that asyncio.iscoroutine() uses collections.abc.Coroutine class FakeCoro: def send(self, value): pass def throw(self, typ, val=None, tb=None): pass def close(self): pass def __await__(self): yield self.assertTrue(asyncio.iscoroutine(FakeCoro())) def test_iscoroutinefunction(self): async def foo(): pass self.assertTrue(asyncio.iscoroutinefunction(foo)) def test_function_returning_awaitable(self): class Awaitable: def __await__(self): return ('spam',) @asyncio.coroutine def func(): return Awaitable() coro = func() self.assertEqual(coro.send(None), 'spam') coro.close() def test_async_def_coroutines(self): async def bar(): return 'spam' async def foo(): return await bar() # production mode data = self.loop.run_until_complete(foo()) self.assertEqual(data, 'spam') # debug mode self.loop.set_debug(True) data = self.loop.run_until_complete(foo()) self.assertEqual(data, 'spam') @mock.patch('asyncio.coroutines.logger') def test_async_def_wrapped(self, m_log): async def foo(): pass async def start(): foo_coro = foo() self.assertRegex( repr(foo_coro), r'<CoroWrapper .*\.foo\(\) running at .*pep492.*>') with support.check_warnings((r'.*foo.*was never', RuntimeWarning)): foo_coro = None support.gc_collect() self.assertTrue(m_log.error.called) message = m_log.error.call_args[0][0] self.assertRegex(message, r'CoroWrapper.*foo.*was never') self.loop.set_debug(True) self.loop.run_until_complete(start()) async def start(): foo_coro = foo() task = asyncio.ensure_future(foo_coro, loop=self.loop) self.assertRegex(repr(task), r'Task.*foo.*running') self.loop.run_until_complete(start()) def test_types_coroutine(self): def gen(): yield from () return 'spam' @types.coroutine def func(): return gen() async def coro(): wrapper = func() self.assertIsInstance(wrapper, types._GeneratorWrapper) return await wrapper data = self.loop.run_until_complete(coro()) self.assertEqual(data, 'spam') def test_task_print_stack(self): T = None async def foo(): f = T.get_stack(limit=1) try: self.assertEqual(f[0].f_code.co_name, 'foo') finally: f = None async def runner(): nonlocal T T = asyncio.ensure_future(foo(), loop=self.loop) await T self.loop.run_until_complete(runner()) def test_double_await(self): async def afunc(): await asyncio.sleep(0.1, loop=self.loop) async def runner(): coro = afunc() t = asyncio.Task(coro, loop=self.loop) try: await asyncio.sleep(0, loop=self.loop) await coro finally: t.cancel() self.loop.set_debug(True) with self.assertRaisesRegex( RuntimeError, r'Cannot await.*test_double_await.*\bafunc\b.*while.*\bsleep\b'): self.loop.run_until_complete(runner()) if __name__ == '__main__': unittest.main()
6,713
233
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_asyncio/test_proactor_events.py
"""Tests for proactor_events.py""" import socket import unittest from unittest import mock import asyncio from asyncio.proactor_events import BaseProactorEventLoop from asyncio.proactor_events import _ProactorSocketTransport from asyncio.proactor_events import _ProactorWritePipeTransport from asyncio.proactor_events import _ProactorDuplexPipeTransport from asyncio import test_utils def close_transport(transport): # Don't call transport.close() because the event loop and the IOCP proactor # are mocked if transport._sock is None: return transport._sock.close() transport._sock = None class ProactorSocketTransportTests(test_utils.TestCase): def setUp(self): super().setUp() self.loop = self.new_test_loop() self.addCleanup(self.loop.close) self.proactor = mock.Mock() self.loop._proactor = self.proactor self.protocol = test_utils.make_test_protocol(asyncio.Protocol) self.sock = mock.Mock(socket.socket) def socket_transport(self, waiter=None): transport = _ProactorSocketTransport(self.loop, self.sock, self.protocol, waiter=waiter) self.addCleanup(close_transport, transport) return transport def test_ctor(self): fut = asyncio.Future(loop=self.loop) tr = self.socket_transport(waiter=fut) test_utils.run_briefly(self.loop) self.assertIsNone(fut.result()) self.protocol.connection_made(tr) self.proactor.recv.assert_called_with(self.sock, 4096) def test_loop_reading(self): tr = self.socket_transport() tr._loop_reading() self.loop._proactor.recv.assert_called_with(self.sock, 4096) self.assertFalse(self.protocol.data_received.called) self.assertFalse(self.protocol.eof_received.called) def test_loop_reading_data(self): res = asyncio.Future(loop=self.loop) res.set_result(b'data') tr = self.socket_transport() tr._read_fut = res tr._loop_reading(res) self.loop._proactor.recv.assert_called_with(self.sock, 4096) self.protocol.data_received.assert_called_with(b'data') def test_loop_reading_no_data(self): res = asyncio.Future(loop=self.loop) res.set_result(b'') tr = self.socket_transport() self.assertRaises(AssertionError, tr._loop_reading, res) tr.close = mock.Mock() tr._read_fut = res tr._loop_reading(res) self.assertFalse(self.loop._proactor.recv.called) self.assertTrue(self.protocol.eof_received.called) self.assertTrue(tr.close.called) def test_loop_reading_aborted(self): err = self.loop._proactor.recv.side_effect = ConnectionAbortedError() tr = self.socket_transport() tr._fatal_error = mock.Mock() tr._loop_reading() tr._fatal_error.assert_called_with( err, 'Fatal read error on pipe transport') def test_loop_reading_aborted_closing(self): self.loop._proactor.recv.side_effect = ConnectionAbortedError() tr = self.socket_transport() tr._closing = True tr._fatal_error = mock.Mock() tr._loop_reading() self.assertFalse(tr._fatal_error.called) def test_loop_reading_aborted_is_fatal(self): self.loop._proactor.recv.side_effect = ConnectionAbortedError() tr = self.socket_transport() tr._closing = False tr._fatal_error = mock.Mock() tr._loop_reading() self.assertTrue(tr._fatal_error.called) def test_loop_reading_conn_reset_lost(self): err = self.loop._proactor.recv.side_effect = ConnectionResetError() tr = self.socket_transport() tr._closing = False tr._fatal_error = mock.Mock() tr._force_close = mock.Mock() tr._loop_reading() self.assertFalse(tr._fatal_error.called) tr._force_close.assert_called_with(err) def test_loop_reading_exception(self): err = self.loop._proactor.recv.side_effect = (OSError()) tr = self.socket_transport() tr._fatal_error = mock.Mock() tr._loop_reading() tr._fatal_error.assert_called_with( err, 'Fatal read error on pipe transport') def test_write(self): tr = self.socket_transport() tr._loop_writing = mock.Mock() tr.write(b'data') self.assertEqual(tr._buffer, None) tr._loop_writing.assert_called_with(data=b'data') def test_write_no_data(self): tr = self.socket_transport() tr.write(b'') self.assertFalse(tr._buffer) def test_write_more(self): tr = self.socket_transport() tr._write_fut = mock.Mock() tr._loop_writing = mock.Mock() tr.write(b'data') self.assertEqual(tr._buffer, b'data') self.assertFalse(tr._loop_writing.called) def test_loop_writing(self): tr = self.socket_transport() tr._buffer = bytearray(b'data') tr._loop_writing() self.loop._proactor.send.assert_called_with(self.sock, b'data') self.loop._proactor.send.return_value.add_done_callback.\ assert_called_with(tr._loop_writing) @mock.patch('asyncio.proactor_events.logger') def test_loop_writing_err(self, m_log): err = self.loop._proactor.send.side_effect = OSError() tr = self.socket_transport() tr._fatal_error = mock.Mock() tr._buffer = [b'da', b'ta'] tr._loop_writing() tr._fatal_error.assert_called_with( err, 'Fatal write error on pipe transport') tr._conn_lost = 1 tr.write(b'data') tr.write(b'data') tr.write(b'data') tr.write(b'data') tr.write(b'data') self.assertEqual(tr._buffer, None) m_log.warning.assert_called_with('socket.send() raised exception.') def test_loop_writing_stop(self): fut = asyncio.Future(loop=self.loop) fut.set_result(b'data') tr = self.socket_transport() tr._write_fut = fut tr._loop_writing(fut) self.assertIsNone(tr._write_fut) def test_loop_writing_closing(self): fut = asyncio.Future(loop=self.loop) fut.set_result(1) tr = self.socket_transport() tr._write_fut = fut tr.close() tr._loop_writing(fut) self.assertIsNone(tr._write_fut) test_utils.run_briefly(self.loop) self.protocol.connection_lost.assert_called_with(None) def test_abort(self): tr = self.socket_transport() tr._force_close = mock.Mock() tr.abort() tr._force_close.assert_called_with(None) def test_close(self): tr = self.socket_transport() tr.close() test_utils.run_briefly(self.loop) self.protocol.connection_lost.assert_called_with(None) self.assertTrue(tr.is_closing()) self.assertEqual(tr._conn_lost, 1) self.protocol.connection_lost.reset_mock() tr.close() test_utils.run_briefly(self.loop) self.assertFalse(self.protocol.connection_lost.called) def test_close_write_fut(self): tr = self.socket_transport() tr._write_fut = mock.Mock() tr.close() test_utils.run_briefly(self.loop) self.assertFalse(self.protocol.connection_lost.called) def test_close_buffer(self): tr = self.socket_transport() tr._buffer = [b'data'] tr.close() test_utils.run_briefly(self.loop) self.assertFalse(self.protocol.connection_lost.called) @mock.patch('asyncio.base_events.logger') def test_fatal_error(self, m_logging): tr = self.socket_transport() tr._force_close = mock.Mock() tr._fatal_error(None) self.assertTrue(tr._force_close.called) self.assertTrue(m_logging.error.called) def test_force_close(self): tr = self.socket_transport() tr._buffer = [b'data'] read_fut = tr._read_fut = mock.Mock() write_fut = tr._write_fut = mock.Mock() tr._force_close(None) read_fut.cancel.assert_called_with() write_fut.cancel.assert_called_with() test_utils.run_briefly(self.loop) self.protocol.connection_lost.assert_called_with(None) self.assertEqual(None, tr._buffer) self.assertEqual(tr._conn_lost, 1) def test_force_close_idempotent(self): tr = self.socket_transport() tr._closing = True tr._force_close(None) test_utils.run_briefly(self.loop) self.assertFalse(self.protocol.connection_lost.called) def test_fatal_error_2(self): tr = self.socket_transport() tr._buffer = [b'data'] tr._force_close(None) test_utils.run_briefly(self.loop) self.protocol.connection_lost.assert_called_with(None) self.assertEqual(None, tr._buffer) def test_call_connection_lost(self): tr = self.socket_transport() tr._call_connection_lost(None) self.assertTrue(self.protocol.connection_lost.called) self.assertTrue(self.sock.close.called) def test_write_eof(self): tr = self.socket_transport() self.assertTrue(tr.can_write_eof()) tr.write_eof() self.sock.shutdown.assert_called_with(socket.SHUT_WR) tr.write_eof() self.assertEqual(self.sock.shutdown.call_count, 1) tr.close() def test_write_eof_buffer(self): tr = self.socket_transport() f = asyncio.Future(loop=self.loop) tr._loop._proactor.send.return_value = f tr.write(b'data') tr.write_eof() self.assertTrue(tr._eof_written) self.assertFalse(self.sock.shutdown.called) tr._loop._proactor.send.assert_called_with(self.sock, b'data') f.set_result(4) self.loop._run_once() self.sock.shutdown.assert_called_with(socket.SHUT_WR) tr.close() def test_write_eof_write_pipe(self): tr = _ProactorWritePipeTransport( self.loop, self.sock, self.protocol) self.assertTrue(tr.can_write_eof()) tr.write_eof() self.assertTrue(tr.is_closing()) self.loop._run_once() self.assertTrue(self.sock.close.called) tr.close() def test_write_eof_buffer_write_pipe(self): tr = _ProactorWritePipeTransport(self.loop, self.sock, self.protocol) f = asyncio.Future(loop=self.loop) tr._loop._proactor.send.return_value = f tr.write(b'data') tr.write_eof() self.assertTrue(tr.is_closing()) self.assertFalse(self.sock.shutdown.called) tr._loop._proactor.send.assert_called_with(self.sock, b'data') f.set_result(4) self.loop._run_once() self.loop._run_once() self.assertTrue(self.sock.close.called) tr.close() def test_write_eof_duplex_pipe(self): tr = _ProactorDuplexPipeTransport( self.loop, self.sock, self.protocol) self.assertFalse(tr.can_write_eof()) with self.assertRaises(NotImplementedError): tr.write_eof() close_transport(tr) def test_pause_resume_reading(self): tr = self.socket_transport() futures = [] for msg in [b'data1', b'data2', b'data3', b'data4', b'data5', b'']: f = asyncio.Future(loop=self.loop) f.set_result(msg) futures.append(f) self.loop._proactor.recv.side_effect = futures self.loop._run_once() self.assertFalse(tr._paused) self.loop._run_once() self.protocol.data_received.assert_called_with(b'data1') self.loop._run_once() self.protocol.data_received.assert_called_with(b'data2') tr.pause_reading() tr.pause_reading() self.assertTrue(tr._paused) for i in range(10): self.loop._run_once() self.protocol.data_received.assert_called_with(b'data2') tr.resume_reading() tr.resume_reading() self.assertFalse(tr._paused) self.loop._run_once() self.protocol.data_received.assert_called_with(b'data3') self.loop._run_once() self.protocol.data_received.assert_called_with(b'data4') tr.pause_reading() tr.resume_reading() self.loop.call_exception_handler = mock.Mock() self.loop._run_once() self.loop.call_exception_handler.assert_not_called() self.protocol.data_received.assert_called_with(b'data5') tr.close() def pause_writing_transport(self, high): tr = self.socket_transport() tr.set_write_buffer_limits(high=high) self.assertEqual(tr.get_write_buffer_size(), 0) self.assertFalse(self.protocol.pause_writing.called) self.assertFalse(self.protocol.resume_writing.called) return tr def test_pause_resume_writing(self): tr = self.pause_writing_transport(high=4) # write a large chunk, must pause writing fut = asyncio.Future(loop=self.loop) self.loop._proactor.send.return_value = fut tr.write(b'large data') self.loop._run_once() self.assertTrue(self.protocol.pause_writing.called) # flush the buffer fut.set_result(None) self.loop._run_once() self.assertEqual(tr.get_write_buffer_size(), 0) self.assertTrue(self.protocol.resume_writing.called) def test_pause_writing_2write(self): tr = self.pause_writing_transport(high=4) # first short write, the buffer is not full (3 <= 4) fut1 = asyncio.Future(loop=self.loop) self.loop._proactor.send.return_value = fut1 tr.write(b'123') self.loop._run_once() self.assertEqual(tr.get_write_buffer_size(), 3) self.assertFalse(self.protocol.pause_writing.called) # fill the buffer, must pause writing (6 > 4) tr.write(b'abc') self.loop._run_once() self.assertEqual(tr.get_write_buffer_size(), 6) self.assertTrue(self.protocol.pause_writing.called) def test_pause_writing_3write(self): tr = self.pause_writing_transport(high=4) # first short write, the buffer is not full (1 <= 4) fut = asyncio.Future(loop=self.loop) self.loop._proactor.send.return_value = fut tr.write(b'1') self.loop._run_once() self.assertEqual(tr.get_write_buffer_size(), 1) self.assertFalse(self.protocol.pause_writing.called) # second short write, the buffer is not full (3 <= 4) tr.write(b'23') self.loop._run_once() self.assertEqual(tr.get_write_buffer_size(), 3) self.assertFalse(self.protocol.pause_writing.called) # fill the buffer, must pause writing (6 > 4) tr.write(b'abc') self.loop._run_once() self.assertEqual(tr.get_write_buffer_size(), 6) self.assertTrue(self.protocol.pause_writing.called) def test_dont_pause_writing(self): tr = self.pause_writing_transport(high=4) # write a large chunk which completes immedialty, # it should not pause writing fut = asyncio.Future(loop=self.loop) fut.set_result(None) self.loop._proactor.send.return_value = fut tr.write(b'very large data') self.loop._run_once() self.assertEqual(tr.get_write_buffer_size(), 0) self.assertFalse(self.protocol.pause_writing.called) class BaseProactorEventLoopTests(test_utils.TestCase): def setUp(self): super().setUp() self.sock = test_utils.mock_nonblocking_socket() self.proactor = mock.Mock() self.ssock, self.csock = mock.Mock(), mock.Mock() class EventLoop(BaseProactorEventLoop): def _socketpair(s): return (self.ssock, self.csock) self.loop = EventLoop(self.proactor) self.set_event_loop(self.loop) @mock.patch.object(BaseProactorEventLoop, 'call_soon') @mock.patch.object(BaseProactorEventLoop, '_socketpair') def test_ctor(self, socketpair, call_soon): ssock, csock = socketpair.return_value = ( mock.Mock(), mock.Mock()) loop = BaseProactorEventLoop(self.proactor) self.assertIs(loop._ssock, ssock) self.assertIs(loop._csock, csock) self.assertEqual(loop._internal_fds, 1) call_soon.assert_called_with(loop._loop_self_reading) loop.close() def test_close_self_pipe(self): self.loop._close_self_pipe() self.assertEqual(self.loop._internal_fds, 0) self.assertTrue(self.ssock.close.called) self.assertTrue(self.csock.close.called) self.assertIsNone(self.loop._ssock) self.assertIsNone(self.loop._csock) # Don't call close(): _close_self_pipe() cannot be called twice self.loop._closed = True def test_close(self): self.loop._close_self_pipe = mock.Mock() self.loop.close() self.assertTrue(self.loop._close_self_pipe.called) self.assertTrue(self.proactor.close.called) self.assertIsNone(self.loop._proactor) self.loop._close_self_pipe.reset_mock() self.loop.close() self.assertFalse(self.loop._close_self_pipe.called) def test_sock_recv(self): self.loop.sock_recv(self.sock, 1024) self.proactor.recv.assert_called_with(self.sock, 1024) def test_sock_sendall(self): self.loop.sock_sendall(self.sock, b'data') self.proactor.send.assert_called_with(self.sock, b'data') def test_sock_connect(self): self.loop.sock_connect(self.sock, ('1.2.3.4', 123)) self.proactor.connect.assert_called_with(self.sock, ('1.2.3.4', 123)) def test_sock_accept(self): self.loop.sock_accept(self.sock) self.proactor.accept.assert_called_with(self.sock) def test_socketpair(self): class EventLoop(BaseProactorEventLoop): # override the destructor to not log a ResourceWarning def __del__(self): pass self.assertRaises( NotImplementedError, EventLoop, self.proactor) def test_make_socket_transport(self): tr = self.loop._make_socket_transport(self.sock, asyncio.Protocol()) self.assertIsInstance(tr, _ProactorSocketTransport) close_transport(tr) def test_loop_self_reading(self): self.loop._loop_self_reading() self.proactor.recv.assert_called_with(self.ssock, 4096) self.proactor.recv.return_value.add_done_callback.assert_called_with( self.loop._loop_self_reading) def test_loop_self_reading_fut(self): fut = mock.Mock() self.loop._loop_self_reading(fut) self.assertTrue(fut.result.called) self.proactor.recv.assert_called_with(self.ssock, 4096) self.proactor.recv.return_value.add_done_callback.assert_called_with( self.loop._loop_self_reading) def test_loop_self_reading_exception(self): self.loop.call_exception_handler = mock.Mock() self.proactor.recv.side_effect = OSError() self.loop._loop_self_reading() self.assertTrue(self.loop.call_exception_handler.called) def test_write_to_self(self): self.loop._write_to_self() self.csock.send.assert_called_with(b'\0') def test_process_events(self): self.loop._process_events([]) @mock.patch('asyncio.base_events.logger') def test_create_server(self, m_log): pf = mock.Mock() call_soon = self.loop.call_soon = mock.Mock() self.loop._start_serving(pf, self.sock) self.assertTrue(call_soon.called) # callback loop = call_soon.call_args[0][0] loop() self.proactor.accept.assert_called_with(self.sock) # conn fut = mock.Mock() fut.result.return_value = (mock.Mock(), mock.Mock()) make_tr = self.loop._make_socket_transport = mock.Mock() loop(fut) self.assertTrue(fut.result.called) self.assertTrue(make_tr.called) # exception fut.result.side_effect = OSError() loop(fut) self.assertTrue(self.sock.close.called) self.assertTrue(m_log.error.called) def test_create_server_cancel(self): pf = mock.Mock() call_soon = self.loop.call_soon = mock.Mock() self.loop._start_serving(pf, self.sock) loop = call_soon.call_args[0][0] # cancelled fut = asyncio.Future(loop=self.loop) fut.cancel() loop(fut) self.assertTrue(self.sock.close.called) def test_stop_serving(self): sock = mock.Mock() self.loop._stop_serving(sock) self.assertTrue(sock.close.called) self.proactor._stop_serving.assert_called_with(sock) if __name__ == '__main__': unittest.main()
21,043
606
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_asyncio/test_base_events.py
"""Tests for base_events.py""" import errno import logging import math import os import socket import sys import threading import time import unittest from unittest import mock import asyncio from asyncio import base_events from asyncio import constants from asyncio import test_utils try: from test import support except ImportError: from asyncio import test_support as support try: from test.support.script_helper import assert_python_ok except ImportError: try: from test.script_helper import assert_python_ok except ImportError: from asyncio.test_support import assert_python_ok MOCK_ANY = mock.ANY PY34 = sys.version_info >= (3, 4) def mock_socket_module(): m_socket = mock.MagicMock(spec=socket) for name in ( 'AF_INET', 'AF_INET6', 'AF_UNSPEC', 'IPPROTO_TCP', 'IPPROTO_UDP', 'SOCK_STREAM', 'SOCK_DGRAM', 'SOL_SOCKET', 'SO_REUSEADDR', 'inet_pton' ): if hasattr(socket, name): setattr(m_socket, name, getattr(socket, name)) else: delattr(m_socket, name) m_socket.socket = mock.MagicMock() m_socket.socket.return_value = test_utils.mock_nonblocking_socket() m_socket.getaddrinfo._is_coroutine = False return m_socket def patch_socket(f): return mock.patch('asyncio.base_events.socket', new_callable=mock_socket_module)(f) class BaseEventTests(test_utils.TestCase): def test_ipaddr_info(self): UNSPEC = socket.AF_UNSPEC INET = socket.AF_INET INET6 = socket.AF_INET6 STREAM = socket.SOCK_STREAM DGRAM = socket.SOCK_DGRAM TCP = socket.IPPROTO_TCP UDP = socket.IPPROTO_UDP self.assertEqual( (INET, STREAM, TCP, '', ('1.2.3.4', 1)), base_events._ipaddr_info('1.2.3.4', 1, INET, STREAM, TCP)) self.assertEqual( (INET, STREAM, TCP, '', ('1.2.3.4', 1)), base_events._ipaddr_info(b'1.2.3.4', 1, INET, STREAM, TCP)) self.assertEqual( (INET, STREAM, TCP, '', ('1.2.3.4', 1)), base_events._ipaddr_info('1.2.3.4', 1, UNSPEC, STREAM, TCP)) self.assertEqual( (INET, DGRAM, UDP, '', ('1.2.3.4', 1)), base_events._ipaddr_info('1.2.3.4', 1, UNSPEC, DGRAM, UDP)) # Socket type STREAM implies TCP protocol. self.assertEqual( (INET, STREAM, TCP, '', ('1.2.3.4', 1)), base_events._ipaddr_info('1.2.3.4', 1, UNSPEC, STREAM, 0)) # Socket type DGRAM implies UDP protocol. self.assertEqual( (INET, DGRAM, UDP, '', ('1.2.3.4', 1)), base_events._ipaddr_info('1.2.3.4', 1, UNSPEC, DGRAM, 0)) # No socket type. self.assertIsNone( base_events._ipaddr_info('1.2.3.4', 1, UNSPEC, 0, 0)) # IPv4 address with family IPv6. self.assertIsNone( base_events._ipaddr_info('1.2.3.4', 1, INET6, STREAM, TCP)) self.assertEqual( (INET6, STREAM, TCP, '', ('::3', 1, 0, 0)), base_events._ipaddr_info('::3', 1, INET6, STREAM, TCP)) self.assertEqual( (INET6, STREAM, TCP, '', ('::3', 1, 0, 0)), base_events._ipaddr_info('::3', 1, UNSPEC, STREAM, TCP)) # IPv6 address with family IPv4. self.assertIsNone( base_events._ipaddr_info('::3', 1, INET, STREAM, TCP)) # IPv6 address with zone index. self.assertIsNone( base_events._ipaddr_info('::3%lo0', 1, INET6, STREAM, TCP)) def test_port_parameter_types(self): # Test obscure kinds of arguments for "port". INET = socket.AF_INET STREAM = socket.SOCK_STREAM TCP = socket.IPPROTO_TCP self.assertEqual( (INET, STREAM, TCP, '', ('1.2.3.4', 0)), base_events._ipaddr_info('1.2.3.4', None, INET, STREAM, TCP)) self.assertEqual( (INET, STREAM, TCP, '', ('1.2.3.4', 0)), base_events._ipaddr_info('1.2.3.4', b'', INET, STREAM, TCP)) self.assertEqual( (INET, STREAM, TCP, '', ('1.2.3.4', 0)), base_events._ipaddr_info('1.2.3.4', '', INET, STREAM, TCP)) self.assertEqual( (INET, STREAM, TCP, '', ('1.2.3.4', 1)), base_events._ipaddr_info('1.2.3.4', '1', INET, STREAM, TCP)) self.assertEqual( (INET, STREAM, TCP, '', ('1.2.3.4', 1)), base_events._ipaddr_info('1.2.3.4', b'1', INET, STREAM, TCP)) @patch_socket def test_ipaddr_info_no_inet_pton(self, m_socket): del m_socket.inet_pton self.assertIsNone(base_events._ipaddr_info('1.2.3.4', 1, socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP)) class BaseEventLoopTests(test_utils.TestCase): def setUp(self): super().setUp() self.loop = base_events.BaseEventLoop() self.loop._selector = mock.Mock() self.loop._selector.select.return_value = () self.set_event_loop(self.loop) def test_not_implemented(self): m = mock.Mock() self.assertRaises( NotImplementedError, self.loop._make_socket_transport, m, m) self.assertRaises( NotImplementedError, self.loop._make_ssl_transport, m, m, m, m) self.assertRaises( NotImplementedError, self.loop._make_datagram_transport, m, m) self.assertRaises( NotImplementedError, self.loop._process_events, []) self.assertRaises( NotImplementedError, self.loop._write_to_self) self.assertRaises( NotImplementedError, self.loop._make_read_pipe_transport, m, m) self.assertRaises( NotImplementedError, self.loop._make_write_pipe_transport, m, m) gen = self.loop._make_subprocess_transport(m, m, m, m, m, m, m) with self.assertRaises(NotImplementedError): gen.send(None) def test_close(self): self.assertFalse(self.loop.is_closed()) self.loop.close() self.assertTrue(self.loop.is_closed()) # it should be possible to call close() more than once self.loop.close() self.loop.close() # operation blocked when the loop is closed f = asyncio.Future(loop=self.loop) self.assertRaises(RuntimeError, self.loop.run_forever) self.assertRaises(RuntimeError, self.loop.run_until_complete, f) def test__add_callback_handle(self): h = asyncio.Handle(lambda: False, (), self.loop) self.loop._add_callback(h) self.assertFalse(self.loop._scheduled) self.assertIn(h, self.loop._ready) def test__add_callback_cancelled_handle(self): h = asyncio.Handle(lambda: False, (), self.loop) h.cancel() self.loop._add_callback(h) self.assertFalse(self.loop._scheduled) self.assertFalse(self.loop._ready) def test_set_default_executor(self): executor = mock.Mock() self.loop.set_default_executor(executor) self.assertIs(executor, self.loop._default_executor) def test_getnameinfo(self): sockaddr = mock.Mock() self.loop.run_in_executor = mock.Mock() self.loop.getnameinfo(sockaddr) self.assertEqual( (None, socket.getnameinfo, sockaddr, 0), self.loop.run_in_executor.call_args[0]) def test_call_soon(self): def cb(): pass h = self.loop.call_soon(cb) self.assertEqual(h._callback, cb) self.assertIsInstance(h, asyncio.Handle) self.assertIn(h, self.loop._ready) def test_call_soon_non_callable(self): self.loop.set_debug(True) with self.assertRaisesRegex(TypeError, 'a callable object'): self.loop.call_soon(1) def test_call_later(self): def cb(): pass h = self.loop.call_later(10.0, cb) self.assertIsInstance(h, asyncio.TimerHandle) self.assertIn(h, self.loop._scheduled) self.assertNotIn(h, self.loop._ready) def test_call_later_negative_delays(self): calls = [] def cb(arg): calls.append(arg) self.loop._process_events = mock.Mock() self.loop.call_later(-1, cb, 'a') self.loop.call_later(-2, cb, 'b') test_utils.run_briefly(self.loop) self.assertEqual(calls, ['b', 'a']) def test_time_and_call_at(self): def cb(): self.loop.stop() self.loop._process_events = mock.Mock() delay = 0.1 when = self.loop.time() + delay self.loop.call_at(when, cb) t0 = self.loop.time() self.loop.run_forever() dt = self.loop.time() - t0 # 50 ms: maximum granularity of the event loop self.assertGreaterEqual(dt, delay - 0.050, dt) # tolerate a difference of +800 ms because some Python buildbots # are really slow self.assertLessEqual(dt, 0.9, dt) def check_thread(self, loop, debug): def cb(): pass loop.set_debug(debug) if debug: msg = ("Non-thread-safe operation invoked on an event loop other " "than the current one") with self.assertRaisesRegex(RuntimeError, msg): loop.call_soon(cb) with self.assertRaisesRegex(RuntimeError, msg): loop.call_later(60, cb) with self.assertRaisesRegex(RuntimeError, msg): loop.call_at(loop.time() + 60, cb) else: loop.call_soon(cb) loop.call_later(60, cb) loop.call_at(loop.time() + 60, cb) def test_check_thread(self): def check_in_thread(loop, event, debug, create_loop, fut): # wait until the event loop is running event.wait() try: if create_loop: loop2 = base_events.BaseEventLoop() try: asyncio.set_event_loop(loop2) self.check_thread(loop, debug) finally: asyncio.set_event_loop(None) loop2.close() else: self.check_thread(loop, debug) except Exception as exc: loop.call_soon_threadsafe(fut.set_exception, exc) else: loop.call_soon_threadsafe(fut.set_result, None) def test_thread(loop, debug, create_loop=False): event = threading.Event() fut = asyncio.Future(loop=loop) loop.call_soon(event.set) args = (loop, event, debug, create_loop, fut) thread = threading.Thread(target=check_in_thread, args=args) thread.start() loop.run_until_complete(fut) thread.join() self.loop._process_events = mock.Mock() self.loop._write_to_self = mock.Mock() # raise RuntimeError if the thread has no event loop test_thread(self.loop, True) # check disabled if debug mode is disabled test_thread(self.loop, False) # raise RuntimeError if the event loop of the thread is not the called # event loop test_thread(self.loop, True, create_loop=True) # check disabled if debug mode is disabled test_thread(self.loop, False, create_loop=True) def test_run_once_in_executor_plain(self): def cb(): pass f = asyncio.Future(loop=self.loop) executor = mock.Mock() executor.submit.return_value = f self.loop.set_default_executor(executor) res = self.loop.run_in_executor(None, cb) self.assertIs(f, res) executor = mock.Mock() executor.submit.return_value = f res = self.loop.run_in_executor(executor, cb) self.assertIs(f, res) self.assertTrue(executor.submit.called) f.cancel() # Don't complain about abandoned Future. def test__run_once(self): h1 = asyncio.TimerHandle(time.monotonic() + 5.0, lambda: True, (), self.loop) h2 = asyncio.TimerHandle(time.monotonic() + 10.0, lambda: True, (), self.loop) h1.cancel() self.loop._process_events = mock.Mock() self.loop._scheduled.append(h1) self.loop._scheduled.append(h2) self.loop._run_once() t = self.loop._selector.select.call_args[0][0] self.assertTrue(9.5 < t < 10.5, t) self.assertEqual([h2], self.loop._scheduled) self.assertTrue(self.loop._process_events.called) def test_set_debug(self): self.loop.set_debug(True) self.assertTrue(self.loop.get_debug()) self.loop.set_debug(False) self.assertFalse(self.loop.get_debug()) @mock.patch('asyncio.base_events.logger') def test__run_once_logging(self, m_logger): def slow_select(timeout): # Sleep a bit longer than a second to avoid timer resolution # issues. time.sleep(1.1) return [] # logging needs debug flag self.loop.set_debug(True) # Log to INFO level if timeout > 1.0 sec. self.loop._selector.select = slow_select self.loop._process_events = mock.Mock() self.loop._run_once() self.assertEqual(logging.INFO, m_logger.log.call_args[0][0]) def fast_select(timeout): time.sleep(0.001) return [] self.loop._selector.select = fast_select self.loop._run_once() self.assertEqual(logging.DEBUG, m_logger.log.call_args[0][0]) def test__run_once_schedule_handle(self): handle = None processed = False def cb(loop): nonlocal processed, handle processed = True handle = loop.call_soon(lambda: True) h = asyncio.TimerHandle(time.monotonic() - 1, cb, (self.loop,), self.loop) self.loop._process_events = mock.Mock() self.loop._scheduled.append(h) self.loop._run_once() self.assertTrue(processed) self.assertEqual([handle], list(self.loop._ready)) def test__run_once_cancelled_event_cleanup(self): self.loop._process_events = mock.Mock() self.assertTrue( 0 < base_events._MIN_CANCELLED_TIMER_HANDLES_FRACTION < 1.0) def cb(): pass # Set up one "blocking" event that will not be cancelled to # ensure later cancelled events do not make it to the head # of the queue and get cleaned. not_cancelled_count = 1 self.loop.call_later(3000, cb) # Add less than threshold (base_events._MIN_SCHEDULED_TIMER_HANDLES) # cancelled handles, ensure they aren't removed cancelled_count = 2 for x in range(2): h = self.loop.call_later(3600, cb) h.cancel() # Add some cancelled events that will be at head and removed cancelled_count += 2 for x in range(2): h = self.loop.call_later(100, cb) h.cancel() # This test is invalid if _MIN_SCHEDULED_TIMER_HANDLES is too low self.assertLessEqual(cancelled_count + not_cancelled_count, base_events._MIN_SCHEDULED_TIMER_HANDLES) self.assertEqual(self.loop._timer_cancelled_count, cancelled_count) self.loop._run_once() cancelled_count -= 2 self.assertEqual(self.loop._timer_cancelled_count, cancelled_count) self.assertEqual(len(self.loop._scheduled), cancelled_count + not_cancelled_count) # Need enough events to pass _MIN_CANCELLED_TIMER_HANDLES_FRACTION # so that deletion of cancelled events will occur on next _run_once add_cancel_count = int(math.ceil( base_events._MIN_SCHEDULED_TIMER_HANDLES * base_events._MIN_CANCELLED_TIMER_HANDLES_FRACTION)) + 1 add_not_cancel_count = max(base_events._MIN_SCHEDULED_TIMER_HANDLES - add_cancel_count, 0) # Add some events that will not be cancelled not_cancelled_count += add_not_cancel_count for x in range(add_not_cancel_count): self.loop.call_later(3600, cb) # Add enough cancelled events cancelled_count += add_cancel_count for x in range(add_cancel_count): h = self.loop.call_later(3600, cb) h.cancel() # Ensure all handles are still scheduled self.assertEqual(len(self.loop._scheduled), cancelled_count + not_cancelled_count) self.loop._run_once() # Ensure cancelled events were removed self.assertEqual(len(self.loop._scheduled), not_cancelled_count) # Ensure only uncancelled events remain scheduled self.assertTrue(all([not x._cancelled for x in self.loop._scheduled])) def test_run_until_complete_type_error(self): self.assertRaises(TypeError, self.loop.run_until_complete, 'blah') def test_run_until_complete_loop(self): task = asyncio.Future(loop=self.loop) other_loop = self.new_test_loop() self.addCleanup(other_loop.close) self.assertRaises(ValueError, other_loop.run_until_complete, task) def test_subprocess_exec_invalid_args(self): args = [sys.executable, '-c', 'pass'] # missing program parameter (empty args) self.assertRaises(TypeError, self.loop.run_until_complete, self.loop.subprocess_exec, asyncio.SubprocessProtocol) # expected multiple arguments, not a list self.assertRaises(TypeError, self.loop.run_until_complete, self.loop.subprocess_exec, asyncio.SubprocessProtocol, args) # program arguments must be strings, not int self.assertRaises(TypeError, self.loop.run_until_complete, self.loop.subprocess_exec, asyncio.SubprocessProtocol, sys.executable, 123) # universal_newlines, shell, bufsize must not be set self.assertRaises(TypeError, self.loop.run_until_complete, self.loop.subprocess_exec, asyncio.SubprocessProtocol, *args, universal_newlines=True) self.assertRaises(TypeError, self.loop.run_until_complete, self.loop.subprocess_exec, asyncio.SubprocessProtocol, *args, shell=True) self.assertRaises(TypeError, self.loop.run_until_complete, self.loop.subprocess_exec, asyncio.SubprocessProtocol, *args, bufsize=4096) def test_subprocess_shell_invalid_args(self): # expected a string, not an int or a list self.assertRaises(TypeError, self.loop.run_until_complete, self.loop.subprocess_shell, asyncio.SubprocessProtocol, 123) self.assertRaises(TypeError, self.loop.run_until_complete, self.loop.subprocess_shell, asyncio.SubprocessProtocol, [sys.executable, '-c', 'pass']) # universal_newlines, shell, bufsize must not be set self.assertRaises(TypeError, self.loop.run_until_complete, self.loop.subprocess_shell, asyncio.SubprocessProtocol, 'exit 0', universal_newlines=True) self.assertRaises(TypeError, self.loop.run_until_complete, self.loop.subprocess_shell, asyncio.SubprocessProtocol, 'exit 0', shell=True) self.assertRaises(TypeError, self.loop.run_until_complete, self.loop.subprocess_shell, asyncio.SubprocessProtocol, 'exit 0', bufsize=4096) def test_default_exc_handler_callback(self): self.loop._process_events = mock.Mock() def zero_error(fut): fut.set_result(True) 1/0 # Test call_soon (events.Handle) with mock.patch('asyncio.base_events.logger') as log: fut = asyncio.Future(loop=self.loop) self.loop.call_soon(zero_error, fut) fut.add_done_callback(lambda fut: self.loop.stop()) self.loop.run_forever() log.error.assert_called_with( test_utils.MockPattern('Exception in callback.*zero'), exc_info=(ZeroDivisionError, MOCK_ANY, MOCK_ANY)) # Test call_later (events.TimerHandle) with mock.patch('asyncio.base_events.logger') as log: fut = asyncio.Future(loop=self.loop) self.loop.call_later(0.01, zero_error, fut) fut.add_done_callback(lambda fut: self.loop.stop()) self.loop.run_forever() log.error.assert_called_with( test_utils.MockPattern('Exception in callback.*zero'), exc_info=(ZeroDivisionError, MOCK_ANY, MOCK_ANY)) def test_default_exc_handler_coro(self): self.loop._process_events = mock.Mock() @asyncio.coroutine def zero_error_coro(): yield from asyncio.sleep(0.01, loop=self.loop) 1/0 # Test Future.__del__ with mock.patch('asyncio.base_events.logger') as log: fut = asyncio.ensure_future(zero_error_coro(), loop=self.loop) fut.add_done_callback(lambda *args: self.loop.stop()) self.loop.run_forever() fut = None # Trigger Future.__del__ or futures._TracebackLogger support.gc_collect() if PY34: # Future.__del__ in Python 3.4 logs error with # an actual exception context log.error.assert_called_with( test_utils.MockPattern('.*exception was never retrieved'), exc_info=(ZeroDivisionError, MOCK_ANY, MOCK_ANY)) else: # futures._TracebackLogger logs only textual traceback log.error.assert_called_with( test_utils.MockPattern( '.*exception was never retrieved.*ZeroDiv'), exc_info=False) def test_set_exc_handler_invalid(self): with self.assertRaisesRegex(TypeError, 'A callable object or None'): self.loop.set_exception_handler('spam') def test_set_exc_handler_custom(self): def zero_error(): 1/0 def run_loop(): handle = self.loop.call_soon(zero_error) self.loop._run_once() return handle self.loop.set_debug(True) self.loop._process_events = mock.Mock() self.assertIsNone(self.loop.get_exception_handler()) mock_handler = mock.Mock() self.loop.set_exception_handler(mock_handler) self.assertIs(self.loop.get_exception_handler(), mock_handler) handle = run_loop() mock_handler.assert_called_with(self.loop, { 'exception': MOCK_ANY, 'message': test_utils.MockPattern( 'Exception in callback.*zero_error'), 'handle': handle, 'source_traceback': handle._source_traceback, }) mock_handler.reset_mock() self.loop.set_exception_handler(None) with mock.patch('asyncio.base_events.logger') as log: run_loop() log.error.assert_called_with( test_utils.MockPattern( 'Exception in callback.*zero'), exc_info=(ZeroDivisionError, MOCK_ANY, MOCK_ANY)) assert not mock_handler.called def test_set_exc_handler_broken(self): def run_loop(): def zero_error(): 1/0 self.loop.call_soon(zero_error) self.loop._run_once() def handler(loop, context): raise AttributeError('spam') self.loop._process_events = mock.Mock() self.loop.set_exception_handler(handler) with mock.patch('asyncio.base_events.logger') as log: run_loop() log.error.assert_called_with( test_utils.MockPattern( 'Unhandled error in exception handler'), exc_info=(AttributeError, MOCK_ANY, MOCK_ANY)) def test_default_exc_handler_broken(self): _context = None class Loop(base_events.BaseEventLoop): _selector = mock.Mock() _process_events = mock.Mock() def default_exception_handler(self, context): nonlocal _context _context = context # Simulates custom buggy "default_exception_handler" raise ValueError('spam') loop = Loop() self.addCleanup(loop.close) asyncio.set_event_loop(loop) def run_loop(): def zero_error(): 1/0 loop.call_soon(zero_error) loop._run_once() with mock.patch('asyncio.base_events.logger') as log: run_loop() log.error.assert_called_with( 'Exception in default exception handler', exc_info=True) def custom_handler(loop, context): raise ValueError('ham') _context = None loop.set_exception_handler(custom_handler) with mock.patch('asyncio.base_events.logger') as log: run_loop() log.error.assert_called_with( test_utils.MockPattern('Exception in default exception.*' 'while handling.*in custom'), exc_info=True) # Check that original context was passed to default # exception handler. self.assertIn('context', _context) self.assertIs(type(_context['context']['exception']), ZeroDivisionError) def test_set_task_factory_invalid(self): with self.assertRaisesRegex( TypeError, 'task factory must be a callable or None'): self.loop.set_task_factory(1) self.assertIsNone(self.loop.get_task_factory()) def test_set_task_factory(self): self.loop._process_events = mock.Mock() class MyTask(asyncio.Task): pass @asyncio.coroutine def coro(): pass factory = lambda loop, coro: MyTask(coro, loop=loop) self.assertIsNone(self.loop.get_task_factory()) self.loop.set_task_factory(factory) self.assertIs(self.loop.get_task_factory(), factory) task = self.loop.create_task(coro()) self.assertTrue(isinstance(task, MyTask)) self.loop.run_until_complete(task) self.loop.set_task_factory(None) self.assertIsNone(self.loop.get_task_factory()) task = self.loop.create_task(coro()) self.assertTrue(isinstance(task, asyncio.Task)) self.assertFalse(isinstance(task, MyTask)) self.loop.run_until_complete(task) def test_env_var_debug(self): code = '\n'.join(( 'import asyncio', 'loop = asyncio.get_event_loop()', 'print(loop.get_debug())')) # Test with -E to not fail if the unit test was run with # PYTHONASYNCIODEBUG set to a non-empty string sts, stdout, stderr = assert_python_ok('-E', '-c', code) self.assertEqual(stdout.rstrip(), b'False') sts, stdout, stderr = assert_python_ok('-c', code, PYTHONASYNCIODEBUG='') self.assertEqual(stdout.rstrip(), b'False') sts, stdout, stderr = assert_python_ok('-c', code, PYTHONASYNCIODEBUG='1') self.assertEqual(stdout.rstrip(), b'True') sts, stdout, stderr = assert_python_ok('-E', '-c', code, PYTHONASYNCIODEBUG='1') self.assertEqual(stdout.rstrip(), b'False') def test_create_task(self): class MyTask(asyncio.Task): pass @asyncio.coroutine def test(): pass class EventLoop(base_events.BaseEventLoop): def create_task(self, coro): return MyTask(coro, loop=loop) loop = EventLoop() self.set_event_loop(loop) coro = test() task = asyncio.ensure_future(coro, loop=loop) self.assertIsInstance(task, MyTask) # make warnings quiet task._log_destroy_pending = False coro.close() def test_run_forever_keyboard_interrupt(self): # Python issue #22601: ensure that the temporary task created by # run_forever() consumes the KeyboardInterrupt and so don't log # a warning @asyncio.coroutine def raise_keyboard_interrupt(): raise KeyboardInterrupt self.loop._process_events = mock.Mock() self.loop.call_exception_handler = mock.Mock() try: self.loop.run_until_complete(raise_keyboard_interrupt()) except KeyboardInterrupt: pass self.loop.close() support.gc_collect() self.assertFalse(self.loop.call_exception_handler.called) def test_run_until_complete_baseexception(self): # Python issue #22429: run_until_complete() must not schedule a pending # call to stop() if the future raised a BaseException @asyncio.coroutine def raise_keyboard_interrupt(): raise KeyboardInterrupt self.loop._process_events = mock.Mock() try: self.loop.run_until_complete(raise_keyboard_interrupt()) except KeyboardInterrupt: pass def func(): self.loop.stop() func.called = True func.called = False try: self.loop.call_soon(func) self.loop.run_forever() except KeyboardInterrupt: pass self.assertTrue(func.called) def test_single_selecter_event_callback_after_stopping(self): # Python issue #25593: A stopped event loop may cause event callbacks # to run more than once. event_sentinel = object() callcount = 0 doer = None def proc_events(event_list): nonlocal doer if event_sentinel in event_list: doer = self.loop.call_soon(do_event) def do_event(): nonlocal callcount callcount += 1 self.loop.call_soon(clear_selector) def clear_selector(): doer.cancel() self.loop._selector.select.return_value = () self.loop._process_events = proc_events self.loop._selector.select.return_value = (event_sentinel,) for i in range(1, 3): with self.subTest('Loop %d/2' % i): self.loop.call_soon(self.loop.stop) self.loop.run_forever() self.assertEqual(callcount, 1) def test_run_once(self): # Simple test for test_utils.run_once(). It may seem strange # to have a test for this (the function isn't even used!) but # it's a de-factor standard API for library tests. This tests # the idiom: loop.call_soon(loop.stop); loop.run_forever(). count = 0 def callback(): nonlocal count count += 1 self.loop._process_events = mock.Mock() self.loop.call_soon(callback) test_utils.run_once(self.loop) self.assertEqual(count, 1) def test_run_forever_pre_stopped(self): # Test that the old idiom for pre-stopping the loop works. self.loop._process_events = mock.Mock() self.loop.stop() self.loop.run_forever() self.loop._selector.select.assert_called_once_with(0) async def leave_unfinalized_asyncgen(self): # Create an async generator, iterate it partially, and leave it # to be garbage collected. # Used in async generator finalization tests. # Depends on implementation details of garbage collector. Changes # in gc may break this function. status = {'started': False, 'stopped': False, 'finalized': False} async def agen(): status['started'] = True try: for item in ['ZERO', 'ONE', 'TWO', 'THREE', 'FOUR']: yield item finally: status['finalized'] = True ag = agen() ai = ag.__aiter__() async def iter_one(): try: item = await ai.__anext__() except StopAsyncIteration: return if item == 'THREE': status['stopped'] = True return self.loop.create_task(iter_one()) self.loop.create_task(iter_one()) return status def test_asyncgen_finalization_by_gc(self): # Async generators should be finalized when garbage collected. self.loop._process_events = mock.Mock() self.loop._write_to_self = mock.Mock() with support.disable_gc(): status = self.loop.run_until_complete(self.leave_unfinalized_asyncgen()) while not status['stopped']: test_utils.run_briefly(self.loop) self.assertTrue(status['started']) self.assertTrue(status['stopped']) self.assertFalse(status['finalized']) support.gc_collect() test_utils.run_briefly(self.loop) self.assertTrue(status['finalized']) def test_asyncgen_finalization_by_gc_in_other_thread(self): # Python issue 34769: If garbage collector runs in another # thread, async generators will not finalize in debug # mode. self.loop._process_events = mock.Mock() self.loop._write_to_self = mock.Mock() self.loop.set_debug(True) with support.disable_gc(): status = self.loop.run_until_complete(self.leave_unfinalized_asyncgen()) while not status['stopped']: test_utils.run_briefly(self.loop) self.assertTrue(status['started']) self.assertTrue(status['stopped']) self.assertFalse(status['finalized']) self.loop.run_until_complete( self.loop.run_in_executor(None, support.gc_collect)) test_utils.run_briefly(self.loop) self.assertTrue(status['finalized']) class MyProto(asyncio.Protocol): done = None def __init__(self, create_future=False): self.state = 'INITIAL' self.nbytes = 0 if create_future: self.done = asyncio.Future() def connection_made(self, transport): self.transport = transport assert self.state == 'INITIAL', self.state self.state = 'CONNECTED' transport.write(b'GET / HTTP/1.0\r\nHost: example.com\r\n\r\n') def data_received(self, data): assert self.state == 'CONNECTED', self.state self.nbytes += len(data) def eof_received(self): assert self.state == 'CONNECTED', self.state self.state = 'EOF' def connection_lost(self, exc): assert self.state in ('CONNECTED', 'EOF'), self.state self.state = 'CLOSED' if self.done: self.done.set_result(None) class MyDatagramProto(asyncio.DatagramProtocol): done = None def __init__(self, create_future=False, loop=None): self.state = 'INITIAL' self.nbytes = 0 if create_future: self.done = asyncio.Future(loop=loop) def connection_made(self, transport): self.transport = transport assert self.state == 'INITIAL', self.state self.state = 'INITIALIZED' def datagram_received(self, data, addr): assert self.state == 'INITIALIZED', self.state self.nbytes += len(data) def error_received(self, exc): assert self.state == 'INITIALIZED', self.state def connection_lost(self, exc): assert self.state == 'INITIALIZED', self.state self.state = 'CLOSED' if self.done: self.done.set_result(None) class BaseEventLoopWithSelectorTests(test_utils.TestCase): def setUp(self): super().setUp() self.loop = asyncio.new_event_loop() self.set_event_loop(self.loop) @patch_socket def test_create_connection_multiple_errors(self, m_socket): class MyProto(asyncio.Protocol): pass @asyncio.coroutine def getaddrinfo(*args, **kw): yield from [] return [(2, 1, 6, '', ('107.6.106.82', 80)), (2, 1, 6, '', ('107.6.106.82', 80))] def getaddrinfo_task(*args, **kwds): return asyncio.Task(getaddrinfo(*args, **kwds), loop=self.loop) idx = -1 errors = ['err1', 'err2'] def _socket(*args, **kw): nonlocal idx, errors idx += 1 raise OSError(errors[idx]) m_socket.socket = _socket self.loop.getaddrinfo = getaddrinfo_task coro = self.loop.create_connection(MyProto, 'example.com', 80) with self.assertRaises(OSError) as cm: self.loop.run_until_complete(coro) self.assertEqual(str(cm.exception), 'Multiple exceptions: err1, err2') @patch_socket def test_create_connection_timeout(self, m_socket): # Ensure that the socket is closed on timeout sock = mock.Mock() m_socket.socket.return_value = sock def getaddrinfo(*args, **kw): fut = asyncio.Future(loop=self.loop) addr = (socket.AF_INET, socket.SOCK_STREAM, 0, '', ('127.0.0.1', 80)) fut.set_result([addr]) return fut self.loop.getaddrinfo = getaddrinfo with mock.patch.object(self.loop, 'sock_connect', side_effect=asyncio.TimeoutError): coro = self.loop.create_connection(MyProto, '127.0.0.1', 80) with self.assertRaises(asyncio.TimeoutError): self.loop.run_until_complete(coro) self.assertTrue(sock.close.called) def test_create_connection_host_port_sock(self): coro = self.loop.create_connection( MyProto, 'example.com', 80, sock=object()) self.assertRaises(ValueError, self.loop.run_until_complete, coro) def test_create_connection_wrong_sock(self): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) with sock: coro = self.loop.create_connection(MyProto, sock=sock) with self.assertRaisesRegex(ValueError, 'A Stream Socket was expected'): self.loop.run_until_complete(coro) def test_create_server_wrong_sock(self): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) with sock: coro = self.loop.create_server(MyProto, sock=sock) with self.assertRaisesRegex(ValueError, 'A Stream Socket was expected'): self.loop.run_until_complete(coro) @unittest.skipUnless(hasattr(socket, 'SOCK_NONBLOCK'), 'no socket.SOCK_NONBLOCK (linux only)') def test_create_server_stream_bittype(self): sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM | socket.SOCK_NONBLOCK) with sock: coro = self.loop.create_server(lambda: None, sock=sock) srv = self.loop.run_until_complete(coro) srv.close() self.loop.run_until_complete(srv.wait_closed()) @unittest.skipUnless(hasattr(socket, 'AF_INET6'), 'no IPv6 support') def test_create_server_ipv6(self): async def main(): srv = await asyncio.start_server( lambda: None, '::1', 0, loop=self.loop) try: self.assertGreater(len(srv.sockets), 0) finally: srv.close() await srv.wait_closed() try: self.loop.run_until_complete(main()) except OSError as ex: if (hasattr(errno, 'EADDRNOTAVAIL') and ex.errno == errno.EADDRNOTAVAIL): self.skipTest('failed to bind to ::1') else: raise def test_create_datagram_endpoint_wrong_sock(self): sock = socket.socket(socket.AF_INET) with sock: coro = self.loop.create_datagram_endpoint(MyProto, sock=sock) with self.assertRaisesRegex(ValueError, 'A UDP Socket was expected'): self.loop.run_until_complete(coro) def test_create_connection_no_host_port_sock(self): coro = self.loop.create_connection(MyProto) self.assertRaises(ValueError, self.loop.run_until_complete, coro) def test_create_connection_no_getaddrinfo(self): @asyncio.coroutine def getaddrinfo(*args, **kw): yield from [] def getaddrinfo_task(*args, **kwds): return asyncio.Task(getaddrinfo(*args, **kwds), loop=self.loop) self.loop.getaddrinfo = getaddrinfo_task coro = self.loop.create_connection(MyProto, 'example.com', 80) self.assertRaises( OSError, self.loop.run_until_complete, coro) def test_create_connection_connect_err(self): @asyncio.coroutine def getaddrinfo(*args, **kw): yield from [] return [(2, 1, 6, '', ('107.6.106.82', 80))] def getaddrinfo_task(*args, **kwds): return asyncio.Task(getaddrinfo(*args, **kwds), loop=self.loop) self.loop.getaddrinfo = getaddrinfo_task self.loop.sock_connect = mock.Mock() self.loop.sock_connect.side_effect = OSError coro = self.loop.create_connection(MyProto, 'example.com', 80) self.assertRaises( OSError, self.loop.run_until_complete, coro) def test_create_connection_multiple(self): @asyncio.coroutine def getaddrinfo(*args, **kw): return [(2, 1, 6, '', ('0.0.0.1', 80)), (2, 1, 6, '', ('0.0.0.2', 80))] def getaddrinfo_task(*args, **kwds): return asyncio.Task(getaddrinfo(*args, **kwds), loop=self.loop) self.loop.getaddrinfo = getaddrinfo_task self.loop.sock_connect = mock.Mock() self.loop.sock_connect.side_effect = OSError coro = self.loop.create_connection( MyProto, 'example.com', 80, family=socket.AF_INET) with self.assertRaises(OSError): self.loop.run_until_complete(coro) @patch_socket def test_create_connection_multiple_errors_local_addr(self, m_socket): def bind(addr): if addr[0] == '0.0.0.1': err = OSError('Err') err.strerror = 'Err' raise err m_socket.socket.return_value.bind = bind @asyncio.coroutine def getaddrinfo(*args, **kw): return [(2, 1, 6, '', ('0.0.0.1', 80)), (2, 1, 6, '', ('0.0.0.2', 80))] def getaddrinfo_task(*args, **kwds): return asyncio.Task(getaddrinfo(*args, **kwds), loop=self.loop) self.loop.getaddrinfo = getaddrinfo_task self.loop.sock_connect = mock.Mock() self.loop.sock_connect.side_effect = OSError('Err2') coro = self.loop.create_connection( MyProto, 'example.com', 80, family=socket.AF_INET, local_addr=(None, 8080)) with self.assertRaises(OSError) as cm: self.loop.run_until_complete(coro) self.assertTrue(str(cm.exception).startswith('Multiple exceptions: ')) self.assertTrue(m_socket.socket.return_value.close.called) def _test_create_connection_ip_addr(self, m_socket, allow_inet_pton): # Test the fallback code, even if this system has inet_pton. if not allow_inet_pton: del m_socket.inet_pton m_socket.getaddrinfo = socket.getaddrinfo sock = m_socket.socket.return_value self.loop._add_reader = mock.Mock() self.loop._add_reader._is_coroutine = False self.loop._add_writer = mock.Mock() self.loop._add_writer._is_coroutine = False coro = self.loop.create_connection(asyncio.Protocol, '1.2.3.4', 80) t, p = self.loop.run_until_complete(coro) try: sock.connect.assert_called_with(('1.2.3.4', 80)) _, kwargs = m_socket.socket.call_args self.assertEqual(kwargs['family'], m_socket.AF_INET) self.assertEqual(kwargs['type'], m_socket.SOCK_STREAM) finally: t.close() test_utils.run_briefly(self.loop) # allow transport to close sock.family = socket.AF_INET6 coro = self.loop.create_connection(asyncio.Protocol, '::1', 80) t, p = self.loop.run_until_complete(coro) try: # Without inet_pton we use getaddrinfo, which transforms ('::1', 80) # to ('::1', 80, 0, 0). The last 0s are flow info, scope id. [address] = sock.connect.call_args[0] host, port = address[:2] self.assertRegex(host, r'::(0\.)*1') self.assertEqual(port, 80) _, kwargs = m_socket.socket.call_args self.assertEqual(kwargs['family'], m_socket.AF_INET6) self.assertEqual(kwargs['type'], m_socket.SOCK_STREAM) finally: t.close() test_utils.run_briefly(self.loop) # allow transport to close @patch_socket def test_create_connection_ip_addr(self, m_socket): self._test_create_connection_ip_addr(m_socket, True) @patch_socket def test_create_connection_no_inet_pton(self, m_socket): self._test_create_connection_ip_addr(m_socket, False) @patch_socket def test_create_connection_service_name(self, m_socket): m_socket.getaddrinfo = socket.getaddrinfo sock = m_socket.socket.return_value self.loop._add_reader = mock.Mock() self.loop._add_reader._is_coroutine = False self.loop._add_writer = mock.Mock() self.loop._add_writer._is_coroutine = False for service, port in ('http', 80), (b'http', 80): coro = self.loop.create_connection(asyncio.Protocol, '127.0.0.1', service) t, p = self.loop.run_until_complete(coro) try: sock.connect.assert_called_with(('127.0.0.1', port)) _, kwargs = m_socket.socket.call_args self.assertEqual(kwargs['family'], m_socket.AF_INET) self.assertEqual(kwargs['type'], m_socket.SOCK_STREAM) finally: t.close() test_utils.run_briefly(self.loop) # allow transport to close for service in 'nonsense', b'nonsense': coro = self.loop.create_connection(asyncio.Protocol, '127.0.0.1', service) with self.assertRaises(OSError): self.loop.run_until_complete(coro) def test_create_connection_no_local_addr(self): @asyncio.coroutine def getaddrinfo(host, *args, **kw): if host == 'example.com': return [(2, 1, 6, '', ('107.6.106.82', 80)), (2, 1, 6, '', ('107.6.106.82', 80))] else: return [] def getaddrinfo_task(*args, **kwds): return asyncio.Task(getaddrinfo(*args, **kwds), loop=self.loop) self.loop.getaddrinfo = getaddrinfo_task coro = self.loop.create_connection( MyProto, 'example.com', 80, family=socket.AF_INET, local_addr=(None, 8080)) self.assertRaises( OSError, self.loop.run_until_complete, coro) @patch_socket def test_create_connection_bluetooth(self, m_socket): # See http://bugs.python.org/issue27136, fallback to getaddrinfo when # we can't recognize an address is resolved, e.g. a Bluetooth address. addr = ('00:01:02:03:04:05', 1) def getaddrinfo(host, port, *args, **kw): assert (host, port) == addr return [(999, 1, 999, '', (addr, 1))] m_socket.getaddrinfo = getaddrinfo sock = m_socket.socket() coro = self.loop.sock_connect(sock, addr) self.loop.run_until_complete(coro) def test_create_connection_ssl_server_hostname_default(self): self.loop.getaddrinfo = mock.Mock() def mock_getaddrinfo(*args, **kwds): f = asyncio.Future(loop=self.loop) f.set_result([(socket.AF_INET, socket.SOCK_STREAM, socket.SOL_TCP, '', ('1.2.3.4', 80))]) return f self.loop.getaddrinfo.side_effect = mock_getaddrinfo self.loop.sock_connect = mock.Mock() self.loop.sock_connect.return_value = () self.loop._make_ssl_transport = mock.Mock() class _SelectorTransportMock: _sock = None def get_extra_info(self, key): return mock.Mock() def close(self): self._sock.close() def mock_make_ssl_transport(sock, protocol, sslcontext, waiter, **kwds): waiter.set_result(None) transport = _SelectorTransportMock() transport._sock = sock return transport self.loop._make_ssl_transport.side_effect = mock_make_ssl_transport ANY = mock.ANY # First try the default server_hostname. self.loop._make_ssl_transport.reset_mock() coro = self.loop.create_connection(MyProto, 'python.org', 80, ssl=True) transport, _ = self.loop.run_until_complete(coro) transport.close() self.loop._make_ssl_transport.assert_called_with( ANY, ANY, ANY, ANY, server_side=False, server_hostname='python.org') # Next try an explicit server_hostname. self.loop._make_ssl_transport.reset_mock() coro = self.loop.create_connection(MyProto, 'python.org', 80, ssl=True, server_hostname='perl.com') transport, _ = self.loop.run_until_complete(coro) transport.close() self.loop._make_ssl_transport.assert_called_with( ANY, ANY, ANY, ANY, server_side=False, server_hostname='perl.com') # Finally try an explicit empty server_hostname. self.loop._make_ssl_transport.reset_mock() coro = self.loop.create_connection(MyProto, 'python.org', 80, ssl=True, server_hostname='') transport, _ = self.loop.run_until_complete(coro) transport.close() self.loop._make_ssl_transport.assert_called_with(ANY, ANY, ANY, ANY, server_side=False, server_hostname='') def test_create_connection_no_ssl_server_hostname_errors(self): # When not using ssl, server_hostname must be None. coro = self.loop.create_connection(MyProto, 'python.org', 80, server_hostname='') self.assertRaises(ValueError, self.loop.run_until_complete, coro) coro = self.loop.create_connection(MyProto, 'python.org', 80, server_hostname='python.org') self.assertRaises(ValueError, self.loop.run_until_complete, coro) def test_create_connection_ssl_server_hostname_errors(self): # When using ssl, server_hostname may be None if host is non-empty. coro = self.loop.create_connection(MyProto, '', 80, ssl=True) self.assertRaises(ValueError, self.loop.run_until_complete, coro) coro = self.loop.create_connection(MyProto, None, 80, ssl=True) self.assertRaises(ValueError, self.loop.run_until_complete, coro) sock = socket.socket() coro = self.loop.create_connection(MyProto, None, None, ssl=True, sock=sock) self.addCleanup(sock.close) self.assertRaises(ValueError, self.loop.run_until_complete, coro) def test_create_server_empty_host(self): # if host is empty string use None instead host = object() @asyncio.coroutine def getaddrinfo(*args, **kw): nonlocal host host = args[0] yield from [] def getaddrinfo_task(*args, **kwds): return asyncio.Task(getaddrinfo(*args, **kwds), loop=self.loop) self.loop.getaddrinfo = getaddrinfo_task fut = self.loop.create_server(MyProto, '', 0) self.assertRaises(OSError, self.loop.run_until_complete, fut) self.assertIsNone(host) def test_create_server_host_port_sock(self): fut = self.loop.create_server( MyProto, '0.0.0.0', 0, sock=object()) self.assertRaises(ValueError, self.loop.run_until_complete, fut) def test_create_server_no_host_port_sock(self): fut = self.loop.create_server(MyProto) self.assertRaises(ValueError, self.loop.run_until_complete, fut) def test_create_server_no_getaddrinfo(self): getaddrinfo = self.loop.getaddrinfo = mock.Mock() getaddrinfo.return_value = [] f = self.loop.create_server(MyProto, 'python.org', 0) self.assertRaises(OSError, self.loop.run_until_complete, f) @patch_socket def test_create_server_nosoreuseport(self, m_socket): m_socket.getaddrinfo = socket.getaddrinfo del m_socket.SO_REUSEPORT m_socket.socket.return_value = mock.Mock() f = self.loop.create_server( MyProto, '0.0.0.0', 0, reuse_port=True) self.assertRaises(ValueError, self.loop.run_until_complete, f) @patch_socket def test_create_server_soreuseport_only_defined(self, m_socket): m_socket.getaddrinfo = socket.getaddrinfo m_socket.socket.return_value = mock.Mock() m_socket.SO_REUSEPORT = -1 f = self.loop.create_server( MyProto, '0.0.0.0', 0, reuse_port=True) self.assertRaises(ValueError, self.loop.run_until_complete, f) @patch_socket def test_create_server_cant_bind(self, m_socket): class Err(OSError): strerror = 'error' m_socket.getaddrinfo.return_value = [ (2, 1, 6, '', ('127.0.0.1', 10100))] m_socket.getaddrinfo._is_coroutine = False m_sock = m_socket.socket.return_value = mock.Mock() m_sock.bind.side_effect = Err fut = self.loop.create_server(MyProto, '0.0.0.0', 0) self.assertRaises(OSError, self.loop.run_until_complete, fut) self.assertTrue(m_sock.close.called) @patch_socket def test_create_datagram_endpoint_no_addrinfo(self, m_socket): m_socket.getaddrinfo.return_value = [] m_socket.getaddrinfo._is_coroutine = False coro = self.loop.create_datagram_endpoint( MyDatagramProto, local_addr=('localhost', 0)) self.assertRaises( OSError, self.loop.run_until_complete, coro) def test_create_datagram_endpoint_addr_error(self): coro = self.loop.create_datagram_endpoint( MyDatagramProto, local_addr='localhost') self.assertRaises( AssertionError, self.loop.run_until_complete, coro) coro = self.loop.create_datagram_endpoint( MyDatagramProto, local_addr=('localhost', 1, 2, 3)) self.assertRaises( AssertionError, self.loop.run_until_complete, coro) def test_create_datagram_endpoint_connect_err(self): self.loop.sock_connect = mock.Mock() self.loop.sock_connect.side_effect = OSError coro = self.loop.create_datagram_endpoint( asyncio.DatagramProtocol, remote_addr=('127.0.0.1', 0)) self.assertRaises( OSError, self.loop.run_until_complete, coro) @patch_socket def test_create_datagram_endpoint_socket_err(self, m_socket): m_socket.getaddrinfo = socket.getaddrinfo m_socket.socket.side_effect = OSError coro = self.loop.create_datagram_endpoint( asyncio.DatagramProtocol, family=socket.AF_INET) self.assertRaises( OSError, self.loop.run_until_complete, coro) coro = self.loop.create_datagram_endpoint( asyncio.DatagramProtocol, local_addr=('127.0.0.1', 0)) self.assertRaises( OSError, self.loop.run_until_complete, coro) @unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 not supported or enabled') def test_create_datagram_endpoint_no_matching_family(self): coro = self.loop.create_datagram_endpoint( asyncio.DatagramProtocol, remote_addr=('127.0.0.1', 0), local_addr=('::1', 0)) self.assertRaises( ValueError, self.loop.run_until_complete, coro) @patch_socket def test_create_datagram_endpoint_setblk_err(self, m_socket): m_socket.socket.return_value.setblocking.side_effect = OSError coro = self.loop.create_datagram_endpoint( asyncio.DatagramProtocol, family=socket.AF_INET) self.assertRaises( OSError, self.loop.run_until_complete, coro) self.assertTrue( m_socket.socket.return_value.close.called) def test_create_datagram_endpoint_noaddr_nofamily(self): coro = self.loop.create_datagram_endpoint( asyncio.DatagramProtocol) self.assertRaises(ValueError, self.loop.run_until_complete, coro) @patch_socket def test_create_datagram_endpoint_cant_bind(self, m_socket): class Err(OSError): pass m_socket.getaddrinfo = socket.getaddrinfo m_sock = m_socket.socket.return_value = mock.Mock() m_sock.bind.side_effect = Err fut = self.loop.create_datagram_endpoint( MyDatagramProto, local_addr=('127.0.0.1', 0), family=socket.AF_INET) self.assertRaises(Err, self.loop.run_until_complete, fut) self.assertTrue(m_sock.close.called) def test_create_datagram_endpoint_sock(self): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(('127.0.0.1', 0)) fut = self.loop.create_datagram_endpoint( lambda: MyDatagramProto(create_future=True, loop=self.loop), sock=sock) transport, protocol = self.loop.run_until_complete(fut) transport.close() self.loop.run_until_complete(protocol.done) self.assertEqual('CLOSED', protocol.state) def test_create_datagram_endpoint_sock_sockopts(self): class FakeSock: type = socket.SOCK_DGRAM fut = self.loop.create_datagram_endpoint( MyDatagramProto, local_addr=('127.0.0.1', 0), sock=FakeSock()) self.assertRaises(ValueError, self.loop.run_until_complete, fut) fut = self.loop.create_datagram_endpoint( MyDatagramProto, remote_addr=('127.0.0.1', 0), sock=FakeSock()) self.assertRaises(ValueError, self.loop.run_until_complete, fut) fut = self.loop.create_datagram_endpoint( MyDatagramProto, family=1, sock=FakeSock()) self.assertRaises(ValueError, self.loop.run_until_complete, fut) fut = self.loop.create_datagram_endpoint( MyDatagramProto, proto=1, sock=FakeSock()) self.assertRaises(ValueError, self.loop.run_until_complete, fut) fut = self.loop.create_datagram_endpoint( MyDatagramProto, flags=1, sock=FakeSock()) self.assertRaises(ValueError, self.loop.run_until_complete, fut) fut = self.loop.create_datagram_endpoint( MyDatagramProto, reuse_port=True, sock=FakeSock()) self.assertRaises(ValueError, self.loop.run_until_complete, fut) fut = self.loop.create_datagram_endpoint( MyDatagramProto, allow_broadcast=True, sock=FakeSock()) self.assertRaises(ValueError, self.loop.run_until_complete, fut) def test_create_datagram_endpoint_sockopts(self): # Socket options should not be applied unless asked for. # SO_REUSEPORT is not available on all platforms. coro = self.loop.create_datagram_endpoint( lambda: MyDatagramProto(create_future=True, loop=self.loop), local_addr=('127.0.0.1', 0)) transport, protocol = self.loop.run_until_complete(coro) sock = transport.get_extra_info('socket') reuseport_supported = hasattr(socket, 'SO_REUSEPORT') if reuseport_supported: self.assertFalse( sock.getsockopt( socket.SOL_SOCKET, socket.SO_REUSEPORT)) self.assertFalse( sock.getsockopt( socket.SOL_SOCKET, socket.SO_BROADCAST)) transport.close() self.loop.run_until_complete(protocol.done) self.assertEqual('CLOSED', protocol.state) coro = self.loop.create_datagram_endpoint( lambda: MyDatagramProto(create_future=True, loop=self.loop), local_addr=('127.0.0.1', 0), reuse_port=reuseport_supported, allow_broadcast=True) transport, protocol = self.loop.run_until_complete(coro) sock = transport.get_extra_info('socket') self.assertFalse( sock.getsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR)) if reuseport_supported: self.assertTrue( sock.getsockopt( socket.SOL_SOCKET, socket.SO_REUSEPORT)) self.assertTrue( sock.getsockopt( socket.SOL_SOCKET, socket.SO_BROADCAST)) transport.close() self.loop.run_until_complete(protocol.done) self.assertEqual('CLOSED', protocol.state) def test_create_datagram_endpoint_reuse_address_error(self): # bpo-37228: Ensure that explicit passing of `reuse_address=True` # raises an error, as it is not safe to use SO_REUSEADDR when using UDP coro = self.loop.create_datagram_endpoint( lambda: MyDatagramProto(create_future=True, loop=self.loop), local_addr=('127.0.0.1', 0), reuse_address=True) with self.assertRaises(ValueError): self.loop.run_until_complete(coro) def test_create_datagram_endpoint_reuse_address_warning(self): # bpo-37228: Deprecate *reuse_address* parameter coro = self.loop.create_datagram_endpoint( lambda: MyDatagramProto(create_future=True, loop=self.loop), local_addr=('127.0.0.1', 0), reuse_address=False) with self.assertWarns(DeprecationWarning): transport, protocol = self.loop.run_until_complete(coro) transport.close() self.loop.run_until_complete(protocol.done) self.assertEqual('CLOSED', protocol.state) @patch_socket def test_create_datagram_endpoint_nosoreuseport(self, m_socket): del m_socket.SO_REUSEPORT m_socket.socket.return_value = mock.Mock() coro = self.loop.create_datagram_endpoint( lambda: MyDatagramProto(loop=self.loop), local_addr=('127.0.0.1', 0), reuse_port=True) self.assertRaises(ValueError, self.loop.run_until_complete, coro) @patch_socket def test_create_datagram_endpoint_ip_addr(self, m_socket): def getaddrinfo(*args, **kw): self.fail('should not have called getaddrinfo') m_socket.getaddrinfo = getaddrinfo m_socket.socket.return_value.bind = bind = mock.Mock() self.loop._add_reader = mock.Mock() self.loop._add_reader._is_coroutine = False reuseport_supported = hasattr(socket, 'SO_REUSEPORT') coro = self.loop.create_datagram_endpoint( lambda: MyDatagramProto(loop=self.loop), local_addr=('1.2.3.4', 0), reuse_port=reuseport_supported) t, p = self.loop.run_until_complete(coro) try: bind.assert_called_with(('1.2.3.4', 0)) m_socket.socket.assert_called_with(family=m_socket.AF_INET, proto=m_socket.IPPROTO_UDP, type=m_socket.SOCK_DGRAM) finally: t.close() test_utils.run_briefly(self.loop) # allow transport to close def test_accept_connection_retry(self): sock = mock.Mock() sock.accept.side_effect = BlockingIOError() self.loop._accept_connection(MyProto, sock) self.assertFalse(sock.close.called) @mock.patch('asyncio.base_events.logger') def test_accept_connection_exception(self, m_log): sock = mock.Mock() sock.fileno.return_value = 10 sock.accept.side_effect = OSError(errno.EMFILE, 'Too many open files') self.loop._remove_reader = mock.Mock() self.loop.call_later = mock.Mock() self.loop._accept_connection(MyProto, sock) self.assertTrue(m_log.error.called) self.assertFalse(sock.close.called) self.loop._remove_reader.assert_called_with(10) self.loop.call_later.assert_called_with(constants.ACCEPT_RETRY_DELAY, # self.loop._start_serving mock.ANY, MyProto, sock, None, None, mock.ANY) def test_call_coroutine(self): @asyncio.coroutine def simple_coroutine(): pass self.loop.set_debug(True) coro_func = simple_coroutine coro_obj = coro_func() self.addCleanup(coro_obj.close) for func in (coro_func, coro_obj): with self.assertRaises(TypeError): self.loop.call_soon(func) with self.assertRaises(TypeError): self.loop.call_soon_threadsafe(func) with self.assertRaises(TypeError): self.loop.call_later(60, func) with self.assertRaises(TypeError): self.loop.call_at(self.loop.time() + 60, func) with self.assertRaises(TypeError): self.loop.run_in_executor(None, func) @mock.patch('asyncio.base_events.logger') def test_log_slow_callbacks(self, m_logger): def stop_loop_cb(loop): loop.stop() @asyncio.coroutine def stop_loop_coro(loop): yield from () loop.stop() asyncio.set_event_loop(self.loop) self.loop.set_debug(True) self.loop.slow_callback_duration = 0.0 # slow callback self.loop.call_soon(stop_loop_cb, self.loop) self.loop.run_forever() fmt, *args = m_logger.warning.call_args[0] self.assertRegex(fmt % tuple(args), "^Executing <Handle.*stop_loop_cb.*> " "took .* seconds$") # slow task asyncio.ensure_future(stop_loop_coro(self.loop), loop=self.loop) self.loop.run_forever() fmt, *args = m_logger.warning.call_args[0] self.assertRegex(fmt % tuple(args), "^Executing <Task.*stop_loop_coro.*> " "took .* seconds$") class RunningLoopTests(unittest.TestCase): def test_running_loop_within_a_loop(self): @asyncio.coroutine def runner(loop): loop.run_forever() loop = asyncio.new_event_loop() outer_loop = asyncio.new_event_loop() try: with self.assertRaisesRegex(RuntimeError, 'while another loop is running'): outer_loop.run_until_complete(runner(loop)) finally: loop.close() outer_loop.close() class TestSelectorUtils(test_utils.TestCase): def check_set_nodelay(self, sock): opt = sock.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY) self.assertFalse(opt) base_events._set_nodelay(sock) opt = sock.getsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY) self.assertTrue(opt) @unittest.skipUnless(hasattr(socket, 'TCP_NODELAY'), 'need socket.TCP_NODELAY') def test_set_nodelay(self): sock = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM, proto=socket.IPPROTO_TCP) with sock: self.check_set_nodelay(sock) sock = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM, proto=socket.IPPROTO_TCP) with sock: sock.setblocking(False) self.check_set_nodelay(sock) if __name__ == '__main__': unittest.main()
69,091
1,876
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_asyncio/echo2.py
import os if __name__ == '__main__': buf = os.read(0, 1024) os.write(1, b'OUT:'+buf) os.write(2, b'ERR:'+buf)
123
7
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_asyncio/test_subprocess.py
import signal import sys import unittest import warnings from unittest import mock import asyncio from asyncio import base_subprocess from asyncio import subprocess from asyncio import test_utils try: from test import support except ImportError: from asyncio import test_support as support if sys.platform != 'win32': from asyncio import unix_events # Program blocking PROGRAM_BLOCKED = [sys.executable, '-c', 'import time; time.sleep(3600)'] # Program copying input to output PROGRAM_CAT = [ sys.executable, '-c', ';'.join(('import sys', 'data = sys.stdin.buffer.read()', 'sys.stdout.buffer.write(data)'))] class TestSubprocessTransport(base_subprocess.BaseSubprocessTransport): def _start(self, *args, **kwargs): self._proc = mock.Mock() self._proc.stdin = None self._proc.stdout = None self._proc.stderr = None class SubprocessTransportTests(test_utils.TestCase): def setUp(self): super().setUp() self.loop = self.new_test_loop() self.set_event_loop(self.loop) def create_transport(self, waiter=None): protocol = mock.Mock() protocol.connection_made._is_coroutine = False protocol.process_exited._is_coroutine = False transport = TestSubprocessTransport( self.loop, protocol, ['test'], False, None, None, None, 0, waiter=waiter) return (transport, protocol) def test_proc_exited(self): waiter = asyncio.Future(loop=self.loop) transport, protocol = self.create_transport(waiter) transport._process_exited(6) self.loop.run_until_complete(waiter) self.assertEqual(transport.get_returncode(), 6) self.assertTrue(protocol.connection_made.called) self.assertTrue(protocol.process_exited.called) self.assertTrue(protocol.connection_lost.called) self.assertEqual(protocol.connection_lost.call_args[0], (None,)) self.assertFalse(transport.is_closing()) self.assertIsNone(transport._loop) self.assertIsNone(transport._proc) self.assertIsNone(transport._protocol) # methods must raise ProcessLookupError if the process exited self.assertRaises(ProcessLookupError, transport.send_signal, signal.SIGTERM) self.assertRaises(ProcessLookupError, transport.terminate) self.assertRaises(ProcessLookupError, transport.kill) transport.close() class SubprocessMixin: def test_stdin_stdout(self): args = PROGRAM_CAT @asyncio.coroutine def run(data): proc = yield from asyncio.create_subprocess_exec( *args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, loop=self.loop) # feed data proc.stdin.write(data) yield from proc.stdin.drain() proc.stdin.close() # get output and exitcode data = yield from proc.stdout.read() exitcode = yield from proc.wait() return (exitcode, data) task = run(b'some data') task = asyncio.wait_for(task, 60.0, loop=self.loop) exitcode, stdout = self.loop.run_until_complete(task) self.assertEqual(exitcode, 0) self.assertEqual(stdout, b'some data') def test_communicate(self): args = PROGRAM_CAT @asyncio.coroutine def run(data): proc = yield from asyncio.create_subprocess_exec( *args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, loop=self.loop) stdout, stderr = yield from proc.communicate(data) return proc.returncode, stdout task = run(b'some data') task = asyncio.wait_for(task, 60.0, loop=self.loop) exitcode, stdout = self.loop.run_until_complete(task) self.assertEqual(exitcode, 0) self.assertEqual(stdout, b'some data') def test_shell(self): create = asyncio.create_subprocess_shell('exit 7', loop=self.loop) proc = self.loop.run_until_complete(create) exitcode = self.loop.run_until_complete(proc.wait()) self.assertEqual(exitcode, 7) def test_start_new_session(self): # start the new process in a new session create = asyncio.create_subprocess_shell('exit 8', start_new_session=True, loop=self.loop) proc = self.loop.run_until_complete(create) exitcode = self.loop.run_until_complete(proc.wait()) self.assertEqual(exitcode, 8) def test_kill(self): args = PROGRAM_BLOCKED create = asyncio.create_subprocess_exec(*args, loop=self.loop) proc = self.loop.run_until_complete(create) proc.kill() returncode = self.loop.run_until_complete(proc.wait()) if sys.platform == 'win32': self.assertIsInstance(returncode, int) # expect 1 but sometimes get 0 else: self.assertEqual(-signal.SIGKILL, returncode) def test_terminate(self): args = PROGRAM_BLOCKED create = asyncio.create_subprocess_exec(*args, loop=self.loop) proc = self.loop.run_until_complete(create) proc.terminate() returncode = self.loop.run_until_complete(proc.wait()) if sys.platform == 'win32': self.assertIsInstance(returncode, int) # expect 1 but sometimes get 0 else: self.assertEqual(-signal.SIGTERM, returncode) @unittest.skipIf(sys.platform == 'win32', "Don't have SIGHUP") def test_send_signal(self): # bpo-31034: Make sure that we get the default signal handler (killing # the process). The parent process may have decided to ignore SIGHUP, # and signal handlers are inherited. old_handler = signal.signal(signal.SIGHUP, signal.SIG_DFL) try: code = 'import time; print("sleeping", flush=True); time.sleep(3600)' args = [sys.executable, '-c', code] create = asyncio.create_subprocess_exec(*args, stdout=subprocess.PIPE, loop=self.loop) proc = self.loop.run_until_complete(create) @asyncio.coroutine def send_signal(proc): # basic synchronization to wait until the program is sleeping line = yield from proc.stdout.readline() self.assertEqual(line, b'sleeping\n') proc.send_signal(signal.SIGHUP) returncode = (yield from proc.wait()) return returncode returncode = self.loop.run_until_complete(send_signal(proc)) self.assertEqual(-signal.SIGHUP, returncode) finally: signal.signal(signal.SIGHUP, old_handler) def prepare_broken_pipe_test(self): # buffer large enough to feed the whole pipe buffer large_data = b'x' * support.PIPE_MAX_SIZE # the program ends before the stdin can be feeded create = asyncio.create_subprocess_exec( sys.executable, '-c', 'pass', stdin=subprocess.PIPE, loop=self.loop) proc = self.loop.run_until_complete(create) return (proc, large_data) def test_stdin_broken_pipe(self): proc, large_data = self.prepare_broken_pipe_test() @asyncio.coroutine def write_stdin(proc, data): yield from asyncio.sleep(0.5, loop=self.loop) proc.stdin.write(data) yield from proc.stdin.drain() coro = write_stdin(proc, large_data) # drain() must raise BrokenPipeError or ConnectionResetError with test_utils.disable_logger(): self.assertRaises((BrokenPipeError, ConnectionResetError), self.loop.run_until_complete, coro) self.loop.run_until_complete(proc.wait()) def test_communicate_ignore_broken_pipe(self): proc, large_data = self.prepare_broken_pipe_test() # communicate() must ignore BrokenPipeError when feeding stdin with test_utils.disable_logger(): self.loop.run_until_complete(proc.communicate(large_data)) self.loop.run_until_complete(proc.wait()) def test_pause_reading(self): limit = 10 size = (limit * 2 + 1) @asyncio.coroutine def test_pause_reading(): code = '\n'.join(( 'import sys', 'sys.stdout.write("x" * %s)' % size, 'sys.stdout.flush()', )) connect_read_pipe = self.loop.connect_read_pipe @asyncio.coroutine def connect_read_pipe_mock(*args, **kw): transport, protocol = yield from connect_read_pipe(*args, **kw) transport.pause_reading = mock.Mock() transport.resume_reading = mock.Mock() return (transport, protocol) self.loop.connect_read_pipe = connect_read_pipe_mock proc = yield from asyncio.create_subprocess_exec( sys.executable, '-c', code, stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, limit=limit, loop=self.loop) stdout_transport = proc._transport.get_pipe_transport(1) stdout, stderr = yield from proc.communicate() # The child process produced more than limit bytes of output, # the stream reader transport should pause the protocol to not # allocate too much memory. return (stdout, stdout_transport) # Issue #22685: Ensure that the stream reader pauses the protocol # when the child process produces too much data stdout, transport = self.loop.run_until_complete(test_pause_reading()) self.assertEqual(stdout, b'x' * size) self.assertTrue(transport.pause_reading.called) self.assertTrue(transport.resume_reading.called) def test_stdin_not_inheritable(self): # asyncio issue #209: stdin must not be inheritable, otherwise # the Process.communicate() hangs @asyncio.coroutine def len_message(message): code = 'import sys; data = sys.stdin.read(); print(len(data))' proc = yield from asyncio.create_subprocess_exec( sys.executable, '-c', code, stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, close_fds=False, loop=self.loop) stdout, stderr = yield from proc.communicate(message) exitcode = yield from proc.wait() return (stdout, exitcode) output, exitcode = self.loop.run_until_complete(len_message(b'abc')) self.assertEqual(output.rstrip(), b'3') self.assertEqual(exitcode, 0) def test_empty_input(self): @asyncio.coroutine def empty_input(): code = 'import sys; data = sys.stdin.read(); print(len(data))' proc = yield from asyncio.create_subprocess_exec( sys.executable, '-c', code, stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, close_fds=False, loop=self.loop) stdout, stderr = yield from proc.communicate(b'') exitcode = yield from proc.wait() return (stdout, exitcode) output, exitcode = self.loop.run_until_complete(empty_input()) self.assertEqual(output.rstrip(), b'0') self.assertEqual(exitcode, 0) def test_cancel_process_wait(self): # Issue #23140: cancel Process.wait() @asyncio.coroutine def cancel_wait(): proc = yield from asyncio.create_subprocess_exec( *PROGRAM_BLOCKED, loop=self.loop) # Create an internal future waiting on the process exit task = self.loop.create_task(proc.wait()) self.loop.call_soon(task.cancel) try: yield from task except asyncio.CancelledError: pass # Cancel the future task.cancel() # Kill the process and wait until it is done proc.kill() yield from proc.wait() self.loop.run_until_complete(cancel_wait()) def test_cancel_make_subprocess_transport_exec(self): @asyncio.coroutine def cancel_make_transport(): coro = asyncio.create_subprocess_exec(*PROGRAM_BLOCKED, loop=self.loop) task = self.loop.create_task(coro) self.loop.call_soon(task.cancel) try: yield from task except asyncio.CancelledError: pass # ignore the log: # "Exception during subprocess creation, kill the subprocess" with test_utils.disable_logger(): self.loop.run_until_complete(cancel_make_transport()) def test_cancel_post_init(self): @asyncio.coroutine def cancel_make_transport(): coro = self.loop.subprocess_exec(asyncio.SubprocessProtocol, *PROGRAM_BLOCKED) task = self.loop.create_task(coro) self.loop.call_soon(task.cancel) try: yield from task except asyncio.CancelledError: pass # ignore the log: # "Exception during subprocess creation, kill the subprocess" with test_utils.disable_logger(): self.loop.run_until_complete(cancel_make_transport()) test_utils.run_briefly(self.loop) def test_close_kill_running(self): @asyncio.coroutine def kill_running(): create = self.loop.subprocess_exec(asyncio.SubprocessProtocol, *PROGRAM_BLOCKED) transport, protocol = yield from create kill_called = False def kill(): nonlocal kill_called kill_called = True orig_kill() proc = transport.get_extra_info('subprocess') orig_kill = proc.kill proc.kill = kill returncode = transport.get_returncode() transport.close() yield from transport._wait() return (returncode, kill_called) # Ignore "Close running child process: kill ..." log with test_utils.disable_logger(): returncode, killed = self.loop.run_until_complete(kill_running()) self.assertIsNone(returncode) # transport.close() must kill the process if it is still running self.assertTrue(killed) test_utils.run_briefly(self.loop) def test_close_dont_kill_finished(self): @asyncio.coroutine def kill_running(): create = self.loop.subprocess_exec(asyncio.SubprocessProtocol, *PROGRAM_BLOCKED) transport, protocol = yield from create proc = transport.get_extra_info('subprocess') # kill the process (but asyncio is not notified immediately) proc.kill() proc.wait() proc.kill = mock.Mock() proc_returncode = proc.poll() transport_returncode = transport.get_returncode() transport.close() return (proc_returncode, transport_returncode, proc.kill.called) # Ignore "Unknown child process pid ..." log of SafeChildWatcher, # emitted because the test already consumes the exit status: # proc.wait() with test_utils.disable_logger(): result = self.loop.run_until_complete(kill_running()) test_utils.run_briefly(self.loop) proc_returncode, transport_return_code, killed = result self.assertIsNotNone(proc_returncode) self.assertIsNone(transport_return_code) # transport.close() must not kill the process if it finished, even if # the transport was not notified yet self.assertFalse(killed) # Unlike SafeChildWatcher, FastChildWatcher does not pop the # callbacks if waitpid() is called elsewhere. Let's clear them # manually to avoid a warning when the watcher is detached. if sys.platform != 'win32' and \ isinstance(self, SubprocessFastWatcherTests): asyncio.get_child_watcher()._callbacks.clear() def test_popen_error(self): # Issue #24763: check that the subprocess transport is closed # when BaseSubprocessTransport fails if sys.platform == 'win32': target = 'asyncio.windows_utils.Popen' else: target = 'subprocess.Popen' with mock.patch(target) as popen: exc = ZeroDivisionError popen.side_effect = exc create = asyncio.create_subprocess_exec(sys.executable, '-c', 'pass', loop=self.loop) with warnings.catch_warnings(record=True) as warns: with self.assertRaises(exc): self.loop.run_until_complete(create) self.assertEqual(warns, []) def test_read_stdout_after_process_exit(self): @asyncio.coroutine def execute(): code = '\n'.join(['import sys', 'for _ in range(64):', ' sys.stdout.write("x" * 4096)', 'sys.stdout.flush()', 'sys.exit(1)']) fut = asyncio.create_subprocess_exec( sys.executable, '-c', code, stdout=asyncio.subprocess.PIPE, loop=self.loop) process = yield from fut while True: data = yield from process.stdout.read(65536) if data: yield from asyncio.sleep(0.3, loop=self.loop) else: break self.loop.run_until_complete(execute()) if sys.platform != 'win32': # Unix class SubprocessWatcherMixin(SubprocessMixin): Watcher = None def setUp(self): super().setUp() policy = asyncio.get_event_loop_policy() self.loop = policy.new_event_loop() self.set_event_loop(self.loop) watcher = self.Watcher() watcher.attach_loop(self.loop) policy.set_child_watcher(watcher) self.addCleanup(policy.set_child_watcher, None) class SubprocessSafeWatcherTests(SubprocessWatcherMixin, test_utils.TestCase): Watcher = unix_events.SafeChildWatcher class SubprocessFastWatcherTests(SubprocessWatcherMixin, test_utils.TestCase): Watcher = unix_events.FastChildWatcher else: # Windows class SubprocessProactorTests(SubprocessMixin, test_utils.TestCase): def setUp(self): super().setUp() self.loop = asyncio.ProactorEventLoop() self.set_event_loop(self.loop) if __name__ == '__main__': unittest.main()
20,451
534
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_asyncio/test_windows_events.py
import os import sys import unittest from unittest import mock if sys.platform != 'win32': raise unittest.SkipTest('Windows only') import _winapi import asyncio from asyncio import _overlapped from asyncio import test_utils from asyncio import windows_events class UpperProto(asyncio.Protocol): def __init__(self): self.buf = [] def connection_made(self, trans): self.trans = trans def data_received(self, data): self.buf.append(data) if b'\n' in data: self.trans.write(b''.join(self.buf).upper()) self.trans.close() class ProactorTests(test_utils.TestCase): def setUp(self): super().setUp() self.loop = asyncio.ProactorEventLoop() self.set_event_loop(self.loop) def test_close(self): a, b = self.loop._socketpair() trans = self.loop._make_socket_transport(a, asyncio.Protocol()) f = asyncio.ensure_future(self.loop.sock_recv(b, 100)) trans.close() self.loop.run_until_complete(f) self.assertEqual(f.result(), b'') b.close() def test_double_bind(self): ADDRESS = r'\\.\pipe\test_double_bind-%s' % os.getpid() server1 = windows_events.PipeServer(ADDRESS) with self.assertRaises(PermissionError): windows_events.PipeServer(ADDRESS) server1.close() def test_pipe(self): res = self.loop.run_until_complete(self._test_pipe()) self.assertEqual(res, 'done') def _test_pipe(self): ADDRESS = r'\\.\pipe\_test_pipe-%s' % os.getpid() with self.assertRaises(FileNotFoundError): yield from self.loop.create_pipe_connection( asyncio.Protocol, ADDRESS) [server] = yield from self.loop.start_serving_pipe( UpperProto, ADDRESS) self.assertIsInstance(server, windows_events.PipeServer) clients = [] for i in range(5): stream_reader = asyncio.StreamReader(loop=self.loop) protocol = asyncio.StreamReaderProtocol(stream_reader, loop=self.loop) trans, proto = yield from self.loop.create_pipe_connection( lambda: protocol, ADDRESS) self.assertIsInstance(trans, asyncio.Transport) self.assertEqual(protocol, proto) clients.append((stream_reader, trans)) for i, (r, w) in enumerate(clients): w.write('lower-{}\n'.format(i).encode()) for i, (r, w) in enumerate(clients): response = yield from r.readline() self.assertEqual(response, 'LOWER-{}\n'.format(i).encode()) w.close() server.close() with self.assertRaises(FileNotFoundError): yield from self.loop.create_pipe_connection( asyncio.Protocol, ADDRESS) return 'done' def test_connect_pipe_cancel(self): exc = OSError() exc.winerror = _overlapped.ERROR_PIPE_BUSY with mock.patch.object(_overlapped, 'ConnectPipe', side_effect=exc) as connect: coro = self.loop._proactor.connect_pipe('pipe_address') task = self.loop.create_task(coro) # check that it's possible to cancel connect_pipe() task.cancel() with self.assertRaises(asyncio.CancelledError): self.loop.run_until_complete(task) def test_wait_for_handle(self): event = _overlapped.CreateEvent(None, True, False, None) self.addCleanup(_winapi.CloseHandle, event) # Wait for unset event with 0.5s timeout; # result should be False at timeout fut = self.loop._proactor.wait_for_handle(event, 0.5) start = self.loop.time() done = self.loop.run_until_complete(fut) elapsed = self.loop.time() - start self.assertEqual(done, False) self.assertFalse(fut.result()) # bpo-31008: Tolerate only 450 ms (at least 500 ms expected), # because of bad clock resolution on Windows self.assertTrue(0.45 <= elapsed <= 0.9, elapsed) _overlapped.SetEvent(event) # Wait for set event; # result should be True immediately fut = self.loop._proactor.wait_for_handle(event, 10) start = self.loop.time() done = self.loop.run_until_complete(fut) elapsed = self.loop.time() - start self.assertEqual(done, True) self.assertTrue(fut.result()) self.assertTrue(0 <= elapsed < 0.3, elapsed) # asyncio issue #195: cancelling a done _WaitHandleFuture # must not crash fut.cancel() def test_wait_for_handle_cancel(self): event = _overlapped.CreateEvent(None, True, False, None) self.addCleanup(_winapi.CloseHandle, event) # Wait for unset event with a cancelled future; # CancelledError should be raised immediately fut = self.loop._proactor.wait_for_handle(event, 10) fut.cancel() start = self.loop.time() with self.assertRaises(asyncio.CancelledError): self.loop.run_until_complete(fut) elapsed = self.loop.time() - start self.assertTrue(0 <= elapsed < 0.1, elapsed) # asyncio issue #195: cancelling a _WaitHandleFuture twice # must not crash fut = self.loop._proactor.wait_for_handle(event) fut.cancel() fut.cancel() if __name__ == '__main__': unittest.main()
5,475
165
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_asyncio/test_unix_events.py
"""Tests for unix_events.py.""" import collections import errno import io import os import pathlib import signal import socket import stat import sys import tempfile import threading import unittest import warnings from unittest import mock if sys.platform == 'win32': raise unittest.SkipTest('UNIX only') import asyncio from asyncio import log from asyncio import test_utils from asyncio import unix_events MOCK_ANY = mock.ANY def close_pipe_transport(transport): # Don't call transport.close() because the event loop and the selector # are mocked if transport._pipe is None: return transport._pipe.close() transport._pipe = None @unittest.skipUnless(signal, 'Signals are not supported') class SelectorEventLoopSignalTests(test_utils.TestCase): def setUp(self): super().setUp() self.loop = asyncio.SelectorEventLoop() self.set_event_loop(self.loop) def test_check_signal(self): self.assertRaises( TypeError, self.loop._check_signal, '1') self.assertRaises( ValueError, self.loop._check_signal, signal.NSIG + 1) def test_handle_signal_no_handler(self): self.loop._handle_signal(signal.NSIG + 1) def test_handle_signal_cancelled_handler(self): h = asyncio.Handle(mock.Mock(), (), loop=mock.Mock()) h.cancel() self.loop._signal_handlers[signal.NSIG + 1] = h self.loop.remove_signal_handler = mock.Mock() self.loop._handle_signal(signal.NSIG + 1) self.loop.remove_signal_handler.assert_called_with(signal.NSIG + 1) @mock.patch('asyncio.unix_events.signal') def test_add_signal_handler_setup_error(self, m_signal): m_signal.NSIG = signal.NSIG m_signal.set_wakeup_fd.side_effect = ValueError self.assertRaises( RuntimeError, self.loop.add_signal_handler, signal.SIGINT, lambda: True) @mock.patch('asyncio.unix_events.signal') def test_add_signal_handler_coroutine_error(self, m_signal): m_signal.NSIG = signal.NSIG @asyncio.coroutine def simple_coroutine(): yield from [] # callback must not be a coroutine function coro_func = simple_coroutine coro_obj = coro_func() self.addCleanup(coro_obj.close) for func in (coro_func, coro_obj): self.assertRaisesRegex( TypeError, 'coroutines cannot be used with add_signal_handler', self.loop.add_signal_handler, signal.SIGINT, func) @mock.patch('asyncio.unix_events.signal') def test_add_signal_handler(self, m_signal): m_signal.NSIG = signal.NSIG cb = lambda: True self.loop.add_signal_handler(signal.SIGHUP, cb) h = self.loop._signal_handlers.get(signal.SIGHUP) self.assertIsInstance(h, asyncio.Handle) self.assertEqual(h._callback, cb) @mock.patch('asyncio.unix_events.signal') def test_add_signal_handler_install_error(self, m_signal): m_signal.NSIG = signal.NSIG def set_wakeup_fd(fd): if fd == -1: raise ValueError() m_signal.set_wakeup_fd = set_wakeup_fd class Err(OSError): errno = errno.EFAULT m_signal.signal.side_effect = Err self.assertRaises( Err, self.loop.add_signal_handler, signal.SIGINT, lambda: True) @mock.patch('asyncio.unix_events.signal') @mock.patch('asyncio.base_events.logger') def test_add_signal_handler_install_error2(self, m_logging, m_signal): m_signal.NSIG = signal.NSIG class Err(OSError): errno = errno.EINVAL m_signal.signal.side_effect = Err self.loop._signal_handlers[signal.SIGHUP] = lambda: True self.assertRaises( RuntimeError, self.loop.add_signal_handler, signal.SIGINT, lambda: True) self.assertFalse(m_logging.info.called) self.assertEqual(1, m_signal.set_wakeup_fd.call_count) @mock.patch('asyncio.unix_events.signal') @mock.patch('asyncio.base_events.logger') def test_add_signal_handler_install_error3(self, m_logging, m_signal): class Err(OSError): errno = errno.EINVAL m_signal.signal.side_effect = Err m_signal.NSIG = signal.NSIG self.assertRaises( RuntimeError, self.loop.add_signal_handler, signal.SIGINT, lambda: True) self.assertFalse(m_logging.info.called) self.assertEqual(2, m_signal.set_wakeup_fd.call_count) @mock.patch('asyncio.unix_events.signal') def test_remove_signal_handler(self, m_signal): m_signal.NSIG = signal.NSIG self.loop.add_signal_handler(signal.SIGHUP, lambda: True) self.assertTrue( self.loop.remove_signal_handler(signal.SIGHUP)) self.assertTrue(m_signal.set_wakeup_fd.called) self.assertTrue(m_signal.signal.called) self.assertEqual( (signal.SIGHUP, m_signal.SIG_DFL), m_signal.signal.call_args[0]) @mock.patch('asyncio.unix_events.signal') def test_remove_signal_handler_2(self, m_signal): m_signal.NSIG = signal.NSIG m_signal.SIGINT = signal.SIGINT self.loop.add_signal_handler(signal.SIGINT, lambda: True) self.loop._signal_handlers[signal.SIGHUP] = object() m_signal.set_wakeup_fd.reset_mock() self.assertTrue( self.loop.remove_signal_handler(signal.SIGINT)) self.assertFalse(m_signal.set_wakeup_fd.called) self.assertTrue(m_signal.signal.called) self.assertEqual( (signal.SIGINT, m_signal.default_int_handler), m_signal.signal.call_args[0]) @mock.patch('asyncio.unix_events.signal') @mock.patch('asyncio.base_events.logger') def test_remove_signal_handler_cleanup_error(self, m_logging, m_signal): m_signal.NSIG = signal.NSIG self.loop.add_signal_handler(signal.SIGHUP, lambda: True) m_signal.set_wakeup_fd.side_effect = ValueError self.loop.remove_signal_handler(signal.SIGHUP) self.assertTrue(m_logging.info) @mock.patch('asyncio.unix_events.signal') def test_remove_signal_handler_error(self, m_signal): m_signal.NSIG = signal.NSIG self.loop.add_signal_handler(signal.SIGHUP, lambda: True) m_signal.signal.side_effect = OSError self.assertRaises( OSError, self.loop.remove_signal_handler, signal.SIGHUP) @mock.patch('asyncio.unix_events.signal') def test_remove_signal_handler_error2(self, m_signal): m_signal.NSIG = signal.NSIG self.loop.add_signal_handler(signal.SIGHUP, lambda: True) class Err(OSError): errno = errno.EINVAL m_signal.signal.side_effect = Err self.assertRaises( RuntimeError, self.loop.remove_signal_handler, signal.SIGHUP) @mock.patch('asyncio.unix_events.signal') def test_close(self, m_signal): m_signal.NSIG = signal.NSIG self.loop.add_signal_handler(signal.SIGHUP, lambda: True) self.loop.add_signal_handler(signal.SIGCHLD, lambda: True) self.assertEqual(len(self.loop._signal_handlers), 2) m_signal.set_wakeup_fd.reset_mock() self.loop.close() self.assertEqual(len(self.loop._signal_handlers), 0) m_signal.set_wakeup_fd.assert_called_once_with(-1) @mock.patch('asyncio.unix_events.sys') @mock.patch('asyncio.unix_events.signal') def test_close_on_finalizing(self, m_signal, m_sys): m_signal.NSIG = signal.NSIG self.loop.add_signal_handler(signal.SIGHUP, lambda: True) self.assertEqual(len(self.loop._signal_handlers), 1) m_sys.is_finalizing.return_value = True m_signal.signal.reset_mock() with self.assertWarnsRegex(ResourceWarning, "skipping signal handlers removal"): self.loop.close() self.assertEqual(len(self.loop._signal_handlers), 0) self.assertFalse(m_signal.signal.called) @unittest.skipUnless(hasattr(socket, 'AF_UNIX'), 'UNIX Sockets are not supported') class SelectorEventLoopUnixSocketTests(test_utils.TestCase): def setUp(self): super().setUp() self.loop = asyncio.SelectorEventLoop() self.set_event_loop(self.loop) def test_create_unix_server_existing_path_sock(self): with test_utils.unix_socket_path() as path: sock = socket.socket(socket.AF_UNIX) sock.bind(path) sock.listen(1) sock.close() coro = self.loop.create_unix_server(lambda: None, path) srv = self.loop.run_until_complete(coro) srv.close() self.loop.run_until_complete(srv.wait_closed()) @unittest.skipUnless(hasattr(os, 'fspath'), 'no os.fspath') def test_create_unix_server_pathlib(self): with test_utils.unix_socket_path() as path: path = pathlib.Path(path) srv_coro = self.loop.create_unix_server(lambda: None, path) srv = self.loop.run_until_complete(srv_coro) srv.close() self.loop.run_until_complete(srv.wait_closed()) def test_create_unix_server_existing_path_nonsock(self): with tempfile.NamedTemporaryFile() as file: coro = self.loop.create_unix_server(lambda: None, file.name) with self.assertRaisesRegex(OSError, 'Address.*is already in use'): self.loop.run_until_complete(coro) def test_create_unix_server_ssl_bool(self): coro = self.loop.create_unix_server(lambda: None, path='spam', ssl=True) with self.assertRaisesRegex(TypeError, 'ssl argument must be an SSLContext'): self.loop.run_until_complete(coro) def test_create_unix_server_nopath_nosock(self): coro = self.loop.create_unix_server(lambda: None, path=None) with self.assertRaisesRegex(ValueError, 'path was not specified, and no sock'): self.loop.run_until_complete(coro) def test_create_unix_server_path_inetsock(self): sock = socket.socket() with sock: coro = self.loop.create_unix_server(lambda: None, path=None, sock=sock) with self.assertRaisesRegex(ValueError, 'A UNIX Domain Stream.*was expected'): self.loop.run_until_complete(coro) def test_create_unix_server_path_dgram(self): sock = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) with sock: coro = self.loop.create_unix_server(lambda: None, path=None, sock=sock) with self.assertRaisesRegex(ValueError, 'A UNIX Domain Stream.*was expected'): self.loop.run_until_complete(coro) @unittest.skipUnless(hasattr(socket, 'SOCK_NONBLOCK'), 'no socket.SOCK_NONBLOCK (linux only)') def test_create_unix_server_path_stream_bittype(self): sock = socket.socket( socket.AF_UNIX, socket.SOCK_STREAM | socket.SOCK_NONBLOCK) with tempfile.NamedTemporaryFile() as file: fn = file.name try: with sock: sock.bind(fn) coro = self.loop.create_unix_server(lambda: None, path=None, sock=sock) srv = self.loop.run_until_complete(coro) srv.close() self.loop.run_until_complete(srv.wait_closed()) finally: os.unlink(fn) def test_create_unix_connection_path_inetsock(self): sock = socket.socket() with sock: coro = self.loop.create_unix_connection(lambda: None, path=None, sock=sock) with self.assertRaisesRegex(ValueError, 'A UNIX Domain Stream.*was expected'): self.loop.run_until_complete(coro) @mock.patch('asyncio.unix_events.socket') def test_create_unix_server_bind_error(self, m_socket): # Ensure that the socket is closed on any bind error sock = mock.Mock() m_socket.socket.return_value = sock sock.bind.side_effect = OSError coro = self.loop.create_unix_server(lambda: None, path="/test") with self.assertRaises(OSError): self.loop.run_until_complete(coro) self.assertTrue(sock.close.called) sock.bind.side_effect = MemoryError coro = self.loop.create_unix_server(lambda: None, path="/test") with self.assertRaises(MemoryError): self.loop.run_until_complete(coro) self.assertTrue(sock.close.called) def test_create_unix_connection_path_sock(self): coro = self.loop.create_unix_connection( lambda: None, os.devnull, sock=object()) with self.assertRaisesRegex(ValueError, 'path and sock can not be'): self.loop.run_until_complete(coro) def test_create_unix_connection_nopath_nosock(self): coro = self.loop.create_unix_connection( lambda: None, None) with self.assertRaisesRegex(ValueError, 'no path and sock were specified'): self.loop.run_until_complete(coro) def test_create_unix_connection_nossl_serverhost(self): coro = self.loop.create_unix_connection( lambda: None, os.devnull, server_hostname='spam') with self.assertRaisesRegex(ValueError, 'server_hostname is only meaningful'): self.loop.run_until_complete(coro) def test_create_unix_connection_ssl_noserverhost(self): coro = self.loop.create_unix_connection( lambda: None, os.devnull, ssl=True) with self.assertRaisesRegex( ValueError, 'you have to pass server_hostname when using ssl'): self.loop.run_until_complete(coro) class UnixReadPipeTransportTests(test_utils.TestCase): def setUp(self): super().setUp() self.loop = self.new_test_loop() self.protocol = test_utils.make_test_protocol(asyncio.Protocol) self.pipe = mock.Mock(spec_set=io.RawIOBase) self.pipe.fileno.return_value = 5 blocking_patcher = mock.patch('asyncio.unix_events._set_nonblocking') blocking_patcher.start() self.addCleanup(blocking_patcher.stop) fstat_patcher = mock.patch('os.fstat') m_fstat = fstat_patcher.start() st = mock.Mock() st.st_mode = stat.S_IFIFO m_fstat.return_value = st self.addCleanup(fstat_patcher.stop) def read_pipe_transport(self, waiter=None): transport = unix_events._UnixReadPipeTransport(self.loop, self.pipe, self.protocol, waiter=waiter) self.addCleanup(close_pipe_transport, transport) return transport def test_ctor(self): waiter = asyncio.Future(loop=self.loop) tr = self.read_pipe_transport(waiter=waiter) self.loop.run_until_complete(waiter) self.protocol.connection_made.assert_called_with(tr) self.loop.assert_reader(5, tr._read_ready) self.assertIsNone(waiter.result()) @mock.patch('os.read') def test__read_ready(self, m_read): tr = self.read_pipe_transport() m_read.return_value = b'data' tr._read_ready() m_read.assert_called_with(5, tr.max_size) self.protocol.data_received.assert_called_with(b'data') @mock.patch('os.read') def test__read_ready_eof(self, m_read): tr = self.read_pipe_transport() m_read.return_value = b'' tr._read_ready() m_read.assert_called_with(5, tr.max_size) self.assertFalse(self.loop.readers) test_utils.run_briefly(self.loop) self.protocol.eof_received.assert_called_with() self.protocol.connection_lost.assert_called_with(None) @mock.patch('os.read') def test__read_ready_blocked(self, m_read): tr = self.read_pipe_transport() m_read.side_effect = BlockingIOError tr._read_ready() m_read.assert_called_with(5, tr.max_size) test_utils.run_briefly(self.loop) self.assertFalse(self.protocol.data_received.called) @mock.patch('asyncio.log.logger.error') @mock.patch('os.read') def test__read_ready_error(self, m_read, m_logexc): tr = self.read_pipe_transport() err = OSError() m_read.side_effect = err tr._close = mock.Mock() tr._read_ready() m_read.assert_called_with(5, tr.max_size) tr._close.assert_called_with(err) m_logexc.assert_called_with( test_utils.MockPattern( 'Fatal read error on pipe transport' '\nprotocol:.*\ntransport:.*'), exc_info=(OSError, MOCK_ANY, MOCK_ANY)) @mock.patch('os.read') def test_pause_reading(self, m_read): tr = self.read_pipe_transport() m = mock.Mock() self.loop.add_reader(5, m) tr.pause_reading() self.assertFalse(self.loop.readers) @mock.patch('os.read') def test_resume_reading(self, m_read): tr = self.read_pipe_transport() tr.resume_reading() self.loop.assert_reader(5, tr._read_ready) @mock.patch('os.read') def test_close(self, m_read): tr = self.read_pipe_transport() tr._close = mock.Mock() tr.close() tr._close.assert_called_with(None) @mock.patch('os.read') def test_close_already_closing(self, m_read): tr = self.read_pipe_transport() tr._closing = True tr._close = mock.Mock() tr.close() self.assertFalse(tr._close.called) @mock.patch('os.read') def test__close(self, m_read): tr = self.read_pipe_transport() err = object() tr._close(err) self.assertTrue(tr.is_closing()) self.assertFalse(self.loop.readers) test_utils.run_briefly(self.loop) self.protocol.connection_lost.assert_called_with(err) def test__call_connection_lost(self): tr = self.read_pipe_transport() self.assertIsNotNone(tr._protocol) self.assertIsNotNone(tr._loop) err = None tr._call_connection_lost(err) self.protocol.connection_lost.assert_called_with(err) self.pipe.close.assert_called_with() self.assertIsNone(tr._protocol) self.assertIsNone(tr._loop) def test__call_connection_lost_with_err(self): tr = self.read_pipe_transport() self.assertIsNotNone(tr._protocol) self.assertIsNotNone(tr._loop) err = OSError() tr._call_connection_lost(err) self.protocol.connection_lost.assert_called_with(err) self.pipe.close.assert_called_with() self.assertIsNone(tr._protocol) self.assertIsNone(tr._loop) class UnixWritePipeTransportTests(test_utils.TestCase): def setUp(self): super().setUp() self.loop = self.new_test_loop() self.protocol = test_utils.make_test_protocol(asyncio.BaseProtocol) self.pipe = mock.Mock(spec_set=io.RawIOBase) self.pipe.fileno.return_value = 5 blocking_patcher = mock.patch('asyncio.unix_events._set_nonblocking') blocking_patcher.start() self.addCleanup(blocking_patcher.stop) fstat_patcher = mock.patch('os.fstat') m_fstat = fstat_patcher.start() st = mock.Mock() st.st_mode = stat.S_IFSOCK m_fstat.return_value = st self.addCleanup(fstat_patcher.stop) def write_pipe_transport(self, waiter=None): transport = unix_events._UnixWritePipeTransport(self.loop, self.pipe, self.protocol, waiter=waiter) self.addCleanup(close_pipe_transport, transport) return transport def test_ctor(self): waiter = asyncio.Future(loop=self.loop) tr = self.write_pipe_transport(waiter=waiter) self.loop.run_until_complete(waiter) self.protocol.connection_made.assert_called_with(tr) self.loop.assert_reader(5, tr._read_ready) self.assertEqual(None, waiter.result()) def test_can_write_eof(self): tr = self.write_pipe_transport() self.assertTrue(tr.can_write_eof()) @mock.patch('os.write') def test_write(self, m_write): tr = self.write_pipe_transport() m_write.return_value = 4 tr.write(b'data') m_write.assert_called_with(5, b'data') self.assertFalse(self.loop.writers) self.assertEqual(bytearray(), tr._buffer) @mock.patch('os.write') def test_write_no_data(self, m_write): tr = self.write_pipe_transport() tr.write(b'') self.assertFalse(m_write.called) self.assertFalse(self.loop.writers) self.assertEqual(bytearray(b''), tr._buffer) @mock.patch('os.write') def test_write_partial(self, m_write): tr = self.write_pipe_transport() m_write.return_value = 2 tr.write(b'data') self.loop.assert_writer(5, tr._write_ready) self.assertEqual(bytearray(b'ta'), tr._buffer) @mock.patch('os.write') def test_write_buffer(self, m_write): tr = self.write_pipe_transport() self.loop.add_writer(5, tr._write_ready) tr._buffer = bytearray(b'previous') tr.write(b'data') self.assertFalse(m_write.called) self.loop.assert_writer(5, tr._write_ready) self.assertEqual(bytearray(b'previousdata'), tr._buffer) @mock.patch('os.write') def test_write_again(self, m_write): tr = self.write_pipe_transport() m_write.side_effect = BlockingIOError() tr.write(b'data') m_write.assert_called_with(5, bytearray(b'data')) self.loop.assert_writer(5, tr._write_ready) self.assertEqual(bytearray(b'data'), tr._buffer) @mock.patch('asyncio.unix_events.logger') @mock.patch('os.write') def test_write_err(self, m_write, m_log): tr = self.write_pipe_transport() err = OSError() m_write.side_effect = err tr._fatal_error = mock.Mock() tr.write(b'data') m_write.assert_called_with(5, b'data') self.assertFalse(self.loop.writers) self.assertEqual(bytearray(), tr._buffer) tr._fatal_error.assert_called_with( err, 'Fatal write error on pipe transport') self.assertEqual(1, tr._conn_lost) tr.write(b'data') self.assertEqual(2, tr._conn_lost) tr.write(b'data') tr.write(b'data') tr.write(b'data') tr.write(b'data') # This is a bit overspecified. :-( m_log.warning.assert_called_with( 'pipe closed by peer or os.write(pipe, data) raised exception.') tr.close() @mock.patch('os.write') def test_write_close(self, m_write): tr = self.write_pipe_transport() tr._read_ready() # pipe was closed by peer tr.write(b'data') self.assertEqual(tr._conn_lost, 1) tr.write(b'data') self.assertEqual(tr._conn_lost, 2) def test__read_ready(self): tr = self.write_pipe_transport() tr._read_ready() self.assertFalse(self.loop.readers) self.assertFalse(self.loop.writers) self.assertTrue(tr.is_closing()) test_utils.run_briefly(self.loop) self.protocol.connection_lost.assert_called_with(None) @mock.patch('os.write') def test__write_ready(self, m_write): tr = self.write_pipe_transport() self.loop.add_writer(5, tr._write_ready) tr._buffer = bytearray(b'data') m_write.return_value = 4 tr._write_ready() self.assertFalse(self.loop.writers) self.assertEqual(bytearray(), tr._buffer) @mock.patch('os.write') def test__write_ready_partial(self, m_write): tr = self.write_pipe_transport() self.loop.add_writer(5, tr._write_ready) tr._buffer = bytearray(b'data') m_write.return_value = 3 tr._write_ready() self.loop.assert_writer(5, tr._write_ready) self.assertEqual(bytearray(b'a'), tr._buffer) @mock.patch('os.write') def test__write_ready_again(self, m_write): tr = self.write_pipe_transport() self.loop.add_writer(5, tr._write_ready) tr._buffer = bytearray(b'data') m_write.side_effect = BlockingIOError() tr._write_ready() m_write.assert_called_with(5, bytearray(b'data')) self.loop.assert_writer(5, tr._write_ready) self.assertEqual(bytearray(b'data'), tr._buffer) @mock.patch('os.write') def test__write_ready_empty(self, m_write): tr = self.write_pipe_transport() self.loop.add_writer(5, tr._write_ready) tr._buffer = bytearray(b'data') m_write.return_value = 0 tr._write_ready() m_write.assert_called_with(5, bytearray(b'data')) self.loop.assert_writer(5, tr._write_ready) self.assertEqual(bytearray(b'data'), tr._buffer) @mock.patch('asyncio.log.logger.error') @mock.patch('os.write') def test__write_ready_err(self, m_write, m_logexc): tr = self.write_pipe_transport() self.loop.add_writer(5, tr._write_ready) tr._buffer = bytearray(b'data') m_write.side_effect = err = OSError() tr._write_ready() self.assertFalse(self.loop.writers) self.assertFalse(self.loop.readers) self.assertEqual(bytearray(), tr._buffer) self.assertTrue(tr.is_closing()) m_logexc.assert_called_with( test_utils.MockPattern( 'Fatal write error on pipe transport' '\nprotocol:.*\ntransport:.*'), exc_info=(OSError, MOCK_ANY, MOCK_ANY)) self.assertEqual(1, tr._conn_lost) test_utils.run_briefly(self.loop) self.protocol.connection_lost.assert_called_with(err) @mock.patch('os.write') def test__write_ready_closing(self, m_write): tr = self.write_pipe_transport() self.loop.add_writer(5, tr._write_ready) tr._closing = True tr._buffer = bytearray(b'data') m_write.return_value = 4 tr._write_ready() self.assertFalse(self.loop.writers) self.assertFalse(self.loop.readers) self.assertEqual(bytearray(), tr._buffer) self.protocol.connection_lost.assert_called_with(None) self.pipe.close.assert_called_with() @mock.patch('os.write') def test_abort(self, m_write): tr = self.write_pipe_transport() self.loop.add_writer(5, tr._write_ready) self.loop.add_reader(5, tr._read_ready) tr._buffer = [b'da', b'ta'] tr.abort() self.assertFalse(m_write.called) self.assertFalse(self.loop.readers) self.assertFalse(self.loop.writers) self.assertEqual([], tr._buffer) self.assertTrue(tr.is_closing()) test_utils.run_briefly(self.loop) self.protocol.connection_lost.assert_called_with(None) def test__call_connection_lost(self): tr = self.write_pipe_transport() self.assertIsNotNone(tr._protocol) self.assertIsNotNone(tr._loop) err = None tr._call_connection_lost(err) self.protocol.connection_lost.assert_called_with(err) self.pipe.close.assert_called_with() self.assertIsNone(tr._protocol) self.assertIsNone(tr._loop) def test__call_connection_lost_with_err(self): tr = self.write_pipe_transport() self.assertIsNotNone(tr._protocol) self.assertIsNotNone(tr._loop) err = OSError() tr._call_connection_lost(err) self.protocol.connection_lost.assert_called_with(err) self.pipe.close.assert_called_with() self.assertIsNone(tr._protocol) self.assertIsNone(tr._loop) def test_close(self): tr = self.write_pipe_transport() tr.write_eof = mock.Mock() tr.close() tr.write_eof.assert_called_with() # closing the transport twice must not fail tr.close() def test_close_closing(self): tr = self.write_pipe_transport() tr.write_eof = mock.Mock() tr._closing = True tr.close() self.assertFalse(tr.write_eof.called) def test_write_eof(self): tr = self.write_pipe_transport() tr.write_eof() self.assertTrue(tr.is_closing()) self.assertFalse(self.loop.readers) test_utils.run_briefly(self.loop) self.protocol.connection_lost.assert_called_with(None) def test_write_eof_pending(self): tr = self.write_pipe_transport() tr._buffer = [b'data'] tr.write_eof() self.assertTrue(tr.is_closing()) self.assertFalse(self.protocol.connection_lost.called) class AbstractChildWatcherTests(unittest.TestCase): def test_not_implemented(self): f = mock.Mock() watcher = asyncio.AbstractChildWatcher() self.assertRaises( NotImplementedError, watcher.add_child_handler, f, f) self.assertRaises( NotImplementedError, watcher.remove_child_handler, f) self.assertRaises( NotImplementedError, watcher.attach_loop, f) self.assertRaises( NotImplementedError, watcher.close) self.assertRaises( NotImplementedError, watcher.__enter__) self.assertRaises( NotImplementedError, watcher.__exit__, f, f, f) class BaseChildWatcherTests(unittest.TestCase): def test_not_implemented(self): f = mock.Mock() watcher = unix_events.BaseChildWatcher() self.assertRaises( NotImplementedError, watcher._do_waitpid, f) WaitPidMocks = collections.namedtuple("WaitPidMocks", ("waitpid", "WIFEXITED", "WIFSIGNALED", "WEXITSTATUS", "WTERMSIG", )) class ChildWatcherTestsMixin: ignore_warnings = mock.patch.object(log.logger, "warning") def setUp(self): super().setUp() self.loop = self.new_test_loop() self.running = False self.zombies = {} with mock.patch.object( self.loop, "add_signal_handler") as self.m_add_signal_handler: self.watcher = self.create_watcher() self.watcher.attach_loop(self.loop) def waitpid(self, pid, flags): if isinstance(self.watcher, asyncio.SafeChildWatcher) or pid != -1: self.assertGreater(pid, 0) try: if pid < 0: return self.zombies.popitem() else: return pid, self.zombies.pop(pid) except KeyError: pass if self.running: return 0, 0 else: raise ChildProcessError() def add_zombie(self, pid, returncode): self.zombies[pid] = returncode + 32768 def WIFEXITED(self, status): return status >= 32768 def WIFSIGNALED(self, status): return 32700 < status < 32768 def WEXITSTATUS(self, status): self.assertTrue(self.WIFEXITED(status)) return status - 32768 def WTERMSIG(self, status): self.assertTrue(self.WIFSIGNALED(status)) return 32768 - status def test_create_watcher(self): self.m_add_signal_handler.assert_called_once_with( signal.SIGCHLD, self.watcher._sig_chld) def waitpid_mocks(func): def wrapped_func(self): def patch(target, wrapper): return mock.patch(target, wraps=wrapper, new_callable=mock.Mock) with patch('os.WTERMSIG', self.WTERMSIG) as m_WTERMSIG, \ patch('os.WEXITSTATUS', self.WEXITSTATUS) as m_WEXITSTATUS, \ patch('os.WIFSIGNALED', self.WIFSIGNALED) as m_WIFSIGNALED, \ patch('os.WIFEXITED', self.WIFEXITED) as m_WIFEXITED, \ patch('os.waitpid', self.waitpid) as m_waitpid: func(self, WaitPidMocks(m_waitpid, m_WIFEXITED, m_WIFSIGNALED, m_WEXITSTATUS, m_WTERMSIG, )) return wrapped_func @waitpid_mocks def test_sigchld(self, m): # register a child callback = mock.Mock() with self.watcher: self.running = True self.watcher.add_child_handler(42, callback, 9, 10, 14) self.assertFalse(callback.called) self.assertFalse(m.WIFEXITED.called) self.assertFalse(m.WIFSIGNALED.called) self.assertFalse(m.WEXITSTATUS.called) self.assertFalse(m.WTERMSIG.called) # child is running self.watcher._sig_chld() self.assertFalse(callback.called) self.assertFalse(m.WIFEXITED.called) self.assertFalse(m.WIFSIGNALED.called) self.assertFalse(m.WEXITSTATUS.called) self.assertFalse(m.WTERMSIG.called) # child terminates (returncode 12) self.running = False self.add_zombie(42, 12) self.watcher._sig_chld() self.assertTrue(m.WIFEXITED.called) self.assertTrue(m.WEXITSTATUS.called) self.assertFalse(m.WTERMSIG.called) callback.assert_called_once_with(42, 12, 9, 10, 14) m.WIFSIGNALED.reset_mock() m.WIFEXITED.reset_mock() m.WEXITSTATUS.reset_mock() callback.reset_mock() # ensure that the child is effectively reaped self.add_zombie(42, 13) with self.ignore_warnings: self.watcher._sig_chld() self.assertFalse(callback.called) self.assertFalse(m.WTERMSIG.called) m.WIFSIGNALED.reset_mock() m.WIFEXITED.reset_mock() m.WEXITSTATUS.reset_mock() # sigchld called again self.zombies.clear() self.watcher._sig_chld() self.assertFalse(callback.called) self.assertFalse(m.WIFEXITED.called) self.assertFalse(m.WIFSIGNALED.called) self.assertFalse(m.WEXITSTATUS.called) self.assertFalse(m.WTERMSIG.called) @waitpid_mocks def test_sigchld_two_children(self, m): callback1 = mock.Mock() callback2 = mock.Mock() # register child 1 with self.watcher: self.running = True self.watcher.add_child_handler(43, callback1, 7, 8) self.assertFalse(callback1.called) self.assertFalse(callback2.called) self.assertFalse(m.WIFEXITED.called) self.assertFalse(m.WIFSIGNALED.called) self.assertFalse(m.WEXITSTATUS.called) self.assertFalse(m.WTERMSIG.called) # register child 2 with self.watcher: self.watcher.add_child_handler(44, callback2, 147, 18) self.assertFalse(callback1.called) self.assertFalse(callback2.called) self.assertFalse(m.WIFEXITED.called) self.assertFalse(m.WIFSIGNALED.called) self.assertFalse(m.WEXITSTATUS.called) self.assertFalse(m.WTERMSIG.called) # children are running self.watcher._sig_chld() self.assertFalse(callback1.called) self.assertFalse(callback2.called) self.assertFalse(m.WIFEXITED.called) self.assertFalse(m.WIFSIGNALED.called) self.assertFalse(m.WEXITSTATUS.called) self.assertFalse(m.WTERMSIG.called) # child 1 terminates (signal 3) self.add_zombie(43, -3) self.watcher._sig_chld() callback1.assert_called_once_with(43, -3, 7, 8) self.assertFalse(callback2.called) self.assertTrue(m.WIFSIGNALED.called) self.assertFalse(m.WEXITSTATUS.called) self.assertTrue(m.WTERMSIG.called) m.WIFSIGNALED.reset_mock() m.WIFEXITED.reset_mock() m.WTERMSIG.reset_mock() callback1.reset_mock() # child 2 still running self.watcher._sig_chld() self.assertFalse(callback1.called) self.assertFalse(callback2.called) self.assertFalse(m.WIFEXITED.called) self.assertFalse(m.WIFSIGNALED.called) self.assertFalse(m.WEXITSTATUS.called) self.assertFalse(m.WTERMSIG.called) # child 2 terminates (code 108) self.add_zombie(44, 108) self.running = False self.watcher._sig_chld() callback2.assert_called_once_with(44, 108, 147, 18) self.assertFalse(callback1.called) self.assertTrue(m.WIFEXITED.called) self.assertTrue(m.WEXITSTATUS.called) self.assertFalse(m.WTERMSIG.called) m.WIFSIGNALED.reset_mock() m.WIFEXITED.reset_mock() m.WEXITSTATUS.reset_mock() callback2.reset_mock() # ensure that the children are effectively reaped self.add_zombie(43, 14) self.add_zombie(44, 15) with self.ignore_warnings: self.watcher._sig_chld() self.assertFalse(callback1.called) self.assertFalse(callback2.called) self.assertFalse(m.WTERMSIG.called) m.WIFSIGNALED.reset_mock() m.WIFEXITED.reset_mock() m.WEXITSTATUS.reset_mock() # sigchld called again self.zombies.clear() self.watcher._sig_chld() self.assertFalse(callback1.called) self.assertFalse(callback2.called) self.assertFalse(m.WIFEXITED.called) self.assertFalse(m.WIFSIGNALED.called) self.assertFalse(m.WEXITSTATUS.called) self.assertFalse(m.WTERMSIG.called) @waitpid_mocks def test_sigchld_two_children_terminating_together(self, m): callback1 = mock.Mock() callback2 = mock.Mock() # register child 1 with self.watcher: self.running = True self.watcher.add_child_handler(45, callback1, 17, 8) self.assertFalse(callback1.called) self.assertFalse(callback2.called) self.assertFalse(m.WIFEXITED.called) self.assertFalse(m.WIFSIGNALED.called) self.assertFalse(m.WEXITSTATUS.called) self.assertFalse(m.WTERMSIG.called) # register child 2 with self.watcher: self.watcher.add_child_handler(46, callback2, 1147, 18) self.assertFalse(callback1.called) self.assertFalse(callback2.called) self.assertFalse(m.WIFEXITED.called) self.assertFalse(m.WIFSIGNALED.called) self.assertFalse(m.WEXITSTATUS.called) self.assertFalse(m.WTERMSIG.called) # children are running self.watcher._sig_chld() self.assertFalse(callback1.called) self.assertFalse(callback2.called) self.assertFalse(m.WIFEXITED.called) self.assertFalse(m.WIFSIGNALED.called) self.assertFalse(m.WEXITSTATUS.called) self.assertFalse(m.WTERMSIG.called) # child 1 terminates (code 78) # child 2 terminates (signal 5) self.add_zombie(45, 78) self.add_zombie(46, -5) self.running = False self.watcher._sig_chld() callback1.assert_called_once_with(45, 78, 17, 8) callback2.assert_called_once_with(46, -5, 1147, 18) self.assertTrue(m.WIFSIGNALED.called) self.assertTrue(m.WIFEXITED.called) self.assertTrue(m.WEXITSTATUS.called) self.assertTrue(m.WTERMSIG.called) m.WIFSIGNALED.reset_mock() m.WIFEXITED.reset_mock() m.WTERMSIG.reset_mock() m.WEXITSTATUS.reset_mock() callback1.reset_mock() callback2.reset_mock() # ensure that the children are effectively reaped self.add_zombie(45, 14) self.add_zombie(46, 15) with self.ignore_warnings: self.watcher._sig_chld() self.assertFalse(callback1.called) self.assertFalse(callback2.called) self.assertFalse(m.WTERMSIG.called) @waitpid_mocks def test_sigchld_race_condition(self, m): # register a child callback = mock.Mock() with self.watcher: # child terminates before being registered self.add_zombie(50, 4) self.watcher._sig_chld() self.watcher.add_child_handler(50, callback, 1, 12) callback.assert_called_once_with(50, 4, 1, 12) callback.reset_mock() # ensure that the child is effectively reaped self.add_zombie(50, -1) with self.ignore_warnings: self.watcher._sig_chld() self.assertFalse(callback.called) @waitpid_mocks def test_sigchld_replace_handler(self, m): callback1 = mock.Mock() callback2 = mock.Mock() # register a child with self.watcher: self.running = True self.watcher.add_child_handler(51, callback1, 19) self.assertFalse(callback1.called) self.assertFalse(callback2.called) self.assertFalse(m.WIFEXITED.called) self.assertFalse(m.WIFSIGNALED.called) self.assertFalse(m.WEXITSTATUS.called) self.assertFalse(m.WTERMSIG.called) # register the same child again with self.watcher: self.watcher.add_child_handler(51, callback2, 21) self.assertFalse(callback1.called) self.assertFalse(callback2.called) self.assertFalse(m.WIFEXITED.called) self.assertFalse(m.WIFSIGNALED.called) self.assertFalse(m.WEXITSTATUS.called) self.assertFalse(m.WTERMSIG.called) # child terminates (signal 8) self.running = False self.add_zombie(51, -8) self.watcher._sig_chld() callback2.assert_called_once_with(51, -8, 21) self.assertFalse(callback1.called) self.assertTrue(m.WIFSIGNALED.called) self.assertFalse(m.WEXITSTATUS.called) self.assertTrue(m.WTERMSIG.called) m.WIFSIGNALED.reset_mock() m.WIFEXITED.reset_mock() m.WTERMSIG.reset_mock() callback2.reset_mock() # ensure that the child is effectively reaped self.add_zombie(51, 13) with self.ignore_warnings: self.watcher._sig_chld() self.assertFalse(callback1.called) self.assertFalse(callback2.called) self.assertFalse(m.WTERMSIG.called) @waitpid_mocks def test_sigchld_remove_handler(self, m): callback = mock.Mock() # register a child with self.watcher: self.running = True self.watcher.add_child_handler(52, callback, 1984) self.assertFalse(callback.called) self.assertFalse(m.WIFEXITED.called) self.assertFalse(m.WIFSIGNALED.called) self.assertFalse(m.WEXITSTATUS.called) self.assertFalse(m.WTERMSIG.called) # unregister the child self.watcher.remove_child_handler(52) self.assertFalse(callback.called) self.assertFalse(m.WIFEXITED.called) self.assertFalse(m.WIFSIGNALED.called) self.assertFalse(m.WEXITSTATUS.called) self.assertFalse(m.WTERMSIG.called) # child terminates (code 99) self.running = False self.add_zombie(52, 99) with self.ignore_warnings: self.watcher._sig_chld() self.assertFalse(callback.called) @waitpid_mocks def test_sigchld_unknown_status(self, m): callback = mock.Mock() # register a child with self.watcher: self.running = True self.watcher.add_child_handler(53, callback, -19) self.assertFalse(callback.called) self.assertFalse(m.WIFEXITED.called) self.assertFalse(m.WIFSIGNALED.called) self.assertFalse(m.WEXITSTATUS.called) self.assertFalse(m.WTERMSIG.called) # terminate with unknown status self.zombies[53] = 1178 self.running = False self.watcher._sig_chld() callback.assert_called_once_with(53, 1178, -19) self.assertTrue(m.WIFEXITED.called) self.assertTrue(m.WIFSIGNALED.called) self.assertFalse(m.WEXITSTATUS.called) self.assertFalse(m.WTERMSIG.called) callback.reset_mock() m.WIFEXITED.reset_mock() m.WIFSIGNALED.reset_mock() # ensure that the child is effectively reaped self.add_zombie(53, 101) with self.ignore_warnings: self.watcher._sig_chld() self.assertFalse(callback.called) @waitpid_mocks def test_remove_child_handler(self, m): callback1 = mock.Mock() callback2 = mock.Mock() callback3 = mock.Mock() # register children with self.watcher: self.running = True self.watcher.add_child_handler(54, callback1, 1) self.watcher.add_child_handler(55, callback2, 2) self.watcher.add_child_handler(56, callback3, 3) # remove child handler 1 self.assertTrue(self.watcher.remove_child_handler(54)) # remove child handler 2 multiple times self.assertTrue(self.watcher.remove_child_handler(55)) self.assertFalse(self.watcher.remove_child_handler(55)) self.assertFalse(self.watcher.remove_child_handler(55)) # all children terminate self.add_zombie(54, 0) self.add_zombie(55, 1) self.add_zombie(56, 2) self.running = False with self.ignore_warnings: self.watcher._sig_chld() self.assertFalse(callback1.called) self.assertFalse(callback2.called) callback3.assert_called_once_with(56, 2, 3) @waitpid_mocks def test_sigchld_unhandled_exception(self, m): callback = mock.Mock() # register a child with self.watcher: self.running = True self.watcher.add_child_handler(57, callback) # raise an exception m.waitpid.side_effect = ValueError with mock.patch.object(log.logger, 'error') as m_error: self.assertEqual(self.watcher._sig_chld(), None) self.assertTrue(m_error.called) @waitpid_mocks def test_sigchld_child_reaped_elsewhere(self, m): # register a child callback = mock.Mock() with self.watcher: self.running = True self.watcher.add_child_handler(58, callback) self.assertFalse(callback.called) self.assertFalse(m.WIFEXITED.called) self.assertFalse(m.WIFSIGNALED.called) self.assertFalse(m.WEXITSTATUS.called) self.assertFalse(m.WTERMSIG.called) # child terminates self.running = False self.add_zombie(58, 4) # waitpid is called elsewhere os.waitpid(58, os.WNOHANG) m.waitpid.reset_mock() # sigchld with self.ignore_warnings: self.watcher._sig_chld() if isinstance(self.watcher, asyncio.FastChildWatcher): # here the FastChildWatche enters a deadlock # (there is no way to prevent it) self.assertFalse(callback.called) else: callback.assert_called_once_with(58, 255) @waitpid_mocks def test_sigchld_unknown_pid_during_registration(self, m): # register two children callback1 = mock.Mock() callback2 = mock.Mock() with self.ignore_warnings, self.watcher: self.running = True # child 1 terminates self.add_zombie(591, 7) # an unknown child terminates self.add_zombie(593, 17) self.watcher._sig_chld() self.watcher.add_child_handler(591, callback1) self.watcher.add_child_handler(592, callback2) callback1.assert_called_once_with(591, 7) self.assertFalse(callback2.called) @waitpid_mocks def test_set_loop(self, m): # register a child callback = mock.Mock() with self.watcher: self.running = True self.watcher.add_child_handler(60, callback) # attach a new loop old_loop = self.loop self.loop = self.new_test_loop() patch = mock.patch.object with patch(old_loop, "remove_signal_handler") as m_old_remove, \ patch(self.loop, "add_signal_handler") as m_new_add: self.watcher.attach_loop(self.loop) m_old_remove.assert_called_once_with( signal.SIGCHLD) m_new_add.assert_called_once_with( signal.SIGCHLD, self.watcher._sig_chld) # child terminates self.running = False self.add_zombie(60, 9) self.watcher._sig_chld() callback.assert_called_once_with(60, 9) @waitpid_mocks def test_set_loop_race_condition(self, m): # register 3 children callback1 = mock.Mock() callback2 = mock.Mock() callback3 = mock.Mock() with self.watcher: self.running = True self.watcher.add_child_handler(61, callback1) self.watcher.add_child_handler(62, callback2) self.watcher.add_child_handler(622, callback3) # detach the loop old_loop = self.loop self.loop = None with mock.patch.object( old_loop, "remove_signal_handler") as m_remove_signal_handler: with self.assertWarnsRegex( RuntimeWarning, 'A loop is being detached'): self.watcher.attach_loop(None) m_remove_signal_handler.assert_called_once_with( signal.SIGCHLD) # child 1 & 2 terminate self.add_zombie(61, 11) self.add_zombie(62, -5) # SIGCHLD was not caught self.assertFalse(callback1.called) self.assertFalse(callback2.called) self.assertFalse(callback3.called) # attach a new loop self.loop = self.new_test_loop() with mock.patch.object( self.loop, "add_signal_handler") as m_add_signal_handler: self.watcher.attach_loop(self.loop) m_add_signal_handler.assert_called_once_with( signal.SIGCHLD, self.watcher._sig_chld) callback1.assert_called_once_with(61, 11) # race condition! callback2.assert_called_once_with(62, -5) # race condition! self.assertFalse(callback3.called) callback1.reset_mock() callback2.reset_mock() # child 3 terminates self.running = False self.add_zombie(622, 19) self.watcher._sig_chld() self.assertFalse(callback1.called) self.assertFalse(callback2.called) callback3.assert_called_once_with(622, 19) @waitpid_mocks def test_close(self, m): # register two children callback1 = mock.Mock() with self.watcher: self.running = True # child 1 terminates self.add_zombie(63, 9) # other child terminates self.add_zombie(65, 18) self.watcher._sig_chld() self.watcher.add_child_handler(63, callback1) self.watcher.add_child_handler(64, callback1) self.assertEqual(len(self.watcher._callbacks), 1) if isinstance(self.watcher, asyncio.FastChildWatcher): self.assertEqual(len(self.watcher._zombies), 1) with mock.patch.object( self.loop, "remove_signal_handler") as m_remove_signal_handler: self.watcher.close() m_remove_signal_handler.assert_called_once_with( signal.SIGCHLD) self.assertFalse(self.watcher._callbacks) if isinstance(self.watcher, asyncio.FastChildWatcher): self.assertFalse(self.watcher._zombies) @waitpid_mocks def test_add_child_handler_with_no_loop_attached(self, m): callback = mock.Mock() with self.create_watcher() as watcher: with self.assertRaisesRegex( RuntimeError, 'the child watcher does not have a loop attached'): watcher.add_child_handler(100, callback) class SafeChildWatcherTests (ChildWatcherTestsMixin, test_utils.TestCase): def create_watcher(self): return asyncio.SafeChildWatcher() class FastChildWatcherTests (ChildWatcherTestsMixin, test_utils.TestCase): def create_watcher(self): return asyncio.FastChildWatcher() class PolicyTests(unittest.TestCase): def create_policy(self): return asyncio.DefaultEventLoopPolicy() def test_get_child_watcher(self): policy = self.create_policy() self.assertIsNone(policy._watcher) watcher = policy.get_child_watcher() self.assertIsInstance(watcher, asyncio.SafeChildWatcher) self.assertIs(policy._watcher, watcher) self.assertIs(watcher, policy.get_child_watcher()) self.assertIsNone(watcher._loop) def test_get_child_watcher_after_set(self): policy = self.create_policy() watcher = asyncio.FastChildWatcher() policy.set_child_watcher(watcher) self.assertIs(policy._watcher, watcher) self.assertIs(watcher, policy.get_child_watcher()) def test_get_child_watcher_with_mainloop_existing(self): policy = self.create_policy() loop = policy.get_event_loop() self.assertIsNone(policy._watcher) watcher = policy.get_child_watcher() self.assertIsInstance(watcher, asyncio.SafeChildWatcher) self.assertIs(watcher._loop, loop) loop.close() def test_get_child_watcher_thread(self): def f(): policy.set_event_loop(policy.new_event_loop()) self.assertIsInstance(policy.get_event_loop(), asyncio.AbstractEventLoop) watcher = policy.get_child_watcher() self.assertIsInstance(watcher, asyncio.SafeChildWatcher) self.assertIsNone(watcher._loop) policy.get_event_loop().close() policy = self.create_policy() th = threading.Thread(target=f) th.start() th.join() def test_child_watcher_replace_mainloop_existing(self): policy = self.create_policy() loop = policy.get_event_loop() watcher = policy.get_child_watcher() self.assertIs(watcher._loop, loop) new_loop = policy.new_event_loop() policy.set_event_loop(new_loop) self.assertIs(watcher._loop, new_loop) policy.set_event_loop(None) self.assertIs(watcher._loop, None) loop.close() new_loop.close() if __name__ == '__main__': unittest.main()
55,549
1,639
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_asyncio/__main__.py
from . import load_tests import unittest unittest.main()
58
5
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_asyncio/test_selector_events.py
"""Tests for selector_events.py""" import errno import socket import unittest from unittest import mock try: import ssl except ImportError: ssl = None import asyncio from asyncio import selectors from asyncio import test_utils from asyncio.selector_events import BaseSelectorEventLoop from asyncio.selector_events import _SelectorTransport from asyncio.selector_events import _SelectorSslTransport from asyncio.selector_events import _SelectorSocketTransport from asyncio.selector_events import _SelectorDatagramTransport MOCK_ANY = mock.ANY class TestBaseSelectorEventLoop(BaseSelectorEventLoop): def _make_self_pipe(self): self._ssock = mock.Mock() self._csock = mock.Mock() self._internal_fds += 1 def _close_self_pipe(self): pass def list_to_buffer(l=()): return bytearray().join(l) def close_transport(transport): # Don't call transport.close() because the event loop and the selector # are mocked if transport._sock is None: return transport._sock.close() transport._sock = None class BaseSelectorEventLoopTests(test_utils.TestCase): def setUp(self): super().setUp() self.selector = mock.Mock() self.selector.select.return_value = [] self.loop = TestBaseSelectorEventLoop(self.selector) self.set_event_loop(self.loop) def test_make_socket_transport(self): m = mock.Mock() self.loop.add_reader = mock.Mock() self.loop.add_reader._is_coroutine = False transport = self.loop._make_socket_transport(m, asyncio.Protocol()) self.assertIsInstance(transport, _SelectorSocketTransport) # Calling repr() must not fail when the event loop is closed self.loop.close() repr(transport) close_transport(transport) @unittest.skipIf(ssl is None, 'No ssl module') def test_make_ssl_transport(self): m = mock.Mock() self.loop._add_reader = mock.Mock() self.loop._add_reader._is_coroutine = False self.loop._add_writer = mock.Mock() self.loop._remove_reader = mock.Mock() self.loop._remove_writer = mock.Mock() waiter = asyncio.Future(loop=self.loop) with test_utils.disable_logger(): transport = self.loop._make_ssl_transport( m, asyncio.Protocol(), m, waiter) # execute the handshake while the logger is disabled # to ignore SSL handshake failure test_utils.run_briefly(self.loop) # Sanity check class_name = transport.__class__.__name__ self.assertIn("ssl", class_name.lower()) self.assertIn("transport", class_name.lower()) transport.close() # execute pending callbacks to close the socket transport test_utils.run_briefly(self.loop) @mock.patch('asyncio.selector_events.ssl', None) @mock.patch('asyncio.sslproto.ssl', None) def test_make_ssl_transport_without_ssl_error(self): m = mock.Mock() self.loop.add_reader = mock.Mock() self.loop.add_writer = mock.Mock() self.loop.remove_reader = mock.Mock() self.loop.remove_writer = mock.Mock() with self.assertRaises(RuntimeError): self.loop._make_ssl_transport(m, m, m, m) def test_close(self): class EventLoop(BaseSelectorEventLoop): def _make_self_pipe(self): self._ssock = mock.Mock() self._csock = mock.Mock() self._internal_fds += 1 self.loop = EventLoop(self.selector) self.set_event_loop(self.loop) ssock = self.loop._ssock ssock.fileno.return_value = 7 csock = self.loop._csock csock.fileno.return_value = 1 remove_reader = self.loop._remove_reader = mock.Mock() self.loop._selector.close() self.loop._selector = selector = mock.Mock() self.assertFalse(self.loop.is_closed()) self.loop.close() self.assertTrue(self.loop.is_closed()) self.assertIsNone(self.loop._selector) self.assertIsNone(self.loop._csock) self.assertIsNone(self.loop._ssock) selector.close.assert_called_with() ssock.close.assert_called_with() csock.close.assert_called_with() remove_reader.assert_called_with(7) # it should be possible to call close() more than once self.loop.close() self.loop.close() # operation blocked when the loop is closed f = asyncio.Future(loop=self.loop) self.assertRaises(RuntimeError, self.loop.run_forever) self.assertRaises(RuntimeError, self.loop.run_until_complete, f) fd = 0 def callback(): pass self.assertRaises(RuntimeError, self.loop.add_reader, fd, callback) self.assertRaises(RuntimeError, self.loop.add_writer, fd, callback) def test_close_no_selector(self): self.loop.remove_reader = mock.Mock() self.loop._selector.close() self.loop._selector = None self.loop.close() self.assertIsNone(self.loop._selector) def test_socketpair(self): self.assertRaises(NotImplementedError, self.loop._socketpair) def test_read_from_self_tryagain(self): self.loop._ssock.recv.side_effect = BlockingIOError self.assertIsNone(self.loop._read_from_self()) def test_read_from_self_exception(self): self.loop._ssock.recv.side_effect = OSError self.assertRaises(OSError, self.loop._read_from_self) def test_write_to_self_tryagain(self): self.loop._csock.send.side_effect = BlockingIOError with test_utils.disable_logger(): self.assertIsNone(self.loop._write_to_self()) def test_write_to_self_exception(self): # _write_to_self() swallows OSError self.loop._csock.send.side_effect = RuntimeError() self.assertRaises(RuntimeError, self.loop._write_to_self) def test_sock_recv(self): sock = test_utils.mock_nonblocking_socket() self.loop._sock_recv = mock.Mock() f = self.loop.sock_recv(sock, 1024) self.assertIsInstance(f, asyncio.Future) self.loop._sock_recv.assert_called_with(f, None, sock, 1024) def test_sock_recv_reconnection(self): sock = mock.Mock() sock.fileno.return_value = 10 sock.recv.side_effect = BlockingIOError sock.gettimeout.return_value = 0.0 self.loop.add_reader = mock.Mock() self.loop.remove_reader = mock.Mock() fut = self.loop.sock_recv(sock, 1024) callback = self.loop.add_reader.call_args[0][1] params = self.loop.add_reader.call_args[0][2:] # emulate the old socket has closed, but the new one has # the same fileno, so callback is called with old (closed) socket sock.fileno.return_value = -1 sock.recv.side_effect = OSError(9) callback(*params) self.assertIsInstance(fut.exception(), OSError) self.assertEqual((10,), self.loop.remove_reader.call_args[0]) def test__sock_recv_canceled_fut(self): sock = mock.Mock() f = asyncio.Future(loop=self.loop) f.cancel() self.loop._sock_recv(f, None, sock, 1024) self.assertFalse(sock.recv.called) def test__sock_recv_unregister(self): sock = mock.Mock() sock.fileno.return_value = 10 f = asyncio.Future(loop=self.loop) f.cancel() self.loop.remove_reader = mock.Mock() self.loop._sock_recv(f, 10, sock, 1024) self.assertEqual((10,), self.loop.remove_reader.call_args[0]) def test__sock_recv_tryagain(self): f = asyncio.Future(loop=self.loop) sock = mock.Mock() sock.fileno.return_value = 10 sock.recv.side_effect = BlockingIOError self.loop.add_reader = mock.Mock() self.loop._sock_recv(f, None, sock, 1024) self.assertEqual((10, self.loop._sock_recv, f, 10, sock, 1024), self.loop.add_reader.call_args[0]) def test__sock_recv_exception(self): f = asyncio.Future(loop=self.loop) sock = mock.Mock() sock.fileno.return_value = 10 err = sock.recv.side_effect = OSError() self.loop._sock_recv(f, None, sock, 1024) self.assertIs(err, f.exception()) def test_sock_sendall(self): sock = test_utils.mock_nonblocking_socket() self.loop._sock_sendall = mock.Mock() f = self.loop.sock_sendall(sock, b'data') self.assertIsInstance(f, asyncio.Future) self.assertEqual( (f, None, sock, b'data'), self.loop._sock_sendall.call_args[0]) def test_sock_sendall_nodata(self): sock = test_utils.mock_nonblocking_socket() self.loop._sock_sendall = mock.Mock() f = self.loop.sock_sendall(sock, b'') self.assertIsInstance(f, asyncio.Future) self.assertTrue(f.done()) self.assertIsNone(f.result()) self.assertFalse(self.loop._sock_sendall.called) def test_sock_sendall_reconnection(self): sock = mock.Mock() sock.fileno.return_value = 10 sock.send.side_effect = BlockingIOError sock.gettimeout.return_value = 0.0 self.loop.add_writer = mock.Mock() self.loop.remove_writer = mock.Mock() fut = self.loop.sock_sendall(sock, b'data') callback = self.loop.add_writer.call_args[0][1] params = self.loop.add_writer.call_args[0][2:] # emulate the old socket has closed, but the new one has # the same fileno, so callback is called with old (closed) socket sock.fileno.return_value = -1 sock.send.side_effect = OSError(9) callback(*params) self.assertIsInstance(fut.exception(), OSError) self.assertEqual((10,), self.loop.remove_writer.call_args[0]) def test__sock_sendall_canceled_fut(self): sock = mock.Mock() f = asyncio.Future(loop=self.loop) f.cancel() self.loop._sock_sendall(f, None, sock, b'data') self.assertFalse(sock.send.called) def test__sock_sendall_unregister(self): sock = mock.Mock() sock.fileno.return_value = 10 f = asyncio.Future(loop=self.loop) f.cancel() self.loop.remove_writer = mock.Mock() self.loop._sock_sendall(f, 10, sock, b'data') self.assertEqual((10,), self.loop.remove_writer.call_args[0]) def test__sock_sendall_tryagain(self): f = asyncio.Future(loop=self.loop) sock = mock.Mock() sock.fileno.return_value = 10 sock.send.side_effect = BlockingIOError self.loop.add_writer = mock.Mock() self.loop._sock_sendall(f, None, sock, b'data') self.assertEqual( (10, self.loop._sock_sendall, f, 10, sock, b'data'), self.loop.add_writer.call_args[0]) def test__sock_sendall_interrupted(self): f = asyncio.Future(loop=self.loop) sock = mock.Mock() sock.fileno.return_value = 10 sock.send.side_effect = InterruptedError self.loop.add_writer = mock.Mock() self.loop._sock_sendall(f, None, sock, b'data') self.assertEqual( (10, self.loop._sock_sendall, f, 10, sock, b'data'), self.loop.add_writer.call_args[0]) def test__sock_sendall_exception(self): f = asyncio.Future(loop=self.loop) sock = mock.Mock() sock.fileno.return_value = 10 err = sock.send.side_effect = OSError() self.loop._sock_sendall(f, None, sock, b'data') self.assertIs(f.exception(), err) def test__sock_sendall(self): sock = mock.Mock() f = asyncio.Future(loop=self.loop) sock.fileno.return_value = 10 sock.send.return_value = 4 self.loop._sock_sendall(f, None, sock, b'data') self.assertTrue(f.done()) self.assertIsNone(f.result()) def test__sock_sendall_partial(self): sock = mock.Mock() f = asyncio.Future(loop=self.loop) sock.fileno.return_value = 10 sock.send.return_value = 2 self.loop.add_writer = mock.Mock() self.loop._sock_sendall(f, None, sock, b'data') self.assertFalse(f.done()) self.assertEqual( (10, self.loop._sock_sendall, f, 10, sock, b'ta'), self.loop.add_writer.call_args[0]) def test__sock_sendall_none(self): sock = mock.Mock() f = asyncio.Future(loop=self.loop) sock.fileno.return_value = 10 sock.send.return_value = 0 self.loop.add_writer = mock.Mock() self.loop._sock_sendall(f, None, sock, b'data') self.assertFalse(f.done()) self.assertEqual( (10, self.loop._sock_sendall, f, 10, sock, b'data'), self.loop.add_writer.call_args[0]) def test_sock_connect_timeout(self): # asyncio issue #205: sock_connect() must unregister the socket on # timeout error # prepare mocks self.loop.add_writer = mock.Mock() self.loop.remove_writer = mock.Mock() sock = test_utils.mock_nonblocking_socket() sock.connect.side_effect = BlockingIOError # first call to sock_connect() registers the socket fut = self.loop.create_task( self.loop.sock_connect(sock, ('127.0.0.1', 80))) self.loop._run_once() self.assertTrue(sock.connect.called) self.assertTrue(self.loop.add_writer.called) # on timeout, the socket must be unregistered sock.connect.reset_mock() fut.cancel() with self.assertRaises(asyncio.CancelledError): self.loop.run_until_complete(fut) self.assertTrue(self.loop.remove_writer.called) @mock.patch('socket.getaddrinfo') def test_sock_connect_resolve_using_socket_params(self, m_gai): addr = ('need-resolution.com', 8080) sock = test_utils.mock_nonblocking_socket() m_gai.side_effect = (None, None, None, None, ('127.0.0.1', 0)) m_gai._is_coroutine = False con = self.loop.create_task(self.loop.sock_connect(sock, addr)) while not m_gai.called: self.loop._run_once() m_gai.assert_called_with( addr[0], addr[1], sock.family, sock.type, sock.proto, 0) con.cancel() with self.assertRaises(asyncio.CancelledError): self.loop.run_until_complete(con) def test__sock_connect(self): f = asyncio.Future(loop=self.loop) sock = mock.Mock() sock.fileno.return_value = 10 resolved = self.loop.create_future() resolved.set_result([(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, '', ('127.0.0.1', 8080))]) self.loop._sock_connect(f, sock, resolved) self.assertTrue(f.done()) self.assertIsNone(f.result()) self.assertTrue(sock.connect.called) def test__sock_connect_cb_cancelled_fut(self): sock = mock.Mock() self.loop.remove_writer = mock.Mock() f = asyncio.Future(loop=self.loop) f.cancel() self.loop._sock_connect_cb(f, sock, ('127.0.0.1', 8080)) self.assertFalse(sock.getsockopt.called) def test__sock_connect_writer(self): # check that the fd is registered and then unregistered self.loop._process_events = mock.Mock() self.loop.add_writer = mock.Mock() self.loop.remove_writer = mock.Mock() sock = mock.Mock() sock.fileno.return_value = 10 sock.connect.side_effect = BlockingIOError sock.getsockopt.return_value = 0 address = ('127.0.0.1', 8080) resolved = self.loop.create_future() resolved.set_result([(socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, '', address)]) f = asyncio.Future(loop=self.loop) self.loop._sock_connect(f, sock, resolved) self.loop._run_once() self.assertTrue(self.loop.add_writer.called) self.assertEqual(10, self.loop.add_writer.call_args[0][0]) self.loop._sock_connect_cb(f, sock, address) # need to run the event loop to execute _sock_connect_done() callback self.loop.run_until_complete(f) self.assertEqual((10,), self.loop.remove_writer.call_args[0]) def test__sock_connect_cb_tryagain(self): f = asyncio.Future(loop=self.loop) sock = mock.Mock() sock.fileno.return_value = 10 sock.getsockopt.return_value = errno.EAGAIN # check that the exception is handled self.loop._sock_connect_cb(f, sock, ('127.0.0.1', 8080)) def test__sock_connect_cb_exception(self): f = asyncio.Future(loop=self.loop) sock = mock.Mock() sock.fileno.return_value = 10 sock.getsockopt.return_value = errno.ENOTCONN self.loop.remove_writer = mock.Mock() self.loop._sock_connect_cb(f, sock, ('127.0.0.1', 8080)) self.assertIsInstance(f.exception(), OSError) def test_sock_accept(self): sock = test_utils.mock_nonblocking_socket() self.loop._sock_accept = mock.Mock() f = self.loop.sock_accept(sock) self.assertIsInstance(f, asyncio.Future) self.assertEqual( (f, False, sock), self.loop._sock_accept.call_args[0]) def test__sock_accept(self): f = asyncio.Future(loop=self.loop) conn = mock.Mock() sock = mock.Mock() sock.fileno.return_value = 10 sock.accept.return_value = conn, ('127.0.0.1', 1000) self.loop._sock_accept(f, False, sock) self.assertTrue(f.done()) self.assertEqual((conn, ('127.0.0.1', 1000)), f.result()) self.assertEqual((False,), conn.setblocking.call_args[0]) def test__sock_accept_canceled_fut(self): sock = mock.Mock() f = asyncio.Future(loop=self.loop) f.cancel() self.loop._sock_accept(f, False, sock) self.assertFalse(sock.accept.called) def test__sock_accept_unregister(self): sock = mock.Mock() sock.fileno.return_value = 10 f = asyncio.Future(loop=self.loop) f.cancel() self.loop.remove_reader = mock.Mock() self.loop._sock_accept(f, True, sock) self.assertEqual((10,), self.loop.remove_reader.call_args[0]) def test__sock_accept_tryagain(self): f = asyncio.Future(loop=self.loop) sock = mock.Mock() sock.fileno.return_value = 10 sock.accept.side_effect = BlockingIOError self.loop.add_reader = mock.Mock() self.loop._sock_accept(f, False, sock) self.assertEqual( (10, self.loop._sock_accept, f, True, sock), self.loop.add_reader.call_args[0]) def test__sock_accept_exception(self): f = asyncio.Future(loop=self.loop) sock = mock.Mock() sock.fileno.return_value = 10 err = sock.accept.side_effect = OSError() self.loop._sock_accept(f, False, sock) self.assertIs(err, f.exception()) def test_add_reader(self): self.loop._selector.get_key.side_effect = KeyError cb = lambda: True self.loop.add_reader(1, cb) self.assertTrue(self.loop._selector.register.called) fd, mask, (r, w) = self.loop._selector.register.call_args[0] self.assertEqual(1, fd) self.assertEqual(selectors.EVENT_READ, mask) self.assertEqual(cb, r._callback) self.assertIsNone(w) def test_add_reader_existing(self): reader = mock.Mock() writer = mock.Mock() self.loop._selector.get_key.return_value = selectors.SelectorKey( 1, 1, selectors.EVENT_WRITE, (reader, writer)) cb = lambda: True self.loop.add_reader(1, cb) self.assertTrue(reader.cancel.called) self.assertFalse(self.loop._selector.register.called) self.assertTrue(self.loop._selector.modify.called) fd, mask, (r, w) = self.loop._selector.modify.call_args[0] self.assertEqual(1, fd) self.assertEqual(selectors.EVENT_WRITE | selectors.EVENT_READ, mask) self.assertEqual(cb, r._callback) self.assertEqual(writer, w) def test_add_reader_existing_writer(self): writer = mock.Mock() self.loop._selector.get_key.return_value = selectors.SelectorKey( 1, 1, selectors.EVENT_WRITE, (None, writer)) cb = lambda: True self.loop.add_reader(1, cb) self.assertFalse(self.loop._selector.register.called) self.assertTrue(self.loop._selector.modify.called) fd, mask, (r, w) = self.loop._selector.modify.call_args[0] self.assertEqual(1, fd) self.assertEqual(selectors.EVENT_WRITE | selectors.EVENT_READ, mask) self.assertEqual(cb, r._callback) self.assertEqual(writer, w) def test_remove_reader(self): self.loop._selector.get_key.return_value = selectors.SelectorKey( 1, 1, selectors.EVENT_READ, (None, None)) self.assertFalse(self.loop.remove_reader(1)) self.assertTrue(self.loop._selector.unregister.called) def test_remove_reader_read_write(self): reader = mock.Mock() writer = mock.Mock() self.loop._selector.get_key.return_value = selectors.SelectorKey( 1, 1, selectors.EVENT_READ | selectors.EVENT_WRITE, (reader, writer)) self.assertTrue( self.loop.remove_reader(1)) self.assertFalse(self.loop._selector.unregister.called) self.assertEqual( (1, selectors.EVENT_WRITE, (None, writer)), self.loop._selector.modify.call_args[0]) def test_remove_reader_unknown(self): self.loop._selector.get_key.side_effect = KeyError self.assertFalse( self.loop.remove_reader(1)) def test_add_writer(self): self.loop._selector.get_key.side_effect = KeyError cb = lambda: True self.loop.add_writer(1, cb) self.assertTrue(self.loop._selector.register.called) fd, mask, (r, w) = self.loop._selector.register.call_args[0] self.assertEqual(1, fd) self.assertEqual(selectors.EVENT_WRITE, mask) self.assertIsNone(r) self.assertEqual(cb, w._callback) def test_add_writer_existing(self): reader = mock.Mock() writer = mock.Mock() self.loop._selector.get_key.return_value = selectors.SelectorKey( 1, 1, selectors.EVENT_READ, (reader, writer)) cb = lambda: True self.loop.add_writer(1, cb) self.assertTrue(writer.cancel.called) self.assertFalse(self.loop._selector.register.called) self.assertTrue(self.loop._selector.modify.called) fd, mask, (r, w) = self.loop._selector.modify.call_args[0] self.assertEqual(1, fd) self.assertEqual(selectors.EVENT_WRITE | selectors.EVENT_READ, mask) self.assertEqual(reader, r) self.assertEqual(cb, w._callback) def test_remove_writer(self): self.loop._selector.get_key.return_value = selectors.SelectorKey( 1, 1, selectors.EVENT_WRITE, (None, None)) self.assertFalse(self.loop.remove_writer(1)) self.assertTrue(self.loop._selector.unregister.called) def test_remove_writer_read_write(self): reader = mock.Mock() writer = mock.Mock() self.loop._selector.get_key.return_value = selectors.SelectorKey( 1, 1, selectors.EVENT_READ | selectors.EVENT_WRITE, (reader, writer)) self.assertTrue( self.loop.remove_writer(1)) self.assertFalse(self.loop._selector.unregister.called) self.assertEqual( (1, selectors.EVENT_READ, (reader, None)), self.loop._selector.modify.call_args[0]) def test_remove_writer_unknown(self): self.loop._selector.get_key.side_effect = KeyError self.assertFalse( self.loop.remove_writer(1)) def test_process_events_read(self): reader = mock.Mock() reader._cancelled = False self.loop._add_callback = mock.Mock() self.loop._process_events( [(selectors.SelectorKey( 1, 1, selectors.EVENT_READ, (reader, None)), selectors.EVENT_READ)]) self.assertTrue(self.loop._add_callback.called) self.loop._add_callback.assert_called_with(reader) def test_process_events_read_cancelled(self): reader = mock.Mock() reader.cancelled = True self.loop._remove_reader = mock.Mock() self.loop._process_events( [(selectors.SelectorKey( 1, 1, selectors.EVENT_READ, (reader, None)), selectors.EVENT_READ)]) self.loop._remove_reader.assert_called_with(1) def test_process_events_write(self): writer = mock.Mock() writer._cancelled = False self.loop._add_callback = mock.Mock() self.loop._process_events( [(selectors.SelectorKey(1, 1, selectors.EVENT_WRITE, (None, writer)), selectors.EVENT_WRITE)]) self.loop._add_callback.assert_called_with(writer) def test_process_events_write_cancelled(self): writer = mock.Mock() writer.cancelled = True self.loop._remove_writer = mock.Mock() self.loop._process_events( [(selectors.SelectorKey(1, 1, selectors.EVENT_WRITE, (None, writer)), selectors.EVENT_WRITE)]) self.loop._remove_writer.assert_called_with(1) def test_accept_connection_multiple(self): sock = mock.Mock() sock.accept.return_value = (mock.Mock(), mock.Mock()) backlog = 100 # Mock the coroutine generation for a connection to prevent # warnings related to un-awaited coroutines. mock_obj = mock.patch.object with mock_obj(self.loop, '_accept_connection2') as accept2_mock: accept2_mock.return_value = None with mock_obj(self.loop, 'create_task') as task_mock: task_mock.return_value = None self.loop._accept_connection(mock.Mock(), sock, backlog=backlog) self.assertEqual(sock.accept.call_count, backlog) class SelectorTransportTests(test_utils.TestCase): def setUp(self): super().setUp() self.loop = self.new_test_loop() self.protocol = test_utils.make_test_protocol(asyncio.Protocol) self.sock = mock.Mock(socket.socket) self.sock.fileno.return_value = 7 def create_transport(self): transport = _SelectorTransport(self.loop, self.sock, self.protocol, None) self.addCleanup(close_transport, transport) return transport def test_ctor(self): tr = self.create_transport() self.assertIs(tr._loop, self.loop) self.assertIs(tr._sock, self.sock) self.assertIs(tr._sock_fd, 7) def test_abort(self): tr = self.create_transport() tr._force_close = mock.Mock() tr.abort() tr._force_close.assert_called_with(None) def test_close(self): tr = self.create_transport() tr.close() self.assertTrue(tr.is_closing()) self.assertEqual(1, self.loop.remove_reader_count[7]) self.protocol.connection_lost(None) self.assertEqual(tr._conn_lost, 1) tr.close() self.assertEqual(tr._conn_lost, 1) self.assertEqual(1, self.loop.remove_reader_count[7]) def test_close_write_buffer(self): tr = self.create_transport() tr._buffer.extend(b'data') tr.close() self.assertFalse(self.loop.readers) test_utils.run_briefly(self.loop) self.assertFalse(self.protocol.connection_lost.called) def test_force_close(self): tr = self.create_transport() tr._buffer.extend(b'1') self.loop._add_reader(7, mock.sentinel) self.loop._add_writer(7, mock.sentinel) tr._force_close(None) self.assertTrue(tr.is_closing()) self.assertEqual(tr._buffer, list_to_buffer()) self.assertFalse(self.loop.readers) self.assertFalse(self.loop.writers) # second close should not remove reader tr._force_close(None) self.assertFalse(self.loop.readers) self.assertEqual(1, self.loop.remove_reader_count[7]) @mock.patch('asyncio.log.logger.error') def test_fatal_error(self, m_exc): exc = OSError() tr = self.create_transport() tr._force_close = mock.Mock() tr._fatal_error(exc) m_exc.assert_called_with( test_utils.MockPattern( 'Fatal error on transport\nprotocol:.*\ntransport:.*'), exc_info=(OSError, MOCK_ANY, MOCK_ANY)) tr._force_close.assert_called_with(exc) def test_connection_lost(self): exc = OSError() tr = self.create_transport() self.assertIsNotNone(tr._protocol) self.assertIsNotNone(tr._loop) tr._call_connection_lost(exc) self.protocol.connection_lost.assert_called_with(exc) self.sock.close.assert_called_with() self.assertIsNone(tr._sock) self.assertIsNone(tr._protocol) self.assertIsNone(tr._loop) def test__add_reader(self): tr = self.create_transport() tr._buffer.extend(b'1') tr._add_reader(7, mock.sentinel) self.assertTrue(self.loop.readers) tr._force_close(None) self.assertTrue(tr.is_closing()) self.assertFalse(self.loop.readers) # can not add readers after closing tr._add_reader(7, mock.sentinel) self.assertFalse(self.loop.readers) class SelectorSocketTransportTests(test_utils.TestCase): def setUp(self): super().setUp() self.loop = self.new_test_loop() self.protocol = test_utils.make_test_protocol(asyncio.Protocol) self.sock = mock.Mock(socket.socket) self.sock_fd = self.sock.fileno.return_value = 7 def socket_transport(self, waiter=None): transport = _SelectorSocketTransport(self.loop, self.sock, self.protocol, waiter=waiter) self.addCleanup(close_transport, transport) return transport def test_ctor(self): waiter = asyncio.Future(loop=self.loop) tr = self.socket_transport(waiter=waiter) self.loop.run_until_complete(waiter) self.loop.assert_reader(7, tr._read_ready) test_utils.run_briefly(self.loop) self.protocol.connection_made.assert_called_with(tr) def test_ctor_with_waiter(self): waiter = asyncio.Future(loop=self.loop) self.socket_transport(waiter=waiter) self.loop.run_until_complete(waiter) self.assertIsNone(waiter.result()) def test_pause_resume_reading(self): tr = self.socket_transport() test_utils.run_briefly(self.loop) self.assertFalse(tr._paused) self.loop.assert_reader(7, tr._read_ready) tr.pause_reading() tr.pause_reading() self.assertTrue(tr._paused) self.loop.assert_no_reader(7) tr.resume_reading() tr.resume_reading() self.assertFalse(tr._paused) self.loop.assert_reader(7, tr._read_ready) tr.close() self.loop.assert_no_reader(7) def test_read_ready(self): transport = self.socket_transport() self.sock.recv.return_value = b'data' transport._read_ready() self.protocol.data_received.assert_called_with(b'data') def test_read_ready_eof(self): transport = self.socket_transport() transport.close = mock.Mock() self.sock.recv.return_value = b'' transport._read_ready() self.protocol.eof_received.assert_called_with() transport.close.assert_called_with() def test_read_ready_eof_keep_open(self): transport = self.socket_transport() transport.close = mock.Mock() self.sock.recv.return_value = b'' self.protocol.eof_received.return_value = True transport._read_ready() self.protocol.eof_received.assert_called_with() self.assertFalse(transport.close.called) @mock.patch('logging.exception') def test_read_ready_tryagain(self, m_exc): self.sock.recv.side_effect = BlockingIOError transport = self.socket_transport() transport._fatal_error = mock.Mock() transport._read_ready() self.assertFalse(transport._fatal_error.called) @mock.patch('logging.exception') def test_read_ready_tryagain_interrupted(self, m_exc): self.sock.recv.side_effect = InterruptedError transport = self.socket_transport() transport._fatal_error = mock.Mock() transport._read_ready() self.assertFalse(transport._fatal_error.called) @mock.patch('logging.exception') def test_read_ready_conn_reset(self, m_exc): err = self.sock.recv.side_effect = ConnectionResetError() transport = self.socket_transport() transport._force_close = mock.Mock() with test_utils.disable_logger(): transport._read_ready() transport._force_close.assert_called_with(err) @mock.patch('logging.exception') def test_read_ready_err(self, m_exc): err = self.sock.recv.side_effect = OSError() transport = self.socket_transport() transport._fatal_error = mock.Mock() transport._read_ready() transport._fatal_error.assert_called_with( err, 'Fatal read error on socket transport') def test_write(self): data = b'data' self.sock.send.return_value = len(data) transport = self.socket_transport() transport.write(data) self.sock.send.assert_called_with(data) def test_write_bytearray(self): data = bytearray(b'data') self.sock.send.return_value = len(data) transport = self.socket_transport() transport.write(data) self.sock.send.assert_called_with(data) self.assertEqual(data, bytearray(b'data')) # Hasn't been mutated. def test_write_memoryview(self): data = memoryview(b'data') self.sock.send.return_value = len(data) transport = self.socket_transport() transport.write(data) self.sock.send.assert_called_with(data) def test_write_no_data(self): transport = self.socket_transport() transport._buffer.extend(b'data') transport.write(b'') self.assertFalse(self.sock.send.called) self.assertEqual(list_to_buffer([b'data']), transport._buffer) def test_write_buffer(self): transport = self.socket_transport() transport._buffer.extend(b'data1') transport.write(b'data2') self.assertFalse(self.sock.send.called) self.assertEqual(list_to_buffer([b'data1', b'data2']), transport._buffer) def test_write_partial(self): data = b'data' self.sock.send.return_value = 2 transport = self.socket_transport() transport.write(data) self.loop.assert_writer(7, transport._write_ready) self.assertEqual(list_to_buffer([b'ta']), transport._buffer) def test_write_partial_bytearray(self): data = bytearray(b'data') self.sock.send.return_value = 2 transport = self.socket_transport() transport.write(data) self.loop.assert_writer(7, transport._write_ready) self.assertEqual(list_to_buffer([b'ta']), transport._buffer) self.assertEqual(data, bytearray(b'data')) # Hasn't been mutated. def test_write_partial_memoryview(self): data = memoryview(b'data') self.sock.send.return_value = 2 transport = self.socket_transport() transport.write(data) self.loop.assert_writer(7, transport._write_ready) self.assertEqual(list_to_buffer([b'ta']), transport._buffer) def test_write_partial_none(self): data = b'data' self.sock.send.return_value = 0 self.sock.fileno.return_value = 7 transport = self.socket_transport() transport.write(data) self.loop.assert_writer(7, transport._write_ready) self.assertEqual(list_to_buffer([b'data']), transport._buffer) def test_write_tryagain(self): self.sock.send.side_effect = BlockingIOError data = b'data' transport = self.socket_transport() transport.write(data) self.loop.assert_writer(7, transport._write_ready) self.assertEqual(list_to_buffer([b'data']), transport._buffer) @mock.patch('asyncio.selector_events.logger') def test_write_exception(self, m_log): err = self.sock.send.side_effect = OSError() data = b'data' transport = self.socket_transport() transport._fatal_error = mock.Mock() transport.write(data) transport._fatal_error.assert_called_with( err, 'Fatal write error on socket transport') transport._conn_lost = 1 self.sock.reset_mock() transport.write(data) self.assertFalse(self.sock.send.called) self.assertEqual(transport._conn_lost, 2) transport.write(data) transport.write(data) transport.write(data) transport.write(data) m_log.warning.assert_called_with('socket.send() raised exception.') def test_write_str(self): transport = self.socket_transport() self.assertRaises(TypeError, transport.write, 'str') def test_write_closing(self): transport = self.socket_transport() transport.close() self.assertEqual(transport._conn_lost, 1) transport.write(b'data') self.assertEqual(transport._conn_lost, 2) def test_write_ready(self): data = b'data' self.sock.send.return_value = len(data) transport = self.socket_transport() transport._buffer.extend(data) self.loop._add_writer(7, transport._write_ready) transport._write_ready() self.assertTrue(self.sock.send.called) self.assertFalse(self.loop.writers) def test_write_ready_closing(self): data = b'data' self.sock.send.return_value = len(data) transport = self.socket_transport() transport._closing = True transport._buffer.extend(data) self.loop._add_writer(7, transport._write_ready) transport._write_ready() self.assertTrue(self.sock.send.called) self.assertFalse(self.loop.writers) self.sock.close.assert_called_with() self.protocol.connection_lost.assert_called_with(None) def test_write_ready_no_data(self): transport = self.socket_transport() # This is an internal error. self.assertRaises(AssertionError, transport._write_ready) def test_write_ready_partial(self): data = b'data' self.sock.send.return_value = 2 transport = self.socket_transport() transport._buffer.extend(data) self.loop._add_writer(7, transport._write_ready) transport._write_ready() self.loop.assert_writer(7, transport._write_ready) self.assertEqual(list_to_buffer([b'ta']), transport._buffer) def test_write_ready_partial_none(self): data = b'data' self.sock.send.return_value = 0 transport = self.socket_transport() transport._buffer.extend(data) self.loop._add_writer(7, transport._write_ready) transport._write_ready() self.loop.assert_writer(7, transport._write_ready) self.assertEqual(list_to_buffer([b'data']), transport._buffer) def test_write_ready_tryagain(self): self.sock.send.side_effect = BlockingIOError transport = self.socket_transport() transport._buffer = list_to_buffer([b'data1', b'data2']) self.loop._add_writer(7, transport._write_ready) transport._write_ready() self.loop.assert_writer(7, transport._write_ready) self.assertEqual(list_to_buffer([b'data1data2']), transport._buffer) def test_write_ready_exception(self): err = self.sock.send.side_effect = OSError() transport = self.socket_transport() transport._fatal_error = mock.Mock() transport._buffer.extend(b'data') transport._write_ready() transport._fatal_error.assert_called_with( err, 'Fatal write error on socket transport') def test_write_eof(self): tr = self.socket_transport() self.assertTrue(tr.can_write_eof()) tr.write_eof() self.sock.shutdown.assert_called_with(socket.SHUT_WR) tr.write_eof() self.assertEqual(self.sock.shutdown.call_count, 1) tr.close() def test_write_eof_buffer(self): tr = self.socket_transport() self.sock.send.side_effect = BlockingIOError tr.write(b'data') tr.write_eof() self.assertEqual(tr._buffer, list_to_buffer([b'data'])) self.assertTrue(tr._eof) self.assertFalse(self.sock.shutdown.called) self.sock.send.side_effect = lambda _: 4 tr._write_ready() self.assertTrue(self.sock.send.called) self.sock.shutdown.assert_called_with(socket.SHUT_WR) tr.close() def test_write_eof_after_close(self): tr = self.socket_transport() tr.close() self.loop.run_until_complete(asyncio.sleep(0)) tr.write_eof() @mock.patch('asyncio.base_events.logger') def test_transport_close_remove_writer(self, m_log): remove_writer = self.loop._remove_writer = mock.Mock() transport = self.socket_transport() transport.close() remove_writer.assert_called_with(self.sock_fd) @unittest.skipIf(ssl is None, 'No ssl module') class SelectorSslTransportTests(test_utils.TestCase): def setUp(self): super().setUp() self.loop = self.new_test_loop() self.protocol = test_utils.make_test_protocol(asyncio.Protocol) self.sock = mock.Mock(socket.socket) self.sock.fileno.return_value = 7 self.sslsock = mock.Mock() self.sslsock.fileno.return_value = 1 self.sslcontext = mock.Mock() self.sslcontext.wrap_socket.return_value = self.sslsock def ssl_transport(self, waiter=None, server_hostname=None): transport = _SelectorSslTransport(self.loop, self.sock, self.protocol, self.sslcontext, waiter=waiter, server_hostname=server_hostname) self.addCleanup(close_transport, transport) return transport def _make_one(self, create_waiter=None): transport = self.ssl_transport() self.sock.reset_mock() self.sslsock.reset_mock() self.sslcontext.reset_mock() self.loop.reset_counters() return transport def test_on_handshake(self): waiter = asyncio.Future(loop=self.loop) tr = self.ssl_transport(waiter=waiter) self.assertTrue(self.sslsock.do_handshake.called) self.loop.assert_reader(1, tr._read_ready) test_utils.run_briefly(self.loop) self.assertIsNone(waiter.result()) def test_on_handshake_reader_retry(self): self.loop.set_debug(False) self.sslsock.do_handshake.side_effect = ssl.SSLWantReadError transport = self.ssl_transport() self.loop.assert_reader(1, transport._on_handshake, None) def test_on_handshake_writer_retry(self): self.loop.set_debug(False) self.sslsock.do_handshake.side_effect = ssl.SSLWantWriteError transport = self.ssl_transport() self.loop.assert_writer(1, transport._on_handshake, None) def test_on_handshake_exc(self): exc = ValueError() self.sslsock.do_handshake.side_effect = exc with test_utils.disable_logger(): waiter = asyncio.Future(loop=self.loop) self.ssl_transport(waiter=waiter) self.assertTrue(waiter.done()) self.assertIs(exc, waiter.exception()) self.assertTrue(self.sslsock.close.called) def test_on_handshake_base_exc(self): waiter = asyncio.Future(loop=self.loop) transport = self.ssl_transport(waiter=waiter) exc = BaseException() self.sslsock.do_handshake.side_effect = exc with test_utils.disable_logger(): self.assertRaises(BaseException, transport._on_handshake, 0) self.assertTrue(self.sslsock.close.called) self.assertTrue(waiter.done()) self.assertIs(exc, waiter.exception()) def test_cancel_handshake(self): # Python issue #23197: cancelling a handshake must not raise an # exception or log an error, even if the handshake failed waiter = asyncio.Future(loop=self.loop) transport = self.ssl_transport(waiter=waiter) waiter.cancel() exc = ValueError() self.sslsock.do_handshake.side_effect = exc with test_utils.disable_logger(): transport._on_handshake(0) transport.close() test_utils.run_briefly(self.loop) def test_pause_resume_reading(self): tr = self._make_one() self.assertFalse(tr._paused) self.loop.assert_reader(1, tr._read_ready) tr.pause_reading() self.assertTrue(tr._paused) self.assertFalse(1 in self.loop.readers) tr.resume_reading() self.assertFalse(tr._paused) self.loop.assert_reader(1, tr._read_ready) with self.assertRaises(RuntimeError): tr.resume_reading() def test_write(self): transport = self._make_one() transport.write(b'data') self.assertEqual(list_to_buffer([b'data']), transport._buffer) def test_write_bytearray(self): transport = self._make_one() data = bytearray(b'data') transport.write(data) self.assertEqual(list_to_buffer([b'data']), transport._buffer) self.assertEqual(data, bytearray(b'data')) # Hasn't been mutated. self.assertIsNot(data, transport._buffer) # Hasn't been incorporated. def test_write_memoryview(self): transport = self._make_one() data = memoryview(b'data') transport.write(data) self.assertEqual(list_to_buffer([b'data']), transport._buffer) def test_write_no_data(self): transport = self._make_one() transport._buffer.extend(b'data') transport.write(b'') self.assertEqual(list_to_buffer([b'data']), transport._buffer) def test_write_str(self): transport = self._make_one() self.assertRaises(TypeError, transport.write, 'str') def test_write_closing(self): transport = self._make_one() transport.close() self.assertEqual(transport._conn_lost, 1) transport.write(b'data') self.assertEqual(transport._conn_lost, 2) @mock.patch('asyncio.selector_events.logger') def test_write_exception(self, m_log): transport = self._make_one() transport._conn_lost = 1 transport.write(b'data') self.assertEqual(transport._buffer, list_to_buffer()) transport.write(b'data') transport.write(b'data') transport.write(b'data') transport.write(b'data') m_log.warning.assert_called_with('socket.send() raised exception.') def test_read_ready_recv(self): self.sslsock.recv.return_value = b'data' transport = self._make_one() transport._read_ready() self.assertTrue(self.sslsock.recv.called) self.assertEqual((b'data',), self.protocol.data_received.call_args[0]) def test_read_ready_write_wants_read(self): self.loop._add_writer = mock.Mock() self.sslsock.recv.side_effect = BlockingIOError transport = self._make_one() transport._write_wants_read = True transport._write_ready = mock.Mock() transport._buffer.extend(b'data') transport._read_ready() self.assertFalse(transport._write_wants_read) transport._write_ready.assert_called_with() self.loop._add_writer.assert_called_with( transport._sock_fd, transport._write_ready) def test_read_ready_recv_eof(self): self.sslsock.recv.return_value = b'' transport = self._make_one() transport.close = mock.Mock() transport._read_ready() transport.close.assert_called_with() self.protocol.eof_received.assert_called_with() def test_read_ready_recv_conn_reset(self): err = self.sslsock.recv.side_effect = ConnectionResetError() transport = self._make_one() transport._force_close = mock.Mock() with test_utils.disable_logger(): transport._read_ready() transport._force_close.assert_called_with(err) def test_read_ready_recv_retry(self): self.sslsock.recv.side_effect = ssl.SSLWantReadError transport = self._make_one() transport._read_ready() self.assertTrue(self.sslsock.recv.called) self.assertFalse(self.protocol.data_received.called) self.sslsock.recv.side_effect = BlockingIOError transport._read_ready() self.assertFalse(self.protocol.data_received.called) self.sslsock.recv.side_effect = InterruptedError transport._read_ready() self.assertFalse(self.protocol.data_received.called) def test_read_ready_recv_write(self): self.loop._remove_reader = mock.Mock() self.loop._add_writer = mock.Mock() self.sslsock.recv.side_effect = ssl.SSLWantWriteError transport = self._make_one() transport._read_ready() self.assertFalse(self.protocol.data_received.called) self.assertTrue(transport._read_wants_write) self.loop._remove_reader.assert_called_with(transport._sock_fd) self.loop._add_writer.assert_called_with( transport._sock_fd, transport._write_ready) def test_read_ready_recv_exc(self): err = self.sslsock.recv.side_effect = OSError() transport = self._make_one() transport._fatal_error = mock.Mock() transport._read_ready() transport._fatal_error.assert_called_with( err, 'Fatal read error on SSL transport') def test_write_ready_send(self): self.sslsock.send.return_value = 4 transport = self._make_one() transport._buffer = list_to_buffer([b'data']) transport._write_ready() self.assertEqual(list_to_buffer(), transport._buffer) self.assertTrue(self.sslsock.send.called) def test_write_ready_send_none(self): self.sslsock.send.return_value = 0 transport = self._make_one() transport._buffer = list_to_buffer([b'data1', b'data2']) transport._write_ready() self.assertTrue(self.sslsock.send.called) self.assertEqual(list_to_buffer([b'data1data2']), transport._buffer) def test_write_ready_send_partial(self): self.sslsock.send.return_value = 2 transport = self._make_one() transport._buffer = list_to_buffer([b'data1', b'data2']) transport._write_ready() self.assertTrue(self.sslsock.send.called) self.assertEqual(list_to_buffer([b'ta1data2']), transport._buffer) def test_write_ready_send_closing_partial(self): self.sslsock.send.return_value = 2 transport = self._make_one() transport._buffer = list_to_buffer([b'data1', b'data2']) transport._write_ready() self.assertTrue(self.sslsock.send.called) self.assertFalse(self.sslsock.close.called) def test_write_ready_send_closing(self): self.sslsock.send.return_value = 4 transport = self._make_one() transport._buffer = list_to_buffer([b'data']) transport.close() transport._write_ready() self.protocol.connection_lost.assert_called_with(None) def test_write_ready_send_closing_empty_buffer(self): self.sslsock.send.return_value = 4 call_soon = self.loop.call_soon = mock.Mock() transport = self._make_one() transport._buffer = list_to_buffer() transport.close() transport._write_ready() call_soon.assert_called_with(transport._call_connection_lost, None) def test_write_ready_send_retry(self): transport = self._make_one() transport._buffer = list_to_buffer([b'data']) self.sslsock.send.side_effect = ssl.SSLWantWriteError transport._write_ready() self.assertEqual(list_to_buffer([b'data']), transport._buffer) self.sslsock.send.side_effect = BlockingIOError() transport._write_ready() self.assertEqual(list_to_buffer([b'data']), transport._buffer) def test_write_ready_send_read(self): transport = self._make_one() transport._buffer = list_to_buffer([b'data']) self.loop._remove_writer = mock.Mock() self.sslsock.send.side_effect = ssl.SSLWantReadError transport._write_ready() self.assertFalse(self.protocol.data_received.called) self.assertTrue(transport._write_wants_read) self.loop._remove_writer.assert_called_with(transport._sock_fd) def test_write_ready_send_exc(self): err = self.sslsock.send.side_effect = OSError() transport = self._make_one() transport._buffer = list_to_buffer([b'data']) transport._fatal_error = mock.Mock() transport._write_ready() transport._fatal_error.assert_called_with( err, 'Fatal write error on SSL transport') self.assertEqual(list_to_buffer(), transport._buffer) def test_write_ready_read_wants_write(self): self.loop._add_reader = mock.Mock() self.sslsock.send.side_effect = BlockingIOError transport = self._make_one() transport._read_wants_write = True transport._read_ready = mock.Mock() transport._write_ready() self.assertFalse(transport._read_wants_write) transport._read_ready.assert_called_with() self.loop._add_reader.assert_called_with( transport._sock_fd, transport._read_ready) def test_write_eof(self): tr = self._make_one() self.assertFalse(tr.can_write_eof()) self.assertRaises(NotImplementedError, tr.write_eof) def check_close(self): tr = self._make_one() tr.close() self.assertTrue(tr.is_closing()) self.assertEqual(1, self.loop.remove_reader_count[1]) self.assertEqual(tr._conn_lost, 1) tr.close() self.assertEqual(tr._conn_lost, 1) self.assertEqual(1, self.loop.remove_reader_count[1]) test_utils.run_briefly(self.loop) def test_close(self): self.check_close() self.assertTrue(self.protocol.connection_made.called) self.assertTrue(self.protocol.connection_lost.called) def test_close_not_connected(self): self.sslsock.do_handshake.side_effect = ssl.SSLWantReadError self.check_close() self.assertFalse(self.protocol.connection_made.called) self.assertFalse(self.protocol.connection_lost.called) @unittest.skipIf(ssl is None, 'No SSL support') def test_server_hostname(self): self.ssl_transport(server_hostname='localhost') self.sslcontext.wrap_socket.assert_called_with( self.sock, do_handshake_on_connect=False, server_side=False, server_hostname='localhost') class SelectorSslWithoutSslTransportTests(unittest.TestCase): @mock.patch('asyncio.selector_events.ssl', None) def test_ssl_transport_requires_ssl_module(self): Mock = mock.Mock with self.assertRaises(RuntimeError): _SelectorSslTransport(Mock(), Mock(), Mock(), Mock()) class SelectorDatagramTransportTests(test_utils.TestCase): def setUp(self): super().setUp() self.loop = self.new_test_loop() self.protocol = test_utils.make_test_protocol(asyncio.DatagramProtocol) self.sock = mock.Mock(spec_set=socket.socket) self.sock.fileno.return_value = 7 def datagram_transport(self, address=None): transport = _SelectorDatagramTransport(self.loop, self.sock, self.protocol, address=address) self.addCleanup(close_transport, transport) return transport def test_read_ready(self): transport = self.datagram_transport() self.sock.recvfrom.return_value = (b'data', ('0.0.0.0', 1234)) transport._read_ready() self.protocol.datagram_received.assert_called_with( b'data', ('0.0.0.0', 1234)) def test_read_ready_tryagain(self): transport = self.datagram_transport() self.sock.recvfrom.side_effect = BlockingIOError transport._fatal_error = mock.Mock() transport._read_ready() self.assertFalse(transport._fatal_error.called) def test_read_ready_err(self): transport = self.datagram_transport() err = self.sock.recvfrom.side_effect = RuntimeError() transport._fatal_error = mock.Mock() transport._read_ready() transport._fatal_error.assert_called_with( err, 'Fatal read error on datagram transport') def test_read_ready_oserr(self): transport = self.datagram_transport() err = self.sock.recvfrom.side_effect = OSError() transport._fatal_error = mock.Mock() transport._read_ready() self.assertFalse(transport._fatal_error.called) self.protocol.error_received.assert_called_with(err) def test_sendto(self): data = b'data' transport = self.datagram_transport() transport.sendto(data, ('0.0.0.0', 1234)) self.assertTrue(self.sock.sendto.called) self.assertEqual( self.sock.sendto.call_args[0], (data, ('0.0.0.0', 1234))) def test_sendto_bytearray(self): data = bytearray(b'data') transport = self.datagram_transport() transport.sendto(data, ('0.0.0.0', 1234)) self.assertTrue(self.sock.sendto.called) self.assertEqual( self.sock.sendto.call_args[0], (data, ('0.0.0.0', 1234))) def test_sendto_memoryview(self): data = memoryview(b'data') transport = self.datagram_transport() transport.sendto(data, ('0.0.0.0', 1234)) self.assertTrue(self.sock.sendto.called) self.assertEqual( self.sock.sendto.call_args[0], (data, ('0.0.0.0', 1234))) def test_sendto_no_data(self): transport = self.datagram_transport() transport._buffer.append((b'data', ('0.0.0.0', 12345))) transport.sendto(b'', ()) self.assertFalse(self.sock.sendto.called) self.assertEqual( [(b'data', ('0.0.0.0', 12345))], list(transport._buffer)) def test_sendto_buffer(self): transport = self.datagram_transport() transport._buffer.append((b'data1', ('0.0.0.0', 12345))) transport.sendto(b'data2', ('0.0.0.0', 12345)) self.assertFalse(self.sock.sendto.called) self.assertEqual( [(b'data1', ('0.0.0.0', 12345)), (b'data2', ('0.0.0.0', 12345))], list(transport._buffer)) def test_sendto_buffer_bytearray(self): data2 = bytearray(b'data2') transport = self.datagram_transport() transport._buffer.append((b'data1', ('0.0.0.0', 12345))) transport.sendto(data2, ('0.0.0.0', 12345)) self.assertFalse(self.sock.sendto.called) self.assertEqual( [(b'data1', ('0.0.0.0', 12345)), (b'data2', ('0.0.0.0', 12345))], list(transport._buffer)) self.assertIsInstance(transport._buffer[1][0], bytes) def test_sendto_buffer_memoryview(self): data2 = memoryview(b'data2') transport = self.datagram_transport() transport._buffer.append((b'data1', ('0.0.0.0', 12345))) transport.sendto(data2, ('0.0.0.0', 12345)) self.assertFalse(self.sock.sendto.called) self.assertEqual( [(b'data1', ('0.0.0.0', 12345)), (b'data2', ('0.0.0.0', 12345))], list(transport._buffer)) self.assertIsInstance(transport._buffer[1][0], bytes) def test_sendto_tryagain(self): data = b'data' self.sock.sendto.side_effect = BlockingIOError transport = self.datagram_transport() transport.sendto(data, ('0.0.0.0', 12345)) self.loop.assert_writer(7, transport._sendto_ready) self.assertEqual( [(b'data', ('0.0.0.0', 12345))], list(transport._buffer)) @mock.patch('asyncio.selector_events.logger') def test_sendto_exception(self, m_log): data = b'data' err = self.sock.sendto.side_effect = RuntimeError() transport = self.datagram_transport() transport._fatal_error = mock.Mock() transport.sendto(data, ()) self.assertTrue(transport._fatal_error.called) transport._fatal_error.assert_called_with( err, 'Fatal write error on datagram transport') transport._conn_lost = 1 transport._address = ('123',) transport.sendto(data) transport.sendto(data) transport.sendto(data) transport.sendto(data) transport.sendto(data) m_log.warning.assert_called_with('socket.send() raised exception.') def test_sendto_error_received(self): data = b'data' self.sock.sendto.side_effect = ConnectionRefusedError transport = self.datagram_transport() transport._fatal_error = mock.Mock() transport.sendto(data, ()) self.assertEqual(transport._conn_lost, 0) self.assertFalse(transport._fatal_error.called) def test_sendto_error_received_connected(self): data = b'data' self.sock.send.side_effect = ConnectionRefusedError transport = self.datagram_transport(address=('0.0.0.0', 1)) transport._fatal_error = mock.Mock() transport.sendto(data) self.assertFalse(transport._fatal_error.called) self.assertTrue(self.protocol.error_received.called) def test_sendto_str(self): transport = self.datagram_transport() self.assertRaises(TypeError, transport.sendto, 'str', ()) def test_sendto_connected_addr(self): transport = self.datagram_transport(address=('0.0.0.0', 1)) self.assertRaises( ValueError, transport.sendto, b'str', ('0.0.0.0', 2)) def test_sendto_closing(self): transport = self.datagram_transport(address=(1,)) transport.close() self.assertEqual(transport._conn_lost, 1) transport.sendto(b'data', (1,)) self.assertEqual(transport._conn_lost, 2) def test_sendto_ready(self): data = b'data' self.sock.sendto.return_value = len(data) transport = self.datagram_transport() transport._buffer.append((data, ('0.0.0.0', 12345))) self.loop._add_writer(7, transport._sendto_ready) transport._sendto_ready() self.assertTrue(self.sock.sendto.called) self.assertEqual( self.sock.sendto.call_args[0], (data, ('0.0.0.0', 12345))) self.assertFalse(self.loop.writers) def test_sendto_ready_closing(self): data = b'data' self.sock.send.return_value = len(data) transport = self.datagram_transport() transport._closing = True transport._buffer.append((data, ())) self.loop._add_writer(7, transport._sendto_ready) transport._sendto_ready() self.sock.sendto.assert_called_with(data, ()) self.assertFalse(self.loop.writers) self.sock.close.assert_called_with() self.protocol.connection_lost.assert_called_with(None) def test_sendto_ready_no_data(self): transport = self.datagram_transport() self.loop._add_writer(7, transport._sendto_ready) transport._sendto_ready() self.assertFalse(self.sock.sendto.called) self.assertFalse(self.loop.writers) def test_sendto_ready_tryagain(self): self.sock.sendto.side_effect = BlockingIOError transport = self.datagram_transport() transport._buffer.extend([(b'data1', ()), (b'data2', ())]) self.loop._add_writer(7, transport._sendto_ready) transport._sendto_ready() self.loop.assert_writer(7, transport._sendto_ready) self.assertEqual( [(b'data1', ()), (b'data2', ())], list(transport._buffer)) def test_sendto_ready_exception(self): err = self.sock.sendto.side_effect = RuntimeError() transport = self.datagram_transport() transport._fatal_error = mock.Mock() transport._buffer.append((b'data', ())) transport._sendto_ready() transport._fatal_error.assert_called_with( err, 'Fatal write error on datagram transport') def test_sendto_ready_error_received(self): self.sock.sendto.side_effect = ConnectionRefusedError transport = self.datagram_transport() transport._fatal_error = mock.Mock() transport._buffer.append((b'data', ())) transport._sendto_ready() self.assertFalse(transport._fatal_error.called) def test_sendto_ready_error_received_connection(self): self.sock.send.side_effect = ConnectionRefusedError transport = self.datagram_transport(address=('0.0.0.0', 1)) transport._fatal_error = mock.Mock() transport._buffer.append((b'data', ())) transport._sendto_ready() self.assertFalse(transport._fatal_error.called) self.assertTrue(self.protocol.error_received.called) @mock.patch('asyncio.base_events.logger.error') def test_fatal_error_connected(self, m_exc): transport = self.datagram_transport(address=('0.0.0.0', 1)) err = ConnectionRefusedError() transport._fatal_error(err) self.assertFalse(self.protocol.error_received.called) m_exc.assert_called_with( test_utils.MockPattern( 'Fatal error on transport\nprotocol:.*\ntransport:.*'), exc_info=(ConnectionRefusedError, MOCK_ANY, MOCK_ANY)) if __name__ == '__main__': unittest.main()
67,144
1,862
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_asyncio/test_streams.py
"""Tests for streams.py.""" import gc import os import queue import pickle import socket import sys import threading import unittest from unittest import mock try: import ssl except ImportError: ssl = None import asyncio from asyncio import test_utils class StreamReaderTests(test_utils.TestCase): DATA = b'line1\nline2\nline3\n' def setUp(self): super().setUp() self.loop = asyncio.new_event_loop() self.set_event_loop(self.loop) def tearDown(self): # just in case if we have transport close callbacks test_utils.run_briefly(self.loop) self.loop.close() gc.collect() super().tearDown() @mock.patch('asyncio.streams.events') def test_ctor_global_loop(self, m_events): stream = asyncio.StreamReader() self.assertIs(stream._loop, m_events.get_event_loop.return_value) def _basetest_open_connection(self, open_connection_fut): reader, writer = self.loop.run_until_complete(open_connection_fut) writer.write(b'GET / HTTP/1.0\r\n\r\n') f = reader.readline() data = self.loop.run_until_complete(f) self.assertEqual(data, b'HTTP/1.0 200 OK\r\n') f = reader.read() data = self.loop.run_until_complete(f) self.assertTrue(data.endswith(b'\r\n\r\nTest message')) writer.close() def test_open_connection(self): with test_utils.run_test_server() as httpd: conn_fut = asyncio.open_connection(*httpd.address, loop=self.loop) self._basetest_open_connection(conn_fut) @unittest.skipUnless(hasattr(socket, 'AF_UNIX'), 'No UNIX Sockets') def test_open_unix_connection(self): with test_utils.run_test_unix_server() as httpd: conn_fut = asyncio.open_unix_connection(httpd.address, loop=self.loop) self._basetest_open_connection(conn_fut) def _basetest_open_connection_no_loop_ssl(self, open_connection_fut): try: reader, writer = self.loop.run_until_complete(open_connection_fut) finally: asyncio.set_event_loop(None) writer.write(b'GET / HTTP/1.0\r\n\r\n') f = reader.read() data = self.loop.run_until_complete(f) self.assertTrue(data.endswith(b'\r\n\r\nTest message')) writer.close() @unittest.skipIf(ssl is None, 'No ssl module') def test_open_connection_no_loop_ssl(self): with test_utils.run_test_server(use_ssl=True) as httpd: conn_fut = asyncio.open_connection( *httpd.address, ssl=test_utils.dummy_ssl_context(), loop=self.loop) self._basetest_open_connection_no_loop_ssl(conn_fut) @unittest.skipIf(ssl is None, 'No ssl module') @unittest.skipUnless(hasattr(socket, 'AF_UNIX'), 'No UNIX Sockets') def test_open_unix_connection_no_loop_ssl(self): with test_utils.run_test_unix_server(use_ssl=True) as httpd: conn_fut = asyncio.open_unix_connection( httpd.address, ssl=test_utils.dummy_ssl_context(), server_hostname='', loop=self.loop) self._basetest_open_connection_no_loop_ssl(conn_fut) def _basetest_open_connection_error(self, open_connection_fut): reader, writer = self.loop.run_until_complete(open_connection_fut) writer._protocol.connection_lost(ZeroDivisionError()) f = reader.read() with self.assertRaises(ZeroDivisionError): self.loop.run_until_complete(f) writer.close() test_utils.run_briefly(self.loop) def test_open_connection_error(self): with test_utils.run_test_server() as httpd: conn_fut = asyncio.open_connection(*httpd.address, loop=self.loop) self._basetest_open_connection_error(conn_fut) @unittest.skipUnless(hasattr(socket, 'AF_UNIX'), 'No UNIX Sockets') def test_open_unix_connection_error(self): with test_utils.run_test_unix_server() as httpd: conn_fut = asyncio.open_unix_connection(httpd.address, loop=self.loop) self._basetest_open_connection_error(conn_fut) def test_feed_empty_data(self): stream = asyncio.StreamReader(loop=self.loop) stream.feed_data(b'') self.assertEqual(b'', stream._buffer) def test_feed_nonempty_data(self): stream = asyncio.StreamReader(loop=self.loop) stream.feed_data(self.DATA) self.assertEqual(self.DATA, stream._buffer) def test_read_zero(self): # Read zero bytes. stream = asyncio.StreamReader(loop=self.loop) stream.feed_data(self.DATA) data = self.loop.run_until_complete(stream.read(0)) self.assertEqual(b'', data) self.assertEqual(self.DATA, stream._buffer) def test_read(self): # Read bytes. stream = asyncio.StreamReader(loop=self.loop) read_task = asyncio.Task(stream.read(30), loop=self.loop) def cb(): stream.feed_data(self.DATA) self.loop.call_soon(cb) data = self.loop.run_until_complete(read_task) self.assertEqual(self.DATA, data) self.assertEqual(b'', stream._buffer) def test_read_line_breaks(self): # Read bytes without line breaks. stream = asyncio.StreamReader(loop=self.loop) stream.feed_data(b'line1') stream.feed_data(b'line2') data = self.loop.run_until_complete(stream.read(5)) self.assertEqual(b'line1', data) self.assertEqual(b'line2', stream._buffer) def test_read_eof(self): # Read bytes, stop at eof. stream = asyncio.StreamReader(loop=self.loop) read_task = asyncio.Task(stream.read(1024), loop=self.loop) def cb(): stream.feed_eof() self.loop.call_soon(cb) data = self.loop.run_until_complete(read_task) self.assertEqual(b'', data) self.assertEqual(b'', stream._buffer) def test_read_until_eof(self): # Read all bytes until eof. stream = asyncio.StreamReader(loop=self.loop) read_task = asyncio.Task(stream.read(-1), loop=self.loop) def cb(): stream.feed_data(b'chunk1\n') stream.feed_data(b'chunk2') stream.feed_eof() self.loop.call_soon(cb) data = self.loop.run_until_complete(read_task) self.assertEqual(b'chunk1\nchunk2', data) self.assertEqual(b'', stream._buffer) def test_read_exception(self): stream = asyncio.StreamReader(loop=self.loop) stream.feed_data(b'line\n') data = self.loop.run_until_complete(stream.read(2)) self.assertEqual(b'li', data) stream.set_exception(ValueError()) self.assertRaises( ValueError, self.loop.run_until_complete, stream.read(2)) def test_invalid_limit(self): with self.assertRaisesRegex(ValueError, 'imit'): asyncio.StreamReader(limit=0, loop=self.loop) with self.assertRaisesRegex(ValueError, 'imit'): asyncio.StreamReader(limit=-1, loop=self.loop) def test_read_limit(self): stream = asyncio.StreamReader(limit=3, loop=self.loop) stream.feed_data(b'chunk') data = self.loop.run_until_complete(stream.read(5)) self.assertEqual(b'chunk', data) self.assertEqual(b'', stream._buffer) def test_readline(self): # Read one line. 'readline' will need to wait for the data # to come from 'cb' stream = asyncio.StreamReader(loop=self.loop) stream.feed_data(b'chunk1 ') read_task = asyncio.Task(stream.readline(), loop=self.loop) def cb(): stream.feed_data(b'chunk2 ') stream.feed_data(b'chunk3 ') stream.feed_data(b'\n chunk4') self.loop.call_soon(cb) line = self.loop.run_until_complete(read_task) self.assertEqual(b'chunk1 chunk2 chunk3 \n', line) self.assertEqual(b' chunk4', stream._buffer) def test_readline_limit_with_existing_data(self): # Read one line. The data is in StreamReader's buffer # before the event loop is run. stream = asyncio.StreamReader(limit=3, loop=self.loop) stream.feed_data(b'li') stream.feed_data(b'ne1\nline2\n') self.assertRaises( ValueError, self.loop.run_until_complete, stream.readline()) # The buffer should contain the remaining data after exception self.assertEqual(b'line2\n', stream._buffer) stream = asyncio.StreamReader(limit=3, loop=self.loop) stream.feed_data(b'li') stream.feed_data(b'ne1') stream.feed_data(b'li') self.assertRaises( ValueError, self.loop.run_until_complete, stream.readline()) # No b'\n' at the end. The 'limit' is set to 3. So before # waiting for the new data in buffer, 'readline' will consume # the entire buffer, and since the length of the consumed data # is more than 3, it will raise a ValueError. The buffer is # expected to be empty now. self.assertEqual(b'', stream._buffer) def test_at_eof(self): stream = asyncio.StreamReader(loop=self.loop) self.assertFalse(stream.at_eof()) stream.feed_data(b'some data\n') self.assertFalse(stream.at_eof()) self.loop.run_until_complete(stream.readline()) self.assertFalse(stream.at_eof()) stream.feed_data(b'some data\n') stream.feed_eof() self.loop.run_until_complete(stream.readline()) self.assertTrue(stream.at_eof()) def test_readline_limit(self): # Read one line. StreamReaders are fed with data after # their 'readline' methods are called. stream = asyncio.StreamReader(limit=7, loop=self.loop) def cb(): stream.feed_data(b'chunk1') stream.feed_data(b'chunk2') stream.feed_data(b'chunk3\n') stream.feed_eof() self.loop.call_soon(cb) self.assertRaises( ValueError, self.loop.run_until_complete, stream.readline()) # The buffer had just one line of data, and after raising # a ValueError it should be empty. self.assertEqual(b'', stream._buffer) stream = asyncio.StreamReader(limit=7, loop=self.loop) def cb(): stream.feed_data(b'chunk1') stream.feed_data(b'chunk2\n') stream.feed_data(b'chunk3\n') stream.feed_eof() self.loop.call_soon(cb) self.assertRaises( ValueError, self.loop.run_until_complete, stream.readline()) self.assertEqual(b'chunk3\n', stream._buffer) # check strictness of the limit stream = asyncio.StreamReader(limit=7, loop=self.loop) stream.feed_data(b'1234567\n') line = self.loop.run_until_complete(stream.readline()) self.assertEqual(b'1234567\n', line) self.assertEqual(b'', stream._buffer) stream.feed_data(b'12345678\n') with self.assertRaises(ValueError) as cm: self.loop.run_until_complete(stream.readline()) self.assertEqual(b'', stream._buffer) stream.feed_data(b'12345678') with self.assertRaises(ValueError) as cm: self.loop.run_until_complete(stream.readline()) self.assertEqual(b'', stream._buffer) def test_readline_nolimit_nowait(self): # All needed data for the first 'readline' call will be # in the buffer. stream = asyncio.StreamReader(loop=self.loop) stream.feed_data(self.DATA[:6]) stream.feed_data(self.DATA[6:]) line = self.loop.run_until_complete(stream.readline()) self.assertEqual(b'line1\n', line) self.assertEqual(b'line2\nline3\n', stream._buffer) def test_readline_eof(self): stream = asyncio.StreamReader(loop=self.loop) stream.feed_data(b'some data') stream.feed_eof() line = self.loop.run_until_complete(stream.readline()) self.assertEqual(b'some data', line) def test_readline_empty_eof(self): stream = asyncio.StreamReader(loop=self.loop) stream.feed_eof() line = self.loop.run_until_complete(stream.readline()) self.assertEqual(b'', line) def test_readline_read_byte_count(self): stream = asyncio.StreamReader(loop=self.loop) stream.feed_data(self.DATA) self.loop.run_until_complete(stream.readline()) data = self.loop.run_until_complete(stream.read(7)) self.assertEqual(b'line2\nl', data) self.assertEqual(b'ine3\n', stream._buffer) def test_readline_exception(self): stream = asyncio.StreamReader(loop=self.loop) stream.feed_data(b'line\n') data = self.loop.run_until_complete(stream.readline()) self.assertEqual(b'line\n', data) stream.set_exception(ValueError()) self.assertRaises( ValueError, self.loop.run_until_complete, stream.readline()) self.assertEqual(b'', stream._buffer) def test_readuntil_separator(self): stream = asyncio.StreamReader(loop=self.loop) with self.assertRaisesRegex(ValueError, 'Separator should be'): self.loop.run_until_complete(stream.readuntil(separator=b'')) def test_readuntil_multi_chunks(self): stream = asyncio.StreamReader(loop=self.loop) stream.feed_data(b'lineAAA') data = self.loop.run_until_complete(stream.readuntil(separator=b'AAA')) self.assertEqual(b'lineAAA', data) self.assertEqual(b'', stream._buffer) stream.feed_data(b'lineAAA') data = self.loop.run_until_complete(stream.readuntil(b'AAA')) self.assertEqual(b'lineAAA', data) self.assertEqual(b'', stream._buffer) stream.feed_data(b'lineAAAxxx') data = self.loop.run_until_complete(stream.readuntil(b'AAA')) self.assertEqual(b'lineAAA', data) self.assertEqual(b'xxx', stream._buffer) def test_readuntil_multi_chunks_1(self): stream = asyncio.StreamReader(loop=self.loop) stream.feed_data(b'QWEaa') stream.feed_data(b'XYaa') stream.feed_data(b'a') data = self.loop.run_until_complete(stream.readuntil(b'aaa')) self.assertEqual(b'QWEaaXYaaa', data) self.assertEqual(b'', stream._buffer) stream.feed_data(b'QWEaa') stream.feed_data(b'XYa') stream.feed_data(b'aa') data = self.loop.run_until_complete(stream.readuntil(b'aaa')) self.assertEqual(b'QWEaaXYaaa', data) self.assertEqual(b'', stream._buffer) stream.feed_data(b'aaa') data = self.loop.run_until_complete(stream.readuntil(b'aaa')) self.assertEqual(b'aaa', data) self.assertEqual(b'', stream._buffer) stream.feed_data(b'Xaaa') data = self.loop.run_until_complete(stream.readuntil(b'aaa')) self.assertEqual(b'Xaaa', data) self.assertEqual(b'', stream._buffer) stream.feed_data(b'XXX') stream.feed_data(b'a') stream.feed_data(b'a') stream.feed_data(b'a') data = self.loop.run_until_complete(stream.readuntil(b'aaa')) self.assertEqual(b'XXXaaa', data) self.assertEqual(b'', stream._buffer) def test_readuntil_eof(self): stream = asyncio.StreamReader(loop=self.loop) stream.feed_data(b'some dataAA') stream.feed_eof() with self.assertRaises(asyncio.IncompleteReadError) as cm: self.loop.run_until_complete(stream.readuntil(b'AAA')) self.assertEqual(cm.exception.partial, b'some dataAA') self.assertIsNone(cm.exception.expected) self.assertEqual(b'', stream._buffer) def test_readuntil_limit_found_sep(self): stream = asyncio.StreamReader(loop=self.loop, limit=3) stream.feed_data(b'some dataAA') with self.assertRaisesRegex(asyncio.LimitOverrunError, 'not found') as cm: self.loop.run_until_complete(stream.readuntil(b'AAA')) self.assertEqual(b'some dataAA', stream._buffer) stream.feed_data(b'A') with self.assertRaisesRegex(asyncio.LimitOverrunError, 'is found') as cm: self.loop.run_until_complete(stream.readuntil(b'AAA')) self.assertEqual(b'some dataAAA', stream._buffer) def test_readexactly_zero_or_less(self): # Read exact number of bytes (zero or less). stream = asyncio.StreamReader(loop=self.loop) stream.feed_data(self.DATA) data = self.loop.run_until_complete(stream.readexactly(0)) self.assertEqual(b'', data) self.assertEqual(self.DATA, stream._buffer) with self.assertRaisesRegex(ValueError, 'less than zero'): self.loop.run_until_complete(stream.readexactly(-1)) self.assertEqual(self.DATA, stream._buffer) def test_readexactly(self): # Read exact number of bytes. stream = asyncio.StreamReader(loop=self.loop) n = 2 * len(self.DATA) read_task = asyncio.Task(stream.readexactly(n), loop=self.loop) def cb(): stream.feed_data(self.DATA) stream.feed_data(self.DATA) stream.feed_data(self.DATA) self.loop.call_soon(cb) data = self.loop.run_until_complete(read_task) self.assertEqual(self.DATA + self.DATA, data) self.assertEqual(self.DATA, stream._buffer) def test_readexactly_limit(self): stream = asyncio.StreamReader(limit=3, loop=self.loop) stream.feed_data(b'chunk') data = self.loop.run_until_complete(stream.readexactly(5)) self.assertEqual(b'chunk', data) self.assertEqual(b'', stream._buffer) def test_readexactly_eof(self): # Read exact number of bytes (eof). stream = asyncio.StreamReader(loop=self.loop) n = 2 * len(self.DATA) read_task = asyncio.Task(stream.readexactly(n), loop=self.loop) def cb(): stream.feed_data(self.DATA) stream.feed_eof() self.loop.call_soon(cb) with self.assertRaises(asyncio.IncompleteReadError) as cm: self.loop.run_until_complete(read_task) self.assertEqual(cm.exception.partial, self.DATA) self.assertEqual(cm.exception.expected, n) self.assertEqual(str(cm.exception), '18 bytes read on a total of 36 expected bytes') self.assertEqual(b'', stream._buffer) def test_readexactly_exception(self): stream = asyncio.StreamReader(loop=self.loop) stream.feed_data(b'line\n') data = self.loop.run_until_complete(stream.readexactly(2)) self.assertEqual(b'li', data) stream.set_exception(ValueError()) self.assertRaises( ValueError, self.loop.run_until_complete, stream.readexactly(2)) def test_exception(self): stream = asyncio.StreamReader(loop=self.loop) self.assertIsNone(stream.exception()) exc = ValueError() stream.set_exception(exc) self.assertIs(stream.exception(), exc) def test_exception_waiter(self): stream = asyncio.StreamReader(loop=self.loop) @asyncio.coroutine def set_err(): stream.set_exception(ValueError()) t1 = asyncio.Task(stream.readline(), loop=self.loop) t2 = asyncio.Task(set_err(), loop=self.loop) self.loop.run_until_complete(asyncio.wait([t1, t2], loop=self.loop)) self.assertRaises(ValueError, t1.result) def test_exception_cancel(self): stream = asyncio.StreamReader(loop=self.loop) t = asyncio.Task(stream.readline(), loop=self.loop) test_utils.run_briefly(self.loop) t.cancel() test_utils.run_briefly(self.loop) # The following line fails if set_exception() isn't careful. stream.set_exception(RuntimeError('message')) test_utils.run_briefly(self.loop) self.assertIs(stream._waiter, None) def test_start_server(self): class MyServer: def __init__(self, loop): self.server = None self.loop = loop @asyncio.coroutine def handle_client(self, client_reader, client_writer): data = yield from client_reader.readline() client_writer.write(data) yield from client_writer.drain() client_writer.close() def start(self): sock = socket.socket() sock.bind(('127.0.0.1', 0)) self.server = self.loop.run_until_complete( asyncio.start_server(self.handle_client, sock=sock, loop=self.loop)) return sock.getsockname() def handle_client_callback(self, client_reader, client_writer): self.loop.create_task(self.handle_client(client_reader, client_writer)) def start_callback(self): sock = socket.socket() sock.bind(('127.0.0.1', 0)) addr = sock.getsockname() sock.close() self.server = self.loop.run_until_complete( asyncio.start_server(self.handle_client_callback, host=addr[0], port=addr[1], loop=self.loop)) return addr def stop(self): if self.server is not None: self.server.close() self.loop.run_until_complete(self.server.wait_closed()) self.server = None @asyncio.coroutine def client(addr): reader, writer = yield from asyncio.open_connection( *addr, loop=self.loop) # send a line writer.write(b"hello world!\n") # read it back msgback = yield from reader.readline() writer.close() return msgback # test the server variant with a coroutine as client handler server = MyServer(self.loop) addr = server.start() msg = self.loop.run_until_complete(asyncio.Task(client(addr), loop=self.loop)) server.stop() self.assertEqual(msg, b"hello world!\n") # test the server variant with a callback as client handler server = MyServer(self.loop) addr = server.start_callback() msg = self.loop.run_until_complete(asyncio.Task(client(addr), loop=self.loop)) server.stop() self.assertEqual(msg, b"hello world!\n") @unittest.skipUnless(hasattr(socket, 'AF_UNIX'), 'No UNIX Sockets') def test_start_unix_server(self): class MyServer: def __init__(self, loop, path): self.server = None self.loop = loop self.path = path @asyncio.coroutine def handle_client(self, client_reader, client_writer): data = yield from client_reader.readline() client_writer.write(data) yield from client_writer.drain() client_writer.close() def start(self): self.server = self.loop.run_until_complete( asyncio.start_unix_server(self.handle_client, path=self.path, loop=self.loop)) def handle_client_callback(self, client_reader, client_writer): self.loop.create_task(self.handle_client(client_reader, client_writer)) def start_callback(self): start = asyncio.start_unix_server(self.handle_client_callback, path=self.path, loop=self.loop) self.server = self.loop.run_until_complete(start) def stop(self): if self.server is not None: self.server.close() self.loop.run_until_complete(self.server.wait_closed()) self.server = None @asyncio.coroutine def client(path): reader, writer = yield from asyncio.open_unix_connection( path, loop=self.loop) # send a line writer.write(b"hello world!\n") # read it back msgback = yield from reader.readline() writer.close() return msgback # test the server variant with a coroutine as client handler with test_utils.unix_socket_path() as path: server = MyServer(self.loop, path) server.start() msg = self.loop.run_until_complete(asyncio.Task(client(path), loop=self.loop)) server.stop() self.assertEqual(msg, b"hello world!\n") # test the server variant with a callback as client handler with test_utils.unix_socket_path() as path: server = MyServer(self.loop, path) server.start_callback() msg = self.loop.run_until_complete(asyncio.Task(client(path), loop=self.loop)) server.stop() self.assertEqual(msg, b"hello world!\n") @unittest.skipIf(sys.platform == 'win32', "Don't have pipes") def test_read_all_from_pipe_reader(self): # See asyncio issue 168. This test is derived from the example # subprocess_attach_read_pipe.py, but we configure the # StreamReader's limit so that twice it is less than the size # of the data writter. Also we must explicitly attach a child # watcher to the event loop. code = """\ import os, sys fd = int(sys.argv[1]) os.write(fd, b'data') os.close(fd) """ rfd, wfd = os.pipe() args = [sys.executable, '-c', code, str(wfd)] pipe = open(rfd, 'rb', 0) reader = asyncio.StreamReader(loop=self.loop, limit=1) protocol = asyncio.StreamReaderProtocol(reader, loop=self.loop) transport, _ = self.loop.run_until_complete( self.loop.connect_read_pipe(lambda: protocol, pipe)) watcher = asyncio.SafeChildWatcher() watcher.attach_loop(self.loop) try: asyncio.set_child_watcher(watcher) create = asyncio.create_subprocess_exec(*args, pass_fds={wfd}, loop=self.loop) proc = self.loop.run_until_complete(create) self.loop.run_until_complete(proc.wait()) finally: asyncio.set_child_watcher(None) os.close(wfd) data = self.loop.run_until_complete(reader.read(-1)) self.assertEqual(data, b'data') def test_streamreader_constructor(self): self.addCleanup(asyncio.set_event_loop, None) asyncio.set_event_loop(self.loop) # asyncio issue #184: Ensure that StreamReaderProtocol constructor # retrieves the current loop if the loop parameter is not set reader = asyncio.StreamReader() self.assertIs(reader._loop, self.loop) def test_streamreaderprotocol_constructor(self): self.addCleanup(asyncio.set_event_loop, None) asyncio.set_event_loop(self.loop) # asyncio issue #184: Ensure that StreamReaderProtocol constructor # retrieves the current loop if the loop parameter is not set reader = mock.Mock() protocol = asyncio.StreamReaderProtocol(reader) self.assertIs(protocol._loop, self.loop) def test_drain_raises(self): # See http://bugs.python.org/issue25441 # This test should not use asyncio for the mock server; the # whole point of the test is to test for a bug in drain() # where it never gives up the event loop but the socket is # closed on the server side. q = queue.Queue() def server(): # Runs in a separate thread. sock = socket.socket() with sock: sock.bind(('localhost', 0)) sock.listen(1) addr = sock.getsockname() q.put(addr) clt, _ = sock.accept() clt.close() @asyncio.coroutine def client(host, port): reader, writer = yield from asyncio.open_connection( host, port, loop=self.loop) while True: writer.write(b"foo\n") yield from writer.drain() # Start the server thread and wait for it to be listening. thread = threading.Thread(target=server) thread.setDaemon(True) thread.start() addr = q.get() # Should not be stuck in an infinite loop. with self.assertRaises((ConnectionResetError, BrokenPipeError)): self.loop.run_until_complete(client(*addr)) # Clean up the thread. (Only on success; on failure, it may # be stuck in accept().) thread.join() def test___repr__(self): stream = asyncio.StreamReader(loop=self.loop) self.assertEqual("<StreamReader>", repr(stream)) def test___repr__nondefault_limit(self): stream = asyncio.StreamReader(loop=self.loop, limit=123) self.assertEqual("<StreamReader l=123>", repr(stream)) def test___repr__eof(self): stream = asyncio.StreamReader(loop=self.loop) stream.feed_eof() self.assertEqual("<StreamReader eof>", repr(stream)) def test___repr__data(self): stream = asyncio.StreamReader(loop=self.loop) stream.feed_data(b'data') self.assertEqual("<StreamReader 4 bytes>", repr(stream)) def test___repr__exception(self): stream = asyncio.StreamReader(loop=self.loop) exc = RuntimeError() stream.set_exception(exc) self.assertEqual("<StreamReader e=RuntimeError()>", repr(stream)) def test___repr__waiter(self): stream = asyncio.StreamReader(loop=self.loop) stream._waiter = asyncio.Future(loop=self.loop) self.assertRegex( repr(stream), r"<StreamReader w=<Future pending[\S ]*>>") stream._waiter.set_result(None) self.loop.run_until_complete(stream._waiter) stream._waiter = None self.assertEqual("<StreamReader>", repr(stream)) def test___repr__transport(self): stream = asyncio.StreamReader(loop=self.loop) stream._transport = mock.Mock() stream._transport.__repr__ = mock.Mock() stream._transport.__repr__.return_value = "<Transport>" self.assertEqual("<StreamReader t=<Transport>>", repr(stream)) def test_IncompleteReadError_pickleable(self): e = asyncio.IncompleteReadError(b'abc', 10) for proto in range(pickle.HIGHEST_PROTOCOL + 1): with self.subTest(pickle_protocol=proto): e2 = pickle.loads(pickle.dumps(e, protocol=proto)) self.assertEqual(str(e), str(e2)) self.assertEqual(e.partial, e2.partial) self.assertEqual(e.expected, e2.expected) def test_LimitOverrunError_pickleable(self): e = asyncio.LimitOverrunError('message', 10) for proto in range(pickle.HIGHEST_PROTOCOL + 1): with self.subTest(pickle_protocol=proto): e2 = pickle.loads(pickle.dumps(e, protocol=proto)) self.assertEqual(str(e), str(e2)) self.assertEqual(e.consumed, e2.consumed) if __name__ == '__main__': unittest.main()
32,350
869
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_asyncio/test_locks.py
"""Tests for lock.py""" import unittest from unittest import mock import re import asyncio from asyncio import test_utils STR_RGX_REPR = ( r'^<(?P<class>.*?) object at (?P<address>.*?)' r'\[(?P<extras>' r'(set|unset|locked|unlocked)(,value:\d)?(,waiters:\d+)?' r')\]>\Z' ) RGX_REPR = re.compile(STR_RGX_REPR) class LockTests(test_utils.TestCase): def setUp(self): super().setUp() self.loop = self.new_test_loop() def test_ctor_loop(self): loop = mock.Mock() lock = asyncio.Lock(loop=loop) self.assertIs(lock._loop, loop) lock = asyncio.Lock(loop=self.loop) self.assertIs(lock._loop, self.loop) def test_ctor_noloop(self): asyncio.set_event_loop(self.loop) lock = asyncio.Lock() self.assertIs(lock._loop, self.loop) def test_repr(self): lock = asyncio.Lock(loop=self.loop) self.assertTrue(repr(lock).endswith('[unlocked]>')) self.assertTrue(RGX_REPR.match(repr(lock))) @asyncio.coroutine def acquire_lock(): yield from lock self.loop.run_until_complete(acquire_lock()) self.assertTrue(repr(lock).endswith('[locked]>')) self.assertTrue(RGX_REPR.match(repr(lock))) def test_lock(self): lock = asyncio.Lock(loop=self.loop) @asyncio.coroutine def acquire_lock(): return (yield from lock) res = self.loop.run_until_complete(acquire_lock()) self.assertTrue(res) self.assertTrue(lock.locked()) lock.release() self.assertFalse(lock.locked()) def test_acquire(self): lock = asyncio.Lock(loop=self.loop) result = [] self.assertTrue(self.loop.run_until_complete(lock.acquire())) @asyncio.coroutine def c1(result): if (yield from lock.acquire()): result.append(1) return True @asyncio.coroutine def c2(result): if (yield from lock.acquire()): result.append(2) return True @asyncio.coroutine def c3(result): if (yield from lock.acquire()): result.append(3) return True t1 = asyncio.Task(c1(result), loop=self.loop) t2 = asyncio.Task(c2(result), loop=self.loop) test_utils.run_briefly(self.loop) self.assertEqual([], result) lock.release() test_utils.run_briefly(self.loop) self.assertEqual([1], result) test_utils.run_briefly(self.loop) self.assertEqual([1], result) t3 = asyncio.Task(c3(result), loop=self.loop) lock.release() test_utils.run_briefly(self.loop) self.assertEqual([1, 2], result) lock.release() test_utils.run_briefly(self.loop) self.assertEqual([1, 2, 3], result) self.assertTrue(t1.done()) self.assertTrue(t1.result()) self.assertTrue(t2.done()) self.assertTrue(t2.result()) self.assertTrue(t3.done()) self.assertTrue(t3.result()) def test_acquire_cancel(self): lock = asyncio.Lock(loop=self.loop) self.assertTrue(self.loop.run_until_complete(lock.acquire())) task = asyncio.Task(lock.acquire(), loop=self.loop) self.loop.call_soon(task.cancel) self.assertRaises( asyncio.CancelledError, self.loop.run_until_complete, task) self.assertFalse(lock._waiters) def test_cancel_race(self): # Several tasks: # - A acquires the lock # - B is blocked in acquire() # - C is blocked in acquire() # # Now, concurrently: # - B is cancelled # - A releases the lock # # If B's waiter is marked cancelled but not yet removed from # _waiters, A's release() call will crash when trying to set # B's waiter; instead, it should move on to C's waiter. # Setup: A has the lock, b and c are waiting. lock = asyncio.Lock(loop=self.loop) @asyncio.coroutine def lockit(name, blocker): yield from lock.acquire() try: if blocker is not None: yield from blocker finally: lock.release() fa = asyncio.Future(loop=self.loop) ta = asyncio.Task(lockit('A', fa), loop=self.loop) test_utils.run_briefly(self.loop) self.assertTrue(lock.locked()) tb = asyncio.Task(lockit('B', None), loop=self.loop) test_utils.run_briefly(self.loop) self.assertEqual(len(lock._waiters), 1) tc = asyncio.Task(lockit('C', None), loop=self.loop) test_utils.run_briefly(self.loop) self.assertEqual(len(lock._waiters), 2) # Create the race and check. # Without the fix this failed at the last assert. fa.set_result(None) tb.cancel() self.assertTrue(lock._waiters[0].cancelled()) test_utils.run_briefly(self.loop) self.assertFalse(lock.locked()) self.assertTrue(ta.done()) self.assertTrue(tb.cancelled()) self.assertTrue(tc.done()) def test_cancel_release_race(self): # Issue 32734 # Acquire 4 locks, cancel second, release first # and 2 locks are taken at once. lock = asyncio.Lock(loop=self.loop) lock_count = 0 call_count = 0 async def lockit(): nonlocal lock_count nonlocal call_count call_count += 1 await lock.acquire() lock_count += 1 async def lockandtrigger(): await lock.acquire() self.loop.call_soon(trigger) def trigger(): t1.cancel() lock.release() t0 = self.loop.create_task(lockandtrigger()) t1 = self.loop.create_task(lockit()) t2 = self.loop.create_task(lockit()) t3 = self.loop.create_task(lockit()) # First loop acquires all test_utils.run_briefly(self.loop) self.assertTrue(t0.done()) # Second loop calls trigger test_utils.run_briefly(self.loop) # Third loop calls cancellation test_utils.run_briefly(self.loop) # Make sure only one lock was taken self.assertEqual(lock_count, 1) # While 3 calls were made to lockit() self.assertEqual(call_count, 3) self.assertTrue(t1.cancelled() and t2.done()) # Cleanup the task that is stuck on acquire. t3.cancel() test_utils.run_briefly(self.loop) self.assertTrue(t3.cancelled()) def test_finished_waiter_cancelled(self): lock = asyncio.Lock(loop=self.loop) ta = asyncio.Task(lock.acquire(), loop=self.loop) test_utils.run_briefly(self.loop) self.assertTrue(lock.locked()) tb = asyncio.Task(lock.acquire(), loop=self.loop) test_utils.run_briefly(self.loop) self.assertEqual(len(lock._waiters), 1) # Create a second waiter, wake up the first, and cancel it. # Without the fix, the second was not woken up. tc = asyncio.Task(lock.acquire(), loop=self.loop) lock.release() tb.cancel() test_utils.run_briefly(self.loop) self.assertTrue(lock.locked()) self.assertTrue(ta.done()) self.assertTrue(tb.cancelled()) def test_release_not_acquired(self): lock = asyncio.Lock(loop=self.loop) self.assertRaises(RuntimeError, lock.release) def test_release_no_waiters(self): lock = asyncio.Lock(loop=self.loop) self.loop.run_until_complete(lock.acquire()) self.assertTrue(lock.locked()) lock.release() self.assertFalse(lock.locked()) def test_context_manager(self): lock = asyncio.Lock(loop=self.loop) @asyncio.coroutine def acquire_lock(): return (yield from lock) with self.loop.run_until_complete(acquire_lock()): self.assertTrue(lock.locked()) self.assertFalse(lock.locked()) def test_context_manager_cant_reuse(self): lock = asyncio.Lock(loop=self.loop) @asyncio.coroutine def acquire_lock(): return (yield from lock) # This spells "yield from lock" outside a generator. cm = self.loop.run_until_complete(acquire_lock()) with cm: self.assertTrue(lock.locked()) self.assertFalse(lock.locked()) with self.assertRaises(AttributeError): with cm: pass def test_context_manager_no_yield(self): lock = asyncio.Lock(loop=self.loop) try: with lock: self.fail('RuntimeError is not raised in with expression') except RuntimeError as err: self.assertEqual( str(err), '"yield from" should be used as context manager expression') self.assertFalse(lock.locked()) class EventTests(test_utils.TestCase): def setUp(self): super().setUp() self.loop = self.new_test_loop() def test_ctor_loop(self): loop = mock.Mock() ev = asyncio.Event(loop=loop) self.assertIs(ev._loop, loop) ev = asyncio.Event(loop=self.loop) self.assertIs(ev._loop, self.loop) def test_ctor_noloop(self): asyncio.set_event_loop(self.loop) ev = asyncio.Event() self.assertIs(ev._loop, self.loop) def test_repr(self): ev = asyncio.Event(loop=self.loop) self.assertTrue(repr(ev).endswith('[unset]>')) match = RGX_REPR.match(repr(ev)) self.assertEqual(match.group('extras'), 'unset') ev.set() self.assertTrue(repr(ev).endswith('[set]>')) self.assertTrue(RGX_REPR.match(repr(ev))) ev._waiters.append(mock.Mock()) self.assertTrue('waiters:1' in repr(ev)) self.assertTrue(RGX_REPR.match(repr(ev))) def test_wait(self): ev = asyncio.Event(loop=self.loop) self.assertFalse(ev.is_set()) result = [] @asyncio.coroutine def c1(result): if (yield from ev.wait()): result.append(1) @asyncio.coroutine def c2(result): if (yield from ev.wait()): result.append(2) @asyncio.coroutine def c3(result): if (yield from ev.wait()): result.append(3) t1 = asyncio.Task(c1(result), loop=self.loop) t2 = asyncio.Task(c2(result), loop=self.loop) test_utils.run_briefly(self.loop) self.assertEqual([], result) t3 = asyncio.Task(c3(result), loop=self.loop) ev.set() test_utils.run_briefly(self.loop) self.assertEqual([3, 1, 2], result) self.assertTrue(t1.done()) self.assertIsNone(t1.result()) self.assertTrue(t2.done()) self.assertIsNone(t2.result()) self.assertTrue(t3.done()) self.assertIsNone(t3.result()) def test_wait_on_set(self): ev = asyncio.Event(loop=self.loop) ev.set() res = self.loop.run_until_complete(ev.wait()) self.assertTrue(res) def test_wait_cancel(self): ev = asyncio.Event(loop=self.loop) wait = asyncio.Task(ev.wait(), loop=self.loop) self.loop.call_soon(wait.cancel) self.assertRaises( asyncio.CancelledError, self.loop.run_until_complete, wait) self.assertFalse(ev._waiters) def test_clear(self): ev = asyncio.Event(loop=self.loop) self.assertFalse(ev.is_set()) ev.set() self.assertTrue(ev.is_set()) ev.clear() self.assertFalse(ev.is_set()) def test_clear_with_waiters(self): ev = asyncio.Event(loop=self.loop) result = [] @asyncio.coroutine def c1(result): if (yield from ev.wait()): result.append(1) return True t = asyncio.Task(c1(result), loop=self.loop) test_utils.run_briefly(self.loop) self.assertEqual([], result) ev.set() ev.clear() self.assertFalse(ev.is_set()) ev.set() ev.set() self.assertEqual(1, len(ev._waiters)) test_utils.run_briefly(self.loop) self.assertEqual([1], result) self.assertEqual(0, len(ev._waiters)) self.assertTrue(t.done()) self.assertTrue(t.result()) class ConditionTests(test_utils.TestCase): def setUp(self): super().setUp() self.loop = self.new_test_loop() def test_ctor_loop(self): loop = mock.Mock() cond = asyncio.Condition(loop=loop) self.assertIs(cond._loop, loop) cond = asyncio.Condition(loop=self.loop) self.assertIs(cond._loop, self.loop) def test_ctor_noloop(self): asyncio.set_event_loop(self.loop) cond = asyncio.Condition() self.assertIs(cond._loop, self.loop) def test_wait(self): cond = asyncio.Condition(loop=self.loop) result = [] @asyncio.coroutine def c1(result): yield from cond.acquire() if (yield from cond.wait()): result.append(1) return True @asyncio.coroutine def c2(result): yield from cond.acquire() if (yield from cond.wait()): result.append(2) return True @asyncio.coroutine def c3(result): yield from cond.acquire() if (yield from cond.wait()): result.append(3) return True t1 = asyncio.Task(c1(result), loop=self.loop) t2 = asyncio.Task(c2(result), loop=self.loop) t3 = asyncio.Task(c3(result), loop=self.loop) test_utils.run_briefly(self.loop) self.assertEqual([], result) self.assertFalse(cond.locked()) self.assertTrue(self.loop.run_until_complete(cond.acquire())) cond.notify() test_utils.run_briefly(self.loop) self.assertEqual([], result) self.assertTrue(cond.locked()) cond.release() test_utils.run_briefly(self.loop) self.assertEqual([1], result) self.assertTrue(cond.locked()) cond.notify(2) test_utils.run_briefly(self.loop) self.assertEqual([1], result) self.assertTrue(cond.locked()) cond.release() test_utils.run_briefly(self.loop) self.assertEqual([1, 2], result) self.assertTrue(cond.locked()) cond.release() test_utils.run_briefly(self.loop) self.assertEqual([1, 2, 3], result) self.assertTrue(cond.locked()) self.assertTrue(t1.done()) self.assertTrue(t1.result()) self.assertTrue(t2.done()) self.assertTrue(t2.result()) self.assertTrue(t3.done()) self.assertTrue(t3.result()) def test_wait_cancel(self): cond = asyncio.Condition(loop=self.loop) self.loop.run_until_complete(cond.acquire()) wait = asyncio.Task(cond.wait(), loop=self.loop) self.loop.call_soon(wait.cancel) self.assertRaises( asyncio.CancelledError, self.loop.run_until_complete, wait) self.assertFalse(cond._waiters) self.assertTrue(cond.locked()) def test_wait_cancel_contested(self): cond = asyncio.Condition(loop=self.loop) self.loop.run_until_complete(cond.acquire()) self.assertTrue(cond.locked()) wait_task = asyncio.Task(cond.wait(), loop=self.loop) test_utils.run_briefly(self.loop) self.assertFalse(cond.locked()) # Notify, but contest the lock before cancelling self.loop.run_until_complete(cond.acquire()) self.assertTrue(cond.locked()) cond.notify() self.loop.call_soon(wait_task.cancel) self.loop.call_soon(cond.release) try: self.loop.run_until_complete(wait_task) except asyncio.CancelledError: # Should not happen, since no cancellation points pass self.assertTrue(cond.locked()) def test_wait_cancel_after_notify(self): # See bpo-32841 cond = asyncio.Condition(loop=self.loop) waited = False async def wait_on_cond(): nonlocal waited async with cond: waited = True # Make sure this area was reached await cond.wait() waiter = asyncio.ensure_future(wait_on_cond(), loop=self.loop) test_utils.run_briefly(self.loop) # Start waiting self.loop.run_until_complete(cond.acquire()) cond.notify() test_utils.run_briefly(self.loop) # Get to acquire() waiter.cancel() test_utils.run_briefly(self.loop) # Activate cancellation cond.release() test_utils.run_briefly(self.loop) # Cancellation should occur self.assertTrue(waiter.cancelled()) self.assertTrue(waited) def test_wait_unacquired(self): cond = asyncio.Condition(loop=self.loop) self.assertRaises( RuntimeError, self.loop.run_until_complete, cond.wait()) def test_wait_for(self): cond = asyncio.Condition(loop=self.loop) presult = False def predicate(): return presult result = [] @asyncio.coroutine def c1(result): yield from cond.acquire() if (yield from cond.wait_for(predicate)): result.append(1) cond.release() return True t = asyncio.Task(c1(result), loop=self.loop) test_utils.run_briefly(self.loop) self.assertEqual([], result) self.loop.run_until_complete(cond.acquire()) cond.notify() cond.release() test_utils.run_briefly(self.loop) self.assertEqual([], result) presult = True self.loop.run_until_complete(cond.acquire()) cond.notify() cond.release() test_utils.run_briefly(self.loop) self.assertEqual([1], result) self.assertTrue(t.done()) self.assertTrue(t.result()) def test_wait_for_unacquired(self): cond = asyncio.Condition(loop=self.loop) # predicate can return true immediately res = self.loop.run_until_complete(cond.wait_for(lambda: [1, 2, 3])) self.assertEqual([1, 2, 3], res) self.assertRaises( RuntimeError, self.loop.run_until_complete, cond.wait_for(lambda: False)) def test_notify(self): cond = asyncio.Condition(loop=self.loop) result = [] @asyncio.coroutine def c1(result): yield from cond.acquire() if (yield from cond.wait()): result.append(1) cond.release() return True @asyncio.coroutine def c2(result): yield from cond.acquire() if (yield from cond.wait()): result.append(2) cond.release() return True @asyncio.coroutine def c3(result): yield from cond.acquire() if (yield from cond.wait()): result.append(3) cond.release() return True t1 = asyncio.Task(c1(result), loop=self.loop) t2 = asyncio.Task(c2(result), loop=self.loop) t3 = asyncio.Task(c3(result), loop=self.loop) test_utils.run_briefly(self.loop) self.assertEqual([], result) self.loop.run_until_complete(cond.acquire()) cond.notify(1) cond.release() test_utils.run_briefly(self.loop) self.assertEqual([1], result) self.loop.run_until_complete(cond.acquire()) cond.notify(1) cond.notify(2048) cond.release() test_utils.run_briefly(self.loop) self.assertEqual([1, 2, 3], result) self.assertTrue(t1.done()) self.assertTrue(t1.result()) self.assertTrue(t2.done()) self.assertTrue(t2.result()) self.assertTrue(t3.done()) self.assertTrue(t3.result()) def test_notify_all(self): cond = asyncio.Condition(loop=self.loop) result = [] @asyncio.coroutine def c1(result): yield from cond.acquire() if (yield from cond.wait()): result.append(1) cond.release() return True @asyncio.coroutine def c2(result): yield from cond.acquire() if (yield from cond.wait()): result.append(2) cond.release() return True t1 = asyncio.Task(c1(result), loop=self.loop) t2 = asyncio.Task(c2(result), loop=self.loop) test_utils.run_briefly(self.loop) self.assertEqual([], result) self.loop.run_until_complete(cond.acquire()) cond.notify_all() cond.release() test_utils.run_briefly(self.loop) self.assertEqual([1, 2], result) self.assertTrue(t1.done()) self.assertTrue(t1.result()) self.assertTrue(t2.done()) self.assertTrue(t2.result()) def test_notify_unacquired(self): cond = asyncio.Condition(loop=self.loop) self.assertRaises(RuntimeError, cond.notify) def test_notify_all_unacquired(self): cond = asyncio.Condition(loop=self.loop) self.assertRaises(RuntimeError, cond.notify_all) def test_repr(self): cond = asyncio.Condition(loop=self.loop) self.assertTrue('unlocked' in repr(cond)) self.assertTrue(RGX_REPR.match(repr(cond))) self.loop.run_until_complete(cond.acquire()) self.assertTrue('locked' in repr(cond)) cond._waiters.append(mock.Mock()) self.assertTrue('waiters:1' in repr(cond)) self.assertTrue(RGX_REPR.match(repr(cond))) cond._waiters.append(mock.Mock()) self.assertTrue('waiters:2' in repr(cond)) self.assertTrue(RGX_REPR.match(repr(cond))) def test_context_manager(self): cond = asyncio.Condition(loop=self.loop) @asyncio.coroutine def acquire_cond(): return (yield from cond) with self.loop.run_until_complete(acquire_cond()): self.assertTrue(cond.locked()) self.assertFalse(cond.locked()) def test_context_manager_no_yield(self): cond = asyncio.Condition(loop=self.loop) try: with cond: self.fail('RuntimeError is not raised in with expression') except RuntimeError as err: self.assertEqual( str(err), '"yield from" should be used as context manager expression') self.assertFalse(cond.locked()) def test_explicit_lock(self): lock = asyncio.Lock(loop=self.loop) cond = asyncio.Condition(lock, loop=self.loop) self.assertIs(cond._lock, lock) self.assertIs(cond._loop, lock._loop) def test_ambiguous_loops(self): loop = self.new_test_loop() self.addCleanup(loop.close) lock = asyncio.Lock(loop=self.loop) with self.assertRaises(ValueError): asyncio.Condition(lock, loop=loop) class SemaphoreTests(test_utils.TestCase): def setUp(self): super().setUp() self.loop = self.new_test_loop() def test_ctor_loop(self): loop = mock.Mock() sem = asyncio.Semaphore(loop=loop) self.assertIs(sem._loop, loop) sem = asyncio.Semaphore(loop=self.loop) self.assertIs(sem._loop, self.loop) def test_ctor_noloop(self): asyncio.set_event_loop(self.loop) sem = asyncio.Semaphore() self.assertIs(sem._loop, self.loop) def test_initial_value_zero(self): sem = asyncio.Semaphore(0, loop=self.loop) self.assertTrue(sem.locked()) def test_repr(self): sem = asyncio.Semaphore(loop=self.loop) self.assertTrue(repr(sem).endswith('[unlocked,value:1]>')) self.assertTrue(RGX_REPR.match(repr(sem))) self.loop.run_until_complete(sem.acquire()) self.assertTrue(repr(sem).endswith('[locked]>')) self.assertTrue('waiters' not in repr(sem)) self.assertTrue(RGX_REPR.match(repr(sem))) sem._waiters.append(mock.Mock()) self.assertTrue('waiters:1' in repr(sem)) self.assertTrue(RGX_REPR.match(repr(sem))) sem._waiters.append(mock.Mock()) self.assertTrue('waiters:2' in repr(sem)) self.assertTrue(RGX_REPR.match(repr(sem))) def test_semaphore(self): sem = asyncio.Semaphore(loop=self.loop) self.assertEqual(1, sem._value) @asyncio.coroutine def acquire_lock(): return (yield from sem) res = self.loop.run_until_complete(acquire_lock()) self.assertTrue(res) self.assertTrue(sem.locked()) self.assertEqual(0, sem._value) sem.release() self.assertFalse(sem.locked()) self.assertEqual(1, sem._value) def test_semaphore_value(self): self.assertRaises(ValueError, asyncio.Semaphore, -1) def test_acquire(self): sem = asyncio.Semaphore(3, loop=self.loop) result = [] self.assertTrue(self.loop.run_until_complete(sem.acquire())) self.assertTrue(self.loop.run_until_complete(sem.acquire())) self.assertFalse(sem.locked()) @asyncio.coroutine def c1(result): yield from sem.acquire() result.append(1) return True @asyncio.coroutine def c2(result): yield from sem.acquire() result.append(2) return True @asyncio.coroutine def c3(result): yield from sem.acquire() result.append(3) return True @asyncio.coroutine def c4(result): yield from sem.acquire() result.append(4) return True t1 = asyncio.Task(c1(result), loop=self.loop) t2 = asyncio.Task(c2(result), loop=self.loop) t3 = asyncio.Task(c3(result), loop=self.loop) test_utils.run_briefly(self.loop) self.assertEqual([1], result) self.assertTrue(sem.locked()) self.assertEqual(2, len(sem._waiters)) self.assertEqual(0, sem._value) t4 = asyncio.Task(c4(result), loop=self.loop) sem.release() sem.release() self.assertEqual(2, sem._value) test_utils.run_briefly(self.loop) self.assertEqual(0, sem._value) self.assertEqual(3, len(result)) self.assertTrue(sem.locked()) self.assertEqual(1, len(sem._waiters)) self.assertEqual(0, sem._value) self.assertTrue(t1.done()) self.assertTrue(t1.result()) race_tasks = [t2, t3, t4] done_tasks = [t for t in race_tasks if t.done() and t.result()] self.assertTrue(2, len(done_tasks)) # cleanup locked semaphore sem.release() self.loop.run_until_complete(asyncio.gather(*race_tasks)) def test_acquire_cancel(self): sem = asyncio.Semaphore(loop=self.loop) self.loop.run_until_complete(sem.acquire()) acquire = asyncio.Task(sem.acquire(), loop=self.loop) self.loop.call_soon(acquire.cancel) self.assertRaises( asyncio.CancelledError, self.loop.run_until_complete, acquire) self.assertTrue((not sem._waiters) or all(waiter.done() for waiter in sem._waiters)) def test_acquire_cancel_before_awoken(self): sem = asyncio.Semaphore(value=0, loop=self.loop) t1 = asyncio.Task(sem.acquire(), loop=self.loop) t2 = asyncio.Task(sem.acquire(), loop=self.loop) t3 = asyncio.Task(sem.acquire(), loop=self.loop) t4 = asyncio.Task(sem.acquire(), loop=self.loop) test_utils.run_briefly(self.loop) sem.release() t1.cancel() t2.cancel() test_utils.run_briefly(self.loop) num_done = sum(t.done() for t in [t3, t4]) self.assertEqual(num_done, 1) t3.cancel() t4.cancel() test_utils.run_briefly(self.loop) def test_acquire_hang(self): sem = asyncio.Semaphore(value=0, loop=self.loop) t1 = asyncio.Task(sem.acquire(), loop=self.loop) t2 = asyncio.Task(sem.acquire(), loop=self.loop) test_utils.run_briefly(self.loop) sem.release() t1.cancel() test_utils.run_briefly(self.loop) self.assertTrue(sem.locked()) def test_release_not_acquired(self): sem = asyncio.BoundedSemaphore(loop=self.loop) self.assertRaises(ValueError, sem.release) def test_release_no_waiters(self): sem = asyncio.Semaphore(loop=self.loop) self.loop.run_until_complete(sem.acquire()) self.assertTrue(sem.locked()) sem.release() self.assertFalse(sem.locked()) def test_context_manager(self): sem = asyncio.Semaphore(2, loop=self.loop) @asyncio.coroutine def acquire_lock(): return (yield from sem) with self.loop.run_until_complete(acquire_lock()): self.assertFalse(sem.locked()) self.assertEqual(1, sem._value) with self.loop.run_until_complete(acquire_lock()): self.assertTrue(sem.locked()) self.assertEqual(2, sem._value) def test_context_manager_no_yield(self): sem = asyncio.Semaphore(2, loop=self.loop) try: with sem: self.fail('RuntimeError is not raised in with expression') except RuntimeError as err: self.assertEqual( str(err), '"yield from" should be used as context manager expression') self.assertEqual(2, sem._value) if __name__ == '__main__': unittest.main()
30,147
1,017
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_asyncio/test_tasks.py
"""Tests for tasks.py.""" import collections import contextlib import functools import gc import io import os import re import sys import time import types import unittest import weakref from unittest import mock import asyncio from asyncio import coroutines from asyncio import futures from asyncio import tasks from asyncio import test_utils try: from test import support except ImportError: from asyncio import test_support as support try: from test.support.script_helper import assert_python_ok except ImportError: try: from test.script_helper import assert_python_ok except ImportError: from asyncio.test_support import assert_python_ok PY34 = (sys.version_info >= (3, 4)) PY35 = (sys.version_info >= (3, 5)) @asyncio.coroutine def coroutine_function(): pass @contextlib.contextmanager def set_coroutine_debug(enabled): coroutines = asyncio.coroutines old_debug = coroutines._DEBUG try: coroutines._DEBUG = enabled yield finally: coroutines._DEBUG = old_debug def format_coroutine(qualname, state, src, source_traceback, generator=False): if generator: state = '%s' % state else: state = '%s, defined' % state if source_traceback is not None: frame = source_traceback[-1] return ('coro=<%s() %s at %s> created at %s:%s' % (qualname, state, src, frame[0], frame[1])) else: return 'coro=<%s() %s at %s>' % (qualname, state, src) class Dummy: def __repr__(self): return '<Dummy>' def __call__(self, *args): pass class BaseTaskTests: Task = None Future = None def new_task(self, loop, coro): return self.__class__.Task(coro, loop=loop) def new_future(self, loop): return self.__class__.Future(loop=loop) def setUp(self): super().setUp() self.loop = self.new_test_loop() self.loop.set_task_factory(self.new_task) self.loop.create_future = lambda: self.new_future(self.loop) def test_task_del_collect(self): class Evil: def __del__(self): gc.collect() @asyncio.coroutine def run(): return Evil() self.loop.run_until_complete( asyncio.gather(*[ self.new_task(self.loop, run()) for _ in range(100) ], loop=self.loop)) def test_other_loop_future(self): other_loop = asyncio.new_event_loop() fut = self.new_future(other_loop) @asyncio.coroutine def run(fut): yield from fut try: with self.assertRaisesRegex(RuntimeError, r'Task .* got Future .* attached'): self.loop.run_until_complete(run(fut)) finally: other_loop.close() def test_task_awaits_on_itself(self): @asyncio.coroutine def test(): yield from task task = asyncio.ensure_future(test(), loop=self.loop) with self.assertRaisesRegex(RuntimeError, 'Task cannot await on itself'): self.loop.run_until_complete(task) def test_task_class(self): @asyncio.coroutine def notmuch(): return 'ok' t = self.new_task(self.loop, notmuch()) self.loop.run_until_complete(t) self.assertTrue(t.done()) self.assertEqual(t.result(), 'ok') self.assertIs(t._loop, self.loop) loop = asyncio.new_event_loop() self.set_event_loop(loop) t = self.new_task(loop, notmuch()) self.assertIs(t._loop, loop) loop.run_until_complete(t) loop.close() def test_ensure_future_coroutine(self): @asyncio.coroutine def notmuch(): return 'ok' t = asyncio.ensure_future(notmuch(), loop=self.loop) self.loop.run_until_complete(t) self.assertTrue(t.done()) self.assertEqual(t.result(), 'ok') self.assertIs(t._loop, self.loop) loop = asyncio.new_event_loop() self.set_event_loop(loop) t = asyncio.ensure_future(notmuch(), loop=loop) self.assertIs(t._loop, loop) loop.run_until_complete(t) loop.close() def test_ensure_future_future(self): f_orig = self.new_future(self.loop) f_orig.set_result('ko') f = asyncio.ensure_future(f_orig) self.loop.run_until_complete(f) self.assertTrue(f.done()) self.assertEqual(f.result(), 'ko') self.assertIs(f, f_orig) loop = asyncio.new_event_loop() self.set_event_loop(loop) with self.assertRaises(ValueError): f = asyncio.ensure_future(f_orig, loop=loop) loop.close() f = asyncio.ensure_future(f_orig, loop=self.loop) self.assertIs(f, f_orig) def test_ensure_future_task(self): @asyncio.coroutine def notmuch(): return 'ok' t_orig = self.new_task(self.loop, notmuch()) t = asyncio.ensure_future(t_orig) self.loop.run_until_complete(t) self.assertTrue(t.done()) self.assertEqual(t.result(), 'ok') self.assertIs(t, t_orig) loop = asyncio.new_event_loop() self.set_event_loop(loop) with self.assertRaises(ValueError): t = asyncio.ensure_future(t_orig, loop=loop) loop.close() t = asyncio.ensure_future(t_orig, loop=self.loop) self.assertIs(t, t_orig) @unittest.skipUnless(PY35, 'need python 3.5 or later') def test_ensure_future_awaitable(self): class Aw: def __init__(self, coro): self.coro = coro def __await__(self): return (yield from self.coro) @asyncio.coroutine def coro(): return 'ok' loop = asyncio.new_event_loop() self.set_event_loop(loop) fut = asyncio.ensure_future(Aw(coro()), loop=loop) loop.run_until_complete(fut) assert fut.result() == 'ok' def test_ensure_future_neither(self): with self.assertRaises(TypeError): asyncio.ensure_future('ok') def test_async_warning(self): f = self.new_future(self.loop) with self.assertWarnsRegex(DeprecationWarning, 'function is deprecated, use ensure_'): self.assertIs(f, asyncio.async(f)) def test_get_stack(self): T = None @asyncio.coroutine def foo(): yield from bar() @asyncio.coroutine def bar(): # test get_stack() f = T.get_stack(limit=1) try: self.assertEqual(f[0].f_code.co_name, 'foo') finally: f = None # test print_stack() file = io.StringIO() T.print_stack(limit=1, file=file) file.seek(0) tb = file.read() self.assertRegex(tb, r'foo\(\) running') @asyncio.coroutine def runner(): nonlocal T T = asyncio.ensure_future(foo(), loop=self.loop) yield from T self.loop.run_until_complete(runner()) def test_task_repr(self): self.loop.set_debug(False) @asyncio.coroutine def notmuch(): yield from [] return 'abc' # test coroutine function self.assertEqual(notmuch.__name__, 'notmuch') if PY35: self.assertRegex(notmuch.__qualname__, r'\w+.test_task_repr.<locals>.notmuch') self.assertEqual(notmuch.__module__, __name__) filename, lineno = test_utils.get_function_source(notmuch) src = "%s:%s" % (filename, lineno) # test coroutine object gen = notmuch() if coroutines._DEBUG or PY35: coro_qualname = 'BaseTaskTests.test_task_repr.<locals>.notmuch' else: coro_qualname = 'notmuch' self.assertEqual(gen.__name__, 'notmuch') if PY35: self.assertEqual(gen.__qualname__, coro_qualname) # test pending Task t = self.new_task(self.loop, gen) t.add_done_callback(Dummy()) coro = format_coroutine(coro_qualname, 'running', src, t._source_traceback, generator=True) self.assertEqual(repr(t), '<Task pending %s cb=[<Dummy>()]>' % coro) # test cancelling Task t.cancel() # Does not take immediate effect! self.assertEqual(repr(t), '<Task cancelling %s cb=[<Dummy>()]>' % coro) # test cancelled Task self.assertRaises(asyncio.CancelledError, self.loop.run_until_complete, t) coro = format_coroutine(coro_qualname, 'done', src, t._source_traceback) self.assertEqual(repr(t), '<Task cancelled %s>' % coro) # test finished Task t = self.new_task(self.loop, notmuch()) self.loop.run_until_complete(t) coro = format_coroutine(coro_qualname, 'done', src, t._source_traceback) self.assertEqual(repr(t), "<Task finished %s result='abc'>" % coro) def test_task_repr_coro_decorator(self): self.loop.set_debug(False) @asyncio.coroutine def notmuch(): # notmuch() function doesn't use yield from: it will be wrapped by # @coroutine decorator return 123 # test coroutine function self.assertEqual(notmuch.__name__, 'notmuch') if PY35: self.assertRegex(notmuch.__qualname__, r'\w+.test_task_repr_coro_decorator' r'\.<locals>\.notmuch') self.assertEqual(notmuch.__module__, __name__) # test coroutine object gen = notmuch() if coroutines._DEBUG or PY35: # On Python >= 3.5, generators now inherit the name of the # function, as expected, and have a qualified name (__qualname__ # attribute). coro_name = 'notmuch' coro_qualname = ('BaseTaskTests.test_task_repr_coro_decorator' '.<locals>.notmuch') else: # On Python < 3.5, generators inherit the name of the code, not of # the function. See: http://bugs.python.org/issue21205 coro_name = coro_qualname = 'coro' self.assertEqual(gen.__name__, coro_name) if PY35: self.assertEqual(gen.__qualname__, coro_qualname) # test repr(CoroWrapper) if coroutines._DEBUG: # format the coroutine object if coroutines._DEBUG: filename, lineno = test_utils.get_function_source(notmuch) frame = gen._source_traceback[-1] coro = ('%s() running, defined at %s:%s, created at %s:%s' % (coro_qualname, filename, lineno, frame[0], frame[1])) else: code = gen.gi_code coro = ('%s() running at %s:%s' % (coro_qualname, code.co_filename, code.co_firstlineno)) self.assertEqual(repr(gen), '<CoroWrapper %s>' % coro) # test pending Task t = self.new_task(self.loop, gen) t.add_done_callback(Dummy()) # format the coroutine object if coroutines._DEBUG: src = '%s:%s' % test_utils.get_function_source(notmuch) else: code = gen.gi_code src = '%s:%s' % (code.co_filename, code.co_firstlineno) coro = format_coroutine(coro_qualname, 'running', src, t._source_traceback, generator=not coroutines._DEBUG) self.assertEqual(repr(t), '<Task pending %s cb=[<Dummy>()]>' % coro) self.loop.run_until_complete(t) def test_task_repr_wait_for(self): self.loop.set_debug(False) @asyncio.coroutine def wait_for(fut): return (yield from fut) fut = self.new_future(self.loop) task = self.new_task(self.loop, wait_for(fut)) test_utils.run_briefly(self.loop) self.assertRegex(repr(task), '<Task .* wait_for=%s>' % re.escape(repr(fut))) fut.set_result(None) self.loop.run_until_complete(task) def test_task_repr_partial_corowrapper(self): # Issue #222: repr(CoroWrapper) must not fail in debug mode if the # coroutine is a partial function with set_coroutine_debug(True): self.loop.set_debug(True) @asyncio.coroutine def func(x, y): yield from asyncio.sleep(0) partial_func = asyncio.coroutine(functools.partial(func, 1)) task = self.loop.create_task(partial_func(2)) # make warnings quiet task._log_destroy_pending = False self.addCleanup(task._coro.close) coro_repr = repr(task._coro) expected = ( r'<CoroWrapper \w+.test_task_repr_partial_corowrapper' r'\.<locals>\.func\(1\)\(\) running, ' ) self.assertRegex(coro_repr, expected) def test_task_basics(self): @asyncio.coroutine def outer(): a = yield from inner1() b = yield from inner2() return a+b @asyncio.coroutine def inner1(): return 42 @asyncio.coroutine def inner2(): return 1000 t = outer() self.assertEqual(self.loop.run_until_complete(t), 1042) def test_cancel(self): def gen(): when = yield self.assertAlmostEqual(10.0, when) yield 0 loop = self.new_test_loop(gen) @asyncio.coroutine def task(): yield from asyncio.sleep(10.0, loop=loop) return 12 t = self.new_task(loop, task()) loop.call_soon(t.cancel) with self.assertRaises(asyncio.CancelledError): loop.run_until_complete(t) self.assertTrue(t.done()) self.assertTrue(t.cancelled()) self.assertFalse(t.cancel()) def test_cancel_yield(self): @asyncio.coroutine def task(): yield yield return 12 t = self.new_task(self.loop, task()) test_utils.run_briefly(self.loop) # start coro t.cancel() self.assertRaises( asyncio.CancelledError, self.loop.run_until_complete, t) self.assertTrue(t.done()) self.assertTrue(t.cancelled()) self.assertFalse(t.cancel()) def test_cancel_inner_future(self): f = self.new_future(self.loop) @asyncio.coroutine def task(): yield from f return 12 t = self.new_task(self.loop, task()) test_utils.run_briefly(self.loop) # start task f.cancel() with self.assertRaises(asyncio.CancelledError): self.loop.run_until_complete(t) self.assertTrue(f.cancelled()) self.assertTrue(t.cancelled()) def test_cancel_both_task_and_inner_future(self): f = self.new_future(self.loop) @asyncio.coroutine def task(): yield from f return 12 t = self.new_task(self.loop, task()) test_utils.run_briefly(self.loop) f.cancel() t.cancel() with self.assertRaises(asyncio.CancelledError): self.loop.run_until_complete(t) self.assertTrue(t.done()) self.assertTrue(f.cancelled()) self.assertTrue(t.cancelled()) def test_cancel_task_catching(self): fut1 = self.new_future(self.loop) fut2 = self.new_future(self.loop) @asyncio.coroutine def task(): yield from fut1 try: yield from fut2 except asyncio.CancelledError: return 42 t = self.new_task(self.loop, task()) test_utils.run_briefly(self.loop) self.assertIs(t._fut_waiter, fut1) # White-box test. fut1.set_result(None) test_utils.run_briefly(self.loop) self.assertIs(t._fut_waiter, fut2) # White-box test. t.cancel() self.assertTrue(fut2.cancelled()) res = self.loop.run_until_complete(t) self.assertEqual(res, 42) self.assertFalse(t.cancelled()) def test_cancel_task_ignoring(self): fut1 = self.new_future(self.loop) fut2 = self.new_future(self.loop) fut3 = self.new_future(self.loop) @asyncio.coroutine def task(): yield from fut1 try: yield from fut2 except asyncio.CancelledError: pass res = yield from fut3 return res t = self.new_task(self.loop, task()) test_utils.run_briefly(self.loop) self.assertIs(t._fut_waiter, fut1) # White-box test. fut1.set_result(None) test_utils.run_briefly(self.loop) self.assertIs(t._fut_waiter, fut2) # White-box test. t.cancel() self.assertTrue(fut2.cancelled()) test_utils.run_briefly(self.loop) self.assertIs(t._fut_waiter, fut3) # White-box test. fut3.set_result(42) res = self.loop.run_until_complete(t) self.assertEqual(res, 42) self.assertFalse(fut3.cancelled()) self.assertFalse(t.cancelled()) def test_cancel_current_task(self): loop = asyncio.new_event_loop() self.set_event_loop(loop) @asyncio.coroutine def task(): t.cancel() self.assertTrue(t._must_cancel) # White-box test. # The sleep should be cancelled immediately. yield from asyncio.sleep(100, loop=loop) return 12 t = self.new_task(loop, task()) self.assertRaises( asyncio.CancelledError, loop.run_until_complete, t) self.assertTrue(t.done()) self.assertFalse(t._must_cancel) # White-box test. self.assertFalse(t.cancel()) def test_cancel_at_end(self): """coroutine end right after task is cancelled""" loop = asyncio.new_event_loop() self.set_event_loop(loop) @asyncio.coroutine def task(): t.cancel() self.assertTrue(t._must_cancel) # White-box test. return 12 t = self.new_task(loop, task()) self.assertRaises( asyncio.CancelledError, loop.run_until_complete, t) self.assertTrue(t.done()) self.assertFalse(t._must_cancel) # White-box test. self.assertFalse(t.cancel()) def test_cancel_awaited_task(self): # This tests for a relatively rare condition when # a task cancellation is requested for a task which is not # currently blocked, such as a task cancelling itself. # In this situation we must ensure that whatever next future # or task the cancelled task blocks on is cancelled correctly # as well. See also bpo-34872. loop = asyncio.new_event_loop() self.addCleanup(lambda: loop.close()) task = nested_task = None fut = self.new_future(loop) async def nested(): await fut async def coro(): nonlocal nested_task # Create a sub-task and wait for it to run. nested_task = self.new_task(loop, nested()) await asyncio.sleep(0) # Request the current task to be cancelled. task.cancel() # Block on the nested task, which should be immediately # cancelled. await nested_task task = self.new_task(loop, coro()) with self.assertRaises(asyncio.CancelledError): loop.run_until_complete(task) self.assertTrue(task.cancelled()) self.assertTrue(nested_task.cancelled()) self.assertTrue(fut.cancelled()) def test_stop_while_run_in_complete(self): def gen(): when = yield self.assertAlmostEqual(0.1, when) when = yield 0.1 self.assertAlmostEqual(0.2, when) when = yield 0.1 self.assertAlmostEqual(0.3, when) yield 0.1 loop = self.new_test_loop(gen) x = 0 waiters = [] @asyncio.coroutine def task(): nonlocal x while x < 10: waiters.append(asyncio.sleep(0.1, loop=loop)) yield from waiters[-1] x += 1 if x == 2: loop.stop() t = self.new_task(loop, task()) with self.assertRaises(RuntimeError) as cm: loop.run_until_complete(t) self.assertEqual(str(cm.exception), 'Event loop stopped before Future completed.') self.assertFalse(t.done()) self.assertEqual(x, 2) self.assertAlmostEqual(0.3, loop.time()) # close generators for w in waiters: w.close() t.cancel() self.assertRaises(asyncio.CancelledError, loop.run_until_complete, t) def test_wait_for(self): def gen(): when = yield self.assertAlmostEqual(0.2, when) when = yield 0 self.assertAlmostEqual(0.1, when) when = yield 0.1 loop = self.new_test_loop(gen) foo_running = None @asyncio.coroutine def foo(): nonlocal foo_running foo_running = True try: yield from asyncio.sleep(0.2, loop=loop) finally: foo_running = False return 'done' fut = self.new_task(loop, foo()) with self.assertRaises(asyncio.TimeoutError): loop.run_until_complete(asyncio.wait_for(fut, 0.1, loop=loop)) self.assertTrue(fut.done()) # it should have been cancelled due to the timeout self.assertTrue(fut.cancelled()) self.assertAlmostEqual(0.1, loop.time()) self.assertEqual(foo_running, False) def test_wait_for_blocking(self): loop = self.new_test_loop() @asyncio.coroutine def coro(): return 'done' res = loop.run_until_complete(asyncio.wait_for(coro(), timeout=None, loop=loop)) self.assertEqual(res, 'done') def test_wait_for_with_global_loop(self): def gen(): when = yield self.assertAlmostEqual(0.2, when) when = yield 0 self.assertAlmostEqual(0.01, when) yield 0.01 loop = self.new_test_loop(gen) @asyncio.coroutine def foo(): yield from asyncio.sleep(0.2, loop=loop) return 'done' asyncio.set_event_loop(loop) try: fut = self.new_task(loop, foo()) with self.assertRaises(asyncio.TimeoutError): loop.run_until_complete(asyncio.wait_for(fut, 0.01)) finally: asyncio.set_event_loop(None) self.assertAlmostEqual(0.01, loop.time()) self.assertTrue(fut.done()) self.assertTrue(fut.cancelled()) def test_wait_for_race_condition(self): def gen(): yield 0.1 yield 0.1 yield 0.1 loop = self.new_test_loop(gen) fut = self.new_future(loop) task = asyncio.wait_for(fut, timeout=0.2, loop=loop) loop.call_later(0.1, fut.set_result, "ok") res = loop.run_until_complete(task) self.assertEqual(res, "ok") def test_wait(self): def gen(): when = yield self.assertAlmostEqual(0.1, when) when = yield 0 self.assertAlmostEqual(0.15, when) yield 0.15 loop = self.new_test_loop(gen) a = self.new_task(loop, asyncio.sleep(0.1, loop=loop)) b = self.new_task(loop, asyncio.sleep(0.15, loop=loop)) @asyncio.coroutine def foo(): done, pending = yield from asyncio.wait([b, a], loop=loop) self.assertEqual(done, set([a, b])) self.assertEqual(pending, set()) return 42 res = loop.run_until_complete(self.new_task(loop, foo())) self.assertEqual(res, 42) self.assertAlmostEqual(0.15, loop.time()) # Doing it again should take no time and exercise a different path. res = loop.run_until_complete(self.new_task(loop, foo())) self.assertAlmostEqual(0.15, loop.time()) self.assertEqual(res, 42) def test_wait_with_global_loop(self): def gen(): when = yield self.assertAlmostEqual(0.01, when) when = yield 0 self.assertAlmostEqual(0.015, when) yield 0.015 loop = self.new_test_loop(gen) a = self.new_task(loop, asyncio.sleep(0.01, loop=loop)) b = self.new_task(loop, asyncio.sleep(0.015, loop=loop)) @asyncio.coroutine def foo(): done, pending = yield from asyncio.wait([b, a]) self.assertEqual(done, set([a, b])) self.assertEqual(pending, set()) return 42 asyncio.set_event_loop(loop) res = loop.run_until_complete( self.new_task(loop, foo())) self.assertEqual(res, 42) def test_wait_duplicate_coroutines(self): @asyncio.coroutine def coro(s): return s c = coro('test') task =self.new_task( self.loop, asyncio.wait([c, c, coro('spam')], loop=self.loop)) done, pending = self.loop.run_until_complete(task) self.assertFalse(pending) self.assertEqual(set(f.result() for f in done), {'test', 'spam'}) def test_wait_errors(self): self.assertRaises( ValueError, self.loop.run_until_complete, asyncio.wait(set(), loop=self.loop)) # -1 is an invalid return_when value sleep_coro = asyncio.sleep(10.0, loop=self.loop) wait_coro = asyncio.wait([sleep_coro], return_when=-1, loop=self.loop) self.assertRaises(ValueError, self.loop.run_until_complete, wait_coro) sleep_coro.close() def test_wait_first_completed(self): def gen(): when = yield self.assertAlmostEqual(10.0, when) when = yield 0 self.assertAlmostEqual(0.1, when) yield 0.1 loop = self.new_test_loop(gen) a = self.new_task(loop, asyncio.sleep(10.0, loop=loop)) b = self.new_task(loop, asyncio.sleep(0.1, loop=loop)) task = self.new_task( loop, asyncio.wait([b, a], return_when=asyncio.FIRST_COMPLETED, loop=loop)) done, pending = loop.run_until_complete(task) self.assertEqual({b}, done) self.assertEqual({a}, pending) self.assertFalse(a.done()) self.assertTrue(b.done()) self.assertIsNone(b.result()) self.assertAlmostEqual(0.1, loop.time()) # move forward to close generator loop.advance_time(10) loop.run_until_complete(asyncio.wait([a, b], loop=loop)) def test_wait_really_done(self): # there is possibility that some tasks in the pending list # became done but their callbacks haven't all been called yet @asyncio.coroutine def coro1(): yield @asyncio.coroutine def coro2(): yield yield a = self.new_task(self.loop, coro1()) b = self.new_task(self.loop, coro2()) task = self.new_task( self.loop, asyncio.wait([b, a], return_when=asyncio.FIRST_COMPLETED, loop=self.loop)) done, pending = self.loop.run_until_complete(task) self.assertEqual({a, b}, done) self.assertTrue(a.done()) self.assertIsNone(a.result()) self.assertTrue(b.done()) self.assertIsNone(b.result()) def test_wait_first_exception(self): def gen(): when = yield self.assertAlmostEqual(10.0, when) yield 0 loop = self.new_test_loop(gen) # first_exception, task already has exception a = self.new_task(loop, asyncio.sleep(10.0, loop=loop)) @asyncio.coroutine def exc(): raise ZeroDivisionError('err') b = self.new_task(loop, exc()) task = self.new_task( loop, asyncio.wait([b, a], return_when=asyncio.FIRST_EXCEPTION, loop=loop)) done, pending = loop.run_until_complete(task) self.assertEqual({b}, done) self.assertEqual({a}, pending) self.assertAlmostEqual(0, loop.time()) # move forward to close generator loop.advance_time(10) loop.run_until_complete(asyncio.wait([a, b], loop=loop)) def test_wait_first_exception_in_wait(self): def gen(): when = yield self.assertAlmostEqual(10.0, when) when = yield 0 self.assertAlmostEqual(0.01, when) yield 0.01 loop = self.new_test_loop(gen) # first_exception, exception during waiting a = self.new_task(loop, asyncio.sleep(10.0, loop=loop)) @asyncio.coroutine def exc(): yield from asyncio.sleep(0.01, loop=loop) raise ZeroDivisionError('err') b = self.new_task(loop, exc()) task = asyncio.wait([b, a], return_when=asyncio.FIRST_EXCEPTION, loop=loop) done, pending = loop.run_until_complete(task) self.assertEqual({b}, done) self.assertEqual({a}, pending) self.assertAlmostEqual(0.01, loop.time()) # move forward to close generator loop.advance_time(10) loop.run_until_complete(asyncio.wait([a, b], loop=loop)) def test_wait_with_exception(self): def gen(): when = yield self.assertAlmostEqual(0.1, when) when = yield 0 self.assertAlmostEqual(0.15, when) yield 0.15 loop = self.new_test_loop(gen) a = self.new_task(loop, asyncio.sleep(0.1, loop=loop)) @asyncio.coroutine def sleeper(): yield from asyncio.sleep(0.15, loop=loop) raise ZeroDivisionError('really') b = self.new_task(loop, sleeper()) @asyncio.coroutine def foo(): done, pending = yield from asyncio.wait([b, a], loop=loop) self.assertEqual(len(done), 2) self.assertEqual(pending, set()) errors = set(f for f in done if f.exception() is not None) self.assertEqual(len(errors), 1) loop.run_until_complete(self.new_task(loop, foo())) self.assertAlmostEqual(0.15, loop.time()) loop.run_until_complete(self.new_task(loop, foo())) self.assertAlmostEqual(0.15, loop.time()) def test_wait_with_timeout(self): def gen(): when = yield self.assertAlmostEqual(0.1, when) when = yield 0 self.assertAlmostEqual(0.15, when) when = yield 0 self.assertAlmostEqual(0.11, when) yield 0.11 loop = self.new_test_loop(gen) a = self.new_task(loop, asyncio.sleep(0.1, loop=loop)) b = self.new_task(loop, asyncio.sleep(0.15, loop=loop)) @asyncio.coroutine def foo(): done, pending = yield from asyncio.wait([b, a], timeout=0.11, loop=loop) self.assertEqual(done, set([a])) self.assertEqual(pending, set([b])) loop.run_until_complete(self.new_task(loop, foo())) self.assertAlmostEqual(0.11, loop.time()) # move forward to close generator loop.advance_time(10) loop.run_until_complete(asyncio.wait([a, b], loop=loop)) def test_wait_concurrent_complete(self): def gen(): when = yield self.assertAlmostEqual(0.1, when) when = yield 0 self.assertAlmostEqual(0.15, when) when = yield 0 self.assertAlmostEqual(0.1, when) yield 0.1 loop = self.new_test_loop(gen) a = self.new_task(loop, asyncio.sleep(0.1, loop=loop)) b = self.new_task(loop, asyncio.sleep(0.15, loop=loop)) done, pending = loop.run_until_complete( asyncio.wait([b, a], timeout=0.1, loop=loop)) self.assertEqual(done, set([a])) self.assertEqual(pending, set([b])) self.assertAlmostEqual(0.1, loop.time()) # move forward to close generator loop.advance_time(10) loop.run_until_complete(asyncio.wait([a, b], loop=loop)) def test_as_completed(self): def gen(): yield 0 yield 0 yield 0.01 yield 0 loop = self.new_test_loop(gen) # disable "slow callback" warning loop.slow_callback_duration = 1.0 completed = set() time_shifted = False @asyncio.coroutine def sleeper(dt, x): nonlocal time_shifted yield from asyncio.sleep(dt, loop=loop) completed.add(x) if not time_shifted and 'a' in completed and 'b' in completed: time_shifted = True loop.advance_time(0.14) return x a = sleeper(0.01, 'a') b = sleeper(0.01, 'b') c = sleeper(0.15, 'c') @asyncio.coroutine def foo(): values = [] for f in asyncio.as_completed([b, c, a], loop=loop): values.append((yield from f)) return values res = loop.run_until_complete(self.new_task(loop, foo())) self.assertAlmostEqual(0.15, loop.time()) self.assertTrue('a' in res[:2]) self.assertTrue('b' in res[:2]) self.assertEqual(res[2], 'c') # Doing it again should take no time and exercise a different path. res = loop.run_until_complete(self.new_task(loop, foo())) self.assertAlmostEqual(0.15, loop.time()) def test_as_completed_with_timeout(self): def gen(): yield yield 0 yield 0 yield 0.1 loop = self.new_test_loop(gen) a = asyncio.sleep(0.1, 'a', loop=loop) b = asyncio.sleep(0.15, 'b', loop=loop) @asyncio.coroutine def foo(): values = [] for f in asyncio.as_completed([a, b], timeout=0.12, loop=loop): if values: loop.advance_time(0.02) try: v = yield from f values.append((1, v)) except asyncio.TimeoutError as exc: values.append((2, exc)) return values res = loop.run_until_complete(self.new_task(loop, foo())) self.assertEqual(len(res), 2, res) self.assertEqual(res[0], (1, 'a')) self.assertEqual(res[1][0], 2) self.assertIsInstance(res[1][1], asyncio.TimeoutError) self.assertAlmostEqual(0.12, loop.time()) # move forward to close generator loop.advance_time(10) loop.run_until_complete(asyncio.wait([a, b], loop=loop)) def test_as_completed_with_unused_timeout(self): def gen(): yield yield 0 yield 0.01 loop = self.new_test_loop(gen) a = asyncio.sleep(0.01, 'a', loop=loop) @asyncio.coroutine def foo(): for f in asyncio.as_completed([a], timeout=1, loop=loop): v = yield from f self.assertEqual(v, 'a') loop.run_until_complete(self.new_task(loop, foo())) def test_as_completed_reverse_wait(self): def gen(): yield 0 yield 0.05 yield 0 loop = self.new_test_loop(gen) a = asyncio.sleep(0.05, 'a', loop=loop) b = asyncio.sleep(0.10, 'b', loop=loop) fs = {a, b} futs = list(asyncio.as_completed(fs, loop=loop)) self.assertEqual(len(futs), 2) x = loop.run_until_complete(futs[1]) self.assertEqual(x, 'a') self.assertAlmostEqual(0.05, loop.time()) loop.advance_time(0.05) y = loop.run_until_complete(futs[0]) self.assertEqual(y, 'b') self.assertAlmostEqual(0.10, loop.time()) def test_as_completed_concurrent(self): def gen(): when = yield self.assertAlmostEqual(0.05, when) when = yield 0 self.assertAlmostEqual(0.05, when) yield 0.05 loop = self.new_test_loop(gen) a = asyncio.sleep(0.05, 'a', loop=loop) b = asyncio.sleep(0.05, 'b', loop=loop) fs = {a, b} futs = list(asyncio.as_completed(fs, loop=loop)) self.assertEqual(len(futs), 2) waiter = asyncio.wait(futs, loop=loop) done, pending = loop.run_until_complete(waiter) self.assertEqual(set(f.result() for f in done), {'a', 'b'}) def test_as_completed_duplicate_coroutines(self): @asyncio.coroutine def coro(s): return s @asyncio.coroutine def runner(): result = [] c = coro('ham') for f in asyncio.as_completed([c, c, coro('spam')], loop=self.loop): result.append((yield from f)) return result fut = self.new_task(self.loop, runner()) self.loop.run_until_complete(fut) result = fut.result() self.assertEqual(set(result), {'ham', 'spam'}) self.assertEqual(len(result), 2) def test_sleep(self): def gen(): when = yield self.assertAlmostEqual(0.05, when) when = yield 0.05 self.assertAlmostEqual(0.1, when) yield 0.05 loop = self.new_test_loop(gen) @asyncio.coroutine def sleeper(dt, arg): yield from asyncio.sleep(dt/2, loop=loop) res = yield from asyncio.sleep(dt/2, arg, loop=loop) return res t = self.new_task(loop, sleeper(0.1, 'yeah')) loop.run_until_complete(t) self.assertTrue(t.done()) self.assertEqual(t.result(), 'yeah') self.assertAlmostEqual(0.1, loop.time()) def test_sleep_cancel(self): def gen(): when = yield self.assertAlmostEqual(10.0, when) yield 0 loop = self.new_test_loop(gen) t = self.new_task(loop, asyncio.sleep(10.0, 'yeah', loop=loop)) handle = None orig_call_later = loop.call_later def call_later(delay, callback, *args): nonlocal handle handle = orig_call_later(delay, callback, *args) return handle loop.call_later = call_later test_utils.run_briefly(loop) self.assertFalse(handle._cancelled) t.cancel() test_utils.run_briefly(loop) self.assertTrue(handle._cancelled) def test_task_cancel_sleeping_task(self): def gen(): when = yield self.assertAlmostEqual(0.1, when) when = yield 0 self.assertAlmostEqual(5000, when) yield 0.1 loop = self.new_test_loop(gen) @asyncio.coroutine def sleep(dt): yield from asyncio.sleep(dt, loop=loop) @asyncio.coroutine def doit(): sleeper = self.new_task(loop, sleep(5000)) loop.call_later(0.1, sleeper.cancel) try: yield from sleeper except asyncio.CancelledError: return 'cancelled' else: return 'slept in' doer = doit() self.assertEqual(loop.run_until_complete(doer), 'cancelled') self.assertAlmostEqual(0.1, loop.time()) def test_task_cancel_waiter_future(self): fut = self.new_future(self.loop) @asyncio.coroutine def coro(): yield from fut task = self.new_task(self.loop, coro()) test_utils.run_briefly(self.loop) self.assertIs(task._fut_waiter, fut) task.cancel() test_utils.run_briefly(self.loop) self.assertRaises( asyncio.CancelledError, self.loop.run_until_complete, task) self.assertIsNone(task._fut_waiter) self.assertTrue(fut.cancelled()) def test_step_in_completed_task(self): @asyncio.coroutine def notmuch(): return 'ko' gen = notmuch() task = self.new_task(self.loop, gen) task.set_result('ok') self.assertRaises(AssertionError, task._step) gen.close() def test_step_result(self): @asyncio.coroutine def notmuch(): yield None yield 1 return 'ko' self.assertRaises( RuntimeError, self.loop.run_until_complete, notmuch()) def test_step_result_future(self): # If coroutine returns future, task waits on this future. class Fut(asyncio.Future): def __init__(self, *args, **kwds): self.cb_added = False super().__init__(*args, **kwds) def add_done_callback(self, fn): self.cb_added = True super().add_done_callback(fn) fut = Fut(loop=self.loop) result = None @asyncio.coroutine def wait_for_future(): nonlocal result result = yield from fut t = self.new_task(self.loop, wait_for_future()) test_utils.run_briefly(self.loop) self.assertTrue(fut.cb_added) res = object() fut.set_result(res) test_utils.run_briefly(self.loop) self.assertIs(res, result) self.assertTrue(t.done()) self.assertIsNone(t.result()) def test_step_with_baseexception(self): @asyncio.coroutine def notmutch(): raise BaseException() task = self.new_task(self.loop, notmutch()) self.assertRaises(BaseException, task._step) self.assertTrue(task.done()) self.assertIsInstance(task.exception(), BaseException) def test_baseexception_during_cancel(self): def gen(): when = yield self.assertAlmostEqual(10.0, when) yield 0 loop = self.new_test_loop(gen) @asyncio.coroutine def sleeper(): yield from asyncio.sleep(10, loop=loop) base_exc = BaseException() @asyncio.coroutine def notmutch(): try: yield from sleeper() except asyncio.CancelledError: raise base_exc task = self.new_task(loop, notmutch()) test_utils.run_briefly(loop) task.cancel() self.assertFalse(task.done()) self.assertRaises(BaseException, test_utils.run_briefly, loop) self.assertTrue(task.done()) self.assertFalse(task.cancelled()) self.assertIs(task.exception(), base_exc) def test_iscoroutinefunction(self): def fn(): pass self.assertFalse(asyncio.iscoroutinefunction(fn)) def fn1(): yield self.assertFalse(asyncio.iscoroutinefunction(fn1)) @asyncio.coroutine def fn2(): yield self.assertTrue(asyncio.iscoroutinefunction(fn2)) self.assertFalse(asyncio.iscoroutinefunction(mock.Mock())) def test_yield_vs_yield_from(self): fut = self.new_future(self.loop) @asyncio.coroutine def wait_for_future(): yield fut task = wait_for_future() with self.assertRaises(RuntimeError): self.loop.run_until_complete(task) self.assertFalse(fut.done()) def test_yield_vs_yield_from_generator(self): @asyncio.coroutine def coro(): yield @asyncio.coroutine def wait_for_future(): gen = coro() try: yield gen finally: gen.close() task = wait_for_future() self.assertRaises( RuntimeError, self.loop.run_until_complete, task) def test_coroutine_non_gen_function(self): @asyncio.coroutine def func(): return 'test' self.assertTrue(asyncio.iscoroutinefunction(func)) coro = func() self.assertTrue(asyncio.iscoroutine(coro)) res = self.loop.run_until_complete(coro) self.assertEqual(res, 'test') def test_coroutine_non_gen_function_return_future(self): fut = self.new_future(self.loop) @asyncio.coroutine def func(): return fut @asyncio.coroutine def coro(): fut.set_result('test') t1 = self.new_task(self.loop, func()) t2 = self.new_task(self.loop, coro()) res = self.loop.run_until_complete(t1) self.assertEqual(res, 'test') self.assertIsNone(t2.result()) def test_current_task(self): Task = self.__class__.Task self.assertIsNone(Task.current_task(loop=self.loop)) @asyncio.coroutine def coro(loop): self.assertTrue(Task.current_task(loop=loop) is task) # See http://bugs.python.org/issue29271 for details: asyncio.set_event_loop(loop) try: self.assertIs(Task.current_task(None), task) self.assertIs(Task.current_task(), task) finally: asyncio.set_event_loop(None) task = self.new_task(self.loop, coro(self.loop)) self.loop.run_until_complete(task) self.assertIsNone(Task.current_task(loop=self.loop)) def test_current_task_with_interleaving_tasks(self): Task = self.__class__.Task self.assertIsNone(Task.current_task(loop=self.loop)) fut1 = self.new_future(self.loop) fut2 = self.new_future(self.loop) @asyncio.coroutine def coro1(loop): self.assertTrue(Task.current_task(loop=loop) is task1) yield from fut1 self.assertTrue(Task.current_task(loop=loop) is task1) fut2.set_result(True) @asyncio.coroutine def coro2(loop): self.assertTrue(Task.current_task(loop=loop) is task2) fut1.set_result(True) yield from fut2 self.assertTrue(Task.current_task(loop=loop) is task2) task1 = self.new_task(self.loop, coro1(self.loop)) task2 = self.new_task(self.loop, coro2(self.loop)) self.loop.run_until_complete(asyncio.wait((task1, task2), loop=self.loop)) self.assertIsNone(Task.current_task(loop=self.loop)) # Some thorough tests for cancellation propagation through # coroutines, tasks and wait(). def test_yield_future_passes_cancel(self): # Cancelling outer() cancels inner() cancels waiter. proof = 0 waiter = self.new_future(self.loop) @asyncio.coroutine def inner(): nonlocal proof try: yield from waiter except asyncio.CancelledError: proof += 1 raise else: self.fail('got past sleep() in inner()') @asyncio.coroutine def outer(): nonlocal proof try: yield from inner() except asyncio.CancelledError: proof += 100 # Expect this path. else: proof += 10 f = asyncio.ensure_future(outer(), loop=self.loop) test_utils.run_briefly(self.loop) f.cancel() self.loop.run_until_complete(f) self.assertEqual(proof, 101) self.assertTrue(waiter.cancelled()) def test_yield_wait_does_not_shield_cancel(self): # Cancelling outer() makes wait() return early, leaves inner() # running. proof = 0 waiter = self.new_future(self.loop) @asyncio.coroutine def inner(): nonlocal proof yield from waiter proof += 1 @asyncio.coroutine def outer(): nonlocal proof d, p = yield from asyncio.wait([inner()], loop=self.loop) proof += 100 f = asyncio.ensure_future(outer(), loop=self.loop) test_utils.run_briefly(self.loop) f.cancel() self.assertRaises( asyncio.CancelledError, self.loop.run_until_complete, f) waiter.set_result(None) test_utils.run_briefly(self.loop) self.assertEqual(proof, 1) def test_shield_result(self): inner = self.new_future(self.loop) outer = asyncio.shield(inner) inner.set_result(42) res = self.loop.run_until_complete(outer) self.assertEqual(res, 42) def test_shield_exception(self): inner = self.new_future(self.loop) outer = asyncio.shield(inner) test_utils.run_briefly(self.loop) exc = RuntimeError('expected') inner.set_exception(exc) test_utils.run_briefly(self.loop) self.assertIs(outer.exception(), exc) def test_shield_cancel(self): inner = self.new_future(self.loop) outer = asyncio.shield(inner) test_utils.run_briefly(self.loop) inner.cancel() test_utils.run_briefly(self.loop) self.assertTrue(outer.cancelled()) def test_shield_shortcut(self): fut = self.new_future(self.loop) fut.set_result(42) res = self.loop.run_until_complete(asyncio.shield(fut)) self.assertEqual(res, 42) def test_shield_effect(self): # Cancelling outer() does not affect inner(). proof = 0 waiter = self.new_future(self.loop) @asyncio.coroutine def inner(): nonlocal proof yield from waiter proof += 1 @asyncio.coroutine def outer(): nonlocal proof yield from asyncio.shield(inner(), loop=self.loop) proof += 100 f = asyncio.ensure_future(outer(), loop=self.loop) test_utils.run_briefly(self.loop) f.cancel() with self.assertRaises(asyncio.CancelledError): self.loop.run_until_complete(f) waiter.set_result(None) test_utils.run_briefly(self.loop) self.assertEqual(proof, 1) def test_shield_gather(self): child1 = self.new_future(self.loop) child2 = self.new_future(self.loop) parent = asyncio.gather(child1, child2, loop=self.loop) outer = asyncio.shield(parent, loop=self.loop) test_utils.run_briefly(self.loop) outer.cancel() test_utils.run_briefly(self.loop) self.assertTrue(outer.cancelled()) child1.set_result(1) child2.set_result(2) test_utils.run_briefly(self.loop) self.assertEqual(parent.result(), [1, 2]) def test_gather_shield(self): child1 = self.new_future(self.loop) child2 = self.new_future(self.loop) inner1 = asyncio.shield(child1, loop=self.loop) inner2 = asyncio.shield(child2, loop=self.loop) parent = asyncio.gather(inner1, inner2, loop=self.loop) test_utils.run_briefly(self.loop) parent.cancel() # This should cancel inner1 and inner2 but bot child1 and child2. test_utils.run_briefly(self.loop) self.assertIsInstance(parent.exception(), asyncio.CancelledError) self.assertTrue(inner1.cancelled()) self.assertTrue(inner2.cancelled()) child1.set_result(1) child2.set_result(2) test_utils.run_briefly(self.loop) def test_as_completed_invalid_args(self): fut = self.new_future(self.loop) # as_completed() expects a list of futures, not a future instance self.assertRaises(TypeError, self.loop.run_until_complete, asyncio.as_completed(fut, loop=self.loop)) coro = coroutine_function() self.assertRaises(TypeError, self.loop.run_until_complete, asyncio.as_completed(coro, loop=self.loop)) coro.close() def test_wait_invalid_args(self): fut = self.new_future(self.loop) # wait() expects a list of futures, not a future instance self.assertRaises(TypeError, self.loop.run_until_complete, asyncio.wait(fut, loop=self.loop)) coro = coroutine_function() self.assertRaises(TypeError, self.loop.run_until_complete, asyncio.wait(coro, loop=self.loop)) coro.close() # wait() expects at least a future self.assertRaises(ValueError, self.loop.run_until_complete, asyncio.wait([], loop=self.loop)) def test_corowrapper_mocks_generator(self): def check(): # A function that asserts various things. # Called twice, with different debug flag values. @asyncio.coroutine def coro(): # The actual coroutine. self.assertTrue(gen.gi_running) yield from fut # A completed Future used to run the coroutine. fut = self.new_future(self.loop) fut.set_result(None) # Call the coroutine. gen = coro() # Check some properties. self.assertTrue(asyncio.iscoroutine(gen)) self.assertIsInstance(gen.gi_frame, types.FrameType) self.assertFalse(gen.gi_running) self.assertIsInstance(gen.gi_code, types.CodeType) # Run it. self.loop.run_until_complete(gen) # The frame should have changed. self.assertIsNone(gen.gi_frame) # Test with debug flag cleared. with set_coroutine_debug(False): check() # Test with debug flag set. with set_coroutine_debug(True): check() def test_yield_from_corowrapper(self): with set_coroutine_debug(True): @asyncio.coroutine def t1(): return (yield from t2()) @asyncio.coroutine def t2(): f = self.new_future(self.loop) self.new_task(self.loop, t3(f)) return (yield from f) @asyncio.coroutine def t3(f): f.set_result((1, 2, 3)) task = self.new_task(self.loop, t1()) val = self.loop.run_until_complete(task) self.assertEqual(val, (1, 2, 3)) def test_yield_from_corowrapper_send(self): def foo(): a = yield return a def call(arg): cw = asyncio.coroutines.CoroWrapper(foo()) cw.send(None) try: cw.send(arg) except StopIteration as ex: return ex.args[0] else: raise AssertionError('StopIteration was expected') self.assertEqual(call((1, 2)), (1, 2)) self.assertEqual(call('spam'), 'spam') def test_corowrapper_weakref(self): wd = weakref.WeakValueDictionary() def foo(): yield from [] cw = asyncio.coroutines.CoroWrapper(foo()) wd['cw'] = cw # Would fail without __weakref__ slot. cw.gen = None # Suppress warning from __del__. def test_corowrapper_throw(self): # Issue 429: CoroWrapper.throw must be compatible with gen.throw def foo(): value = None while True: try: value = yield value except Exception as e: value = e exception = Exception("foo") cw = asyncio.coroutines.CoroWrapper(foo()) cw.send(None) self.assertIs(exception, cw.throw(exception)) cw = asyncio.coroutines.CoroWrapper(foo()) cw.send(None) self.assertIs(exception, cw.throw(Exception, exception)) cw = asyncio.coroutines.CoroWrapper(foo()) cw.send(None) exception = cw.throw(Exception, "foo") self.assertIsInstance(exception, Exception) self.assertEqual(exception.args, ("foo", )) cw = asyncio.coroutines.CoroWrapper(foo()) cw.send(None) exception = cw.throw(Exception, "foo", None) self.assertIsInstance(exception, Exception) self.assertEqual(exception.args, ("foo", )) @unittest.skipUnless(PY34, 'need python 3.4 or later') def test_log_destroyed_pending_task(self): Task = self.__class__.Task @asyncio.coroutine def kill_me(loop): future = self.new_future(loop) yield from future # at this point, the only reference to kill_me() task is # the Task._wakeup() method in future._callbacks raise Exception("code never reached") mock_handler = mock.Mock() self.loop.set_debug(True) self.loop.set_exception_handler(mock_handler) # schedule the task coro = kill_me(self.loop) task = asyncio.ensure_future(coro, loop=self.loop) self.assertEqual(Task.all_tasks(loop=self.loop), {task}) # See http://bugs.python.org/issue29271 for details: asyncio.set_event_loop(self.loop) try: self.assertEqual(Task.all_tasks(), {task}) self.assertEqual(Task.all_tasks(None), {task}) finally: asyncio.set_event_loop(None) # execute the task so it waits for future self.loop._run_once() self.assertEqual(len(self.loop._ready), 0) # remove the future used in kill_me(), and references to the task del coro.gi_frame.f_locals['future'] coro = None source_traceback = task._source_traceback task = None # no more reference to kill_me() task: the task is destroyed by the GC support.gc_collect() self.assertEqual(Task.all_tasks(loop=self.loop), set()) mock_handler.assert_called_with(self.loop, { 'message': 'Task was destroyed but it is pending!', 'task': mock.ANY, 'source_traceback': source_traceback, }) mock_handler.reset_mock() @mock.patch('asyncio.base_events.logger') def test_tb_logger_not_called_after_cancel(self, m_log): loop = asyncio.new_event_loop() self.set_event_loop(loop) @asyncio.coroutine def coro(): raise TypeError @asyncio.coroutine def runner(): task = self.new_task(loop, coro()) yield from asyncio.sleep(0.05, loop=loop) task.cancel() task = None loop.run_until_complete(runner()) self.assertFalse(m_log.error.called) @mock.patch('asyncio.coroutines.logger') def test_coroutine_never_yielded(self, m_log): with set_coroutine_debug(True): @asyncio.coroutine def coro_noop(): pass tb_filename = __file__ tb_lineno = sys._getframe().f_lineno + 2 # create a coroutine object but don't use it coro_noop() support.gc_collect() self.assertTrue(m_log.error.called) message = m_log.error.call_args[0][0] func_filename, func_lineno = test_utils.get_function_source(coro_noop) regex = (r'^<CoroWrapper %s\(?\)? .* at %s:%s, .*> ' r'was never yielded from\n' r'Coroutine object created at \(most recent call last, truncated to \d+ last lines\):\n' r'.*\n' r' File "%s", line %s, in test_coroutine_never_yielded\n' r' coro_noop\(\)$' % (re.escape(coro_noop.__qualname__), re.escape(func_filename), func_lineno, re.escape(tb_filename), tb_lineno)) self.assertRegex(message, re.compile(regex, re.DOTALL)) def test_return_coroutine_from_coroutine(self): """Return of @asyncio.coroutine()-wrapped function generator object from @asyncio.coroutine()-wrapped function should have same effect as returning generator object or Future.""" def check(): @asyncio.coroutine def outer_coro(): @asyncio.coroutine def inner_coro(): return 1 return inner_coro() result = self.loop.run_until_complete(outer_coro()) self.assertEqual(result, 1) # Test with debug flag cleared. with set_coroutine_debug(False): check() # Test with debug flag set. with set_coroutine_debug(True): check() def test_task_source_traceback(self): self.loop.set_debug(True) task = self.new_task(self.loop, coroutine_function()) lineno = sys._getframe().f_lineno - 1 self.assertIsInstance(task._source_traceback, list) self.assertEqual(task._source_traceback[-2][:3], (__file__, lineno, 'test_task_source_traceback')) self.loop.run_until_complete(task) def _test_cancel_wait_for(self, timeout): loop = asyncio.new_event_loop() self.addCleanup(loop.close) @asyncio.coroutine def blocking_coroutine(): fut = self.new_future(loop) # Block: fut result is never set yield from fut task = loop.create_task(blocking_coroutine()) wait = loop.create_task(asyncio.wait_for(task, timeout, loop=loop)) loop.call_soon(wait.cancel) self.assertRaises(asyncio.CancelledError, loop.run_until_complete, wait) # Python issue #23219: cancelling the wait must also cancel the task self.assertTrue(task.cancelled()) def test_cancel_blocking_wait_for(self): self._test_cancel_wait_for(None) def test_cancel_wait_for(self): self._test_cancel_wait_for(60.0) def test_cancel_gather_1(self): """Ensure that a gathering future refuses to be cancelled once all children are done""" loop = asyncio.new_event_loop() self.addCleanup(loop.close) fut = self.new_future(loop) # The indirection fut->child_coro is needed since otherwise the # gathering task is done at the same time as the child future def child_coro(): return (yield from fut) gather_future = asyncio.gather(child_coro(), loop=loop) gather_task = asyncio.ensure_future(gather_future, loop=loop) cancel_result = None def cancelling_callback(_): nonlocal cancel_result cancel_result = gather_task.cancel() fut.add_done_callback(cancelling_callback) fut.set_result(42) # calls the cancelling_callback after fut is done() # At this point the task should complete. loop.run_until_complete(gather_task) # Python issue #26923: asyncio.gather drops cancellation self.assertEqual(cancel_result, False) self.assertFalse(gather_task.cancelled()) self.assertEqual(gather_task.result(), [42]) def test_cancel_gather_2(self): loop = asyncio.new_event_loop() self.addCleanup(loop.close) async def test(): time = 0 while True: time += 0.05 await asyncio.gather(asyncio.sleep(0.05, loop=loop), return_exceptions=True, loop=loop) if time > 1: return async def main(): qwe = self.new_task(loop, test()) await asyncio.sleep(0.2, loop=loop) qwe.cancel() try: await qwe except asyncio.CancelledError: pass else: self.fail('gather did not propagate the cancellation request') loop.run_until_complete(main()) def test_exception_traceback(self): # See http://bugs.python.org/issue28843 @asyncio.coroutine def foo(): 1 / 0 @asyncio.coroutine def main(): task = self.new_task(self.loop, foo()) yield # skip one loop iteration self.assertIsNotNone(task.exception().__traceback__) self.loop.run_until_complete(main()) @mock.patch('asyncio.base_events.logger') def test_error_in_call_soon(self, m_log): def call_soon(callback, *args): raise ValueError self.loop.call_soon = call_soon @asyncio.coroutine def coro(): pass self.assertFalse(m_log.error.called) with self.assertRaises(ValueError): gen = coro() try: self.new_task(self.loop, gen) finally: gen.close() self.assertTrue(m_log.error.called) message = m_log.error.call_args[0][0] self.assertIn('Task was destroyed but it is pending', message) self.assertEqual(self.Task.all_tasks(self.loop), set()) def add_subclass_tests(cls): BaseTask = cls.Task BaseFuture = cls.Future if BaseTask is None or BaseFuture is None: return cls class CommonFuture: def __init__(self, *args, **kwargs): self.calls = collections.defaultdict(lambda: 0) super().__init__(*args, **kwargs) def _schedule_callbacks(self): self.calls['_schedule_callbacks'] += 1 return super()._schedule_callbacks() def add_done_callback(self, *args): self.calls['add_done_callback'] += 1 return super().add_done_callback(*args) class Task(CommonFuture, BaseTask): def _step(self, *args): self.calls['_step'] += 1 return super()._step(*args) def _wakeup(self, *args): self.calls['_wakeup'] += 1 return super()._wakeup(*args) class Future(CommonFuture, BaseFuture): pass def test_subclasses_ctask_cfuture(self): fut = self.Future(loop=self.loop) async def func(): self.loop.call_soon(lambda: fut.set_result('spam')) return await fut task = self.Task(func(), loop=self.loop) result = self.loop.run_until_complete(task) self.assertEqual(result, 'spam') self.assertEqual( dict(task.calls), {'_step': 2, '_wakeup': 1, 'add_done_callback': 1, '_schedule_callbacks': 1}) self.assertEqual( dict(fut.calls), {'add_done_callback': 1, '_schedule_callbacks': 1}) # Add patched Task & Future back to the test case cls.Task = Task cls.Future = Future # Add an extra unit-test cls.test_subclasses_ctask_cfuture = test_subclasses_ctask_cfuture # Disable the "test_task_source_traceback" test # (the test is hardcoded for a particular call stack, which # is slightly different for Task subclasses) cls.test_task_source_traceback = None return cls @unittest.skipUnless(hasattr(futures, '_CFuture'), 'requires the C _asyncio module') class CTask_CFuture_Tests(BaseTaskTests, test_utils.TestCase): Task = getattr(tasks, '_CTask', None) Future = getattr(futures, '_CFuture', None) @support.refcount_test def test_refleaks_in_task___init__(self): gettotalrefcount = support.get_attribute(sys, 'gettotalrefcount') @asyncio.coroutine def coro(): pass task = self.new_task(self.loop, coro()) self.loop.run_until_complete(task) refs_before = gettotalrefcount() for i in range(100): task.__init__(coro(), loop=self.loop) self.loop.run_until_complete(task) self.assertAlmostEqual(gettotalrefcount() - refs_before, 0, delta=10) @unittest.skipUnless(hasattr(futures, '_CFuture'), 'requires the C _asyncio module') @add_subclass_tests class CTask_CFuture_SubclassTests(BaseTaskTests, test_utils.TestCase): Task = getattr(tasks, '_CTask', None) Future = getattr(futures, '_CFuture', None) @unittest.skipUnless(hasattr(futures, '_CFuture'), 'requires the C _asyncio module') class CTask_PyFuture_Tests(BaseTaskTests, test_utils.TestCase): Task = getattr(tasks, '_CTask', None) Future = futures._PyFuture @unittest.skipUnless(hasattr(futures, '_CFuture'), 'requires the C _asyncio module') class PyTask_CFuture_Tests(BaseTaskTests, test_utils.TestCase): Task = tasks._PyTask Future = getattr(futures, '_CFuture', None) class PyTask_PyFuture_Tests(BaseTaskTests, test_utils.TestCase): Task = tasks._PyTask Future = futures._PyFuture @add_subclass_tests class PyTask_PyFuture_SubclassTests(BaseTaskTests, test_utils.TestCase): Task = tasks._PyTask Future = futures._PyFuture class GenericTaskTests(test_utils.TestCase): def test_future_subclass(self): self.assertTrue(issubclass(asyncio.Task, asyncio.Future)) def test_asyncio_module_compiled(self): # Because of circular imports it's easy to make _asyncio # module non-importable. This is a simple test that will # fail on systems where C modules were successfully compiled # (hence the test for _functools), but _asyncio somehow didn't. try: import _functools except ImportError: pass else: try: import _asyncio except ImportError: self.fail('_asyncio module is missing') class GatherTestsBase: def setUp(self): super().setUp() self.one_loop = self.new_test_loop() self.other_loop = self.new_test_loop() self.set_event_loop(self.one_loop, cleanup=False) def _run_loop(self, loop): while loop._ready: test_utils.run_briefly(loop) def _check_success(self, **kwargs): a, b, c = [asyncio.Future(loop=self.one_loop) for i in range(3)] fut = asyncio.gather(*self.wrap_futures(a, b, c), **kwargs) cb = test_utils.MockCallback() fut.add_done_callback(cb) b.set_result(1) a.set_result(2) self._run_loop(self.one_loop) self.assertEqual(cb.called, False) self.assertFalse(fut.done()) c.set_result(3) self._run_loop(self.one_loop) cb.assert_called_once_with(fut) self.assertEqual(fut.result(), [2, 1, 3]) def test_success(self): self._check_success() self._check_success(return_exceptions=False) def test_result_exception_success(self): self._check_success(return_exceptions=True) def test_one_exception(self): a, b, c, d, e = [asyncio.Future(loop=self.one_loop) for i in range(5)] fut = asyncio.gather(*self.wrap_futures(a, b, c, d, e)) cb = test_utils.MockCallback() fut.add_done_callback(cb) exc = ZeroDivisionError() a.set_result(1) b.set_exception(exc) self._run_loop(self.one_loop) self.assertTrue(fut.done()) cb.assert_called_once_with(fut) self.assertIs(fut.exception(), exc) # Does nothing c.set_result(3) d.cancel() e.set_exception(RuntimeError()) e.exception() def test_return_exceptions(self): a, b, c, d = [asyncio.Future(loop=self.one_loop) for i in range(4)] fut = asyncio.gather(*self.wrap_futures(a, b, c, d), return_exceptions=True) cb = test_utils.MockCallback() fut.add_done_callback(cb) exc = ZeroDivisionError() exc2 = RuntimeError() b.set_result(1) c.set_exception(exc) a.set_result(3) self._run_loop(self.one_loop) self.assertFalse(fut.done()) d.set_exception(exc2) self._run_loop(self.one_loop) self.assertTrue(fut.done()) cb.assert_called_once_with(fut) self.assertEqual(fut.result(), [3, 1, exc, exc2]) def test_env_var_debug(self): aio_path = os.path.dirname(os.path.dirname(asyncio.__file__)) code = '\n'.join(( 'import asyncio.coroutines', 'print(asyncio.coroutines._DEBUG)')) # Test with -E to not fail if the unit test was run with # PYTHONASYNCIODEBUG set to a non-empty string sts, stdout, stderr = assert_python_ok('-E', '-c', code, PYTHONPATH=aio_path) self.assertEqual(stdout.rstrip(), b'False') sts, stdout, stderr = assert_python_ok('-c', code, PYTHONASYNCIODEBUG='', PYTHONPATH=aio_path) self.assertEqual(stdout.rstrip(), b'False') sts, stdout, stderr = assert_python_ok('-c', code, PYTHONASYNCIODEBUG='1', PYTHONPATH=aio_path) self.assertEqual(stdout.rstrip(), b'True') sts, stdout, stderr = assert_python_ok('-E', '-c', code, PYTHONASYNCIODEBUG='1', PYTHONPATH=aio_path) self.assertEqual(stdout.rstrip(), b'False') class FutureGatherTests(GatherTestsBase, test_utils.TestCase): def wrap_futures(self, *futures): return futures def _check_empty_sequence(self, seq_or_iter): asyncio.set_event_loop(self.one_loop) self.addCleanup(asyncio.set_event_loop, None) fut = asyncio.gather(*seq_or_iter) self.assertIsInstance(fut, asyncio.Future) self.assertIs(fut._loop, self.one_loop) self._run_loop(self.one_loop) self.assertTrue(fut.done()) self.assertEqual(fut.result(), []) fut = asyncio.gather(*seq_or_iter, loop=self.other_loop) self.assertIs(fut._loop, self.other_loop) def test_constructor_empty_sequence(self): self._check_empty_sequence([]) self._check_empty_sequence(()) self._check_empty_sequence(set()) self._check_empty_sequence(iter("")) def test_constructor_heterogenous_futures(self): fut1 = asyncio.Future(loop=self.one_loop) fut2 = asyncio.Future(loop=self.other_loop) with self.assertRaises(ValueError): asyncio.gather(fut1, fut2) with self.assertRaises(ValueError): asyncio.gather(fut1, loop=self.other_loop) def test_constructor_homogenous_futures(self): children = [asyncio.Future(loop=self.other_loop) for i in range(3)] fut = asyncio.gather(*children) self.assertIs(fut._loop, self.other_loop) self._run_loop(self.other_loop) self.assertFalse(fut.done()) fut = asyncio.gather(*children, loop=self.other_loop) self.assertIs(fut._loop, self.other_loop) self._run_loop(self.other_loop) self.assertFalse(fut.done()) def test_one_cancellation(self): a, b, c, d, e = [asyncio.Future(loop=self.one_loop) for i in range(5)] fut = asyncio.gather(a, b, c, d, e) cb = test_utils.MockCallback() fut.add_done_callback(cb) a.set_result(1) b.cancel() self._run_loop(self.one_loop) self.assertTrue(fut.done()) cb.assert_called_once_with(fut) self.assertFalse(fut.cancelled()) self.assertIsInstance(fut.exception(), asyncio.CancelledError) # Does nothing c.set_result(3) d.cancel() e.set_exception(RuntimeError()) e.exception() def test_result_exception_one_cancellation(self): a, b, c, d, e, f = [asyncio.Future(loop=self.one_loop) for i in range(6)] fut = asyncio.gather(a, b, c, d, e, f, return_exceptions=True) cb = test_utils.MockCallback() fut.add_done_callback(cb) a.set_result(1) zde = ZeroDivisionError() b.set_exception(zde) c.cancel() self._run_loop(self.one_loop) self.assertFalse(fut.done()) d.set_result(3) e.cancel() rte = RuntimeError() f.set_exception(rte) res = self.one_loop.run_until_complete(fut) self.assertIsInstance(res[2], asyncio.CancelledError) self.assertIsInstance(res[4], asyncio.CancelledError) res[2] = res[4] = None self.assertEqual(res, [1, zde, None, 3, None, rte]) cb.assert_called_once_with(fut) class CoroutineGatherTests(GatherTestsBase, test_utils.TestCase): def setUp(self): super().setUp() asyncio.set_event_loop(self.one_loop) def wrap_futures(self, *futures): coros = [] for fut in futures: @asyncio.coroutine def coro(fut=fut): return (yield from fut) coros.append(coro()) return coros def test_constructor_loop_selection(self): @asyncio.coroutine def coro(): return 'abc' gen1 = coro() gen2 = coro() fut = asyncio.gather(gen1, gen2) self.assertIs(fut._loop, self.one_loop) self.one_loop.run_until_complete(fut) self.set_event_loop(self.other_loop, cleanup=False) gen3 = coro() gen4 = coro() fut2 = asyncio.gather(gen3, gen4, loop=self.other_loop) self.assertIs(fut2._loop, self.other_loop) self.other_loop.run_until_complete(fut2) def test_duplicate_coroutines(self): @asyncio.coroutine def coro(s): return s c = coro('abc') fut = asyncio.gather(c, c, coro('def'), c, loop=self.one_loop) self._run_loop(self.one_loop) self.assertEqual(fut.result(), ['abc', 'abc', 'def', 'abc']) def test_cancellation_broadcast(self): # Cancelling outer() cancels all children. proof = 0 waiter = asyncio.Future(loop=self.one_loop) @asyncio.coroutine def inner(): nonlocal proof yield from waiter proof += 1 child1 = asyncio.ensure_future(inner(), loop=self.one_loop) child2 = asyncio.ensure_future(inner(), loop=self.one_loop) gatherer = None @asyncio.coroutine def outer(): nonlocal proof, gatherer gatherer = asyncio.gather(child1, child2, loop=self.one_loop) yield from gatherer proof += 100 f = asyncio.ensure_future(outer(), loop=self.one_loop) test_utils.run_briefly(self.one_loop) self.assertTrue(f.cancel()) with self.assertRaises(asyncio.CancelledError): self.one_loop.run_until_complete(f) self.assertFalse(gatherer.cancel()) self.assertTrue(waiter.cancelled()) self.assertTrue(child1.cancelled()) self.assertTrue(child2.cancelled()) test_utils.run_briefly(self.one_loop) self.assertEqual(proof, 0) def test_exception_marking(self): # Test for the first line marked "Mark exception retrieved." @asyncio.coroutine def inner(f): yield from f raise RuntimeError('should not be ignored') a = asyncio.Future(loop=self.one_loop) b = asyncio.Future(loop=self.one_loop) @asyncio.coroutine def outer(): yield from asyncio.gather(inner(a), inner(b), loop=self.one_loop) f = asyncio.ensure_future(outer(), loop=self.one_loop) test_utils.run_briefly(self.one_loop) a.set_result(None) test_utils.run_briefly(self.one_loop) b.set_result(None) test_utils.run_briefly(self.one_loop) self.assertIsInstance(f.exception(), RuntimeError) class RunCoroutineThreadsafeTests(test_utils.TestCase): """Test case for asyncio.run_coroutine_threadsafe.""" def setUp(self): super().setUp() self.loop = asyncio.new_event_loop() self.set_event_loop(self.loop) # Will cleanup properly @asyncio.coroutine def add(self, a, b, fail=False, cancel=False): """Wait 0.05 second and return a + b.""" yield from asyncio.sleep(0.05, loop=self.loop) if fail: raise RuntimeError("Fail!") if cancel: asyncio.tasks.Task.current_task(self.loop).cancel() yield return a + b def target(self, fail=False, cancel=False, timeout=None, advance_coro=False): """Run add coroutine in the event loop.""" coro = self.add(1, 2, fail=fail, cancel=cancel) future = asyncio.run_coroutine_threadsafe(coro, self.loop) if advance_coro: # this is for test_run_coroutine_threadsafe_task_factory_exception; # otherwise it spills errors and breaks **other** unittests, since # 'target' is interacting with threads. # With this call, `coro` will be advanced, so that # CoroWrapper.__del__ won't do anything when asyncio tests run # in debug mode. self.loop.call_soon_threadsafe(coro.send, None) try: return future.result(timeout) finally: future.done() or future.cancel() def test_run_coroutine_threadsafe(self): """Test coroutine submission from a thread to an event loop.""" future = self.loop.run_in_executor(None, self.target) result = self.loop.run_until_complete(future) self.assertEqual(result, 3) def test_run_coroutine_threadsafe_with_exception(self): """Test coroutine submission from a thread to an event loop when an exception is raised.""" future = self.loop.run_in_executor(None, self.target, True) with self.assertRaises(RuntimeError) as exc_context: self.loop.run_until_complete(future) self.assertIn("Fail!", exc_context.exception.args) def test_run_coroutine_threadsafe_with_timeout(self): """Test coroutine submission from a thread to an event loop when a timeout is raised.""" callback = lambda: self.target(timeout=0) future = self.loop.run_in_executor(None, callback) with self.assertRaises(asyncio.TimeoutError): self.loop.run_until_complete(future) test_utils.run_briefly(self.loop) # Check that there's no pending task (add has been cancelled) for task in asyncio.Task.all_tasks(self.loop): self.assertTrue(task.done()) def test_run_coroutine_threadsafe_task_cancelled(self): """Test coroutine submission from a tread to an event loop when the task is cancelled.""" callback = lambda: self.target(cancel=True) future = self.loop.run_in_executor(None, callback) with self.assertRaises(asyncio.CancelledError): self.loop.run_until_complete(future) def test_run_coroutine_threadsafe_task_factory_exception(self): """Test coroutine submission from a tread to an event loop when the task factory raise an exception.""" # Schedule the target future = self.loop.run_in_executor( None, lambda: self.target(advance_coro=True)) # Set corrupted task factory self.loop.set_task_factory(lambda loop, coro: wrong_name) # Set exception handler callback = test_utils.MockCallback() self.loop.set_exception_handler(callback) # Run event loop with self.assertRaises(NameError) as exc_context: self.loop.run_until_complete(future) # Check exceptions self.assertIn('wrong_name', exc_context.exception.args[0]) self.assertEqual(len(callback.call_args_list), 1) (loop, context), kwargs = callback.call_args self.assertEqual(context['exception'], exc_context.exception) class SleepTests(test_utils.TestCase): def setUp(self): super().setUp() self.loop = asyncio.new_event_loop() asyncio.set_event_loop(None) def tearDown(self): self.loop.close() self.loop = None super().tearDown() def test_sleep_zero(self): result = 0 def inc_result(num): nonlocal result result += num @asyncio.coroutine def coro(): self.loop.call_soon(inc_result, 1) self.assertEqual(result, 0) num = yield from asyncio.sleep(0, loop=self.loop, result=10) self.assertEqual(result, 1) # inc'ed by call_soon inc_result(num) # num should be 11 self.loop.run_until_complete(coro()) self.assertEqual(result, 11) if __name__ == '__main__': unittest.main()
85,839
2,680
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_asyncio/test_sslproto.py
"""Tests for asyncio/sslproto.py.""" import logging import unittest from unittest import mock try: import ssl except ImportError: ssl = None import asyncio from asyncio import log from asyncio import sslproto from asyncio import test_utils @unittest.skipIf(ssl is None, 'No ssl module') class SslProtoHandshakeTests(test_utils.TestCase): def setUp(self): super().setUp() self.loop = asyncio.new_event_loop() self.set_event_loop(self.loop) def ssl_protocol(self, *, waiter=None, proto=None): sslcontext = test_utils.dummy_ssl_context() if proto is None: # app protocol proto = asyncio.Protocol() ssl_proto = sslproto.SSLProtocol(self.loop, proto, sslcontext, waiter) self.assertIs(ssl_proto._app_transport.get_protocol(), proto) self.addCleanup(ssl_proto._app_transport.close) return ssl_proto def connection_made(self, ssl_proto, *, do_handshake=None): transport = mock.Mock() sslpipe = mock.Mock() sslpipe.shutdown.return_value = b'' if do_handshake: sslpipe.do_handshake.side_effect = do_handshake else: def mock_handshake(callback): return [] sslpipe.do_handshake.side_effect = mock_handshake with mock.patch('asyncio.sslproto._SSLPipe', return_value=sslpipe): ssl_proto.connection_made(transport) return transport def test_cancel_handshake(self): # Python issue #23197: cancelling a handshake must not raise an # exception or log an error, even if the handshake failed waiter = asyncio.Future(loop=self.loop) ssl_proto = self.ssl_protocol(waiter=waiter) handshake_fut = asyncio.Future(loop=self.loop) def do_handshake(callback): exc = Exception() callback(exc) handshake_fut.set_result(None) return [] waiter.cancel() with test_utils.disable_logger(): self.connection_made(ssl_proto, do_handshake=do_handshake) self.loop.run_until_complete(handshake_fut) def test_eof_received_waiter(self): waiter = asyncio.Future(loop=self.loop) ssl_proto = self.ssl_protocol(waiter=waiter) self.connection_made(ssl_proto) ssl_proto.eof_received() test_utils.run_briefly(self.loop) self.assertIsInstance(waiter.exception(), ConnectionResetError) def test_fatal_error_no_name_error(self): # From issue #363. # _fatal_error() generates a NameError if sslproto.py # does not import base_events. waiter = asyncio.Future(loop=self.loop) ssl_proto = self.ssl_protocol(waiter=waiter) # Temporarily turn off error logging so as not to spoil test output. log_level = log.logger.getEffectiveLevel() log.logger.setLevel(logging.FATAL) try: ssl_proto._fatal_error(None) finally: # Restore error logging. log.logger.setLevel(log_level) def test_connection_lost(self): # From issue #472. # yield from waiter hang if lost_connection was called. waiter = asyncio.Future(loop=self.loop) ssl_proto = self.ssl_protocol(waiter=waiter) self.connection_made(ssl_proto) ssl_proto.connection_lost(ConnectionAbortedError) test_utils.run_briefly(self.loop) self.assertIsInstance(waiter.exception(), ConnectionAbortedError) def test_close_during_handshake(self): # bpo-29743 Closing transport during handshake process leaks socket waiter = asyncio.Future(loop=self.loop) ssl_proto = self.ssl_protocol(waiter=waiter) transport = self.connection_made(ssl_proto) test_utils.run_briefly(self.loop) ssl_proto._app_transport.close() self.assertTrue(transport.abort.called) def test_get_extra_info_on_closed_connection(self): waiter = asyncio.Future(loop=self.loop) ssl_proto = self.ssl_protocol(waiter=waiter) self.assertIsNone(ssl_proto._get_extra_info('socket')) default = object() self.assertIs(ssl_proto._get_extra_info('socket', default), default) self.connection_made(ssl_proto) self.assertIsNotNone(ssl_proto._get_extra_info('socket')) ssl_proto.connection_lost(None) self.assertIsNone(ssl_proto._get_extra_info('socket')) def test_set_new_app_protocol(self): waiter = asyncio.Future(loop=self.loop) ssl_proto = self.ssl_protocol(waiter=waiter) new_app_proto = asyncio.Protocol() ssl_proto._app_transport.set_protocol(new_app_proto) self.assertIs(ssl_proto._app_transport.get_protocol(), new_app_proto) self.assertIs(ssl_proto._app_protocol, new_app_proto) def test_data_received_after_closing(self): ssl_proto = self.ssl_protocol() self.connection_made(ssl_proto) transp = ssl_proto._app_transport transp.close() # should not raise self.assertIsNone(ssl_proto.data_received(b'data')) def test_write_after_closing(self): ssl_proto = self.ssl_protocol() self.connection_made(ssl_proto) transp = ssl_proto._app_transport transp.close() # should not raise self.assertIsNone(transp.write(b'data')) if __name__ == '__main__': unittest.main()
5,427
152
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_asyncio/test_events.py
"""Tests for events.py.""" import collections.abc import concurrent.futures import functools import gc import io import os import platform import re import signal import socket try: import ssl except ImportError: ssl = None import subprocess import sys import threading import time import errno import unittest from unittest import mock import weakref if sys.platform != 'win32': import tty import asyncio from asyncio import coroutines from asyncio import proactor_events from asyncio import selector_events from asyncio import sslproto from asyncio import test_utils from asyncio.test_utils import ONLYKEY, ONLYCERT, data_file try: from test import support except ImportError: from asyncio import test_support as support def osx_tiger(): """Return True if the platform is Mac OS 10.4 or older.""" if sys.platform != 'darwin': return False version = platform.mac_ver()[0] version = tuple(map(int, version.split('.'))) return version < (10, 5) def _test_get_event_loop_new_process__sub_proc(): async def doit(): return 'hello' loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) return loop.run_until_complete(doit()) SIGNED_CERTFILE = test_utils.data_file('keycert3.pem') SIGNING_CA = test_utils.data_file('pycacert.pem') PEERCERT = { 'OCSP': ('http://testca.pythontest.net/testca/ocsp/',), 'caIssuers': ('http://testca.pythontest.net/testca/pycacert.cer',), 'crlDistributionPoints': ('http://testca.pythontest.net/testca/revocation.crl',), 'issuer': ((('countryName', 'XY'),), (('organizationName', 'Python Software Foundation CA'),), (('commonName', 'our-ca-server'),)), 'notAfter': 'Jul 7 14:23:16 2028 GMT', 'notBefore': 'Aug 29 14:23:16 2018 GMT', 'serialNumber': 'CB2D80995A69525C', 'subject': ((('countryName', 'XY'),), (('localityName', 'Castle Anthrax'),), (('organizationName', 'Python Software Foundation'),), (('commonName', 'localhost'),)), 'subjectAltName': (('DNS', 'localhost'),), 'version': 3 } class MyBaseProto(asyncio.Protocol): connected = None done = None def __init__(self, loop=None): self.transport = None self.state = 'INITIAL' self.nbytes = 0 if loop is not None: self.connected = asyncio.Future(loop=loop) self.done = asyncio.Future(loop=loop) def connection_made(self, transport): self.transport = transport assert self.state == 'INITIAL', self.state self.state = 'CONNECTED' if self.connected: self.connected.set_result(None) def data_received(self, data): assert self.state == 'CONNECTED', self.state self.nbytes += len(data) def eof_received(self): assert self.state == 'CONNECTED', self.state self.state = 'EOF' def connection_lost(self, exc): assert self.state in ('CONNECTED', 'EOF'), self.state self.state = 'CLOSED' if self.done: self.done.set_result(None) class MyProto(MyBaseProto): def connection_made(self, transport): super().connection_made(transport) transport.write(b'GET / HTTP/1.0\r\nHost: example.com\r\n\r\n') class MyDatagramProto(asyncio.DatagramProtocol): done = None def __init__(self, loop=None): self.state = 'INITIAL' self.nbytes = 0 if loop is not None: self.done = asyncio.Future(loop=loop) def connection_made(self, transport): self.transport = transport assert self.state == 'INITIAL', self.state self.state = 'INITIALIZED' def datagram_received(self, data, addr): assert self.state == 'INITIALIZED', self.state self.nbytes += len(data) def error_received(self, exc): assert self.state == 'INITIALIZED', self.state def connection_lost(self, exc): assert self.state == 'INITIALIZED', self.state self.state = 'CLOSED' if self.done: self.done.set_result(None) class MyReadPipeProto(asyncio.Protocol): done = None def __init__(self, loop=None): self.state = ['INITIAL'] self.nbytes = 0 self.transport = None if loop is not None: self.done = asyncio.Future(loop=loop) def connection_made(self, transport): self.transport = transport assert self.state == ['INITIAL'], self.state self.state.append('CONNECTED') def data_received(self, data): assert self.state == ['INITIAL', 'CONNECTED'], self.state self.nbytes += len(data) def eof_received(self): assert self.state == ['INITIAL', 'CONNECTED'], self.state self.state.append('EOF') def connection_lost(self, exc): if 'EOF' not in self.state: self.state.append('EOF') # It is okay if EOF is missed. assert self.state == ['INITIAL', 'CONNECTED', 'EOF'], self.state self.state.append('CLOSED') if self.done: self.done.set_result(None) class MyWritePipeProto(asyncio.BaseProtocol): done = None def __init__(self, loop=None): self.state = 'INITIAL' self.transport = None if loop is not None: self.done = asyncio.Future(loop=loop) def connection_made(self, transport): self.transport = transport assert self.state == 'INITIAL', self.state self.state = 'CONNECTED' def connection_lost(self, exc): assert self.state == 'CONNECTED', self.state self.state = 'CLOSED' if self.done: self.done.set_result(None) class MySubprocessProtocol(asyncio.SubprocessProtocol): def __init__(self, loop): self.state = 'INITIAL' self.transport = None self.connected = asyncio.Future(loop=loop) self.completed = asyncio.Future(loop=loop) self.disconnects = {fd: asyncio.Future(loop=loop) for fd in range(3)} self.data = {1: b'', 2: b''} self.returncode = None self.got_data = {1: asyncio.Event(loop=loop), 2: asyncio.Event(loop=loop)} def connection_made(self, transport): self.transport = transport assert self.state == 'INITIAL', self.state self.state = 'CONNECTED' self.connected.set_result(None) def connection_lost(self, exc): assert self.state == 'CONNECTED', self.state self.state = 'CLOSED' self.completed.set_result(None) def pipe_data_received(self, fd, data): assert self.state == 'CONNECTED', self.state self.data[fd] += data self.got_data[fd].set() def pipe_connection_lost(self, fd, exc): assert self.state == 'CONNECTED', self.state if exc: self.disconnects[fd].set_exception(exc) else: self.disconnects[fd].set_result(exc) def process_exited(self): assert self.state == 'CONNECTED', self.state self.returncode = self.transport.get_returncode() class EventLoopTestsMixin: def setUp(self): super().setUp() self.loop = self.create_event_loop() self.set_event_loop(self.loop) def tearDown(self): # just in case if we have transport close callbacks if not self.loop.is_closed(): test_utils.run_briefly(self.loop) self.doCleanups() support.gc_collect() super().tearDown() def test_run_until_complete_nesting(self): @asyncio.coroutine def coro1(): yield @asyncio.coroutine def coro2(): self.assertTrue(self.loop.is_running()) self.loop.run_until_complete(coro1()) self.assertRaises( RuntimeError, self.loop.run_until_complete, coro2()) # Note: because of the default Windows timing granularity of # 15.6 msec, we use fairly long sleep times here (~100 msec). def test_run_until_complete(self): t0 = self.loop.time() self.loop.run_until_complete(asyncio.sleep(0.1, loop=self.loop)) t1 = self.loop.time() self.assertTrue(0.08 <= t1-t0 <= 0.8, t1-t0) def test_run_until_complete_stopped(self): @asyncio.coroutine def cb(): self.loop.stop() yield from asyncio.sleep(0.1, loop=self.loop) task = cb() self.assertRaises(RuntimeError, self.loop.run_until_complete, task) def test_call_later(self): results = [] def callback(arg): results.append(arg) self.loop.stop() self.loop.call_later(0.1, callback, 'hello world') t0 = time.monotonic() self.loop.run_forever() t1 = time.monotonic() self.assertEqual(results, ['hello world']) self.assertTrue(0.08 <= t1-t0 <= 0.8, t1-t0) def test_call_soon(self): results = [] def callback(arg1, arg2): results.append((arg1, arg2)) self.loop.stop() self.loop.call_soon(callback, 'hello', 'world') self.loop.run_forever() self.assertEqual(results, [('hello', 'world')]) def test_call_soon_threadsafe(self): results = [] lock = threading.Lock() def callback(arg): results.append(arg) if len(results) >= 2: self.loop.stop() def run_in_thread(): self.loop.call_soon_threadsafe(callback, 'hello') lock.release() lock.acquire() t = threading.Thread(target=run_in_thread) t.start() with lock: self.loop.call_soon(callback, 'world') self.loop.run_forever() t.join() self.assertEqual(results, ['hello', 'world']) def test_call_soon_threadsafe_same_thread(self): results = [] def callback(arg): results.append(arg) if len(results) >= 2: self.loop.stop() self.loop.call_soon_threadsafe(callback, 'hello') self.loop.call_soon(callback, 'world') self.loop.run_forever() self.assertEqual(results, ['hello', 'world']) def test_run_in_executor(self): def run(arg): return (arg, threading.get_ident()) f2 = self.loop.run_in_executor(None, run, 'yo') res, thread_id = self.loop.run_until_complete(f2) self.assertEqual(res, 'yo') self.assertNotEqual(thread_id, threading.get_ident()) def test_run_in_executor_cancel(self): called = False def patched_call_soon(*args): nonlocal called called = True def run(): time.sleep(0.05) f2 = self.loop.run_in_executor(None, run) f2.cancel() self.loop.close() self.loop.call_soon = patched_call_soon self.loop.call_soon_threadsafe = patched_call_soon time.sleep(0.4) self.assertFalse(called) def test_reader_callback(self): r, w = test_utils.socketpair() r.setblocking(False) bytes_read = bytearray() def reader(): try: data = r.recv(1024) except BlockingIOError: # Spurious readiness notifications are possible # at least on Linux -- see man select. return if data: bytes_read.extend(data) else: self.assertTrue(self.loop.remove_reader(r.fileno())) r.close() self.loop.add_reader(r.fileno(), reader) self.loop.call_soon(w.send, b'abc') test_utils.run_until(self.loop, lambda: len(bytes_read) >= 3) self.loop.call_soon(w.send, b'def') test_utils.run_until(self.loop, lambda: len(bytes_read) >= 6) self.loop.call_soon(w.close) self.loop.call_soon(self.loop.stop) self.loop.run_forever() self.assertEqual(bytes_read, b'abcdef') def test_writer_callback(self): r, w = test_utils.socketpair() w.setblocking(False) def writer(data): w.send(data) self.loop.stop() data = b'x' * 1024 self.loop.add_writer(w.fileno(), writer, data) self.loop.run_forever() self.assertTrue(self.loop.remove_writer(w.fileno())) self.assertFalse(self.loop.remove_writer(w.fileno())) w.close() read = r.recv(len(data) * 2) r.close() self.assertEqual(read, data) def _basetest_sock_client_ops(self, httpd, sock): if not isinstance(self.loop, proactor_events.BaseProactorEventLoop): # in debug mode, socket operations must fail # if the socket is not in blocking mode self.loop.set_debug(True) sock.setblocking(True) with self.assertRaises(ValueError): self.loop.run_until_complete( self.loop.sock_connect(sock, httpd.address)) with self.assertRaises(ValueError): self.loop.run_until_complete( self.loop.sock_sendall(sock, b'GET / HTTP/1.0\r\n\r\n')) with self.assertRaises(ValueError): self.loop.run_until_complete( self.loop.sock_recv(sock, 1024)) with self.assertRaises(ValueError): self.loop.run_until_complete( self.loop.sock_accept(sock)) # test in non-blocking mode sock.setblocking(False) self.loop.run_until_complete( self.loop.sock_connect(sock, httpd.address)) self.loop.run_until_complete( self.loop.sock_sendall(sock, b'GET / HTTP/1.0\r\n\r\n')) data = self.loop.run_until_complete( self.loop.sock_recv(sock, 1024)) # consume data self.loop.run_until_complete( self.loop.sock_recv(sock, 1024)) sock.close() self.assertTrue(data.startswith(b'HTTP/1.0 200 OK')) def test_sock_client_ops(self): with test_utils.run_test_server() as httpd: sock = socket.socket() self._basetest_sock_client_ops(httpd, sock) @unittest.skipUnless(hasattr(socket, 'AF_UNIX'), 'No UNIX Sockets') def test_unix_sock_client_ops(self): with test_utils.run_test_unix_server() as httpd: sock = socket.socket(socket.AF_UNIX) self._basetest_sock_client_ops(httpd, sock) def test_sock_client_fail(self): # Make sure that we will get an unused port address = None try: s = socket.socket() s.bind(('127.0.0.1', 0)) address = s.getsockname() finally: s.close() sock = socket.socket() sock.setblocking(False) with self.assertRaises(ConnectionRefusedError): self.loop.run_until_complete( self.loop.sock_connect(sock, address)) sock.close() def test_sock_accept(self): listener = socket.socket() listener.setblocking(False) listener.bind(('127.0.0.1', 0)) listener.listen(1) client = socket.socket() client.connect(listener.getsockname()) f = self.loop.sock_accept(listener) conn, addr = self.loop.run_until_complete(f) self.assertEqual(conn.gettimeout(), 0) self.assertEqual(addr, client.getsockname()) self.assertEqual(client.getpeername(), listener.getsockname()) client.close() conn.close() listener.close() @unittest.skipUnless(hasattr(signal, 'SIGKILL'), 'No SIGKILL') def test_add_signal_handler(self): caught = 0 def my_handler(): nonlocal caught caught += 1 # Check error behavior first. self.assertRaises( TypeError, self.loop.add_signal_handler, 'boom', my_handler) self.assertRaises( TypeError, self.loop.remove_signal_handler, 'boom') self.assertRaises( ValueError, self.loop.add_signal_handler, signal.NSIG+1, my_handler) self.assertRaises( ValueError, self.loop.remove_signal_handler, signal.NSIG+1) self.assertRaises( ValueError, self.loop.add_signal_handler, 0, my_handler) self.assertRaises( ValueError, self.loop.remove_signal_handler, 0) self.assertRaises( ValueError, self.loop.add_signal_handler, -1, my_handler) self.assertRaises( ValueError, self.loop.remove_signal_handler, -1) self.assertRaises( RuntimeError, self.loop.add_signal_handler, signal.SIGKILL, my_handler) # Removing SIGKILL doesn't raise, since we don't call signal(). self.assertFalse(self.loop.remove_signal_handler(signal.SIGKILL)) # Now set a handler and handle it. self.loop.add_signal_handler(signal.SIGINT, my_handler) os.kill(os.getpid(), signal.SIGINT) test_utils.run_until(self.loop, lambda: caught) # Removing it should restore the default handler. self.assertTrue(self.loop.remove_signal_handler(signal.SIGINT)) self.assertEqual(signal.getsignal(signal.SIGINT), signal.default_int_handler) # Removing again returns False. self.assertFalse(self.loop.remove_signal_handler(signal.SIGINT)) @unittest.skipUnless(hasattr(signal, 'SIGALRM'), 'No SIGALRM') def test_signal_handling_while_selecting(self): # Test with a signal actually arriving during a select() call. caught = 0 def my_handler(): nonlocal caught caught += 1 self.loop.stop() self.loop.add_signal_handler(signal.SIGALRM, my_handler) signal.setitimer(signal.ITIMER_REAL, 0.01, 0) # Send SIGALRM once. self.loop.call_later(60, self.loop.stop) self.loop.run_forever() self.assertEqual(caught, 1) @unittest.skipUnless(hasattr(signal, 'SIGALRM'), 'No SIGALRM') def test_signal_handling_args(self): some_args = (42,) caught = 0 def my_handler(*args): nonlocal caught caught += 1 self.assertEqual(args, some_args) self.loop.stop() self.loop.add_signal_handler(signal.SIGALRM, my_handler, *some_args) signal.setitimer(signal.ITIMER_REAL, 0.1, 0) # Send SIGALRM once. self.loop.call_later(60, self.loop.stop) self.loop.run_forever() self.assertEqual(caught, 1) def _basetest_create_connection(self, connection_fut, check_sockname=True): tr, pr = self.loop.run_until_complete(connection_fut) self.assertIsInstance(tr, asyncio.Transport) self.assertIsInstance(pr, asyncio.Protocol) self.assertIs(pr.transport, tr) if check_sockname: self.assertIsNotNone(tr.get_extra_info('sockname')) self.loop.run_until_complete(pr.done) self.assertGreater(pr.nbytes, 0) tr.close() def test_create_connection(self): with test_utils.run_test_server() as httpd: conn_fut = self.loop.create_connection( lambda: MyProto(loop=self.loop), *httpd.address) self._basetest_create_connection(conn_fut) @unittest.skipUnless(hasattr(socket, 'AF_UNIX'), 'No UNIX Sockets') def test_create_unix_connection(self): # Issue #20682: On Mac OS X Tiger, getsockname() returns a # zero-length address for UNIX socket. check_sockname = not osx_tiger() with test_utils.run_test_unix_server() as httpd: conn_fut = self.loop.create_unix_connection( lambda: MyProto(loop=self.loop), httpd.address) self._basetest_create_connection(conn_fut, check_sockname) def test_create_connection_sock(self): with test_utils.run_test_server() as httpd: sock = None infos = self.loop.run_until_complete( self.loop.getaddrinfo( *httpd.address, type=socket.SOCK_STREAM)) for family, type, proto, cname, address in infos: try: sock = socket.socket(family=family, type=type, proto=proto) sock.setblocking(False) self.loop.run_until_complete( self.loop.sock_connect(sock, address)) except: pass else: break else: assert False, 'Can not create socket.' f = self.loop.create_connection( lambda: MyProto(loop=self.loop), sock=sock) tr, pr = self.loop.run_until_complete(f) self.assertIsInstance(tr, asyncio.Transport) self.assertIsInstance(pr, asyncio.Protocol) self.loop.run_until_complete(pr.done) self.assertGreater(pr.nbytes, 0) tr.close() def check_ssl_extra_info(self, client, check_sockname=True, peername=None, peercert={}): if check_sockname: self.assertIsNotNone(client.get_extra_info('sockname')) if peername: self.assertEqual(peername, client.get_extra_info('peername')) else: self.assertIsNotNone(client.get_extra_info('peername')) self.assertEqual(peercert, client.get_extra_info('peercert')) # test SSL cipher cipher = client.get_extra_info('cipher') self.assertIsInstance(cipher, tuple) self.assertEqual(len(cipher), 3, cipher) self.assertIsInstance(cipher[0], str) self.assertIsInstance(cipher[1], str) self.assertIsInstance(cipher[2], int) # test SSL object sslobj = client.get_extra_info('ssl_object') self.assertIsNotNone(sslobj) self.assertEqual(sslobj.compression(), client.get_extra_info('compression')) self.assertEqual(sslobj.cipher(), client.get_extra_info('cipher')) self.assertEqual(sslobj.getpeercert(), client.get_extra_info('peercert')) self.assertEqual(sslobj.compression(), client.get_extra_info('compression')) def _basetest_create_ssl_connection(self, connection_fut, check_sockname=True, peername=None): tr, pr = self.loop.run_until_complete(connection_fut) self.assertIsInstance(tr, asyncio.Transport) self.assertIsInstance(pr, asyncio.Protocol) self.assertTrue('ssl' in tr.__class__.__name__.lower()) self.check_ssl_extra_info(tr, check_sockname, peername) self.loop.run_until_complete(pr.done) self.assertGreater(pr.nbytes, 0) tr.close() def _test_create_ssl_connection(self, httpd, create_connection, check_sockname=True, peername=None): conn_fut = create_connection(ssl=test_utils.dummy_ssl_context()) self._basetest_create_ssl_connection(conn_fut, check_sockname, peername) # ssl.Purpose was introduced in Python 3.4 if hasattr(ssl, 'Purpose'): def _dummy_ssl_create_context(purpose=ssl.Purpose.SERVER_AUTH, *, cafile=None, capath=None, cadata=None): """ A ssl.create_default_context() replacement that doesn't enable cert validation. """ self.assertEqual(purpose, ssl.Purpose.SERVER_AUTH) return test_utils.dummy_ssl_context() # With ssl=True, ssl.create_default_context() should be called with mock.patch('ssl.create_default_context', side_effect=_dummy_ssl_create_context) as m: conn_fut = create_connection(ssl=True) self._basetest_create_ssl_connection(conn_fut, check_sockname, peername) self.assertEqual(m.call_count, 1) # With the real ssl.create_default_context(), certificate # validation will fail with self.assertRaises(ssl.SSLError) as cm: conn_fut = create_connection(ssl=True) # Ignore the "SSL handshake failed" log in debug mode with test_utils.disable_logger(): self._basetest_create_ssl_connection(conn_fut, check_sockname, peername) self.assertEqual(cm.exception.reason, 'CERTIFICATE_VERIFY_FAILED') @unittest.skipIf(ssl is None, 'No ssl module') def test_create_ssl_connection(self): with test_utils.run_test_server(use_ssl=True) as httpd: create_connection = functools.partial( self.loop.create_connection, lambda: MyProto(loop=self.loop), *httpd.address) self._test_create_ssl_connection(httpd, create_connection, peername=httpd.address) def test_legacy_create_ssl_connection(self): with test_utils.force_legacy_ssl_support(): self.test_create_ssl_connection() @unittest.skipIf(ssl is None, 'No ssl module') @unittest.skipUnless(hasattr(socket, 'AF_UNIX'), 'No UNIX Sockets') def test_create_ssl_unix_connection(self): # Issue #20682: On Mac OS X Tiger, getsockname() returns a # zero-length address for UNIX socket. check_sockname = not osx_tiger() with test_utils.run_test_unix_server(use_ssl=True) as httpd: create_connection = functools.partial( self.loop.create_unix_connection, lambda: MyProto(loop=self.loop), httpd.address, server_hostname='127.0.0.1') self._test_create_ssl_connection(httpd, create_connection, check_sockname, peername=httpd.address) def test_legacy_create_ssl_unix_connection(self): with test_utils.force_legacy_ssl_support(): self.test_create_ssl_unix_connection() def test_create_connection_local_addr(self): with test_utils.run_test_server() as httpd: port = support.find_unused_port() f = self.loop.create_connection( lambda: MyProto(loop=self.loop), *httpd.address, local_addr=(httpd.address[0], port)) tr, pr = self.loop.run_until_complete(f) expected = pr.transport.get_extra_info('sockname')[1] self.assertEqual(port, expected) tr.close() def test_create_connection_local_addr_in_use(self): with test_utils.run_test_server() as httpd: f = self.loop.create_connection( lambda: MyProto(loop=self.loop), *httpd.address, local_addr=httpd.address) with self.assertRaises(OSError) as cm: self.loop.run_until_complete(f) self.assertEqual(cm.exception.errno, errno.EADDRINUSE) self.assertIn(str(httpd.address), cm.exception.strerror) def test_connect_accepted_socket(self, server_ssl=None, client_ssl=None): loop = self.loop class MyProto(MyBaseProto): def connection_lost(self, exc): super().connection_lost(exc) loop.call_soon(loop.stop) def data_received(self, data): super().data_received(data) self.transport.write(expected_response) lsock = socket.socket() lsock.bind(('127.0.0.1', 0)) lsock.listen(1) addr = lsock.getsockname() message = b'test data' response = None expected_response = b'roger' def client(): nonlocal response try: csock = socket.socket() if client_ssl is not None: csock = client_ssl.wrap_socket(csock) csock.connect(addr) csock.sendall(message) response = csock.recv(99) csock.close() except Exception as exc: print( "Failure in client thread in test_connect_accepted_socket", exc) thread = threading.Thread(target=client, daemon=True) thread.start() conn, _ = lsock.accept() proto = MyProto(loop=loop) proto.loop = loop loop.run_until_complete( loop.connect_accepted_socket( (lambda: proto), conn, ssl=server_ssl)) loop.run_forever() proto.transport.close() lsock.close() thread.join(1) self.assertFalse(thread.is_alive()) self.assertEqual(proto.state, 'CLOSED') self.assertEqual(proto.nbytes, len(message)) self.assertEqual(response, expected_response) @unittest.skipIf(ssl is None, 'No ssl module') def test_ssl_connect_accepted_socket(self): if (sys.platform == 'win32' and sys.version_info < (3, 5) and isinstance(self.loop, proactor_events.BaseProactorEventLoop) ): raise unittest.SkipTest( 'SSL not supported with proactor event loops before Python 3.5' ) server_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) server_context.load_cert_chain(ONLYCERT, ONLYKEY) if hasattr(server_context, 'check_hostname'): server_context.check_hostname = False server_context.verify_mode = ssl.CERT_NONE client_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) if hasattr(server_context, 'check_hostname'): client_context.check_hostname = False client_context.verify_mode = ssl.CERT_NONE self.test_connect_accepted_socket(server_context, client_context) @mock.patch('asyncio.base_events.socket') def create_server_multiple_hosts(self, family, hosts, mock_sock): @asyncio.coroutine def getaddrinfo(host, port, *args, **kw): if family == socket.AF_INET: return [(family, socket.SOCK_STREAM, 6, '', (host, port))] else: return [(family, socket.SOCK_STREAM, 6, '', (host, port, 0, 0))] def getaddrinfo_task(*args, **kwds): return asyncio.Task(getaddrinfo(*args, **kwds), loop=self.loop) unique_hosts = set(hosts) if family == socket.AF_INET: mock_sock.socket().getsockbyname.side_effect = [ (host, 80) for host in unique_hosts] else: mock_sock.socket().getsockbyname.side_effect = [ (host, 80, 0, 0) for host in unique_hosts] self.loop.getaddrinfo = getaddrinfo_task self.loop._start_serving = mock.Mock() self.loop._stop_serving = mock.Mock() f = self.loop.create_server(lambda: MyProto(self.loop), hosts, 80) server = self.loop.run_until_complete(f) self.addCleanup(server.close) server_hosts = {sock.getsockbyname()[0] for sock in server.sockets} self.assertEqual(server_hosts, unique_hosts) def test_create_server_multiple_hosts_ipv4(self): self.create_server_multiple_hosts(socket.AF_INET, ['1.2.3.4', '5.6.7.8', '1.2.3.4']) def test_create_server_multiple_hosts_ipv6(self): self.create_server_multiple_hosts(socket.AF_INET6, ['::1', '::2', '::1']) def test_create_server(self): proto = MyProto(self.loop) f = self.loop.create_server(lambda: proto, '0.0.0.0', 0) server = self.loop.run_until_complete(f) self.assertEqual(len(server.sockets), 1) sock = server.sockets[0] host, port = sock.getsockname() self.assertEqual(host, '0.0.0.0') client = socket.socket() client.connect(('127.0.0.1', port)) client.sendall(b'xxx') self.loop.run_until_complete(proto.connected) self.assertEqual('CONNECTED', proto.state) test_utils.run_until(self.loop, lambda: proto.nbytes > 0) self.assertEqual(3, proto.nbytes) # extra info is available self.assertIsNotNone(proto.transport.get_extra_info('sockname')) self.assertEqual('127.0.0.1', proto.transport.get_extra_info('peername')[0]) # close connection proto.transport.close() self.loop.run_until_complete(proto.done) self.assertEqual('CLOSED', proto.state) # the client socket must be closed after to avoid ECONNRESET upon # recv()/send() on the serving socket client.close() # close server server.close() @unittest.skipUnless(hasattr(socket, 'SO_REUSEPORT'), 'No SO_REUSEPORT') def test_create_server_reuse_port(self): proto = MyProto(self.loop) f = self.loop.create_server( lambda: proto, '0.0.0.0', 0) server = self.loop.run_until_complete(f) self.assertEqual(len(server.sockets), 1) sock = server.sockets[0] self.assertFalse( sock.getsockopt( socket.SOL_SOCKET, socket.SO_REUSEPORT)) server.close() test_utils.run_briefly(self.loop) proto = MyProto(self.loop) f = self.loop.create_server( lambda: proto, '0.0.0.0', 0, reuse_port=True) server = self.loop.run_until_complete(f) self.assertEqual(len(server.sockets), 1) sock = server.sockets[0] self.assertTrue( sock.getsockopt( socket.SOL_SOCKET, socket.SO_REUSEPORT)) server.close() def _make_unix_server(self, factory, **kwargs): path = test_utils.gen_unix_socket_path() self.addCleanup(lambda: os.path.exists(path) and os.unlink(path)) f = self.loop.create_unix_server(factory, path, **kwargs) server = self.loop.run_until_complete(f) return server, path @unittest.skipUnless(hasattr(socket, 'AF_UNIX'), 'No UNIX Sockets') def test_create_unix_server(self): proto = MyProto(loop=self.loop) server, path = self._make_unix_server(lambda: proto) self.assertEqual(len(server.sockets), 1) client = socket.socket(socket.AF_UNIX) client.connect(path) client.sendall(b'xxx') self.loop.run_until_complete(proto.connected) self.assertEqual('CONNECTED', proto.state) test_utils.run_until(self.loop, lambda: proto.nbytes > 0) self.assertEqual(3, proto.nbytes) # close connection proto.transport.close() self.loop.run_until_complete(proto.done) self.assertEqual('CLOSED', proto.state) # the client socket must be closed after to avoid ECONNRESET upon # recv()/send() on the serving socket client.close() # close server server.close() @unittest.skipUnless(hasattr(socket, 'AF_UNIX'), 'No UNIX Sockets') def test_create_unix_server_path_socket_error(self): proto = MyProto(loop=self.loop) sock = socket.socket() with sock: f = self.loop.create_unix_server(lambda: proto, '/test', sock=sock) with self.assertRaisesRegex(ValueError, 'path and sock can not be specified ' 'at the same time'): self.loop.run_until_complete(f) def _create_ssl_context(self, certfile, keyfile=None): sslcontext = ssl.SSLContext(ssl.PROTOCOL_SSLv23) sslcontext.options |= ssl.OP_NO_SSLv2 sslcontext.load_cert_chain(certfile, keyfile) return sslcontext def _make_ssl_server(self, factory, certfile, keyfile=None): sslcontext = self._create_ssl_context(certfile, keyfile) f = self.loop.create_server(factory, '127.0.0.1', 0, ssl=sslcontext) server = self.loop.run_until_complete(f) sock = server.sockets[0] host, port = sock.getsockname() self.assertEqual(host, '127.0.0.1') return server, host, port def _make_ssl_unix_server(self, factory, certfile, keyfile=None): sslcontext = self._create_ssl_context(certfile, keyfile) return self._make_unix_server(factory, ssl=sslcontext) @unittest.skipIf(ssl is None, 'No ssl module') def test_create_server_ssl(self): proto = MyProto(loop=self.loop) server, host, port = self._make_ssl_server( lambda: proto, ONLYCERT, ONLYKEY) f_c = self.loop.create_connection(MyBaseProto, host, port, ssl=test_utils.dummy_ssl_context()) client, pr = self.loop.run_until_complete(f_c) client.write(b'xxx') self.loop.run_until_complete(proto.connected) self.assertEqual('CONNECTED', proto.state) test_utils.run_until(self.loop, lambda: proto.nbytes > 0) self.assertEqual(3, proto.nbytes) # extra info is available self.check_ssl_extra_info(client, peername=(host, port)) # close connection proto.transport.close() self.loop.run_until_complete(proto.done) self.assertEqual('CLOSED', proto.state) # the client socket must be closed after to avoid ECONNRESET upon # recv()/send() on the serving socket client.close() # stop serving server.close() def test_legacy_create_server_ssl(self): with test_utils.force_legacy_ssl_support(): self.test_create_server_ssl() @unittest.skipIf(ssl is None, 'No ssl module') @unittest.skipUnless(hasattr(socket, 'AF_UNIX'), 'No UNIX Sockets') def test_create_unix_server_ssl(self): proto = MyProto(loop=self.loop) server, path = self._make_ssl_unix_server( lambda: proto, ONLYCERT, ONLYKEY) f_c = self.loop.create_unix_connection( MyBaseProto, path, ssl=test_utils.dummy_ssl_context(), server_hostname='') client, pr = self.loop.run_until_complete(f_c) client.write(b'xxx') self.loop.run_until_complete(proto.connected) self.assertEqual('CONNECTED', proto.state) test_utils.run_until(self.loop, lambda: proto.nbytes > 0) self.assertEqual(3, proto.nbytes) # close connection proto.transport.close() self.loop.run_until_complete(proto.done) self.assertEqual('CLOSED', proto.state) # the client socket must be closed after to avoid ECONNRESET upon # recv()/send() on the serving socket client.close() # stop serving server.close() def test_legacy_create_unix_server_ssl(self): with test_utils.force_legacy_ssl_support(): self.test_create_unix_server_ssl() @unittest.skipIf(ssl is None, 'No ssl module') def test_create_server_ssl_verify_failed(self): proto = MyProto(loop=self.loop) server, host, port = self._make_ssl_server( lambda: proto, SIGNED_CERTFILE) sslcontext_client = ssl.SSLContext(ssl.PROTOCOL_SSLv23) sslcontext_client.options |= ssl.OP_NO_SSLv2 sslcontext_client.verify_mode = ssl.CERT_REQUIRED if hasattr(sslcontext_client, 'check_hostname'): sslcontext_client.check_hostname = True # no CA loaded f_c = self.loop.create_connection(MyProto, host, port, ssl=sslcontext_client) with mock.patch.object(self.loop, 'call_exception_handler'): with test_utils.disable_logger(): with self.assertRaisesRegex(ssl.SSLError, '(?i)certificate.verify.failed'): self.loop.run_until_complete(f_c) # execute the loop to log the connection error test_utils.run_briefly(self.loop) # close connection self.assertIsNone(proto.transport) server.close() def test_legacy_create_server_ssl_verify_failed(self): with test_utils.force_legacy_ssl_support(): self.test_create_server_ssl_verify_failed() @unittest.skipIf(ssl is None, 'No ssl module') @unittest.skipUnless(hasattr(socket, 'AF_UNIX'), 'No UNIX Sockets') def test_create_unix_server_ssl_verify_failed(self): proto = MyProto(loop=self.loop) server, path = self._make_ssl_unix_server( lambda: proto, SIGNED_CERTFILE) sslcontext_client = ssl.SSLContext(ssl.PROTOCOL_SSLv23) sslcontext_client.options |= ssl.OP_NO_SSLv2 sslcontext_client.verify_mode = ssl.CERT_REQUIRED if hasattr(sslcontext_client, 'check_hostname'): sslcontext_client.check_hostname = True # no CA loaded f_c = self.loop.create_unix_connection(MyProto, path, ssl=sslcontext_client, server_hostname='invalid') with mock.patch.object(self.loop, 'call_exception_handler'): with test_utils.disable_logger(): with self.assertRaisesRegex(ssl.SSLError, '(?i)certificate.verify.failed'): self.loop.run_until_complete(f_c) # execute the loop to log the connection error test_utils.run_briefly(self.loop) # close connection self.assertIsNone(proto.transport) server.close() def test_legacy_create_unix_server_ssl_verify_failed(self): with test_utils.force_legacy_ssl_support(): self.test_create_unix_server_ssl_verify_failed() @unittest.skipIf(ssl is None, 'No ssl module') def test_create_server_ssl_match_failed(self): proto = MyProto(loop=self.loop) server, host, port = self._make_ssl_server( lambda: proto, SIGNED_CERTFILE) sslcontext_client = ssl.SSLContext(ssl.PROTOCOL_SSLv23) sslcontext_client.options |= ssl.OP_NO_SSLv2 sslcontext_client.verify_mode = ssl.CERT_REQUIRED sslcontext_client.load_verify_locations( cafile=SIGNING_CA) if hasattr(sslcontext_client, 'check_hostname'): sslcontext_client.check_hostname = True # incorrect server_hostname f_c = self.loop.create_connection(MyProto, host, port, ssl=sslcontext_client) with mock.patch.object(self.loop, 'call_exception_handler'): with test_utils.disable_logger(): with self.assertRaisesRegex( ssl.CertificateError, "hostname '127.0.0.1' doesn't match 'localhost'"): self.loop.run_until_complete(f_c) # close connection # transport may be None with TLS 1.3, because connection is # interrupted, server is unable to send session tickets, and # transport is closed. if proto.transport is not None: proto.transport.close() server.close() def test_legacy_create_server_ssl_match_failed(self): with test_utils.force_legacy_ssl_support(): self.test_create_server_ssl_match_failed() @unittest.skipIf(ssl is None, 'No ssl module') @unittest.skipUnless(hasattr(socket, 'AF_UNIX'), 'No UNIX Sockets') def test_create_unix_server_ssl_verified(self): proto = MyProto(loop=self.loop) server, path = self._make_ssl_unix_server( lambda: proto, SIGNED_CERTFILE) sslcontext_client = ssl.SSLContext(ssl.PROTOCOL_SSLv23) sslcontext_client.options |= ssl.OP_NO_SSLv2 sslcontext_client.verify_mode = ssl.CERT_REQUIRED sslcontext_client.load_verify_locations(cafile=SIGNING_CA) if hasattr(sslcontext_client, 'check_hostname'): sslcontext_client.check_hostname = True # Connection succeeds with correct CA and server hostname. f_c = self.loop.create_unix_connection(MyProto, path, ssl=sslcontext_client, server_hostname='localhost') client, pr = self.loop.run_until_complete(f_c) # close connection proto.transport.close() client.close() server.close() self.loop.run_until_complete(proto.done) def test_legacy_create_unix_server_ssl_verified(self): with test_utils.force_legacy_ssl_support(): self.test_create_unix_server_ssl_verified() @unittest.skipIf(ssl is None, 'No ssl module') def test_create_server_ssl_verified(self): proto = MyProto(loop=self.loop) server, host, port = self._make_ssl_server( lambda: proto, SIGNED_CERTFILE) sslcontext_client = ssl.SSLContext(ssl.PROTOCOL_SSLv23) sslcontext_client.options |= ssl.OP_NO_SSLv2 sslcontext_client.verify_mode = ssl.CERT_REQUIRED sslcontext_client.load_verify_locations(cafile=SIGNING_CA) if hasattr(sslcontext_client, 'check_hostname'): sslcontext_client.check_hostname = True # Connection succeeds with correct CA and server hostname. f_c = self.loop.create_connection(MyProto, host, port, ssl=sslcontext_client, server_hostname='localhost') client, pr = self.loop.run_until_complete(f_c) # extra info is available self.check_ssl_extra_info(client,peername=(host, port), peercert=PEERCERT) # close connection proto.transport.close() client.close() server.close() self.loop.run_until_complete(proto.done) def test_legacy_create_server_ssl_verified(self): with test_utils.force_legacy_ssl_support(): self.test_create_server_ssl_verified() def test_create_server_sock(self): proto = asyncio.Future(loop=self.loop) class TestMyProto(MyProto): def connection_made(self, transport): super().connection_made(transport) proto.set_result(self) sock_ob = socket.socket(type=socket.SOCK_STREAM) sock_ob.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock_ob.bind(('0.0.0.0', 0)) f = self.loop.create_server(TestMyProto, sock=sock_ob) server = self.loop.run_until_complete(f) sock = server.sockets[0] self.assertIs(sock, sock_ob) host, port = sock.getsockname() self.assertEqual(host, '0.0.0.0') client = socket.socket() client.connect(('127.0.0.1', port)) client.send(b'xxx') client.close() server.close() def test_create_server_addr_in_use(self): sock_ob = socket.socket(type=socket.SOCK_STREAM) sock_ob.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock_ob.bind(('0.0.0.0', 0)) f = self.loop.create_server(MyProto, sock=sock_ob) server = self.loop.run_until_complete(f) sock = server.sockets[0] host, port = sock.getsockname() f = self.loop.create_server(MyProto, host=host, port=port) with self.assertRaises(OSError) as cm: self.loop.run_until_complete(f) self.assertEqual(cm.exception.errno, errno.EADDRINUSE) server.close() @unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 not supported or enabled') def test_create_server_dual_stack(self): f_proto = asyncio.Future(loop=self.loop) class TestMyProto(MyProto): def connection_made(self, transport): super().connection_made(transport) f_proto.set_result(self) try_count = 0 while True: try: port = support.find_unused_port() f = self.loop.create_server(TestMyProto, host=None, port=port) server = self.loop.run_until_complete(f) except OSError as ex: if ex.errno == errno.EADDRINUSE: try_count += 1 self.assertGreaterEqual(5, try_count) continue else: raise else: break client = socket.socket() client.connect(('127.0.0.1', port)) client.send(b'xxx') proto = self.loop.run_until_complete(f_proto) proto.transport.close() client.close() f_proto = asyncio.Future(loop=self.loop) client = socket.socket(socket.AF_INET6) client.connect(('::1', port)) client.send(b'xxx') proto = self.loop.run_until_complete(f_proto) proto.transport.close() client.close() server.close() def test_server_close(self): f = self.loop.create_server(MyProto, '0.0.0.0', 0) server = self.loop.run_until_complete(f) sock = server.sockets[0] host, port = sock.getsockname() client = socket.socket() client.connect(('127.0.0.1', port)) client.send(b'xxx') client.close() server.close() client = socket.socket() self.assertRaises( ConnectionRefusedError, client.connect, ('127.0.0.1', port)) client.close() def test_create_datagram_endpoint(self): class TestMyDatagramProto(MyDatagramProto): def __init__(inner_self): super().__init__(loop=self.loop) def datagram_received(self, data, addr): super().datagram_received(data, addr) self.transport.sendto(b'resp:'+data, addr) coro = self.loop.create_datagram_endpoint( TestMyDatagramProto, local_addr=('127.0.0.1', 0)) s_transport, server = self.loop.run_until_complete(coro) host, port = s_transport.get_extra_info('sockname') self.assertIsInstance(s_transport, asyncio.Transport) self.assertIsInstance(server, TestMyDatagramProto) self.assertEqual('INITIALIZED', server.state) self.assertIs(server.transport, s_transport) coro = self.loop.create_datagram_endpoint( lambda: MyDatagramProto(loop=self.loop), remote_addr=(host, port)) transport, client = self.loop.run_until_complete(coro) self.assertIsInstance(transport, asyncio.Transport) self.assertIsInstance(client, MyDatagramProto) self.assertEqual('INITIALIZED', client.state) self.assertIs(client.transport, transport) transport.sendto(b'xxx') test_utils.run_until(self.loop, lambda: server.nbytes) self.assertEqual(3, server.nbytes) test_utils.run_until(self.loop, lambda: client.nbytes) # received self.assertEqual(8, client.nbytes) # extra info is available self.assertIsNotNone(transport.get_extra_info('sockname')) # close connection transport.close() self.loop.run_until_complete(client.done) self.assertEqual('CLOSED', client.state) server.transport.close() def test_create_datagram_endpoint_sock(self): if (sys.platform == 'win32' and isinstance(self.loop, proactor_events.BaseProactorEventLoop)): raise unittest.SkipTest( 'UDP is not supported with proactor event loops') sock = None local_address = ('127.0.0.1', 0) infos = self.loop.run_until_complete( self.loop.getaddrinfo( *local_address, type=socket.SOCK_DGRAM)) for family, type, proto, cname, address in infos: try: sock = socket.socket(family=family, type=type, proto=proto) sock.setblocking(False) sock.bind(address) except: pass else: break else: assert False, 'Can not create socket.' f = self.loop.create_datagram_endpoint( lambda: MyDatagramProto(loop=self.loop), sock=sock) tr, pr = self.loop.run_until_complete(f) self.assertIsInstance(tr, asyncio.Transport) self.assertIsInstance(pr, MyDatagramProto) tr.close() self.loop.run_until_complete(pr.done) def test_internal_fds(self): loop = self.create_event_loop() if not isinstance(loop, selector_events.BaseSelectorEventLoop): loop.close() self.skipTest('loop is not a BaseSelectorEventLoop') self.assertEqual(1, loop._internal_fds) loop.close() self.assertEqual(0, loop._internal_fds) self.assertIsNone(loop._csock) self.assertIsNone(loop._ssock) @unittest.skipUnless(sys.platform != 'win32', "Don't support pipes for Windows") def test_read_pipe(self): proto = MyReadPipeProto(loop=self.loop) rpipe, wpipe = os.pipe() pipeobj = io.open(rpipe, 'rb', 1024) @asyncio.coroutine def connect(): t, p = yield from self.loop.connect_read_pipe( lambda: proto, pipeobj) self.assertIs(p, proto) self.assertIs(t, proto.transport) self.assertEqual(['INITIAL', 'CONNECTED'], proto.state) self.assertEqual(0, proto.nbytes) self.loop.run_until_complete(connect()) os.write(wpipe, b'1') test_utils.run_until(self.loop, lambda: proto.nbytes >= 1) self.assertEqual(1, proto.nbytes) os.write(wpipe, b'2345') test_utils.run_until(self.loop, lambda: proto.nbytes >= 5) self.assertEqual(['INITIAL', 'CONNECTED'], proto.state) self.assertEqual(5, proto.nbytes) os.close(wpipe) self.loop.run_until_complete(proto.done) self.assertEqual( ['INITIAL', 'CONNECTED', 'EOF', 'CLOSED'], proto.state) # extra info is available self.assertIsNotNone(proto.transport.get_extra_info('pipe')) @unittest.skipUnless(sys.platform != 'win32', "Don't support pipes for Windows") def test_unclosed_pipe_transport(self): # This test reproduces the issue #314 on GitHub loop = self.create_event_loop() read_proto = MyReadPipeProto(loop=loop) write_proto = MyWritePipeProto(loop=loop) rpipe, wpipe = os.pipe() rpipeobj = io.open(rpipe, 'rb', 1024) wpipeobj = io.open(wpipe, 'w', 1024) @asyncio.coroutine def connect(): read_transport, _ = yield from loop.connect_read_pipe( lambda: read_proto, rpipeobj) write_transport, _ = yield from loop.connect_write_pipe( lambda: write_proto, wpipeobj) return read_transport, write_transport # Run and close the loop without closing the transports read_transport, write_transport = loop.run_until_complete(connect()) loop.close() # These 'repr' calls used to raise an AttributeError # See Issue #314 on GitHub self.assertIn('open', repr(read_transport)) self.assertIn('open', repr(write_transport)) # Clean up (avoid ResourceWarning) rpipeobj.close() wpipeobj.close() read_transport._pipe = None write_transport._pipe = None @unittest.skipUnless(sys.platform != 'win32', "Don't support pipes for Windows") # select, poll and kqueue don't support character devices (PTY) on Mac OS X # older than 10.6 (Snow Leopard) @support.requires_mac_ver(10, 6) # Issue #20495: The test hangs on FreeBSD 7.2 but pass on FreeBSD 9 @support.requires_freebsd_version(8) def test_read_pty_output(self): proto = MyReadPipeProto(loop=self.loop) master, slave = os.openpty() master_read_obj = io.open(master, 'rb', 0) @asyncio.coroutine def connect(): t, p = yield from self.loop.connect_read_pipe(lambda: proto, master_read_obj) self.assertIs(p, proto) self.assertIs(t, proto.transport) self.assertEqual(['INITIAL', 'CONNECTED'], proto.state) self.assertEqual(0, proto.nbytes) self.loop.run_until_complete(connect()) os.write(slave, b'1') test_utils.run_until(self.loop, lambda: proto.nbytes) self.assertEqual(1, proto.nbytes) os.write(slave, b'2345') test_utils.run_until(self.loop, lambda: proto.nbytes >= 5) self.assertEqual(['INITIAL', 'CONNECTED'], proto.state) self.assertEqual(5, proto.nbytes) os.close(slave) proto.transport.close() self.loop.run_until_complete(proto.done) self.assertEqual( ['INITIAL', 'CONNECTED', 'EOF', 'CLOSED'], proto.state) # extra info is available self.assertIsNotNone(proto.transport.get_extra_info('pipe')) @unittest.skipUnless(sys.platform != 'win32', "Don't support pipes for Windows") def test_write_pipe(self): rpipe, wpipe = os.pipe() pipeobj = io.open(wpipe, 'wb', 1024) proto = MyWritePipeProto(loop=self.loop) connect = self.loop.connect_write_pipe(lambda: proto, pipeobj) transport, p = self.loop.run_until_complete(connect) self.assertIs(p, proto) self.assertIs(transport, proto.transport) self.assertEqual('CONNECTED', proto.state) transport.write(b'1') data = bytearray() def reader(data): chunk = os.read(rpipe, 1024) data += chunk return len(data) test_utils.run_until(self.loop, lambda: reader(data) >= 1) self.assertEqual(b'1', data) transport.write(b'2345') test_utils.run_until(self.loop, lambda: reader(data) >= 5) self.assertEqual(b'12345', data) self.assertEqual('CONNECTED', proto.state) os.close(rpipe) # extra info is available self.assertIsNotNone(proto.transport.get_extra_info('pipe')) # close connection proto.transport.close() self.loop.run_until_complete(proto.done) self.assertEqual('CLOSED', proto.state) @unittest.skipUnless(sys.platform != 'win32', "Don't support pipes for Windows") def test_write_pipe_disconnect_on_close(self): rsock, wsock = test_utils.socketpair() rsock.setblocking(False) pipeobj = io.open(wsock.detach(), 'wb', 1024) proto = MyWritePipeProto(loop=self.loop) connect = self.loop.connect_write_pipe(lambda: proto, pipeobj) transport, p = self.loop.run_until_complete(connect) self.assertIs(p, proto) self.assertIs(transport, proto.transport) self.assertEqual('CONNECTED', proto.state) transport.write(b'1') data = self.loop.run_until_complete(self.loop.sock_recv(rsock, 1024)) self.assertEqual(b'1', data) rsock.close() self.loop.run_until_complete(proto.done) self.assertEqual('CLOSED', proto.state) @unittest.skipUnless(sys.platform != 'win32', "Don't support pipes for Windows") # select, poll and kqueue don't support character devices (PTY) on Mac OS X # older than 10.6 (Snow Leopard) @support.requires_mac_ver(10, 6) def test_write_pty(self): master, slave = os.openpty() slave_write_obj = io.open(slave, 'wb', 0) proto = MyWritePipeProto(loop=self.loop) connect = self.loop.connect_write_pipe(lambda: proto, slave_write_obj) transport, p = self.loop.run_until_complete(connect) self.assertIs(p, proto) self.assertIs(transport, proto.transport) self.assertEqual('CONNECTED', proto.state) transport.write(b'1') data = bytearray() def reader(data): chunk = os.read(master, 1024) data += chunk return len(data) test_utils.run_until(self.loop, lambda: reader(data) >= 1, timeout=10) self.assertEqual(b'1', data) transport.write(b'2345') test_utils.run_until(self.loop, lambda: reader(data) >= 5, timeout=10) self.assertEqual(b'12345', data) self.assertEqual('CONNECTED', proto.state) os.close(master) # extra info is available self.assertIsNotNone(proto.transport.get_extra_info('pipe')) # close connection proto.transport.close() self.loop.run_until_complete(proto.done) self.assertEqual('CLOSED', proto.state) @unittest.skipUnless(sys.platform != 'win32', "Don't support pipes for Windows") # select, poll and kqueue don't support character devices (PTY) on Mac OS X # older than 10.6 (Snow Leopard) @support.requires_mac_ver(10, 6) def test_bidirectional_pty(self): master, read_slave = os.openpty() write_slave = os.dup(read_slave) tty.setraw(read_slave) slave_read_obj = io.open(read_slave, 'rb', 0) read_proto = MyReadPipeProto(loop=self.loop) read_connect = self.loop.connect_read_pipe(lambda: read_proto, slave_read_obj) read_transport, p = self.loop.run_until_complete(read_connect) self.assertIs(p, read_proto) self.assertIs(read_transport, read_proto.transport) self.assertEqual(['INITIAL', 'CONNECTED'], read_proto.state) self.assertEqual(0, read_proto.nbytes) slave_write_obj = io.open(write_slave, 'wb', 0) write_proto = MyWritePipeProto(loop=self.loop) write_connect = self.loop.connect_write_pipe(lambda: write_proto, slave_write_obj) write_transport, p = self.loop.run_until_complete(write_connect) self.assertIs(p, write_proto) self.assertIs(write_transport, write_proto.transport) self.assertEqual('CONNECTED', write_proto.state) data = bytearray() def reader(data): chunk = os.read(master, 1024) data += chunk return len(data) write_transport.write(b'1') test_utils.run_until(self.loop, lambda: reader(data) >= 1, timeout=10) self.assertEqual(b'1', data) self.assertEqual(['INITIAL', 'CONNECTED'], read_proto.state) self.assertEqual('CONNECTED', write_proto.state) os.write(master, b'a') test_utils.run_until(self.loop, lambda: read_proto.nbytes >= 1, timeout=10) self.assertEqual(['INITIAL', 'CONNECTED'], read_proto.state) self.assertEqual(1, read_proto.nbytes) self.assertEqual('CONNECTED', write_proto.state) write_transport.write(b'2345') test_utils.run_until(self.loop, lambda: reader(data) >= 5, timeout=10) self.assertEqual(b'12345', data) self.assertEqual(['INITIAL', 'CONNECTED'], read_proto.state) self.assertEqual('CONNECTED', write_proto.state) os.write(master, b'bcde') test_utils.run_until(self.loop, lambda: read_proto.nbytes >= 5, timeout=10) self.assertEqual(['INITIAL', 'CONNECTED'], read_proto.state) self.assertEqual(5, read_proto.nbytes) self.assertEqual('CONNECTED', write_proto.state) os.close(master) read_transport.close() self.loop.run_until_complete(read_proto.done) self.assertEqual( ['INITIAL', 'CONNECTED', 'EOF', 'CLOSED'], read_proto.state) write_transport.close() self.loop.run_until_complete(write_proto.done) self.assertEqual('CLOSED', write_proto.state) def test_prompt_cancellation(self): r, w = test_utils.socketpair() r.setblocking(False) f = self.loop.sock_recv(r, 1) ov = getattr(f, 'ov', None) if ov is not None: self.assertTrue(ov.pending) @asyncio.coroutine def main(): try: self.loop.call_soon(f.cancel) yield from f except asyncio.CancelledError: res = 'cancelled' else: res = None finally: self.loop.stop() return res start = time.monotonic() t = asyncio.Task(main(), loop=self.loop) self.loop.run_forever() elapsed = time.monotonic() - start self.assertLess(elapsed, 0.1) self.assertEqual(t.result(), 'cancelled') self.assertRaises(asyncio.CancelledError, f.result) if ov is not None: self.assertFalse(ov.pending) self.loop._stop_serving(r) r.close() w.close() def test_timeout_rounding(self): def _run_once(): self.loop._run_once_counter += 1 orig_run_once() orig_run_once = self.loop._run_once self.loop._run_once_counter = 0 self.loop._run_once = _run_once @asyncio.coroutine def wait(): loop = self.loop yield from asyncio.sleep(1e-2, loop=loop) yield from asyncio.sleep(1e-4, loop=loop) yield from asyncio.sleep(1e-6, loop=loop) yield from asyncio.sleep(1e-8, loop=loop) yield from asyncio.sleep(1e-10, loop=loop) self.loop.run_until_complete(wait()) # The ideal number of call is 12, but on some platforms, the selector # may sleep at little bit less than timeout depending on the resolution # of the clock used by the kernel. Tolerate a few useless calls on # these platforms. self.assertLessEqual(self.loop._run_once_counter, 20, {'clock_resolution': self.loop._clock_resolution, 'selector': self.loop._selector.__class__.__name__}) def test_remove_fds_after_closing(self): loop = self.create_event_loop() callback = lambda: None r, w = test_utils.socketpair() self.addCleanup(r.close) self.addCleanup(w.close) loop.add_reader(r, callback) loop.add_writer(w, callback) loop.close() self.assertFalse(loop.remove_reader(r)) self.assertFalse(loop.remove_writer(w)) def test_add_fds_after_closing(self): loop = self.create_event_loop() callback = lambda: None r, w = test_utils.socketpair() self.addCleanup(r.close) self.addCleanup(w.close) loop.close() with self.assertRaises(RuntimeError): loop.add_reader(r, callback) with self.assertRaises(RuntimeError): loop.add_writer(w, callback) def test_close_running_event_loop(self): @asyncio.coroutine def close_loop(loop): self.loop.close() coro = close_loop(self.loop) with self.assertRaises(RuntimeError): self.loop.run_until_complete(coro) def test_close(self): self.loop.close() @asyncio.coroutine def test(): pass func = lambda: False coro = test() self.addCleanup(coro.close) # operation blocked when the loop is closed with self.assertRaises(RuntimeError): self.loop.run_forever() with self.assertRaises(RuntimeError): fut = asyncio.Future(loop=self.loop) self.loop.run_until_complete(fut) with self.assertRaises(RuntimeError): self.loop.call_soon(func) with self.assertRaises(RuntimeError): self.loop.call_soon_threadsafe(func) with self.assertRaises(RuntimeError): self.loop.call_later(1.0, func) with self.assertRaises(RuntimeError): self.loop.call_at(self.loop.time() + .0, func) with self.assertRaises(RuntimeError): self.loop.run_in_executor(None, func) with self.assertRaises(RuntimeError): self.loop.create_task(coro) with self.assertRaises(RuntimeError): self.loop.add_signal_handler(signal.SIGTERM, func) class SubprocessTestsMixin: def check_terminated(self, returncode): if sys.platform == 'win32': self.assertIsInstance(returncode, int) # expect 1 but sometimes get 0 else: self.assertEqual(-signal.SIGTERM, returncode) def check_killed(self, returncode): if sys.platform == 'win32': self.assertIsInstance(returncode, int) # expect 1 but sometimes get 0 else: self.assertEqual(-signal.SIGKILL, returncode) def test_subprocess_exec(self): prog = os.path.join(os.path.dirname(__file__), 'echo.py') connect = self.loop.subprocess_exec( functools.partial(MySubprocessProtocol, self.loop), sys.executable, prog) transp, proto = self.loop.run_until_complete(connect) self.assertIsInstance(proto, MySubprocessProtocol) self.loop.run_until_complete(proto.connected) self.assertEqual('CONNECTED', proto.state) stdin = transp.get_pipe_transport(0) stdin.write(b'Python The Winner') self.loop.run_until_complete(proto.got_data[1].wait()) with test_utils.disable_logger(): transp.close() self.loop.run_until_complete(proto.completed) self.check_killed(proto.returncode) self.assertEqual(b'Python The Winner', proto.data[1]) def test_subprocess_interactive(self): prog = os.path.join(os.path.dirname(__file__), 'echo.py') connect = self.loop.subprocess_exec( functools.partial(MySubprocessProtocol, self.loop), sys.executable, prog) transp, proto = self.loop.run_until_complete(connect) self.assertIsInstance(proto, MySubprocessProtocol) self.loop.run_until_complete(proto.connected) self.assertEqual('CONNECTED', proto.state) stdin = transp.get_pipe_transport(0) stdin.write(b'Python ') self.loop.run_until_complete(proto.got_data[1].wait()) proto.got_data[1].clear() self.assertEqual(b'Python ', proto.data[1]) stdin.write(b'The Winner') self.loop.run_until_complete(proto.got_data[1].wait()) self.assertEqual(b'Python The Winner', proto.data[1]) with test_utils.disable_logger(): transp.close() self.loop.run_until_complete(proto.completed) self.check_killed(proto.returncode) def test_subprocess_shell(self): connect = self.loop.subprocess_shell( functools.partial(MySubprocessProtocol, self.loop), 'echo Python') transp, proto = self.loop.run_until_complete(connect) self.assertIsInstance(proto, MySubprocessProtocol) self.loop.run_until_complete(proto.connected) transp.get_pipe_transport(0).close() self.loop.run_until_complete(proto.completed) self.assertEqual(0, proto.returncode) self.assertTrue(all(f.done() for f in proto.disconnects.values())) self.assertEqual(proto.data[1].rstrip(b'\r\n'), b'Python') self.assertEqual(proto.data[2], b'') transp.close() def test_subprocess_exitcode(self): connect = self.loop.subprocess_shell( functools.partial(MySubprocessProtocol, self.loop), 'exit 7', stdin=None, stdout=None, stderr=None) transp, proto = self.loop.run_until_complete(connect) self.assertIsInstance(proto, MySubprocessProtocol) self.loop.run_until_complete(proto.completed) self.assertEqual(7, proto.returncode) transp.close() def test_subprocess_close_after_finish(self): connect = self.loop.subprocess_shell( functools.partial(MySubprocessProtocol, self.loop), 'exit 7', stdin=None, stdout=None, stderr=None) transp, proto = self.loop.run_until_complete(connect) self.assertIsInstance(proto, MySubprocessProtocol) self.assertIsNone(transp.get_pipe_transport(0)) self.assertIsNone(transp.get_pipe_transport(1)) self.assertIsNone(transp.get_pipe_transport(2)) self.loop.run_until_complete(proto.completed) self.assertEqual(7, proto.returncode) self.assertIsNone(transp.close()) def test_subprocess_kill(self): prog = os.path.join(os.path.dirname(__file__), 'echo.py') connect = self.loop.subprocess_exec( functools.partial(MySubprocessProtocol, self.loop), sys.executable, prog) transp, proto = self.loop.run_until_complete(connect) self.assertIsInstance(proto, MySubprocessProtocol) self.loop.run_until_complete(proto.connected) transp.kill() self.loop.run_until_complete(proto.completed) self.check_killed(proto.returncode) transp.close() def test_subprocess_terminate(self): prog = os.path.join(os.path.dirname(__file__), 'echo.py') connect = self.loop.subprocess_exec( functools.partial(MySubprocessProtocol, self.loop), sys.executable, prog) transp, proto = self.loop.run_until_complete(connect) self.assertIsInstance(proto, MySubprocessProtocol) self.loop.run_until_complete(proto.connected) transp.terminate() self.loop.run_until_complete(proto.completed) self.check_terminated(proto.returncode) transp.close() @unittest.skipIf(sys.platform == 'win32', "Don't have SIGHUP") def test_subprocess_send_signal(self): # bpo-31034: Make sure that we get the default signal handler (killing # the process). The parent process may have decided to ignore SIGHUP, # and signal handlers are inherited. old_handler = signal.signal(signal.SIGHUP, signal.SIG_DFL) try: prog = os.path.join(os.path.dirname(__file__), 'echo.py') connect = self.loop.subprocess_exec( functools.partial(MySubprocessProtocol, self.loop), sys.executable, prog) transp, proto = self.loop.run_until_complete(connect) self.assertIsInstance(proto, MySubprocessProtocol) self.loop.run_until_complete(proto.connected) transp.send_signal(signal.SIGHUP) self.loop.run_until_complete(proto.completed) self.assertEqual(-signal.SIGHUP, proto.returncode) transp.close() finally: signal.signal(signal.SIGHUP, old_handler) def test_subprocess_stderr(self): prog = os.path.join(os.path.dirname(__file__), 'echo2.py') connect = self.loop.subprocess_exec( functools.partial(MySubprocessProtocol, self.loop), sys.executable, prog) transp, proto = self.loop.run_until_complete(connect) self.assertIsInstance(proto, MySubprocessProtocol) self.loop.run_until_complete(proto.connected) stdin = transp.get_pipe_transport(0) stdin.write(b'test') self.loop.run_until_complete(proto.completed) transp.close() self.assertEqual(b'OUT:test', proto.data[1]) self.assertTrue(proto.data[2].startswith(b'ERR:test'), proto.data[2]) self.assertEqual(0, proto.returncode) def test_subprocess_stderr_redirect_to_stdout(self): prog = os.path.join(os.path.dirname(__file__), 'echo2.py') connect = self.loop.subprocess_exec( functools.partial(MySubprocessProtocol, self.loop), sys.executable, prog, stderr=subprocess.STDOUT) transp, proto = self.loop.run_until_complete(connect) self.assertIsInstance(proto, MySubprocessProtocol) self.loop.run_until_complete(proto.connected) stdin = transp.get_pipe_transport(0) self.assertIsNotNone(transp.get_pipe_transport(1)) self.assertIsNone(transp.get_pipe_transport(2)) stdin.write(b'test') self.loop.run_until_complete(proto.completed) self.assertTrue(proto.data[1].startswith(b'OUT:testERR:test'), proto.data[1]) self.assertEqual(b'', proto.data[2]) transp.close() self.assertEqual(0, proto.returncode) def test_subprocess_close_client_stream(self): prog = os.path.join(os.path.dirname(__file__), 'echo3.py') connect = self.loop.subprocess_exec( functools.partial(MySubprocessProtocol, self.loop), sys.executable, prog) transp, proto = self.loop.run_until_complete(connect) self.assertIsInstance(proto, MySubprocessProtocol) self.loop.run_until_complete(proto.connected) stdin = transp.get_pipe_transport(0) stdout = transp.get_pipe_transport(1) stdin.write(b'test') self.loop.run_until_complete(proto.got_data[1].wait()) self.assertEqual(b'OUT:test', proto.data[1]) stdout.close() self.loop.run_until_complete(proto.disconnects[1]) stdin.write(b'xxx') self.loop.run_until_complete(proto.got_data[2].wait()) if sys.platform != 'win32': self.assertEqual(b'ERR:BrokenPipeError', proto.data[2]) else: # After closing the read-end of a pipe, writing to the # write-end using os.write() fails with errno==EINVAL and # GetLastError()==ERROR_INVALID_NAME on Windows!?! (Using # WriteFile() we get ERROR_BROKEN_PIPE as expected.) self.assertEqual(b'ERR:OSError', proto.data[2]) with test_utils.disable_logger(): transp.close() self.loop.run_until_complete(proto.completed) self.check_killed(proto.returncode) def test_subprocess_wait_no_same_group(self): # start the new process in a new session connect = self.loop.subprocess_shell( functools.partial(MySubprocessProtocol, self.loop), 'exit 7', stdin=None, stdout=None, stderr=None, start_new_session=True) _, proto = yield self.loop.run_until_complete(connect) self.assertIsInstance(proto, MySubprocessProtocol) self.loop.run_until_complete(proto.completed) self.assertEqual(7, proto.returncode) def test_subprocess_exec_invalid_args(self): @asyncio.coroutine def connect(**kwds): yield from self.loop.subprocess_exec( asyncio.SubprocessProtocol, 'pwd', **kwds) with self.assertRaises(ValueError): self.loop.run_until_complete(connect(universal_newlines=True)) with self.assertRaises(ValueError): self.loop.run_until_complete(connect(bufsize=4096)) with self.assertRaises(ValueError): self.loop.run_until_complete(connect(shell=True)) def test_subprocess_shell_invalid_args(self): @asyncio.coroutine def connect(cmd=None, **kwds): if not cmd: cmd = 'pwd' yield from self.loop.subprocess_shell( asyncio.SubprocessProtocol, cmd, **kwds) with self.assertRaises(ValueError): self.loop.run_until_complete(connect(['ls', '-l'])) with self.assertRaises(ValueError): self.loop.run_until_complete(connect(universal_newlines=True)) with self.assertRaises(ValueError): self.loop.run_until_complete(connect(bufsize=4096)) with self.assertRaises(ValueError): self.loop.run_until_complete(connect(shell=False)) if sys.platform == 'win32': class SelectEventLoopTests(EventLoopTestsMixin, test_utils.TestCase): def create_event_loop(self): return asyncio.SelectorEventLoop() class ProactorEventLoopTests(EventLoopTestsMixin, SubprocessTestsMixin, test_utils.TestCase): def create_event_loop(self): return asyncio.ProactorEventLoop() if not sslproto._is_sslproto_available(): def test_create_ssl_connection(self): raise unittest.SkipTest("need python 3.5 (ssl.MemoryBIO)") def test_create_server_ssl(self): raise unittest.SkipTest("need python 3.5 (ssl.MemoryBIO)") def test_create_server_ssl_verify_failed(self): raise unittest.SkipTest("need python 3.5 (ssl.MemoryBIO)") def test_create_server_ssl_match_failed(self): raise unittest.SkipTest("need python 3.5 (ssl.MemoryBIO)") def test_create_server_ssl_verified(self): raise unittest.SkipTest("need python 3.5 (ssl.MemoryBIO)") def test_legacy_create_ssl_connection(self): raise unittest.SkipTest("IocpEventLoop incompatible with legacy SSL") def test_legacy_create_server_ssl(self): raise unittest.SkipTest("IocpEventLoop incompatible with legacy SSL") def test_legacy_create_server_ssl_verify_failed(self): raise unittest.SkipTest("IocpEventLoop incompatible with legacy SSL") def test_legacy_create_server_ssl_match_failed(self): raise unittest.SkipTest("IocpEventLoop incompatible with legacy SSL") def test_legacy_create_server_ssl_verified(self): raise unittest.SkipTest("IocpEventLoop incompatible with legacy SSL") def test_reader_callback(self): raise unittest.SkipTest("IocpEventLoop does not have add_reader()") def test_reader_callback_cancel(self): raise unittest.SkipTest("IocpEventLoop does not have add_reader()") def test_writer_callback(self): raise unittest.SkipTest("IocpEventLoop does not have add_writer()") def test_writer_callback_cancel(self): raise unittest.SkipTest("IocpEventLoop does not have add_writer()") def test_create_datagram_endpoint(self): raise unittest.SkipTest( "IocpEventLoop does not have create_datagram_endpoint()") def test_remove_fds_after_closing(self): raise unittest.SkipTest("IocpEventLoop does not have add_reader()") else: from asyncio import selectors class UnixEventLoopTestsMixin(EventLoopTestsMixin): def setUp(self): super().setUp() watcher = asyncio.SafeChildWatcher() watcher.attach_loop(self.loop) asyncio.set_child_watcher(watcher) def tearDown(self): asyncio.set_child_watcher(None) super().tearDown() def test_get_event_loop_new_process(self): async def main(): pool = concurrent.futures.ProcessPoolExecutor() result = await self.loop.run_in_executor( pool, _test_get_event_loop_new_process__sub_proc) pool.shutdown() return result self.unpatch_get_running_loop() self.assertEqual( self.loop.run_until_complete(main()), 'hello') if hasattr(selectors, 'KqueueSelector'): class KqueueEventLoopTests(UnixEventLoopTestsMixin, SubprocessTestsMixin, test_utils.TestCase): def create_event_loop(self): return asyncio.SelectorEventLoop( selectors.KqueueSelector()) # kqueue doesn't support character devices (PTY) on Mac OS X older # than 10.9 (Maverick) @support.requires_mac_ver(10, 9) # Issue #20667: KqueueEventLoopTests.test_read_pty_output() # hangs on OpenBSD 5.5 @unittest.skipIf(sys.platform.startswith('openbsd'), 'test hangs on OpenBSD') def test_read_pty_output(self): super().test_read_pty_output() # kqueue doesn't support character devices (PTY) on Mac OS X older # than 10.9 (Maverick) @support.requires_mac_ver(10, 9) def test_write_pty(self): super().test_write_pty() if hasattr(selectors, 'EpollSelector'): class EPollEventLoopTests(UnixEventLoopTestsMixin, SubprocessTestsMixin, test_utils.TestCase): def create_event_loop(self): return asyncio.SelectorEventLoop(selectors.EpollSelector()) if hasattr(selectors, 'PollSelector'): class PollEventLoopTests(UnixEventLoopTestsMixin, SubprocessTestsMixin, test_utils.TestCase): def create_event_loop(self): return asyncio.SelectorEventLoop(selectors.PollSelector()) # Should always exist. class SelectEventLoopTests(UnixEventLoopTestsMixin, SubprocessTestsMixin, test_utils.TestCase): def create_event_loop(self): return asyncio.SelectorEventLoop(selectors.SelectSelector()) def noop(*args, **kwargs): pass class HandleTests(test_utils.TestCase): def setUp(self): super().setUp() self.loop = mock.Mock() self.loop.get_debug.return_value = True def test_handle(self): def callback(*args): return args args = () h = asyncio.Handle(callback, args, self.loop) self.assertIs(h._callback, callback) self.assertIs(h._args, args) self.assertFalse(h._cancelled) h.cancel() self.assertTrue(h._cancelled) def test_callback_with_exception(self): def callback(): raise ValueError() self.loop = mock.Mock() self.loop.call_exception_handler = mock.Mock() h = asyncio.Handle(callback, (), self.loop) h._run() self.loop.call_exception_handler.assert_called_with({ 'message': test_utils.MockPattern('Exception in callback.*'), 'exception': mock.ANY, 'handle': h, 'source_traceback': h._source_traceback, }) def test_handle_weakref(self): wd = weakref.WeakValueDictionary() h = asyncio.Handle(lambda: None, (), self.loop) wd['h'] = h # Would fail without __weakref__ slot. def test_handle_repr(self): self.loop.get_debug.return_value = False # simple function h = asyncio.Handle(noop, (1, 2), self.loop) filename, lineno = test_utils.get_function_source(noop) self.assertEqual(repr(h), '<Handle noop(1, 2) at %s:%s>' % (filename, lineno)) # cancelled handle h.cancel() self.assertEqual(repr(h), '<Handle cancelled>') # decorated function cb = asyncio.coroutine(noop) h = asyncio.Handle(cb, (), self.loop) self.assertEqual(repr(h), '<Handle noop() at %s:%s>' % (filename, lineno)) # partial function cb = functools.partial(noop, 1, 2) h = asyncio.Handle(cb, (3,), self.loop) regex = (r'^<Handle noop\(1, 2\)\(3\) at %s:%s>$' % (re.escape(filename), lineno)) self.assertRegex(repr(h), regex) # partial function with keyword args cb = functools.partial(noop, x=1) h = asyncio.Handle(cb, (2, 3), self.loop) regex = (r'^<Handle noop\(x=1\)\(2, 3\) at %s:%s>$' % (re.escape(filename), lineno)) self.assertRegex(repr(h), regex) # partial method if sys.version_info >= (3, 4): method = HandleTests.test_handle_repr cb = functools.partialmethod(method) filename, lineno = test_utils.get_function_source(method) h = asyncio.Handle(cb, (), self.loop) cb_regex = r'<function HandleTests.test_handle_repr .*>' cb_regex = (r'functools.partialmethod\(%s, , \)\(\)' % cb_regex) regex = (r'^<Handle %s at %s:%s>$' % (cb_regex, re.escape(filename), lineno)) self.assertRegex(repr(h), regex) def test_handle_repr_debug(self): self.loop.get_debug.return_value = True # simple function create_filename = __file__ create_lineno = sys._getframe().f_lineno + 1 h = asyncio.Handle(noop, (1, 2), self.loop) filename, lineno = test_utils.get_function_source(noop) self.assertEqual(repr(h), '<Handle noop(1, 2) at %s:%s created at %s:%s>' % (filename, lineno, create_filename, create_lineno)) # cancelled handle h.cancel() self.assertEqual( repr(h), '<Handle cancelled noop(1, 2) at %s:%s created at %s:%s>' % (filename, lineno, create_filename, create_lineno)) # double cancellation won't overwrite _repr h.cancel() self.assertEqual( repr(h), '<Handle cancelled noop(1, 2) at %s:%s created at %s:%s>' % (filename, lineno, create_filename, create_lineno)) def test_handle_source_traceback(self): loop = asyncio.get_event_loop_policy().new_event_loop() loop.set_debug(True) self.set_event_loop(loop) def check_source_traceback(h): lineno = sys._getframe(1).f_lineno - 1 self.assertIsInstance(h._source_traceback, list) self.assertEqual(h._source_traceback[-1][:3], (__file__, lineno, 'test_handle_source_traceback')) # call_soon h = loop.call_soon(noop) check_source_traceback(h) # call_soon_threadsafe h = loop.call_soon_threadsafe(noop) check_source_traceback(h) # call_later h = loop.call_later(0, noop) check_source_traceback(h) # call_at h = loop.call_later(0, noop) check_source_traceback(h) @unittest.skipUnless(hasattr(collections.abc, 'Coroutine'), 'No collections.abc.Coroutine') def test_coroutine_like_object_debug_formatting(self): # Test that asyncio can format coroutines that are instances of # collections.abc.Coroutine, but lack cr_core or gi_code attributes # (such as ones compiled with Cython). class Coro: def send(self, v): pass def throw(self, *exc): pass def close(self): pass def __await__(self): pass coro = Coro() coro.__name__ = 'AAA' self.assertTrue(asyncio.iscoroutine(coro)) self.assertEqual(coroutines._format_coroutine(coro), 'AAA()') coro.__qualname__ = 'BBB' self.assertEqual(coroutines._format_coroutine(coro), 'BBB()') coro.cr_running = True self.assertEqual(coroutines._format_coroutine(coro), 'BBB() running') coro = Coro() # Some coroutines might not have '__name__', such as # built-in async_gen.asend(). self.assertEqual(coroutines._format_coroutine(coro), 'Coro()') coro = Coro() coro.__qualname__ = 'AAA' coro.cr_code = None self.assertEqual(coroutines._format_coroutine(coro), 'AAA()') coro = Coro() coro.__qualname__ = 'AAA' coro.cr_code = None coro.cr_frame = None self.assertEqual(coroutines._format_coroutine(coro), 'AAA()') coro = Coro() coro.__qualname__ = None coro.cr_code = None coro.cr_frame = None self.assertEqual(coroutines._format_coroutine(coro), f'{repr(coro)}()') coro = Coro() coro.cr_code = None coro.cr_frame = None self.assertEqual(coroutines._format_coroutine(coro), f'{repr(coro)}()') class TimerTests(unittest.TestCase): def setUp(self): super().setUp() self.loop = mock.Mock() def test_hash(self): when = time.monotonic() h = asyncio.TimerHandle(when, lambda: False, (), mock.Mock()) self.assertEqual(hash(h), hash(when)) def test_timer(self): def callback(*args): return args args = (1, 2, 3) when = time.monotonic() h = asyncio.TimerHandle(when, callback, args, mock.Mock()) self.assertIs(h._callback, callback) self.assertIs(h._args, args) self.assertFalse(h._cancelled) # cancel h.cancel() self.assertTrue(h._cancelled) self.assertIsNone(h._callback) self.assertIsNone(h._args) # when cannot be None self.assertRaises(AssertionError, asyncio.TimerHandle, None, callback, args, self.loop) def test_timer_repr(self): self.loop.get_debug.return_value = False # simple function h = asyncio.TimerHandle(123, noop, (), self.loop) src = test_utils.get_function_source(noop) self.assertEqual(repr(h), '<TimerHandle when=123 noop() at %s:%s>' % src) # cancelled handle h.cancel() self.assertEqual(repr(h), '<TimerHandle cancelled when=123>') def test_timer_repr_debug(self): self.loop.get_debug.return_value = True # simple function create_filename = __file__ create_lineno = sys._getframe().f_lineno + 1 h = asyncio.TimerHandle(123, noop, (), self.loop) filename, lineno = test_utils.get_function_source(noop) self.assertEqual(repr(h), '<TimerHandle when=123 noop() ' 'at %s:%s created at %s:%s>' % (filename, lineno, create_filename, create_lineno)) # cancelled handle h.cancel() self.assertEqual(repr(h), '<TimerHandle cancelled when=123 noop() ' 'at %s:%s created at %s:%s>' % (filename, lineno, create_filename, create_lineno)) def test_timer_comparison(self): def callback(*args): return args when = time.monotonic() h1 = asyncio.TimerHandle(when, callback, (), self.loop) h2 = asyncio.TimerHandle(when, callback, (), self.loop) # TODO: Use assertLess etc. self.assertFalse(h1 < h2) self.assertFalse(h2 < h1) self.assertTrue(h1 <= h2) self.assertTrue(h2 <= h1) self.assertFalse(h1 > h2) self.assertFalse(h2 > h1) self.assertTrue(h1 >= h2) self.assertTrue(h2 >= h1) self.assertTrue(h1 == h2) self.assertFalse(h1 != h2) h2.cancel() self.assertFalse(h1 == h2) h1 = asyncio.TimerHandle(when, callback, (), self.loop) h2 = asyncio.TimerHandle(when + 10.0, callback, (), self.loop) self.assertTrue(h1 < h2) self.assertFalse(h2 < h1) self.assertTrue(h1 <= h2) self.assertFalse(h2 <= h1) self.assertFalse(h1 > h2) self.assertTrue(h2 > h1) self.assertFalse(h1 >= h2) self.assertTrue(h2 >= h1) self.assertFalse(h1 == h2) self.assertTrue(h1 != h2) h3 = asyncio.Handle(callback, (), self.loop) self.assertIs(NotImplemented, h1.__eq__(h3)) self.assertIs(NotImplemented, h1.__ne__(h3)) class AbstractEventLoopTests(unittest.TestCase): def test_not_implemented(self): f = mock.Mock() loop = asyncio.AbstractEventLoop() self.assertRaises( NotImplementedError, loop.run_forever) self.assertRaises( NotImplementedError, loop.run_until_complete, None) self.assertRaises( NotImplementedError, loop.stop) self.assertRaises( NotImplementedError, loop.is_running) self.assertRaises( NotImplementedError, loop.is_closed) self.assertRaises( NotImplementedError, loop.close) self.assertRaises( NotImplementedError, loop.create_task, None) self.assertRaises( NotImplementedError, loop.call_later, None, None) self.assertRaises( NotImplementedError, loop.call_at, f, f) self.assertRaises( NotImplementedError, loop.call_soon, None) self.assertRaises( NotImplementedError, loop.time) self.assertRaises( NotImplementedError, loop.call_soon_threadsafe, None) self.assertRaises( NotImplementedError, loop.run_in_executor, f, f) self.assertRaises( NotImplementedError, loop.set_default_executor, f) self.assertRaises( NotImplementedError, loop.getaddrinfo, 'localhost', 8080) self.assertRaises( NotImplementedError, loop.getnameinfo, ('localhost', 8080)) self.assertRaises( NotImplementedError, loop.create_connection, f) self.assertRaises( NotImplementedError, loop.create_server, f) self.assertRaises( NotImplementedError, loop.create_datagram_endpoint, f) self.assertRaises( NotImplementedError, loop.add_reader, 1, f) self.assertRaises( NotImplementedError, loop.remove_reader, 1) self.assertRaises( NotImplementedError, loop.add_writer, 1, f) self.assertRaises( NotImplementedError, loop.remove_writer, 1) self.assertRaises( NotImplementedError, loop.sock_recv, f, 10) self.assertRaises( NotImplementedError, loop.sock_sendall, f, 10) self.assertRaises( NotImplementedError, loop.sock_connect, f, f) self.assertRaises( NotImplementedError, loop.sock_accept, f) self.assertRaises( NotImplementedError, loop.add_signal_handler, 1, f) self.assertRaises( NotImplementedError, loop.remove_signal_handler, 1) self.assertRaises( NotImplementedError, loop.remove_signal_handler, 1) self.assertRaises( NotImplementedError, loop.connect_read_pipe, f, mock.sentinel.pipe) self.assertRaises( NotImplementedError, loop.connect_write_pipe, f, mock.sentinel.pipe) self.assertRaises( NotImplementedError, loop.subprocess_shell, f, mock.sentinel) self.assertRaises( NotImplementedError, loop.subprocess_exec, f) self.assertRaises( NotImplementedError, loop.set_exception_handler, f) self.assertRaises( NotImplementedError, loop.default_exception_handler, f) self.assertRaises( NotImplementedError, loop.call_exception_handler, f) self.assertRaises( NotImplementedError, loop.get_debug) self.assertRaises( NotImplementedError, loop.set_debug, f) class ProtocolsAbsTests(unittest.TestCase): def test_empty(self): f = mock.Mock() p = asyncio.Protocol() self.assertIsNone(p.connection_made(f)) self.assertIsNone(p.connection_lost(f)) self.assertIsNone(p.data_received(f)) self.assertIsNone(p.eof_received()) dp = asyncio.DatagramProtocol() self.assertIsNone(dp.connection_made(f)) self.assertIsNone(dp.connection_lost(f)) self.assertIsNone(dp.error_received(f)) self.assertIsNone(dp.datagram_received(f, f)) sp = asyncio.SubprocessProtocol() self.assertIsNone(sp.connection_made(f)) self.assertIsNone(sp.connection_lost(f)) self.assertIsNone(sp.pipe_data_received(1, f)) self.assertIsNone(sp.pipe_connection_lost(1, f)) self.assertIsNone(sp.process_exited()) class PolicyTests(unittest.TestCase): def test_event_loop_policy(self): policy = asyncio.AbstractEventLoopPolicy() self.assertRaises(NotImplementedError, policy.get_event_loop) self.assertRaises(NotImplementedError, policy.set_event_loop, object()) self.assertRaises(NotImplementedError, policy.new_event_loop) self.assertRaises(NotImplementedError, policy.get_child_watcher) self.assertRaises(NotImplementedError, policy.set_child_watcher, object()) def test_get_event_loop(self): policy = asyncio.DefaultEventLoopPolicy() self.assertIsNone(policy._local._loop) loop = policy.get_event_loop() self.assertIsInstance(loop, asyncio.AbstractEventLoop) self.assertIs(policy._local._loop, loop) self.assertIs(loop, policy.get_event_loop()) loop.close() def test_get_event_loop_calls_set_event_loop(self): policy = asyncio.DefaultEventLoopPolicy() with mock.patch.object( policy, "set_event_loop", wraps=policy.set_event_loop) as m_set_event_loop: loop = policy.get_event_loop() # policy._local._loop must be set through .set_event_loop() # (the unix DefaultEventLoopPolicy needs this call to attach # the child watcher correctly) m_set_event_loop.assert_called_with(loop) loop.close() def test_get_event_loop_after_set_none(self): policy = asyncio.DefaultEventLoopPolicy() policy.set_event_loop(None) self.assertRaises(RuntimeError, policy.get_event_loop) @mock.patch('asyncio.events.threading.current_thread') def test_get_event_loop_thread(self, m_current_thread): def f(): policy = asyncio.DefaultEventLoopPolicy() self.assertRaises(RuntimeError, policy.get_event_loop) th = threading.Thread(target=f) th.start() th.join() def test_new_event_loop(self): policy = asyncio.DefaultEventLoopPolicy() loop = policy.new_event_loop() self.assertIsInstance(loop, asyncio.AbstractEventLoop) loop.close() def test_set_event_loop(self): policy = asyncio.DefaultEventLoopPolicy() old_loop = policy.get_event_loop() self.assertRaises(AssertionError, policy.set_event_loop, object()) loop = policy.new_event_loop() policy.set_event_loop(loop) self.assertIs(loop, policy.get_event_loop()) self.assertIsNot(old_loop, policy.get_event_loop()) loop.close() old_loop.close() def test_get_event_loop_policy(self): policy = asyncio.get_event_loop_policy() self.assertIsInstance(policy, asyncio.AbstractEventLoopPolicy) self.assertIs(policy, asyncio.get_event_loop_policy()) def test_set_event_loop_policy(self): self.assertRaises( AssertionError, asyncio.set_event_loop_policy, object()) old_policy = asyncio.get_event_loop_policy() policy = asyncio.DefaultEventLoopPolicy() asyncio.set_event_loop_policy(policy) self.assertIs(policy, asyncio.get_event_loop_policy()) self.assertIsNot(policy, old_policy) def test_get_event_loop_returns_running_loop(self): class Policy(asyncio.DefaultEventLoopPolicy): def get_event_loop(self): raise NotImplementedError loop = None old_policy = asyncio.get_event_loop_policy() try: asyncio.set_event_loop_policy(Policy()) loop = asyncio.new_event_loop() self.assertIs(asyncio._get_running_loop(), None) async def func(): self.assertIs(asyncio.get_event_loop(), loop) self.assertIs(asyncio._get_running_loop(), loop) loop.run_until_complete(func()) finally: asyncio.set_event_loop_policy(old_policy) if loop is not None: loop.close() self.assertIs(asyncio._get_running_loop(), None) if __name__ == '__main__': unittest.main()
104,975
2,833
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_asyncio/test_futures.py
"""Tests for futures.py.""" import concurrent.futures import gc import re import sys import threading import unittest from unittest import mock import asyncio from asyncio import test_utils from asyncio import futures try: from test import support except ImportError: from asyncio import test_support as support def _fakefunc(f): return f def first_cb(): pass def last_cb(): pass class DuckFuture: # Class that does not inherit from Future but aims to be duck-type # compatible with it. _asyncio_future_blocking = False __cancelled = False __result = None __exception = None def cancel(self): if self.done(): return False self.__cancelled = True return True def cancelled(self): return self.__cancelled def done(self): return (self.__cancelled or self.__result is not None or self.__exception is not None) def result(self): assert not self.cancelled() if self.__exception is not None: raise self.__exception return self.__result def exception(self): assert not self.cancelled() return self.__exception def set_result(self, result): assert not self.done() assert result is not None self.__result = result def set_exception(self, exception): assert not self.done() assert exception is not None self.__exception = exception def __iter__(self): if not self.done(): self._asyncio_future_blocking = True yield self assert self.done() return self.result() class DuckTests(test_utils.TestCase): def setUp(self): super().setUp() self.loop = self.new_test_loop() self.addCleanup(self.loop.close) def test_wrap_future(self): f = DuckFuture() g = asyncio.wrap_future(f) assert g is f def test_ensure_future(self): f = DuckFuture() g = asyncio.ensure_future(f) assert g is f class BaseFutureTests: def _new_future(self, *args, **kwargs): return self.cls(*args, **kwargs) def setUp(self): super().setUp() self.loop = self.new_test_loop() self.addCleanup(self.loop.close) def test_isfuture(self): class MyFuture: _asyncio_future_blocking = None def __init__(self): self._asyncio_future_blocking = False self.assertFalse(asyncio.isfuture(MyFuture)) self.assertTrue(asyncio.isfuture(MyFuture())) self.assertFalse(asyncio.isfuture(1)) # As `isinstance(Mock(), Future)` returns `False` self.assertFalse(asyncio.isfuture(mock.Mock())) f = self._new_future(loop=self.loop) self.assertTrue(asyncio.isfuture(f)) self.assertFalse(asyncio.isfuture(type(f))) # As `isinstance(Mock(Future), Future)` returns `True` self.assertTrue(asyncio.isfuture(mock.Mock(type(f)))) f.cancel() def test_initial_state(self): f = self._new_future(loop=self.loop) self.assertFalse(f.cancelled()) self.assertFalse(f.done()) f.cancel() self.assertTrue(f.cancelled()) def test_init_constructor_default_loop(self): asyncio.set_event_loop(self.loop) f = self._new_future() self.assertIs(f._loop, self.loop) def test_constructor_positional(self): # Make sure Future doesn't accept a positional argument self.assertRaises(TypeError, self._new_future, 42) def test_uninitialized(self): fut = self.cls.__new__(self.cls, loop=self.loop) self.assertRaises(asyncio.InvalidStateError, fut.result) fut = self.cls.__new__(self.cls, loop=self.loop) self.assertRaises(asyncio.InvalidStateError, fut.exception) fut = self.cls.__new__(self.cls, loop=self.loop) with self.assertRaises((RuntimeError, AttributeError)): fut.set_result(None) fut = self.cls.__new__(self.cls, loop=self.loop) with self.assertRaises((RuntimeError, AttributeError)): fut.set_exception(Exception) fut = self.cls.__new__(self.cls, loop=self.loop) with self.assertRaises((RuntimeError, AttributeError)): fut.cancel() fut = self.cls.__new__(self.cls, loop=self.loop) with self.assertRaises((RuntimeError, AttributeError)): fut.add_done_callback(lambda f: None) fut = self.cls.__new__(self.cls, loop=self.loop) with self.assertRaises((RuntimeError, AttributeError)): fut.remove_done_callback(lambda f: None) fut = self.cls.__new__(self.cls, loop=self.loop) with self.assertRaises((RuntimeError, AttributeError)): fut._schedule_callbacks() fut = self.cls.__new__(self.cls, loop=self.loop) try: repr(fut) except AttributeError: pass fut = self.cls.__new__(self.cls, loop=self.loop) fut.cancelled() fut.done() iter(fut) def test_cancel(self): f = self._new_future(loop=self.loop) self.assertTrue(f.cancel()) self.assertTrue(f.cancelled()) self.assertTrue(f.done()) self.assertRaises(asyncio.CancelledError, f.result) self.assertRaises(asyncio.CancelledError, f.exception) self.assertRaises(asyncio.InvalidStateError, f.set_result, None) self.assertRaises(asyncio.InvalidStateError, f.set_exception, None) self.assertFalse(f.cancel()) def test_result(self): f = self._new_future(loop=self.loop) self.assertRaises(asyncio.InvalidStateError, f.result) f.set_result(42) self.assertFalse(f.cancelled()) self.assertTrue(f.done()) self.assertEqual(f.result(), 42) self.assertEqual(f.exception(), None) self.assertRaises(asyncio.InvalidStateError, f.set_result, None) self.assertRaises(asyncio.InvalidStateError, f.set_exception, None) self.assertFalse(f.cancel()) def test_exception(self): exc = RuntimeError() f = self._new_future(loop=self.loop) self.assertRaises(asyncio.InvalidStateError, f.exception) # StopIteration cannot be raised into a Future - CPython issue26221 self.assertRaisesRegex(TypeError, "StopIteration .* cannot be raised", f.set_exception, StopIteration) f.set_exception(exc) self.assertFalse(f.cancelled()) self.assertTrue(f.done()) self.assertRaises(RuntimeError, f.result) self.assertEqual(f.exception(), exc) self.assertRaises(asyncio.InvalidStateError, f.set_result, None) self.assertRaises(asyncio.InvalidStateError, f.set_exception, None) self.assertFalse(f.cancel()) def test_exception_class(self): f = self._new_future(loop=self.loop) f.set_exception(RuntimeError) self.assertIsInstance(f.exception(), RuntimeError) def test_yield_from_twice(self): f = self._new_future(loop=self.loop) def fixture(): yield 'A' x = yield from f yield 'B', x y = yield from f yield 'C', y g = fixture() self.assertEqual(next(g), 'A') # yield 'A'. self.assertEqual(next(g), f) # First yield from f. f.set_result(42) self.assertEqual(next(g), ('B', 42)) # yield 'B', x. # The second "yield from f" does not yield f. self.assertEqual(next(g), ('C', 42)) # yield 'C', y. def test_future_repr(self): self.loop.set_debug(True) f_pending_debug = self._new_future(loop=self.loop) frame = f_pending_debug._source_traceback[-1] self.assertEqual(repr(f_pending_debug), '<Future pending created at %s:%s>' % (frame[0], frame[1])) f_pending_debug.cancel() self.loop.set_debug(False) f_pending = self._new_future(loop=self.loop) self.assertEqual(repr(f_pending), '<Future pending>') f_pending.cancel() f_cancelled = self._new_future(loop=self.loop) f_cancelled.cancel() self.assertEqual(repr(f_cancelled), '<Future cancelled>') f_result = self._new_future(loop=self.loop) f_result.set_result(4) self.assertEqual(repr(f_result), '<Future finished result=4>') self.assertEqual(f_result.result(), 4) exc = RuntimeError() f_exception = self._new_future(loop=self.loop) f_exception.set_exception(exc) self.assertEqual(repr(f_exception), '<Future finished exception=RuntimeError()>') self.assertIs(f_exception.exception(), exc) def func_repr(func): filename, lineno = test_utils.get_function_source(func) text = '%s() at %s:%s' % (func.__qualname__, filename, lineno) return re.escape(text) f_one_callbacks = self._new_future(loop=self.loop) f_one_callbacks.add_done_callback(_fakefunc) fake_repr = func_repr(_fakefunc) self.assertRegex(repr(f_one_callbacks), r'<Future pending cb=\[%s\]>' % fake_repr) f_one_callbacks.cancel() self.assertEqual(repr(f_one_callbacks), '<Future cancelled>') f_two_callbacks = self._new_future(loop=self.loop) f_two_callbacks.add_done_callback(first_cb) f_two_callbacks.add_done_callback(last_cb) first_repr = func_repr(first_cb) last_repr = func_repr(last_cb) self.assertRegex(repr(f_two_callbacks), r'<Future pending cb=\[%s, %s\]>' % (first_repr, last_repr)) f_many_callbacks = self._new_future(loop=self.loop) f_many_callbacks.add_done_callback(first_cb) for i in range(8): f_many_callbacks.add_done_callback(_fakefunc) f_many_callbacks.add_done_callback(last_cb) cb_regex = r'%s, <8 more>, %s' % (first_repr, last_repr) self.assertRegex(repr(f_many_callbacks), r'<Future pending cb=\[%s\]>' % cb_regex) f_many_callbacks.cancel() self.assertEqual(repr(f_many_callbacks), '<Future cancelled>') def test_copy_state(self): from asyncio.futures import _copy_future_state f = self._new_future(loop=self.loop) f.set_result(10) newf = self._new_future(loop=self.loop) _copy_future_state(f, newf) self.assertTrue(newf.done()) self.assertEqual(newf.result(), 10) f_exception = self._new_future(loop=self.loop) f_exception.set_exception(RuntimeError()) newf_exception = self._new_future(loop=self.loop) _copy_future_state(f_exception, newf_exception) self.assertTrue(newf_exception.done()) self.assertRaises(RuntimeError, newf_exception.result) f_cancelled = self._new_future(loop=self.loop) f_cancelled.cancel() newf_cancelled = self._new_future(loop=self.loop) _copy_future_state(f_cancelled, newf_cancelled) self.assertTrue(newf_cancelled.cancelled()) def test_iter(self): fut = self._new_future(loop=self.loop) def coro(): yield from fut def test(): arg1, arg2 = coro() self.assertRaises(AssertionError, test) fut.cancel() @mock.patch('asyncio.base_events.logger') def test_tb_logger_abandoned(self, m_log): fut = self._new_future(loop=self.loop) del fut self.assertFalse(m_log.error.called) @mock.patch('asyncio.base_events.logger') def test_tb_logger_not_called_after_cancel(self, m_log): fut = self._new_future(loop=self.loop) fut.set_exception(Exception()) fut.cancel() del fut self.assertFalse(m_log.error.called) @mock.patch('asyncio.base_events.logger') def test_tb_logger_result_unretrieved(self, m_log): fut = self._new_future(loop=self.loop) fut.set_result(42) del fut self.assertFalse(m_log.error.called) @mock.patch('asyncio.base_events.logger') def test_tb_logger_result_retrieved(self, m_log): fut = self._new_future(loop=self.loop) fut.set_result(42) fut.result() del fut self.assertFalse(m_log.error.called) @mock.patch('asyncio.base_events.logger') def test_tb_logger_exception_unretrieved(self, m_log): fut = self._new_future(loop=self.loop) fut.set_exception(RuntimeError('boom')) del fut test_utils.run_briefly(self.loop) support.gc_collect() self.assertTrue(m_log.error.called) @mock.patch('asyncio.base_events.logger') def test_tb_logger_exception_retrieved(self, m_log): fut = self._new_future(loop=self.loop) fut.set_exception(RuntimeError('boom')) fut.exception() del fut self.assertFalse(m_log.error.called) @mock.patch('asyncio.base_events.logger') def test_tb_logger_exception_result_retrieved(self, m_log): fut = self._new_future(loop=self.loop) fut.set_exception(RuntimeError('boom')) self.assertRaises(RuntimeError, fut.result) del fut self.assertFalse(m_log.error.called) def test_wrap_future(self): def run(arg): return (arg, threading.get_ident()) ex = concurrent.futures.ThreadPoolExecutor(1) f1 = ex.submit(run, 'oi') f2 = asyncio.wrap_future(f1, loop=self.loop) res, ident = self.loop.run_until_complete(f2) self.assertTrue(asyncio.isfuture(f2)) self.assertEqual(res, 'oi') self.assertNotEqual(ident, threading.get_ident()) ex.shutdown(wait=True) def test_wrap_future_future(self): f1 = self._new_future(loop=self.loop) f2 = asyncio.wrap_future(f1) self.assertIs(f1, f2) def test_wrap_future_use_global_loop(self): with mock.patch('asyncio.futures.events') as events: events.get_event_loop = lambda: self.loop def run(arg): return (arg, threading.get_ident()) ex = concurrent.futures.ThreadPoolExecutor(1) f1 = ex.submit(run, 'oi') f2 = asyncio.wrap_future(f1) self.assertIs(self.loop, f2._loop) ex.shutdown(wait=True) def test_wrap_future_cancel(self): f1 = concurrent.futures.Future() f2 = asyncio.wrap_future(f1, loop=self.loop) f2.cancel() test_utils.run_briefly(self.loop) self.assertTrue(f1.cancelled()) self.assertTrue(f2.cancelled()) def test_wrap_future_cancel2(self): f1 = concurrent.futures.Future() f2 = asyncio.wrap_future(f1, loop=self.loop) f1.set_result(42) f2.cancel() test_utils.run_briefly(self.loop) self.assertFalse(f1.cancelled()) self.assertEqual(f1.result(), 42) self.assertTrue(f2.cancelled()) def test_future_source_traceback(self): self.loop.set_debug(True) future = self._new_future(loop=self.loop) lineno = sys._getframe().f_lineno - 1 self.assertIsInstance(future._source_traceback, list) self.assertEqual(future._source_traceback[-2][:3], (__file__, lineno, 'test_future_source_traceback')) @mock.patch('asyncio.base_events.logger') def check_future_exception_never_retrieved(self, debug, m_log): self.loop.set_debug(debug) def memory_error(): try: raise MemoryError() except BaseException as exc: return exc exc = memory_error() future = self._new_future(loop=self.loop) future.set_exception(exc) future = None test_utils.run_briefly(self.loop) support.gc_collect() if sys.version_info >= (3, 4): regex = r'^Future exception was never retrieved\n' exc_info = (type(exc), exc, exc.__traceback__) m_log.error.assert_called_once_with(mock.ANY, exc_info=exc_info) else: regex = r'^Future/Task exception was never retrieved\n' m_log.error.assert_called_once_with(mock.ANY, exc_info=False) message = m_log.error.call_args[0][0] self.assertRegex(message, re.compile(regex, re.DOTALL)) def test_future_exception_never_retrieved(self): self.check_future_exception_never_retrieved(False) def test_future_exception_never_retrieved_debug(self): self.check_future_exception_never_retrieved(True) def test_set_result_unless_cancelled(self): fut = self._new_future(loop=self.loop) fut.cancel() futures._set_result_unless_cancelled(fut, 2) self.assertTrue(fut.cancelled()) def test_future_stop_iteration_args(self): fut = self._new_future(loop=self.loop) fut.set_result((1, 2)) fi = fut.__iter__() result = None try: fi.send(None) except StopIteration as ex: result = ex.args[0] else: self.fail('StopIteration was expected') self.assertEqual(result, (1, 2)) def test_future_iter_throw(self): fut = self._new_future(loop=self.loop) fi = iter(fut) self.assertRaises(TypeError, fi.throw, Exception, Exception("elephant"), 32) self.assertRaises(TypeError, fi.throw, Exception("elephant"), Exception("elephant")) self.assertRaises(TypeError, fi.throw, list) def test_future_del_collect(self): class Evil: def __del__(self): gc.collect() for i in range(100): fut = self._new_future(loop=self.loop) fut.set_result(Evil()) @unittest.skipUnless(hasattr(futures, '_CFuture'), 'requires the C _asyncio module') class CFutureTests(BaseFutureTests, test_utils.TestCase): cls = getattr(futures, '_CFuture') class PyFutureTests(BaseFutureTests, test_utils.TestCase): cls = futures._PyFuture class BaseFutureDoneCallbackTests(): def setUp(self): super().setUp() self.loop = self.new_test_loop() def run_briefly(self): test_utils.run_briefly(self.loop) def _make_callback(self, bag, thing): # Create a callback function that appends thing to bag. def bag_appender(future): bag.append(thing) return bag_appender def _new_future(self): raise NotImplementedError def test_callbacks_invoked_on_set_result(self): bag = [] f = self._new_future() f.add_done_callback(self._make_callback(bag, 42)) f.add_done_callback(self._make_callback(bag, 17)) self.assertEqual(bag, []) f.set_result('foo') self.run_briefly() self.assertEqual(bag, [42, 17]) self.assertEqual(f.result(), 'foo') def test_callbacks_invoked_on_set_exception(self): bag = [] f = self._new_future() f.add_done_callback(self._make_callback(bag, 100)) self.assertEqual(bag, []) exc = RuntimeError() f.set_exception(exc) self.run_briefly() self.assertEqual(bag, [100]) self.assertEqual(f.exception(), exc) def test_remove_done_callback(self): bag = [] f = self._new_future() cb1 = self._make_callback(bag, 1) cb2 = self._make_callback(bag, 2) cb3 = self._make_callback(bag, 3) # Add one cb1 and one cb2. f.add_done_callback(cb1) f.add_done_callback(cb2) # One instance of cb2 removed. Now there's only one cb1. self.assertEqual(f.remove_done_callback(cb2), 1) # Never had any cb3 in there. self.assertEqual(f.remove_done_callback(cb3), 0) # After this there will be 6 instances of cb1 and one of cb2. f.add_done_callback(cb2) for i in range(5): f.add_done_callback(cb1) # Remove all instances of cb1. One cb2 remains. self.assertEqual(f.remove_done_callback(cb1), 6) self.assertEqual(bag, []) f.set_result('foo') self.run_briefly() self.assertEqual(bag, [2]) self.assertEqual(f.result(), 'foo') def test_remove_done_callbacks_list_mutation(self): # see http://bugs.python.org/issue28963 for details fut = self._new_future() fut.add_done_callback(str) for _ in range(63): fut.add_done_callback(id) class evil: def __eq__(self, other): fut.remove_done_callback(id) return False fut.remove_done_callback(evil()) def test_schedule_callbacks_list_mutation_1(self): # see http://bugs.python.org/issue28963 for details def mut(f): f.remove_done_callback(str) fut = self._new_future() fut.add_done_callback(mut) fut.add_done_callback(str) fut.add_done_callback(str) fut.set_result(1) test_utils.run_briefly(self.loop) def test_schedule_callbacks_list_mutation_2(self): # see http://bugs.python.org/issue30828 for details fut = self._new_future() fut.add_done_callback(str) for _ in range(63): fut.add_done_callback(id) max_extra_cbs = 100 extra_cbs = 0 class evil: def __eq__(self, other): nonlocal extra_cbs extra_cbs += 1 if extra_cbs < max_extra_cbs: fut.add_done_callback(id) return False fut.remove_done_callback(evil()) @unittest.skipUnless(hasattr(futures, '_CFuture'), 'requires the C _asyncio module') class CFutureDoneCallbackTests(BaseFutureDoneCallbackTests, test_utils.TestCase): def _new_future(self): return futures._CFuture(loop=self.loop) class PyFutureDoneCallbackTests(BaseFutureDoneCallbackTests, test_utils.TestCase): def _new_future(self): return futures._PyFuture(loop=self.loop) if __name__ == '__main__': unittest.main()
22,511
693
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_asyncio/__init__.py
import os from test.support import load_package_tests, import_module # Skip tests if we don't have threading. import_module('threading') # Skip tests if we don't have concurrent.futures. import_module('concurrent.futures') def load_tests(*args): return load_package_tests(os.path.dirname(__file__), *args)
312
11
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_asyncio/echo3.py
import os if __name__ == '__main__': while True: buf = os.read(0, 1024) if not buf: break try: os.write(1, b'OUT:'+buf) except OSError as ex: os.write(2, b'ERR:' + ex.__class__.__name__.encode('ascii'))
276
12
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/encoded_modules/module_iso_8859_1.py
# test iso-8859-1 encoding # -*- encoding: iso-8859-1 -*- test = ("Les hommes ont oublié cette vérité, " "dit le renard. Mais tu ne dois pas l'oublier. Tu deviens " "responsable pour toujours de ce que tu as apprivoisé.")
238
6
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/encoded_modules/module_koi8_r.py
# test koi8-r encoding # -*- encoding: koi8-r -*- test = "ðÏÚÎÁÎÉÅ ÂÅÓËÏÎÅÞÎÏÓÔÉ ÔÒÅÂÕÅÔ ÂÅÓËÏÎÅÞÎÏÇÏ ×ÒÅÍÅÎÉ."
113
4
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/encoded_modules/__init__.py
# -*- encoding: utf-8 -*- # This is a package that contains a number of modules that are used to # test import from the source files that have different encodings. # This file (the __init__ module of the package), is encoded in utf-8 # and contains a list of strings from various unicode planes that are # encoded differently to compare them to the same strings encoded # differently in submodules. The following list, test_strings, # contains a list of tuples. The first element of each tuple is the # suffix that should be prepended with 'module_' to arrive at the # encoded submodule name, the second item is the encoding and the last # is the test string. The same string is assigned to the variable # named 'test' inside the submodule. If the decoding of modules works # correctly, from module_xyz import test should result in the same # string as listed below in the 'xyz' entry. # module, encoding, test string test_strings = ( ('iso_8859_1', 'iso-8859-1', "Les hommes ont oublié cette vérité, " "dit le renard. Mais tu ne dois pas l'oublier. Tu deviens " "responsable pour toujours de ce que tu as apprivoisé."), ('koi8_r', 'koi8-r', "Познание бесконечности требует бесконечного времени.") )
1,274
24
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/leakers/README.txt
This directory contains test cases that are known to leak references. The idea is that you can import these modules while in the interpreter and call the leak function repeatedly. This will only be helpful if the interpreter was built in debug mode. If the total ref count doesn't increase, the bug has been fixed and the file should be removed from the repository. Note: be careful to check for cyclic garbage. Sometimes it may be helpful to define the leak function like: def leak(): def inner_leak(): # this is the function that leaks, but also creates cycles inner_leak() gc.collect() ; gc.collect() ; gc.collect() Here's an example interpreter session for test_gestalt which still leaks: >>> from test.leakers.test_gestalt import leak [24275 refs] >>> leak() [28936 refs] >>> leak() [28938 refs] >>> leak() [28940 refs] >>> Once the leak is fixed, the test case should be moved into an appropriate test (even if it was originally from the test suite). This ensures the regression doesn't happen again. And if it does, it should be easier to track down.
1,090
33
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/leakers/test_selftype.py
# Reference cycles involving only the ob_type field are rather uncommon # but possible. Inspired by SF bug 1469629. import gc def leak(): class T(type): pass class U(type, metaclass=T): pass U.__class__ = U del U gc.collect(); gc.collect(); gc.collect()
293
14
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/leakers/test_ctypes.py
# Taken from Lib/ctypes/test/test_keeprefs.py, PointerToStructure.test(). from ctypes import Structure, c_int, POINTER import gc def leak_inner(): class POINT(Structure): _fields_ = [("x", c_int)] class RECT(Structure): _fields_ = [("a", POINTER(POINT))] def leak(): leak_inner() gc.collect()
329
16
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/leakers/__init__.py
0
1
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_warnings/__main__.py
import unittest unittest.main('test.test_warnings')
53
4
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_warnings/__init__.py
from contextlib import contextmanager import linecache import os import cosmo from io import StringIO import re import sys import textwrap import unittest from test import support from test.support.script_helper import assert_python_ok, assert_python_failure from test.test_warnings.data import stacklevel as warning_tests import warnings as original_warnings py_warnings = support.import_fresh_module('warnings', blocked=['_warnings']) c_warnings = support.import_fresh_module('warnings', fresh=['_warnings']) @contextmanager def warnings_state(module): """Use a specific warnings implementation in warning_tests.""" global __warningregistry__ for to_clear in (sys, warning_tests): try: to_clear.__warningregistry__.clear() except AttributeError: pass try: __warningregistry__.clear() except NameError: pass original_warnings = warning_tests.warnings original_filters = module.filters try: module.filters = original_filters[:] module.simplefilter("once") warning_tests.warnings = module yield finally: warning_tests.warnings = original_warnings module.filters = original_filters class BaseTest: """Basic bookkeeping required for testing.""" def setUp(self): self.old_unittest_module = unittest.case.warnings # The __warningregistry__ needs to be in a pristine state for tests # to work properly. if '__warningregistry__' in globals(): del globals()['__warningregistry__'] if hasattr(warning_tests, '__warningregistry__'): del warning_tests.__warningregistry__ if hasattr(sys, '__warningregistry__'): del sys.__warningregistry__ # The 'warnings' module must be explicitly set so that the proper # interaction between _warnings and 'warnings' can be controlled. sys.modules['warnings'] = self.module # Ensure that unittest.TestCase.assertWarns() uses the same warnings # module than warnings.catch_warnings(). Otherwise, # warnings.catch_warnings() will be unable to remove the added filter. unittest.case.warnings = self.module super(BaseTest, self).setUp() def tearDown(self): sys.modules['warnings'] = original_warnings unittest.case.warnings = self.old_unittest_module super(BaseTest, self).tearDown() class PublicAPITests(BaseTest): """Ensures that the correct values are exposed in the public API. """ def test_module_all_attribute(self): self.assertTrue(hasattr(self.module, '__all__')) target_api = ["warn", "warn_explicit", "showwarning", "formatwarning", "filterwarnings", "simplefilter", "resetwarnings", "catch_warnings"] self.assertSetEqual(set(self.module.__all__), set(target_api)) class CPublicAPITests(PublicAPITests, unittest.TestCase): module = c_warnings class PyPublicAPITests(PublicAPITests, unittest.TestCase): module = py_warnings class FilterTests(BaseTest): """Testing the filtering functionality.""" def test_error(self): with original_warnings.catch_warnings(module=self.module) as w: self.module.resetwarnings() self.module.filterwarnings("error", category=UserWarning) self.assertRaises(UserWarning, self.module.warn, "FilterTests.test_error") def test_error_after_default(self): with original_warnings.catch_warnings(module=self.module) as w: self.module.resetwarnings() message = "FilterTests.test_ignore_after_default" def f(): self.module.warn(message, UserWarning) with support.captured_stderr() as stderr: f() stderr = stderr.getvalue() self.assertIn("UserWarning: FilterTests.test_ignore_after_default", stderr) self.assertIn("self.module.warn(message, UserWarning)", stderr) self.module.filterwarnings("error", category=UserWarning) self.assertRaises(UserWarning, f) def test_ignore(self): with original_warnings.catch_warnings(record=True, module=self.module) as w: self.module.resetwarnings() self.module.filterwarnings("ignore", category=UserWarning) self.module.warn("FilterTests.test_ignore", UserWarning) self.assertEqual(len(w), 0) def test_ignore_after_default(self): with original_warnings.catch_warnings(record=True, module=self.module) as w: self.module.resetwarnings() message = "FilterTests.test_ignore_after_default" def f(): self.module.warn(message, UserWarning) f() self.module.filterwarnings("ignore", category=UserWarning) f() f() self.assertEqual(len(w), 1) def test_always(self): with original_warnings.catch_warnings(record=True, module=self.module) as w: self.module.resetwarnings() self.module.filterwarnings("always", category=UserWarning) message = "FilterTests.test_always" def f(): self.module.warn(message, UserWarning) f() self.assertEqual(len(w), 1) self.assertEqual(w[-1].message.args[0], message) f() self.assertEqual(len(w), 2) self.assertEqual(w[-1].message.args[0], message) def test_always_after_default(self): with original_warnings.catch_warnings(record=True, module=self.module) as w: self.module.resetwarnings() message = "FilterTests.test_always_after_ignore" def f(): self.module.warn(message, UserWarning) f() self.assertEqual(len(w), 1) self.assertEqual(w[-1].message.args[0], message) f() self.assertEqual(len(w), 1) self.module.filterwarnings("always", category=UserWarning) f() self.assertEqual(len(w), 2) self.assertEqual(w[-1].message.args[0], message) f() self.assertEqual(len(w), 3) self.assertEqual(w[-1].message.args[0], message) def test_default(self): with original_warnings.catch_warnings(record=True, module=self.module) as w: self.module.resetwarnings() self.module.filterwarnings("default", category=UserWarning) message = UserWarning("FilterTests.test_default") for x in range(2): self.module.warn(message, UserWarning) if x == 0: self.assertEqual(w[-1].message, message) del w[:] elif x == 1: self.assertEqual(len(w), 0) else: raise ValueError("loop variant unhandled") def test_module(self): with original_warnings.catch_warnings(record=True, module=self.module) as w: self.module.resetwarnings() self.module.filterwarnings("module", category=UserWarning) message = UserWarning("FilterTests.test_module") self.module.warn(message, UserWarning) self.assertEqual(w[-1].message, message) del w[:] self.module.warn(message, UserWarning) self.assertEqual(len(w), 0) def test_once(self): with original_warnings.catch_warnings(record=True, module=self.module) as w: self.module.resetwarnings() self.module.filterwarnings("once", category=UserWarning) message = UserWarning("FilterTests.test_once") self.module.warn_explicit(message, UserWarning, "__init__.py", 42) self.assertEqual(w[-1].message, message) del w[:] self.module.warn_explicit(message, UserWarning, "__init__.py", 13) self.assertEqual(len(w), 0) self.module.warn_explicit(message, UserWarning, "test_warnings2.py", 42) self.assertEqual(len(w), 0) def test_inheritance(self): with original_warnings.catch_warnings(module=self.module) as w: self.module.resetwarnings() self.module.filterwarnings("error", category=Warning) self.assertRaises(UserWarning, self.module.warn, "FilterTests.test_inheritance", UserWarning) def test_ordering(self): with original_warnings.catch_warnings(record=True, module=self.module) as w: self.module.resetwarnings() self.module.filterwarnings("ignore", category=UserWarning) self.module.filterwarnings("error", category=UserWarning, append=True) del w[:] try: self.module.warn("FilterTests.test_ordering", UserWarning) except UserWarning: self.fail("order handling for actions failed") self.assertEqual(len(w), 0) def test_filterwarnings(self): # Test filterwarnings(). # Implicitly also tests resetwarnings(). with original_warnings.catch_warnings(record=True, module=self.module) as w: self.module.filterwarnings("error", "", Warning, "", 0) self.assertRaises(UserWarning, self.module.warn, 'convert to error') self.module.resetwarnings() text = 'handle normally' self.module.warn(text) self.assertEqual(str(w[-1].message), text) self.assertTrue(w[-1].category is UserWarning) self.module.filterwarnings("ignore", "", Warning, "", 0) text = 'filtered out' self.module.warn(text) self.assertNotEqual(str(w[-1].message), text) self.module.resetwarnings() self.module.filterwarnings("error", "hex*", Warning, "", 0) self.assertRaises(UserWarning, self.module.warn, 'hex/oct') text = 'nonmatching text' self.module.warn(text) self.assertEqual(str(w[-1].message), text) self.assertTrue(w[-1].category is UserWarning) def test_message_matching(self): with original_warnings.catch_warnings(record=True, module=self.module) as w: self.module.simplefilter("ignore", UserWarning) self.module.filterwarnings("error", "match", UserWarning) self.assertRaises(UserWarning, self.module.warn, "match") self.assertRaises(UserWarning, self.module.warn, "match prefix") self.module.warn("suffix match") self.assertEqual(w, []) self.module.warn("something completely different") self.assertEqual(w, []) def test_mutate_filter_list(self): class X: def match(self, a): L[:] = [] L = [("default",X(),UserWarning,X(),0) for i in range(2)] with original_warnings.catch_warnings(record=True, module=self.module) as w: self.module.filters = L self.module.warn_explicit(UserWarning("b"), None, "f.py", 42) self.assertEqual(str(w[-1].message), "b") def test_filterwarnings_duplicate_filters(self): with original_warnings.catch_warnings(module=self.module): self.module.resetwarnings() self.module.filterwarnings("error", category=UserWarning) self.assertEqual(len(self.module.filters), 1) self.module.filterwarnings("ignore", category=UserWarning) self.module.filterwarnings("error", category=UserWarning) self.assertEqual( len(self.module.filters), 2, "filterwarnings inserted duplicate filter" ) self.assertEqual( self.module.filters[0][0], "error", "filterwarnings did not promote filter to " "the beginning of list" ) def test_simplefilter_duplicate_filters(self): with original_warnings.catch_warnings(module=self.module): self.module.resetwarnings() self.module.simplefilter("error", category=UserWarning) self.assertEqual(len(self.module.filters), 1) self.module.simplefilter("ignore", category=UserWarning) self.module.simplefilter("error", category=UserWarning) self.assertEqual( len(self.module.filters), 2, "simplefilter inserted duplicate filter" ) self.assertEqual( self.module.filters[0][0], "error", "simplefilter did not promote filter to the beginning of list" ) def test_append_duplicate(self): with original_warnings.catch_warnings(module=self.module, record=True) as w: self.module.resetwarnings() self.module.simplefilter("ignore") self.module.simplefilter("error", append=True) self.module.simplefilter("ignore", append=True) self.module.warn("test_append_duplicate", category=UserWarning) self.assertEqual(len(self.module.filters), 2, "simplefilter inserted duplicate filter" ) self.assertEqual(len(w), 0, "appended duplicate changed order of filters" ) class CFilterTests(FilterTests, unittest.TestCase): module = c_warnings class PyFilterTests(FilterTests, unittest.TestCase): module = py_warnings class WarnTests(BaseTest): """Test warnings.warn() and warnings.warn_explicit().""" def test_message(self): with original_warnings.catch_warnings(record=True, module=self.module) as w: self.module.simplefilter("once") for i in range(4): text = 'multi %d' %i # Different text on each call. self.module.warn(text) self.assertEqual(str(w[-1].message), text) self.assertTrue(w[-1].category is UserWarning) # Issue 3639 def test_warn_nonstandard_types(self): # warn() should handle non-standard types without issue. for ob in (Warning, None, 42): with original_warnings.catch_warnings(record=True, module=self.module) as w: self.module.simplefilter("once") self.module.warn(ob) # Don't directly compare objects since # ``Warning() != Warning()``. self.assertEqual(str(w[-1].message), str(UserWarning(ob))) def test_filename(self): with warnings_state(self.module): with original_warnings.catch_warnings(record=True, module=self.module) as w: warning_tests.inner("spam1") self.assertEqual(os.path.basename(w[-1].filename), "stacklevel.py") warning_tests.outer("spam2") self.assertEqual(os.path.basename(w[-1].filename), "stacklevel.py") def test_stacklevel(self): # Test stacklevel argument # make sure all messages are different, so the warning won't be skipped with warnings_state(self.module): with original_warnings.catch_warnings(record=True, module=self.module) as w: warning_tests.inner("spam3", stacklevel=1) self.assertEqual(os.path.basename(w[-1].filename), "stacklevel.py") warning_tests.outer("spam4", stacklevel=1) self.assertEqual(os.path.basename(w[-1].filename), "stacklevel.py") warning_tests.inner("spam5", stacklevel=2) self.assertEqual(os.path.basename(w[-1].filename), "__init__.py") warning_tests.outer("spam6", stacklevel=2) self.assertEqual(os.path.basename(w[-1].filename), "stacklevel.py") warning_tests.outer("spam6.5", stacklevel=3) self.assertEqual(os.path.basename(w[-1].filename), "__init__.py") warning_tests.inner("spam7", stacklevel=9999) self.assertEqual(os.path.basename(w[-1].filename), "sys") def test_stacklevel_import(self): # Issue #24305: With stacklevel=2, module-level warnings should work. support.unload('test.test_warnings.data.import_warning') with warnings_state(self.module): with original_warnings.catch_warnings(record=True, module=self.module) as w: self.module.simplefilter('always') import test.test_warnings.data.import_warning self.assertEqual(len(w), 1) self.assertEqual(w[0].filename, __file__) def test_missing_filename_not_main(self): # If __file__ is not specified and __main__ is not the module name, # then __file__ should be set to the module name. filename = warning_tests.__file__ try: del warning_tests.__file__ with warnings_state(self.module): with original_warnings.catch_warnings(record=True, module=self.module) as w: warning_tests.inner("spam8", stacklevel=1) self.assertEqual(w[-1].filename, warning_tests.__name__) finally: warning_tests.__file__ = filename @unittest.skipUnless(hasattr(sys, 'argv'), 'test needs sys.argv') def test_missing_filename_main_with_argv(self): # If __file__ is not specified and the caller is __main__ and sys.argv # exists, then use sys.argv[0] as the file. filename = warning_tests.__file__ module_name = warning_tests.__name__ try: del warning_tests.__file__ warning_tests.__name__ = '__main__' with warnings_state(self.module): with original_warnings.catch_warnings(record=True, module=self.module) as w: warning_tests.inner('spam9', stacklevel=1) self.assertEqual(w[-1].filename, sys.argv[0]) finally: warning_tests.__file__ = filename warning_tests.__name__ = module_name def test_missing_filename_main_without_argv(self): # If __file__ is not specified, the caller is __main__, and sys.argv # is not set, then '__main__' is the file name. filename = warning_tests.__file__ module_name = warning_tests.__name__ argv = sys.argv try: del warning_tests.__file__ warning_tests.__name__ = '__main__' del sys.argv with warnings_state(self.module): with original_warnings.catch_warnings(record=True, module=self.module) as w: warning_tests.inner('spam10', stacklevel=1) self.assertEqual(w[-1].filename, '__main__') finally: warning_tests.__file__ = filename warning_tests.__name__ = module_name sys.argv = argv def test_missing_filename_main_with_argv_empty_string(self): # If __file__ is not specified, the caller is __main__, and sys.argv[0] # is the empty string, then '__main__ is the file name. # Tests issue 2743. file_name = warning_tests.__file__ module_name = warning_tests.__name__ argv = sys.argv try: del warning_tests.__file__ warning_tests.__name__ = '__main__' sys.argv = [''] with warnings_state(self.module): with original_warnings.catch_warnings(record=True, module=self.module) as w: warning_tests.inner('spam11', stacklevel=1) self.assertEqual(w[-1].filename, '__main__') finally: warning_tests.__file__ = file_name warning_tests.__name__ = module_name sys.argv = argv def test_warn_explicit_non_ascii_filename(self): with original_warnings.catch_warnings(record=True, module=self.module) as w: self.module.resetwarnings() self.module.filterwarnings("always", category=UserWarning) for filename in ("nonascii\xe9\u20ac", "surrogate\udc80"): try: os.fsencode(filename) except UnicodeEncodeError: continue self.module.warn_explicit("text", UserWarning, filename, 1) self.assertEqual(w[-1].filename, filename) def test_warn_explicit_type_errors(self): # warn_explicit() should error out gracefully if it is given objects # of the wrong types. # lineno is expected to be an integer. self.assertRaises(TypeError, self.module.warn_explicit, None, UserWarning, None, None) # Either 'message' needs to be an instance of Warning or 'category' # needs to be a subclass. self.assertRaises(TypeError, self.module.warn_explicit, None, None, None, 1) # 'registry' must be a dict or None. self.assertRaises((TypeError, AttributeError), self.module.warn_explicit, None, Warning, None, 1, registry=42) def test_bad_str(self): # issue 6415 # Warnings instance with a bad format string for __str__ should not # trigger a bus error. class BadStrWarning(Warning): """Warning with a bad format string for __str__.""" def __str__(self): return ("A bad formatted string %(err)" % {"err" : "there is no %(err)s"}) with self.assertRaises(ValueError): self.module.warn(BadStrWarning()) def test_warning_classes(self): class MyWarningClass(Warning): pass class NonWarningSubclass: pass # passing a non-subclass of Warning should raise a TypeError with self.assertRaises(TypeError) as cm: self.module.warn('bad warning category', '') self.assertIn('category must be a Warning subclass, not ', str(cm.exception)) with self.assertRaises(TypeError) as cm: self.module.warn('bad warning category', NonWarningSubclass) self.assertIn('category must be a Warning subclass, not ', str(cm.exception)) # check that warning instances also raise a TypeError with self.assertRaises(TypeError) as cm: self.module.warn('bad warning category', MyWarningClass()) self.assertIn('category must be a Warning subclass, not ', str(cm.exception)) with original_warnings.catch_warnings(module=self.module): self.module.resetwarnings() self.module.filterwarnings('default') with self.assertWarns(MyWarningClass) as cm: self.module.warn('good warning category', MyWarningClass) self.assertEqual('good warning category', str(cm.warning)) with self.assertWarns(UserWarning) as cm: self.module.warn('good warning category', None) self.assertEqual('good warning category', str(cm.warning)) with self.assertWarns(MyWarningClass) as cm: self.module.warn('good warning category', MyWarningClass) self.assertIsInstance(cm.warning, Warning) class CWarnTests(WarnTests, unittest.TestCase): module = c_warnings # As an early adopter, we sanity check the # test.support.import_fresh_module utility function def test_accelerated(self): self.assertFalse(original_warnings is self.module) self.assertFalse(hasattr(self.module.warn, '__code__')) class PyWarnTests(WarnTests, unittest.TestCase): module = py_warnings # As an early adopter, we sanity check the # test.support.import_fresh_module utility function def test_pure_python(self): self.assertFalse(original_warnings is self.module) self.assertTrue(hasattr(self.module.warn, '__code__')) class WCmdLineTests(BaseTest): def test_improper_input(self): # Uses the private _setoption() function to test the parsing # of command-line warning arguments with original_warnings.catch_warnings(module=self.module): self.assertRaises(self.module._OptionError, self.module._setoption, '1:2:3:4:5:6') self.assertRaises(self.module._OptionError, self.module._setoption, 'bogus::Warning') self.assertRaises(self.module._OptionError, self.module._setoption, 'ignore:2::4:-5') self.module._setoption('error::Warning::0') self.assertRaises(UserWarning, self.module.warn, 'convert to error') class CWCmdLineTests(WCmdLineTests, unittest.TestCase): module = c_warnings class PyWCmdLineTests(WCmdLineTests, unittest.TestCase): module = py_warnings def test_improper_option(self): # Same as above, but check that the message is printed out when # the interpreter is executed. This also checks that options are # actually parsed at all. rc, out, err = assert_python_ok("-Wxxx", "-c", "pass") self.assertIn(b"Invalid -W option ignored: invalid action: 'xxx'", err) def test_warnings_bootstrap(self): # Check that the warnings module does get loaded when -W<some option> # is used (see issue #10372 for an example of silent bootstrap failure). rc, out, err = assert_python_ok("-Wi", "-c", "import sys; sys.modules['warnings'].warn('foo', RuntimeWarning)") # '-Wi' was observed self.assertFalse(out.strip()) self.assertNotIn(b'RuntimeWarning', err) class _WarningsTests(BaseTest, unittest.TestCase): """Tests specific to the _warnings module.""" module = c_warnings def test_filter(self): # Everything should function even if 'filters' is not in warnings. with original_warnings.catch_warnings(module=self.module) as w: self.module.filterwarnings("error", "", Warning, "", 0) self.assertRaises(UserWarning, self.module.warn, 'convert to error') del self.module.filters self.assertRaises(UserWarning, self.module.warn, 'convert to error') def test_onceregistry(self): # Replacing or removing the onceregistry should be okay. global __warningregistry__ message = UserWarning('onceregistry test') try: original_registry = self.module.onceregistry __warningregistry__ = {} with original_warnings.catch_warnings(record=True, module=self.module) as w: self.module.resetwarnings() self.module.filterwarnings("once", category=UserWarning) self.module.warn_explicit(message, UserWarning, "file", 42) self.assertEqual(w[-1].message, message) del w[:] self.module.warn_explicit(message, UserWarning, "file", 42) self.assertEqual(len(w), 0) # Test the resetting of onceregistry. self.module.onceregistry = {} __warningregistry__ = {} self.module.warn('onceregistry test') self.assertEqual(w[-1].message.args, message.args) # Removal of onceregistry is okay. del w[:] del self.module.onceregistry __warningregistry__ = {} self.module.warn_explicit(message, UserWarning, "file", 42) self.assertEqual(len(w), 0) finally: self.module.onceregistry = original_registry def test_default_action(self): # Replacing or removing defaultaction should be okay. message = UserWarning("defaultaction test") original = self.module.defaultaction try: with original_warnings.catch_warnings(record=True, module=self.module) as w: self.module.resetwarnings() registry = {} self.module.warn_explicit(message, UserWarning, "<test>", 42, registry=registry) self.assertEqual(w[-1].message, message) self.assertEqual(len(w), 1) # One actual registry key plus the "version" key self.assertEqual(len(registry), 2) self.assertIn("version", registry) del w[:] # Test removal. del self.module.defaultaction __warningregistry__ = {} registry = {} self.module.warn_explicit(message, UserWarning, "<test>", 43, registry=registry) self.assertEqual(w[-1].message, message) self.assertEqual(len(w), 1) self.assertEqual(len(registry), 2) del w[:] # Test setting. self.module.defaultaction = "ignore" __warningregistry__ = {} registry = {} self.module.warn_explicit(message, UserWarning, "<test>", 44, registry=registry) self.assertEqual(len(w), 0) finally: self.module.defaultaction = original def test_showwarning_missing(self): # Test that showwarning() missing is okay. text = 'del showwarning test' with original_warnings.catch_warnings(module=self.module): self.module.filterwarnings("always", category=UserWarning) del self.module.showwarning with support.captured_output('stderr') as stream: self.module.warn(text) result = stream.getvalue() self.assertIn(text, result) def test_showwarnmsg_missing(self): # Test that _showwarnmsg() missing is okay. text = 'del _showwarnmsg test' with original_warnings.catch_warnings(module=self.module): self.module.filterwarnings("always", category=UserWarning) show = self.module._showwarnmsg try: del self.module._showwarnmsg with support.captured_output('stderr') as stream: self.module.warn(text) result = stream.getvalue() finally: self.module._showwarnmsg = show self.assertIn(text, result) def test_showwarning_not_callable(self): with original_warnings.catch_warnings(module=self.module): self.module.filterwarnings("always", category=UserWarning) self.module.showwarning = print with support.captured_output('stdout'): self.module.warn('Warning!') self.module.showwarning = 23 self.assertRaises(TypeError, self.module.warn, "Warning!") def test_show_warning_output(self): # With showarning() missing, make sure that output is okay. text = 'test show_warning' with original_warnings.catch_warnings(module=self.module): self.module.filterwarnings("always", category=UserWarning) del self.module.showwarning with support.captured_output('stderr') as stream: warning_tests.inner(text) result = stream.getvalue() self.assertEqual(result.count('\n'), 2, "Too many newlines in %r" % result) first_line, second_line = result.split('\n', 1) expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py' first_line_parts = first_line.rsplit(':', 3) path, line, warning_class, message = first_line_parts line = int(line) self.assertEqual(expected_file, path) self.assertEqual(warning_class, ' ' + UserWarning.__name__) self.assertEqual(message, ' ' + text) expected_line = ' ' + linecache.getline(path, line).strip() + '\n' assert expected_line self.assertEqual(second_line, expected_line) def test_filename_none(self): # issue #12467: race condition if a warning is emitted at shutdown globals_dict = globals() oldfile = globals_dict['__file__'] try: catch = original_warnings.catch_warnings(record=True, module=self.module) with catch as w: self.module.filterwarnings("always", category=UserWarning) globals_dict['__file__'] = None original_warnings.warn('test', UserWarning) self.assertTrue(len(w)) finally: globals_dict['__file__'] = oldfile def test_stderr_none(self): rc, stdout, stderr = assert_python_ok("-c", "import sys; sys.stderr = None; " "import warnings; warnings.simplefilter('always'); " "warnings.warn('Warning!')") self.assertEqual(stdout, b'') self.assertNotIn(b'Warning!', stderr) self.assertNotIn(b'Error', stderr) def test_issue31285(self): # warn_explicit() should neither raise a SystemError nor cause an # assertion failure, in case the return value of get_source() has a # bad splitlines() method. def get_bad_loader(splitlines_ret_val): class BadLoader: def get_source(self, fullname): class BadSource(str): def splitlines(self): return splitlines_ret_val return BadSource('spam') return BadLoader() wmod = self.module with original_warnings.catch_warnings(module=wmod): wmod.filterwarnings('default', category=UserWarning) with support.captured_stderr() as stderr: wmod.warn_explicit( 'foo', UserWarning, 'bar', 1, module_globals={'__loader__': get_bad_loader(42), '__name__': 'foobar'}) self.assertIn('UserWarning: foo', stderr.getvalue()) show = wmod._showwarnmsg try: del wmod._showwarnmsg with support.captured_stderr() as stderr: wmod.warn_explicit( 'eggs', UserWarning, 'bar', 1, module_globals={'__loader__': get_bad_loader([42]), '__name__': 'foobar'}) self.assertIn('UserWarning: eggs', stderr.getvalue()) finally: wmod._showwarnmsg = show @support.cpython_only def test_issue31411(self): # warn_explicit() shouldn't raise a SystemError in case # warnings.onceregistry isn't a dictionary. wmod = self.module with original_warnings.catch_warnings(module=wmod): wmod.filterwarnings('once') with support.swap_attr(wmod, 'onceregistry', None): with self.assertRaises(TypeError): wmod.warn_explicit('foo', Warning, 'bar', 1, registry=None) @support.cpython_only def test_issue31416(self): # warn_explicit() shouldn't cause an assertion failure in case of a # bad warnings.filters or warnings.defaultaction. wmod = self.module with original_warnings.catch_warnings(module=wmod): wmod.filters = [(None, None, Warning, None, 0)] with self.assertRaises(TypeError): wmod.warn_explicit('foo', Warning, 'bar', 1) wmod.filters = [] with support.swap_attr(wmod, 'defaultaction', None), \ self.assertRaises(TypeError): wmod.warn_explicit('foo', Warning, 'bar', 1) @support.cpython_only def test_issue31566(self): # warn() shouldn't cause an assertion failure in case of a bad # __name__ global. with original_warnings.catch_warnings(module=self.module): self.module.filterwarnings('error', category=UserWarning) with support.swap_item(globals(), '__name__', b'foo'), \ support.swap_item(globals(), '__file__', None): self.assertRaises(UserWarning, self.module.warn, 'bar') class WarningsDisplayTests(BaseTest): """Test the displaying of warnings and the ability to overload functions related to displaying warnings.""" def test_formatwarning(self): message = "msg" category = Warning file_name = os.path.splitext(warning_tests.__file__)[0] + '.py' line_num = 3 file_line = linecache.getline(file_name, line_num).strip() format = "%s:%s: %s: %s\n %s\n" expect = format % (file_name, line_num, category.__name__, message, file_line) self.assertEqual(expect, self.module.formatwarning(message, category, file_name, line_num)) # Test the 'line' argument. file_line += " for the win!" expect = format % (file_name, line_num, category.__name__, message, file_line) self.assertEqual(expect, self.module.formatwarning(message, category, file_name, line_num, file_line)) def test_showwarning(self): file_name = os.path.splitext(warning_tests.__file__)[0] + '.py' line_num = 3 expected_file_line = linecache.getline(file_name, line_num).strip() message = 'msg' category = Warning file_object = StringIO() expect = self.module.formatwarning(message, category, file_name, line_num) self.module.showwarning(message, category, file_name, line_num, file_object) self.assertEqual(file_object.getvalue(), expect) # Test 'line' argument. expected_file_line += "for the win!" expect = self.module.formatwarning(message, category, file_name, line_num, expected_file_line) file_object = StringIO() self.module.showwarning(message, category, file_name, line_num, file_object, expected_file_line) self.assertEqual(expect, file_object.getvalue()) class CWarningsDisplayTests(WarningsDisplayTests, unittest.TestCase): module = c_warnings class PyWarningsDisplayTests(WarningsDisplayTests, unittest.TestCase): module = py_warnings @unittest.skipUnless(cosmo.MODE == "dbg", "requires APE debug build") def test_tracemalloc(self): self.addCleanup(support.unlink, support.TESTFN) with open(support.TESTFN, 'w') as fp: fp.write(textwrap.dedent(""" def func(): f = open(__file__) # Emit ResourceWarning f = None func() """)) res = assert_python_ok('-Wd', '-X', 'tracemalloc=2', support.TESTFN) stderr = res.err.decode('ascii', 'replace') # normalize newlines stderr = '\n'.join(stderr.splitlines()) stderr = re.sub('<.*>', '<...>', stderr) expected = textwrap.dedent(''' {fname}:5: ResourceWarning: unclosed file <...> f = None Object allocated at (most recent call first): File "{fname}", lineno 3 f = open(__file__) File "{fname}", lineno 7 func() ''') expected = expected.format(fname=support.TESTFN).strip() self.assertEqual(stderr, expected) class CatchWarningTests(BaseTest): """Test catch_warnings().""" def test_catch_warnings_restore(self): wmod = self.module orig_filters = wmod.filters orig_showwarning = wmod.showwarning # Ensure both showwarning and filters are restored when recording with wmod.catch_warnings(module=wmod, record=True): wmod.filters = wmod.showwarning = object() self.assertTrue(wmod.filters is orig_filters) self.assertTrue(wmod.showwarning is orig_showwarning) # Same test, but with recording disabled with wmod.catch_warnings(module=wmod, record=False): wmod.filters = wmod.showwarning = object() self.assertTrue(wmod.filters is orig_filters) self.assertTrue(wmod.showwarning is orig_showwarning) def test_catch_warnings_recording(self): wmod = self.module # Ensure warnings are recorded when requested with wmod.catch_warnings(module=wmod, record=True) as w: self.assertEqual(w, []) self.assertTrue(type(w) is list) wmod.simplefilter("always") wmod.warn("foo") self.assertEqual(str(w[-1].message), "foo") wmod.warn("bar") self.assertEqual(str(w[-1].message), "bar") self.assertEqual(str(w[0].message), "foo") self.assertEqual(str(w[1].message), "bar") del w[:] self.assertEqual(w, []) # Ensure warnings are not recorded when not requested orig_showwarning = wmod.showwarning with wmod.catch_warnings(module=wmod, record=False) as w: self.assertTrue(w is None) self.assertTrue(wmod.showwarning is orig_showwarning) def test_catch_warnings_reentry_guard(self): wmod = self.module # Ensure catch_warnings is protected against incorrect usage x = wmod.catch_warnings(module=wmod, record=True) self.assertRaises(RuntimeError, x.__exit__) with x: self.assertRaises(RuntimeError, x.__enter__) # Same test, but with recording disabled x = wmod.catch_warnings(module=wmod, record=False) self.assertRaises(RuntimeError, x.__exit__) with x: self.assertRaises(RuntimeError, x.__enter__) def test_catch_warnings_defaults(self): wmod = self.module orig_filters = wmod.filters orig_showwarning = wmod.showwarning # Ensure default behaviour is not to record warnings with wmod.catch_warnings(module=wmod) as w: self.assertTrue(w is None) self.assertTrue(wmod.showwarning is orig_showwarning) self.assertTrue(wmod.filters is not orig_filters) self.assertTrue(wmod.filters is orig_filters) if wmod is sys.modules['warnings']: # Ensure the default module is this one with wmod.catch_warnings() as w: self.assertTrue(w is None) self.assertTrue(wmod.showwarning is orig_showwarning) self.assertTrue(wmod.filters is not orig_filters) self.assertTrue(wmod.filters is orig_filters) def test_record_override_showwarning_before(self): # Issue #28835: If warnings.showwarning() was overriden, make sure # that catch_warnings(record=True) overrides it again. text = "This is a warning" wmod = self.module my_log = [] def my_logger(message, category, filename, lineno, file=None, line=None): nonlocal my_log my_log.append(message) # Override warnings.showwarning() before calling catch_warnings() with support.swap_attr(wmod, 'showwarning', my_logger): with wmod.catch_warnings(module=wmod, record=True) as log: self.assertIsNot(wmod.showwarning, my_logger) wmod.simplefilter("always") wmod.warn(text) self.assertIs(wmod.showwarning, my_logger) self.assertEqual(len(log), 1, log) self.assertEqual(log[0].message.args[0], text) self.assertEqual(my_log, []) def test_record_override_showwarning_inside(self): # Issue #28835: It is possible to override warnings.showwarning() # in the catch_warnings(record=True) context manager. text = "This is a warning" wmod = self.module my_log = [] def my_logger(message, category, filename, lineno, file=None, line=None): nonlocal my_log my_log.append(message) with wmod.catch_warnings(module=wmod, record=True) as log: wmod.simplefilter("always") wmod.showwarning = my_logger wmod.warn(text) self.assertEqual(len(my_log), 1, my_log) self.assertEqual(my_log[0].args[0], text) self.assertEqual(log, []) def test_check_warnings(self): # Explicit tests for the test.support convenience wrapper wmod = self.module if wmod is not sys.modules['warnings']: self.skipTest('module to test is not loaded warnings module') with support.check_warnings(quiet=False) as w: self.assertEqual(w.warnings, []) wmod.simplefilter("always") wmod.warn("foo") self.assertEqual(str(w.message), "foo") wmod.warn("bar") self.assertEqual(str(w.message), "bar") self.assertEqual(str(w.warnings[0].message), "foo") self.assertEqual(str(w.warnings[1].message), "bar") w.reset() self.assertEqual(w.warnings, []) with support.check_warnings(): # defaults to quiet=True without argument pass with support.check_warnings(('foo', UserWarning)): wmod.warn("foo") with self.assertRaises(AssertionError): with support.check_warnings(('', RuntimeWarning)): # defaults to quiet=False with argument pass with self.assertRaises(AssertionError): with support.check_warnings(('foo', RuntimeWarning)): wmod.warn("foo") class CCatchWarningTests(CatchWarningTests, unittest.TestCase): module = c_warnings class PyCatchWarningTests(CatchWarningTests, unittest.TestCase): module = py_warnings class EnvironmentVariableTests(BaseTest): def test_single_warning(self): rc, stdout, stderr = assert_python_ok("-c", "import sys; sys.stdout.write(str(sys.warnoptions))", PYTHONWARNINGS="ignore::DeprecationWarning") self.assertEqual(stdout, b"['ignore::DeprecationWarning']") def test_comma_separated_warnings(self): rc, stdout, stderr = assert_python_ok("-c", "import sys; sys.stdout.write(str(sys.warnoptions))", PYTHONWARNINGS="ignore::DeprecationWarning,ignore::UnicodeWarning") self.assertEqual(stdout, b"['ignore::DeprecationWarning', 'ignore::UnicodeWarning']") def test_envvar_and_command_line(self): rc, stdout, stderr = assert_python_ok("-Wignore::UnicodeWarning", "-c", "import sys; sys.stdout.write(str(sys.warnoptions))", PYTHONWARNINGS="ignore::DeprecationWarning") self.assertEqual(stdout, b"['ignore::DeprecationWarning', 'ignore::UnicodeWarning']") def test_conflicting_envvar_and_command_line(self): rc, stdout, stderr = assert_python_failure("-Werror::DeprecationWarning", "-c", "import sys, warnings; sys.stdout.write(str(sys.warnoptions)); " "warnings.warn('Message', DeprecationWarning)", PYTHONWARNINGS="default::DeprecationWarning") self.assertEqual(stdout, b"['default::DeprecationWarning', 'error::DeprecationWarning']") self.assertEqual(stderr.splitlines(), [b"Traceback (most recent call last):", b" File \"<string>\", line 1, in <module>", b"DeprecationWarning: Message"]) @unittest.skipUnless(sys.getfilesystemencoding() != 'ascii', 'requires non-ascii filesystemencoding') def test_nonascii(self): rc, stdout, stderr = assert_python_ok("-c", "import sys; sys.stdout.write(str(sys.warnoptions))", PYTHONIOENCODING="utf-8", PYTHONWARNINGS="ignore:DeprecaciónWarning") self.assertEqual(stdout, "['ignore:DeprecaciónWarning']".encode('utf-8')) class CEnvironmentVariableTests(EnvironmentVariableTests, unittest.TestCase): module = c_warnings class PyEnvironmentVariableTests(EnvironmentVariableTests, unittest.TestCase): module = py_warnings class BootstrapTest(unittest.TestCase): def test_issue_8766(self): # "import encodings" emits a warning whereas the warnings is not loaded # or not completely loaded (warnings imports indirectly encodings by # importing linecache) yet with support.temp_cwd() as cwd, support.temp_cwd('encodings'): # encodings loaded by initfsencoding() assert_python_ok('-c', 'pass', PYTHONPATH=cwd) # Use -W to load warnings module at startup assert_python_ok('-c', 'pass', '-W', 'always', PYTHONPATH=cwd) class FinalizationTest(unittest.TestCase): @support.requires_type_collecting def test_finalization(self): # Issue #19421: warnings.warn() should not crash # during Python finalization code = """ import warnings warn = warnings.warn class A: def __del__(self): warn("test") a=A() """ rc, out, err = assert_python_ok("-c", code) # note: "__main__" filename is not correct, it should be the name # of the script self.assertEqual(err, b'__main__:7: UserWarning: test') def test_late_resource_warning(self): # Issue #21925: Emitting a ResourceWarning late during the Python # shutdown must be logged. expected = b"sys:1: ResourceWarning: unclosed file " # don't import the warnings module # (_warnings will try to import it) code = "f = open(%a)" % __file__ rc, out, err = assert_python_ok("-Wd", "-c", code) self.assertTrue(err.startswith(expected), ascii(err)) # import the warnings module code = "import warnings; f = open(%a)" % __file__ rc, out, err = assert_python_ok("-Wd", "-c", code) self.assertTrue(err.startswith(expected), ascii(err)) def setUpModule(): py_warnings.onceregistry.clear() c_warnings.onceregistry.clear() tearDownModule = setUpModule if __name__ == "__main__": unittest.main()
51,447
1,223
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_warnings/data/import_warning.py
import warnings warnings.warn('module-level warning', DeprecationWarning, stacklevel=2)
89
4
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_warnings/data/stacklevel.py
# Helper module for testing the skipmodules argument of warnings.warn() import warnings def outer(message, stacklevel=1): inner(message, stacklevel) def inner(message, stacklevel=1): warnings.warn(message, stacklevel=stacklevel)
240
10
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_warnings/data/__init__.py
0
1
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/crashers/trace_at_recursion_limit.py
""" From http://bugs.python.org/issue6717 A misbehaving trace hook can trigger a segfault by exceeding the recursion limit. """ import sys def x(): pass def g(*args): if True: # change to True to crash interpreter try: x() except: pass return g def f(): print(sys.getrecursionlimit()) f() sys.settrace(g) f()
376
28
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/crashers/mutation_inside_cyclegc.py
# The cycle GC collector can be executed when any GC-tracked object is # allocated, e.g. during a call to PyList_New(), PyDict_New(), ... # Moreover, it can invoke arbitrary Python code via a weakref callback. # This means that there are many places in the source where an arbitrary # mutation could unexpectedly occur. # The example below shows list_slice() not expecting the call to # PyList_New to mutate the input list. (Of course there are many # more examples like this one.) import weakref class A(object): pass def callback(x): del lst[:] keepalive = [] for i in range(100): lst = [str(i)] a = A() a.cycle = a keepalive.append(weakref.ref(a, callback)) del a while lst: keepalive.append(lst[:])
753
32
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/crashers/underlying_dict.py
import gc thingy = object() class A(object): def f(self): return 1 x = thingy r = gc.get_referrers(thingy) if "__module__" in r[0]: dct = r[0] else: dct = r[1] a = A() for i in range(10): a.f() dct["f"] = lambda self: 2 print(a.f()) # should print 1
282
21
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/crashers/recursive_call.py
#!/usr/bin/env python3 # No bug report AFAIK, mail on python-dev on 2006-01-10 # This is a "won't fix" case. It is known that setting a high enough # recursion limit crashes by overflowing the stack. Unless this is # redesigned somehow, it won't go away. import sys sys.setrecursionlimit(1 << 30) f = lambda f:f(f) if __name__ == '__main__': f(f)
358
16
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/crashers/bogus_code_obj.py
""" Broken bytecode objects can easily crash the interpreter. This is not going to be fixed. It is generally agreed that there is no point in writing a bytecode verifier and putting it in CPython just for this. Moreover, a verifier is bound to accept only a subset of all safe bytecodes, so it could lead to unnecessary breakage. For security purposes, "restricted" interpreters are not going to let the user build or load random bytecodes anyway. Otherwise, this is a "won't fix" case. """ import types co = types.CodeType(0, 0, 0, 0, 0, b'\x04\x71\x00\x00', (), (), (), '', '', 1, b'') exec(co)
625
20
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/crashers/README
This directory only contains tests for outstanding bugs that cause the interpreter to segfault. Ideally this directory should always be empty, but sometimes it may not be easy to fix the underlying cause and the bug is deemed too obscure to invest the effort. Each test should fail when run from the command line: ./python Lib/test/crashers/weakref_in_del.py Put as much info into a docstring or comments to help determine the cause of the failure, as well as a bugs.python.org issue number if it exists. Particularly note if the cause is system or environment dependent and what the variables are. Once the crash is fixed, the test case should be moved into an appropriate test (even if it was originally from the test suite). This ensures the regression doesn't happen again. And if it does, it should be easier to track down. Also see Lib/test_crashers.py which exercises the crashers in this directory. In particular, make sure to add any new infinite loop crashers to the black list so it doesn't try to run them.
1,029
21
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/crashers/gc_inspection.py
""" gc.get_referrers() can be used to see objects before they are fully built. Note that this is only an example. There are many ways to crash Python by using gc.get_referrers(), as well as many extension modules (even when they are using perfectly documented patterns to build objects). Identifying and removing all places that expose to the GC a partially-built object is a long-term project. A patch was proposed on SF specifically for this example but I consider fixing just this single example a bit pointless (#1517042). A fix would include a whole-scale code review, possibly with an API change to decouple object creation and GC registration, and according fixes to the documentation for extension module writers. It's unlikely to happen, though. So this is currently classified as "gc.get_referrers() is dangerous, use only for debugging". """ import gc def g(): marker = object() yield marker # now the marker is in the tuple being constructed [tup] = [x for x in gc.get_referrers(marker) if type(x) is tuple] print(tup) print(tup[1]) tuple(g())
1,092
33
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/crashers/infinite_loop_re.py
# This was taken from http://python.org/sf/1541697 # It's not technically a crasher. It may not even truly be infinite, # however, I haven't waited a long time to see the result. It takes # 100% of CPU while running this and should be fixed. import re starttag = re.compile(r'<[a-zA-Z][-_.:a-zA-Z0-9]*\s*(' r'\s*([a-zA-Z_][-:.a-zA-Z_0-9]*)(\s*=\s*' r'(\'[^\']*\'|"[^"]*"|[-a-zA-Z0-9./,:;+*%?!&$\(\)_#=~@]' r'[][\-a-zA-Z0-9./,:;+*%?!&$\(\)_#=~\'"@]*(?=[\s>/<])))?' r')*\s*/?\s*(?=[<>])') if __name__ == '__main__': foo = '<table cellspacing="0" cellpadding="0" style="border-collapse' starttag.match(foo)
645
17
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_tools/test_i18n.py
"""Tests to cover the Tools/i18n package""" import os import unittest from textwrap import dedent from test.support.script_helper import assert_python_ok from test.test_tools import skip_if_missing, toolsdir from test.support import temp_cwd, temp_dir skip_if_missing() class Test_pygettext(unittest.TestCase): """Tests for the pygettext.py tool""" script = os.path.join(toolsdir,'i18n', 'pygettext.py') def get_header(self, data): """ utility: return the header of a .po file as a dictionary """ headers = {} for line in data.split('\n'): if not line or line.startswith(('#', 'msgid','msgstr')): continue line = line.strip('"') key, val = line.split(':',1) headers[key] = val.strip() return headers def get_msgids(self, data): """ utility: return all msgids in .po file as a list of strings """ msgids = [] reading_msgid = False cur_msgid = [] for line in data.split('\n'): if reading_msgid: if line.startswith('"'): cur_msgid.append(line.strip('"')) else: msgids.append('\n'.join(cur_msgid)) cur_msgid = [] reading_msgid = False continue if line.startswith('msgid '): line = line[len('msgid '):] cur_msgid.append(line.strip('"')) reading_msgid = True else: if reading_msgid: msgids.append('\n'.join(cur_msgid)) return msgids def extract_docstrings_from_str(self, module_content): """ utility: return all msgids extracted from module_content """ filename = 'test_docstrings.py' with temp_cwd(None) as cwd: with open(filename, 'w') as fp: fp.write(module_content) assert_python_ok(self.script, '-D', filename) with open('messages.pot') as fp: data = fp.read() return self.get_msgids(data) def test_header(self): """Make sure the required fields are in the header, according to: http://www.gnu.org/software/gettext/manual/gettext.html#Header-Entry """ with temp_cwd(None) as cwd: assert_python_ok(self.script) with open('messages.pot') as fp: data = fp.read() header = self.get_header(data) self.assertIn("Project-Id-Version", header) self.assertIn("POT-Creation-Date", header) self.assertIn("PO-Revision-Date", header) self.assertIn("Last-Translator", header) self.assertIn("Language-Team", header) self.assertIn("MIME-Version", header) self.assertIn("Content-Type", header) self.assertIn("Content-Transfer-Encoding", header) self.assertIn("Generated-By", header) # not clear if these should be required in POT (template) files #self.assertIn("Report-Msgid-Bugs-To", header) #self.assertIn("Language", header) #"Plural-Forms" is optional def test_POT_Creation_Date(self): """ Match the date format from xgettext for POT-Creation-Date """ from datetime import datetime with temp_cwd(None) as cwd: assert_python_ok(self.script) with open('messages.pot') as fp: data = fp.read() header = self.get_header(data) creationDate = header['POT-Creation-Date'] # peel off the escaped newline at the end of string if creationDate.endswith('\\n'): creationDate = creationDate[:-len('\\n')] # This will raise if the date format does not exactly match. datetime.strptime(creationDate, '%Y-%m-%d %H:%M%z') def test_funcdocstring(self): for doc in ('"""doc"""', "r'''doc'''", "R'doc'", 'u"doc"'): with self.subTest(doc): msgids = self.extract_docstrings_from_str(dedent('''\ def foo(bar): %s ''' % doc)) self.assertIn('doc', msgids) def test_funcdocstring_bytes(self): msgids = self.extract_docstrings_from_str(dedent('''\ def foo(bar): b"""doc""" ''')) self.assertFalse([msgid for msgid in msgids if 'doc' in msgid]) def test_funcdocstring_fstring(self): msgids = self.extract_docstrings_from_str(dedent('''\ def foo(bar): f"""doc""" ''')) self.assertFalse([msgid for msgid in msgids if 'doc' in msgid]) def test_classdocstring(self): for doc in ('"""doc"""', "r'''doc'''", "R'doc'", 'u"doc"'): with self.subTest(doc): msgids = self.extract_docstrings_from_str(dedent('''\ class C: %s ''' % doc)) self.assertIn('doc', msgids) def test_classdocstring_bytes(self): msgids = self.extract_docstrings_from_str(dedent('''\ class C: b"""doc""" ''')) self.assertFalse([msgid for msgid in msgids if 'doc' in msgid]) def test_classdocstring_fstring(self): msgids = self.extract_docstrings_from_str(dedent('''\ class C: f"""doc""" ''')) self.assertFalse([msgid for msgid in msgids if 'doc' in msgid]) def test_msgid(self): msgids = self.extract_docstrings_from_str( '''_("""doc""" r'str' u"ing")''') self.assertIn('docstring', msgids) def test_msgid_bytes(self): msgids = self.extract_docstrings_from_str('_(b"""doc""")') self.assertFalse([msgid for msgid in msgids if 'doc' in msgid]) def test_msgid_fstring(self): msgids = self.extract_docstrings_from_str('_(f"""doc""")') self.assertFalse([msgid for msgid in msgids if 'doc' in msgid]) def test_funcdocstring_annotated_args(self): """ Test docstrings for functions with annotated args """ msgids = self.extract_docstrings_from_str(dedent('''\ def foo(bar: str): """doc""" ''')) self.assertIn('doc', msgids) def test_funcdocstring_annotated_return(self): """ Test docstrings for functions with annotated return type """ msgids = self.extract_docstrings_from_str(dedent('''\ def foo(bar) -> str: """doc""" ''')) self.assertIn('doc', msgids) def test_funcdocstring_defvalue_args(self): """ Test docstring for functions with default arg values """ msgids = self.extract_docstrings_from_str(dedent('''\ def foo(bar=()): """doc""" ''')) self.assertIn('doc', msgids) def test_funcdocstring_multiple_funcs(self): """ Test docstring extraction for multiple functions combining annotated args, annotated return types and default arg values """ msgids = self.extract_docstrings_from_str(dedent('''\ def foo1(bar: tuple=()) -> str: """doc1""" def foo2(bar: List[1:2]) -> (lambda x: x): """doc2""" def foo3(bar: 'func'=lambda x: x) -> {1: 2}: """doc3""" ''')) self.assertIn('doc1', msgids) self.assertIn('doc2', msgids) self.assertIn('doc3', msgids) def test_classdocstring_early_colon(self): """ Test docstring extraction for a class with colons occuring within the parentheses. """ msgids = self.extract_docstrings_from_str(dedent('''\ class D(L[1:2], F({1: 2}), metaclass=M(lambda x: x)): """doc""" ''')) self.assertIn('doc', msgids) def test_files_list(self): """Make sure the directories are inspected for source files bpo-31920 """ text1 = 'Text to translate1' text2 = 'Text to translate2' text3 = 'Text to ignore' with temp_cwd(None), temp_dir(None) as sdir: os.mkdir(os.path.join(sdir, 'pypkg')) with open(os.path.join(sdir, 'pypkg', 'pymod.py'), 'w') as sfile: sfile.write(f'_({text1!r})') os.mkdir(os.path.join(sdir, 'pkg.py')) with open(os.path.join(sdir, 'pkg.py', 'pymod2.py'), 'w') as sfile: sfile.write(f'_({text2!r})') os.mkdir(os.path.join(sdir, 'CVS')) with open(os.path.join(sdir, 'CVS', 'pymod3.py'), 'w') as sfile: sfile.write(f'_({text3!r})') assert_python_ok(self.script, sdir) with open('messages.pot') as fp: data = fp.read() self.assertIn(f'msgid "{text1}"', data) self.assertIn(f'msgid "{text2}"', data) self.assertNotIn(text3, data)
8,928
244
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_tools/test_gprof2html.py
"""Tests for the gprof2html script in the Tools directory.""" import os import sys import unittest from unittest import mock import tempfile from test.test_tools import skip_if_missing, import_tool skip_if_missing() class Gprof2htmlTests(unittest.TestCase): def setUp(self): self.gprof = import_tool('gprof2html') oldargv = sys.argv def fixup(): sys.argv = oldargv self.addCleanup(fixup) sys.argv = [] def test_gprof(self): # Issue #14508: this used to fail with a NameError. with mock.patch.object(self.gprof, 'webbrowser') as wmock, \ tempfile.TemporaryDirectory() as tmpdir: fn = os.path.join(tmpdir, 'abc') open(fn, 'w').close() sys.argv = ['gprof2html', fn] self.gprof.main() self.assertTrue(wmock.open.called) if __name__ == '__main__': unittest.main()
919
36
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_tools/test_md5sum.py
"""Tests for the md5sum script in the Tools directory.""" import os import unittest from test import support from test.support.script_helper import assert_python_ok, assert_python_failure from test.test_tools import scriptsdir, skip_if_missing skip_if_missing() class MD5SumTests(unittest.TestCase): @classmethod def setUpClass(cls): cls.script = os.path.join(scriptsdir, 'md5sum.py') os.mkdir(support.TESTFN) cls.fodder = os.path.join(support.TESTFN, 'md5sum.fodder') with open(cls.fodder, 'wb') as f: f.write(b'md5sum\r\ntest file\r\n') cls.fodder_md5 = b'd38dae2eb1ab346a292ef6850f9e1a0d' cls.fodder_textmode_md5 = b'a8b07894e2ca3f2a4c3094065fa6e0a5' @classmethod def tearDownClass(cls): support.rmtree(support.TESTFN) def test_noargs(self): rc, out, err = assert_python_ok(self.script) self.assertEqual(rc, 0) self.assertTrue( out.startswith(b'd41d8cd98f00b204e9800998ecf8427e <stdin>')) self.assertFalse(err) def test_checksum_fodder(self): rc, out, err = assert_python_ok(self.script, self.fodder) self.assertEqual(rc, 0) self.assertTrue(out.startswith(self.fodder_md5)) for part in self.fodder.split(os.path.sep): self.assertIn(part.encode(), out) self.assertFalse(err) def test_dash_l(self): rc, out, err = assert_python_ok(self.script, '-l', self.fodder) self.assertEqual(rc, 0) self.assertIn(self.fodder_md5, out) parts = self.fodder.split(os.path.sep) self.assertIn(parts[-1].encode(), out) self.assertNotIn(parts[-2].encode(), out) def test_dash_t(self): rc, out, err = assert_python_ok(self.script, '-t', self.fodder) self.assertEqual(rc, 0) self.assertTrue(out.startswith(self.fodder_textmode_md5)) self.assertNotIn(self.fodder_md5, out) def test_dash_s(self): rc, out, err = assert_python_ok(self.script, '-s', '512', self.fodder) self.assertEqual(rc, 0) self.assertIn(self.fodder_md5, out) def test_multiple_files(self): rc, out, err = assert_python_ok(self.script, self.fodder, self.fodder) self.assertEqual(rc, 0) lines = out.splitlines() self.assertEqual(len(lines), 2) self.assertEqual(*lines) def test_usage(self): rc, out, err = assert_python_failure(self.script, '-h') self.assertEqual(rc, 2) self.assertEqual(out, b'') self.assertGreater(err, b'') if __name__ == '__main__': unittest.main()
2,617
77
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_tools/test_pdeps.py
"""Tests for the pdeps script in the Tools directory.""" import os import unittest import tempfile from test.test_tools import skip_if_missing, import_tool skip_if_missing() class PdepsTests(unittest.TestCase): @classmethod def setUpClass(self): self.pdeps = import_tool('pdeps') def test_process_errors(self): # Issue #14492: m_import.match(line) can be None. with tempfile.TemporaryDirectory() as tmpdir: fn = os.path.join(tmpdir, 'foo') with open(fn, 'w') as stream: stream.write("#!/this/will/fail") self.pdeps.process(fn, {}) def test_inverse_attribute_error(self): # Issue #14492: this used to fail with an AttributeError. self.pdeps.inverse({'a': []}) if __name__ == '__main__': unittest.main()
824
33
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_tools/test_unparse.py
"""Tests for the unparse.py script in the Tools/parser directory.""" import unittest import test.support import io import os import random import tokenize import ast from test.test_tools import basepath, toolsdir, skip_if_missing skip_if_missing() parser_path = os.path.join(toolsdir, "parser") with test.support.DirsOnSysPath(parser_path): import unparse def read_pyfile(filename): """Read and return the contents of a Python source file (as a string), taking into account the file encoding.""" with open(filename, "rb") as pyfile: encoding = tokenize.detect_encoding(pyfile.readline)[0] with open(filename, "r", encoding=encoding) as pyfile: source = pyfile.read() return source for_else = """\ def f(): for x in range(10): break else: y = 2 z = 3 """ while_else = """\ def g(): while True: break else: y = 2 z = 3 """ relative_import = """\ from . import fred from .. import barney from .australia import shrimp as prawns """ nonlocal_ex = """\ def f(): x = 1 def g(): nonlocal x x = 2 y = 7 def h(): nonlocal x, y """ # also acts as test for 'except ... as ...' raise_from = """\ try: 1 / 0 except ZeroDivisionError as e: raise ArithmeticError from e """ class_decorator = """\ @f1(arg) @f2 class Foo: pass """ elif1 = """\ if cond1: suite1 elif cond2: suite2 else: suite3 """ elif2 = """\ if cond1: suite1 elif cond2: suite2 """ try_except_finally = """\ try: suite1 except ex1: suite2 except ex2: suite3 else: suite4 finally: suite5 """ with_simple = """\ with f(): suite1 """ with_as = """\ with f() as x: suite1 """ with_two_items = """\ with f() as x, g() as y: suite1 """ class ASTTestCase(unittest.TestCase): def assertASTEqual(self, ast1, ast2): self.assertEqual(ast.dump(ast1), ast.dump(ast2)) def check_roundtrip(self, code1, filename="internal"): ast1 = compile(code1, filename, "exec", ast.PyCF_ONLY_AST) unparse_buffer = io.StringIO() unparse.Unparser(ast1, unparse_buffer) code2 = unparse_buffer.getvalue() ast2 = compile(code2, filename, "exec", ast.PyCF_ONLY_AST) self.assertASTEqual(ast1, ast2) class UnparseTestCase(ASTTestCase): # Tests for specific bugs found in earlier versions of unparse def test_fstrings(self): # See issue 25180 self.check_roundtrip(r"""f'{f"{0}"*3}'""") self.check_roundtrip(r"""f'{f"{y}"*3}'""") def test_del_statement(self): self.check_roundtrip("del x, y, z") def test_shifts(self): self.check_roundtrip("45 << 2") self.check_roundtrip("13 >> 7") def test_for_else(self): self.check_roundtrip(for_else) def test_while_else(self): self.check_roundtrip(while_else) def test_unary_parens(self): self.check_roundtrip("(-1)**7") self.check_roundtrip("(-1.)**8") self.check_roundtrip("(-1j)**6") self.check_roundtrip("not True or False") self.check_roundtrip("True or not False") def test_integer_parens(self): self.check_roundtrip("3 .__abs__()") def test_huge_float(self): self.check_roundtrip("1e1000") self.check_roundtrip("-1e1000") self.check_roundtrip("1e1000j") self.check_roundtrip("-1e1000j") def test_min_int(self): self.check_roundtrip(str(-2**31)) self.check_roundtrip(str(-2**63)) def test_imaginary_literals(self): self.check_roundtrip("7j") self.check_roundtrip("-7j") self.check_roundtrip("0j") self.check_roundtrip("-0j") def test_lambda_parentheses(self): self.check_roundtrip("(lambda: int)()") def test_chained_comparisons(self): self.check_roundtrip("1 < 4 <= 5") self.check_roundtrip("a is b is c is not d") def test_function_arguments(self): self.check_roundtrip("def f(): pass") self.check_roundtrip("def f(a): pass") self.check_roundtrip("def f(b = 2): pass") self.check_roundtrip("def f(a, b): pass") self.check_roundtrip("def f(a, b = 2): pass") self.check_roundtrip("def f(a = 5, b = 2): pass") self.check_roundtrip("def f(*, a = 1, b = 2): pass") self.check_roundtrip("def f(*, a = 1, b): pass") self.check_roundtrip("def f(*, a, b = 2): pass") self.check_roundtrip("def f(a, b = None, *, c, **kwds): pass") self.check_roundtrip("def f(a=2, *args, c=5, d, **kwds): pass") self.check_roundtrip("def f(*args, **kwargs): pass") def test_relative_import(self): self.check_roundtrip(relative_import) def test_nonlocal(self): self.check_roundtrip(nonlocal_ex) def test_raise_from(self): self.check_roundtrip(raise_from) def test_bytes(self): self.check_roundtrip("b'123'") def test_annotations(self): self.check_roundtrip("def f(a : int): pass") self.check_roundtrip("def f(a: int = 5): pass") self.check_roundtrip("def f(*args: [int]): pass") self.check_roundtrip("def f(**kwargs: dict): pass") self.check_roundtrip("def f() -> None: pass") def test_set_literal(self): self.check_roundtrip("{'a', 'b', 'c'}") def test_set_comprehension(self): self.check_roundtrip("{x for x in range(5)}") def test_dict_comprehension(self): self.check_roundtrip("{x: x*x for x in range(10)}") def test_class_decorators(self): self.check_roundtrip(class_decorator) def test_class_definition(self): self.check_roundtrip("class A(metaclass=type, *[], **{}): pass") def test_elifs(self): self.check_roundtrip(elif1) self.check_roundtrip(elif2) def test_try_except_finally(self): self.check_roundtrip(try_except_finally) def test_starred_assignment(self): self.check_roundtrip("a, *b, c = seq") self.check_roundtrip("a, (*b, c) = seq") self.check_roundtrip("a, *b[0], c = seq") self.check_roundtrip("a, *(b, c) = seq") def test_with_simple(self): self.check_roundtrip(with_simple) def test_with_as(self): self.check_roundtrip(with_as) def test_with_two_items(self): self.check_roundtrip(with_two_items) def test_dict_unpacking_in_dict(self): # See issue 26489 self.check_roundtrip(r"""{**{'y': 2}, 'x': 1}""") self.check_roundtrip(r"""{**{'y': 2}, **{'x': 1}}""") class DirectoryTestCase(ASTTestCase): """Test roundtrip behaviour on all files in Lib and Lib/test.""" NAMES = None # test directories, relative to the root of the distribution test_directories = 'Lib', os.path.join('Lib', 'test') @classmethod def get_names(cls): if cls.NAMES is not None: return cls.NAMES names = [] for d in cls.test_directories: test_dir = os.path.join(basepath, d) for n in os.listdir(test_dir): if n.endswith('.py') and not n.startswith('bad'): names.append(os.path.join(test_dir, n)) # Test limited subset of files unless the 'cpu' resource is specified. if not test.support.is_resource_enabled("cpu"): names = random.sample(names, 10) # bpo-31174: Store the names sample to always test the same files. # It prevents false alarms when hunting reference leaks. cls.NAMES = names return names def test_files(self): # get names of files to test names = self.get_names() for filename in names: if test.support.verbose: print('Testing %s' % filename) # Some f-strings are not correctly round-tripped by # Tools/parser/unparse.py. See issue 28002 for details. # We need to skip files that contain such f-strings. if os.path.basename(filename) in ('test_fstring.py', ): if test.support.verbose: print(f'Skipping {filename}: see issue 28002') continue with self.subTest(filename=filename): source = read_pyfile(filename) self.check_roundtrip(source) if __name__ == '__main__': unittest.main()
8,393
314
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_tools/__main__.py
from test.test_tools import load_tests import unittest unittest.main()
72
5
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_tools/test_reindent.py
"""Tests for scripts in the Tools directory. This file contains regression tests for some of the scripts found in the Tools directory of a Python checkout or tarball, such as reindent.py. """ import os import unittest from test.support.script_helper import assert_python_ok from test.support import findfile from test.test_tools import scriptsdir, skip_if_missing skip_if_missing() class ReindentTests(unittest.TestCase): script = os.path.join(scriptsdir, 'reindent.py') def test_noargs(self): assert_python_ok(self.script) def test_help(self): rc, out, err = assert_python_ok(self.script, '-h') self.assertEqual(out, b'') self.assertGreater(err, b'') def test_reindent_file_with_bad_encoding(self): bad_coding_path = findfile('bad_coding.py') rc, out, err = assert_python_ok(self.script, '-r', bad_coding_path) self.assertEqual(out, b'') self.assertNotEqual(err, b'') if __name__ == '__main__': unittest.main()
1,006
36
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_tools/test_pindent.py
"""Tests for the pindent script in the Tools directory.""" import os import sys import unittest import subprocess import textwrap from test import support from test.support.script_helper import assert_python_ok from test.test_tools import scriptsdir, skip_if_missing skip_if_missing() class PindentTests(unittest.TestCase): script = os.path.join(scriptsdir, 'pindent.py') def assertFileEqual(self, fn1, fn2): with open(fn1) as f1, open(fn2) as f2: self.assertEqual(f1.readlines(), f2.readlines()) def pindent(self, source, *args): with subprocess.Popen( (sys.executable, self.script) + args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True) as proc: out, err = proc.communicate(source) self.assertIsNone(err) return out def lstriplines(self, data): return '\n'.join(line.lstrip() for line in data.splitlines()) + '\n' def test_selftest(self): self.maxDiff = None with support.temp_dir() as directory: data_path = os.path.join(directory, '_test.py') with open(self.script) as f: closed = f.read() with open(data_path, 'w') as f: f.write(closed) rc, out, err = assert_python_ok(self.script, '-d', data_path) self.assertEqual(out, b'') self.assertEqual(err, b'') backup = data_path + '~' self.assertTrue(os.path.exists(backup)) with open(backup) as f: self.assertEqual(f.read(), closed) with open(data_path) as f: clean = f.read() compile(clean, '_test.py', 'exec') self.assertEqual(self.pindent(clean, '-c'), closed) self.assertEqual(self.pindent(closed, '-d'), clean) rc, out, err = assert_python_ok(self.script, '-c', data_path) self.assertEqual(out, b'') self.assertEqual(err, b'') with open(backup) as f: self.assertEqual(f.read(), clean) with open(data_path) as f: self.assertEqual(f.read(), closed) broken = self.lstriplines(closed) with open(data_path, 'w') as f: f.write(broken) rc, out, err = assert_python_ok(self.script, '-r', data_path) self.assertEqual(out, b'') self.assertEqual(err, b'') with open(backup) as f: self.assertEqual(f.read(), broken) with open(data_path) as f: indented = f.read() compile(indented, '_test.py', 'exec') self.assertEqual(self.pindent(broken, '-r'), indented) def pindent_test(self, clean, closed): self.assertEqual(self.pindent(clean, '-c'), closed) self.assertEqual(self.pindent(closed, '-d'), clean) broken = self.lstriplines(closed) self.assertEqual(self.pindent(broken, '-r', '-e', '-s', '4'), closed) def test_statements(self): clean = textwrap.dedent("""\ if a: pass if a: pass else: pass if a: pass elif: pass else: pass while a: break while a: break else: pass for i in a: break for i in a: break else: pass try: pass finally: pass try: pass except TypeError: pass except ValueError: pass else: pass try: pass except TypeError: pass except ValueError: pass finally: pass with a: pass class A: pass def f(): pass """) closed = textwrap.dedent("""\ if a: pass # end if if a: pass else: pass # end if if a: pass elif: pass else: pass # end if while a: break # end while while a: break else: pass # end while for i in a: break # end for for i in a: break else: pass # end for try: pass finally: pass # end try try: pass except TypeError: pass except ValueError: pass else: pass # end try try: pass except TypeError: pass except ValueError: pass finally: pass # end try with a: pass # end with class A: pass # end class A def f(): pass # end def f """) self.pindent_test(clean, closed) def test_multilevel(self): clean = textwrap.dedent("""\ def foobar(a, b): if a == b: a = a+1 elif a < b: b = b-1 if b > a: a = a-1 else: print 'oops!' """) closed = textwrap.dedent("""\ def foobar(a, b): if a == b: a = a+1 elif a < b: b = b-1 if b > a: a = a-1 # end if else: print 'oops!' # end if # end def foobar """) self.pindent_test(clean, closed) def test_preserve_indents(self): clean = textwrap.dedent("""\ if a: if b: pass """) closed = textwrap.dedent("""\ if a: if b: pass # end if # end if """) self.assertEqual(self.pindent(clean, '-c'), closed) self.assertEqual(self.pindent(closed, '-d'), clean) broken = self.lstriplines(closed) self.assertEqual(self.pindent(broken, '-r', '-e', '-s', '9'), closed) clean = textwrap.dedent("""\ if a: \tif b: \t\tpass """) closed = textwrap.dedent("""\ if a: \tif b: \t\tpass \t# end if # end if """) self.assertEqual(self.pindent(clean, '-c'), closed) self.assertEqual(self.pindent(closed, '-d'), clean) broken = self.lstriplines(closed) self.assertEqual(self.pindent(broken, '-r'), closed) def test_escaped_newline(self): clean = textwrap.dedent("""\ class\\ \\ A: def\ \\ f: pass """) closed = textwrap.dedent("""\ class\\ \\ A: def\ \\ f: pass # end def f # end class A """) self.assertEqual(self.pindent(clean, '-c'), closed) self.assertEqual(self.pindent(closed, '-d'), clean) def test_empty_line(self): clean = textwrap.dedent("""\ if a: pass """) closed = textwrap.dedent("""\ if a: pass # end if """) self.pindent_test(clean, closed) def test_oneline(self): clean = textwrap.dedent("""\ if a: pass """) closed = textwrap.dedent("""\ if a: pass # end if """) self.pindent_test(clean, closed) if __name__ == '__main__': unittest.main()
8,624
340
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_tools/test_fixcid.py
'''Test Tools/scripts/fixcid.py.''' from io import StringIO import os, os.path import runpy import sys from test import support from test.test_tools import skip_if_missing, scriptsdir import unittest skip_if_missing() class Test(unittest.TestCase): def test_parse_strings(self): old1 = 'int xx = "xx\\"xx"[xx];\n' old2 = "int xx = 'x\\'xx' + xx;\n" output = self.run_script(old1 + old2) new1 = 'int yy = "xx\\"xx"[yy];\n' new2 = "int yy = 'x\\'xx' + yy;\n" self.assertMultiLineEqual(output, "1\n" "< {old1}" "> {new1}" "{new1}" "2\n" "< {old2}" "> {new2}" "{new2}".format(old1=old1, old2=old2, new1=new1, new2=new2) ) def test_alter_comments(self): output = self.run_script( substfile= "xx yy\n" "*aa bb\n", args=("-c", "-",), input= "/* xx altered */\n" "int xx;\n" "/* aa unaltered */\n" "int aa;\n", ) self.assertMultiLineEqual(output, "1\n" "< /* xx altered */\n" "> /* yy altered */\n" "/* yy altered */\n" "2\n" "< int xx;\n" "> int yy;\n" "int yy;\n" "/* aa unaltered */\n" "4\n" "< int aa;\n" "> int bb;\n" "int bb;\n" ) def test_directory(self): os.mkdir(support.TESTFN) self.addCleanup(support.rmtree, support.TESTFN) c_filename = os.path.join(support.TESTFN, "file.c") with open(c_filename, "w") as file: file.write("int xx;\n") with open(os.path.join(support.TESTFN, "file.py"), "w") as file: file.write("xx = 'unaltered'\n") script = os.path.join(scriptsdir, "fixcid.py") output = self.run_script(args=(support.TESTFN,)) self.assertMultiLineEqual(output, "{}:\n" "1\n" '< int xx;\n' '> int yy;\n'.format(c_filename) ) def run_script(self, input="", *, args=("-",), substfile="xx yy\n"): substfilename = support.TESTFN + ".subst" with open(substfilename, "w") as file: file.write(substfile) self.addCleanup(support.unlink, substfilename) argv = ["fixcid.py", "-s", substfilename] + list(args) script = os.path.join(scriptsdir, "fixcid.py") with support.swap_attr(sys, "argv", argv), \ support.swap_attr(sys, "stdin", StringIO(input)), \ support.captured_stdout() as output, \ support.captured_stderr(): try: runpy.run_path(script, run_name="__main__") except SystemExit as exit: self.assertEqual(exit.code, 0) return output.getvalue()
2,958
93
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_tools/test_sundry.py
"""Tests for scripts in the Tools directory. This file contains extremely basic regression tests for the scripts found in the Tools directory of a Python checkout or tarball which don't have separate tests of their own, such as h2py.py. """ import os import sys import unittest from test import support from test.test_tools import scriptsdir, import_tool, skip_if_missing skip_if_missing() class TestSundryScripts(unittest.TestCase): # At least make sure the rest don't have syntax errors. When tests are # added for a script it should be added to the whitelist below. # scripts that have independent tests. whitelist = ['reindent', 'pdeps', 'gprof2html', 'md5sum'] # scripts that can't be imported without running blacklist = ['make_ctype'] # scripts that use windows-only modules windows_only = ['win_add2path'] # blacklisted for other reasons other = ['analyze_dxp', '2to3'] skiplist = blacklist + whitelist + windows_only + other def test_sundry(self): old_modules = support.modules_setup() try: for fn in os.listdir(scriptsdir): if not fn.endswith('.py'): continue name = fn[:-3] if name in self.skiplist: continue import_tool(name) finally: # Unload all modules loaded in this test support.modules_cleanup(*old_modules) @unittest.skipIf(sys.platform != "win32", "Windows-only test") def test_sundry_windows(self): for name in self.windows_only: import_tool(name) @unittest.skipIf(not support.threading, "test requires _thread module") def test_analyze_dxp_import(self): if hasattr(sys, 'getdxp'): import_tool('analyze_dxp') else: with self.assertRaises(RuntimeError): import_tool('analyze_dxp') if __name__ == '__main__': unittest.main()
1,967
64
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_tools/__init__.py
"""Support functions for testing scripts in the Tools directory.""" import os import unittest import importlib from test import support basepath = os.path.dirname( # <src/install dir> os.path.dirname( # Lib os.path.dirname( # test os.path.dirname(__file__)))) # test_tools toolsdir = os.path.join(basepath, 'Tools') scriptsdir = os.path.join(toolsdir, 'scripts') def skip_if_missing(): if not os.path.isdir(scriptsdir): raise unittest.SkipTest('scripts directory could not be found') def import_tool(toolname): with support.DirsOnSysPath(scriptsdir): return importlib.import_module(toolname) def load_tests(*args): return support.load_package_tests(os.path.dirname(__file__), *args)
825
25
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_email/test_generator.py
import io import textwrap import unittest from email import message_from_string, message_from_bytes from email.message import EmailMessage from email.generator import Generator, BytesGenerator from email import policy from test.test_email import TestEmailBase, parameterize @parameterize class TestGeneratorBase: policy = policy.default def msgmaker(self, msg, policy=None): policy = self.policy if policy is None else policy return self.msgfunc(msg, policy=policy) refold_long_expected = { 0: textwrap.dedent("""\ To: [email protected] From: [email protected] Subject: We the willing led by the unknowing are doing the impossible for the ungrateful. We have done so much for so long with so little we are now qualified to do anything with nothing. None """), 40: textwrap.dedent("""\ To: [email protected] From: [email protected] Subject: We the willing led by the unknowing are doing the impossible for the ungrateful. We have done so much for so long with so little we are now qualified to do anything with nothing. None """), 20: textwrap.dedent("""\ To: [email protected] From: [email protected] Subject: We the willing led by the unknowing are doing the impossible for the ungrateful. We have done so much for so long with so little we are now qualified to do anything with nothing. None """), } refold_long_expected[100] = refold_long_expected[0] refold_all_expected = refold_long_expected.copy() refold_all_expected[0] = ( "To: [email protected]\n" "From: [email protected]\n" "Subject: We the willing led by the unknowing are doing the " "impossible for the ungrateful. We have done so much for " "so long with so little we are now qualified to do anything " "with nothing.\n" "\n" "None\n") refold_all_expected[100] = ( "To: [email protected]\n" "From: [email protected]\n" "Subject: We the willing led by the unknowing are doing the " "impossible for the ungrateful. We have\n" " done so much for so long with so little we are now qualified " "to do anything with nothing.\n" "\n" "None\n") length_params = [n for n in refold_long_expected] def length_as_maxheaderlen_parameter(self, n): msg = self.msgmaker(self.typ(self.refold_long_expected[0])) s = self.ioclass() g = self.genclass(s, maxheaderlen=n, policy=self.policy) g.flatten(msg) self.assertEqual(s.getvalue(), self.typ(self.refold_long_expected[n])) def length_as_max_line_length_policy(self, n): msg = self.msgmaker(self.typ(self.refold_long_expected[0])) s = self.ioclass() g = self.genclass(s, policy=self.policy.clone(max_line_length=n)) g.flatten(msg) self.assertEqual(s.getvalue(), self.typ(self.refold_long_expected[n])) def length_as_maxheaderlen_parm_overrides_policy(self, n): msg = self.msgmaker(self.typ(self.refold_long_expected[0])) s = self.ioclass() g = self.genclass(s, maxheaderlen=n, policy=self.policy.clone(max_line_length=10)) g.flatten(msg) self.assertEqual(s.getvalue(), self.typ(self.refold_long_expected[n])) def length_as_max_line_length_with_refold_none_does_not_fold(self, n): msg = self.msgmaker(self.typ(self.refold_long_expected[0])) s = self.ioclass() g = self.genclass(s, policy=self.policy.clone(refold_source='none', max_line_length=n)) g.flatten(msg) self.assertEqual(s.getvalue(), self.typ(self.refold_long_expected[0])) def length_as_max_line_length_with_refold_all_folds(self, n): msg = self.msgmaker(self.typ(self.refold_long_expected[0])) s = self.ioclass() g = self.genclass(s, policy=self.policy.clone(refold_source='all', max_line_length=n)) g.flatten(msg) self.assertEqual(s.getvalue(), self.typ(self.refold_all_expected[n])) def test_crlf_control_via_policy(self): source = "Subject: test\r\n\r\ntest body\r\n" expected = source msg = self.msgmaker(self.typ(source)) s = self.ioclass() g = self.genclass(s, policy=policy.SMTP) g.flatten(msg) self.assertEqual(s.getvalue(), self.typ(expected)) def test_flatten_linesep_overrides_policy(self): source = "Subject: test\n\ntest body\n" expected = source msg = self.msgmaker(self.typ(source)) s = self.ioclass() g = self.genclass(s, policy=policy.SMTP) g.flatten(msg, linesep='\n') self.assertEqual(s.getvalue(), self.typ(expected)) def test_set_mangle_from_via_policy(self): source = textwrap.dedent("""\ Subject: test that from is mangled in the body! From time to time I write a rhyme. """) variants = ( (None, True), (policy.compat32, True), (policy.default, False), (policy.default.clone(mangle_from_=True), True), ) for p, mangle in variants: expected = source.replace('From ', '>From ') if mangle else source with self.subTest(policy=p, mangle_from_=mangle): msg = self.msgmaker(self.typ(source)) s = self.ioclass() g = self.genclass(s, policy=p) g.flatten(msg) self.assertEqual(s.getvalue(), self.typ(expected)) def test_compat32_max_line_length_does_not_fold_when_none(self): msg = self.msgmaker(self.typ(self.refold_long_expected[0])) s = self.ioclass() g = self.genclass(s, policy=policy.compat32.clone(max_line_length=None)) g.flatten(msg) self.assertEqual(s.getvalue(), self.typ(self.refold_long_expected[0])) def test_rfc2231_wrapping(self): # This is pretty much just to make sure we don't have an infinite # loop; I don't expect anyone to hit this in the field. msg = self.msgmaker(self.typ(textwrap.dedent("""\ To: nobody Content-Disposition: attachment; filename="afilenamelongenoghtowraphere" None """))) expected = textwrap.dedent("""\ To: nobody Content-Disposition: attachment; filename*0*=us-ascii''afilename; filename*1*=longenoghtowraphere None """) s = self.ioclass() g = self.genclass(s, policy=self.policy.clone(max_line_length=33)) g.flatten(msg) self.assertEqual(s.getvalue(), self.typ(expected)) def test_rfc2231_wrapping_switches_to_default_len_if_too_narrow(self): # This is just to make sure we don't have an infinite loop; I don't # expect anyone to hit this in the field, so I'm not bothering to make # the result optimal (the encoding isn't needed). msg = self.msgmaker(self.typ(textwrap.dedent("""\ To: nobody Content-Disposition: attachment; filename="afilenamelongenoghtowraphere" None """))) expected = textwrap.dedent("""\ To: nobody Content-Disposition: attachment; filename*0*=us-ascii''afilenamelongenoghtowraphere None """) s = self.ioclass() g = self.genclass(s, policy=self.policy.clone(max_line_length=20)) g.flatten(msg) self.assertEqual(s.getvalue(), self.typ(expected)) class TestGenerator(TestGeneratorBase, TestEmailBase): msgfunc = staticmethod(message_from_string) genclass = Generator ioclass = io.StringIO typ = str class TestBytesGenerator(TestGeneratorBase, TestEmailBase): msgfunc = staticmethod(message_from_bytes) genclass = BytesGenerator ioclass = io.BytesIO typ = lambda self, x: x.encode('ascii') def test_cte_type_7bit_handles_unknown_8bit(self): source = ("Subject: Maintenant je vous présente mon " "collègue\n\n").encode('utf-8') expected = ('Subject: Maintenant je vous =?unknown-8bit?q?' 'pr=C3=A9sente_mon_coll=C3=A8gue?=\n\n').encode('ascii') msg = message_from_bytes(source) s = io.BytesIO() g = BytesGenerator(s, policy=self.policy.clone(cte_type='7bit')) g.flatten(msg) self.assertEqual(s.getvalue(), expected) def test_cte_type_7bit_transforms_8bit_cte(self): source = textwrap.dedent("""\ From: [email protected] To: Dinsdale Subject: Nudge nudge, wink, wink Mime-Version: 1.0 Content-Type: text/plain; charset="latin-1" Content-Transfer-Encoding: 8bit oh là là, know what I mean, know what I mean? """).encode('latin1') msg = message_from_bytes(source) expected = textwrap.dedent("""\ From: [email protected] To: Dinsdale Subject: Nudge nudge, wink, wink Mime-Version: 1.0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable oh l=E0 l=E0, know what I mean, know what I mean? """).encode('ascii') s = io.BytesIO() g = BytesGenerator(s, policy=self.policy.clone(cte_type='7bit', linesep='\n')) g.flatten(msg) self.assertEqual(s.getvalue(), expected) def test_smtputf8_policy(self): msg = EmailMessage() msg['From'] = "Páolo <fő[email protected]>" msg['To'] = 'Dinsdale' msg['Subject'] = 'Nudge nudge, wink, wink \u1F609' msg.set_content("oh là là, know what I mean, know what I mean?") expected = textwrap.dedent("""\ From: Páolo <fő[email protected]> To: Dinsdale Subject: Nudge nudge, wink, wink \u1F609 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: 8bit MIME-Version: 1.0 oh là là, know what I mean, know what I mean? """).encode('utf-8').replace(b'\n', b'\r\n') s = io.BytesIO() g = BytesGenerator(s, policy=policy.SMTPUTF8) g.flatten(msg) self.assertEqual(s.getvalue(), expected) if __name__ == '__main__': unittest.main()
11,233
297
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_email/test_message.py
import unittest import textwrap from email import policy, message_from_string from email.message import EmailMessage, MIMEPart from test.test_email import TestEmailBase, parameterize # Helper. def first(iterable): return next(filter(lambda x: x is not None, iterable), None) class Test(TestEmailBase): policy = policy.default def test_error_on_setitem_if_max_count_exceeded(self): m = self._str_msg("") m['To'] = 'abc@xyz' with self.assertRaises(ValueError): m['To'] = 'xyz@abc' def test_rfc2043_auto_decoded_and_emailmessage_used(self): m = message_from_string(textwrap.dedent("""\ Subject: Ayons asperges pour le =?utf-8?q?d=C3=A9jeuner?= From: =?utf-8?q?Pep=C3=A9?= Le Pew <[email protected]> To: "Penelope Pussycat" <"[email protected]"> MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" sample text """), policy=policy.default) self.assertEqual(m['subject'], "Ayons asperges pour le déjeuner") self.assertEqual(m['from'], "Pepé Le Pew <[email protected]>") self.assertIsInstance(m, EmailMessage) @parameterize class TestEmailMessageBase: policy = policy.default # The first argument is a triple (related, html, plain) of indices into the # list returned by 'walk' called on a Message constructed from the third. # The indices indicate which part should match the corresponding part-type # when passed to get_body (ie: the "first" part of that type in the # message). The second argument is a list of indices into the 'walk' list # of the attachments that should be returned by a call to # 'iter_attachments'. The third argument is a list of indices into 'walk' # that should be returned by a call to 'iter_parts'. Note that the first # item returned by 'walk' is the Message itself. message_params = { 'empty_message': ( (None, None, 0), (), (), ""), 'non_mime_plain': ( (None, None, 0), (), (), textwrap.dedent("""\ To: [email protected] simple text body """)), 'mime_non_text': ( (None, None, None), (), (), textwrap.dedent("""\ To: [email protected] MIME-Version: 1.0 Content-Type: image/jpg bogus body. """)), 'plain_html_alternative': ( (None, 2, 1), (), (1, 2), textwrap.dedent("""\ To: [email protected] MIME-Version: 1.0 Content-Type: multipart/alternative; boundary="===" preamble --=== Content-Type: text/plain simple body --=== Content-Type: text/html <p>simple body</p> --===-- """)), 'plain_html_mixed': ( (None, 2, 1), (), (1, 2), textwrap.dedent("""\ To: [email protected] MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="===" preamble --=== Content-Type: text/plain simple body --=== Content-Type: text/html <p>simple body</p> --===-- """)), 'plain_html_attachment_mixed': ( (None, None, 1), (2,), (1, 2), textwrap.dedent("""\ To: [email protected] MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="===" --=== Content-Type: text/plain simple body --=== Content-Type: text/html Content-Disposition: attachment <p>simple body</p> --===-- """)), 'html_text_attachment_mixed': ( (None, 2, None), (1,), (1, 2), textwrap.dedent("""\ To: [email protected] MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="===" --=== Content-Type: text/plain Content-Disposition: AtTaChment simple body --=== Content-Type: text/html <p>simple body</p> --===-- """)), 'html_text_attachment_inline_mixed': ( (None, 2, 1), (), (1, 2), textwrap.dedent("""\ To: [email protected] MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="===" --=== Content-Type: text/plain Content-Disposition: InLine simple body --=== Content-Type: text/html Content-Disposition: inline <p>simple body</p> --===-- """)), # RFC 2387 'related': ( (0, 1, None), (2,), (1, 2), textwrap.dedent("""\ To: [email protected] MIME-Version: 1.0 Content-Type: multipart/related; boundary="==="; type=text/html --=== Content-Type: text/html <p>simple body</p> --=== Content-Type: image/jpg Content-ID: <image1> bogus data --===-- """)), # This message structure will probably never be seen in the wild, but # it proves we distinguish between text parts based on 'start'. The # content would not, of course, actually work :) 'related_with_start': ( (0, 2, None), (1,), (1, 2), textwrap.dedent("""\ To: [email protected] MIME-Version: 1.0 Content-Type: multipart/related; boundary="==="; type=text/html; start="<body>" --=== Content-Type: text/html Content-ID: <include> useless text --=== Content-Type: text/html Content-ID: <body> <p>simple body</p> <!--#include file="<include>"--> --===-- """)), 'mixed_alternative_plain_related': ( (3, 4, 2), (6, 7), (1, 6, 7), textwrap.dedent("""\ To: [email protected] MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="===" --=== Content-Type: multipart/alternative; boundary="+++" --+++ Content-Type: text/plain simple body --+++ Content-Type: multipart/related; boundary="___" --___ Content-Type: text/html <p>simple body</p> --___ Content-Type: image/jpg Content-ID: <image1@cid> bogus jpg body --___-- --+++-- --=== Content-Type: image/jpg Content-Disposition: attachment bogus jpg body --=== Content-Type: image/jpg Content-Disposition: AttacHmenT another bogus jpg body --===-- """)), # This structure suggested by Stephen J. Turnbull...may not exist/be # supported in the wild, but we want to support it. 'mixed_related_alternative_plain_html': ( (1, 4, 3), (6, 7), (1, 6, 7), textwrap.dedent("""\ To: [email protected] MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="===" --=== Content-Type: multipart/related; boundary="+++" --+++ Content-Type: multipart/alternative; boundary="___" --___ Content-Type: text/plain simple body --___ Content-Type: text/html <p>simple body</p> --___-- --+++ Content-Type: image/jpg Content-ID: <image1@cid> bogus jpg body --+++-- --=== Content-Type: image/jpg Content-Disposition: attachment bogus jpg body --=== Content-Type: image/jpg Content-Disposition: attachment another bogus jpg body --===-- """)), # Same thing, but proving we only look at the root part, which is the # first one if there isn't any start parameter. That is, this is a # broken related. 'mixed_related_alternative_plain_html_wrong_order': ( (1, None, None), (6, 7), (1, 6, 7), textwrap.dedent("""\ To: [email protected] MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="===" --=== Content-Type: multipart/related; boundary="+++" --+++ Content-Type: image/jpg Content-ID: <image1@cid> bogus jpg body --+++ Content-Type: multipart/alternative; boundary="___" --___ Content-Type: text/plain simple body --___ Content-Type: text/html <p>simple body</p> --___-- --+++-- --=== Content-Type: image/jpg Content-Disposition: attachment bogus jpg body --=== Content-Type: image/jpg Content-Disposition: attachment another bogus jpg body --===-- """)), 'message_rfc822': ( (None, None, None), (), (), textwrap.dedent("""\ To: [email protected] MIME-Version: 1.0 Content-Type: message/rfc822 To: [email protected] From: [email protected] this is a message body. """)), 'mixed_text_message_rfc822': ( (None, None, 1), (2,), (1, 2), textwrap.dedent("""\ To: [email protected] MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="===" --=== Content-Type: text/plain Your message has bounced, ser. --=== Content-Type: message/rfc822 To: [email protected] From: [email protected] this is a message body. --===-- """)), } def message_as_get_body(self, body_parts, attachments, parts, msg): m = self._str_msg(msg) allparts = list(m.walk()) expected = [None if n is None else allparts[n] for n in body_parts] related = 0; html = 1; plain = 2 self.assertEqual(m.get_body(), first(expected)) self.assertEqual(m.get_body(preferencelist=( 'related', 'html', 'plain')), first(expected)) self.assertEqual(m.get_body(preferencelist=('related', 'html')), first(expected[related:html+1])) self.assertEqual(m.get_body(preferencelist=('related', 'plain')), first([expected[related], expected[plain]])) self.assertEqual(m.get_body(preferencelist=('html', 'plain')), first(expected[html:plain+1])) self.assertEqual(m.get_body(preferencelist=['related']), expected[related]) self.assertEqual(m.get_body(preferencelist=['html']), expected[html]) self.assertEqual(m.get_body(preferencelist=['plain']), expected[plain]) self.assertEqual(m.get_body(preferencelist=('plain', 'html')), first(expected[plain:html-1:-1])) self.assertEqual(m.get_body(preferencelist=('plain', 'related')), first([expected[plain], expected[related]])) self.assertEqual(m.get_body(preferencelist=('html', 'related')), first(expected[html::-1])) self.assertEqual(m.get_body(preferencelist=('plain', 'html', 'related')), first(expected[::-1])) self.assertEqual(m.get_body(preferencelist=('html', 'plain', 'related')), first([expected[html], expected[plain], expected[related]])) def message_as_iter_attachment(self, body_parts, attachments, parts, msg): m = self._str_msg(msg) allparts = list(m.walk()) attachments = [allparts[n] for n in attachments] self.assertEqual(list(m.iter_attachments()), attachments) def message_as_iter_parts(self, body_parts, attachments, parts, msg): m = self._str_msg(msg) allparts = list(m.walk()) parts = [allparts[n] for n in parts] self.assertEqual(list(m.iter_parts()), parts) class _TestContentManager: def get_content(self, msg, *args, **kw): return msg, args, kw def set_content(self, msg, *args, **kw): self.msg = msg self.args = args self.kw = kw def test_get_content_with_cm(self): m = self._str_msg('') cm = self._TestContentManager() self.assertEqual(m.get_content(content_manager=cm), (m, (), {})) msg, args, kw = m.get_content('foo', content_manager=cm, bar=1, k=2) self.assertEqual(msg, m) self.assertEqual(args, ('foo',)) self.assertEqual(kw, dict(bar=1, k=2)) def test_get_content_default_cm_comes_from_policy(self): p = policy.default.clone(content_manager=self._TestContentManager()) m = self._str_msg('', policy=p) self.assertEqual(m.get_content(), (m, (), {})) msg, args, kw = m.get_content('foo', bar=1, k=2) self.assertEqual(msg, m) self.assertEqual(args, ('foo',)) self.assertEqual(kw, dict(bar=1, k=2)) def test_set_content_with_cm(self): m = self._str_msg('') cm = self._TestContentManager() m.set_content(content_manager=cm) self.assertEqual(cm.msg, m) self.assertEqual(cm.args, ()) self.assertEqual(cm.kw, {}) m.set_content('foo', content_manager=cm, bar=1, k=2) self.assertEqual(cm.msg, m) self.assertEqual(cm.args, ('foo',)) self.assertEqual(cm.kw, dict(bar=1, k=2)) def test_set_content_default_cm_comes_from_policy(self): cm = self._TestContentManager() p = policy.default.clone(content_manager=cm) m = self._str_msg('', policy=p) m.set_content() self.assertEqual(cm.msg, m) self.assertEqual(cm.args, ()) self.assertEqual(cm.kw, {}) m.set_content('foo', bar=1, k=2) self.assertEqual(cm.msg, m) self.assertEqual(cm.args, ('foo',)) self.assertEqual(cm.kw, dict(bar=1, k=2)) # outcome is whether xxx_method should raise ValueError error when called # on multipart/subtype. Blank outcome means it depends on xxx (add # succeeds, make raises). Note: 'none' means there are content-type # headers but payload is None...this happening in practice would be very # unusual, so treating it as if there were content seems reasonable. # method subtype outcome subtype_params = ( ('related', 'no_content', 'succeeds'), ('related', 'none', 'succeeds'), ('related', 'plain', 'succeeds'), ('related', 'related', ''), ('related', 'alternative', 'raises'), ('related', 'mixed', 'raises'), ('alternative', 'no_content', 'succeeds'), ('alternative', 'none', 'succeeds'), ('alternative', 'plain', 'succeeds'), ('alternative', 'related', 'succeeds'), ('alternative', 'alternative', ''), ('alternative', 'mixed', 'raises'), ('mixed', 'no_content', 'succeeds'), ('mixed', 'none', 'succeeds'), ('mixed', 'plain', 'succeeds'), ('mixed', 'related', 'succeeds'), ('mixed', 'alternative', 'succeeds'), ('mixed', 'mixed', ''), ) def _make_subtype_test_message(self, subtype): m = self.message() payload = None msg_headers = [ ('To', '[email protected]'), ('From', '[email protected]'), ] if subtype != 'no_content': ('content-shadow', 'Logrus'), msg_headers.append(('X-Random-Header', 'Corwin')) if subtype == 'text': payload = '' msg_headers.append(('Content-Type', 'text/plain')) m.set_payload('') elif subtype != 'no_content': payload = [] msg_headers.append(('Content-Type', 'multipart/' + subtype)) msg_headers.append(('X-Trump', 'Random')) m.set_payload(payload) for name, value in msg_headers: m[name] = value return m, msg_headers, payload def _check_disallowed_subtype_raises(self, m, method_name, subtype, method): with self.assertRaises(ValueError) as ar: getattr(m, method)() exc_text = str(ar.exception) self.assertIn(subtype, exc_text) self.assertIn(method_name, exc_text) def _check_make_multipart(self, m, msg_headers, payload): count = 0 for name, value in msg_headers: if not name.lower().startswith('content-'): self.assertEqual(m[name], value) count += 1 self.assertEqual(len(m), count+1) # +1 for new Content-Type part = next(m.iter_parts()) count = 0 for name, value in msg_headers: if name.lower().startswith('content-'): self.assertEqual(part[name], value) count += 1 self.assertEqual(len(part), count) self.assertEqual(part.get_payload(), payload) def subtype_as_make(self, method, subtype, outcome): m, msg_headers, payload = self._make_subtype_test_message(subtype) make_method = 'make_' + method if outcome in ('', 'raises'): self._check_disallowed_subtype_raises(m, method, subtype, make_method) return getattr(m, make_method)() self.assertEqual(m.get_content_maintype(), 'multipart') self.assertEqual(m.get_content_subtype(), method) if subtype == 'no_content': self.assertEqual(len(m.get_payload()), 0) self.assertEqual(m.items(), msg_headers + [('Content-Type', 'multipart/'+method)]) else: self.assertEqual(len(m.get_payload()), 1) self._check_make_multipart(m, msg_headers, payload) def subtype_as_make_with_boundary(self, method, subtype, outcome): # Doing all variation is a bit of overkill... m = self.message() if outcome in ('', 'raises'): m['Content-Type'] = 'multipart/' + subtype with self.assertRaises(ValueError) as cm: getattr(m, 'make_' + method)() return if subtype == 'plain': m['Content-Type'] = 'text/plain' elif subtype != 'no_content': m['Content-Type'] = 'multipart/' + subtype getattr(m, 'make_' + method)(boundary="abc") self.assertTrue(m.is_multipart()) self.assertEqual(m.get_boundary(), 'abc') def test_policy_on_part_made_by_make_comes_from_message(self): for method in ('make_related', 'make_alternative', 'make_mixed'): m = self.message(policy=self.policy.clone(content_manager='foo')) m['Content-Type'] = 'text/plain' getattr(m, method)() self.assertEqual(m.get_payload(0).policy.content_manager, 'foo') class _TestSetContentManager: def set_content(self, msg, content, *args, **kw): msg['Content-Type'] = 'text/plain' msg.set_payload(content) def subtype_as_add(self, method, subtype, outcome): m, msg_headers, payload = self._make_subtype_test_message(subtype) cm = self._TestSetContentManager() add_method = 'add_attachment' if method=='mixed' else 'add_' + method if outcome == 'raises': self._check_disallowed_subtype_raises(m, method, subtype, add_method) return getattr(m, add_method)('test', content_manager=cm) self.assertEqual(m.get_content_maintype(), 'multipart') self.assertEqual(m.get_content_subtype(), method) if method == subtype or subtype == 'no_content': self.assertEqual(len(m.get_payload()), 1) for name, value in msg_headers: self.assertEqual(m[name], value) part = m.get_payload()[0] else: self.assertEqual(len(m.get_payload()), 2) self._check_make_multipart(m, msg_headers, payload) part = m.get_payload()[1] self.assertEqual(part.get_content_type(), 'text/plain') self.assertEqual(part.get_payload(), 'test') if method=='mixed': self.assertEqual(part['Content-Disposition'], 'attachment') elif method=='related': self.assertEqual(part['Content-Disposition'], 'inline') else: # Otherwise we don't guess. self.assertIsNone(part['Content-Disposition']) class _TestSetRaisingContentManager: def set_content(self, msg, content, *args, **kw): raise Exception('test') def test_default_content_manager_for_add_comes_from_policy(self): cm = self._TestSetRaisingContentManager() m = self.message(policy=self.policy.clone(content_manager=cm)) for method in ('add_related', 'add_alternative', 'add_attachment'): with self.assertRaises(Exception) as ar: getattr(m, method)('') self.assertEqual(str(ar.exception), 'test') def message_as_clear(self, body_parts, attachments, parts, msg): m = self._str_msg(msg) m.clear() self.assertEqual(len(m), 0) self.assertEqual(list(m.items()), []) self.assertIsNone(m.get_payload()) self.assertEqual(list(m.iter_parts()), []) def message_as_clear_content(self, body_parts, attachments, parts, msg): m = self._str_msg(msg) expected_headers = [h for h in m.keys() if not h.lower().startswith('content-')] m.clear_content() self.assertEqual(list(m.keys()), expected_headers) self.assertIsNone(m.get_payload()) self.assertEqual(list(m.iter_parts()), []) def test_is_attachment(self): m = self._make_message() self.assertFalse(m.is_attachment()) m['Content-Disposition'] = 'inline' self.assertFalse(m.is_attachment()) m.replace_header('Content-Disposition', 'attachment') self.assertTrue(m.is_attachment()) m.replace_header('Content-Disposition', 'AtTachMent') self.assertTrue(m.is_attachment()) m.set_param('filename', 'abc.png', 'Content-Disposition') self.assertTrue(m.is_attachment()) def test_iter_attachments_mutation(self): # We had a bug where iter_attachments was mutating the list. m = self._make_message() m.set_content('arbitrary text as main part') m.add_related('more text as a related part') m.add_related('yet more text as a second "attachment"') orig = m.get_payload().copy() self.assertEqual(len(list(m.iter_attachments())), 2) self.assertEqual(m.get_payload(), orig) class TestEmailMessage(TestEmailMessageBase, TestEmailBase): message = EmailMessage def test_set_content_adds_MIME_Version(self): m = self._str_msg('') cm = self._TestContentManager() self.assertNotIn('MIME-Version', m) m.set_content(content_manager=cm) self.assertEqual(m['MIME-Version'], '1.0') class _MIME_Version_adding_CM: def set_content(self, msg, *args, **kw): msg['MIME-Version'] = '1.0' def test_set_content_does_not_duplicate_MIME_Version(self): m = self._str_msg('') cm = self._MIME_Version_adding_CM() self.assertNotIn('MIME-Version', m) m.set_content(content_manager=cm) self.assertEqual(m['MIME-Version'], '1.0') def test_as_string_uses_max_header_length_by_default(self): m = self._str_msg('Subject: long line' + ' ab'*50 + '\n\n') self.assertEqual(len(m.as_string().strip().splitlines()), 3) def test_as_string_allows_maxheaderlen(self): m = self._str_msg('Subject: long line' + ' ab'*50 + '\n\n') self.assertEqual(len(m.as_string(maxheaderlen=0).strip().splitlines()), 1) self.assertEqual(len(m.as_string(maxheaderlen=34).strip().splitlines()), 6) def test_str_defaults_to_policy_max_line_length(self): m = self._str_msg('Subject: long line' + ' ab'*50 + '\n\n') self.assertEqual(len(str(m).strip().splitlines()), 3) def test_str_defaults_to_utf8(self): m = EmailMessage() m['Subject'] = 'unicöde' self.assertEqual(str(m), 'Subject: unicöde\n\n') class TestMIMEPart(TestEmailMessageBase, TestEmailBase): # Doing the full test run here may seem a bit redundant, since the two # classes are almost identical. But what if they drift apart? So we do # the full tests so that any future drift doesn't introduce bugs. message = MIMEPart def test_set_content_does_not_add_MIME_Version(self): m = self._str_msg('') cm = self._TestContentManager() self.assertNotIn('MIME-Version', m) m.set_content(content_manager=cm) self.assertNotIn('MIME-Version', m) if __name__ == '__main__': unittest.main()
27,251
804
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_email/test_policy.py
import io import types import textwrap import unittest import email.errors import email.policy import email.parser import email.generator import email.message from email import headerregistry def make_defaults(base_defaults, differences): defaults = base_defaults.copy() defaults.update(differences) return defaults class PolicyAPITests(unittest.TestCase): longMessage = True # Base default values. compat32_defaults = { 'max_line_length': 78, 'linesep': '\n', 'cte_type': '8bit', 'raise_on_defect': False, 'mangle_from_': True, 'message_factory': None, } # These default values are the ones set on email.policy.default. # If any of these defaults change, the docs must be updated. policy_defaults = compat32_defaults.copy() policy_defaults.update({ 'utf8': False, 'raise_on_defect': False, 'header_factory': email.policy.EmailPolicy.header_factory, 'refold_source': 'long', 'content_manager': email.policy.EmailPolicy.content_manager, 'mangle_from_': False, 'message_factory': email.message.EmailMessage, }) # For each policy under test, we give here what we expect the defaults to # be for that policy. The second argument to make defaults is the # difference between the base defaults and that for the particular policy. new_policy = email.policy.EmailPolicy() policies = { email.policy.compat32: make_defaults(compat32_defaults, {}), email.policy.default: make_defaults(policy_defaults, {}), email.policy.SMTP: make_defaults(policy_defaults, {'linesep': '\r\n'}), email.policy.SMTPUTF8: make_defaults(policy_defaults, {'linesep': '\r\n', 'utf8': True}), email.policy.HTTP: make_defaults(policy_defaults, {'linesep': '\r\n', 'max_line_length': None}), email.policy.strict: make_defaults(policy_defaults, {'raise_on_defect': True}), new_policy: make_defaults(policy_defaults, {}), } # Creating a new policy creates a new header factory. There is a test # later that proves this. policies[new_policy]['header_factory'] = new_policy.header_factory def test_defaults(self): for policy, expected in self.policies.items(): for attr, value in expected.items(): with self.subTest(policy=policy, attr=attr): self.assertEqual(getattr(policy, attr), value, ("change {} docs/docstrings if defaults have " "changed").format(policy)) def test_all_attributes_covered(self): for policy, expected in self.policies.items(): for attr in dir(policy): with self.subTest(policy=policy, attr=attr): if (attr.startswith('_') or isinstance(getattr(email.policy.EmailPolicy, attr), types.FunctionType)): continue else: self.assertIn(attr, expected, "{} is not fully tested".format(attr)) def test_abc(self): with self.assertRaises(TypeError) as cm: email.policy.Policy() msg = str(cm.exception) abstract_methods = ('fold', 'fold_binary', 'header_fetch_parse', 'header_source_parse', 'header_store_parse') for method in abstract_methods: self.assertIn(method, msg) def test_policy_is_immutable(self): for policy, defaults in self.policies.items(): for attr in defaults: with self.assertRaisesRegex(AttributeError, attr+".*read-only"): setattr(policy, attr, None) with self.assertRaisesRegex(AttributeError, 'no attribute.*foo'): policy.foo = None def test_set_policy_attrs_when_cloned(self): # None of the attributes has a default value of None, so we set them # all to None in the clone call and check that it worked. for policyclass, defaults in self.policies.items(): testattrdict = {attr: None for attr in defaults} policy = policyclass.clone(**testattrdict) for attr in defaults: self.assertIsNone(getattr(policy, attr)) def test_reject_non_policy_keyword_when_called(self): for policyclass in self.policies: with self.assertRaises(TypeError): policyclass(this_keyword_should_not_be_valid=None) with self.assertRaises(TypeError): policyclass(newtline=None) def test_policy_addition(self): expected = self.policy_defaults.copy() p1 = email.policy.default.clone(max_line_length=100) p2 = email.policy.default.clone(max_line_length=50) added = p1 + p2 expected.update(max_line_length=50) for attr, value in expected.items(): self.assertEqual(getattr(added, attr), value) added = p2 + p1 expected.update(max_line_length=100) for attr, value in expected.items(): self.assertEqual(getattr(added, attr), value) added = added + email.policy.default for attr, value in expected.items(): self.assertEqual(getattr(added, attr), value) def test_register_defect(self): class Dummy: def __init__(self): self.defects = [] obj = Dummy() defect = object() policy = email.policy.EmailPolicy() policy.register_defect(obj, defect) self.assertEqual(obj.defects, [defect]) defect2 = object() policy.register_defect(obj, defect2) self.assertEqual(obj.defects, [defect, defect2]) class MyObj: def __init__(self): self.defects = [] class MyDefect(Exception): pass def test_handle_defect_raises_on_strict(self): foo = self.MyObj() defect = self.MyDefect("the telly is broken") with self.assertRaisesRegex(self.MyDefect, "the telly is broken"): email.policy.strict.handle_defect(foo, defect) def test_handle_defect_registers_defect(self): foo = self.MyObj() defect1 = self.MyDefect("one") email.policy.default.handle_defect(foo, defect1) self.assertEqual(foo.defects, [defect1]) defect2 = self.MyDefect("two") email.policy.default.handle_defect(foo, defect2) self.assertEqual(foo.defects, [defect1, defect2]) class MyPolicy(email.policy.EmailPolicy): defects = None def __init__(self, *args, **kw): super().__init__(*args, defects=[], **kw) def register_defect(self, obj, defect): self.defects.append(defect) def test_overridden_register_defect_still_raises(self): foo = self.MyObj() defect = self.MyDefect("the telly is broken") with self.assertRaisesRegex(self.MyDefect, "the telly is broken"): self.MyPolicy(raise_on_defect=True).handle_defect(foo, defect) def test_overridden_register_defect_works(self): foo = self.MyObj() defect1 = self.MyDefect("one") my_policy = self.MyPolicy() my_policy.handle_defect(foo, defect1) self.assertEqual(my_policy.defects, [defect1]) self.assertEqual(foo.defects, []) defect2 = self.MyDefect("two") my_policy.handle_defect(foo, defect2) self.assertEqual(my_policy.defects, [defect1, defect2]) self.assertEqual(foo.defects, []) def test_default_header_factory(self): h = email.policy.default.header_factory('Test', 'test') self.assertEqual(h.name, 'Test') self.assertIsInstance(h, headerregistry.UnstructuredHeader) self.assertIsInstance(h, headerregistry.BaseHeader) class Foo: parse = headerregistry.UnstructuredHeader.parse def test_each_Policy_gets_unique_factory(self): policy1 = email.policy.EmailPolicy() policy2 = email.policy.EmailPolicy() policy1.header_factory.map_to_type('foo', self.Foo) h = policy1.header_factory('foo', 'test') self.assertIsInstance(h, self.Foo) self.assertNotIsInstance(h, headerregistry.UnstructuredHeader) h = policy2.header_factory('foo', 'test') self.assertNotIsInstance(h, self.Foo) self.assertIsInstance(h, headerregistry.UnstructuredHeader) def test_clone_copies_factory(self): policy1 = email.policy.EmailPolicy() policy2 = policy1.clone() policy1.header_factory.map_to_type('foo', self.Foo) h = policy1.header_factory('foo', 'test') self.assertIsInstance(h, self.Foo) h = policy2.header_factory('foo', 'test') self.assertIsInstance(h, self.Foo) def test_new_factory_overrides_default(self): mypolicy = email.policy.EmailPolicy() myfactory = mypolicy.header_factory newpolicy = mypolicy + email.policy.strict self.assertEqual(newpolicy.header_factory, myfactory) newpolicy = email.policy.strict + mypolicy self.assertEqual(newpolicy.header_factory, myfactory) def test_adding_default_policies_preserves_default_factory(self): newpolicy = email.policy.default + email.policy.strict self.assertEqual(newpolicy.header_factory, email.policy.EmailPolicy.header_factory) self.assertEqual(newpolicy.__dict__, {'raise_on_defect': True}) def test_non_ascii_chars_do_not_cause_inf_loop(self): policy = email.policy.default.clone(max_line_length=20) actual = policy.fold('Subject', 'ą' * 12) self.assertEqual( actual, 'Subject: \n' + 12 * ' =?utf-8?q?=C4=85?=\n') def test_short_maxlen_error(self): # RFC 2047 chrome takes up 7 characters, plus the length of the charset # name, so folding should fail if maxlen is lower than the minimum # required length for a line. # Note: This is only triggered when there is a single word longer than # max_line_length, hence the 1234567890 at the end of this whimsical # subject. This is because when we encounter a word longer than # max_line_length, it is broken down into encoded words to fit # max_line_length. If the max_line_length isn't large enough to even # contain the RFC 2047 chrome (`?=<charset>?q??=`), we fail. subject = "Melt away the pounds with this one simple trick! 1234567890" for maxlen in [3, 7, 9]: with self.subTest(maxlen=maxlen): policy = email.policy.default.clone(max_line_length=maxlen) with self.assertRaises(email.errors.HeaderParseError): policy.fold("Subject", subject) # XXX: Need subclassing tests. # For adding subclassed objects, make sure the usual rules apply (subclass # wins), but that the order still works (right overrides left). class TestException(Exception): pass class TestPolicyPropagation(unittest.TestCase): # The abstract methods are used by the parser but not by the wrapper # functions that call it, so if the exception gets raised we know that the # policy was actually propagated all the way to feedparser. class MyPolicy(email.policy.Policy): def badmethod(self, *args, **kw): raise TestException("test") fold = fold_binary = header_fetch_parser = badmethod header_source_parse = header_store_parse = badmethod def test_message_from_string(self): with self.assertRaisesRegex(TestException, "^test$"): email.message_from_string("Subject: test\n\n", policy=self.MyPolicy) def test_message_from_bytes(self): with self.assertRaisesRegex(TestException, "^test$"): email.message_from_bytes(b"Subject: test\n\n", policy=self.MyPolicy) def test_message_from_file(self): f = io.StringIO('Subject: test\n\n') with self.assertRaisesRegex(TestException, "^test$"): email.message_from_file(f, policy=self.MyPolicy) def test_message_from_binary_file(self): f = io.BytesIO(b'Subject: test\n\n') with self.assertRaisesRegex(TestException, "^test$"): email.message_from_binary_file(f, policy=self.MyPolicy) # These are redundant, but we need them for black-box completeness. def test_parser(self): p = email.parser.Parser(policy=self.MyPolicy) with self.assertRaisesRegex(TestException, "^test$"): p.parsestr('Subject: test\n\n') def test_bytes_parser(self): p = email.parser.BytesParser(policy=self.MyPolicy) with self.assertRaisesRegex(TestException, "^test$"): p.parsebytes(b'Subject: test\n\n') # Now that we've established that all the parse methods get the # policy in to feedparser, we can use message_from_string for # the rest of the propagation tests. def _make_msg(self, source='Subject: test\n\n', policy=None): self.policy = email.policy.default.clone() if policy is None else policy return email.message_from_string(source, policy=self.policy) def test_parser_propagates_policy_to_message(self): msg = self._make_msg() self.assertIs(msg.policy, self.policy) def test_parser_propagates_policy_to_sub_messages(self): msg = self._make_msg(textwrap.dedent("""\ Subject: mime test MIME-Version: 1.0 Content-Type: multipart/mixed, boundary="XXX" --XXX Content-Type: text/plain test --XXX Content-Type: text/plain test2 --XXX-- """)) for part in msg.walk(): self.assertIs(part.policy, self.policy) def test_message_policy_propagates_to_generator(self): msg = self._make_msg("Subject: test\nTo: foo\n\n", policy=email.policy.default.clone(linesep='X')) s = io.StringIO() g = email.generator.Generator(s) g.flatten(msg) self.assertEqual(s.getvalue(), "Subject: testXTo: fooXX") def test_message_policy_used_by_as_string(self): msg = self._make_msg("Subject: test\nTo: foo\n\n", policy=email.policy.default.clone(linesep='X')) self.assertEqual(msg.as_string(), "Subject: testXTo: fooXX") class TestConcretePolicies(unittest.TestCase): def test_header_store_parse_rejects_newlines(self): instance = email.policy.EmailPolicy() self.assertRaises(ValueError, instance.header_store_parse, 'From', 'spam\[email protected]') if __name__ == '__main__': unittest.main()
15,442
375
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_email/test_pickleable.py
import unittest import textwrap import copy import pickle import email import email.message from email import policy from email.headerregistry import HeaderRegistry from test.test_email import TestEmailBase, parameterize @parameterize class TestPickleCopyHeader(TestEmailBase): header_factory = HeaderRegistry() unstructured = header_factory('subject', 'this is a test') header_params = { 'subject': ('subject', 'this is a test'), 'from': ('from', '[email protected]'), 'to': ('to', 'a: [email protected], [email protected];, [email protected]'), 'date': ('date', 'Tue, 29 May 2012 09:24:26 +1000'), } def header_as_deepcopy(self, name, value): header = self.header_factory(name, value) h = copy.deepcopy(header) self.assertEqual(str(h), str(header)) def header_as_pickle(self, name, value): header = self.header_factory(name, value) for proto in range(pickle.HIGHEST_PROTOCOL + 1): p = pickle.dumps(header, proto) h = pickle.loads(p) self.assertEqual(str(h), str(header)) @parameterize class TestPickleCopyMessage(TestEmailBase): # Message objects are a sequence, so we have to make them a one-tuple in # msg_params so they get passed to the parameterized test method as a # single argument instead of as a list of headers. msg_params = {} # Note: there will be no custom header objects in the parsed message. msg_params['parsed'] = (email.message_from_string(textwrap.dedent("""\ Date: Tue, 29 May 2012 09:24:26 +1000 From: [email protected] To: [email protected] Subject: help I think I forgot the ring. """), policy=policy.default),) msg_params['created'] = (email.message.Message(policy=policy.default),) msg_params['created'][0]['Date'] = 'Tue, 29 May 2012 09:24:26 +1000' msg_params['created'][0]['From'] = '[email protected]' msg_params['created'][0]['To'] = '[email protected]' msg_params['created'][0]['Subject'] = 'help' msg_params['created'][0].set_payload('I think I forgot the ring.') def msg_as_deepcopy(self, msg): msg2 = copy.deepcopy(msg) self.assertEqual(msg2.as_string(), msg.as_string()) def msg_as_pickle(self, msg): for proto in range(pickle.HIGHEST_PROTOCOL + 1): p = pickle.dumps(msg, proto) msg2 = pickle.loads(p) self.assertEqual(msg2.as_string(), msg.as_string()) if __name__ == '__main__': unittest.main()
2,549
77
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_email/test__header_value_parser.py
import string import unittest from email import _header_value_parser as parser from email import errors from email import policy from test.test_email import TestEmailBase, parameterize class TestTokens(TestEmailBase): # EWWhiteSpaceTerminal def test_EWWhiteSpaceTerminal(self): x = parser.EWWhiteSpaceTerminal(' \t', 'fws') self.assertEqual(x, ' \t') self.assertEqual(str(x), '') self.assertEqual(x.value, '') self.assertEqual(x.token_type, 'fws') class TestParserMixin: def _assert_results(self, tl, rest, string, value, defects, remainder, comments=None): self.assertEqual(str(tl), string) self.assertEqual(tl.value, value) self.assertDefectsEqual(tl.all_defects, defects) self.assertEqual(rest, remainder) if comments is not None: self.assertEqual(tl.comments, comments) def _test_get_x(self, method, source, string, value, defects, remainder, comments=None): tl, rest = method(source) self._assert_results(tl, rest, string, value, defects, remainder, comments=None) return tl def _test_parse_x(self, method, input, string, value, defects, comments=None): tl = method(input) self._assert_results(tl, '', string, value, defects, '', comments) return tl class TestParser(TestParserMixin, TestEmailBase): # _wsp_splitter rfc_printable_ascii = bytes(range(33, 127)).decode('ascii') rfc_atext_chars = (string.ascii_letters + string.digits + "!#$%&\'*+-/=?^_`{}|~") rfc_dtext_chars = rfc_printable_ascii.translate(str.maketrans('','',r'\[]')) def test__wsp_splitter_one_word(self): self.assertEqual(parser._wsp_splitter('foo', 1), ['foo']) def test__wsp_splitter_two_words(self): self.assertEqual(parser._wsp_splitter('foo def', 1), ['foo', ' ', 'def']) def test__wsp_splitter_ws_runs(self): self.assertEqual(parser._wsp_splitter('foo \t def jik', 1), ['foo', ' \t ', 'def jik']) # get_fws def test_get_fws_only(self): fws = self._test_get_x(parser.get_fws, ' \t ', ' \t ', ' ', [], '') self.assertEqual(fws.token_type, 'fws') def test_get_fws_space(self): self._test_get_x(parser.get_fws, ' foo', ' ', ' ', [], 'foo') def test_get_fws_ws_run(self): self._test_get_x(parser.get_fws, ' \t foo ', ' \t ', ' ', [], 'foo ') # get_encoded_word def test_get_encoded_word_missing_start_raises(self): with self.assertRaises(errors.HeaderParseError): parser.get_encoded_word('abc') def test_get_encoded_word_missing_end_raises(self): with self.assertRaises(errors.HeaderParseError): parser.get_encoded_word('=?abc') def test_get_encoded_word_missing_middle_raises(self): with self.assertRaises(errors.HeaderParseError): parser.get_encoded_word('=?abc?=') def test_get_encoded_word_valid_ew(self): self._test_get_x(parser.get_encoded_word, '=?us-ascii?q?this_is_a_test?= bird', 'this is a test', 'this is a test', [], ' bird') def test_get_encoded_word_internal_spaces(self): self._test_get_x(parser.get_encoded_word, '=?us-ascii?q?this is a test?= bird', 'this is a test', 'this is a test', [errors.InvalidHeaderDefect], ' bird') def test_get_encoded_word_gets_first(self): self._test_get_x(parser.get_encoded_word, '=?us-ascii?q?first?= =?utf-8?q?second?=', 'first', 'first', [], ' =?utf-8?q?second?=') def test_get_encoded_word_gets_first_even_if_no_space(self): self._test_get_x(parser.get_encoded_word, '=?us-ascii?q?first?==?utf-8?q?second?=', 'first', 'first', [], '=?utf-8?q?second?=') def test_get_encoded_word_sets_extra_attributes(self): ew = self._test_get_x(parser.get_encoded_word, '=?us-ascii*jive?q?first_second?=', 'first second', 'first second', [], '') self.assertEqual(ew.charset, 'us-ascii') self.assertEqual(ew.lang, 'jive') def test_get_encoded_word_lang_default_is_blank(self): ew = self._test_get_x(parser.get_encoded_word, '=?us-ascii?q?first_second?=', 'first second', 'first second', [], '') self.assertEqual(ew.charset, 'us-ascii') self.assertEqual(ew.lang, '') def test_get_encoded_word_non_printable_defect(self): self._test_get_x(parser.get_encoded_word, '=?us-ascii?q?first\x02second?=', 'first\x02second', 'first\x02second', [errors.NonPrintableDefect], '') def test_get_encoded_word_leading_internal_space(self): self._test_get_x(parser.get_encoded_word, '=?us-ascii?q?=20foo?=', ' foo', ' foo', [], '') def test_get_encoded_word_quopri_utf_escape_follows_cte(self): # Issue 18044 self._test_get_x(parser.get_encoded_word, '=?utf-8?q?=C3=89ric?=', 'Éric', 'Éric', [], '') # get_unstructured def _get_unst(self, value): token = parser.get_unstructured(value) return token, '' def test_get_unstructured_null(self): self._test_get_x(self._get_unst, '', '', '', [], '') def test_get_unstructured_one_word(self): self._test_get_x(self._get_unst, 'foo', 'foo', 'foo', [], '') def test_get_unstructured_normal_phrase(self): self._test_get_x(self._get_unst, 'foo bar bird', 'foo bar bird', 'foo bar bird', [], '') def test_get_unstructured_normal_phrase_with_whitespace(self): self._test_get_x(self._get_unst, 'foo \t bar bird', 'foo \t bar bird', 'foo bar bird', [], '') def test_get_unstructured_leading_whitespace(self): self._test_get_x(self._get_unst, ' foo bar', ' foo bar', ' foo bar', [], '') def test_get_unstructured_trailing_whitespace(self): self._test_get_x(self._get_unst, 'foo bar ', 'foo bar ', 'foo bar ', [], '') def test_get_unstructured_leading_and_trailing_whitespace(self): self._test_get_x(self._get_unst, ' foo bar ', ' foo bar ', ' foo bar ', [], '') def test_get_unstructured_one_valid_ew_no_ws(self): self._test_get_x(self._get_unst, '=?us-ascii?q?bar?=', 'bar', 'bar', [], '') def test_get_unstructured_one_ew_trailing_ws(self): self._test_get_x(self._get_unst, '=?us-ascii?q?bar?= ', 'bar ', 'bar ', [], '') def test_get_unstructured_one_valid_ew_trailing_text(self): self._test_get_x(self._get_unst, '=?us-ascii?q?bar?= bird', 'bar bird', 'bar bird', [], '') def test_get_unstructured_phrase_with_ew_in_middle_of_text(self): self._test_get_x(self._get_unst, 'foo =?us-ascii?q?bar?= bird', 'foo bar bird', 'foo bar bird', [], '') def test_get_unstructured_phrase_with_two_ew(self): self._test_get_x(self._get_unst, 'foo =?us-ascii?q?bar?= =?us-ascii?q?bird?=', 'foo barbird', 'foo barbird', [], '') def test_get_unstructured_phrase_with_two_ew_trailing_ws(self): self._test_get_x(self._get_unst, 'foo =?us-ascii?q?bar?= =?us-ascii?q?bird?= ', 'foo barbird ', 'foo barbird ', [], '') def test_get_unstructured_phrase_with_ew_with_leading_ws(self): self._test_get_x(self._get_unst, ' =?us-ascii?q?bar?=', ' bar', ' bar', [], '') def test_get_unstructured_phrase_with_two_ew_extra_ws(self): self._test_get_x(self._get_unst, 'foo =?us-ascii?q?bar?= \t =?us-ascii?q?bird?=', 'foo barbird', 'foo barbird', [], '') def test_get_unstructured_two_ew_extra_ws_trailing_text(self): self._test_get_x(self._get_unst, '=?us-ascii?q?test?= =?us-ascii?q?foo?= val', 'testfoo val', 'testfoo val', [], '') def test_get_unstructured_ew_with_internal_ws(self): self._test_get_x(self._get_unst, '=?iso-8859-1?q?hello=20world?=', 'hello world', 'hello world', [], '') def test_get_unstructured_ew_with_internal_leading_ws(self): self._test_get_x(self._get_unst, ' =?us-ascii?q?=20test?= =?us-ascii?q?=20foo?= val', ' test foo val', ' test foo val', [], '') def test_get_unstructured_invaild_ew(self): self._test_get_x(self._get_unst, '=?test val', '=?test val', '=?test val', [], '') def test_get_unstructured_undecodable_bytes(self): self._test_get_x(self._get_unst, b'test \xACfoo val'.decode('ascii', 'surrogateescape'), 'test \uDCACfoo val', 'test \uDCACfoo val', [errors.UndecodableBytesDefect], '') def test_get_unstructured_undecodable_bytes_in_EW(self): self._test_get_x(self._get_unst, (b'=?us-ascii?q?=20test?= =?us-ascii?q?=20\xACfoo?=' b' val').decode('ascii', 'surrogateescape'), ' test \uDCACfoo val', ' test \uDCACfoo val', [errors.UndecodableBytesDefect]*2, '') def test_get_unstructured_missing_base64_padding(self): self._test_get_x(self._get_unst, '=?utf-8?b?dmk?=', 'vi', 'vi', [errors.InvalidBase64PaddingDefect], '') def test_get_unstructured_invalid_base64_character(self): self._test_get_x(self._get_unst, '=?utf-8?b?dm\x01k===?=', 'vi', 'vi', [errors.InvalidBase64CharactersDefect], '') def test_get_unstructured_invalid_base64_character_and_bad_padding(self): self._test_get_x(self._get_unst, '=?utf-8?b?dm\x01k?=', 'vi', 'vi', [errors.InvalidBase64CharactersDefect, errors.InvalidBase64PaddingDefect], '') def test_get_unstructured_invalid_base64_length(self): # bpo-27397: Return the encoded string since there's no way to decode. self._test_get_x(self._get_unst, '=?utf-8?b?abcde?=', 'abcde', 'abcde', [errors.InvalidBase64LengthDefect], '') def test_get_unstructured_no_whitespace_between_ews(self): self._test_get_x(self._get_unst, '=?utf-8?q?foo?==?utf-8?q?bar?=', 'foobar', 'foobar', [errors.InvalidHeaderDefect], '') # get_qp_ctext def test_get_qp_ctext_only(self): ptext = self._test_get_x(parser.get_qp_ctext, 'foobar', 'foobar', ' ', [], '') self.assertEqual(ptext.token_type, 'ptext') def test_get_qp_ctext_all_printables(self): with_qp = self.rfc_printable_ascii.replace('\\', '\\\\') with_qp = with_qp. replace('(', r'\(') with_qp = with_qp.replace(')', r'\)') ptext = self._test_get_x(parser.get_qp_ctext, with_qp, self.rfc_printable_ascii, ' ', [], '') def test_get_qp_ctext_two_words_gets_first(self): self._test_get_x(parser.get_qp_ctext, 'foo de', 'foo', ' ', [], ' de') def test_get_qp_ctext_following_wsp_preserved(self): self._test_get_x(parser.get_qp_ctext, 'foo \t\tde', 'foo', ' ', [], ' \t\tde') def test_get_qp_ctext_up_to_close_paren_only(self): self._test_get_x(parser.get_qp_ctext, 'foo)', 'foo', ' ', [], ')') def test_get_qp_ctext_wsp_before_close_paren_preserved(self): self._test_get_x(parser.get_qp_ctext, 'foo )', 'foo', ' ', [], ' )') def test_get_qp_ctext_close_paren_mid_word(self): self._test_get_x(parser.get_qp_ctext, 'foo)bar', 'foo', ' ', [], ')bar') def test_get_qp_ctext_up_to_open_paren_only(self): self._test_get_x(parser.get_qp_ctext, 'foo(', 'foo', ' ', [], '(') def test_get_qp_ctext_wsp_before_open_paren_preserved(self): self._test_get_x(parser.get_qp_ctext, 'foo (', 'foo', ' ', [], ' (') def test_get_qp_ctext_open_paren_mid_word(self): self._test_get_x(parser.get_qp_ctext, 'foo(bar', 'foo', ' ', [], '(bar') def test_get_qp_ctext_non_printables(self): ptext = self._test_get_x(parser.get_qp_ctext, 'foo\x00bar)', 'foo\x00bar', ' ', [errors.NonPrintableDefect], ')') self.assertEqual(ptext.defects[0].non_printables[0], '\x00') # get_qcontent def test_get_qcontent_only(self): ptext = self._test_get_x(parser.get_qcontent, 'foobar', 'foobar', 'foobar', [], '') self.assertEqual(ptext.token_type, 'ptext') def test_get_qcontent_all_printables(self): with_qp = self.rfc_printable_ascii.replace('\\', '\\\\') with_qp = with_qp. replace('"', r'\"') ptext = self._test_get_x(parser.get_qcontent, with_qp, self.rfc_printable_ascii, self.rfc_printable_ascii, [], '') def test_get_qcontent_two_words_gets_first(self): self._test_get_x(parser.get_qcontent, 'foo de', 'foo', 'foo', [], ' de') def test_get_qcontent_following_wsp_preserved(self): self._test_get_x(parser.get_qcontent, 'foo \t\tde', 'foo', 'foo', [], ' \t\tde') def test_get_qcontent_up_to_dquote_only(self): self._test_get_x(parser.get_qcontent, 'foo"', 'foo', 'foo', [], '"') def test_get_qcontent_wsp_before_close_paren_preserved(self): self._test_get_x(parser.get_qcontent, 'foo "', 'foo', 'foo', [], ' "') def test_get_qcontent_close_paren_mid_word(self): self._test_get_x(parser.get_qcontent, 'foo"bar', 'foo', 'foo', [], '"bar') def test_get_qcontent_non_printables(self): ptext = self._test_get_x(parser.get_qcontent, 'foo\x00fg"', 'foo\x00fg', 'foo\x00fg', [errors.NonPrintableDefect], '"') self.assertEqual(ptext.defects[0].non_printables[0], '\x00') # get_atext def test_get_atext_only(self): atext = self._test_get_x(parser.get_atext, 'foobar', 'foobar', 'foobar', [], '') self.assertEqual(atext.token_type, 'atext') def test_get_atext_all_atext(self): atext = self._test_get_x(parser.get_atext, self.rfc_atext_chars, self.rfc_atext_chars, self.rfc_atext_chars, [], '') def test_get_atext_two_words_gets_first(self): self._test_get_x(parser.get_atext, 'foo bar', 'foo', 'foo', [], ' bar') def test_get_atext_following_wsp_preserved(self): self._test_get_x(parser.get_atext, 'foo \t\tbar', 'foo', 'foo', [], ' \t\tbar') def test_get_atext_up_to_special(self): self._test_get_x(parser.get_atext, 'foo@bar', 'foo', 'foo', [], '@bar') def test_get_atext_non_printables(self): atext = self._test_get_x(parser.get_atext, 'foo\x00bar(', 'foo\x00bar', 'foo\x00bar', [errors.NonPrintableDefect], '(') self.assertEqual(atext.defects[0].non_printables[0], '\x00') # get_bare_quoted_string def test_get_bare_quoted_string_only(self): bqs = self._test_get_x(parser.get_bare_quoted_string, '"foo"', '"foo"', 'foo', [], '') self.assertEqual(bqs.token_type, 'bare-quoted-string') def test_get_bare_quoted_string_must_start_with_dquote(self): with self.assertRaises(errors.HeaderParseError): parser.get_bare_quoted_string('foo"') with self.assertRaises(errors.HeaderParseError): parser.get_bare_quoted_string(' "foo"') def test_get_bare_quoted_string_only_quotes(self): self._test_get_x(parser.get_bare_quoted_string, '""', '""', '', [], '') def test_get_bare_quoted_string_following_wsp_preserved(self): self._test_get_x(parser.get_bare_quoted_string, '"foo"\t bar', '"foo"', 'foo', [], '\t bar') def test_get_bare_quoted_string_multiple_words(self): self._test_get_x(parser.get_bare_quoted_string, '"foo bar moo"', '"foo bar moo"', 'foo bar moo', [], '') def test_get_bare_quoted_string_multiple_words_wsp_preserved(self): self._test_get_x(parser.get_bare_quoted_string, '" foo moo\t"', '" foo moo\t"', ' foo moo\t', [], '') def test_get_bare_quoted_string_end_dquote_mid_word(self): self._test_get_x(parser.get_bare_quoted_string, '"foo"bar', '"foo"', 'foo', [], 'bar') def test_get_bare_quoted_string_quoted_dquote(self): self._test_get_x(parser.get_bare_quoted_string, r'"foo\"in"a', r'"foo\"in"', 'foo"in', [], 'a') def test_get_bare_quoted_string_non_printables(self): self._test_get_x(parser.get_bare_quoted_string, '"a\x01a"', '"a\x01a"', 'a\x01a', [errors.NonPrintableDefect], '') def test_get_bare_quoted_string_no_end_dquote(self): self._test_get_x(parser.get_bare_quoted_string, '"foo', '"foo"', 'foo', [errors.InvalidHeaderDefect], '') self._test_get_x(parser.get_bare_quoted_string, '"foo ', '"foo "', 'foo ', [errors.InvalidHeaderDefect], '') def test_get_bare_quoted_string_empty_quotes(self): self._test_get_x(parser.get_bare_quoted_string, '""', '""', '', [], '') # Issue 16983: apply postel's law to some bad encoding. def test_encoded_word_inside_quotes(self): self._test_get_x(parser.get_bare_quoted_string, '"=?utf-8?Q?not_really_valid?="', '"not really valid"', 'not really valid', [errors.InvalidHeaderDefect], '') # get_comment def test_get_comment_only(self): comment = self._test_get_x(parser.get_comment, '(comment)', '(comment)', ' ', [], '', ['comment']) self.assertEqual(comment.token_type, 'comment') def test_get_comment_must_start_with_paren(self): with self.assertRaises(errors.HeaderParseError): parser.get_comment('foo"') with self.assertRaises(errors.HeaderParseError): parser.get_comment(' (foo"') def test_get_comment_following_wsp_preserved(self): self._test_get_x(parser.get_comment, '(comment) \t', '(comment)', ' ', [], ' \t', ['comment']) def test_get_comment_multiple_words(self): self._test_get_x(parser.get_comment, '(foo bar) \t', '(foo bar)', ' ', [], ' \t', ['foo bar']) def test_get_comment_multiple_words_wsp_preserved(self): self._test_get_x(parser.get_comment, '( foo bar\t ) \t', '( foo bar\t )', ' ', [], ' \t', [' foo bar\t ']) def test_get_comment_end_paren_mid_word(self): self._test_get_x(parser.get_comment, '(foo)bar', '(foo)', ' ', [], 'bar', ['foo']) def test_get_comment_quoted_parens(self): self._test_get_x(parser.get_comment, r'(foo\) \(\)bar)', r'(foo\) \(\)bar)', ' ', [], '', ['foo) ()bar']) def test_get_comment_non_printable(self): self._test_get_x(parser.get_comment, '(foo\x7Fbar)', '(foo\x7Fbar)', ' ', [errors.NonPrintableDefect], '', ['foo\x7Fbar']) def test_get_comment_no_end_paren(self): self._test_get_x(parser.get_comment, '(foo bar', '(foo bar)', ' ', [errors.InvalidHeaderDefect], '', ['foo bar']) self._test_get_x(parser.get_comment, '(foo bar ', '(foo bar )', ' ', [errors.InvalidHeaderDefect], '', ['foo bar ']) def test_get_comment_nested_comment(self): comment = self._test_get_x(parser.get_comment, '(foo(bar))', '(foo(bar))', ' ', [], '', ['foo(bar)']) self.assertEqual(comment[1].content, 'bar') def test_get_comment_nested_comment_wsp(self): comment = self._test_get_x(parser.get_comment, '(foo ( bar ) )', '(foo ( bar ) )', ' ', [], '', ['foo ( bar ) ']) self.assertEqual(comment[2].content, ' bar ') def test_get_comment_empty_comment(self): self._test_get_x(parser.get_comment, '()', '()', ' ', [], '', ['']) def test_get_comment_multiple_nesting(self): comment = self._test_get_x(parser.get_comment, '(((((foo)))))', '(((((foo)))))', ' ', [], '', ['((((foo))))']) for i in range(4, 0, -1): self.assertEqual(comment[0].content, '('*(i-1)+'foo'+')'*(i-1)) comment = comment[0] self.assertEqual(comment.content, 'foo') def test_get_comment_missing_end_of_nesting(self): self._test_get_x(parser.get_comment, '(((((foo)))', '(((((foo)))))', ' ', [errors.InvalidHeaderDefect]*2, '', ['((((foo))))']) def test_get_comment_qs_in_nested_comment(self): comment = self._test_get_x(parser.get_comment, r'(foo (b\)))', r'(foo (b\)))', ' ', [], '', [r'foo (b\))']) self.assertEqual(comment[2].content, 'b)') # get_cfws def test_get_cfws_only_ws(self): cfws = self._test_get_x(parser.get_cfws, ' \t \t', ' \t \t', ' ', [], '', []) self.assertEqual(cfws.token_type, 'cfws') def test_get_cfws_only_comment(self): cfws = self._test_get_x(parser.get_cfws, '(foo)', '(foo)', ' ', [], '', ['foo']) self.assertEqual(cfws[0].content, 'foo') def test_get_cfws_only_mixed(self): cfws = self._test_get_x(parser.get_cfws, ' (foo ) ( bar) ', ' (foo ) ( bar) ', ' ', [], '', ['foo ', ' bar']) self.assertEqual(cfws[1].content, 'foo ') self.assertEqual(cfws[3].content, ' bar') def test_get_cfws_ends_at_non_leader(self): cfws = self._test_get_x(parser.get_cfws, '(foo) bar', '(foo) ', ' ', [], 'bar', ['foo']) self.assertEqual(cfws[0].content, 'foo') def test_get_cfws_ends_at_non_printable(self): cfws = self._test_get_x(parser.get_cfws, '(foo) \x07', '(foo) ', ' ', [], '\x07', ['foo']) self.assertEqual(cfws[0].content, 'foo') def test_get_cfws_non_printable_in_comment(self): cfws = self._test_get_x(parser.get_cfws, '(foo \x07) "test"', '(foo \x07) ', ' ', [errors.NonPrintableDefect], '"test"', ['foo \x07']) self.assertEqual(cfws[0].content, 'foo \x07') def test_get_cfws_header_ends_in_comment(self): cfws = self._test_get_x(parser.get_cfws, ' (foo ', ' (foo )', ' ', [errors.InvalidHeaderDefect], '', ['foo ']) self.assertEqual(cfws[1].content, 'foo ') def test_get_cfws_multiple_nested_comments(self): cfws = self._test_get_x(parser.get_cfws, '(foo (bar)) ((a)(a))', '(foo (bar)) ((a)(a))', ' ', [], '', ['foo (bar)', '(a)(a)']) self.assertEqual(cfws[0].comments, ['foo (bar)']) self.assertEqual(cfws[2].comments, ['(a)(a)']) # get_quoted_string def test_get_quoted_string_only(self): qs = self._test_get_x(parser.get_quoted_string, '"bob"', '"bob"', 'bob', [], '') self.assertEqual(qs.token_type, 'quoted-string') self.assertEqual(qs.quoted_value, '"bob"') self.assertEqual(qs.content, 'bob') def test_get_quoted_string_with_wsp(self): qs = self._test_get_x(parser.get_quoted_string, '\t "bob" ', '\t "bob" ', ' bob ', [], '') self.assertEqual(qs.quoted_value, ' "bob" ') self.assertEqual(qs.content, 'bob') def test_get_quoted_string_with_comments_and_wsp(self): qs = self._test_get_x(parser.get_quoted_string, ' (foo) "bob"(bar)', ' (foo) "bob"(bar)', ' bob ', [], '') self.assertEqual(qs[0][1].content, 'foo') self.assertEqual(qs[2][0].content, 'bar') self.assertEqual(qs.content, 'bob') self.assertEqual(qs.quoted_value, ' "bob" ') def test_get_quoted_string_with_multiple_comments(self): qs = self._test_get_x(parser.get_quoted_string, ' (foo) (bar) "bob"(bird)', ' (foo) (bar) "bob"(bird)', ' bob ', [], '') self.assertEqual(qs[0].comments, ['foo', 'bar']) self.assertEqual(qs[2].comments, ['bird']) self.assertEqual(qs.content, 'bob') self.assertEqual(qs.quoted_value, ' "bob" ') def test_get_quoted_string_non_printable_in_comment(self): qs = self._test_get_x(parser.get_quoted_string, ' (\x0A) "bob"', ' (\x0A) "bob"', ' bob', [errors.NonPrintableDefect], '') self.assertEqual(qs[0].comments, ['\x0A']) self.assertEqual(qs.content, 'bob') self.assertEqual(qs.quoted_value, ' "bob"') def test_get_quoted_string_non_printable_in_qcontent(self): qs = self._test_get_x(parser.get_quoted_string, ' (a) "a\x0B"', ' (a) "a\x0B"', ' a\x0B', [errors.NonPrintableDefect], '') self.assertEqual(qs[0].comments, ['a']) self.assertEqual(qs.content, 'a\x0B') self.assertEqual(qs.quoted_value, ' "a\x0B"') def test_get_quoted_string_internal_ws(self): qs = self._test_get_x(parser.get_quoted_string, ' (a) "foo bar "', ' (a) "foo bar "', ' foo bar ', [], '') self.assertEqual(qs[0].comments, ['a']) self.assertEqual(qs.content, 'foo bar ') self.assertEqual(qs.quoted_value, ' "foo bar "') def test_get_quoted_string_header_ends_in_comment(self): qs = self._test_get_x(parser.get_quoted_string, ' (a) "bob" (a', ' (a) "bob" (a)', ' bob ', [errors.InvalidHeaderDefect], '') self.assertEqual(qs[0].comments, ['a']) self.assertEqual(qs[2].comments, ['a']) self.assertEqual(qs.content, 'bob') self.assertEqual(qs.quoted_value, ' "bob" ') def test_get_quoted_string_header_ends_in_qcontent(self): qs = self._test_get_x(parser.get_quoted_string, ' (a) "bob', ' (a) "bob"', ' bob', [errors.InvalidHeaderDefect], '') self.assertEqual(qs[0].comments, ['a']) self.assertEqual(qs.content, 'bob') self.assertEqual(qs.quoted_value, ' "bob"') def test_get_quoted_string_no_quoted_string(self): with self.assertRaises(errors.HeaderParseError): parser.get_quoted_string(' (ab) xyz') def test_get_quoted_string_qs_ends_at_noncfws(self): qs = self._test_get_x(parser.get_quoted_string, '\t "bob" fee', '\t "bob" ', ' bob ', [], 'fee') self.assertEqual(qs.content, 'bob') self.assertEqual(qs.quoted_value, ' "bob" ') # get_atom def test_get_atom_only(self): atom = self._test_get_x(parser.get_atom, 'bob', 'bob', 'bob', [], '') self.assertEqual(atom.token_type, 'atom') def test_get_atom_with_wsp(self): self._test_get_x(parser.get_atom, '\t bob ', '\t bob ', ' bob ', [], '') def test_get_atom_with_comments_and_wsp(self): atom = self._test_get_x(parser.get_atom, ' (foo) bob(bar)', ' (foo) bob(bar)', ' bob ', [], '') self.assertEqual(atom[0][1].content, 'foo') self.assertEqual(atom[2][0].content, 'bar') def test_get_atom_with_multiple_comments(self): atom = self._test_get_x(parser.get_atom, ' (foo) (bar) bob(bird)', ' (foo) (bar) bob(bird)', ' bob ', [], '') self.assertEqual(atom[0].comments, ['foo', 'bar']) self.assertEqual(atom[2].comments, ['bird']) def test_get_atom_non_printable_in_comment(self): atom = self._test_get_x(parser.get_atom, ' (\x0A) bob', ' (\x0A) bob', ' bob', [errors.NonPrintableDefect], '') self.assertEqual(atom[0].comments, ['\x0A']) def test_get_atom_non_printable_in_atext(self): atom = self._test_get_x(parser.get_atom, ' (a) a\x0B', ' (a) a\x0B', ' a\x0B', [errors.NonPrintableDefect], '') self.assertEqual(atom[0].comments, ['a']) def test_get_atom_header_ends_in_comment(self): atom = self._test_get_x(parser.get_atom, ' (a) bob (a', ' (a) bob (a)', ' bob ', [errors.InvalidHeaderDefect], '') self.assertEqual(atom[0].comments, ['a']) self.assertEqual(atom[2].comments, ['a']) def test_get_atom_no_atom(self): with self.assertRaises(errors.HeaderParseError): parser.get_atom(' (ab) ') def test_get_atom_no_atom_before_special(self): with self.assertRaises(errors.HeaderParseError): parser.get_atom(' (ab) @') def test_get_atom_atom_ends_at_special(self): atom = self._test_get_x(parser.get_atom, ' (foo) bob(bar) @bang', ' (foo) bob(bar) ', ' bob ', [], '@bang') self.assertEqual(atom[0].comments, ['foo']) self.assertEqual(atom[2].comments, ['bar']) def test_get_atom_atom_ends_at_noncfws(self): self._test_get_x(parser.get_atom, 'bob fred', 'bob ', 'bob ', [], 'fred') def test_get_atom_rfc2047_atom(self): self._test_get_x(parser.get_atom, '=?utf-8?q?=20bob?=', ' bob', ' bob', [], '') # get_dot_atom_text def test_get_dot_atom_text(self): dot_atom_text = self._test_get_x(parser.get_dot_atom_text, 'foo.bar.bang', 'foo.bar.bang', 'foo.bar.bang', [], '') self.assertEqual(dot_atom_text.token_type, 'dot-atom-text') self.assertEqual(len(dot_atom_text), 5) def test_get_dot_atom_text_lone_atom_is_valid(self): dot_atom_text = self._test_get_x(parser.get_dot_atom_text, 'foo', 'foo', 'foo', [], '') def test_get_dot_atom_text_raises_on_leading_dot(self): with self.assertRaises(errors.HeaderParseError): parser.get_dot_atom_text('.foo.bar') def test_get_dot_atom_text_raises_on_trailing_dot(self): with self.assertRaises(errors.HeaderParseError): parser.get_dot_atom_text('foo.bar.') def test_get_dot_atom_text_raises_on_leading_non_atext(self): with self.assertRaises(errors.HeaderParseError): parser.get_dot_atom_text(' foo.bar') with self.assertRaises(errors.HeaderParseError): parser.get_dot_atom_text('@foo.bar') with self.assertRaises(errors.HeaderParseError): parser.get_dot_atom_text('"foo.bar"') def test_get_dot_atom_text_trailing_text_preserved(self): dot_atom_text = self._test_get_x(parser.get_dot_atom_text, 'foo@bar', 'foo', 'foo', [], '@bar') def test_get_dot_atom_text_trailing_ws_preserved(self): dot_atom_text = self._test_get_x(parser.get_dot_atom_text, 'foo .bar', 'foo', 'foo', [], ' .bar') # get_dot_atom def test_get_dot_atom_only(self): dot_atom = self._test_get_x(parser.get_dot_atom, 'foo.bar.bing', 'foo.bar.bing', 'foo.bar.bing', [], '') self.assertEqual(dot_atom.token_type, 'dot-atom') self.assertEqual(len(dot_atom), 1) def test_get_dot_atom_with_wsp(self): self._test_get_x(parser.get_dot_atom, '\t foo.bar.bing ', '\t foo.bar.bing ', ' foo.bar.bing ', [], '') def test_get_dot_atom_with_comments_and_wsp(self): self._test_get_x(parser.get_dot_atom, ' (sing) foo.bar.bing (here) ', ' (sing) foo.bar.bing (here) ', ' foo.bar.bing ', [], '') def test_get_dot_atom_space_ends_dot_atom(self): self._test_get_x(parser.get_dot_atom, ' (sing) foo.bar .bing (here) ', ' (sing) foo.bar ', ' foo.bar ', [], '.bing (here) ') def test_get_dot_atom_no_atom_raises(self): with self.assertRaises(errors.HeaderParseError): parser.get_dot_atom(' (foo) ') def test_get_dot_atom_leading_dot_raises(self): with self.assertRaises(errors.HeaderParseError): parser.get_dot_atom(' (foo) .bar') def test_get_dot_atom_two_dots_raises(self): with self.assertRaises(errors.HeaderParseError): parser.get_dot_atom('bar..bang') def test_get_dot_atom_trailing_dot_raises(self): with self.assertRaises(errors.HeaderParseError): parser.get_dot_atom(' (foo) bar.bang. foo') def test_get_dot_atom_rfc2047_atom(self): self._test_get_x(parser.get_dot_atom, '=?utf-8?q?=20bob?=', ' bob', ' bob', [], '') # get_word (if this were black box we'd repeat all the qs/atom tests) def test_get_word_atom_yields_atom(self): word = self._test_get_x(parser.get_word, ' (foo) bar (bang) :ah', ' (foo) bar (bang) ', ' bar ', [], ':ah') self.assertEqual(word.token_type, 'atom') self.assertEqual(word[0].token_type, 'cfws') def test_get_word_qs_yields_qs(self): word = self._test_get_x(parser.get_word, '"bar " (bang) ah', '"bar " (bang) ', 'bar ', [], 'ah') self.assertEqual(word.token_type, 'quoted-string') self.assertEqual(word[0].token_type, 'bare-quoted-string') self.assertEqual(word[0].value, 'bar ') self.assertEqual(word.content, 'bar ') def test_get_word_ends_at_dot(self): self._test_get_x(parser.get_word, 'foo.', 'foo', 'foo', [], '.') # get_phrase def test_get_phrase_simple(self): phrase = self._test_get_x(parser.get_phrase, '"Fred A. Johnson" is his name, oh.', '"Fred A. Johnson" is his name', 'Fred A. Johnson is his name', [], ', oh.') self.assertEqual(phrase.token_type, 'phrase') def test_get_phrase_complex(self): phrase = self._test_get_x(parser.get_phrase, ' (A) bird (in (my|your)) "hand " is messy\t<>\t', ' (A) bird (in (my|your)) "hand " is messy\t', ' bird hand is messy ', [], '<>\t') self.assertEqual(phrase[0][0].comments, ['A']) self.assertEqual(phrase[0][2].comments, ['in (my|your)']) def test_get_phrase_obsolete(self): phrase = self._test_get_x(parser.get_phrase, 'Fred A.(weird).O Johnson', 'Fred A.(weird).O Johnson', 'Fred A. .O Johnson', [errors.ObsoleteHeaderDefect]*3, '') self.assertEqual(len(phrase), 7) self.assertEqual(phrase[3].comments, ['weird']) def test_get_phrase_pharse_must_start_with_word(self): phrase = self._test_get_x(parser.get_phrase, '(even weirder).name', '(even weirder).name', ' .name', [errors.InvalidHeaderDefect] + [errors.ObsoleteHeaderDefect]*2, '') self.assertEqual(len(phrase), 3) self.assertEqual(phrase[0].comments, ['even weirder']) def test_get_phrase_ending_with_obsolete(self): phrase = self._test_get_x(parser.get_phrase, 'simple phrase.(with trailing comment):boo', 'simple phrase.(with trailing comment)', 'simple phrase. ', [errors.ObsoleteHeaderDefect]*2, ':boo') self.assertEqual(len(phrase), 4) self.assertEqual(phrase[3].comments, ['with trailing comment']) def get_phrase_cfws_only_raises(self): with self.assertRaises(errors.HeaderParseError): parser.get_phrase(' (foo) ') # get_local_part def test_get_local_part_simple(self): local_part = self._test_get_x(parser.get_local_part, '[email protected]', 'dinsdale', 'dinsdale', [], '@python.org') self.assertEqual(local_part.token_type, 'local-part') self.assertEqual(local_part.local_part, 'dinsdale') def test_get_local_part_with_dot(self): local_part = self._test_get_x(parser.get_local_part, '[email protected]', 'Fred.A.Johnson', 'Fred.A.Johnson', [], '@python.org') self.assertEqual(local_part.local_part, 'Fred.A.Johnson') def test_get_local_part_with_whitespace(self): local_part = self._test_get_x(parser.get_local_part, ' Fred.A.Johnson @python.org', ' Fred.A.Johnson ', ' Fred.A.Johnson ', [], '@python.org') self.assertEqual(local_part.local_part, 'Fred.A.Johnson') def test_get_local_part_with_cfws(self): local_part = self._test_get_x(parser.get_local_part, ' (foo) Fred.A.Johnson (bar (bird)) @python.org', ' (foo) Fred.A.Johnson (bar (bird)) ', ' Fred.A.Johnson ', [], '@python.org') self.assertEqual(local_part.local_part, 'Fred.A.Johnson') self.assertEqual(local_part[0][0].comments, ['foo']) self.assertEqual(local_part[0][2].comments, ['bar (bird)']) def test_get_local_part_simple_quoted(self): local_part = self._test_get_x(parser.get_local_part, '"dinsdale"@python.org', '"dinsdale"', '"dinsdale"', [], '@python.org') self.assertEqual(local_part.token_type, 'local-part') self.assertEqual(local_part.local_part, 'dinsdale') def test_get_local_part_with_quoted_dot(self): local_part = self._test_get_x(parser.get_local_part, '"Fred.A.Johnson"@python.org', '"Fred.A.Johnson"', '"Fred.A.Johnson"', [], '@python.org') self.assertEqual(local_part.local_part, 'Fred.A.Johnson') def test_get_local_part_quoted_with_whitespace(self): local_part = self._test_get_x(parser.get_local_part, ' "Fred A. Johnson" @python.org', ' "Fred A. Johnson" ', ' "Fred A. Johnson" ', [], '@python.org') self.assertEqual(local_part.local_part, 'Fred A. Johnson') def test_get_local_part_quoted_with_cfws(self): local_part = self._test_get_x(parser.get_local_part, ' (foo) " Fred A. Johnson " (bar (bird)) @python.org', ' (foo) " Fred A. Johnson " (bar (bird)) ', ' " Fred A. Johnson " ', [], '@python.org') self.assertEqual(local_part.local_part, ' Fred A. Johnson ') self.assertEqual(local_part[0][0].comments, ['foo']) self.assertEqual(local_part[0][2].comments, ['bar (bird)']) def test_get_local_part_simple_obsolete(self): local_part = self._test_get_x(parser.get_local_part, 'Fred. [email protected]', 'Fred. A.Johnson', 'Fred. A.Johnson', [errors.ObsoleteHeaderDefect], '@python.org') self.assertEqual(local_part.local_part, 'Fred.A.Johnson') def test_get_local_part_complex_obsolete_1(self): local_part = self._test_get_x(parser.get_local_part, ' (foo )Fred (bar).(bird) A.(sheep)Johnson."and dogs "@python.org', ' (foo )Fred (bar).(bird) A.(sheep)Johnson."and dogs "', ' Fred . A. Johnson.and dogs ', [errors.ObsoleteHeaderDefect], '@python.org') self.assertEqual(local_part.local_part, 'Fred.A.Johnson.and dogs ') def test_get_local_part_complex_obsolete_invalid(self): local_part = self._test_get_x(parser.get_local_part, ' (foo )Fred (bar).(bird) A.(sheep)Johnson "and dogs"@python.org', ' (foo )Fred (bar).(bird) A.(sheep)Johnson "and dogs"', ' Fred . A. Johnson and dogs', [errors.InvalidHeaderDefect]*2, '@python.org') self.assertEqual(local_part.local_part, 'Fred.A.Johnson and dogs') def test_get_local_part_no_part_raises(self): with self.assertRaises(errors.HeaderParseError): parser.get_local_part(' (foo) ') def test_get_local_part_special_instead_raises(self): with self.assertRaises(errors.HeaderParseError): parser.get_local_part(' (foo) @python.org') def test_get_local_part_trailing_dot(self): local_part = self._test_get_x(parser.get_local_part, ' [email protected]', ' borris.', ' borris.', [errors.InvalidHeaderDefect]*2, '@python.org') self.assertEqual(local_part.local_part, 'borris.') def test_get_local_part_trailing_dot_with_ws(self): local_part = self._test_get_x(parser.get_local_part, ' borris. @python.org', ' borris. ', ' borris. ', [errors.InvalidHeaderDefect]*2, '@python.org') self.assertEqual(local_part.local_part, 'borris.') def test_get_local_part_leading_dot(self): local_part = self._test_get_x(parser.get_local_part, '[email protected]', '.borris', '.borris', [errors.InvalidHeaderDefect]*2, '@python.org') self.assertEqual(local_part.local_part, '.borris') def test_get_local_part_leading_dot_after_ws(self): local_part = self._test_get_x(parser.get_local_part, ' [email protected]', ' .borris', ' .borris', [errors.InvalidHeaderDefect]*2, '@python.org') self.assertEqual(local_part.local_part, '.borris') def test_get_local_part_double_dot_raises(self): local_part = self._test_get_x(parser.get_local_part, ' borris.(foo)[email protected]', ' borris.(foo).natasha', ' borris. .natasha', [errors.InvalidHeaderDefect]*2, '@python.org') self.assertEqual(local_part.local_part, 'borris..natasha') def test_get_local_part_quoted_strings_in_atom_list(self): local_part = self._test_get_x(parser.get_local_part, '""example" example"@example.com', '""example" example"', 'example example', [errors.InvalidHeaderDefect]*3, '@example.com') self.assertEqual(local_part.local_part, 'example example') def test_get_local_part_valid_and_invalid_qp_in_atom_list(self): local_part = self._test_get_x(parser.get_local_part, r'"\\"example\\" example"@example.com', r'"\\"example\\" example"', r'\example\\ example', [errors.InvalidHeaderDefect]*5, '@example.com') self.assertEqual(local_part.local_part, r'\example\\ example') def test_get_local_part_unicode_defect(self): # Currently this only happens when parsing unicode, not when parsing # stuff that was originally binary. local_part = self._test_get_x(parser.get_local_part, 'exá[email protected]', 'exámple', 'exámple', [errors.NonASCIILocalPartDefect], '@example.com') self.assertEqual(local_part.local_part, 'exámple') # get_dtext def test_get_dtext_only(self): dtext = self._test_get_x(parser.get_dtext, 'foobar', 'foobar', 'foobar', [], '') self.assertEqual(dtext.token_type, 'ptext') def test_get_dtext_all_dtext(self): dtext = self._test_get_x(parser.get_dtext, self.rfc_dtext_chars, self.rfc_dtext_chars, self.rfc_dtext_chars, [], '') def test_get_dtext_two_words_gets_first(self): self._test_get_x(parser.get_dtext, 'foo bar', 'foo', 'foo', [], ' bar') def test_get_dtext_following_wsp_preserved(self): self._test_get_x(parser.get_dtext, 'foo \t\tbar', 'foo', 'foo', [], ' \t\tbar') def test_get_dtext_non_printables(self): dtext = self._test_get_x(parser.get_dtext, 'foo\x00bar]', 'foo\x00bar', 'foo\x00bar', [errors.NonPrintableDefect], ']') self.assertEqual(dtext.defects[0].non_printables[0], '\x00') def test_get_dtext_with_qp(self): ptext = self._test_get_x(parser.get_dtext, r'foo\]\[\\bar\b\e\l\l', r'foo][\barbell', r'foo][\barbell', [errors.ObsoleteHeaderDefect], '') def test_get_dtext_up_to_close_bracket_only(self): self._test_get_x(parser.get_dtext, 'foo]', 'foo', 'foo', [], ']') def test_get_dtext_wsp_before_close_bracket_preserved(self): self._test_get_x(parser.get_dtext, 'foo ]', 'foo', 'foo', [], ' ]') def test_get_dtext_close_bracket_mid_word(self): self._test_get_x(parser.get_dtext, 'foo]bar', 'foo', 'foo', [], ']bar') def test_get_dtext_up_to_open_bracket_only(self): self._test_get_x(parser.get_dtext, 'foo[', 'foo', 'foo', [], '[') def test_get_dtext_wsp_before_open_bracket_preserved(self): self._test_get_x(parser.get_dtext, 'foo [', 'foo', 'foo', [], ' [') def test_get_dtext_open_bracket_mid_word(self): self._test_get_x(parser.get_dtext, 'foo[bar', 'foo', 'foo', [], '[bar') # get_domain_literal def test_get_domain_literal_only(self): domain_literal = domain_literal = self._test_get_x(parser.get_domain_literal, '[127.0.0.1]', '[127.0.0.1]', '[127.0.0.1]', [], '') self.assertEqual(domain_literal.token_type, 'domain-literal') self.assertEqual(domain_literal.domain, '[127.0.0.1]') self.assertEqual(domain_literal.ip, '127.0.0.1') def test_get_domain_literal_with_internal_ws(self): domain_literal = self._test_get_x(parser.get_domain_literal, '[ 127.0.0.1\t ]', '[ 127.0.0.1\t ]', '[ 127.0.0.1 ]', [], '') self.assertEqual(domain_literal.domain, '[127.0.0.1]') self.assertEqual(domain_literal.ip, '127.0.0.1') def test_get_domain_literal_with_surrounding_cfws(self): domain_literal = self._test_get_x(parser.get_domain_literal, '(foo)[ 127.0.0.1] (bar)', '(foo)[ 127.0.0.1] (bar)', ' [ 127.0.0.1] ', [], '') self.assertEqual(domain_literal.domain, '[127.0.0.1]') self.assertEqual(domain_literal.ip, '127.0.0.1') def test_get_domain_literal_no_start_char_raises(self): with self.assertRaises(errors.HeaderParseError): parser.get_domain_literal('(foo) ') def test_get_domain_literal_no_start_char_before_special_raises(self): with self.assertRaises(errors.HeaderParseError): parser.get_domain_literal('(foo) @') def test_get_domain_literal_bad_dtext_char_before_special_raises(self): with self.assertRaises(errors.HeaderParseError): parser.get_domain_literal('(foo) [abc[@') # get_domain def test_get_domain_regular_domain_only(self): domain = self._test_get_x(parser.get_domain, 'example.com', 'example.com', 'example.com', [], '') self.assertEqual(domain.token_type, 'domain') self.assertEqual(domain.domain, 'example.com') def test_get_domain_domain_literal_only(self): domain = self._test_get_x(parser.get_domain, '[127.0.0.1]', '[127.0.0.1]', '[127.0.0.1]', [], '') self.assertEqual(domain.token_type, 'domain') self.assertEqual(domain.domain, '[127.0.0.1]') def test_get_domain_with_cfws(self): domain = self._test_get_x(parser.get_domain, '(foo) example.com(bar)\t', '(foo) example.com(bar)\t', ' example.com ', [], '') self.assertEqual(domain.domain, 'example.com') def test_get_domain_domain_literal_with_cfws(self): domain = self._test_get_x(parser.get_domain, '(foo)[127.0.0.1]\t(bar)', '(foo)[127.0.0.1]\t(bar)', ' [127.0.0.1] ', [], '') self.assertEqual(domain.domain, '[127.0.0.1]') def test_get_domain_domain_with_cfws_ends_at_special(self): domain = self._test_get_x(parser.get_domain, '(foo)example.com\t(bar), next', '(foo)example.com\t(bar)', ' example.com ', [], ', next') self.assertEqual(domain.domain, 'example.com') def test_get_domain_domain_literal_with_cfws_ends_at_special(self): domain = self._test_get_x(parser.get_domain, '(foo)[127.0.0.1]\t(bar), next', '(foo)[127.0.0.1]\t(bar)', ' [127.0.0.1] ', [], ', next') self.assertEqual(domain.domain, '[127.0.0.1]') def test_get_domain_obsolete(self): domain = self._test_get_x(parser.get_domain, '(foo) example . (bird)com(bar)\t', '(foo) example . (bird)com(bar)\t', ' example . com ', [errors.ObsoleteHeaderDefect], '') self.assertEqual(domain.domain, 'example.com') def test_get_domain_no_non_cfws_raises(self): with self.assertRaises(errors.HeaderParseError): parser.get_domain(" (foo)\t") def test_get_domain_no_atom_raises(self): with self.assertRaises(errors.HeaderParseError): parser.get_domain(" (foo)\t, broken") # get_addr_spec def test_get_addr_spec_normal(self): addr_spec = self._test_get_x(parser.get_addr_spec, '[email protected]', '[email protected]', '[email protected]', [], '') self.assertEqual(addr_spec.token_type, 'addr-spec') self.assertEqual(addr_spec.local_part, 'dinsdale') self.assertEqual(addr_spec.domain, 'example.com') self.assertEqual(addr_spec.addr_spec, '[email protected]') def test_get_addr_spec_with_doamin_literal(self): addr_spec = self._test_get_x(parser.get_addr_spec, 'dinsdale@[127.0.0.1]', 'dinsdale@[127.0.0.1]', 'dinsdale@[127.0.0.1]', [], '') self.assertEqual(addr_spec.local_part, 'dinsdale') self.assertEqual(addr_spec.domain, '[127.0.0.1]') self.assertEqual(addr_spec.addr_spec, 'dinsdale@[127.0.0.1]') def test_get_addr_spec_with_cfws(self): addr_spec = self._test_get_x(parser.get_addr_spec, '(foo) dinsdale(bar)@ (bird) example.com (bog)', '(foo) dinsdale(bar)@ (bird) example.com (bog)', ' [email protected] ', [], '') self.assertEqual(addr_spec.local_part, 'dinsdale') self.assertEqual(addr_spec.domain, 'example.com') self.assertEqual(addr_spec.addr_spec, '[email protected]') def test_get_addr_spec_with_qouoted_string_and_cfws(self): addr_spec = self._test_get_x(parser.get_addr_spec, '(foo) "roy a bug"(bar)@ (bird) example.com (bog)', '(foo) "roy a bug"(bar)@ (bird) example.com (bog)', ' "roy a bug"@example.com ', [], '') self.assertEqual(addr_spec.local_part, 'roy a bug') self.assertEqual(addr_spec.domain, 'example.com') self.assertEqual(addr_spec.addr_spec, '"roy a bug"@example.com') def test_get_addr_spec_ends_at_special(self): addr_spec = self._test_get_x(parser.get_addr_spec, '(foo) "roy a bug"(bar)@ (bird) example.com (bog) , next', '(foo) "roy a bug"(bar)@ (bird) example.com (bog) ', ' "roy a bug"@example.com ', [], ', next') self.assertEqual(addr_spec.local_part, 'roy a bug') self.assertEqual(addr_spec.domain, 'example.com') self.assertEqual(addr_spec.addr_spec, '"roy a bug"@example.com') def test_get_addr_spec_quoted_strings_in_atom_list(self): addr_spec = self._test_get_x(parser.get_addr_spec, '""example" example"@example.com', '""example" example"@example.com', 'example [email protected]', [errors.InvalidHeaderDefect]*3, '') self.assertEqual(addr_spec.local_part, 'example example') self.assertEqual(addr_spec.domain, 'example.com') self.assertEqual(addr_spec.addr_spec, '"example example"@example.com') def test_get_addr_spec_dot_atom(self): addr_spec = self._test_get_x(parser.get_addr_spec, '[email protected]', '[email protected]', '[email protected]', [], '') self.assertEqual(addr_spec.local_part, 'star.a.star') self.assertEqual(addr_spec.domain, 'example.com') self.assertEqual(addr_spec.addr_spec, '[email protected]') def test_get_addr_spec_multiple_domains(self): with self.assertRaises(errors.HeaderParseError): parser.get_addr_spec('[email protected]@example.com') with self.assertRaises(errors.HeaderParseError): parser.get_addr_spec('star@[email protected]') with self.assertRaises(errors.HeaderParseError): parser.get_addr_spec('[email protected]@example.com') # get_obs_route def test_get_obs_route_simple(self): obs_route = self._test_get_x(parser.get_obs_route, '@example.com, @two.example.com:', '@example.com, @two.example.com:', '@example.com, @two.example.com:', [], '') self.assertEqual(obs_route.token_type, 'obs-route') self.assertEqual(obs_route.domains, ['example.com', 'two.example.com']) def test_get_obs_route_complex(self): obs_route = self._test_get_x(parser.get_obs_route, '(foo),, (blue)@example.com (bar),@two.(foo) example.com (bird):', '(foo),, (blue)@example.com (bar),@two.(foo) example.com (bird):', ' ,, @example.com ,@two. example.com :', [errors.ObsoleteHeaderDefect], # This is the obs-domain '') self.assertEqual(obs_route.token_type, 'obs-route') self.assertEqual(obs_route.domains, ['example.com', 'two.example.com']) def test_get_obs_route_no_route_before_end_raises(self): with self.assertRaises(errors.HeaderParseError): parser.get_obs_route('(foo) @example.com,') def test_get_obs_route_no_route_before_special_raises(self): with self.assertRaises(errors.HeaderParseError): parser.get_obs_route('(foo) [abc],') def test_get_obs_route_no_route_before_special_raises2(self): with self.assertRaises(errors.HeaderParseError): parser.get_obs_route('(foo) @example.com [abc],') # get_angle_addr def test_get_angle_addr_simple(self): angle_addr = self._test_get_x(parser.get_angle_addr, '<[email protected]>', '<[email protected]>', '<[email protected]>', [], '') self.assertEqual(angle_addr.token_type, 'angle-addr') self.assertEqual(angle_addr.local_part, 'dinsdale') self.assertEqual(angle_addr.domain, 'example.com') self.assertIsNone(angle_addr.route) self.assertEqual(angle_addr.addr_spec, '[email protected]') def test_get_angle_addr_empty(self): angle_addr = self._test_get_x(parser.get_angle_addr, '<>', '<>', '<>', [errors.InvalidHeaderDefect], '') self.assertEqual(angle_addr.token_type, 'angle-addr') self.assertIsNone(angle_addr.local_part) self.assertIsNone(angle_addr.domain) self.assertIsNone(angle_addr.route) self.assertEqual(angle_addr.addr_spec, '<>') def test_get_angle_addr_qs_only_quotes(self): angle_addr = self._test_get_x(parser.get_angle_addr, '<""@example.com>', '<""@example.com>', '<""@example.com>', [], '') self.assertEqual(angle_addr.token_type, 'angle-addr') self.assertEqual(angle_addr.local_part, '') self.assertEqual(angle_addr.domain, 'example.com') self.assertIsNone(angle_addr.route) self.assertEqual(angle_addr.addr_spec, '""@example.com') def test_get_angle_addr_with_cfws(self): angle_addr = self._test_get_x(parser.get_angle_addr, ' (foo) <[email protected]>(bar)', ' (foo) <[email protected]>(bar)', ' <[email protected]> ', [], '') self.assertEqual(angle_addr.token_type, 'angle-addr') self.assertEqual(angle_addr.local_part, 'dinsdale') self.assertEqual(angle_addr.domain, 'example.com') self.assertIsNone(angle_addr.route) self.assertEqual(angle_addr.addr_spec, '[email protected]') def test_get_angle_addr_qs_and_domain_literal(self): angle_addr = self._test_get_x(parser.get_angle_addr, '<"Fred Perfect"@[127.0.0.1]>', '<"Fred Perfect"@[127.0.0.1]>', '<"Fred Perfect"@[127.0.0.1]>', [], '') self.assertEqual(angle_addr.local_part, 'Fred Perfect') self.assertEqual(angle_addr.domain, '[127.0.0.1]') self.assertIsNone(angle_addr.route) self.assertEqual(angle_addr.addr_spec, '"Fred Perfect"@[127.0.0.1]') def test_get_angle_addr_internal_cfws(self): angle_addr = self._test_get_x(parser.get_angle_addr, '<(foo) [email protected](bar)>', '<(foo) [email protected](bar)>', '< [email protected] >', [], '') self.assertEqual(angle_addr.local_part, 'dinsdale') self.assertEqual(angle_addr.domain, 'example.com') self.assertIsNone(angle_addr.route) self.assertEqual(angle_addr.addr_spec, '[email protected]') def test_get_angle_addr_obs_route(self): angle_addr = self._test_get_x(parser.get_angle_addr, '(foo)<@example.com, (bird) @two.example.com: [email protected]> (bar) ', '(foo)<@example.com, (bird) @two.example.com: [email protected]> (bar) ', ' <@example.com, @two.example.com: [email protected]> ', [errors.ObsoleteHeaderDefect], '') self.assertEqual(angle_addr.local_part, 'dinsdale') self.assertEqual(angle_addr.domain, 'example.com') self.assertEqual(angle_addr.route, ['example.com', 'two.example.com']) self.assertEqual(angle_addr.addr_spec, '[email protected]') def test_get_angle_addr_missing_closing_angle(self): angle_addr = self._test_get_x(parser.get_angle_addr, '<[email protected]', '<[email protected]>', '<[email protected]>', [errors.InvalidHeaderDefect], '') self.assertEqual(angle_addr.local_part, 'dinsdale') self.assertEqual(angle_addr.domain, 'example.com') self.assertIsNone(angle_addr.route) self.assertEqual(angle_addr.addr_spec, '[email protected]') def test_get_angle_addr_missing_closing_angle_with_cfws(self): angle_addr = self._test_get_x(parser.get_angle_addr, '<[email protected] (foo)', '<[email protected] (foo)>', '<[email protected] >', [errors.InvalidHeaderDefect], '') self.assertEqual(angle_addr.local_part, 'dinsdale') self.assertEqual(angle_addr.domain, 'example.com') self.assertIsNone(angle_addr.route) self.assertEqual(angle_addr.addr_spec, '[email protected]') def test_get_angle_addr_ends_at_special(self): angle_addr = self._test_get_x(parser.get_angle_addr, '<[email protected]> (foo), next', '<[email protected]> (foo)', '<[email protected]> ', [], ', next') self.assertEqual(angle_addr.local_part, 'dinsdale') self.assertEqual(angle_addr.domain, 'example.com') self.assertIsNone(angle_addr.route) self.assertEqual(angle_addr.addr_spec, '[email protected]') def test_get_angle_addr_no_angle_raise(self): with self.assertRaises(errors.HeaderParseError): parser.get_angle_addr('(foo) ') def test_get_angle_addr_no_angle_before_special_raises(self): with self.assertRaises(errors.HeaderParseError): parser.get_angle_addr('(foo) , next') def test_get_angle_addr_no_angle_raises(self): with self.assertRaises(errors.HeaderParseError): parser.get_angle_addr('bar') def test_get_angle_addr_special_after_angle_raises(self): with self.assertRaises(errors.HeaderParseError): parser.get_angle_addr('(foo) <, bar') # get_display_name This is phrase but with a different value. def test_get_display_name_simple(self): display_name = self._test_get_x(parser.get_display_name, 'Fred A Johnson', 'Fred A Johnson', 'Fred A Johnson', [], '') self.assertEqual(display_name.token_type, 'display-name') self.assertEqual(display_name.display_name, 'Fred A Johnson') def test_get_display_name_complex1(self): display_name = self._test_get_x(parser.get_display_name, '"Fred A. Johnson" is his name, oh.', '"Fred A. Johnson" is his name', '"Fred A. Johnson is his name"', [], ', oh.') self.assertEqual(display_name.token_type, 'display-name') self.assertEqual(display_name.display_name, 'Fred A. Johnson is his name') def test_get_display_name_complex2(self): display_name = self._test_get_x(parser.get_display_name, ' (A) bird (in (my|your)) "hand " is messy\t<>\t', ' (A) bird (in (my|your)) "hand " is messy\t', ' "bird hand is messy" ', [], '<>\t') self.assertEqual(display_name[0][0].comments, ['A']) self.assertEqual(display_name[0][2].comments, ['in (my|your)']) self.assertEqual(display_name.display_name, 'bird hand is messy') def test_get_display_name_obsolete(self): display_name = self._test_get_x(parser.get_display_name, 'Fred A.(weird).O Johnson', 'Fred A.(weird).O Johnson', '"Fred A. .O Johnson"', [errors.ObsoleteHeaderDefect]*3, '') self.assertEqual(len(display_name), 7) self.assertEqual(display_name[3].comments, ['weird']) self.assertEqual(display_name.display_name, 'Fred A. .O Johnson') def test_get_display_name_pharse_must_start_with_word(self): display_name = self._test_get_x(parser.get_display_name, '(even weirder).name', '(even weirder).name', ' ".name"', [errors.InvalidHeaderDefect] + [errors.ObsoleteHeaderDefect]*2, '') self.assertEqual(len(display_name), 3) self.assertEqual(display_name[0].comments, ['even weirder']) self.assertEqual(display_name.display_name, '.name') def test_get_display_name_ending_with_obsolete(self): display_name = self._test_get_x(parser.get_display_name, 'simple phrase.(with trailing comment):boo', 'simple phrase.(with trailing comment)', '"simple phrase." ', [errors.ObsoleteHeaderDefect]*2, ':boo') self.assertEqual(len(display_name), 4) self.assertEqual(display_name[3].comments, ['with trailing comment']) self.assertEqual(display_name.display_name, 'simple phrase.') # get_name_addr def test_get_name_addr_angle_addr_only(self): name_addr = self._test_get_x(parser.get_name_addr, '<[email protected]>', '<[email protected]>', '<[email protected]>', [], '') self.assertEqual(name_addr.token_type, 'name-addr') self.assertIsNone(name_addr.display_name) self.assertEqual(name_addr.local_part, 'dinsdale') self.assertEqual(name_addr.domain, 'example.com') self.assertIsNone(name_addr.route) self.assertEqual(name_addr.addr_spec, '[email protected]') def test_get_name_addr_atom_name(self): name_addr = self._test_get_x(parser.get_name_addr, 'Dinsdale <[email protected]>', 'Dinsdale <[email protected]>', 'Dinsdale <[email protected]>', [], '') self.assertEqual(name_addr.token_type, 'name-addr') self.assertEqual(name_addr.display_name, 'Dinsdale') self.assertEqual(name_addr.local_part, 'dinsdale') self.assertEqual(name_addr.domain, 'example.com') self.assertIsNone(name_addr.route) self.assertEqual(name_addr.addr_spec, '[email protected]') def test_get_name_addr_atom_name_with_cfws(self): name_addr = self._test_get_x(parser.get_name_addr, '(foo) Dinsdale (bar) <[email protected]> (bird)', '(foo) Dinsdale (bar) <[email protected]> (bird)', ' Dinsdale <[email protected]> ', [], '') self.assertEqual(name_addr.display_name, 'Dinsdale') self.assertEqual(name_addr.local_part, 'dinsdale') self.assertEqual(name_addr.domain, 'example.com') self.assertIsNone(name_addr.route) self.assertEqual(name_addr.addr_spec, '[email protected]') def test_get_name_addr_name_with_cfws_and_dots(self): name_addr = self._test_get_x(parser.get_name_addr, '(foo) Roy.A.Bear (bar) <[email protected]> (bird)', '(foo) Roy.A.Bear (bar) <[email protected]> (bird)', ' "Roy.A.Bear" <[email protected]> ', [errors.ObsoleteHeaderDefect]*2, '') self.assertEqual(name_addr.display_name, 'Roy.A.Bear') self.assertEqual(name_addr.local_part, 'dinsdale') self.assertEqual(name_addr.domain, 'example.com') self.assertIsNone(name_addr.route) self.assertEqual(name_addr.addr_spec, '[email protected]') def test_get_name_addr_qs_name(self): name_addr = self._test_get_x(parser.get_name_addr, '"Roy.A.Bear" <[email protected]>', '"Roy.A.Bear" <[email protected]>', '"Roy.A.Bear" <[email protected]>', [], '') self.assertEqual(name_addr.display_name, 'Roy.A.Bear') self.assertEqual(name_addr.local_part, 'dinsdale') self.assertEqual(name_addr.domain, 'example.com') self.assertIsNone(name_addr.route) self.assertEqual(name_addr.addr_spec, '[email protected]') def test_get_name_addr_with_route(self): name_addr = self._test_get_x(parser.get_name_addr, '"Roy.A.Bear" <@two.example.com: [email protected]>', '"Roy.A.Bear" <@two.example.com: [email protected]>', '"Roy.A.Bear" <@two.example.com: [email protected]>', [errors.ObsoleteHeaderDefect], '') self.assertEqual(name_addr.display_name, 'Roy.A.Bear') self.assertEqual(name_addr.local_part, 'dinsdale') self.assertEqual(name_addr.domain, 'example.com') self.assertEqual(name_addr.route, ['two.example.com']) self.assertEqual(name_addr.addr_spec, '[email protected]') def test_get_name_addr_ends_at_special(self): name_addr = self._test_get_x(parser.get_name_addr, '"Roy.A.Bear" <[email protected]>, next', '"Roy.A.Bear" <[email protected]>', '"Roy.A.Bear" <[email protected]>', [], ', next') self.assertEqual(name_addr.display_name, 'Roy.A.Bear') self.assertEqual(name_addr.local_part, 'dinsdale') self.assertEqual(name_addr.domain, 'example.com') self.assertIsNone(name_addr.route) self.assertEqual(name_addr.addr_spec, '[email protected]') def test_get_name_addr_no_content_raises(self): with self.assertRaises(errors.HeaderParseError): parser.get_name_addr(' (foo) ') def test_get_name_addr_no_content_before_special_raises(self): with self.assertRaises(errors.HeaderParseError): parser.get_name_addr(' (foo) ,') def test_get_name_addr_no_angle_after_display_name_raises(self): with self.assertRaises(errors.HeaderParseError): parser.get_name_addr('foo bar') # get_mailbox def test_get_mailbox_addr_spec_only(self): mailbox = self._test_get_x(parser.get_mailbox, '[email protected]', '[email protected]', '[email protected]', [], '') self.assertEqual(mailbox.token_type, 'mailbox') self.assertIsNone(mailbox.display_name) self.assertEqual(mailbox.local_part, 'dinsdale') self.assertEqual(mailbox.domain, 'example.com') self.assertIsNone(mailbox.route) self.assertEqual(mailbox.addr_spec, '[email protected]') def test_get_mailbox_angle_addr_only(self): mailbox = self._test_get_x(parser.get_mailbox, '<[email protected]>', '<[email protected]>', '<[email protected]>', [], '') self.assertEqual(mailbox.token_type, 'mailbox') self.assertIsNone(mailbox.display_name) self.assertEqual(mailbox.local_part, 'dinsdale') self.assertEqual(mailbox.domain, 'example.com') self.assertIsNone(mailbox.route) self.assertEqual(mailbox.addr_spec, '[email protected]') def test_get_mailbox_name_addr(self): mailbox = self._test_get_x(parser.get_mailbox, '"Roy A. Bear" <[email protected]>', '"Roy A. Bear" <[email protected]>', '"Roy A. Bear" <[email protected]>', [], '') self.assertEqual(mailbox.token_type, 'mailbox') self.assertEqual(mailbox.display_name, 'Roy A. Bear') self.assertEqual(mailbox.local_part, 'dinsdale') self.assertEqual(mailbox.domain, 'example.com') self.assertIsNone(mailbox.route) self.assertEqual(mailbox.addr_spec, '[email protected]') def test_get_mailbox_ends_at_special(self): mailbox = self._test_get_x(parser.get_mailbox, '"Roy A. Bear" <[email protected]>, rest', '"Roy A. Bear" <[email protected]>', '"Roy A. Bear" <[email protected]>', [], ', rest') self.assertEqual(mailbox.token_type, 'mailbox') self.assertEqual(mailbox.display_name, 'Roy A. Bear') self.assertEqual(mailbox.local_part, 'dinsdale') self.assertEqual(mailbox.domain, 'example.com') self.assertIsNone(mailbox.route) self.assertEqual(mailbox.addr_spec, '[email protected]') def test_get_mailbox_quoted_strings_in_atom_list(self): mailbox = self._test_get_x(parser.get_mailbox, '""example" example"@example.com', '""example" example"@example.com', 'example [email protected]', [errors.InvalidHeaderDefect]*3, '') self.assertEqual(mailbox.local_part, 'example example') self.assertEqual(mailbox.domain, 'example.com') self.assertEqual(mailbox.addr_spec, '"example example"@example.com') # get_mailbox_list def test_get_mailbox_list_single_addr(self): mailbox_list = self._test_get_x(parser.get_mailbox_list, '[email protected]', '[email protected]', '[email protected]', [], '') self.assertEqual(mailbox_list.token_type, 'mailbox-list') self.assertEqual(len(mailbox_list.mailboxes), 1) mailbox = mailbox_list.mailboxes[0] self.assertIsNone(mailbox.display_name) self.assertEqual(mailbox.local_part, 'dinsdale') self.assertEqual(mailbox.domain, 'example.com') self.assertIsNone(mailbox.route) self.assertEqual(mailbox.addr_spec, '[email protected]') self.assertEqual(mailbox_list.mailboxes, mailbox_list.all_mailboxes) def test_get_mailbox_list_two_simple_addr(self): mailbox_list = self._test_get_x(parser.get_mailbox_list, '[email protected], [email protected]', '[email protected], [email protected]', '[email protected], [email protected]', [], '') self.assertEqual(mailbox_list.token_type, 'mailbox-list') self.assertEqual(len(mailbox_list.mailboxes), 2) self.assertEqual(mailbox_list.mailboxes[0].addr_spec, '[email protected]') self.assertEqual(mailbox_list.mailboxes[1].addr_spec, '[email protected]') self.assertEqual(mailbox_list.mailboxes, mailbox_list.all_mailboxes) def test_get_mailbox_list_two_name_addr(self): mailbox_list = self._test_get_x(parser.get_mailbox_list, ('"Roy A. Bear" <[email protected]>,' ' "Fred Flintstone" <[email protected]>'), ('"Roy A. Bear" <[email protected]>,' ' "Fred Flintstone" <[email protected]>'), ('"Roy A. Bear" <[email protected]>,' ' "Fred Flintstone" <[email protected]>'), [], '') self.assertEqual(len(mailbox_list.mailboxes), 2) self.assertEqual(mailbox_list.mailboxes[0].addr_spec, '[email protected]') self.assertEqual(mailbox_list.mailboxes[0].display_name, 'Roy A. Bear') self.assertEqual(mailbox_list.mailboxes[1].addr_spec, '[email protected]') self.assertEqual(mailbox_list.mailboxes[1].display_name, 'Fred Flintstone') self.assertEqual(mailbox_list.mailboxes, mailbox_list.all_mailboxes) def test_get_mailbox_list_two_complex(self): mailbox_list = self._test_get_x(parser.get_mailbox_list, ('(foo) "Roy A. Bear" <[email protected]>(bar),' ' "Fred Flintstone" <dinsdale@test.(bird)example.com>'), ('(foo) "Roy A. Bear" <[email protected]>(bar),' ' "Fred Flintstone" <dinsdale@test.(bird)example.com>'), (' "Roy A. Bear" <[email protected]> ,' ' "Fred Flintstone" <dinsdale@test. example.com>'), [errors.ObsoleteHeaderDefect], '') self.assertEqual(len(mailbox_list.mailboxes), 2) self.assertEqual(mailbox_list.mailboxes[0].addr_spec, '[email protected]') self.assertEqual(mailbox_list.mailboxes[0].display_name, 'Roy A. Bear') self.assertEqual(mailbox_list.mailboxes[1].addr_spec, '[email protected]') self.assertEqual(mailbox_list.mailboxes[1].display_name, 'Fred Flintstone') self.assertEqual(mailbox_list.mailboxes, mailbox_list.all_mailboxes) def test_get_mailbox_list_unparseable_mailbox_null(self): mailbox_list = self._test_get_x(parser.get_mailbox_list, ('"Roy A. Bear"[] [email protected],' ' "Fred Flintstone" <dinsdale@test.(bird)example.com>'), ('"Roy A. Bear"[] [email protected],' ' "Fred Flintstone" <dinsdale@test.(bird)example.com>'), ('"Roy A. Bear"[] [email protected],' ' "Fred Flintstone" <dinsdale@test. example.com>'), [errors.InvalidHeaderDefect, # the 'extra' text after the local part errors.InvalidHeaderDefect, # the local part with no angle-addr errors.ObsoleteHeaderDefect, # period in extra text (example.com) errors.ObsoleteHeaderDefect], # (bird) in valid address. '') self.assertEqual(len(mailbox_list.mailboxes), 1) self.assertEqual(len(mailbox_list.all_mailboxes), 2) self.assertEqual(mailbox_list.all_mailboxes[0].token_type, 'invalid-mailbox') self.assertIsNone(mailbox_list.all_mailboxes[0].display_name) self.assertEqual(mailbox_list.all_mailboxes[0].local_part, 'Roy A. Bear') self.assertIsNone(mailbox_list.all_mailboxes[0].domain) self.assertEqual(mailbox_list.all_mailboxes[0].addr_spec, '"Roy A. Bear"') self.assertIs(mailbox_list.all_mailboxes[1], mailbox_list.mailboxes[0]) self.assertEqual(mailbox_list.mailboxes[0].addr_spec, '[email protected]') self.assertEqual(mailbox_list.mailboxes[0].display_name, 'Fred Flintstone') def test_get_mailbox_list_junk_after_valid_address(self): mailbox_list = self._test_get_x(parser.get_mailbox_list, ('"Roy A. Bear" <[email protected]>@@,' ' "Fred Flintstone" <[email protected]>'), ('"Roy A. Bear" <[email protected]>@@,' ' "Fred Flintstone" <[email protected]>'), ('"Roy A. Bear" <[email protected]>@@,' ' "Fred Flintstone" <[email protected]>'), [errors.InvalidHeaderDefect], '') self.assertEqual(len(mailbox_list.mailboxes), 1) self.assertEqual(len(mailbox_list.all_mailboxes), 2) self.assertEqual(mailbox_list.all_mailboxes[0].addr_spec, '[email protected]') self.assertEqual(mailbox_list.all_mailboxes[0].display_name, 'Roy A. Bear') self.assertEqual(mailbox_list.all_mailboxes[0].token_type, 'invalid-mailbox') self.assertIs(mailbox_list.all_mailboxes[1], mailbox_list.mailboxes[0]) self.assertEqual(mailbox_list.mailboxes[0].addr_spec, '[email protected]') self.assertEqual(mailbox_list.mailboxes[0].display_name, 'Fred Flintstone') def test_get_mailbox_list_empty_list_element(self): mailbox_list = self._test_get_x(parser.get_mailbox_list, ('"Roy A. Bear" <[email protected]>, (bird),,' ' "Fred Flintstone" <[email protected]>'), ('"Roy A. Bear" <[email protected]>, (bird),,' ' "Fred Flintstone" <[email protected]>'), ('"Roy A. Bear" <[email protected]>, ,,' ' "Fred Flintstone" <[email protected]>'), [errors.ObsoleteHeaderDefect]*2, '') self.assertEqual(len(mailbox_list.mailboxes), 2) self.assertEqual(mailbox_list.all_mailboxes, mailbox_list.mailboxes) self.assertEqual(mailbox_list.all_mailboxes[0].addr_spec, '[email protected]') self.assertEqual(mailbox_list.all_mailboxes[0].display_name, 'Roy A. Bear') self.assertEqual(mailbox_list.mailboxes[1].addr_spec, '[email protected]') self.assertEqual(mailbox_list.mailboxes[1].display_name, 'Fred Flintstone') def test_get_mailbox_list_only_empty_elements(self): mailbox_list = self._test_get_x(parser.get_mailbox_list, '(foo),, (bar)', '(foo),, (bar)', ' ,, ', [errors.ObsoleteHeaderDefect]*3, '') self.assertEqual(len(mailbox_list.mailboxes), 0) self.assertEqual(mailbox_list.all_mailboxes, mailbox_list.mailboxes) # get_group_list def test_get_group_list_cfws_only(self): group_list = self._test_get_x(parser.get_group_list, '(hidden);', '(hidden)', ' ', [], ';') self.assertEqual(group_list.token_type, 'group-list') self.assertEqual(len(group_list.mailboxes), 0) self.assertEqual(group_list.mailboxes, group_list.all_mailboxes) def test_get_group_list_mailbox_list(self): group_list = self._test_get_x(parser.get_group_list, '[email protected], "Fred A. Bear" <[email protected]>', '[email protected], "Fred A. Bear" <[email protected]>', '[email protected], "Fred A. Bear" <[email protected]>', [], '') self.assertEqual(group_list.token_type, 'group-list') self.assertEqual(len(group_list.mailboxes), 2) self.assertEqual(group_list.mailboxes, group_list.all_mailboxes) self.assertEqual(group_list.mailboxes[1].display_name, 'Fred A. Bear') def test_get_group_list_obs_group_list(self): group_list = self._test_get_x(parser.get_group_list, ', (foo),,(bar)', ', (foo),,(bar)', ', ,, ', [errors.ObsoleteHeaderDefect], '') self.assertEqual(group_list.token_type, 'group-list') self.assertEqual(len(group_list.mailboxes), 0) self.assertEqual(group_list.mailboxes, group_list.all_mailboxes) def test_get_group_list_comment_only_invalid(self): group_list = self._test_get_x(parser.get_group_list, '(bar)', '(bar)', ' ', [errors.InvalidHeaderDefect], '') self.assertEqual(group_list.token_type, 'group-list') self.assertEqual(len(group_list.mailboxes), 0) self.assertEqual(group_list.mailboxes, group_list.all_mailboxes) # get_group def test_get_group_empty(self): group = self._test_get_x(parser.get_group, 'Monty Python:;', 'Monty Python:;', 'Monty Python:;', [], '') self.assertEqual(group.token_type, 'group') self.assertEqual(group.display_name, 'Monty Python') self.assertEqual(len(group.mailboxes), 0) self.assertEqual(group.mailboxes, group.all_mailboxes) def test_get_group_null_addr_spec(self): group = self._test_get_x(parser.get_group, 'foo: <>;', 'foo: <>;', 'foo: <>;', [errors.InvalidHeaderDefect], '') self.assertEqual(group.display_name, 'foo') self.assertEqual(len(group.mailboxes), 0) self.assertEqual(len(group.all_mailboxes), 1) self.assertEqual(group.all_mailboxes[0].value, '<>') def test_get_group_cfws_only(self): group = self._test_get_x(parser.get_group, 'Monty Python: (hidden);', 'Monty Python: (hidden);', 'Monty Python: ;', [], '') self.assertEqual(group.token_type, 'group') self.assertEqual(group.display_name, 'Monty Python') self.assertEqual(len(group.mailboxes), 0) self.assertEqual(group.mailboxes, group.all_mailboxes) def test_get_group_single_mailbox(self): group = self._test_get_x(parser.get_group, 'Monty Python: "Fred A. Bear" <[email protected]>;', 'Monty Python: "Fred A. Bear" <[email protected]>;', 'Monty Python: "Fred A. Bear" <[email protected]>;', [], '') self.assertEqual(group.token_type, 'group') self.assertEqual(group.display_name, 'Monty Python') self.assertEqual(len(group.mailboxes), 1) self.assertEqual(group.mailboxes, group.all_mailboxes) self.assertEqual(group.mailboxes[0].addr_spec, '[email protected]') def test_get_group_mixed_list(self): group = self._test_get_x(parser.get_group, ('Monty Python: "Fred A. Bear" <[email protected]>,' '(foo) Roger <[email protected]>, [email protected];'), ('Monty Python: "Fred A. Bear" <[email protected]>,' '(foo) Roger <[email protected]>, [email protected];'), ('Monty Python: "Fred A. Bear" <[email protected]>,' ' Roger <[email protected]>, [email protected];'), [], '') self.assertEqual(group.token_type, 'group') self.assertEqual(group.display_name, 'Monty Python') self.assertEqual(len(group.mailboxes), 3) self.assertEqual(group.mailboxes, group.all_mailboxes) self.assertEqual(group.mailboxes[0].display_name, 'Fred A. Bear') self.assertEqual(group.mailboxes[1].display_name, 'Roger') self.assertEqual(group.mailboxes[2].local_part, 'x') def test_get_group_one_invalid(self): group = self._test_get_x(parser.get_group, ('Monty Python: "Fred A. Bear" <[email protected]>,' '(foo) Roger [email protected], [email protected];'), ('Monty Python: "Fred A. Bear" <[email protected]>,' '(foo) Roger [email protected], [email protected];'), ('Monty Python: "Fred A. Bear" <[email protected]>,' ' Roger [email protected], [email protected];'), [errors.InvalidHeaderDefect, # non-angle addr makes local part invalid errors.InvalidHeaderDefect], # and its not obs-local either: no dots. '') self.assertEqual(group.token_type, 'group') self.assertEqual(group.display_name, 'Monty Python') self.assertEqual(len(group.mailboxes), 2) self.assertEqual(len(group.all_mailboxes), 3) self.assertEqual(group.mailboxes[0].display_name, 'Fred A. Bear') self.assertEqual(group.mailboxes[1].local_part, 'x') self.assertIsNone(group.all_mailboxes[1].display_name) def test_get_group_missing_final_semicol(self): group = self._test_get_x(parser.get_group, ('Monty Python:"Fred A. Bear" <[email protected]>,' '[email protected],John <jdoe@test>'), ('Monty Python:"Fred A. Bear" <[email protected]>,' '[email protected],John <jdoe@test>;'), ('Monty Python:"Fred A. Bear" <[email protected]>,' '[email protected],John <jdoe@test>;'), [errors.InvalidHeaderDefect], '') self.assertEqual(group.token_type, 'group') self.assertEqual(group.display_name, 'Monty Python') self.assertEqual(len(group.mailboxes), 3) self.assertEqual(group.mailboxes, group.all_mailboxes) self.assertEqual(group.mailboxes[0].addr_spec, '[email protected]') self.assertEqual(group.mailboxes[0].display_name, 'Fred A. Bear') self.assertEqual(group.mailboxes[1].addr_spec, '[email protected]') self.assertEqual(group.mailboxes[2].display_name, 'John') self.assertEqual(group.mailboxes[2].addr_spec, 'jdoe@test') # get_address def test_get_address_simple(self): address = self._test_get_x(parser.get_address, '[email protected]', '[email protected]', '[email protected]', [], '') self.assertEqual(address.token_type, 'address') self.assertEqual(len(address.mailboxes), 1) self.assertEqual(address.mailboxes, address.all_mailboxes) self.assertEqual(address.mailboxes[0].domain, 'example.com') self.assertEqual(address[0].token_type, 'mailbox') def test_get_address_complex(self): address = self._test_get_x(parser.get_address, '(foo) "Fred A. Bear" <(bird)[email protected]>', '(foo) "Fred A. Bear" <(bird)[email protected]>', ' "Fred A. Bear" < [email protected]>', [], '') self.assertEqual(address.token_type, 'address') self.assertEqual(len(address.mailboxes), 1) self.assertEqual(address.mailboxes, address.all_mailboxes) self.assertEqual(address.mailboxes[0].display_name, 'Fred A. Bear') self.assertEqual(address[0].token_type, 'mailbox') def test_get_address_rfc2047_display_name(self): address = self._test_get_x(parser.get_address, '=?utf-8?q?=C3=89ric?= <[email protected]>', 'Éric <[email protected]>', 'Éric <[email protected]>', [], '') self.assertEqual(address.token_type, 'address') self.assertEqual(len(address.mailboxes), 1) self.assertEqual(address.mailboxes, address.all_mailboxes) self.assertEqual(address.mailboxes[0].display_name, 'Éric') self.assertEqual(address[0].token_type, 'mailbox') def test_get_address_empty_group(self): address = self._test_get_x(parser.get_address, 'Monty Python:;', 'Monty Python:;', 'Monty Python:;', [], '') self.assertEqual(address.token_type, 'address') self.assertEqual(len(address.mailboxes), 0) self.assertEqual(address.mailboxes, address.all_mailboxes) self.assertEqual(address[0].token_type, 'group') self.assertEqual(address[0].display_name, 'Monty Python') def test_get_address_group(self): address = self._test_get_x(parser.get_address, 'Monty Python: [email protected], [email protected];', 'Monty Python: [email protected], [email protected];', 'Monty Python: [email protected], [email protected];', [], '') self.assertEqual(address.token_type, 'address') self.assertEqual(len(address.mailboxes), 2) self.assertEqual(address.mailboxes, address.all_mailboxes) self.assertEqual(address[0].token_type, 'group') self.assertEqual(address[0].display_name, 'Monty Python') self.assertEqual(address.mailboxes[0].local_part, 'x') def test_get_address_quoted_local_part(self): address = self._test_get_x(parser.get_address, '"foo bar"@example.com', '"foo bar"@example.com', '"foo bar"@example.com', [], '') self.assertEqual(address.token_type, 'address') self.assertEqual(len(address.mailboxes), 1) self.assertEqual(address.mailboxes, address.all_mailboxes) self.assertEqual(address.mailboxes[0].domain, 'example.com') self.assertEqual(address.mailboxes[0].local_part, 'foo bar') self.assertEqual(address[0].token_type, 'mailbox') def test_get_address_ends_at_special(self): address = self._test_get_x(parser.get_address, '[email protected], next', '[email protected]', '[email protected]', [], ', next') self.assertEqual(address.token_type, 'address') self.assertEqual(len(address.mailboxes), 1) self.assertEqual(address.mailboxes, address.all_mailboxes) self.assertEqual(address.mailboxes[0].domain, 'example.com') self.assertEqual(address[0].token_type, 'mailbox') def test_get_address_invalid_mailbox_invalid(self): address = self._test_get_x(parser.get_address, 'ping example.com, next', 'ping example.com', 'ping example.com', [errors.InvalidHeaderDefect, # addr-spec with no domain errors.InvalidHeaderDefect, # invalid local-part errors.InvalidHeaderDefect, # missing .s in local-part ], ', next') self.assertEqual(address.token_type, 'address') self.assertEqual(len(address.mailboxes), 0) self.assertEqual(len(address.all_mailboxes), 1) self.assertIsNone(address.all_mailboxes[0].domain) self.assertEqual(address.all_mailboxes[0].local_part, 'ping example.com') self.assertEqual(address[0].token_type, 'invalid-mailbox') def test_get_address_quoted_strings_in_atom_list(self): address = self._test_get_x(parser.get_address, '""example" example"@example.com', '""example" example"@example.com', 'example [email protected]', [errors.InvalidHeaderDefect]*3, '') self.assertEqual(address.all_mailboxes[0].local_part, 'example example') self.assertEqual(address.all_mailboxes[0].domain, 'example.com') self.assertEqual(address.all_mailboxes[0].addr_spec, '"example example"@example.com') # get_address_list def test_get_address_list_mailboxes_simple(self): address_list = self._test_get_x(parser.get_address_list, '[email protected]', '[email protected]', '[email protected]', [], '') self.assertEqual(address_list.token_type, 'address-list') self.assertEqual(len(address_list.mailboxes), 1) self.assertEqual(address_list.mailboxes, address_list.all_mailboxes) self.assertEqual([str(x) for x in address_list.mailboxes], [str(x) for x in address_list.addresses]) self.assertEqual(address_list.mailboxes[0].domain, 'example.com') self.assertEqual(address_list[0].token_type, 'address') self.assertIsNone(address_list[0].display_name) def test_get_address_list_mailboxes_two_simple(self): address_list = self._test_get_x(parser.get_address_list, '[email protected], "Fred A. Bar" <[email protected]>', '[email protected], "Fred A. Bar" <[email protected]>', '[email protected], "Fred A. Bar" <[email protected]>', [], '') self.assertEqual(address_list.token_type, 'address-list') self.assertEqual(len(address_list.mailboxes), 2) self.assertEqual(address_list.mailboxes, address_list.all_mailboxes) self.assertEqual([str(x) for x in address_list.mailboxes], [str(x) for x in address_list.addresses]) self.assertEqual(address_list.mailboxes[0].local_part, 'foo') self.assertEqual(address_list.mailboxes[1].display_name, "Fred A. Bar") def test_get_address_list_mailboxes_complex(self): address_list = self._test_get_x(parser.get_address_list, ('"Roy A. Bear" <[email protected]>, ' '(ping) Foo <[email protected]>,' 'Nobody Is. Special <y@(bird)example.(bad)com>'), ('"Roy A. Bear" <[email protected]>, ' '(ping) Foo <[email protected]>,' 'Nobody Is. Special <y@(bird)example.(bad)com>'), ('"Roy A. Bear" <[email protected]>, ' 'Foo <[email protected]>,' '"Nobody Is. Special" <y@example. com>'), [errors.ObsoleteHeaderDefect, # period in Is. errors.ObsoleteHeaderDefect], # cfws in domain '') self.assertEqual(address_list.token_type, 'address-list') self.assertEqual(len(address_list.mailboxes), 3) self.assertEqual(address_list.mailboxes, address_list.all_mailboxes) self.assertEqual([str(x) for x in address_list.mailboxes], [str(x) for x in address_list.addresses]) self.assertEqual(address_list.mailboxes[0].domain, 'example.com') self.assertEqual(address_list.mailboxes[0].token_type, 'mailbox') self.assertEqual(address_list.addresses[0].token_type, 'address') self.assertEqual(address_list.mailboxes[1].local_part, 'x') self.assertEqual(address_list.mailboxes[2].display_name, 'Nobody Is. Special') def test_get_address_list_mailboxes_invalid_addresses(self): address_list = self._test_get_x(parser.get_address_list, ('"Roy A. Bear" <[email protected]>, ' '(ping) Foo [email protected][],' 'Nobody Is. Special <(bird)example.(bad)com>'), ('"Roy A. Bear" <[email protected]>, ' '(ping) Foo [email protected][],' 'Nobody Is. Special <(bird)example.(bad)com>'), ('"Roy A. Bear" <[email protected]>, ' 'Foo [email protected][],' '"Nobody Is. Special" < example. com>'), [errors.InvalidHeaderDefect, # invalid address in list errors.InvalidHeaderDefect, # 'Foo x' local part invalid. errors.InvalidHeaderDefect, # Missing . in 'Foo x' local part errors.ObsoleteHeaderDefect, # period in 'Is.' disp-name phrase errors.InvalidHeaderDefect, # no domain part in addr-spec errors.ObsoleteHeaderDefect], # addr-spec has comment in it '') self.assertEqual(address_list.token_type, 'address-list') self.assertEqual(len(address_list.mailboxes), 1) self.assertEqual(len(address_list.all_mailboxes), 3) self.assertEqual([str(x) for x in address_list.all_mailboxes], [str(x) for x in address_list.addresses]) self.assertEqual(address_list.mailboxes[0].domain, 'example.com') self.assertEqual(address_list.mailboxes[0].token_type, 'mailbox') self.assertEqual(address_list.addresses[0].token_type, 'address') self.assertEqual(address_list.addresses[1].token_type, 'address') self.assertEqual(len(address_list.addresses[0].mailboxes), 1) self.assertEqual(len(address_list.addresses[1].mailboxes), 0) self.assertEqual(len(address_list.addresses[1].mailboxes), 0) self.assertEqual( address_list.addresses[1].all_mailboxes[0].local_part, 'Foo x') self.assertEqual( address_list.addresses[2].all_mailboxes[0].display_name, "Nobody Is. Special") def test_get_address_list_group_empty(self): address_list = self._test_get_x(parser.get_address_list, 'Monty Python: ;', 'Monty Python: ;', 'Monty Python: ;', [], '') self.assertEqual(address_list.token_type, 'address-list') self.assertEqual(len(address_list.mailboxes), 0) self.assertEqual(address_list.mailboxes, address_list.all_mailboxes) self.assertEqual(len(address_list.addresses), 1) self.assertEqual(address_list.addresses[0].token_type, 'address') self.assertEqual(address_list.addresses[0].display_name, 'Monty Python') self.assertEqual(len(address_list.addresses[0].mailboxes), 0) def test_get_address_list_group_simple(self): address_list = self._test_get_x(parser.get_address_list, 'Monty Python: [email protected];', 'Monty Python: [email protected];', 'Monty Python: [email protected];', [], '') self.assertEqual(address_list.token_type, 'address-list') self.assertEqual(len(address_list.mailboxes), 1) self.assertEqual(address_list.mailboxes, address_list.all_mailboxes) self.assertEqual(address_list.mailboxes[0].domain, 'example.com') self.assertEqual(address_list.addresses[0].display_name, 'Monty Python') self.assertEqual(address_list.addresses[0].mailboxes[0].domain, 'example.com') def test_get_address_list_group_and_mailboxes(self): address_list = self._test_get_x(parser.get_address_list, ('Monty Python: [email protected], "Fred" <[email protected]>;, ' 'Abe <[email protected]>, Bee <[email protected]>'), ('Monty Python: [email protected], "Fred" <[email protected]>;, ' 'Abe <[email protected]>, Bee <[email protected]>'), ('Monty Python: [email protected], "Fred" <[email protected]>;, ' 'Abe <[email protected]>, Bee <[email protected]>'), [], '') self.assertEqual(address_list.token_type, 'address-list') self.assertEqual(len(address_list.mailboxes), 4) self.assertEqual(address_list.mailboxes, address_list.all_mailboxes) self.assertEqual(len(address_list.addresses), 3) self.assertEqual(address_list.mailboxes[0].local_part, 'dinsdale') self.assertEqual(address_list.addresses[0].display_name, 'Monty Python') self.assertEqual(address_list.addresses[0].mailboxes[0].domain, 'example.com') self.assertEqual(address_list.addresses[0].mailboxes[1].local_part, 'flint') self.assertEqual(address_list.addresses[1].mailboxes[0].local_part, 'x') self.assertEqual(address_list.addresses[2].mailboxes[0].local_part, 'y') self.assertEqual(str(address_list.addresses[1]), str(address_list.mailboxes[2])) def test_invalid_content_disposition(self): content_disp = self._test_parse_x( parser.parse_content_disposition_header, ";attachment", "; attachment", ";attachment", [errors.InvalidHeaderDefect]*2 ) def test_invalid_content_transfer_encoding(self): cte = self._test_parse_x( parser.parse_content_transfer_encoding_header, ";foo", ";foo", ";foo", [errors.InvalidHeaderDefect]*3 ) @parameterize class Test_parse_mime_parameters(TestParserMixin, TestEmailBase): def mime_parameters_as_value(self, value, tl_str, tl_value, params, defects): mime_parameters = self._test_parse_x(parser.parse_mime_parameters, value, tl_str, tl_value, defects) self.assertEqual(mime_parameters.token_type, 'mime-parameters') self.assertEqual(list(mime_parameters.params), params) mime_parameters_params = { 'simple': ( 'filename="abc.py"', ' filename="abc.py"', 'filename=abc.py', [('filename', 'abc.py')], []), 'multiple_keys': ( 'filename="abc.py"; xyz=abc', ' filename="abc.py"; xyz="abc"', 'filename=abc.py; xyz=abc', [('filename', 'abc.py'), ('xyz', 'abc')], []), 'split_value': ( "filename*0*=iso-8859-1''%32%30%31%2E; filename*1*=%74%69%66", ' filename="201.tif"', "filename*0*=iso-8859-1''%32%30%31%2E; filename*1*=%74%69%66", [('filename', '201.tif')], []), # Note that it is undefined what we should do for error recovery when # there are duplicate parameter names or duplicate parts in a split # part. We choose to ignore all duplicate parameters after the first # and to take duplicate or missing rfc 2231 parts in appearance order. # This is backward compatible with get_param's behavior, but the # decisions are arbitrary. 'duplicate_key': ( 'filename=abc.gif; filename=def.tiff', ' filename="abc.gif"', "filename=abc.gif; filename=def.tiff", [('filename', 'abc.gif')], [errors.InvalidHeaderDefect]), 'duplicate_key_with_split_value': ( "filename*0*=iso-8859-1''%32%30%31%2E; filename*1*=%74%69%66;" " filename=abc.gif", ' filename="201.tif"', "filename*0*=iso-8859-1''%32%30%31%2E; filename*1*=%74%69%66;" " filename=abc.gif", [('filename', '201.tif')], [errors.InvalidHeaderDefect]), 'duplicate_key_with_split_value_other_order': ( "filename=abc.gif; " " filename*0*=iso-8859-1''%32%30%31%2E; filename*1*=%74%69%66", ' filename="abc.gif"', "filename=abc.gif;" " filename*0*=iso-8859-1''%32%30%31%2E; filename*1*=%74%69%66", [('filename', 'abc.gif')], [errors.InvalidHeaderDefect]), 'duplicate_in_split_value': ( "filename*0*=iso-8859-1''%32%30%31%2E; filename*1*=%74%69%66;" " filename*1*=abc.gif", ' filename="201.tifabc.gif"', "filename*0*=iso-8859-1''%32%30%31%2E; filename*1*=%74%69%66;" " filename*1*=abc.gif", [('filename', '201.tifabc.gif')], [errors.InvalidHeaderDefect]), 'missing_split_value': ( "filename*0*=iso-8859-1''%32%30%31%2E; filename*3*=%74%69%66;", ' filename="201.tif"', "filename*0*=iso-8859-1''%32%30%31%2E; filename*3*=%74%69%66;", [('filename', '201.tif')], [errors.InvalidHeaderDefect]), 'duplicate_and_missing_split_value': ( "filename*0*=iso-8859-1''%32%30%31%2E; filename*3*=%74%69%66;" " filename*3*=abc.gif", ' filename="201.tifabc.gif"', "filename*0*=iso-8859-1''%32%30%31%2E; filename*3*=%74%69%66;" " filename*3*=abc.gif", [('filename', '201.tifabc.gif')], [errors.InvalidHeaderDefect]*2), # Here we depart from get_param and assume the *0* was missing. 'duplicate_with_broken_split_value': ( "filename=abc.gif; " " filename*2*=iso-8859-1''%32%30%31%2E; filename*3*=%74%69%66", ' filename="abc.gif201.tif"', "filename=abc.gif;" " filename*2*=iso-8859-1''%32%30%31%2E; filename*3*=%74%69%66", [('filename', 'abc.gif201.tif')], # Defects are apparent missing *0*, and two 'out of sequence'. [errors.InvalidHeaderDefect]*3), # bpo-37461: Check that we don't go into an infinite loop. 'extra_dquote': ( 'r*="\'a\'\\"', ' r="\\""', 'r*=\'a\'"', [('r', '"')], [errors.InvalidHeaderDefect]*2), } @parameterize class Test_parse_mime_version(TestParserMixin, TestEmailBase): def mime_version_as_value(self, value, tl_str, tl_value, major, minor, defects): mime_version = self._test_parse_x(parser.parse_mime_version, value, tl_str, tl_value, defects) self.assertEqual(mime_version.major, major) self.assertEqual(mime_version.minor, minor) mime_version_params = { 'rfc_2045_1': ( '1.0', '1.0', '1.0', 1, 0, []), 'RFC_2045_2': ( '1.0 (produced by MetaSend Vx.x)', '1.0 (produced by MetaSend Vx.x)', '1.0 ', 1, 0, []), 'RFC_2045_3': ( '(produced by MetaSend Vx.x) 1.0', '(produced by MetaSend Vx.x) 1.0', ' 1.0', 1, 0, []), 'RFC_2045_4': ( '1.(produced by MetaSend Vx.x)0', '1.(produced by MetaSend Vx.x)0', '1. 0', 1, 0, []), 'empty': ( '', '', '', None, None, [errors.HeaderMissingRequiredValue]), } class TestFolding(TestEmailBase): policy = policy.default def _test(self, tl, folded, policy=policy): self.assertEqual(tl.fold(policy=policy), folded, tl.ppstr()) def test_simple_unstructured_no_folds(self): self._test(parser.get_unstructured("This is a test"), "This is a test\n") def test_simple_unstructured_folded(self): self._test(parser.get_unstructured("This is also a test, but this " "time there are enough words (and even some " "symbols) to make it wrap; at least in theory."), "This is also a test, but this time there are enough " "words (and even some\n" " symbols) to make it wrap; at least in theory.\n") def test_unstructured_with_unicode_no_folds(self): self._test(parser.get_unstructured("hübsch kleiner beißt"), "=?utf-8?q?h=C3=BCbsch_kleiner_bei=C3=9Ft?=\n") def test_one_ew_on_each_of_two_wrapped_lines(self): self._test(parser.get_unstructured("Mein kleiner Kaktus ist sehr " "hübsch. Es hat viele Stacheln " "und oft beißt mich."), "Mein kleiner Kaktus ist sehr =?utf-8?q?h=C3=BCbsch=2E?= " "Es hat viele Stacheln\n" " und oft =?utf-8?q?bei=C3=9Ft?= mich.\n") def test_ews_combined_before_wrap(self): self._test(parser.get_unstructured("Mein Kaktus ist hübsch. " "Es beißt mich. " "And that's all I'm sayin."), "Mein Kaktus ist =?utf-8?q?h=C3=BCbsch=2E__Es_bei=C3=9Ft?= " "mich. And that's\n" " all I'm sayin.\n") # XXX Need test of an encoded word so long that it needs to be wrapped def test_simple_address(self): self._test(parser.get_address_list("abc <[email protected]>")[0], "abc <[email protected]>\n") def test_address_list_folding_at_commas(self): self._test(parser.get_address_list('abc <[email protected]>, ' '"Fred Blunt" <[email protected]>, ' '"J.P.Cool" <[email protected]>, ' '"K<>y" <[email protected]>, ' 'Firesale <[email protected]>, ' '<[email protected]>')[0], 'abc <[email protected]>, "Fred Blunt" <[email protected]>,\n' ' "J.P.Cool" <[email protected]>, "K<>y" <[email protected]>,\n' ' Firesale <[email protected]>, <[email protected]>\n') def test_address_list_with_unicode_names(self): self._test(parser.get_address_list( 'Hübsch Kaktus <[email protected]>, ' 'beißt beißt <[email protected]>')[0], '=?utf-8?q?H=C3=BCbsch?= Kaktus <[email protected]>,\n' ' =?utf-8?q?bei=C3=9Ft_bei=C3=9Ft?= <[email protected]>\n') def test_address_list_with_unicode_names_in_quotes(self): self._test(parser.get_address_list( '"Hübsch Kaktus" <[email protected]>, ' '"beißt" beißt <[email protected]>')[0], '=?utf-8?q?H=C3=BCbsch?= Kaktus <[email protected]>,\n' ' =?utf-8?q?bei=C3=9Ft_bei=C3=9Ft?= <[email protected]>\n') # XXX Need tests with comments on various sides of a unicode token, # and with unicode tokens in the comments. Spaces inside the quotes # currently don't do the right thing. def test_split_at_whitespace_after_header_before_long_token(self): body = parser.get_unstructured(' ' + 'x'*77) header = parser.Header([ parser.HeaderLabel([parser.ValueTerminal('test:', 'atext')]), parser.CFWSList([parser.WhiteSpaceTerminal(' ', 'fws')]), body]) self._test(header, 'test: \n ' + 'x'*77 + '\n') def test_split_at_whitespace_before_long_token(self): self._test(parser.get_unstructured('xxx ' + 'y'*77), 'xxx \n ' + 'y'*77 + '\n') def test_overlong_encodeable_is_wrapped(self): first_token_with_whitespace = 'xxx ' chrome_leader = '=?utf-8?q?' len_chrome = len(chrome_leader) + 2 len_non_y = len_chrome + len(first_token_with_whitespace) self._test(parser.get_unstructured(first_token_with_whitespace + 'y'*80), first_token_with_whitespace + chrome_leader + 'y'*(78-len_non_y) + '?=\n' + ' ' + chrome_leader + 'y'*(80-(78-len_non_y)) + '?=\n') def test_long_filename_attachment(self): self._test(parser.parse_content_disposition_header( 'attachment; filename="TEST_TEST_TEST_TEST' '_TEST_TEST_TEST_TEST_TEST_TEST_TEST_TEST_TES.txt"'), "attachment;\n" " filename*0*=us-ascii''TEST_TEST_TEST_TEST_TEST_TEST" "_TEST_TEST_TEST_TEST_TEST;\n" " filename*1*=_TEST_TES.txt\n", ) if __name__ == '__main__': unittest.main()
119,121
2,792
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_email/test_utils.py
import datetime from email import utils import test.support import time import unittest import sys import os.path class DateTimeTests(unittest.TestCase): datestring = 'Sun, 23 Sep 2001 20:10:55' dateargs = (2001, 9, 23, 20, 10, 55) offsetstring = ' -0700' utcoffset = datetime.timedelta(hours=-7) tz = datetime.timezone(utcoffset) naive_dt = datetime.datetime(*dateargs) aware_dt = datetime.datetime(*dateargs, tzinfo=tz) def test_naive_datetime(self): self.assertEqual(utils.format_datetime(self.naive_dt), self.datestring + ' -0000') def test_aware_datetime(self): self.assertEqual(utils.format_datetime(self.aware_dt), self.datestring + self.offsetstring) def test_usegmt(self): utc_dt = datetime.datetime(*self.dateargs, tzinfo=datetime.timezone.utc) self.assertEqual(utils.format_datetime(utc_dt, usegmt=True), self.datestring + ' GMT') def test_usegmt_with_naive_datetime_raises(self): with self.assertRaises(ValueError): utils.format_datetime(self.naive_dt, usegmt=True) def test_usegmt_with_non_utc_datetime_raises(self): with self.assertRaises(ValueError): utils.format_datetime(self.aware_dt, usegmt=True) def test_parsedate_to_datetime(self): self.assertEqual( utils.parsedate_to_datetime(self.datestring + self.offsetstring), self.aware_dt) def test_parsedate_to_datetime_naive(self): self.assertEqual( utils.parsedate_to_datetime(self.datestring + ' -0000'), self.naive_dt) class LocaltimeTests(unittest.TestCase): def test_localtime_is_tz_aware_daylight_true(self): test.support.patch(self, time, 'daylight', True) t = utils.localtime() self.assertIsNotNone(t.tzinfo) def test_localtime_is_tz_aware_daylight_false(self): test.support.patch(self, time, 'daylight', False) t = utils.localtime() self.assertIsNotNone(t.tzinfo) def test_localtime_daylight_true_dst_false(self): test.support.patch(self, time, 'daylight', True) t0 = datetime.datetime(2012, 3, 12, 1, 1) t1 = utils.localtime(t0, isdst=-1) t2 = utils.localtime(t1) self.assertEqual(t1, t2) def test_localtime_daylight_false_dst_false(self): test.support.patch(self, time, 'daylight', False) t0 = datetime.datetime(2012, 3, 12, 1, 1) t1 = utils.localtime(t0, isdst=-1) t2 = utils.localtime(t1) self.assertEqual(t1, t2) @test.support.run_with_tz('EST+05EDT,M3.2.0,M11.1.0') def test_localtime_epoch_utc_daylight_true(self): test.support.patch(self, time, 'daylight', True) t0 = datetime.datetime(1990, 1, 1, tzinfo = datetime.timezone.utc) t1 = utils.localtime(t0) t2 = t0 - datetime.timedelta(hours=5) t2 = t2.replace(tzinfo = datetime.timezone(datetime.timedelta(hours=-5))) self.assertEqual(t1, t2) @test.support.run_with_tz('EST+05EDT,M3.2.0,M11.1.0') def test_localtime_epoch_utc_daylight_false(self): test.support.patch(self, time, 'daylight', False) t0 = datetime.datetime(1990, 1, 1, tzinfo = datetime.timezone.utc) t1 = utils.localtime(t0) t2 = t0 - datetime.timedelta(hours=5) t2 = t2.replace(tzinfo = datetime.timezone(datetime.timedelta(hours=-5))) self.assertEqual(t1, t2) def test_localtime_epoch_notz_daylight_true(self): test.support.patch(self, time, 'daylight', True) t0 = datetime.datetime(1990, 1, 1) t1 = utils.localtime(t0) t2 = utils.localtime(t0.replace(tzinfo=None)) self.assertEqual(t1, t2) def test_localtime_epoch_notz_daylight_false(self): test.support.patch(self, time, 'daylight', False) t0 = datetime.datetime(1990, 1, 1) t1 = utils.localtime(t0) t2 = utils.localtime(t0.replace(tzinfo=None)) self.assertEqual(t1, t2) # XXX: Need a more robust test for Olson's tzdata @unittest.skipIf(sys.platform.startswith(('win','cosmo')), "Windows does not use Olson's TZ database") @unittest.skipUnless(os.path.exists('/zip/usr/share/zoneinfo') or os.path.exists('/zip/usr/lib/zoneinfo'), "Can't find the Olson's TZ database") @test.support.run_with_tz('Europe/Kiev') def test_variable_tzname(self): t0 = datetime.datetime(1984, 1, 1, tzinfo=datetime.timezone.utc) t1 = utils.localtime(t0) self.assertEqual(t1.tzname(), 'MSK') t0 = datetime.datetime(1994, 1, 1, tzinfo=datetime.timezone.utc) t1 = utils.localtime(t0) self.assertEqual(t1.tzname(), 'EET') if __name__ == '__main__': unittest.main()
4,900
127
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_email/test_defect_handling.py
import textwrap import unittest import contextlib from email import policy from email import errors from test.test_email import TestEmailBase class TestDefectsBase: policy = policy.default raise_expected = False @contextlib.contextmanager def _raise_point(self, defect): yield def test_same_boundary_inner_outer(self): source = textwrap.dedent("""\ Subject: XX From: [email protected] To: XX Mime-version: 1.0 Content-type: multipart/mixed; boundary="MS_Mac_OE_3071477847_720252_MIME_Part" --MS_Mac_OE_3071477847_720252_MIME_Part Content-type: multipart/alternative; boundary="MS_Mac_OE_3071477847_720252_MIME_Part" --MS_Mac_OE_3071477847_720252_MIME_Part Content-type: text/plain; charset="ISO-8859-1" Content-transfer-encoding: quoted-printable text --MS_Mac_OE_3071477847_720252_MIME_Part Content-type: text/html; charset="ISO-8859-1" Content-transfer-encoding: quoted-printable <HTML></HTML> --MS_Mac_OE_3071477847_720252_MIME_Part-- --MS_Mac_OE_3071477847_720252_MIME_Part Content-type: image/gif; name="xx.gif"; Content-disposition: attachment Content-transfer-encoding: base64 Some removed base64 encoded chars. --MS_Mac_OE_3071477847_720252_MIME_Part-- """) # XXX better would be to actually detect the duplicate. with self._raise_point(errors.StartBoundaryNotFoundDefect): msg = self._str_msg(source) if self.raise_expected: return inner = msg.get_payload(0) self.assertTrue(hasattr(inner, 'defects')) self.assertEqual(len(self.get_defects(inner)), 1) self.assertIsInstance(self.get_defects(inner)[0], errors.StartBoundaryNotFoundDefect) def test_multipart_no_boundary(self): source = textwrap.dedent("""\ Date: Fri, 6 Apr 2001 09:23:06 -0800 (GMT-0800) From: foobar Subject: broken mail MIME-Version: 1.0 Content-Type: multipart/report; report-type=delivery-status; --JAB03225.986577786/zinfandel.lacita.com One part --JAB03225.986577786/zinfandel.lacita.com Content-Type: message/delivery-status Header: Another part --JAB03225.986577786/zinfandel.lacita.com-- """) with self._raise_point(errors.NoBoundaryInMultipartDefect): msg = self._str_msg(source) if self.raise_expected: return self.assertIsInstance(msg.get_payload(), str) self.assertEqual(len(self.get_defects(msg)), 2) self.assertIsInstance(self.get_defects(msg)[0], errors.NoBoundaryInMultipartDefect) self.assertIsInstance(self.get_defects(msg)[1], errors.MultipartInvariantViolationDefect) multipart_msg = textwrap.dedent("""\ Date: Wed, 14 Nov 2007 12:56:23 GMT From: [email protected] To: [email protected] Subject: Content-Transfer-Encoding: base64 and multipart MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="===============3344438784458119861=="{} --===============3344438784458119861== Content-Type: text/plain Test message --===============3344438784458119861== Content-Type: application/octet-stream Content-Transfer-Encoding: base64 YWJj --===============3344438784458119861==-- """) def test_multipart_invalid_cte(self): with self._raise_point( errors.InvalidMultipartContentTransferEncodingDefect): msg = self._str_msg( self.multipart_msg.format( "\nContent-Transfer-Encoding: base64")) if self.raise_expected: return self.assertEqual(len(self.get_defects(msg)), 1) self.assertIsInstance(self.get_defects(msg)[0], errors.InvalidMultipartContentTransferEncodingDefect) def test_multipart_no_cte_no_defect(self): if self.raise_expected: return msg = self._str_msg(self.multipart_msg.format('')) self.assertEqual(len(self.get_defects(msg)), 0) def test_multipart_valid_cte_no_defect(self): if self.raise_expected: return for cte in ('7bit', '8bit', 'BINary'): msg = self._str_msg( self.multipart_msg.format("\nContent-Transfer-Encoding: "+cte)) self.assertEqual(len(self.get_defects(msg)), 0, "cte="+cte) def test_lying_multipart(self): source = textwrap.dedent("""\ From: "Allison Dunlap" <[email protected]> To: [email protected] Subject: 64423 Date: Sun, 11 Jul 2004 16:09:27 -0300 MIME-Version: 1.0 Content-Type: multipart/alternative; Blah blah blah """) with self._raise_point(errors.NoBoundaryInMultipartDefect): msg = self._str_msg(source) if self.raise_expected: return self.assertTrue(hasattr(msg, 'defects')) self.assertEqual(len(self.get_defects(msg)), 2) self.assertIsInstance(self.get_defects(msg)[0], errors.NoBoundaryInMultipartDefect) self.assertIsInstance(self.get_defects(msg)[1], errors.MultipartInvariantViolationDefect) def test_missing_start_boundary(self): source = textwrap.dedent("""\ Content-Type: multipart/mixed; boundary="AAA" From: Mail Delivery Subsystem <[email protected]> To: [email protected] --AAA Stuff --AAA Content-Type: message/rfc822 From: [email protected] To: [email protected] Content-Type: multipart/mixed; boundary="BBB" --BBB-- --AAA-- """) # The message structure is: # # multipart/mixed # text/plain # message/rfc822 # multipart/mixed [*] # # [*] This message is missing its start boundary with self._raise_point(errors.StartBoundaryNotFoundDefect): outer = self._str_msg(source) if self.raise_expected: return bad = outer.get_payload(1).get_payload(0) self.assertEqual(len(self.get_defects(bad)), 1) self.assertIsInstance(self.get_defects(bad)[0], errors.StartBoundaryNotFoundDefect) def test_first_line_is_continuation_header(self): with self._raise_point(errors.FirstHeaderLineIsContinuationDefect): msg = self._str_msg(' Line 1\nSubject: test\n\nbody') if self.raise_expected: return self.assertEqual(msg.keys(), ['Subject']) self.assertEqual(msg.get_payload(), 'body') self.assertEqual(len(self.get_defects(msg)), 1) self.assertDefectsEqual(self.get_defects(msg), [errors.FirstHeaderLineIsContinuationDefect]) self.assertEqual(self.get_defects(msg)[0].line, ' Line 1\n') def test_missing_header_body_separator(self): # Our heuristic if we see a line that doesn't look like a header (no # leading whitespace but no ':') is to assume that the blank line that # separates the header from the body is missing, and to stop parsing # headers and start parsing the body. with self._raise_point(errors.MissingHeaderBodySeparatorDefect): msg = self._str_msg('Subject: test\nnot a header\nTo: abc\n\nb\n') if self.raise_expected: return self.assertEqual(msg.keys(), ['Subject']) self.assertEqual(msg.get_payload(), 'not a header\nTo: abc\n\nb\n') self.assertDefectsEqual(self.get_defects(msg), [errors.MissingHeaderBodySeparatorDefect]) def test_bad_padding_in_base64_payload(self): source = textwrap.dedent("""\ Subject: test MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: base64 dmk """) msg = self._str_msg(source) with self._raise_point(errors.InvalidBase64PaddingDefect): payload = msg.get_payload(decode=True) if self.raise_expected: return self.assertEqual(payload, b'vi') self.assertDefectsEqual(self.get_defects(msg), [errors.InvalidBase64PaddingDefect]) def test_invalid_chars_in_base64_payload(self): source = textwrap.dedent("""\ Subject: test MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: base64 dm\x01k=== """) msg = self._str_msg(source) with self._raise_point(errors.InvalidBase64CharactersDefect): payload = msg.get_payload(decode=True) if self.raise_expected: return self.assertEqual(payload, b'vi') self.assertDefectsEqual(self.get_defects(msg), [errors.InvalidBase64CharactersDefect]) def test_invalid_length_of_base64_payload(self): source = textwrap.dedent("""\ Subject: test MIME-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: base64 abcde """) msg = self._str_msg(source) with self._raise_point(errors.InvalidBase64LengthDefect): payload = msg.get_payload(decode=True) if self.raise_expected: return self.assertEqual(payload, b'abcde') self.assertDefectsEqual(self.get_defects(msg), [errors.InvalidBase64LengthDefect]) def test_missing_ending_boundary(self): source = textwrap.dedent("""\ To: [email protected] Subject: Fwd: 1 MIME-Version: 1.0 Content-Type: multipart/alternative; boundary="------------000101020201080900040301" --------------000101020201080900040301 Content-Type: text/plain; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Alternative 1 --------------000101020201080900040301 Content-Type: text/html; charset=ISO-8859-1 Content-Transfer-Encoding: 7bit Alternative 2 """) with self._raise_point(errors.CloseBoundaryNotFoundDefect): msg = self._str_msg(source) if self.raise_expected: return self.assertEqual(len(msg.get_payload()), 2) self.assertEqual(msg.get_payload(1).get_payload(), 'Alternative 2\n') self.assertDefectsEqual(self.get_defects(msg), [errors.CloseBoundaryNotFoundDefect]) class TestDefectDetection(TestDefectsBase, TestEmailBase): def get_defects(self, obj): return obj.defects class TestDefectCapture(TestDefectsBase, TestEmailBase): class CapturePolicy(policy.EmailPolicy): captured = None def register_defect(self, obj, defect): self.captured.append(defect) def setUp(self): self.policy = self.CapturePolicy(captured=list()) def get_defects(self, obj): return self.policy.captured class TestDefectRaising(TestDefectsBase, TestEmailBase): policy = TestDefectsBase.policy policy = policy.clone(raise_on_defect=True) raise_expected = True @contextlib.contextmanager def _raise_point(self, defect): with self.assertRaises(defect): yield if __name__ == '__main__': unittest.main()
11,968
338
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_email/test_contentmanager.py
import unittest from test.test_email import TestEmailBase, parameterize import textwrap from email import policy from email.message import EmailMessage from email.contentmanager import ContentManager, raw_data_manager from encodings import ( base64_codec, quopri_codec, ) @parameterize class TestContentManager(TestEmailBase): policy = policy.default message = EmailMessage get_key_params = { 'full_type': (1, 'text/plain',), 'maintype_only': (2, 'text',), 'null_key': (3, '',), } def get_key_as_get_content_key(self, order, key): def foo_getter(msg, foo=None): bar = msg['X-Bar-Header'] return foo, bar cm = ContentManager() cm.add_get_handler(key, foo_getter) m = self._make_message() m['Content-Type'] = 'text/plain' m['X-Bar-Header'] = 'foo' self.assertEqual(cm.get_content(m, foo='bar'), ('bar', 'foo')) def get_key_as_get_content_key_order(self, order, key): def bar_getter(msg): return msg['X-Bar-Header'] def foo_getter(msg): return msg['X-Foo-Header'] cm = ContentManager() cm.add_get_handler(key, foo_getter) for precedence, key in self.get_key_params.values(): if precedence > order: cm.add_get_handler(key, bar_getter) m = self._make_message() m['Content-Type'] = 'text/plain' m['X-Bar-Header'] = 'bar' m['X-Foo-Header'] = 'foo' self.assertEqual(cm.get_content(m), ('foo')) def test_get_content_raises_if_unknown_mimetype_and_no_default(self): cm = ContentManager() m = self._make_message() m['Content-Type'] = 'text/plain' with self.assertRaisesRegex(KeyError, 'text/plain'): cm.get_content(m) class BaseThing(str): pass baseobject_full_path = __name__ + '.' + 'TestContentManager.BaseThing' class Thing(BaseThing): pass testobject_full_path = __name__ + '.' + 'TestContentManager.Thing' set_key_params = { 'type': (0, Thing,), 'full_path': (1, testobject_full_path,), 'qualname': (2, 'TestContentManager.Thing',), 'name': (3, 'Thing',), 'base_type': (4, BaseThing,), 'base_full_path': (5, baseobject_full_path,), 'base_qualname': (6, 'TestContentManager.BaseThing',), 'base_name': (7, 'BaseThing',), 'str_type': (8, str,), 'str_full_path': (9, 'builtins.str',), 'str_name': (10, 'str',), # str name and qualname are the same 'null_key': (11, None,), } def set_key_as_set_content_key(self, order, key): def foo_setter(msg, obj, foo=None): msg['X-Foo-Header'] = foo msg.set_payload(obj) cm = ContentManager() cm.add_set_handler(key, foo_setter) m = self._make_message() msg_obj = self.Thing() cm.set_content(m, msg_obj, foo='bar') self.assertEqual(m['X-Foo-Header'], 'bar') self.assertEqual(m.get_payload(), msg_obj) def set_key_as_set_content_key_order(self, order, key): def foo_setter(msg, obj): msg['X-FooBar-Header'] = 'foo' msg.set_payload(obj) def bar_setter(msg, obj): msg['X-FooBar-Header'] = 'bar' cm = ContentManager() cm.add_set_handler(key, foo_setter) for precedence, key in self.get_key_params.values(): if precedence > order: cm.add_set_handler(key, bar_setter) m = self._make_message() msg_obj = self.Thing() cm.set_content(m, msg_obj) self.assertEqual(m['X-FooBar-Header'], 'foo') self.assertEqual(m.get_payload(), msg_obj) def test_set_content_raises_if_unknown_type_and_no_default(self): cm = ContentManager() m = self._make_message() msg_obj = self.Thing() with self.assertRaisesRegex(KeyError, self.testobject_full_path): cm.set_content(m, msg_obj) def test_set_content_raises_if_called_on_multipart(self): cm = ContentManager() m = self._make_message() m['Content-Type'] = 'multipart/foo' with self.assertRaises(TypeError): cm.set_content(m, 'test') def test_set_content_calls_clear_content(self): m = self._make_message() m['Content-Foo'] = 'bar' m['Content-Type'] = 'text/html' m['To'] = 'test' m.set_payload('abc') cm = ContentManager() cm.add_set_handler(str, lambda *args, **kw: None) m.set_content('xyz', content_manager=cm) self.assertIsNone(m['Content-Foo']) self.assertIsNone(m['Content-Type']) self.assertEqual(m['To'], 'test') self.assertIsNone(m.get_payload()) @parameterize class TestRawDataManager(TestEmailBase): # Note: these tests are dependent on the order in which headers are added # to the message objects by the code. There's no defined ordering in # RFC5322/MIME, so this makes the tests more fragile than the standards # require. However, if the header order changes it is best to understand # *why*, and make sure it isn't a subtle bug in whatever change was # applied. policy = policy.default.clone(max_line_length=60, content_manager=raw_data_manager) message = EmailMessage def test_get_text_plain(self): m = self._str_msg(textwrap.dedent("""\ Content-Type: text/plain Basic text. """)) self.assertEqual(raw_data_manager.get_content(m), "Basic text.\n") def test_get_text_html(self): m = self._str_msg(textwrap.dedent("""\ Content-Type: text/html <p>Basic text.</p> """)) self.assertEqual(raw_data_manager.get_content(m), "<p>Basic text.</p>\n") def test_get_text_plain_latin1(self): m = self._bytes_msg(textwrap.dedent("""\ Content-Type: text/plain; charset=latin1 Basìc tëxt. """).encode('latin1')) self.assertEqual(raw_data_manager.get_content(m), "Basìc tëxt.\n") def test_get_text_plain_latin1_quoted_printable(self): m = self._str_msg(textwrap.dedent("""\ Content-Type: text/plain; charset="latin-1" Content-Transfer-Encoding: quoted-printable Bas=ECc t=EBxt. """)) self.assertEqual(raw_data_manager.get_content(m), "Basìc tëxt.\n") def test_get_text_plain_utf8_base64(self): m = self._str_msg(textwrap.dedent("""\ Content-Type: text/plain; charset="utf8" Content-Transfer-Encoding: base64 QmFzw6xjIHTDq3h0Lgo= """)) self.assertEqual(raw_data_manager.get_content(m), "Basìc tëxt.\n") def test_get_text_plain_bad_utf8_quoted_printable(self): m = self._str_msg(textwrap.dedent("""\ Content-Type: text/plain; charset="utf8" Content-Transfer-Encoding: quoted-printable Bas=c3=acc t=c3=abxt=fd. """)) self.assertEqual(raw_data_manager.get_content(m), "Basìc tëxt�.\n") def test_get_text_plain_bad_utf8_quoted_printable_ignore_errors(self): m = self._str_msg(textwrap.dedent("""\ Content-Type: text/plain; charset="utf8" Content-Transfer-Encoding: quoted-printable Bas=c3=acc t=c3=abxt=fd. """)) self.assertEqual(raw_data_manager.get_content(m, errors='ignore'), "Basìc tëxt.\n") def test_get_text_plain_utf8_base64_recoverable_bad_CTE_data(self): m = self._str_msg(textwrap.dedent("""\ Content-Type: text/plain; charset="utf8" Content-Transfer-Encoding: base64 QmFzw6xjIHTDq3h0Lgo\xFF= """)) self.assertEqual(raw_data_manager.get_content(m, errors='ignore'), "Basìc tëxt.\n") def test_get_text_invalid_keyword(self): m = self._str_msg(textwrap.dedent("""\ Content-Type: text/plain Basic text. """)) with self.assertRaises(TypeError): raw_data_manager.get_content(m, foo='ignore') def test_get_non_text(self): template = textwrap.dedent("""\ Content-Type: {} Content-Transfer-Encoding: base64 Ym9ndXMgZGF0YQ== """) for maintype in 'audio image video application'.split(): with self.subTest(maintype=maintype): m = self._str_msg(template.format(maintype+'/foo')) self.assertEqual(raw_data_manager.get_content(m), b"bogus data") def test_get_non_text_invalid_keyword(self): m = self._str_msg(textwrap.dedent("""\ Content-Type: image/jpg Content-Transfer-Encoding: base64 Ym9ndXMgZGF0YQ== """)) with self.assertRaises(TypeError): raw_data_manager.get_content(m, errors='ignore') def test_get_raises_on_multipart(self): m = self._str_msg(textwrap.dedent("""\ Content-Type: multipart/mixed; boundary="===" --=== --===-- """)) with self.assertRaises(KeyError): raw_data_manager.get_content(m) def test_get_message_rfc822_and_external_body(self): template = textwrap.dedent("""\ Content-Type: message/{} To: [email protected] From: [email protected] Subject: example an example message """) for subtype in 'rfc822 external-body'.split(): with self.subTest(subtype=subtype): m = self._str_msg(template.format(subtype)) sub_msg = raw_data_manager.get_content(m) self.assertIsInstance(sub_msg, self.message) self.assertEqual(raw_data_manager.get_content(sub_msg), "an example message\n") self.assertEqual(sub_msg['to'], '[email protected]') self.assertEqual(sub_msg['from'].addresses[0].username, 'bar') def test_get_message_non_rfc822_or_external_body_yields_bytes(self): m = self._str_msg(textwrap.dedent("""\ Content-Type: message/partial To: [email protected] From: [email protected] Subject: example The real body is in another message. """)) self.assertEqual(raw_data_manager.get_content(m)[:10], b'To: foo@ex') def test_set_text_plain(self): m = self._make_message() content = "Simple message.\n" raw_data_manager.set_content(m, content) self.assertEqual(str(m), textwrap.dedent("""\ Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: 7bit Simple message. """)) self.assertEqual(m.get_payload(decode=True).decode('utf-8'), content) self.assertEqual(m.get_content(), content) def test_set_text_html(self): m = self._make_message() content = "<p>Simple message.</p>\n" raw_data_manager.set_content(m, content, subtype='html') self.assertEqual(str(m), textwrap.dedent("""\ Content-Type: text/html; charset="utf-8" Content-Transfer-Encoding: 7bit <p>Simple message.</p> """)) self.assertEqual(m.get_payload(decode=True).decode('utf-8'), content) self.assertEqual(m.get_content(), content) def test_set_text_charset_latin_1(self): m = self._make_message() content = "Simple message.\n" raw_data_manager.set_content(m, content, charset='latin-1') self.assertEqual(str(m), textwrap.dedent("""\ Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit Simple message. """)) self.assertEqual(m.get_payload(decode=True).decode('utf-8'), content) self.assertEqual(m.get_content(), content) def test_set_text_short_line_minimal_non_ascii_heuristics(self): m = self._make_message() content = "et là il est monté sur moi et il commence à m'éto.\n" raw_data_manager.set_content(m, content) self.assertEqual(bytes(m), textwrap.dedent("""\ Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: 8bit et là il est monté sur moi et il commence à m'éto. """).encode('utf-8')) self.assertEqual(m.get_payload(decode=True).decode('utf-8'), content) self.assertEqual(m.get_content(), content) def test_set_text_long_line_minimal_non_ascii_heuristics(self): m = self._make_message() content = ("j'ai un problème de python. il est sorti de son" " vivarium. et là il est monté sur moi et il commence" " à m'éto.\n") raw_data_manager.set_content(m, content) self.assertEqual(bytes(m), textwrap.dedent("""\ Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable j'ai un probl=C3=A8me de python. il est sorti de son vivari= um. et l=C3=A0 il est mont=C3=A9 sur moi et il commence = =C3=A0 m'=C3=A9to. """).encode('utf-8')) self.assertEqual(m.get_payload(decode=True).decode('utf-8'), content) self.assertEqual(m.get_content(), content) def test_set_text_11_lines_long_line_minimal_non_ascii_heuristics(self): m = self._make_message() content = '\n'*10 + ( "j'ai un problème de python. il est sorti de son" " vivarium. et là il est monté sur moi et il commence" " à m'éto.\n") raw_data_manager.set_content(m, content) self.assertEqual(bytes(m), textwrap.dedent("""\ Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable """ + '\n'*10 + """ j'ai un probl=C3=A8me de python. il est sorti de son vivari= um. et l=C3=A0 il est mont=C3=A9 sur moi et il commence = =C3=A0 m'=C3=A9to. """).encode('utf-8')) self.assertEqual(m.get_payload(decode=True).decode('utf-8'), content) self.assertEqual(m.get_content(), content) def test_set_text_maximal_non_ascii_heuristics(self): m = self._make_message() content = "áàäéèęöő.\n" raw_data_manager.set_content(m, content) self.assertEqual(bytes(m), textwrap.dedent("""\ Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: 8bit áàäéèęöő. """).encode('utf-8')) self.assertEqual(m.get_payload(decode=True).decode('utf-8'), content) self.assertEqual(m.get_content(), content) def test_set_text_11_lines_maximal_non_ascii_heuristics(self): m = self._make_message() content = '\n'*10 + "áàäéèęöő.\n" raw_data_manager.set_content(m, content) self.assertEqual(bytes(m), textwrap.dedent("""\ Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: 8bit """ + '\n'*10 + """ áàäéèęöő. """).encode('utf-8')) self.assertEqual(m.get_payload(decode=True).decode('utf-8'), content) self.assertEqual(m.get_content(), content) def test_set_text_long_line_maximal_non_ascii_heuristics(self): m = self._make_message() content = ("áàäéèęöőáàäéèęöőáàäéèęöőáàäéèęöő" "áàäéèęöőáàäéèęöőáàäéèęöőáàäéèęöő" "áàäéèęöőáàäéèęöőáàäéèęöőáàäéèęöő.\n") raw_data_manager.set_content(m, content) self.assertEqual(bytes(m), textwrap.dedent("""\ Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: base64 w6HDoMOkw6nDqMSZw7bFkcOhw6DDpMOpw6jEmcO2xZHDocOgw6TDqcOoxJnD tsWRw6HDoMOkw6nDqMSZw7bFkcOhw6DDpMOpw6jEmcO2xZHDocOgw6TDqcOo xJnDtsWRw6HDoMOkw6nDqMSZw7bFkcOhw6DDpMOpw6jEmcO2xZHDocOgw6TD qcOoxJnDtsWRw6HDoMOkw6nDqMSZw7bFkcOhw6DDpMOpw6jEmcO2xZHDocOg w6TDqcOoxJnDtsWRLgo= """).encode('utf-8')) self.assertEqual(m.get_payload(decode=True).decode('utf-8'), content) self.assertEqual(m.get_content(), content) def test_set_text_11_lines_long_line_maximal_non_ascii_heuristics(self): # Yes, it chooses "wrong" here. It's a heuristic. So this result # could change if we come up with a better heuristic. m = self._make_message() content = ('\n'*10 + "áàäéèęöőáàäéèęöőáàäéèęöőáàäéèęöő" "áàäéèęöőáàäéèęöőáàäéèęöőáàäéèęöő" "áàäéèęöőáàäéèęöőáàäéèęöőáàäéèęöő.\n") raw_data_manager.set_content(m, "\n"*10 + "áàäéèęöőáàäéèęöőáàäéèęöőáàäéèęöő" "áàäéèęöőáàäéèęöőáàäéèęöőáàäéèęöő" "áàäéèęöőáàäéèęöőáàäéèęöőáàäéèęöő.\n") self.assertEqual(bytes(m), textwrap.dedent("""\ Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable """ + '\n'*10 + """ =C3=A1=C3=A0=C3=A4=C3=A9=C3=A8=C4=99=C3=B6=C5=91=C3=A1=C3= =A0=C3=A4=C3=A9=C3=A8=C4=99=C3=B6=C5=91=C3=A1=C3=A0=C3=A4= =C3=A9=C3=A8=C4=99=C3=B6=C5=91=C3=A1=C3=A0=C3=A4=C3=A9=C3= =A8=C4=99=C3=B6=C5=91=C3=A1=C3=A0=C3=A4=C3=A9=C3=A8=C4=99= =C3=B6=C5=91=C3=A1=C3=A0=C3=A4=C3=A9=C3=A8=C4=99=C3=B6=C5= =91=C3=A1=C3=A0=C3=A4=C3=A9=C3=A8=C4=99=C3=B6=C5=91=C3=A1= =C3=A0=C3=A4=C3=A9=C3=A8=C4=99=C3=B6=C5=91=C3=A1=C3=A0=C3= =A4=C3=A9=C3=A8=C4=99=C3=B6=C5=91=C3=A1=C3=A0=C3=A4=C3=A9= =C3=A8=C4=99=C3=B6=C5=91=C3=A1=C3=A0=C3=A4=C3=A9=C3=A8=C4= =99=C3=B6=C5=91=C3=A1=C3=A0=C3=A4=C3=A9=C3=A8=C4=99=C3=B6= =C5=91. """).encode('utf-8')) self.assertEqual(m.get_payload(decode=True).decode('utf-8'), content) self.assertEqual(m.get_content(), content) def test_set_text_non_ascii_with_cte_7bit_raises(self): m = self._make_message() with self.assertRaises(UnicodeError): raw_data_manager.set_content(m,"áàäéèęöő.\n", cte='7bit') def test_set_text_non_ascii_with_charset_ascii_raises(self): m = self._make_message() with self.assertRaises(UnicodeError): raw_data_manager.set_content(m,"áàäéèęöő.\n", charset='ascii') def test_set_text_non_ascii_with_cte_7bit_and_charset_ascii_raises(self): m = self._make_message() with self.assertRaises(UnicodeError): raw_data_manager.set_content(m,"áàäéèęöő.\n", cte='7bit', charset='ascii') def test_set_message(self): m = self._make_message() m['Subject'] = "Forwarded message" content = self._make_message() content['To'] = '[email protected]' content['From'] = '[email protected]' content['Subject'] = "get back in your box" content.set_content("Or face the comfy chair.") raw_data_manager.set_content(m, content) self.assertEqual(str(m), textwrap.dedent("""\ Subject: Forwarded message Content-Type: message/rfc822 Content-Transfer-Encoding: 8bit To: [email protected] From: [email protected] Subject: get back in your box Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: 7bit MIME-Version: 1.0 Or face the comfy chair. """)) payload = m.get_payload(0) self.assertIsInstance(payload, self.message) self.assertEqual(str(payload), str(content)) self.assertIsInstance(m.get_content(), self.message) self.assertEqual(str(m.get_content()), str(content)) def test_set_message_with_non_ascii_and_coercion_to_7bit(self): m = self._make_message() m['Subject'] = "Escape report" content = self._make_message() content['To'] = '[email protected]' content['From'] = '[email protected]' content['Subject'] = "Help" content.set_content("j'ai un problème de python. il est sorti de son" " vivarium.") raw_data_manager.set_content(m, content) self.assertEqual(bytes(m), textwrap.dedent("""\ Subject: Escape report Content-Type: message/rfc822 Content-Transfer-Encoding: 8bit To: [email protected] From: [email protected] Subject: Help Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: 8bit MIME-Version: 1.0 j'ai un problème de python. il est sorti de son vivarium. """).encode('utf-8')) # The choice of base64 for the body encoding is because generator # doesn't bother with heuristics and uses it unconditionally for utf-8 # text. # XXX: the first cte should be 7bit, too...that's a generator bug. # XXX: the line length in the body also looks like a generator bug. self.assertEqual(m.as_string(maxheaderlen=self.policy.max_line_length), textwrap.dedent("""\ Subject: Escape report Content-Type: message/rfc822 Content-Transfer-Encoding: 8bit To: [email protected] From: [email protected] Subject: Help Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: base64 MIME-Version: 1.0 aidhaSB1biBwcm9ibMOobWUgZGUgcHl0aG9uLiBpbCBlc3Qgc29ydGkgZGUgc29uIHZpdmFyaXVt Lgo= """)) self.assertIsInstance(m.get_content(), self.message) self.assertEqual(str(m.get_content()), str(content)) def test_set_message_invalid_cte_raises(self): m = self._make_message() content = self._make_message() for cte in 'quoted-printable base64'.split(): for subtype in 'rfc822 external-body'.split(): with self.subTest(cte=cte, subtype=subtype): with self.assertRaises(ValueError) as ar: m.set_content(content, subtype, cte=cte) exc = str(ar.exception) self.assertIn(cte, exc) self.assertIn(subtype, exc) subtype = 'external-body' for cte in '8bit binary'.split(): with self.subTest(cte=cte, subtype=subtype): with self.assertRaises(ValueError) as ar: m.set_content(content, subtype, cte=cte) exc = str(ar.exception) self.assertIn(cte, exc) self.assertIn(subtype, exc) def test_set_image_jpg(self): for content in (b"bogus content", bytearray(b"bogus content"), memoryview(b"bogus content")): with self.subTest(content=content): m = self._make_message() raw_data_manager.set_content(m, content, 'image', 'jpeg') self.assertEqual(str(m), textwrap.dedent("""\ Content-Type: image/jpeg Content-Transfer-Encoding: base64 Ym9ndXMgY29udGVudA== """)) self.assertEqual(m.get_payload(decode=True), content) self.assertEqual(m.get_content(), content) def test_set_audio_aif_with_quoted_printable_cte(self): # Why you would use qp, I don't know, but it is technically supported. # XXX: the incorrect line length is because binascii.b2a_qp doesn't # support a line length parameter, but we must use it to get newline # encoding. # XXX: what about that lack of tailing newline? Do we actually handle # that correctly in all cases? That is, if the *source* has an # unencoded newline, do we add an extra newline to the returned payload # or not? And can that actually be disambiguated based on the RFC? m = self._make_message() content = b'b\xFFgus\tcon\nt\rent ' + b'z'*100 m.set_content(content, 'audio', 'aif', cte='quoted-printable') self.assertEqual(bytes(m), textwrap.dedent("""\ Content-Type: audio/aif Content-Transfer-Encoding: quoted-printable MIME-Version: 1.0 b=FFgus=09con=0At=0Dent=20zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz= zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz""").encode('latin-1')) self.assertEqual(m.get_payload(decode=True), content) self.assertEqual(m.get_content(), content) def test_set_video_mpeg_with_binary_cte(self): m = self._make_message() content = b'b\xFFgus\tcon\nt\rent ' + b'z'*100 m.set_content(content, 'video', 'mpeg', cte='binary') self.assertEqual(bytes(m), textwrap.dedent("""\ Content-Type: video/mpeg Content-Transfer-Encoding: binary MIME-Version: 1.0 """).encode('ascii') + # XXX: the second \n ought to be a \r, but generator gets it wrong. # THIS MEANS WE DON'T ACTUALLY SUPPORT THE 'binary' CTE. b'b\xFFgus\tcon\nt\nent zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz' + b'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz') self.assertEqual(m.get_payload(decode=True), content) self.assertEqual(m.get_content(), content) def test_set_application_octet_stream_with_8bit_cte(self): # In 8bit mode, universal line end logic applies. It is up to the # application to make sure the lines are short enough; we don't check. m = self._make_message() content = b'b\xFFgus\tcon\nt\rent\n' + b'z'*60 + b'\n' m.set_content(content, 'application', 'octet-stream', cte='8bit') self.assertEqual(bytes(m), textwrap.dedent("""\ Content-Type: application/octet-stream Content-Transfer-Encoding: 8bit MIME-Version: 1.0 """).encode('ascii') + b'b\xFFgus\tcon\nt\nent\n' + b'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz\n') self.assertEqual(m.get_payload(decode=True), content) self.assertEqual(m.get_content(), content) def test_set_headers_from_header_objects(self): m = self._make_message() content = "Simple message.\n" header_factory = self.policy.header_factory raw_data_manager.set_content(m, content, headers=( header_factory("To", "[email protected]"), header_factory("From", "[email protected]"), header_factory("Subject", "I'm talking to myself."))) self.assertEqual(str(m), textwrap.dedent("""\ Content-Type: text/plain; charset="utf-8" To: [email protected] From: [email protected] Subject: I'm talking to myself. Content-Transfer-Encoding: 7bit Simple message. """)) def test_set_headers_from_strings(self): m = self._make_message() content = "Simple message.\n" raw_data_manager.set_content(m, content, headers=( "X-Foo-Header: foo", "X-Bar-Header: bar",)) self.assertEqual(str(m), textwrap.dedent("""\ Content-Type: text/plain; charset="utf-8" X-Foo-Header: foo X-Bar-Header: bar Content-Transfer-Encoding: 7bit Simple message. """)) def test_set_headers_with_invalid_duplicate_string_header_raises(self): m = self._make_message() content = "Simple message.\n" with self.assertRaisesRegex(ValueError, 'Content-Type'): raw_data_manager.set_content(m, content, headers=( "Content-Type: foo/bar",) ) def test_set_headers_with_invalid_duplicate_header_header_raises(self): m = self._make_message() content = "Simple message.\n" header_factory = self.policy.header_factory with self.assertRaisesRegex(ValueError, 'Content-Type'): raw_data_manager.set_content(m, content, headers=( header_factory("Content-Type", " foo/bar"),) ) def test_set_headers_with_defective_string_header_raises(self): m = self._make_message() content = "Simple message.\n" with self.assertRaisesRegex(ValueError, 'a@fairly@@invalid@address'): raw_data_manager.set_content(m, content, headers=( 'To: a@fairly@@invalid@address',) ) print(m['To'].defects) def test_set_headers_with_defective_header_header_raises(self): m = self._make_message() content = "Simple message.\n" header_factory = self.policy.header_factory with self.assertRaisesRegex(ValueError, 'a@fairly@@invalid@address'): raw_data_manager.set_content(m, content, headers=( header_factory('To', 'a@fairly@@invalid@address'),) ) print(m['To'].defects) def test_set_disposition_inline(self): m = self._make_message() m.set_content('foo', disposition='inline') self.assertEqual(m['Content-Disposition'], 'inline') def test_set_disposition_attachment(self): m = self._make_message() m.set_content('foo', disposition='attachment') self.assertEqual(m['Content-Disposition'], 'attachment') def test_set_disposition_foo(self): m = self._make_message() m.set_content('foo', disposition='foo') self.assertEqual(m['Content-Disposition'], 'foo') # XXX: we should have a 'strict' policy mode (beyond raise_on_defect) that # would cause 'foo' above to raise. def test_set_filename(self): m = self._make_message() m.set_content('foo', filename='bar.txt') self.assertEqual(m['Content-Disposition'], 'attachment; filename="bar.txt"') def test_set_filename_and_disposition_inline(self): m = self._make_message() m.set_content('foo', disposition='inline', filename='bar.txt') self.assertEqual(m['Content-Disposition'], 'inline; filename="bar.txt"') def test_set_non_ascii_filename(self): m = self._make_message() m.set_content('foo', filename='ábárî.txt') self.assertEqual(bytes(m), textwrap.dedent("""\ Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: 7bit Content-Disposition: attachment; filename*=utf-8''%C3%A1b%C3%A1r%C3%AE.txt MIME-Version: 1.0 foo """).encode('ascii')) content_object_params = { 'text_plain': ('content', ()), 'text_html': ('content', ('html',)), 'application_octet_stream': (b'content', ('application', 'octet_stream')), 'image_jpeg': (b'content', ('image', 'jpeg')), 'message_rfc822': (message(), ()), 'message_external_body': (message(), ('external-body',)), } def content_object_as_header_receiver(self, obj, mimetype): m = self._make_message() m.set_content(obj, *mimetype, headers=( 'To: [email protected]', 'From: [email protected]')) self.assertEqual(m['to'], '[email protected]') self.assertEqual(m['from'], '[email protected]') def content_object_as_disposition_inline_receiver(self, obj, mimetype): m = self._make_message() m.set_content(obj, *mimetype, disposition='inline') self.assertEqual(m['Content-Disposition'], 'inline') def content_object_as_non_ascii_filename_receiver(self, obj, mimetype): m = self._make_message() m.set_content(obj, *mimetype, disposition='inline', filename='bár.txt') self.assertEqual(m['Content-Disposition'], 'inline; filename="bár.txt"') self.assertEqual(m.get_filename(), "bár.txt") self.assertEqual(m['Content-Disposition'].params['filename'], "bár.txt") def content_object_as_cid_receiver(self, obj, mimetype): m = self._make_message() m.set_content(obj, *mimetype, cid='some_random_stuff') self.assertEqual(m['Content-ID'], 'some_random_stuff') def content_object_as_params_receiver(self, obj, mimetype): m = self._make_message() params = {'foo': 'bár', 'abc': 'xyz'} m.set_content(obj, *mimetype, params=params) if isinstance(obj, str): params['charset'] = 'utf-8' self.assertEqual(m['Content-Type'].params, params) if __name__ == '__main__': unittest.main()
33,602
802
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_email/__main__.py
from test.test_email import load_tests import unittest unittest.main()
72
5
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_email/test_parser.py
import io import email import unittest from email.message import Message, EmailMessage from email.policy import default from test.test_email import TestEmailBase class TestCustomMessage(TestEmailBase): class MyMessage(Message): def __init__(self, policy): self.check_policy = policy super().__init__() MyPolicy = TestEmailBase.policy.clone(linesep='boo') def test_custom_message_gets_policy_if_possible_from_string(self): msg = email.message_from_string("Subject: bogus\n\nmsg\n", self.MyMessage, policy=self.MyPolicy) self.assertIsInstance(msg, self.MyMessage) self.assertIs(msg.check_policy, self.MyPolicy) def test_custom_message_gets_policy_if_possible_from_file(self): source_file = io.StringIO("Subject: bogus\n\nmsg\n") msg = email.message_from_file(source_file, self.MyMessage, policy=self.MyPolicy) self.assertIsInstance(msg, self.MyMessage) self.assertIs(msg.check_policy, self.MyPolicy) # XXX add tests for other functions that take Message arg. class TestParserBase: def test_only_split_on_cr_lf(self): # The unicode line splitter splits on unicode linebreaks, which are # more numerous than allowed by the email RFCs; make sure we are only # splitting on those two. for parser in self.parsers: with self.subTest(parser=parser.__name__): msg = parser( "Next-Line: not\x85broken\r\n" "Null: not\x00broken\r\n" "Vertical-Tab: not\vbroken\r\n" "Form-Feed: not\fbroken\r\n" "File-Separator: not\x1Cbroken\r\n" "Group-Separator: not\x1Dbroken\r\n" "Record-Separator: not\x1Ebroken\r\n" "Line-Separator: not\u2028broken\r\n" "Paragraph-Separator: not\u2029broken\r\n" "\r\n", policy=default, ) self.assertEqual(msg.items(), [ ("Next-Line", "not\x85broken"), ("Null", "not\x00broken"), ("Vertical-Tab", "not\vbroken"), ("Form-Feed", "not\fbroken"), ("File-Separator", "not\x1Cbroken"), ("Group-Separator", "not\x1Dbroken"), ("Record-Separator", "not\x1Ebroken"), ("Line-Separator", "not\u2028broken"), ("Paragraph-Separator", "not\u2029broken"), ]) self.assertEqual(msg.get_payload(), "") class MyMessage(EmailMessage): pass def test_custom_message_factory_on_policy(self): for parser in self.parsers: with self.subTest(parser=parser.__name__): MyPolicy = default.clone(message_factory=self.MyMessage) msg = parser("To: foo\n\ntest", policy=MyPolicy) self.assertIsInstance(msg, self.MyMessage) def test_factory_arg_overrides_policy(self): for parser in self.parsers: with self.subTest(parser=parser.__name__): MyPolicy = default.clone(message_factory=self.MyMessage) msg = parser("To: foo\n\ntest", Message, policy=MyPolicy) self.assertNotIsInstance(msg, self.MyMessage) self.assertIsInstance(msg, Message) # Play some games to get nice output in subTest. This code could be clearer # if staticmethod supported __name__. def message_from_file(s, *args, **kw): f = io.StringIO(s) return email.message_from_file(f, *args, **kw) class TestParser(TestParserBase, TestEmailBase): parsers = (email.message_from_string, message_from_file) def message_from_bytes(s, *args, **kw): return email.message_from_bytes(s.encode(), *args, **kw) def message_from_binary_file(s, *args, **kw): f = io.BytesIO(s.encode()) return email.message_from_binary_file(f, *args, **kw) class TestBytesParser(TestParserBase, TestEmailBase): parsers = (message_from_bytes, message_from_binary_file) if __name__ == '__main__': unittest.main()
4,333
111
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_email/test_asian_codecs.py
# Copyright (C) 2002-2006 Python Software Foundation # Contact: [email protected] # email package unit tests for (optional) Asian codecs import unittest from test.test_email import TestEmailBase from email.charset import Charset from email.header import Header, decode_header from email.message import Message # We're compatible with Python 2.3, but it doesn't have the built-in Asian # codecs, so we have to skip all these tests. try: str(b'foo', 'euc-jp') except LookupError: raise unittest.SkipTest class TestEmailAsianCodecs(TestEmailBase): def test_japanese_codecs(self): eq = self.ndiffAssertEqual jcode = "euc-jp" gcode = "iso-8859-1" j = Charset(jcode) g = Charset(gcode) h = Header("Hello World!") jhello = str(b'\xa5\xcf\xa5\xed\xa1\xbc\xa5\xef\xa1\xbc' b'\xa5\xeb\xa5\xc9\xa1\xaa', jcode) ghello = str(b'Gr\xfc\xdf Gott!', gcode) h.append(jhello, j) h.append(ghello, g) # BAW: This used to -- and maybe should -- fold the two iso-8859-1 # chunks into a single encoded word. However it doesn't violate the # standard to have them as two encoded chunks and maybe it's # reasonable <wink> for each .append() call to result in a separate # encoded word. eq(h.encode(), """\ Hello World! =?iso-2022-jp?b?GyRCJU8lbSE8JW8hPCVrJUkhKhsoQg==?= =?iso-8859-1?q?Gr=FC=DF_Gott!?=""") eq(decode_header(h.encode()), [(b'Hello World! ', None), (b'\x1b$B%O%m!<%o!<%k%I!*\x1b(B', 'iso-2022-jp'), (b'Gr\xfc\xdf Gott!', gcode)]) subject_bytes = (b'test-ja \xa4\xd8\xc5\xea\xb9\xc6\xa4\xb5' b'\xa4\xec\xa4\xbf\xa5\xe1\xa1\xbc\xa5\xeb\xa4\xcf\xbb\xca\xb2' b'\xf1\xbc\xd4\xa4\xce\xbe\xb5\xc7\xa7\xa4\xf2\xc2\xd4\xa4\xc3' b'\xa4\xc6\xa4\xa4\xa4\xde\xa4\xb9') subject = str(subject_bytes, jcode) h = Header(subject, j, header_name="Subject") # test a very long header enc = h.encode() # TK: splitting point may differ by codec design and/or Header encoding eq(enc , """\ =?iso-2022-jp?b?dGVzdC1qYSAbJEIkWEVqOUYkNSRsJD8lYSE8JWskTztKGyhC?= =?iso-2022-jp?b?GyRCMnE8VCROPjVHJyRyQlQkQyRGJCQkXiQ5GyhC?=""") # TK: full decode comparison eq(str(h).encode(jcode), subject_bytes) def test_payload_encoding_utf8(self): jhello = str(b'\xa5\xcf\xa5\xed\xa1\xbc\xa5\xef\xa1\xbc' b'\xa5\xeb\xa5\xc9\xa1\xaa', 'euc-jp') msg = Message() msg.set_payload(jhello, 'utf-8') ustr = msg.get_payload(decode=True).decode(msg.get_content_charset()) self.assertEqual(jhello, ustr) def test_payload_encoding(self): jcode = 'euc-jp' jhello = str(b'\xa5\xcf\xa5\xed\xa1\xbc\xa5\xef\xa1\xbc' b'\xa5\xeb\xa5\xc9\xa1\xaa', jcode) msg = Message() msg.set_payload(jhello, jcode) ustr = msg.get_payload(decode=True).decode(msg.get_content_charset()) self.assertEqual(jhello, ustr) if __name__ == '__main__': unittest.main()
3,145
82
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_email/torture_test.py
# Copyright (C) 2002-2004 Python Software Foundation # # A torture test of the email package. This should not be run as part of the # standard Python test suite since it requires several meg of email messages # collected in the wild. These source messages are not checked into the # Python distro, but are available as part of the standalone email package at # http://sf.net/projects/mimelib import sys import os import unittest from io import StringIO from test.test_email import TestEmailBase from test.support import run_unittest import email from email import __file__ as testfile from email.iterators import _structure def openfile(filename): from os.path import join, dirname, abspath path = abspath(join(dirname(testfile), os.pardir, 'moredata', filename)) return open(path, 'r') # Prevent this test from running in the Python distro try: openfile('crispin-torture.txt') except OSError: raise unittest.SkipTest class TortureBase(TestEmailBase): def _msgobj(self, filename): fp = openfile(filename) try: msg = email.message_from_file(fp) finally: fp.close() return msg class TestCrispinTorture(TortureBase): # Mark Crispin's torture test from the SquirrelMail project def test_mondo_message(self): eq = self.assertEqual neq = self.ndiffAssertEqual msg = self._msgobj('crispin-torture.txt') payload = msg.get_payload() eq(type(payload), list) eq(len(payload), 12) eq(msg.preamble, None) eq(msg.epilogue, '\n') # Probably the best way to verify the message is parsed correctly is to # dump its structure and compare it against the known structure. fp = StringIO() _structure(msg, fp=fp) neq(fp.getvalue(), """\ multipart/mixed text/plain message/rfc822 multipart/alternative text/plain multipart/mixed text/richtext application/andrew-inset message/rfc822 audio/basic audio/basic image/pbm message/rfc822 multipart/mixed multipart/mixed text/plain audio/x-sun multipart/mixed image/gif image/gif application/x-be2 application/atomicmail audio/x-sun message/rfc822 multipart/mixed text/plain image/pgm text/plain message/rfc822 multipart/mixed text/plain image/pbm message/rfc822 application/postscript image/gif message/rfc822 multipart/mixed audio/basic audio/basic message/rfc822 multipart/mixed application/postscript text/plain message/rfc822 multipart/mixed text/plain multipart/parallel image/gif audio/basic application/atomicmail message/rfc822 audio/x-sun """) def _testclasses(): mod = sys.modules[__name__] return [getattr(mod, name) for name in dir(mod) if name.startswith('Test')] def suite(): suite = unittest.TestSuite() for testclass in _testclasses(): suite.addTest(unittest.makeSuite(testclass)) return suite def test_main(): for testclass in _testclasses(): run_unittest(testclass) if __name__ == '__main__': unittest.main(defaultTest='suite')
3,607
134
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_email/test_headerregistry.py
import datetime import textwrap import unittest from email import errors from email import policy from email.message import Message from test.test_email import TestEmailBase, parameterize from email import headerregistry from email.headerregistry import Address, Group DITTO = object() class TestHeaderRegistry(TestEmailBase): def test_arbitrary_name_unstructured(self): factory = headerregistry.HeaderRegistry() h = factory('foobar', 'test') self.assertIsInstance(h, headerregistry.BaseHeader) self.assertIsInstance(h, headerregistry.UnstructuredHeader) def test_name_case_ignored(self): factory = headerregistry.HeaderRegistry() # Whitebox check that test is valid self.assertNotIn('Subject', factory.registry) h = factory('Subject', 'test') self.assertIsInstance(h, headerregistry.BaseHeader) self.assertIsInstance(h, headerregistry.UniqueUnstructuredHeader) class FooBase: def __init__(self, *args, **kw): pass def test_override_default_base_class(self): factory = headerregistry.HeaderRegistry(base_class=self.FooBase) h = factory('foobar', 'test') self.assertIsInstance(h, self.FooBase) self.assertIsInstance(h, headerregistry.UnstructuredHeader) class FooDefault: parse = headerregistry.UnstructuredHeader.parse def test_override_default_class(self): factory = headerregistry.HeaderRegistry(default_class=self.FooDefault) h = factory('foobar', 'test') self.assertIsInstance(h, headerregistry.BaseHeader) self.assertIsInstance(h, self.FooDefault) def test_override_default_class_only_overrides_default(self): factory = headerregistry.HeaderRegistry(default_class=self.FooDefault) h = factory('subject', 'test') self.assertIsInstance(h, headerregistry.BaseHeader) self.assertIsInstance(h, headerregistry.UniqueUnstructuredHeader) def test_dont_use_default_map(self): factory = headerregistry.HeaderRegistry(use_default_map=False) h = factory('subject', 'test') self.assertIsInstance(h, headerregistry.BaseHeader) self.assertIsInstance(h, headerregistry.UnstructuredHeader) def test_map_to_type(self): factory = headerregistry.HeaderRegistry() h1 = factory('foobar', 'test') factory.map_to_type('foobar', headerregistry.UniqueUnstructuredHeader) h2 = factory('foobar', 'test') self.assertIsInstance(h1, headerregistry.BaseHeader) self.assertIsInstance(h1, headerregistry.UnstructuredHeader) self.assertIsInstance(h2, headerregistry.BaseHeader) self.assertIsInstance(h2, headerregistry.UniqueUnstructuredHeader) class TestHeaderBase(TestEmailBase): factory = headerregistry.HeaderRegistry() def make_header(self, name, value): return self.factory(name, value) class TestBaseHeaderFeatures(TestHeaderBase): def test_str(self): h = self.make_header('subject', 'this is a test') self.assertIsInstance(h, str) self.assertEqual(h, 'this is a test') self.assertEqual(str(h), 'this is a test') def test_substr(self): h = self.make_header('subject', 'this is a test') self.assertEqual(h[5:7], 'is') def test_has_name(self): h = self.make_header('subject', 'this is a test') self.assertEqual(h.name, 'subject') def _test_attr_ro(self, attr): h = self.make_header('subject', 'this is a test') with self.assertRaises(AttributeError): setattr(h, attr, 'foo') def test_name_read_only(self): self._test_attr_ro('name') def test_defects_read_only(self): self._test_attr_ro('defects') def test_defects_is_tuple(self): h = self.make_header('subject', 'this is a test') self.assertEqual(len(h.defects), 0) self.assertIsInstance(h.defects, tuple) # Make sure it is still true when there are defects. h = self.make_header('date', '') self.assertEqual(len(h.defects), 1) self.assertIsInstance(h.defects, tuple) # XXX: FIXME #def test_CR_in_value(self): # # XXX: this also re-raises the issue of embedded headers, # # need test and solution for that. # value = '\r'.join(['this is', ' a test']) # h = self.make_header('subject', value) # self.assertEqual(h, value) # self.assertDefectsEqual(h.defects, [errors.ObsoleteHeaderDefect]) @parameterize class TestUnstructuredHeader(TestHeaderBase): def string_as_value(self, source, decoded, *args): l = len(args) defects = args[0] if l>0 else [] header = 'Subject:' + (' ' if source else '') folded = header + (args[1] if l>1 else source) + '\n' h = self.make_header('Subject', source) self.assertEqual(h, decoded) self.assertDefectsEqual(h.defects, defects) self.assertEqual(h.fold(policy=policy.default), folded) string_params = { 'rfc2047_simple_quopri': ( '=?utf-8?q?this_is_a_test?=', 'this is a test', [], 'this is a test'), 'rfc2047_gb2312_base64': ( '=?gb2312?b?1eLKx9bQzsSy4srUo6E=?=', '\u8fd9\u662f\u4e2d\u6587\u6d4b\u8bd5\uff01', [], '=?utf-8?b?6L+Z5piv5Lit5paH5rWL6K+V77yB?='), 'rfc2047_simple_nonascii_quopri': ( '=?utf-8?q?=C3=89ric?=', 'Éric'), 'rfc2047_quopri_with_regular_text': ( 'The =?utf-8?q?=C3=89ric=2C?= Himself', 'The Éric, Himself'), } @parameterize class TestDateHeader(TestHeaderBase): datestring = 'Sun, 23 Sep 2001 20:10:55 -0700' utcoffset = datetime.timedelta(hours=-7) tz = datetime.timezone(utcoffset) dt = datetime.datetime(2001, 9, 23, 20, 10, 55, tzinfo=tz) def test_parse_date(self): h = self.make_header('date', self.datestring) self.assertEqual(h, self.datestring) self.assertEqual(h.datetime, self.dt) self.assertEqual(h.datetime.utcoffset(), self.utcoffset) self.assertEqual(h.defects, ()) def test_set_from_datetime(self): h = self.make_header('date', self.dt) self.assertEqual(h, self.datestring) self.assertEqual(h.datetime, self.dt) self.assertEqual(h.defects, ()) def test_date_header_properties(self): h = self.make_header('date', self.datestring) self.assertIsInstance(h, headerregistry.UniqueDateHeader) self.assertEqual(h.max_count, 1) self.assertEqual(h.defects, ()) def test_resent_date_header_properties(self): h = self.make_header('resent-date', self.datestring) self.assertIsInstance(h, headerregistry.DateHeader) self.assertEqual(h.max_count, None) self.assertEqual(h.defects, ()) def test_no_value_is_defect(self): h = self.make_header('date', '') self.assertEqual(len(h.defects), 1) self.assertIsInstance(h.defects[0], errors.HeaderMissingRequiredValue) def test_datetime_read_only(self): h = self.make_header('date', self.datestring) with self.assertRaises(AttributeError): h.datetime = 'foo' def test_set_date_header_from_datetime(self): m = Message(policy=policy.default) m['Date'] = self.dt self.assertEqual(m['Date'], self.datestring) self.assertEqual(m['Date'].datetime, self.dt) @parameterize class TestContentTypeHeader(TestHeaderBase): def content_type_as_value(self, source, content_type, maintype, subtype, *args): l = len(args) parmdict = args[0] if l>0 else {} defects = args[1] if l>1 else [] decoded = args[2] if l>2 and args[2] is not DITTO else source header = 'Content-Type:' + ' ' if source else '' folded = args[3] if l>3 else header + decoded + '\n' h = self.make_header('Content-Type', source) self.assertEqual(h.content_type, content_type) self.assertEqual(h.maintype, maintype) self.assertEqual(h.subtype, subtype) self.assertEqual(h.params, parmdict) with self.assertRaises(TypeError): h.params['abc'] = 'xyz' # make sure params is read-only. self.assertDefectsEqual(h.defects, defects) self.assertEqual(h, decoded) self.assertEqual(h.fold(policy=policy.default), folded) content_type_params = { # Examples from RFC 2045. 'RFC_2045_1': ( 'text/plain; charset=us-ascii (Plain text)', 'text/plain', 'text', 'plain', {'charset': 'us-ascii'}, [], 'text/plain; charset="us-ascii"'), 'RFC_2045_2': ( 'text/plain; charset=us-ascii', 'text/plain', 'text', 'plain', {'charset': 'us-ascii'}, [], 'text/plain; charset="us-ascii"'), 'RFC_2045_3': ( 'text/plain; charset="us-ascii"', 'text/plain', 'text', 'plain', {'charset': 'us-ascii'}), # RFC 2045 5.2 says syntactically invalid values are to be treated as # text/plain. 'no_subtype_in_content_type': ( 'text/', 'text/plain', 'text', 'plain', {}, [errors.InvalidHeaderDefect]), 'no_slash_in_content_type': ( 'foo', 'text/plain', 'text', 'plain', {}, [errors.InvalidHeaderDefect]), 'junk_text_in_content_type': ( '<crazy "stuff">', 'text/plain', 'text', 'plain', {}, [errors.InvalidHeaderDefect]), 'too_many_slashes_in_content_type': ( 'image/jpeg/foo', 'text/plain', 'text', 'plain', {}, [errors.InvalidHeaderDefect]), # But unknown names are OK. We could make non-IANA names a defect, but # by not doing so we make ourselves future proof. The fact that they # are unknown will be detectable by the fact that they don't appear in # the mime_registry...and the application is free to extend that list # to handle them even if the core library doesn't. 'unknown_content_type': ( 'bad/names', 'bad/names', 'bad', 'names'), # The content type is case insensitive, and CFWS is ignored. 'mixed_case_content_type': ( 'ImAge/JPeg', 'image/jpeg', 'image', 'jpeg'), 'spaces_in_content_type': ( ' text / plain ', 'text/plain', 'text', 'plain'), 'cfws_in_content_type': ( '(foo) text (bar)/(baz)plain(stuff)', 'text/plain', 'text', 'plain'), # test some parameters (more tests could be added for parameters # associated with other content types, but since parameter parsing is # generic they would be redundant for the current implementation). 'charset_param': ( 'text/plain; charset="utf-8"', 'text/plain', 'text', 'plain', {'charset': 'utf-8'}), 'capitalized_charset': ( 'text/plain; charset="US-ASCII"', 'text/plain', 'text', 'plain', {'charset': 'US-ASCII'}), 'unknown_charset': ( 'text/plain; charset="fOo"', 'text/plain', 'text', 'plain', {'charset': 'fOo'}), 'capitalized_charset_param_name_and_comment': ( 'text/plain; (interjection) Charset="utf-8"', 'text/plain', 'text', 'plain', {'charset': 'utf-8'}, [], # Should the parameter name be lowercased here? 'text/plain; Charset="utf-8"'), # Since this is pretty much the ur-mimeheader, we'll put all the tests # that exercise the parameter parsing and formatting here. Note that # when we refold we may canonicalize, so things like whitespace, # quoting, and rfc2231 encoding may change from what was in the input # header. 'unquoted_param_value': ( 'text/plain; title=foo', 'text/plain', 'text', 'plain', {'title': 'foo'}, [], 'text/plain; title="foo"', ), 'param_value_with_tspecials': ( 'text/plain; title="(bar)foo blue"', 'text/plain', 'text', 'plain', {'title': '(bar)foo blue'}), 'param_with_extra_quoted_whitespace': ( 'text/plain; title=" a loong way \t home "', 'text/plain', 'text', 'plain', {'title': ' a loong way \t home '}), 'bad_params': ( 'blarg; baz; boo', 'text/plain', 'text', 'plain', {'baz': '', 'boo': ''}, [errors.InvalidHeaderDefect]*3), 'spaces_around_param_equals': ( 'Multipart/mixed; boundary = "CPIMSSMTPC06p5f3tG"', 'multipart/mixed', 'multipart', 'mixed', {'boundary': 'CPIMSSMTPC06p5f3tG'}, [], 'Multipart/mixed; boundary="CPIMSSMTPC06p5f3tG"', ), 'spaces_around_semis': ( ('image/jpeg; name="wibble.JPG" ; x-mac-type="4A504547" ; ' 'x-mac-creator="474B4F4E"'), 'image/jpeg', 'image', 'jpeg', {'name': 'wibble.JPG', 'x-mac-type': '4A504547', 'x-mac-creator': '474B4F4E'}, [], ('image/jpeg; name="wibble.JPG"; x-mac-type="4A504547"; ' 'x-mac-creator="474B4F4E"'), ('Content-Type: image/jpeg; name="wibble.JPG";' ' x-mac-type="4A504547";\n' ' x-mac-creator="474B4F4E"\n'), ), 'lots_of_mime_params': ( ('image/jpeg; name="wibble.JPG"; x-mac-type="4A504547"; ' 'x-mac-creator="474B4F4E"; x-extrastuff="make it longer"'), 'image/jpeg', 'image', 'jpeg', {'name': 'wibble.JPG', 'x-mac-type': '4A504547', 'x-mac-creator': '474B4F4E', 'x-extrastuff': 'make it longer'}, [], ('image/jpeg; name="wibble.JPG"; x-mac-type="4A504547"; ' 'x-mac-creator="474B4F4E"; x-extrastuff="make it longer"'), # In this case the whole of the MimeParameters does *not* fit # one one line, so we break at a lower syntactic level. ('Content-Type: image/jpeg; name="wibble.JPG";' ' x-mac-type="4A504547";\n' ' x-mac-creator="474B4F4E"; x-extrastuff="make it longer"\n'), ), 'semis_inside_quotes': ( 'image/jpeg; name="Jim&amp;&amp;Jill"', 'image/jpeg', 'image', 'jpeg', {'name': 'Jim&amp;&amp;Jill'}), 'single_quotes_inside_quotes': ( 'image/jpeg; name="Jim \'Bob\' Jill"', 'image/jpeg', 'image', 'jpeg', {'name': "Jim 'Bob' Jill"}), 'double_quotes_inside_quotes': ( r'image/jpeg; name="Jim \"Bob\" Jill"', 'image/jpeg', 'image', 'jpeg', {'name': 'Jim "Bob" Jill'}, [], r'image/jpeg; name="Jim \"Bob\" Jill"'), 'non_ascii_in_params': ( ('foo\xa7/bar; b\xa7r=two; ' 'baz=thr\xa7e'.encode('latin-1').decode('us-ascii', 'surrogateescape')), 'foo\uFFFD/bar', 'foo\uFFFD', 'bar', {'b\uFFFDr': 'two', 'baz': 'thr\uFFFDe'}, [errors.UndecodableBytesDefect]*3, 'foo�/bar; b�r="two"; baz="thr�e"', # XXX Two bugs here: the mime type is not allowed to be an encoded # word, and we shouldn't be emitting surrogates in the parameter # names. But I don't know what the behavior should be here, so I'm # punting for now. In practice this is unlikely to be encountered # since headers with binary in them only come from a binary source # and are almost certain to be re-emitted without refolding. 'Content-Type: =?unknown-8bit?q?foo=A7?=/bar; b\udca7r="two";\n' " baz*=unknown-8bit''thr%A7e\n", ), # RFC 2231 parameter tests. 'rfc2231_segmented_normal_values': ( 'image/jpeg; name*0="abc"; name*1=".html"', 'image/jpeg', 'image', 'jpeg', {'name': "abc.html"}, [], 'image/jpeg; name="abc.html"'), 'quotes_inside_rfc2231_value': ( r'image/jpeg; bar*0="baz\"foobar"; bar*1="\"baz"', 'image/jpeg', 'image', 'jpeg', {'bar': 'baz"foobar"baz'}, [], r'image/jpeg; bar="baz\"foobar\"baz"'), 'non_ascii_rfc2231_value': ( ('text/plain; charset=us-ascii; ' "title*=us-ascii'en'This%20is%20" 'not%20f\xa7n').encode('latin-1').decode('us-ascii', 'surrogateescape'), 'text/plain', 'text', 'plain', {'charset': 'us-ascii', 'title': 'This is not f\uFFFDn'}, [errors.UndecodableBytesDefect], 'text/plain; charset="us-ascii"; title="This is not f�n"', 'Content-Type: text/plain; charset="us-ascii";\n' " title*=unknown-8bit''This%20is%20not%20f%A7n\n", ), 'rfc2231_encoded_charset': ( 'text/plain; charset*=ansi-x3.4-1968\'\'us-ascii', 'text/plain', 'text', 'plain', {'charset': 'us-ascii'}, [], 'text/plain; charset="us-ascii"'), # This follows the RFC: no double quotes around encoded values. 'rfc2231_encoded_no_double_quotes': ( ("text/plain;" "\tname*0*=''This%20is%20;" "\tname*1*=%2A%2A%2Afun%2A%2A%2A%20;" '\tname*2="is it not.pdf"'), 'text/plain', 'text', 'plain', {'name': 'This is ***fun*** is it not.pdf'}, [], 'text/plain; name="This is ***fun*** is it not.pdf"', ), # Make sure we also handle it if there are spurious double quotes. 'rfc2231_encoded_with_double_quotes': ( ("text/plain;" '\tname*0*="us-ascii\'\'This%20is%20even%20more%20";' '\tname*1*="%2A%2A%2Afun%2A%2A%2A%20";' '\tname*2="is it not.pdf"'), 'text/plain', 'text', 'plain', {'name': 'This is even more ***fun*** is it not.pdf'}, [errors.InvalidHeaderDefect]*2, 'text/plain; name="This is even more ***fun*** is it not.pdf"', ), 'rfc2231_single_quote_inside_double_quotes': ( ('text/plain; charset=us-ascii;' '\ttitle*0*="us-ascii\'en\'This%20is%20really%20";' '\ttitle*1*="%2A%2A%2Afun%2A%2A%2A%20";' '\ttitle*2="isn\'t it!"'), 'text/plain', 'text', 'plain', {'charset': 'us-ascii', 'title': "This is really ***fun*** isn't it!"}, [errors.InvalidHeaderDefect]*2, ('text/plain; charset="us-ascii"; ' 'title="This is really ***fun*** isn\'t it!"'), ('Content-Type: text/plain; charset="us-ascii";\n' ' title="This is really ***fun*** isn\'t it!"\n'), ), 'rfc2231_single_quote_in_value_with_charset_and_lang': ( ('application/x-foo;' "\tname*0*=\"us-ascii'en-us'Frank's\"; name*1*=\" Document\""), 'application/x-foo', 'application', 'x-foo', {'name': "Frank's Document"}, [errors.InvalidHeaderDefect]*2, 'application/x-foo; name="Frank\'s Document"', ), 'rfc2231_single_quote_in_non_encoded_value': ( ('application/x-foo;' "\tname*0=\"us-ascii'en-us'Frank's\"; name*1=\" Document\""), 'application/x-foo', 'application', 'x-foo', {'name': "us-ascii'en-us'Frank's Document"}, [], 'application/x-foo; name="us-ascii\'en-us\'Frank\'s Document"', ), 'rfc2231_no_language_or_charset': ( 'text/plain; NAME*0*=english_is_the_default.html', 'text/plain', 'text', 'plain', {'name': 'english_is_the_default.html'}, [errors.InvalidHeaderDefect], 'text/plain; NAME="english_is_the_default.html"'), 'rfc2231_encoded_no_charset': ( ("text/plain;" '\tname*0*="\'\'This%20is%20even%20more%20";' '\tname*1*="%2A%2A%2Afun%2A%2A%2A%20";' '\tname*2="is it.pdf"'), 'text/plain', 'text', 'plain', {'name': 'This is even more ***fun*** is it.pdf'}, [errors.InvalidHeaderDefect]*2, 'text/plain; name="This is even more ***fun*** is it.pdf"', ), 'rfc2231_partly_encoded': ( ("text/plain;" '\tname*0*="\'\'This%20is%20even%20more%20";' '\tname*1*="%2A%2A%2Afun%2A%2A%2A%20";' '\tname*2="is it.pdf"'), 'text/plain', 'text', 'plain', {'name': 'This is even more ***fun*** is it.pdf'}, [errors.InvalidHeaderDefect]*2, 'text/plain; name="This is even more ***fun*** is it.pdf"', ), 'rfc2231_partly_encoded_2': ( ("text/plain;" '\tname*0*="\'\'This%20is%20even%20more%20";' '\tname*1="%2A%2A%2Afun%2A%2A%2A%20";' '\tname*2="is it.pdf"'), 'text/plain', 'text', 'plain', {'name': 'This is even more %2A%2A%2Afun%2A%2A%2A%20is it.pdf'}, [errors.InvalidHeaderDefect], ('text/plain;' ' name="This is even more %2A%2A%2Afun%2A%2A%2A%20is it.pdf"'), ('Content-Type: text/plain;\n' ' name="This is even more %2A%2A%2Afun%2A%2A%2A%20is' ' it.pdf"\n'), ), 'rfc2231_unknown_charset_treated_as_ascii': ( "text/plain; name*0*=bogus'xx'ascii_is_the_default", 'text/plain', 'text', 'plain', {'name': 'ascii_is_the_default'}, [], 'text/plain; name="ascii_is_the_default"'), 'rfc2231_bad_character_in_charset_parameter_value': ( "text/plain; charset*=ascii''utf-8%F1%F2%F3", 'text/plain', 'text', 'plain', {'charset': 'utf-8\uFFFD\uFFFD\uFFFD'}, [errors.UndecodableBytesDefect], 'text/plain; charset="utf-8\uFFFD\uFFFD\uFFFD"', "Content-Type: text/plain;" " charset*=unknown-8bit''utf-8%F1%F2%F3\n", ), 'rfc2231_utf8_in_supposedly_ascii_charset_parameter_value': ( "text/plain; charset*=ascii''utf-8%E2%80%9D", 'text/plain', 'text', 'plain', {'charset': 'utf-8”'}, [errors.UndecodableBytesDefect], 'text/plain; charset="utf-8”"', # XXX Should folding change the charset to utf8? Currently it just # reproduces the original, which is arguably fine. "Content-Type: text/plain;" " charset*=unknown-8bit''utf-8%E2%80%9D\n", ), 'rfc2231_encoded_then_unencoded_segments': ( ('application/x-foo;' '\tname*0*="us-ascii\'en-us\'My";' '\tname*1=" Document";' '\tname*2=" For You"'), 'application/x-foo', 'application', 'x-foo', {'name': 'My Document For You'}, [errors.InvalidHeaderDefect], 'application/x-foo; name="My Document For You"', ), # My reading of the RFC is that this is an invalid header. The RFC # says that if charset and language information is given, the first # segment *must* be encoded. 'rfc2231_unencoded_then_encoded_segments': ( ('application/x-foo;' '\tname*0=us-ascii\'en-us\'My;' '\tname*1*=" Document";' '\tname*2*=" For You"'), 'application/x-foo', 'application', 'x-foo', {'name': 'My Document For You'}, [errors.InvalidHeaderDefect]*3, 'application/x-foo; name="My Document For You"', ), # XXX: I would say this one should default to ascii/en for the # "encoded" segment, since the first segment is not encoded and is # in double quotes, making the value a valid non-encoded string. The # old parser decodes this just like the previous case, which may be the # better Postel rule, but could equally result in borking headers that # intentionally have quoted quotes in them. We could get this 98% # right if we treat it as a quoted string *unless* it matches the # charset'lang'value pattern exactly *and* there is at least one # encoded segment. Implementing that algorithm will require some # refactoring, so I haven't done it (yet). 'rfc2231_quoted_unencoded_then_encoded_segments': ( ('application/x-foo;' '\tname*0="us-ascii\'en-us\'My";' '\tname*1*=" Document";' '\tname*2*=" For You"'), 'application/x-foo', 'application', 'x-foo', {'name': "us-ascii'en-us'My Document For You"}, [errors.InvalidHeaderDefect]*2, 'application/x-foo; name="us-ascii\'en-us\'My Document For You"', ), # Make sure our folding algorithm produces multiple sections correctly. # We could mix encoded and non-encoded segments, but we don't, we just # make them all encoded. It might be worth fixing that, since the # sections can get used for wrapping ascii text. 'rfc2231_folded_segments_correctly_formatted': ( ('application/x-foo;' '\tname="' + "with spaces"*8 + '"'), 'application/x-foo', 'application', 'x-foo', {'name': "with spaces"*8}, [], 'application/x-foo; name="' + "with spaces"*8 + '"', "Content-Type: application/x-foo;\n" " name*0*=us-ascii''with%20spaceswith%20spaceswith%20spaceswith" "%20spaceswith;\n" " name*1*=%20spaceswith%20spaceswith%20spaceswith%20spaces\n" ), } @parameterize class TestContentTransferEncoding(TestHeaderBase): def cte_as_value(self, source, cte, *args): l = len(args) defects = args[0] if l>0 else [] decoded = args[1] if l>1 and args[1] is not DITTO else source header = 'Content-Transfer-Encoding:' + ' ' if source else '' folded = args[2] if l>2 else header + source + '\n' h = self.make_header('Content-Transfer-Encoding', source) self.assertEqual(h.cte, cte) self.assertDefectsEqual(h.defects, defects) self.assertEqual(h, decoded) self.assertEqual(h.fold(policy=policy.default), folded) cte_params = { 'RFC_2183_1': ( 'base64', 'base64',), 'no_value': ( '', '7bit', [errors.HeaderMissingRequiredValue], '', 'Content-Transfer-Encoding:\n', ), 'junk_after_cte': ( '7bit and a bunch more', '7bit', [errors.InvalidHeaderDefect]), } @parameterize class TestContentDisposition(TestHeaderBase): def content_disp_as_value(self, source, content_disposition, *args): l = len(args) parmdict = args[0] if l>0 else {} defects = args[1] if l>1 else [] decoded = args[2] if l>2 and args[2] is not DITTO else source header = 'Content-Disposition:' + ' ' if source else '' folded = args[3] if l>3 else header + source + '\n' h = self.make_header('Content-Disposition', source) self.assertEqual(h.content_disposition, content_disposition) self.assertEqual(h.params, parmdict) self.assertDefectsEqual(h.defects, defects) self.assertEqual(h, decoded) self.assertEqual(h.fold(policy=policy.default), folded) content_disp_params = { # Examples from RFC 2183. 'RFC_2183_1': ( 'inline', 'inline',), 'RFC_2183_2': ( ('attachment; filename=genome.jpeg;' ' modification-date="Wed, 12 Feb 1997 16:29:51 -0500";'), 'attachment', {'filename': 'genome.jpeg', 'modification-date': 'Wed, 12 Feb 1997 16:29:51 -0500'}, [], ('attachment; filename="genome.jpeg"; ' 'modification-date="Wed, 12 Feb 1997 16:29:51 -0500"'), ('Content-Disposition: attachment; filename="genome.jpeg";\n' ' modification-date="Wed, 12 Feb 1997 16:29:51 -0500"\n'), ), 'no_value': ( '', None, {}, [errors.HeaderMissingRequiredValue], '', 'Content-Disposition:\n'), 'invalid_value': ( 'ab./k', 'ab.', {}, [errors.InvalidHeaderDefect]), 'invalid_value_with_params': ( 'ab./k; filename="foo"', 'ab.', {'filename': 'foo'}, [errors.InvalidHeaderDefect]), } @parameterize class TestMIMEVersionHeader(TestHeaderBase): def version_string_as_MIME_Version(self, source, decoded, version, major, minor, defects): h = self.make_header('MIME-Version', source) self.assertEqual(h, decoded) self.assertEqual(h.version, version) self.assertEqual(h.major, major) self.assertEqual(h.minor, minor) self.assertDefectsEqual(h.defects, defects) if source: source = ' ' + source self.assertEqual(h.fold(policy=policy.default), 'MIME-Version:' + source + '\n') version_string_params = { # Examples from the RFC. 'RFC_2045_1': ( '1.0', '1.0', '1.0', 1, 0, []), 'RFC_2045_2': ( '1.0 (produced by MetaSend Vx.x)', '1.0 (produced by MetaSend Vx.x)', '1.0', 1, 0, []), 'RFC_2045_3': ( '(produced by MetaSend Vx.x) 1.0', '(produced by MetaSend Vx.x) 1.0', '1.0', 1, 0, []), 'RFC_2045_4': ( '1.(produced by MetaSend Vx.x)0', '1.(produced by MetaSend Vx.x)0', '1.0', 1, 0, []), # Other valid values. '1_1': ( '1.1', '1.1', '1.1', 1, 1, []), '2_1': ( '2.1', '2.1', '2.1', 2, 1, []), 'whitespace': ( '1 .0', '1 .0', '1.0', 1, 0, []), 'leading_trailing_whitespace_ignored': ( ' 1.0 ', ' 1.0 ', '1.0', 1, 0, []), # Recoverable invalid values. We can recover here only because we # already have a valid value by the time we encounter the garbage. # Anywhere else, and we don't know where the garbage ends. 'non_comment_garbage_after': ( '1.0 <abc>', '1.0 <abc>', '1.0', 1, 0, [errors.InvalidHeaderDefect]), # Unrecoverable invalid values. We *could* apply more heuristics to # get something out of the first two, but doing so is not worth the # effort. 'non_comment_garbage_before': ( '<abc> 1.0', '<abc> 1.0', None, None, None, [errors.InvalidHeaderDefect]), 'non_comment_garbage_inside': ( '1.<abc>0', '1.<abc>0', None, None, None, [errors.InvalidHeaderDefect]), 'two_periods': ( '1..0', '1..0', None, None, None, [errors.InvalidHeaderDefect]), '2_x': ( '2.x', '2.x', None, # This could be 2, but it seems safer to make it None. None, None, [errors.InvalidHeaderDefect]), 'foo': ( 'foo', 'foo', None, None, None, [errors.InvalidHeaderDefect]), 'missing': ( '', '', None, None, None, [errors.HeaderMissingRequiredValue]), } @parameterize class TestAddressHeader(TestHeaderBase): example_params = { 'empty': ('<>', [errors.InvalidHeaderDefect], '<>', '', '<>', '', '', None), 'address_only': ('[email protected]', [], '[email protected]', '', '[email protected]', 'zippy', 'pinhead.com', None), 'name_and_address': ('Zaphrod Beblebrux <[email protected]>', [], 'Zaphrod Beblebrux <[email protected]>', 'Zaphrod Beblebrux', '[email protected]', 'zippy', 'pinhead.com', None), 'quoted_local_part': ('Zaphrod Beblebrux <"foo bar"@pinhead.com>', [], 'Zaphrod Beblebrux <"foo bar"@pinhead.com>', 'Zaphrod Beblebrux', '"foo bar"@pinhead.com', 'foo bar', 'pinhead.com', None), 'quoted_parens_in_name': (r'"A \(Special\) Person" <[email protected]>', [], '"A (Special) Person" <[email protected]>', 'A (Special) Person', '[email protected]', 'person', 'dom.ain', None), 'quoted_backslashes_in_name': (r'"Arthur \\Backslash\\ Foobar" <[email protected]>', [], r'"Arthur \\Backslash\\ Foobar" <[email protected]>', r'Arthur \Backslash\ Foobar', '[email protected]', 'person', 'dom.ain', None), 'name_with_dot': ('John X. Doe <[email protected]>', [errors.ObsoleteHeaderDefect], '"John X. Doe" <[email protected]>', 'John X. Doe', '[email protected]', 'jxd', 'example.com', None), 'quoted_strings_in_local_part': ('""example" example"@example.com', [errors.InvalidHeaderDefect]*3, '"example example"@example.com', '', '"example example"@example.com', 'example example', 'example.com', None), 'escaped_quoted_strings_in_local_part': (r'"\"example\" example"@example.com', [], r'"\"example\" example"@example.com', '', r'"\"example\" example"@example.com', r'"example" example', 'example.com', None), 'escaped_escapes_in_local_part': (r'"\\"example\\" example"@example.com', [errors.InvalidHeaderDefect]*5, r'"\\example\\\\ example"@example.com', '', r'"\\example\\\\ example"@example.com', r'\example\\ example', 'example.com', None), 'spaces_in_unquoted_local_part_collapsed': ('merwok wok @example.com', [errors.InvalidHeaderDefect]*2, '"merwok wok"@example.com', '', '"merwok wok"@example.com', 'merwok wok', 'example.com', None), 'spaces_around_dots_in_local_part_removed': ('merwok. wok . [email protected]', [errors.ObsoleteHeaderDefect], '[email protected]', '', '[email protected]', 'merwok.wok.wok', 'example.com', None), 'rfc2047_atom_is_decoded': ('=?utf-8?q?=C3=89ric?= <[email protected]>', [], 'Éric <[email protected]>', 'Éric', '[email protected]', 'foo', 'example.com', None), 'rfc2047_atom_in_phrase_is_decoded': ('The =?utf-8?q?=C3=89ric=2C?= Himself <[email protected]>', [], '"The Éric, Himself" <[email protected]>', 'The Éric, Himself', '[email protected]', 'foo', 'example.com', None), 'rfc2047_atom_in_quoted_string_is_decoded': ('"=?utf-8?q?=C3=89ric?=" <[email protected]>', [errors.InvalidHeaderDefect], 'Éric <[email protected]>', 'Éric', '[email protected]', 'foo', 'example.com', None), } # XXX: Need many more examples, and in particular some with names in # trailing comments, which aren't currently handled. comments in # general are not handled yet. def example_as_address(self, source, defects, decoded, display_name, addr_spec, username, domain, comment): h = self.make_header('sender', source) self.assertEqual(h, decoded) self.assertDefectsEqual(h.defects, defects) a = h.address self.assertEqual(str(a), decoded) self.assertEqual(len(h.groups), 1) self.assertEqual([a], list(h.groups[0].addresses)) self.assertEqual([a], list(h.addresses)) self.assertEqual(a.display_name, display_name) self.assertEqual(a.addr_spec, addr_spec) self.assertEqual(a.username, username) self.assertEqual(a.domain, domain) # XXX: we have no comment support yet. #self.assertEqual(a.comment, comment) def example_as_group(self, source, defects, decoded, display_name, addr_spec, username, domain, comment): source = 'foo: {};'.format(source) gdecoded = 'foo: {};'.format(decoded) if decoded else 'foo:;' h = self.make_header('to', source) self.assertEqual(h, gdecoded) self.assertDefectsEqual(h.defects, defects) self.assertEqual(h.groups[0].addresses, h.addresses) self.assertEqual(len(h.groups), 1) self.assertEqual(len(h.addresses), 1) a = h.addresses[0] self.assertEqual(str(a), decoded) self.assertEqual(a.display_name, display_name) self.assertEqual(a.addr_spec, addr_spec) self.assertEqual(a.username, username) self.assertEqual(a.domain, domain) def test_simple_address_list(self): value = ('Fred <[email protected]>, [email protected], ' '"Harry W. Hastings" <[email protected]>') h = self.make_header('to', value) self.assertEqual(h, value) self.assertEqual(len(h.groups), 3) self.assertEqual(len(h.addresses), 3) for i in range(3): self.assertEqual(h.groups[i].addresses[0], h.addresses[i]) self.assertEqual(str(h.addresses[0]), 'Fred <[email protected]>') self.assertEqual(str(h.addresses[1]), '[email protected]') self.assertEqual(str(h.addresses[2]), '"Harry W. Hastings" <[email protected]>') self.assertEqual(h.addresses[2].display_name, 'Harry W. Hastings') def test_complex_address_list(self): examples = list(self.example_params.values()) source = ('dummy list:;, another: (empty);,' + ', '.join([x[0] for x in examples[:4]]) + ', ' + r'"A \"list\"": ' + ', '.join([x[0] for x in examples[4:6]]) + ';,' + ', '.join([x[0] for x in examples[6:]]) ) # XXX: the fact that (empty) disappears here is a potential API design # bug. We don't currently have a way to preserve comments. expected = ('dummy list:;, another:;, ' + ', '.join([x[2] for x in examples[:4]]) + ', ' + r'"A \"list\"": ' + ', '.join([x[2] for x in examples[4:6]]) + ';, ' + ', '.join([x[2] for x in examples[6:]]) ) h = self.make_header('to', source) self.assertEqual(h.split(','), expected.split(',')) self.assertEqual(h, expected) self.assertEqual(len(h.groups), 7 + len(examples) - 6) self.assertEqual(h.groups[0].display_name, 'dummy list') self.assertEqual(h.groups[1].display_name, 'another') self.assertEqual(h.groups[6].display_name, 'A "list"') self.assertEqual(len(h.addresses), len(examples)) for i in range(4): self.assertIsNone(h.groups[i+2].display_name) self.assertEqual(str(h.groups[i+2].addresses[0]), examples[i][2]) for i in range(7, 7 + len(examples) - 6): self.assertIsNone(h.groups[i].display_name) self.assertEqual(str(h.groups[i].addresses[0]), examples[i-1][2]) for i in range(len(examples)): self.assertEqual(str(h.addresses[i]), examples[i][2]) self.assertEqual(h.addresses[i].addr_spec, examples[i][4]) def test_address_read_only(self): h = self.make_header('sender', '[email protected]') with self.assertRaises(AttributeError): h.address = 'foo' def test_addresses_read_only(self): h = self.make_header('sender', '[email protected]') with self.assertRaises(AttributeError): h.addresses = 'foo' def test_groups_read_only(self): h = self.make_header('sender', '[email protected]') with self.assertRaises(AttributeError): h.groups = 'foo' def test_addresses_types(self): source = 'me <[email protected]>' h = self.make_header('to', source) self.assertIsInstance(h.addresses, tuple) self.assertIsInstance(h.addresses[0], Address) def test_groups_types(self): source = 'me <[email protected]>' h = self.make_header('to', source) self.assertIsInstance(h.groups, tuple) self.assertIsInstance(h.groups[0], Group) def test_set_from_Address(self): h = self.make_header('to', Address('me', 'foo', 'example.com')) self.assertEqual(h, 'me <[email protected]>') def test_set_from_Address_list(self): h = self.make_header('to', [Address('me', 'foo', 'example.com'), Address('you', 'bar', 'example.com')]) self.assertEqual(h, 'me <[email protected]>, you <[email protected]>') def test_set_from_Address_and_Group_list(self): h = self.make_header('to', [Address('me', 'foo', 'example.com'), Group('bing', [Address('fiz', 'z', 'b.com'), Address('zif', 'f', 'c.com')]), Address('you', 'bar', 'example.com')]) self.assertEqual(h, 'me <[email protected]>, bing: fiz <[email protected]>, ' 'zif <[email protected]>;, you <[email protected]>') self.assertEqual(h.fold(policy=policy.default.clone(max_line_length=40)), 'to: me <[email protected]>,\n' ' bing: fiz <[email protected]>, zif <[email protected]>;,\n' ' you <[email protected]>\n') def test_set_from_Group_list(self): h = self.make_header('to', [Group('bing', [Address('fiz', 'z', 'b.com'), Address('zif', 'f', 'c.com')])]) self.assertEqual(h, 'bing: fiz <[email protected]>, zif <[email protected]>;') class TestAddressAndGroup(TestEmailBase): def _test_attr_ro(self, obj, attr): with self.assertRaises(AttributeError): setattr(obj, attr, 'foo') def test_address_display_name_ro(self): self._test_attr_ro(Address('foo', 'bar', 'baz'), 'display_name') def test_address_username_ro(self): self._test_attr_ro(Address('foo', 'bar', 'baz'), 'username') def test_address_domain_ro(self): self._test_attr_ro(Address('foo', 'bar', 'baz'), 'domain') def test_group_display_name_ro(self): self._test_attr_ro(Group('foo'), 'display_name') def test_group_addresses_ro(self): self._test_attr_ro(Group('foo'), 'addresses') def test_address_from_username_domain(self): a = Address('foo', 'bar', 'baz') self.assertEqual(a.display_name, 'foo') self.assertEqual(a.username, 'bar') self.assertEqual(a.domain, 'baz') self.assertEqual(a.addr_spec, 'bar@baz') self.assertEqual(str(a), 'foo <bar@baz>') def test_address_from_addr_spec(self): a = Address('foo', addr_spec='bar@baz') self.assertEqual(a.display_name, 'foo') self.assertEqual(a.username, 'bar') self.assertEqual(a.domain, 'baz') self.assertEqual(a.addr_spec, 'bar@baz') self.assertEqual(str(a), 'foo <bar@baz>') def test_address_with_no_display_name(self): a = Address(addr_spec='bar@baz') self.assertEqual(a.display_name, '') self.assertEqual(a.username, 'bar') self.assertEqual(a.domain, 'baz') self.assertEqual(a.addr_spec, 'bar@baz') self.assertEqual(str(a), 'bar@baz') def test_null_address(self): a = Address() self.assertEqual(a.display_name, '') self.assertEqual(a.username, '') self.assertEqual(a.domain, '') self.assertEqual(a.addr_spec, '<>') self.assertEqual(str(a), '<>') def test_domain_only(self): # This isn't really a valid address. a = Address(domain='buzz') self.assertEqual(a.display_name, '') self.assertEqual(a.username, '') self.assertEqual(a.domain, 'buzz') self.assertEqual(a.addr_spec, '@buzz') self.assertEqual(str(a), '@buzz') def test_username_only(self): # This isn't really a valid address. a = Address(username='buzz') self.assertEqual(a.display_name, '') self.assertEqual(a.username, 'buzz') self.assertEqual(a.domain, '') self.assertEqual(a.addr_spec, 'buzz') self.assertEqual(str(a), 'buzz') def test_display_name_only(self): a = Address('buzz') self.assertEqual(a.display_name, 'buzz') self.assertEqual(a.username, '') self.assertEqual(a.domain, '') self.assertEqual(a.addr_spec, '<>') self.assertEqual(str(a), 'buzz <>') def test_quoting(self): # Ideally we'd check every special individually, but I'm not up for # writing that many tests. a = Address('Sara J.', 'bad name', 'example.com') self.assertEqual(a.display_name, 'Sara J.') self.assertEqual(a.username, 'bad name') self.assertEqual(a.domain, 'example.com') self.assertEqual(a.addr_spec, '"bad name"@example.com') self.assertEqual(str(a), '"Sara J." <"bad name"@example.com>') def test_il8n(self): a = Address('Éric', 'wok', 'exàmple.com') self.assertEqual(a.display_name, 'Éric') self.assertEqual(a.username, 'wok') self.assertEqual(a.domain, 'exàmple.com') self.assertEqual(a.addr_spec, 'wok@exàmple.com') self.assertEqual(str(a), 'Éric <wok@exàmple.com>') # XXX: there is an API design issue that needs to be solved here. #def test_non_ascii_username_raises(self): # with self.assertRaises(ValueError): # Address('foo', 'wők', 'example.com') def test_crlf_in_constructor_args_raises(self): cases = ( dict(display_name='foo\r'), dict(display_name='foo\n'), dict(display_name='foo\r\n'), dict(domain='example.com\r'), dict(domain='example.com\n'), dict(domain='example.com\r\n'), dict(username='wok\r'), dict(username='wok\n'), dict(username='wok\r\n'), dict(addr_spec='[email protected]\r'), dict(addr_spec='[email protected]\n'), dict(addr_spec='[email protected]\r\n') ) for kwargs in cases: with self.subTest(kwargs=kwargs), self.assertRaisesRegex(ValueError, "invalid arguments"): Address(**kwargs) def test_non_ascii_username_in_addr_spec_raises(self): with self.assertRaises(ValueError): Address('foo', addr_spec='wő[email protected]') def test_address_addr_spec_and_username_raises(self): with self.assertRaises(TypeError): Address('foo', username='bing', addr_spec='bar@baz') def test_address_addr_spec_and_domain_raises(self): with self.assertRaises(TypeError): Address('foo', domain='bing', addr_spec='bar@baz') def test_address_addr_spec_and_username_and_domain_raises(self): with self.assertRaises(TypeError): Address('foo', username='bong', domain='bing', addr_spec='bar@baz') def test_space_in_addr_spec_username_raises(self): with self.assertRaises(ValueError): Address('foo', addr_spec="bad [email protected]") def test_bad_addr_sepc_raises(self): with self.assertRaises(ValueError): Address('foo', addr_spec="name@ex[]ample.com") def test_empty_group(self): g = Group('foo') self.assertEqual(g.display_name, 'foo') self.assertEqual(g.addresses, tuple()) self.assertEqual(str(g), 'foo:;') def test_empty_group_list(self): g = Group('foo', addresses=[]) self.assertEqual(g.display_name, 'foo') self.assertEqual(g.addresses, tuple()) self.assertEqual(str(g), 'foo:;') def test_null_group(self): g = Group() self.assertIsNone(g.display_name) self.assertEqual(g.addresses, tuple()) self.assertEqual(str(g), 'None:;') def test_group_with_addresses(self): addrs = [Address('b', 'b', 'c'), Address('a', 'b','c')] g = Group('foo', addrs) self.assertEqual(g.display_name, 'foo') self.assertEqual(g.addresses, tuple(addrs)) self.assertEqual(str(g), 'foo: b <b@c>, a <b@c>;') def test_group_with_addresses_no_display_name(self): addrs = [Address('b', 'b', 'c'), Address('a', 'b','c')] g = Group(addresses=addrs) self.assertIsNone(g.display_name) self.assertEqual(g.addresses, tuple(addrs)) self.assertEqual(str(g), 'None: b <b@c>, a <b@c>;') def test_group_with_one_address_no_display_name(self): addrs = [Address('b', 'b', 'c')] g = Group(addresses=addrs) self.assertIsNone(g.display_name) self.assertEqual(g.addresses, tuple(addrs)) self.assertEqual(str(g), 'b <b@c>') def test_display_name_quoting(self): g = Group('foo.bar') self.assertEqual(g.display_name, 'foo.bar') self.assertEqual(g.addresses, tuple()) self.assertEqual(str(g), '"foo.bar":;') def test_display_name_blanks_not_quoted(self): g = Group('foo bar') self.assertEqual(g.display_name, 'foo bar') self.assertEqual(g.addresses, tuple()) self.assertEqual(str(g), 'foo bar:;') def test_set_message_header_from_address(self): a = Address('foo', 'bar', 'example.com') m = Message(policy=policy.default) m['To'] = a self.assertEqual(m['to'], 'foo <[email protected]>') self.assertEqual(m['to'].addresses, (a,)) def test_set_message_header_from_group(self): g = Group('foo bar') m = Message(policy=policy.default) m['To'] = g self.assertEqual(m['to'], 'foo bar:;') self.assertEqual(m['to'].addresses, g.addresses) class TestFolding(TestHeaderBase): def test_short_unstructured(self): h = self.make_header('subject', 'this is a test') self.assertEqual(h.fold(policy=policy.default), 'subject: this is a test\n') def test_long_unstructured(self): h = self.make_header('Subject', 'This is a long header ' 'line that will need to be folded into two lines ' 'and will demonstrate basic folding') self.assertEqual(h.fold(policy=policy.default), 'Subject: This is a long header line that will ' 'need to be folded into two lines\n' ' and will demonstrate basic folding\n') def test_unstructured_short_max_line_length(self): h = self.make_header('Subject', 'this is a short header ' 'that will be folded anyway') self.assertEqual( h.fold(policy=policy.default.clone(max_line_length=20)), textwrap.dedent("""\ Subject: this is a short header that will be folded anyway """)) def test_fold_unstructured_single_word(self): h = self.make_header('Subject', 'test') self.assertEqual(h.fold(policy=policy.default), 'Subject: test\n') def test_fold_unstructured_short(self): h = self.make_header('Subject', 'test test test') self.assertEqual(h.fold(policy=policy.default), 'Subject: test test test\n') def test_fold_unstructured_with_overlong_word(self): h = self.make_header('Subject', 'thisisaverylonglineconsistingofa' 'singlewordthatwontfit') self.assertEqual( h.fold(policy=policy.default.clone(max_line_length=20)), 'Subject: \n' ' =?utf-8?q?thisisa?=\n' ' =?utf-8?q?verylon?=\n' ' =?utf-8?q?glineco?=\n' ' =?utf-8?q?nsistin?=\n' ' =?utf-8?q?gofasin?=\n' ' =?utf-8?q?gleword?=\n' ' =?utf-8?q?thatwon?=\n' ' =?utf-8?q?tfit?=\n' ) def test_fold_unstructured_with_two_overlong_words(self): h = self.make_header('Subject', 'thisisaverylonglineconsistingofa' 'singlewordthatwontfit plusanotherverylongwordthatwontfit') self.assertEqual( h.fold(policy=policy.default.clone(max_line_length=20)), 'Subject: \n' ' =?utf-8?q?thisisa?=\n' ' =?utf-8?q?verylon?=\n' ' =?utf-8?q?glineco?=\n' ' =?utf-8?q?nsistin?=\n' ' =?utf-8?q?gofasin?=\n' ' =?utf-8?q?gleword?=\n' ' =?utf-8?q?thatwon?=\n' ' =?utf-8?q?tfit_pl?=\n' ' =?utf-8?q?usanoth?=\n' ' =?utf-8?q?erveryl?=\n' ' =?utf-8?q?ongword?=\n' ' =?utf-8?q?thatwon?=\n' ' =?utf-8?q?tfit?=\n' ) # XXX Need test for when max_line_length is less than the chrome size. def test_fold_unstructured_with_slightly_long_word(self): h = self.make_header('Subject', 'thislongwordislessthanmaxlinelen') self.assertEqual( h.fold(policy=policy.default.clone(max_line_length=35)), 'Subject:\n thislongwordislessthanmaxlinelen\n') def test_fold_unstructured_with_commas(self): # The old wrapper would fold this at the commas. h = self.make_header('Subject', "This header is intended to " "demonstrate, in a fairly succinct way, that we now do " "not give a , special treatment in unstructured headers.") self.assertEqual( h.fold(policy=policy.default.clone(max_line_length=60)), textwrap.dedent("""\ Subject: This header is intended to demonstrate, in a fairly succinct way, that we now do not give a , special treatment in unstructured headers. """)) def test_fold_address_list(self): h = self.make_header('To', '"Theodore H. Perfect" <[email protected]>, ' '"My address is very long because my name is long" <[email protected]>, ' '"Only A. Friend" <[email protected]>') self.assertEqual(h.fold(policy=policy.default), textwrap.dedent("""\ To: "Theodore H. Perfect" <[email protected]>, "My address is very long because my name is long" <[email protected]>, "Only A. Friend" <[email protected]> """)) def test_fold_date_header(self): h = self.make_header('Date', 'Sat, 2 Feb 2002 17:00:06 -0800') self.assertEqual(h.fold(policy=policy.default), 'Date: Sat, 02 Feb 2002 17:00:06 -0800\n') def test_fold_overlong_words_using_RFC2047(self): h = self.make_header( 'X-Report-Abuse', '<https://www.mailitapp.com/report_abuse.php?' 'mid=xxx-xxx-xxxxxxxxxxxxxxxxxxxxxxxx==-xxx-xx-xx>') self.assertEqual( h.fold(policy=policy.default), 'X-Report-Abuse: =?utf-8?q?=3Chttps=3A//www=2Emailitapp=2E' 'com/report=5Fabuse?=\n' ' =?utf-8?q?=2Ephp=3Fmid=3Dxxx-xxx-xxxx' 'xxxxxxxxxxxxxxxxxxxx=3D=3D-xxx-xx-xx?=\n' ' =?utf-8?q?=3E?=\n') if __name__ == '__main__': unittest.main()
59,612
1,673
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_email/test__encoded_words.py
import unittest from email import _encoded_words as _ew from email import errors from test.test_email import TestEmailBase class TestDecodeQ(TestEmailBase): def _test(self, source, ex_result, ex_defects=[]): result, defects = _ew.decode_q(source) self.assertEqual(result, ex_result) self.assertDefectsEqual(defects, ex_defects) def test_no_encoded(self): self._test(b'foobar', b'foobar') def test_spaces(self): self._test(b'foo=20bar=20', b'foo bar ') self._test(b'foo_bar_', b'foo bar ') def test_run_of_encoded(self): self._test(b'foo=20=20=21=2Cbar', b'foo !,bar') class TestDecodeB(TestEmailBase): def _test(self, source, ex_result, ex_defects=[]): result, defects = _ew.decode_b(source) self.assertEqual(result, ex_result) self.assertDefectsEqual(defects, ex_defects) def test_simple(self): self._test(b'Zm9v', b'foo') def test_missing_padding(self): # 1 missing padding character self._test(b'dmk', b'vi', [errors.InvalidBase64PaddingDefect]) # 2 missing padding characters self._test(b'dg', b'v', [errors.InvalidBase64PaddingDefect]) def test_invalid_character(self): self._test(b'dm\x01k===', b'vi', [errors.InvalidBase64CharactersDefect]) def test_invalid_character_and_bad_padding(self): self._test(b'dm\x01k', b'vi', [errors.InvalidBase64CharactersDefect, errors.InvalidBase64PaddingDefect]) def test_invalid_length(self): self._test(b'abcde', b'abcde', [errors.InvalidBase64LengthDefect]) class TestDecode(TestEmailBase): def test_wrong_format_input_raises(self): with self.assertRaises(ValueError): _ew.decode('=?badone?=') with self.assertRaises(ValueError): _ew.decode('=?') with self.assertRaises(ValueError): _ew.decode('') def _test(self, source, result, charset='us-ascii', lang='', defects=[]): res, char, l, d = _ew.decode(source) self.assertEqual(res, result) self.assertEqual(char, charset) self.assertEqual(l, lang) self.assertDefectsEqual(d, defects) def test_simple_q(self): self._test('=?us-ascii?q?foo?=', 'foo') def test_simple_b(self): self._test('=?us-ascii?b?dmk=?=', 'vi') def test_q_case_ignored(self): self._test('=?us-ascii?Q?foo?=', 'foo') def test_b_case_ignored(self): self._test('=?us-ascii?B?dmk=?=', 'vi') def test_non_trivial_q(self): self._test('=?latin-1?q?=20F=fcr=20Elise=20?=', ' Für Elise ', 'latin-1') def test_q_escaped_bytes_preserved(self): self._test(b'=?us-ascii?q?=20\xACfoo?='.decode('us-ascii', 'surrogateescape'), ' \uDCACfoo', defects = [errors.UndecodableBytesDefect]) def test_b_undecodable_bytes_ignored_with_defect(self): self._test(b'=?us-ascii?b?dm\xACk?='.decode('us-ascii', 'surrogateescape'), 'vi', defects = [ errors.InvalidBase64CharactersDefect, errors.InvalidBase64PaddingDefect]) def test_b_invalid_bytes_ignored_with_defect(self): self._test('=?us-ascii?b?dm\x01k===?=', 'vi', defects = [errors.InvalidBase64CharactersDefect]) def test_b_invalid_bytes_incorrect_padding(self): self._test('=?us-ascii?b?dm\x01k?=', 'vi', defects = [ errors.InvalidBase64CharactersDefect, errors.InvalidBase64PaddingDefect]) def test_b_padding_defect(self): self._test('=?us-ascii?b?dmk?=', 'vi', defects = [errors.InvalidBase64PaddingDefect]) def test_nonnull_lang(self): self._test('=?us-ascii*jive?q?test?=', 'test', lang='jive') def test_unknown_8bit_charset(self): self._test('=?unknown-8bit?q?foo=ACbar?=', b'foo\xacbar'.decode('ascii', 'surrogateescape'), charset = 'unknown-8bit', defects = []) def test_unknown_charset(self): self._test('=?foobar?q?foo=ACbar?=', b'foo\xacbar'.decode('ascii', 'surrogateescape'), charset = 'foobar', # XXX Should this be a new Defect instead? defects = [errors.CharsetError]) def test_q_nonascii(self): self._test('=?utf-8?q?=C3=89ric?=', 'Éric', charset='utf-8') class TestEncodeQ(TestEmailBase): def _test(self, src, expected): self.assertEqual(_ew.encode_q(src), expected) def test_all_safe(self): self._test(b'foobar', 'foobar') def test_spaces(self): self._test(b'foo bar ', 'foo_bar_') def test_run_of_encodables(self): self._test(b'foo ,,bar', 'foo__=2C=2Cbar') class TestEncodeB(TestEmailBase): def test_simple(self): self.assertEqual(_ew.encode_b(b'foo'), 'Zm9v') def test_padding(self): self.assertEqual(_ew.encode_b(b'vi'), 'dmk=') class TestEncode(TestEmailBase): def test_q(self): self.assertEqual(_ew.encode('foo', 'utf-8', 'q'), '=?utf-8?q?foo?=') def test_b(self): self.assertEqual(_ew.encode('foo', 'utf-8', 'b'), '=?utf-8?b?Zm9v?=') def test_auto_q(self): self.assertEqual(_ew.encode('foo', 'utf-8'), '=?utf-8?q?foo?=') def test_auto_q_if_short_mostly_safe(self): self.assertEqual(_ew.encode('vi.', 'utf-8'), '=?utf-8?q?vi=2E?=') def test_auto_b_if_enough_unsafe(self): self.assertEqual(_ew.encode('.....', 'utf-8'), '=?utf-8?b?Li4uLi4=?=') def test_auto_b_if_long_unsafe(self): self.assertEqual(_ew.encode('vi.vi.vi.vi.vi.', 'utf-8'), '=?utf-8?b?dmkudmkudmkudmkudmku?=') def test_auto_q_if_long_mostly_safe(self): self.assertEqual(_ew.encode('vi vi vi.vi ', 'utf-8'), '=?utf-8?q?vi_vi_vi=2Evi_?=') def test_utf8_default(self): self.assertEqual(_ew.encode('foo'), '=?utf-8?q?foo?=') def test_lang(self): self.assertEqual(_ew.encode('foo', lang='jive'), '=?utf-8*jive?q?foo?=') def test_unknown_8bit(self): self.assertEqual(_ew.encode('foo\uDCACbar', charset='unknown-8bit'), '=?unknown-8bit?q?foo=ACbar?=') if __name__ == '__main__': unittest.main()
6,644
199
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_email/test_inversion.py
"""Test the parser and generator are inverses. Note that this is only strictly true if we are parsing RFC valid messages and producing RFC valid messages. """ import io import unittest from email import policy, message_from_bytes from email.message import EmailMessage from email.generator import BytesGenerator from test.test_email import TestEmailBase, parameterize # This is like textwrap.dedent for bytes, except that it uses \r\n for the line # separators on the rebuilt string. def dedent(bstr): lines = bstr.splitlines() if not lines[0].strip(): raise ValueError("First line must contain text") stripamt = len(lines[0]) - len(lines[0].lstrip()) return b'\r\n'.join( [x[stripamt:] if len(x)>=stripamt else b'' for x in lines]) @parameterize class TestInversion(TestEmailBase): policy = policy.default message = EmailMessage def msg_as_input(self, msg): m = message_from_bytes(msg, policy=policy.SMTP) b = io.BytesIO() g = BytesGenerator(b) g.flatten(m) self.assertEqual(b.getvalue(), msg) # XXX: spaces are not preserved correctly here yet in the general case. msg_params = { 'header_with_one_space_body': (dedent(b"""\ From: [email protected] X-Status:\x20 Subject: test foo """),), } payload_params = { 'plain_text': dict(payload='This is a test\n'*20), 'base64_text': dict(payload=(('xy a'*40+'\n')*5), cte='base64'), 'qp_text': dict(payload=(('xy a'*40+'\n')*5), cte='quoted-printable'), } def payload_as_body(self, payload, **kw): msg = self._make_message() msg['From'] = 'foo' msg['To'] = 'bar' msg['Subject'] = 'payload round trip test' msg.set_content(payload, **kw) b = bytes(msg) msg2 = message_from_bytes(b, policy=self.policy) self.assertEqual(bytes(msg2), b) self.assertEqual(msg2.get_content(), payload) if __name__ == '__main__': unittest.main()
2,075
71
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_email/test_email.py
# Copyright (C) 2001-2010 Python Software Foundation # Contact: [email protected] # email package unit tests import os import re import sys import time import base64 import unittest import textwrap from io import StringIO, BytesIO from itertools import chain from random import choice from socket import getfqdn try: from threading import Thread except ImportError: from dummy_threading import Thread import email import email.policy from email.charset import Charset from email.header import Header, decode_header, make_header from email.parser import Parser, HeaderParser from email.generator import Generator, DecodedGenerator, BytesGenerator from email.message import Message from email.mime.application import MIMEApplication from email.mime.audio import MIMEAudio from email.mime.text import MIMEText from email.mime.image import MIMEImage from email.mime.base import MIMEBase from email.mime.message import MIMEMessage from email.mime.multipart import MIMEMultipart from email.mime.nonmultipart import MIMENonMultipart from email import utils from email import errors from email import encoders from email import iterators from email import base64mime from email import quoprimime from test.support import unlink, start_threads from test.test_email import openfile, TestEmailBase from encodings import iso2022_jp, mac_iceland # These imports are documented to work, but we are testing them using a # different path, so we import them here just to make sure they are importable. from email.parser import FeedParser, BytesFeedParser NL = '\n' EMPTYSTRING = '' SPACE = ' ' # Test various aspects of the Message class's API class TestMessageAPI(TestEmailBase): def test_get_all(self): eq = self.assertEqual msg = self._msgobj('msg_20.txt') eq(msg.get_all('cc'), ['[email protected]', '[email protected]', '[email protected]']) eq(msg.get_all('xx', 'n/a'), 'n/a') def test_getset_charset(self): eq = self.assertEqual msg = Message() eq(msg.get_charset(), None) charset = Charset('iso-8859-1') msg.set_charset(charset) eq(msg['mime-version'], '1.0') eq(msg.get_content_type(), 'text/plain') eq(msg['content-type'], 'text/plain; charset="iso-8859-1"') eq(msg.get_param('charset'), 'iso-8859-1') eq(msg['content-transfer-encoding'], 'quoted-printable') eq(msg.get_charset().input_charset, 'iso-8859-1') # Remove the charset msg.set_charset(None) eq(msg.get_charset(), None) eq(msg['content-type'], 'text/plain') # Try adding a charset when there's already MIME headers present msg = Message() msg['MIME-Version'] = '2.0' msg['Content-Type'] = 'text/x-weird' msg['Content-Transfer-Encoding'] = 'quinted-puntable' msg.set_charset(charset) eq(msg['mime-version'], '2.0') eq(msg['content-type'], 'text/x-weird; charset="iso-8859-1"') eq(msg['content-transfer-encoding'], 'quinted-puntable') def test_set_charset_from_string(self): eq = self.assertEqual msg = Message() msg.set_charset('us-ascii') eq(msg.get_charset().input_charset, 'us-ascii') eq(msg['content-type'], 'text/plain; charset="us-ascii"') def test_set_payload_with_charset(self): msg = Message() charset = Charset('iso-8859-1') msg.set_payload('This is a string payload', charset) self.assertEqual(msg.get_charset().input_charset, 'iso-8859-1') def test_set_payload_with_8bit_data_and_charset(self): data = b'\xd0\x90\xd0\x91\xd0\x92' charset = Charset('utf-8') msg = Message() msg.set_payload(data, charset) self.assertEqual(msg['content-transfer-encoding'], 'base64') self.assertEqual(msg.get_payload(decode=True), data) self.assertEqual(msg.get_payload(), '0JDQkdCS\n') def test_set_payload_with_non_ascii_and_charset_body_encoding_none(self): data = b'\xd0\x90\xd0\x91\xd0\x92' charset = Charset('utf-8') charset.body_encoding = None # Disable base64 encoding msg = Message() msg.set_payload(data.decode('utf-8'), charset) self.assertEqual(msg['content-transfer-encoding'], '8bit') self.assertEqual(msg.get_payload(decode=True), data) def test_set_payload_with_8bit_data_and_charset_body_encoding_none(self): data = b'\xd0\x90\xd0\x91\xd0\x92' charset = Charset('utf-8') charset.body_encoding = None # Disable base64 encoding msg = Message() msg.set_payload(data, charset) self.assertEqual(msg['content-transfer-encoding'], '8bit') self.assertEqual(msg.get_payload(decode=True), data) def test_set_payload_to_list(self): msg = Message() msg.set_payload([]) self.assertEqual(msg.get_payload(), []) def test_attach_when_payload_is_string(self): msg = Message() msg['Content-Type'] = 'multipart/mixed' msg.set_payload('string payload') sub_msg = MIMEMessage(Message()) self.assertRaisesRegex(TypeError, "[Aa]ttach.*non-multipart", msg.attach, sub_msg) def test_get_charsets(self): eq = self.assertEqual msg = self._msgobj('msg_08.txt') charsets = msg.get_charsets() eq(charsets, [None, 'us-ascii', 'iso-8859-1', 'iso-8859-2', 'koi8-r']) msg = self._msgobj('msg_09.txt') charsets = msg.get_charsets('dingbat') eq(charsets, ['dingbat', 'us-ascii', 'iso-8859-1', 'dingbat', 'koi8-r']) msg = self._msgobj('msg_12.txt') charsets = msg.get_charsets() eq(charsets, [None, 'us-ascii', 'iso-8859-1', None, 'iso-8859-2', 'iso-8859-3', 'us-ascii', 'koi8-r']) def test_get_filename(self): eq = self.assertEqual msg = self._msgobj('msg_04.txt') filenames = [p.get_filename() for p in msg.get_payload()] eq(filenames, ['msg.txt', 'msg.txt']) msg = self._msgobj('msg_07.txt') subpart = msg.get_payload(1) eq(subpart.get_filename(), 'dingusfish.gif') def test_get_filename_with_name_parameter(self): eq = self.assertEqual msg = self._msgobj('msg_44.txt') filenames = [p.get_filename() for p in msg.get_payload()] eq(filenames, ['msg.txt', 'msg.txt']) def test_get_boundary(self): eq = self.assertEqual msg = self._msgobj('msg_07.txt') # No quotes! eq(msg.get_boundary(), 'BOUNDARY') def test_set_boundary(self): eq = self.assertEqual # This one has no existing boundary parameter, but the Content-Type: # header appears fifth. msg = self._msgobj('msg_01.txt') msg.set_boundary('BOUNDARY') header, value = msg.items()[4] eq(header.lower(), 'content-type') eq(value, 'text/plain; charset="us-ascii"; boundary="BOUNDARY"') # This one has a Content-Type: header, with a boundary, stuck in the # middle of its headers. Make sure the order is preserved; it should # be fifth. msg = self._msgobj('msg_04.txt') msg.set_boundary('BOUNDARY') header, value = msg.items()[4] eq(header.lower(), 'content-type') eq(value, 'multipart/mixed; boundary="BOUNDARY"') # And this one has no Content-Type: header at all. msg = self._msgobj('msg_03.txt') self.assertRaises(errors.HeaderParseError, msg.set_boundary, 'BOUNDARY') def test_make_boundary(self): msg = MIMEMultipart('form-data') # Note that when the boundary gets created is an implementation # detail and might change. self.assertEqual(msg.items()[0][1], 'multipart/form-data') # Trigger creation of boundary msg.as_string() self.assertEqual(msg.items()[0][1][:33], 'multipart/form-data; boundary="==') # XXX: there ought to be tests of the uniqueness of the boundary, too. def test_message_rfc822_only(self): # Issue 7970: message/rfc822 not in multipart parsed by # HeaderParser caused an exception when flattened. with openfile('msg_46.txt') as fp: msgdata = fp.read() parser = HeaderParser() msg = parser.parsestr(msgdata) out = StringIO() gen = Generator(out, True, 0) gen.flatten(msg, False) self.assertEqual(out.getvalue(), msgdata) def test_byte_message_rfc822_only(self): # Make sure new bytes header parser also passes this. with openfile('msg_46.txt') as fp: msgdata = fp.read().encode('ascii') parser = email.parser.BytesHeaderParser() msg = parser.parsebytes(msgdata) out = BytesIO() gen = email.generator.BytesGenerator(out) gen.flatten(msg) self.assertEqual(out.getvalue(), msgdata) def test_get_decoded_payload(self): eq = self.assertEqual msg = self._msgobj('msg_10.txt') # The outer message is a multipart eq(msg.get_payload(decode=True), None) # Subpart 1 is 7bit encoded eq(msg.get_payload(0).get_payload(decode=True), b'This is a 7bit encoded message.\n') # Subpart 2 is quopri eq(msg.get_payload(1).get_payload(decode=True), b'\xa1This is a Quoted Printable encoded message!\n') # Subpart 3 is base64 eq(msg.get_payload(2).get_payload(decode=True), b'This is a Base64 encoded message.') # Subpart 4 is base64 with a trailing newline, which # used to be stripped (issue 7143). eq(msg.get_payload(3).get_payload(decode=True), b'This is a Base64 encoded message.\n') # Subpart 5 has no Content-Transfer-Encoding: header. eq(msg.get_payload(4).get_payload(decode=True), b'This has no Content-Transfer-Encoding: header.\n') def test_get_decoded_uu_payload(self): eq = self.assertEqual msg = Message() msg.set_payload('begin 666 -\n+:&5L;&\\@=V]R;&0 \n \nend\n') for cte in ('x-uuencode', 'uuencode', 'uue', 'x-uue'): msg['content-transfer-encoding'] = cte eq(msg.get_payload(decode=True), b'hello world') # Now try some bogus data msg.set_payload('foo') eq(msg.get_payload(decode=True), b'foo') def test_get_payload_n_raises_on_non_multipart(self): msg = Message() self.assertRaises(TypeError, msg.get_payload, 1) def test_decoded_generator(self): eq = self.assertEqual msg = self._msgobj('msg_07.txt') with openfile('msg_17.txt') as fp: text = fp.read() s = StringIO() g = DecodedGenerator(s) g.flatten(msg) eq(s.getvalue(), text) def test__contains__(self): msg = Message() msg['From'] = 'Me' msg['to'] = 'You' # Check for case insensitivity self.assertIn('from', msg) self.assertIn('From', msg) self.assertIn('FROM', msg) self.assertIn('to', msg) self.assertIn('To', msg) self.assertIn('TO', msg) def test_as_string(self): msg = self._msgobj('msg_01.txt') with openfile('msg_01.txt') as fp: text = fp.read() self.assertEqual(text, str(msg)) fullrepr = msg.as_string(unixfrom=True) lines = fullrepr.split('\n') self.assertTrue(lines[0].startswith('From ')) self.assertEqual(text, NL.join(lines[1:])) def test_as_string_policy(self): msg = self._msgobj('msg_01.txt') newpolicy = msg.policy.clone(linesep='\r\n') fullrepr = msg.as_string(policy=newpolicy) s = StringIO() g = Generator(s, policy=newpolicy) g.flatten(msg) self.assertEqual(fullrepr, s.getvalue()) def test_as_bytes(self): msg = self._msgobj('msg_01.txt') with openfile('msg_01.txt') as fp: data = fp.read().encode('ascii') self.assertEqual(data, bytes(msg)) fullrepr = msg.as_bytes(unixfrom=True) lines = fullrepr.split(b'\n') self.assertTrue(lines[0].startswith(b'From ')) self.assertEqual(data, b'\n'.join(lines[1:])) def test_as_bytes_policy(self): msg = self._msgobj('msg_01.txt') newpolicy = msg.policy.clone(linesep='\r\n') fullrepr = msg.as_bytes(policy=newpolicy) s = BytesIO() g = BytesGenerator(s,policy=newpolicy) g.flatten(msg) self.assertEqual(fullrepr, s.getvalue()) # test_headerregistry.TestContentTypeHeader.bad_params def test_bad_param(self): msg = email.message_from_string("Content-Type: blarg; baz; boo\n") self.assertEqual(msg.get_param('baz'), '') def test_missing_filename(self): msg = email.message_from_string("From: foo\n") self.assertEqual(msg.get_filename(), None) def test_bogus_filename(self): msg = email.message_from_string( "Content-Disposition: blarg; filename\n") self.assertEqual(msg.get_filename(), '') def test_missing_boundary(self): msg = email.message_from_string("From: foo\n") self.assertEqual(msg.get_boundary(), None) def test_get_params(self): eq = self.assertEqual msg = email.message_from_string( 'X-Header: foo=one; bar=two; baz=three\n') eq(msg.get_params(header='x-header'), [('foo', 'one'), ('bar', 'two'), ('baz', 'three')]) msg = email.message_from_string( 'X-Header: foo; bar=one; baz=two\n') eq(msg.get_params(header='x-header'), [('foo', ''), ('bar', 'one'), ('baz', 'two')]) eq(msg.get_params(), None) msg = email.message_from_string( 'X-Header: foo; bar="one"; baz=two\n') eq(msg.get_params(header='x-header'), [('foo', ''), ('bar', 'one'), ('baz', 'two')]) # test_headerregistry.TestContentTypeHeader.spaces_around_param_equals def test_get_param_liberal(self): msg = Message() msg['Content-Type'] = 'Content-Type: Multipart/mixed; boundary = "CPIMSSMTPC06p5f3tG"' self.assertEqual(msg.get_param('boundary'), 'CPIMSSMTPC06p5f3tG') def test_get_param(self): eq = self.assertEqual msg = email.message_from_string( "X-Header: foo=one; bar=two; baz=three\n") eq(msg.get_param('bar', header='x-header'), 'two') eq(msg.get_param('quuz', header='x-header'), None) eq(msg.get_param('quuz'), None) msg = email.message_from_string( 'X-Header: foo; bar="one"; baz=two\n') eq(msg.get_param('foo', header='x-header'), '') eq(msg.get_param('bar', header='x-header'), 'one') eq(msg.get_param('baz', header='x-header'), 'two') # XXX: We are not RFC-2045 compliant! We cannot parse: # msg["Content-Type"] = 'text/plain; weird="hey; dolly? [you] @ <\\"home\\">?"' # msg.get_param("weird") # yet. # test_headerregistry.TestContentTypeHeader.spaces_around_semis def test_get_param_funky_continuation_lines(self): msg = self._msgobj('msg_22.txt') self.assertEqual(msg.get_payload(1).get_param('name'), 'wibble.JPG') # test_headerregistry.TestContentTypeHeader.semis_inside_quotes def test_get_param_with_semis_in_quotes(self): msg = email.message_from_string( 'Content-Type: image/pjpeg; name="Jim&amp;&amp;Jill"\n') self.assertEqual(msg.get_param('name'), 'Jim&amp;&amp;Jill') self.assertEqual(msg.get_param('name', unquote=False), '"Jim&amp;&amp;Jill"') # test_headerregistry.TestContentTypeHeader.quotes_inside_rfc2231_value def test_get_param_with_quotes(self): msg = email.message_from_string( 'Content-Type: foo; bar*0="baz\\"foobar"; bar*1="\\"baz"') self.assertEqual(msg.get_param('bar'), 'baz"foobar"baz') msg = email.message_from_string( "Content-Type: foo; bar*0=\"baz\\\"foobar\"; bar*1=\"\\\"baz\"") self.assertEqual(msg.get_param('bar'), 'baz"foobar"baz') def test_field_containment(self): msg = email.message_from_string('Header: exists') self.assertIn('header', msg) self.assertIn('Header', msg) self.assertIn('HEADER', msg) self.assertNotIn('headerx', msg) def test_set_param(self): eq = self.assertEqual msg = Message() msg.set_param('charset', 'iso-2022-jp') eq(msg.get_param('charset'), 'iso-2022-jp') msg.set_param('importance', 'high value') eq(msg.get_param('importance'), 'high value') eq(msg.get_param('importance', unquote=False), '"high value"') eq(msg.get_params(), [('text/plain', ''), ('charset', 'iso-2022-jp'), ('importance', 'high value')]) eq(msg.get_params(unquote=False), [('text/plain', ''), ('charset', '"iso-2022-jp"'), ('importance', '"high value"')]) msg.set_param('charset', 'iso-9999-xx', header='X-Jimmy') eq(msg.get_param('charset', header='X-Jimmy'), 'iso-9999-xx') def test_del_param(self): eq = self.assertEqual msg = self._msgobj('msg_05.txt') eq(msg.get_params(), [('multipart/report', ''), ('report-type', 'delivery-status'), ('boundary', 'D1690A7AC1.996856090/mail.example.com')]) old_val = msg.get_param("report-type") msg.del_param("report-type") eq(msg.get_params(), [('multipart/report', ''), ('boundary', 'D1690A7AC1.996856090/mail.example.com')]) msg.set_param("report-type", old_val) eq(msg.get_params(), [('multipart/report', ''), ('boundary', 'D1690A7AC1.996856090/mail.example.com'), ('report-type', old_val)]) def test_del_param_on_other_header(self): msg = Message() msg.add_header('Content-Disposition', 'attachment', filename='bud.gif') msg.del_param('filename', 'content-disposition') self.assertEqual(msg['content-disposition'], 'attachment') def test_del_param_on_nonexistent_header(self): msg = Message() # Deleting param on empty msg should not raise exception. msg.del_param('filename', 'content-disposition') def test_del_nonexistent_param(self): msg = Message() msg.add_header('Content-Type', 'text/plain', charset='utf-8') existing_header = msg['Content-Type'] msg.del_param('foobar', header='Content-Type') self.assertEqual(msg['Content-Type'], existing_header) def test_set_type(self): eq = self.assertEqual msg = Message() self.assertRaises(ValueError, msg.set_type, 'text') msg.set_type('text/plain') eq(msg['content-type'], 'text/plain') msg.set_param('charset', 'us-ascii') eq(msg['content-type'], 'text/plain; charset="us-ascii"') msg.set_type('text/html') eq(msg['content-type'], 'text/html; charset="us-ascii"') def test_set_type_on_other_header(self): msg = Message() msg['X-Content-Type'] = 'text/plain' msg.set_type('application/octet-stream', 'X-Content-Type') self.assertEqual(msg['x-content-type'], 'application/octet-stream') def test_get_content_type_missing(self): msg = Message() self.assertEqual(msg.get_content_type(), 'text/plain') def test_get_content_type_missing_with_default_type(self): msg = Message() msg.set_default_type('message/rfc822') self.assertEqual(msg.get_content_type(), 'message/rfc822') def test_get_content_type_from_message_implicit(self): msg = self._msgobj('msg_30.txt') self.assertEqual(msg.get_payload(0).get_content_type(), 'message/rfc822') def test_get_content_type_from_message_explicit(self): msg = self._msgobj('msg_28.txt') self.assertEqual(msg.get_payload(0).get_content_type(), 'message/rfc822') def test_get_content_type_from_message_text_plain_implicit(self): msg = self._msgobj('msg_03.txt') self.assertEqual(msg.get_content_type(), 'text/plain') def test_get_content_type_from_message_text_plain_explicit(self): msg = self._msgobj('msg_01.txt') self.assertEqual(msg.get_content_type(), 'text/plain') def test_get_content_maintype_missing(self): msg = Message() self.assertEqual(msg.get_content_maintype(), 'text') def test_get_content_maintype_missing_with_default_type(self): msg = Message() msg.set_default_type('message/rfc822') self.assertEqual(msg.get_content_maintype(), 'message') def test_get_content_maintype_from_message_implicit(self): msg = self._msgobj('msg_30.txt') self.assertEqual(msg.get_payload(0).get_content_maintype(), 'message') def test_get_content_maintype_from_message_explicit(self): msg = self._msgobj('msg_28.txt') self.assertEqual(msg.get_payload(0).get_content_maintype(), 'message') def test_get_content_maintype_from_message_text_plain_implicit(self): msg = self._msgobj('msg_03.txt') self.assertEqual(msg.get_content_maintype(), 'text') def test_get_content_maintype_from_message_text_plain_explicit(self): msg = self._msgobj('msg_01.txt') self.assertEqual(msg.get_content_maintype(), 'text') def test_get_content_subtype_missing(self): msg = Message() self.assertEqual(msg.get_content_subtype(), 'plain') def test_get_content_subtype_missing_with_default_type(self): msg = Message() msg.set_default_type('message/rfc822') self.assertEqual(msg.get_content_subtype(), 'rfc822') def test_get_content_subtype_from_message_implicit(self): msg = self._msgobj('msg_30.txt') self.assertEqual(msg.get_payload(0).get_content_subtype(), 'rfc822') def test_get_content_subtype_from_message_explicit(self): msg = self._msgobj('msg_28.txt') self.assertEqual(msg.get_payload(0).get_content_subtype(), 'rfc822') def test_get_content_subtype_from_message_text_plain_implicit(self): msg = self._msgobj('msg_03.txt') self.assertEqual(msg.get_content_subtype(), 'plain') def test_get_content_subtype_from_message_text_plain_explicit(self): msg = self._msgobj('msg_01.txt') self.assertEqual(msg.get_content_subtype(), 'plain') def test_get_content_maintype_error(self): msg = Message() msg['Content-Type'] = 'no-slash-in-this-string' self.assertEqual(msg.get_content_maintype(), 'text') def test_get_content_subtype_error(self): msg = Message() msg['Content-Type'] = 'no-slash-in-this-string' self.assertEqual(msg.get_content_subtype(), 'plain') def test_replace_header(self): eq = self.assertEqual msg = Message() msg.add_header('First', 'One') msg.add_header('Second', 'Two') msg.add_header('Third', 'Three') eq(msg.keys(), ['First', 'Second', 'Third']) eq(msg.values(), ['One', 'Two', 'Three']) msg.replace_header('Second', 'Twenty') eq(msg.keys(), ['First', 'Second', 'Third']) eq(msg.values(), ['One', 'Twenty', 'Three']) msg.add_header('First', 'Eleven') msg.replace_header('First', 'One Hundred') eq(msg.keys(), ['First', 'Second', 'Third', 'First']) eq(msg.values(), ['One Hundred', 'Twenty', 'Three', 'Eleven']) self.assertRaises(KeyError, msg.replace_header, 'Fourth', 'Missing') def test_get_content_disposition(self): msg = Message() self.assertIsNone(msg.get_content_disposition()) msg.add_header('Content-Disposition', 'attachment', filename='random.avi') self.assertEqual(msg.get_content_disposition(), 'attachment') msg.replace_header('Content-Disposition', 'inline') self.assertEqual(msg.get_content_disposition(), 'inline') msg.replace_header('Content-Disposition', 'InlinE') self.assertEqual(msg.get_content_disposition(), 'inline') # test_defect_handling:test_invalid_chars_in_base64_payload def test_broken_base64_payload(self): x = 'AwDp0P7//y6LwKEAcPa/6Q=9' msg = Message() msg['content-type'] = 'audio/x-midi' msg['content-transfer-encoding'] = 'base64' msg.set_payload(x) self.assertEqual(msg.get_payload(decode=True), (b'\x03\x00\xe9\xd0\xfe\xff\xff.\x8b\xc0' b'\xa1\x00p\xf6\xbf\xe9\x0f')) self.assertIsInstance(msg.defects[0], errors.InvalidBase64CharactersDefect) def test_broken_unicode_payload(self): # This test improves coverage but is not a compliance test. # The behavior in this situation is currently undefined by the API. x = 'this is a br\xf6ken thing to do' msg = Message() msg['content-type'] = 'text/plain' msg['content-transfer-encoding'] = '8bit' msg.set_payload(x) self.assertEqual(msg.get_payload(decode=True), bytes(x, 'raw-unicode-escape')) def test_questionable_bytes_payload(self): # This test improves coverage but is not a compliance test, # since it involves poking inside the black box. x = 'this is a quéstionable thing to do'.encode('utf-8') msg = Message() msg['content-type'] = 'text/plain; charset="utf-8"' msg['content-transfer-encoding'] = '8bit' msg._payload = x self.assertEqual(msg.get_payload(decode=True), x) # Issue 1078919 def test_ascii_add_header(self): msg = Message() msg.add_header('Content-Disposition', 'attachment', filename='bud.gif') self.assertEqual('attachment; filename="bud.gif"', msg['Content-Disposition']) def test_noascii_add_header(self): msg = Message() msg.add_header('Content-Disposition', 'attachment', filename="Fußballer.ppt") self.assertEqual( 'attachment; filename*=utf-8\'\'Fu%C3%9Fballer.ppt', msg['Content-Disposition']) def test_nonascii_add_header_via_triple(self): msg = Message() msg.add_header('Content-Disposition', 'attachment', filename=('iso-8859-1', '', 'Fußballer.ppt')) self.assertEqual( 'attachment; filename*=iso-8859-1\'\'Fu%DFballer.ppt', msg['Content-Disposition']) def test_ascii_add_header_with_tspecial(self): msg = Message() msg.add_header('Content-Disposition', 'attachment', filename="windows [filename].ppt") self.assertEqual( 'attachment; filename="windows [filename].ppt"', msg['Content-Disposition']) def test_nonascii_add_header_with_tspecial(self): msg = Message() msg.add_header('Content-Disposition', 'attachment', filename="Fußballer [filename].ppt") self.assertEqual( "attachment; filename*=utf-8''Fu%C3%9Fballer%20%5Bfilename%5D.ppt", msg['Content-Disposition']) def test_binary_quopri_payload(self): for charset in ('latin-1', 'ascii'): msg = Message() msg['content-type'] = 'text/plain; charset=%s' % charset msg['content-transfer-encoding'] = 'quoted-printable' msg.set_payload(b'foo=e6=96=87bar') self.assertEqual( msg.get_payload(decode=True), b'foo\xe6\x96\x87bar', 'get_payload returns wrong result with charset %s.' % charset) def test_binary_base64_payload(self): for charset in ('latin-1', 'ascii'): msg = Message() msg['content-type'] = 'text/plain; charset=%s' % charset msg['content-transfer-encoding'] = 'base64' msg.set_payload(b'Zm9v5paHYmFy') self.assertEqual( msg.get_payload(decode=True), b'foo\xe6\x96\x87bar', 'get_payload returns wrong result with charset %s.' % charset) def test_binary_uuencode_payload(self): for charset in ('latin-1', 'ascii'): for encoding in ('x-uuencode', 'uuencode', 'uue', 'x-uue'): msg = Message() msg['content-type'] = 'text/plain; charset=%s' % charset msg['content-transfer-encoding'] = encoding msg.set_payload(b"begin 666 -\n)9F]OYI:'8F%R\n \nend\n") self.assertEqual( msg.get_payload(decode=True), b'foo\xe6\x96\x87bar', str(('get_payload returns wrong result ', 'with charset {0} and encoding {1}.')).\ format(charset, encoding)) def test_add_header_with_name_only_param(self): msg = Message() msg.add_header('Content-Disposition', 'inline', foo_bar=None) self.assertEqual("inline; foo-bar", msg['Content-Disposition']) def test_add_header_with_no_value(self): msg = Message() msg.add_header('X-Status', None) self.assertEqual('', msg['X-Status']) # Issue 5871: reject an attempt to embed a header inside a header value # (header injection attack). def test_embedded_header_via_Header_rejected(self): msg = Message() msg['Dummy'] = Header('dummy\nX-Injected-Header: test') self.assertRaises(errors.HeaderParseError, msg.as_string) def test_embedded_header_via_string_rejected(self): msg = Message() msg['Dummy'] = 'dummy\nX-Injected-Header: test' self.assertRaises(errors.HeaderParseError, msg.as_string) def test_unicode_header_defaults_to_utf8_encoding(self): # Issue 14291 m = MIMEText('abc\n') m['Subject'] = 'É test' self.assertEqual(str(m),textwrap.dedent("""\ Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: =?utf-8?q?=C3=89_test?= abc """)) def test_unicode_body_defaults_to_utf8_encoding(self): # Issue 14291 m = MIMEText('É testabc\n') self.assertEqual(str(m),textwrap.dedent("""\ Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: base64 w4kgdGVzdGFiYwo= """)) # Test the email.encoders module class TestEncoders(unittest.TestCase): def test_EncodersEncode_base64(self): with openfile('PyBanner048.gif', 'rb') as fp: bindata = fp.read() mimed = email.mime.image.MIMEImage(bindata) base64ed = mimed.get_payload() # the transfer-encoded body lines should all be <=76 characters lines = base64ed.split('\n') self.assertLessEqual(max([ len(x) for x in lines ]), 76) def test_encode_empty_payload(self): eq = self.assertEqual msg = Message() msg.set_charset('us-ascii') eq(msg['content-transfer-encoding'], '7bit') def test_default_cte(self): eq = self.assertEqual # 7bit data and the default us-ascii _charset msg = MIMEText('hello world') eq(msg['content-transfer-encoding'], '7bit') # Similar, but with 8bit data msg = MIMEText('hello \xf8 world') eq(msg['content-transfer-encoding'], 'base64') # And now with a different charset msg = MIMEText('hello \xf8 world', _charset='iso-8859-1') eq(msg['content-transfer-encoding'], 'quoted-printable') def test_encode7or8bit(self): # Make sure a charset whose input character set is 8bit but # whose output character set is 7bit gets a transfer-encoding # of 7bit. eq = self.assertEqual msg = MIMEText('文\n', _charset='euc-jp') eq(msg['content-transfer-encoding'], '7bit') eq(msg.as_string(), textwrap.dedent("""\ MIME-Version: 1.0 Content-Type: text/plain; charset="iso-2022-jp" Content-Transfer-Encoding: 7bit \x1b$BJ8\x1b(B """)) def test_qp_encode_latin1(self): msg = MIMEText('\xe1\xf6\n', 'text', 'ISO-8859-1') self.assertEqual(str(msg), textwrap.dedent("""\ MIME-Version: 1.0 Content-Type: text/text; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable =E1=F6 """)) def test_qp_encode_non_latin1(self): # Issue 16948 msg = MIMEText('\u017c\n', 'text', 'ISO-8859-2') self.assertEqual(str(msg), textwrap.dedent("""\ MIME-Version: 1.0 Content-Type: text/text; charset="iso-8859-2" Content-Transfer-Encoding: quoted-printable =BF """)) # Test long header wrapping class TestLongHeaders(TestEmailBase): maxDiff = None def test_split_long_continuation(self): eq = self.ndiffAssertEqual msg = email.message_from_string("""\ Subject: bug demonstration \t12345678911234567892123456789312345678941234567895123456789612345678971234567898112345678911234567892123456789112345678911234567892123456789 \tmore text test """) sfp = StringIO() g = Generator(sfp) g.flatten(msg) eq(sfp.getvalue(), """\ Subject: bug demonstration \t12345678911234567892123456789312345678941234567895123456789612345678971234567898112345678911234567892123456789112345678911234567892123456789 \tmore text test """) def test_another_long_almost_unsplittable_header(self): eq = self.ndiffAssertEqual hstr = """\ bug demonstration \t12345678911234567892123456789312345678941234567895123456789612345678971234567898112345678911234567892123456789112345678911234567892123456789 \tmore text""" h = Header(hstr, continuation_ws='\t') eq(h.encode(), """\ bug demonstration \t12345678911234567892123456789312345678941234567895123456789612345678971234567898112345678911234567892123456789112345678911234567892123456789 \tmore text""") h = Header(hstr.replace('\t', ' ')) eq(h.encode(), """\ bug demonstration 12345678911234567892123456789312345678941234567895123456789612345678971234567898112345678911234567892123456789112345678911234567892123456789 more text""") def test_long_nonstring(self): eq = self.ndiffAssertEqual g = Charset("iso-8859-1") cz = Charset("iso-8859-2") utf8 = Charset("utf-8") g_head = (b'Die Mieter treten hier ein werden mit einem Foerderband ' b'komfortabel den Korridor entlang, an s\xfcdl\xfcndischen ' b'Wandgem\xe4lden vorbei, gegen die rotierenden Klingen ' b'bef\xf6rdert. ') cz_head = (b'Finan\xe8ni metropole se hroutily pod tlakem jejich ' b'd\xf9vtipu.. ') utf8_head = ('\u6b63\u78ba\u306b\u8a00\u3046\u3068\u7ffb\u8a33\u306f' '\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002\u4e00' '\u90e8\u306f\u30c9\u30a4\u30c4\u8a9e\u3067\u3059\u304c' '\u3001\u3042\u3068\u306f\u3067\u305f\u3089\u3081\u3067' '\u3059\u3002\u5b9f\u969b\u306b\u306f\u300cWenn ist das ' 'Nunstuck git und Slotermeyer? Ja! Beiherhund das Oder ' 'die Flipperwaldt gersput.\u300d\u3068\u8a00\u3063\u3066' '\u3044\u307e\u3059\u3002') h = Header(g_head, g, header_name='Subject') h.append(cz_head, cz) h.append(utf8_head, utf8) msg = Message() msg['Subject'] = h sfp = StringIO() g = Generator(sfp) g.flatten(msg) eq(sfp.getvalue(), """\ Subject: =?iso-8859-1?q?Die_Mieter_treten_hier_ein_werden_mit_einem_Foerderb?= =?iso-8859-1?q?and_komfortabel_den_Korridor_entlang=2C_an_s=FCdl=FCndischen?= =?iso-8859-1?q?_Wandgem=E4lden_vorbei=2C_gegen_die_rotierenden_Klingen_bef?= =?iso-8859-1?q?=F6rdert=2E_?= =?iso-8859-2?q?Finan=E8ni_metropole_se_hrouti?= =?iso-8859-2?q?ly_pod_tlakem_jejich_d=F9vtipu=2E=2E_?= =?utf-8?b?5q2j56K6?= =?utf-8?b?44Gr6KiA44GG44Go57+76Kiz44Gv44GV44KM44Gm44GE44G+44Gb44KT44CC5LiA?= =?utf-8?b?6YOo44Gv44OJ44Kk44OE6Kqe44Gn44GZ44GM44CB44GC44Go44Gv44Gn44Gf44KJ?= =?utf-8?b?44KB44Gn44GZ44CC5a6f6Zqb44Gr44Gv44CMV2VubiBpc3QgZGFzIE51bnN0dWNr?= =?utf-8?b?IGdpdCB1bmQgU2xvdGVybWV5ZXI/IEphISBCZWloZXJodW5kIGRhcyBPZGVyIGRp?= =?utf-8?b?ZSBGbGlwcGVyd2FsZHQgZ2Vyc3B1dC7jgI3jgajoqIDjgaPjgabjgYTjgb7jgZk=?= =?utf-8?b?44CC?= """) eq(h.encode(maxlinelen=76), """\ =?iso-8859-1?q?Die_Mieter_treten_hier_ein_werden_mit_einem_Foerde?= =?iso-8859-1?q?rband_komfortabel_den_Korridor_entlang=2C_an_s=FCdl=FCndis?= =?iso-8859-1?q?chen_Wandgem=E4lden_vorbei=2C_gegen_die_rotierenden_Klinge?= =?iso-8859-1?q?n_bef=F6rdert=2E_?= =?iso-8859-2?q?Finan=E8ni_metropole_se?= =?iso-8859-2?q?_hroutily_pod_tlakem_jejich_d=F9vtipu=2E=2E_?= =?utf-8?b?5q2j56K644Gr6KiA44GG44Go57+76Kiz44Gv44GV44KM44Gm44GE44G+44Gb?= =?utf-8?b?44KT44CC5LiA6YOo44Gv44OJ44Kk44OE6Kqe44Gn44GZ44GM44CB44GC44Go?= =?utf-8?b?44Gv44Gn44Gf44KJ44KB44Gn44GZ44CC5a6f6Zqb44Gr44Gv44CMV2VubiBp?= =?utf-8?b?c3QgZGFzIE51bnN0dWNrIGdpdCB1bmQgU2xvdGVybWV5ZXI/IEphISBCZWlo?= =?utf-8?b?ZXJodW5kIGRhcyBPZGVyIGRpZSBGbGlwcGVyd2FsZHQgZ2Vyc3B1dC7jgI0=?= =?utf-8?b?44Go6KiA44Gj44Gm44GE44G+44GZ44CC?=""") def test_long_header_encode(self): eq = self.ndiffAssertEqual h = Header('wasnipoop; giraffes="very-long-necked-animals"; ' 'spooge="yummy"; hippos="gargantuan"; marshmallows="gooey"', header_name='X-Foobar-Spoink-Defrobnit') eq(h.encode(), '''\ wasnipoop; giraffes="very-long-necked-animals"; spooge="yummy"; hippos="gargantuan"; marshmallows="gooey"''') def test_long_header_encode_with_tab_continuation_is_just_a_hint(self): eq = self.ndiffAssertEqual h = Header('wasnipoop; giraffes="very-long-necked-animals"; ' 'spooge="yummy"; hippos="gargantuan"; marshmallows="gooey"', header_name='X-Foobar-Spoink-Defrobnit', continuation_ws='\t') eq(h.encode(), '''\ wasnipoop; giraffes="very-long-necked-animals"; spooge="yummy"; hippos="gargantuan"; marshmallows="gooey"''') def test_long_header_encode_with_tab_continuation(self): eq = self.ndiffAssertEqual h = Header('wasnipoop; giraffes="very-long-necked-animals";\t' 'spooge="yummy"; hippos="gargantuan"; marshmallows="gooey"', header_name='X-Foobar-Spoink-Defrobnit', continuation_ws='\t') eq(h.encode(), '''\ wasnipoop; giraffes="very-long-necked-animals"; \tspooge="yummy"; hippos="gargantuan"; marshmallows="gooey"''') def test_header_encode_with_different_output_charset(self): h = Header('文', 'euc-jp') self.assertEqual(h.encode(), "=?iso-2022-jp?b?GyRCSjgbKEI=?=") def test_long_header_encode_with_different_output_charset(self): h = Header(b'test-ja \xa4\xd8\xc5\xea\xb9\xc6\xa4\xb5\xa4\xec\xa4' b'\xbf\xa5\xe1\xa1\xbc\xa5\xeb\xa4\xcf\xbb\xca\xb2\xf1\xbc\xd4' b'\xa4\xce\xbe\xb5\xc7\xa7\xa4\xf2\xc2\xd4\xa4\xc3\xa4\xc6\xa4' b'\xa4\xa4\xde\xa4\xb9'.decode('euc-jp'), 'euc-jp') res = """\ =?iso-2022-jp?b?dGVzdC1qYSAbJEIkWEVqOUYkNSRsJD8lYSE8JWskTztKMnE8VCROPjUbKEI=?= =?iso-2022-jp?b?GyRCRyckckJUJEMkRiQkJF4kORsoQg==?=""" self.assertEqual(h.encode(), res) def test_header_splitter(self): eq = self.ndiffAssertEqual msg = MIMEText('') # It'd be great if we could use add_header() here, but that doesn't # guarantee an order of the parameters. msg['X-Foobar-Spoink-Defrobnit'] = ( 'wasnipoop; giraffes="very-long-necked-animals"; ' 'spooge="yummy"; hippos="gargantuan"; marshmallows="gooey"') sfp = StringIO() g = Generator(sfp) g.flatten(msg) eq(sfp.getvalue(), '''\ Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit X-Foobar-Spoink-Defrobnit: wasnipoop; giraffes="very-long-necked-animals"; spooge="yummy"; hippos="gargantuan"; marshmallows="gooey" ''') def test_no_semis_header_splitter(self): eq = self.ndiffAssertEqual msg = Message() msg['From'] = '[email protected]' msg['References'] = SPACE.join('<%[email protected]>' % i for i in range(10)) msg.set_payload('Test') sfp = StringIO() g = Generator(sfp) g.flatten(msg) eq(sfp.getvalue(), """\ From: [email protected] References: <[email protected]> <[email protected]> <[email protected]> <[email protected]> <[email protected]> <[email protected]> <[email protected]> <[email protected]> <[email protected]> <[email protected]> Test""") def test_last_split_chunk_does_not_fit(self): eq = self.ndiffAssertEqual h = Header('Subject: the first part of this is short, but_the_second' '_part_does_not_fit_within_maxlinelen_and_thus_should_be_on_a_line' '_all_by_itself') eq(h.encode(), """\ Subject: the first part of this is short, but_the_second_part_does_not_fit_within_maxlinelen_and_thus_should_be_on_a_line_all_by_itself""") def test_splittable_leading_char_followed_by_overlong_unsplitable(self): eq = self.ndiffAssertEqual h = Header(', but_the_second' '_part_does_not_fit_within_maxlinelen_and_thus_should_be_on_a_line' '_all_by_itself') eq(h.encode(), """\ , but_the_second_part_does_not_fit_within_maxlinelen_and_thus_should_be_on_a_line_all_by_itself""") def test_multiple_splittable_leading_char_followed_by_overlong_unsplitable(self): eq = self.ndiffAssertEqual h = Header(', , but_the_second' '_part_does_not_fit_within_maxlinelen_and_thus_should_be_on_a_line' '_all_by_itself') eq(h.encode(), """\ , , but_the_second_part_does_not_fit_within_maxlinelen_and_thus_should_be_on_a_line_all_by_itself""") def test_trailing_splitable_on_overlong_unsplitable(self): eq = self.ndiffAssertEqual h = Header('this_part_does_not_fit_within_maxlinelen_and_thus_should_' 'be_on_a_line_all_by_itself;') eq(h.encode(), "this_part_does_not_fit_within_maxlinelen_and_thus_should_" "be_on_a_line_all_by_itself;") def test_trailing_splitable_on_overlong_unsplitable_with_leading_splitable(self): eq = self.ndiffAssertEqual h = Header('; ' 'this_part_does_not_fit_within_maxlinelen_and_thus_should_' 'be_on_a_line_all_by_itself; ') eq(h.encode(), """\ ; this_part_does_not_fit_within_maxlinelen_and_thus_should_be_on_a_line_all_by_itself; """) def test_long_header_with_multiple_sequential_split_chars(self): eq = self.ndiffAssertEqual h = Header('This is a long line that has two whitespaces in a row. ' 'This used to cause truncation of the header when folded') eq(h.encode(), """\ This is a long line that has two whitespaces in a row. This used to cause truncation of the header when folded""") def test_splitter_split_on_punctuation_only_if_fws_with_header(self): eq = self.ndiffAssertEqual h = Header('thisverylongheaderhas;semicolons;and,commas,but' 'they;arenotlegal;fold,points') eq(h.encode(), "thisverylongheaderhas;semicolons;and,commas,butthey;" "arenotlegal;fold,points") def test_leading_splittable_in_the_middle_just_before_overlong_last_part(self): eq = self.ndiffAssertEqual h = Header('this is a test where we need to have more than one line ' 'before; our final line that is just too big to fit;; ' 'this_part_does_not_fit_within_maxlinelen_and_thus_should_' 'be_on_a_line_all_by_itself;') eq(h.encode(), """\ this is a test where we need to have more than one line before; our final line that is just too big to fit;; this_part_does_not_fit_within_maxlinelen_and_thus_should_be_on_a_line_all_by_itself;""") def test_overlong_last_part_followed_by_split_point(self): eq = self.ndiffAssertEqual h = Header('this_part_does_not_fit_within_maxlinelen_and_thus_should_' 'be_on_a_line_all_by_itself ') eq(h.encode(), "this_part_does_not_fit_within_maxlinelen_and_thus_" "should_be_on_a_line_all_by_itself ") def test_multiline_with_overlong_parts_separated_by_two_split_points(self): eq = self.ndiffAssertEqual h = Header('this_is_a__test_where_we_need_to_have_more_than_one_line_' 'before_our_final_line_; ; ' 'this_part_does_not_fit_within_maxlinelen_and_thus_should_' 'be_on_a_line_all_by_itself; ') eq(h.encode(), """\ this_is_a__test_where_we_need_to_have_more_than_one_line_before_our_final_line_; ; this_part_does_not_fit_within_maxlinelen_and_thus_should_be_on_a_line_all_by_itself; """) def test_multiline_with_overlong_last_part_followed_by_split_point(self): eq = self.ndiffAssertEqual h = Header('this is a test where we need to have more than one line ' 'before our final line; ; ' 'this_part_does_not_fit_within_maxlinelen_and_thus_should_' 'be_on_a_line_all_by_itself; ') eq(h.encode(), """\ this is a test where we need to have more than one line before our final line; ; this_part_does_not_fit_within_maxlinelen_and_thus_should_be_on_a_line_all_by_itself; """) def test_long_header_with_whitespace_runs(self): eq = self.ndiffAssertEqual msg = Message() msg['From'] = '[email protected]' msg['References'] = SPACE.join(['<[email protected]> '] * 10) msg.set_payload('Test') sfp = StringIO() g = Generator(sfp) g.flatten(msg) eq(sfp.getvalue(), """\ From: [email protected] References: <[email protected]> <[email protected]> <[email protected]> <[email protected]> <[email protected]> <[email protected]> <[email protected]> <[email protected]> <[email protected]> <[email protected]>\x20\x20 Test""") def test_long_run_with_semi_header_splitter(self): eq = self.ndiffAssertEqual msg = Message() msg['From'] = '[email protected]' msg['References'] = SPACE.join(['<[email protected]>'] * 10) + '; abc' msg.set_payload('Test') sfp = StringIO() g = Generator(sfp) g.flatten(msg) eq(sfp.getvalue(), """\ From: [email protected] References: <[email protected]> <[email protected]> <[email protected]> <[email protected]> <[email protected]> <[email protected]> <[email protected]> <[email protected]> <[email protected]> <[email protected]>; abc Test""") def test_splitter_split_on_punctuation_only_if_fws(self): eq = self.ndiffAssertEqual msg = Message() msg['From'] = '[email protected]' msg['References'] = ('thisverylongheaderhas;semicolons;and,commas,but' 'they;arenotlegal;fold,points') msg.set_payload('Test') sfp = StringIO() g = Generator(sfp) g.flatten(msg) # XXX the space after the header should not be there. eq(sfp.getvalue(), """\ From: [email protected] References:\x20 thisverylongheaderhas;semicolons;and,commas,butthey;arenotlegal;fold,points Test""") def test_no_split_long_header(self): eq = self.ndiffAssertEqual hstr = 'References: ' + 'x' * 80 h = Header(hstr) # These come on two lines because Headers are really field value # classes and don't really know about their field names. eq(h.encode(), """\ References: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx""") h = Header('x' * 80) eq(h.encode(), 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx') def test_splitting_multiple_long_lines(self): eq = self.ndiffAssertEqual hstr = """\ from babylon.socal-raves.org (localhost [127.0.0.1]); by babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81; for <[email protected]>; Sat, 2 Feb 2002 17:00:06 -0800 (PST) \tfrom babylon.socal-raves.org (localhost [127.0.0.1]); by babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81; for <[email protected]>; Sat, 2 Feb 2002 17:00:06 -0800 (PST) \tfrom babylon.socal-raves.org (localhost [127.0.0.1]); by babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81; for <[email protected]>; Sat, 2 Feb 2002 17:00:06 -0800 (PST) """ h = Header(hstr, continuation_ws='\t') eq(h.encode(), """\ from babylon.socal-raves.org (localhost [127.0.0.1]); by babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81; for <[email protected]>; Sat, 2 Feb 2002 17:00:06 -0800 (PST) \tfrom babylon.socal-raves.org (localhost [127.0.0.1]); by babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81; for <[email protected]>; Sat, 2 Feb 2002 17:00:06 -0800 (PST) \tfrom babylon.socal-raves.org (localhost [127.0.0.1]); by babylon.socal-raves.org (Postfix) with ESMTP id B570E51B81; for <[email protected]>; Sat, 2 Feb 2002 17:00:06 -0800 (PST)""") def test_splitting_first_line_only_is_long(self): eq = self.ndiffAssertEqual hstr = """\ from modemcable093.139-201-24.que.mc.videotron.ca ([24.201.139.93] helo=cthulhu.gerg.ca) \tby kronos.mems-exchange.org with esmtp (Exim 4.05) \tid 17k4h5-00034i-00 \tfor [email protected]; Wed, 28 Aug 2002 11:25:20 -0400""" h = Header(hstr, maxlinelen=78, header_name='Received', continuation_ws='\t') eq(h.encode(), """\ from modemcable093.139-201-24.que.mc.videotron.ca ([24.201.139.93] helo=cthulhu.gerg.ca) \tby kronos.mems-exchange.org with esmtp (Exim 4.05) \tid 17k4h5-00034i-00 \tfor [email protected]; Wed, 28 Aug 2002 11:25:20 -0400""") def test_long_8bit_header(self): eq = self.ndiffAssertEqual msg = Message() h = Header('Britische Regierung gibt', 'iso-8859-1', header_name='Subject') h.append('gr\xfcnes Licht f\xfcr Offshore-Windkraftprojekte') eq(h.encode(maxlinelen=76), """\ =?iso-8859-1?q?Britische_Regierung_gibt_gr=FCnes_Licht_f=FCr_Offs?= =?iso-8859-1?q?hore-Windkraftprojekte?=""") msg['Subject'] = h eq(msg.as_string(maxheaderlen=76), """\ Subject: =?iso-8859-1?q?Britische_Regierung_gibt_gr=FCnes_Licht_f=FCr_Offs?= =?iso-8859-1?q?hore-Windkraftprojekte?= """) eq(msg.as_string(maxheaderlen=0), """\ Subject: =?iso-8859-1?q?Britische_Regierung_gibt_gr=FCnes_Licht_f=FCr_Offshore-Windkraftprojekte?= """) def test_long_8bit_header_no_charset(self): eq = self.ndiffAssertEqual msg = Message() header_string = ('Britische Regierung gibt gr\xfcnes Licht ' 'f\xfcr Offshore-Windkraftprojekte ' '<[email protected]>') msg['Reply-To'] = header_string eq(msg.as_string(maxheaderlen=78), """\ Reply-To: =?utf-8?q?Britische_Regierung_gibt_gr=C3=BCnes_Licht_f=C3=BCr_Offs?= =?utf-8?q?hore-Windkraftprojekte_=3Ca-very-long-address=40example=2Ecom=3E?= """) msg = Message() msg['Reply-To'] = Header(header_string, header_name='Reply-To') eq(msg.as_string(maxheaderlen=78), """\ Reply-To: =?utf-8?q?Britische_Regierung_gibt_gr=C3=BCnes_Licht_f=C3=BCr_Offs?= =?utf-8?q?hore-Windkraftprojekte_=3Ca-very-long-address=40example=2Ecom=3E?= """) def test_long_to_header(self): eq = self.ndiffAssertEqual to = ('"Someone Test #A" <[email protected]>,' '<[email protected]>, ' '"Someone Test #B" <[email protected]>, ' '"Someone Test #C" <[email protected]>, ' '"Someone Test #D" <[email protected]>') msg = Message() msg['To'] = to eq(msg.as_string(maxheaderlen=78), '''\ To: "Someone Test #A" <[email protected]>,<[email protected]>, "Someone Test #B" <[email protected]>, "Someone Test #C" <[email protected]>, "Someone Test #D" <[email protected]> ''') def test_long_line_after_append(self): eq = self.ndiffAssertEqual s = 'This is an example of string which has almost the limit of header length.' h = Header(s) h.append('Add another line.') eq(h.encode(maxlinelen=76), """\ This is an example of string which has almost the limit of header length. Add another line.""") def test_shorter_line_with_append(self): eq = self.ndiffAssertEqual s = 'This is a shorter line.' h = Header(s) h.append('Add another sentence. (Surprise?)') eq(h.encode(), 'This is a shorter line. Add another sentence. (Surprise?)') def test_long_field_name(self): eq = self.ndiffAssertEqual fn = 'X-Very-Very-Very-Long-Header-Name' gs = ('Die Mieter treten hier ein werden mit einem Foerderband ' 'komfortabel den Korridor entlang, an s\xfcdl\xfcndischen ' 'Wandgem\xe4lden vorbei, gegen die rotierenden Klingen ' 'bef\xf6rdert. ') h = Header(gs, 'iso-8859-1', header_name=fn) # BAW: this seems broken because the first line is too long eq(h.encode(maxlinelen=76), """\ =?iso-8859-1?q?Die_Mieter_treten_hier_e?= =?iso-8859-1?q?in_werden_mit_einem_Foerderband_komfortabel_den_Korridor_e?= =?iso-8859-1?q?ntlang=2C_an_s=FCdl=FCndischen_Wandgem=E4lden_vorbei=2C_ge?= =?iso-8859-1?q?gen_die_rotierenden_Klingen_bef=F6rdert=2E_?=""") def test_long_received_header(self): h = ('from FOO.TLD (vizworld.acl.foo.tld [123.452.678.9]) ' 'by hrothgar.la.mastaler.com (tmda-ofmipd) with ESMTP; ' 'Wed, 05 Mar 2003 18:10:18 -0700') msg = Message() msg['Received-1'] = Header(h, continuation_ws='\t') msg['Received-2'] = h # This should be splitting on spaces not semicolons. self.ndiffAssertEqual(msg.as_string(maxheaderlen=78), """\ Received-1: from FOO.TLD (vizworld.acl.foo.tld [123.452.678.9]) by hrothgar.la.mastaler.com (tmda-ofmipd) with ESMTP; Wed, 05 Mar 2003 18:10:18 -0700 Received-2: from FOO.TLD (vizworld.acl.foo.tld [123.452.678.9]) by hrothgar.la.mastaler.com (tmda-ofmipd) with ESMTP; Wed, 05 Mar 2003 18:10:18 -0700 """) def test_string_headerinst_eq(self): h = ('<[email protected].' 'tu-muenchen.de> (David Bremner\'s message of ' '"Thu, 6 Mar 2003 13:58:21 +0100")') msg = Message() msg['Received-1'] = Header(h, header_name='Received-1', continuation_ws='\t') msg['Received-2'] = h # XXX The space after the ':' should not be there. self.ndiffAssertEqual(msg.as_string(maxheaderlen=78), """\ Received-1:\x20 <15975.17901.207240.414604@sgigritzmann1.mathematik.tu-muenchen.de> (David Bremner's message of \"Thu, 6 Mar 2003 13:58:21 +0100\") Received-2:\x20 <15975.17901.207240.414604@sgigritzmann1.mathematik.tu-muenchen.de> (David Bremner's message of \"Thu, 6 Mar 2003 13:58:21 +0100\") """) def test_long_unbreakable_lines_with_continuation(self): eq = self.ndiffAssertEqual msg = Message() t = """\ iVBORw0KGgoAAAANSUhEUgAAADAAAAAwBAMAAAClLOS0AAAAGFBMVEUAAAAkHiJeRUIcGBi9 locQDQ4zJykFBAXJfWDjAAACYUlEQVR4nF2TQY/jIAyFc6lydlG5x8Nyp1Y69wj1PN2I5gzp""" msg['Face-1'] = t msg['Face-2'] = Header(t, header_name='Face-2') msg['Face-3'] = ' ' + t # XXX This splitting is all wrong. It the first value line should be # snug against the field name or the space after the header not there. eq(msg.as_string(maxheaderlen=78), """\ Face-1:\x20 iVBORw0KGgoAAAANSUhEUgAAADAAAAAwBAMAAAClLOS0AAAAGFBMVEUAAAAkHiJeRUIcGBi9 locQDQ4zJykFBAXJfWDjAAACYUlEQVR4nF2TQY/jIAyFc6lydlG5x8Nyp1Y69wj1PN2I5gzp Face-2:\x20 iVBORw0KGgoAAAANSUhEUgAAADAAAAAwBAMAAAClLOS0AAAAGFBMVEUAAAAkHiJeRUIcGBi9 locQDQ4zJykFBAXJfWDjAAACYUlEQVR4nF2TQY/jIAyFc6lydlG5x8Nyp1Y69wj1PN2I5gzp Face-3:\x20 iVBORw0KGgoAAAANSUhEUgAAADAAAAAwBAMAAAClLOS0AAAAGFBMVEUAAAAkHiJeRUIcGBi9 locQDQ4zJykFBAXJfWDjAAACYUlEQVR4nF2TQY/jIAyFc6lydlG5x8Nyp1Y69wj1PN2I5gzp """) def test_another_long_multiline_header(self): eq = self.ndiffAssertEqual m = ('Received: from siimage.com ' '([172.25.1.3]) by zima.siliconimage.com with ' 'Microsoft SMTPSVC(5.0.2195.4905); ' 'Wed, 16 Oct 2002 07:41:11 -0700') msg = email.message_from_string(m) eq(msg.as_string(maxheaderlen=78), '''\ Received: from siimage.com ([172.25.1.3]) by zima.siliconimage.com with Microsoft SMTPSVC(5.0.2195.4905); Wed, 16 Oct 2002 07:41:11 -0700 ''') def test_long_lines_with_different_header(self): eq = self.ndiffAssertEqual h = ('List-Unsubscribe: ' '<http://lists.sourceforge.net/lists/listinfo/spamassassin-talk>,' ' <mailto:[email protected]' '?subject=unsubscribe>') msg = Message() msg['List'] = h msg['List'] = Header(h, header_name='List') eq(msg.as_string(maxheaderlen=78), """\ List: List-Unsubscribe: <http://lists.sourceforge.net/lists/listinfo/spamassassin-talk>, <mailto:[email protected]?subject=unsubscribe> List: List-Unsubscribe: <http://lists.sourceforge.net/lists/listinfo/spamassassin-talk>, <mailto:[email protected]?subject=unsubscribe> """) def test_long_rfc2047_header_with_embedded_fws(self): h = Header(textwrap.dedent("""\ We're going to pretend this header is in a non-ascii character set \tto see if line wrapping with encoded words and embedded folding white space works"""), charset='utf-8', header_name='Test') self.assertEqual(h.encode()+'\n', textwrap.dedent("""\ =?utf-8?q?We=27re_going_to_pretend_this_header_is_in_a_non-ascii_chara?= =?utf-8?q?cter_set?= =?utf-8?q?_to_see_if_line_wrapping_with_encoded_words_and_embedded?= =?utf-8?q?_folding_white_space_works?=""")+'\n') # Test mangling of "From " lines in the body of a message class TestFromMangling(unittest.TestCase): def setUp(self): self.msg = Message() self.msg['From'] = '[email protected]' self.msg.set_payload("""\ From the desk of A.A.A.: Blah blah blah """) def test_mangled_from(self): s = StringIO() g = Generator(s, mangle_from_=True) g.flatten(self.msg) self.assertEqual(s.getvalue(), """\ From: [email protected] >From the desk of A.A.A.: Blah blah blah """) def test_dont_mangle_from(self): s = StringIO() g = Generator(s, mangle_from_=False) g.flatten(self.msg) self.assertEqual(s.getvalue(), """\ From: [email protected] From the desk of A.A.A.: Blah blah blah """) def test_mangle_from_in_preamble_and_epilog(self): s = StringIO() g = Generator(s, mangle_from_=True) msg = email.message_from_string(textwrap.dedent("""\ From: [email protected] Mime-Version: 1.0 Content-Type: multipart/mixed; boundary=XXX From somewhere unknown --XXX Content-Type: text/plain foo --XXX-- From somewhere unknowable """)) g.flatten(msg) self.assertEqual(len([1 for x in s.getvalue().split('\n') if x.startswith('>From ')]), 2) def test_mangled_from_with_bad_bytes(self): source = textwrap.dedent("""\ Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 8bit From: [email protected] """).encode('utf-8') msg = email.message_from_bytes(source + b'From R\xc3\xb6lli\n') b = BytesIO() g = BytesGenerator(b, mangle_from_=True) g.flatten(msg) self.assertEqual(b.getvalue(), source + b'>From R\xc3\xb6lli\n') # Test the basic MIMEAudio class class TestMIMEAudio(unittest.TestCase): def setUp(self): with openfile('audiotest.au', 'rb') as fp: self._audiodata = fp.read() self._au = MIMEAudio(self._audiodata) def test_guess_minor_type(self): self.assertEqual(self._au.get_content_type(), 'audio/basic') def test_encoding(self): payload = self._au.get_payload() self.assertEqual(base64.decodebytes(bytes(payload, 'ascii')), self._audiodata) def test_checkSetMinor(self): au = MIMEAudio(self._audiodata, 'fish') self.assertEqual(au.get_content_type(), 'audio/fish') def test_add_header(self): eq = self.assertEqual self._au.add_header('Content-Disposition', 'attachment', filename='audiotest.au') eq(self._au['content-disposition'], 'attachment; filename="audiotest.au"') eq(self._au.get_params(header='content-disposition'), [('attachment', ''), ('filename', 'audiotest.au')]) eq(self._au.get_param('filename', header='content-disposition'), 'audiotest.au') missing = [] eq(self._au.get_param('attachment', header='content-disposition'), '') self.assertIs(self._au.get_param('foo', failobj=missing, header='content-disposition'), missing) # Try some missing stuff self.assertIs(self._au.get_param('foobar', missing), missing) self.assertIs(self._au.get_param('attachment', missing, header='foobar'), missing) # Test the basic MIMEImage class class TestMIMEImage(unittest.TestCase): def setUp(self): with openfile('PyBanner048.gif', 'rb') as fp: self._imgdata = fp.read() self._im = MIMEImage(self._imgdata) def test_guess_minor_type(self): self.assertEqual(self._im.get_content_type(), 'image/gif') def test_encoding(self): payload = self._im.get_payload() self.assertEqual(base64.decodebytes(bytes(payload, 'ascii')), self._imgdata) def test_checkSetMinor(self): im = MIMEImage(self._imgdata, 'fish') self.assertEqual(im.get_content_type(), 'image/fish') def test_add_header(self): eq = self.assertEqual self._im.add_header('Content-Disposition', 'attachment', filename='dingusfish.gif') eq(self._im['content-disposition'], 'attachment; filename="dingusfish.gif"') eq(self._im.get_params(header='content-disposition'), [('attachment', ''), ('filename', 'dingusfish.gif')]) eq(self._im.get_param('filename', header='content-disposition'), 'dingusfish.gif') missing = [] eq(self._im.get_param('attachment', header='content-disposition'), '') self.assertIs(self._im.get_param('foo', failobj=missing, header='content-disposition'), missing) # Try some missing stuff self.assertIs(self._im.get_param('foobar', missing), missing) self.assertIs(self._im.get_param('attachment', missing, header='foobar'), missing) # Test the basic MIMEApplication class class TestMIMEApplication(unittest.TestCase): def test_headers(self): eq = self.assertEqual msg = MIMEApplication(b'\xfa\xfb\xfc\xfd\xfe\xff') eq(msg.get_content_type(), 'application/octet-stream') eq(msg['content-transfer-encoding'], 'base64') def test_body(self): eq = self.assertEqual bytesdata = b'\xfa\xfb\xfc\xfd\xfe\xff' msg = MIMEApplication(bytesdata) # whitespace in the cte encoded block is RFC-irrelevant. eq(msg.get_payload().strip(), '+vv8/f7/') eq(msg.get_payload(decode=True), bytesdata) def test_binary_body_with_encode_7or8bit(self): # Issue 17171. bytesdata = b'\xfa\xfb\xfc\xfd\xfe\xff' msg = MIMEApplication(bytesdata, _encoder=encoders.encode_7or8bit) # Treated as a string, this will be invalid code points. self.assertEqual(msg.get_payload(), '\uFFFD' * len(bytesdata)) self.assertEqual(msg.get_payload(decode=True), bytesdata) self.assertEqual(msg['Content-Transfer-Encoding'], '8bit') s = BytesIO() g = BytesGenerator(s) g.flatten(msg) wireform = s.getvalue() msg2 = email.message_from_bytes(wireform) self.assertEqual(msg.get_payload(), '\uFFFD' * len(bytesdata)) self.assertEqual(msg2.get_payload(decode=True), bytesdata) self.assertEqual(msg2['Content-Transfer-Encoding'], '8bit') def test_binary_body_with_encode_noop(self): # Issue 16564: This does not produce an RFC valid message, since to be # valid it should have a CTE of binary. But the below works in # Python2, and is documented as working this way. bytesdata = b'\xfa\xfb\xfc\xfd\xfe\xff' msg = MIMEApplication(bytesdata, _encoder=encoders.encode_noop) # Treated as a string, this will be invalid code points. self.assertEqual(msg.get_payload(), '\uFFFD' * len(bytesdata)) self.assertEqual(msg.get_payload(decode=True), bytesdata) s = BytesIO() g = BytesGenerator(s) g.flatten(msg) wireform = s.getvalue() msg2 = email.message_from_bytes(wireform) self.assertEqual(msg.get_payload(), '\uFFFD' * len(bytesdata)) self.assertEqual(msg2.get_payload(decode=True), bytesdata) def test_binary_body_with_unicode_linend_encode_noop(self): # Issue 19003: This is a variation on #16564. bytesdata = b'\x0b\xfa\xfb\xfc\xfd\xfe\xff' msg = MIMEApplication(bytesdata, _encoder=encoders.encode_noop) self.assertEqual(msg.get_payload(decode=True), bytesdata) s = BytesIO() g = BytesGenerator(s) g.flatten(msg) wireform = s.getvalue() msg2 = email.message_from_bytes(wireform) self.assertEqual(msg2.get_payload(decode=True), bytesdata) def test_binary_body_with_encode_quopri(self): # Issue 14360. bytesdata = b'\xfa\xfb\xfc\xfd\xfe\xff ' msg = MIMEApplication(bytesdata, _encoder=encoders.encode_quopri) self.assertEqual(msg.get_payload(), '=FA=FB=FC=FD=FE=FF=20') self.assertEqual(msg.get_payload(decode=True), bytesdata) self.assertEqual(msg['Content-Transfer-Encoding'], 'quoted-printable') s = BytesIO() g = BytesGenerator(s) g.flatten(msg) wireform = s.getvalue() msg2 = email.message_from_bytes(wireform) self.assertEqual(msg.get_payload(), '=FA=FB=FC=FD=FE=FF=20') self.assertEqual(msg2.get_payload(decode=True), bytesdata) self.assertEqual(msg2['Content-Transfer-Encoding'], 'quoted-printable') def test_binary_body_with_encode_base64(self): bytesdata = b'\xfa\xfb\xfc\xfd\xfe\xff' msg = MIMEApplication(bytesdata, _encoder=encoders.encode_base64) self.assertEqual(msg.get_payload(), '+vv8/f7/\n') self.assertEqual(msg.get_payload(decode=True), bytesdata) s = BytesIO() g = BytesGenerator(s) g.flatten(msg) wireform = s.getvalue() msg2 = email.message_from_bytes(wireform) self.assertEqual(msg.get_payload(), '+vv8/f7/\n') self.assertEqual(msg2.get_payload(decode=True), bytesdata) # Test the basic MIMEText class class TestMIMEText(unittest.TestCase): def setUp(self): self._msg = MIMEText('hello there') def test_types(self): eq = self.assertEqual eq(self._msg.get_content_type(), 'text/plain') eq(self._msg.get_param('charset'), 'us-ascii') missing = [] self.assertIs(self._msg.get_param('foobar', missing), missing) self.assertIs(self._msg.get_param('charset', missing, header='foobar'), missing) def test_payload(self): self.assertEqual(self._msg.get_payload(), 'hello there') self.assertFalse(self._msg.is_multipart()) def test_charset(self): eq = self.assertEqual msg = MIMEText('hello there', _charset='us-ascii') eq(msg.get_charset().input_charset, 'us-ascii') eq(msg['content-type'], 'text/plain; charset="us-ascii"') # Also accept a Charset instance charset = Charset('utf-8') charset.body_encoding = None msg = MIMEText('hello there', _charset=charset) eq(msg.get_charset().input_charset, 'utf-8') eq(msg['content-type'], 'text/plain; charset="utf-8"') eq(msg.get_payload(), 'hello there') def test_7bit_input(self): eq = self.assertEqual msg = MIMEText('hello there', _charset='us-ascii') eq(msg.get_charset().input_charset, 'us-ascii') eq(msg['content-type'], 'text/plain; charset="us-ascii"') def test_7bit_input_no_charset(self): eq = self.assertEqual msg = MIMEText('hello there') eq(msg.get_charset(), 'us-ascii') eq(msg['content-type'], 'text/plain; charset="us-ascii"') self.assertIn('hello there', msg.as_string()) def test_utf8_input(self): teststr = '\u043a\u0438\u0440\u0438\u043b\u0438\u0446\u0430' eq = self.assertEqual msg = MIMEText(teststr, _charset='utf-8') eq(msg.get_charset().output_charset, 'utf-8') eq(msg['content-type'], 'text/plain; charset="utf-8"') eq(msg.get_payload(decode=True), teststr.encode('utf-8')) @unittest.skip("can't fix because of backward compat in email5, " "will fix in email6") def test_utf8_input_no_charset(self): teststr = '\u043a\u0438\u0440\u0438\u043b\u0438\u0446\u0430' self.assertRaises(UnicodeEncodeError, MIMEText, teststr) # Test complicated multipart/* messages class TestMultipart(TestEmailBase): def setUp(self): with openfile('PyBanner048.gif', 'rb') as fp: data = fp.read() container = MIMEBase('multipart', 'mixed', boundary='BOUNDARY') image = MIMEImage(data, name='dingusfish.gif') image.add_header('content-disposition', 'attachment', filename='dingusfish.gif') intro = MIMEText('''\ Hi there, This is the dingus fish. ''') container.attach(intro) container.attach(image) container['From'] = 'Barry <[email protected]>' container['To'] = 'Dingus Lovers <[email protected]>' container['Subject'] = 'Here is your dingus fish' now = 987809702.54848599 timetuple = time.localtime(now) if timetuple[-1] == 0: tzsecs = time.timezone else: tzsecs = time.altzone if tzsecs > 0: sign = '-' else: sign = '+' tzoffset = ' %s%04d' % (sign, tzsecs / 36) container['Date'] = time.strftime( '%a, %d %b %Y %H:%M:%S', time.localtime(now)) + tzoffset self._msg = container self._im = image self._txt = intro def test_hierarchy(self): # convenience eq = self.assertEqual raises = self.assertRaises # tests m = self._msg self.assertTrue(m.is_multipart()) eq(m.get_content_type(), 'multipart/mixed') eq(len(m.get_payload()), 2) raises(IndexError, m.get_payload, 2) m0 = m.get_payload(0) m1 = m.get_payload(1) self.assertIs(m0, self._txt) self.assertIs(m1, self._im) eq(m.get_payload(), [m0, m1]) self.assertFalse(m0.is_multipart()) self.assertFalse(m1.is_multipart()) def test_empty_multipart_idempotent(self): text = """\ Content-Type: multipart/mixed; boundary="BOUNDARY" MIME-Version: 1.0 Subject: A subject To: [email protected] From: [email protected] --BOUNDARY --BOUNDARY-- """ msg = Parser().parsestr(text) self.ndiffAssertEqual(text, msg.as_string()) def test_no_parts_in_a_multipart_with_none_epilogue(self): outer = MIMEBase('multipart', 'mixed') outer['Subject'] = 'A subject' outer['To'] = '[email protected]' outer['From'] = '[email protected]' outer.set_boundary('BOUNDARY') self.ndiffAssertEqual(outer.as_string(), '''\ Content-Type: multipart/mixed; boundary="BOUNDARY" MIME-Version: 1.0 Subject: A subject To: [email protected] From: [email protected] --BOUNDARY --BOUNDARY-- ''') def test_no_parts_in_a_multipart_with_empty_epilogue(self): outer = MIMEBase('multipart', 'mixed') outer['Subject'] = 'A subject' outer['To'] = '[email protected]' outer['From'] = '[email protected]' outer.preamble = '' outer.epilogue = '' outer.set_boundary('BOUNDARY') self.ndiffAssertEqual(outer.as_string(), '''\ Content-Type: multipart/mixed; boundary="BOUNDARY" MIME-Version: 1.0 Subject: A subject To: [email protected] From: [email protected] --BOUNDARY --BOUNDARY-- ''') def test_one_part_in_a_multipart(self): eq = self.ndiffAssertEqual outer = MIMEBase('multipart', 'mixed') outer['Subject'] = 'A subject' outer['To'] = '[email protected]' outer['From'] = '[email protected]' outer.set_boundary('BOUNDARY') msg = MIMEText('hello world') outer.attach(msg) eq(outer.as_string(), '''\ Content-Type: multipart/mixed; boundary="BOUNDARY" MIME-Version: 1.0 Subject: A subject To: [email protected] From: [email protected] --BOUNDARY Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit hello world --BOUNDARY-- ''') def test_seq_parts_in_a_multipart_with_empty_preamble(self): eq = self.ndiffAssertEqual outer = MIMEBase('multipart', 'mixed') outer['Subject'] = 'A subject' outer['To'] = '[email protected]' outer['From'] = '[email protected]' outer.preamble = '' msg = MIMEText('hello world') outer.attach(msg) outer.set_boundary('BOUNDARY') eq(outer.as_string(), '''\ Content-Type: multipart/mixed; boundary="BOUNDARY" MIME-Version: 1.0 Subject: A subject To: [email protected] From: [email protected] --BOUNDARY Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit hello world --BOUNDARY-- ''') def test_seq_parts_in_a_multipart_with_none_preamble(self): eq = self.ndiffAssertEqual outer = MIMEBase('multipart', 'mixed') outer['Subject'] = 'A subject' outer['To'] = '[email protected]' outer['From'] = '[email protected]' outer.preamble = None msg = MIMEText('hello world') outer.attach(msg) outer.set_boundary('BOUNDARY') eq(outer.as_string(), '''\ Content-Type: multipart/mixed; boundary="BOUNDARY" MIME-Version: 1.0 Subject: A subject To: [email protected] From: [email protected] --BOUNDARY Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit hello world --BOUNDARY-- ''') def test_seq_parts_in_a_multipart_with_none_epilogue(self): eq = self.ndiffAssertEqual outer = MIMEBase('multipart', 'mixed') outer['Subject'] = 'A subject' outer['To'] = '[email protected]' outer['From'] = '[email protected]' outer.epilogue = None msg = MIMEText('hello world') outer.attach(msg) outer.set_boundary('BOUNDARY') eq(outer.as_string(), '''\ Content-Type: multipart/mixed; boundary="BOUNDARY" MIME-Version: 1.0 Subject: A subject To: [email protected] From: [email protected] --BOUNDARY Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit hello world --BOUNDARY-- ''') def test_seq_parts_in_a_multipart_with_empty_epilogue(self): eq = self.ndiffAssertEqual outer = MIMEBase('multipart', 'mixed') outer['Subject'] = 'A subject' outer['To'] = '[email protected]' outer['From'] = '[email protected]' outer.epilogue = '' msg = MIMEText('hello world') outer.attach(msg) outer.set_boundary('BOUNDARY') eq(outer.as_string(), '''\ Content-Type: multipart/mixed; boundary="BOUNDARY" MIME-Version: 1.0 Subject: A subject To: [email protected] From: [email protected] --BOUNDARY Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit hello world --BOUNDARY-- ''') def test_seq_parts_in_a_multipart_with_nl_epilogue(self): eq = self.ndiffAssertEqual outer = MIMEBase('multipart', 'mixed') outer['Subject'] = 'A subject' outer['To'] = '[email protected]' outer['From'] = '[email protected]' outer.epilogue = '\n' msg = MIMEText('hello world') outer.attach(msg) outer.set_boundary('BOUNDARY') eq(outer.as_string(), '''\ Content-Type: multipart/mixed; boundary="BOUNDARY" MIME-Version: 1.0 Subject: A subject To: [email protected] From: [email protected] --BOUNDARY Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit hello world --BOUNDARY-- ''') def test_message_external_body(self): eq = self.assertEqual msg = self._msgobj('msg_36.txt') eq(len(msg.get_payload()), 2) msg1 = msg.get_payload(1) eq(msg1.get_content_type(), 'multipart/alternative') eq(len(msg1.get_payload()), 2) for subpart in msg1.get_payload(): eq(subpart.get_content_type(), 'message/external-body') eq(len(subpart.get_payload()), 1) subsubpart = subpart.get_payload(0) eq(subsubpart.get_content_type(), 'text/plain') def test_double_boundary(self): # msg_37.txt is a multipart that contains two dash-boundary's in a # row. Our interpretation of RFC 2046 calls for ignoring the second # and subsequent boundaries. msg = self._msgobj('msg_37.txt') self.assertEqual(len(msg.get_payload()), 3) def test_nested_inner_contains_outer_boundary(self): eq = self.ndiffAssertEqual # msg_38.txt has an inner part that contains outer boundaries. My # interpretation of RFC 2046 (based on sections 5.1 and 5.1.2) say # these are illegal and should be interpreted as unterminated inner # parts. msg = self._msgobj('msg_38.txt') sfp = StringIO() iterators._structure(msg, sfp) eq(sfp.getvalue(), """\ multipart/mixed multipart/mixed multipart/alternative text/plain text/plain text/plain text/plain """) def test_nested_with_same_boundary(self): eq = self.ndiffAssertEqual # msg 39.txt is similarly evil in that it's got inner parts that use # the same boundary as outer parts. Again, I believe the way this is # parsed is closest to the spirit of RFC 2046 msg = self._msgobj('msg_39.txt') sfp = StringIO() iterators._structure(msg, sfp) eq(sfp.getvalue(), """\ multipart/mixed multipart/mixed multipart/alternative application/octet-stream application/octet-stream text/plain """) def test_boundary_in_non_multipart(self): msg = self._msgobj('msg_40.txt') self.assertEqual(msg.as_string(), '''\ MIME-Version: 1.0 Content-Type: text/html; boundary="--961284236552522269" ----961284236552522269 Content-Type: text/html; Content-Transfer-Encoding: 7Bit <html></html> ----961284236552522269-- ''') def test_boundary_with_leading_space(self): eq = self.assertEqual msg = email.message_from_string('''\ MIME-Version: 1.0 Content-Type: multipart/mixed; boundary=" XXXX" -- XXXX Content-Type: text/plain -- XXXX Content-Type: text/plain -- XXXX-- ''') self.assertTrue(msg.is_multipart()) eq(msg.get_boundary(), ' XXXX') eq(len(msg.get_payload()), 2) def test_boundary_without_trailing_newline(self): m = Parser().parsestr("""\ Content-Type: multipart/mixed; boundary="===============0012394164==" MIME-Version: 1.0 --===============0012394164== Content-Type: image/file1.jpg MIME-Version: 1.0 Content-Transfer-Encoding: base64 YXNkZg== --===============0012394164==--""") self.assertEqual(m.get_payload(0).get_payload(), 'YXNkZg==') def test_mimebase_default_policy(self): m = MIMEBase('multipart', 'mixed') self.assertIs(m.policy, email.policy.compat32) def test_mimebase_custom_policy(self): m = MIMEBase('multipart', 'mixed', policy=email.policy.default) self.assertIs(m.policy, email.policy.default) # Test some badly formatted messages class TestNonConformant(TestEmailBase): def test_parse_missing_minor_type(self): eq = self.assertEqual msg = self._msgobj('msg_14.txt') eq(msg.get_content_type(), 'text/plain') eq(msg.get_content_maintype(), 'text') eq(msg.get_content_subtype(), 'plain') # test_defect_handling def test_same_boundary_inner_outer(self): msg = self._msgobj('msg_15.txt') # XXX We can probably eventually do better inner = msg.get_payload(0) self.assertTrue(hasattr(inner, 'defects')) self.assertEqual(len(inner.defects), 1) self.assertIsInstance(inner.defects[0], errors.StartBoundaryNotFoundDefect) # test_defect_handling def test_multipart_no_boundary(self): msg = self._msgobj('msg_25.txt') self.assertIsInstance(msg.get_payload(), str) self.assertEqual(len(msg.defects), 2) self.assertIsInstance(msg.defects[0], errors.NoBoundaryInMultipartDefect) self.assertIsInstance(msg.defects[1], errors.MultipartInvariantViolationDefect) multipart_msg = textwrap.dedent("""\ Date: Wed, 14 Nov 2007 12:56:23 GMT From: [email protected] To: [email protected] Subject: Content-Transfer-Encoding: base64 and multipart MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="===============3344438784458119861=="{} --===============3344438784458119861== Content-Type: text/plain Test message --===============3344438784458119861== Content-Type: application/octet-stream Content-Transfer-Encoding: base64 YWJj --===============3344438784458119861==-- """) # test_defect_handling def test_multipart_invalid_cte(self): msg = self._str_msg( self.multipart_msg.format("\nContent-Transfer-Encoding: base64")) self.assertEqual(len(msg.defects), 1) self.assertIsInstance(msg.defects[0], errors.InvalidMultipartContentTransferEncodingDefect) # test_defect_handling def test_multipart_no_cte_no_defect(self): msg = self._str_msg(self.multipart_msg.format('')) self.assertEqual(len(msg.defects), 0) # test_defect_handling def test_multipart_valid_cte_no_defect(self): for cte in ('7bit', '8bit', 'BINary'): msg = self._str_msg( self.multipart_msg.format( "\nContent-Transfer-Encoding: {}".format(cte))) self.assertEqual(len(msg.defects), 0) # test_headerregistry.TestContentTyopeHeader invalid_1 and invalid_2. def test_invalid_content_type(self): eq = self.assertEqual neq = self.ndiffAssertEqual msg = Message() # RFC 2045, $5.2 says invalid yields text/plain msg['Content-Type'] = 'text' eq(msg.get_content_maintype(), 'text') eq(msg.get_content_subtype(), 'plain') eq(msg.get_content_type(), 'text/plain') # Clear the old value and try something /really/ invalid del msg['content-type'] msg['Content-Type'] = 'foo' eq(msg.get_content_maintype(), 'text') eq(msg.get_content_subtype(), 'plain') eq(msg.get_content_type(), 'text/plain') # Still, make sure that the message is idempotently generated s = StringIO() g = Generator(s) g.flatten(msg) neq(s.getvalue(), 'Content-Type: foo\n\n') def test_no_start_boundary(self): eq = self.ndiffAssertEqual msg = self._msgobj('msg_31.txt') eq(msg.get_payload(), """\ --BOUNDARY Content-Type: text/plain message 1 --BOUNDARY Content-Type: text/plain message 2 --BOUNDARY-- """) def test_no_separating_blank_line(self): eq = self.ndiffAssertEqual msg = self._msgobj('msg_35.txt') eq(msg.as_string(), """\ From: [email protected] To: [email protected] Subject: here's something interesting counter to RFC 2822, there's no separating newline here """) # test_defect_handling def test_lying_multipart(self): msg = self._msgobj('msg_41.txt') self.assertTrue(hasattr(msg, 'defects')) self.assertEqual(len(msg.defects), 2) self.assertIsInstance(msg.defects[0], errors.NoBoundaryInMultipartDefect) self.assertIsInstance(msg.defects[1], errors.MultipartInvariantViolationDefect) # test_defect_handling def test_missing_start_boundary(self): outer = self._msgobj('msg_42.txt') # The message structure is: # # multipart/mixed # text/plain # message/rfc822 # multipart/mixed [*] # # [*] This message is missing its start boundary bad = outer.get_payload(1).get_payload(0) self.assertEqual(len(bad.defects), 1) self.assertIsInstance(bad.defects[0], errors.StartBoundaryNotFoundDefect) # test_defect_handling def test_first_line_is_continuation_header(self): eq = self.assertEqual m = ' Line 1\nSubject: test\n\nbody' msg = email.message_from_string(m) eq(msg.keys(), ['Subject']) eq(msg.get_payload(), 'body') eq(len(msg.defects), 1) self.assertDefectsEqual(msg.defects, [errors.FirstHeaderLineIsContinuationDefect]) eq(msg.defects[0].line, ' Line 1\n') # test_defect_handling def test_missing_header_body_separator(self): # Our heuristic if we see a line that doesn't look like a header (no # leading whitespace but no ':') is to assume that the blank line that # separates the header from the body is missing, and to stop parsing # headers and start parsing the body. msg = self._str_msg('Subject: test\nnot a header\nTo: abc\n\nb\n') self.assertEqual(msg.keys(), ['Subject']) self.assertEqual(msg.get_payload(), 'not a header\nTo: abc\n\nb\n') self.assertDefectsEqual(msg.defects, [errors.MissingHeaderBodySeparatorDefect]) # Test RFC 2047 header encoding and decoding class TestRFC2047(TestEmailBase): def test_rfc2047_multiline(self): eq = self.assertEqual s = """Re: =?mac-iceland?q?r=8Aksm=9Arg=8Cs?= baz foo bar =?mac-iceland?q?r=8Aksm=9Arg=8Cs?=""" dh = decode_header(s) eq(dh, [ (b'Re: ', None), (b'r\x8aksm\x9arg\x8cs', 'mac-iceland'), (b' baz foo bar ', None), (b'r\x8aksm\x9arg\x8cs', 'mac-iceland')]) header = make_header(dh) eq(str(header), 'Re: r\xe4ksm\xf6rg\xe5s baz foo bar r\xe4ksm\xf6rg\xe5s') self.ndiffAssertEqual(header.encode(maxlinelen=76), """\ Re: =?mac-iceland?q?r=8Aksm=9Arg=8Cs?= baz foo bar =?mac-iceland?q?r=8Aksm?= =?mac-iceland?q?=9Arg=8Cs?=""") def test_whitespace_keeper_unicode(self): eq = self.assertEqual s = '=?ISO-8859-1?Q?Andr=E9?= Pirard <[email protected]>' dh = decode_header(s) eq(dh, [(b'Andr\xe9', 'iso-8859-1'), (b' Pirard <[email protected]>', None)]) header = str(make_header(dh)) eq(header, 'Andr\xe9 Pirard <[email protected]>') def test_whitespace_keeper_unicode_2(self): eq = self.assertEqual s = 'The =?iso-8859-1?b?cXVpY2sgYnJvd24gZm94?= jumped over the =?iso-8859-1?b?bGF6eSBkb2c=?=' dh = decode_header(s) eq(dh, [(b'The ', None), (b'quick brown fox', 'iso-8859-1'), (b' jumped over the ', None), (b'lazy dog', 'iso-8859-1')]) hu = str(make_header(dh)) eq(hu, 'The quick brown fox jumped over the lazy dog') def test_rfc2047_missing_whitespace(self): s = 'Sm=?ISO-8859-1?B?9g==?=rg=?ISO-8859-1?B?5Q==?=sbord' dh = decode_header(s) self.assertEqual(dh, [(b'Sm', None), (b'\xf6', 'iso-8859-1'), (b'rg', None), (b'\xe5', 'iso-8859-1'), (b'sbord', None)]) def test_rfc2047_with_whitespace(self): s = 'Sm =?ISO-8859-1?B?9g==?= rg =?ISO-8859-1?B?5Q==?= sbord' dh = decode_header(s) self.assertEqual(dh, [(b'Sm ', None), (b'\xf6', 'iso-8859-1'), (b' rg ', None), (b'\xe5', 'iso-8859-1'), (b' sbord', None)]) def test_rfc2047_B_bad_padding(self): s = '=?iso-8859-1?B?%s?=' data = [ # only test complete bytes ('dm==', b'v'), ('dm=', b'v'), ('dm', b'v'), ('dmk=', b'vi'), ('dmk', b'vi') ] for q, a in data: dh = decode_header(s % q) self.assertEqual(dh, [(a, 'iso-8859-1')]) def test_rfc2047_Q_invalid_digits(self): # issue 10004. s = '=?iso-8859-1?Q?andr=e9=zz?=' self.assertEqual(decode_header(s), [(b'andr\xe9=zz', 'iso-8859-1')]) def test_rfc2047_rfc2047_1(self): # 1st testcase at end of rfc2047 s = '(=?ISO-8859-1?Q?a?=)' self.assertEqual(decode_header(s), [(b'(', None), (b'a', 'iso-8859-1'), (b')', None)]) def test_rfc2047_rfc2047_2(self): # 2nd testcase at end of rfc2047 s = '(=?ISO-8859-1?Q?a?= b)' self.assertEqual(decode_header(s), [(b'(', None), (b'a', 'iso-8859-1'), (b' b)', None)]) def test_rfc2047_rfc2047_3(self): # 3rd testcase at end of rfc2047 s = '(=?ISO-8859-1?Q?a?= =?ISO-8859-1?Q?b?=)' self.assertEqual(decode_header(s), [(b'(', None), (b'ab', 'iso-8859-1'), (b')', None)]) def test_rfc2047_rfc2047_4(self): # 4th testcase at end of rfc2047 s = '(=?ISO-8859-1?Q?a?= =?ISO-8859-1?Q?b?=)' self.assertEqual(decode_header(s), [(b'(', None), (b'ab', 'iso-8859-1'), (b')', None)]) def test_rfc2047_rfc2047_5a(self): # 5th testcase at end of rfc2047 newline is \r\n s = '(=?ISO-8859-1?Q?a?=\r\n =?ISO-8859-1?Q?b?=)' self.assertEqual(decode_header(s), [(b'(', None), (b'ab', 'iso-8859-1'), (b')', None)]) def test_rfc2047_rfc2047_5b(self): # 5th testcase at end of rfc2047 newline is \n s = '(=?ISO-8859-1?Q?a?=\n =?ISO-8859-1?Q?b?=)' self.assertEqual(decode_header(s), [(b'(', None), (b'ab', 'iso-8859-1'), (b')', None)]) def test_rfc2047_rfc2047_6(self): # 6th testcase at end of rfc2047 s = '(=?ISO-8859-1?Q?a_b?=)' self.assertEqual(decode_header(s), [(b'(', None), (b'a b', 'iso-8859-1'), (b')', None)]) def test_rfc2047_rfc2047_7(self): # 7th testcase at end of rfc2047 s = '(=?ISO-8859-1?Q?a?= =?ISO-8859-2?Q?_b?=)' self.assertEqual(decode_header(s), [(b'(', None), (b'a', 'iso-8859-1'), (b' b', 'iso-8859-2'), (b')', None)]) self.assertEqual(make_header(decode_header(s)).encode(), s.lower()) self.assertEqual(str(make_header(decode_header(s))), '(a b)') def test_multiline_header(self): s = '=?windows-1252?q?=22M=FCller_T=22?=\r\n <[email protected]>' self.assertEqual(decode_header(s), [(b'"M\xfcller T"', 'windows-1252'), (b'<[email protected]>', None)]) self.assertEqual(make_header(decode_header(s)).encode(), ''.join(s.splitlines())) self.assertEqual(str(make_header(decode_header(s))), '"Müller T" <[email protected]>') # Test the MIMEMessage class class TestMIMEMessage(TestEmailBase): def setUp(self): with openfile('msg_11.txt') as fp: self._text = fp.read() def test_type_error(self): self.assertRaises(TypeError, MIMEMessage, 'a plain string') def test_valid_argument(self): eq = self.assertEqual subject = 'A sub-message' m = Message() m['Subject'] = subject r = MIMEMessage(m) eq(r.get_content_type(), 'message/rfc822') payload = r.get_payload() self.assertIsInstance(payload, list) eq(len(payload), 1) subpart = payload[0] self.assertIs(subpart, m) eq(subpart['subject'], subject) def test_bad_multipart(self): msg1 = Message() msg1['Subject'] = 'subpart 1' msg2 = Message() msg2['Subject'] = 'subpart 2' r = MIMEMessage(msg1) self.assertRaises(errors.MultipartConversionError, r.attach, msg2) def test_generate(self): # First craft the message to be encapsulated m = Message() m['Subject'] = 'An enclosed message' m.set_payload('Here is the body of the message.\n') r = MIMEMessage(m) r['Subject'] = 'The enclosing message' s = StringIO() g = Generator(s) g.flatten(r) self.assertEqual(s.getvalue(), """\ Content-Type: message/rfc822 MIME-Version: 1.0 Subject: The enclosing message Subject: An enclosed message Here is the body of the message. """) def test_parse_message_rfc822(self): eq = self.assertEqual msg = self._msgobj('msg_11.txt') eq(msg.get_content_type(), 'message/rfc822') payload = msg.get_payload() self.assertIsInstance(payload, list) eq(len(payload), 1) submsg = payload[0] self.assertIsInstance(submsg, Message) eq(submsg['subject'], 'An enclosed message') eq(submsg.get_payload(), 'Here is the body of the message.\n') def test_dsn(self): eq = self.assertEqual # msg 16 is a Delivery Status Notification, see RFC 1894 msg = self._msgobj('msg_16.txt') eq(msg.get_content_type(), 'multipart/report') self.assertTrue(msg.is_multipart()) eq(len(msg.get_payload()), 3) # Subpart 1 is a text/plain, human readable section subpart = msg.get_payload(0) eq(subpart.get_content_type(), 'text/plain') eq(subpart.get_payload(), """\ This report relates to a message you sent with the following header fields: Message-id: <[email protected]> Date: Sun, 23 Sep 2001 20:10:55 -0700 From: "Ian T. Henry" <[email protected]> To: SoCal Raves <[email protected]> Subject: [scr] yeah for Ians!! Your message cannot be delivered to the following recipients: Recipient address: [email protected] Reason: recipient reached disk quota """) # Subpart 2 contains the machine parsable DSN information. It # consists of two blocks of headers, represented by two nested Message # objects. subpart = msg.get_payload(1) eq(subpart.get_content_type(), 'message/delivery-status') eq(len(subpart.get_payload()), 2) # message/delivery-status should treat each block as a bunch of # headers, i.e. a bunch of Message objects. dsn1 = subpart.get_payload(0) self.assertIsInstance(dsn1, Message) eq(dsn1['original-envelope-id'], '[email protected]') eq(dsn1.get_param('dns', header='reporting-mta'), '') # Try a missing one <wink> eq(dsn1.get_param('nsd', header='reporting-mta'), None) dsn2 = subpart.get_payload(1) self.assertIsInstance(dsn2, Message) eq(dsn2['action'], 'failed') eq(dsn2.get_params(header='original-recipient'), [('rfc822', ''), ('[email protected]', '')]) eq(dsn2.get_param('rfc822', header='final-recipient'), '') # Subpart 3 is the original message subpart = msg.get_payload(2) eq(subpart.get_content_type(), 'message/rfc822') payload = subpart.get_payload() self.assertIsInstance(payload, list) eq(len(payload), 1) subsubpart = payload[0] self.assertIsInstance(subsubpart, Message) eq(subsubpart.get_content_type(), 'text/plain') eq(subsubpart['message-id'], '<[email protected]>') def test_epilogue(self): eq = self.ndiffAssertEqual with openfile('msg_21.txt') as fp: text = fp.read() msg = Message() msg['From'] = '[email protected]' msg['To'] = '[email protected]' msg['Subject'] = 'Test' msg.preamble = 'MIME message' msg.epilogue = 'End of MIME message\n' msg1 = MIMEText('One') msg2 = MIMEText('Two') msg.add_header('Content-Type', 'multipart/mixed', boundary='BOUNDARY') msg.attach(msg1) msg.attach(msg2) sfp = StringIO() g = Generator(sfp) g.flatten(msg) eq(sfp.getvalue(), text) def test_no_nl_preamble(self): eq = self.ndiffAssertEqual msg = Message() msg['From'] = '[email protected]' msg['To'] = '[email protected]' msg['Subject'] = 'Test' msg.preamble = 'MIME message' msg.epilogue = '' msg1 = MIMEText('One') msg2 = MIMEText('Two') msg.add_header('Content-Type', 'multipart/mixed', boundary='BOUNDARY') msg.attach(msg1) msg.attach(msg2) eq(msg.as_string(), """\ From: [email protected] To: [email protected] Subject: Test Content-Type: multipart/mixed; boundary="BOUNDARY" MIME message --BOUNDARY Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit One --BOUNDARY Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Two --BOUNDARY-- """) def test_default_type(self): eq = self.assertEqual with openfile('msg_30.txt') as fp: msg = email.message_from_file(fp) container1 = msg.get_payload(0) eq(container1.get_default_type(), 'message/rfc822') eq(container1.get_content_type(), 'message/rfc822') container2 = msg.get_payload(1) eq(container2.get_default_type(), 'message/rfc822') eq(container2.get_content_type(), 'message/rfc822') container1a = container1.get_payload(0) eq(container1a.get_default_type(), 'text/plain') eq(container1a.get_content_type(), 'text/plain') container2a = container2.get_payload(0) eq(container2a.get_default_type(), 'text/plain') eq(container2a.get_content_type(), 'text/plain') def test_default_type_with_explicit_container_type(self): eq = self.assertEqual with openfile('msg_28.txt') as fp: msg = email.message_from_file(fp) container1 = msg.get_payload(0) eq(container1.get_default_type(), 'message/rfc822') eq(container1.get_content_type(), 'message/rfc822') container2 = msg.get_payload(1) eq(container2.get_default_type(), 'message/rfc822') eq(container2.get_content_type(), 'message/rfc822') container1a = container1.get_payload(0) eq(container1a.get_default_type(), 'text/plain') eq(container1a.get_content_type(), 'text/plain') container2a = container2.get_payload(0) eq(container2a.get_default_type(), 'text/plain') eq(container2a.get_content_type(), 'text/plain') def test_default_type_non_parsed(self): eq = self.assertEqual neq = self.ndiffAssertEqual # Set up container container = MIMEMultipart('digest', 'BOUNDARY') container.epilogue = '' # Set up subparts subpart1a = MIMEText('message 1\n') subpart2a = MIMEText('message 2\n') subpart1 = MIMEMessage(subpart1a) subpart2 = MIMEMessage(subpart2a) container.attach(subpart1) container.attach(subpart2) eq(subpart1.get_content_type(), 'message/rfc822') eq(subpart1.get_default_type(), 'message/rfc822') eq(subpart2.get_content_type(), 'message/rfc822') eq(subpart2.get_default_type(), 'message/rfc822') neq(container.as_string(0), '''\ Content-Type: multipart/digest; boundary="BOUNDARY" MIME-Version: 1.0 --BOUNDARY Content-Type: message/rfc822 MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit message 1 --BOUNDARY Content-Type: message/rfc822 MIME-Version: 1.0 Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit message 2 --BOUNDARY-- ''') del subpart1['content-type'] del subpart1['mime-version'] del subpart2['content-type'] del subpart2['mime-version'] eq(subpart1.get_content_type(), 'message/rfc822') eq(subpart1.get_default_type(), 'message/rfc822') eq(subpart2.get_content_type(), 'message/rfc822') eq(subpart2.get_default_type(), 'message/rfc822') neq(container.as_string(0), '''\ Content-Type: multipart/digest; boundary="BOUNDARY" MIME-Version: 1.0 --BOUNDARY Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit message 1 --BOUNDARY Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit message 2 --BOUNDARY-- ''') def test_mime_attachments_in_constructor(self): eq = self.assertEqual text1 = MIMEText('') text2 = MIMEText('') msg = MIMEMultipart(_subparts=(text1, text2)) eq(len(msg.get_payload()), 2) eq(msg.get_payload(0), text1) eq(msg.get_payload(1), text2) def test_default_multipart_constructor(self): msg = MIMEMultipart() self.assertTrue(msg.is_multipart()) def test_multipart_default_policy(self): msg = MIMEMultipart() msg['To'] = '[email protected]' msg['To'] = '[email protected]' self.assertEqual(msg.get_all('to'), ['[email protected]', '[email protected]']) def test_multipart_custom_policy(self): msg = MIMEMultipart(policy=email.policy.default) msg['To'] = '[email protected]' with self.assertRaises(ValueError) as cm: msg['To'] = '[email protected]' self.assertEqual(str(cm.exception), 'There may be at most 1 To headers in a message') # A general test of parser->model->generator idempotency. IOW, read a message # in, parse it into a message object tree, then without touching the tree, # regenerate the plain text. The original text and the transformed text # should be identical. Note: that we ignore the Unix-From since that may # contain a changed date. class TestIdempotent(TestEmailBase): linesep = '\n' def _msgobj(self, filename): with openfile(filename) as fp: data = fp.read() msg = email.message_from_string(data) return msg, data def _idempotent(self, msg, text, unixfrom=False): eq = self.ndiffAssertEqual s = StringIO() g = Generator(s, maxheaderlen=0) g.flatten(msg, unixfrom=unixfrom) eq(text, s.getvalue()) def test_parse_text_message(self): eq = self.assertEqual msg, text = self._msgobj('msg_01.txt') eq(msg.get_content_type(), 'text/plain') eq(msg.get_content_maintype(), 'text') eq(msg.get_content_subtype(), 'plain') eq(msg.get_params()[1], ('charset', 'us-ascii')) eq(msg.get_param('charset'), 'us-ascii') eq(msg.preamble, None) eq(msg.epilogue, None) self._idempotent(msg, text) def test_parse_untyped_message(self): eq = self.assertEqual msg, text = self._msgobj('msg_03.txt') eq(msg.get_content_type(), 'text/plain') eq(msg.get_params(), None) eq(msg.get_param('charset'), None) self._idempotent(msg, text) def test_simple_multipart(self): msg, text = self._msgobj('msg_04.txt') self._idempotent(msg, text) def test_MIME_digest(self): msg, text = self._msgobj('msg_02.txt') self._idempotent(msg, text) def test_long_header(self): msg, text = self._msgobj('msg_27.txt') self._idempotent(msg, text) def test_MIME_digest_with_part_headers(self): msg, text = self._msgobj('msg_28.txt') self._idempotent(msg, text) def test_mixed_with_image(self): msg, text = self._msgobj('msg_06.txt') self._idempotent(msg, text) def test_multipart_report(self): msg, text = self._msgobj('msg_05.txt') self._idempotent(msg, text) def test_dsn(self): msg, text = self._msgobj('msg_16.txt') self._idempotent(msg, text) def test_preamble_epilogue(self): msg, text = self._msgobj('msg_21.txt') self._idempotent(msg, text) def test_multipart_one_part(self): msg, text = self._msgobj('msg_23.txt') self._idempotent(msg, text) def test_multipart_no_parts(self): msg, text = self._msgobj('msg_24.txt') self._idempotent(msg, text) def test_no_start_boundary(self): msg, text = self._msgobj('msg_31.txt') self._idempotent(msg, text) def test_rfc2231_charset(self): msg, text = self._msgobj('msg_32.txt') self._idempotent(msg, text) def test_more_rfc2231_parameters(self): msg, text = self._msgobj('msg_33.txt') self._idempotent(msg, text) def test_text_plain_in_a_multipart_digest(self): msg, text = self._msgobj('msg_34.txt') self._idempotent(msg, text) def test_nested_multipart_mixeds(self): msg, text = self._msgobj('msg_12a.txt') self._idempotent(msg, text) def test_message_external_body_idempotent(self): msg, text = self._msgobj('msg_36.txt') self._idempotent(msg, text) def test_message_delivery_status(self): msg, text = self._msgobj('msg_43.txt') self._idempotent(msg, text, unixfrom=True) def test_message_signed_idempotent(self): msg, text = self._msgobj('msg_45.txt') self._idempotent(msg, text) def test_content_type(self): eq = self.assertEqual # Get a message object and reset the seek pointer for other tests msg, text = self._msgobj('msg_05.txt') eq(msg.get_content_type(), 'multipart/report') # Test the Content-Type: parameters params = {} for pk, pv in msg.get_params(): params[pk] = pv eq(params['report-type'], 'delivery-status') eq(params['boundary'], 'D1690A7AC1.996856090/mail.example.com') eq(msg.preamble, 'This is a MIME-encapsulated message.' + self.linesep) eq(msg.epilogue, self.linesep) eq(len(msg.get_payload()), 3) # Make sure the subparts are what we expect msg1 = msg.get_payload(0) eq(msg1.get_content_type(), 'text/plain') eq(msg1.get_payload(), 'Yadda yadda yadda' + self.linesep) msg2 = msg.get_payload(1) eq(msg2.get_content_type(), 'text/plain') eq(msg2.get_payload(), 'Yadda yadda yadda' + self.linesep) msg3 = msg.get_payload(2) eq(msg3.get_content_type(), 'message/rfc822') self.assertIsInstance(msg3, Message) payload = msg3.get_payload() self.assertIsInstance(payload, list) eq(len(payload), 1) msg4 = payload[0] self.assertIsInstance(msg4, Message) eq(msg4.get_payload(), 'Yadda yadda yadda' + self.linesep) def test_parser(self): eq = self.assertEqual msg, text = self._msgobj('msg_06.txt') # Check some of the outer headers eq(msg.get_content_type(), 'message/rfc822') # Make sure the payload is a list of exactly one sub-Message, and that # that submessage has a type of text/plain payload = msg.get_payload() self.assertIsInstance(payload, list) eq(len(payload), 1) msg1 = payload[0] self.assertIsInstance(msg1, Message) eq(msg1.get_content_type(), 'text/plain') self.assertIsInstance(msg1.get_payload(), str) eq(msg1.get_payload(), self.linesep) # Test various other bits of the package's functionality class TestMiscellaneous(TestEmailBase): def test_message_from_string(self): with openfile('msg_01.txt') as fp: text = fp.read() msg = email.message_from_string(text) s = StringIO() # Don't wrap/continue long headers since we're trying to test # idempotency. g = Generator(s, maxheaderlen=0) g.flatten(msg) self.assertEqual(text, s.getvalue()) def test_message_from_file(self): with openfile('msg_01.txt') as fp: text = fp.read() fp.seek(0) msg = email.message_from_file(fp) s = StringIO() # Don't wrap/continue long headers since we're trying to test # idempotency. g = Generator(s, maxheaderlen=0) g.flatten(msg) self.assertEqual(text, s.getvalue()) def test_message_from_string_with_class(self): with openfile('msg_01.txt') as fp: text = fp.read() # Create a subclass class MyMessage(Message): pass msg = email.message_from_string(text, MyMessage) self.assertIsInstance(msg, MyMessage) # Try something more complicated with openfile('msg_02.txt') as fp: text = fp.read() msg = email.message_from_string(text, MyMessage) for subpart in msg.walk(): self.assertIsInstance(subpart, MyMessage) def test_message_from_file_with_class(self): # Create a subclass class MyMessage(Message): pass with openfile('msg_01.txt') as fp: msg = email.message_from_file(fp, MyMessage) self.assertIsInstance(msg, MyMessage) # Try something more complicated with openfile('msg_02.txt') as fp: msg = email.message_from_file(fp, MyMessage) for subpart in msg.walk(): self.assertIsInstance(subpart, MyMessage) def test_custom_message_does_not_require_arguments(self): class MyMessage(Message): def __init__(self): super().__init__() msg = self._str_msg("Subject: test\n\ntest", MyMessage) self.assertIsInstance(msg, MyMessage) def test__all__(self): module = __import__('email') self.assertEqual(sorted(module.__all__), [ 'base64mime', 'charset', 'encoders', 'errors', 'feedparser', 'generator', 'header', 'iterators', 'message', 'message_from_binary_file', 'message_from_bytes', 'message_from_file', 'message_from_string', 'mime', 'parser', 'quoprimime', 'utils', ]) def test_formatdate(self): now = time.time() self.assertEqual(utils.parsedate(utils.formatdate(now))[:6], time.gmtime(now)[:6]) def test_formatdate_localtime(self): now = time.time() self.assertEqual( utils.parsedate(utils.formatdate(now, localtime=True))[:6], time.localtime(now)[:6]) def test_formatdate_usegmt(self): now = time.time() self.assertEqual( utils.formatdate(now, localtime=False), time.strftime('%a, %d %b %Y %H:%M:%S -0000', time.gmtime(now))) self.assertEqual( utils.formatdate(now, localtime=False, usegmt=True), time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(now))) # parsedate and parsedate_tz will become deprecated interfaces someday def test_parsedate_returns_None_for_invalid_strings(self): self.assertIsNone(utils.parsedate('')) self.assertIsNone(utils.parsedate_tz('')) self.assertIsNone(utils.parsedate('0')) self.assertIsNone(utils.parsedate_tz('0')) self.assertIsNone(utils.parsedate('A Complete Waste of Time')) self.assertIsNone(utils.parsedate_tz('A Complete Waste of Time')) # Not a part of the spec but, but this has historically worked: self.assertIsNone(utils.parsedate(None)) self.assertIsNone(utils.parsedate_tz(None)) def test_parsedate_compact(self): # The FWS after the comma is optional self.assertEqual(utils.parsedate('Wed,3 Apr 2002 14:58:26 +0800'), utils.parsedate('Wed, 3 Apr 2002 14:58:26 +0800')) def test_parsedate_no_dayofweek(self): eq = self.assertEqual eq(utils.parsedate_tz('25 Feb 2003 13:47:26 -0800'), (2003, 2, 25, 13, 47, 26, 0, 1, -1, -28800)) def test_parsedate_compact_no_dayofweek(self): eq = self.assertEqual eq(utils.parsedate_tz('5 Feb 2003 13:47:26 -0800'), (2003, 2, 5, 13, 47, 26, 0, 1, -1, -28800)) def test_parsedate_no_space_before_positive_offset(self): self.assertEqual(utils.parsedate_tz('Wed, 3 Apr 2002 14:58:26+0800'), (2002, 4, 3, 14, 58, 26, 0, 1, -1, 28800)) def test_parsedate_no_space_before_negative_offset(self): # Issue 1155362: we already handled '+' for this case. self.assertEqual(utils.parsedate_tz('Wed, 3 Apr 2002 14:58:26-0800'), (2002, 4, 3, 14, 58, 26, 0, 1, -1, -28800)) def test_parsedate_accepts_time_with_dots(self): eq = self.assertEqual eq(utils.parsedate_tz('5 Feb 2003 13.47.26 -0800'), (2003, 2, 5, 13, 47, 26, 0, 1, -1, -28800)) eq(utils.parsedate_tz('5 Feb 2003 13.47 -0800'), (2003, 2, 5, 13, 47, 0, 0, 1, -1, -28800)) def test_parsedate_acceptable_to_time_functions(self): eq = self.assertEqual timetup = utils.parsedate('5 Feb 2003 13:47:26 -0800') t = int(time.mktime(timetup)) eq(time.localtime(t)[:6], timetup[:6]) eq(int(time.strftime('%Y', timetup)), 2003) timetup = utils.parsedate_tz('5 Feb 2003 13:47:26 -0800') t = int(time.mktime(timetup[:9])) eq(time.localtime(t)[:6], timetup[:6]) eq(int(time.strftime('%Y', timetup[:9])), 2003) def test_mktime_tz(self): self.assertEqual(utils.mktime_tz((1970, 1, 1, 0, 0, 0, -1, -1, -1, 0)), 0) self.assertEqual(utils.mktime_tz((1970, 1, 1, 0, 0, 0, -1, -1, -1, 1234)), -1234) def test_parsedate_y2k(self): """Test for parsing a date with a two-digit year. Parsing a date with a two-digit year should return the correct four-digit year. RFC822 allows two-digit years, but RFC2822 (which obsoletes RFC822) requires four-digit years. """ self.assertEqual(utils.parsedate_tz('25 Feb 03 13:47:26 -0800'), utils.parsedate_tz('25 Feb 2003 13:47:26 -0800')) self.assertEqual(utils.parsedate_tz('25 Feb 71 13:47:26 -0800'), utils.parsedate_tz('25 Feb 1971 13:47:26 -0800')) def test_parseaddr_empty(self): self.assertEqual(utils.parseaddr('<>'), ('', '')) self.assertEqual(utils.formataddr(utils.parseaddr('<>')), '') def test_parseaddr_multiple_domains(self): self.assertEqual( utils.parseaddr('a@b@c'), ('', '') ) self.assertEqual( utils.parseaddr('[email protected]@c'), ('', '') ) self.assertEqual( utils.parseaddr('[email protected]@c'), ('', '') ) def test_noquote_dump(self): self.assertEqual( utils.formataddr(('A Silly Person', '[email protected]')), 'A Silly Person <[email protected]>') def test_escape_dump(self): self.assertEqual( utils.formataddr(('A (Very) Silly Person', '[email protected]')), r'"A (Very) Silly Person" <[email protected]>') self.assertEqual( utils.parseaddr(r'"A \(Very\) Silly Person" <[email protected]>'), ('A (Very) Silly Person', '[email protected]')) a = r'A \(Special\) Person' b = '[email protected]' self.assertEqual(utils.parseaddr(utils.formataddr((a, b))), (a, b)) def test_escape_backslashes(self): self.assertEqual( utils.formataddr((r'Arthur \Backslash\ Foobar', '[email protected]')), r'"Arthur \\Backslash\\ Foobar" <[email protected]>') a = r'Arthur \Backslash\ Foobar' b = '[email protected]' self.assertEqual(utils.parseaddr(utils.formataddr((a, b))), (a, b)) def test_quotes_unicode_names(self): # issue 1690608. email.utils.formataddr() should be rfc2047 aware. name = "H\u00e4ns W\u00fcrst" addr = '[email protected]' utf8_base64 = "=?utf-8?b?SMOkbnMgV8O8cnN0?= <[email protected]>" latin1_quopri = "=?iso-8859-1?q?H=E4ns_W=FCrst?= <[email protected]>" self.assertEqual(utils.formataddr((name, addr)), utf8_base64) self.assertEqual(utils.formataddr((name, addr), 'iso-8859-1'), latin1_quopri) def test_accepts_any_charset_like_object(self): # issue 1690608. email.utils.formataddr() should be rfc2047 aware. name = "H\u00e4ns W\u00fcrst" addr = '[email protected]' utf8_base64 = "=?utf-8?b?SMOkbnMgV8O8cnN0?= <[email protected]>" foobar = "FOOBAR" class CharsetMock: def header_encode(self, string): return foobar mock = CharsetMock() mock_expected = "%s <%s>" % (foobar, addr) self.assertEqual(utils.formataddr((name, addr), mock), mock_expected) self.assertEqual(utils.formataddr((name, addr), Charset('utf-8')), utf8_base64) def test_invalid_charset_like_object_raises_error(self): # issue 1690608. email.utils.formataddr() should be rfc2047 aware. name = "H\u00e4ns W\u00fcrst" addr = '[email protected]' # An object without a header_encode method: bad_charset = object() self.assertRaises(AttributeError, utils.formataddr, (name, addr), bad_charset) def test_unicode_address_raises_error(self): # issue 1690608. email.utils.formataddr() should be rfc2047 aware. addr = 'pers\[email protected]' self.assertRaises(UnicodeError, utils.formataddr, (None, addr)) self.assertRaises(UnicodeError, utils.formataddr, ("Name", addr)) def test_name_with_dot(self): x = 'John X. Doe <[email protected]>' y = '"John X. Doe" <[email protected]>' a, b = ('John X. Doe', '[email protected]') self.assertEqual(utils.parseaddr(x), (a, b)) self.assertEqual(utils.parseaddr(y), (a, b)) # formataddr() quotes the name if there's a dot in it self.assertEqual(utils.formataddr((a, b)), y) def test_parseaddr_preserves_quoted_pairs_in_addresses(self): # issue 10005. Note that in the third test the second pair of # backslashes is not actually a quoted pair because it is not inside a # comment or quoted string: the address being parsed has a quoted # string containing a quoted backslash, followed by 'example' and two # backslashes, followed by another quoted string containing a space and # the word 'example'. parseaddr copies those two backslashes # literally. Per rfc5322 this is not technically correct since a \ may # not appear in an address outside of a quoted string. It is probably # a sensible Postel interpretation, though. eq = self.assertEqual eq(utils.parseaddr('""example" example"@example.com'), ('', '""example" example"@example.com')) eq(utils.parseaddr('"\\"example\\" example"@example.com'), ('', '"\\"example\\" example"@example.com')) eq(utils.parseaddr('"\\\\"example\\\\" example"@example.com'), ('', '"\\\\"example\\\\" example"@example.com')) def test_parseaddr_preserves_spaces_in_local_part(self): # issue 9286. A normal RFC5322 local part should not contain any # folding white space, but legacy local parts can (they are a sequence # of atoms, not dotatoms). On the other hand we strip whitespace from # before the @ and around dots, on the assumption that the whitespace # around the punctuation is a mistake in what would otherwise be # an RFC5322 local part. Leading whitespace is, usual, stripped as well. self.assertEqual(('', "merwok [email protected]"), utils.parseaddr("merwok [email protected]")) self.assertEqual(('', "merwok [email protected]"), utils.parseaddr("merwok [email protected]")) self.assertEqual(('', "merwok [email protected]"), utils.parseaddr(" merwok wok @xample.com")) self.assertEqual(('', 'merwok"wok" [email protected]'), utils.parseaddr('merwok"wok" [email protected]')) self.assertEqual(('', '[email protected]'), utils.parseaddr('merwok. wok . [email protected]')) def test_formataddr_does_not_quote_parens_in_quoted_string(self): addr = ("'[email protected]' ([email protected])", '[email protected]') addrstr = ('"\'[email protected]\' ' '([email protected])" <[email protected]>') self.assertEqual(utils.parseaddr(addrstr), addr) self.assertEqual(utils.formataddr(addr), addrstr) def test_multiline_from_comment(self): x = """\ Foo \tBar <[email protected]>""" self.assertEqual(utils.parseaddr(x), ('Foo Bar', '[email protected]')) def test_quote_dump(self): self.assertEqual( utils.formataddr(('A Silly; Person', '[email protected]')), r'"A Silly; Person" <[email protected]>') def test_charset_richcomparisons(self): eq = self.assertEqual ne = self.assertNotEqual cset1 = Charset() cset2 = Charset() eq(cset1, 'us-ascii') eq(cset1, 'US-ASCII') eq(cset1, 'Us-AsCiI') eq('us-ascii', cset1) eq('US-ASCII', cset1) eq('Us-AsCiI', cset1) ne(cset1, 'usascii') ne(cset1, 'USASCII') ne(cset1, 'UsAsCiI') ne('usascii', cset1) ne('USASCII', cset1) ne('UsAsCiI', cset1) eq(cset1, cset2) eq(cset2, cset1) def test_getaddresses(self): eq = self.assertEqual eq(utils.getaddresses(['[email protected] (Al Person)', 'Bud Person <[email protected]>']), [('Al Person', '[email protected]'), ('Bud Person', '[email protected]')]) def test_getaddresses_nasty(self): eq = self.assertEqual eq(utils.getaddresses(['foo: ;']), [('', '')]) eq(utils.getaddresses( ['[]*-- =~$']), [('', ''), ('', ''), ('', '*--')]) eq(utils.getaddresses( ['foo: ;', '"Jason R. Mastaler" <[email protected]>']), [('', ''), ('Jason R. Mastaler', '[email protected]')]) def test_getaddresses_embedded_comment(self): """Test proper handling of a nested comment""" eq = self.assertEqual addrs = utils.getaddresses(['User ((nested comment)) <[email protected]>']) eq(addrs[0][1], '[email protected]') @unittest.skipIf(sys.platform.startswith('cosmo'), "no threads") def test_make_msgid_collisions(self): # Test make_msgid uniqueness, even with multiple threads class MsgidsThread(Thread): def run(self): # generate msgids for 3 seconds self.msgids = [] append = self.msgids.append make_msgid = utils.make_msgid clock = time.monotonic tfin = clock() + 3.0 while clock() < tfin: append(make_msgid(domain='testdomain-string')) threads = [MsgidsThread() for i in range(5)] with start_threads(threads): pass all_ids = sum([t.msgids for t in threads], []) self.assertEqual(len(set(all_ids)), len(all_ids)) def test_utils_quote_unquote(self): eq = self.assertEqual msg = Message() msg.add_header('content-disposition', 'attachment', filename='foo\\wacky"name') eq(msg.get_filename(), 'foo\\wacky"name') def test_get_body_encoding_with_bogus_charset(self): charset = Charset('not a charset') self.assertEqual(charset.get_body_encoding(), 'base64') def test_get_body_encoding_with_uppercase_charset(self): eq = self.assertEqual msg = Message() msg['Content-Type'] = 'text/plain; charset=UTF-8' eq(msg['content-type'], 'text/plain; charset=UTF-8') charsets = msg.get_charsets() eq(len(charsets), 1) eq(charsets[0], 'utf-8') charset = Charset(charsets[0]) eq(charset.get_body_encoding(), 'base64') msg.set_payload(b'hello world', charset=charset) eq(msg.get_payload(), 'aGVsbG8gd29ybGQ=\n') eq(msg.get_payload(decode=True), b'hello world') eq(msg['content-transfer-encoding'], 'base64') # Try another one msg = Message() msg['Content-Type'] = 'text/plain; charset="US-ASCII"' charsets = msg.get_charsets() eq(len(charsets), 1) eq(charsets[0], 'us-ascii') charset = Charset(charsets[0]) eq(charset.get_body_encoding(), encoders.encode_7or8bit) msg.set_payload('hello world', charset=charset) eq(msg.get_payload(), 'hello world') eq(msg['content-transfer-encoding'], '7bit') def test_charsets_case_insensitive(self): lc = Charset('us-ascii') uc = Charset('US-ASCII') self.assertEqual(lc.get_body_encoding(), uc.get_body_encoding()) def test_partial_falls_inside_message_delivery_status(self): eq = self.ndiffAssertEqual # The Parser interface provides chunks of data to FeedParser in 8192 # byte gulps. SF bug #1076485 found one of those chunks inside # message/delivery-status header block, which triggered an # unreadline() of NeedMoreData. msg = self._msgobj('msg_43.txt') sfp = StringIO() iterators._structure(msg, sfp) eq(sfp.getvalue(), """\ multipart/report text/plain message/delivery-status text/plain text/plain text/plain text/plain text/plain text/plain text/plain text/plain text/plain text/plain text/plain text/plain text/plain text/plain text/plain text/plain text/plain text/plain text/plain text/plain text/plain text/plain text/plain text/plain text/plain text/plain text/rfc822-headers """) def test_make_msgid_domain(self): self.assertEqual( email.utils.make_msgid(domain='testdomain-string')[-19:], '@testdomain-string>') def test_make_msgid_idstring(self): self.assertEqual( email.utils.make_msgid(idstring='test-idstring', domain='testdomain-string')[-33:], '.test-idstring@testdomain-string>') def test_make_msgid_default_domain(self): self.assertTrue( email.utils.make_msgid().endswith( '@' + getfqdn() + '>')) def test_Generator_linend(self): # Issue 14645. with openfile('msg_26.txt', newline='\n') as f: msgtxt = f.read() msgtxt_nl = msgtxt.replace('\r\n', '\n') msg = email.message_from_string(msgtxt) s = StringIO() g = email.generator.Generator(s) g.flatten(msg) self.assertEqual(s.getvalue(), msgtxt_nl) def test_BytesGenerator_linend(self): # Issue 14645. with openfile('msg_26.txt', newline='\n') as f: msgtxt = f.read() msgtxt_nl = msgtxt.replace('\r\n', '\n') msg = email.message_from_string(msgtxt_nl) s = BytesIO() g = email.generator.BytesGenerator(s) g.flatten(msg, linesep='\r\n') self.assertEqual(s.getvalue().decode('ascii'), msgtxt) def test_BytesGenerator_linend_with_non_ascii(self): # Issue 14645. with openfile('msg_26.txt', 'rb') as f: msgtxt = f.read() msgtxt = msgtxt.replace(b'with attachment', b'fo\xf6') msgtxt_nl = msgtxt.replace(b'\r\n', b'\n') msg = email.message_from_bytes(msgtxt_nl) s = BytesIO() g = email.generator.BytesGenerator(s) g.flatten(msg, linesep='\r\n') self.assertEqual(s.getvalue(), msgtxt) def test_mime_classes_policy_argument(self): with openfile('audiotest.au', 'rb') as fp: audiodata = fp.read() with openfile('PyBanner048.gif', 'rb') as fp: bindata = fp.read() classes = [ (MIMEApplication, ('',)), (MIMEAudio, (audiodata,)), (MIMEImage, (bindata,)), (MIMEMessage, (Message(),)), (MIMENonMultipart, ('multipart', 'mixed')), (MIMEText, ('',)), ] for cls, constructor in classes: with self.subTest(cls=cls.__name__, policy='compat32'): m = cls(*constructor) self.assertIs(m.policy, email.policy.compat32) with self.subTest(cls=cls.__name__, policy='default'): m = cls(*constructor, policy=email.policy.default) self.assertIs(m.policy, email.policy.default) # Test the iterator/generators class TestIterators(TestEmailBase): def test_body_line_iterator(self): eq = self.assertEqual neq = self.ndiffAssertEqual # First a simple non-multipart message msg = self._msgobj('msg_01.txt') it = iterators.body_line_iterator(msg) lines = list(it) eq(len(lines), 6) neq(EMPTYSTRING.join(lines), msg.get_payload()) # Now a more complicated multipart msg = self._msgobj('msg_02.txt') it = iterators.body_line_iterator(msg) lines = list(it) eq(len(lines), 43) with openfile('msg_19.txt') as fp: neq(EMPTYSTRING.join(lines), fp.read()) def test_typed_subpart_iterator(self): eq = self.assertEqual msg = self._msgobj('msg_04.txt') it = iterators.typed_subpart_iterator(msg, 'text') lines = [] subparts = 0 for subpart in it: subparts += 1 lines.append(subpart.get_payload()) eq(subparts, 2) eq(EMPTYSTRING.join(lines), """\ a simple kind of mirror to reflect upon our own a simple kind of mirror to reflect upon our own """) def test_typed_subpart_iterator_default_type(self): eq = self.assertEqual msg = self._msgobj('msg_03.txt') it = iterators.typed_subpart_iterator(msg, 'text', 'plain') lines = [] subparts = 0 for subpart in it: subparts += 1 lines.append(subpart.get_payload()) eq(subparts, 1) eq(EMPTYSTRING.join(lines), """\ Hi, Do you like this message? -Me """) def test_pushCR_LF(self): '''FeedParser BufferedSubFile.push() assumed it received complete line endings. A CR ending one push() followed by a LF starting the next push() added an empty line. ''' imt = [ ("a\r \n", 2), ("b", 0), ("c\n", 1), ("", 0), ("d\r\n", 1), ("e\r", 0), ("\nf", 1), ("\r\n", 1), ] from email.feedparser import BufferedSubFile, NeedMoreData bsf = BufferedSubFile() om = [] nt = 0 for il, n in imt: bsf.push(il) nt += n n1 = 0 for ol in iter(bsf.readline, NeedMoreData): om.append(ol) n1 += 1 self.assertEqual(n, n1) self.assertEqual(len(om), nt) self.assertEqual(''.join([il for il, n in imt]), ''.join(om)) def test_push_random(self): from email.feedparser import BufferedSubFile, NeedMoreData n = 10000 chunksize = 5 chars = 'abcd \t\r\n' s = ''.join(choice(chars) for i in range(n)) + '\n' target = s.splitlines(True) bsf = BufferedSubFile() lines = [] for i in range(0, len(s), chunksize): chunk = s[i:i+chunksize] bsf.push(chunk) lines.extend(iter(bsf.readline, NeedMoreData)) self.assertEqual(lines, target) class TestFeedParsers(TestEmailBase): def parse(self, chunks): feedparser = FeedParser() for chunk in chunks: feedparser.feed(chunk) return feedparser.close() def test_empty_header_name_handled(self): # Issue 19996 msg = self.parse("First: val\n: bad\nSecond: val") self.assertEqual(msg['First'], 'val') self.assertEqual(msg['Second'], 'val') def test_newlines(self): m = self.parse(['a:\nb:\rc:\r\nd:\n']) self.assertEqual(m.keys(), ['a', 'b', 'c', 'd']) m = self.parse(['a:\nb:\rc:\r\nd:']) self.assertEqual(m.keys(), ['a', 'b', 'c', 'd']) m = self.parse(['a:\rb', 'c:\n']) self.assertEqual(m.keys(), ['a', 'bc']) m = self.parse(['a:\r', 'b:\n']) self.assertEqual(m.keys(), ['a', 'b']) m = self.parse(['a:\r', '\nb:\n']) self.assertEqual(m.keys(), ['a', 'b']) # Only CR and LF should break header fields m = self.parse(['a:\x85b:\u2028c:\n']) self.assertEqual(m.items(), [('a', '\x85b:\u2028c:')]) m = self.parse(['a:\r', 'b:\x85', 'c:\n']) self.assertEqual(m.items(), [('a', ''), ('b', '\x85c:')]) def test_long_lines(self): # Expected peak memory use on 32-bit platform: 6*N*M bytes. M, N = 1000, 20000 m = self.parse(['a:b\n\n'] + ['x'*M] * N) self.assertEqual(m.items(), [('a', 'b')]) self.assertEqual(m.get_payload(), 'x'*M*N) m = self.parse(['a:b\r\r'] + ['x'*M] * N) self.assertEqual(m.items(), [('a', 'b')]) self.assertEqual(m.get_payload(), 'x'*M*N) m = self.parse(['a:b\r\r'] + ['x'*M+'\x85'] * N) self.assertEqual(m.items(), [('a', 'b')]) self.assertEqual(m.get_payload(), ('x'*M+'\x85')*N) m = self.parse(['a:\r', 'b: '] + ['x'*M] * N) self.assertEqual(m.items(), [('a', ''), ('b', 'x'*M*N)]) class TestParsers(TestEmailBase): def test_header_parser(self): eq = self.assertEqual # Parse only the headers of a complex multipart MIME document with openfile('msg_02.txt') as fp: msg = HeaderParser().parse(fp) eq(msg['from'], '[email protected]') eq(msg['to'], '[email protected]') eq(msg.get_content_type(), 'multipart/mixed') self.assertFalse(msg.is_multipart()) self.assertIsInstance(msg.get_payload(), str) def test_bytes_header_parser(self): eq = self.assertEqual # Parse only the headers of a complex multipart MIME document with openfile('msg_02.txt', 'rb') as fp: msg = email.parser.BytesHeaderParser().parse(fp) eq(msg['from'], '[email protected]') eq(msg['to'], '[email protected]') eq(msg.get_content_type(), 'multipart/mixed') self.assertFalse(msg.is_multipart()) self.assertIsInstance(msg.get_payload(), str) self.assertIsInstance(msg.get_payload(decode=True), bytes) def test_bytes_parser_does_not_close_file(self): with openfile('msg_02.txt', 'rb') as fp: email.parser.BytesParser().parse(fp) self.assertFalse(fp.closed) def test_bytes_parser_on_exception_does_not_close_file(self): with openfile('msg_15.txt', 'rb') as fp: bytesParser = email.parser.BytesParser self.assertRaises(email.errors.StartBoundaryNotFoundDefect, bytesParser(policy=email.policy.strict).parse, fp) self.assertFalse(fp.closed) def test_parser_does_not_close_file(self): with openfile('msg_02.txt', 'r') as fp: email.parser.Parser().parse(fp) self.assertFalse(fp.closed) def test_parser_on_exception_does_not_close_file(self): with openfile('msg_15.txt', 'r') as fp: parser = email.parser.Parser self.assertRaises(email.errors.StartBoundaryNotFoundDefect, parser(policy=email.policy.strict).parse, fp) self.assertFalse(fp.closed) def test_whitespace_continuation(self): eq = self.assertEqual # This message contains a line after the Subject: header that has only # whitespace, but it is not empty! msg = email.message_from_string("""\ From: [email protected] To: [email protected] Subject: the next line has a space on it \x20 Date: Mon, 8 Apr 2002 15:09:19 -0400 Message-ID: spam Here's the message body """) eq(msg['subject'], 'the next line has a space on it\n ') eq(msg['message-id'], 'spam') eq(msg.get_payload(), "Here's the message body\n") def test_whitespace_continuation_last_header(self): eq = self.assertEqual # Like the previous test, but the subject line is the last # header. msg = email.message_from_string("""\ From: [email protected] To: [email protected] Date: Mon, 8 Apr 2002 15:09:19 -0400 Message-ID: spam Subject: the next line has a space on it \x20 Here's the message body """) eq(msg['subject'], 'the next line has a space on it\n ') eq(msg['message-id'], 'spam') eq(msg.get_payload(), "Here's the message body\n") def test_crlf_separation(self): eq = self.assertEqual with openfile('msg_26.txt', newline='\n') as fp: msg = Parser().parse(fp) eq(len(msg.get_payload()), 2) part1 = msg.get_payload(0) eq(part1.get_content_type(), 'text/plain') eq(part1.get_payload(), 'Simple email with attachment.\r\n\r\n') part2 = msg.get_payload(1) eq(part2.get_content_type(), 'application/riscos') def test_crlf_flatten(self): # Using newline='\n' preserves the crlfs in this input file. with openfile('msg_26.txt', newline='\n') as fp: text = fp.read() msg = email.message_from_string(text) s = StringIO() g = Generator(s) g.flatten(msg, linesep='\r\n') self.assertEqual(s.getvalue(), text) maxDiff = None def test_multipart_digest_with_extra_mime_headers(self): eq = self.assertEqual neq = self.ndiffAssertEqual with openfile('msg_28.txt') as fp: msg = email.message_from_file(fp) # Structure is: # multipart/digest # message/rfc822 # text/plain # message/rfc822 # text/plain eq(msg.is_multipart(), 1) eq(len(msg.get_payload()), 2) part1 = msg.get_payload(0) eq(part1.get_content_type(), 'message/rfc822') eq(part1.is_multipart(), 1) eq(len(part1.get_payload()), 1) part1a = part1.get_payload(0) eq(part1a.is_multipart(), 0) eq(part1a.get_content_type(), 'text/plain') neq(part1a.get_payload(), 'message 1\n') # next message/rfc822 part2 = msg.get_payload(1) eq(part2.get_content_type(), 'message/rfc822') eq(part2.is_multipart(), 1) eq(len(part2.get_payload()), 1) part2a = part2.get_payload(0) eq(part2a.is_multipart(), 0) eq(part2a.get_content_type(), 'text/plain') neq(part2a.get_payload(), 'message 2\n') def test_three_lines(self): # A bug report by Andrew McNamara lines = ['From: Andrew Person <[email protected]', 'Subject: Test', 'Date: Tue, 20 Aug 2002 16:43:45 +1000'] msg = email.message_from_string(NL.join(lines)) self.assertEqual(msg['date'], 'Tue, 20 Aug 2002 16:43:45 +1000') def test_strip_line_feed_and_carriage_return_in_headers(self): eq = self.assertEqual # For [ 1002475 ] email message parser doesn't handle \r\n correctly value1 = 'text' value2 = 'more text' m = 'Header: %s\r\nNext-Header: %s\r\n\r\nBody\r\n\r\n' % ( value1, value2) msg = email.message_from_string(m) eq(msg.get('Header'), value1) eq(msg.get('Next-Header'), value2) def test_rfc2822_header_syntax(self): eq = self.assertEqual m = '>From: foo\nFrom: bar\n!"#QUX;~: zoo\n\nbody' msg = email.message_from_string(m) eq(len(msg), 3) eq(sorted(field for field in msg), ['!"#QUX;~', '>From', 'From']) eq(msg.get_payload(), 'body') def test_rfc2822_space_not_allowed_in_header(self): eq = self.assertEqual m = '>From [email protected] 11:25:53\nFrom: bar\n!"#QUX;~: zoo\n\nbody' msg = email.message_from_string(m) eq(len(msg.keys()), 0) def test_rfc2822_one_character_header(self): eq = self.assertEqual m = 'A: first header\nB: second header\nCC: third header\n\nbody' msg = email.message_from_string(m) headers = msg.keys() headers.sort() eq(headers, ['A', 'B', 'CC']) eq(msg.get_payload(), 'body') def test_CRLFLF_at_end_of_part(self): # issue 5610: feedparser should not eat two chars from body part ending # with "\r\n\n". m = ( "From: [email protected]\n" "To: baz\n" "Mime-Version: 1.0\n" "Content-Type: multipart/mixed; boundary=BOUNDARY\n" "\n" "--BOUNDARY\n" "Content-Type: text/plain\n" "\n" "body ending with CRLF newline\r\n" "\n" "--BOUNDARY--\n" ) msg = email.message_from_string(m) self.assertTrue(msg.get_payload(0).get_payload().endswith('\r\n')) class Test8BitBytesHandling(TestEmailBase): # In Python3 all input is string, but that doesn't work if the actual input # uses an 8bit transfer encoding. To hack around that, in email 5.1 we # decode byte streams using the surrogateescape error handler, and # reconvert to binary at appropriate places if we detect surrogates. This # doesn't allow us to transform headers with 8bit bytes (they get munged), # but it does allow us to parse and preserve them, and to decode body # parts that use an 8bit CTE. bodytest_msg = textwrap.dedent("""\ From: [email protected] To: baz Mime-Version: 1.0 Content-Type: text/plain; charset={charset} Content-Transfer-Encoding: {cte} {bodyline} """) def test_known_8bit_CTE(self): m = self.bodytest_msg.format(charset='utf-8', cte='8bit', bodyline='pöstal').encode('utf-8') msg = email.message_from_bytes(m) self.assertEqual(msg.get_payload(), "pöstal\n") self.assertEqual(msg.get_payload(decode=True), "pöstal\n".encode('utf-8')) def test_unknown_8bit_CTE(self): m = self.bodytest_msg.format(charset='notavalidcharset', cte='8bit', bodyline='pöstal').encode('utf-8') msg = email.message_from_bytes(m) self.assertEqual(msg.get_payload(), "p\uFFFD\uFFFDstal\n") self.assertEqual(msg.get_payload(decode=True), "pöstal\n".encode('utf-8')) def test_8bit_in_quopri_body(self): # This is non-RFC compliant data...without 'decode' the library code # decodes the body using the charset from the headers, and because the # source byte really is utf-8 this works. This is likely to fail # against real dirty data (ie: produce mojibake), but the data is # invalid anyway so it is as good a guess as any. But this means that # this test just confirms the current behavior; that behavior is not # necessarily the best possible behavior. With 'decode' it is # returning the raw bytes, so that test should be of correct behavior, # or at least produce the same result that email4 did. m = self.bodytest_msg.format(charset='utf-8', cte='quoted-printable', bodyline='p=C3=B6stál').encode('utf-8') msg = email.message_from_bytes(m) self.assertEqual(msg.get_payload(), 'p=C3=B6stál\n') self.assertEqual(msg.get_payload(decode=True), 'pöstál\n'.encode('utf-8')) def test_invalid_8bit_in_non_8bit_cte_uses_replace(self): # This is similar to the previous test, but proves that if the 8bit # byte is undecodeable in the specified charset, it gets replaced # by the unicode 'unknown' character. Again, this may or may not # be the ideal behavior. Note that if decode=False none of the # decoders will get involved, so this is the only test we need # for this behavior. m = self.bodytest_msg.format(charset='ascii', cte='quoted-printable', bodyline='p=C3=B6stál').encode('utf-8') msg = email.message_from_bytes(m) self.assertEqual(msg.get_payload(), 'p=C3=B6st\uFFFD\uFFFDl\n') self.assertEqual(msg.get_payload(decode=True), 'pöstál\n'.encode('utf-8')) # test_defect_handling:test_invalid_chars_in_base64_payload def test_8bit_in_base64_body(self): # If we get 8bit bytes in a base64 body, we can just ignore them # as being outside the base64 alphabet and decode anyway. But # we register a defect. m = self.bodytest_msg.format(charset='utf-8', cte='base64', bodyline='cMO2c3RhbAá=').encode('utf-8') msg = email.message_from_bytes(m) self.assertEqual(msg.get_payload(decode=True), 'pöstal'.encode('utf-8')) self.assertIsInstance(msg.defects[0], errors.InvalidBase64CharactersDefect) def test_8bit_in_uuencode_body(self): # Sticking an 8bit byte in a uuencode block makes it undecodable by # normal means, so the block is returned undecoded, but as bytes. m = self.bodytest_msg.format(charset='utf-8', cte='uuencode', bodyline='<,.V<W1A; á ').encode('utf-8') msg = email.message_from_bytes(m) self.assertEqual(msg.get_payload(decode=True), '<,.V<W1A; á \n'.encode('utf-8')) headertest_headers = ( ('From: [email protected]', ('From', '[email protected]')), ('To: báz', ('To', '=?unknown-8bit?q?b=C3=A1z?=')), ('Subject: Maintenant je vous présente mon collègue, le pouf célèbre\n' '\tJean de Baddie', ('Subject', '=?unknown-8bit?q?Maintenant_je_vous_pr=C3=A9sente_mon_' 'coll=C3=A8gue=2C_le_pouf_c=C3=A9l=C3=A8bre?=\n' ' =?unknown-8bit?q?_Jean_de_Baddie?=')), ('From: göst', ('From', '=?unknown-8bit?b?Z8O2c3Q=?=')), ) headertest_msg = ('\n'.join([src for (src, _) in headertest_headers]) + '\nYes, they are flying.\n').encode('utf-8') def test_get_8bit_header(self): msg = email.message_from_bytes(self.headertest_msg) self.assertEqual(str(msg.get('to')), 'b\uFFFD\uFFFDz') self.assertEqual(str(msg['to']), 'b\uFFFD\uFFFDz') def test_print_8bit_headers(self): msg = email.message_from_bytes(self.headertest_msg) self.assertEqual(str(msg), textwrap.dedent("""\ From: {} To: {} Subject: {} From: {} Yes, they are flying. """).format(*[expected[1] for (_, expected) in self.headertest_headers])) def test_values_with_8bit_headers(self): msg = email.message_from_bytes(self.headertest_msg) self.assertListEqual([str(x) for x in msg.values()], ['[email protected]', 'b\uFFFD\uFFFDz', 'Maintenant je vous pr\uFFFD\uFFFDsente mon ' 'coll\uFFFD\uFFFDgue, le pouf ' 'c\uFFFD\uFFFDl\uFFFD\uFFFDbre\n' '\tJean de Baddie', "g\uFFFD\uFFFDst"]) def test_items_with_8bit_headers(self): msg = email.message_from_bytes(self.headertest_msg) self.assertListEqual([(str(x), str(y)) for (x, y) in msg.items()], [('From', '[email protected]'), ('To', 'b\uFFFD\uFFFDz'), ('Subject', 'Maintenant je vous ' 'pr\uFFFD\uFFFDsente ' 'mon coll\uFFFD\uFFFDgue, le pouf ' 'c\uFFFD\uFFFDl\uFFFD\uFFFDbre\n' '\tJean de Baddie'), ('From', 'g\uFFFD\uFFFDst')]) def test_get_all_with_8bit_headers(self): msg = email.message_from_bytes(self.headertest_msg) self.assertListEqual([str(x) for x in msg.get_all('from')], ['[email protected]', 'g\uFFFD\uFFFDst']) def test_get_content_type_with_8bit(self): msg = email.message_from_bytes(textwrap.dedent("""\ Content-Type: text/pl\xA7in; charset=utf-8 """).encode('latin-1')) self.assertEqual(msg.get_content_type(), "text/pl\uFFFDin") self.assertEqual(msg.get_content_maintype(), "text") self.assertEqual(msg.get_content_subtype(), "pl\uFFFDin") # test_headerregistry.TestContentTypeHeader.non_ascii_in_params def test_get_params_with_8bit(self): msg = email.message_from_bytes( 'X-Header: foo=\xa7ne; b\xa7r=two; baz=three\n'.encode('latin-1')) self.assertEqual(msg.get_params(header='x-header'), [('foo', '\uFFFDne'), ('b\uFFFDr', 'two'), ('baz', 'three')]) self.assertEqual(msg.get_param('Foo', header='x-header'), '\uFFFdne') # XXX: someday you might be able to get 'b\xa7r', for now you can't. self.assertEqual(msg.get_param('b\xa7r', header='x-header'), None) # test_headerregistry.TestContentTypeHeader.non_ascii_in_rfc2231_value def test_get_rfc2231_params_with_8bit(self): msg = email.message_from_bytes(textwrap.dedent("""\ Content-Type: text/plain; charset=us-ascii; title*=us-ascii'en'This%20is%20not%20f\xa7n""" ).encode('latin-1')) self.assertEqual(msg.get_param('title'), ('us-ascii', 'en', 'This is not f\uFFFDn')) def test_set_rfc2231_params_with_8bit(self): msg = email.message_from_bytes(textwrap.dedent("""\ Content-Type: text/plain; charset=us-ascii; title*=us-ascii'en'This%20is%20not%20f\xa7n""" ).encode('latin-1')) msg.set_param('title', 'test') self.assertEqual(msg.get_param('title'), 'test') def test_del_rfc2231_params_with_8bit(self): msg = email.message_from_bytes(textwrap.dedent("""\ Content-Type: text/plain; charset=us-ascii; title*=us-ascii'en'This%20is%20not%20f\xa7n""" ).encode('latin-1')) msg.del_param('title') self.assertEqual(msg.get_param('title'), None) self.assertEqual(msg.get_content_maintype(), 'text') def test_get_payload_with_8bit_cte_header(self): msg = email.message_from_bytes(textwrap.dedent("""\ Content-Transfer-Encoding: b\xa7se64 Content-Type: text/plain; charset=latin-1 payload """).encode('latin-1')) self.assertEqual(msg.get_payload(), 'payload\n') self.assertEqual(msg.get_payload(decode=True), b'payload\n') non_latin_bin_msg = textwrap.dedent("""\ From: [email protected] To: báz Subject: Maintenant je vous présente mon collègue, le pouf célèbre \tJean de Baddie Mime-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: 8bit Да, они летят. """).encode('utf-8') def test_bytes_generator(self): msg = email.message_from_bytes(self.non_latin_bin_msg) out = BytesIO() email.generator.BytesGenerator(out).flatten(msg) self.assertEqual(out.getvalue(), self.non_latin_bin_msg) def test_bytes_generator_handles_None_body(self): #Issue 11019 msg = email.message.Message() out = BytesIO() email.generator.BytesGenerator(out).flatten(msg) self.assertEqual(out.getvalue(), b"\n") non_latin_bin_msg_as7bit_wrapped = textwrap.dedent("""\ From: [email protected] To: =?unknown-8bit?q?b=C3=A1z?= Subject: =?unknown-8bit?q?Maintenant_je_vous_pr=C3=A9sente_mon_coll=C3=A8gue?= =?unknown-8bit?q?=2C_le_pouf_c=C3=A9l=C3=A8bre?= =?unknown-8bit?q?_Jean_de_Baddie?= Mime-Version: 1.0 Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: base64 0JTQsCwg0L7QvdC4INC70LXRgtGP0YIuCg== """) def test_generator_handles_8bit(self): msg = email.message_from_bytes(self.non_latin_bin_msg) out = StringIO() email.generator.Generator(out).flatten(msg) self.assertEqual(out.getvalue(), self.non_latin_bin_msg_as7bit_wrapped) def test_str_generator_should_not_mutate_msg_when_handling_8bit(self): msg = email.message_from_bytes(self.non_latin_bin_msg) out = BytesIO() BytesGenerator(out).flatten(msg) orig_value = out.getvalue() Generator(StringIO()).flatten(msg) # Should not mutate msg! out = BytesIO() BytesGenerator(out).flatten(msg) self.assertEqual(out.getvalue(), orig_value) def test_bytes_generator_with_unix_from(self): # The unixfrom contains a current date, so we can't check it # literally. Just make sure the first word is 'From' and the # rest of the message matches the input. msg = email.message_from_bytes(self.non_latin_bin_msg) out = BytesIO() email.generator.BytesGenerator(out).flatten(msg, unixfrom=True) lines = out.getvalue().split(b'\n') self.assertEqual(lines[0].split()[0], b'From') self.assertEqual(b'\n'.join(lines[1:]), self.non_latin_bin_msg) non_latin_bin_msg_as7bit = non_latin_bin_msg_as7bit_wrapped.split('\n') non_latin_bin_msg_as7bit[2:4] = [ 'Subject: =?unknown-8bit?q?Maintenant_je_vous_pr=C3=A9sente_mon_' 'coll=C3=A8gue=2C_le_pouf_c=C3=A9l=C3=A8bre?='] non_latin_bin_msg_as7bit = '\n'.join(non_latin_bin_msg_as7bit) def test_message_from_binary_file(self): fn = os.path.join(os.environ['TMPDIR'], 'test.msg') self.addCleanup(unlink, fn) with open(fn, 'wb') as testfile: testfile.write(self.non_latin_bin_msg) with open(fn, 'rb') as testfile: m = email.parser.BytesParser().parse(testfile) self.assertEqual(str(m), self.non_latin_bin_msg_as7bit) latin_bin_msg = textwrap.dedent("""\ From: [email protected] To: Dinsdale Subject: Nudge nudge, wink, wink Mime-Version: 1.0 Content-Type: text/plain; charset="latin-1" Content-Transfer-Encoding: 8bit oh là là, know what I mean, know what I mean? """).encode('latin-1') latin_bin_msg_as7bit = textwrap.dedent("""\ From: [email protected] To: Dinsdale Subject: Nudge nudge, wink, wink Mime-Version: 1.0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable oh l=E0 l=E0, know what I mean, know what I mean? """) def test_string_generator_reencodes_to_quopri_when_appropriate(self): m = email.message_from_bytes(self.latin_bin_msg) self.assertEqual(str(m), self.latin_bin_msg_as7bit) def test_decoded_generator_emits_unicode_body(self): m = email.message_from_bytes(self.latin_bin_msg) out = StringIO() email.generator.DecodedGenerator(out).flatten(m) #DecodedHeader output contains an extra blank line compared #to the input message. RDM: not sure if this is a bug or not, #but it is not specific to the 8bit->7bit conversion. self.assertEqual(out.getvalue(), self.latin_bin_msg.decode('latin-1')+'\n') def test_bytes_feedparser(self): bfp = email.feedparser.BytesFeedParser() for i in range(0, len(self.latin_bin_msg), 10): bfp.feed(self.latin_bin_msg[i:i+10]) m = bfp.close() self.assertEqual(str(m), self.latin_bin_msg_as7bit) def test_crlf_flatten(self): with openfile('msg_26.txt', 'rb') as fp: text = fp.read() msg = email.message_from_bytes(text) s = BytesIO() g = email.generator.BytesGenerator(s) g.flatten(msg, linesep='\r\n') self.assertEqual(s.getvalue(), text) def test_8bit_multipart(self): # Issue 11605 source = textwrap.dedent("""\ Date: Fri, 18 Mar 2011 17:15:43 +0100 To: [email protected] From: foodwatch-Newsletter <[email protected]> Subject: Aktuelles zu Japan, Klonfleisch und Smiley-System Message-ID: <[email protected]> MIME-Version: 1.0 Content-Type: multipart/alternative; boundary="b1_76a486bee62b0d200f33dc2ca08220ad" --b1_76a486bee62b0d200f33dc2ca08220ad Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: 8bit Guten Tag, , mit großer Betroffenheit verfolgen auch wir im foodwatch-Team die Nachrichten aus Japan. --b1_76a486bee62b0d200f33dc2ca08220ad Content-Type: text/html; charset="utf-8" Content-Transfer-Encoding: 8bit <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html lang="de"> <head> <title>foodwatch - Newsletter</title> </head> <body> <p>mit gro&szlig;er Betroffenheit verfolgen auch wir im foodwatch-Team die Nachrichten aus Japan.</p> </body> </html> --b1_76a486bee62b0d200f33dc2ca08220ad-- """).encode('utf-8') msg = email.message_from_bytes(source) s = BytesIO() g = email.generator.BytesGenerator(s) g.flatten(msg) self.assertEqual(s.getvalue(), source) def test_bytes_generator_b_encoding_linesep(self): # Issue 14062: b encoding was tacking on an extra \n. m = Message() # This has enough non-ascii that it should always end up b encoded. m['Subject'] = Header('žluÅ¥oučký kůň') s = BytesIO() g = email.generator.BytesGenerator(s) g.flatten(m, linesep='\r\n') self.assertEqual( s.getvalue(), b'Subject: =?utf-8?b?xb5sdcWlb3XEjWvDvSBrxa/FiA==?=\r\n\r\n') def test_generator_b_encoding_linesep(self): # Since this broke in ByteGenerator, test Generator for completeness. m = Message() # This has enough non-ascii that it should always end up b encoded. m['Subject'] = Header('žluÅ¥oučký kůň') s = StringIO() g = email.generator.Generator(s) g.flatten(m, linesep='\r\n') self.assertEqual( s.getvalue(), 'Subject: =?utf-8?b?xb5sdcWlb3XEjWvDvSBrxa/FiA==?=\r\n\r\n') maxDiff = None class BaseTestBytesGeneratorIdempotent: maxDiff = None def _msgobj(self, filename): with openfile(filename, 'rb') as fp: data = fp.read() data = self.normalize_linesep_regex.sub(self.blinesep, data) msg = email.message_from_bytes(data) return msg, data def _idempotent(self, msg, data, unixfrom=False): b = BytesIO() g = email.generator.BytesGenerator(b, maxheaderlen=0) g.flatten(msg, unixfrom=unixfrom, linesep=self.linesep) self.assertEqual(data, b.getvalue()) class TestBytesGeneratorIdempotentNL(BaseTestBytesGeneratorIdempotent, TestIdempotent): linesep = '\n' blinesep = b'\n' normalize_linesep_regex = re.compile(br'\r\n') class TestBytesGeneratorIdempotentCRLF(BaseTestBytesGeneratorIdempotent, TestIdempotent): linesep = '\r\n' blinesep = b'\r\n' normalize_linesep_regex = re.compile(br'(?<!\r)\n') class TestBase64(unittest.TestCase): def test_len(self): eq = self.assertEqual eq(base64mime.header_length('hello'), len(base64mime.body_encode(b'hello', eol=''))) for size in range(15): if size == 0 : bsize = 0 elif size <= 3 : bsize = 4 elif size <= 6 : bsize = 8 elif size <= 9 : bsize = 12 elif size <= 12: bsize = 16 else : bsize = 20 eq(base64mime.header_length('x' * size), bsize) def test_decode(self): eq = self.assertEqual eq(base64mime.decode(''), b'') eq(base64mime.decode('aGVsbG8='), b'hello') def test_encode(self): eq = self.assertEqual eq(base64mime.body_encode(b''), b'') eq(base64mime.body_encode(b'hello'), 'aGVsbG8=\n') # Test the binary flag eq(base64mime.body_encode(b'hello\n'), 'aGVsbG8K\n') # Test the maxlinelen arg eq(base64mime.body_encode(b'xxxx ' * 20, maxlinelen=40), """\ eHh4eCB4eHh4IHh4eHggeHh4eCB4eHh4IHh4eHgg eHh4eCB4eHh4IHh4eHggeHh4eCB4eHh4IHh4eHgg eHh4eCB4eHh4IHh4eHggeHh4eCB4eHh4IHh4eHgg eHh4eCB4eHh4IA== """) # Test the eol argument eq(base64mime.body_encode(b'xxxx ' * 20, maxlinelen=40, eol='\r\n'), """\ eHh4eCB4eHh4IHh4eHggeHh4eCB4eHh4IHh4eHgg\r eHh4eCB4eHh4IHh4eHggeHh4eCB4eHh4IHh4eHgg\r eHh4eCB4eHh4IHh4eHggeHh4eCB4eHh4IHh4eHgg\r eHh4eCB4eHh4IA==\r """) def test_header_encode(self): eq = self.assertEqual he = base64mime.header_encode eq(he('hello'), '=?iso-8859-1?b?aGVsbG8=?=') eq(he('hello\r\nworld'), '=?iso-8859-1?b?aGVsbG8NCndvcmxk?=') eq(he('hello\nworld'), '=?iso-8859-1?b?aGVsbG8Kd29ybGQ=?=') # Test the charset option eq(he('hello', charset='iso-8859-2'), '=?iso-8859-2?b?aGVsbG8=?=') eq(he('hello\nworld'), '=?iso-8859-1?b?aGVsbG8Kd29ybGQ=?=') class TestQuopri(unittest.TestCase): def setUp(self): # Set of characters (as byte integers) that don't need to be encoded # in headers. self.hlit = list(chain( range(ord('a'), ord('z') + 1), range(ord('A'), ord('Z') + 1), range(ord('0'), ord('9') + 1), (c for c in b'!*+-/'))) # Set of characters (as byte integers) that do need to be encoded in # headers. self.hnon = [c for c in range(256) if c not in self.hlit] assert len(self.hlit) + len(self.hnon) == 256 # Set of characters (as byte integers) that don't need to be encoded # in bodies. self.blit = list(range(ord(' '), ord('~') + 1)) self.blit.append(ord('\t')) self.blit.remove(ord('=')) # Set of characters (as byte integers) that do need to be encoded in # bodies. self.bnon = [c for c in range(256) if c not in self.blit] assert len(self.blit) + len(self.bnon) == 256 def test_quopri_header_check(self): for c in self.hlit: self.assertFalse(quoprimime.header_check(c), 'Should not be header quopri encoded: %s' % chr(c)) for c in self.hnon: self.assertTrue(quoprimime.header_check(c), 'Should be header quopri encoded: %s' % chr(c)) def test_quopri_body_check(self): for c in self.blit: self.assertFalse(quoprimime.body_check(c), 'Should not be body quopri encoded: %s' % chr(c)) for c in self.bnon: self.assertTrue(quoprimime.body_check(c), 'Should be body quopri encoded: %s' % chr(c)) def test_header_quopri_len(self): eq = self.assertEqual eq(quoprimime.header_length(b'hello'), 5) # RFC 2047 chrome is not included in header_length(). eq(len(quoprimime.header_encode(b'hello', charset='xxx')), quoprimime.header_length(b'hello') + # =?xxx?q?...?= means 10 extra characters 10) eq(quoprimime.header_length(b'h@e@l@l@o@'), 20) # RFC 2047 chrome is not included in header_length(). eq(len(quoprimime.header_encode(b'h@e@l@l@o@', charset='xxx')), quoprimime.header_length(b'h@e@l@l@o@') + # =?xxx?q?...?= means 10 extra characters 10) for c in self.hlit: eq(quoprimime.header_length(bytes([c])), 1, 'expected length 1 for %r' % chr(c)) for c in self.hnon: # Space is special; it's encoded to _ if c == ord(' '): continue eq(quoprimime.header_length(bytes([c])), 3, 'expected length 3 for %r' % chr(c)) eq(quoprimime.header_length(b' '), 1) def test_body_quopri_len(self): eq = self.assertEqual for c in self.blit: eq(quoprimime.body_length(bytes([c])), 1) for c in self.bnon: eq(quoprimime.body_length(bytes([c])), 3) def test_quote_unquote_idempotent(self): for x in range(256): c = chr(x) self.assertEqual(quoprimime.unquote(quoprimime.quote(c)), c) def _test_header_encode(self, header, expected_encoded_header, charset=None): if charset is None: encoded_header = quoprimime.header_encode(header) else: encoded_header = quoprimime.header_encode(header, charset) self.assertEqual(encoded_header, expected_encoded_header) def test_header_encode_null(self): self._test_header_encode(b'', '') def test_header_encode_one_word(self): self._test_header_encode(b'hello', '=?iso-8859-1?q?hello?=') def test_header_encode_two_lines(self): self._test_header_encode(b'hello\nworld', '=?iso-8859-1?q?hello=0Aworld?=') def test_header_encode_non_ascii(self): self._test_header_encode(b'hello\xc7there', '=?iso-8859-1?q?hello=C7there?=') def test_header_encode_alt_charset(self): self._test_header_encode(b'hello', '=?iso-8859-2?q?hello?=', charset='iso-8859-2') def _test_header_decode(self, encoded_header, expected_decoded_header): decoded_header = quoprimime.header_decode(encoded_header) self.assertEqual(decoded_header, expected_decoded_header) def test_header_decode_null(self): self._test_header_decode('', '') def test_header_decode_one_word(self): self._test_header_decode('hello', 'hello') def test_header_decode_two_lines(self): self._test_header_decode('hello=0Aworld', 'hello\nworld') def test_header_decode_non_ascii(self): self._test_header_decode('hello=C7there', 'hello\xc7there') def test_header_decode_re_bug_18380(self): # Issue 18380: Call re.sub with a positional argument for flags in the wrong position self.assertEqual(quoprimime.header_decode('=30' * 257), '0' * 257) def _test_decode(self, encoded, expected_decoded, eol=None): if eol is None: decoded = quoprimime.decode(encoded) else: decoded = quoprimime.decode(encoded, eol=eol) self.assertEqual(decoded, expected_decoded) def test_decode_null_word(self): self._test_decode('', '') def test_decode_null_line_null_word(self): self._test_decode('\r\n', '\n') def test_decode_one_word(self): self._test_decode('hello', 'hello') def test_decode_one_word_eol(self): self._test_decode('hello', 'hello', eol='X') def test_decode_one_line(self): self._test_decode('hello\r\n', 'hello\n') def test_decode_one_line_lf(self): self._test_decode('hello\n', 'hello\n') def test_decode_one_line_cr(self): self._test_decode('hello\r', 'hello\n') def test_decode_one_line_nl(self): self._test_decode('hello\n', 'helloX', eol='X') def test_decode_one_line_crnl(self): self._test_decode('hello\r\n', 'helloX', eol='X') def test_decode_one_line_one_word(self): self._test_decode('hello\r\nworld', 'hello\nworld') def test_decode_one_line_one_word_eol(self): self._test_decode('hello\r\nworld', 'helloXworld', eol='X') def test_decode_two_lines(self): self._test_decode('hello\r\nworld\r\n', 'hello\nworld\n') def test_decode_two_lines_eol(self): self._test_decode('hello\r\nworld\r\n', 'helloXworldX', eol='X') def test_decode_one_long_line(self): self._test_decode('Spam' * 250, 'Spam' * 250) def test_decode_one_space(self): self._test_decode(' ', '') def test_decode_multiple_spaces(self): self._test_decode(' ' * 5, '') def test_decode_one_line_trailing_spaces(self): self._test_decode('hello \r\n', 'hello\n') def test_decode_two_lines_trailing_spaces(self): self._test_decode('hello \r\nworld \r\n', 'hello\nworld\n') def test_decode_quoted_word(self): self._test_decode('=22quoted=20words=22', '"quoted words"') def test_decode_uppercase_quoting(self): self._test_decode('ab=CD=EF', 'ab\xcd\xef') def test_decode_lowercase_quoting(self): self._test_decode('ab=cd=ef', 'ab\xcd\xef') def test_decode_soft_line_break(self): self._test_decode('soft line=\r\nbreak', 'soft linebreak') def test_decode_false_quoting(self): self._test_decode('A=1,B=A ==> A+B==2', 'A=1,B=A ==> A+B==2') def _test_encode(self, body, expected_encoded_body, maxlinelen=None, eol=None): kwargs = {} if maxlinelen is None: # Use body_encode's default. maxlinelen = 76 else: kwargs['maxlinelen'] = maxlinelen if eol is None: # Use body_encode's default. eol = '\n' else: kwargs['eol'] = eol encoded_body = quoprimime.body_encode(body, **kwargs) self.assertEqual(encoded_body, expected_encoded_body) if eol == '\n' or eol == '\r\n': # We know how to split the result back into lines, so maxlinelen # can be checked. for line in encoded_body.splitlines(): self.assertLessEqual(len(line), maxlinelen) def test_encode_null(self): self._test_encode('', '') def test_encode_null_lines(self): self._test_encode('\n\n', '\n\n') def test_encode_one_line(self): self._test_encode('hello\n', 'hello\n') def test_encode_one_line_crlf(self): self._test_encode('hello\r\n', 'hello\n') def test_encode_one_line_eol(self): self._test_encode('hello\n', 'hello\r\n', eol='\r\n') def test_encode_one_line_eol_after_non_ascii(self): # issue 20206; see changeset 0cf700464177 for why the encode/decode. self._test_encode('hello\u03c5\n'.encode('utf-8').decode('latin1'), 'hello=CF=85\r\n', eol='\r\n') def test_encode_one_space(self): self._test_encode(' ', '=20') def test_encode_one_line_one_space(self): self._test_encode(' \n', '=20\n') # XXX: body_encode() expect strings, but uses ord(char) from these strings # to index into a 256-entry list. For code points above 255, this will fail. # Should there be a check for 8-bit only ord() values in body, or at least # a comment about the expected input? def test_encode_two_lines_one_space(self): self._test_encode(' \n \n', '=20\n=20\n') def test_encode_one_word_trailing_spaces(self): self._test_encode('hello ', 'hello =20') def test_encode_one_line_trailing_spaces(self): self._test_encode('hello \n', 'hello =20\n') def test_encode_one_word_trailing_tab(self): self._test_encode('hello \t', 'hello =09') def test_encode_one_line_trailing_tab(self): self._test_encode('hello \t\n', 'hello =09\n') def test_encode_trailing_space_before_maxlinelen(self): self._test_encode('abcd \n1234', 'abcd =\n\n1234', maxlinelen=6) def test_encode_trailing_space_at_maxlinelen(self): self._test_encode('abcd \n1234', 'abcd=\n=20\n1234', maxlinelen=5) def test_encode_trailing_space_beyond_maxlinelen(self): self._test_encode('abcd \n1234', 'abc=\nd=20\n1234', maxlinelen=4) def test_encode_whitespace_lines(self): self._test_encode(' \n' * 5, '=20\n' * 5) def test_encode_quoted_equals(self): self._test_encode('a = b', 'a =3D b') def test_encode_one_long_string(self): self._test_encode('x' * 100, 'x' * 75 + '=\n' + 'x' * 25) def test_encode_one_long_line(self): self._test_encode('x' * 100 + '\n', 'x' * 75 + '=\n' + 'x' * 25 + '\n') def test_encode_one_very_long_line(self): self._test_encode('x' * 200 + '\n', 2 * ('x' * 75 + '=\n') + 'x' * 50 + '\n') def test_encode_shortest_maxlinelen(self): self._test_encode('=' * 5, '=3D=\n' * 4 + '=3D', maxlinelen=4) def test_encode_maxlinelen_too_small(self): self.assertRaises(ValueError, self._test_encode, '', '', maxlinelen=3) def test_encode(self): eq = self.assertEqual eq(quoprimime.body_encode(''), '') eq(quoprimime.body_encode('hello'), 'hello') # Test the binary flag eq(quoprimime.body_encode('hello\r\nworld'), 'hello\nworld') # Test the maxlinelen arg eq(quoprimime.body_encode('xxxx ' * 20, maxlinelen=40), """\ xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx= xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxx= x xxxx xxxx xxxx xxxx=20""") # Test the eol argument eq(quoprimime.body_encode('xxxx ' * 20, maxlinelen=40, eol='\r\n'), """\ xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx=\r xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxx=\r x xxxx xxxx xxxx xxxx=20""") eq(quoprimime.body_encode("""\ one line two line"""), """\ one line two line""") # Test the Charset class class TestCharset(unittest.TestCase): def tearDown(self): from email import charset as CharsetModule try: del CharsetModule.CHARSETS['fake'] except KeyError: pass def test_codec_encodeable(self): eq = self.assertEqual # Make sure us-ascii = no Unicode conversion c = Charset('us-ascii') eq(c.header_encode('Hello World!'), 'Hello World!') # Test 8-bit idempotency with us-ascii s = '\xa4\xa2\xa4\xa4\xa4\xa6\xa4\xa8\xa4\xaa' self.assertRaises(UnicodeError, c.header_encode, s) c = Charset('utf-8') eq(c.header_encode(s), '=?utf-8?b?wqTCosKkwqTCpMKmwqTCqMKkwqo=?=') def test_body_encode(self): eq = self.assertEqual # Try a charset with QP body encoding c = Charset('iso-8859-1') eq('hello w=F6rld', c.body_encode('hello w\xf6rld')) # Try a charset with Base64 body encoding c = Charset('utf-8') eq('aGVsbG8gd29ybGQ=\n', c.body_encode(b'hello world')) # Try a charset with None body encoding c = Charset('us-ascii') eq('hello world', c.body_encode('hello world')) # Try the convert argument, where input codec != output codec c = Charset('euc-jp') # With apologies to Tokio Kikuchi ;) # XXX FIXME ## try: ## eq('\x1b$B5FCO;~IW\x1b(B', ## c.body_encode('\xb5\xc6\xc3\xcf\xbb\xfe\xc9\xd7')) ## eq('\xb5\xc6\xc3\xcf\xbb\xfe\xc9\xd7', ## c.body_encode('\xb5\xc6\xc3\xcf\xbb\xfe\xc9\xd7', False)) ## except LookupError: ## # We probably don't have the Japanese codecs installed ## pass # Testing SF bug #625509, which we have to fake, since there are no # built-in encodings where the header encoding is QP but the body # encoding is not. from email import charset as CharsetModule CharsetModule.add_charset('fake', CharsetModule.QP, None, 'utf-8') c = Charset('fake') eq('hello world', c.body_encode('hello world')) def test_unicode_charset_name(self): charset = Charset('us-ascii') self.assertEqual(str(charset), 'us-ascii') self.assertRaises(errors.CharsetError, Charset, 'asc\xffii') # Test multilingual MIME headers. class TestHeader(TestEmailBase): def test_simple(self): eq = self.ndiffAssertEqual h = Header('Hello World!') eq(h.encode(), 'Hello World!') h.append(' Goodbye World!') eq(h.encode(), 'Hello World! Goodbye World!') def test_simple_surprise(self): eq = self.ndiffAssertEqual h = Header('Hello World!') eq(h.encode(), 'Hello World!') h.append('Goodbye World!') eq(h.encode(), 'Hello World! Goodbye World!') def test_header_needs_no_decoding(self): h = 'no decoding needed' self.assertEqual(decode_header(h), [(h, None)]) def test_long(self): h = Header("I am the very model of a modern Major-General; I've information vegetable, animal, and mineral; I know the kings of England, and I quote the fights historical from Marathon to Waterloo, in order categorical; I'm very well acquainted, too, with matters mathematical; I understand equations, both the simple and quadratical; about binomial theorem I'm teeming with a lot o' news, with many cheerful facts about the square of the hypotenuse.", maxlinelen=76) for l in h.encode(splitchars=' ').split('\n '): self.assertLessEqual(len(l), 76) def test_multilingual(self): eq = self.ndiffAssertEqual g = Charset("iso-8859-1") cz = Charset("iso-8859-2") utf8 = Charset("utf-8") g_head = (b'Die Mieter treten hier ein werden mit einem ' b'Foerderband komfortabel den Korridor entlang, ' b'an s\xfcdl\xfcndischen Wandgem\xe4lden vorbei, ' b'gegen die rotierenden Klingen bef\xf6rdert. ') cz_head = (b'Finan\xe8ni metropole se hroutily pod tlakem jejich ' b'd\xf9vtipu.. ') utf8_head = ('\u6b63\u78ba\u306b\u8a00\u3046\u3068\u7ffb\u8a33\u306f' '\u3055\u308c\u3066\u3044\u307e\u305b\u3093\u3002\u4e00' '\u90e8\u306f\u30c9\u30a4\u30c4\u8a9e\u3067\u3059\u304c' '\u3001\u3042\u3068\u306f\u3067\u305f\u3089\u3081\u3067' '\u3059\u3002\u5b9f\u969b\u306b\u306f\u300cWenn ist das ' 'Nunstuck git und Slotermeyer? Ja! Beiherhund das Oder ' 'die Flipperwaldt gersput.\u300d\u3068\u8a00\u3063\u3066' '\u3044\u307e\u3059\u3002') h = Header(g_head, g) h.append(cz_head, cz) h.append(utf8_head, utf8) enc = h.encode(maxlinelen=76) eq(enc, """\ =?iso-8859-1?q?Die_Mieter_treten_hier_ein_werden_mit_einem_Foerderband_kom?= =?iso-8859-1?q?fortabel_den_Korridor_entlang=2C_an_s=FCdl=FCndischen_Wand?= =?iso-8859-1?q?gem=E4lden_vorbei=2C_gegen_die_rotierenden_Klingen_bef=F6r?= =?iso-8859-1?q?dert=2E_?= =?iso-8859-2?q?Finan=E8ni_metropole_se_hroutily?= =?iso-8859-2?q?_pod_tlakem_jejich_d=F9vtipu=2E=2E_?= =?utf-8?b?5q2j56K6?= =?utf-8?b?44Gr6KiA44GG44Go57+76Kiz44Gv44GV44KM44Gm44GE44G+44Gb44KT44CC?= =?utf-8?b?5LiA6YOo44Gv44OJ44Kk44OE6Kqe44Gn44GZ44GM44CB44GC44Go44Gv44Gn?= =?utf-8?b?44Gf44KJ44KB44Gn44GZ44CC5a6f6Zqb44Gr44Gv44CMV2VubiBpc3QgZGFz?= =?utf-8?b?IE51bnN0dWNrIGdpdCB1bmQgU2xvdGVybWV5ZXI/IEphISBCZWloZXJodW5k?= =?utf-8?b?IGRhcyBPZGVyIGRpZSBGbGlwcGVyd2FsZHQgZ2Vyc3B1dC7jgI3jgajoqIA=?= =?utf-8?b?44Gj44Gm44GE44G+44GZ44CC?=""") decoded = decode_header(enc) eq(len(decoded), 3) eq(decoded[0], (g_head, 'iso-8859-1')) eq(decoded[1], (cz_head, 'iso-8859-2')) eq(decoded[2], (utf8_head.encode('utf-8'), 'utf-8')) ustr = str(h) eq(ustr, (b'Die Mieter treten hier ein werden mit einem Foerderband ' b'komfortabel den Korridor entlang, an s\xc3\xbcdl\xc3\xbcndischen ' b'Wandgem\xc3\xa4lden vorbei, gegen die rotierenden Klingen ' b'bef\xc3\xb6rdert. Finan\xc4\x8dni metropole se hroutily pod ' b'tlakem jejich d\xc5\xafvtipu.. \xe6\xad\xa3\xe7\xa2\xba\xe3\x81' b'\xab\xe8\xa8\x80\xe3\x81\x86\xe3\x81\xa8\xe7\xbf\xbb\xe8\xa8\xb3' b'\xe3\x81\xaf\xe3\x81\x95\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x84\xe3' b'\x81\xbe\xe3\x81\x9b\xe3\x82\x93\xe3\x80\x82\xe4\xb8\x80\xe9\x83' b'\xa8\xe3\x81\xaf\xe3\x83\x89\xe3\x82\xa4\xe3\x83\x84\xe8\xaa\x9e' b'\xe3\x81\xa7\xe3\x81\x99\xe3\x81\x8c\xe3\x80\x81\xe3\x81\x82\xe3' b'\x81\xa8\xe3\x81\xaf\xe3\x81\xa7\xe3\x81\x9f\xe3\x82\x89\xe3\x82' b'\x81\xe3\x81\xa7\xe3\x81\x99\xe3\x80\x82\xe5\xae\x9f\xe9\x9a\x9b' b'\xe3\x81\xab\xe3\x81\xaf\xe3\x80\x8cWenn ist das Nunstuck git ' b'und Slotermeyer? Ja! Beiherhund das Oder die Flipperwaldt ' b'gersput.\xe3\x80\x8d\xe3\x81\xa8\xe8\xa8\x80\xe3\x81\xa3\xe3\x81' b'\xa6\xe3\x81\x84\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82' ).decode('utf-8')) # Test make_header() newh = make_header(decode_header(enc)) eq(newh, h) def test_empty_header_encode(self): h = Header() self.assertEqual(h.encode(), '') def test_header_ctor_default_args(self): eq = self.ndiffAssertEqual h = Header() eq(h, '') h.append('foo', Charset('iso-8859-1')) eq(h, 'foo') def test_explicit_maxlinelen(self): eq = self.ndiffAssertEqual hstr = ('A very long line that must get split to something other ' 'than at the 76th character boundary to test the non-default ' 'behavior') h = Header(hstr) eq(h.encode(), '''\ A very long line that must get split to something other than at the 76th character boundary to test the non-default behavior''') eq(str(h), hstr) h = Header(hstr, header_name='Subject') eq(h.encode(), '''\ A very long line that must get split to something other than at the 76th character boundary to test the non-default behavior''') eq(str(h), hstr) h = Header(hstr, maxlinelen=1024, header_name='Subject') eq(h.encode(), hstr) eq(str(h), hstr) def test_quopri_splittable(self): eq = self.ndiffAssertEqual h = Header(charset='iso-8859-1', maxlinelen=20) x = 'xxxx ' * 20 h.append(x) s = h.encode() eq(s, """\ =?iso-8859-1?q?xxx?= =?iso-8859-1?q?x_?= =?iso-8859-1?q?xx?= =?iso-8859-1?q?xx?= =?iso-8859-1?q?_x?= =?iso-8859-1?q?xx?= =?iso-8859-1?q?x_?= =?iso-8859-1?q?xx?= =?iso-8859-1?q?xx?= =?iso-8859-1?q?_x?= =?iso-8859-1?q?xx?= =?iso-8859-1?q?x_?= =?iso-8859-1?q?xx?= =?iso-8859-1?q?xx?= =?iso-8859-1?q?_x?= =?iso-8859-1?q?xx?= =?iso-8859-1?q?x_?= =?iso-8859-1?q?xx?= =?iso-8859-1?q?xx?= =?iso-8859-1?q?_x?= =?iso-8859-1?q?xx?= =?iso-8859-1?q?x_?= =?iso-8859-1?q?xx?= =?iso-8859-1?q?xx?= =?iso-8859-1?q?_x?= =?iso-8859-1?q?xx?= =?iso-8859-1?q?x_?= =?iso-8859-1?q?xx?= =?iso-8859-1?q?xx?= =?iso-8859-1?q?_x?= =?iso-8859-1?q?xx?= =?iso-8859-1?q?x_?= =?iso-8859-1?q?xx?= =?iso-8859-1?q?xx?= =?iso-8859-1?q?_x?= =?iso-8859-1?q?xx?= =?iso-8859-1?q?x_?= =?iso-8859-1?q?xx?= =?iso-8859-1?q?xx?= =?iso-8859-1?q?_x?= =?iso-8859-1?q?xx?= =?iso-8859-1?q?x_?= =?iso-8859-1?q?xx?= =?iso-8859-1?q?xx?= =?iso-8859-1?q?_x?= =?iso-8859-1?q?xx?= =?iso-8859-1?q?x_?= =?iso-8859-1?q?xx?= =?iso-8859-1?q?xx?= =?iso-8859-1?q?_?=""") eq(x, str(make_header(decode_header(s)))) h = Header(charset='iso-8859-1', maxlinelen=40) h.append('xxxx ' * 20) s = h.encode() eq(s, """\ =?iso-8859-1?q?xxxx_xxxx_xxxx_xxxx_xxx?= =?iso-8859-1?q?x_xxxx_xxxx_xxxx_xxxx_?= =?iso-8859-1?q?xxxx_xxxx_xxxx_xxxx_xx?= =?iso-8859-1?q?xx_xxxx_xxxx_xxxx_xxxx?= =?iso-8859-1?q?_xxxx_xxxx_?=""") eq(x, str(make_header(decode_header(s)))) def test_base64_splittable(self): eq = self.ndiffAssertEqual h = Header(charset='koi8-r', maxlinelen=20) x = 'xxxx ' * 20 h.append(x) s = h.encode() eq(s, """\ =?koi8-r?b?eHh4?= =?koi8-r?b?eCB4?= =?koi8-r?b?eHh4?= =?koi8-r?b?IHh4?= =?koi8-r?b?eHgg?= =?koi8-r?b?eHh4?= =?koi8-r?b?eCB4?= =?koi8-r?b?eHh4?= =?koi8-r?b?IHh4?= =?koi8-r?b?eHgg?= =?koi8-r?b?eHh4?= =?koi8-r?b?eCB4?= =?koi8-r?b?eHh4?= =?koi8-r?b?IHh4?= =?koi8-r?b?eHgg?= =?koi8-r?b?eHh4?= =?koi8-r?b?eCB4?= =?koi8-r?b?eHh4?= =?koi8-r?b?IHh4?= =?koi8-r?b?eHgg?= =?koi8-r?b?eHh4?= =?koi8-r?b?eCB4?= =?koi8-r?b?eHh4?= =?koi8-r?b?IHh4?= =?koi8-r?b?eHgg?= =?koi8-r?b?eHh4?= =?koi8-r?b?eCB4?= =?koi8-r?b?eHh4?= =?koi8-r?b?IHh4?= =?koi8-r?b?eHgg?= =?koi8-r?b?eHh4?= =?koi8-r?b?eCB4?= =?koi8-r?b?eHh4?= =?koi8-r?b?IA==?=""") eq(x, str(make_header(decode_header(s)))) h = Header(charset='koi8-r', maxlinelen=40) h.append(x) s = h.encode() eq(s, """\ =?koi8-r?b?eHh4eCB4eHh4IHh4eHggeHh4?= =?koi8-r?b?eCB4eHh4IHh4eHggeHh4eCB4?= =?koi8-r?b?eHh4IHh4eHggeHh4eCB4eHh4?= =?koi8-r?b?IHh4eHggeHh4eCB4eHh4IHh4?= =?koi8-r?b?eHggeHh4eCB4eHh4IHh4eHgg?= =?koi8-r?b?eHh4eCB4eHh4IA==?=""") eq(x, str(make_header(decode_header(s)))) def test_us_ascii_header(self): eq = self.assertEqual s = 'hello' x = decode_header(s) eq(x, [('hello', None)]) h = make_header(x) eq(s, h.encode()) def test_string_charset(self): eq = self.assertEqual h = Header() h.append('hello', 'iso-8859-1') eq(h, 'hello') ## def test_unicode_error(self): ## raises = self.assertRaises ## raises(UnicodeError, Header, u'[P\xf6stal]', 'us-ascii') ## raises(UnicodeError, Header, '[P\xf6stal]', 'us-ascii') ## h = Header() ## raises(UnicodeError, h.append, u'[P\xf6stal]', 'us-ascii') ## raises(UnicodeError, h.append, '[P\xf6stal]', 'us-ascii') ## raises(UnicodeError, Header, u'\u83ca\u5730\u6642\u592b', 'iso-8859-1') def test_utf8_shortest(self): eq = self.assertEqual h = Header('p\xf6stal', 'utf-8') eq(h.encode(), '=?utf-8?q?p=C3=B6stal?=') h = Header('\u83ca\u5730\u6642\u592b', 'utf-8') eq(h.encode(), '=?utf-8?b?6I+K5Zyw5pmC5aSr?=') def test_bad_8bit_header(self): raises = self.assertRaises eq = self.assertEqual x = b'Ynwp4dUEbay Auction Semiar- No Charge \x96 Earn Big' raises(UnicodeError, Header, x) h = Header() raises(UnicodeError, h.append, x) e = x.decode('utf-8', 'replace') eq(str(Header(x, errors='replace')), e) h.append(x, errors='replace') eq(str(h), e) def test_escaped_8bit_header(self): x = b'Ynwp4dUEbay Auction Semiar- No Charge \x96 Earn Big' e = x.decode('ascii', 'surrogateescape') h = Header(e, charset=email.charset.UNKNOWN8BIT) self.assertEqual(str(h), 'Ynwp4dUEbay Auction Semiar- No Charge \uFFFD Earn Big') self.assertEqual(email.header.decode_header(h), [(x, 'unknown-8bit')]) def test_header_handles_binary_unknown8bit(self): x = b'Ynwp4dUEbay Auction Semiar- No Charge \x96 Earn Big' h = Header(x, charset=email.charset.UNKNOWN8BIT) self.assertEqual(str(h), 'Ynwp4dUEbay Auction Semiar- No Charge \uFFFD Earn Big') self.assertEqual(email.header.decode_header(h), [(x, 'unknown-8bit')]) def test_make_header_handles_binary_unknown8bit(self): x = b'Ynwp4dUEbay Auction Semiar- No Charge \x96 Earn Big' h = Header(x, charset=email.charset.UNKNOWN8BIT) h2 = email.header.make_header(email.header.decode_header(h)) self.assertEqual(str(h2), 'Ynwp4dUEbay Auction Semiar- No Charge \uFFFD Earn Big') self.assertEqual(email.header.decode_header(h2), [(x, 'unknown-8bit')]) def test_modify_returned_list_does_not_change_header(self): h = Header('test') chunks = email.header.decode_header(h) chunks.append(('ascii', 'test2')) self.assertEqual(str(h), 'test') def test_encoded_adjacent_nonencoded(self): eq = self.assertEqual h = Header() h.append('hello', 'iso-8859-1') h.append('world') s = h.encode() eq(s, '=?iso-8859-1?q?hello?= world') h = make_header(decode_header(s)) eq(h.encode(), s) def test_whitespace_keeper(self): eq = self.assertEqual s = 'Subject: =?koi8-r?b?8NLP18XSy8EgzsEgxsnOwczYztk=?= =?koi8-r?q?=CA?= zz.' parts = decode_header(s) eq(parts, [(b'Subject: ', None), (b'\xf0\xd2\xcf\xd7\xc5\xd2\xcb\xc1 \xce\xc1 \xc6\xc9\xce\xc1\xcc\xd8\xce\xd9\xca', 'koi8-r'), (b' zz.', None)]) hdr = make_header(parts) eq(hdr.encode(), 'Subject: =?koi8-r?b?8NLP18XSy8EgzsEgxsnOwczYztnK?= zz.') def test_broken_base64_header(self): raises = self.assertRaises s = 'Subject: =?EUC-KR?B?CSixpLDtKSC/7Liuvsax4iC6uLmwMcijIKHaILzSwd/H0SC8+LCjwLsgv7W/+Mj3I ?=' raises(errors.HeaderParseError, decode_header, s) def test_shift_jis_charset(self): h = Header('文', charset='shift_jis') self.assertEqual(h.encode(), '=?iso-2022-jp?b?GyRCSjgbKEI=?=') def test_flatten_header_with_no_value(self): # Issue 11401 (regression from email 4.x) Note that the space after # the header doesn't reflect the input, but this is also the way # email 4.x behaved. At some point it would be nice to fix that. msg = email.message_from_string("EmptyHeader:") self.assertEqual(str(msg), "EmptyHeader: \n\n") def test_encode_preserves_leading_ws_on_value(self): msg = Message() msg['SomeHeader'] = ' value with leading ws' self.assertEqual(str(msg), "SomeHeader: value with leading ws\n\n") # Test RFC 2231 header parameters (en/de)coding class TestRFC2231(TestEmailBase): # test_headerregistry.TestContentTypeHeader.rfc2231_encoded_with_double_quotes # test_headerregistry.TestContentTypeHeader.rfc2231_single_quote_inside_double_quotes def test_get_param(self): eq = self.assertEqual msg = self._msgobj('msg_29.txt') eq(msg.get_param('title'), ('us-ascii', 'en', 'This is even more ***fun*** isn\'t it!')) eq(msg.get_param('title', unquote=False), ('us-ascii', 'en', '"This is even more ***fun*** isn\'t it!"')) def test_set_param(self): eq = self.ndiffAssertEqual msg = Message() msg.set_param('title', 'This is even more ***fun*** isn\'t it!', charset='us-ascii') eq(msg.get_param('title'), ('us-ascii', '', 'This is even more ***fun*** isn\'t it!')) msg.set_param('title', 'This is even more ***fun*** isn\'t it!', charset='us-ascii', language='en') eq(msg.get_param('title'), ('us-ascii', 'en', 'This is even more ***fun*** isn\'t it!')) msg = self._msgobj('msg_01.txt') msg.set_param('title', 'This is even more ***fun*** isn\'t it!', charset='us-ascii', language='en') eq(msg.as_string(maxheaderlen=78), """\ Return-Path: <[email protected]> Delivered-To: [email protected] Received: by mail.zzz.org (Postfix, from userid 889) \tid 27CEAD38CC; Fri, 4 May 2001 14:05:44 -0400 (EDT) MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Message-ID: <[email protected]> From: [email protected] (John X. Doe) To: [email protected] Subject: This is a test message Date: Fri, 4 May 2001 14:05:44 -0400 Content-Type: text/plain; charset=us-ascii; title*=us-ascii'en'This%20is%20even%20more%20%2A%2A%2Afun%2A%2A%2A%20isn%27t%20it%21 Hi, Do you like this message? -Me """) def test_set_param_requote(self): msg = Message() msg.set_param('title', 'foo') self.assertEqual(msg['content-type'], 'text/plain; title="foo"') msg.set_param('title', 'bar', requote=False) self.assertEqual(msg['content-type'], 'text/plain; title=bar') # tspecial is still quoted. msg.set_param('title', "(bar)bell", requote=False) self.assertEqual(msg['content-type'], 'text/plain; title="(bar)bell"') def test_del_param(self): eq = self.ndiffAssertEqual msg = self._msgobj('msg_01.txt') msg.set_param('foo', 'bar', charset='us-ascii', language='en') msg.set_param('title', 'This is even more ***fun*** isn\'t it!', charset='us-ascii', language='en') msg.del_param('foo', header='Content-Type') eq(msg.as_string(maxheaderlen=78), """\ Return-Path: <[email protected]> Delivered-To: [email protected] Received: by mail.zzz.org (Postfix, from userid 889) \tid 27CEAD38CC; Fri, 4 May 2001 14:05:44 -0400 (EDT) MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Message-ID: <[email protected]> From: [email protected] (John X. Doe) To: [email protected] Subject: This is a test message Date: Fri, 4 May 2001 14:05:44 -0400 Content-Type: text/plain; charset="us-ascii"; title*=us-ascii'en'This%20is%20even%20more%20%2A%2A%2Afun%2A%2A%2A%20isn%27t%20it%21 Hi, Do you like this message? -Me """) # test_headerregistry.TestContentTypeHeader.rfc2231_encoded_charset # I changed the charset name, though, because the one in the file isn't # a legal charset name. Should add a test for an illegal charset. def test_rfc2231_get_content_charset(self): eq = self.assertEqual msg = self._msgobj('msg_32.txt') eq(msg.get_content_charset(), 'us-ascii') # test_headerregistry.TestContentTypeHeader.rfc2231_encoded_no_double_quotes def test_rfc2231_parse_rfc_quoting(self): m = textwrap.dedent('''\ Content-Disposition: inline; \tfilename*0*=''This%20is%20even%20more%20; \tfilename*1*=%2A%2A%2Afun%2A%2A%2A%20; \tfilename*2="is it not.pdf" ''') msg = email.message_from_string(m) self.assertEqual(msg.get_filename(), 'This is even more ***fun*** is it not.pdf') self.assertEqual(m, msg.as_string()) # test_headerregistry.TestContentTypeHeader.rfc2231_encoded_with_double_quotes def test_rfc2231_parse_extra_quoting(self): m = textwrap.dedent('''\ Content-Disposition: inline; \tfilename*0*="''This%20is%20even%20more%20"; \tfilename*1*="%2A%2A%2Afun%2A%2A%2A%20"; \tfilename*2="is it not.pdf" ''') msg = email.message_from_string(m) self.assertEqual(msg.get_filename(), 'This is even more ***fun*** is it not.pdf') self.assertEqual(m, msg.as_string()) # test_headerregistry.TestContentTypeHeader.rfc2231_no_language_or_charset # but new test uses *0* because otherwise lang/charset is not valid. # test_headerregistry.TestContentTypeHeader.rfc2231_segmented_normal_values def test_rfc2231_no_language_or_charset(self): m = '''\ Content-Transfer-Encoding: 8bit Content-Disposition: inline; filename="file____C__DOCUMENTS_20AND_20SETTINGS_FABIEN_LOCAL_20SETTINGS_TEMP_nsmail.htm" Content-Type: text/html; NAME*0=file____C__DOCUMENTS_20AND_20SETTINGS_FABIEN_LOCAL_20SETTINGS_TEM; NAME*1=P_nsmail.htm ''' msg = email.message_from_string(m) param = msg.get_param('NAME') self.assertNotIsInstance(param, tuple) self.assertEqual( param, 'file____C__DOCUMENTS_20AND_20SETTINGS_FABIEN_LOCAL_20SETTINGS_TEMP_nsmail.htm') # test_headerregistry.TestContentTypeHeader.rfc2231_encoded_no_charset def test_rfc2231_no_language_or_charset_in_filename(self): m = '''\ Content-Disposition: inline; \tfilename*0*="''This%20is%20even%20more%20"; \tfilename*1*="%2A%2A%2Afun%2A%2A%2A%20"; \tfilename*2="is it not.pdf" ''' msg = email.message_from_string(m) self.assertEqual(msg.get_filename(), 'This is even more ***fun*** is it not.pdf') # Duplicate of previous test? def test_rfc2231_no_language_or_charset_in_filename_encoded(self): m = '''\ Content-Disposition: inline; \tfilename*0*="''This%20is%20even%20more%20"; \tfilename*1*="%2A%2A%2Afun%2A%2A%2A%20"; \tfilename*2="is it not.pdf" ''' msg = email.message_from_string(m) self.assertEqual(msg.get_filename(), 'This is even more ***fun*** is it not.pdf') # test_headerregistry.TestContentTypeHeader.rfc2231_partly_encoded, # but the test below is wrong (the first part should be decoded). def test_rfc2231_partly_encoded(self): m = '''\ Content-Disposition: inline; \tfilename*0="''This%20is%20even%20more%20"; \tfilename*1*="%2A%2A%2Afun%2A%2A%2A%20"; \tfilename*2="is it not.pdf" ''' msg = email.message_from_string(m) self.assertEqual( msg.get_filename(), 'This%20is%20even%20more%20***fun*** is it not.pdf') def test_rfc2231_partly_nonencoded(self): m = '''\ Content-Disposition: inline; \tfilename*0="This%20is%20even%20more%20"; \tfilename*1="%2A%2A%2Afun%2A%2A%2A%20"; \tfilename*2="is it not.pdf" ''' msg = email.message_from_string(m) self.assertEqual( msg.get_filename(), 'This%20is%20even%20more%20%2A%2A%2Afun%2A%2A%2A%20is it not.pdf') def test_rfc2231_no_language_or_charset_in_boundary(self): m = '''\ Content-Type: multipart/alternative; \tboundary*0*="''This%20is%20even%20more%20"; \tboundary*1*="%2A%2A%2Afun%2A%2A%2A%20"; \tboundary*2="is it not.pdf" ''' msg = email.message_from_string(m) self.assertEqual(msg.get_boundary(), 'This is even more ***fun*** is it not.pdf') def test_rfc2231_no_language_or_charset_in_charset(self): # This is a nonsensical charset value, but tests the code anyway m = '''\ Content-Type: text/plain; \tcharset*0*="This%20is%20even%20more%20"; \tcharset*1*="%2A%2A%2Afun%2A%2A%2A%20"; \tcharset*2="is it not.pdf" ''' msg = email.message_from_string(m) self.assertEqual(msg.get_content_charset(), 'this is even more ***fun*** is it not.pdf') # test_headerregistry.TestContentTypeHeader.rfc2231_unknown_charset_treated_as_ascii def test_rfc2231_bad_encoding_in_filename(self): m = '''\ Content-Disposition: inline; \tfilename*0*="bogus'xx'This%20is%20even%20more%20"; \tfilename*1*="%2A%2A%2Afun%2A%2A%2A%20"; \tfilename*2="is it not.pdf" ''' msg = email.message_from_string(m) self.assertEqual(msg.get_filename(), 'This is even more ***fun*** is it not.pdf') def test_rfc2231_bad_encoding_in_charset(self): m = """\ Content-Type: text/plain; charset*=bogus''utf-8%E2%80%9D """ msg = email.message_from_string(m) # This should return None because non-ascii characters in the charset # are not allowed. self.assertEqual(msg.get_content_charset(), None) def test_rfc2231_bad_character_in_charset(self): m = """\ Content-Type: text/plain; charset*=ascii''utf-8%E2%80%9D """ msg = email.message_from_string(m) # This should return None because non-ascii characters in the charset # are not allowed. self.assertEqual(msg.get_content_charset(), None) def test_rfc2231_bad_character_in_filename(self): m = '''\ Content-Disposition: inline; \tfilename*0*="ascii'xx'This%20is%20even%20more%20"; \tfilename*1*="%2A%2A%2Afun%2A%2A%2A%20"; \tfilename*2*="is it not.pdf%E2" ''' msg = email.message_from_string(m) self.assertEqual(msg.get_filename(), 'This is even more ***fun*** is it not.pdf\ufffd') def test_rfc2231_unknown_encoding(self): m = """\ Content-Transfer-Encoding: 8bit Content-Disposition: inline; filename*=X-UNKNOWN''myfile.txt """ msg = email.message_from_string(m) self.assertEqual(msg.get_filename(), 'myfile.txt') def test_rfc2231_single_tick_in_filename_extended(self): eq = self.assertEqual m = """\ Content-Type: application/x-foo; \tname*0*=\"Frank's\"; name*1*=\" Document\" """ msg = email.message_from_string(m) charset, language, s = msg.get_param('name') eq(charset, None) eq(language, None) eq(s, "Frank's Document") # test_headerregistry.TestContentTypeHeader.rfc2231_single_quote_inside_double_quotes def test_rfc2231_single_tick_in_filename(self): m = """\ Content-Type: application/x-foo; name*0=\"Frank's\"; name*1=\" Document\" """ msg = email.message_from_string(m) param = msg.get_param('name') self.assertNotIsInstance(param, tuple) self.assertEqual(param, "Frank's Document") def test_rfc2231_missing_tick(self): m = '''\ Content-Disposition: inline; \tfilename*0*="'This%20is%20broken"; ''' msg = email.message_from_string(m) self.assertEqual( msg.get_filename(), "'This is broken") def test_rfc2231_missing_tick_with_encoded_non_ascii(self): m = '''\ Content-Disposition: inline; \tfilename*0*="'This%20is%E2broken"; ''' msg = email.message_from_string(m) self.assertEqual( msg.get_filename(), "'This is\ufffdbroken") # test_headerregistry.TestContentTypeHeader.rfc2231_single_quote_in_value_with_charset_and_lang def test_rfc2231_tick_attack_extended(self): eq = self.assertEqual m = """\ Content-Type: application/x-foo; \tname*0*=\"us-ascii'en-us'Frank's\"; name*1*=\" Document\" """ msg = email.message_from_string(m) charset, language, s = msg.get_param('name') eq(charset, 'us-ascii') eq(language, 'en-us') eq(s, "Frank's Document") # test_headerregistry.TestContentTypeHeader.rfc2231_single_quote_in_non_encoded_value def test_rfc2231_tick_attack(self): m = """\ Content-Type: application/x-foo; \tname*0=\"us-ascii'en-us'Frank's\"; name*1=\" Document\" """ msg = email.message_from_string(m) param = msg.get_param('name') self.assertNotIsInstance(param, tuple) self.assertEqual(param, "us-ascii'en-us'Frank's Document") # test_headerregistry.TestContentTypeHeader.rfc2231_single_quotes_inside_quotes def test_rfc2231_no_extended_values(self): eq = self.assertEqual m = """\ Content-Type: application/x-foo; name=\"Frank's Document\" """ msg = email.message_from_string(m) eq(msg.get_param('name'), "Frank's Document") # test_headerregistry.TestContentTypeHeader.rfc2231_encoded_then_unencoded_segments def test_rfc2231_encoded_then_unencoded_segments(self): eq = self.assertEqual m = """\ Content-Type: application/x-foo; \tname*0*=\"us-ascii'en-us'My\"; \tname*1=\" Document\"; \tname*2*=\" For You\" """ msg = email.message_from_string(m) charset, language, s = msg.get_param('name') eq(charset, 'us-ascii') eq(language, 'en-us') eq(s, 'My Document For You') # test_headerregistry.TestContentTypeHeader.rfc2231_unencoded_then_encoded_segments # test_headerregistry.TestContentTypeHeader.rfc2231_quoted_unencoded_then_encoded_segments def test_rfc2231_unencoded_then_encoded_segments(self): eq = self.assertEqual m = """\ Content-Type: application/x-foo; \tname*0=\"us-ascii'en-us'My\"; \tname*1*=\" Document\"; \tname*2*=\" For You\" """ msg = email.message_from_string(m) charset, language, s = msg.get_param('name') eq(charset, 'us-ascii') eq(language, 'en-us') eq(s, 'My Document For You') # Tests to ensure that signed parts of an email are completely preserved, as # required by RFC1847 section 2.1. Note that these are incomplete, because the # email package does not currently always preserve the body. See issue 1670765. class TestSigned(TestEmailBase): def _msg_and_obj(self, filename): with openfile(filename) as fp: original = fp.read() msg = email.message_from_string(original) return original, msg def _signed_parts_eq(self, original, result): # Extract the first mime part of each message import re repart = re.compile(r'^--([^\n]+)\n(.*?)\n--\1$', re.S | re.M) inpart = repart.search(original).group(2) outpart = repart.search(result).group(2) self.assertEqual(outpart, inpart) def test_long_headers_as_string(self): original, msg = self._msg_and_obj('msg_45.txt') result = msg.as_string() self._signed_parts_eq(original, result) def test_long_headers_as_string_maxheaderlen(self): original, msg = self._msg_and_obj('msg_45.txt') result = msg.as_string(maxheaderlen=60) self._signed_parts_eq(original, result) def test_long_headers_flatten(self): original, msg = self._msg_and_obj('msg_45.txt') fp = StringIO() Generator(fp).flatten(msg) result = fp.getvalue() self._signed_parts_eq(original, result) if __name__ == '__main__': unittest.main()
208,800
5,421
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_email/__init__.py
import os import unittest import collections import email from email.message import Message from email._policybase import compat32 from test.support import load_package_tests landmark = __file__ # Load all tests in package def load_tests(*args): return load_package_tests(os.path.dirname(__file__), *args) # helper code used by a number of test modules. def openfile(filename, *args, **kws): path = os.path.join(os.path.dirname(landmark), 'data', filename) return open(path, *args, **kws) # Base test class class TestEmailBase(unittest.TestCase): maxDiff = None # Currently the default policy is compat32. By setting that as the default # here we make minimal changes in the test_email tests compared to their # pre-3.3 state. policy = compat32 # Likewise, the default message object is Message. message = Message def __init__(self, *args, **kw): super().__init__(*args, **kw) self.addTypeEqualityFunc(bytes, self.assertBytesEqual) # Backward compatibility to minimize test_email test changes. ndiffAssertEqual = unittest.TestCase.assertEqual def _msgobj(self, filename): with openfile(filename) as fp: return email.message_from_file(fp, policy=self.policy) def _str_msg(self, string, message=None, policy=None): if policy is None: policy = self.policy if message is None: message = self.message return email.message_from_string(string, message, policy=policy) def _bytes_msg(self, bytestring, message=None, policy=None): if policy is None: policy = self.policy if message is None: message = self.message return email.message_from_bytes(bytestring, message, policy=policy) def _make_message(self): return self.message(policy=self.policy) def _bytes_repr(self, b): return [repr(x) for x in b.splitlines(keepends=True)] def assertBytesEqual(self, first, second, msg): """Our byte strings are really encoded strings; improve diff output""" self.assertEqual(self._bytes_repr(first), self._bytes_repr(second)) def assertDefectsEqual(self, actual, expected): self.assertEqual(len(actual), len(expected), actual) for i in range(len(actual)): self.assertIsInstance(actual[i], expected[i], 'item {}'.format(i)) def parameterize(cls): """A test method parameterization class decorator. Parameters are specified as the value of a class attribute that ends with the string '_params'. Call the portion before '_params' the prefix. Then a method to be parameterized must have the same prefix, the string '_as_', and an arbitrary suffix. The value of the _params attribute may be either a dictionary or a list. The values in the dictionary and the elements of the list may either be single values, or a list. If single values, they are turned into single element tuples. However derived, the resulting sequence is passed via *args to the parameterized test function. In a _params dictionary, the keys become part of the name of the generated tests. In a _params list, the values in the list are converted into a string by joining the string values of the elements of the tuple by '_' and converting any blanks into '_'s, and this become part of the name. The full name of a generated test is a 'test_' prefix, the portion of the test function name after the '_as_' separator, plus an '_', plus the name derived as explained above. For example, if we have: count_params = range(2) def count_as_foo_arg(self, foo): self.assertEqual(foo+1, myfunc(foo)) we will get parameterized test methods named: test_foo_arg_0 test_foo_arg_1 test_foo_arg_2 Or we could have: example_params = {'foo': ('bar', 1), 'bing': ('bang', 2)} def example_as_myfunc_input(self, name, count): self.assertEqual(name+str(count), myfunc(name, count)) and get: test_myfunc_input_foo test_myfunc_input_bing Note: if and only if the generated test name is a valid identifier can it be used to select the test individually from the unittest command line. The values in the params dict can be a single value, a tuple, or a dict. If a single value of a tuple, it is passed to the test function as positional arguments. If a dict, it is a passed via **kw. """ paramdicts = {} testers = collections.defaultdict(list) for name, attr in cls.__dict__.items(): if name.endswith('_params'): if not hasattr(attr, 'keys'): d = {} for x in attr: if not hasattr(x, '__iter__'): x = (x,) n = '_'.join(str(v) for v in x).replace(' ', '_') d[n] = x attr = d paramdicts[name[:-7] + '_as_'] = attr if '_as_' in name: testers[name.split('_as_')[0] + '_as_'].append(name) testfuncs = {} for name in paramdicts: if name not in testers: raise ValueError("No tester found for {}".format(name)) for name in testers: if name not in paramdicts: raise ValueError("No params found for {}".format(name)) for name, attr in cls.__dict__.items(): for paramsname, paramsdict in paramdicts.items(): if name.startswith(paramsname): testnameroot = 'test_' + name[len(paramsname):] for paramname, params in paramsdict.items(): if hasattr(params, 'keys'): test = (lambda self, name=name, params=params: getattr(self, name)(**params)) else: test = (lambda self, name=name, params=params: getattr(self, name)(*params)) testname = testnameroot + '_' + paramname test.__name__ = testname testfuncs[testname] = test for key, value in testfuncs.items(): setattr(cls, key, value) return cls
6,295
168
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_email/data/msg_35.txt
From: [email protected] To: [email protected] Subject: here's something interesting counter to RFC 2822, there's no separating newline here
136
5
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_email/data/msg_46.txt
Return-Path: <[email protected]> Delivery-Date: Mon, 08 Feb 2010 14:05:16 +0100 Received: from example.org (example.org [64.5.53.58]) by example.net (node=mxbap2) with ESMTP (Nemesis) id UNIQUE for [email protected]; Mon, 08 Feb 2010 14:05:16 +0100 Date: Mon, 01 Feb 2010 12:21:16 +0100 From: "Sender" <[email protected]> To: <[email protected]> Subject: GroupwiseForwardingTest Mime-Version: 1.0 Content-Type: message/rfc822 Return-path: <[email protected]> Message-ID: <[email protected]> Date: Mon, 01 Feb 2010 12:18:40 +0100 From: "Dr. Sender" <[email protected]> MIME-Version: 1.0 To: "Recipient" <[email protected]> Subject: GroupwiseForwardingTest Content-Type: text/plain; charset=ISO-8859-15 Content-Transfer-Encoding: 7bit Testing email forwarding with Groupwise 1.2.2010
816
24
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_email/data/msg_25.txt
From MAILER-DAEMON Fri Apr 06 16:46:09 2001 Received: from [204.245.199.98] (helo=zinfandel.lacita.com) by www.linux.org.uk with esmtp (Exim 3.13 #1) id 14lYR6-0008Iv-00 for [email protected]; Fri, 06 Apr 2001 16:46:09 +0100 Received: from localhost (localhost) by zinfandel.lacita.com (8.7.3/8.6.10-MT4.00) with internal id JAB03225; Fri, 6 Apr 2001 09:23:06 -0800 (GMT-0800) Date: Fri, 6 Apr 2001 09:23:06 -0800 (GMT-0800) From: Mail Delivery Subsystem <[email protected]> Subject: Returned mail: Too many hops 19 (17 max): from <[email protected]> via [199.164.235.226], to <[email protected]> Message-Id: <[email protected]> To: <[email protected]> To: [email protected] MIME-Version: 1.0 Content-Type: multipart/report; report-type=delivery-status; bo Auto-Submitted: auto-generated (failure) This is a MIME-encapsulated message --JAB03225.986577786/zinfandel.lacita.com The original message was received at Fri, 6 Apr 2001 09:23:03 -0800 (GMT-0800) from [199.164.235.226] ----- The following addresses have delivery notifications ----- <[email protected]> (unrecoverable error) ----- Transcript of session follows ----- 554 Too many hops 19 (17 max): from <[email protected]> via [199.164.235.226], to <[email protected]> --JAB03225.986577786/zinfandel.lacita.com Content-Type: message/delivery-status Reporting-MTA: dns; zinfandel.lacita.com Received-From-MTA: dns; [199.164.235.226] Arrival-Date: Fri, 6 Apr 2001 09:23:03 -0800 (GMT-0800) Final-Recipient: rfc822; [email protected] Action: failed Status: 5.4.6 Last-Attempt-Date: Fri, 6 Apr 2001 09:23:06 -0800 (GMT-0800) --JAB03225.986577786/zinfandel.lacita.com Content-Type: text/rfc822-headers Return-Path: [email protected] Received: from ns1.wellpartner.net ([199.164.235.226]) by zinfandel.lacita.com (8.7.3/8.6.10-MT4.00) with ESMTP id JAA03225 for <[email protected]>; Fri, 6 Apr 2001 09:23:03 -0800 (GMT-0800) Received: from zinfandel.lacita.com ([204.245.199.98]) by fo Received: from ns1.wellpartner.net ([199.164.235.226]) by zinfandel.lacita.com (8.7.3/8.6.10-MT4.00) with ESMTP id JAA03221 for <[email protected]>; Fri, 6 Apr 2001 09:22:18 -0800 (GMT-0800) Received: from zinfandel.lacita.com ([204.245.199.98]) by fo Received: from ns1.wellpartner.net ([199.164.235.226]) by zinfandel.lacita.com (8.7.3/8.6.10-MT4.00) with ESMTP id JAA03217 for <[email protected]>; Fri, 6 Apr 2001 09:21:37 -0800 (GMT-0800) Received: from zinfandel.lacita.com ([204.245.199.98]) by fo Received: from ns1.wellpartner.net ([199.164.235.226]) by zinfandel.lacita.com (8.7.3/8.6.10-MT4.00) with ESMTP id JAA03213 for <[email protected]>; Fri, 6 Apr 2001 09:20:56 -0800 (GMT-0800) Received: from zinfandel.lacita.com ([204.245.199.98]) by fo Received: from ns1.wellpartner.net ([199.164.235.226]) by zinfandel.lacita.com (8.7.3/8.6.10-MT4.00) with ESMTP id JAA03209 for <[email protected]>; Fri, 6 Apr 2001 09:20:15 -0800 (GMT-0800) Received: from zinfandel.lacita.com ([204.245.199.98]) by fo Received: from ns1.wellpartner.net ([199.164.235.226]) by zinfandel.lacita.com (8.7.3/8.6.10-MT4.00) with ESMTP id JAA03205 for <[email protected]>; Fri, 6 Apr 2001 09:19:33 -0800 (GMT-0800) Received: from zinfandel.lacita.com ([204.245.199.98]) by fo Received: from ns1.wellpartner.net ([199.164.235.226]) by zinfandel.lacita.com (8.7.3/8.6.10-MT4.00) with ESMTP id JAA03201 for <[email protected]>; Fri, 6 Apr 2001 09:18:52 -0800 (GMT-0800) Received: from zinfandel.lacita.com ([204.245.199.98]) by fo Received: from ns1.wellpartner.net ([199.164.235.226]) by zinfandel.lacita.com (8.7.3/8.6.10-MT4.00) with ESMTP id JAA03197 for <[email protected]>; Fri, 6 Apr 2001 09:17:54 -0800 (GMT-0800) Received: from www.linux.org.uk (parcelfarce.linux.theplanet.co.uk [195.92.249.252]) by fo Received: from localhost.localdomain ([ by id Received: from [212.1.130.11] (helo=s1.uklinux.net ident=root) by id fo Received: from server (ppp-2-22.cvx4.telinco.net [212.1.149.22]) by fo From: Daniel James <[email protected]> Organization: LinuxUser To: [email protected] X-Mailer: KMail [version 1.1.99] Content-Type: text/plain; c MIME-Version: 1.0 Message-Id: <01040616033903.00962@server> Content-Transfer-Encoding: 8bit Subject: [LinuxUser] bulletin no. 45 Sender: [email protected] Errors-To: [email protected] X-BeenThere: [email protected] X-Mailman-Version: 2.0.3 Precedence: bulk List-Help: <mailto:[email protected]?subject=help> List-Post: <mailto:[email protected]> List-Subscribe: <http://www.linux.org.uk/mailman/listinfo/linuxuser>, <m List-Id: bulletins from LinuxUser magazine <linuxuser.www.linux.org.uk> List-Unsubscribe: <http://www.linux.org.uk/mailman/listinfo/linuxuser>, <m List-Archive: <http://www.linux.org.uk/pipermail/linuxuser/> Date: Fri, 6 Apr 2001 16:03:39 +0100 --JAB03225.986577786/zinfandel.lacita.com--
5,122
118
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_email/data/msg_44.txt
Return-Path: <[email protected]> Delivered-To: [email protected] Received: by mail.python.org (Postfix, from userid 889) id C2BF0D37C6; Tue, 11 Sep 2001 00:05:05 -0400 (EDT) MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="h90VIIIKmx" Content-Transfer-Encoding: 7bit Message-ID: <[email protected]> From: [email protected] (Barry A. Warsaw) To: [email protected] Subject: a simple multipart Date: Tue, 11 Sep 2001 00:05:05 -0400 X-Mailer: VM 6.95 under 21.4 (patch 4) "Artificial Intelligence" XEmacs Lucid X-Attribution: BAW X-Oblique-Strategy: Make a door into a window --h90VIIIKmx Content-Type: text/plain; name="msg.txt" Content-Transfer-Encoding: 7bit a simple kind of mirror to reflect upon our own --h90VIIIKmx Content-Type: text/plain; name="msg.txt" Content-Transfer-Encoding: 7bit a simple kind of mirror to reflect upon our own --h90VIIIKmx--
895
34
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_email/data/msg_09.txt
MIME-Version: 1.0 From: Barry Warsaw <[email protected]> To: Dingus Lovers <[email protected]> Subject: Lyrics Date: Fri, 20 Apr 2001 19:35:02 -0400 Content-Type: multipart/mixed; boundary="BOUNDARY" --BOUNDARY Content-Type: text/plain; charset="us-ascii" --BOUNDARY Content-Type: text/html; charset="iso-8859-1" --BOUNDARY Content-Type: text/plain --BOUNDARY Content-Type: text/plain; charset="koi8-r" --BOUNDARY--
432
25
jart/cosmopolitan
false
cosmopolitan/third_party/python/Lib/test/test_email/data/msg_34.txt
From: [email protected] To: [email protected] Content-Type: multipart/digest; boundary=XYZ --XYZ Content-Type: text/plain This is a text plain part that is counter to recommended practice in RFC 2046, $5.1.5, but is not illegal --XYZ From: [email protected] To: [email protected] A submessage --XYZ--
300
20
jart/cosmopolitan
false