org.hamcrest.Matchers Java Examples

The following examples show how to use org.hamcrest.Matchers. 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: TestGameRunner.java    From TerasologyLauncher with Apache License 2.0 6 votes vote down vote up
@Test
@PrintLogs(category = "org.terasology.launcher.game.GameRunner", minLevel = Level.OFF, ideMinLevel = Level.OFF, greedy = true)
public void testGameOutputError() throws Exception {
    // Simulate an invalid output stream (that throws an IOException when read from because it's unhappy with its life)
    InputStream badStream = mock(InputStream.class);
    when(badStream.read(any(byte[].class), anyInt(), anyInt())).thenThrow(new IOException("Unhappy with life!"));

    when(gameProcess.getInputStream()).thenReturn(badStream);

    var loggedException = testLog.expect("", Level.ERROR, Matchers.allOf(
            LogMatchers.hasMatchingExtraThrowable(Matchers.instanceOf(IOException.class)),
            LogMatchers.hasMessage("Could not read game output!")
    ));

    // Run game process
    GameRunner gameRunner = new GameRunner(gameProcess);
    gameRunner.run();

    // Make sure GameRunner logs an error with an IOException
    loggedException.assertObservation();
}
 
Example #2
Source File: DirectGraphVisitorTest.java    From beam with Apache License 2.0 6 votes vote down vote up
@Test
public void getViewsReturnsViews() {
  PCollectionView<List<String>> listView =
      p.apply("listCreate", Create.of("foo", "bar"))
          .apply(
              ParDo.of(
                  new DoFn<String, String>() {
                    @ProcessElement
                    public void processElement(DoFn<String, String>.ProcessContext c)
                        throws Exception {
                      c.output(Integer.toString(c.element().length()));
                    }
                  }))
          .apply(View.asList());
  PCollectionView<Object> singletonView =
      p.apply("singletonCreate", Create.<Object>of(1, 2, 3)).apply(View.asSingleton());
  p.replaceAll(
      DirectRunner.fromOptions(TestPipeline.testingPipelineOptions())
          .defaultTransformOverrides());
  p.traverseTopologically(visitor);
  assertThat(visitor.getGraph().getViews(), Matchers.containsInAnyOrder(listView, singletonView));
}
 
Example #3
Source File: BoxTrashTest.java    From box-java-sdk with Apache License 2.0 6 votes vote down vote up
@Test
@Category(IntegrationTest.class)
public void restoreTrashedFileSucceeds() {
    BoxAPIConnection api = new BoxAPIConnection(TestConfig.getAccessToken());
    BoxTrash trash = new BoxTrash(api);
    BoxFolder rootFolder = BoxFolder.getRootFolder(api);
    String fileName = "[restoreTrashedFileSucceeds] Trashed File.txt";
    String fileContent = "Trashed file";
    byte[] fileBytes = fileContent.getBytes(StandardCharsets.UTF_8);

    InputStream uploadStream = new ByteArrayInputStream(fileBytes);
    BoxFile uploadedFile = rootFolder.uploadFile(uploadStream, fileName).getResource();
    uploadedFile.delete();
    trash.restoreFile(uploadedFile.getID());

    assertThat(trash, not(hasItem(Matchers.<BoxItem.Info>hasProperty("ID", equalTo(uploadedFile.getID())))));
    assertThat(rootFolder, hasItem(Matchers.<BoxItem.Info>hasProperty("ID", equalTo(uploadedFile.getID()))));

    uploadedFile.delete();
}
 
Example #4
Source File: TrainBenchmarkTest.java    From trainbenchmark with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void semaphoreNeighborInjectTest() throws Exception {
	// Arrange
	final String modelFilename = "railway-inject-" + largeSize;
	final String workload = "SemaphoreNeighborInjectTest";
	final List<RailwayOperation> operations = ImmutableList.of(//
			RailwayOperation.SEMAPHORENEIGHBOR, //
			RailwayOperation.SEMAPHORENEIGHBOR_INJECT //
	);
	final BenchmarkConfigBase bcb = bcbbTransformation.setModelFilename(modelFilename).setOperations(operations)
			.setWorkload(workload).createConfigBase();

	// Act
	final BenchmarkResult result = runTest(bcb);

	// Assert
	final ListMultimap<RailwayQuery, Integer> allMatches = result.getLastRunResult().getMatches();
	collector.checkThat(allMatches.get(RailwayQuery.SEMAPHORENEIGHBOR).get(0), Matchers.equalTo(5));
	collector.checkThat(allMatches.get(RailwayQuery.SEMAPHORENEIGHBOR).get(1), Matchers.equalTo(53));
}
 
