Last active
July 20, 2022 18:13
-
-
Save Mahoney/2009e2391d2665aa64f3f53f12a6976d to your computer and use it in GitHub Desktop.
Test liquibase migration output
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package mything.db | |
import com.zaxxer.hikari.HikariDataSource | |
import liquibase.Liquibase | |
import liquibase.database.DatabaseFactory | |
import liquibase.database.jvm.JdbcConnection | |
import liquibase.resource.ClassLoaderResourceAccessor | |
import org.testcontainers.containers.PostgreSQLContainer | |
import org.testcontainers.spock.Testcontainers | |
import spock.lang.Shared | |
import spock.lang.Specification | |
@Testcontainers | |
class DatabaseMigrationSpec extends Specification { | |
@Shared | |
PostgreSQLContainer migratedDbContainer = new PostgreSQLContainer('postgres:11.13') | |
def 'migration produces expected db'() { | |
given: | |
def expectedDump = new File("src/test/resources/expecteddb.sql") | |
def expectedDumpText = expectedDump.text | |
when: | |
migrate(migratedDbContainer) | |
def actualDumpText = dumpDb(migratedDbContainer) | |
if (actualDumpText != expectedDumpText) { | |
expectedDump.text = actualDumpText | |
System.err.println( | |
""" | |
This test failing may just mean that your intended changes need to be committed. | |
$expectedDump has been updated - compare it with the previous version, and if you are | |
happy with the changes commit them. | |
""".stripIndent() | |
) | |
} | |
then: | |
actualDumpText == expectedDumpText | |
} | |
private static void migrate(PostgreSQLContainer container) { | |
def dataSource = new HikariDataSource( | |
jdbcUrl: container.jdbcUrl, | |
username: container.username, | |
password: container.password, | |
) | |
def database = DatabaseFactory.getInstance() | |
.findCorrectDatabaseImplementation(new JdbcConnection(dataSource.getConnection())) | |
def liquibase = new Liquibase("db/schema.yaml", new ClassLoaderResourceAccessor(), database) | |
liquibase.update("app_start") | |
} | |
private static String dumpDb(PostgreSQLContainer container) { | |
container.execInContainer( | |
"pg_dump", | |
"--username=${container.username}", | |
"--format=plain", | |
"--exclude-table=databasechangelog*", | |
"--file=/tmp/db_dump", | |
container.databaseName | |
) | |
container.copyFileFromContainer("/tmp/db_dump", "/tmp/actual_db") | |
new File("/tmp/actual_db").text | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment