Skip to content

Commit

Permalink
fix(cron): Correctly detect if an expression is fuzzy or not (#549)
Browse files Browse the repository at this point in the history
The current logic is flawed in that it just looks for the character `H`
hence an expression like `0 0 0 ? * MON-THU` will be considered fuzzy and will
be described correctly by `validateCronExpression`
  • Loading branch information
marchello2000 committed May 16, 2019
1 parent d175913 commit b55709f
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public static boolean isValid(String expression) {
}

public static boolean hasFuzzyExpression(String expression) {
return expression.contains(TOKEN);
return Tokens.tokenize(expression).hasFuzzyToken();
}

private static class Tokens {
Expand Down Expand Up @@ -81,6 +81,10 @@ static Tokens tokenize(String expression) {
return new Tokens(t[0], t[1], t[2], t[3], t[4], t[5], (t.length == 7) ? t[6] : null);
}

boolean hasFuzzyToken() {
return seconds.contains(TOKEN) || minutes.contains(TOKEN) || hours.contains(TOKEN);
}

String toFuzzedExpression(String id) {
if (seconds.contains(TOKEN)) {
seconds = seconds.replace(TOKEN, hash(id, 59));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,24 @@ class CronExpressionFuzzerSpec extends Specification {
"abcd" | "H * * * * *" || "34 * * * * *"
"abcde" | "* * H * * *" || "* * 3 * * *"
"abcd" | "H/5 * * * * *" || "34/5 * * * * *"
"abcd" | "00 05 09 ? * MON-THU" || "00 05 09 ? * MON-THU"
}

@Unroll
def "should correctly detect fuzz tokens"() {
when:
def result = CronExpressionFuzzer.hasFuzzyExpression(expression)

then:
result == expected

where:
expression || expected
"H * * * * *" || true
"* * H * * *" || true
"H/5 * * * * *" || true
"H/5 * * * * THU" || true
"00 05 09 ? * MON-THU" || false
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,13 @@ class ValidationControllerSpec extends Specification {

void 'should include description when expression is valid'() {
when:
def result = validate("0 0 10 ? * 1")
def result = validate("0 0 10 ? * THU")

def responseBody = objectMapper.readValue(result.response.contentAsByteArray, Map)

then:
responseBody.response == "Cron expression is valid"
responseBody.description == "At 10:00 AM, only on Sunday"
responseBody.description == "At 10:00 AM, only on Thursday"
}

void 'should include failure message when expression is invalid'() {
Expand Down

0 comments on commit b55709f

Please sign in to comment.