Example #5
Source File: GitHubSCMSourceTraitsTest.java    From github-branch-source-plugin with MIT License 6 votes vote down vote up
@Test
public void build_111001() throws Exception {
    GitHubSCMSource instance = load();
    assertThat(instance.getTraits(),
            containsInAnyOrder(
                    Matchers.allOf(
                            instanceOf(BranchDiscoveryTrait.class),
                            hasProperty("buildBranch", is(true)),
                            hasProperty("buildBranchesWithPR", is(true))
                    ),
                    Matchers.allOf(
                            instanceOf(OriginPullRequestDiscoveryTrait.class),
                            hasProperty("strategyId", is(1))
                    ),
                    Matchers.allOf(
                            instanceOf(ForkPullRequestDiscoveryTrait.class),
                            hasProperty("strategyId", is(2))
                    )
            )
    );
}
 
Example #6
Source File: SameIndentationLevelTestCase.java    From eo-yaml with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * SameIndentationLevel should return all the lines
 * that it encapsulates.
 */
@Test
public void fetchesTheLines() {
    final List<YamlLine> lines = new ArrayList<>();
    lines.add(new RtYamlLine("first: somethingElse", 0));
    lines.add(new RtYamlLine("second: ", 1));
    lines.add(new RtYamlLine("  fourth: some", 2));
    lines.add(new RtYamlLine("  fifth: values", 3));
    lines.add(new RtYamlLine("third: something", 4));
    final YamlLines yaml = new SameIndentationLevel(
        new AllYamlLines(lines)
    );
    MatcherAssert.assertThat(
        yaml.original().size(),
        Matchers.equalTo(lines.size())
    );
}
 
Example #7
Source File: RuntimeCommandsTests.java    From spring-cloud-dashboard with Apache License 2.0 6 votes vote down vote up
@Test
public void testStatusWithoutSummary() {
	Collection<AppStatusResource> data = new ArrayList<>();
	data.add(appStatusResource1);
	data.add(appStatusResource2);
	PagedResources.PageMetadata metadata = new PagedResources.PageMetadata(data.size(), 1, data.size(), 1);
	PagedResources<AppStatusResource> result = new PagedResources<>(data, metadata);
	when(runtimeOperations.status()).thenReturn(result);
	Object[][] expected = new String[][] {
			{"1", "deployed", "2"},
			{"10", "deployed"},
			{"20", "deployed"},
			{"2", "undeployed", "0"}
	};
	TableModel model = runtimeCommands.list(false, null).getModel();
	for (int row = 0; row < expected.length; row++) {
		for (int col = 0; col < expected[row].length; col++) {
			assertThat(String.valueOf(model.getValue(row + 1, col)), Matchers.is(expected[row][col]));
		}
	}
}
 
Example #8
Source File: XsWorkbookTest.java    From excel-io with MIT License 6 votes vote down vote up
/**
 * Creates workbook with multiple sheets.
 * @throws IOException If fails
 */
@Test
public void createsWorkbookWithMultipleSheets() throws IOException {
    final String fsheet = "sheet1";
    final String ssheet = "sheet2";
    final Workbook wbook = new XsWorkbook()
        .with(new XsSheet(new XsRow(new TextCell(fsheet))))
        .with(new XsSheet(new XsRow(new TextCell(ssheet))))
        .asWorkbook();
    MatcherAssert.assertThat(
        wbook.getSheetAt(0).getRow(0).getCell(0)
            .getStringCellValue(),
        Matchers.equalTo(fsheet)
    );
    MatcherAssert.assertThat(
        wbook.getSheetAt(1).getRow(0).getCell(0)
            .getStringCellValue(),
        Matchers.equalTo(ssheet)
    );
}
 
