像这样设置测试:
postgresContainer, err := postgres.RunContainer(ctx,
testcontainers.WithImage("docker.io/postgres:16-alpine"),
postgres.WithDatabase(dbName),
postgres.WithUsername(dbUser),
postgres.WithPassword(dbPassword),
postgres.WithInitScripts(filepath.Join("..", "postgres_migrations", "v1_create_bands.sql"),
filepath.Join("..", "tests", "postgres_scripts", "bands_init.sql")),
testcontainers.WithWaitStrategy(
wait.ForLog("database system is ready to accept connections").
WithOccurrence(2).
WithStartupTimeout(5*time.Second)),
)
v1_create_bands.sql:
CREATE TABLE bands (
id INT PRIMARY KEY,
name VARCHAR(255)
);
bands_init.sql:
INSERT INTO bands(id, name) VALUES
(1, 'Band1'),
(2, 'Band2');
当我运行测试时,在尝试运行 band_init.sql 时出现错误
relation "bands" does not exist at character 13
。
但是如果我将 CREATE TABLE 语句复制到 band_init.sql 中,则会收到错误
relation "bands" already exists
!
如果我只保留 band_init.sql 作为唯一包含 2 个语句的脚本,则测试可以正确通过。我不明白这是怎么回事。
我错过的部分是第二个场景中的错误是在运行 v1_create_bands.sql 时发生的。因此,脚本只是按照字母顺序执行,而不是按照将它们传递给函数的顺序执行。我重命名了bands_init.sql,使其按字母顺序大于v1_create_bands.sql,然后测试通过了。