]> granicus.if.org Git - python/commitdiff
[3.6] bpo-31566: Fix an assertion failure in _warnings.warn() in case of a bad __name...
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Sun, 24 Sep 2017 20:14:41 +0000 (13:14 -0700)
committerSerhiy Storchaka <storchaka@gmail.com>
Sun, 24 Sep 2017 20:14:41 +0000 (23:14 +0300)
(cherry picked from commit 5d3e80021ab33360191eb0fbff34e0246c913884)

Lib/test/test_warnings/__init__.py
Misc/NEWS.d/next/Core and Builtins/2017-09-24-09-57-04.bpo-31566.OxwINs.rst [new file with mode: 0644]
Python/_warnings.c

index 354da6b46f01d01861589573292efbcef160405a..a07886c6f54b8e7a171231e36e845e8ab904b25b 100644 (file)
@@ -820,6 +820,16 @@ class _WarningsTests(BaseTest, unittest.TestCase):
                  self.assertRaises(TypeError):
                 wmod.warn_explicit('foo', Warning, 'bar', 1)
 
+    @support.cpython_only
+    def test_issue31566(self):
+        # warn() shouldn't cause an assertion failure in case of a bad
+        # __name__ global.
+        with original_warnings.catch_warnings(module=self.module):
+            self.module.filterwarnings('error', category=UserWarning)
+            with support.swap_item(globals(), '__name__', b'foo'), \
+                 support.swap_item(globals(), '__file__', None):
+                self.assertRaises(UserWarning, self.module.warn, 'bar')
+
 
 class WarningsDisplayTests(BaseTest):
 
diff --git a/Misc/NEWS.d/next/Core and Builtins/2017-09-24-09-57-04.bpo-31566.OxwINs.rst b/Misc/NEWS.d/next/Core and Builtins/2017-09-24-09-57-04.bpo-31566.OxwINs.rst
new file mode 100644 (file)
index 0000000..d3ccfd7
--- /dev/null
@@ -0,0 +1,2 @@
+Fix an assertion failure in `_warnings.warn()` in case of a bad
+``__name__`` global. Patch by Oren Milman.
index 7270d2c2ecb15c1f14421bd5aa2aaedf9f7debb4..b074788f5b6d02d2f1a5dbf2018f3230a3a5c1bf 100644 (file)
@@ -694,13 +694,14 @@ setup_context(Py_ssize_t stack_level, PyObject **filename, int *lineno,
 
     /* Setup module. */
     *module = PyDict_GetItemString(globals, "__name__");
-    if (*module == NULL) {
+    if (*module == Py_None || (*module != NULL && PyUnicode_Check(*module))) {
+        Py_INCREF(*module);
+    }
+    else {
         *module = PyUnicode_FromString("<string>");
         if (*module == NULL)
             goto handle_error;
     }
-    else
-        Py_INCREF(*module);
 
     /* Setup filename. */
     *filename = PyDict_GetItemString(globals, "__file__");