Example #1
0
    def test_issue3221(self):
        # Regression test for http://bugs.python.org/issue3221.
        def check_absolute():
            exec "from os import path" in ns
        def check_relative():
            exec "from . import relimport" in ns

        # Check both OK with __package__ and __name__ correct
        ns = dict(__package__='test', __name__='test.notarealmodule')
        check_absolute()
        check_relative()

        # Check both OK with only __name__ wrong
        ns = dict(__package__='test', __name__='notarealpkg.notarealmodule')
        check_absolute()
        check_relative()

        # Check relative fails with only __package__ wrong
        ns = dict(__package__='foo', __name__='test.notarealmodule')
        with check_warnings(('.+foo', RuntimeWarning)):
            check_absolute()
        self.assertRaises(SystemError, check_relative)

        # Check relative fails with __package__ and __name__ wrong
        ns = dict(__package__='foo', __name__='notarealpkg.notarealmodule')
        with check_warnings(('.+foo', RuntimeWarning)):
            check_absolute()
        self.assertRaises(SystemError, check_relative)

        # Check both fail with package set to a non-string
        ns = dict(__package__=object())
        self.assertRaises(ValueError, check_absolute)
        self.assertRaises(ValueError, check_relative)
Example #2
0
    def test_compress_deprecated(self):
        tmpdir, tmpdir2, base_name =  self._create_files()

        # using compress and testing the PendingDeprecationWarning
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        try:
            with check_warnings() as w:
                warnings.simplefilter("always")
                make_tarball(base_name, 'dist', compress='compress')
        finally:
            os.chdir(old_dir)
        tarball = base_name + '.tar.Z'
        self.assertTrue(os.path.exists(tarball))
        self.assertEqual(len(w.warnings), 1)

        # same test with dry_run
        os.remove(tarball)
        old_dir = os.getcwd()
        os.chdir(tmpdir)
        try:
            with check_warnings() as w:
                warnings.simplefilter("always")
                make_tarball(base_name, 'dist', compress='compress',
                             dry_run=True)
        finally:
            os.chdir(old_dir)
        self.assertFalse(os.path.exists(tarball))
        self.assertEqual(len(w.warnings), 1)
Example #3
0
    def test_check_warnings(self):
        # Explicit tests for the test_support convenience wrapper
        wmod = self.module
        if wmod is not sys.modules['warnings']:
            self.skipTest('module to test is not loaded warnings module')
        with test_support.check_warnings(quiet=False) as w:
            self.assertEqual(w.warnings, [])
            wmod.simplefilter("always")
            wmod.warn("foo")
            self.assertEqual(str(w.message), "foo")
            wmod.warn("bar")
            self.assertEqual(str(w.message), "bar")
            self.assertEqual(str(w.warnings[0].message), "foo")
            self.assertEqual(str(w.warnings[1].message), "bar")
            w.reset()
            self.assertEqual(w.warnings, [])

        with test_support.check_warnings():
            # defaults to quiet=True without argument
            pass
        with test_support.check_warnings(('foo', UserWarning)):
            wmod.warn("foo")

        with self.assertRaises(AssertionError):
            with test_support.check_warnings(('', RuntimeWarning)):
                # defaults to quiet=False with argument
                pass
        with self.assertRaises(AssertionError):
            with test_support.check_warnings(('foo', RuntimeWarning)):
                wmod.warn("foo")
 def test_issue3221(self):
     def check_absolute():
         exec "from os import path" in ns
     def check_relative():
         exec "from . import relimport" in ns
     # Check both OK with __package__ and __name__ correct
     ns = dict(__package__='test', __name__='test.notarealmodule')
     check_absolute()
     check_relative()
     # Check both OK with only __name__ wrong
     ns = dict(__package__='test', __name__='notarealpkg.notarealmodule')
     check_absolute()
     check_relative()
     # Check relative fails with only __package__ wrong
     ns = dict(__package__='foo', __name__='test.notarealmodule')
     with check_warnings() as w:
         check_absolute()
         self.assert_('foo' in str(w.message))
         self.assertEqual(w.category, RuntimeWarning)
     self.assertRaises(SystemError, check_relative)
     # Check relative fails with __package__ and __name__ wrong
     ns = dict(__package__='foo', __name__='notarealpkg.notarealmodule')
     with check_warnings() as w:
         check_absolute()
         self.assert_('foo' in str(w.message))
         self.assertEqual(w.category, RuntimeWarning)
     self.assertRaises(SystemError, check_relative)
     # Check both fail with package set to a non-string
     ns = dict(__package__=object())
     self.assertRaises(ValueError, check_absolute)
     self.assertRaises(ValueError, check_relative)
Example #5
0
 def test_softspace(self):
     expected = 'file.softspace not supported in 3.x'
     with file(__file__) as f:
         with check_warnings() as w:
             self.assertWarning(f.softspace, w, expected)
         def set():
             f.softspace = 0
         with check_warnings() as w:
             self.assertWarning(set(), w, expected)
Example #6
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 #7
0
    def testAssertItemsEqual(self):
        a = object()
        self.assertItemsEqual([1, 2, 3], [3, 2, 1])
        self.assertItemsEqual(["foo", "bar", "baz"], ["bar", "baz", "foo"])
        self.assertItemsEqual([a, a, 2, 2, 3], (a, 2, 3, a, 2))
        self.assertItemsEqual([1, "2", "a", "a"], ["a", "2", True, "a"])
        self.assertRaises(self.failureException, self.assertItemsEqual, [1, 2] + [3] * 100, [1] * 100 + [2, 3])
        self.assertRaises(self.failureException, self.assertItemsEqual, [1, "2", "a", "a"], ["a", "2", True, 1])
        self.assertRaises(self.failureException, self.assertItemsEqual, [10], [10, 11])
        self.assertRaises(self.failureException, self.assertItemsEqual, [10, 11], [10])
        self.assertRaises(self.failureException, self.assertItemsEqual, [10, 11, 10], [10, 11])

        # Test that sequences of unhashable objects can be tested for sameness:
        self.assertItemsEqual([[1, 2], [3, 4], 0], [False, [3, 4], [1, 2]])
        with test_support.check_warnings(quiet=True) as w:
            # hashable types, but not orderable
            self.assertRaises(self.failureException, self.assertItemsEqual, [], [divmod, "x", 1, 5j, 2j, frozenset()])
            # comparing dicts raises a py3k warning
            self.assertItemsEqual([{"a": 1}, {"b": 2}], [{"b": 2}, {"a": 1}])
            # comparing heterogenous non-hashable sequences raises a py3k warning
            self.assertItemsEqual([1, "x", divmod, []], [divmod, [], "x", 1])
            self.assertRaises(self.failureException, self.assertItemsEqual, [], [divmod, [], "x", 1, 5j, 2j, set()])
            # fail the test if warnings are not silenced
            if w.warnings:
                self.fail("assertItemsEqual raised a warning: " + str(w.warnings[0]))
        self.assertRaises(self.failureException, self.assertItemsEqual, [[1]], [[2]])

        # Same elements, but not same sequence length
        self.assertRaises(self.failureException, self.assertItemsEqual, [1, 1, 2], [2, 1])
        self.assertRaises(self.failureException, self.assertItemsEqual, [1, 1, "2", "a", "a"], ["2", "2", True, "a"])
        self.assertRaises(
            self.failureException, self.assertItemsEqual, [1, {"b": 2}, None, True], [{"b": 2}, True, None]
        )
