In Cloudpickle, expected behaviour when pickling an opened file is to send its contents over the wire and seek to the same position.
| 11 | |
| 12 | |
| 13 | class CloudPickleFileTests(unittest.TestCase): |
| 14 | """In Cloudpickle, expected behaviour when pickling an opened file |
| 15 | is to send its contents over the wire and seek to the same position.""" |
| 16 | |
| 17 | def setUp(self): |
| 18 | self.tmpdir = tempfile.mkdtemp() |
| 19 | self.tmpfilepath = os.path.join(self.tmpdir, "testfile") |
| 20 | self.teststring = "Hello world!" |
| 21 | |
| 22 | def tearDown(self): |
| 23 | shutil.rmtree(self.tmpdir) |
| 24 | |
| 25 | def test_empty_file(self): |
| 26 | # Empty file |
| 27 | open(self.tmpfilepath, "w").close() |
| 28 | with open(self.tmpfilepath) as f: |
| 29 | self.assertEqual("", pickle.loads(cloudpickle.dumps(f)).read()) |
| 30 | os.remove(self.tmpfilepath) |
| 31 | |
| 32 | def test_closed_file(self): |
| 33 | # Write & close |
| 34 | with open(self.tmpfilepath, "w") as f: |
| 35 | f.write(self.teststring) |
| 36 | with pytest.raises(pickle.PicklingError) as excinfo: |
| 37 | cloudpickle.dumps(f) |
| 38 | assert "Cannot pickle closed files" in str(excinfo.value) |
| 39 | os.remove(self.tmpfilepath) |
| 40 | |
| 41 | def test_r_mode(self): |
| 42 | # Write & close |
| 43 | with open(self.tmpfilepath, "w") as f: |
| 44 | f.write(self.teststring) |
| 45 | # Open for reading |
| 46 | with open(self.tmpfilepath) as f: |
| 47 | new_f = pickle.loads(cloudpickle.dumps(f)) |
| 48 | self.assertEqual(self.teststring, new_f.read()) |
| 49 | os.remove(self.tmpfilepath) |
| 50 | |
| 51 | def test_w_mode(self): |
| 52 | with open(self.tmpfilepath, "w") as f: |
| 53 | f.write(self.teststring) |
| 54 | f.seek(0) |
| 55 | self.assertRaises(pickle.PicklingError, lambda: cloudpickle.dumps(f)) |
| 56 | os.remove(self.tmpfilepath) |
| 57 | |
| 58 | def test_plus_mode(self): |
| 59 | # Write, then seek to 0 |
| 60 | with open(self.tmpfilepath, "w+") as f: |
| 61 | f.write(self.teststring) |
| 62 | f.seek(0) |
| 63 | new_f = pickle.loads(cloudpickle.dumps(f)) |
| 64 | self.assertEqual(self.teststring, new_f.read()) |
| 65 | os.remove(self.tmpfilepath) |
| 66 | |
| 67 | def test_seek(self): |
| 68 | # Write, then seek to arbitrary position |
| 69 | with open(self.tmpfilepath, "w+") as f: |
| 70 | f.write(self.teststring) |
nothing calls this directly
no outgoing calls
no test coverage detected