package be.jeffcheasey88.peeratcode.parser.java; import static org.junit.Assert.assertNotNull; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junit.jupiter.api.TestInstance.Lifecycle; import be.jeffcheasey88.peeratcode.parser.java.operations.ConditionalOperation; import be.jeffcheasey88.peeratcode.parser.java.operations.ConditionalOperation.IfOperation; import be.jeffcheasey88.peeratcode.parser.java.operations.MethodCallOperation; @TestInstance(Lifecycle.PER_CLASS) class SearchTest{ JavaParser parse(String code) throws Exception{ BufferedReader reader = new BufferedReader(new Reader(){public int read(char[] cbuf, int off, int len) throws IOException{return 0;}public void close() throws IOException {}}) { private boolean read = false; @Override public String readLine() throws IOException{ if(read) return null; read = true; return code; } }; JavaParser parser = new JavaParser(reader); parser.parse(); return parser; } @Test void methodCallSearch(){ try { JavaParser parser = parse("package be.jeffcheasey88.peeratcode.parser.java; class Test{ void function(){ int i = 0; if(i == 0){ this.none(); } } }"); JavaElement element = parser.find( (e) -> e instanceof MethodCallOperation, (trace) -> true); assertNotNull(element); } catch (Exception e) { e.printStackTrace(); } } @Test void methodCallOutOfIfSearch(){ try { JavaParser parser = parse("package be.jeffcheasey88.peeratcode.parser.java; class Test{ void function(){ int i = 0; if(i == 0){ this.none(); } valid(); } }"); JavaElement element = parser.find( (e) -> e instanceof MethodCallOperation, (trace) -> !trace.stream().anyMatch((e) -> (e instanceof ConditionalOperation))); assertNotNull(element); assertEquals("valid()", ((MethodCallOperation)element).getValue()); } catch (Exception e) { e.printStackTrace(); } } @Test void siplifiedMethodCallInIfSearch(){ try { JavaParser parser = parse("package be.jeffcheasey88.peeratcode.parser.java; class Test{ void function(){ int i = 0; if(i == 0){ this.none(); } valid(); } }"); MethodCallOperation element = parser.find( (e, trace) -> { return (e instanceof MethodCallOperation) && (trace.get(trace.size()-2) instanceof IfOperation); }); assertNotNull(element); assertEquals("this.none()", element.getValue()); } catch (Exception e) { e.printStackTrace(); } } }