Example #8
0
 def testWarnings(self):
     with check_warnings(quiet=True) as w:
         self.assertEqual(w.warnings, [])
         self.assertRaises(TypeError, _FileIO, [])
         self.assertEqual(w.warnings, [])
         self.assertRaises(ValueError, _FileIO, "/some/invalid/name", "rt")
         self.assertEqual(w.warnings, [])
Example #9
0
def test_main():
    with check_warnings(
        ("complex divmod.., // and % are deprecated", DeprecationWarning),
        ("classic (int|long) division", DeprecationWarning),
        quiet=True,
    ):
        run_unittest(CoercionTest)
Example #10
0
    def test_forbidden_names(self):
        # So we don't screw up our globals
        def safe_exec(expr):
            def f(**kwargs): pass
            exec expr in {'f' : f}

        tests = [("True", "assignment to True or False is forbidden in 3.x"),
                 ("False", "assignment to True or False is forbidden in 3.x"),
                 ("nonlocal", "nonlocal is a keyword in 3.x")]
        with check_warnings() as w:
            for keyword, expected in tests:
                safe_exec("{0} = False".format(keyword))
                self.assertWarning(None, w, expected)
                w.reset()
                try:
                    safe_exec("obj.{0} = True".format(keyword))
                except NameError:
                    pass
                self.assertWarning(None, w, expected)
                w.reset()
                safe_exec("def {0}(): pass".format(keyword))
                self.assertWarning(None, w, expected)
                w.reset()
                safe_exec("class {0}: pass".format(keyword))
                self.assertWarning(None, w, expected)
                w.reset()
                safe_exec("def f({0}=43): pass".format(keyword))
                self.assertWarning(None, w, expected)
                w.reset()
Example #11
0
 def test_check_metadata_deprecated(self):
     # makes sure make_metadata is deprecated
     dist, cmd = self.get_cmd()
     with check_warnings() as w:
         warnings.simplefilter("always")
         cmd.check_metadata()
         self.assertEqual(len(w.warnings), 1)
    def test_extension_init(self):
        # the first argument, which is the name, must be a string
        self.assertRaises(AssertionError, Extension, 1, [])
        ext = Extension('name', [])
        self.assertEquals(ext.name, 'name')

        # the second argument, which is the list of files, must
        # be a list of strings
        self.assertRaises(AssertionError, Extension, 'name', 'file')
        self.assertRaises(AssertionError, Extension, 'name', ['file', 1])
        ext = Extension('name', ['file1', 'file2'])
        self.assertEquals(ext.sources, ['file1', 'file2'])

        # others arguments have defaults
        for attr in ('include_dirs', 'define_macros', 'undef_macros',
                     'library_dirs', 'libraries', 'runtime_library_dirs',
                     'extra_objects', 'extra_compile_args', 'extra_link_args',
                     'export_symbols', 'swig_opts', 'depends'):
            self.assertEquals(getattr(ext, attr), [])

        self.assertEquals(ext.language, None)
        self.assertEquals(ext.optional, None)

        # if there are unknown keyword options, warn about them
        with check_warnings() as w:
            warnings.simplefilter('always')
            ext = Extension('name', ['file1', 'file2'], chic=True)

        self.assertEquals(len(w.warnings), 1)
        self.assertEquals(str(w.warnings[0].message),
                          "Unknown Extension options: 'chic'")
Example #13
0
 def testDeprecatedMessageAttribute(self):
     # Accessing BaseException.message and relying on its value set by
     # BaseException.__init__ triggers a deprecation warning.
     exc = BaseException("foo")
     with check_warnings(("BaseException.message has been deprecated " "as of Python 2.6", DeprecationWarning)) as w:
         self.assertEqual(exc.message, "foo")
     self.assertEqual(len(w.warnings), 1)
 def check_all(self, modname):
     names = {}
     with support.check_warnings((".* (module|package)",
                                  DeprecationWarning), quiet=True):
         try:
             exec "import %s" % modname in names
         except:
             # Silent fail here seems the best route since some modules
             # may not be available or not initialize properly in all
             # environments.
             raise FailedImport(modname)
     if not hasattr(sys.modules[modname], "__all__"):
         raise NoAll(modname)
     names = {}
     try:
         exec "from %s import *" % modname in names
     except Exception as e:
         # Include the module name in the exception string
         self.fail("__all__ failure in {}: {}: {}".format(
                   modname, e.__class__.__name__, e))
     if "__builtins__" in names:
         del names["__builtins__"]
     keys = set(names)
     all = set(sys.modules[modname].__all__)
     self.assertEqual(keys, all)
Example #15
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})
     with test_support.check_warnings(('', UnicodeWarning)):
         one = ''.join((chr(i) for i in range(255)))
         with self.assertRaises(self.failureException):
             self.assertDictContainsSubset({'foo': one}, {'foo': u'\ufffd'})
Example #16
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})

        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 #17
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})

        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 #18
0
    def test_format_deprecation(self):
        buf = create_string_buffer(' ' * 100)

        with check_warnings(('PyOS_ascii_formatd is deprecated',
                             DeprecationWarning)):
            PyOS_ascii_formatd(byref(buf), sizeof(buf), '%+.10f',
                               c_double(10.0))
            self.assertEqual(buf.value, '+10.0000000000')
Example #19
0
 def test_methods_members(self):
     expected = '__members__ and __methods__ not supported in 3.x'
     class C:
         __methods__ = ['a']
         __members__ = ['b']
     c = C()
     with check_warnings() as w:
         self.assertWarning(dir(c), w, expected)
Example #20
0
 def testPendingDeprecationMethodNames(self):
     with test_support.check_warnings():
         self.failIfEqual(3, 5)
         self.assertEqual(3, 3)
         self.failUnlessAlmostEqual(2.0, 2.0)
         self.failIfAlmostEqual(3.0, 5.0)
         self.assertTrue(True)
         self.failUnlessRaises(TypeError, lambda _: 3.14 + u'spam')
         self.assertFalse(False)
Example #21
0
 def test_os_path_walk(self):
     msg = "In 3.x, os.path.walk is removed in favor of os.walk."
     def dumbo(where, names, args): pass
     for path_mod in ("ntpath", "macpath", "os2emxpath", "posixpath"):
         mod = __import__(path_mod)
         reset_module_registry(mod)
         with check_warnings() as w:
             mod.walk("crashers", dumbo, None)
         self.assertEquals(str(w.message), msg)
