Advertisement
hakonhagland

Test of parse_replacement

Mar 15th, 2015
616
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.94 KB | None | 0 0
  1. ---------------------------------------------------------------
  2. Perl code for running test of the parse_replacement sub routine
  3. ---------------------------------------------------------------
  4.  
  5. use feature qw(say);
  6. use strict;
  7. use warnings;
  8.  
  9. use Carp;
  10. use Data::Dump qw(dd dump);
  11. use Scalar::Util 'reftype';
  12.  
  13. # Test cases:
  14. # Format:
  15. # string, regex, replacement, expected
  16. my @test_cases = (
  17. ['aba', 'a(.*?)a', '$1', 'b'],
  18. ['ababaxxa', 'a(.*?)a', '$1', 'bxx'],
  19. ['acccb','a(.*?)b', '$1\$', 'ccc$'],
  20. ['abxybaxy','(x)(y)', '${2}3$1', 'aby3xbay3x']
  21. );
  22.  
  23. for (0..$#test_cases) {
  24. say "Case " . ($_ + 1);
  25. say "--------";
  26. my ($str, $regex, $replacement, $expected_result) = @{$test_cases[$_]};
  27. say "String: '$str'";
  28. say "Regex: " . dump($regex);
  29. say "Replacement: '$replacement'";
  30. say "Expected: '$expected_result'";
  31. my @captures = $str =~ /$regex/g;
  32. say "Captures: " . dump(@captures);
  33. my $func = parse_replacement( $replacement );
  34. my $result = $func->(\@captures);
  35. say "Result1: '$result'";
  36. $str =~ s/$regex/$result/g;
  37. say "Result2: '$str'";
  38. say "Test result: " . (($expected_result eq $str) ? "passed" : "failed");
  39. say "";
  40. }
  41.  
  42.  
  43. ************************
  44. Output:
  45. ************************
  46.  
  47. Case 1
  48. --------
  49. String: 'aba'
  50. Regex: "a(.*?)a"
  51. Replacement: '$1'
  52. Expected: 'b'
  53. Captures: "b"
  54. Result1: 'b'
  55. Result2: 'b'
  56. Test result: passed
  57.  
  58. Case 2
  59. --------
  60. String: 'ababaxxa'
  61. Regex: "a(.*?)a"
  62. Replacement: '$1'
  63. Expected: 'bxx'
  64. Captures: ("b", "xx")
  65. Result1: 'b'
  66. Result2: 'bbb'
  67. Test result: failed
  68.  
  69. Case 3
  70. --------
  71. String: 'acccb'
  72. Regex: "a(.*?)b"
  73. Replacement: '$1\$'
  74. Expected: 'ccc$'
  75. Captures: "ccc"
  76. Result1: 'ccc$'
  77. Result2: 'ccc$'
  78. Test result: passed
  79.  
  80. Case 4
  81. --------
  82. String: 'abxybaxy'
  83. Regex: "(x)(y)"
  84. Replacement: '${2}3$1'
  85. Expected: 'aby3xbay3x'
  86. Captures: ("x", "y", "x", "y")
  87. Result1: 'y3x'
  88. Result2: 'aby3xbay3x'
  89. Test result: passed
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement