tools.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. # -*- coding: utf-8 -*-
  2. """
  3. Common tools that are useful for neo.io object tests
  4. """
  5. # needed for python 3 compatibility
  6. from __future__ import absolute_import
  7. import logging
  8. import os
  9. import shutil
  10. import tempfile
  11. try:
  12. from urllib2 import urlopen
  13. except ImportError:
  14. from urllib.request import urlopen
  15. def can_use_network():
  16. """
  17. Return True if network access is allowed
  18. """
  19. if os.environ.get('NOSETESTS_NO_NETWORK', False):
  20. return False
  21. if os.environ.get('TRAVIS') == 'true':
  22. return False
  23. return True
  24. def make_all_directories(filename, localdir):
  25. """
  26. Make the directories needed to store test files
  27. """
  28. # handle case of multiple filenames
  29. if not hasattr(filename, 'lower'):
  30. for ifilename in filename:
  31. make_all_directories(ifilename, localdir)
  32. return
  33. fullpath = os.path.join(localdir, os.path.dirname(filename))
  34. if os.path.dirname(filename) != '' and not os.path.exists(fullpath):
  35. if not os.path.exists(os.path.dirname(fullpath)):
  36. make_all_directories(os.path.dirname(filename), localdir)
  37. os.mkdir(fullpath)
  38. def download_test_file(filename, localdir, url):
  39. """
  40. Download a test file from a server if it isn't already available.
  41. filename is the name of the file.
  42. localdir is the local directory to store the file in.
  43. url is the remote url that the file should be downloaded from.
  44. """
  45. # handle case of multiple filenames
  46. if not hasattr(filename, 'lower'):
  47. for ifilename in filename:
  48. download_test_file(ifilename, localdir, url)
  49. return
  50. localfile = os.path.join(localdir, filename)
  51. distantfile = url + '/' + filename
  52. if not os.path.exists(localfile):
  53. logging.info('Downloading %s here %s', distantfile, localfile)
  54. dist = urlopen(distantfile)
  55. with open(localfile, 'wb') as f:
  56. f.write(dist.read())
  57. def create_local_temp_dir(name, directory=None):
  58. """
  59. Create a directory for storing temporary files needed for testing neo
  60. If directory is None or not specified, automatically create the directory
  61. in {tempdir}/files_for_testing_neo on linux/unix/mac or
  62. {tempdir}\files_for_testing_neo on windows, where {tempdir} is the system
  63. temporary directory returned by tempfile.gettempdir().
  64. """
  65. if directory is None:
  66. directory = os.path.join(tempfile.gettempdir(),
  67. 'files_for_testing_neo')
  68. if not os.path.exists(directory):
  69. os.mkdir(directory)
  70. directory = os.path.join(directory, name)
  71. if not os.path.exists(directory):
  72. os.mkdir(directory)
  73. return directory