Java Code Examples for org.springframework.test.context.jdbc.Sql.ExecutionPhase

The following examples show how to use org.springframework.test.context.jdbc.Sql.ExecutionPhase. These examples are extracted from open source projects. 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
/**
 * Execute SQL scripts configured via {@link Sql @Sql} for the supplied
 * {@link TestContext} and {@link ExecutionPhase}.
 */
private void executeSqlScripts(TestContext testContext, ExecutionPhase executionPhase) throws Exception {
	boolean classLevel = false;

	Set<Sql> sqlAnnotations = AnnotatedElementUtils.getMergedRepeatableAnnotations(
			testContext.getTestMethod(), Sql.class, SqlGroup.class);
	if (sqlAnnotations.isEmpty()) {
		sqlAnnotations = AnnotatedElementUtils.getMergedRepeatableAnnotations(
				testContext.getTestClass(), Sql.class, SqlGroup.class);
		if (!sqlAnnotations.isEmpty()) {
			classLevel = true;
		}
	}

	for (Sql sql : sqlAnnotations) {
		executeSqlScripts(sql, executionPhase, testContext, classLevel);
	}
}
 
Example 2
/**
 * Execute SQL scripts configured via {@link Sql @Sql} for the supplied
 * {@link TestContext} and {@link ExecutionPhase}.
 */
private void executeSqlScripts(TestContext testContext, ExecutionPhase executionPhase) throws Exception {
	boolean classLevel = false;

	Set<Sql> sqlAnnotations = AnnotatedElementUtils.getMergedRepeatableAnnotations(
			testContext.getTestMethod(), Sql.class, SqlGroup.class);
	if (sqlAnnotations.isEmpty()) {
		sqlAnnotations = AnnotatedElementUtils.getMergedRepeatableAnnotations(
				testContext.getTestClass(), Sql.class, SqlGroup.class);
		if (!sqlAnnotations.isEmpty()) {
			classLevel = true;
		}
	}

	for (Sql sql : sqlAnnotations) {
		executeSqlScripts(sql, executionPhase, testContext, classLevel);
	}
}
 