Example #9
Source File: RqCookiesTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * RqCookies can parse a request with multiple cookies.
 * @throws IOException If some problem inside
 */
@Test
public void parsesHttpRequestWithMultipleCookies() throws IOException {
    MatcherAssert.assertThat(
        new RqCookies.Base(
            new RqFake(
                Arrays.asList(
                    "GET /hz09",
                    "Host: as0.example.com",
                    "Cookie: ttt=ALPHA",
                    "Cookie: f=1;   g=55;   xxx=9090",
                    "Cookie: z=ALPHA"
                ),
                ""
            )
        ).cookie("g"),
        Matchers.hasItem("55")
    );
}
 
Example #10
Source File: RtImageTestCase.java    From docker-java-api with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * RtImage can return its Docker parent.
 */
@Test
public void returnsDocker() {
    MatcherAssert.assertThat(
        new RtImage(
            Json.createObjectBuilder().build(),
            new AssertRequest(
                new Response(
                    HttpStatus.SC_OK,
                    Json.createArrayBuilder().build().toString()
                )
            ),
            URI.create("http://localhost:80/1.30/images/456"),
            DOCKER
        ).docker(),
        Matchers.is(DOCKER)
    );
}
 
Example #11
Source File: EasyMapperTest.java    From easy-mapper with Apache License 2.0 6 votes vote down vote up
@Test
public void testMapOnNullTrue() throws Exception {
    Person p = new Person();
    p.firstName = "neo";
    p.salary = 1000L;

    PersonDto dto = new PersonDto();
    dto.firstName = "neo2";
    dto.lastName = "Jason2";
    dto.jobTitles = Lists.newArrayList("1", "2", "3");
    dto.salary = 1000L;
    MapperFactory.getCopyByRefMapper().mapClass(Person.class, PersonDto.class)
            .mapOnNull(true)
            .register()
            .map(p, dto);
    System.out.println(dto);
    assertThat(dto.firstName, Matchers.is(p.firstName));
    assertThat(dto.lastName, Matchers.is(p.lastName));
    assertThat(dto.jobTitles, Matchers.is(p.jobTitles));
    assertThat(dto.salary, Matchers.is(p.salary));
}
 
Example #12
Source File: YamlSequencePrintTest.java    From eo-yaml with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * An null YamlSequence value is printed as null.
 */
@Test
public void printsNullSequenceAsNull() {
    final YamlSequence seq = null;
    final YamlSequence sequence = Yaml.createYamlSequenceBuilder()
        .add("value1")
        .add(seq)
        .add("value2")
        .build();
    final StringBuilder expected = new StringBuilder();
    expected
        .append("- value1").append(System.lineSeparator())
        .append("- null").append(System.lineSeparator())
        .append("- value2");
    MatcherAssert.assertThat(
        sequence.toString(),
        Matchers.equalTo(expected.toString())
    );
}
 
Example #13
Source File: SamlClientTest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testLoginWithOIDCClient() throws ParsingException, ConfigurationException, ProcessingException, IOException {
    ClientRepresentation salesRep = adminClient.realm(REALM_NAME).clients().findByClientId(SAML_CLIENT_ID_SALES_POST).get(0);
    adminClient.realm(REALM_NAME).clients().get(salesRep.getId()).update(ClientBuilder.edit(salesRep)
                    .protocol(OIDCLoginProtocol.LOGIN_PROTOCOL).build());

    AuthnRequestType loginRep = createLoginRequestDocument(SAML_CLIENT_ID_SALES_POST, SAML_ASSERTION_CONSUMER_URL_SALES_POST, REALM_NAME);
    Document samlRequest = SAML2Request.convert(loginRep);

    SamlClient.RedirectStrategyWithSwitchableFollowRedirect strategy = new SamlClient.RedirectStrategyWithSwitchableFollowRedirect();
    URI samlEndpoint = getAuthServerSamlEndpoint(REALM_NAME);

    try (CloseableHttpClient client = HttpClientBuilder.create().setRedirectStrategy(strategy).build()) {
        HttpUriRequest post = SamlClient.Binding.POST.createSamlUnsignedRequest(samlEndpoint, null, samlRequest);
        CloseableHttpResponse response = sendPost(post, client);
        Assert.assertEquals(response.getStatusLine().getStatusCode(), 400);
        String s = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
        Assert.assertThat(s, Matchers.containsString("Wrong client protocol."));

        response.close();
    }

    adminClient.realm(REALM_NAME).clients().get(salesRep.getId()).update(ClientBuilder.edit(salesRep)
            .protocol(SamlProtocol.LOGIN_PROTOCOL).build());
}
 
