View Javadoc

1   /*
2      Copyright 2011 Atlassian
3   
4      Licensed under the Apache License, Version 2.0 (the "License");
5      you may not use this file except in compliance with the License.
6      You may obtain a copy of the License at
7   
8          http://www.apache.org/licenses/LICENSE-2.0
9   
10     Unless required by applicable law or agreed to in writing, software
11     distributed under the License is distributed on an "AS IS" BASIS,
12     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13     See the License for the specific language governing permissions and
14     limitations under the License.
15   */
16  package io.atlassian.fugue;
17  
18  import org.junit.Test;
19  
20  import java.util.Arrays;
21  import java.util.List;
22  
23  import static io.atlassian.fugue.Either.left;
24  import static io.atlassian.fugue.Either.right;
25  import static io.atlassian.fugue.Eithers.sequenceLeft;
26  import static io.atlassian.fugue.Eithers.sequenceRight;
27  import static org.hamcrest.Matchers.contains;
28  import static org.hamcrest.Matchers.is;
29  import static org.junit.Assert.assertThat;
30  
31  @SuppressWarnings("unchecked") public class EitherSequenceTest {
32    @Test public void sequenceRights() {
33      final List<Either<Object, Integer>> eithers = Arrays.asList(right(1), right(2), right(3));
34      assertThat(sequenceRight(eithers).right().get(), contains(1, 2, 3));
35    }
36  
37    @Test public void sequenceRightWithLeft() {
38      final Iterable<Either<String, Integer>> eithers = build(Build.<String, Integer> r(1), Build.<String, Integer> l("2"),
39        Build.<String, Integer> r(3));
40      assertThat(sequenceRight(eithers), is(Build.<String, Iterable<Integer>> l("2")));
41    }
42  
43    @Test public void sequenceLefts() {
44      final List<Either<Integer, Object>> eithers = Arrays.asList(left(1), left(2), left(3));
45      assertThat(sequenceLeft(eithers).left().get(), contains(1, 2, 3));
46    }
47  
48    @Test public void sequenceLeftWithRight() {
49      final Iterable<Either<String, Integer>> eithers = build(Build.<String, Integer> l("1"), Build.<String, Integer> r(2),
50        Build.<String, Integer> l("3"));
51      assertThat(sequenceLeft(eithers), is(Build.<Iterable<String>, Integer> r(2)));
52    }
53  
54    static class Build {
55      static <L, R> Either<L, R> r(final R i) {
56        return right(i);
57      }
58  
59      static <L, R> Either<L, R> l(final L s) {
60        return left(s);
61      }
62    }
63  
64    static <L, R> Iterable<Either<L, R>> build(final Either<L, R>... e) {
65      return Arrays.asList(e);
66    }
67  }