diff Lib/test/test_csv.py @ 87272:6e5afeada7ca 3.3

#19449: Handle non-string keys when generating 'fieldnames' error. csv was handling non-string keys fine except for the error message generated when a non-string key was not in 'fieldnames'. Fix by Tomas Grahn, full patch-with-test by Vajrasky Kok (tweaked slightly).
author R David Murray <rdmurray@bitdance.com>
date Tue, 19 Nov 2013 13:16:20 -0500
parents 1feeeb8992f8
children ee2c80eeca2a
line wrap: on
line diff
--- a/Lib/test/test_csv.py	Tue Nov 19 11:05:20 2013 -0500
+++ b/Lib/test/test_csv.py	Tue Nov 19 13:16:20 2013 -0500
@@ -570,6 +570,18 @@
         fileobj = StringIO()
         self.assertRaises(TypeError, csv.DictWriter, fileobj)
 
+    def test_write_fields_not_in_fieldnames(self):
+        with TemporaryFile("w+", newline='') as fileobj:
+            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)
+
     def test_read_dict_fields(self):
         with TemporaryFile("w+") as fileobj:
             fileobj.write("1,2,abc\r\n")