Example #22
0
 def test_paren_arg_names(self):
     expected = 'parenthesized argument names are invalid in 3.x'
     def check(s):
         exec s in {}
         self.assertWarning(None, w, expected)
     with check_warnings() as w:
         check("def f((x)): pass")
         check("def f((((x))), (y)): pass")
         check("def f((x), (((y))), m=32): pass")
Example #23
0
 def test_deep_copy(self):
     dup = copy.deepcopy(self.set)
     ##print type(dup), repr(dup)
     with test_support.check_warnings():
         dup_list = sorted(dup)
         set_list = sorted(self.set)
     self.assertEqual(len(dup_list), len(set_list))
     for i in range(len(dup_list)):
         self.assertEqual(dup_list[i], set_list[i])
Example #24
0
 def test_frame_attributes(self):
     template = "%s has been removed in 3.x"
     f = sys._getframe(0)
     for attr in ("f_exc_traceback", "f_exc_value", "f_exc_type"):
         expected = template % attr
         with check_warnings() as w:
             self.assertWarning(getattr(f, attr), w, expected)
             w.reset()
             self.assertWarning(setattr(f, attr, None), w, expected)
Example #25
0
def test_main():
    with check_warnings(("complex divmod.., // and % are deprecated",
                         DeprecationWarning),
                        ("classic (int|long) division", DeprecationWarning),
                        quiet=True):
        process_infix_results()
        # now infix_results has two lists of results for every pairing.

        run_unittest(CoercionTest)
Example #26
0
 def test_hash_inheritance(self):
     with check_warnings() as w:
         # With object as the base class
         class WarnOnlyCmp(object):
             def __cmp__(self, other): pass
         self.assertEqual(len(w.warnings), 1)
         self.assertWarning(None, w,
              "Overriding __cmp__ blocks inheritance of __hash__ in 3.x")
         w.reset()
         class WarnOnlyEq(object):
             def __eq__(self, other): pass
         self.assertEqual(len(w.warnings), 1)
         self.assertWarning(None, w,
              "Overriding __eq__ blocks inheritance of __hash__ in 3.x")
         w.reset()
         class WarnCmpAndEq(object):
             def __cmp__(self, other): pass
             def __eq__(self, other): pass
         self.assertEqual(len(w.warnings), 2)
         self.assertWarning(None, w.warnings[0],
              "Overriding __cmp__ blocks inheritance of __hash__ in 3.x")
         self.assertWarning(None, w,
              "Overriding __eq__ blocks inheritance of __hash__ in 3.x")
         w.reset()
         class NoWarningOnlyHash(object):
             def __hash__(self): pass
         self.assertEqual(len(w.warnings), 0)
         # With an intermediate class in the heirarchy
         class DefinesAllThree(object):
             def __cmp__(self, other): pass
             def __eq__(self, other): pass
             def __hash__(self): pass
         class WarnOnlyCmp(DefinesAllThree):
             def __cmp__(self, other): pass
         self.assertEqual(len(w.warnings), 1)
         self.assertWarning(None, w,
              "Overriding __cmp__ blocks inheritance of __hash__ in 3.x")
         w.reset()
         class WarnOnlyEq(DefinesAllThree):
             def __eq__(self, other): pass
         self.assertEqual(len(w.warnings), 1)
         self.assertWarning(None, w,
              "Overriding __eq__ blocks inheritance of __hash__ in 3.x")
         w.reset()
         class WarnCmpAndEq(DefinesAllThree):
             def __cmp__(self, other): pass
             def __eq__(self, other): pass
         self.assertEqual(len(w.warnings), 2)
         self.assertWarning(None, w.warnings[0],
              "Overriding __cmp__ blocks inheritance of __hash__ in 3.x")
         self.assertWarning(None, w,
              "Overriding __eq__ blocks inheritance of __hash__ in 3.x")
         w.reset()
         class NoWarningOnlyHash(DefinesAllThree):
             def __hash__(self): pass
         self.assertEqual(len(w.warnings), 0)
Example #27
0
 def assertOldResultWarning(self, test, failures):
     if test_support.due_to_ironpython_bug("http://ironpython.codeplex.com/workitem/28171"):
         result = OldResult()
         test.run(result)
         self.assertEqual(len(result.failures), failures)
     else:
         with test_support.check_warnings(("TestResult has no add.+ method,", RuntimeWarning)):
             result = OldResult()
             test.run(result)
             self.assertEqual(len(result.failures), failures)
Example #28
0
 def test_dict_inequality_comparisons(self):
     expected = 'dict inequality comparisons not supported in 3.x'
     with check_warnings() as w:
         self.assertWarning({} < {2:3}, w, expected)
         w.reset()
         self.assertWarning({} <= {}, w, expected)
         w.reset()
         self.assertWarning({} > {2:3}, w, expected)
         w.reset()
         self.assertWarning({2:3} >= {}, w, expected)
Example #29
0
 def test_urandom(self):
     with test_support.check_warnings():
         self.assertEqual(len(os.urandom(1)), 1)
         self.assertEqual(len(os.urandom(10)), 10)
         self.assertEqual(len(os.urandom(100)), 100)
         self.assertEqual(len(os.urandom(1000)), 1000)
         # see http://bugs.python.org/issue3708
         self.assertEqual(len(os.urandom(0.9)), 0)
         self.assertEqual(len(os.urandom(1.1)), 1)
         self.assertEqual(len(os.urandom(2.0)), 2)
Example #30
0
 def test_deprecated_parse_qsl(self):
     # this func is moved to urlparse, this is just a sanity check
     if due_to_ironpython_bug("http://ironpython.codeplex.com/workitem/28171"):
         self.assertEqual([('a', 'A1'), ('b', 'B2'), ('B', 'B3')],
                          cgi.parse_qsl('a=A1&b=B2&B=B3'))
     else:
         with check_warnings(('cgi.parse_qsl is deprecated, use urlparse.'
                              'parse_qsl instead', PendingDeprecationWarning)):
             self.assertEqual([('a', 'A1'), ('b', 'B2'), ('B', 'B3')],
                              cgi.parse_qsl('a=A1&b=B2&B=B3'))
 def test_short_min(self):
     with test_support.check_warnings(('', RuntimeWarning)):
         ts.T_SHORT = SHRT_MIN - 1
Example #32
0
 def test_type_inequality_comparisons(self):
     expected = 'type inequality comparisons not supported in 3.x'
     with check_warnings() as w:
         self.assertWarning(int < str, w, expected)
         w.reset()
         self.assertWarning(type < object, w, expected)
 def test_byte_min(self):
     with test_support.check_warnings() as w:
         ts.T_BYTE = CHAR_MIN - 1
         self.has_warned(w)
 def test_short_min(self):
     with test_support.check_warnings() as w:
         ts.T_SHORT = SHRT_MIN - 1
         self.has_warned(w)
