MakeExpectedRegex transform a raw string of an expected output into a regex suitable for testing. Some markers like ExpId are available to substitute the appropriate regex for element that can vary randomly.
(input string)
| 15 | // MakeExpectedRegex transform a raw string of an expected output into a regex suitable for testing. |
| 16 | // Some markers like ExpId are available to substitute the appropriate regex for element that can vary randomly. |
| 17 | func MakeExpectedRegex(input string) string { |
| 18 | var substitutes = map[string]string{ |
| 19 | ExpId: `[0-9a-f]{64}`, |
| 20 | ExpHumanId: `[0-9a-f]{7}`, |
| 21 | ExpTimestamp: `[0-9]{7,10}`, |
| 22 | ExpISO8601: `\d{4}(-\d\d(-\d\d(T\d\d:\d\d(:\d\d)?(\.\d+)?(([+-]\d\d:\d\d)|Z)?)?)?)?`, |
| 23 | ExpOrgModeDate: `\d\d\d\d-\d\d-\d\d [[:alpha:]]{3} \d\d:\d\d`, |
| 24 | } |
| 25 | |
| 26 | escaped := []rune(regexp.QuoteMeta(input)) |
| 27 | |
| 28 | var result strings.Builder |
| 29 | var inSubstitute bool |
| 30 | var substitute strings.Builder |
| 31 | |
| 32 | result.WriteString("^") |
| 33 | |
| 34 | for i := 0; i < len(escaped); i++ { |
| 35 | r := escaped[i] |
| 36 | if !inSubstitute && r == '\x07' { |
| 37 | substitute.Reset() |
| 38 | substitute.WriteRune(r) |
| 39 | inSubstitute = true |
| 40 | continue |
| 41 | } |
| 42 | if inSubstitute && r == '\x07' { |
| 43 | substitute.WriteRune(r) |
| 44 | sub, ok := substitutes[substitute.String()] |
| 45 | if !ok { |
| 46 | panic("unknown substitute: " + substitute.String()) |
| 47 | } |
| 48 | result.WriteString(sub) |
| 49 | inSubstitute = false |
| 50 | continue |
| 51 | } |
| 52 | if inSubstitute { |
| 53 | substitute.WriteRune(r) |
| 54 | } else { |
| 55 | result.WriteRune(r) |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | result.WriteString("$") |
| 60 | |
| 61 | return result.String() |
| 62 | } |