Python sys.getrecursionlimit() Examples

The following are code examples for showing how to use sys.getrecursionlimit(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: osbrain   Author: opensistemas-hub   File: test_bugs.py    (license) View Source Project 6 votes vote down vote up
def test_timer_recursion(nsproxy):
    """
    This bug occured with the first implementation of the timer. After
    some iterations the timer would throw an exception when the recursion
    limit was exceeded. Timers should never reach a recursion limit.
    """
    def inc(agent):
        agent.count += 1

    agent = run_agent('a0')
    agent.set_attr(count=0)
    agent.each(0.0, inc)

    limit = sys.getrecursionlimit()
    assert wait_agent_condition(agent, lambda agent: agent.count > limit,
                                timeout=10) 
Example 2
Project: zeronet-debian   Author: bashrc   File: test_stealth.py    (license) View Source Project 6 votes vote down vote up
def setUp(self):
        
        if sys.getrecursionlimit() < 1000:
            sys.setrecursionlimit(1000)
        
        self.addr = 'vJmtjxSDxNPXL4RNapp9ARdqKz3uJyf1EDGjr1Fgqs9c8mYsVH82h8wvnA4i5rtJ57mr3kor1EVJrd4e5upACJd588xe52yXtzumxj'
        self.scan_pub = '025e58a31122b38c86abc119b9379fe247410aee87a533f9c07b189aef6c3c1f52'
        self.scan_priv = '3e49e7257cb31db997edb1cf8299af0f37e2663e2260e4b8033e49d39a6d02f2'
        self.spend_pub = '03616562c98e7d7b74be409a787cec3a912122f3fb331a9bee9b0b73ce7b9f50af'
        self.spend_priv = 'aa3db0cfb3edc94de4d10f873f8190843f2a17484f6021a95a7742302c744748'
        self.ephem_pub = '03403d306ec35238384c7e340393335f9bc9bb4a2e574eb4e419452c4ea19f14b0'
        self.ephem_priv = '9e63abaf8dcd5ea3919e6de0b6c544e00bf51bf92496113a01d6e369944dc091'
        self.shared_secret = 'a4047ee231f4121e3a99a3a3378542e34a384b865a9917789920e1f13ffd91c6'
        self.pay_pub = '02726112ad39cb6bf848b1b1ef30b88e35286bf99f746c2be575f96c0e02a9357c'
        self.pay_priv = '4e422fb1e5e1db6c1f6ab32a7706d368ceb385e7fab098e633c5c5949c3b97cd'
        
        self.testnet_addr = 'waPUuLLykSnY3itzf1AyrQZm42F7KyB7SR5zpfqmnzPXWhx9kXLzV3EcyqzDdpTwngiyCCMUqztS9S1d7XJs3JMt3MsHPDpBCudvx9' 
Example 3
Project: CSB   Author: csb-toolbox   File: __init__.py    (license) View Source Project 6 votes vote down vote up
def deepcopy(obj, recursion=100000):
    """
    Perform a deep copy of obj using cPickle. Faster than copy.deepcopy()
    for large objects.
    
    @param obj: the object to copy
    @return: a deep copy of obj
    @param recursion: maximum recursion limit
    @type recursion: int
    """
    from csb.io import Pickle
    
    current = sys.getrecursionlimit()
    sys.setrecursionlimit(recursion)
    
    tmp = Pickle.dumps(obj, Pickle.HIGHEST_PROTOCOL)
    copy = Pickle.loads(tmp)
    
    sys.setrecursionlimit(current)
    return copy 
Example 4
Project: zippy   Author: securesystemslab   File: test_spelling.py    (license) View Source Project 6 votes vote down vote up
def test_very_long_words():
    import sys
    length = int(sys.getrecursionlimit() * 1.5)

    strings1 = [u(chr(i) * length) for i in range(65, 70)]
    strings2 = [u(chr(i) * length) for i in range(71, 75)]

    ana = analysis.StemmingAnalyzer()
    schema = fields.Schema(text=fields.TEXT(analyzer=ana, spelling=True))
    ix = RamStorage().create_index(schema)
    with ix.writer() as w:
        for string in strings1:
            w.add_document(text=string)

    with ix.writer() as w:
        for string in strings2:
            w.add_document(text=string)
        w.optimize = True 
Example 5
Project: zippy   Author: securesystemslab   File: test_sys.py    (license) View Source Project 6 votes vote down vote up
def test_recursionlimit_recovery(self):
        # NOTE: this test is slightly fragile in that it depends on the current
        # recursion count when executing the test being low enough so as to
        # trigger the recursion recovery detection in the _Py_MakeEndRecCheck
        # macro (see ceval.h).
        oldlimit = sys.getrecursionlimit()
        def f():
            f()
        try:
            for i in (50, 1000):
                # Issue #5392: stack overflow after hitting recursion limit twice
                sys.setrecursionlimit(i)
                self.assertRaises(RuntimeError, f)
                self.assertRaises(RuntimeError, f)
        finally:
            sys.setrecursionlimit(oldlimit) 
Example 6
Project: zippy   Author: securesystemslab   File: test_sys_settrace.py    (license) View Source Project 6 votes vote down vote up
def run_test_for_event(self, event):
        """Tests that an exception raised in response to the given event is
        handled OK."""
        self.raiseOnEvent = event
        try:
            for i in range(sys.getrecursionlimit() + 1):
                sys.settrace(self.trace)
                try:
                    self.f()
                except ValueError:
                    pass
                else:
                    self.fail("exception not thrown!")
        except RuntimeError:
            self.fail("recursion counter not reset")

    # Test the handling of exceptions raised by each kind of trace event. 
Example 7
Project: zippy   Author: securesystemslab   File: list_tests.py    (license) View Source Project 6 votes vote down vote up
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]")

        l0 = []
        for i in range(sys.getrecursionlimit() + 10000):
            l0 = [l0]
        self.assertRaises(RuntimeError, repr, l0) 
