Example #1
0
    def testTwoResults(self):
        if due_to_ironpython_bug("http://ironpython.codeplex.com/workitem/28171"):
            return

        unittest.installHandler()

        result = unittest.TestResult()
        unittest.registerResult(result)
        new_handler = signal.getsignal(signal.SIGINT)

        result2 = unittest.TestResult()
        unittest.registerResult(result2)
        self.assertEqual(signal.getsignal(signal.SIGINT), new_handler)

        result3 = unittest.TestResult()

        def test(result):
            pid = os.getpid()
            os.kill(pid, signal.SIGINT)

        try:
            test(result)
        except KeyboardInterrupt:
            self.fail("KeyboardInterrupt not handled")

        if not due_to_ironpython_bug("http://ironpython.codeplex.com/workitem/28171"):
            self.assertTrue(result.shouldStop)
            self.assertTrue(result2.shouldStop)
        self.assertFalse(result3.shouldStop)
Example #2
0
def test_main():
    import ctypes.test

    skipped, testcases = ctypes.test.get_tests(ctypes.test, "test_*.py", verbosity=0)
    suites = [unittest.makeSuite(t) for t in testcases]

    if due_to_ironpython_bug("http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=374"):
        for suite in suites:
            length = len(suite._tests)
            i = 0
            while i < length:
                if suite._tests[i].id() in IRONPYTHON_DISABLED_LIST:
                    suite._tests.pop(i)
                    i -= 1
                    length -= 1
                i += 1

    try:
        run_unittest(unittest.TestSuite(suites))
    finally:
        if due_to_ironpython_bug("http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=22393"):
            try:
                System.IO.File.Delete(nt.getcwd() + r"\Python26.dll")
            except:
                pass
            print "%d of these test cases were disabled under IronPython." % len(IRONPYTHON_DISABLED_LIST)
Example #3
0
    def test_format_auto_numbering(self):
        class C:
            def __init__(self, x=100):
                self._x = x
            def __format__(self, spec):
                return spec

        self.assertEqual('{}'.format(10), '10')
        self.assertEqual('{:5}'.format('s'), 's    ')
        self.assertEqual('{!r}'.format('s'), "'s'")
        self.assertEqual('{._x}'.format(C(10)), '10')
        self.assertEqual('{[1]}'.format([1, 2]), '2')
        self.assertEqual('{[a]}'.format({'a':4, 'b':2}), '4')
        self.assertEqual('a{}b{}c'.format(0, 1), 'a0b1c')

        if not test_support.due_to_ironpython_bug("http://ironpython.codeplex.com/workitem/28171"):
            self.assertEqual('a{:{}}b'.format('x', '^10'), 'a    x     b')
            self.assertEqual('a{:{}x}b'.format(20, '#'), 'a0x14b')

        # can't mix and match numbering and auto-numbering
        self.assertRaises(ValueError, '{}{1}'.format, 1, 2)
        self.assertRaises(ValueError, '{1}{}'.format, 1, 2)
        if not test_support.due_to_ironpython_bug("http://ironpython.codeplex.com/workitem/28171"):
            self.assertRaises(ValueError, '{:{1}}'.format, 1, 2)
            self.assertRaises(ValueError, '{0:{}}'.format, 1, 2)

        # can mix and match auto-numbering and named
        self.assertEqual('{f}{}'.format(4, f='test'), 'test4')
        self.assertEqual('{}{f}'.format(4, f='test'), '4test')
        self.assertEqual('{:{f}}{g}{}'.format(1, 3, g='g', f=2), ' 1g3')
        if not test_support.due_to_ironpython_bug("http://ironpython.codeplex.com/workitem/28171"):
            self.assertEqual('{f:{}}{}{g}'.format(2, 4, f=1, g='g'), ' 14g')
Example #4
0
    def test_1(self):
        from sys import getrefcount as grc

        f = dll._testfunc_callback_i_if
        f.restype = ctypes.c_int
        f.argtypes = [ctypes.c_int, MyCallback]

        def callback(value):
            #print "called back with", value
            return value

        if not test_support.due_to_ironpython_bug("http://www.codeplex.com/IronPython/WorkItem/View.aspx?WorkItemId=22374"):
            self.assertEqual(grc(callback), 2)
        cb = MyCallback(callback)

        if not test_support.due_to_ironpython_bug("http://www.codeplex.com/IronPython/WorkItem/View.aspx?WorkItemId=22374"):
            self.assertTrue(grc(callback) > 2)
        result = f(-10, cb)
        self.assertEqual(result, -18)
        cb = None

        gc.collect()

        if not test_support.due_to_ironpython_bug("http://www.codeplex.com/IronPython/WorkItem/View.aspx?WorkItemId=22374"):
            self.assertEqual(grc(callback), 2)
Example #5
0
 def test_special_escapes(self):
     self.assertEqual(re.search(r"\b(b.)\b",
                                "abcd abc bcd bx").group(1), "bx")
     if not due_to_ironpython_bug("http://vstfdevdiv:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=306834"):
         self.assertEqual(re.search(r"\B(b.)\B",
                                    "abc bcd bc abxd").group(1), "bx")
     self.assertEqual(re.search(r"\b(b.)\b",
                                "abcd abc bcd bx", re.LOCALE).group(1), "bx")
     if not due_to_ironpython_bug("http://vstfdevdiv:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=306834"):
         self.assertEqual(re.search(r"\B(b.)\B",
                                    "abc bcd bc abxd", re.LOCALE).group(1), "bx")
     self.assertEqual(re.search(r"\b(b.)\b",
                                "abcd abc bcd bx", re.UNICODE).group(1), "bx")
     if not due_to_ironpython_bug("http://vstfdevdiv:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=306834"):
         self.assertEqual(re.search(r"\B(b.)\B",
                                    "abc bcd bc abxd", re.UNICODE).group(1), "bx")
     self.assertEqual(re.search(r"^abc$", "\nabc\n", re.M).group(0), "abc")
     self.assertEqual(re.search(r"^\Aabc\Z$", "abc", re.M).group(0), "abc")
     self.assertEqual(re.search(r"^\Aabc\Z$", "\nabc\n", re.M), None)
     self.assertEqual(re.search(r"\b(b.)\b",
                                u"abcd abc bcd bx").group(1), "bx")
     if not due_to_ironpython_bug("http://vstfdevdiv:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=306834"):
         self.assertEqual(re.search(r"\B(b.)\B",
                                    u"abc bcd bc abxd").group(1), "bx")
     self.assertEqual(re.search(r"^abc$", u"\nabc\n", re.M).group(0), "abc")
     self.assertEqual(re.search(r"^\Aabc\Z$", u"abc", re.M).group(0), "abc")
     self.assertEqual(re.search(r"^\Aabc\Z$", u"\nabc\n", re.M), None)
     self.assertEqual(re.search(r"\d\D\w\W\s\S",
                                "1aa! a").group(0), "1aa! a")
     self.assertEqual(re.search(r"\d\D\w\W\s\S",
                                "1aa! a", re.LOCALE).group(0), "1aa! a")
     self.assertEqual(re.search(r"\d\D\w\W\s\S",
                                "1aa! a", re.UNICODE).group(0), "1aa! a")