Example #35
0
 def test_deprecated_parse_qsl(self):
     with check_warnings():
         # this func is moved to urlparse, this is just a sanity check
         self.assertEqual([('a', 'A1'), ('b', 'B2'), ('B', 'B3')],
                          cgi.parse_qsl('a=A1&b=B2&B=B3'))
Example #36
0
            def run(self):
                from random import randrange

                # Create all interesting powers of 2.
                values = []
                for exp in range(self.bitsize + 3):
                    values.append(1L << exp)

                # Add some random values.
                for i in range(self.bitsize):
                    val = 0L
                    for j in range(self.bytesize):
                        val = (val << 8) | randrange(256)
                    values.append(val)

                # Values absorbed from other tests
                values.extend([300, 700000, sys.maxint * 4])

                # Try all those, and their negations, and +-1 from
                # them.  Note that this tests all power-of-2
                # boundaries in range, and a few out of range, plus
                # +-(2**n +- 1).
                for base in values:
                    for val in -base, base:
                        for incr in -1, 0, 1:
                            x = val + incr
                            self.test_one(int(x))
                            self.test_one(long(x))

                # Some error cases.
                class NotAnIntNS(object):
                    def __int__(self):
                        return 42

                    def __long__(self):
                        return 1729L

                class NotAnIntOS:
                    def __int__(self):
                        return 85

                    def __long__(self):
                        return -163L

                # Objects with an '__index__' method should be allowed
                # to pack as integers.  That is assuming the implemented
                # '__index__' method returns and 'int' or 'long'.
                class Indexable(object):
                    def __init__(self, value):
                        self._value = value

                    def __index__(self):
                        return self._value

                # If the '__index__' method raises a type error, then
                # '__int__' should be used with a deprecation warning.
                class BadIndex(object):
                    def __index__(self):
                        raise TypeError

                    def __int__(self):
                        return 42

                self.assertRaises((TypeError, struct.error), struct.pack,
                                  self.format, "a string")
                self.assertRaises((TypeError, struct.error), struct.pack,
                                  self.format, randrange)
                with check_warnings(("integer argument expected, "
                                     "got non-integer", DeprecationWarning)):
                    with self.assertRaises((TypeError, struct.error)):
                        struct.pack(self.format, 3 + 42j)

                # an attempt to convert a non-integer (with an
                # implicit conversion via __int__) should succeed,
                # with a DeprecationWarning
                for nonint in NotAnIntNS(), NotAnIntOS(), BadIndex():
                    with check_warnings((".*integer argument expected, got non"
                                         "-integer", DeprecationWarning)) as w:
                        got = struct.pack(self.format, nonint)
                    lineno = inspect.currentframe().f_lineno - 1
                    self.assertEqual(w.filename, testmod_filename)
                    self.assertEqual(w.lineno, lineno)
                    self.assertEqual(len(w.warnings), 1)
                    expected = struct.pack(self.format, int(nonint))
                    self.assertEqual(got, expected)

                # Check for legitimate values from '__index__'.
                for obj in (Indexable(0), Indexable(10), Indexable(17),
                            Indexable(42), Indexable(100), Indexable(127)):
                    try:
                        struct.pack(format, obj)
                    except:
                        self.fail("integer code pack failed on object "
                                  "with '__index__' method")

                # Check for bogus values from '__index__'.
                for obj in (Indexable('a'), Indexable(u'b'), Indexable(None),
                            Indexable({'a': 1}), Indexable([1, 2, 3])):
                    self.assertRaises((TypeError, struct.error), struct.pack,
                                      self.format, obj)
Example #37
0
def test_main():
    with test_support.check_warnings(
        ("With-statements now directly support "
         "multiple context managers", DeprecationWarning)):
        test_support.run_unittest(__name__)