Example 8
Project: oil   Author: oilshell   File: test_sys.py    (license) View Source Project 6 votes vote down vote up
def test_recursionlimit(self):
        self.assertRaises(TypeError, sys.getrecursionlimit, 42)
        oldlimit = sys.getrecursionlimit()
        self.assertRaises(TypeError, sys.setrecursionlimit)
        self.assertRaises(ValueError, sys.setrecursionlimit, -42)
        sys.setrecursionlimit(10000)
        self.assertEqual(sys.getrecursionlimit(), 10000)
        sys.setrecursionlimit(oldlimit)

        self.assertRaises(OverflowError, sys.setrecursionlimit, 1 << 31)
        try:
            sys.setrecursionlimit((1 << 31) - 5)
            try:
                # issue13546: isinstance(e, ValueError) used to fail
                # when the recursion limit is close to 1<<31
                raise ValueError()
            except ValueError, e:
                pass
        finally:
            sys.setrecursionlimit(oldlimit) 
Example 9
Project: oil   Author: oilshell   File: test_sys_settrace.py    (license) View Source Project 6 votes vote down vote up
def run_test_for_event(self, event):
        """Tests that an exception raised in response to the given event is
        handled OK."""
        self.raiseOnEvent = event
        try:
            for i in xrange(sys.getrecursionlimit() + 1):
                sys.settrace(self.trace)
                try:
                    self.f()
                except ValueError:
                    pass
                else:
                    self.fail("exception not raised!")
        except RuntimeError:
            self.fail("recursion counter not reset")

    # Test the handling of exceptions raised by each kind of trace event. 
Example 10
Project: oil   Author: oilshell   File: list_tests.py    (license) View Source Project 6 votes vote down vote up
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]")

        l0 = []
        for i in xrange(sys.getrecursionlimit() + 100):
            l0 = [l0]
        self.assertRaises(RuntimeError, repr, l0) 
Example 11
Project: python2-tracer   Author: extremecoders-re   File: test_sys.py    (license) View Source Project 6 votes vote down vote up
def test_recursionlimit(self):
        self.assertRaises(TypeError, sys.getrecursionlimit, 42)
        oldlimit = sys.getrecursionlimit()
        self.assertRaises(TypeError, sys.setrecursionlimit)
        self.assertRaises(ValueError, sys.setrecursionlimit, -42)
        sys.setrecursionlimit(10000)
        self.assertEqual(sys.getrecursionlimit(), 10000)
        sys.setrecursionlimit(oldlimit)

        self.assertRaises(OverflowError, sys.setrecursionlimit, 1 << 31)
        try:
            sys.setrecursionlimit((1 << 31) - 5)
            try:
                # issue13546: isinstance(e, ValueError) used to fail
                # when the recursion limit is close to 1<<31
                raise ValueError()
            except ValueError, e:
                pass
        finally:
            sys.setrecursionlimit(oldlimit) 
