regex_test.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #!/usr/bin/env python
  2. """
  3. This program generates random text that matches a given regex-pattern.
  4. The pattern is given via sys.argv and the generated text is passed to
  5. the binary 'tests/test_rand' to check if the generated text also matches
  6. the regex-pattern in the C implementation.
  7. The exit-code of the testing program, is used to determine test success.
  8. This script is called by the Makefile when doing 'make test'
  9. """
  10. import re
  11. import sys
  12. import exrex
  13. from subprocess import call
  14. prog = "./tests/test_rand"
  15. if len(sys.argv) < 2:
  16. print("")
  17. print("usage: %s pattern [nrepeat]" % sys.argv[0])
  18. print(" where [nrepeat] is optional")
  19. print("")
  20. sys.exit(-1)
  21. own_prog = sys.argv[0]
  22. pattern = sys.argv[1]
  23. if len(sys.argv) > 2:
  24. ntests = int(sys.argv[2])
  25. else:
  26. ntests = 10
  27. nfails = 0
  28. repeats = ntests
  29. try:
  30. repeats = int(sys.argv[2])
  31. except:
  32. pass
  33. r = 50
  34. while r < 0:
  35. try:
  36. g = exrex.generate(pattern)
  37. break
  38. except:
  39. pass
  40. sys.stdout.write("%-35s" % (" pattern '%s': " % pattern))
  41. while repeats >= 0:
  42. try:
  43. repeats -= 1
  44. example = exrex.getone(pattern)
  45. #print("%s %s %s" % (prog, pattern, example))
  46. ret = call([prog, "\"%s\"" % pattern, "\"%s\"" % example])
  47. if ret != 0:
  48. escaped = repr(example) # escapes special chars for better printing
  49. print(" FAIL : doesn't match %s as expected [%s]." % (escaped, ", ".join([("0x%02x" % ord(e)) for e in example]) ))
  50. nfails += 1
  51. except:
  52. #import traceback
  53. #print("EXCEPTION!")
  54. #raw_input(traceback.format_exc())
  55. ntests -= 1
  56. repeats += 1
  57. #nfails += 1
  58. sys.stdout.write("%4d/%d tests succeeded \n" % (ntests - nfails, ntests))
  59. #print("")