org.mockserver.verify.VerificationTimes Java Examples

The following examples show how to use org.mockserver.verify.VerificationTimes. 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: SessionTest.java    From openerp-java-api with Apache License 2.0 6 votes vote down vote up
@Test
public void should_call_method_exec_workflow_on_executeCommand() throws Exception {
	if (isUsingMockServer()) {
		mockServer
				.when(request().withPath("/xmlrpc/2/object")
						.withBody(RegexBody.regex(".*<methodName>exec_workflow</methodName>.*")))
				.respond(response().withStatusCode(200).withBody(
						"<?xml version='1.0'?>\n<methodResponse>\n<params>\n<param>\n<value><int>1</int></value>\n</param>\n</params>\n</methodResponse>\n"));
	} else {
		session.startSession();
	}
	session.executeWorkflow("account.invoice", "invoice_open", 42424242);
	if (isUsingMockServer()) {
		mockServer.verify(request().withBody(new RegexBody(".*<methodName>exec_workflow</methodName>.*")),
				VerificationTimes.once());
	}
}
 
Example #2
Source File: SessionTest.java    From openerp-java-api with Apache License 2.0 6 votes vote down vote up
@Test
public void should_call_method_execute_on_executeCommand() throws Exception {
	if (isUsingMockServer()) {
		mockServer
				.when(request().withPath("/xmlrpc/2/object")
						.withBody(RegexBody.regex(".*<methodName>execute</methodName>.*")))
				.respond(response().withStatusCode(200).withBody(
						"<?xml version='1.0'?>\n<methodResponse>\n<params>\n<param>\n<value><int>1</int></value>\n</param>\n</params>\n</methodResponse>\n"));
	} else {
		session.startSession();
	}
	session.executeCommand("res.users", "context_get", null);
	if (isUsingMockServer()) {
		mockServer.verify(request().withBody(new RegexBody(".*<methodName>execute</methodName>.*")),
				VerificationTimes.once());
	}
}
 
Example #3
Source File: NotificationsTest.java    From apollo with Apache License 2.0 6 votes vote down vote up
@Test
public void testSlackNotification() throws Exception {

    ApolloTestClient apolloTestClient = Common.signupAndLogin();
    Notification notification = ModelsGenerator.createAndSubmitNotification(apolloTestClient,
            NotificationType.SLACK, slackNotificationConfiguration);

    Environment environment = apolloTestClient.getEnvironment(notification.getEnvironmentId());
    Service service = apolloTestClient.getService(notification.getServiceId());

    DeployableVersion deployableVersion = ModelsGenerator.createAndSubmitDeployableVersion(apolloTestClient, service);
    Deployment deployment = ModelsGenerator.createAndSubmitDeployment(apolloTestClient, environment, service, deployableVersion);

    mockSlackServer();

    StandaloneApollo.getOrCreateServer().getInstance(ApolloNotifications.class).notify(Deployment.DeploymentStatus.DONE, deployment);

    waitForRequest();

    mockServerClient.verify(
            HttpRequest.request()
            .withMethod("POST")
            .withPath(pseudoUrl),
            VerificationTimes.exactly(1)
    );
}
 
Example #4
Source File: UrlGetCollectorTest.java    From monsoon with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test(timeout = 10000)
public void scrape_without_contentlength() throws Exception {
    final HttpRequest REQUEST = HttpRequest.request("/scrapeWCL")
            .withMethod("GET");
    final UrlGetCollector collector = endpoint("/scrapeWCL");
    mockServerClient
            .when(REQUEST)
            .respond(HttpResponse.response("chocoladevla")
                    .withConnectionOptions(ConnectionOptions.connectionOptions().withSuppressContentLengthHeader(true).withCloseSocket(true)));

    Collection<MetricGroup> groups = GroupGenerator.deref(collector.getGroups(threadpool, new CompletableFuture<>()));
    mockServerClient.verify(REQUEST, VerificationTimes.once());

    assertThat(groups.stream().map(MetricGroup::getName).collect(Collectors.toList()),
            Matchers.contains(GroupName.valueOf("test")));

    // Verify data in test_group.
    final Map<MetricName, MetricValue> metrics = Arrays.stream(groups.stream()
            .filter(mg -> mg.getName().equals(GroupName.valueOf("test")))
            .findFirst()
            .get()
            .getMetrics()
    )
            .collect(Collectors.toMap(Metric::getName, Metric::getValue));
    System.err.println(metrics);
    assertThat(metrics, allOf(
            hasEntry(MetricName.valueOf("up"), MetricValue.TRUE),
            hasEntry(MetricName.valueOf("content", "length"), MetricValue.fromIntValue(12))));
}
 
Example #5
Source File: MockServerLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
private void verifyGetRequest() {
    new MockServerClient("localhost", 1080).verify(
            request()
                    .withMethod("GET")
                    .withPath("/index.html"),
            VerificationTimes.exactly(1)
    );
}
 
Example #6
Source File: MockServerLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
private void verifyPostRequest() {
    new MockServerClient("localhost", 1080).verify(
            request()
                    .withMethod("POST")
                    .withPath("/validate")
                    .withBody(exact("{username: 'foo', password: 'bar'}")),
            VerificationTimes.exactly(1)
    );
}
 