Example #6
0
 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)
Example #7
0
    def testSecondInterrupt(self):
        if due_to_ironpython_bug("http://ironpython.codeplex.com/workitem/28171"):
            return

        result = unittest.TestResult()
        unittest.installHandler()
        unittest.registerResult(result)

        def test(result):
            pid = os.getpid()
            os.kill(pid, signal.SIGINT)
            result.breakCaught = True
            if not due_to_ironpython_bug("http://ironpython.codeplex.com/workitem/28171"):
                self.assertTrue(result.shouldStop)
            os.kill(pid, signal.SIGINT)
            if not due_to_ironpython_bug("http://ironpython.codeplex.com/workitem/28171"):
                self.fail("Second KeyboardInterrupt not raised")

        try:
            test(result)
        except KeyboardInterrupt:
            pass
        else:
            if not due_to_ironpython_bug("http://ironpython.codeplex.com/workitem/28171"):
                self.fail("Second KeyboardInterrupt not raised")
        self.assertTrue(result.breakCaught)
Example #8
0
    def testGetSetAndDel(self):
        # Interfering tests
        class ExtraTests(AllTests):
            @trackCall
            def __getattr__(self, *args):
                return "SomeVal"

            @trackCall
            def __setattr__(self, *args):
                pass

            @trackCall
            def __delattr__(self, *args):
                pass

        testme = ExtraTests()

        callLst[:] = []
        testme.spam
        if not test_support.due_to_ironpython_bug("http://www.codeplex.com/IronPython/WorkItem/View.aspx?WorkItemId=21116"):
            self.assertCallStack([('__getattr__', (testme, "spam"))])

        callLst[:] = []
        testme.eggs = "spam, spam, spam and ham"
        if not test_support.due_to_ironpython_bug("http://www.codeplex.com/IronPython/WorkItem/View.aspx?WorkItemId=21116"):
            self.assertCallStack([('__setattr__', (testme, "eggs",
                                                   "spam, spam, spam and ham"))])

        callLst[:] = []
        del testme.cardinal
        if not test_support.due_to_ironpython_bug("http://www.codeplex.com/IronPython/WorkItem/View.aspx?WorkItemId=21116"):
            self.assertCallStack([('__delattr__', (testme, "cardinal"))])
Example #9
0
 def test_none_assignment(self):
     stmts = [
         "None = 0",
         "None += 0",
         "__builtins__.None = 0",
         "def None(): pass",
         "class None: pass",
         "(a, None) = 0, 0",
         "for None in range(10): pass",
         "def f(None): pass",
         "import None",
         "import x as None",
         "from x import None",
         "from x import y as None",
     ]
     for stmt in stmts:
         stmt += "\n"
         if not test_support.due_to_ironpython_bug(
             "http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=314864"
         ):
             self.assertRaises(SyntaxError, compile, stmt, "tmp", "single")
             self.assertRaises(SyntaxError, compile, stmt, "tmp", "exec")
     if test_support.due_to_ironpython_bug("http://ironpython.codeplex.com/workitem/28171"):
         return
     # This is ok.
     compile("from None import x", "tmp", "exec")
     compile("from x import None as y", "tmp", "exec")
     compile("import None as x", "tmp", "exec")
Example #10
0
    def _do_single(self, filename):
        self.assertTrue(os.path.exists(filename))
        self.assertTrue(os.path.isfile(filename))
        self.assertTrue(os.access(filename, os.R_OK))
        self.assertTrue(os.path.exists(os.path.abspath(filename)))
        self.assertTrue(os.path.isfile(os.path.abspath(filename)))
        self.assertTrue(os.access(os.path.abspath(filename), os.R_OK))
        if not test_support.due_to_ironpython_bug("http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=363042"):
            os.chmod(filename, 0777)
        os.utime(filename, None)
        os.utime(filename, (time.time(), time.time()))
        # Copy/rename etc tests using the same filename
        self._do_copyish(filename, filename)
        # Filename should appear in glob output
        self.assertTrue(
            os.path.abspath(filename)==os.path.abspath(glob.glob(filename)[0]))
        # basename should appear in listdir.
        path, base = os.path.split(os.path.abspath(filename))
        if isinstance(base, str):
            base = base.decode(TESTFN_ENCODING)
        file_list = os.listdir(path)
        # listdir() with a unicode arg may or may not return Unicode
        # objects, depending on the platform.
        if file_list and isinstance(file_list[0], str):
            file_list = [f.decode(TESTFN_ENCODING) for f in file_list]

        # Normalize the unicode strings, as round-tripping the name via the OS
        # may return a different (but equivalent) value.
        if not test_support.due_to_ironpython_bug("http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=303481"):
            base = unicodedata.normalize("NFD", base)
            file_list = [unicodedata.normalize("NFD", f) for f in file_list]

            self.assertIn(base, file_list)
Example #11
0
    def test__format__(self):
        def test(value, format, expected):
            # test both with and without the trailing 's'
            self.assertEqual(value.__format__(format), expected)
            self.assertEqual(value.__format__(format + 's'), expected)

        test('', '', '')
        test('abc', '', 'abc')
        test('abc', '.3', 'abc')
        test('ab', '.3', 'ab')
        if not test_support.due_to_ironpython_bug("http://www.codeplex.com/IronPython/WorkItem/View.aspx?WorkItemId=21116"):
            test('abcdef', '.3', 'abc')
            test('abcdef', '.0', '')
        test('abc', '3.3', 'abc')
        test('abc', '2.3', 'abc')
        if not test_support.due_to_ironpython_bug("http://www.codeplex.com/IronPython/WorkItem/View.aspx?WorkItemId=21116"):
            test('abc', '2.2', 'ab')
            test('abc', '3.2', 'ab ')
        test('result', 'x<0', 'result')
        test('result', 'x<5', 'result')
        test('result', 'x<6', 'result')
        if test_support.due_to_ironpython_bug("http://www.codeplex.com/IronPython/WorkItem/View.aspx?WorkItemId=21116"):
            return
        test('result', 'x<7', 'resultx')
        test('result', 'x<8', 'resultxx')
        test('result', ' <7', 'result ')
        test('result', '<7', 'result ')
        test('result', '>7', ' result')
        test('result', '>8', '  result')
        test('result', '^8', ' result ')
        test('result', '^9', ' result  ')
        test('result', '^10', '  result  ')
        test('a', '10000', 'a' + ' ' * 9999)
        test('', '10000', ' ' * 10000)
        test('', '10000000', ' ' * 10000000)
