org.junit.jupiter.api.TestTemplate Java Examples

The following examples show how to use org.junit.jupiter.api.TestTemplate. 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: CompleteTaskAccTest.java    From taskana with Apache License 2.0 6 votes vote down vote up
@WithAccessId(user = "admin")
@WithAccessId(user = "taskadmin")
@TestTemplate
void should_ForceCompleteTask_When_NoExplicitPermissionsButUserIsInAdministrativeRole()
    throws TaskNotFoundException, InvalidStateException, InvalidOwnerException,
        NotAuthorizedException, SQLException {
  resetDb(false);

  assertThat(TASK_SERVICE.getTask("TKI:000000000000000000000000000000000000").getState())
      .isEqualTo(TaskState.CLAIMED);
  Task completedTask = TASK_SERVICE.forceCompleteTask("TKI:000000000000000000000000000000000000");
  assertThat(completedTask).isNotNull();
  assertThat(completedTask.getCompleted()).isNotNull();
  assertThat(completedTask.getState()).isEqualTo(TaskState.COMPLETED);
  assertThat(completedTask.getModified()).isNotEqualTo(completedTask.getCreated());
}
 
Example #2
Source File: SslAuthenticationTest.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
/**
 * Connect to the local simple https server with SSL authentication enabled explicitly.
 * This should throw an exception because the SSL authentication fails.
 */
@TestTemplate
public void localSslAuthenticationEnabled() throws Exception {

    CouchDbException thrownException = null;
    try {
        CloudantClient dbClient = CloudantClientHelper.newMockWebServerClientBuilder(server)
                .build();

        // Queue a 200 OK response
        server.enqueue(new MockResponse());

        // Make an arbitrary connection to the DB.
        dbClient.getAllDbs();
    } catch (CouchDbException e) {
        thrownException = e;
    }
    validateClientAuthenticationException(thrownException);
}
 
Example #3
Source File: SslAuthenticationTest.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
/**
 * Repeat the localSSLAuthenticationDisabled, but with the cookie auth enabled.
 * This test validates that the SSL settings also get applied to the cookie interceptor.
 */
@TestTemplate
public void localSSLAuthenticationDisabledWithCookieAuth() throws Exception {

    // Mock up an OK cookie response then an OK response for the getAllDbs()
    server.enqueue(MockWebServerResources.OK_COOKIE);
    server.enqueue(new MockResponse()); //OK 200

    // Use a username and password to enable the cookie auth interceptor
    CloudantClient dbClient = CloudantClientHelper.newMockWebServerClientBuilder(server)
            .username("user")
            .password("password")
            .disableSSLAuthentication()
            .build();

    dbClient.getAllDbs();
}
 
Example #4
Source File: SslAuthenticationTest.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
/**
 * Connect to the local simple https server with SSL authentication disabled.
 */
@TestTemplate
public void localSslAuthenticationDisabled() throws Exception {

    // Build a client that connects to the mock server with SSL authentication disabled
    CloudantClient dbClient = CloudantClientHelper.newMockWebServerClientBuilder(server)
            .disableSSLAuthentication()
            .build();

    // Queue a 200 OK response
    server.enqueue(new MockResponse());

    // Make an arbitrary connection to the DB.
    dbClient.getAllDbs();

    // Test is successful if no exception is thrown, so no explicit check is needed.
}
 
Example #5
Source File: HttpTest.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
@TestTemplate
public void testReadBeforeExecute() throws Exception {
    HttpConnection conn = new HttpConnection("POST", new URL(dbResource.getDbURIWithUserInfo()),
            "application/json");
    ByteArrayInputStream bis = new ByteArrayInputStream(data.getBytes());

    // nothing read from stream
    assertEquals(data.getBytes().length, bis.available());

    conn.setRequestBody(bis);
    try {
        String response = conn.responseAsString();
        fail("IOException not thrown as expected instead had response " + response);
    } catch (IOException ioe) {
        ; // "Attempted to read response from server before calling execute()"
    }

    // stream was not read because execute() was not called
    assertEquals(data.getBytes().length, bis.available());
}
 
