actc
actc

Reputation: 682

Regular Expression to find incomplete Java assertions

In Java you can use assert() statements like these:

// ok
assertFalse(",", Boolean.FALSE);
assertFalse("", Boolean.FALSE);
assertFalse("ab" + "cd" + "de", Boolean.FALSE);
assertFalse(errorMessage, Boolean.FALSE);
assertFalse(errorMessage.toString(), Boolean.FALSE);
assertFalse("Assertion failed, because: " + errorMessage.toString(), Boolean.FALSE);

// nok    
assertFalse(Boolean.FALSE);
assertFalse(expectedMessage.endsWith("ab,cd"));

From a code style point-of-view we define asserts as OK if the assert has an assertion error message as first argument and NOK = Not OK if it is absent.

Having said that, I need a regular expression that searches for asserts that do not have a comma , in their round brackets (). Commas inside string constants (delimited by quotes ") must also be excluded as they lead to false positives.

I ended up with this regular expression which obviously does not take quotes into account as I cannot get those working for me:

assert(False|NotNull|Null|True)\(\s*.*(?!,).*\s*\);

We also use assertEquals and assertSame which need three commas but this could be a separate regex.

Any ideas or solutions on that? How can we find assertFalse() statements that only have one argument?

Please don't come up with any other tools or plugins as they are forbidden to use. Just pure regex. Thank you.

Upvotes: 0

Views: 207

Answers (1)

ctwheels
ctwheels

Reputation: 22837

See regex in use here

assert(?:False|(?:Not)?Null|True)\([^(),]*(?:\([^)]*\))*\);
  • assert Match this literally
  • (?:False|(?:Not)?Null|True) Match either False, NotNull, Null, or True
  • \( Match ( literally
  • [^(),]* Match any number of any character except (, ) or ,
  • (?:\([^)]*\))* Match the following any number of times
    • Match (, followed by any character except ) any number of times, then by )
  • \); Match ); literally

To properly catch these instances, however, you're better to write a parser because Java's regex engine doesn't allow recursion or balancing. This means a regex (like the one I provided) will break on nested () within () such as assertFalse(something(somethingelse()));. If you don't care about these cases, then you can use regex, otherwise, I'd advise you to create a parser or use another method.

Upvotes: 2

Related Questions