Example #14
Source File: StorableActivityFenceTest.java    From JCVD with MIT License 6 votes vote down vote up
@Test
public void testValues() {
    StorableActivityFence fence = StorableActivityFence.starting(
            DetectedActivityFence.IN_VEHICLE, DetectedActivityFence.RUNNING);
    int[] startActivities = {DetectedActivityFence.IN_VEHICLE, DetectedActivityFence.RUNNING};
    assertThat(fence.getType(), Matchers.is(StorableFence.Type.ACTIVITY));
    assertThat(fence.getActivityTypes(), is(startActivities));
    assertThat(fence.getTransitionType(), is(StorableActivityFence.START_TYPE));

    fence = StorableActivityFence.stopping(
            DetectedActivityFence.ON_BICYCLE, DetectedActivityFence.WALKING);
    int[] stopActivities = {DetectedActivityFence.ON_BICYCLE, DetectedActivityFence.WALKING};
    assertThat(fence.getType(), Matchers.is(StorableFence.Type.ACTIVITY));
    assertThat(fence.getActivityTypes(), is(stopActivities));
    assertThat(fence.getTransitionType(), is(StorableActivityFence.STOP_TYPE));

    fence = StorableActivityFence.during(
            DetectedActivityFence.ON_FOOT, DetectedActivityFence.STILL, DetectedActivityFence.UNKNOWN);
    int[] duringActivities = {DetectedActivityFence.ON_FOOT, DetectedActivityFence.STILL, DetectedActivityFence.UNKNOWN};
    assertThat(fence.getType(), Matchers.is(StorableFence.Type.ACTIVITY));
    assertThat(fence.getActivityTypes(), is(duringActivities));
    assertThat(fence.getTransitionType(), is(StorableActivityFence.DURING_TYPE));
}
 
Example #15
Source File: EntitlementAPITest.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvalidRequestWithClaimsFromPublicClient() throws IOException {
    oauth.realm("authz-test");
    oauth.clientId(PUBLIC_TEST_CLIENT);

    oauth.doLogin("marta", "password");

    // Token request
    String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE);
    OAuthClient.AccessTokenResponse response = oauth.doAccessTokenRequest(code, null);

    AuthorizationRequest request = new AuthorizationRequest();

    request.addPermission("Resource 13");
    HashMap<Object, Object> obj = new HashMap<>();

    obj.put("claim-a", "claim-a");

    request.setClaimToken(Base64Url.encode(JsonSerialization.writeValueAsBytes(obj)));
    this.expectedException.expect(AuthorizationDeniedException.class);
    this.expectedException.expectCause(Matchers.allOf(Matchers.instanceOf(HttpResponseException.class), Matchers.hasProperty("statusCode", Matchers.is(403))));
    this.expectedException.expectMessage("Public clients are not allowed to send claims");
    this.expectedException.reportMissingExceptionWithMessage("Should fail, public clients not allowed");

    getAuthzClient(AUTHZ_CLIENT_CONFIG).authorization(response.getAccessToken()).authorize(request);
}
 
