Tests for fileinput module.
from test
.test_support
import verify
, verbose
, TESTFN
from StringIO
import StringIO
from fileinput
import FileInput
# The fileinput module has 2 interfaces: the FileInput class which does
# all the work, and a few functions (input, etc.) that use a global _state
# variable. We only test the FileInput class, since the other functions
# only provide a thin facade over FileInput.
# Write lines (a list of lines) to temp file number i, and return the
pat
= re
.compile(r
'LINE (\d+) OF FILE (\d+)')
def remove_tempfiles(*names
):
def runTests(t1
, t2
, t3
, t4
, bs
=0, round=0):
print '%s. Simple iteration (bs=%s)' % (start
+0, bs
)
fi
= FileInput(files
=(t1
, t2
, t3
, t4
), bufsize
=bs
)
verify(lines
[4] == 'Line 5 of file 1\n')
verify(lines
[30] == 'Line 1 of file 4\n')
verify(fi
.lineno() == 31)
verify(fi
.filename() == t4
)
print '%s. Status variables (bs=%s)' % (start
+1, bs
)
fi
= FileInput(files
=(t1
, t2
, t3
, t4
), bufsize
=bs
)
while s
and s
!= 'Line 6 of file 2\n':
verify(fi
.filename() == t2
)
verify(fi
.lineno() == 21)
verify(fi
.filelineno() == 6)
verify(not fi
.isfirstline())
print '%s. Nextfile (bs=%s)' % (start
+2, bs
)
verify(fi
.readline() == 'Line 1 of file 3\n')
verify(fi
.lineno() == 22)
print '%s. Stdin (bs=%s)' % (start
+3, bs
)
fi
= FileInput(files
=(t1
, t2
, t3
, t4
, '-'), bufsize
=bs
)
sys
.stdin
= StringIO("Line 1 of stdin\nLine 2 of stdin\n")
verify(lines
[32] == 'Line 2 of stdin\n')
verify(fi
.filename() == '<stdin>')
print '%s. Boundary conditions (bs=%s)' % (start
+4, bs
)
fi
= FileInput(files
=(t1
, t2
, t3
, t4
), bufsize
=bs
)
verify(fi
.filename() == None)
verify(fi
.filename() == None)
print '%s. Inplace (bs=%s)' % (start
+5, bs
)
fi
= FileInput(files
=(t1
, t2
, t3
, t4
), inplace
=1, bufsize
=bs
)
fi
= FileInput(files
=(t1
, t2
, t3
, t4
), bufsize
=bs
)
verify(int(m
.group(1)) == fi
.filelineno())
t1
= writeTmp(1, ["Line %s of file 1\n" % (i
+1) for i
in range(15)])
t2
= writeTmp(2, ["Line %s of file 2\n" % (i
+1) for i
in range(10)])
t3
= writeTmp(3, ["Line %s of file 3\n" % (i
+1) for i
in range(5)])
t4
= writeTmp(4, ["Line %s of file 4\n" % (i
+1) for i
in range(1)])
# First, run the tests with default and teeny buffer size.
for round, bs
in (0, 0), (1, 30):
runTests(t1
, t2
, t3
, t4
, bs
, round)
remove_tempfiles(t1
, t2
, t3
, t4
)
# Next, check for proper behavior with 0-byte files.
t3
= writeTmp(3, ["The only line there is.\n"])
fi
= FileInput(files
=(t1
, t2
, t3
, t4
))
verify(line
== 'The only line there is.\n')
verify(fi
.filelineno() == 1)
verify(fi
.filename() == t3
)
verify(fi
.filelineno() == 0)
verify(fi
.filename() == t4
)
remove_tempfiles(t1
, t2
, t3
, t4
)
print "14. Files that don't end with newline"
t1
= writeTmp(1, ["A\nB\nC"])
t2
= writeTmp(2, ["D\nE\nF"])
fi
= FileInput(files
=(t1
, t2
))
verify(lines
== ["A\n", "B\n", "C", "D\n", "E\n", "F"])
verify(fi
.filelineno() == 3)