Example #12
0
    def test_hangul_syllables(self):
        if test_support.due_to_ironpython_bug(
            "http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=323261"
        ):
            return
        self.checkletter("HANGUL SYLLABLE GA", u"\uac00")
        self.checkletter("HANGUL SYLLABLE GGWEOSS", u"\uafe8")
        self.checkletter("HANGUL SYLLABLE DOLS", u"\ub3d0")
        self.checkletter("HANGUL SYLLABLE RYAN", u"\ub7b8")
        self.checkletter("HANGUL SYLLABLE MWIK", u"\ubba0")
        self.checkletter("HANGUL SYLLABLE BBWAEM", u"\ubf88")
        self.checkletter("HANGUL SYLLABLE SSEOL", u"\uc370")
        self.checkletter("HANGUL SYLLABLE YI", u"\uc758")
        self.checkletter("HANGUL SYLLABLE JJYOSS", u"\ucb40")
        self.checkletter("HANGUL SYLLABLE KYEOLS", u"\ucf28")
        self.checkletter("HANGUL SYLLABLE PAN", u"\ud310")
        self.checkletter("HANGUL SYLLABLE HWEOK", u"\ud6f8")
        self.checkletter("HANGUL SYLLABLE HIH", u"\ud7a3")

        # no unicodedata module
        if test_support.due_to_ironpython_bug(
            "http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=303481"
        ):
            return
        import unicodedata

        self.assertRaises(ValueError, unicodedata.name, u"\ud7a4")
Example #13
0
    def test_infix_binops(self):
        for ia, a in enumerate(candidates):
            for ib, b in enumerate(candidates):
                results = infix_results[(ia, ib)]
                for op, res, ires in zip(infix_binops, results[0], results[1]):
                    if res is TE:
                        if not due_to_ironpython_bug("http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=299894"):                                   
                            self.assertRaises(TypeError, eval,
                                              'a %s b' % op, {'a': a, 'b': b})
                    else:
                        self.assertEquals(format_result(res),
                                          format_result(eval('a %s b' % op)),
                                          '%s %s %s == %s failed' % (a, op, b, res))

                    if not due_to_ironpython_bug("http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=151094"):                                          
                        try:
                            z = copy.copy(a)
                        except copy.Error:
                            z = a # assume it has no inplace ops
                        if ires is TE:
                            try:
                                exec 'z %s= b' % op
                            except TypeError:
                                pass
                            else:
                                self.fail("TypeError not raised")
                        else:
                            exec('z %s= b' % op)
                            self.assertEquals(ires, z)
Example #14
0
 def test(result):
     pid = os.getpid()
     os.kill(pid, signal.SIGINT)
     result.breakCaught = True
     if not due_to_ironpython_bug("http://ironpython.codeplex.com/workitem/28171"):
         self.assertTrue(result.shouldStop)
     os.kill(pid, signal.SIGINT)
     if not due_to_ironpython_bug("http://ironpython.codeplex.com/workitem/28171"):
         self.fail("Second KeyboardInterrupt not raised")
Example #15
0
 def tearDown(self):
     if test_support.due_to_ironpython_bug("http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=317178"):
         return
     sys.version = self.save_version
     sys.subversion = self.save_subversion
     sys.platform = self.save_platform
     if test_support.due_to_ironpython_bug("http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=317178"):
         return
     if test_support.due_to_ironpython_bug("http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=317178"):
         return
Example #16
0
 def test_leading_newlines(self):
     s256 = "".join(["\n"] * 256 + ["spam"])
     co = compile(s256, "fn", "exec")
     if not test_support.due_to_ironpython_bug(
         "http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=314895"
     ):
         self.assertEqual(co.co_firstlineno, 257)
     if not test_support.due_to_ironpython_bug(
         "http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=314898"
     ):
         self.assertEqual(co.co_lnotab, "")
Example #17
0
 def test_Hashable(self):
     # Check some non-hashables
     non_samples = [list(), set(), dict()]
     for x in non_samples:
         self.assertNotIsInstance(x, Hashable)
         self.assertFalse(issubclass(type(x), Hashable), repr(type(x)))
     # Check some hashables
     samples = [None,
                int(), float(), complex(),
                str(),
                tuple(), frozenset(),
                int, list, object, type,
                ]
     for x in samples:
         self.assertIsInstance(x, Hashable)
         self.assertTrue(issubclass(type(x), Hashable), repr(type(x)))
     self.assertRaises(TypeError, Hashable)
     # Check direct subclassing
     if test_support.due_to_ironpython_bug("http://ironpython.codeplex.com/workitem/28171"):
         return
     class H(Hashable):
         def __hash__(self):
             return super(H, self).__hash__()
         __eq__ = Hashable.__eq__ # Silence Py3k warning
     self.assertEqual(hash(H()), 0)
     self.assertFalse(issubclass(int, H))
     self.validate_abstract_methods(Hashable, '__hash__')
     self.validate_isinstance(Hashable, '__hash__')
Example #18
0
 def test_default_action(self):
     # Replacing or removing defaultaction should be okay.
     message = UserWarning("defaultaction test")
     original = self.module.defaultaction
     try:
         with original_warnings.catch_warnings(record=True,
                 module=self.module) as w:
             self.module.resetwarnings()
             registry = {}
             self.module.warn_explicit(message, UserWarning, "<test>", 42,
                                         registry=registry)
             self.assertEqual(w[-1].message, message)
             self.assertEqual(len(w), 1)
             self.assertEqual(len(registry), 1)
             del w[:]
             # Test removal.
             del self.module.defaultaction
             __warningregistry__ = {}
             registry = {}
             if not test_support.due_to_ironpython_bug("http://ironpython.codeplex.com/workitem/28171"):
                 self.module.warn_explicit(message, UserWarning, "<test>", 43,
                                             registry=registry)
                 self.assertEqual(w[-1].message, message)
                 self.assertEqual(len(w), 1)
                 self.assertEqual(len(registry), 1)
             del w[:]
             # Test setting.
             self.module.defaultaction = "ignore"
             __warningregistry__ = {}
             registry = {}
             self.module.warn_explicit(message, UserWarning, "<test>", 44,
                                         registry=registry)
             self.assertEqual(len(w), 0)
     finally:
         self.module.defaultaction = original
