org.springframework.test.context.util.TestContextResourceUtils Java Examples

The following examples show how to use org.springframework.test.context.util.TestContextResourceUtils. 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: TestPropertySourceUtils.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
private static String[] mergeLocations(List<TestPropertySourceAttributes> attributesList) {
	final List<String> locations = new ArrayList<String>();

	for (TestPropertySourceAttributes attrs : attributesList) {
		if (logger.isTraceEnabled()) {
			logger.trace(String.format("Processing locations for TestPropertySource attributes %s", attrs));
		}

		String[] locationsArray = TestContextResourceUtils.convertToClasspathResourcePaths(
			attrs.getDeclaringClass(), attrs.getLocations());
		locations.addAll(0, Arrays.<String> asList(locationsArray));

		if (!attrs.isInheritLocations()) {
			break;
		}
	}

	return StringUtils.toStringArray(locations);
}
 
Example #2
Source File: TestPropertySourceUtils.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private static String[] mergeLocations(List<TestPropertySourceAttributes> attributesList) {
	List<String> locations = new ArrayList<>();
	for (TestPropertySourceAttributes attrs : attributesList) {
		if (logger.isTraceEnabled()) {
			logger.trace(String.format("Processing locations for TestPropertySource attributes %s", attrs));
		}
		String[] locationsArray = TestContextResourceUtils.convertToClasspathResourcePaths(
				attrs.getDeclaringClass(), attrs.getLocations());
		locations.addAll(0, Arrays.asList(locationsArray));
		if (!attrs.isInheritLocations()) {
			break;
		}
	}
	return StringUtils.toStringArray(locations);
}
 
Example #3
Source File: TestPropertySourceUtils.java    From java-technology-stack with MIT License 5 votes vote down vote up
private static String[] mergeLocations(List<TestPropertySourceAttributes> attributesList) {
	List<String> locations = new ArrayList<>();
	for (TestPropertySourceAttributes attrs : attributesList) {
		if (logger.isTraceEnabled()) {
			logger.trace(String.format("Processing locations for TestPropertySource attributes %s", attrs));
		}
		String[] locationsArray = TestContextResourceUtils.convertToClasspathResourcePaths(
				attrs.getDeclaringClass(), attrs.getLocations());
		locations.addAll(0, Arrays.asList(locationsArray));
		if (!attrs.isInheritLocations()) {
			break;
		}
	}
	return StringUtils.toStringArray(locations);
}
 
Example #4
Source File: SqlScriptsTestExecutionListener.java    From spring-analysis-note with MIT License 4 votes vote down vote up
/**
 * 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 #5
Source File: SqlScriptsTestExecutionListener.java    From java-technology-stack with MIT License 4 votes vote down vote up
/**
 * 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 #6
Source File: AbstractContextLoader.java    From spring-analysis-note with MIT License 2 votes vote down vote up
/**
 * Generate a modified version of the supplied locations array and return it.
 * <p>The default implementation simply delegates to
 * {@link TestContextResourceUtils#convertToClasspathResourcePaths}.
 * <p>Subclasses can override this method to implement a different
 * <em>location modification</em> strategy.
 * @param clazz the class with which the locations are associated
 * @param locations the resource locations to be modified
 * @return an array of modified application context resource locations
 * @since 2.5
 */
protected String[] modifyLocations(Class<?> clazz, String... locations) {
	return TestContextResourceUtils.convertToClasspathResourcePaths(clazz, locations);
}
 
Example #7
Source File: AbstractContextLoader.java    From java-technology-stack with MIT License 2 votes vote down vote up
/**
 * Generate a modified version of the supplied locations array and return it.
 * <p>The default implementation simply delegates to
 * {@link TestContextResourceUtils#convertToClasspathResourcePaths}.
 * <p>Subclasses can override this method to implement a different
 * <em>location modification</em> strategy.
 * @param clazz the class with which the locations are associated
 * @param locations the resource locations to be modified
 * @return an array of modified application context resource locations
 * @since 2.5
 */
protected String[] modifyLocations(Class<?> clazz, String... locations) {
	return TestContextResourceUtils.convertToClasspathResourcePaths(clazz, locations);
}
 
Example #8
Source File: AbstractContextLoader.java    From spring4-understanding with Apache License 2.0 2 votes vote down vote up
/**
 * Generate a modified version of the supplied locations array and return it.
 * <p>The default implementation simply delegates to
 * {@link TestContextResourceUtils#convertToClasspathResourcePaths}.
 * <p>Subclasses can override this method to implement a different
 * <em>location modification</em> strategy.
 * @param clazz the class with which the locations are associated
 * @param locations the resource locations to be modified
 * @return an array of modified application context resource locations
 * @since 2.5
 */
protected String[] modifyLocations(Class<?> clazz, String... locations) {
	return TestContextResourceUtils.convertToClasspathResourcePaths(clazz, locations);
}