helper.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import difflib
  2. import os
  3. import sys
  4. def helper_init(file, subdir):
  5. # I hate how clumsy Python is here
  6. dirname = os.path.join(".", os.path.dirname(file))
  7. parent_dir = os.path.join("..", os.path.dirname(file))
  8. sys.path.append(parent_dir)
  9. return os.path.join(dirname, subdir)
  10. def compare_one(func, python_file, verbose=True):
  11. from spark_parser.example.python2.py2_scan import ENDMARKER
  12. right_file = python_file[:-2] + "right"
  13. got_file = python_file[:-2] + "got"
  14. # Python 2.5 tolerance
  15. py_fp = open(python_file, "r")
  16. input_data = py_fp.read() + ENDMARKER
  17. items = func(input_data)
  18. got = [str(t) + "\n" for t in items]
  19. same = True
  20. right_fp = open(right_file, "r")
  21. right_data = right_fp.readlines()
  22. lines = difflib.unified_diff(got, right_data, fromfile=right_file, tofile=got_file)
  23. for line in lines:
  24. same = False
  25. sys.stdout.write(line)
  26. pass
  27. if not same:
  28. got_fp = open(got_file, "w")
  29. got_fp.writelines(got)
  30. got_fp.close()
  31. else:
  32. if verbose:
  33. print("Yay! %s matches" % python_file)
  34. if verbose:
  35. print("-" * 30)
  36. py_fp.close()
  37. right_fp.close()
  38. return same
  39. def run_tests(func, test_dir, match_files=None):
  40. old_dir = os.getcwd()
  41. os.chdir(test_dir)
  42. for python_file in os.listdir(os.getcwd()):
  43. if python_file.endswith(".py"):
  44. if not match_files or python_file in match_files:
  45. compare_one(func, python_file)
  46. pass
  47. pass
  48. pass
  49. os.chdir(old_dir)
  50. return
  51. def run_tests_unit(cls, func, test_dir, match_files=None, verbose=False):
  52. old_dir = os.getcwd()
  53. os.chdir(test_dir)
  54. for python_file in os.listdir(os.getcwd()):
  55. if python_file.endswith(".py"):
  56. print(python_file)
  57. if not match_files or python_file in match_files:
  58. cls.assertTrue(compare_one(func, python_file, verbose), python_file)
  59. pass
  60. pass
  61. pass
  62. os.chdir(old_dir)
  63. return