Skip to content

Commit abb3e2c

Browse files
authored
Merge pull request #2405 from oesteban/enh/add-hashfile-tests
[ENH] Add tests to ``hash_files``
2 parents c28dbd4 + 50c7cb0 commit abb3e2c

File tree

1 file changed

+39
-13
lines changed

1 file changed

+39
-13
lines changed

nipype/utils/filemanip.py

Lines changed: 39 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,13 @@
33
# vi: set ft=python sts=4 ts=4 sw=4 et:
44
"""Miscellaneous file manipulation functions
55
6+
.. testsetup::
7+
# Change directory to provide relative paths for doctests
8+
>>> import os
9+
>>> filepath = os.path.dirname(os.path.realpath( __file__ ))
10+
>>> datadir = os.path.realpath(os.path.join(filepath, '../testing/data'))
11+
>>> os.chdir(datadir)
12+
613
"""
714
from __future__ import (print_function, division, unicode_literals,
815
absolute_import)
@@ -222,19 +229,38 @@ def check_forhash(filename):
222229
return False, None
223230

224231

225-
def hash_infile(afile, chunk_len=8192, crypto=hashlib.md5):
226-
""" Computes hash of a file using 'crypto' module"""
227-
hex = None
228-
if op.isfile(afile):
229-
crypto_obj = crypto()
230-
with open(afile, 'rb') as fp:
231-
while True:
232-
data = fp.read(chunk_len)
233-
if not data:
234-
break
235-
crypto_obj.update(data)
236-
hex = crypto_obj.hexdigest()
237-
return hex
232+
def hash_infile(afile, chunk_len=8192, crypto=hashlib.md5,
233+
raise_notfound=False):
234+
"""
235+
Computes hash of a file using 'crypto' module
236+
237+
>>> hash_infile('smri_ants_registration_settings.json')
238+
'49b956387ed8d95a4eb44576fc5103b6'
239+
240+
>>> hash_infile('surf01.vtk')
241+
'fdf1cf359b4e346034372cdeb58f9a88'
242+
243+
>>> hash_infile('spminfo')
244+
'0dc55e3888c98a182dab179b976dfffc'
245+
246+
>>> hash_infile('fsl_motion_outliers_fd.txt')
247+
'defd1812c22405b1ee4431aac5bbdd73'
248+
249+
250+
"""
251+
if not op.isfile(afile):
252+
if raise_notfound:
253+
raise RuntimeError('File "%s" not found.' % afile)
254+
return None
255+
256+
crypto_obj = crypto()
257+
with open(afile, 'rb') as fp:
258+
while True:
259+
data = fp.read(chunk_len)
260+
if not data:
261+
break
262+
crypto_obj.update(data)
263+
return crypto_obj.hexdigest()
238264

239265

240266
def hash_timestamp(afile):

0 commit comments

Comments
 (0)