Example 3
Source Project: apollo   Source File: AccessKeyRepositoryTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@Sql(scripts = "/sql/accesskey-test.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/sql/clean.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
public void testFindFirst500ByDataChangeLastModifiedTimeGreaterThanOrderByDataChangeLastModifiedTime() {
  Instant instant = LocalDateTime.of(2019, 12, 19, 13, 44, 20)
      .atZone(ZoneId.systemDefault())
      .toInstant();
  Date date = Date.from(instant);

  List<AccessKey> accessKeyList = accessKeyRepository
      .findFirst500ByDataChangeLastModifiedTimeGreaterThanOrderByDataChangeLastModifiedTimeAsc(date);

  assertThat(accessKeyList).hasSize(2);
  assertThat(accessKeyList.get(0).getAppId()).isEqualTo("100004458");
  assertThat(accessKeyList.get(0).getSecret()).isEqualTo("4003c4d7783443dc9870932bebf3b7fe");
  assertThat(accessKeyList.get(1).getAppId()).isEqualTo("100004458");
  assertThat(accessKeyList.get(1).getSecret()).isEqualTo("c715cbc80fc44171b43732c3119c9456");
}
 
Example 4
Source Project: apollo   Source File: ControllerIntegrationExceptionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
public void testCreateFailed() {
  AppDTO dto = generateSampleDTOData();

  when(adminService.createNewApp(any(App.class))).thenThrow(new RuntimeException("save failed"));

  try {
    restTemplate.postForEntity(getBaseAppUrl(), dto, AppDTO.class);
  } catch (HttpStatusCodeException e) {
    @SuppressWarnings("unchecked")
    Map<String, String> attr = gson.fromJson(e.getResponseBodyAsString(), Map.class);
    Assert.assertEquals("save failed", attr.get("message"));
  }
  App savedApp = appService.findOne(dto.getAppId());
  Assert.assertNull(savedApp);
}
 
Example 5
Source Project: apollo   Source File: AppControllerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
public void testCheckIfAppIdUnique() {
  AppDTO dto = generateSampleDTOData();
  ResponseEntity<AppDTO> response =
      restTemplate.postForEntity(getBaseAppUrl(), dto, AppDTO.class);
  AppDTO result = response.getBody();
  Assert.assertEquals(HttpStatus.OK, response.getStatusCode());
  Assert.assertEquals(dto.getAppId(), result.getAppId());
  Assert.assertTrue(result.getId() > 0);

  Boolean falseUnique =
      restTemplate.getForObject(getBaseAppUrl() + dto.getAppId() + "/unique", Boolean.class);
  Assert.assertFalse(falseUnique);
  Boolean trueUnique = restTemplate
      .getForObject(getBaseAppUrl() + dto.getAppId() + "true" + "/unique", Boolean.class);
  Assert.assertTrue(trueUnique);
}
 
Example 6
Source Project: apollo   Source File: AppControllerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
public void testCreateTwice() {
  AppDTO dto = generateSampleDTOData();
  ResponseEntity<AppDTO> response =
      restTemplate.postForEntity(getBaseAppUrl(), dto, AppDTO.class);
  AppDTO first = response.getBody();
  Assert.assertEquals(HttpStatus.OK, response.getStatusCode());
  Assert.assertEquals(dto.getAppId(), first.getAppId());
  Assert.assertTrue(first.getId() > 0);

  App savedApp = appRepository.findById(first.getId()).orElse(null);
  Assert.assertEquals(dto.getAppId(), savedApp.getAppId());
  Assert.assertNotNull(savedApp.getDataChangeCreatedTime());

  try {
    restTemplate.postForEntity(getBaseAppUrl(), dto, AppDTO.class);
  }catch (HttpClientErrorException e){
    Assert.assertEquals(HttpStatus.BAD_REQUEST, e.getStatusCode());
  }

}
 
Example 7
/**
 * Execute SQL scripts configured via {@link Sql @Sql} for the supplied
 * {@link TestContext} and {@link ExecutionPhase}.
 */
private void executeSqlScripts(TestContext testContext, ExecutionPhase executionPhase) throws Exception {
	boolean classLevel = false;

	Set<Sql> sqlAnnotations = AnnotationUtils.getRepeatableAnnotations(testContext.getTestMethod(), Sql.class,
		SqlGroup.class);
	if (sqlAnnotations.isEmpty()) {
		sqlAnnotations = AnnotationUtils.getRepeatableAnnotations(testContext.getTestClass(), Sql.class,
			SqlGroup.class);
		if (!sqlAnnotations.isEmpty()) {
			classLevel = true;
		}
	}

	for (Sql sql : sqlAnnotations) {
		executeSqlScripts(sql, executionPhase, testContext, classLevel);
	}
}
 
Example 8
Source Project: learning-code   Source File: SpringDataBaseTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@Sql(value = "classpath:drop.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
public void testFindByUsername() {
  String username = "data.sql";
  String password = "123456";
  User user = userService.findByUsername(username);
  Assert.assertThat(user == null ? null : user.getPassword(), Matchers.equalTo(password));
}
 
Example 9
Source Project: apollo   Source File: AccessKeyRepositoryTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@Sql(scripts = "/sql/accesskey-test.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/sql/clean.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
public void testFindByAppId() {
  String appId = "someAppId";

  List<AccessKey> accessKeyList = accessKeyRepository.findByAppId(appId);

  assertThat(accessKeyList).hasSize(1);
  assertThat(accessKeyList.get(0).getAppId()).isEqualTo(appId);
  assertThat(accessKeyList.get(0).getSecret()).isEqualTo("someSecret");
}
 
Example 10
Source Project: apollo   Source File: AppControllerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
public void testCreate() {
  AppDTO dto = generateSampleDTOData();
  ResponseEntity<AppDTO> response =
      restTemplate.postForEntity(getBaseAppUrl(), dto, AppDTO.class);
  AppDTO result = response.getBody();
  Assert.assertEquals(HttpStatus.OK, response.getStatusCode());
  Assert.assertEquals(dto.getAppId(), result.getAppId());
  Assert.assertTrue(result.getId() > 0);

  App savedApp = appRepository.findById(result.getId()).orElse(null);
  Assert.assertEquals(dto.getAppId(), savedApp.getAppId());
  Assert.assertNotNull(savedApp.getDataChangeCreatedTime());
}
 
Example 11
Source Project: apollo   Source File: AppControllerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
public void testFind() {
  AppDTO dto = generateSampleDTOData();
  App app = BeanUtils.transform(App.class, dto);
  app = appRepository.save(app);

  AppDTO result = restTemplate.getForObject(getBaseAppUrl() + dto.getAppId(), AppDTO.class);
  Assert.assertEquals(dto.getAppId(), result.getAppId());
  Assert.assertEquals(dto.getName(), result.getName());
}
 
Example 12
Source Project: apollo   Source File: AppControllerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
public void testDelete() {
  AppDTO dto = generateSampleDTOData();
  App app = BeanUtils.transform(App.class, dto);
  app = appRepository.save(app);

  restTemplate.delete("http://localhost:{port}/apps/{appId}?operator={operator}", port, app.getAppId(), "test");

  App deletedApp = appRepository.findById(app.getId()).orElse(null);
  Assert.assertNull(deletedApp);
}
 
Example 13
Source Project: apollo   Source File: AppControllerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
public void shouldFailedWhenAppIdIsInvalid() {
  AppDTO dto = generateSampleDTOData();
  dto.setAppId("invalid app id");
  try {
    restTemplate.postForEntity(getBaseAppUrl(), dto, String.class);
    Assert.fail("Should throw");
  } catch (HttpClientErrorException e) {
    Assert.assertEquals(HttpStatus.BAD_REQUEST, e.getStatusCode());
    Assert.assertThat(new String(e.getResponseBodyAsByteArray()), containsString(InputValidator.INVALID_CLUSTER_NAMESPACE_MESSAGE));
  }
}
 
Example 14
/**
 * Execute SQL scripts configured via {@link Sql @Sql} for the supplied
 * {@link TestContext} <em>before</em> the current test method.
 */
@Override
public void beforeTestMethod(TestContext testContext) throws Exception {
	executeSqlScripts(testContext, ExecutionPhase.BEFORE_TEST_METHOD);
}
 
Example 15
/**
 * Execute SQL scripts configured via {@link Sql @Sql} for the supplied
 * {@link TestContext} <em>after</em> the current test method.
 */
@Override
public void afterTestMethod(TestContext testContext) throws Exception {
	executeSqlScripts(testContext, ExecutionPhase.AFTER_TEST_METHOD);
}
 
Example 16
/**
 * Execute the SQL scripts configured via the supplied {@link Sql @Sql}
 * annotation for the given {@link ExecutionPhase} and {@link TestContext}.
 * <p>Special care must be taken in order to properly support the configured
 * {@link SqlConfig#transactionMode}.
 * @param sql the {@code @Sql} annotation to parse
 * @param executionPhase the current execution phase
 * @param testContext the current {@code TestContext}
 * @param classLevel {@code true} if {@link Sql @Sql} was declared at the class level
 */
private void executeSqlScripts(Sql sql, ExecutionPhase executionPhase, TestContext testContext, boolean classLevel)
		throws Exception {

	if (executionPhase != sql.executionPhase()) {
		return;
	}

	MergedSqlConfig mergedSqlConfig = new MergedSqlConfig(sql.config(), testContext.getTestClass());
	if (logger.isDebugEnabled()) {
		logger.debug(String.format("Processing %s for execution phase [%s] and test context %s.",
				mergedSqlConfig, executionPhase, testContext));
	}

	final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
	populator.setSqlScriptEncoding(mergedSqlConfig.getEncoding());
	populator.setSeparator(mergedSqlConfig.getSeparator());
	populator.setCommentPrefix(mergedSqlConfig.getCommentPrefix());
	populator.setBlockCommentStartDelimiter(mergedSqlConfig.getBlockCommentStartDelimiter());
	populator.setBlockCommentEndDelimiter(mergedSqlConfig.getBlockCommentEndDelimiter());
	populator.setContinueOnError(mergedSqlConfig.getErrorMode() == ErrorMode.CONTINUE_ON_ERROR);
	populator.setIgnoreFailedDrops(mergedSqlConfig.getErrorMode() == ErrorMode.IGNORE_FAILED_DROPS);

	String[] scripts = getScripts(sql, testContext, classLevel);
	scripts = TestContextResourceUtils.convertToClasspathResourcePaths(testContext.getTestClass(), scripts);
	List<Resource> scriptResources = TestContextResourceUtils.convertToResourceList(
			testContext.getApplicationContext(), scripts);
	for (String stmt : sql.statements()) {
		if (StringUtils.hasText(stmt)) {
			stmt = stmt.trim();
			scriptResources.add(new ByteArrayResource(stmt.getBytes(), "from inlined SQL statement: " + stmt));
		}
	}
	populator.setScripts(scriptResources.toArray(new Resource[0]));
	if (logger.isDebugEnabled()) {
		logger.debug("Executing SQL scripts: " + ObjectUtils.nullSafeToString(scriptResources));
	}

	String dsName = mergedSqlConfig.getDataSource();
	String tmName = mergedSqlConfig.getTransactionManager();
	DataSource dataSource = TestContextTransactionUtils.retrieveDataSource(testContext, dsName);
	PlatformTransactionManager txMgr = TestContextTransactionUtils.retrieveTransactionManager(testContext, tmName);
	boolean newTxRequired = (mergedSqlConfig.getTransactionMode() == TransactionMode.ISOLATED);

	if (txMgr == null) {
		Assert.state(!newTxRequired, () -> String.format("Failed to execute SQL scripts for test context %s: " +
				"cannot execute SQL scripts using Transaction Mode " +
				"[%s] without a PlatformTransactionManager.", testContext, TransactionMode.ISOLATED));
		Assert.state(dataSource != null, () -> String.format("Failed to execute SQL scripts for test context %s: " +
				"supply at least a DataSource or PlatformTransactionManager.", testContext));
		// Execute scripts directly against the DataSource
		populator.execute(dataSource);
	}
	else {
		DataSource dataSourceFromTxMgr = getDataSourceFromTransactionManager(txMgr);
		// Ensure user configured an appropriate DataSource/TransactionManager pair.
		if (dataSource != null && dataSourceFromTxMgr != null && !dataSource.equals(dataSourceFromTxMgr)) {
			throw new IllegalStateException(String.format("Failed to execute SQL scripts for test context %s: " +
					"the configured DataSource [%s] (named '%s') is not the one associated with " +
					"transaction manager [%s] (named '%s').", testContext, dataSource.getClass().getName(),
					dsName, txMgr.getClass().getName(), tmName));
		}
		if (dataSource == null) {
			dataSource = dataSourceFromTxMgr;
			Assert.state(dataSource != null, () -> String.format("Failed to execute SQL scripts for " +
					"test context %s: could not obtain DataSource from transaction manager [%s] (named '%s').",
					testContext, txMgr.getClass().getName(), tmName));
		}
		final DataSource finalDataSource = dataSource;
		int propagation = (newTxRequired ? TransactionDefinition.PROPAGATION_REQUIRES_NEW :
				TransactionDefinition.PROPAGATION_REQUIRED);
		TransactionAttribute txAttr = TestContextTransactionUtils.createDelegatingTransactionAttribute(
				testContext, new DefaultTransactionAttribute(propagation));
		new TransactionTemplate(txMgr, txAttr).execute(status -> {
			populator.execute(finalDataSource);
			return null;
		});
	}
}
 
Example 17
/**
 * Execute SQL scripts configured via {@link Sql @Sql} for the supplied
 * {@link TestContext} <em>before</em> the current test method.
 */
@Override
public void beforeTestMethod(TestContext testContext) throws Exception {
	executeSqlScripts(testContext, ExecutionPhase.BEFORE_TEST_METHOD);
}
 
Example 18
/**
 * Execute SQL scripts configured via {@link Sql @Sql} for the supplied
 * {@link TestContext} <em>after</em> the current test method.
 */
@Override
public void afterTestMethod(TestContext testContext) throws Exception {
	executeSqlScripts(testContext, ExecutionPhase.AFTER_TEST_METHOD);
}
 
Example 19
/**
 * Execute the SQL scripts configured via the supplied {@link Sql @Sql}
 * annotation for the given {@link ExecutionPhase} and {@link TestContext}.
 * <p>Special care must be taken in order to properly support the configured
 * {@link SqlConfig#transactionMode}.
 * @param sql the {@code @Sql} annotation to parse
 * @param executionPhase the current execution phase
 * @param testContext the current {@code TestContext}
 * @param classLevel {@code true} if {@link Sql @Sql} was declared at the class level
 */
private void executeSqlScripts(Sql sql, ExecutionPhase executionPhase, TestContext testContext, boolean classLevel)
		throws Exception {

	if (executionPhase != sql.executionPhase()) {
		return;
	}

	MergedSqlConfig mergedSqlConfig = new MergedSqlConfig(sql.config(), testContext.getTestClass());
	if (logger.isDebugEnabled()) {
		logger.debug(String.format("Processing %s for execution phase [%s] and test context %s.",
				mergedSqlConfig, executionPhase, testContext));
	}

	final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
	populator.setSqlScriptEncoding(mergedSqlConfig.getEncoding());
	populator.setSeparator(mergedSqlConfig.getSeparator());
	populator.setCommentPrefix(mergedSqlConfig.getCommentPrefix());
	populator.setBlockCommentStartDelimiter(mergedSqlConfig.getBlockCommentStartDelimiter());
	populator.setBlockCommentEndDelimiter(mergedSqlConfig.getBlockCommentEndDelimiter());
	populator.setContinueOnError(mergedSqlConfig.getErrorMode() == ErrorMode.CONTINUE_ON_ERROR);
	populator.setIgnoreFailedDrops(mergedSqlConfig.getErrorMode() == ErrorMode.IGNORE_FAILED_DROPS);

	String[] scripts = getScripts(sql, testContext, classLevel);
	scripts = TestContextResourceUtils.convertToClasspathResourcePaths(testContext.getTestClass(), scripts);
	List<Resource> scriptResources = TestContextResourceUtils.convertToResourceList(
			testContext.getApplicationContext(), scripts);
	for (String stmt : sql.statements()) {
		if (StringUtils.hasText(stmt)) {
			stmt = stmt.trim();
			scriptResources.add(new ByteArrayResource(stmt.getBytes(), "from inlined SQL statement: " + stmt));
		}
	}
	populator.setScripts(scriptResources.toArray(new Resource[0]));
	if (logger.isDebugEnabled()) {
		logger.debug("Executing SQL scripts: " + ObjectUtils.nullSafeToString(scriptResources));
	}

	String dsName = mergedSqlConfig.getDataSource();
	String tmName = mergedSqlConfig.getTransactionManager();
	DataSource dataSource = TestContextTransactionUtils.retrieveDataSource(testContext, dsName);
	PlatformTransactionManager txMgr = TestContextTransactionUtils.retrieveTransactionManager(testContext, tmName);
	boolean newTxRequired = (mergedSqlConfig.getTransactionMode() == TransactionMode.ISOLATED);

	if (txMgr == null) {
		Assert.state(!newTxRequired, () -> String.format("Failed to execute SQL scripts for test context %s: " +
				"cannot execute SQL scripts using Transaction Mode " +
				"[%s] without a PlatformTransactionManager.", testContext, TransactionMode.ISOLATED));
		Assert.state(dataSource != null, () -> String.format("Failed to execute SQL scripts for test context %s: " +
				"supply at least a DataSource or PlatformTransactionManager.", testContext));
		// Execute scripts directly against the DataSource
		populator.execute(dataSource);
	}
	else {
		DataSource dataSourceFromTxMgr = getDataSourceFromTransactionManager(txMgr);
		// Ensure user configured an appropriate DataSource/TransactionManager pair.
		if (dataSource != null && dataSourceFromTxMgr != null && !dataSource.equals(dataSourceFromTxMgr)) {
			throw new IllegalStateException(String.format("Failed to execute SQL scripts for test context %s: " +
					"the configured DataSource [%s] (named '%s') is not the one associated with " +
					"transaction manager [%s] (named '%s').", testContext, dataSource.getClass().getName(),
					dsName, txMgr.getClass().getName(), tmName));
		}
		if (dataSource == null) {
			dataSource = dataSourceFromTxMgr;
			Assert.state(dataSource != null, () -> String.format("Failed to execute SQL scripts for " +
					"test context %s: could not obtain DataSource from transaction manager [%s] (named '%s').",
					testContext, txMgr.getClass().getName(), tmName));
		}
		final DataSource finalDataSource = dataSource;
		int propagation = (newTxRequired ? TransactionDefinition.PROPAGATION_REQUIRES_NEW :
				TransactionDefinition.PROPAGATION_REQUIRED);
		TransactionAttribute txAttr = TestContextTransactionUtils.createDelegatingTransactionAttribute(
				testContext, new DefaultTransactionAttribute(propagation));
		new TransactionTemplate(txMgr, txAttr).execute(status -> {
			populator.execute(finalDataSource);
			return null;
		});
	}
}
 
Example 20
Source Project: apollo   Source File: ReleaseControllerTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
@Sql(scripts = "/controller/test-release.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
public void testReleaseBuild() {
  String appId = "someAppId";
  AppDTO app =
      restTemplate.getForObject("http://localhost:" + port + "/apps/" + appId, AppDTO.class);

  ClusterDTO cluster = restTemplate.getForObject(
      "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/default",
      ClusterDTO.class);

  NamespaceDTO namespace =
      restTemplate.getForObject("http://localhost:" + port + "/apps/" + app.getAppId()
          + "/clusters/" + cluster.getName() + "/namespaces/application", NamespaceDTO.class);

  Assert.assertEquals("someAppId", app.getAppId());
  Assert.assertEquals("default", cluster.getName());
  Assert.assertEquals("application", namespace.getNamespaceName());

  ItemDTO[] items =
      restTemplate.getForObject(
          "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/"
              + cluster.getName() + "/namespaces/" + namespace.getNamespaceName() + "/items",
          ItemDTO[].class);
  Assert.assertEquals(3, items.length);

  HttpHeaders headers = new HttpHeaders();
  headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
  MultiValueMap<String, String> parameters = new LinkedMultiValueMap<String, String>();
  parameters.add("name", "someReleaseName");
  parameters.add("comment", "someComment");
  parameters.add("operator", "test");
  HttpEntity<MultiValueMap<String, String>> entity =
      new HttpEntity<MultiValueMap<String, String>>(parameters, headers);
  ResponseEntity<ReleaseDTO> response = restTemplate.postForEntity(
      "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/" + cluster.getName()
          + "/namespaces/" + namespace.getNamespaceName() + "/releases",
      entity, ReleaseDTO.class);
  Assert.assertEquals(HttpStatus.OK, response.getStatusCode());
  ReleaseDTO release = response.getBody();
  Assert.assertEquals("someReleaseName", release.getName());
  Assert.assertEquals("someComment", release.getComment());
  Assert.assertEquals("someAppId", release.getAppId());
  Assert.assertEquals("default", release.getClusterName());
  Assert.assertEquals("application", release.getNamespaceName());

  Map<String, String> configurations = new HashMap<String, String>();
  configurations.put("k1", "v1");
  configurations.put("k2", "v2");
  configurations.put("k3", "v3");
  Gson gson = new Gson();
  Assert.assertEquals(gson.toJson(configurations), release.getConfigurations());
}
 
Example 21
Source Project: apollo   Source File: ItemSetControllerTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
@Sql(scripts = "/controller/test-itemset.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
public void testItemSetCreated() {
  String appId = "someAppId";
  AppDTO app =
      restTemplate.getForObject("http://localhost:" + port + "/apps/" + appId, AppDTO.class);

  ClusterDTO cluster = restTemplate.getForObject(
      "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/default",
      ClusterDTO.class);

  NamespaceDTO namespace =
      restTemplate.getForObject("http://localhost:" + port + "/apps/" + app.getAppId()
          + "/clusters/" + cluster.getName() + "/namespaces/application", NamespaceDTO.class);

  Assert.assertEquals("someAppId", app.getAppId());
  Assert.assertEquals("default", cluster.getName());
  Assert.assertEquals("application", namespace.getNamespaceName());

  ItemChangeSets itemSet = new ItemChangeSets();
  itemSet.setDataChangeLastModifiedBy("created");
  RestTemplate createdTemplate = (new TestRestTemplate()).getRestTemplate();
  createdTemplate.setMessageConverters(restTemplate.getMessageConverters());
  
  int createdSize = 3;
  for (int i = 0; i < createdSize; i++) {
    ItemDTO item = new ItemDTO();
    item.setNamespaceId(namespace.getId());
    item.setKey("key_" + i);
    item.setValue("created_value_" + i);
    itemSet.addCreateItem(item);
  }

  ResponseEntity<Void> response =
      createdTemplate.postForEntity(
          "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/"
              + cluster.getName() + "/namespaces/" + namespace.getNamespaceName() + "/itemset",
          itemSet, Void.class);
  Assert.assertEquals(HttpStatus.OK, response.getStatusCode());
  List<Item> items = itemRepository.findByNamespaceIdOrderByLineNumAsc(namespace.getId());
  Assert.assertEquals(createdSize, items.size());
  Item item0 = items.get(0);
  Assert.assertEquals("key_0", item0.getKey());
  Assert.assertEquals("created_value_0", item0.getValue());
  Assert.assertEquals("created", item0.getDataChangeCreatedBy());
  Assert.assertNotNull(item0.getDataChangeCreatedTime());
}
 
Example 22
Source Project: apollo   Source File: ItemSetControllerTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
@Sql(scripts = "/controller/test-itemset.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
public void testItemSetUpdated() {
  String appId = "someAppId";
  AppDTO app =
      restTemplate.getForObject("http://localhost:" + port + "/apps/" + appId, AppDTO.class);

  ClusterDTO cluster = restTemplate.getForObject(
      "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/default",
      ClusterDTO.class);

  NamespaceDTO namespace =
      restTemplate.getForObject("http://localhost:" + port + "/apps/" + app.getAppId()
          + "/clusters/" + cluster.getName() + "/namespaces/application", NamespaceDTO.class);

  Assert.assertEquals("someAppId", app.getAppId());
  Assert.assertEquals("default", cluster.getName());
  Assert.assertEquals("application", namespace.getNamespaceName());

  ItemChangeSets createChangeSet = new ItemChangeSets();
  createChangeSet.setDataChangeLastModifiedBy("created");
  RestTemplate createdRestTemplate = (new TestRestTemplate()).getRestTemplate();
  createdRestTemplate.setMessageConverters(restTemplate.getMessageConverters());
  
  int createdSize = 3;
  for (int i = 0; i < createdSize; i++) {
    ItemDTO item = new ItemDTO();
    item.setNamespaceId(namespace.getId());
    item.setKey("key_" + i);
    item.setValue("created_value_" + i);
    createChangeSet.addCreateItem(item);
  }

  ResponseEntity<Void> response = createdRestTemplate.postForEntity(
      "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/" + cluster.getName()
          + "/namespaces/" + namespace.getNamespaceName() + "/itemset",
      createChangeSet, Void.class);
  Assert.assertEquals(HttpStatus.OK, response.getStatusCode());

  ItemDTO[] items =
      createdRestTemplate.getForObject(
          "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/"
              + cluster.getName() + "/namespaces/" + namespace.getNamespaceName() + "/items",
          ItemDTO[].class);

  ItemChangeSets updateChangeSet = new ItemChangeSets();
  updateChangeSet.setDataChangeLastModifiedBy("updated");

  RestTemplate updatedRestTemplate = (new TestRestTemplate()).getRestTemplate();
  updatedRestTemplate.setMessageConverters(restTemplate.getMessageConverters());
  
  int updatedSize = 2;
  for (int i = 0; i < updatedSize; i++) {
    items[i].setValue("updated_value_" + i);
    updateChangeSet.addUpdateItem(items[i]);
  }

  response = updatedRestTemplate.postForEntity(
      "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/" + cluster.getName()
          + "/namespaces/" + namespace.getNamespaceName() + "/itemset",
      updateChangeSet, Void.class);
  Assert.assertEquals(HttpStatus.OK, response.getStatusCode());
  List<Item> savedItems = itemRepository.findByNamespaceIdOrderByLineNumAsc(namespace.getId());
  Assert.assertEquals(createdSize, savedItems.size());
  Item item0 = savedItems.get(0);
  Assert.assertEquals("key_0", item0.getKey());
  Assert.assertEquals("updated_value_0", item0.getValue());
  Assert.assertEquals("created", item0.getDataChangeCreatedBy());
  Assert.assertEquals("updated", item0.getDataChangeLastModifiedBy());
  Assert.assertNotNull(item0.getDataChangeCreatedTime());
  Assert.assertNotNull(item0.getDataChangeLastModifiedTime());
}
 
Example 23
Source Project: apollo   Source File: ItemSetControllerTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
@Sql(scripts = "/controller/test-itemset.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
public void testItemSetDeleted() {
  String appId = "someAppId";
  AppDTO app =
      restTemplate.getForObject("http://localhost:" + port + "/apps/" + appId, AppDTO.class);

  ClusterDTO cluster = restTemplate.getForObject(
      "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/default",
      ClusterDTO.class);

  NamespaceDTO namespace =
      restTemplate.getForObject("http://localhost:" + port + "/apps/" + app.getAppId()
          + "/clusters/" + cluster.getName() + "/namespaces/application", NamespaceDTO.class);

  Assert.assertEquals("someAppId", app.getAppId());
  Assert.assertEquals("default", cluster.getName());
  Assert.assertEquals("application", namespace.getNamespaceName());

  ItemChangeSets createChangeSet = new ItemChangeSets();
  createChangeSet.setDataChangeLastModifiedBy("created");
  RestTemplate createdTemplate = (new TestRestTemplate()).getRestTemplate();
  createdTemplate.setMessageConverters(restTemplate.getMessageConverters());
  
  int createdSize = 3;
  for (int i = 0; i < createdSize; i++) {
    ItemDTO item = new ItemDTO();
    item.setNamespaceId(namespace.getId());
    item.setKey("key_" + i);
    item.setValue("created_value_" + i);
    createChangeSet.addCreateItem(item);
  }

  ResponseEntity<Void> response = createdTemplate.postForEntity(
      "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/" + cluster.getName()
          + "/namespaces/" + namespace.getNamespaceName() + "/itemset",
      createChangeSet, Void.class);
  Assert.assertEquals(HttpStatus.OK, response.getStatusCode());

  ItemDTO[] items =
      restTemplate.getForObject(
          "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/"
              + cluster.getName() + "/namespaces/" + namespace.getNamespaceName() + "/items",
          ItemDTO[].class);

  ItemChangeSets deleteChangeSet = new ItemChangeSets();
  deleteChangeSet.setDataChangeLastModifiedBy("deleted");
  RestTemplate deletedTemplate = (new TestRestTemplate()).getRestTemplate();
  deletedTemplate.setMessageConverters(restTemplate.getMessageConverters());
  
  int deletedSize = 1;
  for (int i = 0; i < deletedSize; i++) {
    items[i].setValue("deleted_value_" + i);
    deleteChangeSet.addDeleteItem(items[i]);
  }

  response = deletedTemplate.postForEntity(
      "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/" + cluster.getName()
          + "/namespaces/" + namespace.getNamespaceName() + "/itemset",
      deleteChangeSet, Void.class);
  Assert.assertEquals(HttpStatus.OK, response.getStatusCode());
  List<Item> savedItems = itemRepository.findByNamespaceIdOrderByLineNumAsc(namespace.getId());
  Assert.assertEquals(createdSize - deletedSize, savedItems.size());
  Item item0 = savedItems.get(0);
  Assert.assertEquals("key_1", item0.getKey());
  Assert.assertEquals("created_value_1", item0.getValue());
  Assert.assertEquals("created", item0.getDataChangeCreatedBy());
  Assert.assertNotNull(item0.getDataChangeCreatedTime());
}
 
Example 24
Source Project: apollo   Source File: AppControllerTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test(expected = HttpClientErrorException.class)
@Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
public void testFindNotExist() {
  restTemplate.getForEntity(getBaseAppUrl() + "notExists", AppDTO.class);
}
 
Example 25
/**
 * Execute SQL scripts configured via {@link Sql @Sql} for the supplied
 * {@link TestContext} <em>before</em> the current test method.
 */
@Override
public void beforeTestMethod(TestContext testContext) throws Exception {
	executeSqlScripts(testContext, ExecutionPhase.BEFORE_TEST_METHOD);
}
 
Example 26
/**
 * Execute SQL scripts configured via {@link Sql @Sql} for the supplied
 * {@link TestContext} <em>after</em> the current test method.
 */
@Override
public void afterTestMethod(TestContext testContext) throws Exception {
	executeSqlScripts(testContext, ExecutionPhase.AFTER_TEST_METHOD);
}