Java Code Examples for org.junit.jupiter.api.Test

The following are top voted examples for showing how to use org.junit.jupiter.api.Test. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: EvoMaster   File: HeuristicsForJumpsTest.java   Source Code and License 6 votes vote down vote up
@Test
public void test_IF_ACMPNE(){
    // x != y

    Object x = "a";
    Object[] values = new Object[]{new Object(), x, "foo", 5};
    for(Object val: values){

        Truthness eq = getForObjectComparison(x, val, Opcodes.IF_ACMPEQ);
        Truthness ne = getForObjectComparison(x, val, Opcodes.IF_ACMPNE);

        //should be inverted
        assertEquals(eq.getOfTrue(), ne.getOfFalse(), 0.001);
        assertEquals(eq.getOfFalse(), ne.getOfTrue(), 0.001);
    }
}
 
Example 2
Project: incubator-plc4x   File: IsoTPProtocolTest.java   Source Code and License 6 votes vote down vote up
@Test
@Tag("fast")
public void encodeDisconnectionConfirm() throws Exception {
    ChannelHandlerContext ctx = new MockChannelHandlerContext();
    ByteBuf buf = Unpooled.buffer();
    DisconnectConfirmTpdu tpdu = new DisconnectConfirmTpdu((short)0x1, (short)(0x2), Collections.emptyList(), buf);
    ArrayList<Object> out = new ArrayList<>();

    isoTPProtocol.encode(ctx, tpdu, out);

    assertTrue(out.size() == 1, "Message not decoded");

    ByteBuf userData = ((IsoOnTcpMessage)out.get(0)).getUserData();

    assertTrue(userData.writerIndex() == 6, "Incorrect message length");
    assertTrue(userData.readByte() == (byte)0x5, "Incorrect header length");
    assertTrue(userData.readByte() == TpduCode.DISCONNECT_CONFIRM.getCode(), "Incorrect Tpdu code");
    assertTrue(userData.readShort() == (short)0x1, "Incorrect destination reference code");
    assertTrue(userData.readShort() == (short)0x2, "Incorrect source reference code");
}
 
Example 3
Project: trellis   File: PutHandlerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testRdfToNonRDFSource() {
    when(mockResource.getInteractionModel()).thenReturn(LDP.NonRDFSource);
    when(mockLdpRequest.getContentType()).thenReturn(TEXT_TURTLE);
    when(mockLdpRequest.getLink()).thenReturn(fromUri(LDP.NonRDFSource.getIRIString()).rel("type").build());

    final File entity = new File(getClass().getResource("/simpleTriple.ttl").getFile());
    final PutHandler putHandler = new PutHandler(mockLdpRequest, entity, mockResourceService,
            mockIoService, mockBinaryService, null);

    final Response res = putHandler.setResource(mockResource).build();
    assertEquals(NO_CONTENT, res.getStatusInfo());
    assertTrue(res.getLinks().stream().anyMatch(hasType(LDP.Resource)));
    assertFalse(res.getLinks().stream().anyMatch(hasType(LDP.RDFSource)));
    assertFalse(res.getLinks().stream().anyMatch(hasType(LDP.Container)));
    assertTrue(res.getLinks().stream().anyMatch(hasType(LDP.NonRDFSource)));
}
 
Example 4
Project: trellis-rosid   File: FileResourceServiceTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testPurge() throws Exception {
    final String myPartition = new File(getClass().getResource("/purgeable").toURI()).getAbsolutePath();
    service = new FileResourceService(myPartition, baseUrl, curator, mockProducer, mockEventService,
            mockIdSupplier, false);
    assertTrue(service.get(identifier).isPresent());
    final List<IRI> binaries = service.purge(identifier).collect(toList());
    assertEquals(1L, binaries.size());
    assertEquals(rdf.createIRI("s3://bucket/some-resource"), binaries.get(0));

    assertFalse(service.get(identifier).isPresent());

    assertTrue(service.get(testResource).isPresent());
    assertEquals(0L, service.purge(testResource).count());
    assertFalse(service.get(testResource).isPresent());
}
 
Example 5
Project: qpp-conversion-tool   File: QualityMeasureIdValidatorTest.java   Source Code and License 6 votes vote down vote up
@Test
void testInvalidMeasureId() {
	Node measureReferenceResultsNode = new MeasureReferenceBuilder()
			.addMeasureId("InvalidMeasureId")
			.addSubPopulationMeasureDataWithCounts(SubPopulations.IPOP, REQUIRES_DENOM_EXCLUSION_IPOP_GUID, ONE_HUNDRED)
			.addSubPopulationMeasureDataWithCounts(SubPopulations.DENOM, REQUIRES_DENOM_EXCLUSION_DENOM_GUID, ONE_HUNDRED)
			.addSubPopulationMeasureDataWithCounts(SubPopulations.NUMER, REQUIRES_DENOM_EXCLUSION_NUMER_GUID, ONE_HUNDRED)
			.addSubPopulationMeasureDataWithCounts(SubPopulations.DENEX, REQUIRES_DENOM_EXCLUSION_DENEX_GUID, ONE_HUNDRED)
			.build();

	Set<Detail> details = objectUnderTest.validateSingleNode(measureReferenceResultsNode);

	assertWithMessage("There must be one validation errors.")
			.that(details).comparingElementsUsing(DetailsErrorEquals.INSTANCE)
			.containsExactly(ErrorCode.MEASURE_GUID_MISSING);
}
 