Example #6
Source File: UpdateWorkbasketAuthorizationsAccTest.java    From taskana with Apache License 2.0 6 votes vote down vote up
@WithAccessId(user = "user-1-1")
@WithAccessId(user = "taskadmin")
@TestTemplate
void should_ThrowException_When_UserIsNotAdminOrBusinessAdmin() {

  final WorkbasketService workbasketService = taskanaEngine.getWorkbasketService();

  WorkbasketAccessItem workbasketAccessItem =
      workbasketService.newWorkbasketAccessItem(
          "WBI:100000000000000000000000000000000008", "newAccessIdForUpdate");

  workbasketAccessItem.setPermCustom1(true);

  ThrowingCallable updateWorkbasketAccessItemCall =
      () -> {
        workbasketService.updateWorkbasketAccessItem(workbasketAccessItem);
      };

  assertThatThrownBy(updateWorkbasketAccessItemCall).isInstanceOf(NotAuthorizedException.class);
}
 
Example #7
Source File: HttpTest.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
/**
 * Test that the default maximum number of retries is reached and the backoff is of at least the
 * expected duration.
 *
 * @throws Exception
 */
@TestTemplate
public void test429BackoffMaxDefault() throws Exception {

    // Always respond 429 for this test
    mockWebServer.setDispatcher(MockWebServerResources.ALL_429);

    TestTimer t = TestTimer.startTimer();
    try {
        CloudantClient c = CloudantClientHelper.newMockWebServerClientBuilder(mockWebServer)
                .interceptors(Replay429Interceptor.WITH_DEFAULTS)
                .build();
        String response = c.executeRequest(Http.GET(c.getBaseUri())).responseAsString();
        fail("There should be a TooManyRequestsException instead had response " + response);
    } catch (TooManyRequestsException e) {
        long duration = t.stopTimer(TimeUnit.MILLISECONDS);
        // 3 backoff periods for 4 attempts: 250 + 500 + 1000 = 1750 ms
        assertTrue(duration >=
                1750, "The duration should be at least 1750 ms, but was " + duration);
        assertEquals(4, mockWebServer
                .getRequestCount(), "There should be 4 request attempts");
    }
}
 
Example #8
Source File: HttpTest.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
/**
 * Test that cookie authentication throws a CouchDbException if the credentials were bad.
 *
 * @throws Exception
 */
@TestTemplate
public void badCredsCookieThrows() {
    mockWebServer.enqueue(new MockResponse().setResponseCode(401));

    CloudantClient c = CloudantClientHelper.newMockWebServerClientBuilder(mockWebServer)
            .username("bad")
            .password("worse")
            .build();

    CouchDbException re =
            assertThrows(CouchDbException.class,
                    () -> c.executeRequest(Http.GET(c.getBaseUri())).responseAsString(),
                    "Bad credentials should throw a CouchDbException.");

    assertTrue(re.getMessage().startsWith("401 Credentials are incorrect for server"), "The " +
            "exception should have been for bad creds.");
}
 
Example #9
Source File: TerminateTaskAccTest.java    From taskana with Apache License 2.0 6 votes vote down vote up
@WithAccessId(user = "admin")
@WithAccessId(user = "taskadmin")
@TestTemplate
void should_TerminateTask_When_TaskStateIsClaimed()
    throws NotAuthorizedException, TaskNotFoundException, InvalidStateException {
  List<TaskSummary> taskSummaries =
      taskService.createTaskQuery().stateIn(TaskState.CLAIMED).list();
  assertThat(taskSummaries.size()).isEqualTo(20);

  long numTasksTerminated = taskService.createTaskQuery().stateIn(TaskState.TERMINATED).count();
  assertThat(numTasksTerminated).isEqualTo(5);

  taskService.terminateTask(taskSummaries.get(0).getId());
  long numTasksClaimed = taskService.createTaskQuery().stateIn(TaskState.CLAIMED).count();
  assertThat(numTasksClaimed).isEqualTo(19);
  numTasksTerminated = taskService.createTaskQuery().stateIn(TaskState.TERMINATED).count();
  assertThat(numTasksTerminated).isEqualTo(6);
}
 