Example 12
Project: python2-tracer   Author: extremecoders-re   File: test_sys_settrace.py    (license) View Source Project 6 votes vote down vote up
def run_test_for_event(self, event):
        """Tests that an exception raised in response to the given event is
        handled OK."""
        self.raiseOnEvent = event
        try:
            for i in xrange(sys.getrecursionlimit() + 1):
                sys.settrace(self.trace)
                try:
                    self.f()
                except ValueError:
                    pass
                else:
                    self.fail("exception not raised!")
        except RuntimeError:
            self.fail("recursion counter not reset")

    # Test the handling of exceptions raised by each kind of trace event. 
Example 13
Project: python2-tracer   Author: extremecoders-re   File: list_tests.py    (license) View Source Project 6 votes vote down vote up
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]")

        l0 = []
        for i in xrange(sys.getrecursionlimit() + 100):
            l0 = [l0]
        self.assertRaises(RuntimeError, repr, l0) 
Example 14
Project: goldmine   Author: Armored-Dragon   File: asizeof.py    (license) View Source Project 6 votes vote down vote up
def _objs_opts(objs, all=None, **opts):
    '''Return given or 'all' objects
       and the remaining options.
    '''
    if objs:  # given objects
        t = objs
    elif all in (False, None):
        t = ()
    elif all is True:  # 'all' objects ...
         # ... modules first, globals and stack
         # (may contain duplicate objects)
        t = tuple(_values(sys.modules)) + (
            globals(), stack(sys.getrecursionlimit())[2:])
    else:
        raise ValueError('invalid option: %s=%r' % ('all', all))
    return t, opts 
Example 15
Project: web_ctp   Author: molebot   File: test_compile.py    (license) View Source Project 6 votes vote down vote up
def test_compiler_recursion_limit(self):
        # Expected limit is sys.getrecursionlimit() * the scaling factor
        # in symtable.c (currently 3)
        # We expect to fail *at* that limit, because we use up some of
        # the stack depth limit in the test suite code
        # So we check the expected limit and 75% of that
        # XXX (ncoghlan): duplicating the scaling factor here is a little
        # ugly. Perhaps it should be exposed somewhere...
        fail_depth = sys.getrecursionlimit() * 3
        success_depth = int(fail_depth * 0.75)

        def check_limit(prefix, repeated):
            expect_ok = prefix + repeated * success_depth
            self.compile_single(expect_ok)
            broken = prefix + repeated * fail_depth
            details = "Compiling ({!r} + {!r} * {})".format(
                         prefix, repeated, fail_depth)
            with self.assertRaises(RuntimeError, msg=details):
                self.compile_single(broken)

        check_limit("a", "()")
        check_limit("a", ".b")
        check_limit("a", "[0]")
        check_limit("a", "*a") 
Example 16
Project: web_ctp   Author: molebot   File: test_sys.py    (license) View Source Project 6 votes vote down vote up
def test_recursionlimit_recovery(self):
        # NOTE: this test is slightly fragile in that it depends on the current
        # recursion count when executing the test being low enough so as to
        # trigger the recursion recovery detection in the _Py_MakeEndRecCheck
        # macro (see ceval.h).
        oldlimit = sys.getrecursionlimit()
        def f():
            f()
        try:
            for i in (50, 1000):
                # Issue #5392: stack overflow after hitting recursion limit twice
                sys.setrecursionlimit(i)
                self.assertRaises(RuntimeError, f)
                self.assertRaises(RuntimeError, f)
        finally:
            sys.setrecursionlimit(oldlimit) 
Example 17
Project: web_ctp   Author: molebot   File: list_tests.py    (license) View Source Project 6 votes vote down vote up
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]")

        l0 = []
        for i in range(sys.getrecursionlimit() + 100):
            l0 = [l0]
        self.assertRaises(RuntimeError, repr, l0) 
Example 18
Project: fython   Author: nicolasessisbreton   File: fymodule.py    (license) View Source Project 6 votes vote down vote up
def save(s):
		# increasing recursion depth to avoid pickle: maximum recursion depth error, see:
		#	http://stackoverflow.com/q/2134706/1030312

		current_limit = sys.getrecursionlimit()
		
		if current_limit < fypickling_recursion_limit:
			sys.setrecursionlimit(fypickling_recursion_limit)	

		dump(
			s, 
			open(s.url.pickle, 'wb'), 
			protocol = HIGHEST_PROTOCOL, 
		)


		if current_limit < fypickling_recursion_limit:
			sys.setrecursionlimit(current_limit) 