Example #7
Source File: SessionTest.java    From openerp-java-api with Apache License 2.0 5 votes vote down vote up
@Test
public void should_send_given_parameters() throws Exception {
	// Check parameters given are sent in order
	if (isUsingMockServer()) {
		mockServer
				.when(request().withMethod("POST").withPath("/xmlrpc/2/object")
						.withBody(new RegexBody(".*res.users.*context_get.*")))
				.respond(response().withStatusCode(200).withBody(
						"<?xml version='1.0'?>\n<methodResponse>\n<params>\n<param>\n<value><int>1</int></value>\n</param>\n</params>\n</methodResponse>\n"));
	} else {
		session.startSession();
	}
	Object[] parameters = new Object[] { "parameter1" };
	session.executeCommand("res.users", "context_get", parameters);
	if (isUsingMockServer()) {
		mockServer.verify(request().withBody(new RegexBody(".*parameter1.*")), VerificationTimes.once());
	}

	// Check empty array is working
	parameters = new Object[] {};
	session.executeCommand("res.users", "context_get", parameters);
	if (isUsingMockServer()) {
		mockServer.verify(request().withBody(new RegexBody(".*res.users.*context_get.*")),
				VerificationTimes.exactly(2));
	}

	// Check null is working
	parameters = null;
	session.executeCommand("res.users", "context_get", parameters);
	if (isUsingMockServer()) {
		mockServer.verify(request().withBody(new RegexBody(".*res.users.*context_get.*")),
				VerificationTimes.exactly(3));
	}
}
 
Example #8
Source File: GitLabCommitStatusPublisherTest.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void running_commitNotExists() throws UnsupportedEncodingException {
    AbstractBuild build = mockBuild(GITLAB_CONNECTION_V4, null, "test/project.git");
    HttpRequest updateCommitStatus = prepareUpdateCommitStatusWithSuccessResponse("v4", "test/project", build, BuildState.running);

    new GitLabCommitStatusPublisher("jenkins", false).prebuild(build, listener);
    mockServerClient.verify(updateCommitStatus, VerificationTimes.exactly(0));
}
 
Example #9
Source File: UrlGetCollectorTest.java    From monsoon with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test(timeout = 10000)
public void scrape() throws Exception {
    final HttpRequest REQUEST = HttpRequest.request("/scrape")
            .withMethod("GET");
    final UrlGetCollector collector = endpoint("/scrape");
    mockServerClient
            .when(REQUEST)
            .respond(HttpResponse.response("chocoladevla")
                    .withHeader("Test-Header", "Test-Response")
                    .withHeader("Double-Value", "17.1"));

    Collection<MetricGroup> groups = GroupGenerator.deref(collector.getGroups(threadpool, new CompletableFuture<>()));
    mockServerClient.verify(REQUEST, VerificationTimes.once());

    assertThat(groups.stream().map(MetricGroup::getName).collect(Collectors.toList()),
            Matchers.contains(GroupName.valueOf("test")));

    // Verify data in test_group.
    final Map<MetricName, MetricValue> metrics = Arrays.stream(groups.stream()
            .filter(mg -> mg.getName().equals(GroupName.valueOf("test")))
            .findFirst()
            .get()
            .getMetrics()
    )
            .collect(Collectors.toMap(Metric::getName, Metric::getValue));
    System.err.println(metrics);
    assertThat(metrics, allOf(
            hasEntry(MetricName.valueOf("up"), MetricValue.TRUE),
            hasEntry(MetricName.valueOf("header", "Test-Header"), MetricValue.fromStrValue("Test-Response")),
            hasEntry(MetricName.valueOf("header", "Double-Value"), MetricValue.fromDblValue(17.1)),
            hasEntry(MetricName.valueOf("content", "length"), MetricValue.fromIntValue(12)),
            hasEntry(MetricName.valueOf("content", "type"), MetricValue.fromStrValue("text/plain")),
            hasEntry(MetricName.valueOf("status", "code"), MetricValue.fromIntValue(200)),
            not(hasKey(MetricName.valueOf("body")))));
}
 
Example #10
Source File: UrlJsonCollectorTest.java    From monsoon with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test(timeout = 10000)
public void scrape() throws Exception {
    final HttpRequest REQUEST = HttpRequest.request("/json_scrape")
            .withMethod("GET");
    final UrlJsonCollector collector = endpoint("/json_scrape");
    mockServerClient
            .when(REQUEST)
            .respond(HttpResponse.response(JSON));

    Collection<MetricGroup> groups = GroupGenerator.deref(collector.getGroups(threadpool, new CompletableFuture<>()));
    mockServerClient.verify(REQUEST, VerificationTimes.once());

    assertThat(groups.stream().map(MetricGroup::getName).collect(Collectors.toList()),
            Matchers.contains(GroupName.valueOf("test")));

    // Verify data in test_group.
    final Map<MetricName, MetricValue> metrics = Arrays.stream(groups.stream()
            .filter(mg -> mg.getName().equals(GroupName.valueOf("test")))
            .findFirst()
            .get()
            .getMetrics()
    )
            .collect(Collectors.toMap(Metric::getName, Metric::getValue));
    System.err.println(metrics);
    assertThat(metrics, allOf(
            hasEntry(MetricName.valueOf("up"), MetricValue.TRUE),
            hasEntry(MetricName.valueOf("body", "bool"), MetricValue.TRUE),
            hasEntry(MetricName.valueOf("body", "int"), MetricValue.fromIntValue(7)),
            hasEntry(MetricName.valueOf("body", "dbl"), MetricValue.fromDblValue(3.1415)),
            hasEntry(MetricName.valueOf("body", "str"), MetricValue.fromStrValue("foobar")),
            hasEntry(MetricName.valueOf("body", "map", "key"), MetricValue.fromStrValue("value")),
            hasEntry(MetricName.valueOf("body", "list", "0"), MetricValue.fromStrValue("item")),
            hasEntry(MetricName.valueOf("content", "type"), MetricValue.fromStrValue("text/plain")),
            hasEntry(MetricName.valueOf("status", "code"), MetricValue.fromIntValue(200))));
}
 