Example #19
0
 def test_new_style_iter_class(self):
     if due_to_ironpython_bug("http://ironpython.codeplex.com/workitem/28171"):
         return
     class IterClass(object):
         def __iter__(self):
             return self
     self.assertRaises(TypeError, iter, IterClass())
Example #20
0
    def test_readline(self):
        buf = self.buftype("1234567890\n")
        memio = self.ioclass(buf * 2)

        self.assertEqual(memio.readline(0), self.EOF)
        self.assertEqual(memio.readline(), buf)
        self.assertEqual(memio.readline(), buf)
        self.assertEqual(memio.readline(), self.EOF)
        memio.seek(0)
        self.assertEqual(memio.readline(5), buf[:5])
        # readline() accepts long objects
        if support.due_to_ironpython_bug("http://ironpython.codeplex.com/workitem/22896"):
            self.assertEqual(memio.readline(5), buf[5:10])
        else:
            self.assertEqual(memio.readline(5L), buf[5:10])
        self.assertEqual(memio.readline(5), buf[10:15])
        memio.seek(0)
        self.assertEqual(memio.readline(-1), buf)
        memio.seek(0)
        self.assertEqual(memio.readline(0), self.EOF)

        buf = self.buftype("1234567890\n")
        memio = self.ioclass((buf * 3)[:-1])
        self.assertEqual(memio.readline(), buf)
        self.assertEqual(memio.readline(), buf)
        self.assertEqual(memio.readline(), buf[:-1])
        self.assertEqual(memio.readline(), self.EOF)
        memio.seek(0)
        self.assertEqual(type(memio.readline()), type(buf))
        self.assertEqual(memio.readline(), buf)
        self.assertRaises(TypeError, memio.readline, '')
        memio.close()
        self.assertRaises(ValueError,  memio.readline)
Example #21
0
    def test_6(self):
        hier = [
                ("t6", None),
                ("t6 __init__"+os.extsep+"py",
                 "__all__ = ['spam', 'ham', 'eggs']"),
                ("t6 spam"+os.extsep+"py", ""),
                ("t6 ham"+os.extsep+"py", ""),
                ("t6 eggs"+os.extsep+"py", ""),
               ]
        self.mkhier(hier)

        import t6
        self.assertEqual(fixdir(dir(t6)),
                         ['__all__', '__doc__', '__file__',
                          '__name__', '__package__', '__path__'])
        if test_support.due_to_ironpython_bug("http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=21116"):
            return
        s = """
            import t6
            from t6 import *
            self.assertEqual(fixdir(dir(t6)),
                             ['__all__', '__doc__', '__file__',
                              '__name__', '__package__', '__path__',
                              'eggs', 'ham', 'spam'])
            self.assertEqual(dir(), ['eggs', 'ham', 'self', 'spam', 't6'])
            """
        self.run_code(s)
Example #22
0
    def testHashComparisonOfMethods(self):
        # Test comparison and hash of methods
        class A:
            def __init__(self, x):
                self.x = x
            def f(self):
                pass
            def g(self):
                pass
            def __eq__(self, other):
                return self.x == other.x
            def __hash__(self):
                return self.x
        class B(A):
            pass

        a1 = A(1)
        a2 = A(2)
        if not test_support.due_to_ironpython_bug("http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=314165"): 
            self.assertEquals(a1.f, a1.f)
            self.assertNotEquals(a1.f, a2.f)
            self.assertNotEquals(a1.f, a1.g)
            self.assertEquals(a1.f, A(1).f)
            self.assertEquals(hash(a1.f), hash(a1.f))
            self.assertEquals(hash(a1.f), hash(A(1).f))

            self.assertNotEquals(A.f, a1.f)
            self.assertNotEquals(A.f, A.g)
            self.assertEquals(B.f, A.f)
            self.assertEquals(hash(B.f), hash(A.f))

        # the following triggers a SystemError in 2.4
        a = A(hash(A.f.im_func)^(-1))
        hash(a.f)
Example #23
0
 def test_expand_environment_strings(self):
     # _winreg lacks ExpandEnvironmentStrings
     if test_support.due_to_ironpython_bug("http://www.codeplex.com/IronPython/WorkItem/View.aspx?WorkItemId=21116"):
         return
     r = ExpandEnvironmentStrings(u"%windir%\\test")
     self.assertEqual(type(r), unicode)
     self.assertEqual(r, os.environ["windir"] + "\\test")
Example #24
0
 def test_compile(self):
     # Check that compiled regex is correct
     found = self.time_re.compile(r"%A").match(self.locale_time.f_weekday[6])
     self.assertTrue(found and found.group('A') == self.locale_time.f_weekday[6],
                     "re object for '%A' failed")
     compiled = self.time_re.compile(r"%a %b")
     found = compiled.match("%s %s" % (self.locale_time.a_weekday[4],
                            self.locale_time.a_month[4]))
     self.assertTrue(found,
         "Match failed with '%s' regex and '%s' string" %
          (compiled.pattern, "%s %s" % (self.locale_time.a_weekday[4],
                                        self.locale_time.a_month[4])))
     self.assertTrue(found.group('a') == self.locale_time.a_weekday[4] and
                      found.group('b') == self.locale_time.a_month[4],
                     "re object couldn't find the abbreviated weekday month in "
                      "'%s' using '%s'; group 'a' = '%s', group 'b' = %s'" %
                      (found.string, found.re.pattern, found.group('a'),
                       found.group('b')))
     if test_support.due_to_ironpython_bug("http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=409557"):
        return
     for directive in ('a','A','b','B','c','d','H','I','j','m','M','p','S',
                       'U','w','W','x','X','y','Y','Z','%'):
         compiled = self.time_re.compile("%" + directive)
         found = compiled.match(time.strftime("%" + directive))
         self.assertTrue(found, "Matching failed on '%s' using '%s' regex" %
                                 (time.strftime("%" + directive),
                                  compiled.pattern))
