test_tutorials.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import os.path as osp
  15. import re
  16. import tempfile
  17. import shutil
  18. from glob import iglob
  19. from testing_utils import run_script, CpuCommonTest
  20. class TestTutorial(CpuCommonTest):
  21. SUBDIR = "./"
  22. TIMEOUT = 300
  23. REGEX = ".*"
  24. @classmethod
  25. def setUpClass(cls):
  26. cls._td = tempfile.TemporaryDirectory(dir='./')
  27. # Recursively copy the content of cls.SUBDIR to td.
  28. # This is necessary for running scripts in td.
  29. cls._TSUBDIR = osp.join(cls._td.name, osp.basename(cls.SUBDIR))
  30. shutil.copytree(cls.SUBDIR, cls._TSUBDIR)
  31. return super().setUpClass()
  32. @classmethod
  33. def tearDownClass(cls):
  34. cls._td.cleanup()
  35. @staticmethod
  36. def add_tests(cls):
  37. """
  38. Automatically patch testing functions to cls.
  39. """
  40. def _test_tutorial(script_name):
  41. def _test_tutorial_impl(self):
  42. # Set working directory to cls._TSUBDIR such that the
  43. # files generated by the script will be automatically cleaned.
  44. run_script(f"python {script_name}", wd=cls._TSUBDIR)
  45. return _test_tutorial_impl
  46. for script_path in filter(
  47. re.compile(cls.REGEX).match,
  48. iglob(osp.join(cls.SUBDIR, '*.py'))):
  49. script_name = osp.basename(script_path)
  50. if osp.normpath(osp.join(cls.SUBDIR, script_name)) != osp.normpath(
  51. script_path):
  52. raise ValueError(
  53. f"{script_name} should be directly contained in {cls.SUBDIR}"
  54. )
  55. setattr(cls, 'test_' + osp.splitext(script_name)[0],
  56. _test_tutorial(script_name))
  57. return cls
  58. @TestTutorial.add_tests
  59. class TestCDTutorial(TestTutorial):
  60. SUBDIR = "../tutorials/train/change_detection"
  61. @TestTutorial.add_tests
  62. class TestClasTutorial(TestTutorial):
  63. SUBDIR = "../tutorials/train/classification"
  64. @TestTutorial.add_tests
  65. class TestDetTutorial(TestTutorial):
  66. SUBDIR = "../tutorials/train/object_detection"
  67. @TestTutorial.add_tests
  68. class TestSegTutorial(TestTutorial):
  69. SUBDIR = "../tutorials/train/semantic_segmentation"