Example 6
Project: qpp-conversion-tool   File: AciNumeratorDenominatorEncoderTest.java   Source Code and License 6 votes vote down vote up
@Test
void testNoChildEncoder() throws EncodeException {
	JsonWrapper jsonWrapper = new JsonWrapper();
	AciNumeratorDenominatorEncoder objectUnderTest = new AciNumeratorDenominatorEncoder(new Context());
	Node unknownNode = new Node();
	aciProportionMeasureNode.addChildNode(unknownNode);

	//execute
	objectUnderTest.internalEncode(jsonWrapper, aciProportionMeasureNode);

	//assert
	assertThat(objectUnderTest.getDetails())
			.hasSize(1);
	assertWithMessage("The validation error must be the inability to find an encoder")
			.that(objectUnderTest.getDetails().get(0).getMessage())
			.isEqualTo("Failed to find an encoder");
}
 
Example 7
Project: trellis-rosid-file   File: FileResourceServiceTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testResourcePast() {
    final Instant time = parse("2017-02-15T11:00:00Z");
    final Resource res = service.get(identifier, time).get();
    assertEquals(identifier, res.getIdentifier());
    assertEquals(LDP.Container, res.getInteractionModel());
    assertFalse(res.getMembershipResource().isPresent());
    assertFalse(res.getMemberRelation().isPresent());
    assertFalse(res.getMemberOfRelation().isPresent());
    assertFalse(res.getInsertedContentRelation().isPresent());
    assertFalse(res.getBinary().isPresent());
    assertTrue(res.isMemento());
    assertFalse(res.getInbox().isPresent());
    assertEquals(parse("2017-02-15T10:05:00Z"), res.getModified());
    assertEquals(0L, res.getTypes().size());
    assertEquals(0L, res.stream().filter(TestUtils.isContainment.or(TestUtils.isMembership)).count());

    final List<Triple> triples = res.stream().filter(TestUtils.isUserManaged)
        .map(Quad::asTriple).collect(toList());
    assertEquals(0L, triples.size());

    final List<VersionRange> mementos = res.getMementos();
    assertEquals(1L, mementos.size());
    assertEquals(parse("2017-02-15T10:05:00Z"), mementos.get(0).getFrom());
    assertEquals(parse("2017-02-15T11:15:00Z"), mementos.get(0).getUntil());
}
 
Example 8
Project: traute   File: MethodParameterTest.java   Source Code and License 6 votes vote down vote up
@Test
public void constructor_super() {
    String testSource = String.format(
            "package %s;\n" +
            "\n" +
            "import %s;\n" +
            "\n" +
            "public class %s {\n" +
            "\n" +
            "  public %s(@NotNull Integer intParam) {\n" +
            "    super();\n" +
            "  }\n" +
            "\n" +
            "  public static void main(String[] args) {\n" +
            "    new %s(null);\n" +
            "  }\n" +
            "}", PACKAGE, NotNull.class.getName(), CLASS_NAME, CLASS_NAME, CLASS_NAME);
    expectNpeFromParameterCheck(testSource, "intParam", expectRunResult);
    doTest(testSource);
}
 
Example 9
Project: dragoman   File: DatasetResourceTest.java   Source Code and License 6 votes vote down vote up
@Test
public void canHandleFailureWhenGettingADatasetSample() {
  Dataset dataset = aPersistedDataset();

  when(datasetDao.get(dataset.getId())).thenReturn(dataset);

  Throwable exception = new RuntimeException("boom!");
  when(reader.read(dataset, "", "", "", 10)).thenReturn(Observable.error(exception));

  String endpoint = "dataset/" + dataset.getId() + "/sample";
  HttpResponse response = read(endpoint);
  assertThat(response.getStatusCode(), is(INTERNAL_SERVER_ERROR.code()));
  assertThat(response.getStatusMessage(), is(INTERNAL_SERVER_ERROR.reasonPhrase()));

  assertThatErrorResponseIsCorrect(
      response.getPayload(), exception.getMessage(), endpoint, INTERNAL_SERVER_ERROR);
}
 
Example 10
Project: qpp-conversion-tool   File: EncoderNegativeConditionsTest.java   Source Code and License 6 votes vote down vote up
@Test
void testExceptionAddsValidation() throws EncodeException {
	Node numeratorDenominatorNode;
	List<Node> nodes;

	numeratorDenominatorNode = new Node(TemplateId.ACI_AGGREGATE_COUNT);
	numeratorDenominatorNode.putValue("aggregateCount", "600");

	nodes = new ArrayList<>();
	nodes.add(numeratorDenominatorNode);

	QppOutputEncoder encoder = new QppOutputEncoder(new Context());

	encoder.setNodes(nodes);

	FailingWriter failWrite = new FailingWriter();

	encoder.encode(new BufferedWriter(failWrite));

	assertThat(encoder.getDetails()).hasSize(1);
	assertThat(encoder.getDetails().get(0).getMessage())
			.isEqualTo("Fake IOException");
}
 
Example 11
Project: trellis-rosid-file   File: FileUtilsTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testPartition3() {
    assertEquals(join(separator, "2a", "79", "8c", "70a37cae7da1c312e0d052297e9921aa"),
            FileUtils.partition("trellis:repository/other"));
    assertEquals(join(separator, "2a", "79", "8c", "70a37cae7da1c312e0d052297e9921aa"),
            FileUtils.partition(rdf.createIRI("trellis:repository/other")));
}
 