Example #25
0
    def test_fnmatch(self):
        check = self.check_match
        check('abc', 'abc')
        check('abc', '?*?')
        check('abc', '???*')
        check('abc', '*???')
        check('abc', '???')
        check('abc', '*')
        check('abc', 'ab[cd]')
        check('abc', 'ab[!de]')
        check('abc', 'ab[de]', 0)
        check('a', '??', 0)
        check('a', 'b', 0)

        # these test that '\' is handled correctly in character sets;
        # see SF bug #409651
        check('\\', r'[\]')
        check('a', r'[!\]')
        check('\\', r'[!\]', 0)

        if test_support.due_to_ironpython_bug("http://ironpython.codeplex.com/workitem/28171"):
            return
        # test that filenames with newlines in them are handled correctly.
        # http://bugs.python.org/issue6665
        check('foo\nbar', 'foo*')
        check('foo\nbar\n', 'foo*')
        check('\nfoo', 'foo*', False)
        check('\n', '*')
Example #26
0
 def testPlainIntegers(self):
     self.assertEqual(0xff, 255)
     self.assertEqual(0377, 255)
     self.assertEqual(2147483647, 017777777777)
     # "0x" is not a valid literal
     if not due_to_ironpython_bug("http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=21116"):
         self.assertRaises(SyntaxError, eval, "0x")
     from sys import maxint
     if maxint == 2147483647:
         self.assertEqual(-2147483647-1, -020000000000)
         # XXX -2147483648
         self.assertTrue(037777777777 > 0)
         self.assertTrue(0xffffffff > 0)
         for s in '2147483648', '040000000000', '0x100000000':
             try:
                 x = eval(s)
             except OverflowError:
                 self.fail("OverflowError on huge integer literal %r" % s)
     elif maxint == 9223372036854775807:
         self.assertEqual(-9223372036854775807-1, -01000000000000000000000)
         self.assertTrue(01777777777777777777777 > 0)
         self.assertTrue(0xffffffffffffffff > 0)
         for s in '9223372036854775808', '02000000000000000000000', \
                  '0x10000000000000000':
             try:
                 x = eval(s)
             except OverflowError:
                 self.fail("OverflowError on huge integer literal %r" % s)
     else:
         self.fail('Weird maxint value %r' % maxint)
Example #27
0
    def testAssertDictContainsSubset(self):
        self.assertDictContainsSubset({}, {})
        self.assertDictContainsSubset({}, {"a": 1})
        self.assertDictContainsSubset({"a": 1}, {"a": 1})
        self.assertDictContainsSubset({"a": 1}, {"a": 1, "b": 2})
        self.assertDictContainsSubset({"a": 1, "b": 2}, {"a": 1, "b": 2})

        with self.assertRaises(self.failureException):
            self.assertDictContainsSubset({1: "one"}, {})

        with self.assertRaises(self.failureException):
            self.assertDictContainsSubset({"a": 2}, {"a": 1})

        with self.assertRaises(self.failureException):
            self.assertDictContainsSubset({"c": 1}, {"a": 1})

        with self.assertRaises(self.failureException):
            self.assertDictContainsSubset({"a": 1, "c": 1}, {"a": 1})

        with self.assertRaises(self.failureException):
            self.assertDictContainsSubset({"a": 1, "c": 1}, {"a": 1})

        if test_support.due_to_ironpython_bug("http://ironpython.codeplex.com/workitem/28171"):
            one = "".join(chr(i) for i in range(255))
            # this used to cause a UnicodeDecodeError constructing the failure msg
            with self.assertRaises(self.failureException):
                self.assertDictContainsSubset({"foo": one}, {"foo": u"\uFFFD"})
        else:
            with test_support.check_warnings(("", UnicodeWarning)):
                one = "".join(chr(i) for i in range(255))
                # this used to cause a UnicodeDecodeError constructing the failure msg
                with self.assertRaises(self.failureException):
                    self.assertDictContainsSubset({"foo": one}, {"foo": u"\uFFFD"})
Example #28
0
    def send_to_worker(self, python, obj, proto):
        """Bounce a pickled object through another version of Python.

        This will pickle the object, send it to a child process where it will be
        unpickled, then repickled and sent back to the parent process.

        Args:
            python: the name of the Python binary to start.
            obj: object to pickle.
            proto: pickle protocol number to use.

        Returns:
            The pickled data received from the child process.
        """
        if test_support.due_to_ironpython_bug("http://ironpython.codeplex.com/workitem/15512"):
            return
        # Prevent the subprocess from picking up invalid .pyc files.
        target = __file__
        if target[-1] in ("c", "o"):
            target = target[:-1]

        data = self.module.dumps((proto, obj), proto)
        worker = subprocess.Popen([python, target, "worker"],
                                  stdin=subprocess.PIPE,
                                  stdout=subprocess.PIPE,
                                  stderr=subprocess.PIPE)
        stdout, stderr = worker.communicate(data)
        if worker.returncode != 0:
            raise RuntimeError(stderr)
        return stdout
Example #29
0
    def assertFloatsAreIdentical(self, x, y):
        """assert that floats x and y are identical, in the sense that:
        (1) both x and y are nans, or
        (2) both x and y are infinities, with the same sign, or
        (3) both x and y are zeros, with the same sign, or
        (4) x and y are both finite and nonzero, and x == y

        """
        msg = 'floats {!r} and {!r} are not identical'

        if isnan(x) or isnan(y):
            if isnan(x) and isnan(y):
                return
        elif x == y:
            if x != 0.0:
                return
            # both zero; check that signs match
            elif copysign(1.0, x) == copysign(1.0, y):
                return
            else:
                msg += ': zeros have different signs'
                if test_support.due_to_ironpython_bug("http://ironpython.codeplex.com/workitem/28352"):
                    print msg.format(x, y)
                    return
        self.fail(msg.format(x, y))
Example #30
0
    def test_attributes(self):
        p = self.thetype(capture, 1, 2, a=10, b=20)
        # attributes should be readable
        self.assertEqual(p.func, capture)
        self.assertEqual(p.args, (1, 2))
        self.assertEqual(p.keywords, dict(a=10, b=20))
        # attributes should not be writable
        if not isinstance(self.thetype, type):
            return
        if test_support.due_to_ironpython_bug("http://ironpython.codeplex.com/workitem/28171"):
            if self.thetype is not functools.partial:
                return
            self.assertRaises((TypeError, AttributeError), setattr, p, "func", map)
            self.assertRaises(AttributeError, setattr, p, "args", (1, 2))
            self.assertRaises(AttributeError, setattr, p, "keywords", dict(a=1, b=2))
        else:
            self.assertRaises(TypeError, setattr, p, "func", map)
            self.assertRaises(TypeError, setattr, p, "args", (1, 2))
            self.assertRaises(TypeError, setattr, p, "keywords", dict(a=1, b=2))

        p = self.thetype(hex)
        try:
            del p.__dict__
        except TypeError:
            pass
        else:
            self.fail("partial object allowed __dict__ to be deleted")
Example #31
0
 def test_wrappers(self):
     self.o.ind = 4
     self.n.ind = 5
     if test_support.due_to_ironpython_bug(
             "http://ironpython.codeplex.com/workitem/28171"):
         return
     self.assertEqual(self.seq.__getitem__(self.o), self.seq[4])
     self.assertEqual(self.seq.__mul__(self.o), self.seq * 4)
     self.assertEqual(self.seq.__rmul__(self.o), self.seq * 4)
     self.assertEqual(self.seq.__getitem__(self.n), self.seq[5])
     self.assertEqual(self.seq.__mul__(self.n), self.seq * 5)
     self.assertEqual(self.seq.__rmul__(self.n), self.seq * 5)
Example #32
0
 def test_extendleft(self):
     d = deque('a')
     self.assertRaises(TypeError, d.extendleft, 1)
     d.extendleft('bcd')
     self.assertEqual(list(d), list(reversed('abcd')))
     if not test_support.due_to_ironpython_bug("http://ironpython.codeplex.com/workitem/28359"):
         d.extendleft(d)
         self.assertEqual(list(d), list('abcddcba'))
     d = deque()
     d.extendleft(range(1000))
     self.assertEqual(list(d), list(reversed(range(1000))))
     self.assertRaises(SyntaxError, d.extendleft, fail())
Example #33
0
    def test_callback_in_cycle_resurrection(self):
        import gc

        # Do something nasty in a weakref callback:  resurrect objects
        # from dead cycles.  For this to be attempted, the weakref and
        # its callback must also be part of the cyclic trash (else the
        # objects reachable via the callback couldn't be in cyclic trash
        # to begin with -- the callback would act like an external root).
        # But gc clears trash weakrefs with callbacks early now, which
        # disables the callbacks, so the callbacks shouldn't get called
        # at all (and so nothing actually gets resurrected).

        def runTest():
            alist = []
            class C(object):
                def __init__(self, value):
                    self.attribute = value

                def acallback(self, ignore):
                    alist.append(self.c)

            c1, c2 = C(1), C(2)
            c1.c = c2
            c2.c = c1
            c1.wr = weakref.ref(c2, c1.acallback)
            c2.wr = weakref.ref(c1, c2.acallback)

            def C_went_away(ignore):
                alist.append("C went away")
            wr = weakref.ref(C, C_went_away)

            del c1, c2, C   # make them all trash
            self.assertEqual(alist, [])  # del isn't enough to reclaim anything

            return alist, wr

        alist, wr = runTest()
        if not test_support.due_to_ironpython_bug("http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=25221"):
            gc.collect()
        else:
            return
        # c1.wr and c2.wr were part of the cyclic trash, so should have
        # been cleared without their callbacks executing.  OTOH, the weakref
        # to C is bound to a function local (wr), and wasn't trash, so that
        # callback should have been invoked when C went away.
        self.assertEqual(alist, ["C went away"])
        # The remaining weakref should be dead now (its callback ran).
        self.assertEqual(wr(), None)

        del alist[:]
        gc.collect()
        self.assertEqual(alist, [])
Example #34
0
 def testRepr(self):
     self.assertEquals(
         repr(self.f),
         "<_io.FileIO name=%r mode='%s'>" % (self.f.name, self.f.mode))
     if due_to_ironpython_bug(
             "http://ironpython.codeplex.com/workitem/22896"):
         return
     del self.f.name
     self.assertEquals(
         repr(self.f),
         "<_io.FileIO fd=%r mode='%s'>" % (self.f.fileno(), self.f.mode))
     self.f.close()
     self.assertEquals(repr(self.f), "<_io.FileIO [closed]>")
Example #35
0
 def testWeakRefs(self):
     if due_to_ironpython_bug(
             "http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=313703"
     ):
         return
     # verify weak references
     p = proxy(self.f)
     p.write(bytes(range(10)))
     self.assertEquals(self.f.tell(), p.tell())
     self.f.close()
     self.f = None
     gc_collect()
     self.assertRaises(ReferenceError, getattr, p, 'tell')
 def test_WindowsError(self):
     try:
         WindowsError
     except NameError:
         pass
     else:
         self.assertEqual(str(WindowsError(1001)),
                              "1001")
         if not due_to_ironpython_bug("http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=21116"):
             self.assertEqual(str(WindowsError(1001, "message")),
                                 "[Error 1001] message")
         self.assertEqual(WindowsError(1001, "message").errno, 22)
         self.assertEqual(WindowsError(1001, "message").winerror, 1001)
Example #37
0
 def test_showwarning_missing(self):
     if test_support.due_to_ironpython_bug(
             "http://ironpython.codeplex.com/workitem/28171"):
         return
     # Test that showwarning() missing is okay.
     text = 'del showwarning test'
     with original_warnings.catch_warnings(module=self.module):
         self.module.filterwarnings("always", category=UserWarning)
         del self.module.showwarning
         with test_support.captured_output('stderr') as stream:
             self.module.warn(text)
             result = stream.getvalue()
     self.assertIn(text, result)
Example #38
0
 def test_julian_calculation(self):
     if test_support.due_to_ironpython_bug(
             "http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=409557"
     ):
         return
     # Make sure that when Julian is missing that it is calculated
     format_string = "%Y %m %d %H %M %S %w %Z"
     result = _strptime._strptime_time(
         time.strftime(format_string, self.time_tuple), format_string)
     self.assertTrue(
         result.tm_yday == self.time_tuple.tm_yday,
         "Calculation of tm_yday failed; %s != %s" %
         (result.tm_yday, self.time_tuple.tm_yday))
Example #39
0
 def test_day_of_week_calculation(self):
     if test_support.due_to_ironpython_bug(
             "http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=409557"
     ):
         return
     # Test that the day of the week is calculated as needed
     format_string = "%Y %m %d %H %S %j %Z"
     result = _strptime._strptime_time(
         time.strftime(format_string, self.time_tuple), format_string)
     self.assertTrue(
         result.tm_wday == self.time_tuple.tm_wday,
         "Calculation of day of the week failed;"
         "%s != %s" % (result.tm_wday, self.time_tuple.tm_wday))