Example #11
Source File: SplunkEventWriterTest.java    From beam with Apache License 2.0 4 votes vote down vote up
@Test
@Category(NeedsRunner.class)
public void successfulSplunkWriteMultiBatchTest() {

  // Create server expectation for success.
  mockServerListening(200);

  int testPort = mockServerRule.getPort();

  List<KV<Integer, SplunkEvent>> testEvents =
      ImmutableList.of(
          KV.of(
              123,
              SplunkEvent.newBuilder()
                  .withEvent("test-event-1")
                  .withHost("test-host-1")
                  .withIndex("test-index-1")
                  .withSource("test-source-1")
                  .withSourceType("test-source-type-1")
                  .withTime(12345L)
                  .create()),
          KV.of(
              123,
              SplunkEvent.newBuilder()
                  .withEvent("test-event-2")
                  .withHost("test-host-2")
                  .withIndex("test-index-2")
                  .withSource("test-source-2")
                  .withSourceType("test-source-type-2")
                  .withTime(12345L)
                  .create()));

  PCollection<SplunkWriteError> actual =
      pipeline
          .apply("Create Input data", Create.of(testEvents))
          // .withCoder(KvCoder.of(BigEndianIntegerCoder.of(), SplunkEventCoder.of())))
          .apply(
              "SplunkEventWriter",
              ParDo.of(
                  SplunkEventWriter.newBuilder()
                      .withUrl(Joiner.on(':').join("http://localhost", testPort))
                      .withInputBatchCount(
                          StaticValueProvider.of(
                              testEvents.size())) // all requests in a single batch.
                      .withToken("test-token")
                      .build()));

  // All successful responses.
  PAssert.that(actual).empty();

  pipeline.run();

  // Server received exactly one POST request.
  mockServerClient.verify(HttpRequest.request(EXPECTED_PATH), VerificationTimes.once());
}
 
Example #12
Source File: GerritCheckStepTest.java    From gerrit-code-review-plugin with Apache License 2.0 4 votes vote down vote up
@Test
public void gerritCheckStepInvokeTest() throws Exception {
  int changeId = 4321;
  int revision = 1;
  String checkerUuid = "checker";
  String checkStatus = "SUCCESSFUL";
  String message = "Does work";
  String branch = String.format("%02d/%d/%d", changeId % 100, changeId, revision);

  UsernamePasswordCredentialsImpl c =
      new UsernamePasswordCredentialsImpl(
          CredentialsScope.GLOBAL, "cid", "cid", "USERNAME", "PASSWORD");
  CredentialsProvider.lookupStores(j.jenkins)
      .iterator()
      .next()
      .addCredentials(Domain.global(), c);
  WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "q");
  p.setDefinition(
      new CpsFlowDefinition(
          String.format(
              ""
                  + "node {\n"
                  + "  withEnv([\n"
                  + "    'GERRIT_API_URL=https://%s:%s/a/project',\n"
                  + "    'GERRIT_API_INSECURE_HTTPS=true',\n"
                  + "    'GERRIT_CREDENTIALS_ID=cid',\n"
                  + "    'BRANCH_NAME=%s',\n"
                  + "  ]) {\n"
                  + "    gerritCheck checks: [%s: '%s'], message: '%s'\n"
                  + "  }\n"
                  + "}",
              g.getClient().remoteAddress().getHostString(),
              g.getClient().remoteAddress().getPort(),
              branch,
              checkerUuid,
              checkStatus,
              message),
          true));

  String expectedUrl = String.format("/a/changes/%s/revisions/%s/checks/", changeId, revision);

  CheckInput checkInput = new CheckInputForObjectMapper();
  checkInput.checkerUuid = checkerUuid;
  checkInput.state = CheckState.valueOf(checkStatus);
  checkInput.message = message;
  checkInput.url = j.getURL().toString() + p.getUrl() + "1/console";
  g.getClient()
      .when(
          HttpRequest.request(expectedUrl).withMethod("POST").withBody(JsonBody.json(checkInput)))
      .respond(
          HttpResponse.response()
              .withStatusCode(200)
              .withBody(JsonBody.json(Collections.emptyMap())));

  WorkflowRun run = j.assertBuildStatusSuccess(p.scheduleBuild2(0));
  String log = JenkinsRule.getLog(run);

  g.getClient().verify(HttpRequest.request(expectedUrl), VerificationTimes.once());
}
 
Example #13
Source File: GerritCheckStepTest.java    From gerrit-code-review-plugin with Apache License 2.0 4 votes vote down vote up
@Test
public void gerritCheckStepTestWithUrlSet() throws Exception {
  int changeId = 4321;
  int revision = 1;
  String checkerUuid = "checker";
  String checkStatus = "SUCCESSFUL";
  String url = "https://example.com/test";
  String branch = String.format("%02d/%d/%d", changeId % 100, changeId, revision);
  UsernamePasswordCredentialsImpl c =
      new UsernamePasswordCredentialsImpl(
          CredentialsScope.GLOBAL, "cid", "cid", "USERNAME", "PASSWORD");
  CredentialsProvider.lookupStores(j.jenkins)
      .iterator()
      .next()
      .addCredentials(Domain.global(), c);
  WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
  p.setDefinition(
      new CpsFlowDefinition(
          String.format(
              ""
                  + "node {\n"
                  + "  withEnv([\n"
                  + "    'GERRIT_API_URL=https://%s:%s/a/project',\n"
                  + "    'GERRIT_API_INSECURE_HTTPS=true',\n"
                  + "    'GERRIT_CREDENTIALS_ID=cid',\n"
                  + "    'BRANCH_NAME=%s',\n"
                  + "  ]) {\n"
                  + "    gerritCheck checks: [%s: '%s'], url: '%s'\n"
                  + "  }\n"
                  + "}",
              g.getClient().remoteAddress().getHostString(),
              g.getClient().remoteAddress().getPort(),
              branch,
              checkerUuid,
              checkStatus,
              url),
          true));

  String expectedUrl = String.format("/a/changes/%s/revisions/%s/checks/", changeId, revision);

  CheckInput checkInput = new CheckInputForObjectMapper();
  checkInput.checkerUuid = checkerUuid;
  checkInput.state = CheckState.valueOf(checkStatus);
  checkInput.url = url;
  g.getClient()
      .when(
          HttpRequest.request(expectedUrl).withMethod("POST").withBody(JsonBody.json(checkInput)))
      .respond(
          HttpResponse.response()
              .withStatusCode(200)
              .withBody(JsonBody.json(Collections.emptyMap())));

  WorkflowRun run = j.assertBuildStatusSuccess(p.scheduleBuild2(0));
  String log = JenkinsRule.getLog(run);

  g.getClient().verify(HttpRequest.request(expectedUrl), VerificationTimes.once());
}
 