Example 19
Project: pefile.pypy   Author: cloudtracer   File: test_sys.py    (license) View Source Project 6 votes vote down vote up
def test_recursionlimit(self):
        self.assertRaises(TypeError, sys.getrecursionlimit, 42)
        oldlimit = sys.getrecursionlimit()
        self.assertRaises(TypeError, sys.setrecursionlimit)
        self.assertRaises(ValueError, sys.setrecursionlimit, -42)
        sys.setrecursionlimit(10000)
        self.assertEqual(sys.getrecursionlimit(), 10000)
        sys.setrecursionlimit(oldlimit)

        self.assertRaises(OverflowError, sys.setrecursionlimit, 1 << 31)
        try:
            sys.setrecursionlimit((1 << 31) - 5)
            try:
                # issue13546: isinstance(e, ValueError) used to fail
                # when the recursion limit is close to 1<<31
                raise ValueError()
            except ValueError, e:
                pass
        finally:
            sys.setrecursionlimit(oldlimit) 
Example 20
Project: pefile.pypy   Author: cloudtracer   File: test_sys_settrace.py    (license) View Source Project 6 votes vote down vote up
def run_test_for_event(self, event):
        """Tests that an exception raised in response to the given event is
        handled OK."""
        self.raiseOnEvent = event
        try:
            for i in xrange(sys.getrecursionlimit() + 1):
                sys.settrace(self.trace)
                try:
                    self.f()
                except ValueError:
                    pass
                else:
                    self.fail("exception not raised!")
        except RuntimeError:
            self.fail("recursion counter not reset")

    # Test the handling of exceptions raised by each kind of trace event. 
Example 21
Project: pefile.pypy   Author: cloudtracer   File: test_isinstance.py    (license) View Source Project 6 votes vote down vote up
def blowstack(fxn, arg, compare_to):
    # Make sure that calling isinstance with a deeply nested tuple for its
    # argument will raise RuntimeError eventually.
    tuple_arg = (compare_to,)


    if test_support.check_impl_detail(cpython=True):
        RECURSION_LIMIT = sys.getrecursionlimit()
    else:
        # on non-CPython implementations, the maximum
        # actual recursion limit might be higher, but
        # probably not higher than 99999
        #
        RECURSION_LIMIT = 99999

    for cnt in xrange(RECURSION_LIMIT+5):
        tuple_arg = (tuple_arg,)
        fxn(arg, tuple_arg) 
Example 22
Project: pefile.pypy   Author: cloudtracer   File: list_tests.py    (license) View Source Project 6 votes vote down vote up
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]")

        if test_support.check_impl_detail():
            depth = sys.getrecursionlimit() + 100
        else:
            depth = 1000 * 1000 # should be enough to exhaust the stack
        l0 = []
        for i in xrange(depth):
            l0 = [l0]
        self.assertRaises(RuntimeError, repr, l0) 
Example 23
Project: ouroboros   Author: pybee   File: test_compile.py    (license) View Source Project 6 votes vote down vote up
def test_compiler_recursion_limit(self):
        # Expected limit is sys.getrecursionlimit() * the scaling factor
        # in symtable.c (currently 3)
        # We expect to fail *at* that limit, because we use up some of
        # the stack depth limit in the test suite code
        # So we check the expected limit and 75% of that
        # XXX (ncoghlan): duplicating the scaling factor here is a little
        # ugly. Perhaps it should be exposed somewhere...
        fail_depth = sys.getrecursionlimit() * 3
        success_depth = int(fail_depth * 0.75)

        def check_limit(prefix, repeated):
            expect_ok = prefix + repeated * success_depth
            self.compile_single(expect_ok)
            broken = prefix + repeated * fail_depth
            details = "Compiling ({!r} + {!r} * {})".format(
                         prefix, repeated, fail_depth)
            with self.assertRaises(RuntimeError, msg=details):
                self.compile_single(broken)

        check_limit("a", "()")
        check_limit("a", ".b")
        check_limit("a", "[0]")
        check_limit("a", "*a") 
