ยปCore Development>Code coverage>Lib/test/test_file.py

Python code coverage for Lib/test/test_file.py

#countcontent
1n/aimport sys
2n/aimport os
3n/aimport unittest
4n/afrom array import array
5n/afrom weakref import proxy
6n/a
7n/aimport io
8n/aimport _pyio as pyio
9n/a
10n/afrom test.support import TESTFN
11n/afrom collections import UserList
12n/a
13n/aclass AutoFileTests:
14n/a # file tests for which a test file is automatically set up
15n/a
16n/a def setUp(self):
17n/a self.f = self.open(TESTFN, 'wb')
18n/a
19n/a def tearDown(self):
20n/a if self.f:
21n/a self.f.close()
22n/a os.remove(TESTFN)
23n/a
24n/a def testWeakRefs(self):
25n/a # verify weak references
26n/a p = proxy(self.f)
27n/a p.write(b'teststring')
28n/a self.assertEqual(self.f.tell(), p.tell())
29n/a self.f.close()
30n/a self.f = None
31n/a self.assertRaises(ReferenceError, getattr, p, 'tell')
32n/a
33n/a def testAttributes(self):
34n/a # verify expected attributes exist
35n/a f = self.f
36n/a f.name # merely shouldn't blow up
37n/a f.mode # ditto
38n/a f.closed # ditto
39n/a
40n/a def testReadinto(self):
41n/a # verify readinto
42n/a self.f.write(b'12')
43n/a self.f.close()
44n/a a = array('b', b'x'*10)
45n/a self.f = self.open(TESTFN, 'rb')
46n/a n = self.f.readinto(a)
47n/a self.assertEqual(b'12', a.tobytes()[:n])
48n/a
49n/a def testReadinto_text(self):
50n/a # verify readinto refuses text files
51n/a a = array('b', b'x'*10)
52n/a self.f.close()
53n/a self.f = self.open(TESTFN, 'r')
54n/a if hasattr(self.f, "readinto"):
55n/a self.assertRaises(TypeError, self.f.readinto, a)
56n/a
57n/a def testWritelinesUserList(self):
58n/a # verify writelines with instance sequence
59n/a l = UserList([b'1', b'2'])
60n/a self.f.writelines(l)
61n/a self.f.close()
62n/a self.f = self.open(TESTFN, 'rb')
63n/a buf = self.f.read()
64n/a self.assertEqual(buf, b'12')
65n/a
66n/a def testWritelinesIntegers(self):
67n/a # verify writelines with integers
68n/a self.assertRaises(TypeError, self.f.writelines, [1, 2, 3])
69n/a
70n/a def testWritelinesIntegersUserList(self):
71n/a # verify writelines with integers in UserList
72n/a l = UserList([1,2,3])
73n/a self.assertRaises(TypeError, self.f.writelines, l)
74n/a
75n/a def testWritelinesNonString(self):
76n/a # verify writelines with non-string object
77n/a class NonString:
78n/a pass
79n/a
80n/a self.assertRaises(TypeError, self.f.writelines,
81n/a [NonString(), NonString()])
82n/a
83n/a def testErrors(self):
84n/a f = self.f
85n/a self.assertEqual(f.name, TESTFN)
86n/a self.assertFalse(f.isatty())
87n/a self.assertFalse(f.closed)
88n/a
89n/a if hasattr(f, "readinto"):
90n/a self.assertRaises((OSError, TypeError), f.readinto, "")
91n/a f.close()
92n/a self.assertTrue(f.closed)
93n/a
94n/a def testMethods(self):
95n/a methods = [('fileno', ()),
96n/a ('flush', ()),
97n/a ('isatty', ()),
98n/a ('__next__', ()),
99n/a ('read', ()),
100n/a ('write', (b"",)),
101n/a ('readline', ()),
102n/a ('readlines', ()),
103n/a ('seek', (0,)),
104n/a ('tell', ()),
105n/a ('write', (b"",)),
106n/a ('writelines', ([],)),
107n/a ('__iter__', ()),
108n/a ]
109n/a methods.append(('truncate', ()))
110n/a
111n/a # __exit__ should close the file
112n/a self.f.__exit__(None, None, None)
113n/a self.assertTrue(self.f.closed)
114n/a
115n/a for methodname, args in methods:
116n/a method = getattr(self.f, methodname)
117n/a # should raise on closed file
118n/a self.assertRaises(ValueError, method, *args)
119n/a
120n/a # file is closed, __exit__ shouldn't do anything
121n/a self.assertEqual(self.f.__exit__(None, None, None), None)
122n/a # it must also return None if an exception was given
123n/a try:
124n/a 1/0
125n/a except:
126n/a self.assertEqual(self.f.__exit__(*sys.exc_info()), None)
127n/a
128n/a def testReadWhenWriting(self):
129n/a self.assertRaises(OSError, self.f.read)
130n/a
131n/aclass CAutoFileTests(AutoFileTests, unittest.TestCase):
132n/a open = io.open
133n/a
134n/aclass PyAutoFileTests(AutoFileTests, unittest.TestCase):
135n/a open = staticmethod(pyio.open)
136n/a
137n/a
138n/aclass OtherFileTests:
139n/a
140n/a def testModeStrings(self):
141n/a # check invalid mode strings
142n/a for mode in ("", "aU", "wU+", "U+", "+U", "rU+"):
143n/a try:
144n/a f = self.open(TESTFN, mode)
145n/a except ValueError:
146n/a pass
147n/a else:
148n/a f.close()
149n/a self.fail('%r is an invalid file mode' % mode)
150n/a
151n/a def testBadModeArgument(self):
152n/a # verify that we get a sensible error message for bad mode argument
153n/a bad_mode = "qwerty"
154n/a try:
155n/a f = self.open(TESTFN, bad_mode)
156n/a except ValueError as msg:
157n/a if msg.args[0] != 0:
158n/a s = str(msg)
159n/a if TESTFN in s or bad_mode not in s:
160n/a self.fail("bad error message for invalid mode: %s" % s)
161n/a # if msg.args[0] == 0, we're probably on Windows where there may be
162n/a # no obvious way to discover why open() failed.
163n/a else:
164n/a f.close()
165n/a self.fail("no error for invalid mode: %s" % bad_mode)
166n/a
167n/a def testSetBufferSize(self):
168n/a # make sure that explicitly setting the buffer size doesn't cause
169n/a # misbehaviour especially with repeated close() calls
170n/a for s in (-1, 0, 1, 512):
171n/a try:
172n/a f = self.open(TESTFN, 'wb', s)
173n/a f.write(str(s).encode("ascii"))
174n/a f.close()
175n/a f.close()
176n/a f = self.open(TESTFN, 'rb', s)
177n/a d = int(f.read().decode("ascii"))
178n/a f.close()
179n/a f.close()
180n/a except OSError as msg:
181n/a self.fail('error setting buffer size %d: %s' % (s, str(msg)))
182n/a self.assertEqual(d, s)
183n/a
184n/a def testTruncateOnWindows(self):
185n/a # SF bug <http://www.python.org/sf/801631>
186n/a # "file.truncate fault on windows"
187n/a
188n/a os.unlink(TESTFN)
189n/a f = self.open(TESTFN, 'wb')
190n/a
191n/a try:
192n/a f.write(b'12345678901') # 11 bytes
193n/a f.close()
194n/a
195n/a f = self.open(TESTFN,'rb+')
196n/a data = f.read(5)
197n/a if data != b'12345':
198n/a self.fail("Read on file opened for update failed %r" % data)
199n/a if f.tell() != 5:
200n/a self.fail("File pos after read wrong %d" % f.tell())
201n/a
202n/a f.truncate()
203n/a if f.tell() != 5:
204n/a self.fail("File pos after ftruncate wrong %d" % f.tell())
205n/a
206n/a f.close()
207n/a size = os.path.getsize(TESTFN)
208n/a if size != 5:
209n/a self.fail("File size after ftruncate wrong %d" % size)
210n/a finally:
211n/a f.close()
212n/a os.unlink(TESTFN)
213n/a
214n/a def testIteration(self):
215n/a # Test the complex interaction when mixing file-iteration and the
216n/a # various read* methods.
217n/a dataoffset = 16384
218n/a filler = b"ham\n"
219n/a assert not dataoffset % len(filler), \
220n/a "dataoffset must be multiple of len(filler)"
221n/a nchunks = dataoffset // len(filler)
222n/a testlines = [
223n/a b"spam, spam and eggs\n",
224n/a b"eggs, spam, ham and spam\n",
225n/a b"saussages, spam, spam and eggs\n",
226n/a b"spam, ham, spam and eggs\n",
227n/a b"spam, spam, spam, spam, spam, ham, spam\n",
228n/a b"wonderful spaaaaaam.\n"
229n/a ]
230n/a methods = [("readline", ()), ("read", ()), ("readlines", ()),
231n/a ("readinto", (array("b", b" "*100),))]
232n/a
233n/a try:
234n/a # Prepare the testfile
235n/a bag = self.open(TESTFN, "wb")
236n/a bag.write(filler * nchunks)
237n/a bag.writelines(testlines)
238n/a bag.close()
239n/a # Test for appropriate errors mixing read* and iteration
240n/a for methodname, args in methods:
241n/a f = self.open(TESTFN, 'rb')
242n/a if next(f) != filler:
243n/a self.fail, "Broken testfile"
244n/a meth = getattr(f, methodname)
245n/a meth(*args) # This simply shouldn't fail
246n/a f.close()
247n/a
248n/a # Test to see if harmless (by accident) mixing of read* and
249n/a # iteration still works. This depends on the size of the internal
250n/a # iteration buffer (currently 8192,) but we can test it in a
251n/a # flexible manner. Each line in the bag o' ham is 4 bytes
252n/a # ("h", "a", "m", "\n"), so 4096 lines of that should get us
253n/a # exactly on the buffer boundary for any power-of-2 buffersize
254n/a # between 4 and 16384 (inclusive).
255n/a f = self.open(TESTFN, 'rb')
256n/a for i in range(nchunks):
257n/a next(f)
258n/a testline = testlines.pop(0)
259n/a try:
260n/a line = f.readline()
261n/a except ValueError:
262n/a self.fail("readline() after next() with supposedly empty "
263n/a "iteration-buffer failed anyway")
264n/a if line != testline:
265n/a self.fail("readline() after next() with empty buffer "
266n/a "failed. Got %r, expected %r" % (line, testline))
267n/a testline = testlines.pop(0)
268n/a buf = array("b", b"\x00" * len(testline))
269n/a try:
270n/a f.readinto(buf)
271n/a except ValueError:
272n/a self.fail("readinto() after next() with supposedly empty "
273n/a "iteration-buffer failed anyway")
274n/a line = buf.tobytes()
275n/a if line != testline:
276n/a self.fail("readinto() after next() with empty buffer "
277n/a "failed. Got %r, expected %r" % (line, testline))
278n/a
279n/a testline = testlines.pop(0)
280n/a try:
281n/a line = f.read(len(testline))
282n/a except ValueError:
283n/a self.fail("read() after next() with supposedly empty "
284n/a "iteration-buffer failed anyway")
285n/a if line != testline:
286n/a self.fail("read() after next() with empty buffer "
287n/a "failed. Got %r, expected %r" % (line, testline))
288n/a try:
289n/a lines = f.readlines()
290n/a except ValueError:
291n/a self.fail("readlines() after next() with supposedly empty "
292n/a "iteration-buffer failed anyway")
293n/a if lines != testlines:
294n/a self.fail("readlines() after next() with empty buffer "
295n/a "failed. Got %r, expected %r" % (line, testline))
296n/a f.close()
297n/a
298n/a # Reading after iteration hit EOF shouldn't hurt either
299n/a f = self.open(TESTFN, 'rb')
300n/a try:
301n/a for line in f:
302n/a pass
303n/a try:
304n/a f.readline()
305n/a f.readinto(buf)
306n/a f.read()
307n/a f.readlines()
308n/a except ValueError:
309n/a self.fail("read* failed after next() consumed file")
310n/a finally:
311n/a f.close()
312n/a finally:
313n/a os.unlink(TESTFN)
314n/a
315n/aclass COtherFileTests(OtherFileTests, unittest.TestCase):
316n/a open = io.open
317n/a
318n/aclass PyOtherFileTests(OtherFileTests, unittest.TestCase):
319n/a open = staticmethod(pyio.open)
320n/a
321n/a
322n/adef tearDownModule():
323n/a # Historically, these tests have been sloppy about removing TESTFN.
324n/a # So get rid of it no matter what.
325n/a if os.path.exists(TESTFN):
326n/a os.unlink(TESTFN)
327n/a
328n/aif __name__ == '__main__':
329n/a unittest.main()