Example #38
0
    def test_format(self):
        self.assertEqual(''.format(), '')
        self.assertEqual('a'.format(), 'a')
        self.assertEqual('ab'.format(), 'ab')
        self.assertEqual('a{{'.format(), 'a{')
        self.assertEqual('a}}'.format(), 'a}')
        self.assertEqual('{{b'.format(), '{b')
        self.assertEqual('}}b'.format(), '}b')
        self.assertEqual('a{{b'.format(), 'a{b')

        # examples from the PEP:
        import datetime
        self.assertEqual("My name is {0}".format('Fred'), "My name is Fred")
        self.assertEqual("My name is {0[name]}".format(dict(name='Fred')),
                         "My name is Fred")
        self.assertEqual("My name is {0} :-{{}}".format('Fred'),
                         "My name is Fred :-{}")

        d = datetime.date(2007, 8, 18)
        self.assertEqual("The year is {0.year}".format(d), "The year is 2007")

        # classes we'll use for testing
        class C:
            def __init__(self, x=100):
                self._x = x

            def __format__(self, spec):
                return spec

        class D:
            def __init__(self, x):
                self.x = x

            def __format__(self, spec):
                return str(self.x)

        # class with __str__, but no __format__
        class E:
            def __init__(self, x):
                self.x = x

            def __str__(self):
                return 'E(' + self.x + ')'

        # class with __repr__, but no __format__ or __str__
        class F:
            def __init__(self, x):
                self.x = x

            def __repr__(self):
                return 'F(' + self.x + ')'

        # class with __format__ that forwards to string, for some format_spec's
        class G:
            def __init__(self, x):
                self.x = x

            def __str__(self):
                return "string is " + self.x

            def __format__(self, format_spec):
                if format_spec == 'd':
                    return 'G(' + self.x + ')'
                return object.__format__(self, format_spec)

        # class that returns a bad type from __format__
        class H:
            def __format__(self, format_spec):
                return 1.0

        class I(datetime.date):
            def __format__(self, format_spec):
                return self.strftime(format_spec)

        class J(int):
            def __format__(self, format_spec):
                return int.__format__(self * 2, format_spec)

        self.assertEqual(''.format(), '')
        self.assertEqual('abc'.format(), 'abc')
        self.assertEqual('{0}'.format('abc'), 'abc')
        self.assertEqual('{0:}'.format('abc'), 'abc')
        self.assertEqual('X{0}'.format('abc'), 'Xabc')
        self.assertEqual('{0}X'.format('abc'), 'abcX')
        self.assertEqual('X{0}Y'.format('abc'), 'XabcY')
        self.assertEqual('{1}'.format(1, 'abc'), 'abc')
        self.assertEqual('X{1}'.format(1, 'abc'), 'Xabc')
        self.assertEqual('{1}X'.format(1, 'abc'), 'abcX')
        self.assertEqual('X{1}Y'.format(1, 'abc'), 'XabcY')
        self.assertEqual('{0}'.format(-15), '-15')
        self.assertEqual('{0}{1}'.format(-15, 'abc'), '-15abc')
        self.assertEqual('{0}X{1}'.format(-15, 'abc'), '-15Xabc')
        self.assertEqual('{{'.format(), '{')
        self.assertEqual('}}'.format(), '}')
        self.assertEqual('{{}}'.format(), '{}')
        self.assertEqual('{{x}}'.format(), '{x}')
        self.assertEqual('{{{0}}}'.format(123), '{123}')
        self.assertEqual('{{{{0}}}}'.format(), '{{0}}')
        self.assertEqual('}}{{'.format(), '}{')
        self.assertEqual('}}x{{'.format(), '}x{')

        # weird field names
        self.assertEqual("{0[foo-bar]}".format({'foo-bar': 'baz'}), 'baz')
        self.assertEqual("{0[foo bar]}".format({'foo bar': 'baz'}), 'baz')
        self.assertEqual("{0[ ]}".format({' ': 3}), '3')

        self.assertEqual('{foo._x}'.format(foo=C(20)), '20')
        self.assertEqual('{1}{0}'.format(D(10), D(20)), '2010')
        self.assertEqual('{0._x.x}'.format(C(D('abc'))), 'abc')
        self.assertEqual('{0[0]}'.format(['abc', 'def']), 'abc')
        self.assertEqual('{0[1]}'.format(['abc', 'def']), 'def')
        self.assertEqual('{0[1][0]}'.format(['abc', ['def']]), 'def')
        self.assertEqual('{0[1][0].x}'.format(['abc', [D('def')]]), 'def')

        # strings
        self.assertEqual('{0:.3s}'.format('abc'), 'abc')
        self.assertEqual('{0:.3s}'.format('ab'), 'ab')
        self.assertEqual('{0:.3s}'.format('abcdef'), 'abc')
        self.assertEqual('{0:.0s}'.format('abcdef'), '')
        self.assertEqual('{0:3.3s}'.format('abc'), 'abc')
        self.assertEqual('{0:2.3s}'.format('abc'), 'abc')
        self.assertEqual('{0:2.2s}'.format('abc'), 'ab')
        self.assertEqual('{0:3.2s}'.format('abc'), 'ab ')
        self.assertEqual('{0:x<0s}'.format('result'), 'result')
        self.assertEqual('{0:x<5s}'.format('result'), 'result')
        self.assertEqual('{0:x<6s}'.format('result'), 'result')
        self.assertEqual('{0:x<7s}'.format('result'), 'resultx')
        self.assertEqual('{0:x<8s}'.format('result'), 'resultxx')
        self.assertEqual('{0: <7s}'.format('result'), 'result ')
        self.assertEqual('{0:<7s}'.format('result'), 'result ')
        self.assertEqual('{0:>7s}'.format('result'), ' result')
        self.assertEqual('{0:>8s}'.format('result'), '  result')
        self.assertEqual('{0:^8s}'.format('result'), ' result ')
        self.assertEqual('{0:^9s}'.format('result'), ' result  ')
        self.assertEqual('{0:^10s}'.format('result'), '  result  ')
        self.assertEqual('{0:10000}'.format('a'), 'a' + ' ' * 9999)
        self.assertEqual('{0:10000}'.format(''), ' ' * 10000)
        self.assertEqual('{0:10000000}'.format(''), ' ' * 10000000)

        # format specifiers for user defined type
        self.assertEqual('{0:abc}'.format(C()), 'abc')

        # !r and !s coercions
        self.assertEqual('{0!s}'.format('Hello'), 'Hello')
        self.assertEqual('{0!s:}'.format('Hello'), 'Hello')
        self.assertEqual('{0!s:15}'.format('Hello'), 'Hello          ')
        self.assertEqual('{0!s:15s}'.format('Hello'), 'Hello          ')
        self.assertEqual('{0!r}'.format('Hello'), "'Hello'")
        self.assertEqual('{0!r:}'.format('Hello'), "'Hello'")
        self.assertEqual('{0!r}'.format(F('Hello')), 'F(Hello)')

        # test fallback to object.__format__
        self.assertEqual('{0}'.format({}), '{}')
        self.assertEqual('{0}'.format([]), '[]')
        self.assertEqual('{0}'.format([1]), '[1]')
        self.assertEqual('{0}'.format(E('data')), 'E(data)')
        self.assertEqual('{0:d}'.format(G('data')), 'G(data)')
        self.assertEqual('{0!s}'.format(G('data')), 'string is data')

        msg = 'object.__format__ with a non-empty format string is deprecated'
        with test_support.check_warnings((msg, PendingDeprecationWarning)):
            self.assertEqual('{0:^10}'.format(E('data')), ' E(data)  ')
            self.assertEqual('{0:^10s}'.format(E('data')), ' E(data)  ')
            self.assertEqual('{0:>15s}'.format(G('data')), ' string is data')

        self.assertEqual(
            "{0:date: %Y-%m-%d}".format(I(year=2007, month=8, day=27)),
            "date: 2007-08-27")

        # test deriving from a builtin type and overriding __format__
        self.assertEqual("{0}".format(J(10)), "20")

        # string format specifiers
        self.assertEqual('{0:}'.format('a'), 'a')

        # computed format specifiers
        self.assertEqual("{0:.{1}}".format('hello world', 5), 'hello')
        self.assertEqual("{0:.{1}s}".format('hello world', 5), 'hello')
        self.assertEqual(
            "{0:.{precision}s}".format('hello world', precision=5), 'hello')
        self.assertEqual(
            "{0:{width}.{precision}s}".format('hello world',
                                              width=10,
                                              precision=5), 'hello     ')
        self.assertEqual(
            "{0:{width}.{precision}s}".format('hello world',
                                              width='10',
                                              precision='5'), 'hello     ')

        # test various errors
        self.assertRaises(ValueError, '{'.format)
        self.assertRaises(ValueError, '}'.format)
        self.assertRaises(ValueError, 'a{'.format)
        self.assertRaises(ValueError, 'a}'.format)
        self.assertRaises(ValueError, '{a'.format)
        self.assertRaises(ValueError, '}a'.format)
        self.assertRaises(IndexError, '{0}'.format)
        self.assertRaises(IndexError, '{1}'.format, 'abc')
        self.assertRaises(KeyError, '{x}'.format)
        self.assertRaises(ValueError, "}{".format)
        self.assertRaises(ValueError, "{".format)
        self.assertRaises(ValueError, "}".format)
        self.assertRaises(ValueError, "abc{0:{}".format)
        self.assertRaises(ValueError, "{0".format)
        self.assertRaises(IndexError, "{0.}".format)
        self.assertRaises(ValueError, "{0.}".format, 0)
        self.assertRaises(IndexError, "{0[}".format)
        self.assertRaises(ValueError, "{0[}".format, [])
        self.assertRaises(KeyError, "{0]}".format)
        self.assertRaises(ValueError, "{0.[]}".format, 0)
        self.assertRaises(ValueError, "{0..foo}".format, 0)
        self.assertRaises(ValueError, "{0[0}".format, 0)
        self.assertRaises(ValueError, "{0[0:foo}".format, 0)
        self.assertRaises(KeyError, "{c]}".format)
        self.assertRaises(ValueError, "{{ {{{0}}".format, 0)
        self.assertRaises(ValueError, "{0}}".format, 0)
        self.assertRaises(KeyError, "{foo}".format, bar=3)
        self.assertRaises(ValueError, "{0!x}".format, 3)
        self.assertRaises(ValueError, "{0!}".format, 0)
        self.assertRaises(ValueError, "{0!rs}".format, 0)
        self.assertRaises(ValueError, "{!}".format)
        self.assertRaises(IndexError, "{:}".format)
        self.assertRaises(IndexError, "{:s}".format)
        self.assertRaises(IndexError, "{}".format)

        # issue 6089
        self.assertRaises(ValueError, "{0[0]x}".format, [None])
        self.assertRaises(ValueError, "{0[0](10)}".format, [None])

        # can't have a replacement on the field name portion
        self.assertRaises(TypeError, '{0[{1}]}'.format, 'abcdefg', 4)

        # exceed maximum recursion depth
        self.assertRaises(ValueError, "{0:{1:{2}}}".format, 'abc', 's', '')
        self.assertRaises(ValueError, "{0:{1:{2:{3:{4:{5:{6}}}}}}}".format, 0,
                          1, 2, 3, 4, 5, 6, 7)

        # string format spec errors
        self.assertRaises(ValueError, "{0:-s}".format, '')
        self.assertRaises(ValueError, format, "", "-")
        self.assertRaises(ValueError, "{0:=s}".format, '')