Example 12
Project: trellis-webac   File: AuthorizationTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testGraph() {
    final Authorization auth = Authorization.from(subject, graph);

    assertEquals(subject, auth.getIdentifier());

    assertEquals(2, auth.getAgent().size());
    assertTrue(auth.getAgent().contains(rdf.createIRI("info:agent/foo")));
    assertTrue(auth.getAgent().contains(rdf.createIRI("info:agent/bar")));

    assertEquals(1, auth.getAgentClass().size());
    assertTrue(auth.getAgentClass().contains(rdf.createIRI("info:agent/SomeClass")));

    assertEquals(4, auth.getAgentGroup().size());
    assertTrue(auth.getAgentGroup().contains(rdf.createIRI("info:group/group1")));

    assertEquals(1, auth.getMode().size());
    assertTrue(auth.getMode().contains(ACL.Read));

    assertEquals(3, auth.getAccessTo().size());
    assertTrue(auth.getAccessTo().contains(rdf.createIRI("trellis:repository/resource2")));
    assertTrue(auth.getAccessTo().contains(rdf.createIRI("trellis:repository/resource3")));
    assertTrue(auth.getAccessTo().contains(rdf.createIRI("trellis:repository/resource4")));

    assertEquals(1, auth.getDefault().size());
    assertTrue(auth.getDefault().contains(rdf.createIRI("trellis:repository/container")));
}
 
Example 13
Project: incubator-plc4x   File: APIMessageTests.java   Source Code and License 5 votes vote down vote up
@Test
@Tag("fast")
void plcWriteRequestItem() {
    MockAddress address = new MockAddress("mock:/DATA");
    WriteRequestItem writeRequestItem = new WriteRequestItem(Byte.class, address, (byte) 0x45);

    assertTrue(writeRequestItem.getAddress().equals(address), "Unexpected address");
    assertTrue(writeRequestItem.getDatatype() == Byte.class, "Unexpected data type");
    assertTrue((Byte) writeRequestItem.getValues()[0] == 0x45, "Unexpected value");
}
 
Example 14
Project: trellis   File: LdpForbiddenResourceTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testPut1() {
    final Response res = target("repo1/resource").queryParam("ext", "acl").request()
        .put(entity("<> <http://purl.org/dc/terms/title> \"A title\" . ", APPLICATION_N_TRIPLES_TYPE));

    assertEquals(FORBIDDEN, res.getStatusInfo());
}
 
Example 15
Project: fuse-nio-adapter   File: FileAttributesUtilTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testBasicFileAttributesToFileStat() {
	Instant instant = Instant.ofEpochSecond(424242l, 42);
	FileTime ftime = FileTime.from(instant);
	BasicFileAttributes attr = Mockito.mock(BasicFileAttributes.class);
	Mockito.when(attr.isDirectory()).thenReturn(true);
	Mockito.when(attr.lastModifiedTime()).thenReturn(ftime);
	Mockito.when(attr.creationTime()).thenReturn(ftime);
	Mockito.when(attr.lastAccessTime()).thenReturn(ftime);
	Mockito.when(attr.size()).thenReturn(42l);

	FileAttributesUtil util = new FileAttributesUtil();
	FileStat stat = util.basicFileAttributesToFileStat(attr);

	Assertions.assertTrue((FileStat.S_IFDIR & stat.st_mode.intValue()) == FileStat.S_IFDIR);
	Assertions.assertEquals(424242l, stat.st_mtim.tv_sec.get());
	Assertions.assertEquals(42, stat.st_mtim.tv_nsec.intValue());
	Assertions.assertEquals(424242l, stat.st_ctim.tv_sec.get());
	Assertions.assertEquals(42, stat.st_ctim.tv_nsec.intValue());
	Assumptions.assumingThat(Platform.IS_MAC || Platform.IS_WINDOWS, () -> {
		Assertions.assertEquals(424242l, stat.st_birthtime.tv_sec.get());
		Assertions.assertEquals(42, stat.st_birthtime.tv_nsec.intValue());
	});
	Assertions.assertEquals(424242l, stat.st_atim.tv_sec.get());
	Assertions.assertEquals(42, stat.st_atim.tv_nsec.intValue());
	Assertions.assertEquals(42l, stat.st_size.longValue());
}
 
Example 16
Project: hygene   File: MenuControllerTest.java   Source Code and License 5 votes vote down vote up
@Test
void testGfaFileOpenerCancel() throws Exception {
    final GraphStore graphStore = mock(GraphStore.class);
    final FileChooser fileChooser = mock(FileChooser.class);

    menuController.setGfaFileChooser(fileChooser);
    menuController.setGraphStore(graphStore);
    menuController.openGfaFileAction(mock(ActionEvent.class));

    verify(graphStore, never()).loadGfaFile(any(File.class), any(ProgressUpdater.class));
}
 
Example 17
Project: trellis-rosid   File: JwtAuthenticatorTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testAuthenticateTokenIssSub() throws AuthenticationException {
    final String key = "secret";
    final String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhY29idXJuIiwibmFtZSI6IkFhcm9" +
        "uIENvYnVybiIsImlzcyI6Imh0dHA6Ly9leGFtcGxlLm9yZy8ifQ.DPb_i9vfI5um2X_g_df2y1uFktThGdDBo-Q7AMqjaWc";

    final Authenticator<String, Principal> authenticator = new JwtAuthenticator(key, false);

    final Optional<Principal> result = authenticator.authenticate(token);
    assertTrue(result.isPresent());
    result.ifPresent(p -> {
        assertEquals("http://example.org/acoburn", p.getName());
    });
}
 
Example 18
Project: incubator-plc4x   File: S7AddressTests.java   Source Code and License 5 votes vote down vote up
@Test
@Tag("fast")
void testS7Address() {
    MemoryArea memoryArea = MemoryArea.DATA_BLOCKS;
    S7Address s7Address = new S7Address(memoryArea, (short) 0x100);

    assertTrue(s7Address.getMemoryArea() == MemoryArea.DATA_BLOCKS, "Wrong memory area");
    assertTrue( s7Address.getByteOffset() == 0x100, "Memory area byte offset incorrect");
}
 
Example 19
Project: base62   File: Base62Test.java   Source Code and License 5 votes vote down vote up
@Test
@DisplayName("should behave correctly on naive test set")
public void naiveTestSet() {
    for (Map.Entry<String, String> testSetEntry : Environment.getNaiveTestSet().entrySet()) {
        assertEquals(encode(testSetEntry.getKey()), testSetEntry.getValue());
    }
}
 