Example #14
Source File: GerritReviewStepTest.java    From gerrit-code-review-plugin with Apache License 2.0 4 votes vote down vote up
@Test
public void gerritReviewStepInvokeTest() throws Exception {
  int changeId = 4321;
  int revision = 1;
  String label = "Verfied";
  int score = -1;
  String message = "Does not work";
  String branch = String.format("%02d/%d/%d", changeId % 100, changeId, revision);

  UsernamePasswordCredentialsImpl c =
      new UsernamePasswordCredentialsImpl(
          CredentialsScope.GLOBAL, "cid", "cid", "USERNAME", "PASSWORD");
  CredentialsProvider.lookupStores(j.jenkins)
      .iterator()
      .next()
      .addCredentials(Domain.global(), c);
  WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
  p.setDefinition(
      new CpsFlowDefinition(
          String.format(
              ""
                  + "node {\n"
                  + "  withEnv([\n"
                  + "    'GERRIT_API_URL=https://%s:%s/a/project',\n"
                  + "    'GERRIT_API_INSECURE_HTTPS=true',\n"
                  + "    'GERRIT_CREDENTIALS_ID=cid',\n"
                  + "    'BRANCH_NAME=%s',\n"
                  + "  ]) {\n"
                  + "    gerritReview labels: ['%s': %s], message: '%s'\n"
                  + "  }\n"
                  + "}",
              g.getClient().remoteAddress().getHostString(),
              g.getClient().remoteAddress().getPort(),
              branch,
              label,
              score,
              message),
          true));

  ReviewInput reviewInput = new ReviewInputForObjectMapper().label(label, score).message(message);
  reviewInput.drafts = ReviewInput.DraftHandling.PUBLISH;
  reviewInput.tag = "autogenerated:jenkins";
  reviewInput.notify = NotifyHandling.OWNER;
  g.getClient()
      .when(
          HttpRequest.request(
                  String.format(
                      "/a/project/a/changes/%s/revisions/%s/review", changeId, revision))
              .withMethod("POST")
              .withBody(JsonBody.json(reviewInput)))
      .respond(
          HttpResponse.response()
              .withStatusCode(200)
              .withBody(JsonBody.json(Collections.emptyMap())));

  WorkflowRun run = j.assertBuildStatusSuccess(p.scheduleBuild2(0));
  String log = JenkinsRule.getLog(run);

  g.getClient()
      .verify(
          HttpRequest.request(
              String.format("/a/project/a/changes/%s/revisions/%s/review", changeId, revision)),
          VerificationTimes.once());
}
 
Example #15
Source File: GerritReviewStepTest.java    From gerrit-code-review-plugin with Apache License 2.0 4 votes vote down vote up
@Test
public void gerritReviewStepInvokeLabelsTest() throws Exception {
  int changeId = 4321;
  int revision = 1;
  String label1 = "Verfied";
  int score1 = -1;
  String label2 = "CI-Review";
  int score2 = -1;
  String message = "Does not work";
  String branch = String.format("%02d/%d/%d", changeId % 100, changeId, revision);

  UsernamePasswordCredentialsImpl c =
      new UsernamePasswordCredentialsImpl(
          CredentialsScope.GLOBAL, "cid", "cid", "USERNAME", "PASSWORD");
  CredentialsProvider.lookupStores(j.jenkins)
      .iterator()
      .next()
      .addCredentials(Domain.global(), c);
  WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
  p.setDefinition(
      new CpsFlowDefinition(
          String.format(
              ""
                  + "node {\n"
                  + "  withEnv([\n"
                  + "    'GERRIT_API_URL=https://%s:%s/a/project',\n"
                  + "    'GERRIT_API_INSECURE_HTTPS=true',\n"
                  + "    'GERRIT_CREDENTIALS_ID=cid',\n"
                  + "    'BRANCH_NAME=%s',\n"
                  + "  ]) {\n"
                  + "    gerritReview labels: ['%s': %s, '%s': %s], message: '%s'\n"
                  + "  }\n"
                  + "}",
              g.getClient().remoteAddress().getHostString(),
              g.getClient().remoteAddress().getPort(),
              branch,
              label1,
              score1,
              label2,
              score2,
              message),
          true));

  ReviewInput reviewInput =
      new ReviewInputForObjectMapper()
          .label(label1, score1)
          .label(label2, score2)
          .message(message);
  reviewInput.drafts = ReviewInput.DraftHandling.PUBLISH;
  reviewInput.tag = "autogenerated:jenkins";
  reviewInput.notify = NotifyHandling.OWNER;
  g.getClient()
      .when(
          HttpRequest.request(
                  String.format(
                      "/a/project/a/changes/%s/revisions/%s/review", changeId, revision))
              .withMethod("POST")
              .withBody(JsonBody.json(reviewInput)))
      .respond(
          HttpResponse.response()
              .withStatusCode(200)
              .withBody(JsonBody.json(Collections.emptyMap())));

  WorkflowRun run = j.assertBuildStatusSuccess(p.scheduleBuild2(0));
  String log = JenkinsRule.getLog(run);

  g.getClient()
      .verify(
          HttpRequest.request(
              String.format("/a/project/a/changes/%s/revisions/%s/review", changeId, revision)),
          VerificationTimes.once());
}
 
