aa86d90c80f0f5e67f7b689bad946299e06bab35
[jalview.git] / test / jalview / testutils / AnnotationsMatcher.java
1 package jalview.testutils;
2
3 import java.util.List;
4 import java.util.Objects;
5 import static java.util.Objects.requireNonNullElse;
6
7 import org.hamcrest.Description;
8 import org.hamcrest.TypeSafeMatcher;
9
10 import jalview.datamodel.Annotation;
11
12 public class AnnotationsMatcher extends TypeSafeMatcher<Annotation[]>
13 {
14   final List<Annotation> annotations;
15
16   public AnnotationsMatcher(List<Annotation> annotations)
17   {
18     this.annotations = annotations;
19   }
20
21   @Override
22   public boolean matchesSafely(Annotation[] items)
23   {
24     if (annotations.size() != items.length)
25       return false;
26     for (int i = 0; i < annotations.size(); i++)
27     {
28       var actual = items[i];
29       var expected = annotations.get(i);
30       if (!annotationsEqual(actual, expected))
31         return false;
32     }
33     return true;
34   }
35
36   static boolean annotationsEqual(Annotation a, Annotation b)
37   {
38     return a.secondaryStructure == b.secondaryStructure && a.value == b.value
39         && Objects.equals(a.colour, b.colour)
40         && Objects
41             .equals(requireNonNullElse(a.displayCharacter, ""),
42                 requireNonNullElse(b.displayCharacter, ""))
43         && Objects
44             .equals(requireNonNullElse(a.description, ""),
45                 requireNonNullElse(b.description, ""));
46   }
47
48   @Override
49   public void describeTo(Description description)
50   {
51     description.appendText("annotations ").appendValue(annotations);
52   }
53
54   @Override
55   public void describeMismatchSafely(Annotation[] items,
56       Description description)
57   {
58     if (annotations.size() != items.length)
59     {
60       description.appendText("but had length ").appendValue(items.length);
61       return;
62     }
63     boolean first = true;
64     for (int i = 0; i < annotations.size(); i++)
65     {
66       var actual = items[i];
67       var expected = annotations.get(i);
68       if (!annotationsEqual(actual, expected))
69       {
70         description
71             .appendText(first ? "but " : ", ")
72             .appendText("element [" + i + "] was ")
73             .appendValue(items[i]);
74         first = false;
75       }
76     }
77   }
78 }