test_builtin.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. # Python test set -- built-in functions
  2. import unittest
  3. from operator import neg
  4. import sys
  5. class Squares:
  6. def __init__(self, max):
  7. self.max = max
  8. self.sofar = []
  9. def __len__(self): return len(self.sofar)
  10. def __getitem__(self, i):
  11. if not 0 <= i < self.max: raise IndexError
  12. n = len(self.sofar)
  13. while n <= i:
  14. self.sofar.append(n*n)
  15. n += 1
  16. return self.sofar[i]
  17. class TestFailingIter:
  18. def __iter__(self):
  19. raise RuntimeError
  20. class BuiltinTest(unittest.TestCase):
  21. def test_getattr(self):
  22. import sys
  23. self.assertTrue(getattr(sys, 'maxint') is sys.maxint)
  24. self.assertRaises(TypeError, getattr, sys, 1)
  25. self.assertRaises(TypeError, getattr)
  26. def test_hasattr(self):
  27. import sys
  28. self.assertTrue(hasattr(sys, 'maxint'))
  29. self.assertRaises(TypeError, hasattr, sys, 1)
  30. self.assertRaises(TypeError, hasattr)
  31. class A:
  32. def __init__(self):
  33. self.undef_self = None
  34. def undefxz(self):
  35. return None
  36. def __getattr__(self, name):
  37. if name == 'undef':
  38. return None
  39. if name == 'one':
  40. return 1
  41. raise AttributeError
  42. class NoGAtt:
  43. def __init__(self):
  44. self.undef_self = None
  45. def undefxz(self):
  46. return None
  47. a = A()
  48. b = NoGAtt()
  49. self.assertTrue(hasattr(a, 'undefxz'))
  50. self.assertTrue(hasattr(a, 'undef_self'))
  51. self.assertTrue(hasattr(a, 'one'))
  52. self.assertTrue(hasattr(a, 'undef'))
  53. self.assertFalse(hasattr(a, "Robyn"))
  54. self.assertTrue(hasattr(b, 'undefxz'))
  55. self.assertTrue(hasattr(b, 'undef_self'))
  56. self.assertFalse(hasattr(b, 'one'))
  57. self.assertFalse(hasattr(b, 'undef'))
  58. self.assertFalse(hasattr(a, "Robyn"))
  59. def test_setattr(self):
  60. setattr(sys, 'spam', 1)
  61. self.assertEqual(sys.spam, 1)
  62. self.assertRaises(TypeError, setattr, sys, 1, 'spam')
  63. self.assertRaises(AttributeError, setattr, 1, 'spam', 9)
  64. self.assertRaises(TypeError, setattr)
  65. def test_delattr(self):
  66. class NoName:
  67. def color(self):
  68. return "green"
  69. x = NoName()
  70. y = NoName
  71. setattr(NoName, "shape", "square")
  72. self.assertEqual(getattr(NoName, "shape"), "square")
  73. self.assertTrue(hasattr(NoName, "shape"))
  74. self.assertEqual(getattr(NoName(), "shape"), "square")
  75. self.assertTrue(hasattr(NoName(), "shape"))
  76. self.assertRaises(AttributeError, delattr, NoName(), "shape")
  77. self.assertEqual(getattr(x, "shape"), "square")
  78. self.assertEqual(getattr(y, "shape"), "square")
  79. setattr(y, "shape", "circle")
  80. setattr(x, "shape", "square")
  81. self.assertEqual(getattr(NoName, "shape"), "circle")
  82. self.assertEqual(getattr(NoName(), "shape"), "circle")
  83. self.assertEqual(getattr(x, "shape"), "square")
  84. self.assertEqual(getattr(y, "shape"), "circle")
  85. delattr(NoName, "shape")
  86. self.assertEqual(getattr(x, "shape"), "square")
  87. self.assertRaises(AttributeError, delattr, y, "shape")
  88. self.assertRaises(AttributeError, delattr, NoName(), "shape")
  89. self.assertRaises(AttributeError, delattr, NoName, "shape")
  90. self.assertEqual(getattr(x, "color")(), "green")
  91. self.assertEqual(getattr(NoName(), "color")(), "green")
  92. self.assertEqual(getattr(x, "color")(), "green")
  93. setattr(x, "color", "red")
  94. self.assertEqual(x.color, "red")
  95. delattr(NoName, "color")
  96. self.assertEqual(x.color, "red")
  97. self.assertRaises(AttributeError, delattr, NoName, "color")
  98. self.assertEqual(x.color, "red")
  99. self.assertRaises(AttributeError, delattr, NoName, "color")
  100. self.assertRaises(TypeError, delattr, list, "append")
  101. self.assertRaises(TypeError, setattr, dict, "k", "v")
  102. def test_dir_subclasses(self):
  103. class Base:
  104. def method1(self):
  105. pass
  106. class Sub(Base):
  107. def method2(self):
  108. pass
  109. self.assertIn("method1", dir(Sub))
  110. self.assertIn("method2", dir(Sub))
  111. sub = Sub()
  112. self.assertIn("method1", dir(sub))
  113. self.assertIn("method2", dir(sub))
  114. def test_all(self):
  115. self.assertEqual(all([2, 4, 6]), True)
  116. self.assertEqual(all([2, None, 6]), False)
  117. # self.assertRaises(RuntimeError, all, [2, TestFailingBool(), 6])
  118. self.assertRaises(RuntimeError, all, TestFailingIter())
  119. self.assertRaises(TypeError, all, 10) # Non-iterable
  120. self.assertRaises(TypeError, all) # No args
  121. self.assertRaises(TypeError, all, [2, 4, 6], []) # Too many args
  122. self.assertEqual(all([]), True) # Empty iterator
  123. # self.assertEqual(all([0, TestFailingBool()]), False)# Short-circuit
  124. S = [50, 60]
  125. self.assertEqual(all(x > 42 for x in S), True)
  126. S = [50, 40, 60]
  127. self.assertEqual(all(x > 42 for x in S), False)
  128. def test_any(self):
  129. self.assertEqual(any([None, None, None]), False)
  130. self.assertEqual(any([None, 4, None]), True)
  131. # self.assertRaises(RuntimeError, any, [None, TestFailingBool(), 6])
  132. self.assertRaises(RuntimeError, any, TestFailingIter())
  133. self.assertRaises(TypeError, any, 10) # Non-iterable
  134. self.assertRaises(TypeError, any) # No args
  135. self.assertRaises(TypeError, any, [2, 4, 6], []) # Too many args
  136. self.assertEqual(any([]), False) # Empty iterator
  137. # self.assertEqual(any([1, TestFailingBool()]), True) # Short-circuit
  138. S = [40, 60, 30]
  139. self.assertEqual(any(x > 42 for x in S), True)
  140. S = [10, 20, 30]
  141. self.assertEqual(any(x > 42 for x in S), False)
  142. def test_sum(self):
  143. self.assertEqual(sum([]), 0)
  144. self.assertEqual(sum(list(range(2,8))), 27)
  145. # self.assertEqual(sum(iter(list(range(2,8)))), 27)
  146. self.assertEqual(sum(Squares(10)), 285)
  147. # self.assertEqual(sum(iter(Squares(10))), 285)
  148. self.assertEqual(sum([[1], [2], [3]], []), [1, 2, 3])
  149. self.assertRaises(TypeError, sum)
  150. self.assertRaises(TypeError, sum, 42)
  151. self.assertRaises(TypeError, sum, ['a', 'b', 'c'])
  152. self.assertRaises(TypeError, sum, ['a', 'b', 'c'], '')
  153. self.assertRaises(TypeError, sum, [[1], [2], [3]])
  154. self.assertRaises(TypeError, sum, [{2:3}])
  155. self.assertRaises(TypeError, sum, [{2:3}]*2, {2:3})
  156. class BadSeq:
  157. def __getitem__(self, index):
  158. raise ValueError
  159. self.assertRaises(ValueError, sum, BadSeq())
  160. empty = []
  161. sum(([x] for x in range(10)), empty)
  162. self.assertEqual(empty, [])
  163. def test_zip(self):
  164. a = (1, 2, 3)
  165. b = (4, 5, 6)
  166. t = [(1, 4), (2, 5), (3, 6)]
  167. self.assertEqual(zip(a, b), t)
  168. b = [4, 5, 6]
  169. self.assertEqual(zip(a, b), t)
  170. b = (4, 5, 6, 7)
  171. self.assertEqual(zip(a, b), t)
  172. class I:
  173. def __getitem__(self, i):
  174. if i < 0 or i > 2: raise IndexError
  175. return i + 4
  176. self.assertEqual(zip(a, I()), t)
  177. self.assertEqual(zip(), [])
  178. self.assertEqual(zip(*[]), [])
  179. self.assertRaises(TypeError, zip, None)
  180. class G:
  181. pass
  182. self.assertRaises(TypeError, zip, a, G())
  183. # Make sure zip doesn't try to allocate a billion elements for the
  184. # result list when one of its arguments doesn't say how long it is.
  185. # A MemoryError is the most likely failure mode.
  186. class SequenceWithoutALength:
  187. def __getitem__(self, i):
  188. if i == 5:
  189. raise IndexError
  190. else:
  191. return i
  192. self.assertEqual(
  193. #zip(SequenceWithoutALength(), xrange(2**30)),
  194. zip(SequenceWithoutALength(), xrange(2**8)), # no working xrange
  195. list(enumerate(range(5)))
  196. )
  197. class BadSeq:
  198. def __getitem__(self, i):
  199. if i == 5:
  200. raise ValueError
  201. else:
  202. return i
  203. self.assertRaises(ValueError, zip, BadSeq(), BadSeq())
  204. def test_map(self):
  205. self.assertEqual(
  206. map(None, 'hello world'),
  207. ['h','e','l','l','o',' ','w','o','r','l','d']
  208. )
  209. self.assertEqual(
  210. map(None, 'abcd', 'efg'),
  211. [('a', 'e'), ('b', 'f'), ('c', 'g'), ('d', None)]
  212. )
  213. self.assertEqual(
  214. map(None, range(10)),
  215. [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
  216. )
  217. self.assertEqual(
  218. map(lambda x: x*x, range(1,4)),
  219. [1, 4, 9]
  220. )
  221. try:
  222. from math import sqrt
  223. except ImportError:
  224. def sqrt(x):
  225. return pow(x, 0.5)
  226. self.assertEqual(
  227. map(lambda x: map(sqrt,x), [[16, 4], [81, 9]]),
  228. [[4.0, 2.0], [9.0, 3.0]]
  229. )
  230. self.assertEqual(
  231. map(lambda x, y: x+y, [1,3,2], [9,1,4]),
  232. [10, 4, 6]
  233. )
  234. def plus(*v):
  235. accu = 0
  236. for i in v: accu = accu + i
  237. return accu
  238. self.assertEqual(
  239. map(plus, [1, 3, 7]),
  240. [1, 3, 7]
  241. )
  242. self.assertEqual(
  243. map(plus, [1, 3, 7], [4, 9, 2]),
  244. [1+4, 3+9, 7+2]
  245. )
  246. self.assertEqual(
  247. map(plus, [1, 3, 7], [4, 9, 2], [1, 1, 0]),
  248. [1+4+1, 3+9+1, 7+2+0]
  249. )
  250. self.assertEqual(
  251. map(None, Squares(10)),
  252. [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
  253. )
  254. self.assertEqual(
  255. map(int, Squares(10)),
  256. [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
  257. )
  258. self.assertEqual(
  259. map(None, Squares(3), Squares(2)),
  260. [(0,0), (1,1), (4,None)]
  261. )
  262. self.assertEqual(
  263. map(max, Squares(3), Squares(2)),
  264. [0, 1, 4]
  265. )
  266. self.assertRaises(TypeError, map)
  267. self.assertRaises(TypeError, map, lambda x: x, 42)
  268. self.assertEqual(map(None, [42]), [42])
  269. class BadSeq:
  270. def __getitem__(self, index):
  271. raise ValueError
  272. self.assertRaises(ValueError, map, lambda x: x, BadSeq())
  273. def badfunc(x):
  274. raise RuntimeError
  275. self.assertRaises(RuntimeError, map, badfunc, range(5))
  276. def test_abs(self):
  277. class TestAbs:
  278. def __init__(self):
  279. self.foo = -3
  280. def __abs__(self):
  281. return -self.foo
  282. bar = TestAbs()
  283. self.assertEqual(abs(bar), 3)
  284. self.assertEqual(abs(-3), 3)
  285. def test_reversed(self):
  286. class TestReversed:
  287. def __reversed__(self):
  288. return [5, 4, 3, 2, 1]
  289. self.assertEqual(list(reversed([1, 2, 3])), [3, 2, 1])
  290. obj = TestReversed()
  291. self.assertEqual(reversed(obj), [5, 4, 3, 2, 1])
  292. def test_reduce(self):
  293. add = lambda x, y: x+y
  294. self.assertEqual(reduce(add, ['a', 'b', 'c'], ''), 'abc')
  295. self.assertEqual(
  296. reduce(add, [['a', 'c'], [], ['d', 'w']], []),
  297. ['a','c','d','w']
  298. )
  299. self.assertEqual(reduce(lambda x, y: x*y, range(2,8), 1), 5040)
  300. self.assertEqual(
  301. reduce(lambda x, y: x*y, range(2,21), 1L),
  302. 2432902008176640000L
  303. )
  304. self.assertEqual(reduce(add, Squares(10)), 285)
  305. self.assertEqual(reduce(add, Squares(10), 0), 285)
  306. self.assertEqual(reduce(add, Squares(0), 0), 0)
  307. self.assertRaises(TypeError, reduce)
  308. self.assertRaises(TypeError, reduce, 42)
  309. self.assertRaises(TypeError, reduce, 42, 42)
  310. self.assertRaises(TypeError, reduce, 42, 42, 42)
  311. self.assertRaises(TypeError, reduce, None, range(5))
  312. self.assertRaises(TypeError, reduce, add, 42)
  313. self.assertEqual(reduce(42, "1"), "1") # func is never called with one item
  314. self.assertEqual(reduce(42, "", "1"), "1") # func is never called with one item
  315. self.assertRaises(TypeError, reduce, 42, (42, 42))
  316. self.assertRaises(TypeError, reduce, add, []) # arg 2 must not be empty sequence with no initial value
  317. self.assertRaises(TypeError, reduce, add, "")
  318. self.assertRaises(TypeError, reduce, add, ())
  319. self.assertEqual(reduce(add, [], None), None)
  320. self.assertEqual(reduce(add, [], 42), 42)
  321. class BadSeq:
  322. def __getitem__(self, index):
  323. raise ValueError
  324. self.assertRaises(ValueError, reduce, 42, BadSeq())
  325. def test_filter(self):
  326. self.assertEqual(filter(lambda c: 'a' <= c <= 'z', 'Hello World'), 'elloorld')
  327. self.assertEqual(filter(None, [1, 'hello', [], [3], '', None, 9, 0]), [1, 'hello', [3], 9])
  328. self.assertEqual(filter(lambda x: x > 0, [1, -3, 9, 0, 2]), [1, 9, 2])
  329. self.assertEqual(filter(None, Squares(10)), [1, 4, 9, 16, 25, 36, 49, 64, 81])
  330. self.assertEqual(filter(lambda x: x%2, Squares(10)), [1, 9, 25, 49, 81])
  331. def identity(item):
  332. return 1
  333. filter(identity, Squares(5))
  334. self.assertRaises(TypeError, filter)
  335. class BadSeq(object):
  336. def __getitem__(self, index):
  337. if index<4:
  338. return 42
  339. raise ValueError
  340. self.assertRaises(ValueError, filter, lambda x: x, BadSeq())
  341. def badfunc():
  342. pass
  343. self.assertRaises(TypeError, filter, badfunc, range(5))
  344. # test bltinmodule.c::filtertuple()
  345. self.assertEqual(filter(None, (1, 2)), (1, 2))
  346. self.assertEqual(filter(lambda x: x>=3, (1, 2, 3, 4)), (3, 4))
  347. self.assertRaises(TypeError, filter, 42, (1, 2))
  348. # test bltinmodule.c::filterstring()
  349. self.assertEqual(filter(None, "12"), "12")
  350. self.assertEqual(filter(lambda x: x>="3", "1234"), "34")
  351. self.assertRaises(TypeError, filter, 42, "12")
  352. # class badstr(str):
  353. # def __getitem__(self, index):
  354. # raise ValueError
  355. # self.assertRaises(ValueError, filter, lambda x: x >="3", badstr("1234"))
  356. # class badstr2(str):
  357. # def __getitem__(self, index):
  358. # return 42
  359. # self.assertRaises(TypeError, filter, lambda x: x >=42, badstr2("1234"))
  360. # class weirdstr(str):
  361. # def __getitem__(self, index):
  362. # return weirdstr(2*str.__getitem__(self, index))
  363. # self.assertEqual(filter(lambda x: x>="33", weirdstr("1234")), "3344")
  364. # class shiftstr(str):
  365. # def __getitem__(self, index):
  366. # return chr(ord(str.__getitem__(self, index))+1)
  367. # self.assertEqual(filter(lambda x: x>="3", shiftstr("1234")), "345")
  368. def test_callable(self):
  369. self.assertTrue(callable(len)) # builtin
  370. self.assertFalse(callable("a"))
  371. self.assertTrue(callable(callable)) # builtin
  372. self.assertTrue(callable(lambda x, y: x + y)) # python lambda
  373. def f(): pass
  374. self.assertTrue(callable(f)) # python func
  375. class C1(object):
  376. def meth(self): pass
  377. self.assertTrue(callable(C1)) # class
  378. c = C1()
  379. self.assertTrue(callable(c.meth)) # method (instance)
  380. # __call__ is looked up on the class, not the instance
  381. c.__call__ = None
  382. self.assertFalse(callable(c)) # class instance without __call__ in class
  383. class C2(object):
  384. def __call__(self): pass
  385. c2 = C2()
  386. self.assertTrue(callable(c2)) # class instance with __call__ in class
  387. self.assertFalse(callable(False)) # bool
  388. self.assertFalse(callable(["this is a list"])) # list
  389. self.assertFalse(callable(["this is a list with a function", f])) # list containing function
  390. self.assertFalse(callable({})) # dict
  391. self.assertFalse(callable(None)) # nonetype
  392. self.assertFalse(callable(1)) # number
  393. self.assertTrue(callable(float)) # float builtin
  394. self.assertFalse(callable(float())) # function call
  395. self.assertFalse(callable(float(1))) # float type
  396. self.assertFalse(callable("+")) # string containing symbol
  397. self.assertFalse(callable(4+7)) # expression
  398. self.assertFalse(callable(enumerate(['a', 'b', 'c', 'd']))) # list created by callable function
  399. self.assertFalse(callable(())) # tuple
  400. # generators are callable
  401. def squares(n):
  402. '''Yields the squares from 0 to n-1 squared.'''
  403. for i in range(n):
  404. yield i * i
  405. self.assertTrue(callable(squares)) # generator
  406. class SuperClass(object): #superclass
  407. def getName(self):
  408. raise NotImplementedError
  409. class LittleClass(SuperClass): #subclass/ inherited from SuperClass
  410. def __call__(self):
  411. return "LittleClass"
  412. big = SuperClass()
  413. big.__call__ = "call me super"
  414. self.assertFalse(callable(big)) # checking callable by class (not instances)
  415. class_inst = LittleClass() # class instances are not callable unless they have a .__call__ method
  416. self.assertTrue(callable(class_inst))
  417. #### nested classes
  418. class Outer(object):
  419. def __init__(self):
  420. self.y = 0
  421. class Inner(object):
  422. def __init__(self):
  423. self.x = 1
  424. self.assertTrue(callable(Outer.Inner)) # function object
  425. self.assertTrue(callable(Outer.Inner.__init__))
  426. def test_next(self):
  427. itera = iter([1,2,3]) # iterator
  428. self.assertEqual(next(itera), 1)
  429. self.assertEqual(next(itera), 2)
  430. self.assertEqual(next(itera), 3)
  431. self.assertEqual(next(itera, "stop please"), "stop please") # test default
  432. self.assertRaises(StopIteration, next, itera) # causes StopIteration
  433. self.assertRaises(TypeError, next, [1,2,3,4]) # type errors "not an iterator" : list
  434. self.assertRaises(TypeError, next, (1,2,3,4)) # tuple
  435. self.assertRaises(TypeError, next, "hello") # string
  436. self.assertEqual(next(iter("hello")), "h") # iterator from a string
  437. self.assertRaises(TypeError, next, False) # Type Error: bool object is not an iterator
  438. self.assertRaises(TypeError, next, {1:2}) # TypeError: dict object is not an iterator
  439. self.assertRaises(TypeError, next, 1) # TypeError: int object is not an iterator
  440. class Noniter:
  441. def __init__(self, num):
  442. self.mynum = num
  443. noniterb = Noniter(1) # "class instance without __iter__ method"
  444. self.assertRaises(TypeError, next, noniterb) # TypeError: instance has no next() method
  445. self.assertRaises(TypeError, next, noniterb, "defaultreturn") # class instance without __iter__ method, has default
  446. iterc = Noniter(2)
  447. iterc.__iter__ = iter([1,2,3]) # class instance with __iter__ method
  448. self.assertRaises(TypeError, next, iterc) # TypeError: instance has no next() method # stop iteration
  449. self.assertEqual(next(iterc.__iter__), 1) # iterator class without __iter__, instance with __iter__... should raise StopIteration error
  450. self.assertEqual(next(iterc.__iter__), 2)
  451. self.assertEqual(next(iterc.__iter__), 3)
  452. self.assertRaises(StopIteration, next, iterc.__iter__)
  453. class Iterb:
  454. def __init__(self, lst):
  455. self.lst = lst
  456. self.iter = iter(self.lst)
  457. def __iter__(self):
  458. return self.iter
  459. iterb = Iterb((1, 2))
  460. self.assertRaises(TypeError, next, iterb) # TypeError: instance has no next() method
  461. self.assertEqual(next(iterb.__iter__()), 1) # class with __iter__ method
  462. self.assertEqual(next(iterb.__iter__()), 2)
  463. self.assertRaises(StopIteration, next, iterb.__iter__())
  464. self.assertRaises(StopIteration, next, iterb.__iter__())
  465. iterstr = Iterb("str")
  466. self.assertEqual(next(iterstr.__iter__(), "ing"), "s") # iterator class with string and default
  467. self.assertEqual(next(iterstr.__iter__(), "ing"), "t")
  468. self.assertEqual(next(iterstr.__iter__(), "ing"), "r")
  469. self.assertEqual(next(iterstr.__iter__(), "ing"), "ing") # class instance with __iter__ method, testing default
  470. self.assertEqual(next(iterstr.__iter__(), "ing"), "ing")
  471. self.assertEqual(next(iterstr.__iter__(), "ing"), "ing")
  472. self.assertRaises(StopIteration, next, iterb.__iter__()) # class instance with __iter__ method, testing stop/no default
  473. spellcow = iter("cow") # tuple iterator
  474. self.assertEqual(next(spellcow, "moo"), "c") # sring, with defaul
  475. self.assertEqual(next(spellcow, "moo"), "o")
  476. self.assertEqual(next(spellcow, "moo"), "w")
  477. self.assertEqual(next(spellcow, "moo"), "moo")
  478. iterd = iter([]) # empty iterator
  479. self.assertRaises(StopIteration, next, iterd)
  480. class HasNext:
  481. def __init__(self, num):
  482. self.mynum = num
  483. def next(self):
  484. return "this is the next value"
  485. hasnext1 = HasNext(123)
  486. self.assertEqual(next(hasnext1), "this is the next value") # has a "next" method
  487. class NoNext:
  488. def __iter__(self):
  489. return self
  490. NoNextinst = NoNext()
  491. self.assertRaises(TypeError, next, NoNextinst.__iter__) # TypeError: instancemethod object is not an iterator
  492. self.assertRaises(TypeError, next, NoNextinst.__iter__())
  493. it = iter(range(2)) # cpython testing
  494. self.assertEqual(next(it), 0)
  495. self.assertEqual(next(it), 1)
  496. self.assertRaises(StopIteration, next, it)
  497. self.assertRaises(StopIteration, next, it)
  498. self.assertEqual(next(it, 42), 42)
  499. class Iter:
  500. def __iter__(self):
  501. return self
  502. def next(self):
  503. raise StopIteration
  504. it = iter(Iter())
  505. self.assertEqual(next(it, 42), 42)
  506. self.assertRaises(StopIteration, next, it)
  507. def gen():
  508. yield 1
  509. return
  510. it = gen()
  511. self.assertEqual(next(it), 1)
  512. self.assertRaises(StopIteration, next, it)
  513. self.assertEqual(next(it, 42), 42)
  514. if __name__ == "__main__":
  515. unittest.main()