Example #16
Source File: SplunkIOTest.java    From DataflowTemplates with Apache License 2.0 4 votes vote down vote up
/** Test successful multi-event POST request for SplunkIO without parallelism. */
@Test
@Category(NeedsRunner.class)
public void successfulSplunkIOMultiBatchNoParallelismTest() {

  // Create server expectation for success.
  mockServerListening(200);

  int testPort = mockServerRule.getPort();

  List<SplunkEvent> testEvents =
      ImmutableList.of(
          SplunkEvent.newBuilder()
              .withEvent("test-event-1")
              .withHost("test-host-1")
              .withIndex("test-index-1")
              .withSource("test-source-1")
              .withSourceType("test-source-type-1")
              .withTime(12345L)
              .build(),
          SplunkEvent.newBuilder()
              .withEvent("test-event-2")
              .withHost("test-host-2")
              .withIndex("test-index-2")
              .withSource("test-source-2")
              .withSourceType("test-source-type-2")
              .withTime(12345L)
              .build());

  PCollection<SplunkWriteError> actual =
      pipeline
          .apply("Create Input data", Create.of(testEvents).withCoder(SplunkEventCoder.of()))
          .apply(
              "SplunkIO",
              SplunkIO.writeBuilder()
                  .withParallelism(1)
                  .withBatchCount(testEvents.size())
                  .withToken("test-token")
                  .withUrl(Joiner.on(':').join("http://localhost", testPort))
                  .build())
          .setCoder(SplunkWriteErrorCoder.of());

  // All successful responses.
  PAssert.that(actual).empty();

  pipeline.run();

  // Server received exactly one POST request.
  mockServerClient.verify(HttpRequest.request(EXPECTED_PATH), VerificationTimes.once());
}
 
Example #17
Source File: IntegrationTest.java    From zulip-plugin with MIT License 4 votes vote down vote up
private void verifyNotificationsSent(int count) {
    mockServer.verify(request().withPath("/api/v1/messages"), VerificationTimes.exactly(count));
}
 
Example #18
Source File: SplunkIOTest.java    From DataflowTemplates with Apache License 2.0 4 votes vote down vote up
/** Test successful multi-event POST request for SplunkIO with parallelism. */
@Test
@Category(NeedsRunner.class)
public void successfulSplunkIOMultiBatchParallelismTest() {

  // Create server expectation for success.
  mockServerListening(200);

  int testPort = mockServerRule.getPort();
  int testParallelism = 2;

  List<SplunkEvent> testEvents =
      ImmutableList.of(
          SplunkEvent.newBuilder()
              .withEvent("test-event-1")
              .withHost("test-host-1")
              .withIndex("test-index-1")
              .withSource("test-source-1")
              .withSourceType("test-source-type-1")
              .withTime(12345L)
              .build(),
          SplunkEvent.newBuilder()
              .withEvent("test-event-2")
              .withHost("test-host-2")
              .withIndex("test-index-2")
              .withSource("test-source-2")
              .withSourceType("test-source-type-2")
              .withTime(12345L)
              .build());

  PCollection<SplunkWriteError> actual =
      pipeline
          .apply("Create Input data", Create.of(testEvents).withCoder(SplunkEventCoder.of()))
          .apply(
              "SplunkIO",
              SplunkIO.writeBuilder()
                  .withParallelism(testParallelism)
                  .withBatchCount(testEvents.size())
                  .withToken("test-token")
                  .withUrl(Joiner.on(':').join("http://localhost", testPort))
                  .build())
          .setCoder(SplunkWriteErrorCoder.of());

  // All successful responses.
  PAssert.that(actual).empty();

  pipeline.run();

  // Server received exactly one POST request per parallelism
  mockServerClient.verify(
      HttpRequest.request(EXPECTED_PATH), VerificationTimes.exactly(testParallelism));
}
 
Example #19
Source File: SplunkEventWriterTest.java    From beam with Apache License 2.0 4 votes vote down vote up
@Test
@Category(NeedsRunner.class)
public void failedSplunkWriteSingleBatchTest() {

  // Create server expectation for FAILURE.
  mockServerListening(404);

  int testPort = mockServerRule.getPort();

  List<KV<Integer, SplunkEvent>> testEvents =
      ImmutableList.of(
          KV.of(
              123,
              SplunkEvent.newBuilder()
                  .withEvent("test-event-1")
                  .withHost("test-host-1")
                  .withIndex("test-index-1")
                  .withSource("test-source-1")
                  .withSourceType("test-source-type-1")
                  .withTime(12345L)
                  .create()));

  PCollection<SplunkWriteError> actual =
      pipeline
          .apply("Create Input data", Create.of(testEvents))
          // .withCoder(KvCoder.of(BigEndianIntegerCoder.of(), SplunkEventCoder.of())))
          .apply(
              "SplunkEventWriter",
              ParDo.of(
                  SplunkEventWriter.newBuilder()
                      .withUrl(Joiner.on(':').join("http://localhost", testPort))
                      .withInputBatchCount(
                          StaticValueProvider.of(
                              testEvents.size())) // all requests in a single batch.
                      .withToken("test-token")
                      .build()));

  // Expect a single 404 Not found SplunkWriteError
  PAssert.that(actual)
      .containsInAnyOrder(
          SplunkWriteError.newBuilder()
              .withStatusCode(404)
              .withStatusMessage("Not Found")
              .withPayload(
                  "{\"time\":12345,\"host\":\"test-host-1\","
                      + "\"source\":\"test-source-1\",\"sourcetype\":\"test-source-type-1\","
                      + "\"index\":\"test-index-1\",\"event\":\"test-event-1\"}")
              .create());

  pipeline.run();

  // Server received exactly one POST request.
  mockServerClient.verify(HttpRequest.request(EXPECTED_PATH), VerificationTimes.once());
}
 
