]> granicus.if.org Git - python/commitdiff
#19449: Handle non-string keys when generating 'fieldnames' error.
authorR David Murray <rdmurray@bitdance.com>
Tue, 19 Nov 2013 18:25:24 +0000 (13:25 -0500)
committerR David Murray <rdmurray@bitdance.com>
Tue, 19 Nov 2013 18:25:24 +0000 (13:25 -0500)
Backport from 3.3 6e5afeada7ca.

Lib/csv.py
Lib/test/test_csv.py
Misc/NEWS

index 98480ba16a1d1802e96320e6b0f390952daccebc..fc080cce1ba09cec6f6d2de78bfa4348517a558a 100644 (file)
@@ -140,8 +140,8 @@ class DictWriter:
         if self.extrasaction == "raise":
             wrong_fields = [k for k in rowdict if k not in self.fieldnames]
             if wrong_fields:
-                raise ValueError("dict contains fields not in fieldnames: " +
-                                 ", ".join(wrong_fields))
+                raise ValueError("dict contains fields not in fieldnames: "
+                                 + ", ".join([repr(x) for x in wrong_fields]))
         return [rowdict.get(key, self.restval) for key in self.fieldnames]
 
     def writerow(self, rowdict):
index d3c1dec89576f43827158d04f36328d78b288ee7..5c95fe3fa9276b2267482f9871b7448009cb7963 100644 (file)
@@ -630,6 +630,23 @@ class TestDictFields(unittest.TestCase):
         fileobj = StringIO()
         self.assertRaises(TypeError, csv.DictWriter, fileobj)
 
+    def test_write_fields_not_in_fieldnames(self):
+        fd, name = tempfile.mkstemp()
+        fileobj = os.fdopen(fd, "w+b")
+        try:
+            writer = csv.DictWriter(fileobj, fieldnames = ["f1", "f2", "f3"])
+            # Of special note is the non-string key (issue 19449)
+            with self.assertRaises(ValueError) as cx:
+                writer.writerow({"f4": 10, "f2": "spam", 1: "abc"})
+            exception = str(cx.exception)
+            self.assertIn("fieldnames", exception)
+            self.assertIn("'f4'", exception)
+            self.assertNotIn("'f2'", exception)
+            self.assertIn("1", exception)
+        finally:
+            fileobj.close()
+            os.unlink(name)
+
     def test_read_dict_fields(self):
         fd, name = tempfile.mkstemp()
         fileobj = os.fdopen(fd, "w+b")
index 77bc5a81b0ca2288a536a616ffda4fdd667800bd..d5ed3c9206ce1d081d1722a037e080f1d570f422 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -12,6 +12,9 @@ Core and Builtins
 Library
 -------
 
+- Issue #19449: in csv's writerow, handle non-string keys when generating the
+  error message that certain keys are not in the 'fieldnames' list.
+
 - Issue #12853: Fix NameError in distutils.command.upload.
 
 - Issue #19523: Closed FileHandler leak which occurred when delay was set.