Example 20
Project: qpp-conversion-tool   File: ExceptionHandlerControllerV1Test.java   Source Code and License 5 votes vote down vote up
@Test
void testTransformExceptionBody() {
	TransformException exception =
			new TransformException("test transform exception", new NullPointerException(), report);

	ResponseEntity<AllErrors> responseEntity = objectUnderTest.handleTransformException(exception);
	assertThat(responseEntity.getBody()).isEqualTo(allErrors);
}
 
Example 21
Project: paper   File: BooleanRuleTest.java   Source Code and License 5 votes vote down vote up
@Test
public void isValid() throws Exception {
    assertTrue(this.subject.isValid("Yes"));
    assertTrue(this.subject.isValid("No"));
    assertFalse(this.subject.isValid("Y"));
    assertFalse(this.subject.isValid("N"));
}
 
Example 22
Project: trellis   File: WebACServiceTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testCanWrite1() {
    when(mockSession.getAgent()).thenReturn(acoburnIRI);
    assertFalse(testService.getAccessModes(nonexistentIRI, mockSession).contains(ACL.Write));
    assertFalse(testService.getAccessModes(resourceIRI, mockSession).contains(ACL.Write));
    assertFalse(testService.getAccessModes(childIRI, mockSession).contains(ACL.Write));
    assertFalse(testService.getAccessModes(parentIRI, mockSession).contains(ACL.Write));
    assertFalse(testService.getAccessModes(rootIRI, mockSession).contains(ACL.Write));
}
 
Example 23
Project: xml-namespace-context   File: GetNamespaceTest.java   Source Code and License 5 votes vote down vote up
@Test
void givenDefaultByMapGetNamespaceURIShouldReturnDefaultNSForEmptyPrefix() {

	Map<String, String> map = new HashMap<>();
	map.put(DEFAULT_NS_PREFIX, EXAMPLE_NS);

	context= new HashMapNamespaceContext(map);
	assertEquals(EXAMPLE_NS,context.getNamespaceURI(DEFAULT_NS_PREFIX));
}
 
Example 24
Project: trellis   File: PatchHandlerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testConflict() {
    when(mockRequest.evaluatePreconditions(any(Date.class), any(EntityTag.class)))
        .thenReturn(status(CONFLICT));
    when(mockLdpRequest.getPath()).thenReturn("resource");

    final PatchHandler patchHandler = new PatchHandler(mockLdpRequest, insert,
            mockResourceService, mockIoService, null);

    assertThrows(WebApplicationException.class, () -> patchHandler.updateResource(mockResource));
}
 
Example 25
Project: postmark-java   File: BounceTest.java   Source Code and License 5 votes vote down vote up
@Test
void bounceList() throws PostmarkException, IOException {
    Bounces bounces = client.getBounces(Parameters.init().build("count", 5).build("offset", 0));

    assertTrue(bounces.getTotalCount() > 0);
    assertNotNull(bounces.getBounces().get(0).getBouncedAt());
}
 
Example 26
Project: hygene   File: GraphIteratorTest.java   Source Code and License 5 votes vote down vote up
/**
 * Tests that the depth component of the BiConsumer is correct for the given graph.
 */
@Test
void testVisitAllWithinRangeDepthRandom() {
    createGraph(9);
    addEdges(new int[][] {
            {0, 1}, {1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 5}, {3, 5},
            {4, 5}, {4, 6}, {4, 7}, {5, 6}, {5, 8}, {6, 7}, {6, 8}});

    final int[] depths = new int[9];
    new GraphIterator(getGraph()).visitAllWithinRange(SequenceDirection.RIGHT, 99,
            (depth, node) -> depths[node] = depth);

    assertThat(depths).containsExactly(0, 1, 2, 2, 2, 3, 3, 3, 4);
}
 
Example 27
Project: ocraft-s2client   File: ResponseLeaveGameTest.java   Source Code and License 5 votes vote down vote up
@Test
void throwsExceptionWhenSc2ApiResponseDoesNotHaveLeaveGame() {
    assertThatExceptionOfType(IllegalArgumentException.class)
            .isThrownBy(() -> ResponseLeaveGame.from(nothing()))
            .withMessage("provided argument doesn't have leave game response");

    assertThatExceptionOfType(IllegalArgumentException.class)
            .isThrownBy(() -> ResponseLeaveGame.from(aSc2ApiResponse().build()))
            .withMessage("provided argument doesn't have leave game response");
}
 
Example 28
Project: ocraft-s2client   File: ActionSpatialTest.java   Source Code and License 5 votes vote down vote up
@Test
void serializesToSc2ApiActionSpatialWithCameraMove() {
    Spatial.ActionSpatial sc2ApiActionSpatial = ActionSpatial.of(
            cameraMove().to(PointI.of(1, 1)).build()
    ).toSc2Api();

    assertThat(sc2ApiActionSpatial.hasUnitCommand()).as("sc2api action spatial: case of action is unit command")
            .isFalse();
    assertThat(sc2ApiActionSpatial.hasCameraMove()).as("sc2api action spatial: case of action is camera move")
            .isTrue();
    assertThat(sc2ApiActionSpatial.hasUnitSelectionPoint())
            .as("sc2api action spatial: case of action is unit selection point").isFalse();
    assertThat(sc2ApiActionSpatial.hasUnitSelectionRect())
            .as("sc2api action spatial: case of action is unit selection rect").isFalse();
}
 
Example 29
Project: incubator-plc4x   File: S7TypeTests.java   Source Code and License 5 votes vote down vote up
@Test
@Tag("fast")
void unknownMemoryAccess() {
    MemoryArea memoryArea = MemoryArea.DATA_BLOCKS;

    assertTrue(MemoryArea.valueOf((byte)0xFF) == null, "Unexpected value mapped");
 }
 
