|
| 1 | +package fj.parser; |
| 2 | + |
| 3 | +import fj.F; |
| 4 | +import fj.F0; |
| 5 | +import fj.data.Stream; |
| 6 | +import fj.data.Validation; |
| 7 | +import org.junit.Test; |
| 8 | + |
| 9 | +import static fj.parser.Result.result; |
| 10 | +import static org.hamcrest.core.Is.is; |
| 11 | +import static org.junit.Assert.*; |
| 12 | + |
| 13 | +public class ParserTest { |
| 14 | + @Test |
| 15 | + public void testParserFail() { |
| 16 | + final Parser<String, String, Exception> fail = Parser.fail(new ParseException()); |
| 17 | + assertThat(fail.parse("").fail(), is(new ParseException())); |
| 18 | + } |
| 19 | + |
| 20 | + @Test |
| 21 | + public void testParserValue() { |
| 22 | + final Parser<String, String, Exception> p = Parser.parser(s -> s.isEmpty() ? |
| 23 | + Validation.fail(new ParseException()) : |
| 24 | + Validation.success(result(s.substring(1), s.substring(0, 1))) |
| 25 | + ); |
| 26 | + final Result<String, String> r = p.parse("abc").success(); |
| 27 | + assertThat(r.value(), is("a")); |
| 28 | + assertThat(r.rest(), is("bc")); |
| 29 | + } |
| 30 | + |
| 31 | + @Test |
| 32 | + public void testParserBind() { |
| 33 | + final Parser<String, String, Exception> p = Parser.value("a"); |
| 34 | + final Parser<String, String, Exception> fail = Parser.fail(new ParseException()); |
| 35 | + assertThat(p.bind(o -> fail).parse("aaaa").fail(), is(new ParseException())); |
| 36 | + } |
| 37 | + |
| 38 | + @Test |
| 39 | + public void testParserStream() { |
| 40 | + Stream<Character> s = Stream.fromString("abc"); |
| 41 | + Result<Stream<Character>, Character> r = Parser.CharsParser.character('a').parse(s).success(); |
| 42 | + assertThat(r, is(Result.result(Stream.fromString("bc"), 'a'))); |
| 43 | + } |
| 44 | + |
| 45 | + class ParseException extends Exception { |
| 46 | + @Override |
| 47 | + public boolean equals (Object obj) { |
| 48 | + return (obj instanceof ParseException); |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | +} |
0 commit comments