Example #10
Source File: HttpTest.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
@TestTemplate
public void testCookieRenewOnPost() throws Exception {

    mockWebServer.enqueue(OK_COOKIE);
    mockWebServer.enqueue(new MockResponse().setResponseCode(403).setBody
            ("{\"error\":\"credentials_expired\", \"reason\":\"Session expired\"}\r\n"));
    mockWebServer.enqueue(OK_COOKIE);
    mockWebServer.enqueue(new MockResponse());

    CloudantClient c = CloudantClientHelper.newMockWebServerClientBuilder(mockWebServer)
            .username("a")
            .password("b")
            .build();

    HttpConnection request = Http.POST(mockWebServer.url("/").url(), "application/json");
    request.setRequestBody("{\"some\": \"json\"}");
    HttpConnection response = c.executeRequest(request);
    String responseStr = response.responseAsString();
    assertTrue(responseStr.isEmpty(), "There should be no response body on the mock response");
    response.getConnection().getResponseCode();
}
 
Example #11
Source File: HttpTest.java    From java-cloudant with Apache License 2.0 6 votes vote down vote up
@TestTemplate
public void test429IgnoreRetryAfter() throws Exception {
    mockWebServer.enqueue(MockWebServerResources.get429().addHeader("Retry-After", "1"));
    mockWebServer.enqueue(new MockResponse());

    TestTimer t = TestTimer.startTimer();
    CloudantClient c = CloudantClientHelper.newMockWebServerClientBuilder(mockWebServer)
            .interceptors(new Replay429Interceptor(1, 1, false))
            .build();

    String response = c.executeRequest(Http.GET(c.getBaseUri())).responseAsString();
    assertTrue(response.isEmpty(), "There should be no response body on the mock response");

    long duration = t.stopTimer(TimeUnit.MILLISECONDS);
    assertTrue(duration <
            1000, "The duration should be less than 1000 ms, but was " + duration);
    assertEquals(2, mockWebServer
            .getRequestCount(), "There should be 2 request attempts");
}
 
Example #12
Source File: MetamodelTest.java    From doma with Apache License 2.0 5 votes vote down vote up
@TestTemplate
@ExtendWith(ErrorInvocationContextProvider.class)
void error(Class<?> clazz, Message message, String... options) throws Exception {
  addOption(options);
  addProcessor(new EntityProcessor());
  addCompilationUnit(clazz);
  compile();
  assertFalse(getCompiledResult());
  assertMessage(message);
}
 
Example #13
Source File: ViewPaginationTests.java    From java-cloudant with Apache License 2.0 5 votes vote down vote up
/**
 * Check that we can page through a view where the number of results
 * is not an exact multiple of the number of pages. Check each page contains the documents
 * we expect.
 *
 * Page forward to the last page, back to the first page, forward to the last page and back to
 * the first page.
 */
@TestTemplate
public void partialLastPageAllTheWayInEachDirectionTwice(CheckPagination.Type type,
                                                         boolean descending,
                                                         boolean stateless) throws Exception {
    CheckPagination.newTest(type)
            .descending(descending)
            .docCount(5)
            .docsPerPage(2)
            .pageToPages(3, 1, 3, 1)
            .stateless(stateless)
            .runTest(db);
}
 