Example 30
Project: trellis   File: AbstractLdpResourceTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testPutConstraint() {
    final Response res = target(RESOURCE_PATH).request()
        .put(entity("<> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> \"Some literal\" .",
                TEXT_TURTLE_TYPE));

    assertEquals(CONFLICT, res.getStatusInfo());
    assertTrue(res.getLinks().stream()
            .anyMatch(hasLink(Trellis.InvalidRange, LDP.constrainedBy.getIRIString())));
}
 
Example 31
Project: trellis-api   File: ResourceServiceTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testSkolemization() {
    final BlankNode bnode = rdf.createBlankNode("testing");
    final IRI iri = rdf.createIRI("trellis:bnode/testing");
    final IRI resource = rdf.createIRI("trellis:repository/resource");

    assertTrue(mockResourceService.skolemize(bnode) instanceof IRI);
    assertTrue(((IRI) mockResourceService.skolemize(bnode)).getIRIString().startsWith("trellis:bnode/"));
    assertTrue(mockResourceService.unskolemize(iri) instanceof BlankNode);
    assertEquals(mockResourceService.unskolemize(iri), mockResourceService.unskolemize(iri));

    assertFalse(mockResourceService.unskolemize(rdf.createLiteral("Test")) instanceof BlankNode);
    assertFalse(mockResourceService.unskolemize(resource) instanceof BlankNode);
    assertFalse(mockResourceService.skolemize(rdf.createLiteral("Test2")) instanceof IRI);
}
 
Example 32
Project: shuffleboard   File: PreferencesUtilsTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testSaveDouble() {
  // given
  String name = "double";
  double value = Double.MAX_VALUE;
  DoubleProperty property = new SimpleDoubleProperty(null, name, value);

  // when
  PreferencesUtils.save(property, preferences);

  // then
  double saved = preferences.getDouble(name, -1);
  assertEquals(value, saved);
}
 
Example 33
Project: hygene   File: ThrottledDefaultExecutorTest.java   Source Code and License 5 votes vote down vote up
@Test
void testRunDefaultTwice() {
    final int[] number = {0};

    final ThrottledDefaultExecutor executor = new ThrottledDefaultExecutor(0, () -> number[0]++);

    executor.run();
    executor.run();
    executor.block();

    assertThat(number[0]).isEqualTo(1);
}
 
Example 34
Project: qpp-conversion-tool   File: ValidationServiceImplTest.java   Source Code and License 5 votes vote down vote up
@Test
void testValidationPass() {
	String validationUrl = "https://qpp.net/validate";

	when(environment.getProperty(eq(Constants.VALIDATION_URL_ENV_VARIABLE))).thenReturn(validationUrl);
	ResponseEntity<String> spiedResponseEntity = spy(new ResponseEntity<>(HttpStatus.OK));
	when(restTemplate.postForEntity(eq(validationUrl), any(HttpEntity.class), eq(String.class))).thenReturn(spiedResponseEntity);

	objectUnderTest.validateQpp(converter.getReport());

	verify(spiedResponseEntity, never()).getBody();
}
 
Example 35
Project: EvoMaster   File: HeuristicsForJumpsTest.java   Source Code and License 5 votes vote down vote up
@Test
public void test_IFNONNULL(){
    // x != null

    Object[] values = new Object[]{null, new Object(), "foo", 5};
    for(Object val: values){

        Truthness nn = getForNullComparison(val, Opcodes.IFNONNULL);
        Truthness nu = getForNullComparison(val, Opcodes.IFNULL);

        //should be inverted
        assertEquals(nn.getOfFalse(), nu.getOfTrue(), 0.001);
        assertEquals(nn.getOfTrue(), nu.getOfFalse(), 0.001);
    }
}
 
Example 36
Project: traute   File: MethodReturnTest.java   Source Code and License 5 votes vote down vote up
@Test
public void else_withoutBracesSameLine() {
    doMethodReturnTest(
            "" +
            "if (false) {\n" +
            "  return 1;\n" +
            "} else return count();"
    );
}
 
Example 37
Project: incubator-plc4x   File: APIMessageTests.java   Source Code and License 5 votes vote down vote up
@Test
@Tag("fast")
void plcReadRequestAddress() {
    MockAddress address = new MockAddress("mock:/DATA");
    PlcReadRequest plcReadRequest = new PlcReadRequest(Byte.class, address);
    assertTrue(plcReadRequest.getReadRequestItems().size() == 1, "Expected one request item");
    assertTrue(plcReadRequest.getNumItems() == 1, "Expected one request item");
}
 
Example 38
Project: hygene   File: NodeMetadataCacheTest.java   Source Code and License 5 votes vote down vote up
@Test
void testMergeConstructorMultipleElementsWithDuplicates() {
    final List<NodeMetadata> metadataList = new ArrayList<>();
    final NodeMetadata metadataA = new NodeMetadata("nameA", "sequenceA", Arrays.asList("genA", "genB"));
    final NodeMetadata metadataB = new NodeMetadata("nameB", "sequenceB", Arrays.asList("genB", "genC"));
    metadataList.add(metadataA);
    metadataList.add(metadataB);

    final NodeMetadata mergedMetadata = new NodeMetadata(metadataList);

    assertThat(mergedMetadata.getName()).isEqualTo("[nameA, nameB]");
    assertThat(mergedMetadata.getSequence()).isEqualTo("[sequenceA, sequenceB]");
    assertThat(mergedMetadata.getGenomes()).containsExactly("genA", "genB", "genC");
}
 