Example #20
Source File: SplunkEventWriterTest.java    From DataflowTemplates with Apache License 2.0 4 votes vote down vote up
/**
 * Test failed POST request.
 */
@Test
@Category(NeedsRunner.class)
public void failedSplunkWriteSingleBatchTest() {

  // Create server expectation for FAILURE.
  mockServerListening(404);

  int testPort = mockServerRule.getPort();

  List<KV<Integer, SplunkEvent>> testEvents =
      ImmutableList.of(
          KV.of(
              123,
              SplunkEvent.newBuilder()
                  .withEvent("test-event-1")
                  .withHost("test-host-1")
                  .withIndex("test-index-1")
                  .withSource("test-source-1")
                  .withSourceType("test-source-type-1")
                  .withTime(12345L)
                  .build()));

  PCollection<SplunkWriteError> actual =
      pipeline
          .apply(
              "Create Input data",
              Create.of(testEvents)
                  .withCoder(KvCoder.of(BigEndianIntegerCoder.of(), SplunkEventCoder.of())))
          .apply(
              "SplunkEventWriter",
              ParDo.of(
                  SplunkEventWriter.newBuilder()
                      .withUrl(Joiner.on(':').join("http://localhost", testPort))
                      .withInputBatchCount(StaticValueProvider
                          .of(testEvents.size())) // all requests in a single batch.
                      .withToken("test-token")
                      .build()))
          .setCoder(SplunkWriteErrorCoder.of());

  // Expect a single 404 Not found SplunkWriteError
  PAssert.that(actual)
      .containsInAnyOrder(
          SplunkWriteError.newBuilder()
              .withStatusCode(404)
              .withStatusMessage("Not Found")
              .withPayload(
                  "{\"time\":12345,\"host\":\"test-host-1\","
                      + "\"source\":\"test-source-1\",\"sourcetype\":\"test-source-type-1\","
                      + "\"index\":\"test-index-1\",\"event\":\"test-event-1\"}")
              .build());

  pipeline.run();

  // Server received exactly one POST request.
  mockServerClient.verify(HttpRequest.request(EXPECTED_PATH), VerificationTimes.once());
}
 
Example #21
Source File: SplunkEventWriterTest.java    From beam with Apache License 2.0 4 votes vote down vote up
@Test
@Category(NeedsRunner.class)
public void successfulSplunkWriteSingleBatchTest() {

  // Create server expectation for success.
  mockServerListening(200);

  int testPort = mockServerRule.getPort();

  List<KV<Integer, SplunkEvent>> testEvents =
      ImmutableList.of(
          KV.of(
              123,
              SplunkEvent.newBuilder()
                  .withEvent("test-event-1")
                  .withHost("test-host-1")
                  .withIndex("test-index-1")
                  .withSource("test-source-1")
                  .withSourceType("test-source-type-1")
                  .withTime(12345L)
                  .create()),
          KV.of(
              123,
              SplunkEvent.newBuilder()
                  .withEvent("test-event-2")
                  .withHost("test-host-2")
                  .withIndex("test-index-2")
                  .withSource("test-source-2")
                  .withSourceType("test-source-type-2")
                  .withTime(12345L)
                  .create()));

  PCollection<SplunkWriteError> actual =
      pipeline
          .apply("Create Input data", Create.of(testEvents))
          // .withCoder(KvCoder.of(BigEndianIntegerCoder.of(), SplunkEventCoder.of())))
          .apply(
              "SplunkEventWriter",
              ParDo.of(
                  SplunkEventWriter.newBuilder()
                      .withUrl(Joiner.on(':').join("http://localhost", testPort))
                      .withInputBatchCount(
                          StaticValueProvider.of(1)) // Test one request per SplunkEvent
                      .withToken("test-token")
                      .build()));

  // All successful responses.
  PAssert.that(actual).empty();

  pipeline.run();

  // Server received exactly the expected number of POST requests.
  mockServerClient.verify(
      HttpRequest.request(EXPECTED_PATH), VerificationTimes.exactly(testEvents.size()));
}
 
Example #22
Source File: SplunkIOTest.java    From beam with Apache License 2.0 4 votes vote down vote up
@Test
@Category(NeedsRunner.class)
public void successfulSplunkIOSingleBatchParallelismTest() {

  // Create server expectation for success.
  mockServerListening(200);

  int testPort = mockServerRule.getPort();
  int testParallelism = 2;
  String url = Joiner.on(':').join("http://localhost", testPort);
  String token = "test-token";

  List<SplunkEvent> testEvents =
      ImmutableList.of(
          SplunkEvent.newBuilder()
              .withEvent("test-event-1")
              .withHost("test-host-1")
              .withIndex("test-index-1")
              .withSource("test-source-1")
              .withSourceType("test-source-type-1")
              .withTime(12345L)
              .create(),
          SplunkEvent.newBuilder()
              .withEvent("test-event-2")
              .withHost("test-host-2")
              .withIndex("test-index-2")
              .withSource("test-source-2")
              .withSourceType("test-source-type-2")
              .withTime(12345L)
              .create());

  PCollection<SplunkWriteError> actual =
      pipeline
          .apply("Create Input data", Create.of(testEvents)) // .withCoder(SplunkEventCoder.of()))
          .apply(
              "SplunkIO",
              SplunkIO.write(url, token).withParallelism(testParallelism).withBatchCount(1));

  // All successful responses.
  PAssert.that(actual).empty();

  pipeline.run();

  // Server received exactly 1 post request per SplunkEvent
  mockServerClient.verify(
      HttpRequest.request(EXPECTED_PATH), VerificationTimes.exactly(testEvents.size()));
}
 
