Best Testcontainers-java code snippet using org.testcontainers.jdbc.mysql.JDBCDriverWithPoolTest.sampleInitFunction
Source: JDBCDriverWithPoolTest.java
...25 * TODO: Move to the jdbc module and either (a) implement a barebones {@link org.testcontainers.containers.JdbcDatabaseContainerProvider} for testing, or (b) refactor into a unit test.26 */27@RunWith(Parameterized.class)28public class JDBCDriverWithPoolTest {29 public static final String URL = "jdbc:tc:mysql:5.7.34://hostname/databasename?TC_INITFUNCTION=org.testcontainers.jdbc.mysql.JDBCDriverWithPoolTest::sampleInitFunction";30 private final DataSource dataSource;31 @Parameterized.Parameters32 public static Iterable<Supplier<DataSource>> dataSourceSuppliers() {33 return asList(34 JDBCDriverWithPoolTest::getTomcatDataSourceWithDriverClassName,35 JDBCDriverWithPoolTest::getTomcatDataSource,36 JDBCDriverWithPoolTest::getHikariDataSourceWithDriverClassName,37 JDBCDriverWithPoolTest::getHikariDataSource,38 JDBCDriverWithPoolTest::getViburDataSourceWithDriverClassName,39 JDBCDriverWithPoolTest::getViburDataSource40 );41 }42 public JDBCDriverWithPoolTest(Supplier<DataSource> dataSourceSupplier) {43 this.dataSource = dataSourceSupplier.get();44 }45 private ExecutorService executorService = Executors.newFixedThreadPool(5);46 @Test47 public void testMySQLWithConnectionPoolUsingSameContainer() throws SQLException, InterruptedException {48 // Populate the database with some data in multiple threads, so that multiple connections from the pool will be used49 for (int i = 0; i < 100; i++) {50 executorService.submit(() -> {51 try {52 new QueryRunner(dataSource).insert("INSERT INTO my_counter (n) VALUES (5)",53 (ResultSetHandler<Object>) rs -> true);54 } catch (SQLException e) {55 e.printStackTrace();56 }57 });58 }59 // Complete population of the database60 executorService.shutdown();61 executorService.awaitTermination(5, TimeUnit.MINUTES);62 // compare to expected results63 int count = new QueryRunner(dataSource).query("SELECT COUNT(1) FROM my_counter", rs -> {64 rs.next();65 return rs.getInt(1);66 });67 assertEquals("Reuse of a datasource points to the same DB container", 100, count);68 int sum = new QueryRunner(dataSource).query("SELECT SUM(n) FROM my_counter", rs -> {69 rs.next();70 return rs.getInt(1);71 });72 // 100 records * 5 = 500 expected73 assertEquals("Reuse of a datasource points to the same DB container", 500, sum);74 }75 private static DataSource getTomcatDataSourceWithDriverClassName() {76 PoolProperties poolProperties = new PoolProperties();77 poolProperties.setUrl(URL + ";TEST=TOMCAT_WITH_CLASSNAME"); // append a dummy URL element to ensure different DB per test78 poolProperties.setValidationQuery("SELECT 1");79 poolProperties.setMinIdle(3);80 poolProperties.setMaxActive(10);81 poolProperties.setDriverClassName(ContainerDatabaseDriver.class.getName());82 return new org.apache.tomcat.jdbc.pool.DataSource(poolProperties);83 }84 private static DataSource getTomcatDataSource() {85 PoolProperties poolProperties = new PoolProperties();86 poolProperties.setUrl(URL + ";TEST=TOMCAT"); // append a dummy URL element to ensure different DB per test87 poolProperties.setValidationQuery("SELECT 1");88 poolProperties.setInitialSize(3);89 poolProperties.setMaxActive(10);90 return new org.apache.tomcat.jdbc.pool.DataSource(poolProperties);91 }92 private static HikariDataSource getHikariDataSourceWithDriverClassName() {93 HikariConfig hikariConfig = new HikariConfig();94 hikariConfig.setJdbcUrl(URL + ";TEST=HIKARI_WITH_CLASSNAME"); // append a dummy URL element to ensure different DB per test95 hikariConfig.setConnectionTestQuery("SELECT 1");96 hikariConfig.setMinimumIdle(3);97 hikariConfig.setMaximumPoolSize(10);98 hikariConfig.setDriverClassName(ContainerDatabaseDriver.class.getName());99 return new HikariDataSource(hikariConfig);100 }101 private static HikariDataSource getHikariDataSource() {102 HikariConfig hikariConfig = new HikariConfig();103 hikariConfig.setJdbcUrl(URL + ";TEST=HIKARI"); // append a dummy URL element to ensure different DB per test104 hikariConfig.setConnectionTestQuery("SELECT 1");105 hikariConfig.setMinimumIdle(3);106 hikariConfig.setMaximumPoolSize(10);107 return new HikariDataSource(hikariConfig);108 }109 private static DataSource getViburDataSourceWithDriverClassName() {110 ViburDBCPDataSource ds = new ViburDBCPDataSource();111 ds.setJdbcUrl(URL + ";TEST=VIBUR_WITH_CLASSNAME");112 ds.setUsername("any"); // Recent versions of Vibur require a username, even though it will not be used113 ds.setPassword("");114 ds.setPoolInitialSize(3);115 ds.setPoolMaxSize(10);116 ds.setTestConnectionQuery("SELECT 1");117 ds.setDriverClassName(ContainerDatabaseDriver.class.getName());118 ds.start();119 return ds;120 }121 private static DataSource getViburDataSource() {122 ViburDBCPDataSource ds = new ViburDBCPDataSource();123 ds.setJdbcUrl(URL + ";TEST=VIBUR");124 ds.setUsername("any"); // Recent versions of Vibur require a username, even though it will not be used125 ds.setPassword("");126 ds.setPoolInitialSize(3);127 ds.setPoolMaxSize(10);128 ds.setTestConnectionQuery("SELECT 1");129 ds.start();130 return ds;131 }132 @SuppressWarnings("SqlNoDataSourceInspection")133 public static void sampleInitFunction(Connection connection) throws SQLException {134 connection.createStatement().execute("CREATE TABLE bar (\n" +135 " foo VARCHAR(255)\n" +136 ");");137 connection.createStatement().execute("INSERT INTO bar (foo) VALUES ('hello world');");138 connection.createStatement().execute("CREATE TABLE my_counter (\n" +139 " n INT\n" +140 ");");141 }142}...
sampleInitFunction
Using AI Code Generation
1import org.testcontainers.jdbc.ContainerDatabaseDriver;2import org.testcontainers.jdbc.JdbcDatabaseDelegate;3import java.sql.Connection;4import java.sql.Driver;5import java.sql.SQLException;6import java.util.Properties;7public class JDBCDriverWithPoolTest implements JdbcDatabaseDelegate {8 public static void main(String[] args) throws SQLException {9 Driver driver = new ContainerDatabaseDriver();10 Properties properties = new Properties();11 Connection connection = driver.connect(url, properties);12 }13 public static void sampleInitFunction(Connection connection) throws SQLException {14 connection.createStatement().execute("CREATE TABLE test_table (id INT)");15 }16}17import org.testcontainers.jdbc.ContainerDatabaseDriver;18import org.testcontainers.jdbc.JdbcDatabaseDelegate;19import java.sql.Connection;20import java.sql.Driver;21import java.sql.SQLException;22import java.util.Properties;23public class JDBCDriverWithPoolTest implements JdbcDatabaseDelegate {24 public static void main(String[] args) throws SQLException {25 Driver driver = new ContainerDatabaseDriver();26 Properties properties = new Properties();27 Connection connection = driver.connect(url, properties);28 }29 public static void sampleInitFunction(Connection connection) throws SQLException {30 connection.createStatement().execute("CREATE TABLE test_table (id INT)");31 }32}33import org.testcontainers.jdbc.ContainerDatabaseDriver;34import org.testcontainers.jdbc.JdbcDatabaseDelegate;35import java.sql.Connection;36import java.sql.Driver;37import java.sql.SQLException;38import java.util.Properties;39public class JDBCDriverWithPoolTest implements JdbcDatabaseDelegate {40 public static void main(String[] args) throws SQLException {41 Driver driver = new ContainerDatabaseDriver();42 Properties properties = new Properties();
sampleInitFunction
Using AI Code Generation
1import org.testcontainers.jdbc.JdbcDatabaseContainer;2import org.testcontainers.jdbc.JdbcDriverTest;3import org.testcontainers.jdbc.JdbcDriverTest.SampleInitFunction;4public class JDBCDriverWithPoolTest extends JdbcDriverTest {5 protected JdbcDatabaseContainer<?> createContainer() throws Exception {6 return null;7 }8 protected SampleInitFunction getSampleInitFunction() {9 return new SampleInitFunction() {10 public String getSql() {11 return "CREATE TABLE IF NOT EXISTS test (id INTEGER)";12 }13 public String getExpectedResult() {14 return "id\n1\n2\n3\n4\n5\n";15 }16 };17 }18}19public class JDBCDriverWithPoolTest extends JdbcDriverTest {20 protected JdbcDatabaseContainer<?> createContainer() throws Exception {21 return null;22 }23 protected SampleInitFunction getSampleInitFunction() {24 return new SampleInitFunction() {25 public String getSql() {26 return "CREATE TABLE IF NOT EXISTS test (id INTEGER)";27 }28 public String getExpectedResult() {29 return "id\n1\n2\n3\n4\n5\n";30 }31 };32 }33}34public class JDBCDriverWithPoolTest extends JdbcDriverTest {35 protected JdbcDatabaseContainer<?> createContainer() throws Exception {36 return null;37 }38 protected SampleInitFunction getSampleInitFunction() {39 return new SampleInitFunction() {40 public String getSql() {41 return "CREATE TABLE IF NOT EXISTS test (id INTEGER)";42 }43 public String getExpectedResult() {44 return "id\n1\n2\n3\n4\n5\n";45 }46 };47 }48}49public class JDBCDriverWithPoolTest extends JdbcDriverTest {50 protected JdbcDatabaseContainer<?> createContainer() throws Exception {51 return null;52 }
sampleInitFunction
Using AI Code Generation
1org.testcontainers.jdbc.mysql.JDBCDriverWithPoolTest.testSampleInitFunction()[pri:0, instance:org.testcontainers.jdbc.mysql.JDBCDriverWithPoolTest@3c9d9d1a] 2org.testcontainers.jdbc.mysql.JDBCDriverWithPoolTest.testSampleInitFunction() Time elapsed: 0.001 sec <<< ERROR!3 at org.testcontainers.containers.GenericContainer.doStart(GenericContainer.java:310)4 at org.testcontainers.containers.GenericContainer.start(GenericContainer.java:292)5 at org.testcontainers.jdbc.ContainerDatabaseDriver.connect(ContainerDatabaseDriver.java:78)6 at org.testcontainers.jdbc.ContainerDatabaseDriver.connect(ContainerDatabaseDriver.java:63)7 at java.sql.DriverManager.getConnection(DriverManager.java:664)8 at java.sql.DriverManager.getConnection(DriverManager.java:247)9 at org.testcontainers.jdbc.mysql.JDBCDriverWithPoolTest.testSampleInitFunction(JDBCDriverWithPoolTest.java:78)10Caused by: org.testcontainers.containers.ContainerFetchException: Can't get Docker image: RemoteDockerImage(imageName=mysql:5.7.22, imagePullPolicy=DefaultPullPolicy())11 at org.testcontainers.containers.GenericContainer.getDockerImageName(GenericContainer.java:1194)12 at org.testcontainers.containers.GenericContainer.logger(GenericContainer.java:579)13 at org.testcontainers.containers.GenericContainer.doStart(GenericContainer.java:305)14Caused by: com.github.dockerjava.api.exception.NotFoundException: {"message":"manifest for mysql:5.7.22 not found: manifest unknown: manifest unknown"}15 at org.testcontainers.shaded.com.github.dockerjava.core.DefaultInvocationBuilder.execute(DefaultInvocationBuilder.java:230)16 at org.testcontainers.shaded.com.github.dockerjava.core.DefaultInvocationBuilder.get(DefaultInvocationBuilder.java:136)17 at org.testcontainers.shaded.com.github.dockerjava.core.DefaultImageInfoService.inspectImage(DefaultImageInfoService.java:30)18 at org.testcontainers.shaded.com.github.dockerjava.core.ExecStartResultCallback.getImageId(ExecStartResultCallback.java:43)19 at org.testcontainers.shaded.com.github.dockerjava.core.command.PullImageResultCallback.getImageId(PullImageResultCallback.java:49)
sampleInitFunction
Using AI Code Generation
1 public void testSampleInitFunction() throws Exception {2 final JDBCDriverWithPoolTest testObj = new JDBCDriverWithPoolTest();3 testObj.sampleInitFunction();4 }5}6Source Project: spring-cloud-config Source File: JdbcEnvironmentRepositoryTests.java License: Apache License 2.0 6 votes @Test public void testQuery() { JdbcEnvironmentRepository repository = new JdbcEnvironmentRepository(); repository.setDataSource(dataSource); repository.setQuery("SELECT KEY, VALUE FROM CONFIG_DATA WHERE APPLICATION = ? AND PROFILE = ? AND LABEL = ?"); repository.afterPropertiesSet(); Environment result = repository.findOne("app", "profile", "label"); assertThat(result.getPropertySources().size()).isEqualTo(1); assertThat(result.getPropertySources().get(0).getSource().size()).isEqualTo(1); assertThat(result.getPropertySources().get(0).getSource().get("foo")).isEqualTo("bar"); }7Source Project: spring-cloud-config Source File: JdbcEnvironmentRepositoryTests.java License: Apache License 2.0 6 votes @Test public void testQueryWithPlaceholder() { JdbcEnvironmentRepository repository = new JdbcEnvironmentRepository(); repository.setDataSource(dataSource); repository.setQuery("SELECT KEY, VALUE FROM CONFIG_DATA WHERE APPLICATION = ? AND PROFILE = ? AND LABEL = ?"); repository.setPlaceholderPrefix("@{"); repository.setPlaceholderSuffix("}"); repository.afterPropertiesSet(); Environment result = repository.findOne("app", "profile", "label"); assertThat(result.getPropertySources().size()).isEqualTo(1); assertThat(result.getPropertySources().get(0).getSource().size()).isEqualTo(1); assertThat(result.getPropertySources().get(0).getSource().get("foo")).isEqualTo("bar"); }8Source Project: spring-cloud-config Source File: JdbcEnvironmentRepositoryTests.java License: Apache License 2.0 6 votes @Test public void testQueryWithPlaceholderAndDefault() { JdbcEnvironmentRepository repository = new JdbcEnvironmentRepository(); repository.setDataSource(dataSource); repository.setQuery("SELECT KEY, VALUE FROM CONFIG_DATA WHERE APPLICATION = ? AND PROFILE = ? AND LABEL = ?"); repository.setPlaceholderPrefix("@{"); repository.setPlaceholderSuffix("}"); repository.setPlaceholder
Check out the latest blogs from LambdaTest on this topic:
Having a good web design can empower business and make your brand stand out. According to a survey by Top Design Firms, 50% of users believe that website design is crucial to an organization’s overall brand. Therefore, businesses should prioritize website design to meet customer expectations and build their brand identity. Your website is the face of your business, so it’s important that it’s updated regularly as per the current web design trends.
These days, development teams depend heavily on feedback from automated tests to evaluate the quality of the system they are working on.
ChatGPT broke all Internet records by going viral in the first week of its launch. A million users in 5 days are unprecedented. A conversational AI that can answer natural language-based questions and create poems, write movie scripts, write social media posts, write descriptive essays, and do tons of amazing things. Our first thought when we got access to the platform was how to use this amazing platform to make the lives of web and mobile app testers easier. And most importantly, how we can use ChatGPT for automated testing.
The web paradigm has changed considerably over the last few years. Web 2.0, a term coined way back in 1999, was one of the pivotal moments in the history of the Internet. UGC (User Generated Content), ease of use, and interoperability for the end-users were the key pillars of Web 2.0. Consumers who were only consuming content up till now started creating different forms of content (e.g., text, audio, video, etc.).
We launched LT Browser in 2020, and we were overwhelmed by the response as it was awarded as the #5 product of the day on the ProductHunt platform. Today, after 74,585 downloads and 7,000 total test runs with an average of 100 test runs each day, the LT Browser has continued to help developers build responsive web designs in a jiffy.
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!