PageRenderTime 349ms CodeModel.GetById 101ms app.highlight 178ms RepoModel.GetById 63ms app.codeStats 1ms

/pypy/module/sys/test/test_sysmodule.py

https://bitbucket.org/kcr/pypy
Python | 716 lines | 695 code | 20 blank | 1 comment | 8 complexity | adb50ea26555f5ba0516ee0ed1dfd33b MD5 | raw file
  1# -*- coding: iso-8859-1 -*-
  2import sys
  3
  4def test_stdin_exists(space):
  5    space.sys.get('stdin')
  6    space.sys.get('__stdin__')
  7
  8def test_stdout_exists(space):
  9    space.sys.get('stdout')
 10    space.sys.get('__stdout__')
 11
 12class AppTestAppSysTests:
 13
 14    def setup_class(cls):
 15        cls.w_appdirect = cls.space.wrap(cls.runappdirect)
 16        cls.w_filesystemenc = cls.space.wrap(sys.getfilesystemencoding())
 17
 18    def test_sys_in_modules(self):
 19        import sys
 20        modules = sys.modules
 21        assert 'sys' in modules, ( "An entry for sys "
 22                                        "is not in sys.modules.")
 23        sys2 = sys.modules['sys']
 24        assert sys is sys2, "import sys is not sys.modules[sys]."
 25    def test_builtin_in_modules(self):
 26        import sys
 27        modules = sys.modules
 28        assert '__builtin__' in modules, ( "An entry for __builtin__ "
 29                                                    "is not in sys.modules.")
 30        import __builtin__
 31        builtin2 = sys.modules['__builtin__']
 32        assert __builtin__ is builtin2, ( "import __builtin__ "
 33                                            "is not sys.modules[__builtin__].")
 34    def test_builtin_module_names(self):
 35        import sys
 36        names = sys.builtin_module_names
 37        assert 'sys' in names, (
 38                        "sys is not listed as a builtin module.")
 39        assert '__builtin__' in names, (
 40                        "__builtin__ is not listed as a builtin module.")
 41
 42    def test_sys_exc_info(self):
 43        try:
 44            raise Exception
 45        except Exception,e:
 46            import sys
 47            exc_type,exc_val,tb = sys.exc_info()
 48        try:
 49            raise Exception   # 5 lines below the previous one
 50        except Exception,e2:
 51            exc_type2,exc_val2,tb2 = sys.exc_info()
 52        assert exc_type ==Exception
 53        assert exc_val ==e
 54        assert exc_type2 ==Exception
 55        assert exc_val2 ==e2
 56        assert tb2.tb_lineno - tb.tb_lineno == 5
 57
 58    def test_dynamic_attributes(self):
 59        try:
 60            raise Exception
 61        except Exception,e:
 62            import sys
 63            exc_type = sys.exc_type
 64            exc_val = sys.exc_value
 65            tb = sys.exc_traceback
 66        try:
 67            raise Exception   # 7 lines below the previous one
 68        except Exception,e2:
 69            exc_type2 = sys.exc_type
 70            exc_val2 = sys.exc_value
 71            tb2 = sys.exc_traceback
 72        assert exc_type ==Exception
 73        assert exc_val ==e
 74        assert exc_type2 ==Exception
 75        assert exc_val2 ==e2
 76        assert tb2.tb_lineno - tb.tb_lineno == 7
 77
 78    def test_exc_info_normalization(self):
 79        import sys
 80        try:
 81            1/0
 82        except ZeroDivisionError:
 83            etype, val, tb = sys.exc_info()
 84            assert isinstance(val, etype)
 85        else:
 86            raise AssertionError, "ZeroDivisionError not caught"
 87
 88    def test_io(self):
 89        import sys
 90        assert isinstance(sys.__stdout__, file)
 91        assert isinstance(sys.__stderr__, file)
 92        assert isinstance(sys.__stdin__, file)
 93
 94        if self.appdirect and not isinstance(sys.stdin, file):
 95            return
 96
 97        assert isinstance(sys.stdout, file)
 98        assert isinstance(sys.stderr, file)
 99        assert isinstance(sys.stdin, file)
