#19449: Handle non-string keys when generating 'fieldnames' error.
Backport from 3.3 6e5afeada7ca.
diff --git a/Lib/test/test_csv.py b/Lib/test/test_csv.py
index d3c1dec..5c95fe3 100644
--- a/Lib/test/test_csv.py
+++ b/Lib/test/test_csv.py
@@ -630,6 +630,23 @@
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")