Skip to content

Commit

Permalink
Fix issue with ConfiguredValue.wasDefaultValueUsed method
Browse files Browse the repository at this point in the history
Added more test setup code to create/delete resources

DAT-8640
  • Loading branch information
wwillard7800 committed Dec 3, 2021
1 parent 3002b6e commit 4f0af6e
Show file tree
Hide file tree
Showing 10 changed files with 137 additions and 68 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public class UpdateCommandStep extends AbstractCliWrapperCommandStep {
CommandBuilder builder = new CommandBuilder(COMMAND_NAME, LEGACY_COMMAND_NAME);

URL_ARG = builder.argument("url", String.class).required()
.description("The JDBC database connection URL").build();
.description("The JDBC database connection URL").build();
DEFAULT_SCHEMA_NAME = builder.argument("defaultSchemaName", String.class)
.description("The default schema name to use for the database connection").build();
DEFAULT_CATALOG_NAME_ARG = builder.argument("defaultCatalogName", String.class)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,15 +56,9 @@ public ProvidedValue getProvidedValue() {
return getProvidedValues().get(0);
}


public boolean wasDefaultValueUsed() {
for (ProvidedValue providedValue : this.getProvidedValues()) {
if (providedValue.getProvider() != null && providedValue.getProvider() instanceof ConfigurationDefinition.DefaultValueProvider) {
return true;
}
}

return false;
ProvidedValue winningProvidedValue = getProvidedValue();
return winningProvidedValue != null && winningProvidedValue.getProvider() instanceof ConfigurationDefinition.DefaultValueProvider;
}

/**
Expand Down
2 changes: 1 addition & 1 deletion liquibase-core/src/main/java/liquibase/util/FileUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ private FileUtil() {
throw new IllegalStateException("This utility class must not be instantiated. Sorry.");
}

public static String getContents(File file) throws IOException {
public static String getContents(File file) throws IOException {
if (!file.exists()) {
return null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import liquibase.database.jvm.JdbcConnection
import liquibase.extension.testing.TestDatabaseConnections
import liquibase.extension.testing.TestFilter
import liquibase.extension.testing.setup.*
import liquibase.extension.testing.setup.SetupCleanResources.CleanupMode
import liquibase.hub.HubService
import liquibase.hub.core.MockHubService
import liquibase.integration.commandline.LiquibaseCommandLineConfiguration
Expand Down Expand Up @@ -290,13 +291,6 @@ Long Description: ${commandDefinition.getLongDescription() ?: "NOT SET"}
return
}
}
finally {
if (testDef.setup != null) {
for (def setup : testDef.setup) {
setup.cleanup()
}
}
}
} as Scope.ScopedRunnerWithReturn<CommandResults>)

if (savedException != null && savedException.getCause() != null && savedException.getCause() instanceof CommandFailedException) {
Expand All @@ -311,35 +305,43 @@ Long Description: ${commandDefinition.getLongDescription() ?: "NOT SET"}
throw new RuntimeException("Results were expected but none were found for " + testDef.commandTestDefinition.command)
}


then:
checkOutput("Command Output", outputStream.toString(), testDef.expectedOutput)
checkOutput("UI Output", uiOutputWriter.toString(), testDef.expectedUI)
checkOutput("UI Error Output", uiErrorWriter.toString(), testDef.expectedUIErrors)
checkOutput("Log Messages", logService.getLogAsString(Level.FINE), testDef.expectedLogs)

checkFileContent(testDef.expectedFileContent, "Command File Content")
checkDatabaseContent(testDef.expectedDatabaseContent, database, "Database snapshot content")

if (!testDef.expectedResults.isEmpty()) {
for (def returnedResult : results.getResults().entrySet()) {
def expectedResult = testDef.expectedResults.get(returnedResult.getKey())
def expectedValue = expectedResult instanceof Closure ? expectedResult.call() : String.valueOf(expectedResult)
def seenValue = String.valueOf(returnedResult.getValue())

assert expectedValue != "null": "No expectedResult for returned result '" + returnedResult.getKey() + "' of: " + seenValue
assert seenValue == expectedValue
try {
checkOutput("Command Output", outputStream.toString(), testDef.expectedOutput)
checkOutput("UI Output", uiOutputWriter.toString(), testDef.expectedUI)
checkOutput("UI Error Output", uiErrorWriter.toString(), testDef.expectedUIErrors)
checkOutput("Log Messages", logService.getLogAsString(Level.FINE), testDef.expectedLogs)

checkFileContent(testDef.expectedFileContent, "Command File Content")
checkDatabaseContent(testDef.expectedDatabaseContent, database, "Database snapshot content")

if (!testDef.expectedResults.isEmpty()) {
for (def returnedResult : results.getResults().entrySet()) {
def expectedResult = testDef.expectedResults.get(returnedResult.getKey())
def expectedValue = expectedResult instanceof Closure ? expectedResult.call() : String.valueOf(expectedResult)
def seenValue = String.valueOf(returnedResult.getValue())

assert expectedValue != "null": "No expectedResult for returned result '" + returnedResult.getKey() + "' of: " + seenValue
assert seenValue == expectedValue
}
}
if (testDef.expectFileToExist != null) {
assert testDef.expectFileToExist.exists(): "File '${testDef.expectFileToExist.getAbsolutePath()}' should exist"
}
if (testDef.expectFileToNotExist != null) {
assert !testDef.expectFileToNotExist.exists(): "File '${testDef.expectFileToNotExist.getAbsolutePath()}' should not exist"
}
} finally {
if (testDef.setup != null) {
for (def setup : testDef.setup) {
setup.cleanup()
}
}
}
}
if (testDef.expectFileToExist != null) {
assert testDef.expectFileToExist.exists(): "File '${testDef.expectFileToExist.getAbsolutePath()}' should exist"
}
if (testDef.expectFileToNotExist != null) {
assert !testDef.expectFileToNotExist.exists(): "File '${testDef.expectFileToNotExist.getAbsolutePath()}' should not exist"
}

where:
permutation << getAllRunTestPermutations()

where:
permutation << getAllRunTestPermutations()
}

static OutputCheck assertNotContains(String substring) {
Expand Down Expand Up @@ -836,10 +838,21 @@ Long Description: ${commandDefinition.getLongDescription() ?: "NOT SET"}
this.setups.add(new SetupRunChangelog(changeLogPath, labels))
}

/*
* Create files and directories
*/
void createTempResource(String originalFile, String newFile) {
this.setups.add(new SetupCreateTempResources(originalFile, newFile))
}

void createTempResource(String originalFile, String newFile, String baseDir) {
this.setups.add(new SetupCreateTempResources(originalFile, newFile, baseDir))
}

void createTempDirectoryResource(String directory) {
this.setups.add(new SetupCreateDirectoryResources(directory))
}

/**
*
* Copy a specified file to another path
Expand All @@ -865,13 +878,24 @@ Long Description: ${commandDefinition.getLongDescription() ?: "NOT SET"}
*
* Delete the specified resources
*
* @param fileToDeletes
* @param filesToDelete
*
*/
void cleanResources(String... filesToDelete) {
this.setups.add(new SetupCleanResources(filesToDelete))
}

/**
*
* Delete the specified resources at possibly setup and cleanup
*
* @param filesToDelete
*
*/
void cleanResources(CleanupMode cleanOnSetup, String... filesToDelete) {
this.setups.add(new SetupCleanResources(cleanOnSetup, filesToDelete))
}

/**
* Mark the changeSets within a changelog as ran without actually running them
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -1,41 +1,62 @@
package liquibase.extension.testing.setup

import liquibase.Contexts
import liquibase.LabelExpression
import liquibase.Liquibase
import liquibase.changelog.ChangeLogHistoryService
import liquibase.changelog.ChangeLogHistoryServiceFactory
import liquibase.database.Database
import liquibase.database.DatabaseFactory
import liquibase.database.jvm.JdbcConnection

import liquibase.extension.testing.TestDatabaseConnections
import liquibase.integration.commandline.CommandLineResourceAccessor
import liquibase.resource.CompositeResourceAccessor
import liquibase.resource.FileSystemResourceAccessor

import java.nio.file.Paths
import java.nio.file.FileSystems
import java.nio.file.Files
import java.nio.file.Path

class SetupCleanResources extends TestSetup {

private final List<String> resourcesToDelete = new ArrayList<>()
public enum CleanupMode { CLEAN_ON_SETUP, CLEAN_ON_CLEANUP, CLEAN_ON_BOTH}
private CleanupMode cleanupMode

SetupCleanResources(String[] resourcesToDelete) {
this(CleanupMode.CLEAN_ON_CLEANUP, resourcesToDelete)
}

SetupCleanResources(CleanupMode cleanupMode, String[] resourcesToDelete) {
this.cleanupMode = cleanupMode
this.resourcesToDelete.addAll(resourcesToDelete as Set)
}

@Override
void setup(TestDatabaseConnections.ConnectionStatus connectionStatus) throws Exception {
if (cleanupMode == CleanupMode.CLEAN_ON_CLEANUP) {
return
}
deleteFiles(resourcesToDelete)
}

@Override
void cleanup() {
if (cleanupMode == CleanupMode.CLEAN_ON_SETUP) {
return
}
deleteFiles(resourcesToDelete)
}

private void deleteFiles(List<String> resourcesToDelete) {
for (String fileToDelete : resourcesToDelete) {
File f = null
URL url = Thread.currentThread().getContextClassLoader().getResource(fileToDelete)
if (url == null) {
return
f = new File(fileToDelete)
} else {
f = new File(url.toURI())
}
File f = new File(url.toURI())

//
// This will handle files and directories
//
if (f.exists()) {
boolean b = f.delete()
if (b) {
assert !f.exists(): "The file '$f' was not deleted"
}
Path path = FileSystems.getDefault().getPath(f.getAbsolutePath());
Files.walk(path)
.sorted(Comparator.reverseOrder())
.map({ p -> p.toFile() })
.forEach({ file -> file.delete() })
}
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package liquibase.extension.testing.setup

import liquibase.extension.testing.TestDatabaseConnections

class SetupCreateDirectoryResources extends TestSetup {

private String directory

SetupCreateDirectoryResources(String directory) {
this.directory = directory
}

@Override
void setup(TestDatabaseConnections.ConnectionStatus connectionStatus) throws Exception {
File f = new File(directory)
boolean b = f.mkdirs()
if (! b) {
if (! f.exists()) {
throw new RuntimeException("Unable to create directory '" + directory + "'")
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,24 @@ class SetupCreateTempResources extends TestSetup {

private String originalFile
private String newFile
private String baseDir

SetupCreateTempResources(String originalFile, String newFile) {
this(originalFile, newFile, "target/test-classes")
}

SetupCreateTempResources(String originalFile, String newFile, String baseDir) {
this.originalFile = originalFile
this.newFile = newFile
this.baseDir = baseDir
}

@Override
void setup(TestDatabaseConnections.ConnectionStatus connectionStatus) throws Exception {
URL url = Thread.currentThread().getContextClassLoader().getResource(originalFile)
File f = new File(url.toURI())
String contents = FileUtil.getContents(f)
File outputFile = new File("target/test-classes", newFile)
File outputFile = new File(baseDir, newFile)
FileUtil.write(contents, outputFile)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import liquibase.change.core.AddPrimaryKeyChange
import liquibase.change.core.CreateTableChange
import liquibase.exception.CommandExecutionException
import liquibase.exception.CommandValidationException
import liquibase.extension.testing.setup.SetupCleanResources
import liquibase.structure.core.Column

import java.util.regex.Pattern
Expand Down Expand Up @@ -71,7 +72,7 @@ Optional Args:
]

setup {
cleanResources("diffChangelog-test.xml")
cleanResources(SetupCleanResources.CleanupMode.CLEAN_ON_SETUP, "diffChangelog-test.xml")
database = [
new CreateTableChange(
tableName: "FirstTable",
Expand Down Expand Up @@ -115,7 +116,7 @@ Optional Args:
]

setup {
cleanResources("diffChangeLog-test.xml")
cleanResources(SetupCleanResources.CleanupMode.CLEAN_ON_SETUP, "diffChangeLog-test.xml")
database = [
new CreateTableChange(
tableName: "SharedTable",
Expand Down Expand Up @@ -173,7 +174,7 @@ Optional Args:
]

setup {
cleanResources("diffChangelogOrder-test.xml")
cleanResources(SetupCleanResources.CleanupMode.CLEAN_ON_SETUP, "diffChangelogOrder-test.xml")
database = [
new CreateTableChange(
tableName: "person",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import liquibase.change.ColumnConfig
import liquibase.change.core.CreateTableChange
import liquibase.change.core.TagDatabaseChange
import liquibase.exception.CommandValidationException
import liquibase.extension.testing.setup.SetupCleanResources

CommandTests.define {
command = ["generateChangelog"]
Expand Down Expand Up @@ -51,7 +52,7 @@ Optional Args:
changelogFile: "target/test-classes/changelog-test.xml"
]
setup {
cleanResources("changelog-test.xml")
cleanResources(SetupCleanResources.CleanupMode.CLEAN_ON_SETUP, "changelog-test.xml")
database = [
new CreateTableChange(
tableName: "FirstTable",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package liquibase.extension.testing.command

import liquibase.exception.CommandExecutionException
import liquibase.exception.CommandValidationException
import liquibase.extension.testing.setup.SetupCreateTempResources
import liquibase.hub.core.MockHubService

import java.util.regex.Pattern
Expand Down

0 comments on commit 4f0af6e

Please sign in to comment.