Example #23
Source File: SplunkIOTest.java    From beam with Apache License 2.0 4 votes vote down vote up
@Test
@Category(NeedsRunner.class)
public void successfulSplunkIOMultiBatchParallelismTest() {

  // Create server expectation for success.
  mockServerListening(200);

  int testPort = mockServerRule.getPort();
  int testParallelism = 2;
  String url = Joiner.on(':').join("http://localhost", testPort);
  String token = "test-token";

  List<SplunkEvent> testEvents =
      ImmutableList.of(
          SplunkEvent.newBuilder()
              .withEvent("test-event-1")
              .withHost("test-host-1")
              .withIndex("test-index-1")
              .withSource("test-source-1")
              .withSourceType("test-source-type-1")
              .withTime(12345L)
              .create(),
          SplunkEvent.newBuilder()
              .withEvent("test-event-2")
              .withHost("test-host-2")
              .withIndex("test-index-2")
              .withSource("test-source-2")
              .withSourceType("test-source-type-2")
              .withTime(12345L)
              .create());

  PCollection<SplunkWriteError> actual =
      pipeline
          .apply("Create Input data", Create.of(testEvents)) // .withCoder(SplunkEventCoder.of()))
          .apply(
              "SplunkIO",
              SplunkIO.write(url, token)
                  .withParallelism(testParallelism)
                  .withBatchCount(testEvents.size()));

  // All successful responses.
  PAssert.that(actual).empty();

  pipeline.run();

  // Server received exactly one POST request per parallelism
  mockServerClient.verify(
      HttpRequest.request(EXPECTED_PATH), VerificationTimes.atMost(testParallelism));
}
 
Example #24
Source File: SplunkIOTest.java    From beam with Apache License 2.0 4 votes vote down vote up
@Test
@Category(NeedsRunner.class)
public void successfulSplunkIOMultiBatchNoParallelismTest() {

  // Create server expectation for success.
  mockServerListening(200);

  int testPort = mockServerRule.getPort();
  String url = Joiner.on(':').join("http://localhost", testPort);
  String token = "test-token";

  List<SplunkEvent> testEvents =
      ImmutableList.of(
          SplunkEvent.newBuilder()
              .withEvent("test-event-1")
              .withHost("test-host-1")
              .withIndex("test-index-1")
              .withSource("test-source-1")
              .withSourceType("test-source-type-1")
              .withTime(12345L)
              .create(),
          SplunkEvent.newBuilder()
              .withEvent("test-event-2")
              .withHost("test-host-2")
              .withIndex("test-index-2")
              .withSource("test-source-2")
              .withSourceType("test-source-type-2")
              .withTime(12345L)
              .create());

  PCollection<SplunkWriteError> actual =
      pipeline
          .apply("Create Input data", Create.of(testEvents)) // .withCoder(SplunkEventCoder.of()))
          .apply(
              "SplunkIO",
              SplunkIO.write(url, token).withParallelism(1).withBatchCount(testEvents.size()));

  // All successful responses.
  PAssert.that(actual).empty();

  pipeline.run();

  // Server received exactly one POST request.
  mockServerClient.verify(HttpRequest.request(EXPECTED_PATH), VerificationTimes.once());
}
 
Example #25
Source File: GerritCommentStepTest.java    From gerrit-code-review-plugin with Apache License 2.0 4 votes vote down vote up
@Test
public void gerritCommentStepInvokeTest() throws Exception {
  int changeId = 4321;
  int revision = 1;
  String path = "/path/to/file";
  int line = 1;
  String message = "Invalid spacing";
  String branch = String.format("%02d/%d/%d", changeId % 100, changeId, revision);

  UsernamePasswordCredentialsImpl c =
      new UsernamePasswordCredentialsImpl(
          CredentialsScope.GLOBAL, "cid", "cid", "USERNAME", "PASSWORD");
  CredentialsProvider.lookupStores(j.jenkins)
      .iterator()
      .next()
      .addCredentials(Domain.global(), c);
  WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
  p.setDefinition(
      new CpsFlowDefinition(
          String.format(
              ""
                  + "node {\n"
                  + "  withEnv([\n"
                  + "    'GERRIT_API_URL=https://%s:%s/a/project',\n"
                  + "    'GERRIT_API_INSECURE_HTTPS=true',\n"
                  + "    'GERRIT_CREDENTIALS_ID=cid',\n"
                  + "    'BRANCH_NAME=%s',\n"
                  + "  ]) {\n"
                  + "    gerritComment path: '%s', line: %s, message: '%s'\n"
                  + "  }\n"
                  + "}",
              g.getClient().remoteAddress().getHostString(),
              g.getClient().remoteAddress().getPort(),
              branch,
              path,
              line,
              message),
          true));

  DraftInput draftInput = new DraftInput();
  draftInput.path = path;
  draftInput.line = line;
  draftInput.message = message;
  g.getClient()
      .when(
          HttpRequest.request(
                  String.format(
                      "/a/project/a/changes/%s/revisions/%s/drafts", changeId, revision))
              .withMethod("PUT")
              .withBody(JsonBody.json(draftInput)))
      .respond(
          HttpResponse.response()
              .withStatusCode(200)
              .withBody(JsonBody.json(Collections.emptyMap())));

  WorkflowRun run = j.assertBuildStatusSuccess(p.scheduleBuild2(0));
  String log = JenkinsRule.getLog(run);

  g.getClient()
      .verify(
          HttpRequest.request(
              String.format("/a/project/a/changes/%s/revisions/%s/drafts", changeId, revision)),
          VerificationTimes.once());
}
 
