- * Ideally this would be a failing test. If it's excessively difficult to form as a test (e.g. relates to log - * output, teardown or other side effects) then it would be sufficient to explain the behaviour in the issue - * description. - */ @Test - public void demonstration() { + public void bindMountLogFiles() throws IOException { try ( - // customize the creation of a container as required - GenericContainer> container = new GenericContainer<>(DockerImageName.parse("redis:6.0.5")) - .withExposedPorts(6379) + GenericContainer> container = new GenericContainer<>("nginx:1.19.0-alpine") + .withExposedPorts(80) + .withFileSystemBind(System.getProperty("user.dir") + "/nginx", + "/var/log/nginx", BindMode.READ_WRITE) ) { container.start(); - // ... + // request against existing path + performRequestAgainstContainer(container, "/"); + + // request against nonsense path + long now = System.currentTimeMillis(); + performRequestAgainstContainer(container, "/foobar/" + now); + + // check that nginx/error.log in the project directory contains the now timestamp + String errorLog = System.getProperty("user.dir") + "/nginx/error.log"; + String errorLogContents = new String(java.nio.file.Files.readAllBytes(java.nio.file.Paths.get(errorLog))); + Assert.assertTrue(errorLogContents.contains(Long.toString(now))); + } + + } + + @Test + public void postgresContainerWithBootstrapFiles() throws Exception { + try ( + PostgreSQLContainer> postgres = new PostgreSQLContainer<>("postgres:13.1") + .withClasspathResourceMapping("init.sql", "/docker-entrypoint-initdb.d/init.sql", BindMode.READ_WRITE) + ) { + postgres.start(); + + try ( + Connection conn = DriverManager.getConnection(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword()); + Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT * FROM test_table") + ) { + // count all rows in result set + int rowCount = 0; + while (rs.next()) { + rowCount++; + } + + // assert row count is 3 + Assert.assertEquals(3, rowCount); + } + } + } + + + + private static int performRequestAgainstContainer(GenericContainer> container, String path) throws IOException { + URL url = new URL("http://" + container.getHost() + ":" + container.getMappedPort(80) + path); + + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + conn.setRequestMethod("GET"); + return conn.getResponseCode(); } } diff --git a/src/test/resources/init.sql b/src/test/resources/init.sql new file mode 100644 index 0000000..8e92658 --- /dev/null +++ b/src/test/resources/init.sql @@ -0,0 +1,8 @@ +CREATE TABLE test_table ( + id SERIAL PRIMARY KEY, + data VARCHAR(255) NOT NULL +); + +INSERT INTO test_table (data) VALUES ('Test data 1'); +INSERT INTO test_table (data) VALUES ('Test data 2'); +INSERT INTO test_table (data) VALUES ('Test data 3'); \ No newline at end of file