Example 24
Project: ouroboros   Author: pybee   File: test_sys.py    (license) View Source Project 6 votes vote down vote up
def test_recursionlimit_recovery(self):
        if hasattr(sys, 'gettrace') and sys.gettrace():
            self.skipTest('fatal error if run with a trace function')

        # NOTE: this test is slightly fragile in that it depends on the current
        # recursion count when executing the test being low enough so as to
        # trigger the recursion recovery detection in the _Py_MakeEndRecCheck
        # macro (see ceval.h).
        oldlimit = sys.getrecursionlimit()
        def f():
            f()
        try:
            for i in (50, 1000):
                # Issue #5392: stack overflow after hitting recursion limit twice
                sys.setrecursionlimit(i)
                self.assertRaises(RuntimeError, f)
                self.assertRaises(RuntimeError, f)
        finally:
            sys.setrecursionlimit(oldlimit) 
Example 25
Project: ouroboros   Author: pybee   File: list_tests.py    (license) View Source Project 6 votes vote down vote up
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]")

        l0 = []
        for i in range(sys.getrecursionlimit() + 100):
            l0 = [l0]
        self.assertRaises(RuntimeError, repr, l0) 
Example 26
Project: ndk-python   Author: gittor   File: test_sys.py    (license) View Source Project 6 votes vote down vote up
def test_recursionlimit(self):
        self.assertRaises(TypeError, sys.getrecursionlimit, 42)
        oldlimit = sys.getrecursionlimit()
        self.assertRaises(TypeError, sys.setrecursionlimit)
        self.assertRaises(ValueError, sys.setrecursionlimit, -42)
        sys.setrecursionlimit(10000)
        self.assertEqual(sys.getrecursionlimit(), 10000)
        sys.setrecursionlimit(oldlimit)

        self.assertRaises(OverflowError, sys.setrecursionlimit, 1 << 31)
        try:
            sys.setrecursionlimit((1 << 31) - 5)
            try:
                # issue13546: isinstance(e, ValueError) used to fail
                # when the recursion limit is close to 1<<31
                raise ValueError()
            except ValueError, e:
                pass
        finally:
            sys.setrecursionlimit(oldlimit) 
Example 27
Project: ndk-python   Author: gittor   File: test_sys_settrace.py    (license) View Source Project 6 votes vote down vote up
def run_test_for_event(self, event):
        """Tests that an exception raised in response to the given event is
        handled OK."""
        self.raiseOnEvent = event
        try:
            for i in xrange(sys.getrecursionlimit() + 1):
                sys.settrace(self.trace)
                try:
                    self.f()
                except ValueError:
                    pass
                else:
                    self.fail("exception not raised!")
        except RuntimeError:
            self.fail("recursion counter not reset")

    # Test the handling of exceptions raised by each kind of trace event. 
Example 28
Project: ndk-python   Author: gittor   File: list_tests.py    (license) View Source Project 6 votes vote down vote up
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]")

        l0 = []
        for i in xrange(sys.getrecursionlimit() + 100):
            l0 = [l0]
        self.assertRaises(RuntimeError, repr, l0) 
Example 29
Project: zenchmarks   Author: squeaky-pl   File: test_script.py    (license) View Source Project 6 votes vote down vote up
def test_getWorkerArguments(self):
        """
        C{_getWorkerArguments} discards options like C{random} as they only
        matter in the manager, and forwards options like C{recursionlimit} or
        C{disablegc}.
        """
        self.addCleanup(sys.setrecursionlimit, sys.getrecursionlimit())
        if gc.isenabled():
            self.addCleanup(gc.enable)

        self.options.parseOptions(["--recursionlimit", "2000", "--random",
                                   "4", "--disablegc"])
        args = self.options._getWorkerArguments()
        self.assertIn("--disablegc", args)
        args.remove("--disablegc")
        self.assertEqual(["--recursionlimit", "2000"], args) 
Example 30
Project: pythonista-scripts   Author: khilnani   File: boardcfg.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, **kwargs):
        self.highlight = kwargs.get('highlight', True)
        self.force_moves = kwargs.get('force_moves', False)
        self.disp_coords = kwargs.get('disp_coords', False)
        self.coord_mode = kwargs.get('coord_mode', 'chess')
        self.move_limit = kwargs.get('move_limit', 50)
        self.disp_sqrs = kwargs.get('disp_sqrs', True)
        self.disp_pieces = kwargs.get('disp_pieces', True)
        self.do_checkmate = kwargs.get('do_checkmate', False)
        self.use_unicode = kwargs.get('use_unicode', use_unicode)
        self.recur_limit = kwargs.get('recur_limit', sys.getrecursionlimit())
        self.disp_turn = kwargs.get('disp_turn', True)
        self.disp_timers = kwargs.get('disp_timers', False)
        self.board = None
        self.game = None
        self.has_gui = False 
