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.function.Function;
21  
22  import static io.atlassian.fugue.Functions.compose;
23  import static io.atlassian.fugue.Option.some;
24  import static org.hamcrest.Matchers.is;
25  import static org.hamcrest.Matchers.notNullValue;
26  import static org.junit.Assert.assertThat;
27  import static org.junit.Assert.assertTrue;
28  
29  public class FunctionComposeTest {
30    Function<String, Option<Integer>> toInt = input -> {
31      try {
32        return Option.some(Integer.parseInt(input));
33      } catch (NumberFormatException e) {
34        return Option.none();
35      }
36    };
37  
38    Function<Integer, Option<String>> toString = input -> Option.some(input.toString());
39  
40    @Test public void composeNotNull() {
41      assertThat(Functions.composeOption(toString, toInt), notNullValue());
42    }
43  
44    @Test(expected = NullPointerException.class) public void nullFirst() {
45      compose(null, toInt);
46    }
47  
48    @Test(expected = NullPointerException.class) public void nullSecond() {
49      compose(toInt, null);
50    }
51  
52    @Test public void someForInt() {
53      assertThat(Functions.composeOption(toString, toInt).apply("12"), is(some("12")));
54    }
55  
56    @Test public void noneForNonParsable() {
57      assertThat(Functions.composeOption(toString, toInt).apply("twelve"), is(Option.<String> none()));
58    }
59  
60    @Test public void referenceEqualityOfComposition() {
61      final Function<Integer, Integer> intFunc = (a) -> a + 1;
62      final Function<Integer, Double> intDouble = (a) -> a + 1.0;
63      assertTrue(compose(intDouble, intFunc).equals(compose(intDouble, intFunc)));
64    }
65  }