Example #14
Source File: HttpTest.java    From java-cloudant with Apache License 2.0 5 votes vote down vote up
@TestTemplate
public void inputStreamRetry() throws Exception {
    HttpConnection request = Http.POST(mockWebServer.url("/").url(), "application/json");
    final byte[] content = "abcde".getBytes("UTF-8");
    // Mock up an input stream that doesn't support marking
    request.setRequestBody(new UnmarkableInputStream(content));
    testInputStreamRetry(request, content);
}
 
Example #15
Source File: DatabaseURIHelperTest.java    From java-cloudant with Apache License 2.0 5 votes vote down vote up
@TestTemplate
public void buildChangesUri_options_optionsEncoded(String path) throws Exception {
    URI expected = new URI(uriBase + "/test/_changes?limit=100&since=%22%5B%5D%22");

    Map<String, Object> options = new HashMap<String, Object>();
    options.put("since", "\"[]\"");
    options.put("limit", 100);
    URI actual = helper(path + "/test").changesUri(options);
    Assertions.assertEquals(expected, actual);
}
 
Example #16
Source File: MetamodelTest.java    From doma with Apache License 2.0 5 votes vote down vote up
@TestTemplate
@ExtendWith(SuccessInvocationContextProvider.class)
void success(Class<?> clazz, URL expectedResourceUrl, String generatedClassName, String[] options)
    throws Exception {
  addOption(options);
  addProcessor(new EntityProcessor());
  addCompilationUnit(clazz);
  compile();
  assertEqualsGeneratedSourceWithResource(expectedResourceUrl, generatedClassName);
  assertTrue(getCompiledResult());
}
 
Example #17
Source File: HttpTest.java    From java-cloudant with Apache License 2.0 5 votes vote down vote up
@TestTemplate
public void inputStreamRetryBytes() throws Exception {
    HttpConnection request = Http.POST(mockWebServer.url("/").url(), "application/json");
    byte[] content = "abcde".getBytes("UTF-8");
    request.setRequestBody(content);
    testInputStreamRetry(request, content);
}
 
Example #18
Source File: EntityProcessorTest.java    From doma with Apache License 2.0 5 votes vote down vote up
@TestTemplate
@ExtendWith(ErrorInvocationContextProvider.class)
void error(Class clazz, Message message, String... options) throws Exception {
  addOption(options);
  addProcessor(new EntityProcessor());
  addCompilationUnit(clazz);
  compile();
  assertFalse(getCompiledResult());
  assertMessage(message);
}
 
Example #19
Source File: EntityProcessorTest.java    From doma with Apache License 2.0 5 votes vote down vote up
@TestTemplate
@ExtendWith(SuccessInvocationContextProvider.class)
void success(Class clazz, URL expectedResourceUrl, String generatedClassName, String[] options)
    throws Exception {
  addOption(options);
  addProcessor(new EntityProcessor());
  addCompilationUnit(clazz);
  compile();
  assertEqualsGeneratedSourceWithResource(expectedResourceUrl, generatedClassName);
  assertTrue(getCompiledResult());
}
 
Example #20
Source File: HttpTest.java    From java-cloudant with Apache License 2.0 5 votes vote down vote up
@TestTemplate
public void testCookieAuthWithPath() throws Exception {
    MockWebServer mockWebServer = new MockWebServer();
    mockWebServer.enqueue(OK_COOKIE);
    mockWebServer.enqueue(MockWebServerResources.JSON_OK);
    CloudantClient client = ClientBuilder.url(mockWebServer.url("/pathex").url())
            .username("user")
            .password("password")
            .build();
    //send single request
    client.database("test", true);
    assertThat("_session is the second element of the path",
            mockWebServer.takeRequest().getPath(),
            is("/pathex/_session"));
}
 
Example #21
Source File: SqlTest.java    From doma with Apache License 2.0 5 votes vote down vote up
@TestTemplate
@ExtendWith(ErrorInvocationContextProvider.class)
void error(Class clazz, Message message, String... options) throws Exception {
  addOption(options);
  addProcessor(new DaoProcessor());
  addCompilationUnit(clazz);
  compile();
  assertFalse(getCompiledResult());
  assertMessage(message);
}
 