Example #16
Source File: JadxDecompilerTest.java    From Box with Apache License 2.0 6 votes vote down vote up
@Test
public void testExampleUsage() {
	File sampleApk = InputFileTest.getFileFromSampleDir("app-with-fake-dex.apk");
	File outDir = FileUtils.createTempDir("jadx-usage-example").toFile();

	// test simple apk loading
	JadxArgs args = new JadxArgs();
	args.getInputFiles().add(sampleApk);
	args.setOutDir(outDir);

	JadxDecompiler jadx = new JadxDecompiler(args);
	jadx.load();
	jadx.save();
	jadx.printErrorsReport();

	// test class print
	for (JavaClass cls : jadx.getClasses()) {
		System.out.println(cls.getCode());
	}

	assertThat(jadx.getClasses(), Matchers.hasSize(3));
	assertThat(jadx.getErrorsCount(), Matchers.is(0));
}
 
Example #17
Source File: GitHubSCMSourceTraitsTest.java    From github-branch-source-plugin with MIT License 6 votes vote down vote up
@Test
public void build_101111() throws Exception {
    GitHubSCMSource instance = load();
    assertThat(instance.getTraits(),
            containsInAnyOrder(
                    Matchers.allOf(
                            instanceOf(BranchDiscoveryTrait.class),
                            hasProperty("buildBranch", is(true)),
                            hasProperty("buildBranchesWithPR", is(false))
                    ),
                    Matchers.allOf(
                            instanceOf(OriginPullRequestDiscoveryTrait.class),
                            hasProperty("strategyId", is(3))
                    ),
                    Matchers.allOf(
                            instanceOf(ForkPullRequestDiscoveryTrait.class),
                            hasProperty("strategyId", is(3))
                    )
            )
    );
}
 
Example #18
Source File: StateRepositoryUiControllerTest.java    From synapse with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldLinkToJournal() throws Exception {
    final Journal journal = mock(Journal.class);
    when(journal.getJournalFor("first"))
            .thenReturn(Stream.of(
                    MessageStoreEntry.of("test", TextMessage.of("first", null)))
            );
    when(journals.hasJournal("test")).thenReturn(true);
    when(journals.getJournal("test")).thenReturn(Optional.of(journal));
    mockMvc
            .perform(
                    get("/internal/staterepositories/test/first").accept("text/html"))
            .andExpect(
                    status().isOk())
            .andExpect(
                    model().attribute("journaled", is(true))
            )
            .andExpect(
                    content().string(Matchers.containsString("<a class=\"btn btn-default btn-xs\" href=\"/internal/journals/test/first\" role=\"button\">Open Journal</a>")));
}
 
Example #19
Source File: ExecutionGraphCheckpointCoordinatorTest.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that the checkpoint coordinator is shut down if the execution graph
 * is failed.
 */
@Test
public void testShutdownCheckpointCoordinatorOnFailure() throws Exception {
	final CompletableFuture<JobStatus> counterShutdownFuture = new CompletableFuture<>();
	CheckpointIDCounter counter = new TestingCheckpointIDCounter(counterShutdownFuture);

	final CompletableFuture<JobStatus> storeShutdownFuture = new CompletableFuture<>();
	CompletedCheckpointStore store = new TestingCompletedCheckpointStore(storeShutdownFuture);

	ExecutionGraph graph = createExecutionGraphAndEnableCheckpointing(counter, store);
	final CheckpointCoordinator checkpointCoordinator = graph.getCheckpointCoordinator();

	assertThat(checkpointCoordinator, Matchers.notNullValue());
	assertThat(checkpointCoordinator.isShutdown(), is(false));

	graph.failGlobal(new Exception("Test Exception"));

	assertThat(checkpointCoordinator.isShutdown(), is(true));
	assertThat(counterShutdownFuture.get(), is(JobStatus.FAILED));
	assertThat(storeShutdownFuture.get(), is(JobStatus.FAILED));
}
 