Example 31
Project: kbe_server   Author: xiaohaoppy   File: test_compile.py    (license) View Source Project 6 votes vote down vote up
def test_compiler_recursion_limit(self):
        # Expected limit is sys.getrecursionlimit() * the scaling factor
        # in symtable.c (currently 3)
        # We expect to fail *at* that limit, because we use up some of
        # the stack depth limit in the test suite code
        # So we check the expected limit and 75% of that
        # XXX (ncoghlan): duplicating the scaling factor here is a little
        # ugly. Perhaps it should be exposed somewhere...
        fail_depth = sys.getrecursionlimit() * 3
        success_depth = int(fail_depth * 0.75)

        def check_limit(prefix, repeated):
            expect_ok = prefix + repeated * success_depth
            self.compile_single(expect_ok)
            broken = prefix + repeated * fail_depth
            details = "Compiling ({!r} + {!r} * {})".format(
                         prefix, repeated, fail_depth)
            with self.assertRaises(RuntimeError, msg=details):
                self.compile_single(broken)

        check_limit("a", "()")
        check_limit("a", ".b")
        check_limit("a", "[0]")
        check_limit("a", "*a") 
Example 32
Project: kbe_server   Author: xiaohaoppy   File: test_sys.py    (license) View Source Project 6 votes vote down vote up
def test_recursionlimit_recovery(self):
        # NOTE: this test is slightly fragile in that it depends on the current
        # recursion count when executing the test being low enough so as to
        # trigger the recursion recovery detection in the _Py_MakeEndRecCheck
        # macro (see ceval.h).
        oldlimit = sys.getrecursionlimit()
        def f():
            f()
        try:
            for i in (50, 1000):
                # Issue #5392: stack overflow after hitting recursion limit twice
                sys.setrecursionlimit(i)
                self.assertRaises(RuntimeError, f)
                self.assertRaises(RuntimeError, f)
        finally:
            sys.setrecursionlimit(oldlimit) 
Example 33
Project: kbe_server   Author: xiaohaoppy   File: list_tests.py    (license) View Source Project 6 votes vote down vote up
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]")

        l0 = []
        for i in range(sys.getrecursionlimit() + 100):
            l0 = [l0]
        self.assertRaises(RuntimeError, repr, l0) 
Example 34
Project: visual_turing_test-tutorial   Author: mateuszmalinowski   File: read_write.py    (license) View Source Project 6 votes vote down vote up
def pickle_model(
        path, 
        model, 
        word2index_x,
        word2index_y,
        index2word_x,
        index2word_y):
    import sys
    import cPickle as pickle
    modifier=10
    tmp = sys.getrecursionlimit()
    sys.setrecursionlimit(tmp*modifier)
    with open(path, 'wb') as f:
        p_dict = {'model':model,
                'word2index_x':word2index_x,
                'word2index_y':word2index_y,
                'index2word_x':index2word_x,
                'index2word_y':index2word_y}
        pickle.dump(p_dict, f, protocol=2)
    sys.setrecursionlimit(tmp) 
Example 35
Project: NeoAnalysis   Author: neoanalysis   File: exceptionHandling.py    (license) View Source Project 5 votes vote down vote up
def __call__(self, *args):
        ## Start by extending recursion depth just a bit. 
        ## If the error we are catching is due to recursion, we don't want to generate another one here.
        recursionLimit = sys.getrecursionlimit()
        try:
            sys.setrecursionlimit(recursionLimit+100)
        
        
            ## call original exception handler first (prints exception)
            global original_excepthook, callbacks, clear_tracebacks
            try:
                print("===== %s =====" % str(time.strftime("%Y.%m.%d %H:%m:%S", time.localtime(time.time()))))
            except Exception:
                sys.stderr.write("Warning: stdout is broken! Falling back to stderr.\n")
                sys.stdout = sys.stderr

            ret = original_excepthook(*args)
                
            for cb in callbacks:
                try:
                    cb(*args)
                except Exception:
                    print("   --------------------------------------------------------------")
                    print("      Error occurred during exception callback %s" % str(cb))
                    print("   --------------------------------------------------------------")
                    traceback.print_exception(*sys.exc_info())
                
            
            ## Clear long-term storage of last traceback to prevent memory-hogging.
            ## (If an exception occurs while a lot of data is present on the stack, 
            ## such as when loading large files, the data would ordinarily be kept
            ## until the next exception occurs. We would rather release this memory 
            ## as soon as possible.)
            if clear_tracebacks is True:
                sys.last_traceback = None
        
        finally:
            sys.setrecursionlimit(recursionLimit) 
