filesystem_dynamic_test_helper.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import sys
  2. import os
  3. import socket
  4. import stat
  5. # Ensure that this is being run on a specific platform
  6. assert sys.platform.startswith('linux') or sys.platform.startswith('darwin') \
  7. or sys.platform.startswith('cygwin') or sys.platform.startswith('freebsd') \
  8. or sys.platform.startswith('netbsd')
  9. def env_path():
  10. ep = os.environ.get('LIBCXX_FILESYSTEM_DYNAMIC_TEST_ROOT')
  11. assert ep is not None
  12. ep = os.path.realpath(ep)
  13. assert os.path.isdir(ep)
  14. return ep
  15. env_path_global = env_path()
  16. # Make sure we don't try and write outside of env_path.
  17. # All paths used should be sanitized
  18. def sanitize(p):
  19. p = os.path.realpath(p)
  20. if os.path.commonprefix([env_path_global, p]):
  21. return p
  22. assert False
  23. """
  24. Some of the tests restrict permissions to induce failures.
  25. Before we delete the test environment, we have to walk it and re-raise the
  26. permissions.
  27. """
  28. def clean_recursive(root_p):
  29. if not os.path.islink(root_p):
  30. os.chmod(root_p, 0o777)
  31. for ent in os.listdir(root_p):
  32. p = os.path.join(root_p, ent)
  33. if os.path.islink(p) or not os.path.isdir(p):
  34. os.remove(p)
  35. else:
  36. assert os.path.isdir(p)
  37. clean_recursive(p)
  38. os.rmdir(p)
  39. def init_test_directory(root_p):
  40. root_p = sanitize(root_p)
  41. assert not os.path.exists(root_p)
  42. os.makedirs(root_p)
  43. def destroy_test_directory(root_p):
  44. root_p = sanitize(root_p)
  45. clean_recursive(root_p)
  46. os.rmdir(root_p)
  47. def create_file(fname, size):
  48. with open(sanitize(fname), 'w') as f:
  49. f.write('c' * size)
  50. def create_dir(dname):
  51. os.mkdir(sanitize(dname))
  52. def create_symlink(source, link):
  53. os.symlink(sanitize(source), sanitize(link))
  54. def create_hardlink(source, link):
  55. os.link(sanitize(source), sanitize(link))
  56. def create_fifo(source):
  57. os.mkfifo(sanitize(source))
  58. def create_socket(source):
  59. sock = socket.socket(socket.AF_UNIX)
  60. sanitized_source = sanitize(source)
  61. # AF_UNIX sockets may have very limited path length, so split it
  62. # into chdir call (with technically unlimited length) followed
  63. # by bind() relative to the directory
  64. os.chdir(os.path.dirname(sanitized_source))
  65. sock.bind(os.path.basename(sanitized_source))
  66. if __name__ == '__main__':
  67. command = " ".join(sys.argv[1:])
  68. eval(command)
  69. sys.exit(0)