Example #20
Source File: CliMainTest.java    From styx with Apache License 2.0 6 votes vote down vote up
@Test
public void testWorkflowCreate() throws Exception {
  final String component = "quux";

  final Path workflowsFile = fileFromResource("workflows.yaml");
  final List<WorkflowConfiguration> expected = Json.YAML_MAPPER
      .reader().forType(WorkflowConfiguration.class)
      .<WorkflowConfiguration>readValues(workflowsFile.toFile())
      .readAll();
  assertThat(expected, is(not(Matchers.empty())));

  when(client.createOrUpdateWorkflow(any(), any())).thenAnswer(a -> {
    final String comp = a.getArgument(0);
    final WorkflowConfiguration wfConfig = a.getArgument(1);
    return CompletableFuture.completedFuture(Workflow.create(comp, wfConfig));
  });

  CliMain.run(cliContext, "workflow", "create", component, "-f", workflowsFile.toString());

  for (WorkflowConfiguration workflowConfiguration : expected) {
    verify(client).createOrUpdateWorkflow(component, workflowConfiguration);
    verify(cliOutput).printMessage("Workflow " + workflowConfiguration.id() + " in component "
        + component + " created.");
  }
}
 
Example #21
Source File: PartitionDistributorTest.java    From storm-dynamic-spout with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Test that when we have a negative total consumers value that we toss an exception.
 */
@Test
public void testCalculatePartitionAssignmentWithTotalConsumersNegative() {
    final Throwable thrown = Assertions.assertThrows(IllegalArgumentException.class, () -> {
        PartitionDistributor.calculatePartitionAssignment(
            // Number of consumer instances
            -2,
            // Current instance index
            2,
            // Partition ids to distribute
            new int[] { 0, 1, 2, 3 }
        );
    });

    MatcherAssert.assertThat(thrown.getMessage(), Matchers.containsString("totalConsumers"));
}
 
Example #22
Source File: TokenTest.java    From takes with MIT License 6 votes vote down vote up
/**
 * JWT header is encoded correctly.
 * @throws IOException If some problem inside
 */
@Test
public void jwtEncoded() throws IOException {
    final Identity user = new Identity.Simple("test");
    final byte[] code = new Token.Jwt(
        // @checkstyle MagicNumber (1 line)
        user, 3600L
    ).encoded();
    final JsonObject jose = new Token.Jwt(
        // @checkstyle MagicNumber (1 line)
        user, 3600L
    ).json();
    MatcherAssert.assertThat(
        code,
        Matchers.equalTo(
            Base64.getEncoder().encode(jose.toString().getBytes())
        )
    );
}
 
Example #23
Source File: PrebuiltCxxLibraryGroupDescriptionTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void staticLink() {
  ActionGraphBuilder graphBuilder = new TestActionGraphBuilder();
  BuildTarget target = BuildTargetFactory.newInstance("//:lib");
  SourcePath path = FakeSourcePath.of("include");
  NativeLinkableGroup lib =
      (NativeLinkableGroup)
          new PrebuiltCxxLibraryGroupBuilder(target)
              .setStaticLink(ImmutableList.of("--something", "$(lib 0)", "--something-else"))
              .setStaticLibs(ImmutableList.of(path))
              .build(graphBuilder);
  assertThat(
      lib.getNativeLinkable(CxxPlatformUtils.DEFAULT_PLATFORM, graphBuilder)
          .getNativeLinkableInput(
              Linker.LinkableDepType.STATIC,
              graphBuilder,
              UnconfiguredTargetConfiguration.INSTANCE),
      Matchers.equalTo(
          NativeLinkableInput.builder()
              .addArgs(
                  StringArg.of("--something"),
                  SourcePathArg.of(path),
                  StringArg.of("--something-else"))
              .build()));
}
 
Example #24
Source File: DispatcherTest.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
@Test
public void testPersistedJobGraphWhenDispatcherIsShutDown() throws Exception {
	final InMemorySubmittedJobGraphStore submittedJobGraphStore = new InMemorySubmittedJobGraphStore();
	haServices.setSubmittedJobGraphStore(submittedJobGraphStore);

	dispatcher = createAndStartDispatcher(heartbeatServices, haServices, DefaultJobManagerRunnerFactory.INSTANCE);

	// grant leadership and submit a single job
	final DispatcherId expectedDispatcherId = DispatcherId.generate();
	dispatcherLeaderElectionService.isLeader(expectedDispatcherId.toUUID()).get();

	final DispatcherGateway dispatcherGateway = dispatcher.getSelfGateway(DispatcherGateway.class);
	final CompletableFuture<Acknowledge> submissionFuture = dispatcherGateway.submitJob(jobGraph, TIMEOUT);
	submissionFuture.get();
	assertThat(dispatcher.getNumberJobs(TIMEOUT).get(), Matchers.is(1));

	dispatcher.close();

	assertThat(submittedJobGraphStore.contains(jobGraph.getJobID()), Matchers.is(true));
}
 
