com.pholser.junit.quickcheck.From Java Examples

The following examples show how to use com.pholser.junit.quickcheck.From. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SparseListTest.java    From ReactFX with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Theory
public void depthBounds(
        @ForAll @From(ListMods.class) ListMod listMod) {
    SparseList<Integer> list = listMod.list;
    SparseListModification mod = listMod.mod;

    int depth = list.getDepth();
    int n = countSegments(list);
    assumeThat(depth, lessThanOrEqualTo(maxTreeDepth(n)));
    assumeThat(depth, greaterThanOrEqualTo(minTreeDepth(n)));

    mod.apply(list);

    depth = list.getDepth();
    n = countSegments(list);
    assertThat(depth, lessThanOrEqualTo(maxTreeDepth(n)));
    assertThat(depth, greaterThanOrEqualTo(minTreeDepth(n)));
}
 
Example #2
Source File: HashedMapTest.java    From JQF with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Fuzz
public void queryStringTest(@From(ArbitraryLengthStringGenerator.class) @Size(max=80) String queryString) {
    Assume.assumeTrue(queryString.length() > 0);
    String[] params = queryString.split("&");
    Map<String, String> map = new HashedMap<>();
    for (String param : params) {
        int eqIdx = param.indexOf('=');
        String key, value;
        if (eqIdx == -1 || eqIdx == 0) {
            continue;
        } else {
            key = param.substring(0, eqIdx);
            value = eqIdx < param.length()-1 ? param.substring(eqIdx+1) : "";
        }
        map.put(key, value);
    }
}
 
