test_array.py 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136
  1. """Test the arraymodule.
  2. Roger E. Masse
  3. """
  4. import unittest
  5. import warnings
  6. from test import test_support
  7. from weakref import proxy
  8. import array, cStringIO
  9. from cPickle import loads, dumps, HIGHEST_PROTOCOL
  10. import sys
  11. class ArraySubclass(array.array):
  12. pass
  13. class ArraySubclassWithKwargs(array.array):
  14. def __init__(self, typecode, newarg=None):
  15. array.array.__init__(self, typecode)
  16. tests = [] # list to accumulate all tests
  17. typecodes = "cbBhHiIlLfd"
  18. if test_support.have_unicode:
  19. typecodes += "u"
  20. class BadConstructorTest(unittest.TestCase):
  21. def test_constructor(self):
  22. self.assertRaises(TypeError, array.array)
  23. self.assertRaises(TypeError, array.array, spam=42)
  24. self.assertRaises(TypeError, array.array, 'xx')
  25. self.assertRaises(TypeError, array.array, '')
  26. self.assertRaises(TypeError, array.array, 1)
  27. self.assertRaises(ValueError, array.array, 'x')
  28. self.assertRaises(ValueError, array.array, '\x80')
  29. @test_support.requires_unicode
  30. def test_unicode_constructor(self):
  31. self.assertRaises(TypeError, array.array, u'xx')
  32. self.assertRaises(TypeError, array.array, u'')
  33. self.assertRaises(ValueError, array.array, u'x')
  34. self.assertRaises(ValueError, array.array, u'\x80')
  35. tests.append(BadConstructorTest)
  36. class BaseTest(unittest.TestCase):
  37. # Required class attributes (provided by subclasses
  38. # typecode: the typecode to test
  39. # example: an initializer usable in the constructor for this type
  40. # smallerexample: the same length as example, but smaller
  41. # biggerexample: the same length as example, but bigger
  42. # outside: An entry that is not in example
  43. # minitemsize: the minimum guaranteed itemsize
  44. def assertEntryEqual(self, entry1, entry2):
  45. self.assertEqual(entry1, entry2)
  46. def badtypecode(self):
  47. # Return a typecode that is different from our own
  48. return typecodes[(typecodes.index(self.typecode)+1) % len(typecodes)]
  49. def test_constructor(self):
  50. a = array.array(self.typecode)
  51. self.assertEqual(a.typecode, self.typecode)
  52. self.assertGreaterEqual(a.itemsize, self.minitemsize)
  53. self.assertRaises(TypeError, array.array, self.typecode, None)
  54. def test_len(self):
  55. a = array.array(self.typecode)
  56. a.append(self.example[0])
  57. self.assertEqual(len(a), 1)
  58. a = array.array(self.typecode, self.example)
  59. self.assertEqual(len(a), len(self.example))
  60. def test_buffer_info(self):
  61. a = array.array(self.typecode, self.example)
  62. self.assertRaises(TypeError, a.buffer_info, 42)
  63. bi = a.buffer_info()
  64. self.assertIsInstance(bi, tuple)
  65. self.assertEqual(len(bi), 2)
  66. self.assertIsInstance(bi[0], (int, long))
  67. self.assertIsInstance(bi[1], int)
  68. self.assertEqual(bi[1], len(a))
  69. def test_byteswap(self):
  70. a = array.array(self.typecode, self.example)
  71. self.assertRaises(TypeError, a.byteswap, 42)
  72. if a.itemsize in (1, 2, 4, 8):
  73. b = array.array(self.typecode, self.example)
  74. b.byteswap()
  75. if a.itemsize==1:
  76. self.assertEqual(a, b)
  77. else:
  78. self.assertNotEqual(a, b)
  79. b.byteswap()
  80. self.assertEqual(a, b)
  81. def test_copy(self):
  82. import copy
  83. a = array.array(self.typecode, self.example)
  84. b = copy.copy(a)
  85. self.assertNotEqual(id(a), id(b))
  86. self.assertEqual(a, b)
  87. def test_deepcopy(self):
  88. import copy
  89. a = array.array(self.typecode, self.example)
  90. b = copy.deepcopy(a)
  91. self.assertNotEqual(id(a), id(b))
  92. self.assertEqual(a, b)
  93. def test_pickle(self):
  94. for protocol in range(HIGHEST_PROTOCOL + 1):
  95. a = array.array(self.typecode, self.example)
  96. b = loads(dumps(a, protocol))
  97. self.assertNotEqual(id(a), id(b))
  98. self.assertEqual(a, b)
  99. a = ArraySubclass(self.typecode, self.example)
  100. a.x = 10
  101. b = loads(dumps(a, protocol))
  102. self.assertNotEqual(id(a), id(b))
  103. self.assertEqual(a, b)
  104. self.assertEqual(a.x, b.x)
  105. self.assertEqual(type(a), type(b))
  106. def test_pickle_for_empty_array(self):
  107. for protocol in range(HIGHEST_PROTOCOL + 1):
  108. a = array.array(self.typecode)
  109. b = loads(dumps(a, protocol))
  110. self.assertNotEqual(id(a), id(b))
  111. self.assertEqual(a, b)
  112. a = ArraySubclass(self.typecode)
  113. a.x = 10
  114. b = loads(dumps(a, protocol))
  115. self.assertNotEqual(id(a), id(b))
  116. self.assertEqual(a, b)
  117. self.assertEqual(a.x, b.x)
  118. self.assertEqual(type(a), type(b))
  119. def test_insert(self):
  120. a = array.array(self.typecode, self.example)
  121. a.insert(0, self.example[0])
  122. self.assertEqual(len(a), 1+len(self.example))
  123. self.assertEqual(a[0], a[1])
  124. self.assertRaises(TypeError, a.insert)
  125. self.assertRaises(TypeError, a.insert, None)
  126. self.assertRaises(TypeError, a.insert, 0, None)
  127. a = array.array(self.typecode, self.example)
  128. a.insert(-1, self.example[0])
  129. self.assertEqual(
  130. a,
  131. array.array(
  132. self.typecode,
  133. self.example[:-1] + self.example[:1] + self.example[-1:]
  134. )
  135. )
  136. a = array.array(self.typecode, self.example)
  137. a.insert(-1000, self.example[0])
  138. self.assertEqual(
  139. a,
  140. array.array(self.typecode, self.example[:1] + self.example)
  141. )
  142. a = array.array(self.typecode, self.example)
  143. a.insert(1000, self.example[0])
  144. self.assertEqual(
  145. a,
  146. array.array(self.typecode, self.example + self.example[:1])
  147. )
  148. def test_tofromfile(self):
  149. a = array.array(self.typecode, 2*self.example)
  150. self.assertRaises(TypeError, a.tofile)
  151. self.assertRaises(TypeError, a.tofile, cStringIO.StringIO())
  152. test_support.unlink(test_support.TESTFN)
  153. f = open(test_support.TESTFN, 'wb')
  154. try:
  155. a.tofile(f)
  156. f.close()
  157. b = array.array(self.typecode)
  158. f = open(test_support.TESTFN, 'rb')
  159. self.assertRaises(TypeError, b.fromfile)
  160. self.assertRaises(
  161. TypeError,
  162. b.fromfile,
  163. cStringIO.StringIO(), len(self.example)
  164. )
  165. b.fromfile(f, len(self.example))
  166. self.assertEqual(b, array.array(self.typecode, self.example))
  167. self.assertNotEqual(a, b)
  168. b.fromfile(f, len(self.example))
  169. self.assertEqual(a, b)
  170. self.assertRaises(EOFError, b.fromfile, f, 1)
  171. f.close()
  172. finally:
  173. if not f.closed:
  174. f.close()
  175. test_support.unlink(test_support.TESTFN)
  176. def test_fromfile_ioerror(self):
  177. # Issue #5395: Check if fromfile raises a proper IOError
  178. # instead of EOFError.
  179. a = array.array(self.typecode)
  180. f = open(test_support.TESTFN, 'wb')
  181. try:
  182. self.assertRaises(IOError, a.fromfile, f, len(self.example))
  183. finally:
  184. f.close()
  185. test_support.unlink(test_support.TESTFN)
  186. def test_filewrite(self):
  187. a = array.array(self.typecode, 2*self.example)
  188. f = open(test_support.TESTFN, 'wb')
  189. try:
  190. f.write(a)
  191. f.close()
  192. b = array.array(self.typecode)
  193. f = open(test_support.TESTFN, 'rb')
  194. b.fromfile(f, len(self.example))
  195. self.assertEqual(b, array.array(self.typecode, self.example))
  196. self.assertNotEqual(a, b)
  197. b.fromfile(f, len(self.example))
  198. self.assertEqual(a, b)
  199. f.close()
  200. finally:
  201. if not f.closed:
  202. f.close()
  203. test_support.unlink(test_support.TESTFN)
  204. def test_tofromlist(self):
  205. a = array.array(self.typecode, 2*self.example)
  206. b = array.array(self.typecode)
  207. self.assertRaises(TypeError, a.tolist, 42)
  208. self.assertRaises(TypeError, b.fromlist)
  209. self.assertRaises(TypeError, b.fromlist, 42)
  210. self.assertRaises(TypeError, b.fromlist, [None])
  211. b.fromlist(a.tolist())
  212. self.assertEqual(a, b)
  213. def test_tofromstring(self):
  214. a = array.array(self.typecode, 2*self.example)
  215. b = array.array(self.typecode)
  216. self.assertRaises(TypeError, a.tostring, 42)
  217. self.assertRaises(TypeError, b.fromstring)
  218. self.assertRaises(TypeError, b.fromstring, 42)
  219. self.assertRaises(ValueError, a.fromstring, a)
  220. b.fromstring(a.tostring())
  221. self.assertEqual(a, b)
  222. if a.itemsize>1:
  223. self.assertRaises(ValueError, b.fromstring, "x")
  224. def test_repr(self):
  225. a = array.array(self.typecode, 2*self.example)
  226. self.assertEqual(a, eval(repr(a), {"array": array.array}))
  227. a = array.array(self.typecode)
  228. self.assertEqual(repr(a), "array('%s')" % self.typecode)
  229. def test_str(self):
  230. a = array.array(self.typecode, 2*self.example)
  231. str(a)
  232. def test_cmp(self):
  233. a = array.array(self.typecode, self.example)
  234. self.assertIs(a == 42, False)
  235. self.assertIs(a != 42, True)
  236. self.assertIs(a == a, True)
  237. self.assertIs(a != a, False)
  238. self.assertIs(a < a, False)
  239. self.assertIs(a <= a, True)
  240. self.assertIs(a > a, False)
  241. self.assertIs(a >= a, True)
  242. al = array.array(self.typecode, self.smallerexample)
  243. ab = array.array(self.typecode, self.biggerexample)
  244. self.assertIs(a == 2*a, False)
  245. self.assertIs(a != 2*a, True)
  246. self.assertIs(a < 2*a, True)
  247. self.assertIs(a <= 2*a, True)
  248. self.assertIs(a > 2*a, False)
  249. self.assertIs(a >= 2*a, False)
  250. self.assertIs(a == al, False)
  251. self.assertIs(a != al, True)
  252. self.assertIs(a < al, False)
  253. self.assertIs(a <= al, False)
  254. self.assertIs(a > al, True)
  255. self.assertIs(a >= al, True)
  256. self.assertIs(a == ab, False)
  257. self.assertIs(a != ab, True)
  258. self.assertIs(a < ab, True)
  259. self.assertIs(a <= ab, True)
  260. self.assertIs(a > ab, False)
  261. self.assertIs(a >= ab, False)
  262. def test_add(self):
  263. a = array.array(self.typecode, self.example) \
  264. + array.array(self.typecode, self.example[::-1])
  265. self.assertEqual(
  266. a,
  267. array.array(self.typecode, self.example + self.example[::-1])
  268. )
  269. b = array.array(self.badtypecode())
  270. self.assertRaises(TypeError, a.__add__, b)
  271. self.assertRaises(TypeError, a.__add__, "bad")
  272. def test_iadd(self):
  273. a = array.array(self.typecode, self.example[::-1])
  274. b = a
  275. a += array.array(self.typecode, 2*self.example)
  276. self.assertIs(a, b)
  277. self.assertEqual(
  278. a,
  279. array.array(self.typecode, self.example[::-1]+2*self.example)
  280. )
  281. a = array.array(self.typecode, self.example)
  282. a += a
  283. self.assertEqual(
  284. a,
  285. array.array(self.typecode, self.example + self.example)
  286. )
  287. b = array.array(self.badtypecode())
  288. self.assertRaises(TypeError, a.__add__, b)
  289. self.assertRaises(TypeError, a.__iadd__, "bad")
  290. def test_mul(self):
  291. a = 5*array.array(self.typecode, self.example)
  292. self.assertEqual(
  293. a,
  294. array.array(self.typecode, 5*self.example)
  295. )
  296. a = array.array(self.typecode, self.example)*5
  297. self.assertEqual(
  298. a,
  299. array.array(self.typecode, self.example*5)
  300. )
  301. a = 0*array.array(self.typecode, self.example)
  302. self.assertEqual(
  303. a,
  304. array.array(self.typecode)
  305. )
  306. a = (-1)*array.array(self.typecode, self.example)
  307. self.assertEqual(
  308. a,
  309. array.array(self.typecode)
  310. )
  311. self.assertRaises(TypeError, a.__mul__, "bad")
  312. def test_imul(self):
  313. a = array.array(self.typecode, self.example)
  314. b = a
  315. a *= 5
  316. self.assertIs(a, b)
  317. self.assertEqual(
  318. a,
  319. array.array(self.typecode, 5*self.example)
  320. )
  321. a *= 0
  322. self.assertIs(a, b)
  323. self.assertEqual(a, array.array(self.typecode))
  324. a *= 1000
  325. self.assertIs(a, b)
  326. self.assertEqual(a, array.array(self.typecode))
  327. a *= -1
  328. self.assertIs(a, b)
  329. self.assertEqual(a, array.array(self.typecode))
  330. a = array.array(self.typecode, self.example)
  331. a *= -1
  332. self.assertEqual(a, array.array(self.typecode))
  333. self.assertRaises(TypeError, a.__imul__, "bad")
  334. def test_getitem(self):
  335. a = array.array(self.typecode, self.example)
  336. self.assertEntryEqual(a[0], self.example[0])
  337. self.assertEntryEqual(a[0L], self.example[0])
  338. self.assertEntryEqual(a[-1], self.example[-1])
  339. self.assertEntryEqual(a[-1L], self.example[-1])
  340. self.assertEntryEqual(a[len(self.example)-1], self.example[-1])
  341. self.assertEntryEqual(a[-len(self.example)], self.example[0])
  342. self.assertRaises(TypeError, a.__getitem__)
  343. self.assertRaises(IndexError, a.__getitem__, len(self.example))
  344. self.assertRaises(IndexError, a.__getitem__, -len(self.example)-1)
  345. def test_setitem(self):
  346. a = array.array(self.typecode, self.example)
  347. a[0] = a[-1]
  348. self.assertEntryEqual(a[0], a[-1])
  349. a = array.array(self.typecode, self.example)
  350. a[0L] = a[-1]
  351. self.assertEntryEqual(a[0], a[-1])
  352. a = array.array(self.typecode, self.example)
  353. a[-1] = a[0]
  354. self.assertEntryEqual(a[0], a[-1])
  355. a = array.array(self.typecode, self.example)
  356. a[-1L] = a[0]
  357. self.assertEntryEqual(a[0], a[-1])
  358. a = array.array(self.typecode, self.example)
  359. a[len(self.example)-1] = a[0]
  360. self.assertEntryEqual(a[0], a[-1])
  361. a = array.array(self.typecode, self.example)
  362. a[-len(self.example)] = a[-1]
  363. self.assertEntryEqual(a[0], a[-1])
  364. self.assertRaises(TypeError, a.__setitem__)
  365. self.assertRaises(TypeError, a.__setitem__, None)
  366. self.assertRaises(TypeError, a.__setitem__, 0, None)
  367. self.assertRaises(
  368. IndexError,
  369. a.__setitem__,
  370. len(self.example), self.example[0]
  371. )
  372. self.assertRaises(
  373. IndexError,
  374. a.__setitem__,
  375. -len(self.example)-1, self.example[0]
  376. )
  377. def test_delitem(self):
  378. a = array.array(self.typecode, self.example)
  379. del a[0]
  380. self.assertEqual(
  381. a,
  382. array.array(self.typecode, self.example[1:])
  383. )
  384. a = array.array(self.typecode, self.example)
  385. del a[-1]
  386. self.assertEqual(
  387. a,
  388. array.array(self.typecode, self.example[:-1])
  389. )
  390. a = array.array(self.typecode, self.example)
  391. del a[len(self.example)-1]
  392. self.assertEqual(
  393. a,
  394. array.array(self.typecode, self.example[:-1])
  395. )
  396. a = array.array(self.typecode, self.example)
  397. del a[-len(self.example)]
  398. self.assertEqual(
  399. a,
  400. array.array(self.typecode, self.example[1:])
  401. )
  402. self.assertRaises(TypeError, a.__delitem__)
  403. self.assertRaises(TypeError, a.__delitem__, None)
  404. self.assertRaises(IndexError, a.__delitem__, len(self.example))
  405. self.assertRaises(IndexError, a.__delitem__, -len(self.example)-1)
  406. def test_getslice(self):
  407. a = array.array(self.typecode, self.example)
  408. self.assertEqual(a[:], a)
  409. self.assertEqual(
  410. a[1:],
  411. array.array(self.typecode, self.example[1:])
  412. )
  413. self.assertEqual(
  414. a[:1],
  415. array.array(self.typecode, self.example[:1])
  416. )
  417. self.assertEqual(
  418. a[:-1],
  419. array.array(self.typecode, self.example[:-1])
  420. )
  421. self.assertEqual(
  422. a[-1:],
  423. array.array(self.typecode, self.example[-1:])
  424. )
  425. self.assertEqual(
  426. a[-1:-1],
  427. array.array(self.typecode)
  428. )
  429. self.assertEqual(
  430. a[2:1],
  431. array.array(self.typecode)
  432. )
  433. self.assertEqual(
  434. a[1000:],
  435. array.array(self.typecode)
  436. )
  437. self.assertEqual(a[-1000:], a)
  438. self.assertEqual(a[:1000], a)
  439. self.assertEqual(
  440. a[:-1000],
  441. array.array(self.typecode)
  442. )
  443. self.assertEqual(a[-1000:1000], a)
  444. self.assertEqual(
  445. a[2000:1000],
  446. array.array(self.typecode)
  447. )
  448. def test_extended_getslice(self):
  449. # Test extended slicing by comparing with list slicing
  450. # (Assumes list conversion works correctly, too)
  451. a = array.array(self.typecode, self.example)
  452. indices = (0, None, 1, 3, 19, 100, -1, -2, -31, -100)
  453. for start in indices:
  454. for stop in indices:
  455. # Everything except the initial 0 (invalid step)
  456. for step in indices[1:]:
  457. self.assertEqual(list(a[start:stop:step]),
  458. list(a)[start:stop:step])
  459. def test_setslice(self):
  460. a = array.array(self.typecode, self.example)
  461. a[:1] = a
  462. self.assertEqual(
  463. a,
  464. array.array(self.typecode, self.example + self.example[1:])
  465. )
  466. a = array.array(self.typecode, self.example)
  467. a[:-1] = a
  468. self.assertEqual(
  469. a,
  470. array.array(self.typecode, self.example + self.example[-1:])
  471. )
  472. a = array.array(self.typecode, self.example)
  473. a[-1:] = a
  474. self.assertEqual(
  475. a,
  476. array.array(self.typecode, self.example[:-1] + self.example)
  477. )
  478. a = array.array(self.typecode, self.example)
  479. a[1:] = a
  480. self.assertEqual(
  481. a,
  482. array.array(self.typecode, self.example[:1] + self.example)
  483. )
  484. a = array.array(self.typecode, self.example)
  485. a[1:-1] = a
  486. self.assertEqual(
  487. a,
  488. array.array(
  489. self.typecode,
  490. self.example[:1] + self.example + self.example[-1:]
  491. )
  492. )
  493. a = array.array(self.typecode, self.example)
  494. a[1000:] = a
  495. self.assertEqual(
  496. a,
  497. array.array(self.typecode, 2*self.example)
  498. )
  499. a = array.array(self.typecode, self.example)
  500. a[-1000:] = a
  501. self.assertEqual(
  502. a,
  503. array.array(self.typecode, self.example)
  504. )
  505. a = array.array(self.typecode, self.example)
  506. a[:1000] = a
  507. self.assertEqual(
  508. a,
  509. array.array(self.typecode, self.example)
  510. )
  511. a = array.array(self.typecode, self.example)
  512. a[:-1000] = a
  513. self.assertEqual(
  514. a,
  515. array.array(self.typecode, 2*self.example)
  516. )
  517. a = array.array(self.typecode, self.example)
  518. a[1:0] = a
  519. self.assertEqual(
  520. a,
  521. array.array(self.typecode, self.example[:1] + self.example + self.example[1:])
  522. )
  523. a = array.array(self.typecode, self.example)
  524. a[2000:1000] = a
  525. self.assertEqual(
  526. a,
  527. array.array(self.typecode, 2*self.example)
  528. )
  529. a = array.array(self.typecode, self.example)
  530. self.assertRaises(TypeError, a.__setslice__, 0, 0, None)
  531. self.assertRaises(TypeError, a.__setitem__, slice(0, 0), None)
  532. self.assertRaises(TypeError, a.__setitem__, slice(0, 1), None)
  533. b = array.array(self.badtypecode())
  534. self.assertRaises(TypeError, a.__setslice__, 0, 0, b)
  535. self.assertRaises(TypeError, a.__setitem__, slice(0, 0), b)
  536. self.assertRaises(TypeError, a.__setitem__, slice(0, 1), b)
  537. def test_extended_set_del_slice(self):
  538. indices = (0, None, 1, 3, 19, 100, -1, -2, -31, -100)
  539. for start in indices:
  540. for stop in indices:
  541. # Everything except the initial 0 (invalid step)
  542. for step in indices[1:]:
  543. a = array.array(self.typecode, self.example)
  544. L = list(a)
  545. # Make sure we have a slice of exactly the right length,
  546. # but with (hopefully) different data.
  547. data = L[start:stop:step]
  548. data.reverse()
  549. L[start:stop:step] = data
  550. a[start:stop:step] = array.array(self.typecode, data)
  551. self.assertEqual(a, array.array(self.typecode, L))
  552. del L[start:stop:step]
  553. del a[start:stop:step]
  554. self.assertEqual(a, array.array(self.typecode, L))
  555. def test_index(self):
  556. example = 2*self.example
  557. a = array.array(self.typecode, example)
  558. self.assertRaises(TypeError, a.index)
  559. for x in example:
  560. self.assertEqual(a.index(x), example.index(x))
  561. self.assertRaises(ValueError, a.index, None)
  562. self.assertRaises(ValueError, a.index, self.outside)
  563. def test_count(self):
  564. example = 2*self.example
  565. a = array.array(self.typecode, example)
  566. self.assertRaises(TypeError, a.count)
  567. for x in example:
  568. self.assertEqual(a.count(x), example.count(x))
  569. self.assertEqual(a.count(self.outside), 0)
  570. self.assertEqual(a.count(None), 0)
  571. def test_remove(self):
  572. for x in self.example:
  573. example = 2*self.example
  574. a = array.array(self.typecode, example)
  575. pos = example.index(x)
  576. example2 = example[:pos] + example[pos+1:]
  577. a.remove(x)
  578. self.assertEqual(a, array.array(self.typecode, example2))
  579. a = array.array(self.typecode, self.example)
  580. self.assertRaises(ValueError, a.remove, self.outside)
  581. self.assertRaises(ValueError, a.remove, None)
  582. def test_pop(self):
  583. a = array.array(self.typecode)
  584. self.assertRaises(IndexError, a.pop)
  585. a = array.array(self.typecode, 2*self.example)
  586. self.assertRaises(TypeError, a.pop, 42, 42)
  587. self.assertRaises(TypeError, a.pop, None)
  588. self.assertRaises(IndexError, a.pop, len(a))
  589. self.assertRaises(IndexError, a.pop, -len(a)-1)
  590. self.assertEntryEqual(a.pop(0), self.example[0])
  591. self.assertEqual(
  592. a,
  593. array.array(self.typecode, self.example[1:]+self.example)
  594. )
  595. self.assertEntryEqual(a.pop(1), self.example[2])
  596. self.assertEqual(
  597. a,
  598. array.array(self.typecode, self.example[1:2]+self.example[3:]+self.example)
  599. )
  600. self.assertEntryEqual(a.pop(0), self.example[1])
  601. self.assertEntryEqual(a.pop(), self.example[-1])
  602. self.assertEqual(
  603. a,
  604. array.array(self.typecode, self.example[3:]+self.example[:-1])
  605. )
  606. def test_reverse(self):
  607. a = array.array(self.typecode, self.example)
  608. self.assertRaises(TypeError, a.reverse, 42)
  609. a.reverse()
  610. self.assertEqual(
  611. a,
  612. array.array(self.typecode, self.example[::-1])
  613. )
  614. def test_extend(self):
  615. a = array.array(self.typecode, self.example)
  616. self.assertRaises(TypeError, a.extend)
  617. a.extend(array.array(self.typecode, self.example[::-1]))
  618. self.assertEqual(
  619. a,
  620. array.array(self.typecode, self.example+self.example[::-1])
  621. )
  622. a = array.array(self.typecode, self.example)
  623. a.extend(a)
  624. self.assertEqual(
  625. a,
  626. array.array(self.typecode, self.example+self.example)
  627. )
  628. b = array.array(self.badtypecode())
  629. self.assertRaises(TypeError, a.extend, b)
  630. a = array.array(self.typecode, self.example)
  631. a.extend(self.example[::-1])
  632. self.assertEqual(
  633. a,
  634. array.array(self.typecode, self.example+self.example[::-1])
  635. )
  636. def test_constructor_with_iterable_argument(self):
  637. a = array.array(self.typecode, iter(self.example))
  638. b = array.array(self.typecode, self.example)
  639. self.assertEqual(a, b)
  640. # non-iterable argument
  641. self.assertRaises(TypeError, array.array, self.typecode, 10)
  642. # pass through errors raised in __iter__
  643. class A:
  644. def __iter__(self):
  645. raise UnicodeError
  646. self.assertRaises(UnicodeError, array.array, self.typecode, A())
  647. # pass through errors raised in next()
  648. def B():
  649. raise UnicodeError
  650. yield None
  651. self.assertRaises(UnicodeError, array.array, self.typecode, B())
  652. def test_coveritertraverse(self):
  653. try:
  654. import gc
  655. except ImportError:
  656. self.skipTest('gc module not available')
  657. a = array.array(self.typecode)
  658. l = [iter(a)]
  659. l.append(l)
  660. gc.collect()
  661. def test_buffer(self):
  662. a = array.array(self.typecode, self.example)
  663. with test_support.check_py3k_warnings():
  664. b = buffer(a)
  665. self.assertEqual(b[0], a.tostring()[0])
  666. def test_weakref(self):
  667. s = array.array(self.typecode, self.example)
  668. p = proxy(s)
  669. self.assertEqual(p.tostring(), s.tostring())
  670. s = None
  671. self.assertRaises(ReferenceError, len, p)
  672. @unittest.skipUnless(hasattr(sys, 'getrefcount'),
  673. 'test needs sys.getrefcount()')
  674. def test_bug_782369(self):
  675. for i in range(10):
  676. b = array.array('B', range(64))
  677. rc = sys.getrefcount(10)
  678. for i in range(10):
  679. b = array.array('B', range(64))
  680. self.assertEqual(rc, sys.getrefcount(10))
  681. def test_subclass_with_kwargs(self):
  682. # SF bug #1486663 -- this used to erroneously raise a TypeError
  683. with warnings.catch_warnings():
  684. warnings.filterwarnings("ignore", '', DeprecationWarning)
  685. ArraySubclassWithKwargs('b', newarg=1)
  686. class StringTest(BaseTest):
  687. def test_setitem(self):
  688. super(StringTest, self).test_setitem()
  689. a = array.array(self.typecode, self.example)
  690. self.assertRaises(TypeError, a.__setitem__, 0, self.example[:2])
  691. class CharacterTest(StringTest):
  692. typecode = 'c'
  693. example = '\x01azAZ\x00\xfe'
  694. smallerexample = '\x01azAY\x00\xfe'
  695. biggerexample = '\x01azAZ\x00\xff'
  696. outside = '\x33'
  697. minitemsize = 1
  698. def test_subbclassing(self):
  699. class EditableString(array.array):
  700. def __new__(cls, s, *args, **kwargs):
  701. return array.array.__new__(cls, 'c', s)
  702. def __init__(self, s, color='blue'):
  703. self.color = color
  704. def strip(self):
  705. self[:] = array.array('c', self.tostring().strip())
  706. def __repr__(self):
  707. return 'EditableString(%r)' % self.tostring()
  708. s = EditableString("\ttest\r\n")
  709. s.strip()
  710. self.assertEqual(s.tostring(), "test")
  711. self.assertEqual(s.color, "blue")
  712. s.color = "red"
  713. self.assertEqual(s.color, "red")
  714. self.assertEqual(s.__dict__.keys(), ["color"])
  715. @test_support.requires_unicode
  716. def test_nounicode(self):
  717. a = array.array(self.typecode, self.example)
  718. self.assertRaises(ValueError, a.fromunicode, unicode(''))
  719. self.assertRaises(ValueError, a.tounicode)
  720. tests.append(CharacterTest)
  721. if test_support.have_unicode:
  722. class UnicodeTest(StringTest):
  723. typecode = 'u'
  724. example = unicode(r'\x01\u263a\x00\ufeff', 'unicode-escape')
  725. smallerexample = unicode(r'\x01\u263a\x00\ufefe', 'unicode-escape')
  726. biggerexample = unicode(r'\x01\u263a\x01\ufeff', 'unicode-escape')
  727. outside = unicode('\x33')
  728. minitemsize = 2
  729. def test_unicode(self):
  730. self.assertRaises(TypeError, array.array, 'b', unicode('foo', 'ascii'))
  731. a = array.array('u', unicode(r'\xa0\xc2\u1234', 'unicode-escape'))
  732. a.fromunicode(unicode(' ', 'ascii'))
  733. a.fromunicode(unicode('', 'ascii'))
  734. a.fromunicode(unicode('', 'ascii'))
  735. a.fromunicode(unicode(r'\x11abc\xff\u1234', 'unicode-escape'))
  736. s = a.tounicode()
  737. self.assertEqual(
  738. s,
  739. unicode(r'\xa0\xc2\u1234 \x11abc\xff\u1234', 'unicode-escape')
  740. )
  741. s = unicode(r'\x00="\'a\\b\x80\xff\u0000\u0001\u1234', 'unicode-escape')
  742. a = array.array('u', s)
  743. self.assertEqual(
  744. repr(a),
  745. r"""array('u', u'\x00="\'a\\b\x80\xff\x00\x01\u1234')"""
  746. )
  747. self.assertRaises(TypeError, a.fromunicode)
  748. tests.append(UnicodeTest)
  749. class NumberTest(BaseTest):
  750. def test_extslice(self):
  751. a = array.array(self.typecode, range(5))
  752. self.assertEqual(a[::], a)
  753. self.assertEqual(a[::2], array.array(self.typecode, [0,2,4]))
  754. self.assertEqual(a[1::2], array.array(self.typecode, [1,3]))
  755. self.assertEqual(a[::-1], array.array(self.typecode, [4,3,2,1,0]))
  756. self.assertEqual(a[::-2], array.array(self.typecode, [4,2,0]))
  757. self.assertEqual(a[3::-2], array.array(self.typecode, [3,1]))
  758. self.assertEqual(a[-100:100:], a)
  759. self.assertEqual(a[100:-100:-1], a[::-1])
  760. self.assertEqual(a[-100L:100L:2L], array.array(self.typecode, [0,2,4]))
  761. self.assertEqual(a[1000:2000:2], array.array(self.typecode, []))
  762. self.assertEqual(a[-1000:-2000:-2], array.array(self.typecode, []))
  763. def test_delslice(self):
  764. a = array.array(self.typecode, range(5))
  765. del a[::2]
  766. self.assertEqual(a, array.array(self.typecode, [1,3]))
  767. a = array.array(self.typecode, range(5))
  768. del a[1::2]
  769. self.assertEqual(a, array.array(self.typecode, [0,2,4]))
  770. a = array.array(self.typecode, range(5))
  771. del a[1::-2]
  772. self.assertEqual(a, array.array(self.typecode, [0,2,3,4]))
  773. a = array.array(self.typecode, range(10))
  774. del a[::1000]
  775. self.assertEqual(a, array.array(self.typecode, [1,2,3,4,5,6,7,8,9]))
  776. # test issue7788
  777. a = array.array(self.typecode, range(10))
  778. del a[9::1<<333]
  779. def test_assignment(self):
  780. a = array.array(self.typecode, range(10))
  781. a[::2] = array.array(self.typecode, [42]*5)
  782. self.assertEqual(a, array.array(self.typecode, [42, 1, 42, 3, 42, 5, 42, 7, 42, 9]))
  783. a = array.array(self.typecode, range(10))
  784. a[::-4] = array.array(self.typecode, [10]*3)
  785. self.assertEqual(a, array.array(self.typecode, [0, 10, 2, 3, 4, 10, 6, 7, 8 ,10]))
  786. a = array.array(self.typecode, range(4))
  787. a[::-1] = a
  788. self.assertEqual(a, array.array(self.typecode, [3, 2, 1, 0]))
  789. a = array.array(self.typecode, range(10))
  790. b = a[:]
  791. c = a[:]
  792. ins = array.array(self.typecode, range(2))
  793. a[2:3] = ins
  794. b[slice(2,3)] = ins
  795. c[2:3:] = ins
  796. def test_iterationcontains(self):
  797. a = array.array(self.typecode, range(10))
  798. self.assertEqual(list(a), range(10))
  799. b = array.array(self.typecode, [20])
  800. self.assertEqual(a[-1] in a, True)
  801. self.assertEqual(b[0] not in a, True)
  802. def check_overflow(self, lower, upper):
  803. # method to be used by subclasses
  804. # should not overflow assigning lower limit
  805. a = array.array(self.typecode, [lower])
  806. a[0] = lower
  807. # should overflow assigning less than lower limit
  808. self.assertRaises(OverflowError, array.array, self.typecode, [lower-1])
  809. self.assertRaises(OverflowError, a.__setitem__, 0, lower-1)
  810. # should not overflow assigning upper limit
  811. a = array.array(self.typecode, [upper])
  812. a[0] = upper
  813. # should overflow assigning more than upper limit
  814. self.assertRaises(OverflowError, array.array, self.typecode, [upper+1])
  815. self.assertRaises(OverflowError, a.__setitem__, 0, upper+1)
  816. def test_subclassing(self):
  817. typecode = self.typecode
  818. class ExaggeratingArray(array.array):
  819. __slots__ = ['offset']
  820. def __new__(cls, typecode, data, offset):
  821. return array.array.__new__(cls, typecode, data)
  822. def __init__(self, typecode, data, offset):
  823. self.offset = offset
  824. def __getitem__(self, i):
  825. return array.array.__getitem__(self, i) + self.offset
  826. a = ExaggeratingArray(self.typecode, [3, 6, 7, 11], 4)
  827. self.assertEntryEqual(a[0], 7)
  828. self.assertRaises(AttributeError, setattr, a, "color", "blue")
  829. class SignedNumberTest(NumberTest):
  830. example = [-1, 0, 1, 42, 0x7f]
  831. smallerexample = [-1, 0, 1, 42, 0x7e]
  832. biggerexample = [-1, 0, 1, 43, 0x7f]
  833. outside = 23
  834. def test_overflow(self):
  835. a = array.array(self.typecode)
  836. lower = -1 * long(pow(2, a.itemsize * 8 - 1))
  837. upper = long(pow(2, a.itemsize * 8 - 1)) - 1L
  838. self.check_overflow(lower, upper)
  839. class UnsignedNumberTest(NumberTest):
  840. example = [0, 1, 17, 23, 42, 0xff]
  841. smallerexample = [0, 1, 17, 23, 42, 0xfe]
  842. biggerexample = [0, 1, 17, 23, 43, 0xff]
  843. outside = 0xaa
  844. def test_overflow(self):
  845. a = array.array(self.typecode)
  846. lower = 0
  847. upper = long(pow(2, a.itemsize * 8)) - 1L
  848. self.check_overflow(lower, upper)
  849. @test_support.cpython_only
  850. def test_sizeof_with_buffer(self):
  851. a = array.array(self.typecode, self.example)
  852. basesize = test_support.calcvobjsize('4P')
  853. buffer_size = a.buffer_info()[1] * a.itemsize
  854. test_support.check_sizeof(self, a, basesize + buffer_size)
  855. @test_support.cpython_only
  856. def test_sizeof_without_buffer(self):
  857. a = array.array(self.typecode)
  858. basesize = test_support.calcvobjsize('4P')
  859. test_support.check_sizeof(self, a, basesize)
  860. class ByteTest(SignedNumberTest):
  861. typecode = 'b'
  862. minitemsize = 1
  863. tests.append(ByteTest)
  864. class UnsignedByteTest(UnsignedNumberTest):
  865. typecode = 'B'
  866. minitemsize = 1
  867. tests.append(UnsignedByteTest)
  868. class ShortTest(SignedNumberTest):
  869. typecode = 'h'
  870. minitemsize = 2
  871. tests.append(ShortTest)
  872. class UnsignedShortTest(UnsignedNumberTest):
  873. typecode = 'H'
  874. minitemsize = 2
  875. tests.append(UnsignedShortTest)
  876. class IntTest(SignedNumberTest):
  877. typecode = 'i'
  878. minitemsize = 2
  879. tests.append(IntTest)
  880. class UnsignedIntTest(UnsignedNumberTest):
  881. typecode = 'I'
  882. minitemsize = 2
  883. tests.append(UnsignedIntTest)
  884. class LongTest(SignedNumberTest):
  885. typecode = 'l'
  886. minitemsize = 4
  887. tests.append(LongTest)
  888. class UnsignedLongTest(UnsignedNumberTest):
  889. typecode = 'L'
  890. minitemsize = 4
  891. tests.append(UnsignedLongTest)
  892. @test_support.requires_unicode
  893. class UnicodeTypecodeTest(unittest.TestCase):
  894. def test_unicode_typecode(self):
  895. for typecode in typecodes:
  896. a = array.array(unicode(typecode))
  897. self.assertEqual(a.typecode, typecode)
  898. self.assertIs(type(a.typecode), str)
  899. tests.append(UnicodeTypecodeTest)
  900. class FPTest(NumberTest):
  901. example = [-42.0, 0, 42, 1e5, -1e10]
  902. smallerexample = [-42.0, 0, 42, 1e5, -2e10]
  903. biggerexample = [-42.0, 0, 42, 1e5, 1e10]
  904. outside = 23
  905. def assertEntryEqual(self, entry1, entry2):
  906. self.assertAlmostEqual(entry1, entry2)
  907. def test_byteswap(self):
  908. a = array.array(self.typecode, self.example)
  909. self.assertRaises(TypeError, a.byteswap, 42)
  910. if a.itemsize in (1, 2, 4, 8):
  911. b = array.array(self.typecode, self.example)
  912. b.byteswap()
  913. if a.itemsize==1:
  914. self.assertEqual(a, b)
  915. else:
  916. # On alphas treating the byte swapped bit patters as
  917. # floats/doubles results in floating point exceptions
  918. # => compare the 8bit string values instead
  919. self.assertNotEqual(a.tostring(), b.tostring())
  920. b.byteswap()
  921. self.assertEqual(a, b)
  922. class FloatTest(FPTest):
  923. typecode = 'f'
  924. minitemsize = 4
  925. tests.append(FloatTest)
  926. class DoubleTest(FPTest):
  927. typecode = 'd'
  928. minitemsize = 8
  929. def test_alloc_overflow(self):
  930. from sys import maxsize
  931. a = array.array('d', [-1]*65536)
  932. try:
  933. a *= maxsize//65536 + 1
  934. except MemoryError:
  935. pass
  936. else:
  937. self.fail("Array of size > maxsize created - MemoryError expected")
  938. b = array.array('d', [ 2.71828183, 3.14159265, -1])
  939. try:
  940. b * (maxsize//3 + 1)
  941. except MemoryError:
  942. pass
  943. else:
  944. self.fail("Array of size > maxsize created - MemoryError expected")
  945. tests.append(DoubleTest)
  946. def test_main(verbose=None):
  947. import sys
  948. test_support.run_unittest(*tests)
  949. # verify reference counting
  950. if verbose and hasattr(sys, "gettotalrefcount"):
  951. import gc
  952. counts = [None] * 5
  953. for i in xrange(len(counts)):
  954. test_support.run_unittest(*tests)
  955. gc.collect()
  956. counts[i] = sys.gettotalrefcount()
  957. print counts
  958. if __name__ == "__main__":
  959. test_main(verbose=True)