Example #25
Source File: TrainBenchmarkTest.java    From trainbenchmark with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void posLengthInjectTest() throws Exception {
	// Arrange
	final String modelFilename = "railway-inject-" + largeSize;
	final String workload = "PosLengthInjectTest";
	final List<RailwayOperation> operations = ImmutableList.of(//
			RailwayOperation.POSLENGTH, //
			RailwayOperation.POSLENGTH_INJECT //
	);
	final BenchmarkConfigBase bcb = bcbbTransformation.setModelFilename(modelFilename).setOperations(operations)
			.setWorkload(workload).createConfigBase();

	// Act
	final BenchmarkResult result = runTest(bcb);

	// Assert
	final ListMultimap<RailwayQuery, Integer> allMatches = result.getLastRunResult().getMatches();
	collector.checkThat(allMatches.get(RailwayQuery.POSLENGTH).get(0), Matchers.equalTo(32));
	collector.checkThat(allMatches.get(RailwayQuery.POSLENGTH).get(1), Matchers.equalTo(41));
}
 
Example #26
Source File: AssertEvents.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public ExpectedEvent expectSocialLogin() {
    return expect(EventType.LOGIN)
            .detail(Details.CODE_ID, isCodeId())
            .detail(Details.USERNAME, DEFAULT_USERNAME)
            .detail(Details.AUTH_METHOD, "form")
            .detail(Details.REDIRECT_URI, Matchers.equalTo(DEFAULT_REDIRECT_URI))
            .session(isUUID());
}
 
Example #27
Source File: DoFnLifecycleManagerTest.java    From beam with Apache License 2.0 5 votes vote down vote up
@Test
public void teardownOnRemove() throws Exception {
  TestFn obtained = (TestFn) mgr.get();
  mgr.remove();

  assertThat(obtained, not(theInstance(fn)));
  assertThat(obtained.setupCalled, is(true));
  assertThat(obtained.teardownCalled, is(true));

  assertThat(mgr.get(), not(Matchers.<DoFn<?, ?>>theInstance(obtained)));
}
 
Example #28
Source File: ReadYamlStreamTest.java    From eo-yaml with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * If an empty Yaml stream is provided,
 * then ReadYamlStream should be empty.
 */
@Test
public void worksWithEmptyStream() {
    final List<YamlLine> lines = new ArrayList<>();
    lines.add(new RtYamlLine("---", 0));
    lines.add(new RtYamlLine("...", 1));
    final YamlStream stream = new ReadYamlStream(
        new AllYamlLines(lines)
    );
    MatcherAssert.assertThat(stream.values(), Matchers.emptyIterable());
}
 
Example #29
Source File: AssertEvents.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public ExpectedEvent expectRegister(String username, String email) {
    UserRepresentation user = username != null ? getUser(username) : null;
    return expect(EventType.REGISTER)
            .user(user != null ? user.getId() : null)
            .detail(Details.USERNAME, username)
            .detail(Details.EMAIL, email)
            .detail(Details.REGISTER_METHOD, "form")
            .detail(Details.REDIRECT_URI, Matchers.equalTo(DEFAULT_REDIRECT_URI));
}
 
Example #30
Source File: TMarkLogicConnectionStandaloneTest.java    From components with Apache License 2.0 5 votes vote down vote up
@Test
public void testConnectionFailureToConnectInvalidCredentials() {
    exceptions.expect(MarkLogicException.class);
    exceptions.expectMessage(Matchers.containsString("Invalid credentials."));

    connectionProperties.authentication.setValue("DIGEST");
    connectionStandalone.initialize(container, connectionProperties);
    Mockito.when(client.openTransaction()).thenThrow(new FailedRequestException("Wrong password"));

    connectionStandalone.runAtDriver(container);
}