Example #39
0
 def assertOldResultWarning(self, test, failures):
     with test_support.check_warnings(
         ("TestResult has no add.+ method,", RuntimeWarning)):
         result = OldResult()
         test.run(result)
         self.assertEqual(len(result.failures), failures)
Example #40
0
    def test_at_least_import_untested_modules(self):
        with test_support.check_warnings(quiet=True):
            import CGIHTTPServer
            import audiodev
            import bdb
            import cgitb
            import code
            import compileall

            import distutils.bcppcompiler
            import distutils.ccompiler
            import distutils.cygwinccompiler
            import distutils.emxccompiler
            import distutils.filelist
            if sys.platform.startswith('win'):
                import distutils.msvccompiler
            import distutils.text_file
            import distutils.unixccompiler

            import distutils.command.bdist_dumb
            if sys.platform.startswith('win'):
                import distutils.command.bdist_msi
            import distutils.command.bdist
            import distutils.command.bdist_rpm
            import distutils.command.bdist_wininst
            import distutils.command.build_clib
            import distutils.command.build_ext
            import distutils.command.build
            import distutils.command.clean
            import distutils.command.config
            import distutils.command.install_data
            import distutils.command.install_egg_info
            import distutils.command.install_headers
            import distutils.command.install_lib
            import distutils.command.register
            import distutils.command.sdist
            import distutils.command.upload

            import encodings
            import formatter
            import getpass
            import htmlentitydefs
            import ihooks
            import imghdr
            import imputil
            import keyword
            import linecache
            import macurl2path
            import mailcap
            import mimify
            import nntplib
            import nturl2path
            import opcode
            import os2emxpath
            import pdb
            import posixfile
            import pstats
            import py_compile
            import rexec
            import rlcompleter
            import sched
            import sndhdr
            import statvfs
            import stringold
            import sunau
            import sunaudio
            import symbol
            import tabnanny
            import timeit
            import toaiff
            import token
            try:
                import tty  # not available on Windows
            except ImportError:
                if test_support.verbose:
                    print "skipping tty"

            # Can't test the "user" module -- if the user has a ~/.pythonrc.py, it
            # can screw up all sorts of things (esp. if it prints!).
            #import user
            if not test_support.due_to_ironpython_bug(
                    "http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=301267"
            ):
                import webbrowser
            import xml
Example #41
0
 def test_import_initless_directory_warning(self):
     with check_warnings(('', ImportWarning)):
         # Just a random non-package directory we always expect to be
         # somewhere in sys.path...
         self.assertRaises(ImportError, __import__, "site-packages")
 def test_byte_min(self):
     with test_support.check_warnings(('', RuntimeWarning)):
         ts.T_BYTE = CHAR_MIN - 1
 def test_message_deprecation(self):
     # As of Python 2.6, BaseException.message is deprecated.
     with check_warnings(("", DeprecationWarning)):
         BaseException().message
Example #44
0
def test_main():
    with test_support.check_warnings(("complex divmod.., // and % are "
                                      "deprecated", DeprecationWarning)):
        test_support.run_unittest(ComplexTest)
 def test_check_metadata_deprecated(self):
     cmd = self._get_cmd()
     with check_warnings() as w:
         warnings.simplefilter('always')
         cmd.check_metadata()
         self.assertEqual(len(w.warnings), 1)