100
101    def test_getfilesystemencoding(self):
102        import sys
103        assert sys.getfilesystemencoding() == self.filesystemenc
104
105    def test_float_info(self):
106        import sys
107        fi = sys.float_info
108        assert isinstance(fi.epsilon, float)
109        assert isinstance(fi.dig, int)
110        assert isinstance(fi.mant_dig, int)
111        assert isinstance(fi.max, float)
112        assert isinstance(fi.max_exp, int)
113        assert isinstance(fi.max_10_exp, int)
114        assert isinstance(fi.min, float)
115        assert isinstance(fi.min_exp, int)
116        assert isinstance(fi.min_10_exp, int)
117        assert isinstance(fi.radix, int)
118        assert isinstance(fi.rounds, int)
119
120    def test_long_info(self):
121        import sys
122        li = sys.long_info
123        assert isinstance(li.bits_per_digit, int)
124        assert isinstance(li.sizeof_digit, int)
125
126class AppTestSysModulePortedFromCPython:
127
128    def setup_class(cls):
129        cls.w_appdirect = cls.space.wrap(cls.runappdirect)
130
131    def test_original_displayhook(self):
132        import sys, cStringIO, __builtin__
133        savestdout = sys.stdout
134        out = cStringIO.StringIO()
135        sys.stdout = out
136
137        dh = sys.__displayhook__
138
139        raises(TypeError, dh)
140        if hasattr(__builtin__, "_"):
141            del __builtin__._
142
143        dh(None)
144        assert out.getvalue() == ""
145        assert not hasattr(__builtin__, "_")
146        dh("hello")
147        assert out.getvalue() == "'hello'\n"
148        assert __builtin__._ == "hello"
149
150        del sys.stdout
151        raises(RuntimeError, dh, 42)
152
153        sys.stdout = savestdout
154
155    def test_lost_displayhook(self):
156        import sys
157        olddisplayhook = sys.displayhook
158        del sys.displayhook
159        code = compile("42", "<string>", "single")
160        raises(RuntimeError, eval, code)
161        sys.displayhook = olddisplayhook
162
163    def test_custom_displayhook(self):
164        import sys
165        olddisplayhook = sys.displayhook
166        def baddisplayhook(obj):
167            raise ValueError
168        sys.displayhook = baddisplayhook
169        code = compile("42", "<string>", "single")
170        raises(ValueError, eval, code)
171        sys.displayhook = olddisplayhook
172
173    def test_original_excepthook(self):
174        import sys, cStringIO
175        savestderr = sys.stderr
176        err = cStringIO.StringIO()
177        sys.stderr = err
178
179        eh = sys.__excepthook__
180
181        raises(TypeError, eh)
182        try:
183            raise ValueError(42)
184        except ValueError, exc:
185            eh(*sys.exc_info())
186
187        sys.stderr = savestderr
188        assert err.getvalue().endswith("ValueError: 42\n")
189
190    def test_excepthook_failsafe_path(self):
191        import traceback
192        original_print_exception = traceback.print_exception
193        import sys, cStringIO
194        savestderr = sys.stderr
195        err = cStringIO.StringIO()
196        sys.stderr = err
197        try:
198            traceback.print_exception = "foo"
199            eh = sys.__excepthook__
200            try:
201                raise ValueError(42)
202            except ValueError, exc:
203                eh(*sys.exc_info())
204        finally:
205            traceback.print_exception = original_print_exception
206            sys.stderr = savestderr
207
208        assert err.getvalue() == "ValueError: 42\n"
209
210    # FIXME: testing the code for a lost or replaced excepthook in
211    # Python/pythonrun.c::PyErr_PrintEx() is tricky.
212
213    def test_exc_clear(self):
214        import sys
215        raises(TypeError, sys.exc_clear, 42)
216
217        # Verify that exc_info is present and matches exc, then clear it, and
218        # check that it worked.
219        def clear_check(exc):
220            typ, value, traceback = sys.exc_info()
221            assert typ is not None
222            assert value is exc
223            assert traceback is not None
224
225            sys.exc_clear()
226
227            typ, value, traceback = sys.exc_info()
228            assert typ is None
229            assert value is None
230            assert traceback is None
231
232        def clear():
233            try:
234                raise ValueError, 42
235            except ValueError, exc:
236                clear_check(exc)
237
238        # Raise an exception and check that it can be cleared
239        clear()
240
241        # Verify that a frame currently handling an exception is
242        # unaffected by calling exc_clear in a nested frame.
243        try:
244            raise ValueError, 13
245        except ValueError, exc:
246            typ1, value1, traceback1 = sys.exc_info()
247            clear()
248            typ2, value2, traceback2 = sys.exc_info()
249
250            assert typ1 is typ2
251            assert value1 is exc
252            assert value1 is value2
253            assert traceback1 is traceback2
254
255        # Check that an exception can be cleared outside of an except block
256        clear_check(exc)
257
258    def test_exit(self):
259        import sys
260        raises(TypeError, sys.exit, 42, 42)
261
262        # call without argument
263        try:
264            sys.exit(0)
265        except SystemExit, exc:
266            assert exc.code == 0
267        except:
268            raise AssertionError, "wrong exception"
269        else:
270            raise AssertionError, "no exception"
271
272        # call with tuple argument with one entry
273        # entry will be unpacked
274        try:
275            sys.exit(42)
276        except SystemExit, exc:
277            assert exc.code == 42
278        except:
279            raise AssertionError, "wrong exception"
280        else:
281            raise AssertionError, "no exception"
282
283        # call with integer argument
284        try:
285            sys.exit((42,))
286        except SystemExit, exc:
287            assert exc.code == 42
288        except:
289            raise AssertionError, "wrong exception"
290        else:
291            raise AssertionError, "no exception"
292
293        # call with string argument
294        try:
295            sys.exit("exit")
296        except SystemExit, exc:
297            assert exc.code == "exit"
298        except:
299            raise AssertionError, "wrong exception"
300        else:
301            raise AssertionError, "no exception"
302
303        # call with tuple argument with two entries
304        try:
305            sys.exit((17, 23))
306        except SystemExit, exc:
307            assert exc.code == (17, 23)
308        except:
309            raise AssertionError, "wrong exception"
310        else:
311            raise AssertionError, "no exception"
312
313    def test_getdefaultencoding(self):
314        import sys
315        raises(TypeError, sys.getdefaultencoding, 42)
316        # can't check more than the type, as the user might have changed it
317        assert isinstance(sys.getdefaultencoding(), str)
318
319    def test_setdefaultencoding(self):
320        import sys
321        if self.appdirect:
322            skip("not worth running appdirect")
323
324        encoding = sys.getdefaultencoding()
325        try:
326            sys.setdefaultencoding("ascii")
327            assert sys.getdefaultencoding() == 'ascii'
328            raises(UnicodeDecodeError, unicode, '\x80')
329
330            sys.setdefaultencoding("latin-1")
331            assert sys.getdefaultencoding() == 'latin-1'
332            assert unicode('\x80') == u'\u0080'
333
334        finally:
335            sys.setdefaultencoding(encoding)
336
337
338    # testing sys.settrace() is done in test_trace.py
339    # testing sys.setprofile() is done in test_profile.py
340
341    def test_setcheckinterval(self):
342        import sys
343        raises(TypeError, sys.setcheckinterval)
344        orig = sys.getcheckinterval()
345        for n in 0, 100, 120, orig: # orig last to restore starting state
346            sys.setcheckinterval(n)
347            assert sys.getcheckinterval() == n
348
349    def test_recursionlimit(self):
350        import sys
351        raises(TypeError, sys.getrecursionlimit, 42)
352        oldlimit = sys.getrecursionlimit()
353        raises(TypeError, sys.setrecursionlimit)
354        raises(ValueError, sys.setrecursionlimit, -42)
355        sys.setrecursionlimit(10000)
356        assert sys.getrecursionlimit() == 10000
357        sys.setrecursionlimit(oldlimit)
358        raises(OverflowError, sys.setrecursionlimit, 1<<31)
359
360    def test_getwindowsversion(self):
361        import sys
362        if hasattr(sys, "getwindowsversion"):
363            v = sys.getwindowsversion()
364            assert isinstance(v, tuple)
365            assert len(v) == 5
366            assert isinstance(v[0], int)
367            assert isinstance(v[1], int)
368            assert isinstance(v[2], int)
369            assert isinstance(v[3], int)
370            assert isinstance(v[4], str)
371
372            assert v[0] == v.major
373            assert v[1] == v.minor
374            assert v[2] == v.build
375            assert v[3] == v.platform
376            assert v[4] == v.service_pack
377
378            assert isinstance(v.service_pack_minor, int)
379            assert isinstance(v.service_pack_major, int)
380            assert isinstance(v.suite_mask, int)
381            assert isinstance(v.product_type, int)
382
383            # This is how platform.py calls it. Make sure tuple still has 5
384            # elements
385            maj, min, buildno, plat, csd = sys.getwindowsversion()
386
387    def test_winver(self):
388        import sys
389        if hasattr(sys, "winver"):
390            assert sys.winver == sys.version[:3]
391
392    def test_dlopenflags(self):
393        import sys
394        if hasattr(sys, "setdlopenflags"):
395            assert hasattr(sys, "getdlopenflags")
396            raises(TypeError, sys.getdlopenflags, 42)
397            oldflags = sys.getdlopenflags()
398            raises(TypeError, sys.setdlopenflags)
399            sys.setdlopenflags(oldflags+1)
400            assert sys.getdlopenflags() == oldflags+1
401            sys.setdlopenflags(oldflags)
402
403    def test_refcount(self):
404        import sys
405        if not hasattr(sys, "getrefcount"):
406            skip('Reference counting is not implemented.')
407
408        raises(TypeError, sys.getrefcount)
409        c = sys.getrefcount(None)
410        n = None
411        assert sys.getrefcount(None) == c+1
412        del n
413        assert sys.getrefcount(None) == c
414        if hasattr(sys, "gettotalrefcount"):
415            assert isinstance(sys.gettotalrefcount(), int)
416
417    def test_getframe(self):
418        import sys
419        raises(TypeError, sys._getframe, 42, 42)
420        raises(ValueError, sys._getframe, 2000000000)
421        assert sys._getframe().f_code.co_name == 'test_getframe'
422        #assert (
423        #    TestSysModule.test_getframe.im_func.func_code \
424        #    is sys._getframe().f_code
425        #)
426
427    def test_getframe_in_returned_func(self):
428        import sys
429        def f():
430            return g()
431        def g():
432            return sys._getframe(0)
433        frame = f()
434        assert frame.f_code.co_name == 'g'
435        assert frame.f_back.f_code.co_name == 'f'
436        assert frame.f_back.f_back.f_code.co_name == 'test_getframe_in_returned_func'
437
438    def test_attributes(self):
439        import sys
440        assert sys.__name__ == 'sys'
441        assert isinstance(sys.modules, dict)
442        assert isinstance(sys.path, list)
443        assert isinstance(sys.api_version, int)
444        assert isinstance(sys.argv, list)
445        assert sys.byteorder in ("little", "big")
446        assert isinstance(sys.builtin_module_names, tuple)
447        assert isinstance(sys.copyright, basestring)
448        #assert isinstance(sys.exec_prefix, basestring) -- not present!
449        assert isinstance(sys.executable, basestring)
450        assert isinstance(sys.hexversion, int)
451        assert isinstance(sys.maxint, int)
452        assert isinstance(sys.maxsize, int)
453        assert isinstance(sys.maxunicode, int)
454        assert isinstance(sys.platform, basestring)
455        #assert isinstance(sys.prefix, basestring) -- not present!
456        assert isinstance(sys.version, basestring)
457        assert isinstance(sys.warnoptions, list)
458        vi = sys.version_info
459        assert isinstance(vi, tuple)
460        assert len(vi) == 5
461        assert isinstance(vi[0], int)
462        assert isinstance(vi[1], int)
463        assert isinstance(vi[2], int)
464        assert vi[3] in ("alpha", "beta", "candidate", "final")
465        assert isinstance(vi[4], int)
466
467    def test_settrace(self):
468        import sys
469        counts = []
470        def trace(x, y, z):
471            counts.append(None)
472
473        def x():
474            pass
475        sys.settrace(trace)
476        try:
477            x()
478            assert sys.gettrace() is trace
479        finally:
480            sys.settrace(None)
481        assert len(counts) == 1
482
483    def test_pypy_attributes(self):
484        import sys
485        assert isinstance(sys.pypy_objspaceclass, str)
486        vi = sys.pypy_version_info
487        assert isinstance(vi, tuple)
488        assert len(vi) == 5
489        assert isinstance(vi[0], int)
490        assert isinstance(vi[1], int)
491        assert isinstance(vi[2], int)
492        assert vi[3] in ("alpha", "beta", "candidate", "dev", "final")
493        assert isinstance(vi[4], int)
494
495    def test_allattributes(self):
496        import sys
497        sys.__dict__   # check that we don't crash initializing any attribute
498
499    def test_subversion(self):
500        import sys
501        assert sys.subversion == ('PyPy', '', '')
502
503    def test__mercurial(self):
504        import sys, re
505        project, hgtag, hgid = sys._mercurial
506        assert project == 'PyPy'
507        # the tag or branch may be anything, including the empty string
508        assert isinstance(hgtag, str)
509        # the id is either nothing, or an id of 12 hash digits, with a possible
510        # suffix of '+' if there are local modifications
511        assert hgid == '' or re.match('[0-9a-f]{12}\+?', hgid)
512        # the id should also show up in sys.version
513        if hgid != '':
514            assert hgid in sys.version
515
516    def test_trace_exec_execfile(self):
517        import sys
518        found = []
519        def do_tracing(f, *args):
520            print f.f_code.co_filename, f.f_lineno, args
521            if f.f_code.co_filename == 'foobar':
522                found.append(args[0])
523            return do_tracing
524        co = compile("execfile('this-file-does-not-exist!')",
525                     'foobar', 'exec')
526        sys.settrace(do_tracing)
527        try:
528            exec co in {}
529        except IOError:
530            pass
531        sys.settrace(None)
532        assert found == ['call', 'line', 'exception', 'return']
533
534    def test_float_repr_style(self):
535        import sys
536
537        # If this ever actually becomes a compilation option this test should
538        # be changed.
539        assert sys.float_repr_style == "short"
540
541
542class AppTestCurrentFrames:
543    def test_current_frames(self):
544        try:
545            import thread
546        except ImportError:
547            pass
548        else:
549            skip('This test requires an intepreter without threads')
550        import sys
551
552        def f():
553            return sys._current_frames()
554        frames = f()
555        assert frames.keys() == [0]
556        assert frames[0].f_code.co_name in ('f', '?')
557
558
559class AppTestCurrentFramesWithThread(AppTestCurrentFrames):
560    spaceconfig = {
561        "usemodules": ["rctime", "thread"],
562    }
563
564    def test_current_frames(self):
565        import sys
566        import time
567        import thread
568
569        # XXX workaround for now: to prevent deadlocks, call
570        # sys._current_frames() once before starting threads.
571        # This is an issue in non-translated versions only.
572        sys._current_frames()
573
574        thread_id = thread.get_ident()
575        def other_thread():
576            print "thread started"
577            lock2.release()
578            lock1.acquire()
579        lock1 = thread.allocate_lock()
580        lock2 = thread.allocate_lock()
581        lock1.acquire()
582        lock2.acquire()
583        thread.start_new_thread(other_thread, ())
584
585        def f():
586            lock2.acquire()
587            return sys._current_frames()
588
589        frames = f()
590        lock1.release()
591        thisframe = frames.pop(thread_id)
592        assert thisframe.f_code.co_name in ('f', '?')
593
594        assert len(frames) == 1
595        _, other_frame = frames.popitem()
596        assert other_frame.f_code.co_name in ('other_thread', '?')
597
598
599class AppTestSysExcInfoDirect:
600
601    def setup_method(self, meth):
602        self.checking = not self.runappdirect
603        if self.checking:
604            self.seen = []
605            from pypy.module.sys import vm
606            def exc_info_with_tb(*args):
607                self.seen.append("n")     # not optimized
608                return self.old[0](*args)
609            def exc_info_without_tb(*args):
610                self.seen.append("y")     # optimized
611                return self.old[1](*args)
612            self.old = [vm.exc_info_with_tb, vm.exc_info_without_tb]
613            vm.exc_info_with_tb = exc_info_with_tb
614            vm.exc_info_without_tb = exc_info_without_tb
615            #
616            from rpython.rlib import jit
617            self.old2 = [jit.we_are_jitted]
618            jit.we_are_jitted = lambda: True
619
620    def teardown_method(self, meth):
621        if self.checking:
622            from pypy.module.sys import vm
623            from rpython.rlib import jit
624            vm.exc_info_with_tb = self.old[0]
625            vm.exc_info_without_tb = self.old[1]
626            jit.we_are_jitted = self.old2[0]
627            #
628            assert ''.join(self.seen) == meth.expected
629
630    def test_returns_none(self):
631        import sys
632        assert sys.exc_info() == (None, None, None)
633        assert sys.exc_info()[0] is None
634        assert sys.exc_info()[1] is None
635        assert sys.exc_info()[2] is None
636        assert sys.exc_info()[:2] == (None, None)
637        assert sys.exc_info()[:3] == (None, None, None)
638        assert sys.exc_info()[0:2] == (None, None)
639        assert sys.exc_info()[2:4] == (None,)
640    test_returns_none.expected = 'nnnnnnnn'
641
642    def test_returns_subscr(self):
643        import sys
644        e = KeyError("boom")
645        try:
646            raise e
647        except:
648            assert sys.exc_info()[0] is KeyError  # y
649            assert sys.exc_info()[1] is e         # y
650            assert sys.exc_info()[2] is not None  # n
651            assert sys.exc_info()[-3] is KeyError # y
652            assert sys.exc_info()[-2] is e        # y
653            assert sys.exc_info()[-1] is not None # n
654    test_returns_subscr.expected = 'yynyyn'
655
656    def test_returns_slice_2(self):
657        import sys
658        e = KeyError("boom")
659        try:
660            raise e
661        except:
662            foo = sys.exc_info()                  # n
663            assert sys.exc_info()[:0] == ()       # y
664            assert sys.exc_info()[:1] == foo[:1]  # y
665            assert sys.exc_info()[:2] == foo[:2]  # y
666            assert sys.exc_info()[:3] == foo      # n
667            assert sys.exc_info()[:4] == foo      # n
668            assert sys.exc_info()[:-1] == foo[:2] # y
669            assert sys.exc_info()[:-2] == foo[:1] # y
670            assert sys.exc_info()[:-3] == ()      # y
671    test_returns_slice_2.expected = 'nyyynnyyy'
672
673    def test_returns_slice_3(self):
674        import sys
675        e = KeyError("boom")
676        try:
677            raise e
678        except:
679            foo = sys.exc_info()                   # n
680            assert sys.exc_info()[2:2] == ()       # y
681            assert sys.exc_info()[0:1] == foo[:1]  # y
682            assert sys.exc_info()[1:2] == foo[1:2] # y
683            assert sys.exc_info()[0:3] == foo      # n
684            assert sys.exc_info()[2:4] == foo[2:]  # n
685            assert sys.exc_info()[0:-1] == foo[:2] # y
686            assert sys.exc_info()[0:-2] == foo[:1] # y
687            assert sys.exc_info()[5:-3] == ()      # y
688    test_returns_slice_3.expected = 'nyyynnyyy'
689
690    def test_strange_invocation(self):
691        import sys
692        e = KeyError("boom")
693        try:
694            raise e
695        except:
696            a = []; k = {}
697            assert sys.exc_info(*a)[:0] == ()
698            assert sys.exc_info(**k)[:0] == ()
699    test_strange_invocation.expected = 'nn'
700
701    def test_call_in_subfunction(self):
702        import sys
703        def g():
704            # this case is not optimized, because we need to search the
705            # frame chain.  it's probably not worth the complications
706            return sys.exc_info()[1]
707        e = KeyError("boom")
708        try:
709            raise e
710        except:
711            assert g() is e
712    test_call_in_subfunction.expected = 'n'
713
714
715class AppTestSysExcInfoDirectCallMethod(AppTestSysExcInfoDirect):
716    spaceconfig = {"objspace.opcodes.CALL_METHOD": True}