filesystemmixin.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #!/usr/bin/env python3
  2. # Contest Management System - http://cms-dev.github.io/
  3. # Copyright © 2018 Stefano Maggiolo <s.maggiolo@gmail.com>
  4. #
  5. # This program is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU Affero General Public License as
  7. # published by the Free Software Foundation, either version 3 of the
  8. # License, or (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU Affero General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU Affero General Public License
  16. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. """A unittest.TestCase mixin for tests interacting with the filesystem.
  18. """
  19. import os
  20. import shutil
  21. import tempfile
  22. class FileSystemMixin:
  23. """Mixin for tests with filesystem access."""
  24. def setUp(self):
  25. super().setUp()
  26. self.base_dir = tempfile.mkdtemp()
  27. def tearDown(self):
  28. shutil.rmtree(self.base_dir)
  29. super().tearDown()
  30. def get_path(self, inner_path):
  31. "Return the full path for a given inner path within the temp dir."
  32. return os.path.join(self.base_dir, inner_path)
  33. def makedirs(self, inner_path):
  34. """Create (possibly many) directories up to inner_path.
  35. inner_path (str): path to create.
  36. return (str): full path of the possibly new directory.
  37. """
  38. path = self.get_path(inner_path)
  39. try:
  40. os.makedirs(path)
  41. except FileExistsError:
  42. pass
  43. return path
  44. def write_file(self, inner_path, content):
  45. """Write content and return the full path.
  46. inner_path (str): path inside the temp dir to write to.
  47. content (bytes): content to write.
  48. return (str): full path of the file written.
  49. """
  50. path = self.get_path(inner_path)
  51. with open(path, "wb") as f:
  52. f.write(content)
  53. return path