Example #46
0
    def test_all(self):
        # Test constructors
        u = UserDict.UserDict()
        u0 = UserDict.UserDict(d0)
        u1 = UserDict.UserDict(d1)
        u2 = UserDict.IterableUserDict(d2)

        uu = UserDict.UserDict(u)
        uu0 = UserDict.UserDict(u0)
        uu1 = UserDict.UserDict(u1)
        uu2 = UserDict.UserDict(u2)

        # keyword arg constructor
        self.assertEqual(UserDict.UserDict(one=1, two=2), d2)
        # item sequence constructor
        self.assertEqual(UserDict.UserDict([('one', 1), ('two', 2)]), d2)
        with test_support.check_warnings(
            (".*'dict'.*", PendingDeprecationWarning)):
            self.assertEqual(UserDict.UserDict(dict=[('one', 1), ('two', 2)]),
                             d2)
        # both together
        self.assertEqual(
            UserDict.UserDict([('one', 1), ('two', 2)], two=3, three=5), d3)

        # alternate constructor
        self.assertEqual(UserDict.UserDict.fromkeys('one two'.split()), d4)
        self.assertEqual(UserDict.UserDict().fromkeys('one two'.split()), d4)
        self.assertEqual(UserDict.UserDict.fromkeys('one two'.split(), 1), d5)
        self.assertEqual(UserDict.UserDict().fromkeys('one two'.split(), 1),
                         d5)
        self.assertTrue(u1.fromkeys('one two'.split()) is not u1)
        self.assertIsInstance(u1.fromkeys('one two'.split()),
                              UserDict.UserDict)
        self.assertIsInstance(u2.fromkeys('one two'.split()),
                              UserDict.IterableUserDict)

        # Test __repr__
        self.assertEqual(str(u0), str(d0))
        self.assertEqual(repr(u1), repr(d1))
        self.assertEqual(repr(u2), repr(d2))

        # Test __cmp__ and __len__
        all = [d0, d1, d2, u, u0, u1, u2, uu, uu0, uu1, uu2]
        for a in all:
            for b in all:
                self.assertEqual(cmp(a, b), cmp(len(a), len(b)))

        # Test __getitem__
        self.assertEqual(u2["one"], 1)
        self.assertRaises(KeyError, u1.__getitem__, "two")

        # Test __setitem__
        u3 = UserDict.UserDict(u2)
        u3["two"] = 2
        u3["three"] = 3

        # Test __delitem__
        del u3["three"]
        self.assertRaises(KeyError, u3.__delitem__, "three")

        # Test clear
        u3.clear()
        self.assertEqual(u3, {})

        # Test copy()
        u2a = u2.copy()
        self.assertEqual(u2a, u2)
        u2b = UserDict.UserDict(x=42, y=23)
        u2c = u2b.copy()  # making a copy of a UserDict is special cased
        self.assertEqual(u2b, u2c)

        class MyUserDict(UserDict.UserDict):
            def display(self):
                print self

        m2 = MyUserDict(u2)
        m2a = m2.copy()
        self.assertEqual(m2a, m2)

        # SF bug #476616 -- copy() of UserDict subclass shared data
        m2['foo'] = 'bar'
        self.assertNotEqual(m2a, m2)

        # Test keys, items, values
        self.assertEqual(u2.keys(), d2.keys())
        self.assertEqual(u2.items(), d2.items())
        self.assertEqual(u2.values(), d2.values())

        # Test has_key and "in".
        for i in u2.keys():
            self.assertIn(i, u2)
            self.assertEqual(i in u1, i in d1)
            self.assertEqual(i in u0, i in d0)
            with test_support.check_py3k_warnings():
                self.assertTrue(u2.has_key(i))
                self.assertEqual(u1.has_key(i), d1.has_key(i))
                self.assertEqual(u0.has_key(i), d0.has_key(i))

        # Test update
        t = UserDict.UserDict()
        t.update(u2)
        self.assertEqual(t, u2)

        class Items:
            def items(self):
                return (("x", 42), ("y", 23))

        t = UserDict.UserDict()
        t.update(Items())
        self.assertEqual(t, {"x": 42, "y": 23})

        # Test get
        for i in u2.keys():
            self.assertEqual(u2.get(i), u2[i])
            self.assertEqual(u1.get(i), d1.get(i))
            self.assertEqual(u0.get(i), d0.get(i))

        # Test "in" iteration.
        for i in xrange(20):
            u2[i] = str(i)
        ikeys = []
        for k in u2:
            ikeys.append(k)
        keys = u2.keys()
        self.assertEqual(set(ikeys), set(keys))

        # Test setdefault
        t = UserDict.UserDict()
        self.assertEqual(t.setdefault("x", 42), 42)
        self.assertTrue(t.has_key("x"))
        self.assertEqual(t.setdefault("x", 23), 42)

        # Test pop
        t = UserDict.UserDict(x=42)
        self.assertEqual(t.pop("x"), 42)
        self.assertRaises(KeyError, t.pop, "x")
        self.assertEqual(t.pop("x", 1), 1)
        t["x"] = 42
        self.assertEqual(t.pop("x", 1), 42)

        # Test popitem
        t = UserDict.UserDict(x=42)
        self.assertEqual(t.popitem(), ("x", 42))
        self.assertRaises(KeyError, t.popitem)
Example #47
0
class SymtableTest(unittest.TestCase):

    with test_support.check_warnings(
        ("import \* only allowed at module level", SyntaxWarning)):
        top = symtable.symtable(TEST_CODE, "?", "exec")
    # These correspond to scopes in TEST_CODE
    Mine = find_block(top, "Mine")
    a_method = find_block(Mine, "a_method")
    spam = find_block(top, "spam")
    internal = find_block(spam, "internal")
    foo = find_block(top, "foo")

    def test_type(self):
        self.assertEqual(self.top.get_type(), "module")
        self.assertEqual(self.Mine.get_type(), "class")
        self.assertEqual(self.a_method.get_type(), "function")
        self.assertEqual(self.spam.get_type(), "function")
        self.assertEqual(self.internal.get_type(), "function")

    def test_optimized(self):
        self.assertFalse(self.top.is_optimized())
        self.assertFalse(self.top.has_exec())
        self.assertFalse(self.top.has_import_star())

        self.assertTrue(self.spam.is_optimized())

        self.assertFalse(self.foo.is_optimized())
        self.assertTrue(self.foo.has_exec())
        self.assertTrue(self.foo.has_import_star())

    def test_nested(self):
        self.assertFalse(self.top.is_nested())
        self.assertFalse(self.Mine.is_nested())
        self.assertFalse(self.spam.is_nested())
        self.assertTrue(self.internal.is_nested())

    def test_children(self):
        self.assertTrue(self.top.has_children())
        self.assertTrue(self.Mine.has_children())
        self.assertFalse(self.foo.has_children())

    def test_lineno(self):
        self.assertEqual(self.top.get_lineno(), 0)
        self.assertEqual(self.spam.get_lineno(), 11)

    def test_function_info(self):
        func = self.spam
        self.assertEqual(sorted(func.get_parameters()),
                         ["a", "b", "kw", "var"])
        expected = ["a", "b", "internal", "kw", "var", "x"]
        self.assertEqual(sorted(func.get_locals()), expected)
        self.assertEqual(sorted(func.get_globals()), ["bar", "glob"])
        self.assertEqual(self.internal.get_frees(), ("x", ))

    def test_globals(self):
        self.assertTrue(self.spam.lookup("glob").is_global())
        self.assertFalse(self.spam.lookup("glob").is_declared_global())
        self.assertTrue(self.spam.lookup("bar").is_global())
        self.assertTrue(self.spam.lookup("bar").is_declared_global())
        self.assertFalse(self.internal.lookup("x").is_global())
        self.assertFalse(self.Mine.lookup("instance_var").is_global())

    def test_local(self):
        self.assertTrue(self.spam.lookup("x").is_local())
        self.assertFalse(self.internal.lookup("x").is_local())

    def test_referenced(self):
        self.assertTrue(self.internal.lookup("x").is_referenced())
        self.assertTrue(self.spam.lookup("internal").is_referenced())
        self.assertFalse(self.spam.lookup("x").is_referenced())

    def test_parameters(self):
        for sym in ("a", "var", "kw"):
            self.assertTrue(self.spam.lookup(sym).is_parameter())
        self.assertFalse(self.spam.lookup("x").is_parameter())

    def test_symbol_lookup(self):
        self.assertEqual(len(self.top.get_identifiers()),
                         len(self.top.get_symbols()))

        self.assertRaises(KeyError, self.top.lookup, "not_here")

    def test_namespaces(self):
        self.assertTrue(self.top.lookup("Mine").is_namespace())
        self.assertTrue(self.Mine.lookup("a_method").is_namespace())
        self.assertTrue(self.top.lookup("spam").is_namespace())
        self.assertTrue(self.spam.lookup("internal").is_namespace())
        self.assertTrue(self.top.lookup("namespace_test").is_namespace())
        self.assertFalse(self.spam.lookup("x").is_namespace())

        self.assertTrue(self.top.lookup("spam").get_namespace() is self.spam)
        ns_test = self.top.lookup("namespace_test")
        self.assertEqual(len(ns_test.get_namespaces()), 2)
        self.assertRaises(ValueError, ns_test.get_namespace)

    def test_assigned(self):
        self.assertTrue(self.spam.lookup("x").is_assigned())
        self.assertTrue(self.spam.lookup("bar").is_assigned())
        self.assertTrue(self.top.lookup("spam").is_assigned())
        self.assertTrue(self.Mine.lookup("a_method").is_assigned())
        self.assertFalse(self.internal.lookup("x").is_assigned())

    def test_imported(self):
        self.assertTrue(self.top.lookup("sys").is_imported())

    def test_name(self):
        self.assertEqual(self.top.get_name(), "top")
        self.assertEqual(self.spam.get_name(), "spam")
        self.assertEqual(self.spam.lookup("x").get_name(), "x")
        self.assertEqual(self.Mine.get_name(), "Mine")

    def test_class_info(self):
        self.assertEqual(self.Mine.get_methods(), ('a_method', ))

    def test_filename_correct(self):
        ### Bug tickler: SyntaxError file name correct whether error raised
        ### while parsing or building symbol table.
        def checkfilename(brokencode):
            try:
                symtable.symtable(brokencode, "spam", "exec")
            except SyntaxError as e:
                self.assertEqual(e.filename, "spam")
            else:
                self.fail("no SyntaxError for %r" % (brokencode, ))

        checkfilename("def f(x): foo)(")  # parse-time
        checkfilename("def f(x): global x")  # symtable-build-time

    def test_eval(self):
        symbols = symtable.symtable("42", "?", "eval")

    def test_single(self):
        symbols = symtable.symtable("42", "?", "single")

    def test_exec(self):
        symbols = symtable.symtable("def f(x): return x", "?", "exec")