Example 39
Project: convert-junit4-to-junit5   File: JunitConversionLogicTest.java   Source Code and License 5 votes vote down vote up
@Test
void specificStaticFail() {
	String originalImport = "import org.junit.Assert;";
	String originalMethod = "Assert.fail(a);";
	String expectedImport = "import org.junit.jupiter.api.Assertions;";
	String expectedMethod = "Assertions.fail(a);";
	assertAfterWrappingInMethod(originalImport, originalMethod, expectedImport, expectedMethod);
}
 
Example 40
Project: Nukkit-Java9   File: VarIntTest.java   Source Code and License 5 votes vote down vote up
@DisplayName("Reading")
@Test
void testRead() {
	assertAll(
			() -> assertEquals(2412, VarInt.readUnsignedVarInt(wrapBinaryStream("EC123EC456"))),
			() -> assertEquals(583868, VarInt.readUnsignedVarInt(wrapBinaryStream("BCD123EFA0"))),
			() -> assertEquals(1206, VarInt.readVarInt(wrapBinaryStream("EC123EC456"))),
			() -> assertEquals(291934, VarInt.readVarInt(wrapBinaryStream("BCD123EFA0"))),
			() -> assertEquals(6015, VarInt.readUnsignedVarLong(wrapBinaryStream("FF2EC456EC789EC012EC"))),
			() -> assertEquals(3694, VarInt.readUnsignedVarLong(wrapBinaryStream("EE1CD34BCD56BCD78BCD"))),
			() -> assertEquals(-3008, VarInt.readVarLong(wrapBinaryStream("FF2EC456EC789EC012EC"))),
			() -> assertEquals(1847, VarInt.readVarLong(wrapBinaryStream("EE1CD34BCD56BCD78BCD")))
	);
}
 
Example 41
Project: trellis-rosid   File: ResourceWriterTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testCacheWriter0() throws IOException {
    final Instant time = parse("2017-03-15T01:23:45Z");
    assertFalse(CachedResource.write(null, identifier, time));
    assertFalse(CachedResource.write(null, identifier.getIRIString(), time));
    assertFalse(CachedResource.write(null, identifier.getIRIString()));
}
 
Example 42
Project: traute   File: MethodReturnTest.java   Source Code and License 5 votes vote down vote up
@Test
public void noDoubleEvaluation() {
    String testSource = String.format(
            "package %s;\n" +
            "\n" +
            "public class %s {\n" +
            "\n" +
            "  static int counter;\n" +
            "\n" +
            "  @%s\n" +
            "  public Integer test() {\n" +
            "    return count();\n" +
            "  }\n" +
            "\n" +
            "  private Integer count() {\n" +
            "      counter++;\n" +
            "      return null;\n" +
            "  }\n" +
            "\n" +
            "  public static void main(String[] args) {\n" +
            "    try {\n" +
            "      new Test().test();\n" +
            "    } catch (NullPointerException e) {\n" +
            "      throw new IllegalStateException(String.valueOf(counter));\n" +
            "    }\n" +
            "  }\n" +
            "}", PACKAGE, CLASS_NAME, NotNull.class.getName());
    expectRunResult.withExceptionClass(IllegalStateException.class)
                   .withExceptionMessage("1");
    doTest(testSource);
}
 
Example 43
Project: EvoMaster   File: BranchesInstrumentedTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testNegX(){

    int res = evalNeg(-10, 0);
    //first branch should had been taken
    assertEquals(3, res);

    //so far, seen only first "if", of which the else is not covered
    assertEquals(2, ExecutionTracer.getNumberOfObjectives(ObjectiveNaming.BRANCH));
    assertEquals(1, ExecutionTracer.getNumberOfNonCoveredObjectives(ObjectiveNaming.BRANCH));

    String elseBranch = ExecutionTracer.getNonCoveredObjectives(ObjectiveNaming.BRANCH).iterator().next();
    assertTrue(elseBranch.contains(ObjectiveNaming.FALSE_BRANCH));
    assertFalse(elseBranch.contains(ObjectiveNaming.TRUE_BRANCH));

    double first = ExecutionTracer.getValue(elseBranch);
    assertTrue(first < 1d); // not covered


    evalNeg(-15, 0); //worse value, should have no impact
    double second = ExecutionTracer.getValue(elseBranch);
    assertTrue(second < 1d); // still not covered
    assertEquals(first, second, 0.001);

    evalNeg(-8, 0); //better value
    double third = ExecutionTracer.getValue(elseBranch);
    assertTrue(third < 1d); // still not covered
    assertTrue(third > first);
}
 
Example 44
Project: incubator-plc4x   File: APIMessageTests.java   Source Code and License 5 votes vote down vote up
@Test
@Tag("fast")
void plcWriteResponse() {
    PlcWriteRequest plcWriteRequest = new PlcWriteRequest();
    ArrayList<WriteResponseItem> responseItems  = new ArrayList<>();
    MockAddress address = new MockAddress("mock:/DATA");
    WriteRequestItem writeRequestItem = new WriteRequestItem(Byte.class, address, 1);
    WriteResponseItem writeResponseItem = new WriteResponseItem(writeRequestItem, ResponseCode.OK);
    responseItems.add(writeResponseItem);
    PlcWriteResponse plcReadResponse = new PlcWriteResponse(plcWriteRequest, responseItems);
    assertTrue(plcReadResponse.getRequest().getNumItems() == 0, "Unexpected number of response items");
    assertTrue(plcReadResponse.getRequest().equals(plcWriteRequest), "Unexpected read request");
    assertTrue(plcReadResponse.getResponseItems().size() == 1, "Unexpected number of response items");
    assertTrue(plcReadResponse.getResponseItems().containsAll(responseItems), "Unexpected items in response items");
}
 