Example #22
Source File: TransactionManagerTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@TestTemplate
void saveNewOrUpdate_persistsNewEntity() {
  assertEntityNotExist(theEntity);
  tm().transact(() -> tm().saveNewOrUpdate(theEntity));
  assertEntityExists(theEntity);
  assertThat(tm().transact(() -> tm().load(theEntity.key()))).isEqualTo(theEntity);
}
 
Example #23
Source File: SslAuthenticationTest.java    From java-cloudant with Apache License 2.0 5 votes vote down vote up
/**
 * Assert that building a client with a custom SSL factory first, then setting the
 * SSL Authentication disabled will throw an IllegalStateException.
 */
@TestTemplate
public void testCustomSSLFactorySSLAuthDisabled() {
    assertThrows(IllegalStateException.class, new Executable() {
        @Override
        public void execute() throws Throwable {

            CloudantClient dbClient = CloudantClientHelper.getClientBuilder()
                    .customSSLSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault())

                    .disableSSLAuthentication()
                    .build();
        }
    });
}
 
Example #24
Source File: ExternalDomainProcessorTest.java    From doma with Apache License 2.0 5 votes vote down vote up
@TestTemplate
@ExtendWith(SuccessInvocationContextProvider.class)
void success(Class clazz, URL expectedResourceUrl, String generatedClassName) throws Exception {
  addProcessor(new ExternalDomainProcessor());
  addCompilationUnit(clazz);
  compile();
  assertEqualsGeneratedSourceWithResource(expectedResourceUrl, generatedClassName);
  assertTrue(getCompiledResult());
}
 
Example #25
Source File: HttpTest.java    From java-cloudant with Apache License 2.0 5 votes vote down vote up
@TestTemplate
@DisabledWithIam
@RequiresCloudant
public void testCookieAuthWithoutRetry() throws IOException {
    CookieInterceptor interceptor = new CookieInterceptor(CloudantClientHelper.SERVER_USER,
            CloudantClientHelper.SERVER_PASSWORD, clientResource.get().getBaseUri().toString());

    HttpConnection conn = new HttpConnection("POST", dbResource.get().getDBUri().toURL(),
            "application/json");
    conn.responseInterceptors.add(interceptor);
    conn.requestInterceptors.add(interceptor);
    ByteArrayInputStream bis = new ByteArrayInputStream(data.getBytes());

    // nothing read from stream
    assertEquals(data.getBytes().length, bis.available());

    conn.setRequestBody(bis);
    HttpConnection responseConn = conn.execute();

    // stream was read to end
    assertEquals(0, bis.available());
    assertEquals(2, responseConn.getConnection().getResponseCode() / 100);

    //check the json
    Gson gson = new Gson();
    InputStream is = responseConn.responseAsInputStream();
    try {
        JsonObject response = gson.fromJson(new InputStreamReader(is), JsonObject.class);
        assertTrue(response.has("ok"));
        assertTrue(response.get("ok").getAsBoolean());
        assertTrue(response.has("id"));
        assertTrue(response.has("rev"));
    } finally {
        is.close();
    }
}
 
Example #26
Source File: TransactionManagerTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@TestTemplate
void transact_hasNoEffectWithPartialSuccess() {
  assertEntityNotExist(theEntity);
  assertThrows(
      RuntimeException.class,
      () ->
          tm().transact(
                  () -> {
                    tm().saveNew(theEntity);
                    throw new RuntimeException();
                  }));
  assertEntityNotExist(theEntity);
}
 
Example #27
Source File: HttpTest.java    From java-cloudant with Apache License 2.0 5 votes vote down vote up
/**
 * Test that chunking is used when input stream length is not known.
 *
 * @throws Exception
 */
