Best JavaScript code snippet using devicefarmer-stf
binascii.py
Source:binascii.py
1"""A pure Python implementation of binascii.2Rather slow and buggy in corner cases.3PyPy provides an RPython version too.4"""5# borrowed from https://bitbucket.org/pypy/pypy/src/f2bf94943a41/lib_pypy/binascii.py6class Error(Exception):7 pass8class Done(Exception):9 pass10class Incomplete(Exception):11 pass12def a2b_uu(s):13 if not s:14 return ''15 16 length = (ord(s[0]) - 0x20) % 6417 def quadruplets_gen(s):18 while s:19 try:20 yield ord(s[0]), ord(s[1]), ord(s[2]), ord(s[3])21 except IndexError:22 s += ' '23 yield ord(s[0]), ord(s[1]), ord(s[2]), ord(s[3])24 return25 s = s[4:]26 try:27 result = [''.join(28 [chr((A - 0x20) << 2 | (((B - 0x20) >> 4) & 0x3)),29 chr(((B - 0x20) & 0xf) << 4 | (((C - 0x20) >> 2) & 0xf)),30 chr(((C - 0x20) & 0x3) << 6 | ((D - 0x20) & 0x3f))31 ]) for A, B, C, D in quadruplets_gen(s[1:].rstrip())]32 except ValueError:33 raise Error('Illegal char')34 result = ''.join(result)35 trailingdata = result[length:]36 if trailingdata.strip('\x00'):37 raise Error('Trailing garbage')38 result = result[:length]39 if len(result) < length:40 result += ((length - len(result)) * '\x00')41 return bytes(result, __BRYTHON__.charset)42def b2a_uu(s):43 length = len(s)44 if length > 45:45 raise Error('At most 45 bytes at once')46 def triples_gen(s):47 while s:48 try:49 yield ord(s[0]), ord(s[1]), ord(s[2])50 except IndexError:51 s += '\0\0'52 yield ord(s[0]), ord(s[1]), ord(s[2])53 return54 s = s[3:]55 result = [''.join(56 [chr(0x20 + (( A >> 2 ) & 0x3F)),57 chr(0x20 + (((A << 4) | ((B >> 4) & 0xF)) & 0x3F)),58 chr(0x20 + (((B << 2) | ((C >> 6) & 0x3)) & 0x3F)),59 chr(0x20 + (( C ) & 0x3F))])60 for A, B, C in triples_gen(s)]61 return chr(ord(' ') + (length & 0o77)) + ''.join(result) + '\n'62table_a2b_base64 = {63 'A': 0,64 'B': 1,65 'C': 2,66 'D': 3,67 'E': 4,68 'F': 5,69 'G': 6,70 'H': 7,71 'I': 8,72 'J': 9,73 'K': 10,74 'L': 11,75 'M': 12,76 'N': 13,77 'O': 14,78 'P': 15,79 'Q': 16,80 'R': 17,81 'S': 18,82 'T': 19,83 'U': 20,84 'V': 21,85 'W': 22,86 'X': 23,87 'Y': 24,88 'Z': 25,89 'a': 26,90 'b': 27,91 'c': 28,92 'd': 29,93 'e': 30,94 'f': 31,95 'g': 32,96 'h': 33,97 'i': 34,98 'j': 35,99 'k': 36,100 'l': 37,101 'm': 38,102 'n': 39,103 'o': 40,104 'p': 41,105 'q': 42,106 'r': 43,107 's': 44,108 't': 45,109 'u': 46,110 'v': 47,111 'w': 48,112 'x': 49,113 'y': 50,114 'z': 51,115 '0': 52,116 '1': 53,117 '2': 54,118 '3': 55,119 '4': 56,120 '5': 57,121 '6': 58,122 '7': 59,123 '8': 60,124 '9': 61,125 '+': 62,126 '/': 63,127 '=': 0,128}129def a2b_base64(s):130 if not isinstance(s, (str, bytes)):131 raise TypeError("expected string, got %r" % (s,))132 s = s.rstrip()133 # clean out all invalid characters, this also strips the final '=' padding134 # check for correct padding135 def next_valid_char(s, pos):136 for i in range(pos + 1, len(s)):137 c = s[i]138 if c < '\x7f':139 try:140 table_a2b_base64[c]141 return c142 except KeyError:143 pass144 return None145 146 quad_pos = 0147 leftbits = 0148 leftchar = 0149 res = []150 for i, c in enumerate(s):151 if isinstance(c, int):152 c = chr(c)153 if c > '\x7f' or c == '\n' or c == '\r' or c == ' ':154 continue155 if c == '=':156 if quad_pos < 2 or (quad_pos == 2 and next_valid_char(s, i) != '='):157 continue158 else:159 leftbits = 0160 break161 try:162 next_c = table_a2b_base64[c]163 except KeyError:164 continue165 quad_pos = (quad_pos + 1) & 0x03166 leftchar = (leftchar << 6) | next_c167 leftbits += 6168 if leftbits >= 8:169 leftbits -= 8170 res.append((leftchar >> leftbits & 0xff))171 leftchar &= ((1 << leftbits) - 1)172 if leftbits != 0:173 raise Error('Incorrect padding')174 return bytes(''.join([chr(i) for i in res]),__BRYTHON__.charset)175 176table_b2a_base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"\177 "0123456789+/"178def b2a_base64(s):179 length = len(s)180 final_length = length % 3181 def triples_gen(s):182 while s:183 try:184 yield s[0], s[1], s[2]185 except IndexError:186 s += b'\0\0'187 yield s[0], s[1], s[2]188 return189 s = s[3:]190 a = triples_gen(s[ :length - final_length])191 result = [''.join(192 [table_b2a_base64[( A >> 2 ) & 0x3F],193 table_b2a_base64[((A << 4) | ((B >> 4) & 0xF)) & 0x3F],194 table_b2a_base64[((B << 2) | ((C >> 6) & 0x3)) & 0x3F],195 table_b2a_base64[( C ) & 0x3F]])196 for A, B, C in a]197 final = s[length - final_length:]198 if final_length == 0:199 snippet = ''200 elif final_length == 1:201 a = final[0]202 snippet = table_b2a_base64[(a >> 2 ) & 0x3F] + \203 table_b2a_base64[(a << 4 ) & 0x3F] + '=='204 else:205 a = final[0]206 b = final[1]207 snippet = table_b2a_base64[(a >> 2) & 0x3F] + \208 table_b2a_base64[((a << 4) | (b >> 4) & 0xF) & 0x3F] + \209 table_b2a_base64[(b << 2) & 0x3F] + '='210 return bytes(''.join(result) + snippet + '\n', __BRYTHON__.charset)211def a2b_qp(s, header=False):212 inp = 0213 odata = []214 while inp < len(s):215 if s[inp] == '=':216 inp += 1217 if inp >= len(s):218 break219 # Soft line breaks220 if (s[inp] == '\n') or (s[inp] == '\r'):221 if s[inp] != '\n':222 while inp < len(s) and s[inp] != '\n':223 inp += 1224 if inp < len(s):225 inp += 1226 elif s[inp] == '=':227 # broken case from broken python qp228 odata.append('=')229 inp += 1230 elif s[inp] in hex_numbers and s[inp + 1] in hex_numbers:231 ch = chr(int(s[inp:inp+2], 16))232 inp += 2233 odata.append(ch)234 else:235 odata.append('=')236 elif header and s[inp] == '_':237 odata.append(' ')238 inp += 1239 else:240 odata.append(s[inp])241 inp += 1242 return bytes(''.join(odata), __BRYTHON__.charset)243def b2a_qp(data, quotetabs=False, istext=True, header=False):244 """quotetabs=True means that tab and space characters are always245 quoted.246 istext=False means that \r and \n are treated as regular characters247 header=True encodes space characters with '_' and requires248 real '_' characters to be quoted.249 """250 MAXLINESIZE = 76251 # See if this string is using CRLF line ends252 lf = data.find('\n')253 crlf = lf > 0 and data[lf-1] == '\r'254 inp = 0255 linelen = 0256 odata = []257 while inp < len(data):258 c = data[inp]259 if (c > '~' or260 c == '=' or261 (header and c == '_') or262 (c == '.' and linelen == 0 and (inp+1 == len(data) or263 data[inp+1] == '\n' or264 data[inp+1] == '\r')) or265 (not istext and (c == '\r' or c == '\n')) or266 ((c == '\t' or c == ' ') and (inp + 1 == len(data))) or267 (c <= ' ' and c != '\r' and c != '\n' and268 (quotetabs or (not quotetabs and (c != '\t' and c != ' '))))):269 linelen += 3270 if linelen >= MAXLINESIZE:271 odata.append('=')272 if crlf: odata.append('\r')273 odata.append('\n')274 linelen = 3275 odata.append('=' + two_hex_digits(ord(c)))276 inp += 1277 else:278 if (istext and279 (c == '\n' or (inp+1 < len(data) and c == '\r' and280 data[inp+1] == '\n'))):281 linelen = 0282 # Protect against whitespace on end of line283 if (len(odata) > 0 and284 (odata[-1] == ' ' or odata[-1] == '\t')):285 ch = ord(odata[-1])286 odata[-1] = '='287 odata.append(two_hex_digits(ch))288 if crlf: odata.append('\r')289 odata.append('\n')290 if c == '\r':291 inp += 2292 else:293 inp += 1294 else:295 if (inp + 1 < len(data) and296 data[inp+1] != '\n' and297 (linelen + 1) >= MAXLINESIZE):298 odata.append('=')299 if crlf: odata.append('\r')300 odata.append('\n')301 linelen = 0302 linelen += 1303 if header and c == ' ':304 c = '_'305 odata.append(c)306 inp += 1307 return ''.join(odata)308hex_numbers = '0123456789ABCDEF'309def hex(n):310 if n == 0:311 return '0'312 313 if n < 0:314 n = -n315 sign = '-'316 else:317 sign = ''318 arr = []319 def hex_gen(n):320 """ Yield a nibble at a time. """321 while n:322 yield n % 0x10323 n = n / 0x10324 for nibble in hex_gen(n):325 arr = [hex_numbers[nibble]] + arr326 return sign + ''.join(arr)327def two_hex_digits(n):328 return hex_numbers[n / 0x10] + hex_numbers[n % 0x10]329 330def strhex_to_int(s):331 i = 0332 for c in s:333 i = i * 0x10 + hex_numbers.index(c)334 return i335hqx_encoding = '!"#$%&\'()*+,-012345689@ABCDEFGHIJKLMNPQRSTUVXYZ[`abcdefhijklmpqr'336DONE = 0x7f337SKIP = 0x7e338FAIL = 0x7d339 340table_a2b_hqx = [341 #^@ ^A ^B ^C ^D ^E ^F ^G 342 FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,343 #\b \t \n ^K ^L \r ^N ^O 344 FAIL, FAIL, SKIP, FAIL, FAIL, SKIP, FAIL, FAIL,345 #^P ^Q ^R ^S ^T ^U ^V ^W 346 FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,347 #^X ^Y ^Z ^[ ^\ ^] ^^ ^_ 348 FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,349 # ! " # $ % & ' 350 FAIL, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,351 #( ) * + , - . / 352 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, FAIL, FAIL,353 #0 1 2 3 4 5 6 7 354 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, FAIL,355 #8 9 : ; < = > ? 356 0x14, 0x15, DONE, FAIL, FAIL, FAIL, FAIL, FAIL,357 #@ A B C D E F G 358 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D,359 #H I J K L M N O 360 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, FAIL,361 #P Q R S T U V W 362 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, FAIL,363 #X Y Z [ \ ] ^ _ 364 0x2C, 0x2D, 0x2E, 0x2F, FAIL, FAIL, FAIL, FAIL,365 #` a b c d e f g 366 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, FAIL,367 #h i j k l m n o 368 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, FAIL, FAIL,369 #p q r s t u v w 370 0x3D, 0x3E, 0x3F, FAIL, FAIL, FAIL, FAIL, FAIL,371 #x y z { | } ~ ^? 372 FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,373 FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,374 FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,375 FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,376 FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,377 FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,378 FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,379 FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,380 FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,381 FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,382 FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,383 FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,384 FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,385 FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,386 FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,387 FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,388 FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,389]390def a2b_hqx(s):391 result = []392 def quadruples_gen(s):393 t = []394 for c in s:395 res = table_a2b_hqx[ord(c)]396 if res == SKIP:397 continue398 elif res == FAIL:399 raise Error('Illegal character')400 elif res == DONE:401 yield t402 raise Done403 else:404 t.append(res)405 if len(t) == 4:406 yield t407 t = []408 yield t409 410 done = 0411 try:412 for snippet in quadruples_gen(s):413 length = len(snippet)414 if length == 4:415 result.append(chr(((snippet[0] & 0x3f) << 2) | (snippet[1] >> 4))) 416 result.append(chr(((snippet[1] & 0x0f) << 4) | (snippet[2] >> 2))) 417 result.append(chr(((snippet[2] & 0x03) << 6) | (snippet[3]))) 418 elif length == 3:419 result.append(chr(((snippet[0] & 0x3f) << 2) | (snippet[1] >> 4))) 420 result.append(chr(((snippet[1] & 0x0f) << 4) | (snippet[2] >> 2))) 421 elif length == 2:422 result.append(chr(((snippet[0] & 0x3f) << 2) | (snippet[1] >> 4))) 423 except Done:424 done = 1425 except Error:426 raise427 return (''.join(result), done)428 # should this return a bytes object?429 #return (bytes(''.join(result), __BRYTHON__.charset), done)430def b2a_hqx(s):431 result =[]432 def triples_gen(s):433 while s:434 try:435 yield ord(s[0]), ord(s[1]), ord(s[2])436 except IndexError:437 yield tuple([ord(c) for c in s])438 s = s[3:]439 for snippet in triples_gen(s):440 length = len(snippet)441 if length == 3:442 result.append(443 hqx_encoding[(snippet[0] & 0xfc) >> 2])444 result.append(hqx_encoding[445 ((snippet[0] & 0x03) << 4) | ((snippet[1] & 0xf0) >> 4)])446 result.append(hqx_encoding[447 (snippet[1] & 0x0f) << 2 | ((snippet[2] & 0xc0) >> 6)])448 result.append(hqx_encoding[snippet[2] & 0x3f])449 elif length == 2:450 result.append(451 hqx_encoding[(snippet[0] & 0xfc) >> 2])452 result.append(hqx_encoding[453 ((snippet[0] & 0x03) << 4) | ((snippet[1] & 0xf0) >> 4)])454 result.append(hqx_encoding[455 (snippet[1] & 0x0f) << 2])456 elif length == 1:457 result.append(458 hqx_encoding[(snippet[0] & 0xfc) >> 2])459 result.append(hqx_encoding[460 ((snippet[0] & 0x03) << 4)])461 return ''.join(result)462crctab_hqx = [463 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7,464 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef,465 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6,466 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de,467 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485,468 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d,469 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4,470 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc,471 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823,472 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b,473 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12,474 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a,475 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41,476 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49,477 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70,478 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78,479 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f,480 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067,481 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e,482 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256,483 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d,484 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,485 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c,486 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634,487 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab,488 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3,489 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a,490 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92,491 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9,492 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1,493 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8,494 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0,495]496def crc_hqx(s, crc):497 for c in s:498 crc = ((crc << 8) & 0xff00) ^ crctab_hqx[((crc >> 8) & 0xff) ^ ord(c)]499 return crc500def rlecode_hqx(s):501 """502 Run length encoding for binhex4.503 The CPython implementation does not do run length encoding504 of \x90 characters. This implementation does.505 """506 if not s:507 return ''508 result = []509 prev = s[0]510 count = 1511 # Add a dummy character to get the loop to go one extra round.512 # The dummy must be different from the last character of s.513 # In the same step we remove the first character, which has514 # already been stored in prev.515 if s[-1] == '!':516 s = s[1:] + '?'517 else:518 s = s[1:] + '!'519 520 for c in s:521 if c == prev and count < 255:522 count += 1523 else:524 if count == 1:525 if prev != '\x90':526 result.append(prev)527 else:528 result.extend(['\x90', '\x00'])529 elif count < 4:530 if prev != '\x90':531 result.extend([prev] * count)532 else:533 result.extend(['\x90', '\x00'] * count)534 else:535 if prev != '\x90':536 result.extend([prev, '\x90', chr(count)])537 else:538 result.extend(['\x90', '\x00', '\x90', chr(count)]) 539 count = 1540 prev = c541 542 return ''.join(result)543def rledecode_hqx(s):544 s = s.split('\x90')545 result = [s[0]]546 prev = s[0]547 for snippet in s[1:]:548 count = ord(snippet[0])549 if count > 0:550 result.append(prev[-1] * (count-1))551 prev = snippet552 else:553 result.append('\x90')554 prev = '\x90'555 result.append(snippet[1:])556 return ''.join(result)557crc_32_tab = [558 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419,559 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4,560 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07,561 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,562 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856,563 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,564 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4,565 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,566 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3,567 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a,568 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599,569 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,570 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190,571 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f,572 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e,573 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,574 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed,575 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,576 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3,577 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,578 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a,579 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5,580 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010,581 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,582 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17,583 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6,584 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615,585 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,586 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344,587 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,588 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a,589 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,590 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1,591 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c,592 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef,593 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,594 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe,595 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31,596 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c,597 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,598 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b,599 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,600 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1,601 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,602 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278,603 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7,604 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66,605 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,606 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605,607 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8,608 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b,609 0x2d02ef8d610]611def crc32(s, crc=0):612 result = 0613 crc = ~int(crc) & 0xffffffff614 #crc = ~long(crc) & 0xffffffffL615 for c in s:616 crc = crc_32_tab[(crc ^ int(ord(c))) & 0xff] ^ (crc >> 8)617 #crc = crc_32_tab[(crc ^ long(ord(c))) & 0xffL] ^ (crc >> 8)618 #/* Note: (crc >> 8) MUST zero fill on left619 result = crc ^ 0xffffffff620 621 if result > 2**31:622 result = ((result + 2**31) % 2**32) - 2**31623 return result624def b2a_hex(s):625 result = []626 for char in s:627 c = (ord(char) >> 4) & 0xf628 if c > 9:629 c = c + ord('a') - 10630 else:631 c = c + ord('0')632 result.append(chr(c))633 c = ord(char) & 0xf634 if c > 9:635 c = c + ord('a') - 10636 else:637 c = c + ord('0')638 result.append(chr(c))639 return ''.join(result)640hexlify = b2a_hex641table_hex = [642 -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,643 -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,644 -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,645 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1, -1,-1,-1,-1,646 -1,10,11,12, 13,14,15,-1, -1,-1,-1,-1, -1,-1,-1,-1,647 -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,648 -1,10,11,12, 13,14,15,-1, -1,-1,-1,-1, -1,-1,-1,-1,649 -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1650]651def a2b_hex(t):652 result = []653 def pairs_gen(s):654 while s:655 try:656 yield table_hex[ord(s[0])], table_hex[ord(s[1])]657 except IndexError:658 if len(s):659 raise TypeError('Odd-length string')660 return661 s = s[2:]662 for a, b in pairs_gen(t):663 if a < 0 or b < 0:664 raise TypeError('Non-hexadecimal digit found')665 result.append(chr((a << 4) + b))666 return bytes(''.join(result), __BRYTHON__.charset)667 ...
test_operator.py
Source:test_operator.py
1import operator2import unittest3from test import test_support4class Seq1:5 def __init__(self, lst):6 self.lst = lst7 def __len__(self):8 return len(self.lst)9 def __getitem__(self, i):10 return self.lst[i]11 def __add__(self, other):12 return self.lst + other.lst13 def __mul__(self, other):14 return self.lst * other15 def __rmul__(self, other):16 return other * self.lst17class Seq2(object):18 def __init__(self, lst):19 self.lst = lst20 def __len__(self):21 return len(self.lst)22 def __getitem__(self, i):23 return self.lst[i]24 def __add__(self, other):25 return self.lst + other.lst26 def __mul__(self, other):27 return self.lst * other28 def __rmul__(self, other):29 return other * self.lst30class OperatorTestCase(unittest.TestCase):31 def test_lt(self):32 self.failUnlessRaises(TypeError, operator.lt)33 self.failUnlessRaises(TypeError, operator.lt, 1j, 2j)34 self.failIf(operator.lt(1, 0))35 self.failIf(operator.lt(1, 0.0))36 self.failIf(operator.lt(1, 1))37 self.failIf(operator.lt(1, 1.0))38 self.failUnless(operator.lt(1, 2))39 self.failUnless(operator.lt(1, 2.0))40 def test_le(self):41 self.failUnlessRaises(TypeError, operator.le)42 self.failUnlessRaises(TypeError, operator.le, 1j, 2j)43 self.failIf(operator.le(1, 0))44 self.failIf(operator.le(1, 0.0))45 self.failUnless(operator.le(1, 1))46 self.failUnless(operator.le(1, 1.0))47 self.failUnless(operator.le(1, 2))48 self.failUnless(operator.le(1, 2.0))49 def test_eq(self):50 class C(object):51 def __eq__(self, other):52 raise SyntaxError53 self.failUnlessRaises(TypeError, operator.eq)54 self.failUnlessRaises(SyntaxError, operator.eq, C(), C())55 self.failIf(operator.eq(1, 0))56 self.failIf(operator.eq(1, 0.0))57 self.failUnless(operator.eq(1, 1))58 self.failUnless(operator.eq(1, 1.0))59 self.failIf(operator.eq(1, 2))60 self.failIf(operator.eq(1, 2.0))61 def test_ne(self):62 class C(object):63 def __ne__(self, other):64 raise SyntaxError65 self.failUnlessRaises(TypeError, operator.ne)66 self.failUnlessRaises(SyntaxError, operator.ne, C(), C())67 self.failUnless(operator.ne(1, 0))68 self.failUnless(operator.ne(1, 0.0))69 self.failIf(operator.ne(1, 1))70 self.failIf(operator.ne(1, 1.0))71 self.failUnless(operator.ne(1, 2))72 self.failUnless(operator.ne(1, 2.0))73 def test_ge(self):74 self.failUnlessRaises(TypeError, operator.ge)75 self.failUnlessRaises(TypeError, operator.ge, 1j, 2j)76 self.failUnless(operator.ge(1, 0))77 self.failUnless(operator.ge(1, 0.0))78 self.failUnless(operator.ge(1, 1))79 self.failUnless(operator.ge(1, 1.0))80 self.failIf(operator.ge(1, 2))81 self.failIf(operator.ge(1, 2.0))82 def test_gt(self):83 self.failUnlessRaises(TypeError, operator.gt)84 self.failUnlessRaises(TypeError, operator.gt, 1j, 2j)85 self.failUnless(operator.gt(1, 0))86 self.failUnless(operator.gt(1, 0.0))87 self.failIf(operator.gt(1, 1))88 self.failIf(operator.gt(1, 1.0))89 self.failIf(operator.gt(1, 2))90 self.failIf(operator.gt(1, 2.0))91 def test_abs(self):92 self.failUnlessRaises(TypeError, operator.abs)93 self.failUnlessRaises(TypeError, operator.abs, None)94 self.failUnless(operator.abs(-1) == 1)95 self.failUnless(operator.abs(1) == 1)96 def test_add(self):97 self.failUnlessRaises(TypeError, operator.add)98 self.failUnlessRaises(TypeError, operator.add, None, None)99 self.failUnless(operator.add(3, 4) == 7)100 def test_bitwise_and(self):101 self.failUnlessRaises(TypeError, operator.and_)102 self.failUnlessRaises(TypeError, operator.and_, None, None)103 self.failUnless(operator.and_(0xf, 0xa) == 0xa)104 def test_concat(self):105 self.failUnlessRaises(TypeError, operator.concat)106 self.failUnlessRaises(TypeError, operator.concat, None, None)107 self.failUnless(operator.concat('py', 'thon') == 'python')108 self.failUnless(operator.concat([1, 2], [3, 4]) == [1, 2, 3, 4])109 self.failUnless(operator.concat(Seq1([5, 6]), Seq1([7])) == [5, 6, 7])110 self.failUnless(operator.concat(Seq2([5, 6]), Seq2([7])) == [5, 6, 7])111 self.failUnlessRaises(TypeError, operator.concat, 13, 29)112 def test_countOf(self):113 self.failUnlessRaises(TypeError, operator.countOf)114 self.failUnlessRaises(TypeError, operator.countOf, None, None)115 self.failUnless(operator.countOf([1, 2, 1, 3, 1, 4], 3) == 1)116 self.failUnless(operator.countOf([1, 2, 1, 3, 1, 4], 5) == 0)117 def test_delitem(self):118 a = [4, 3, 2, 1]119 self.failUnlessRaises(TypeError, operator.delitem, a)120 self.failUnlessRaises(TypeError, operator.delitem, a, None)121 self.failUnless(operator.delitem(a, 1) is None)122 self.assert_(a == [4, 2, 1])123 def test_delslice(self):124 a = range(10)125 self.failUnlessRaises(TypeError, operator.delslice, a)126 self.failUnlessRaises(TypeError, operator.delslice, a, None, None)127 self.failUnless(operator.delslice(a, 2, 8) is None)128 self.assert_(a == [0, 1, 8, 9])129 operator.delslice(a, 0, test_support.MAX_Py_ssize_t)130 self.assert_(a == [])131 def test_div(self):132 self.failUnlessRaises(TypeError, operator.div, 5)133 self.failUnlessRaises(TypeError, operator.div, None, None)134 self.failUnless(operator.floordiv(5, 2) == 2)135 def test_floordiv(self):136 self.failUnlessRaises(TypeError, operator.floordiv, 5)137 self.failUnlessRaises(TypeError, operator.floordiv, None, None)138 self.failUnless(operator.floordiv(5, 2) == 2)139 def test_truediv(self):140 self.failUnlessRaises(TypeError, operator.truediv, 5)141 self.failUnlessRaises(TypeError, operator.truediv, None, None)142 self.failUnless(operator.truediv(5, 2) == 2.5)143 def test_getitem(self):144 a = range(10)145 self.failUnlessRaises(TypeError, operator.getitem)146 self.failUnlessRaises(TypeError, operator.getitem, a, None)147 self.failUnless(operator.getitem(a, 2) == 2)148 def test_getslice(self):149 a = range(10)150 self.failUnlessRaises(TypeError, operator.getslice)151 self.failUnlessRaises(TypeError, operator.getslice, a, None, None)152 self.failUnless(operator.getslice(a, 4, 6) == [4, 5])153 b = operator.getslice(a, 0, test_support.MAX_Py_ssize_t)154 self.assert_(b == a)155 def test_indexOf(self):156 self.failUnlessRaises(TypeError, operator.indexOf)157 self.failUnlessRaises(TypeError, operator.indexOf, None, None)158 self.failUnless(operator.indexOf([4, 3, 2, 1], 3) == 1)159 self.assertRaises(ValueError, operator.indexOf, [4, 3, 2, 1], 0)160 def test_invert(self):161 self.failUnlessRaises(TypeError, operator.invert)162 self.failUnlessRaises(TypeError, operator.invert, None)163 self.failUnless(operator.inv(4) == -5)164 def test_isCallable(self):165 self.failUnlessRaises(TypeError, operator.isCallable)166 class C:167 pass168 def check(self, o, v):169 self.assert_(operator.isCallable(o) == callable(o) == v)170 check(self, 4, 0)171 check(self, operator.isCallable, 1)172 check(self, C, 1)173 check(self, C(), 0)174 def test_isMappingType(self):175 self.failUnlessRaises(TypeError, operator.isMappingType)176 self.failIf(operator.isMappingType(1))177 self.failIf(operator.isMappingType(operator.isMappingType))178 self.failUnless(operator.isMappingType(operator.__dict__))179 self.failUnless(operator.isMappingType({}))180 def test_isNumberType(self):181 self.failUnlessRaises(TypeError, operator.isNumberType)182 self.failUnless(operator.isNumberType(8))183 self.failUnless(operator.isNumberType(8j))184 self.failUnless(operator.isNumberType(8L))185 self.failUnless(operator.isNumberType(8.3))186 self.failIf(operator.isNumberType(dir()))187 def test_isSequenceType(self):188 self.failUnlessRaises(TypeError, operator.isSequenceType)189 self.failUnless(operator.isSequenceType(dir()))190 self.failUnless(operator.isSequenceType(()))191 self.failUnless(operator.isSequenceType(xrange(10)))192 self.failUnless(operator.isSequenceType('yeahbuddy'))193 self.failIf(operator.isSequenceType(3))194 class Dict(dict): pass195 self.failIf(operator.isSequenceType(Dict()))196 def test_lshift(self):197 self.failUnlessRaises(TypeError, operator.lshift)198 self.failUnlessRaises(TypeError, operator.lshift, None, 42)199 self.failUnless(operator.lshift(5, 1) == 10)200 self.failUnless(operator.lshift(5, 0) == 5)201 self.assertRaises(ValueError, operator.lshift, 2, -1)202 def test_mod(self):203 self.failUnlessRaises(TypeError, operator.mod)204 self.failUnlessRaises(TypeError, operator.mod, None, 42)205 self.failUnless(operator.mod(5, 2) == 1)206 def test_mul(self):207 self.failUnlessRaises(TypeError, operator.mul)208 self.failUnlessRaises(TypeError, operator.mul, None, None)209 self.failUnless(operator.mul(5, 2) == 10)210 def test_neg(self):211 self.failUnlessRaises(TypeError, operator.neg)212 self.failUnlessRaises(TypeError, operator.neg, None)213 self.failUnless(operator.neg(5) == -5)214 self.failUnless(operator.neg(-5) == 5)215 self.failUnless(operator.neg(0) == 0)216 self.failUnless(operator.neg(-0) == 0)217 def test_bitwise_or(self):218 self.failUnlessRaises(TypeError, operator.or_)219 self.failUnlessRaises(TypeError, operator.or_, None, None)220 self.failUnless(operator.or_(0xa, 0x5) == 0xf)221 def test_pos(self):222 self.failUnlessRaises(TypeError, operator.pos)223 self.failUnlessRaises(TypeError, operator.pos, None)224 self.failUnless(operator.pos(5) == 5)225 self.failUnless(operator.pos(-5) == -5)226 self.failUnless(operator.pos(0) == 0)227 self.failUnless(operator.pos(-0) == 0)228 def test_pow(self):229 self.failUnlessRaises(TypeError, operator.pow)230 self.failUnlessRaises(TypeError, operator.pow, None, None)231 self.failUnless(operator.pow(3,5) == 3**5)232 self.failUnless(operator.__pow__(3,5) == 3**5)233 self.assertRaises(TypeError, operator.pow, 1)234 self.assertRaises(TypeError, operator.pow, 1, 2, 3)235 def test_repeat(self):236 a = range(3)237 self.failUnlessRaises(TypeError, operator.repeat)238 self.failUnlessRaises(TypeError, operator.repeat, a, None)239 self.failUnless(operator.repeat(a, 2) == a+a)240 self.failUnless(operator.repeat(a, 1) == a)241 self.failUnless(operator.repeat(a, 0) == [])242 a = (1, 2, 3)243 self.failUnless(operator.repeat(a, 2) == a+a)244 self.failUnless(operator.repeat(a, 1) == a)245 self.failUnless(operator.repeat(a, 0) == ())246 a = '123'247 self.failUnless(operator.repeat(a, 2) == a+a)248 self.failUnless(operator.repeat(a, 1) == a)249 self.failUnless(operator.repeat(a, 0) == '')250 a = Seq1([4, 5, 6])251 self.failUnless(operator.repeat(a, 2) == [4, 5, 6, 4, 5, 6])252 self.failUnless(operator.repeat(a, 1) == [4, 5, 6])253 self.failUnless(operator.repeat(a, 0) == [])254 a = Seq2([4, 5, 6])255 self.failUnless(operator.repeat(a, 2) == [4, 5, 6, 4, 5, 6])256 self.failUnless(operator.repeat(a, 1) == [4, 5, 6])257 self.failUnless(operator.repeat(a, 0) == [])258 self.failUnlessRaises(TypeError, operator.repeat, 6, 7)259 def test_rshift(self):260 self.failUnlessRaises(TypeError, operator.rshift)261 self.failUnlessRaises(TypeError, operator.rshift, None, 42)262 self.failUnless(operator.rshift(5, 1) == 2)263 self.failUnless(operator.rshift(5, 0) == 5)264 self.assertRaises(ValueError, operator.rshift, 2, -1)265 def test_contains(self):266 self.failUnlessRaises(TypeError, operator.contains)267 self.failUnlessRaises(TypeError, operator.contains, None, None)268 self.failUnless(operator.contains(range(4), 2))269 self.failIf(operator.contains(range(4), 5))270 self.failUnless(operator.sequenceIncludes(range(4), 2))271 self.failIf(operator.sequenceIncludes(range(4), 5))272 def test_setitem(self):273 a = range(3)274 self.failUnlessRaises(TypeError, operator.setitem, a)275 self.failUnlessRaises(TypeError, operator.setitem, a, None, None)276 self.failUnless(operator.setitem(a, 0, 2) is None)277 self.assert_(a == [2, 1, 2])278 self.assertRaises(IndexError, operator.setitem, a, 4, 2)279 def test_setslice(self):280 a = range(4)281 self.failUnlessRaises(TypeError, operator.setslice, a)282 self.failUnlessRaises(TypeError, operator.setslice, a, None, None, None)283 self.failUnless(operator.setslice(a, 1, 3, [2, 1]) is None)284 self.assert_(a == [0, 2, 1, 3])285 operator.setslice(a, 0, test_support.MAX_Py_ssize_t, [])286 self.assert_(a == [])287 def test_sub(self):288 self.failUnlessRaises(TypeError, operator.sub)289 self.failUnlessRaises(TypeError, operator.sub, None, None)290 self.failUnless(operator.sub(5, 2) == 3)291 def test_truth(self):292 class C(object):293 def __nonzero__(self):294 raise SyntaxError295 self.failUnlessRaises(TypeError, operator.truth)296 self.failUnlessRaises(SyntaxError, operator.truth, C())297 self.failUnless(operator.truth(5))298 self.failUnless(operator.truth([0]))299 self.failIf(operator.truth(0))300 self.failIf(operator.truth([]))301 def test_bitwise_xor(self):302 self.failUnlessRaises(TypeError, operator.xor)303 self.failUnlessRaises(TypeError, operator.xor, None, None)304 self.failUnless(operator.xor(0xb, 0xc) == 0x7)305 def test_is(self):306 a = b = 'xyzpdq'307 c = a[:3] + b[3:]308 self.failUnlessRaises(TypeError, operator.is_)309 self.failUnless(operator.is_(a, b))310 self.failIf(operator.is_(a,c))311 def test_is_not(self):312 a = b = 'xyzpdq'313 c = a[:3] + b[3:]314 self.failUnlessRaises(TypeError, operator.is_not)315 self.failIf(operator.is_not(a, b))316 self.failUnless(operator.is_not(a,c))317 def test_attrgetter(self):318 class A:319 pass320 a = A()321 a.name = 'arthur'322 f = operator.attrgetter('name')323 self.assertEqual(f(a), 'arthur')324 f = operator.attrgetter('rank')325 self.assertRaises(AttributeError, f, a)326 f = operator.attrgetter(2)327 self.assertRaises(TypeError, f, a)328 self.assertRaises(TypeError, operator.attrgetter)329 # multiple gets330 record = A()331 record.x = 'X'332 record.y = 'Y'333 record.z = 'Z'334 self.assertEqual(operator.attrgetter('x','z','y')(record), ('X', 'Z', 'Y'))335 self.assertRaises(TypeError, operator.attrgetter('x', (), 'y'), record)336 class C(object):337 def __getattr(self, name):338 raise SyntaxError339 self.failUnlessRaises(AttributeError, operator.attrgetter('foo'), C())340 def test_itemgetter(self):341 a = 'ABCDE'342 f = operator.itemgetter(2)343 self.assertEqual(f(a), 'C')344 f = operator.itemgetter(10)345 self.assertRaises(IndexError, f, a)346 class C(object):347 def __getitem(self, name):348 raise SyntaxError349 self.failUnlessRaises(TypeError, operator.itemgetter(42), C())350 f = operator.itemgetter('name')351 self.assertRaises(TypeError, f, a)352 self.assertRaises(TypeError, operator.itemgetter)353 d = dict(key='val')354 f = operator.itemgetter('key')355 self.assertEqual(f(d), 'val')356 f = operator.itemgetter('nonkey')357 self.assertRaises(KeyError, f, d)358 # example used in the docs359 inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]360 getcount = operator.itemgetter(1)361 self.assertEqual(map(getcount, inventory), [3, 2, 5, 1])362 self.assertEqual(sorted(inventory, key=getcount),363 [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)])364 # multiple gets365 data = map(str, range(20))366 self.assertEqual(operator.itemgetter(2,10,5)(data), ('2', '10', '5'))367 self.assertRaises(TypeError, operator.itemgetter(2, 'x', 5), data)368 def test_inplace(self):369 class C(object):370 def __iadd__ (self, other): return "iadd"371 def __iand__ (self, other): return "iand"372 def __idiv__ (self, other): return "idiv"373 def __ifloordiv__(self, other): return "ifloordiv"374 def __ilshift__ (self, other): return "ilshift"375 def __imod__ (self, other): return "imod"376 def __imul__ (self, other): return "imul"377 def __ior__ (self, other): return "ior"378 def __ipow__ (self, other): return "ipow"379 def __irshift__ (self, other): return "irshift"380 def __isub__ (self, other): return "isub"381 def __itruediv__ (self, other): return "itruediv"382 def __ixor__ (self, other): return "ixor"383 def __getitem__(self, other): return 5 # so that C is a sequence384 c = C()385 self.assertEqual(operator.iadd (c, 5), "iadd")386 self.assertEqual(operator.iand (c, 5), "iand")387 self.assertEqual(operator.idiv (c, 5), "idiv")388 self.assertEqual(operator.ifloordiv(c, 5), "ifloordiv")389 self.assertEqual(operator.ilshift (c, 5), "ilshift")390 self.assertEqual(operator.imod (c, 5), "imod")391 self.assertEqual(operator.imul (c, 5), "imul")392 self.assertEqual(operator.ior (c, 5), "ior")393 self.assertEqual(operator.ipow (c, 5), "ipow")394 self.assertEqual(operator.irshift (c, 5), "irshift")395 self.assertEqual(operator.isub (c, 5), "isub")396 self.assertEqual(operator.itruediv (c, 5), "itruediv")397 self.assertEqual(operator.ixor (c, 5), "ixor")398 self.assertEqual(operator.iconcat (c, c), "iadd")399 self.assertEqual(operator.irepeat (c, 5), "imul")400 self.assertEqual(operator.__iadd__ (c, 5), "iadd")401 self.assertEqual(operator.__iand__ (c, 5), "iand")402 self.assertEqual(operator.__idiv__ (c, 5), "idiv")403 self.assertEqual(operator.__ifloordiv__(c, 5), "ifloordiv")404 self.assertEqual(operator.__ilshift__ (c, 5), "ilshift")405 self.assertEqual(operator.__imod__ (c, 5), "imod")406 self.assertEqual(operator.__imul__ (c, 5), "imul")407 self.assertEqual(operator.__ior__ (c, 5), "ior")408 self.assertEqual(operator.__ipow__ (c, 5), "ipow")409 self.assertEqual(operator.__irshift__ (c, 5), "irshift")410 self.assertEqual(operator.__isub__ (c, 5), "isub")411 self.assertEqual(operator.__itruediv__ (c, 5), "itruediv")412 self.assertEqual(operator.__ixor__ (c, 5), "ixor")413 self.assertEqual(operator.__iconcat__ (c, c), "iadd")414 self.assertEqual(operator.__irepeat__ (c, 5), "imul")415def test_main(verbose=None):416 import sys417 test_classes = (418 OperatorTestCase,419 )420 test_support.run_unittest(*test_classes)421 # verify reference counting422 if verbose and hasattr(sys, "gettotalrefcount"):423 import gc424 counts = [None] * 5425 for i in xrange(len(counts)):426 test_support.run_unittest(*test_classes)427 gc.collect()428 counts[i] = sys.gettotalrefcount()429 print counts430if __name__ == "__main__":...
test_PyCintex_basics.py
Source:test_PyCintex_basics.py
1#!/usr/bin/env python2#3# PyLCGDict unittest programs4# ---------------------------5# Author: Pere Mato6# (June 2003)7#8import unittest9import sys10import PyCintex11class BasicsTestCase(unittest.TestCase):12 def setUp(self):13 PyCintex.makeClass('A::B::C::MyClass') # This is needed to force loading the dictionary14 self.A = PyCintex.makeNamespace('A')15 self.std = PyCintex.makeNamespace('std')16 self.gbl = PyCintex.makeNamespace('')17 18 def tearDown(self):19 pass20 def test01DoSomething(self):21 object = self.A.B.C.MyClass()22 self.failUnless( isinstance(object, self.A.B.C.MyClass),23 'unable to create an instance of A::B::C::MyClass')24 result = object.doSomething('Hello World')25 self.failUnless( result == len('Hello World'),26 'incorrect return value from doSomething')27 self.failUnlessEqual( self.A.B.C.ValidityKeyMin, 0) 28 29 30 def test02PrimitiveArgTypes(self):31 p = self.A.B.C.Primitives()32 self.failUnless( isinstance(p, self.A.B.C.Primitives) )33 p.set_b(False)34 self.failUnless( p.b() == False , 'fail to set bool false')35 p.set_b(True)36 self.failUnless( p.b() == True , 'fail to set bool true')37 self.failUnlessRaises( TypeError, p.set_b, 10 )38 p.set_c('h')39 self.failUnless( p.c() == 'h', 'fail to set char')40 p.set_c(40)41 self.failUnless( p.c() == chr(40), 'fail to set char')42 self.failUnlessRaises( TypeError, p.set_c, 'ssss') 43 p.set_s(-8)44 self.failUnless( p.s() == -8, 'fail to set short' )45 self.failUnlessRaises( TypeError, p.set_s, 1.5) 46 self.failUnlessRaises( TypeError, p.set_s, 'ssss') 47 p.set_i(8)48 self.failUnless( p.i() == 8, 'fail to set int' )49 p.set_l(-8)50 self.failUnless( p.l() == -8, 'fail to set long' )51 p.set_ll(-8)52 self.failUnless( p.ll() == -8, 'fail to set long long' )53 p.set_uc(8)54 self.failUnless( p.uc() == chr(8), 'fail to set unsigned char' )55 p.set_us(8)56 self.failUnless( p.us() == 8, 'fail to set unsigned short' )57 p.set_ui(8)58 self.failUnless( p.ui() == 8, 'fail to set unsigned int' )59 p.set_ul(88)60 p.set_f(8.8)61 self.failUnless( abs(p.f() - 8.8) < 0.00001, 'fail to set float' )62 p.set_d(8.8)63 self.failUnless( p.d() == 8.8, 'fail to set double' )64 p.set_str('This is a string')65 self.failUnless( p.str() == 'This is a string', 'fail to set string' )66 self.failUnless( type(p.str()) is str, 'fail to comprate type of strings' )67 p.set_cstr('This is a C string')68 self.failUnless( p.cstr() == 'This is a C string', 'fail to set string' )69 self.failUnless( p.ccstr() == 'This is a C string', 'fail to set string' )70 p.set_all(1,'g',7,7,7,7.7,7.7,'Another string')71 self.failUnless( (p.b(), p.c(),p.s(),p.i(),p.l(), p.str()) ==72 (1,'g',7,7,7,'Another string'),73 'fail to set multiple argument types' )74 def test03ReturnModes(self):75 myobj = self.A.B.C.MyClass()76 myobj.setMagic(1234567890)77 self.failUnless( myobj.magic() == 1234567890 )78 calling = self.A.B.C.Calling()79 calling.setByReference(myobj)80 self.failUnless( calling.retByValue().magic() == 1234567890 , 'fail return by value')81 self.failUnless( calling.retByPointer().magic() == 1234567890 , 'fail return by pointer')82 self.failUnless( calling.retByReference().magic() == 1234567890 , 'fail return by reference')83 self.failUnless( calling.retByRefPointer().magic() == 1234567890 , 'fail return by reference pointer')84 self.failUnless( calling.retByVoidPointer(), 'fail return by void pointer')85 myobj.setMagic(111111111)86 self.failUnless( myobj.magic() == 111111111 )87 calling = self.A.B.C.Calling()88 calling.setByConstReference(myobj)89 self.failUnless( calling.retByValue().magic() == 111111111 , 'fail return by value')90 self.failUnless( calling.retByPointer().magic() == 111111111 , 'fail return by pointer')91 self.failUnless( calling.retByReference().magic() == 111111111 , 'fail return by reference')92 self.failUnless( calling.retByRefPointer().magic() == 111111111 , 'fail return by reference pointer')93 self.failUnless( calling.retByVoidPointer(), 'fail return by void pointer')94 def test04UnknownTypes(self) :95 calling = self.A.B.C.Calling()96 #---Returning unknown types97 rp = calling.retUnknownTypePointer()98 self.failUnless( rp )99 rr = calling.retUnknownTypeReference()100 self.failUnless( rr )101 #---Passing unknown types102 self.failUnlessEqual( calling.setByUnknownTypePointer(rp), 0x12345678)103 self.failUnlessEqual( calling.setByUnknownTypeReference(rr), 0x12345678)104 self.failUnlessEqual( calling.setByUnknownConstTypePointer(rp), 0x12345678)105 self.failUnlessEqual( calling.setByUnknownConstTypeReference(rr), 0x12345678)106 107 def test05ReturnDynamicType(self):108 dfact = self.A.B.C.DiamondFactory()109 d = dfact.getDiamond()110 self.failUnless(d)111 self.failUnlessEqual(d.vf(), 999.999)112 v = dfact.getVirtual()113 self.failUnless(v)114 self.failUnlessEqual(v.magic(), 987654321 )115 v.setMagic(22222)116 self.failUnlessEqual(d.magic(), 22222 )117 def test06CallingModes(self):118 self.failUnlessEqual( self.A.B.C.MyClass.instances(), 0) 119 self.failUnlessEqual( self.A.B.C.s_public_instances, 0) 120 myobj = self.A.B.C.MyClass()121 calling = self.A.B.C.Calling()122 myobj.setMagic(22222222)123 #---Check calling modes-------------124 calling.setByReference(myobj)125 self.failUnless( calling.retByPointer().magic() == 22222222 , 'fail set by value')126 myobj.setMagic(33333333)127 calling.setByPointer(myobj)128 self.failUnless( calling.retByPointer().magic() == 33333333 , 'fail set by pointer')129 self.failUnless( myobj.magic() == 999999 , 'fail set by pointer')130 # None not acceptable; user ROOT.NULL instead ...131 #calling.setByPointer(None)132 #calling.setByPointer( ROOT.NULL )133 calling.setByPointer(PyCintex.NULL)134 self.failUnless( calling.retByPointer().magic() == 0 , 'fail set by null pointer')135 myobj.setMagic(44444444)136 calling.setByReference(myobj)137 self.failUnless( calling.retByPointer().magic() == 44444444 , 'fail set by reference')138 self.failUnless( myobj.magic() == 999999 , 'fail set by reference')139 myobj.setMagic(55555555)140 calling.setByRefPointer(myobj)141 self.failUnless( calling.retByPointer().magic() == 55555555 , 'fail set by reference pointer')142 self.failUnless( myobj.magic() == 999999 , 'fail set by reference pointer')143 self.failUnlessEqual( calling.retStrByValue(), 'value' )144 self.failUnlessEqual( calling.retStrByRef(), 'reference' )145 self.failUnlessEqual( calling.retStrByConstRef(), 'const reference' )146 self.failUnlessEqual( calling.retConstCStr(), 'const pointer' )147 self.failUnlessEqual( calling.retCStr(), 'pointer' )148 del myobj, calling149 self.failUnlessEqual( self.A.B.C.MyClass.instances(), 0)150 151 def test07CallingChecks(self):152 calling = self.A.B.C.Calling()153 #---Check invalid argument type-------------154 self.assertRaises(TypeError, calling.setByValue, calling)155 self.assertRaises(TypeError, calling.setByPointer, calling)156 #---Implicit cast conversions-------157 xobj = self.A.B.C.Diamond()158 xobj.setMagic(88888888)159 calling.setByReference(xobj)160 self.failUnlessEqual( calling.retByPointer().magic(), 88888888 )161 xobj.setMagic(99999999)162 calling.setByPointer(xobj)163 self.failUnlessEqual( calling.retByPointer().magic(), 99999999 )164 del calling, xobj165 self.failUnlessEqual( self.A.B.C.MyClass.instances(), 0)166 def test08VoidPointerArgument(self):167 calling = self.A.B.C.Calling()168 obj = self.A.B.C.MyClass()169 obj.setMagic(77777777)170 calling.setByVoidPointer(obj)171 self.failUnless( calling.retByPointer().magic() == 77777777 , 'fail set by void pointer') 172 del calling, obj173 self.failUnlessEqual( self.A.B.C.MyClass.instances(), 0 , 'MyClass instances not deleted')174 def test09TemplatedClasses(self) :175 tc1 = getattr(self.A.B.C, 'Template<A::B::C::MyClass,float>')176 tc2 = self.A.B.C.Template(self.A.B.C.MyClass,'float')177 tc3 = self.A.B.C.Template(self.A.B.C.MyClass,float)178 tc4 = self.gbl.GlobalTemplate(self.A.B.C.MyClass, float)179 self.failUnless( str(tc2) == str(tc3), 'template instanciation using TemplateGenerator')180 #[ Bug #2239 ] Invalid python identity on templated classes181 self.failUnless( tc2 is self.A.B.C.Template(self.A.B.C.MyClass,'float'))182 self.failUnless( tc2 is tc3 )183 self.failUnless( tc2 is self.A.B.C.Template(self.A.B.C.MyClass,float))184 self.failUnless( tc4 is self.gbl.GlobalTemplate(self.A.B.C.MyClass, float))185 # Object instantiation186 object = self.A.B.C.Template(self.A.B.C.MyClass,'float')()187 result = object.doSomething('Hello World')188 self.failUnless( result == len('Hello World'), 'incorrect return value from doSomething')189 object = self.gbl.GlobalTemplate(self.A.B.C.MyClass,'float')()190 result = object.doSomething('Hello World')191 self.failUnless( result == len('Hello World'), 'incorrect return value from doSomething')192 del object193 self.failUnless( self.A.B.C.MyClass.instances() == 0 , 'MyClass instances not deleted')194 def test10VectorSemantics(self) :195 vi = self.std.vector('int')()196 for i in range(30) : vi.push_back(i*i)197 self.failUnless( len(vi) == vi.size() , 'invalid vector size')198 vs = vi[6:9]199 self.failUnless( vs.__class__ == vi.__class__, 'slice type is unchanged')200 self.failUnlessEqual(vs[0], 36 )201 """202 def test11ListSemantics(self) :203 li = self.std.list('int')()204 for i in range(30) : li.push_back(i*i)205 self.failUnless( len(li) == li.size() , 'invalid list size')206 self.failUnless( 25 in li )207 self.failUnlessEqual( [i for i in li], [x*x for x in range(30)])208 lo = self.std.list('A::B::C::MyClass*')()209 objs = [self.A.B.C.MyClass() for i in range(10)]210 for i in objs : lo.push_back(i)211 self.failUnlessEqual(len(lo), 10)212 for o in lo : o.setMagic(222)213 it = iter(lo)214 self.failUnlessEqual(it.next().magic(), 222)215 self.failUnlessEqual(it.next().magic(), 222)216 def test12MapSemantics(self) :217 Key = self.gbl.Key218 ma = self.std.map(Key,str)()219 self.failUnlessEqual( len(ma), 0)220 for i in range(30) : ma[Key(i)]='%d'%i221 self.failUnlessEqual( len(ma), 30)222 k1, k2 = Key(10), Key(20)223 self.failUnless( k1 in ma )224 self.failUnless( k1 in ma.keys())225 self.failUnless( k2 in ma )226 self.failUnless( k2 in ma.keys())227 for k in ma :228 self.failUnlessEqual( ma[k], '%d'%k.value())229 del ma[k1]230 del ma[k2]231 self.failUnlessEqual( len(ma), 28)232 """233 234 def test13VirtualInheritance(self) :235 d = self.A.B.C.Diamond()236 self.failUnlessEqual(d.vf(), 999.999 )237 self.failUnlessEqual(d.magic(), 987654321)238 del d239 self.failUnlessEqual(self.A.B.C.MyClass.instances(), 0)240 def test14MethodOverloading(self) :241 #int overloaded( int ) { return 1; }242 #int overloaded( float ) { return 2; }243 #int overloaded( int, float ) { return 3; }244 #int overloaded( float, int ) { return 4; }245 calling = self.A.B.C.Calling()246 self.failUnlessEqual(calling.overloaded(10), 1)247 self.failUnlessEqual(calling.overloaded(10.0), 2)248 self.failUnlessEqual(calling.overloaded(10, 10.0), 3)249 self.failUnlessEqual(calling.overloaded(10.0, 10), 4)250 251 def test15OperatorOverloading(self) :252 Number = self.A.B.C.Number;253 self.failUnlessEqual(Number(20) + Number(10), Number(30) )254 self.failUnlessEqual(Number(20) - Number(10), Number(10) )255 self.failUnlessEqual(Number(20) / Number(10), Number(2) )256 self.failUnlessEqual(Number(20) * Number(10), Number(200) )257 self.failUnlessEqual(Number(5) & Number(14), Number(4) )258 self.failUnlessEqual(Number(5) | Number(14), Number(15) )259 self.failUnlessEqual(Number(5) ^ Number(14), Number(11) )260 self.failUnlessEqual(Number(5) << 2, Number(20) )261 self.failUnlessEqual(Number(20) >> 2, Number(5) )262 n = Number(20)263 n += Number(10)264 n -= Number(10)265 n *= Number(10)266 n /= Number(2)267 self.failUnlessEqual(n ,Number(100) )268 self.failUnlessEqual(Number(20) > Number(10), 1 )269 self.failUnlessEqual(Number(20) < Number(10), 0 )270 self.failUnlessEqual(Number(20) >= Number(20), 1 )271 self.failUnlessEqual(Number(20) <= Number(10), 0 )272 self.failUnlessEqual(Number(20) != Number(10), 1 )273 self.failUnlessEqual(Number(20) == Number(10), 0 )274 275 def test16DataMembers(self) :276 dm = self.A.B.C.DataMembers()277 # testing get278 self.failUnlessEqual(dm.i, 0 )279 self.failUnlessEqual(dm.f, 0.0 )280 self.failUnlessEqual(dm.myclass.magic(), self.A.B.C.MyClass().magic() )281 # testing set282 dm.i = 8283 self.failUnlessEqual(dm.i, 8 )284 dm.f = 8.8285 self.failUnless( abs(dm.f - 8.8) < 0.00001)286 mc = self.A.B.C.MyClass()287 mc.setMagic(99999)288 dm.myclass.setMagic( 123456 )289 dm.myclass = mc290 self.failUnlessEqual(dm.myclass.magic(), 99999 )291 dm.p_myclass.setMagic(555555)292 self.failUnlessEqual(dm.p_myclass.magic(), 555555 )293 dm.d = 88.88294 self.failUnless( abs(dm.d - 88.88) < 0.00001)295 self.failUnlessEqual(dm.s, '')296 dm.s = 'small'297 self.failUnlessEqual(dm.s, 'small')298 s = 'a rather long or very long string this time instead of a using a small one that can not be stored locally'299 dm.s = s300 self.failUnlessEqual(dm.s, s)301 # testing inherited members302 xm = self.A.B.C.ExtDataMembers()303 xm.i = 5304 xm.d = 10.0305 xm.f = 5.0306 xm.xi = 55307 self.failUnlessEqual(xm.i, 5 )308 self.failUnlessEqual(xm.d, 10.0 )309 self.failUnlessEqual(xm.f, 5.0 )310 self.failUnlessEqual(xm.xi, 55 )311 del dm, mc, xm312 self.failUnless( self.A.B.C.MyClass.instances() == 0 , 'MyClass instances not deleted')313 def test17EnumConversion(self) :314 # note that setAnswer in testclasses.h has been changed const Answer& -> Answer, as315 # enums are UInt_ts and references of built-in types are not (yet) supported316 myobj = self.A.B.C.MyClass()317 myobj.setAnswer(0)318 self.failUnlessEqual(myobj.answer(), 0 )319 myobj.setAnswer(1)320 self.failUnlessEqual(myobj.answer(), 1 )321 322 def test18DefaultArguments(self) :323 m0 = self.A.B.C.DefaultArguments() # default arguments (1, 0.0)324 self.failUnlessEqual((m0.i(),m0.f()), (1,0.0))325 m1 = self.A.B.C.DefaultArguments(99)326 self.failUnlessEqual((m1.i(),m1.f()), (99,0.0))327 m2 = self.A.B.C.DefaultArguments(88,8.8)328 self.failUnlessEqual( m1.function('string'), 1004.0)329 self.failUnlessEqual( m1.function('string',10.0), 1015.0)330 self.failUnlessEqual( m1.function('string',20.0,20), 46.0)331 self.assertRaises(TypeError, m2.function, (20.0,20))332 self.assertRaises(TypeError, m2.function, ('a',20.0,20.5))333 self.assertRaises(TypeError, m2.function, ('a',20.0,20,'b'))334 def test19ObjectIdentity(self) :335 c1 = self.A.B.C.Calling()336 c2 = self.A.B.C.Calling()337 # PyROOT objects have no exposed object _theObject (b/c of performance)338 # AddressOf() yields a ptr-to-ptr ('**'), hence deref[0] gives address as long339 #self.failUnless(c1.retByPointer()._theObject == c1.retByReference()._theObject)340 #self.failUnless(c1.retByPointer()._theObject != c2.retByPointer()._theObject)341 self.failUnless(PyCintex.addressOf(c1.retByPointer()) == PyCintex.addressOf(c1.retByReference()))342 self.failUnless(PyCintex.addressOf(c1.retByPointer())!= PyCintex.addressOf(c2.retByPointer()))343 def test20AbstractInterfaces(self) :344 d = self.gbl.I_get()345 self.failUnless(d)346 self.gbl.I_set(d)347 348 def test21TemplatedWithString(self) :349 p = self.gbl.SimpleProperty('string','Verifier<string>')('hello')350 self.failUnless(p)351 del p352 353 def test22VectorPointers(self) :354 v = self.gbl.std.vector('const Pbase*')()355 self.failUnless(v)356 coll = [ self.gbl.PPbase(i) for i in range(10) ]357 for p in coll : v.push_back(p)358 self.failUnlessEqual(len(v),10)359 p = v.at(1)360 self.failUnlessEqual(p.get(),1)361 def test23ExceptionsInCPPCode(self) :362 g = self.gbl.ExceptionGenerator(False) # should not throw exception363 g.doThrow(False) # should not thoow exception364 self.assertRaises(RuntimeError, g.doThrow, True)365 self.assertRaises(RuntimeError, g.intThrow, True)366 self.assertRaises(TypeError, self.gbl.ExceptionGenerator, True)367 def test24STLArgTypes(self):368 p = self.A.B.C.Primitives()369 self.failUnless( isinstance(p, self.A.B.C.Primitives) )370 v = self.std.vector('double')()371 v.push_back(1.0)372 p.set_doubles('a', v)373 self.failUnlessEqual(p.doubles().size(), 1 )374 self.failUnlessEqual(p.doubles()[0], 1.0 )375 def test25STLIterator(self):376 vector = PyCintex.makeClass('std::vector<MyA>')377 self.failUnless( vector )378 self.failUnless( PyCintex.makeClass('std::vector<MyA>::iterator') )379 self.failUnless( PyCintex.makeClass('std::vector<MyA>::reverse_iterator') )380 381 def test26TypedefRet(self):382 self.failUnlessEqual( self.gbl.MyNS.theFunction(), 1)383 self.failUnlessEqual( self.gbl.theFunction(), 1 ) 384 385 def test27Enums(self):386 self.failUnlessEqual( self.gbl.one, 1)387 self.failUnlessEqual( self.gbl.MyNS.one, 1)388 self.failUnlessEqual( self.gbl.MyClass1.one, 1)389 self.failUnlessEqual( self.gbl.MyClass2.one, 1)390 self.failUnlessEqual( self.gbl.MyClass3.one, 1)391 self.failUnlessEqual( self.gbl.MyClass4.one, 1)392 self.failUnless('unknown' not in str(self.gbl.MyClass1()) )393 self.failUnless('unknown' not in str(self.gbl.MyClass2()) )394 self.failUnless('unknown' not in str(self.gbl.MyClass3()) )395 self.failUnless('unknown' not in str(self.gbl.MyClass4()) )396 def test28PrimitiveArgumentsByReference(self):397 c = PyCintex.libPyROOT.Double(10.0+0.0)398 d = PyCintex.libPyROOT.Double(c)399 calling = self.A.B.C.Calling()400 self.failUnlessEqual( calling.GetByPrimitiveReference(c), 10.0 )401 self.failUnlessEqual( c, 999.99 )402 403 def test29MarcoClemencic(self) :404 a = self.gbl.MarcoCl.MyClass()405 i = 0406 self.failUnlessEqual( a.echo("hi there!"), 1)407 self.failUnlessEqual( a.echo(i), 2)408 def test30VectorArguments(self) :409 calling = self.A.B.C.Calling()410 self.gbl.gEnv.SetValue("Root.ErrorIgnoreLevel", "Error")411 self.failUnlessEqual(calling.vectorargument(self.std.vector('double')(3)), 3)412 self.failUnlessEqual(calling.vectorargument(self.std.vector('unsigned long')(4)), 4)413 self.failUnlessEqual(calling.vectorargument(self.std.vector('string')(2)), 2)414 #self.gbl.gEnv.SetValue("Root.ErrorIgnoreLevel", "Warning")415 416 def test31VectorPrimitiveElementAsignments(self) :417 # Not working for 'char', 'short', 'unsigned long',...418 for p in (('int',0, 66) , ('long',0, 77), 419 ('float', 0., 22.0), ('double', 0., 33.3) ) :420 v = self.std.vector(p[0])(3)421 self.failUnlessEqual(v[2], p[1])422 v[2] = p[2]423 self.failUnlessEqual(v[2], p[2])424 def test32CannotfindShowMembers(self) :425 obj = self.gbl.TrackingRecHit()426 self.failUnless(self)427 self.failUnless(hasattr(obj,'ShowMembers'))428suite = unittest.makeSuite(BasicsTestCase,'test')429if __name__ == '__main__':430 ret = unittest.TextTestRunner( sys.stdout, verbosity = 2 ).run(suite)431 raise SystemExit, not ret.wasSuccessful()432 433 ...
TCPSoftAPSTASendRecv.py
Source:TCPSoftAPSTASendRecv.py
1from TCAction import TCActionBase2from NativeLog import NativeLog3import time4import random5import string6TEST_COUNT_ONE_ROUND = 5007class TestCase(TCActionBase.CommonTCActionBase):8 def __init__(self, test_case, test_env, timeout=45, log_path=TCActionBase.LOG_PATH):9 TCActionBase.CommonTCActionBase.__init__(self, test_case, test_env,10 timeout=timeout, log_path=log_path)11 self.send_len = 146012 self.server_port = random.randint(10000, 50000)13 self.server_port_2 = random.randint(10000, 50000)14 self.server_echo = True15 self.test_time = 12 * 6016 self.sta_number = 317 self.send_delay = 5018 # load param from excel19 cmd_set = test_case["cmd set"]20 for i in range(1, len(cmd_set)):21 if cmd_set[i][0] != "dummy":22 cmd_string = "self." + cmd_set[i][0]23 exec cmd_string24 self.result_cntx = TCActionBase.ResultCheckContext(self, test_env, self.tc_name)25 pass26 def cleanup(self):27 checker_stings = []28 test_action_strings = []29 for i in range(self.sta_number + 2):30 checker_stings.append("R SSC%s C +RECVPRINT:1" % (i+1))31 test_action_strings.append("SSC SSC%s soc -R -o 1" % (i+1))32 fail_string = "Fail, Fail to turn on recv print"33 self.load_and_exe_one_step(checker_stings, test_action_strings, fail_string)34 pass35 def execute(self):36 TCActionBase.TCActionBase.execute(self)37 self.result_cntx.start()38 try:39 # configurable params40 send_len = self.send_len41 test_time = self.test_time * 6042 # server port43 server_port = self.server_port44 server_port_t = self.server_port_245 # ap ip46 # ap_ip = self.ap_ip47 # server echo48 server_echo = self.server_echo49 # station number50 sta_number = self.sta_number51 # send delay52 send_delay = self.send_delay53 # configurable params54 except StandardError, e:55 NativeLog.add_trace_critical("Error configuration for TCPTransparent script, error is %s" % e)56 raise StandardError("Error configuration")57 # step0 reboot58 checker_stings = []59 test_action_string = []60 for i in range(sta_number + 2):61 checker_stings.append("P SSC%d C !!!ready!!!" % (i + 1))62 test_action_string.append("SSCC SSC%d reboot" % (i + 1))63 fail_string = "Fail, Fail to reboot"64 if self.load_and_exe_one_step(checker_stings, test_action_string, fail_string) is False:65 return66 # switch off recv print67 checker_stings = []68 test_action_strings = []69 for i in range(self.sta_number + 2):70 checker_stings.append("R SSC%s C +RECVPRINT:0" % (i+1))71 test_action_strings.append("SSC SSC%s soc -R -o 0" % (i+1))72 fail_string = "Fail, Fail to turn off recv print"73 self.load_and_exe_one_step(checker_stings, test_action_strings, fail_string)74 # step1, set ap/STA mode on all target75 for i in range(sta_number + 2):76 checker_stings = ["R SSC%d C +MODE:OK" % (i + 1)]77 test_action_string = ["SSCC SSC%d op -S -o 3" % (i + 1)]78 fail_string = "Fail, Fail to set mode on SSC%d" % (i + 1)79 if self.load_and_exe_one_step(checker_stings, test_action_string, fail_string) is False:80 return81 # set different getway for SSC1 softAP82 checker_stings = ["R SSC1 C +DHCP:AP,OK"]83 test_action_string = ["SSCC SSC1 dhcp -E -o 2"]84 fail_string = "Fail, SSC1 Fail to disable DHCP"85 if self.load_and_exe_one_step(checker_stings, test_action_string, fail_string) is False:86 return87 checker_stings = ["R SSC1 C +IP:OK"]88 test_action_string = ["SSCC SSC1 ip -S -o 2 -i 192.168.6.1"]89 fail_string = "Fail, SSC1 Fail to set IP"90 if self.load_and_exe_one_step(checker_stings, test_action_string, fail_string) is False:91 return92 checker_stings = ["R SSC1 C +DHCP:AP,OK"]93 test_action_string = ["SSCC SSC1 dhcp -S -o 2"]94 fail_string = "Fail, SSC1 Fail to enable DHCP"95 if self.load_and_exe_one_step(checker_stings, test_action_string, fail_string) is False:96 return97 # set different getway for SSC2 softAP98 checker_stings = ["R SSC2 C +DHCP:AP,OK"]99 test_action_string = ["SSCC SSC2 dhcp -E -o 2"]100 fail_string = "Fail, SSC2 Fail to disable DHCP"101 if self.load_and_exe_one_step(checker_stings, test_action_string, fail_string) is False:102 return103 checker_stings = ["R SSC2 C +IP:OK"]104 test_action_string = ["SSCC SSC2 ip -S -o 2 -i 192.168.5.1"]105 fail_string = "Fail, SSC2 Fail to set IP"106 if self.load_and_exe_one_step(checker_stings, test_action_string, fail_string) is False:107 return108 checker_stings = ["R SSC2 C +DHCP:AP,OK"]109 test_action_string = ["SSCC SSC2 dhcp -S -o 2"]110 fail_string = "Fail, SSC2 Fail to enable DHCP"111 if self.load_and_exe_one_step(checker_stings, test_action_string, fail_string) is False:112 return113 # step2, set ssid/password on SSC1114 ssid = "".join([random.choice(string.lowercase) for m in range(10)])115 password = "".join([random.choice(string.lowercase) for m in range(10)])116 checker_stings = ["R SSC1 C +SAP:OK"]117 test_action_string = ["SSCC SSC1 ap -S -s %s -p %s -n 10 -t 0 -m 8" % (ssid, password)]118 fail_string = "Fail, Fail to set ssid/password on SSC1"119 if self.load_and_exe_one_step(checker_stings, test_action_string, fail_string) is False:120 return121 # step3, set ssid/password on SSC2122 ssid_1 = "".join([random.choice(string.lowercase) for m in range(10)])123 password_1 = "".join([random.choice(string.lowercase) for m in range(10)])124 checker_stings = ["R SSC2 C +SAP:OK"]125 test_action_string = ["SSCC SSC2 ap -S -s %s -p %s -n 10 -t 0 -m 8" % (ssid_1, password_1)]126 fail_string = "Fail, Fail to set ap ssid/password on SSC2"127 if self.load_and_exe_one_step(checker_stings, test_action_string, fail_string) is False:128 return129 # step4, SSC2 join SSC1(soft AP)130 checker_stings = []131 test_action_string = []132 checker_stings.append("P SSC2 C +JAP:CONNECTED,%s" % ssid)133 test_action_string.append("SSCC SSC2 ap -C -s %s -p %s" % (ssid, password))134 fail_string = "Fail, Fail to connect to SSC1 SoftAP"135 if self.load_and_exe_one_step(checker_stings, test_action_string, fail_string) is False:136 return137 # step5, create server on SSC1138 checker_stings = ["R SSC1 A <server_sock>:BIND:(\d+),OK"]139 test_action_string = ["SSCC SSC1 soc -B -t TCP -p %s" % server_port]140 fail_string = "Fail, Fail to create server on SSC1 while binding"141 if self.load_and_exe_one_step(checker_stings, test_action_string, fail_string) is False:142 return143 checker_stings = ["R SSC1 RE LISTEN:(\d+),OK"]144 test_action_string = ["SSCC SSC1 soc -L -s <server_sock>"]145 fail_string = "Fail, Fail to create server on SSC1 while listening"146 if self.load_and_exe_one_step(checker_stings, test_action_string, fail_string) is False:147 return148 # step6, create client on SSC2149 checker_stings = []150 test_action_string = []151 checker_stings.append("P SSC2 A <client_sock>:BIND:(\d+),OK")152 test_action_string.append("SSCC SSC2 soc -B -t TCP")153 fail_string = "Fail, SSC2 Fail to connect to server while binding"154 if self.load_and_exe_one_step(checker_stings, test_action_string, fail_string) is False:155 return156 checker_stings = ["P SSC2 RE CONNECT:(\d+),OK", "P SSC1 A <accept_sock>:ACCEPT:(\d+),.+"]157 test_action_string = ["SSCC SSC2 soc -C -s <client_sock> -i %s -p %s" % ("192.168.6.1", server_port)]158 fail_string = "Fail, SSC2 Fail to connect to server while connecting"159 if self.load_and_exe_one_step(checker_stings, test_action_string, fail_string) is False:160 return161 # step7, SSC3 - SSC5 join SSC2162 checker_stings = []163 test_action_string = []164 for i in range(sta_number):165 checker_stings.append("P SSC%d C +JAP:CONNECTED,%s" % (i + 3, ssid_1))166 test_action_string.append("SSCC SSC%d ap -C -s %s -p %s" % (i + 3, ssid_1, password_1))167 fail_string = "Fail, SSC%d Fail to connect to SSC2" % (i + 3)168 if self.load_and_exe_one_step(checker_stings, test_action_string, fail_string, check_time=450) is False:169 return170 # step8, create server on SSC2171 checker_stings = ["R SSC2 A <server_sock_t>:BIND:(\d+),OK"]172 test_action_string = ["SSCC SSC2 soc -B -t TCP -p %s -i 192.168.5.1" % server_port_t]173 fail_string = "Fail, Fail to create server one SSC2 while binding"174 if self.load_and_exe_one_step(checker_stings, test_action_string, fail_string) is False:175 return176 checker_stings = ["R SSC2 RE LISTEN:(\d+),OK"]177 test_action_string = ["SSCC SSC2 soc -L -s <server_sock_t>"]178 fail_string = "Fail, Fail to create server one SSC2 while listening"179 if self.load_and_exe_one_step(checker_stings, test_action_string, fail_string) is False:180 return181 # step9, create client on SSC3 - SSC5182 checker_stings = []183 test_action_string = []184 for i in range(sta_number):185 checker_stings.append("P SSC%d A <client_sock%d>:BIND:(\d+),OK" % (i + 3, i + 3))186 test_action_string.append("SSCC SSC%d soc -B -t TCP" % (i + 3))187 fail_string = "Fail, Fail to connect to SSC2 server while binding"188 if self.load_and_exe_one_step(checker_stings, test_action_string, fail_string) is False:189 return190 for i in range(sta_number):191 checker_stings = ["P SSC%d RE CONNECT:(\d+),OK" % (i + 3),192 "P SSC2 A <accept_sock%d>:ACCEPT:(\d+),.+" % (i + 3)]193 test_action_string = ["SSCC SSC%d soc -C -s <client_sock%d> -i %s -p %s" %194 (i + 3, i + 3, "192.168.5.1", server_port_t)]195 fail_string = "Fail, Fail to connect to SSC2 server while connecting"196 if self.load_and_exe_one_step(checker_stings, test_action_string, fail_string) is False:197 return198 start_time = time.time()199 # step 10, do send/recv200 while time.time() - start_time < test_time:201 checker_stings = []202 test_action_string = []203 if server_echo is True:204 test_action_string.append("SSC SSC1 soc -S -s <accept_sock> -l %d -n %d -j %d" %205 (send_len, TEST_COUNT_ONE_ROUND, send_delay))206 checker_stings.append("P SSC1 RE \+SEND:\d+,OK NC CLOSED")207 test_action_string.append("SSC SSC2 soc -S -s <server_sock> -l %d -n %d -j %d" %208 (send_len, TEST_COUNT_ONE_ROUND, send_delay))209 checker_stings.append("P SSC2 RE \+SEND:\d+,OK NC CLOSED")210 for i in range(sta_number):211 checker_stings.append("P SSC%d RE \+SEND:\d+,OK NC CLOSED" % (i + 3))212 test_action_string.append("SSC SSC%d soc -S -s <client_sock%d> -l %d -n %d -j %d" %213 (i + 3, i + 3, send_len, TEST_COUNT_ONE_ROUND, send_delay))214 for i in range(sta_number):215 test_action_string.append("SSC SSC2 soc -S -s <accept_sock%d> -l %d -n %d -j %d" %216 (i + 3, send_len, TEST_COUNT_ONE_ROUND, send_delay))217 checker_stings.append("P SSC2 RE \+SEND:\d+,OK NC CLOSED")218 fail_string = "Fail, Failed to send/recv data"219 if self.load_and_exe_one_step(checker_stings, test_action_string, fail_string,220 check_freq=1, check_time=300) is False:221 break222 pass223 NativeLog.add_prompt_trace("time escape: %s" % (time.time() - start_time))224 if (time.time() - start_time) > test_time:225 self.result_cntx.set_result("Succeed")226 else:227 self.result_cntx.set_result("Failed")228 checker_stings = []229 test_action_string = []230 for i in range(sta_number + 2):231 checker_stings.append("P SSC%d C CLOSEALL" % (i + 1))232 test_action_string.append("SSCC SSC%d soc -T" % (i + 1))233 fail_string = "Fail, Fail to close socket"234 if self.load_and_exe_one_step(checker_stings, test_action_string, fail_string) is False:235 return236 # re-set server on SSC1237 server_port = random.randint(20000, 30000)238 checker_stings = ["R SSC1 A <server_sock>:BIND:(\d+),OK"]239 test_action_string = ["SSCC SSC1 soc -B -t TCP -p %s" % server_port]240 fail_string = "Fail, Fail to bind socket"241 if self.load_and_exe_one_step(checker_stings, test_action_string, fail_string) is False:242 return243 checker_stings = ["R SSC1 RE LISTEN:(\d+),OK"]244 test_action_string = ["SSCC SSC1 soc -L -s <server_sock>"]245 fail_string = "Fail, Fail to listen"246 if self.load_and_exe_one_step(checker_stings, test_action_string, fail_string) is False:247 return248 # SSC2 connnect SSC1249 checker_stings = []250 test_action_string = []251 checker_stings.append("P SSC2 A <client_sock>:BIND:(\d+),OK")252 test_action_string.append("SSCC SSC2 soc -B -t TCP")253 fail_string = "Fail, SSC2 Fail to bind sock"254 if self.load_and_exe_one_step(checker_stings, test_action_string, fail_string) is False:255 return256 checker_stings = ["P SSC2 RE CONNECT:(\d+),OK", "P SSC1 A <accept_sock>:ACCEPT:(\d+),.+"]257 test_action_string = ["SSCC SSC2 soc -C -s <client_sock> -i %s -p %s" % ("192.168.6.1", server_port)]258 fail_string = "Fail, SSC2 Fail to connect to SSC1 server"259 if self.load_and_exe_one_step(checker_stings, test_action_string, fail_string) is False:260 return261 # create server on SSC2262 checker_stings = []263 test_action_string = []264 checker_stings.append("P SSC2 A <server_sock>:BIND:(\d+),OK")265 test_action_string.append("SSCC SSC2 soc -B -t TCP -p %s -i 192.168.5.1" % server_port_t)266 fail_string = "Fail, SSC2 Fail to bind"267 if self.load_and_exe_one_step(checker_stings, test_action_string, fail_string) is False:268 return269 checker_stings = ["R SSC2 RE LISTEN:(\d+),OK"]270 test_action_string = ["SSCC SSC2 soc -L -s <server_sock>"]271 fail_string = "Fail, SSC2 Fail to listen"272 if self.load_and_exe_one_step(checker_stings, test_action_string, fail_string) is False:273 return274 # create client on SSC3-SSC5275 checker_stings = []276 test_action_string = []277 for i in range(sta_number):278 checker_stings.append("P SSC%d A <client_sock%d>:BIND:(\d+),OK" % (i + 3, i + 3))279 test_action_string.append("SSCC SSC%d soc -B -t TCP" % (i + 3))280 fail_string = "Fail, Fail to connect to SSC2 server while binding"281 if self.load_and_exe_one_step(checker_stings, test_action_string, fail_string) is False:282 return283 for i in range(sta_number):284 checker_stings = ["P SSC%d RE CONNECT:(\d+),OK" % (i + 3),285 "P SSC2 A <accept_sock%d>:ACCEPT:(\d+),.+" % (i + 3)]286 test_action_string = ["SSCC SSC%d soc -C -s <client_sock%d> -i %s -p %s" %287 (i + 3, i + 3, "192.168.5.1", server_port_t)]288 fail_string = "Fail, Fail to connect to server"289 if self.load_and_exe_one_step(checker_stings, test_action_string, fail_string) is False:290 return291 def result_check(self, port_name, data):292 TCActionBase.CommonTCActionBase.result_check(self, port_name, data)293 self.result_cntx.append_data(port_name, data)294def main():295 pass296if __name__ == '__main__':...
test_structures.py
Source:test_structures.py
...310 except AttributeError, details:311 self.failUnless("Structure or union cannot contain itself" in312 str(details))313 else:314 self.fail("Structure or union cannot contain itself")315 def test_vice_versa(self):316 class First(Structure):317 pass318 class Second(Structure):319 pass320 First._fields_ = [("second", Second)]321 try:322 Second._fields_ = [("first", First)]323 except AttributeError, details:324 self.failUnless("_fields_ is final" in325 str(details))326 else:327 self.fail("AttributeError not raised")328if __name__ == '__main__':...
test_byteswap.py
Source:test_byteswap.py
1import sys, unittest, struct, math2from binascii import hexlify3from ctypes import *4def bin(s):5 return hexlify(buffer(s)).upper()6# Each *simple* type that supports different byte orders has an7# __ctype_be__ attribute that specifies the same type in BIG ENDIAN8# byte order, and a __ctype_le__ attribute that is the same type in9# LITTLE ENDIAN byte order.10#11# For Structures and Unions, these types are created on demand.12class Test(unittest.TestCase):13 def X_test(self):14 print >> sys.stderr, sys.byteorder15 for i in range(32):16 bits = BITS()17 setattr(bits, "i%s" % i, 1)18 dump(bits)19 def test_endian_short(self):20 if sys.byteorder == "little":21 self.failUnless(c_short.__ctype_le__ is c_short)22 self.failUnless(c_short.__ctype_be__.__ctype_le__ is c_short)23 else:24 self.failUnless(c_short.__ctype_be__ is c_short)25 self.failUnless(c_short.__ctype_le__.__ctype_be__ is c_short)26 s = c_short.__ctype_be__(0x1234)27 self.failUnlessEqual(bin(struct.pack(">h", 0x1234)), "1234")28 self.failUnlessEqual(bin(s), "1234")29 self.failUnlessEqual(s.value, 0x1234)30 s = c_short.__ctype_le__(0x1234)31 self.failUnlessEqual(bin(struct.pack("<h", 0x1234)), "3412")32 self.failUnlessEqual(bin(s), "3412")33 self.failUnlessEqual(s.value, 0x1234)34 s = c_ushort.__ctype_be__(0x1234)35 self.failUnlessEqual(bin(struct.pack(">h", 0x1234)), "1234")36 self.failUnlessEqual(bin(s), "1234")37 self.failUnlessEqual(s.value, 0x1234)38 s = c_ushort.__ctype_le__(0x1234)39 self.failUnlessEqual(bin(struct.pack("<h", 0x1234)), "3412")40 self.failUnlessEqual(bin(s), "3412")41 self.failUnlessEqual(s.value, 0x1234)42 def test_endian_int(self):43 if sys.byteorder == "little":44 self.failUnless(c_int.__ctype_le__ is c_int)45 self.failUnless(c_int.__ctype_be__.__ctype_le__ is c_int)46 else:47 self.failUnless(c_int.__ctype_be__ is c_int)48 self.failUnless(c_int.__ctype_le__.__ctype_be__ is c_int)49 s = c_int.__ctype_be__(0x12345678)50 self.failUnlessEqual(bin(struct.pack(">i", 0x12345678)), "12345678")51 self.failUnlessEqual(bin(s), "12345678")52 self.failUnlessEqual(s.value, 0x12345678)53 s = c_int.__ctype_le__(0x12345678)54 self.failUnlessEqual(bin(struct.pack("<i", 0x12345678)), "78563412")55 self.failUnlessEqual(bin(s), "78563412")56 self.failUnlessEqual(s.value, 0x12345678)57 s = c_uint.__ctype_be__(0x12345678)58 self.failUnlessEqual(bin(struct.pack(">I", 0x12345678)), "12345678")59 self.failUnlessEqual(bin(s), "12345678")60 self.failUnlessEqual(s.value, 0x12345678)61 s = c_uint.__ctype_le__(0x12345678)62 self.failUnlessEqual(bin(struct.pack("<I", 0x12345678)), "78563412")63 self.failUnlessEqual(bin(s), "78563412")64 self.failUnlessEqual(s.value, 0x12345678)65 def test_endian_longlong(self):66 if sys.byteorder == "little":67 self.failUnless(c_longlong.__ctype_le__ is c_longlong)68 self.failUnless(c_longlong.__ctype_be__.__ctype_le__ is c_longlong)69 else:70 self.failUnless(c_longlong.__ctype_be__ is c_longlong)71 self.failUnless(c_longlong.__ctype_le__.__ctype_be__ is c_longlong)72 s = c_longlong.__ctype_be__(0x1234567890ABCDEF)73 self.failUnlessEqual(bin(struct.pack(">q", 0x1234567890ABCDEF)), "1234567890ABCDEF")74 self.failUnlessEqual(bin(s), "1234567890ABCDEF")75 self.failUnlessEqual(s.value, 0x1234567890ABCDEF)76 s = c_longlong.__ctype_le__(0x1234567890ABCDEF)77 self.failUnlessEqual(bin(struct.pack("<q", 0x1234567890ABCDEF)), "EFCDAB9078563412")78 self.failUnlessEqual(bin(s), "EFCDAB9078563412")79 self.failUnlessEqual(s.value, 0x1234567890ABCDEF)80 s = c_ulonglong.__ctype_be__(0x1234567890ABCDEF)81 self.failUnlessEqual(bin(struct.pack(">Q", 0x1234567890ABCDEF)), "1234567890ABCDEF")82 self.failUnlessEqual(bin(s), "1234567890ABCDEF")83 self.failUnlessEqual(s.value, 0x1234567890ABCDEF)84 s = c_ulonglong.__ctype_le__(0x1234567890ABCDEF)85 self.failUnlessEqual(bin(struct.pack("<Q", 0x1234567890ABCDEF)), "EFCDAB9078563412")86 self.failUnlessEqual(bin(s), "EFCDAB9078563412")87 self.failUnlessEqual(s.value, 0x1234567890ABCDEF)88 def test_endian_float(self):89 if sys.byteorder == "little":90 self.failUnless(c_float.__ctype_le__ is c_float)91 self.failUnless(c_float.__ctype_be__.__ctype_le__ is c_float)92 else:93 self.failUnless(c_float.__ctype_be__ is c_float)94 self.failUnless(c_float.__ctype_le__.__ctype_be__ is c_float)95 s = c_float(math.pi)96 self.failUnlessEqual(bin(struct.pack("f", math.pi)), bin(s))97 # Hm, what's the precision of a float compared to a double?98 self.failUnlessAlmostEqual(s.value, math.pi, 6)99 s = c_float.__ctype_le__(math.pi)100 self.failUnlessAlmostEqual(s.value, math.pi, 6)101 self.failUnlessEqual(bin(struct.pack("<f", math.pi)), bin(s))102 s = c_float.__ctype_be__(math.pi)103 self.failUnlessAlmostEqual(s.value, math.pi, 6)104 self.failUnlessEqual(bin(struct.pack(">f", math.pi)), bin(s))105 def test_endian_double(self):106 if sys.byteorder == "little":107 self.failUnless(c_double.__ctype_le__ is c_double)108 self.failUnless(c_double.__ctype_be__.__ctype_le__ is c_double)109 else:110 self.failUnless(c_double.__ctype_be__ is c_double)111 self.failUnless(c_double.__ctype_le__.__ctype_be__ is c_double)112 s = c_double(math.pi)113 self.failUnlessEqual(s.value, math.pi)114 self.failUnlessEqual(bin(struct.pack("d", math.pi)), bin(s))115 s = c_double.__ctype_le__(math.pi)116 self.failUnlessEqual(s.value, math.pi)117 self.failUnlessEqual(bin(struct.pack("<d", math.pi)), bin(s))118 s = c_double.__ctype_be__(math.pi)119 self.failUnlessEqual(s.value, math.pi)120 self.failUnlessEqual(bin(struct.pack(">d", math.pi)), bin(s))121 def test_endian_other(self):122 self.failUnless(c_byte.__ctype_le__ is c_byte)123 self.failUnless(c_byte.__ctype_be__ is c_byte)124 self.failUnless(c_ubyte.__ctype_le__ is c_ubyte)125 self.failUnless(c_ubyte.__ctype_be__ is c_ubyte)126 self.failUnless(c_char.__ctype_le__ is c_char)127 self.failUnless(c_char.__ctype_be__ is c_char)128 def test_struct_fields_1(self):129 if sys.byteorder == "little":130 base = BigEndianStructure131 else:132 base = LittleEndianStructure133 class T(base):134 pass135 _fields_ = [("a", c_ubyte),136 ("b", c_byte),137 ("c", c_short),138 ("d", c_ushort),139 ("e", c_int),140 ("f", c_uint),141 ("g", c_long),142 ("h", c_ulong),143 ("i", c_longlong),144 ("k", c_ulonglong),145 ("l", c_float),146 ("m", c_double),147 ("n", c_char),148 ("b1", c_byte, 3),149 ("b2", c_byte, 3),150 ("b3", c_byte, 2),151 ("a", c_int * 3 * 3 * 3)]152 T._fields_ = _fields_153 # these fields do not support different byte order:154 for typ in c_wchar, c_void_p, POINTER(c_int):155 _fields_.append(("x", typ))156 class T(base):157 pass158 self.assertRaises(TypeError, setattr, T, "_fields_", [("x", typ)])159 def test_struct_struct(self):160 # Nested structures with different byte order not (yet) supported161 if sys.byteorder == "little":162 base = BigEndianStructure163 else:164 base = LittleEndianStructure165 class T(Structure):166 _fields_ = [("a", c_int),167 ("b", c_int)]168 class S(base):169 pass170 self.assertRaises(TypeError, setattr, S, "_fields_", [("s", T)])171 def test_struct_fields_2(self):172 # standard packing in struct uses no alignment.173 # So, we have to align using pad bytes.174 #175 # Unaligned accesses will crash Python (on those platforms that176 # don't allow it, like sparc solaris).177 if sys.byteorder == "little":178 base = BigEndianStructure179 fmt = ">bxhid"180 else:181 base = LittleEndianStructure182 fmt = "<bxhid"183 class S(base):184 _fields_ = [("b", c_byte),185 ("h", c_short),186 ("i", c_int),187 ("d", c_double)]188 s1 = S(0x12, 0x1234, 0x12345678, 3.14)189 s2 = struct.pack(fmt, 0x12, 0x1234, 0x12345678, 3.14)190 self.failUnlessEqual(bin(s1), bin(s2))191 def test_unaligned_nonnative_struct_fields(self):192 if sys.byteorder == "little":193 base = BigEndianStructure194 fmt = ">b h xi xd"195 else:196 base = LittleEndianStructure197 fmt = "<b h xi xd"198 class S(base):199 _pack_ = 1200 _fields_ = [("b", c_byte),201 ("h", c_short),202 ("_1", c_byte),203 ("i", c_int),204 ("_2", c_byte),205 ("d", c_double)]206 s1 = S()207 s1.b = 0x12208 s1.h = 0x1234209 s1.i = 0x12345678210 s1.d = 3.14211 s2 = struct.pack(fmt, 0x12, 0x1234, 0x12345678, 3.14)212 self.failUnlessEqual(bin(s1), bin(s2))213 def test_unaligned_native_struct_fields(self):214 if sys.byteorder == "little":215 fmt = "<b h xi xd"216 else:217 base = LittleEndianStructure218 fmt = ">b h xi xd"219 class S(Structure):220 _pack_ = 1221 _fields_ = [("b", c_byte),222 ("h", c_short),223 ("_1", c_byte),224 ("i", c_int),225 ("_2", c_byte),226 ("d", c_double)]227 s1 = S()228 s1.b = 0x12229 s1.h = 0x1234230 s1.i = 0x12345678231 s1.d = 3.14232 s2 = struct.pack(fmt, 0x12, 0x1234, 0x12345678, 3.14)233 self.failUnlessEqual(bin(s1), bin(s2))234if __name__ == "__main__":...
test_getargs2.py
Source:test_getargs2.py
1import unittest2from test import test_support3import sys4import warnings, re5warnings.filterwarnings("ignore",6 category=DeprecationWarning,7 message=".*integer argument expected, got float",8 module=__name__)9warnings.filterwarnings("ignore",10 category=DeprecationWarning,11 message=".*integer argument expected, got float",12 module="unittest")13"""14> How about the following counterproposal. This also changes some of15> the other format codes to be a little more regular.16>17> Code C type Range check18>19> b unsigned char 0..UCHAR_MAX20> h signed short SHRT_MIN..SHRT_MAX21> B unsigned char none **22> H unsigned short none **23> k * unsigned long none24> I * unsigned int 0..UINT_MAX25> i int INT_MIN..INT_MAX26> l long LONG_MIN..LONG_MAX27> K * unsigned long long none28> L long long LLONG_MIN..LLONG_MAX29> Notes:30>31> * New format codes.32>33> ** Changed from previous "range-and-a-half" to "none"; the34> range-and-a-half checking wasn't particularly useful.35Plus a C API or two, e.g. PyInt_AsLongMask() ->36unsigned long and PyInt_AsLongLongMask() -> unsigned37long long (if that exists).38"""39LARGE = 0x7FFFFFFF40VERY_LARGE = 0xFF0000121212121212121242L41from _testcapi import UCHAR_MAX, USHRT_MAX, UINT_MAX, ULONG_MAX, INT_MAX, \42 INT_MIN, LONG_MIN, LONG_MAX, PY_SSIZE_T_MIN, PY_SSIZE_T_MAX43# fake, they are not defined in Python's header files44LLONG_MAX = 2**63-145LLONG_MIN = -2**6346ULLONG_MAX = 2**64-147class Long:48 def __int__(self):49 return 99L50class Int:51 def __int__(self):52 return 9953class Unsigned_TestCase(unittest.TestCase):54 def test_b(self):55 from _testcapi import getargs_b56 # b returns 'unsigned char', and does range checking (0 ... UCHAR_MAX)57 self.failUnlessEqual(3, getargs_b(3.14))58 self.failUnlessEqual(99, getargs_b(Long()))59 self.failUnlessEqual(99, getargs_b(Int()))60 self.assertRaises(OverflowError, getargs_b, -1)61 self.failUnlessEqual(0, getargs_b(0))62 self.failUnlessEqual(UCHAR_MAX, getargs_b(UCHAR_MAX))63 self.assertRaises(OverflowError, getargs_b, UCHAR_MAX + 1)64 self.failUnlessEqual(42, getargs_b(42))65 self.failUnlessEqual(42, getargs_b(42L))66 self.assertRaises(OverflowError, getargs_b, VERY_LARGE)67 def test_B(self):68 from _testcapi import getargs_B69 # B returns 'unsigned char', no range checking70 self.failUnlessEqual(3, getargs_B(3.14))71 self.failUnlessEqual(99, getargs_B(Long()))72 self.failUnlessEqual(99, getargs_B(Int()))73 self.failUnlessEqual(UCHAR_MAX, getargs_B(-1))74 self.failUnlessEqual(UCHAR_MAX, getargs_B(-1L))75 self.failUnlessEqual(0, getargs_B(0))76 self.failUnlessEqual(UCHAR_MAX, getargs_B(UCHAR_MAX))77 self.failUnlessEqual(0, getargs_B(UCHAR_MAX+1))78 self.failUnlessEqual(42, getargs_B(42))79 self.failUnlessEqual(42, getargs_B(42L))80 self.failUnlessEqual(UCHAR_MAX & VERY_LARGE, getargs_B(VERY_LARGE))81 def test_H(self):82 from _testcapi import getargs_H83 # H returns 'unsigned short', no range checking84 self.failUnlessEqual(3, getargs_H(3.14))85 self.failUnlessEqual(99, getargs_H(Long()))86 self.failUnlessEqual(99, getargs_H(Int()))87 self.failUnlessEqual(USHRT_MAX, getargs_H(-1))88 self.failUnlessEqual(0, getargs_H(0))89 self.failUnlessEqual(USHRT_MAX, getargs_H(USHRT_MAX))90 self.failUnlessEqual(0, getargs_H(USHRT_MAX+1))91 self.failUnlessEqual(42, getargs_H(42))92 self.failUnlessEqual(42, getargs_H(42L))93 self.failUnlessEqual(VERY_LARGE & USHRT_MAX, getargs_H(VERY_LARGE))94 def test_I(self):95 from _testcapi import getargs_I96 # I returns 'unsigned int', no range checking97 self.failUnlessEqual(3, getargs_I(3.14))98 self.failUnlessEqual(99, getargs_I(Long()))99 self.failUnlessEqual(99, getargs_I(Int()))100 self.failUnlessEqual(UINT_MAX, getargs_I(-1))101 self.failUnlessEqual(0, getargs_I(0))102 self.failUnlessEqual(UINT_MAX, getargs_I(UINT_MAX))103 self.failUnlessEqual(0, getargs_I(UINT_MAX+1))104 self.failUnlessEqual(42, getargs_I(42))105 self.failUnlessEqual(42, getargs_I(42L))106 self.failUnlessEqual(VERY_LARGE & UINT_MAX, getargs_I(VERY_LARGE))107 def test_k(self):108 from _testcapi import getargs_k109 # k returns 'unsigned long', no range checking110 # it does not accept float, or instances with __int__111 self.assertRaises(TypeError, getargs_k, 3.14)112 self.assertRaises(TypeError, getargs_k, Long())113 self.assertRaises(TypeError, getargs_k, Int())114 self.failUnlessEqual(ULONG_MAX, getargs_k(-1))115 self.failUnlessEqual(0, getargs_k(0))116 self.failUnlessEqual(ULONG_MAX, getargs_k(ULONG_MAX))117 self.failUnlessEqual(0, getargs_k(ULONG_MAX+1))118 self.failUnlessEqual(42, getargs_k(42))119 self.failUnlessEqual(42, getargs_k(42L))120 self.failUnlessEqual(VERY_LARGE & ULONG_MAX, getargs_k(VERY_LARGE))121class Signed_TestCase(unittest.TestCase):122 def test_i(self):123 from _testcapi import getargs_i124 # i returns 'int', and does range checking (INT_MIN ... INT_MAX)125 self.failUnlessEqual(3, getargs_i(3.14))126 self.failUnlessEqual(99, getargs_i(Long()))127 self.failUnlessEqual(99, getargs_i(Int()))128 self.assertRaises(OverflowError, getargs_i, INT_MIN-1)129 self.failUnlessEqual(INT_MIN, getargs_i(INT_MIN))130 self.failUnlessEqual(INT_MAX, getargs_i(INT_MAX))131 self.assertRaises(OverflowError, getargs_i, INT_MAX+1)132 self.failUnlessEqual(42, getargs_i(42))133 self.failUnlessEqual(42, getargs_i(42L))134 self.assertRaises(OverflowError, getargs_i, VERY_LARGE)135 def test_l(self):136 from _testcapi import getargs_l137 # l returns 'long', and does range checking (LONG_MIN ... LONG_MAX)138 self.failUnlessEqual(3, getargs_l(3.14))139 self.failUnlessEqual(99, getargs_l(Long()))140 self.failUnlessEqual(99, getargs_l(Int()))141 self.assertRaises(OverflowError, getargs_l, LONG_MIN-1)142 self.failUnlessEqual(LONG_MIN, getargs_l(LONG_MIN))143 self.failUnlessEqual(LONG_MAX, getargs_l(LONG_MAX))144 self.assertRaises(OverflowError, getargs_l, LONG_MAX+1)145 self.failUnlessEqual(42, getargs_l(42))146 self.failUnlessEqual(42, getargs_l(42L))147 self.assertRaises(OverflowError, getargs_l, VERY_LARGE)148 def test_n(self):149 from _testcapi import getargs_n150 # n returns 'Py_ssize_t', and does range checking151 # (PY_SSIZE_T_MIN ... PY_SSIZE_T_MAX)152 self.failUnlessEqual(3, getargs_n(3.14))153 self.failUnlessEqual(99, getargs_n(Long()))154 self.failUnlessEqual(99, getargs_n(Int()))155 self.assertRaises(OverflowError, getargs_n, PY_SSIZE_T_MIN-1)156 self.failUnlessEqual(PY_SSIZE_T_MIN, getargs_n(PY_SSIZE_T_MIN))157 self.failUnlessEqual(PY_SSIZE_T_MAX, getargs_n(PY_SSIZE_T_MAX))158 self.assertRaises(OverflowError, getargs_n, PY_SSIZE_T_MAX+1)159 self.failUnlessEqual(42, getargs_n(42))160 self.failUnlessEqual(42, getargs_n(42L))161 self.assertRaises(OverflowError, getargs_n, VERY_LARGE)162class LongLong_TestCase(unittest.TestCase):163 def test_L(self):164 from _testcapi import getargs_L165 # L returns 'long long', and does range checking (LLONG_MIN ... LLONG_MAX)166 self.failUnlessRaises(TypeError, getargs_L, "Hello")167 self.failUnlessEqual(3, getargs_L(3.14))168 self.failUnlessEqual(99, getargs_L(Long()))169 self.failUnlessEqual(99, getargs_L(Int()))170 self.assertRaises(OverflowError, getargs_L, LLONG_MIN-1)171 self.failUnlessEqual(LLONG_MIN, getargs_L(LLONG_MIN))172 self.failUnlessEqual(LLONG_MAX, getargs_L(LLONG_MAX))173 self.assertRaises(OverflowError, getargs_L, LLONG_MAX+1)174 self.failUnlessEqual(42, getargs_L(42))175 self.failUnlessEqual(42, getargs_L(42L))176 self.assertRaises(OverflowError, getargs_L, VERY_LARGE)177 def test_K(self):178 from _testcapi import getargs_K179 # K return 'unsigned long long', no range checking180 self.assertRaises(TypeError, getargs_K, 3.14)181 self.assertRaises(TypeError, getargs_K, Long())182 self.assertRaises(TypeError, getargs_K, Int())183 self.failUnlessEqual(ULLONG_MAX, getargs_K(ULLONG_MAX))184 self.failUnlessEqual(0, getargs_K(0))185 self.failUnlessEqual(0, getargs_K(ULLONG_MAX+1))186 self.failUnlessEqual(42, getargs_K(42))187 self.failUnlessEqual(42, getargs_K(42L))188 self.failUnlessEqual(VERY_LARGE & ULLONG_MAX, getargs_K(VERY_LARGE))189class Tuple_TestCase(unittest.TestCase):190 def test_tuple(self):191 from _testcapi import getargs_tuple192 ret = getargs_tuple(1, (2, 3))193 self.assertEquals(ret, (1,2,3))194 # make sure invalid tuple arguments are handled correctly195 class seq:196 def __len__(self):197 return 2198 def __getitem__(self, n):199 raise ValueError200 self.assertRaises(TypeError, getargs_tuple, 1, seq())201def test_main():202 tests = [Signed_TestCase, Unsigned_TestCase, Tuple_TestCase]203 try:204 from _testcapi import getargs_L, getargs_K205 except ImportError:206 pass # PY_LONG_LONG not available207 else:208 tests.append(LongLong_TestCase)209 test_support.run_unittest(*tests)210if __name__ == "__main__":...
test_buffers.py
Source:test_buffers.py
1from ctypes import *2import unittest3class StringBufferTestCase(unittest.TestCase):4 def test_buffer(self):5 b = create_string_buffer(32)6 self.failUnlessEqual(len(b), 32)7 self.failUnlessEqual(sizeof(b), 32 * sizeof(c_char))8 self.failUnless(type(b[0]) is str)9 b = create_string_buffer("abc")10 self.failUnlessEqual(len(b), 4) # trailing nul char11 self.failUnlessEqual(sizeof(b), 4 * sizeof(c_char))12 self.failUnless(type(b[0]) is str)13 self.failUnlessEqual(b[0], "a")14 self.failUnlessEqual(b[:], "abc\0")15 def test_string_conversion(self):16 b = create_string_buffer(u"abc")17 self.failUnlessEqual(len(b), 4) # trailing nul char18 self.failUnlessEqual(sizeof(b), 4 * sizeof(c_char))19 self.failUnless(type(b[0]) is str)20 self.failUnlessEqual(b[0], "a")21 self.failUnlessEqual(b[:], "abc\0")22 try:23 c_wchar24 except NameError:25 pass26 else:27 def test_unicode_buffer(self):28 b = create_unicode_buffer(32)29 self.failUnlessEqual(len(b), 32)30 self.failUnlessEqual(sizeof(b), 32 * sizeof(c_wchar))31 self.failUnless(type(b[0]) is unicode)32 b = create_unicode_buffer(u"abc")33 self.failUnlessEqual(len(b), 4) # trailing nul char34 self.failUnlessEqual(sizeof(b), 4 * sizeof(c_wchar))35 self.failUnless(type(b[0]) is unicode)36 self.failUnlessEqual(b[0], u"a")37 self.failUnlessEqual(b[:], "abc\0")38 def test_unicode_conversion(self):39 b = create_unicode_buffer("abc")40 self.failUnlessEqual(len(b), 4) # trailing nul char41 self.failUnlessEqual(sizeof(b), 4 * sizeof(c_wchar))42 self.failUnless(type(b[0]) is unicode)43 self.failUnlessEqual(b[0], u"a")44 self.failUnlessEqual(b[:], "abc\0")45if __name__ == "__main__":...
Using AI Code Generation
1var devicefarmer = require('devicefarmer-stf');2device.fail('test failed');3var devicefarmer = require('devicefarmer-stf');4device.pass('test passed');5var devicefarmer = require('devicefarmer-stf');6device.log('test log');7var devicefarmer = require('devicefarmer-stf');8device.screenshot('test.png');9var devicefarmer = require('devicefarmer-stf');10device.screenshot('test.png');11var devicefarmer = require('devicefarmer-stf');12device.logcat('test.log');13var devicefarmer = require('devicefarmer-stf');14device.logcatClear();15var devicefarmer = require('devicefarmer-stf');16device.logcatDump('test.log');17var devicefarmer = require('devicefarmer-stf');18device.logcatRead('test.log');
Using AI Code Generation
1var devicefarmer = require('devicefarmer-stf');2var stf = new devicefarmer();3stf.fail('device-id', 'reason', function(err, data){4 if(err){5 console.log(err);6 }7 else{8 console.log(data);9 }10});11var devicefarmer = require('devicefarmer-stf');12var stf = new devicefarmer();13stf.pass('device-id', 'reason', function(err, data){14 if(err){15 console.log(err);16 }17 else{18 console.log(data);19 }20});21var devicefarmer = require('devicefarmer-stf');22var stf = new devicefarmer();23stf.getDevice('device-id', function(err, data){24 if(err){25 console.log(err);26 }27 else{28 console.log(data);29 }30});31var devicefarmer = require('devicefarmer-stf');32var stf = new devicefarmer();33stf.getDevices(function(err, data){34 if(err){35 console.log(err);36 }37 else{38 console.log(data);39 }40});41var devicefarmer = require('devicefarmer-stf');42var stf = new devicefarmer();43stf.getDevicesByUser('user-id', function(err, data){44 if(err){45 console.log(err);46 }47 else{48 console.log(data);49 }50});51var devicefarmer = require('devicefarmer-stf');52var stf = new devicefarmer();53stf.getDevicesByGroup('group-id', function(err, data){54 if(err){55 console.log(err);56 }57 else{58 console.log(data);59 }60});61var devicefarmer = require('devicefarmer-stf');62var stf = new devicefarmer();
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!