Example 45
Project: micrometer   File: PrometheusMeterRegistryTest.java   Source Code and License 5 votes vote down vote up
@DisplayName("percentiles are given as a separate sample with a key of 'quantile'")
@Test
void quantiles() {
    Timer.builder("timer")
        .publishPercentiles(0.5)
        .register(registry);
    DistributionSummary.builder("ds").publishPercentiles(0.5).register(registry);

    assertThat(prometheusRegistry.metricFamilySamples()).has(withNameAndTagKey("timer_duration_seconds", "quantile"));
    assertThat(prometheusRegistry.metricFamilySamples()).has(withNameAndTagKey("ds", "quantile"));
}
 
Example 46
Project: traute   File: MethodReturnTest.java   Source Code and License 5 votes vote down vote up
@DisplayName("finally")
@Test
public void fromFinally() {
    doMethodReturnTest(
            "" +
            "try {\n" +
            "  return 1;\n" +
            "} finally {\n" +
            "  return count();\n" +
            "}"
    );
}
 
Example 47
Project: qpp-conversion-tool   File: AciProportionDenominatorRoundTripTest.java   Source Code and License 5 votes vote down vote up
@Test
void parseAciNumeratorDenominatorAsNode() throws Exception {
	String xmlFragment = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
			+ "<component xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"urn:hl7-org:v3\">\n"
			+ "	<observation classCode=\"OBS\" moodCode=\"EVN\">\n"
			+ "		<!-- ACI Numerator Denominator Type Measure Denominator Data templateId -->\n"
			+ "		<templateId root=\"2.16.840.1.113883.10.20.27.3.32\" extension=\"2016-09-01\" />\n"
			+ "		<code code=\"ASSERTION\" codeSystem=\"2.16.840.1.113883.5.4\" codeSystemName=\"ActCode\" displayName=\"Assertion\" />\n"
			+ "		<statusCode code=\"completed\" />\n"
			+ "		<value xsi:type=\"CD\" code=\"DENOM\" codeSystem=\"2.16.840.1.113883.5.4\" codeSystemName=\"ActCode\" />\n"
			+ "		<!-- Denominator Count -->\n"
			+ "		<entryRelationship typeCode=\"SUBJ\" inversionInd=\"true\">\n"
			+ "			<observation classCode=\"OBS\" moodCode=\"EVN\">\n"
			+ "				<templateId root=\"2.16.840.1.113883.10.20.27.3.3\" />\n"
			+ "				<code code=\"MSRAGG\" codeSystem=\"2.16.840.1.113883.5.4\" codeSystemName=\"ActCode\" displayName=\"rate aggregation\" />\n"
			+ "				<statusCode code=\"completed\" />\n"
			+ "				<value xsi:type=\"INT\" value=\"600\" />\n"
			+ "				<methodCode code=\"COUNT\" codeSystem=\"2.16.840.1.113883.5.84\" codeSystemName=\"ObservationMethod\" displayName=\"Count\" />\n"
			+ "			</observation>" + "		</entryRelationship>\n" + "	</observation>\n" + "</component>";

	Context context = new Context();
	Node numDenomNode = new QrdaXmlDecoder(context).decode(XmlUtils.stringToDom(xmlFragment));

	QppOutputEncoder encoder = new QppOutputEncoder(context);
	List<Node> nodes = new ArrayList<>();
	nodes.add(numDenomNode);
	encoder.setNodes(nodes);

	StringWriter sw = new StringWriter();
	encoder.encode(new BufferedWriter(sw));

	String EXPECTED = "{\n  \"denominator\" : 600\n}";
	assertThat(sw.toString())
			.isEqualTo(EXPECTED);
}
 
Example 48
Project: hygene   File: MetadataParserTest.java   Source Code and License 5 votes vote down vote up
@Test
void testParseNodeMetadataWithAnEdgeLine() throws MetadataParseException, IOException {
    final GfaFile gfaFile = createGfaFile("L 12 + 24 - 4M");
    when(randomAccessFile.readLine()).thenReturn(replaceSpacesWithTabs("L 12 + 24 - 4M"));

    final Throwable e = catchThrowable(() -> parser.parseNodeMetadata(gfaFile, 1));

    assertThat(e).isInstanceOf(MetadataParseException.class);
    assertThat(e).hasMessageContaining("Expected line at position 1 to start with S");
}
 
Example 49
Project: ocraft-s2client   File: ActionUiCargoPanelUnloadTest.java   Source Code and License 5 votes vote down vote up
@Test
void throwsExceptionWhenUnitIndexIsNotProvided() {
    assertThatExceptionOfType(IllegalArgumentException.class)
            .isThrownBy(() -> ActionUiCargoPanelUnload.from(without(
                    () -> sc2ApiActionUiCargoPanelUnload().toBuilder(),
                    Ui.ActionCargoPanelUnload.Builder::clearUnitIndex).build()))
            .withMessage("unit index is required");

    assertThatExceptionOfType(IllegalArgumentException.class)
            .isThrownBy(() -> ((ActionUiCargoPanelUnload.Builder) cargoPanelUnload()).build())
            .withMessage("unit index is required");
}
 
Example 50
Project: incubator-plc4x   File: S7MessageTests.java   Source Code and License 5 votes vote down vote up
@Test
@Tag("fast")
void setupCommunictionsRequestMessage() {
    short tpduReference = 1;
    short maxAmqCaller = 4;
    short maxAmqCallee = 8;
    short pduLength = 128;

    SetupCommunicationRequestMessage setupMessage = new SetupCommunicationRequestMessage(tpduReference, maxAmqCaller, maxAmqCallee, pduLength);

    assertTrue(setupMessage.getTpduReference() == tpduReference, "Unexpected tpdu value");
    assertTrue(setupMessage.getMessageType() == MessageType.JOB, "Unexpected message type");
}
 
