run.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. #!/usr/bin/env python3
  2. # -*- Coding: UTF-8 -*-
  3. # ---------------------------------------------------------------------------
  4. # Open Asset Import Library (ASSIMP)
  5. # ---------------------------------------------------------------------------
  6. #
  7. # Copyright (c) 2006-2020, ASSIMP Development Team
  8. #
  9. # All rights reserved.
  10. #
  11. # Redistribution and use of this software in source and binary forms,
  12. # with or without modification, are permitted provided that the following
  13. # conditions are met:
  14. #
  15. # * Redistributions of source code must retain the above
  16. # copyright notice, this list of conditions and the
  17. # following disclaimer.
  18. #
  19. # * Redistributions in binary form must reproduce the above
  20. # copyright notice, this list of conditions and the
  21. # following disclaimer in the documentation and/or other
  22. # materials provided with the distribution.
  23. #
  24. # * Neither the name of the ASSIMP team, nor the names of its
  25. # contributors may be used to endorse or promote products
  26. # derived from this software without specific prior
  27. # written permission of the ASSIMP Development Team.
  28. #
  29. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  30. # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  31. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  32. # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  33. # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  34. # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  35. # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  36. # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  37. # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  38. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  39. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  40. # ---------------------------------------------------------------------------
  41. """
  42. Run the regression test suite using settings from settings.py.
  43. The assimp_cmd (or assimp) binary to use is specified by the first
  44. command line argument and defaults to ``assimp``.
  45. To build, set ``ASSIMP_BUILD_ASSIMP_TOOLS=ON`` in CMake. If generating
  46. configs for an IDE, make sure to build the assimp_cmd project.
  47. On Windows, use ``py run.py <path to assimp>`` to make sure the command
  48. line parameter is forwarded to the script.
  49. """
  50. import sys
  51. import os
  52. import subprocess
  53. import zipfile
  54. import collections
  55. import multiprocessing
  56. import settings
  57. import utils
  58. # -------------------------------------------------------------------------------
  59. EXPECTED_FAILURE_NOT_MET, DATABASE_LENGTH_MISMATCH, \
  60. DATABASE_VALUE_MISMATCH, IMPORT_FAILURE, \
  61. FILE_NOT_READABLE, COMPARE_SUCCESS, EXPECTED_FAILURE = range(7)
  62. messages = collections.defaultdict(lambda: "<unknown", {
  63. EXPECTED_FAILURE_NOT_MET:
  64. """Unexpected success during import\n\
  65. \tReturn code was 0""",
  66. DATABASE_LENGTH_MISMATCH:
  67. """Database mismatch: lengths don't match\n\
  68. \tExpected: {0} Actual: {1}""",
  69. DATABASE_VALUE_MISMATCH:
  70. """Database mismatch: """,
  71. IMPORT_FAILURE:
  72. """Unexpected failure during import\n\
  73. \tReturn code was {0}""",
  74. FILE_NOT_READABLE:
  75. """Unexpected failure reading file""",
  76. COMPARE_SUCCESS:
  77. """Results match archived reference dump in database\n\
  78. \tNumber of bytes compared: {0}""",
  79. EXPECTED_FAILURE:
  80. """Expected failure was met.""",
  81. })
  82. outfilename_output = "run_regression_suite_output.txt"
  83. outfilename_failur = "run_regression_suite_failures.csv"
  84. Environment = {}
  85. # -------------------------------------------------------------------------------
  86. class results:
  87. """ Handle formatting of results"""
  88. def __init__(self, zipin):
  89. """Init, given a ZIPed database """
  90. self.failures = []
  91. self.success = []
  92. self.zipin = zipin
  93. def fail(self, failfile, filename_expect, pp, msg, *args):
  94. """
  95. Report failure of a sub-test
  96. File f failed a test for pp config pp, failure notice is msg,
  97. *args is format()ting args for msg
  98. """
  99. print("[FAILURE] " + messages[msg].format(*args))
  100. self.failures.append((failfile, filename_expect, pp))
  101. def ok(self, f, pp, msg, *args):
  102. """
  103. Report success of a sub-test
  104. File f passed the test, msg is a happy success note,
  105. *args is format()ing args for msg.
  106. """
  107. print("[SUCCESS] " + messages[msg].format(*args))
  108. self.success.append(f)
  109. def report_results(self):
  110. """Write results to ../results/run_regression_suite_failures.txt"""
  111. count_success = len(self.success)
  112. count_fail = len(self.failures)
  113. percent_good = float(count_success) / (count_success + count_fail)
  114. print("\n" + ('='*60) + "\n" + "SUCCESS: {0}\nFAILURE: {1}\nPercentage good: {2}".format(
  115. count_success, count_fail, percent_good) +
  116. "\n" + ('='*60) + "\n")
  117. with open(os.path.join('..', 'results',outfilename_failur), "wt") as f:
  118. f.write("ORIGINAL FILE;EXPECTED DUMP\n")
  119. f.writelines(map(
  120. lambda x: x[0] + ' ' + x[2] + ";" + x[1] + "\n", self.failures))
  121. if self.failures:
  122. print("\nSee " + settings.results + "\\" + outfilename_failur
  123. + " for more details\n\n")
  124. def hasFailures( self ):
  125. """ Return True, if any failures there. """
  126. return 0 != len( self.failures )
  127. # -------------------------------------------------------------------------------
  128. def setEnvVar( var, value ):
  129. print ( "set var " + var +" to" + value)
  130. Environment[ var ] = value
  131. # -------------------------------------------------------------------------------
  132. def getEnvVar( var ):
  133. if var in Environment:
  134. return Environment[ var ]
  135. else:
  136. print ( "Error: cannot find " + var )
  137. return ""
  138. # -------------------------------------------------------------------------------
  139. def prepare_output_dir(fullpath, myhash, app):
  140. outfile = os.path.join(settings.results, "tmp", os.path.split(fullpath)[1] + "_" + myhash)
  141. try:
  142. os.mkdir(outfile)
  143. except OSError:
  144. pass
  145. outfile = os.path.join(outfile, app)
  146. return outfile
  147. # -------------------------------------------------------------------------------
  148. def process_dir(d, outfile_results, zipin, result ):
  149. shellparams = {'stdout':outfile_results, 'stderr':outfile_results, 'shell':False}
  150. print("Processing directory " + d)
  151. all = ""
  152. for f in sorted(os.listdir(d)):
  153. fullpath = os.path.join(d, f)
  154. if os.path.isdir(fullpath) and not f[:1] == '.':
  155. process_dir(fullpath, outfile_results, zipin, result)
  156. continue
  157. if f in settings.files_to_ignore or os.path.splitext(f)[1] in settings.exclude_extensions:
  158. print("Ignoring " + f)
  159. return
  160. for pppreset in settings.pp_configs_to_test:
  161. filehash = utils.hashing(fullpath, pppreset)
  162. failure = False
  163. try:
  164. input_expected = zipin.open(filehash, "r").read()
  165. # empty dump files indicate 'expected import failure'
  166. if not len(input_expected):
  167. failure = True
  168. except KeyError:
  169. # TODO(acgessler): Keep track of this and report as error in the end.
  170. print("Didn't find "+fullpath+" (Hash is "+filehash+") in database. Outdated "+\
  171. "regression database? Use gen_db.zip to re-generate.")
  172. continue
  173. print("-"*60 + "\n " + os.path.realpath(fullpath) + " pp: " + pppreset)
  174. outfile_actual = prepare_output_dir(fullpath, filehash, "ACTUAL")
  175. outfile_expect = prepare_output_dir(fullpath, filehash, "EXPECT")
  176. outfile_results.write("assimp dump "+"-"*80+"\n")
  177. outfile_results.flush()
  178. assimp_bin_path = getEnvVar("assimp_path")
  179. command = [assimp_bin_path,
  180. "dump",
  181. fullpath, outfile_actual, "-b", "-s", "-l" ] +\
  182. pppreset.split()
  183. print( "command = " + str( command ) )
  184. r = subprocess.call(command, **shellparams)
  185. outfile_results.flush()
  186. if r and not failure:
  187. result.fail(fullpath, outfile_expect, pppreset, IMPORT_FAILURE, r)
  188. outfile_results.write("Failed to import\n")
  189. continue
  190. elif failure and not r:
  191. result.fail(fullpath, outfile_expect, pppreset, EXPECTED_FAILURE_NOT_MET)
  192. outfile_results.write("Expected import to fail\n")
  193. continue
  194. elif failure and r:
  195. result.ok(fullpath, pppreset, EXPECTED_FAILURE)
  196. outfile_results.write("Failed as expected, skipping.\n")
  197. continue
  198. with open(outfile_expect, "wb") as s:
  199. s.write(input_expected)
  200. try:
  201. with open(outfile_actual, "rb") as s:
  202. input_actual = s.read()
  203. except IOError:
  204. continue
  205. outfile_results.write("Expected data length: {0}\n".format(len(input_expected)))
  206. outfile_results.write("Actual data length: {0}\n".format(len(input_actual)))
  207. failed = False
  208. if len(input_expected) != len(input_actual):
  209. result.fail(fullpath, outfile_expect, pppreset, DATABASE_LENGTH_MISMATCH,
  210. len(input_expected), len(input_actual))
  211. # Still compare the dumps to see what the difference is
  212. failed = True
  213. outfile_results.write("assimp cmpdump "+"-"*80+"\n")
  214. outfile_results.flush()
  215. command = [ assimp_bin_path, 'cmpdump', outfile_actual, outfile_expect ]
  216. if subprocess.call(command, **shellparams) != 0:
  217. if not failed:
  218. result.fail(fullpath, outfile_expect, pppreset, DATABASE_VALUE_MISMATCH)
  219. continue
  220. result.ok(fullpath, pppreset, COMPARE_SUCCESS, len(input_expected))
  221. # -------------------------------------------------------------------------------
  222. def del_folder_with_contents(folder):
  223. for root, dirs, files in os.walk(folder, topdown=False):
  224. for name in files:
  225. os.remove(os.path.join(root, name))
  226. for name in dirs:
  227. os.rmdir(os.path.join(root, name))
  228. # -------------------------------------------------------------------------------
  229. def run_test():
  230. tmp_target_path = os.path.join(settings.results, "tmp")
  231. try:
  232. print( "try to make " + tmp_target_path )
  233. os.mkdir(tmp_target_path)
  234. except OSError as oerr:
  235. # clear contents if tmp folder exists already
  236. del_folder_with_contents(tmp_target_path)
  237. try:
  238. zipin = zipfile.ZipFile(settings.database_name + ".zip",
  239. "r", zipfile.ZIP_STORED)
  240. except IOError:
  241. print("Regression database ", settings.database_name,
  242. ".zip was not found")
  243. return
  244. res = results(zipin)
  245. with open(os.path.join(settings.results, outfilename_output), "wt") as outfile:
  246. for tp in settings.model_directories:
  247. process_dir(tp, outfile, zipin, res)
  248. res.report_results()
  249. if res.hasFailures():
  250. return 1
  251. return 0
  252. # -------------------------------------------------------------------------------
  253. if __name__ == "__main__":
  254. if len(sys.argv) > 1:
  255. assimp_bin_path = sys.argv[1]
  256. else:
  257. assimp_bin_path = 'assimp'
  258. setEnvVar("assimp_path", assimp_bin_path)
  259. print('Using assimp binary: ' + assimp_bin_path)
  260. sys.exit( run_test() )
  261. # vim: ai ts=4 sts=4 et sw=4