tools.py 2.5 KB

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