Example 36
Project: NeoAnalysis   Author: neoanalysis   File: exceptionHandling.py    (license) View Source Project 5 votes vote down vote up
def __call__(self, *args):
        ## Start by extending recursion depth just a bit. 
        ## If the error we are catching is due to recursion, we don't want to generate another one here.
        recursionLimit = sys.getrecursionlimit()
        try:
            sys.setrecursionlimit(recursionLimit+100)
        
        
            ## call original exception handler first (prints exception)
            global original_excepthook, callbacks, clear_tracebacks
            try:
                print("===== %s =====" % str(time.strftime("%Y.%m.%d %H:%m:%S", time.localtime(time.time()))))
            except Exception:
                sys.stderr.write("Warning: stdout is broken! Falling back to stderr.\n")
                sys.stdout = sys.stderr

            ret = original_excepthook(*args)
                
            for cb in callbacks:
                try:
                    cb(*args)
                except Exception:
                    print("   --------------------------------------------------------------")
                    print("      Error occurred during exception callback %s" % str(cb))
                    print("   --------------------------------------------------------------")
                    traceback.print_exception(*sys.exc_info())
                
            
            ## Clear long-term storage of last traceback to prevent memory-hogging.
            ## (If an exception occurs while a lot of data is present on the stack, 
            ## such as when loading large files, the data would ordinarily be kept
            ## until the next exception occurs. We would rather release this memory 
            ## as soon as possible.)
            if clear_tracebacks is True:
                sys.last_traceback = None
        
        finally:
            sys.setrecursionlimit(recursionLimit) 
Example 37
Project: deb-python-cassandra-driver   Author: openstack   File: test_concurrent.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def test_recursion_limited(self):
        """
        Verify that recursion is controlled when raise_on_first_error=False and something is wrong with the query.

        PYTHON-585
        """
        max_recursion = sys.getrecursionlimit()
        s = Session(Cluster(), [Host("127.0.0.1", SimpleConvictionPolicy)])
        self.assertRaises(TypeError, execute_concurrent_with_args, s, "doesn't matter", [('param',)] * max_recursion, raise_on_first_error=True)

        results = execute_concurrent_with_args(s, "doesn't matter", [('param',)] * max_recursion, raise_on_first_error=False)  # previously
        self.assertEqual(len(results), max_recursion)
        for r in results:
            self.assertFalse(r[0])
            self.assertIsInstance(r[1], TypeError) 
Example 38
Project: code   Author: ActiveState   File: recipe-546530.py    (MIT License) View Source Project 5 votes vote down vote up
def _getobjects():
        # modules first, globals and stack
        # objects (may contain duplicates)
        return tuple(_values(sys.modules)) + (
               globals(), stack(sys.getrecursionlimit())[2:]) 