Example #48
0
 def test_touched(self):
     # This really only tests that nothing unforeseen happens.
     with test_support.check_warnings(
         ('macostools.touched*', DeprecationWarning), quiet=True):
         macostools.touched(test_support.TESTFN)
def test_main():
    run_unittest(CookieTests)
    with check_warnings(
        ('.+Cookie class is insecure; do not use it', DeprecationWarning)):
        run_doctest(Cookie)
 def test_ushort_max(self):
     with test_support.check_warnings(('', RuntimeWarning)):
         ts.T_USHORT = USHRT_MAX + 1
Example #51
0
 def test_unicode(self):
     with test_support.check_warnings(("", UnicodeWarning), quiet=True):
         self.check_match(u'test', u'te*')
         self.check_match(u'test\xff', u'te*\xff')
         self.check_match(u'test' + unichr(0x20ac), u'te*' + unichr(0x20ac))
         self.check_match(u'foo\nbar', u'foo*')
Example #52
0
def test_main():
    with check_warnings(
        ("import \* only allowed at module level", SyntaxWarning)):
        run_unittest(ScopeTests)
 def test_ushort_max(self):
     with test_support.check_warnings() as w:
         ts.T_USHORT = USHRT_MAX + 1
         self.has_warned(w)
Example #54
0
def test_main():
    with check_warnings(("complex divmod.., // and % are deprecated",
                         DeprecationWarning),
                        ("classic (int|long) division", DeprecationWarning),
                        quiet=True):
        run_unittest(CoercionTest)
 def test_ubyte_max(self):
     with test_support.check_warnings() as w:
         ts.T_UBYTE = UCHAR_MAX + 1
         self.has_warned(w)
Example #56
0
            if val[0] == 's':
                res = (val[1], val[2])
            elif val[0] == 'b':
                res = (val[1], val[1])
            for i in range(1):
                if isinstance(res[i][6], tuple):
                    if 1/2 == 0:
                        # testing with classic (floor) division
                        res[i][6] = res[i][6][0]
                    else:
                        # testing with -Qnew
                        res[i][6] = res[i][6][1]
            infix_results[key] = res


with check_warnings(("classic (int|long) division", DeprecationWarning),
                    quiet=True):
    process_infix_results()
    # now infix_results has two lists of results for every pairing.

prefix_binops = [ 'divmod' ]
prefix_results = [
    [(1,0), (1L,0L), (0.0,2.0), ((1+0j),0j), TE, TE, TE, TE, (1,0)],
    [(1L,0L), (1L,0L), (0.0,2.0), ((1+0j),0j), TE, TE, TE, TE, (1L,0L)],
    [(2.0,0.0), (2.0,0.0), (1.0,0.0), ((2+0j),0j), TE, TE, TE, TE, (2.0,0.0)],
    [((1+0j),0j), ((1+0j),0j), (0j,(2+0j)), ((1+0j),0j), TE, TE, TE, TE, ((1+0j),0j)],
    [TE, TE, TE, TE, TE, TE, TE, TE, TE],
    [TE, TE, TE, TE, TE, TE, TE, TE, TE],
    [TE, TE, TE, TE, TE, TE, TE, TE, TE],
    [TE, TE, TE, TE, TE, TE, TE, TE, TE],
    [(1,0), (1L,0L), (0.0,2.0), ((1+0j),0j), TE, TE, TE, TE, (1,0)]
]
Example #57
0
 def test_object_inequality_comparisons(self):
     expected = 'comparing unequal types not supported in 3.x'
     with check_warnings() as w:
         self.assertWarning(str < [], w, expected)
         w.reset()
         self.assertWarning(object() < (1, 2), w, expected)
 def wrapper(*args, **kw):
     with check_warnings(*_deprecations, quiet=True):
         return func(*args, **kw)
Example #59
0
 def test_deprecated_parse_qsl(self):
     # this func is moved to urlparse, this is just a sanity check
     with check_warnings(('cgi.parse_qsl is deprecated, use urlparse.'
                          'parse_qsl instead', PendingDeprecationWarning)):
         self.assertEqual([('a', 'A1'), ('b', 'B2'), ('B', 'B3')],
                          cgi.parse_qsl('a=A1&b=B2&B=B3'))
 def test_ubyte_max(self):
     with test_support.check_warnings(('', RuntimeWarning)):
         ts.T_UBYTE = UCHAR_MAX + 1