Example #26
Source File: SplunkIOTest.java    From DataflowTemplates with Apache License 2.0 4 votes vote down vote up
/** Test successful multi-event POST request for SplunkIO with parallelism. */
@Test
@Category(NeedsRunner.class)
public void successfulSplunkIOSingleBatchParallelismTest() {

  // Create server expectation for success.
  mockServerListening(200);

  int testPort = mockServerRule.getPort();
  int testParallelism = 2;

  List<SplunkEvent> testEvents =
      ImmutableList.of(
          SplunkEvent.newBuilder()
              .withEvent("test-event-1")
              .withHost("test-host-1")
              .withIndex("test-index-1")
              .withSource("test-source-1")
              .withSourceType("test-source-type-1")
              .withTime(12345L)
              .build(),
          SplunkEvent.newBuilder()
              .withEvent("test-event-2")
              .withHost("test-host-2")
              .withIndex("test-index-2")
              .withSource("test-source-2")
              .withSourceType("test-source-type-2")
              .withTime(12345L)
              .build());

  PCollection<SplunkWriteError> actual =
      pipeline
          .apply("Create Input data", Create.of(testEvents).withCoder(SplunkEventCoder.of()))
          .apply(
              "SplunkIO",
              SplunkIO.writeBuilder()
                  .withParallelism(testParallelism)
                  .withBatchCount(1)
                  .withToken("test-token")
                  .withUrl(Joiner.on(':').join("http://localhost", testPort))
                  .build())
          .setCoder(SplunkWriteErrorCoder.of());

  // All successful responses.
  PAssert.that(actual).empty();

  pipeline.run();

  // Server received exactly 1 post request per SplunkEvent
  mockServerClient.verify(
      HttpRequest.request(EXPECTED_PATH), VerificationTimes.exactly(testEvents.size()));
}
 
Example #27
Source File: SplunkEventWriterTest.java    From DataflowTemplates with Apache License 2.0 4 votes vote down vote up
/**
 * Test successful POST request for single batch.
 */
@Test
@Category(NeedsRunner.class)
public void successfulSplunkWriteSingleBatchTest() {

  // Create server expectation for success.
  mockServerListening(200);

  int testPort = mockServerRule.getPort();

  List<KV<Integer, SplunkEvent>> testEvents =
      ImmutableList.of(
          KV.of(
              123,
              SplunkEvent.newBuilder()
                  .withEvent("test-event-1")
                  .withHost("test-host-1")
                  .withIndex("test-index-1")
                  .withSource("test-source-1")
                  .withSourceType("test-source-type-1")
                  .withTime(12345L)
                  .build()),
          KV.of(
              123,
              SplunkEvent.newBuilder()
                  .withEvent("test-event-2")
                  .withHost("test-host-2")
                  .withIndex("test-index-2")
                  .withSource("test-source-2")
                  .withSourceType("test-source-type-2")
                  .withTime(12345L)
                  .build()));

  PCollection<SplunkWriteError> actual =
      pipeline
          .apply(
              "Create Input data",
              Create.of(testEvents)
                  .withCoder(KvCoder.of(BigEndianIntegerCoder.of(), SplunkEventCoder.of())))
          .apply(
              "SplunkEventWriter",
              ParDo.of(
                  SplunkEventWriter.newBuilder()
                      .withUrl(Joiner.on(':').join("http://localhost", testPort))
                      .withInputBatchCount(
                          StaticValueProvider.of(1)) // Test one request per SplunkEvent
                      .withToken("test-token")
                      .build()))
          .setCoder(SplunkWriteErrorCoder.of());

  // All successful responses.
  PAssert.that(actual).empty();

  pipeline.run();

  // Server received exactly the expected number of POST requests.
  mockServerClient.verify(
      HttpRequest.request(EXPECTED_PATH), VerificationTimes.exactly(testEvents.size()));
}
 
Example #28
Source File: SplunkEventWriterTest.java    From DataflowTemplates with Apache License 2.0 4 votes vote down vote up
/**
 * Test successful POST request for multi batch.
 */
@Test
@Category(NeedsRunner.class)
public void successfulSplunkWriteMultiBatchTest() {

  // Create server expectation for success.
  mockServerListening(200);

  int testPort = mockServerRule.getPort();

  List<KV<Integer, SplunkEvent>> testEvents =
      ImmutableList.of(
          KV.of(
              123,
              SplunkEvent.newBuilder()
                  .withEvent("test-event-1")
                  .withHost("test-host-1")
                  .withIndex("test-index-1")
                  .withSource("test-source-1")
                  .withSourceType("test-source-type-1")
                  .withTime(12345L)
                  .build()),
          KV.of(
              123,
              SplunkEvent.newBuilder()
                  .withEvent("test-event-2")
                  .withHost("test-host-2")
                  .withIndex("test-index-2")
                  .withSource("test-source-2")
                  .withSourceType("test-source-type-2")
                  .withTime(12345L)
                  .build()));

  PCollection<SplunkWriteError> actual =
      pipeline
          .apply(
              "Create Input data",
              Create.of(testEvents)
                  .withCoder(KvCoder.of(BigEndianIntegerCoder.of(), SplunkEventCoder.of())))
          .apply(
              "SplunkEventWriter",
              ParDo.of(
                  SplunkEventWriter.newBuilder()
                      .withUrl(Joiner.on(':').join("http://localhost", testPort))
                      .withInputBatchCount(StaticValueProvider
                          .of(testEvents.size())) // all requests in a single batch.
                      .withToken("test-token")
                      .build()))
          .setCoder(SplunkWriteErrorCoder.of());

  // All successful responses.
  PAssert.that(actual).empty();

  pipeline.run();

  // Server received exactly one POST request.
  mockServerClient.verify(HttpRequest.request(EXPECTED_PATH), VerificationTimes.once());
}