Reputation: 3339
I'm migrating quite a few tests from JUnit to Spock:
// before
assertEquals("John Doe", userDTO.getFirstName());
// after
userDTO.getFirstName() == "John Doe"
To help make things quicker I want to replace (most of) JUnit's assert expressions with Spock's via a regular expression - supervised and file-by-file. assertFalse
, assertTrue
and assertNotNull
are easy, but assertEqual
is not since it has 2 parameters.
My current attempt is: assertEquals\(([^;]+),([^;]+)\);
. But this doesn't work so well because it doesn't know whether a ,
separates an assertEquals parameter or not. How to I solve this?
My test cases are:
assertEquals(az, bz);
assertEquals(az(), bz);
assertEquals(az, bz());
assertEquals(az(), bz));
assertEquals(az, bz(cz, dz));
assertEquals(bz(cz, dz), az);
PS: Nested method calls are out of scope here.
Online: https://www.debuggex.com/r/aESv3YmNWsakNgI6/1
Upvotes: 0
Views: 1311
Reputation: 20270
In general, matching arbitrarily nested structures with regexes is not something you should be doing. If we, however, limit your needs to the test cases you've listed here (removing the 4th, which is an error), then we can do something. You can also construct regexes for a variety of additional limited cases without making the thing too difficult.
I'll illustrate with python, but the same things probably work in your IDE.
>>> import re
>>> import pprint
>>> t = ["assertEquals(az, bz);", \
... "assertEquals(az(), bz);", \
... "assertEquals(az, bz());", \
... "assertEquals(az, bz(dz));", \
... "assertEquals(bz(dz), az);", \
... "assertEquals(az, bz(cz, dz));", \
... "assertEquals(bz(cz, dz), az);"]
>>> var = r'([a-z]+(\(([a-z]+(\s*,\s*[a-z]+)*)?\))?)'
>>> res = [ \
... re.sub( \
... r'assertEquals\(\s*' + var + '\s*,\s*' + var + '\s*\)', \
... r'\1 == \5', str \
... ) \
... for str in t]
>>> pprint.pprint(res)
['az == bz;',
'az() == bz;',
'az == bz();',
'az == bz(dz);',
'bz(dz) == az;',
'az == bz(cz, dz);',
'bz(cz, dz) == az;']
The important part is var
:
( # group the entire var before the comma
[a-z]+ # acceptable variable name
( # followed by an optional group
\( # containing a pair of matching parens
( # which contain, optionally
[a-z]+ # an acceptable variable name
( # followed by any number (0 or more)
\s*,\s*[a-z]+ # of commas followed by acceptable variable names
)*
)?
\)
)?
)
To get this to work on your actual code, you'll have to change [a-z]
to something more reasonable like [a-zA-Z0-9_]
Upvotes: 1