vavr refactor (#1871)

* vavr refactor

* small fix
This commit is contained in:
lor6
2017-05-18 21:44:35 +03:00
committed by Grzegorz Piwowarek
parent 7728d58e5b
commit 70680ea79a
15 changed files with 137 additions and 133 deletions
@@ -0,0 +1,112 @@
package com.baeldung.vavr;
import static io.vavr.API.$;
import static io.vavr.API.Case;
import static io.vavr.API.Match;
import static io.vavr.API.run;
import static io.vavr.Predicates.*;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import io.vavr.MatchError;
import io.vavr.control.Option;
public class PatternMatchingUnitTest {
@Test
public void whenMatchesDefault_thenCorrect() {
int input = 5;
String output = Match(input).of(Case($(1), "one"), Case($(2), "two"), Case($(3), "three"), Case($(), "unknown"));
assertEquals("unknown", output);
}
@Test(expected = MatchError.class)
public void givenNoMatchAndNoDefault_whenThrows_thenCorrect() {
int input = 5;
Match(input).of(Case($(1), "one"), Case($(2), "two"));
}
@Test
public void whenMatchWorksWithOption_thenCorrect() {
int i = 10;
Option<String> s = Match(i).option(Case($(0), "zero"));
assertTrue(s.isEmpty());
assertEquals("None", s.toString());
}
@Test
public void whenMatchWorksWithPredicate_thenCorrect() {
int i = 3;
String s = Match(i).of(Case($(is(1)), "one"), Case($(is(2)), "two"), Case($(is(3)), "three"), Case($(), "?"));
assertEquals("three", s);
}
@Test
public void givenInput_whenMatchesClass_thenCorrect() {
Object obj = 5;
String s = Match(obj).of(Case($(instanceOf(String.class)), "string matched"), Case($(), "not string"));
assertEquals("not string", s);
}
@Test
public void givenInput_whenMatchesNull_thenCorrect() {
Object obj = 5;
String s = Match(obj).of(Case($(isNull()), "no value"), Case($(isNotNull()), "value found"));
assertEquals("value found", s);
}
@Test
public void givenInput_whenContainsWorks_thenCorrect() {
int i = 5;
String s = Match(i).of(Case($(isIn(2, 4, 6, 8)), "Even Single Digit"), Case($(isIn(1, 3, 5, 7, 9)), "Odd Single Digit"), Case($(), "Out of range"));
assertEquals("Odd Single Digit", s);
}
@Test
public void givenInput_whenMatchAllWorks_thenCorrect() {
Integer i = null;
String s = Match(i).of(Case($(allOf(isNotNull(), isIn(1, 2, 3, null))), "Number found"), Case($(), "Not found"));
assertEquals("Not found", s);
}
@Test
public void givenInput_whenMatchesAnyOfWorks_thenCorrect() {
Integer year = 1990;
String s = Match(year).of(Case($(anyOf(isIn(1990, 1991, 1992), is(1986))), "Age match"), Case($(), "No age match"));
assertEquals("Age match", s);
}
@Test
public void givenInput_whenMatchesNoneOfWorks_thenCorrect() {
Integer year = 1990;
String s = Match(year).of(Case($(noneOf(isIn(1990, 1991, 1992), is(1986))), "Age match"), Case($(), "No age match"));
assertEquals("No age match", s);
}
@Test
public void whenMatchWorksWithPredicate_thenCorrect2() {
int i = 5;
String s = Match(i).of(Case($(isIn(2, 4, 6, 8)), "Even Single Digit"), Case($(isIn(1, 3, 5, 7, 9)), "Odd Single Digit"), Case($(), "Out of range"));
assertEquals("Odd Single Digit", s);
}
@Test
public void whenMatchCreatesSideEffects_thenCorrect() {
int i = 4;
Match(i).of(Case($(isIn(2, 4, 6, 8)), o -> run(this::displayEven)), Case($(isIn(1, 3, 5, 7, 9)), o -> run(this::displayOdd)), Case($(), o -> run(() -> {
throw new IllegalArgumentException(String.valueOf(i));
})));
}
public void displayEven() {
System.out.println("Input is even");
}
public void displayOdd() {
System.out.println("Input is odd");
}
}
@@ -0,0 +1,71 @@
package com.baeldung.vavr;
import io.vavr.CheckedFunction1;
import io.vavr.collection.Stream;
import io.vavr.test.Arbitrary;
import io.vavr.test.CheckResult;
import io.vavr.test.Property;
import org.junit.Test;
import java.util.function.Predicate;
import static io.vavr.API.*;
public class PropertyBasedLongRunningUnitTest {
private static Predicate<Integer> divisibleByTwo = i -> i % 2 == 0;
private static Predicate<Integer> divisibleByFive = i -> i % 5 == 0;
private Stream<String> stringsSupplier() {
return Stream.from(0).map(i -> Match(i).of(
Case($(divisibleByFive.and(divisibleByTwo)), "DividedByTwoAndFiveWithoutRemainder"),
Case($(divisibleByFive), "DividedByFiveWithoutRemainder"),
Case($(divisibleByTwo), "DividedByTwoWithoutRemainder"),
Case($(), "")));
}
@Test
public void givenArbitrarySeq_whenCheckThatEverySecondElementIsEqualToString_thenTestPass() {
//given
Arbitrary<Integer> multiplesOf2 = Arbitrary
.integer()
.filter(i -> i > 0)
.filter(i -> i % 2 == 0 && i % 5 != 0);
//when
CheckedFunction1<Integer, Boolean> mustEquals = i -> stringsSupplier()
.get(i)
.equals("DividedByTwoWithoutRemainder");
//then
CheckResult result = Property
.def("Every second element must equal to DividedByTwoWithoutRemainder")
.forAll(multiplesOf2)
.suchThat(mustEquals)
.check(10_000, 100);
result.assertIsSatisfied();
}
@Test
public void givenArbitrarySeq_whenCheckThatEveryFifthElementIsEqualToString_thenTestPass() {
//given
Arbitrary<Integer> multiplesOf5 = Arbitrary
.integer()
.filter(i -> i > 0)
.filter(i -> i % 5 == 0 && i % 2 == 0);
//when
CheckedFunction1<Integer, Boolean> mustEquals = i -> stringsSupplier()
.get(i)
.endsWith("DividedByTwoAndFiveWithoutRemainder");
//then
Property
.def("Every fifth element must equal to DividedByTwoAndFiveWithoutRemainder")
.forAll(multiplesOf5)
.suchThat(mustEquals)
.check(10_000, 1_000)
.assertIsSatisfied();
}
}
@@ -0,0 +1,336 @@
package com.baeldung.vavr;
import io.vavr.Function0;
import io.vavr.Function1;
import io.vavr.Function2;
import io.vavr.Function5;
import io.vavr.Lazy;
import io.vavr.*;
import io.vavr.collection.List;
import io.vavr.collection.Seq;
import io.vavr.control.Option;
import io.vavr.control.Try;
import io.vavr.control.Validation;
import org.junit.Test;
import com.baeldung.vavr.Person;
import com.baeldung.vavr.PersonValidator;
import java.util.Arrays;
import java.util.Collections;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.IntStream;
import static io.vavr.API.*;
import static org.junit.Assert.*;
public class VavrUnitTest {
@Test
public void givenList_whenSorts_thenCorrect() {
List<Integer> sortedList = List.of(3, 2, 1)
.sorted();
}
/*
* Tuples
*/
// creating and element access
@Test
public void whenCreatesTuple_thenCorrect1() {
Tuple2<String, Integer> java8 = Tuple.of("Java", 8);
String element1 = java8._1;
int element2 = java8._2();
assertEquals("Java", element1);
assertEquals(8, element2);
}
@Test
public void whenCreatesTuple_thenCorrect2() {
Tuple3<String, Integer, Double> java8 = Tuple.of("Java", 8, 1.8);
String element1 = java8._1;
int element2 = java8._2();
double element3 = java8._3();
assertEquals("Java", element1);
assertEquals(8, element2);
assertEquals(1.8, element3, 0.1);
}
// mapping--component-wise(using Function interface)
@Test
public void givenTuple_whenMapsComponentWise_thenCorrect() {
Tuple2<String, Integer> java8 = Tuple.of("Java", 8);
Tuple2<String, Integer> mapOfJava8 = java8.map(s -> s + "Vavr", i -> i / 2);
int num = mapOfJava8._2();
assertEquals("JavaVavr", mapOfJava8._1);
assertEquals(4, num);
}
// mapping--with one mapper(using BiFunction interface)
@Test
public void givenTuple_whenMapsWithOneMapper_thenCorrect() {
Tuple2<String, Integer> java8 = Tuple.of("Java", 8);
Tuple2<String, Integer> mapOfJava8 = java8.map((s, i) -> Tuple.of(s + "Vavr", i / 2));
int num = mapOfJava8._2();
assertEquals("JavaVavr", mapOfJava8._1);
assertEquals(4, num);
}
// transforming a tuple
@Test
public void givenTuple_whenTransforms_thenCorrect() {
Tuple2<String, Integer> java8 = Tuple.of("Java", 8);
String transformed = java8.apply((s, i) -> s + "Vavr " + i / 2);
assertEquals("JavaVavr 4", transformed);
}
/*
* Functions
*/
@Test
public void givenJava8Function_whenWorks_thenCorrect() {
Function<Integer, Integer> square = (num) -> num * num;
int result = square.apply(2);
assertEquals(4, result);
}
@Test
public void givenJava8BiFunction_whenWorks_thenCorrect() {
BiFunction<Integer, Integer, Integer> sum = (num1, num2) -> num1 + num2;
int result = sum.apply(5, 7);
assertEquals(12, result);
}
@Test
public void givenVavrFunction_whenWorks_thenCorrect() {
Function1<Integer, Integer> square = (num) -> num * num;
Integer result = square.apply(2);
assertEquals(Integer.valueOf(4), result);
}
@Test
public void givenVavrBiFunction_whenWorks_thenCorrect() {
Function2<Integer, Integer, Integer> sum = (num1, num2) -> num1 + num2;
Integer result = sum.apply(5, 7);
assertEquals(Integer.valueOf(12), result);
}
@Test
public void whenCreatesFunction_thenCorrect0() {
Function0<String> getClazzName = () -> this.getClass()
.getName();
String clazzName = getClazzName.apply();
assertEquals("com.baeldung.vavr.VavrUnitTest", clazzName);
}
@Test
public void whenCreatesFunction_thenCorrect2() {
Function2<Integer, Integer, Integer> sum = (a, b) -> a + b;
int summed = sum.apply(5, 6);
assertEquals(11, summed);
}
@Test
public void whenCreatesFunction_thenCorrect5() {
Function5<String, String, String, String, String, String> concat = (a, b, c, d, e) -> a + b + c + d + e;
String finalString = concat.apply("Hello ", "world", "! ", "Learn ", "Vavr");
assertEquals("Hello world! Learn Vavr", finalString);
}
@Test
public void whenCreatesFunctionFromMethodRef_thenCorrect() {
Function2<Integer, Integer, Integer> sum = Function2.of(this::sum);
int summed = sum.apply(5, 6);
assertEquals(11, summed);
}
public int sum(int a, int b) {
return a + b;
}
/*
* Values
*/
// option
@Test
public void givenValue_whenNullCheckNeeded_thenCorrect() {
Object possibleNullObj = null;
if (possibleNullObj == null)
possibleNullObj = "someDefaultValue";
assertNotNull(possibleNullObj);
}
@Test(expected = NullPointerException.class)
public void givenValue_whenNullCheckNeeded_thenCorrect2() {
Object possibleNullObj = null;
assertEquals("somevalue", possibleNullObj.toString());
}
@Test
public void givenValue_whenCreatesOption_thenCorrect() {
Option<Object> noneOption = Option.of(null);
Option<Object> someOption = Option.of("val");
assertEquals("None", noneOption.toString());
assertEquals("Some(val)", someOption.toString());
}
@Test
public void givenNull_whenCreatesOption_thenCorrect() {
String name = null;
Option<String> nameOption = Option.of(name);
assertEquals("baeldung", nameOption.getOrElse("baeldung"));
}
@Test
public void givenNonNull_whenCreatesOption_thenCorrect() {
String name = "baeldung";
Option<String> nameOption = Option.of(name);
assertEquals("baeldung", nameOption.getOrElse("notbaeldung"));
}
// try
@Test(expected = ArithmeticException.class)
public void givenBadCode_whenThrowsException_thenCorrect() {
int i = 1 / 0;
}
@Test
public void givenBadCode_whenTryHandles_thenCorrect() {
Try<Integer> result = Try.of(() -> 1 / 0);
assertTrue(result.isFailure());
}
@Test
public void givenBadCode_whenTryHandles_thenCorrect2() {
Try<Integer> result = Try.of(() -> 1 / 0);
int errorSentinel = result.getOrElse(-1);
assertEquals(-1, errorSentinel);
}
// @Test(expected = ArithmeticException.class)
// public void givenBadCode_whenTryHandles_thenCorrect3() {
// Try<Integer> result = Try.of(() -> 1 / 0);
// result.getOrElseThrow(ArithmeticException::new);
// }
// lazy
@Test
public void givenFunction_whenEvaluatesWithLazy_thenCorrect() {
Lazy<Double> lazy = Lazy.of(Math::random);
assertFalse(lazy.isEvaluated());
double val1 = lazy.get();
assertTrue(lazy.isEvaluated());
double val2 = lazy.get();
assertEquals(val1, val2, 0.1);
}
// validation
@Test
public void whenValidationWorks_thenCorrect() {
PersonValidator personValidator = new PersonValidator();
Validation<Seq<String>, Person> valid = personValidator.validatePerson("John Doe", 30);
Validation<Seq<String>, Person> invalid = personValidator.validatePerson("John? Doe!4", -1);
assertEquals("Valid(Person [name=John Doe, age=30])", valid.toString());
assertEquals("Invalid(List(Invalid characters in name: ?!4, Age must be at least 0))", invalid.toString());
}
/*
* collections
*/
// list
@Test(expected = UnsupportedOperationException.class)
public void whenImmutableCollectionThrows_thenCorrect() {
java.util.List<String> wordList = Arrays.asList("abracadabra");
java.util.List<String> list = Collections.unmodifiableList(wordList);
list.add("boom");
}
@Test
public void whenSumsJava8List_thenCorrect() {
// Arrays.asList(1, 2, 3).stream().reduce((i, j) -> i + j);
int sum = IntStream.of(1, 2, 3)
.sum();
assertEquals(6, sum);
}
@Test
public void whenCreatesVavrList_thenCorrect() {
List<Integer> intList = List.of(1, 2, 3);
assertEquals(3, intList.length());
assertEquals(new Integer(1), intList.get(0));
assertEquals(new Integer(2), intList.get(1));
assertEquals(new Integer(3), intList.get(2));
}
@Test
public void whenSumsVavrList_thenCorrect() {
int sum = List.of(1, 2, 3)
.sum()
.intValue();
assertEquals(6, sum);
}
/*
* pattern matching
*/
@Test
public void whenIfWorksAsMatcher_thenCorrect() {
int input = 3;
String output;
if (input == 0) {
output = "zero";
}
if (input == 1) {
output = "one";
}
if (input == 2) {
output = "two";
}
if (input == 3) {
output = "three";
} else {
output = "unknown";
}
assertEquals("three", output);
}
@Test
public void whenSwitchWorksAsMatcher_thenCorrect() {
int input = 2;
String output;
switch (input) {
case 0:
output = "zero";
break;
case 1:
output = "one";
break;
case 2:
output = "two";
break;
case 3:
output = "three";
break;
default:
output = "unknown";
break;
}
assertEquals("two", output);
}
@Test
public void whenMatchworks_thenCorrect() {
int input = 2;
String output = Match(input).of(Case($(1), "one"), Case($(2), "two"), Case($(3), "three"), Case($(), "?"));
assertEquals("two", output);
}
}
@@ -0,0 +1,113 @@
package com.baeldung.vavr.exception.handling;
import com.baeldung.vavr.exception.handling.client.ClientException;
import com.baeldung.vavr.exception.handling.client.HttpClient;
import com.baeldung.vavr.exception.handling.client.Response;
import com.baeldung.vavr.exception.handling.VavrTry;
import io.vavr.collection.Stream;
import io.vavr.control.Option;
import io.vavr.control.Try;
import org.junit.Test;
import static io.vavr.API.*;
import static io.vavr.Predicates.instanceOf;
import static org.junit.Assert.*;
public class VavrTryUnitTest {
@Test
public void givenHttpClient_whenMakeACall_shouldReturnSuccess() {
//given
Integer defaultChainedResult = 1;
String id = "a";
HttpClient httpClient = () -> new Response(id);
//when
Try<Response> response = new VavrTry(httpClient).getResponse();
Integer chainedResult = response
.map(this::actionThatTakesResponse)
.getOrElse(defaultChainedResult);
Stream<String> stream = response.toStream().map(it -> it.id);
//then
assertTrue(!stream.isEmpty());
assertTrue(response.isSuccess());
response.onSuccess(r -> assertEquals(id, r.id));
response.andThen(r -> assertEquals(id, r.id));
assertNotEquals(defaultChainedResult, chainedResult);
}
@Test
public void givenHttpClientFailure_whenMakeACall_shouldReturnFailure() {
//given
Integer defaultChainedResult = 1;
HttpClient httpClient = () -> {
throw new ClientException("problem");
};
//when
Try<Response> response = new VavrTry(httpClient).getResponse();
Integer chainedResult = response
.map(this::actionThatTakesResponse)
.getOrElse(defaultChainedResult);
Option<Response> optionalResponse = response.toOption();
//then
assertTrue(optionalResponse.isEmpty());
assertTrue(response.isFailure());
response.onFailure(ex -> assertTrue(ex instanceof ClientException));
assertEquals(defaultChainedResult, chainedResult);
}
@Test
public void givenHttpClientThatFailure_whenMakeACall_shouldReturnFailureAndNotRecover() {
//given
Response defaultResponse = new Response("b");
HttpClient httpClient = () -> {
throw new RuntimeException("critical problem");
};
//when
Try<Response> recovered = new VavrTry(httpClient).getResponse()
.recover(r -> Match(r).of(
Case($(instanceOf(ClientException.class)), defaultResponse)
));
//then
assertTrue(recovered.isFailure());
// recovered.getOrElseThrow(throwable -> {
// throw new RuntimeException(throwable);
// });
}
@Test
public void givenHttpClientThatFailure_whenMakeACall_shouldReturnFailureAndRecover() {
//given
Response defaultResponse = new Response("b");
HttpClient httpClient = () -> {
throw new ClientException("non critical problem");
};
//when
Try<Response> recovered = new VavrTry(httpClient).getResponse()
.recover(r -> Match(r).of(
Case($(instanceOf(ClientException.class)), defaultResponse),
Case($(instanceOf(IllegalArgumentException.class)), defaultResponse)
));
//then
assertTrue(recovered.isSuccess());
}
public int actionThatTakesResponse(Response response) {
return response.id.hashCode();
}
public int actionThatTakesTryResponse(Try<Response> response, int defaultTransformation){
return response.transform(responses -> response.map(it -> it.id.hashCode()).getOrElse(defaultTransformation));
}
}