Example #40
0
    def test_dbcs_keep_buffer(self):
        if test_support.due_to_ironpython_bug(
                "http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=321775"
        ):
            return
        decoder = codecs.getincrementaldecoder('cp949')()
        self.assertEqual(decoder.decode('\xc6\xc4\xc0'), u'\ud30c')
        self.assertRaises(UnicodeDecodeError, decoder.decode, '', True)
        self.assertEqual(decoder.decode('\xcc'), u'\uc774')

        self.assertEqual(decoder.decode('\xc6\xc4\xc0'), u'\ud30c')
        self.assertRaises(UnicodeDecodeError, decoder.decode, '\xcc\xbd', True)
        self.assertEqual(decoder.decode('\xcc'), u'\uc774')
Example #41
0
 def test_reverse(self):
     if test_support.due_to_ironpython_bug("http://ironpython.codeplex.com/workitem/28359"):
         return
     n = 500         # O(n**2) test, don't make this too big
     data = [random.random() for i in range(n)]
     for i in range(n):
         d = deque(data[:i])
         r = d.reverse()
         self.assertEqual(list(d), list(reversed(data[:i])))
         self.assert_(r is None)
         d.reverse()
         self.assertEqual(list(d), data[:i])
     self.assertRaises(TypeError, d.reverse, 1)          # Arity is zero
Example #42
0
 def test_buffer_info(self):
     if test_support.due_to_ironpython_bug(
             "http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=313665"
     ):
         return
     a = array.array(self.typecode, self.example)
     self.assertRaises(TypeError, a.buffer_info, 42)
     bi = a.buffer_info()
     self.assertIsInstance(bi, tuple)
     self.assertEqual(len(bi), 2)
     self.assertIsInstance(bi[0], (int, long))
     self.assertIsInstance(bi[1], int)
     self.assertEqual(bi[1], len(a))
Example #43
0
def test_main():
    tests = [
        PyBytesIOTest, PyStringIOTest, CBytesIOTest, CStringIOTest,
        PyStringIOPickleTest, CStringIOPickleTest
    ]
    if support.due_to_ironpython_bug(
            "http://ironpython.codeplex.com/WorkItem/View.aspx?WorkItemId=17454"
    ):
        tests.remove(CStringIOTest)
        tests.remove(PyStringIOTest)
        tests.remove(CStringIOPickleTest)
        tests.remove(PyStringIOPickleTest)
    support.run_unittest(*tests)
    def test_badandgoodstrictexceptions(self):
        # "strict" complains about a non-exception passed in
        self.assertRaises(TypeError, codecs.strict_errors, 42)
        # "strict" complains about the wrong exception type
        self.assertRaises(Exception, codecs.strict_errors, Exception("ouch"))

        # If the correct exception is passed in, "strict" raises it
        if not test_support.due_to_ironpython_bug(
                "http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=303935"
        ):
            self.assertRaises(
                UnicodeEncodeError, codecs.strict_errors,
                UnicodeEncodeError("ascii", u"\u3042", 0, 1, "ouch"))
Example #45
0
 def test_unicodedecodeerror(self):
     if test_support.due_to_ironpython_bug("http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=304331"):
         return
     self.check_exceptionobjectargs(
         UnicodeDecodeError,
         ["ascii", "g\xfcrk", 1, 2, "ouch"],
         "'ascii' codec can't decode byte 0xfc in position 1: ouch"
     )
     self.check_exceptionobjectargs(
         UnicodeDecodeError,
         ["ascii", "g\xfcrk", 1, 3, "ouch"],
         "'ascii' codec can't decode bytes in position 1-2: ouch"
     )
Example #46
0
    def test_jumpahead(self):
        self.gen.seed()
        state1 = self.gen.getstate()
        self.gen.jumpahead(100)
        state2 = self.gen.getstate()  # s/b distinct from state1
        if not test_support.due_to_ironpython_bug(
                "http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=319012"
        ):
            self.assertNotEqual(state1, state2)
        self.gen.jumpahead(100)
        state3 = self.gen.getstate()  # s/b distinct from state2
        if not test_support.due_to_ironpython_bug(
                "http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=319012"
        ):
            self.assertNotEqual(state2, state3)

        with test_support.check_py3k_warnings(quiet=True):
            self.assertRaises(TypeError, self.gen.jumpahead)  # needs an arg
            self.assertRaises(TypeError, self.gen.jumpahead,
                              "ick")  # wrong type
            self.assertRaises(TypeError, self.gen.jumpahead, 2.3)  # wrong type
            self.assertRaises(TypeError, self.gen.jumpahead, 2, 3)  # too many
Example #47
0
 def test_interface_no_arg(self):
     # Make sure that with no args that interface is correct
     if test_support.due_to_ironpython_bug(
             "http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=363657"
     ):
         return
     exc = Exception()
     results = ([len(exc.args),
                 0], [exc.args, tuple()], [exc.message, ''], [str(exc), ''],
                [unicode(exc),
                 u''], [repr(exc),
                        exc.__class__.__name__ + '()'], [True, True])
     self.interface_test_driver(results)
Example #48
0
    def test_1_arg(self):
        """Check same msg for Exceptions with 1 arg"""
        for arg in ('foo', u'foo'):
            self.check_same_msg(Exception(arg), arg)

        # if __str__ is not overridden and self.args[0] is a non-ascii unicode
        # string, str() should try to return str(self.args[0]) and fail.
        # unicode() should return unicode(self.args[0]) and succeed.
        e = Exception(u'f\xf6\xf6')
        if not due_to_ironpython_bug(
                "http://ironpython.codeplex.com/workitem/28171"):
            self.assertRaises(UnicodeEncodeError, str, e)
        self.assertEqual(unicode(e), u'f\xf6\xf6')
Example #49
0
 def test_invalid_names(self):
     # Builtin module
     self.expect_import_error("sys")
     # Non-existent modules
     self.expect_import_error("sys.imp.eric")
     self.expect_import_error("os.path.half")
     self.expect_import_error("a.bee")
     self.expect_import_error(".howard")
     self.expect_import_error("..eaten")
     if due_to_ironpython_bug("http://ironpython.codeplex.com/workitem/28171"):
         return
     # Package without __main__.py
     self.expect_import_error("multiprocessing")
 def test_getmodule_recursion(self):
     from types import ModuleType
     name = '__inspect_dummy'
     m = sys.modules[name] = ModuleType(name)
     m.__file__ = "<string>"  # hopefully not a real filename...
     m.__loader__ = "dummy"  # pretend the filename is understood by a loader
     exec "def x(): pass" in m.__dict__
     self.assertEqual(inspect.getsourcefile(m.x.func_code), '<string>')
     del sys.modules[name]
     if not due_to_ironpython_bug(
             "http://www.codeplex.com/IronPython/WorkItem/View.aspx?WorkItemId=1494"
     ):
         inspect.getmodule(compile('a=10', '', 'single'))