@TestTemplate
public void testChunking() throws Exception {
    mockWebServer.enqueue(new MockResponse());
    final int chunkSize = 1024 * 8;
    final int chunks = 50 * 4;
    CloudantClient client = CloudantClientHelper.newMockWebServerClientBuilder(mockWebServer)
            .build();
    // POST some large random data
    String response = client.executeRequest(Http.POST(mockWebServer.url("/").url(),
            "text/plain")
            .setRequestBody(new RandomInputStreamGenerator(chunks * chunkSize)))
            .responseAsString();
    assertTrue(response.isEmpty(), "There should be no response body on the mock response");
    assertEquals(1, mockWebServer
            .getRequestCount(), "There should have been 1 request");
    RecordedRequest request = MockWebServerResources.takeRequestWithTimeout(mockWebServer);
    assertNotNull(request, "The recorded request should not be null");
    assertNull(request.getHeader("Content-Length"), "There should be no Content-Length header");
    assertEquals("chunked", request.getHeader
            ("Transfer-Encoding"), "The Transfer-Encoding should be chunked");

    // It would be nice to assert that we got the chunk sizes we were expecting, but sadly the
    // HttpURLConnection and ChunkedOutputStream only use the chunkSize as a suggestion and seem
    // to use the buffer size instead. The best assertion we can make is that we did receive
    // multiple chunks.
    assertTrue(request.getChunkSizes().size() > 1, "There should have been at least 2 chunks");
}
 
Example #28
Source File: ViewPaginationTests.java    From java-cloudant with Apache License 2.0 5 votes vote down vote up
/**
 * Check that we can page through a view where the number of results
 * is not an exact multiple of the number of pages. Check each page contains the documents
 * we expect.
 *
 * Page part way forward, and part way back a few times before paging to the last page.
 */
@TestTemplate
public void partialLastPagePartWayInEachDirection(CheckPagination.Type type,
                                                  boolean descending,
                                                  boolean stateless) throws Exception {
    CheckPagination.newTest(type)
            .descending(descending)
            .docCount(28)
            .docsPerPage(5)
            .pageToPages(4, 2, 5, 3, 4, 2, 6)
            .stateless(stateless)
            .runTest(db);
}
 
Example #29
Source File: HttpTest.java    From java-cloudant with Apache License 2.0 5 votes vote down vote up
/**
 * Test the global number of retries
 *
 * @throws Exception
 */
@TestTemplate
public void testHttpConnectionRetries() throws Exception {
    // Just return 200 OK
    mockWebServer.setDispatcher(new MockWebServerResources.ConstantResponseDispatcher(200));

    CloudantClient c = CloudantClientHelper.newMockWebServerClientBuilder(mockWebServer)
            .interceptors(new HttpConnectionResponseInterceptor() {
                @Override
                public HttpConnectionInterceptorContext interceptResponse
                        (HttpConnectionInterceptorContext context) {
                    // At least do something with the connection, otherwise we risk breaking it
                    try {
                        context.connection.getConnection().getResponseCode();
                    } catch (IOException e) {
                        fail("IOException getting response code");
                    }
                    // Set to always replay
                    context.replayRequest = true;
                    return context;
                }
            })
            .build();

    String response = c.executeRequest(Http.GET(c.getBaseUri()).setNumberOfRetries(5))
            .responseAsString();
    assertTrue(response.isEmpty(), "There should be no response body on the mock response");

    assertEquals(5, mockWebServer
            .getRequestCount(), "There should be 5 request attempts");
}
 
Example #30
Source File: DatabaseURIHelperTest.java    From java-cloudant with Apache License 2.0 5 votes vote down vote up
@TestTemplate
public void buildPartitionedDatabaseDocumentUriWithNullPartitionKey(String path) throws Exception {
    URI expected = new URI(uriBase + "/test/documentId");

    URI actual = helper(path + "/test").partition(null).documentId("documentId").build();
    Assertions.assertEquals(expected, actual);
}