Example #3
Source File: CompilerTest.java    From JQF with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Fuzz
public void testWithString(@From(AsciiStringGenerator.class) String classBody) {
    // Construct test class with provided body
    String code = String.format("class Test { %s }", classBody);
    File javaFile;
    try {
        javaFile = writeToFile(code);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    // Compile using javac + error-prone
    Main.Result result = ErrorProneCompiler.compile(new String[]{ javaFile.getAbsolutePath()},
            new PrintWriter(new ByteArrayOutputStream( )));

    // Ensure that there was no issue with test command or environment
    Assert.assertFalse(result == CMDERR);
    Assert.assertFalse(result == SYSERR);

    // Ignore compilation errors (only semantically valid inputs will pass)
    Assume.assumeFalse(result == ERROR);

    // This is the main test criteria -- abnormal exits are bugs
    Assert.assertFalse( result == ABNORMAL);

}
 
Example #4
Source File: ParserTest.java    From JQF with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Fuzz
public void verifyJavaClass(@From(JavaClassGenerator.class) JavaClass javaClass) throws IOException {
    try {
        Repository.addClass(javaClass);
        Verifier verifier = StatelessVerifierFactory.getVerifier(javaClass.getClassName());
        VerificationResult result;
        result = verifier.doPass1();
        assumeThat(result.getMessage(), result.getStatus(), is(VerificationResult.VERIFIED_OK));
        result = verifier.doPass2();
        assumeThat(result.getMessage(), result.getStatus(), is(VerificationResult.VERIFIED_OK));
        for (int i = 0; i < javaClass.getMethods().length; i++) {
            result = verifier.doPass3a(i);
            assumeThat(result.getMessage(), result.getStatus(), is(VerificationResult.VERIFIED_OK));
        }
    } finally {
        Repository.clearCache();
    }
}
 
Example #5
Source File: RobustnessTest.java    From JQF with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Fuzz
public void testTwo(@From(AsciiStringGenerator.class) String s1, @From(AsciiStringGenerator.class) String s2) {
    if (s2.length() == 3) {
        if (s2.charAt(0) == 'a') {
            if (s2.charAt(1) == 'b') {
                if (s2.charAt(2) == 'c') {
                    if (s1.length() == 3) {
                        if (s1.charAt(0) == 'a') {
                            if (s1.charAt(1) == 'b') {
                                if (s1.charAt(2) == 'c') {
                                    assertTrue(false);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
 
Example #6
Source File: AvroUtilsTest.java    From beam with Apache License 2.0 6 votes vote down vote up
@Property(trials = 1000)
@SuppressWarnings("unchecked")
public void avroToBeamRoundTrip(
    @From(RecordSchemaGenerator.class) org.apache.avro.Schema avroSchema) {
  // not everything is possible to translate
  assumeThat(avroSchema, not(containsField(AvroUtilsTest::hasNonNullUnion)));
  // roundtrip for enums returns strings because Beam doesn't have enum type
  assumeThat(avroSchema, not(containsField(x -> x.getType() == Type.ENUM)));
  // roundtrip for fixed returns bytes because Beam doesn't have FIXED type
  assumeThat(avroSchema, not(containsField(x -> x.getType() == Type.FIXED)));

  Schema schema = AvroUtils.toBeamSchema(avroSchema);
  Iterable iterable = new RandomData(avroSchema, 10);
  List<GenericRecord> records = Lists.newArrayList((Iterable<GenericRecord>) iterable);

  for (GenericRecord record : records) {
    Row row = AvroUtils.toBeamRowStrict(record, schema);
    GenericRecord out = AvroUtils.toGenericRecord(row, avroSchema);
    assertEquals(record, out);
  }
}
 
Example #7
Source File: SparseListTest.java    From ReactFX with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Theory
public void leafCountEqualToSegmentCount(
        @ForAll @From(ListMods.class) ListMod listMod) {
    SparseList<Integer> list = listMod.list;
    SparseListModification mod = listMod.mod;

    int segments = countSegments(list);
    int leafs = list.getTree().getLeafCount();
    assumeThat(leafs, equalTo(segments));

    mod.apply(list);

    segments = countSegments(list);
    leafs = list.getTree().getLeafCount();
    assertThat(leafs, equalTo(segments));
}
 
Example #8
Source File: VertxVaadinRequestUT.java    From vertx-vaadin with MIT License 5 votes vote down vote up
@Property(trials = TRIALS)
public void shouldDelegateGetAttributeToRoutingContext(@From(RandomStringGenerator.class) String paramName,
                                                       @From(RandomStringGenerator.class) String value) {
    when(routingContext.get(paramName)).thenReturn(value);
    assertThat(vaadinRequest.getAttribute(paramName)).isEqualTo(value);
    assertThat(vaadinRequest.getAttribute(paramName + "NotExists")).isNull();
}
 
Example #9
Source File: VertxVaadinRequestUT.java    From vertx-vaadin with MIT License 5 votes vote down vote up
@Property(trials = TRIALS)
public void shouldDelegateGetAttributeToRoutingContext(@From(RandomStringGenerator.class) String paramName,
                                                       @From(RandomStringGenerator.class) String value) {
    when(routingContext.get(paramName)).thenReturn(value);
    assertThat(vaadinRequest.getAttribute(paramName)).isEqualTo(value);
    assertThat(vaadinRequest.getAttribute(paramName + "NotExists")).isNull();
}
 
Example #10
Source File: TestSmartPairSerializer.java    From mph-table with Apache License 2.0 5 votes vote down vote up
@Property
public void canRoundTripPairs(@From(PairGenerator.class)final Pair<String, Long> target) throws IOException {
    SmartPairSerializer<String, Long> serializer = new SmartPairSerializer<>(
            new SmartStringSerializer(),
            new SmartLongSerializer()
    );
    assertRoundTrip(serializer, target);
}
 
Example #11
Source File: VertxVaadinRequestUT.java    From vertx-vaadin with MIT License 5 votes vote down vote up
@Property(trials = TRIALS)
public void shouldDelegateGetHeader(@From(RandomStringGenerator.class) String name,
                                    @From(RandomStringGenerator.class) String value) {
    when(httpServerRequest.getHeader(name)).thenReturn(value);
    assertThat(vaadinRequest.getHeader(name)).isEqualTo(value);
    assertThat(vaadinRequest.getHeader(name + "notExist")).isNull();
}
 
Example #12
Source File: CompilerTest.java    From JQF with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Fuzz
public void testWithString(@From(AsciiStringGenerator.class) String input) {
    try {
        Script script = context.compileString(input, "input", 0, null);
    } catch (EvaluatorException e) {
        Assume.assumeNoException(e);
    }

}
 
Example #13
Source File: VertxVaadinRequestUT.java    From vertx-vaadin with MIT License 5 votes vote down vote up
@Property(trials = TRIALS)
public void shouldDelegateGetParameterToHttpServerRequest(@From(RandomStringGenerator.class) String paramName,
                                                          @From(RandomStringGenerator.class) String value) {
    when(httpServerRequest.getParam(paramName)).thenReturn(value);
    assertThat(vaadinRequest.getParameter(paramName)).isEqualTo(value);
    assertThat(vaadinRequest.getParameter(paramName + "NotExists")).isNull();
}
 
Example #14
Source File: PngReaderTest.java    From JQF with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Fuzz
public void readUsingKaitai(@From(PngKaitaiGenerator.class) @Size(max = 1024) InputStream input) throws IOException {
    // Decode image from input stream
    reader.setInput(ImageIO.createImageInputStream(input));
    // Bound dimensions
    Assume.assumeTrue(reader.getHeight(0) < 1024);
    Assume.assumeTrue(reader.getWidth(0) < 1024);
    // Parse PNG
    reader.read(0);
}
 
Example #15
Source File: RegexTest.java    From JQF with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Fuzz
public void patternGenerationTest(@From(ArbitraryLengthStringGenerator.class) String pattern) {
    try {
        Pattern.matches(pattern, "aaaaaa");
    } catch (PatternSyntaxException e) {
        Assume.assumeNoException(e);
    }
}
 
Example #16
Source File: SetsTest.java    From JQF with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Fuzz
public void fuzzHashSetInsertSets(Set<@From(AsciiStringGenerator.class) String> @Size(max=100)[] input) {
    HashSet<Set<?>> setOfSets = new HashSet<>(input.length);
    for (Set<?> set : input) {
        setOfSets.add(set);
    }
}
 
Example #17
Source File: PngReaderTest.java    From JQF with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Fuzz
public void debugKaitai(@From(PngKaitaiGenerator.class) @Size(max = 256) InputStream input)  {
    try (FileOutputStream out = new FileOutputStream("kaitai.png")) {
        int val;
        while ((val = input.read()) != -1) {
            out.write(val);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example #18
Source File: PngReaderTest.java    From JQF with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Fuzz
public void fuzzValidMetadata(@From(PngKaitaiGenerator.class) @Size(max = 256) InputStream input)  {
    // Decode image from input stream
    try {
        reader.setInput(ImageIO.createImageInputStream(input));
        reader.getImageMetadata(0);
    } catch (IOException e) {
        Assume.assumeNoException(e);
    }

}
 
Example #19
Source File: VertxVaadinRequestUT.java    From vertx-vaadin with MIT License 5 votes vote down vote up
@Property(trials = TRIALS)
public void shouldDelegateGetHeader(@From(RandomStringGenerator.class) String name,
                                    @From(RandomStringGenerator.class) String value) {
    when(httpServerRequest.getHeader(name)).thenReturn(value);
    assertThat(vaadinRequest.getHeader(name)).isEqualTo(value);
    assertThat(vaadinRequest.getHeader(name + "notExist")).isNull();
}
 
Example #20
Source File: PngReaderTest.java    From JQF with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Fuzz
public void fuzzValidImage(@From(PngKaitaiGenerator.class) @Size(max = 2048) InputStream input)  {
    // Decode image from input stream
    try {
        reader.setInput(ImageIO.createImageInputStream(input));
        reader.getImageMetadata(0);
        Assume.assumeTrue(reader.getHeight(0) < 1024);
        Assume.assumeTrue(reader.getWidth(0)  < 1024);
    } catch (IOException e) {
        Assume.assumeNoException(e);
    }

}
 
Example #21
Source File: RedBlackBSTTest.java    From JQF with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Fuzz
public void testGen( @InRange(minInt=5, maxInt = 64) @From(RedBlackBSTGenerator.class)
                              RedBlackBST<Integer, Integer> tree) {
    Assume.assumeTrue(tree.check());
    tree.min();
    tree.max();
    tree.rank(tree.floor(17));
    tree.rank(tree.ceiling(17));
    tree.put(17, 17);
    tree.get(17);
}
 
Example #22
Source File: ParserTest.java    From JQF with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Fuzz
public void testWithGenerator(@From(JavaClassGenerator.class) JavaClass javaClass) throws IOException {

    try {
        // Dump the javaclass to a byte stream and get an input pipe
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        javaClass.dump(out);

        ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
        testWithInputStream(in);
    } catch (ClassFormatException e) {
        throw e;
    }
}
 
Example #23
Source File: TikaParserTest.java    From JQF with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Fuzz
public void fuzz(@From(InputStreamGenerator.class) InputStream in) throws IOException {
    Tika tika = new Tika();
    try(Reader reader = tika.parse(in)) {
        char[] buf = new char[1024];
        while (reader.read(buf) != -1); // Keep reading until EOF
    }

}
 
Example #24
Source File: RobustnessTest.java    From JQF with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Fuzz
public void debugTwo(@From(AsciiStringGenerator.class) String s1, @From(AsciiStringGenerator.class) String s2) {
    System.out.print(s2.length() + ": ");
    System.out.println(s2);
    System.out.print(s1.length() + ": ");
    System.out.println(s1);
}
 
Example #25
Source File: KarumiHQsProperties.java    From MaxibonKataJava with Apache License 2.0 5 votes vote down vote up
@Property public void ifThereAreLessThanTwoMaxibonLeft10MaxibonsAreAutomaticallyBought(
    @From(HungryDevelopersGenerator.class) Developer developer) {
  int initialMaxibons = karumiHQs.getMaxibonsLeft();
  karumiHQs.openFridge(developer);

  int expectedMaxibons =
      getMaxibonsAfterOpeningTheFridge(initialMaxibons, developer.getNumberOfMaxibonsToGrab());
  assertEquals(expectedMaxibons, karumiHQs.getMaxibonsLeft());
}
 
Example #26
Source File: KarumiHQsProperties.java    From MaxibonKataJava with Apache License 2.0 5 votes vote down vote up
@Property public void ifThereAreMoreThanTwoMaxibonsLeftNoMessagesAreSentOrderingMore(
    @From(NotSoHungryDevelopersGenerator.class) Developer developer) {
  karumiHQs.openFridge(developer);

  verify(chat, never()).sendMessage(
      "Hi guys, I'm " + developer.getName() + ". We need more maxibons!");
}
 
Example #27
Source File: KarumiHQsProperties.java    From MaxibonKataJava with Apache License 2.0 5 votes vote down vote up
@Property public void ifSomeKarumiesGoToTheKitchenTheNumberOfMaxibonsShouldBeTheExpectedOne(
    List<@From(KarumiesGenerator.class) Developer> developers) {
  int initialMaxibons = karumiHQs.getMaxibonsLeft();
  karumiHQs.openFridge(developers);

  int expectedMaxibons = calculateMaxibonsLeft(initialMaxibons, developers);
  assertEquals(expectedMaxibons, karumiHQs.getMaxibonsLeft());
}
 
Example #28
Source File: BeamDDLNestedTypesTest.java    From beam with Apache License 2.0 5 votes vote down vote up
@Property
public void supportsNestedTypes(@From(AnyFieldType.class) FieldType generatedFieldType)
    throws SqlParseException {
  String fieldTypeDeclaration = unparse(generatedFieldType);

  Table table = executeCreateTableWith(fieldTypeDeclaration);

  Schema expectedSchema = newSimpleSchemaWith(generatedFieldType);

  assertEquals(expectedSchema, table.getSchema());
}
 
Example #29
Source File: BeamDDLNestedTypesTest.java    From beam with Apache License 2.0 5 votes vote down vote up
@Property
public void supportsPrimitiveTypes(@From(PrimitiveTypes.class) FieldType fieldType)
    throws SqlParseException {
  String fieldTypeDeclaration = unparse(fieldType);

  Table table = executeCreateTableWith(fieldTypeDeclaration);

  Schema expectedSchema = newSimpleSchemaWith(fieldType);

  assertEquals(expectedSchema, table.getSchema());
}
 
Example #30
Source File: AvroUtilsTest.java    From beam with Apache License 2.0 5 votes vote down vote up
@Property(trials = 1000)
@SuppressWarnings("unchecked")
public void supportsAnyAvroSchema(
    @From(RecordSchemaGenerator.class) org.apache.avro.Schema avroSchema) {
  // not everything is possible to translate
  assumeThat(avroSchema, not(containsField(AvroUtilsTest::hasNonNullUnion)));

  Schema schema = AvroUtils.toBeamSchema(avroSchema);
  Iterable iterable = new RandomData(avroSchema, 10);
  List<GenericRecord> records = Lists.newArrayList((Iterable<GenericRecord>) iterable);

  for (GenericRecord record : records) {
    AvroUtils.toBeamRowStrict(record, schema);
  }
}