Example 51
Project: micrometer   File: PrometheusMeterRegistryTest.java   Source Code and License 5 votes vote down vote up
@Test
void namingConventionOfCustomMeters() {
    CompositeMeterRegistry composite = new CompositeMeterRegistry();
    composite.add(registry);

    registry.more().counter("my.custom", emptyList(), 0);
    assertThat(registry.scrape())
        .contains("my_custom");
}
 
Example 52
Project: dragoman   File: JsonTransformerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void canTransformMapToJson() {
  Map<String, Object> from = new HashMap<>();
  from.put("a", "b");
  from.put("c", 1);

  String transformed = documentTransformer.transform(from);

  assertThat(transformed, is("{\"a\":\"b\",\"c\":1}"));
}
 
Example 53
Project: trellis-io-jena   File: IOUtilsTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testProfile() {
    assertEquals(JSONLD_COMPACT_FLAT, IOUtils.getJsonLdProfile(JSONLD.compacted));
    assertEquals(JSONLD_EXPAND_FLAT, IOUtils.getJsonLdProfile());
    assertEquals(JSONLD_EXPAND_FLAT, IOUtils.getJsonLdProfile(rdf.createIRI("ex:text")));
    assertEquals(JSONLD_EXPAND_FLAT, IOUtils.getJsonLdProfile(JSONLD.expanded));
    assertEquals(JSONLD_FLATTEN_FLAT, IOUtils.getJsonLdProfile(JSONLD.expanded_flattened));
    assertEquals(JSONLD_FLATTEN_FLAT, IOUtils.getJsonLdProfile(JSONLD.expanded, JSONLD.flattened));
    assertEquals(JSONLD_FLATTEN_FLAT, IOUtils.getJsonLdProfile(JSONLD.flattened));
    assertEquals(JSONLD_FLATTEN_FLAT, IOUtils.getJsonLdProfile(JSONLD.compacted_flattened));
    assertEquals(JSONLD_FLATTEN_FLAT, IOUtils.getJsonLdProfile(JSONLD.compacted, JSONLD.flattened));
}
 
Example 54
Project: EvoMaster   File: HeuristicsForJumpsTest.java   Source Code and License 5 votes vote down vote up
@Test
public void test_IF_ICMPEQ_0(){
    // x == y
    int code = Opcodes.IF_ICMPEQ;

    Truthness t = getForValueComparison(0, 0, code);
    assertTrue(t.isTrue());
    assertFalse(t.isFalse());
}
 
Example 55
Project: Just-Evaluator   File: JustParserImplTest.java   Source Code and License 5 votes vote down vote up
@Test
void testParser() {
    for (int i = 0; i < 20; i++) {
        long start = System.currentTimeMillis();
        for (int j = 0; j < 100; j++) {
            runExpr("lfkdsk.lfkdsk(1111,2222,\"LFKDSK\") == true", false, null);
        }
        System.out.println(System.currentTimeMillis() - start);
    }
}
 
Example 56
Project: ocraft-s2client   File: FeatureLayersMinimapTest.java   Source Code and License 5 votes vote down vote up
@Test
void throwsExceptionWhenPlayerRelativeIsNotProvided() {
    assertThatExceptionOfType(IllegalArgumentException.class)
            .isThrownBy(() -> FeatureLayersMinimap.from(without(
                    () -> sc2ApiFeatureLayersMinimap().toBuilder(),
                    Spatial.FeatureLayersMinimap.Builder::clearPlayerRelative).build()))
            .withMessage("player relative is required");
}
 
Example 57
Project: qpp-conversion-tool   File: ErrorTest.java   Source Code and License 5 votes vote down vote up
@Test
void testMutability() {
	Error objectUnderTest = new Error();

	objectUnderTest.setSourceIdentifier("meep");
	objectUnderTest.setDetails(Collections.singletonList(new Detail()));

	assertWithMessage("The list should be one")
			.that(objectUnderTest.getDetails()).hasSize(1);
	assertWithMessage("The source identifier should be set")
			.that(objectUnderTest.getSourceIdentifier()).isSameAs("meep");
}
 
Example 58
Project: trellis   File: IOServiceTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testJsonLdExpandedSerializer() throws UnsupportedEncodingException {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    service.write(getTriples(), out, JSONLD, expanded);
    final String output = out.toString("UTF-8");
    assertTrue(output.contains("\"http://purl.org/dc/terms/title\":[{\"@value\":\"A title\"}]"));
    assertFalse(output.contains("\"@context\":"));
    assertFalse(output.contains("\"@graph\":"));

    final Graph graph = rdf.createGraph();
    service.read(new ByteArrayInputStream(output.getBytes(UTF_8)), null, JSONLD).forEach(graph::add);
    validateGraph(graph);
}
 
Example 59
Project: selenium-jupiter   File: DockerChromeLatestJupiterTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testFormerChrome(
        @DockerBrowser(type = CHROME, version = "latest-1") RemoteWebDriver driver) {
    driver.get("https://bonigarcia.github.io/selenium-jupiter/");
    assertThat(driver.getTitle(),
            containsString("A JUnit 5 extension for Selenium WebDriver"));
}
 
Example 60
Project: filter-sort-jooq-api   File: FilterParamTest.java   Source Code and License 5 votes vote down vote up
@Test
void ofCustomParserAndManuallyCallBuildConditionWithNoTypeSafety() {
    final FilterValue1<Object> filter = Filter.of("myKey", valueToParse -> 5, value -> DSL.trueCondition());
    Assertions.assertEquals(DSL.trueCondition(), filter.buildCondition(Collections.singletonList("whatever")));
    Assertions.assertEquals(DSL.trueCondition(), filter.buildCondition(Collections.singletonList("54")));
    Assertions.assertEquals(DSL.trueCondition(), filter.buildCondition(Collections.singletonList(56)));
}