Example #51
0
 def test_slotnames(self):
     if test_support.due_to_ironpython_bug("http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=318201"):
         return
     self.assertEquals(copy_reg._slotnames(WithoutSlots), [])
     self.assertEquals(copy_reg._slotnames(WithWeakref), [])
     expected = ['_WithPrivate__spam']
     self.assertEquals(copy_reg._slotnames(WithPrivate), expected)
     self.assertEquals(copy_reg._slotnames(WithSingleString), ['spam'])
     expected = ['eggs', 'spam']
     expected.sort()
     result = copy_reg._slotnames(WithInherited)
     result.sort()
     self.assertEquals(result, expected)
Example #52
0
 def test_while_one(self):
     if test_support.due_to_ironpython_bug("http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=320502"):
         return
     # Skip over:  LOAD_CONST trueconst  POP_JUMP_IF_FALSE xx
     def f():
         while 1:
             pass
         return list
     asm = disassemble(f)
     for elem in ('LOAD_CONST', 'POP_JUMP_IF_FALSE'):
         self.assertNotIn(elem, asm)
     for elem in ('JUMP_ABSOLUTE',):
         self.assertIn(elem, asm)
Example #53
0
 def test_tuple(self):
     if test_support.due_to_ironpython_bug(
             "http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=314459"
     ):
         return
     # since tuples are immutable we close the loop with a list
     l = []
     t = (l, )
     l.append(t)
     gc.collect()
     del t
     del l
     self.assertEqual(gc.collect(), 2)
Example #54
0
 def test_richcompare(self):
     if not test_support.due_to_ironpython_bug(
             "http://ironpython.codeplex.com/workitem/28352"):
         self.assertEqual(complex.__eq__(1 + 1j, 1L << 10000), False)
     self.assertEqual(complex.__lt__(1 + 1j, None), NotImplemented)
     self.assertIs(complex.__eq__(1 + 1j, 1 + 1j), True)
     self.assertIs(complex.__eq__(1 + 1j, 2 + 2j), False)
     self.assertIs(complex.__ne__(1 + 1j, 1 + 1j), False)
     self.assertIs(complex.__ne__(1 + 1j, 2 + 2j), True)
     self.assertRaises(TypeError, complex.__lt__, 1 + 1j, 2 + 2j)
     self.assertRaises(TypeError, complex.__le__, 1 + 1j, 2 + 2j)
     self.assertRaises(TypeError, complex.__gt__, 1 + 1j, 2 + 2j)
     self.assertRaises(TypeError, complex.__ge__, 1 + 1j, 2 + 2j)
Example #55
0
 def test_sparse(self):
     if test_support.due_to_ironpython_bug(
             "http://www.codeplex.com/IronPython/WorkItem/View.aspx?WorkItemId=21116"
     ):
         return
     # A SpooledTemporaryFile that is written late in the file will extend
     # when that occurs
     f = self.do_create(max_size=30)
     self.assertFalse(f._rolled)
     f.seek(100, 0)
     self.assertFalse(f._rolled)
     f.write('x')
     self.assertTrue(f._rolled)
Example #56
0
 def test_collect_generations(self):
     if test_support.due_to_ironpython_bug("http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=314459"):
         return
     # Avoid future allocation of method object
     assertEqual = self.assertEqual
     gc.collect()
     a = dict()
     gc.collect(0)
     assertEqual(gc.get_count(), (0, 1, 0))
     gc.collect(1)
     assertEqual(gc.get_count(), (0, 0, 1))
     gc.collect(2)
     assertEqual(gc.get_count(), (0, 0, 0))
Example #57
0
    def test_instance(self):
        class A:
            pass

        a = A()
        a.a = a
        gc.collect()
        del a
        if test_support.due_to_ironpython_bug(
                "http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=314459"
        ):
            return
        self.assertNotEqual(gc.collect(), 0)
Example #58
0
    def _do_single(self, filename):
        self.assertTrue(os.path.exists(filename))
        self.assertTrue(os.path.isfile(filename))
        self.assertTrue(os.access(filename, os.R_OK))
        self.assertTrue(os.path.exists(os.path.abspath(filename)))
        self.assertTrue(os.path.isfile(os.path.abspath(filename)))
        self.assertTrue(os.access(os.path.abspath(filename), os.R_OK))
        if not test_support.due_to_ironpython_bug(
                "http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=363042"
        ):
            os.chmod(filename, 0777)
        os.utime(filename, None)
        os.utime(filename, (time.time(), time.time()))
        # Copy/rename etc tests using the same filename
        self._do_copyish(filename, filename)
        # Filename should appear in glob output
        self.assertTrue(
            os.path.abspath(filename) == os.path.abspath(
                glob.glob(filename)[0]))
        # basename should appear in listdir.
        path, base = os.path.split(os.path.abspath(filename))
        if isinstance(base, str):
            base = base.decode(TESTFN_ENCODING)
        file_list = os.listdir(path)
        # listdir() with a unicode arg may or may not return Unicode
        # objects, depending on the platform.
        if file_list and isinstance(file_list[0], str):
            file_list = [f.decode(TESTFN_ENCODING) for f in file_list]

        # Normalize the unicode strings, as round-tripping the name via the OS
        # may return a different (but equivalent) value.
        if not test_support.due_to_ironpython_bug(
                "http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=303481"
        ):
            base = unicodedata.normalize("NFD", base)
            file_list = [unicodedata.normalize("NFD", f) for f in file_list]

            self.assertIn(base, file_list)
Example #59
0
 def test_tofromstring(self):
     if test_support.due_to_ironpython_bug(
             "http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=313708"
     ):
         return
     a = array.array(self.typecode, 2 * self.example)
     b = array.array(self.typecode)
     self.assertRaises(TypeError, a.tostring, 42)
     self.assertRaises(TypeError, b.fromstring)
     self.assertRaises(TypeError, b.fromstring, 42)
     b.fromstring(a.tostring())
     self.assertEqual(a, b)
     if a.itemsize > 1:
         self.assertRaises(ValueError, b.fromstring, "x")
Example #60
0
 def test_bmp_characters(self):
     # no unicodedata module
     if test_support.due_to_ironpython_bug(
             "http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=303481"
     ):
         return
     import unicodedata
     count = 0
     for code in xrange(0x10000):
         char = unichr(code)
         name = unicodedata.name(char, None)
         if name is not None:
             self.assertEqual(unicodedata.lookup(name), char)
             count += 1