Example 39
Project: Blender-WMO-import-export-scripts   Author: WowDevTools   File: bsp_tree.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def GenerateBSP(self, vertices, indices, max_face_count):
        resurs_limit = sys.getrecursionlimit()
        sys.setrecursionlimit(100000)

        faces = []
        for iFace in range(len(indices) // 3):
            faces.append(iFace)

        box = calculate_bounding_box(vertices)
        self.add_node(box, faces, vertices, indices, max_face_count)

        sys.setrecursionlimit(resurs_limit) 
Example 40
Project: abusehelper   Author: Exploit-install   File: test_rulelang.py    (license) View Source Project 5 votes vote down vote up
def test_allow_recursion_deeper_than_the_recursion_limit(self):
        limit = 2 * sys.getrecursionlimit()

        rule = Match("a", "b")
        for _ in xrange(limit):
            rule = No(rule)
        self.assertEqual(format(rule), "no " * limit + "a=b") 
Example 41
Project: abusehelper   Author: Exploit-install   File: test_parsing.py    (license) View Source Project 5 votes vote down vote up
def test_allow_recursion_deeper_than_the_recursion_limit(self):
        expr = parsing.forward_ref()
        expr.set(
            parsing.union(
                parsing.seq(parsing.txt("("), expr, parsing.txt(")"), pick=1),
                parsing.txt("a")
            )
        )

        limit = 2 * sys.getrecursionlimit()
        string = (limit * "(") + "a" + (limit * ")")
        self.assertEqual(expr.parse(string), ('a', '')) 
Example 42
Project: office-interoperability-tools   Author: milossramek   File: gflags.py    (license) View Source Project 5 votes vote down vote up
def _GetCallingModuleObjectAndName():
  """Returns the module that's calling into this module.

  We generally use this function to get the name of the module calling a
  DEFINE_foo... function.
  """
  # Walk down the stack to find the first globals dict that's not ours.
  for depth in range(1, sys.getrecursionlimit()):
    if not sys._getframe(depth).f_globals is globals():
      globals_for_frame = sys._getframe(depth).f_globals
      module, module_name = _GetModuleObjectAndName(globals_for_frame)
      if module_name is not None:
        return module, module_name
  raise AssertionError("No module was found") 
Example 43
Project: RPoint   Author: george17-meet   File: testmock.py    (license) View Source Project 5 votes vote down vote up
def test_copy(self):
        current = sys.getrecursionlimit()
        self.addCleanup(sys.setrecursionlimit, current)

        # can't use sys.maxint as this doesn't exist in Python 3
        sys.setrecursionlimit(int(10e8))
        # this segfaults without the fix in place
        copy.copy(Mock()) 
Example 44
Project: CSB   Author: csb-toolbox   File: __init__.py    (license) View Source Project 5 votes vote down vote up
def serialize(self, file_name):
        """
        Serialize this HMM to a file.

        @param file_name: target file name
        @type file_name: str
        """
        rec = sys.getrecursionlimit()        
        sys.setrecursionlimit(10000)
        csb.io.Pickle.dump(self, open(file_name, 'wb'))
        sys.setrecursionlimit(rec) 
Example 45
Project: CSB   Author: csb-toolbox   File: __init__.py    (license) View Source Project 5 votes vote down vote up
def deserialize(file_name):
        """
        De-serialize an HMM from a file.

        @param file_name: source file name (pickle)
        @type file_name: str
        """
        rec = sys.getrecursionlimit()
        sys.setrecursionlimit(10000)
        try:
            return csb.io.Pickle.load(open(file_name, 'rb'))
        finally:
            sys.setrecursionlimit(rec) 
Example 46
Project: CSB   Author: csb-toolbox   File: __init__.py    (license) View Source Project 5 votes vote down vote up
def runTest(self):
        
        rec = sys.getrecursionlimit()
        obj = ['X']
        copy = utils.deepcopy(obj, recursion=(rec + 1))
        
        self.assertEqual(obj, copy)
        self.assertNotEquals(id(obj), id(copy)) 
Example 47
Project: service-notifications   Author: rehive   File: common.py    (license) View Source Project 5 votes vote down vote up
def limited_recursion(recursion_limit):
    """
    Prevent unlimited recursion.
    """

    old_limit = sys.getrecursionlimit()
    sys.setrecursionlimit(recursion_limit)

    try:
        yield
    finally:
        sys.setrecursionlimit(old_limit) 
Example 48
Project: trainer   Author: nutszebra   File: nutszebra_utility.py    (license) View Source Project 5 votes vote down vote up
def get_recursion_limit():
        return sys.getrecursionlimit() 
Example 49
Project: zippy   Author: securesystemslab   File: python-graph-bench.py    (license) View Source Project 5 votes vote down vote up
def test_accessibility_on_very_deep_graph():
    gr = graph()
    gr.add_nodes(range(0,311)) # 2001
    for i in range(0,310): #2000
        gr.add_edge((i,i+1))
    recursionlimit = getrecursionlimit()
    accessibility(gr)
    assert getrecursionlimit() == recursionlimit 
Example 50
Project: zippy   Author: securesystemslab   File: python-graph-bench.py    (license) View Source Project 5 votes vote down vote up
def main(gr, n):
    recursionlimit = getrecursionlimit()
    for i in range(n):
        accessibility(gr)
    assert getrecursionlimit() == recursionlimit