ExpectIt icon indicating copy to clipboard operation
ExpectIt copied to clipboard

How to know which Matcher was used when using Matchers.anyOf.

Open xak2000 opened this issue 8 years ago • 3 comments

For example I want to do:

Result result = expect.expect(anyOf(contains("reconfigure"), regexp("# $")));
if (/* first matcher was used */) {
  // The output contains "reconfigure" string.
  // Do something.
} else if (/* second matcher was used */) {
  // The output doesn't contains "reconfigure" string, but contains "# $" regexp.
  // Do something else.
}

How could I know the index of used matcher?

xak2000 avatar Mar 22 '16 06:03 xak2000

Now I use:

MultiResult result = expect.expect(anyOf(contains("reconfigure"), regexp("# $")));
if (result.getResults().get(0).isSuccessful()) {
    // The output contains "reconfigure" string.
} else {
    // The output doesn't contains "reconfigure" string, but contains "# $" regexp.
}

Is it correct way? Is there a way to just get an index of matched pattern (0 or 1 in this case). Something like result.getMatchedIndex(). Maybe then this is a feature request. :)

xak2000 avatar Mar 22 '16 09:03 xak2000

Sorry for delay. Somehow I missed this github notification among the others.

Note that MultiResult implements Result and delegates their methods to the matched result. So the MultiResult instance will contain the matching information either of contains("reconfigure") or regexp("# $").

You can also consider using interact feature. For example:

        expect.interact()
                .when(contains("reconfigure")).then(r -> System.out.println("A"))
                .when(regexp("# $")).then(r -> System.err.println("B"))
                .until(contains("END"));

agavrilov76 avatar Apr 06 '16 20:04 agavrilov76

Don't worry! The result.getResults().get(0).isSuccessful() solution works fine.

I know that MultiResult implements Result, but I do not understand how it can help me to recognize which matcher is matched from passed to anyOf. Comparing strings? It is not better then just using isSuccessful().

About interact it is definitely interesting feature! Maybe I will try it later. At the moment I'm entirely happy with the result.getResults().get(0).isSuccessful() solution.

By method getMatchedIndex() in MultiResult I meant something like:

public int getMatchedIndex() {
  for(int i = 0; i < results.size(); i++) {
    if (results.get(i).isSuccessful()) {
      return i;
    }
  }
  return -1;
}

But now I'm not sure if this method is really necessary... It will only return correct result for anyOf matcher but not for allOf matcher. For allOf matcher this method has no sense.

xak2000 avatar Apr 07 '16 00:04 xak2000