def test_main(): enabled = gc.isenabled() gc.disable() if not test_support.due_to_ironpython_incompatibility( "http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=314470" ): assert not gc.isenabled() debug = gc.get_debug() if not test_support.due_to_ironpython_incompatibility( "http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=314470" ): gc.set_debug(debug & ~gc.DEBUG_LEAK) # this test is supposed to leak try: gc.collect() # Delete 2nd generation garbage run_unittest(GCTests, GCTogglingTests) finally: if not test_support.due_to_ironpython_incompatibility( "http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=314470" ): gc.set_debug(debug) # test gc.enable() even if GC is disabled by default if verbose: print "restoring automatic collection" # make sure to always test gc.enable() gc.enable() assert gc.isenabled() if not enabled: gc.disable()
def test_genrandbits(self): # Verify cross-platform repeatability self.gen.seed(1234567) if not test_support.due_to_ironpython_incompatibility( "http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=318984" ): self.assertEqual(self.gen.getrandbits(100), 97904845777343510404718956115L) # Verify ranges for k in xrange(1, 1000): if not test_support.due_to_ironpython_incompatibility( "http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=318984" ): self.assertTrue(0 <= self.gen.getrandbits(k) < 2**k) # Verify all bits active getbits = self.gen.getrandbits for span in [1, 2, 3, 4, 31, 32, 32, 52, 53, 54, 119, 127, 128, 129]: cum = 0 for i in xrange(100): cum |= getbits(span) if not test_support.due_to_ironpython_incompatibility( "http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=318984" ): self.assertEqual(cum, 2**span - 1) # Verify argument checking self.assertRaises(TypeError, self.gen.getrandbits) self.assertRaises(TypeError, self.gen.getrandbits, 'a') self.assertRaises(TypeError, self.gen.getrandbits, 1, 2) self.assertRaises(ValueError, self.gen.getrandbits, 0) self.assertRaises(ValueError, self.gen.getrandbits, -1)
def test_module_with_large_stack(self, module='longlist'): # Regression test for http://bugs.python.org/issue561858. filename = module + os.extsep + 'py' # Create a file with a list of 65000 elements. with open(filename, 'w+') as f: f.write('d = [\n') for i in range(65000): f.write('"",\n') f.write(']') # Compile & remove .py file, we only need .pyc (or .pyo). if not due_to_ironpython_incompatibility( "IronPython cannot use pyc files"): with open(filename, 'r') as f: py_compile.compile(filename) unlink(filename) # Need to be able to load from current dir. sys.path.append('') # This used to crash. exec 'import ' + module # Cleanup. del sys.path[-1] unlink(filename + 'c') unlink(filename + 'o') if due_to_ironpython_incompatibility( "IronPython cannot use pyc files"): os.unlink(filename)
def test_module_with_large_stack(self, module='longlist'): # Regression test for http://bugs.python.org/issue561858. filename = module + os.extsep + 'py' # Create a file with a list of 65000 elements. with open(filename, 'w+') as f: f.write('d = [\n') for i in range(65000): f.write('"",\n') f.write(']') # Compile & remove .py file, we only need .pyc (or .pyo). if not due_to_ironpython_incompatibility("IronPython cannot use pyc files"): with open(filename, 'r') as f: py_compile.compile(filename) unlink(filename) # Need to be able to load from current dir. sys.path.append('') # This used to crash. exec 'import ' + module # Cleanup. del sys.path[-1] unlink(filename + 'c') unlink(filename + 'o') if due_to_ironpython_incompatibility("IronPython cannot use pyc files"): os.unlink(filename)
def test_genrandbits(self): # Verify cross-platform repeatability self.gen.seed(1234567) if not test_support.due_to_ironpython_incompatibility("http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=318984"): self.assertEqual(self.gen.getrandbits(100), 97904845777343510404718956115L) # Verify ranges for k in xrange(1, 1000): if not test_support.due_to_ironpython_incompatibility("http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=318984"): self.assertTrue(0 <= self.gen.getrandbits(k) < 2**k) # Verify all bits active getbits = self.gen.getrandbits for span in [1, 2, 3, 4, 31, 32, 32, 52, 53, 54, 119, 127, 128, 129]: cum = 0 for i in xrange(100): cum |= getbits(span) if not test_support.due_to_ironpython_incompatibility("http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=318984"): self.assertEqual(cum, 2**span-1) # Verify argument checking self.assertRaises(TypeError, self.gen.getrandbits) self.assertRaises(TypeError, self.gen.getrandbits, 'a') self.assertRaises(TypeError, self.gen.getrandbits, 1, 2) self.assertRaises(ValueError, self.gen.getrandbits, 0) self.assertRaises(ValueError, self.gen.getrandbits, -1)
def check_getitem_with_type(self, tp): item = self.getitem_type b = tp(self._source) if not test_support.due_to_ironpython_incompatibility( 'http://ironpython.codeplex.com/workitem/17460'): oldrefcount = sys.getrefcount(b) m = self._view(b) self.assertEquals(m[0], item(b"a")) self.assertIsInstance(m[0], bytes) self.assertEquals(m[5], item(b"f")) self.assertEquals(m[-1], item(b"f")) self.assertEquals(m[-6], item(b"a")) # Bounds checking self.assertRaises(IndexError, lambda: m[6]) self.assertRaises(IndexError, lambda: m[-7]) self.assertRaises(IndexError, lambda: m[sys.maxsize]) self.assertRaises(IndexError, lambda: m[-sys.maxsize]) # Type checking self.assertRaises(TypeError, lambda: m[None]) self.assertRaises(TypeError, lambda: m[0.0]) self.assertRaises(TypeError, lambda: m["a"]) m = None if not test_support.due_to_ironpython_incompatibility( 'http://ironpython.codeplex.com/workitem/17460'): self.assertEquals(sys.getrefcount(b), oldrefcount)
def test_isinstance_recursion_limit(self): # IronPython's recursion limit is way higher if test_support.due_to_ironpython_incompatibility("http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=317855"): reclimit = sys.getrecursionlimit() sys.setrecursionlimit(1000) # make sure that issubclass raises RuntimeError before the C stack is # blown self.assertRaises(RuntimeError, blowstack, isinstance, '', str) if test_support.due_to_ironpython_incompatibility("http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=317855"): sys.setrecursionlimit(reclimit)
def setUp(self): self.test_dir = tempfile.mkdtemp() sys.path.append(self.test_dir) self.package_dir = os.path.join(self.test_dir, self.package_name) os.mkdir(self.package_dir) if not due_to_ironpython_incompatibility("need to close file explicitly"): open(os.path.join(self.package_dir, '__init__'+os.extsep+'py'), 'w') else: f = open(os.path.join(self.package_dir, '__init__'+os.extsep+'py'), 'w') self.module_path = os.path.join(self.package_dir, 'foo'+os.extsep+'py') if due_to_ironpython_incompatibility("need to close file explicitly"): f.close()
def check_gc_during_creation(self, makeref): thresholds = gc.get_threshold() gc.set_threshold(1, 1, 1) gc.collect() class A: pass def callback(*args): pass referenced = A() a = A() a.a = a a.wr = makeref(referenced) try: # now make sure the object and the ref get labeled as # cyclic trash: a = A() weakref.ref(referenced, callback) if test_support.due_to_ironpython_incompatibility(): keepalive(referenced) finally: gc.set_threshold(*thresholds)
def test_file_opening_hook(self): try: # cannot use openhook and inplace mode fi = FileInput(inplace=1, openhook=lambda f,m: None) self.fail("FileInput should raise if both inplace " "and openhook arguments are given") except ValueError: pass try: fi = FileInput(openhook=1) self.fail("FileInput should check openhook for being callable") except ValueError: pass if due_to_ironpython_incompatibility("functionality in cpython site.py"): # without it, lookup('rot13') will fail due to lack of search functions # which was registered in encodings\__init__.py import encodings if not due_to_ironpython_bug('http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=148925'): try: t1 = writeTmp(1, ["A\nB"], mode="wb") fi = FileInput(files=t1, openhook=hook_encoded("rot13")) lines = list(fi) self.assertEqual(lines, ["N\n", "O"]) finally: remove_tempfiles(t1)
def test_unicode(self): if not test_support.due_to_ironpython_incompatibility("IronPython can not tell the difference btw unicode and str"): self.assertRaises(TypeError, array.array, 'b', unicode('foo', 'ascii')) else: self.assertEqual(array.array('b', unicode('foo', 'ascii')), array.array('b', [102, 111, 111])) a = array.array('u', unicode(r'\xa0\xc2\u1234', 'unicode-escape')) a.fromunicode(unicode(' ', 'ascii')) a.fromunicode(unicode('', 'ascii')) a.fromunicode(unicode('', 'ascii')) a.fromunicode(unicode(r'\x11abc\xff\u1234', 'unicode-escape')) s = a.tounicode() self.assertEqual( s, unicode(r'\xa0\xc2\u1234 \x11abc\xff\u1234', 'unicode-escape') ) s = unicode(r'\x00="\'a\\b\x80\xff\u0000\u0001\u1234', 'unicode-escape') a = array.array('u', s) self.assertEqual( repr(a), r"""array('u', u'\x00="\'a\\b\x80\xff\x00\x01\u1234')""" ) self.assertRaises(TypeError, a.fromunicode)
def test_repr(self): l0 = [] l2 = [0, 1, 2] a0 = self.type2test(l0) a2 = self.type2test(l2) self.assertEqual(str(a0), str(l0)) self.assertEqual(repr(a0), repr(l0)) self.assertEqual(repr(a2), repr(l2)) self.assertEqual(str(a2), "[0, 1, 2]") self.assertEqual(repr(a2), "[0, 1, 2]") a2.append(a2) a2.append(3) self.assertEqual(str(a2), "[0, 1, 2, [...], 3]") self.assertEqual(repr(a2), "[0, 1, 2, [...], 3]") # IronPython recursion limit is way higher and results in an overflow. If # sys.setrecursionlimit is used to lower it, RuntimeError is still not raised below. if test_support.due_to_ironpython_incompatibility("http://www.codeplex.com/IronPython/WorkItem/View.aspx?WorkItemId=21116"): return l0 = [] for i in xrange(sys.getrecursionlimit() + 100): l0 = [l0] self.assertRaises(RuntimeError, repr, l0)
def test_main(): from doctest import DocFileSuite suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(MathTests)) if not due_to_ironpython_incompatibility("http://www.codeplex.com/IronPython/WorkItem/View.aspx?WorkItemId=21116"): suite.addTest(DocFileSuite("ieee754.txt")) run_unittest(suite)
def test_bug1055820b(self): if test_support.due_to_ironpython_incompatibility( "http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=314470" ): return # Corresponds to temp2b.py in the bug report. ouch = [] def callback(ignored): ouch[:] = [wr() for wr in WRs] Cs = [C1055820(i) for i in range(2)] WRs = [weakref.ref(c, callback) for c in Cs] c = None gc.collect() self.assertEqual(len(ouch), 0) # Make the two instances trash, and collect again. The bug was that # the callback materialized a strong reference to an instance, but gc # cleared the instance's dict anyway. Cs = None gc.collect() self.assertEqual(len(ouch), 2) # else the callbacks didn't run for x in ouch: # If the callback resurrected one of these guys, the instance # would be damaged, with an empty __dict__. self.assertEqual(x, None)
def test_is_tracked(self): if test_support.due_to_ironpython_incompatibility("http://ironpython.codeplex.com/workitem/17458"): return # Atomic built-in types are not tracked, user-defined objects and # mutable containers are. # NOTE: types with special optimizations (e.g. tuple) have tests # in their own test files instead. self.assertFalse(gc.is_tracked(None)) self.assertFalse(gc.is_tracked(1)) self.assertFalse(gc.is_tracked(1.0)) self.assertFalse(gc.is_tracked(1.0 + 5.0j)) self.assertFalse(gc.is_tracked(True)) self.assertFalse(gc.is_tracked(False)) self.assertFalse(gc.is_tracked("a")) self.assertFalse(gc.is_tracked(u"a")) self.assertFalse(gc.is_tracked(bytearray("a"))) self.assertFalse(gc.is_tracked(type)) self.assertFalse(gc.is_tracked(int)) self.assertFalse(gc.is_tracked(object)) self.assertFalse(gc.is_tracked(object())) class OldStyle: pass class NewStyle(object): pass self.assertTrue(gc.is_tracked(gc)) self.assertTrue(gc.is_tracked(OldStyle)) self.assertTrue(gc.is_tracked(OldStyle())) self.assertTrue(gc.is_tracked(NewStyle)) self.assertTrue(gc.is_tracked(NewStyle())) self.assertTrue(gc.is_tracked([])) self.assertTrue(gc.is_tracked(set()))
def test_get_referents(self): if test_support.due_to_ironpython_incompatibility( "http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=314470" ): return alist = [1, 3, 5] got = gc.get_referents(alist) got.sort() self.assertEqual(got, alist) atuple = tuple(alist) got = gc.get_referents(atuple) got.sort() self.assertEqual(got, alist) adict = {1: 3, 5: 7} expected = [1, 3, 5, 7] got = gc.get_referents(adict) got.sort() self.assertEqual(got, expected) got = gc.get_referents([1, 2], {3: 4}, (0, 0, 0)) got.sort() self.assertEqual(got, [0, 0] + range(5)) self.assertEqual(gc.get_referents(1, "a", 4j), [])
def test_referenceImplementation(self): # Compare the python implementation with results from the original # code. Create 2000 53-bit precision random floats. Compare only # the last ten entries to show that the independent implementations # are tracking. Here is the main() function needed to create the # list of expected random numbers: # void main(void){ # int i; # unsigned long init[4]={61731, 24903, 614, 42143}, length=4; # init_by_array(init, length); # for (i=0; i<2000; i++) { # printf("%.15f ", genrand_res53()); # if (i%5==4) printf("\n"); # } # } expected = [ 0.45839803073713259, 0.86057815201978782, 0.92848331726782152, 0.35932681119782461, 0.081823493762449573, 0.14332226470169329, 0.084297823823520024, 0.53814864671831453, 0.089215024911993401, 0.78486196105372907 ] self.gen.seed(61731L + (24903L << 32) + (614L << 64) + (42143L << 96)) actual = self.randomlist(2000)[-10:] for a, e in zip(actual, expected): if not test_support.due_to_ironpython_incompatibility( "http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=318984" ): self.assertAlmostEqual(a, e, places=14)
def test_saveall(self): if test_support.due_to_ironpython_incompatibility( "http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=314470" ): return # Verify that cyclic garbage like lists show up in gc.garbage if the # SAVEALL option is enabled. # First make sure we don't save away other stuff that just happens to # be waiting for collection. gc.collect() # if this fails, someone else created immortal trash self.assertEqual(gc.garbage, []) L = [] L.append(L) id_L = id(L) debug = gc.get_debug() gc.set_debug(debug | gc.DEBUG_SAVEALL) del L gc.collect() gc.set_debug(debug) self.assertEqual(len(gc.garbage), 1) obj = gc.garbage.pop() self.assertEqual(id(obj), id_L)
def test_chunked(self): chunked_start = ( 'HTTP/1.1 200 OK\r\n' 'Transfer-Encoding: chunked\r\n\r\n' 'a\r\n' 'hello worl\r\n' '1\r\n' 'd\r\n' ) sock = FakeSocket(chunked_start + '0\r\n') resp = httplib.HTTPResponse(sock, method="GET") resp.begin() self.assertEquals(resp.read(), 'hello world') resp.close() for x in ('', 'foo\r\n'): sock = FakeSocket(chunked_start + x) resp = httplib.HTTPResponse(sock, method="GET") resp.begin() try: resp.read() except httplib.IncompleteRead, i: self.assertEquals(i.partial, 'hello world') if not test_support.due_to_ironpython_incompatibility("http://www.codeplex.com/IronPython/WorkItem/View.aspx?WorkItemId=21116"): self.assertEqual(repr(i),'IncompleteRead(11 bytes read)') self.assertEqual(str(i),'IncompleteRead(11 bytes read)') else: self.fail('IncompleteRead expected') finally:
def test_basic_proxy(self): o = C() self.check_proxy(o, weakref.proxy(o)) L = UserList.UserList() p = weakref.proxy(L) self.assertFalse(p, "proxy for empty UserList should be false") p.append(12) self.assertEqual(len(L), 1) self.assertTrue(p, "proxy for non-empty UserList should be true") with test_support.check_py3k_warnings(): p[:] = [2, 3] self.assertEqual(len(L), 2) self.assertEqual(len(p), 2) self.assertIn(3, p, "proxy didn't support __contains__() properly") p[1] = 5 self.assertEqual(L[1], 5) self.assertEqual(p[1], 5) L2 = UserList.UserList(L) p2 = weakref.proxy(L2) self.assertEqual(p, p2) ## self.assertEqual(repr(L2), repr(p2)) L3 = UserList.UserList(range(10)) p3 = weakref.proxy(L3) with test_support.check_py3k_warnings(): self.assertEqual(L3[:], p3[:]) self.assertEqual(L3[5:], p3[5:]) self.assertEqual(L3[:5], p3[:5]) self.assertEqual(L3[2:5], p3[2:5]) if test_support.due_to_ironpython_incompatibility(): keepalive(L, L2, L3)
def test_len(self): if test_support.due_to_ironpython_incompatibility( "implementation detail"): return # This is an implementation detail, not an interface requirement from test.test_iterlen import len for s in ('hello', tuple('hello'), list('hello'), xrange(5)): self.assertEqual(len(reversed(s)), len(s)) r = reversed(s) list(r) self.assertEqual(len(r), 0) class SeqWithWeirdLen: called = False def __len__(self): if not self.called: self.called = True return 10 raise ZeroDivisionError def __getitem__(self, index): return index r = reversed(SeqWithWeirdLen()) self.assertRaises(ZeroDivisionError, len, r)
def test_from_regex(self): # Testing new regex from bug #1633678 f = open(self._path, 'w') f.write("""From [email protected] Mon May 31 13:24:50 2004 +0200 Subject: message 1 body1 From [email protected] Mon May 31 13:24:50 2004 -0200 Subject: message 2 body2 From [email protected] Mon May 31 13:24:50 2004 Subject: message 3 body3 From [email protected] Mon May 31 13:24:50 2004 Subject: message 4 body4 """) f.close() if test_support.due_to_ironpython_incompatibility( "http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=321793" ): with open(self._path, 'r') as f: box = mailbox.UnixMailbox(f) self.assert_(len(list(iter(box))) == 4) else: box = mailbox.UnixMailbox(open(self._path, 'r')) self.assertTrue(len(list(iter(box))) == 4)
def test_weak_keyed_iters(self): dict, objects = self.make_weak_keyed_dict() self.check_iters(dict) # Test keyrefs() refs = dict.keyrefs() self.assertEqual(len(refs), len(objects)) objects2 = list(objects) for wr in refs: ob = wr() self.assertIn(ob, dict) self.assertEqual(ob.arg, dict[ob]) objects2.remove(ob) self.assertEqual(len(objects2), 0) # Test iterkeyrefs() objects2 = list(objects) self.assertEqual(len(list(dict.iterkeyrefs())), len(objects)) for wr in dict.iterkeyrefs(): ob = wr() self.assertIn(ob, dict) self.assertEqual(ob.arg, dict[ob]) objects2.remove(ob) self.assertEqual(len(objects2), 0) if test_support.due_to_ironpython_incompatibility(): keepalive(objects)
def test_get_referents(self): if test_support.due_to_ironpython_incompatibility( "http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=314470" ): return alist = [1, 3, 5] got = gc.get_referents(alist) got.sort() self.assertEqual(got, alist) atuple = tuple(alist) got = gc.get_referents(atuple) got.sort() self.assertEqual(got, alist) adict = {1: 3, 5: 7} expected = [1, 3, 5, 7] got = gc.get_referents(adict) got.sort() self.assertEqual(got, expected) got = gc.get_referents([1, 2], {3: 4}, (0, 0, 0)) got.sort() self.assertEqual(got, [0, 0] + range(5)) self.assertEqual(gc.get_referents(1, 'a', 4j), [])
def _check_relative_imports(self, depth, run_name=None): contents = r"""\ from __future__ import absolute_import from . import sibling from ..uncle.cousin import nephew """ pkg_dir, mod_fname, mod_name = ( self._make_pkg(contents, depth)) try: self._add_relative_modules(pkg_dir, contents, depth) pkg_name = mod_name.rpartition('.')[0] if verbose: print "Running from source:", mod_name d1 = run_module(mod_name, run_name=run_name) # Read from source self.assertIn("__package__", d1) self.assertTrue(d1["__package__"] == pkg_name) self.assertIn("sibling", d1) self.assertIn("nephew", d1) del d1 # Ensure __loader__ entry doesn't keep file open __import__(mod_name) os.remove(mod_fname) if not due_to_ironpython_incompatibility("IPy can't load modules from bytecode"): if verbose: print "Running from compiled:", mod_name d2 = run_module(mod_name, run_name=run_name) # Read from bytecode self.assertIn("__package__", d2) self.assertTrue(d2["__package__"] == pkg_name) self.assertIn("sibling", d2) self.assertIn("nephew", d2) del d2 # Ensure __loader__ entry doesn't keep file open finally: self._del_pkg(pkg_dir, depth, mod_name) if verbose: print "Module executed successfully"
def test_tuple_reuse(self): if test_support.due_to_ironpython_incompatibility("implementation detail: http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=20279"): return # Tests an implementation detail where tuple is reused # whenever nothing else holds a reference to it self.assertEqual(len(set(map(id, list(enumerate(self.seq))))), len(self.seq)) self.assertEqual(len(set(map(id, enumerate(self.seq)))), min(1,len(self.seq)))
def test_bug1055820b(self): if test_support.due_to_ironpython_incompatibility("http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=314470"): return # Corresponds to temp2b.py in the bug report. ouch = [] def callback(ignored): ouch[:] = [wr() for wr in WRs] Cs = [C1055820(i) for i in range(2)] WRs = [weakref.ref(c, callback) for c in Cs] c = None gc.collect() self.assertEqual(len(ouch), 0) # Make the two instances trash, and collect again. The bug was that # the callback materialized a strong reference to an instance, but gc # cleared the instance's dict anyway. Cs = None gc.collect() self.assertEqual(len(ouch), 2) # else the callbacks didn't run for x in ouch: # If the callback resurrected one of these guys, the instance # would be damaged, with an empty __dict__. self.assertEqual(x, None)
def test_from_regex (self): # Testing new regex from bug #1633678 f = open(self._path, 'w') f.write("""From [email protected] Mon May 31 13:24:50 2004 +0200 Subject: message 1 body1 From [email protected] Mon May 31 13:24:50 2004 -0200 Subject: message 2 body2 From [email protected] Mon May 31 13:24:50 2004 Subject: message 3 body3 From [email protected] Mon May 31 13:24:50 2004 Subject: message 4 body4 """) f.close() if test_support.due_to_ironpython_incompatibility("http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=321793"): with open(self._path, 'r') as f: box = mailbox.UnixMailbox(f) self.assert_(len(list(iter(box))) == 4) else: box = mailbox.UnixMailbox(open(self._path, 'r')) self.assertTrue(len(list(iter(box))) == 4)
def test_builtin(self): # str != bytes in IronPython if test_support.due_to_ironpython_incompatibility( "http://www.codeplex.com/IronPython/WorkItem/View.aspx?WorkItemId=21116" ): return self.assertTrue(str is bytes)
def test_unicode(self): if not test_support.due_to_ironpython_incompatibility( "IronPython can not tell the difference btw unicode and str" ): self.assertRaises(TypeError, array.array, 'b', unicode('foo', 'ascii')) else: self.assertEqual(array.array('b', unicode('foo', 'ascii')), array.array('b', [102, 111, 111])) a = array.array('u', unicode(r'\xa0\xc2\u1234', 'unicode-escape')) a.fromunicode(unicode(' ', 'ascii')) a.fromunicode(unicode('', 'ascii')) a.fromunicode(unicode('', 'ascii')) a.fromunicode(unicode(r'\x11abc\xff\u1234', 'unicode-escape')) s = a.tounicode() self.assertEqual( s, unicode(r'\xa0\xc2\u1234 \x11abc\xff\u1234', 'unicode-escape')) s = unicode(r'\x00="\'a\\b\x80\xff\u0000\u0001\u1234', 'unicode-escape') a = array.array('u', s) self.assertEqual( repr(a), r"""array('u', u'\x00="\'a\\b\x80\xff\x00\x01\u1234')""") self.assertRaises(TypeError, a.fromunicode)
def testImpWrapper(self): i = ImpWrapper() sys.meta_path.append(i) sys.path_hooks.append(ImpWrapper) mnames = ("colorsys", "urlparse", "distutils.core", "compiler.misc") if test_support.due_to_ironpython_incompatibility( "compiler.misc depends on the 'parser' builtin module"): mnames = tuple([x for x in mnames if x != "compiler.misc"]) for mname in mnames: parent = mname.split(".")[0] for n in sys.modules.keys(): if n.startswith(parent): del sys.modules[n] if test_support.due_to_ironpython_bug( "http://ironpython.codeplex.com/workitem/28171"): for mname in mnames: m = __import__(mname, globals(), locals(), ["__dummy__"]) m.__loader__ # to make sure we actually handled the import else: with test_support.check_warnings( ("The compiler package is deprecated " "and removed", DeprecationWarning)): for mname in mnames: m = __import__(mname, globals(), locals(), ["__dummy__"]) m.__loader__ # to make sure we actually handled the import
def test_saveall(self): if test_support.due_to_ironpython_incompatibility("http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=314470"): return # Verify that cyclic garbage like lists show up in gc.garbage if the # SAVEALL option is enabled. # First make sure we don't save away other stuff that just happens to # be waiting for collection. gc.collect() # if this fails, someone else created immortal trash self.assertEqual(gc.garbage, []) L = [] L.append(L) id_L = id(L) debug = gc.get_debug() gc.set_debug(debug | gc.DEBUG_SAVEALL) del L gc.collect() gc.set_debug(debug) self.assertEqual(len(gc.garbage), 1) obj = gc.garbage.pop() self.assertEqual(id(obj), id_L)
def test_extended_arg(self): if "debug" in sys.version.lower() and test_support.due_to_ironpython_incompatibility( "http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=320062" ): # this test fails on debug builds of IronPython because # we use too much stack space but passes on release builds return longexpr = "x = x or " + "-x" * 2500 code = """ def f(x): %s %s %s %s %s %s %s %s %s %s # the expressions above have no effect, x == argument while x: x -= 1 # EXTENDED_ARG/JUMP_ABSOLUTE here return x """ % ( (longexpr,) * 10 ) exec code self.assertEqual(f(5), 0)
def test_chunked(self): chunked_start = ('HTTP/1.1 200 OK\r\n' 'Transfer-Encoding: chunked\r\n\r\n' 'a\r\n' 'hello worl\r\n' '1\r\n' 'd\r\n') sock = FakeSocket(chunked_start + '0\r\n') resp = httplib.HTTPResponse(sock, method="GET") resp.begin() self.assertEquals(resp.read(), 'hello world') resp.close() for x in ('', 'foo\r\n'): sock = FakeSocket(chunked_start + x) resp = httplib.HTTPResponse(sock, method="GET") resp.begin() try: resp.read() except httplib.IncompleteRead, i: self.assertEquals(i.partial, 'hello world') if not test_support.due_to_ironpython_incompatibility( "http://www.codeplex.com/IronPython/WorkItem/View.aspx?WorkItemId=21116" ): self.assertEqual(repr(i), 'IncompleteRead(11 bytes read)') self.assertEqual(str(i), 'IncompleteRead(11 bytes read)') else: self.fail('IncompleteRead expected') finally:
def test_referenceImplementation(self): # Compare the python implementation with results from the original # code. Create 2000 53-bit precision random floats. Compare only # the last ten entries to show that the independent implementations # are tracking. Here is the main() function needed to create the # list of expected random numbers: # void main(void){ # int i; # unsigned long init[4]={61731, 24903, 614, 42143}, length=4; # init_by_array(init, length); # for (i=0; i<2000; i++) { # printf("%.15f ", genrand_res53()); # if (i%5==4) printf("\n"); # } # } expected = [0.45839803073713259, 0.86057815201978782, 0.92848331726782152, 0.35932681119782461, 0.081823493762449573, 0.14332226470169329, 0.084297823823520024, 0.53814864671831453, 0.089215024911993401, 0.78486196105372907] self.gen.seed(61731L + (24903L<<32) + (614L<<64) + (42143L<<96)) actual = self.randomlist(2000)[-10:] for a, e in zip(actual, expected): if not test_support.due_to_ironpython_incompatibility("http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=318984"): self.assertAlmostEqual(a,e,places=14)
def test_extended_arg(self): if 'debug' in sys.version.lower( ) and test_support.due_to_ironpython_incompatibility( "http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=320062" ): # this test fails on debug builds of IronPython because # we use too much stack space but passes on release builds return longexpr = 'x = x or ' + '-x' * 2500 code = ''' def f(x): %s %s %s %s %s %s %s %s %s %s # the expressions above have no effect, x == argument while x: x -= 1 # EXTENDED_ARG/JUMP_ABSOLUTE here return x ''' % ((longexpr, ) * 10) exec code self.assertEqual(f(5), 0)
def test_weak_valued_iters(self): dict, objects = self.make_weak_valued_dict() self.check_iters(dict) # Test valuerefs() refs = dict.valuerefs() self.assertEqual(len(refs), len(objects)) objects2 = list(objects) for wr in refs: ob = wr() self.assertEqual(ob, dict[ob.arg]) self.assertEqual(ob.arg, dict[ob.arg].arg) objects2.remove(ob) self.assertEqual(len(objects2), 0) # Test itervaluerefs() objects2 = list(objects) self.assertEqual(len(list(dict.itervaluerefs())), len(objects)) for wr in dict.itervaluerefs(): ob = wr() self.assertEqual(ob, dict[ob.arg]) self.assertEqual(ob.arg, dict[ob.arg].arg) objects2.remove(ob) self.assertEqual(len(objects2), 0) if test_support.due_to_ironpython_incompatibility(): keepalive(objects)
def test_setitem_writable(self): if not self.rw_type: return tp = self.rw_type b = self.rw_type(self._source) if not test_support.due_to_ironpython_incompatibility( 'http://ironpython.codeplex.com/workitem/17460'): oldrefcount = sys.getrefcount(b) m = self._view(b) m[0] = tp(b"0") self._check_contents(tp, b, b"0bcdef") m[1:3] = tp(b"12") self._check_contents(tp, b, b"012def") m[1:1] = tp(b"") self._check_contents(tp, b, b"012def") m[:] = tp(b"abcdef") self._check_contents(tp, b, b"abcdef") # Overlapping copies of a view into itself m[0:3] = m[2:5] self._check_contents(tp, b, b"cdedef") m[:] = tp(b"abcdef") m[2:5] = m[0:3] self._check_contents(tp, b, b"ababcf") def setitem(key, value): m[key] = tp(value) # Bounds checking self.assertRaises(IndexError, setitem, 6, b"a") self.assertRaises(IndexError, setitem, -7, b"a") self.assertRaises(IndexError, setitem, sys.maxsize, b"a") self.assertRaises(IndexError, setitem, -sys.maxsize, b"a") # Wrong index/slice types self.assertRaises(TypeError, setitem, 0.0, b"a") self.assertRaises(TypeError, setitem, (0, ), b"a") self.assertRaises(TypeError, setitem, "a", b"a") # Trying to resize the memory object self.assertRaises(ValueError, setitem, 0, b"") self.assertRaises(ValueError, setitem, 0, b"ab") self.assertRaises(ValueError, setitem, slice(1, 1), b"a") self.assertRaises(ValueError, setitem, slice(0, 2), b"a") m = None if not test_support.due_to_ironpython_incompatibility( 'http://ironpython.codeplex.com/workitem/17460'): self.assertEquals(sys.getrefcount(b), oldrefcount)
class BinASCIITest(unittest.TestCase): type2test = str # Create binary test data rawdata = "The quick brown fox jumps over the lazy dog.\r\n" # Be slow so we don't depend on other modules rawdata += "".join(map(chr, xrange(256))) rawdata += "\r\nHello world.\n" if test_support.due_to_ironpython_incompatibility("bytes/str/unicode"): rawdata = bytes(rawdata) def setUp(self): self.data = self.type2test(self.rawdata) def test_exceptions(self): # Check module exceptions self.assertTrue(issubclass(binascii.Error, Exception)) self.assertTrue(issubclass(binascii.Incomplete, Exception)) def test_functions(self): # Check presence of all functions for name in all_functions: self.assertTrue(hasattr(getattr(binascii, name), '__call__')) self.assertRaises(TypeError, getattr(binascii, name)) def test_returned_value(self): # Limit to the minimum of all limits (b2a_uu) if self.type2test is not str and test_support.due_to_ironpython_bug( "http://ironpython.codeplex.com/workitem/28171"): return MAX_ALL = 45 raw = self.rawdata[:MAX_ALL] for fa, fb in zip(a2b_functions, b2a_functions): a2b = getattr(binascii, fa) b2a = getattr(binascii, fb) try: if test_support.due_to_ironpython_bug( "http://ironpython.codeplex.com/workitem/28171"): if 'hqx' in fa or 'qp' in fa: continue a = b2a(self.type2test(raw)) res = a2b(self.type2test(a)) except Exception, err: self.fail("{}/{} conversion raises {!r}".format(fb, fa, err)) if fb == 'b2a_hqx': # b2a_hqx returns a tuple res, _ = res self.assertEqual( res, raw, "{}/{} conversion: " "{!r} != {!r}".format(fb, fa, res, raw)) self.assertIsInstance(res, str) self.assertIsInstance(a, str) self.assertLess(max(ord(c) for c in a), 128) if test_support.due_to_ironpython_bug( "http://ironpython.codeplex.com/workitem/28171"): raw = str(raw) else: self.assertIsInstance(binascii.crc_hqx(raw, 0), int) self.assertIsInstance(binascii.crc32(raw), int)
def test_formatting(self): string_tests.MixinStrUnicodeUserStringTest.test_formatting(self) # this test expects an unsigned byte integer value but in the managed # world chars are 2 bytes and so 0x1234 is valid for conversion; this # needs to be reconciled when work is done to beef up the formatting # codepath if not test_support.due_to_ironpython_incompatibility('char implementation'): self.assertRaises(OverflowError, '%c'.__mod__, 0x1234)
class CodeTestCase(unittest.TestCase): if not test_support.due_to_ironpython_incompatibility( "do we really want to fully support func_code?"): def test_code(self): co = ExceptionTestCase.test_exceptions.func_code new = marshal.loads(marshal.dumps(co)) self.assertEqual(co, new)
def setUp(self): data = self.DATA if "b" in self.WRITEMODE: data = data.encode("ascii") if support.due_to_ironpython_incompatibility("unicode/str/bytes"): data = bytes(data) with self.open(support.TESTFN, self.WRITEMODE) as fp: fp.write(data)
def test_unicode(self): if support.due_to_ironpython_incompatibility("IronPython supports byte operations on unicode strings"): return memio = self.ioclass() self.assertRaises(TypeError, self.ioclass, "1234567890") self.assertRaises(TypeError, memio.write, "1234567890") self.assertRaises(TypeError, memio.writelines, ["1234567890"])
def test_newstyle_number_ops(self): class F(float): pass f = F(2.0) p = weakref.proxy(f) self.assertTrue(p + 1.0 == 3.0) self.assertTrue(1.0 + p == 3.0) # this used to SEGV if test_support.due_to_ironpython_incompatibility(): keepalive(f)
def test_context_manager(self): # A NamedTemporaryFile can be used as a context manager with tempfile.NamedTemporaryFile() as f: self.assertTrue(os.path.exists(f.name)) if not test_support.due_to_ironpython_incompatibility("http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=370828"): self.assertFalse(os.path.exists(f.name)) def use_closed(): with f: pass self.assertRaises(ValueError, use_closed)
def test_key_with_mutating_del(self): data = range(10) class SortKiller(object): def __init__(self, x): pass def __del__(self): del data[:] data[:] = range(20) if not test_support.due_to_ironpython_incompatibility('__del__ related behavior'): self.assertRaises(ValueError, data.sort, key=SortKiller)
def test_choose_directory(self): # _mkstemp_inner can create files in a user-selected directory dir = tempfile.mkdtemp() try: f = self.do_create(dir=dir) f.write("blat") if test_support.due_to_ironpython_incompatibility("http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=370828"): f.__del__() else: del f finally: os.rmdir(dir)
def testSFBug532646(self): # Test for SF bug 532646 class A: pass A.__call__ = A() a = A() if test_support.due_to_ironpython_incompatibility("-X:MaxRecursion"): import sys temp_recursion = sys.getrecursionlimit() sys.setrecursionlimit(100) try: a() # This should not segfault except RuntimeError: pass else: self.fail("Failed to raise RuntimeError") if test_support.due_to_ironpython_incompatibility("-X:MaxRecursion"): sys.setrecursionlimit(temp_recursion)
def test_get_count(self): if test_support.due_to_ironpython_incompatibility( "http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=314470" ): return # Avoid future allocation of method object assertEqual = self._baseAssertEqual gc.collect() assertEqual(gc.get_count(), (0, 0, 0)) a = dict() # since gc.collect(), we created two objects: # the dict, and the tuple returned by get_count() assertEqual(gc.get_count(), (2, 0, 0))