Best Testcontainers-java code snippet using org.testcontainers.junit.GenericContainerRuleTest.writeStringToFile
Source:GenericContainerRuleTest.java
...71 @BeforeClass72 public static void setupContent() throws FileNotFoundException {73 File contentFolder = new File(System.getProperty("user.home") + "/.tmp-test-container");74 contentFolder.mkdir();75 writeStringToFile(contentFolder, "file", "Hello world!");76 }77 /**78 * Redis79 */80 @ClassRule81 public static GenericContainer<?> redis = new GenericContainer<>(REDIS_IMAGE)82 .withExposedPorts(REDIS_PORT);83 /**84 * RabbitMQ85 */86 @ClassRule87 public static GenericContainer<?> rabbitMq = new GenericContainer<>(RABBITMQ_IMAGE)88 .withExposedPorts(RABBITMQ_PORT);89 /**90 * MongoDB91 */92 @ClassRule93 public static GenericContainer<?> mongo = new GenericContainer<>(MONGODB_IMAGE)94 .withExposedPorts(MONGO_PORT);95 /**96 * Pass an environment variable to the container, then run a shell script that exposes the variable in a quick and97 * dirty way for testing.98 */99 @ClassRule100 public static GenericContainer<?> alpineEnvVar = new GenericContainer<>(ALPINE_IMAGE)101 .withExposedPorts(80)102 .withEnv("MAGIC_NUMBER", "4")103 .withEnv("MAGIC_NUMBER", oldValue -> oldValue.orElse("") + "2")104 .withCommand("/bin/sh", "-c", "while true; do echo \"$MAGIC_NUMBER\" | nc -l -p 80; done");105 /**106 * Pass environment variables to the container, then run a shell script that exposes the variables in a quick and107 * dirty way for testing.108 */109 @ClassRule110 public static GenericContainer<?> alpineEnvVarFromMap = new GenericContainer<>(ALPINE_IMAGE)111 .withExposedPorts(80)112 .withEnv(ImmutableMap.of(113 "FIRST", "42",114 "SECOND", "50"115 ))116 .withCommand("/bin/sh", "-c", "while true; do echo \"$FIRST and $SECOND\" | nc -l -p 80; done");117 /**118 * Map a file on the classpath to a file in the container, and then expose the content for testing.119 */120 @ClassRule121 public static GenericContainer<?> alpineClasspathResource = new GenericContainer<>(ALPINE_IMAGE)122 .withExposedPorts(80)123 .withClasspathResourceMapping("mappable-resource/test-resource.txt", "/content.txt", READ_ONLY)124 .withCommand("/bin/sh", "-c", "while true; do cat /content.txt | nc -l -p 80; done");125 /**126 * Map a file on the classpath to a file in the container, and then expose the content for testing.127 */128 @ClassRule129 public static GenericContainer<?> alpineClasspathResourceSelinux = new GenericContainer<>(ALPINE_IMAGE)130 .withExposedPorts(80)131 .withClasspathResourceMapping("mappable-resource/test-resource.txt", "/content.txt", READ_WRITE, SHARED)132 .withCommand("/bin/sh", "-c", "while true; do cat /content.txt | nc -l -p 80; done");133 /**134 * Create a container with an extra host entry and expose the content of /etc/hosts for testing.135 */136 @ClassRule137 public static GenericContainer<?> alpineExtrahost = new GenericContainer<>(ALPINE_IMAGE)138 .withExposedPorts(80)139 .withExtraHost("somehost", "192.168.1.10")140 .withCommand("/bin/sh", "-c", "while true; do cat /etc/hosts | nc -l -p 80; done");141 @Test142 public void testIsRunning() {143 try (144 GenericContainer<?> container = new GenericContainer<>(TINY_IMAGE)145 .withCommand("top")) {146 assertFalse("Container is not started and not running", container.isRunning());147 container.start();148 assertTrue("Container is started and running", container.isRunning());149 }150 }151 @Test152 public void withTmpFsTest() throws Exception {153 try (154 GenericContainer<?> container = new GenericContainer<>(TINY_IMAGE)155 .withCommand("top")156 .withTmpFs(singletonMap("/testtmpfs", "rw"))157 ) {158 container.start();159 // check file doesn't exist160 String path = "/testtmpfs/test.file";161 Container.ExecResult execResult = container.execInContainer("ls", path);162 assertEquals("tmpfs inside container works fine", execResult.getStderr(),163 "ls: /testtmpfs/test.file: No such file or directory\n");164 // touch && check file does exist165 container.execInContainer("touch", path);166 execResult = container.execInContainer("ls", path);167 assertEquals("tmpfs inside container works fine", execResult.getStdout(), path + "\n");168 }169 }170 @Test171 public void simpleRabbitMqTest() throws IOException, TimeoutException {172 ConnectionFactory factory = new ConnectionFactory();173 factory.setHost(rabbitMq.getHost());174 factory.setPort(rabbitMq.getMappedPort(RABBITMQ_PORT));175 Connection connection = factory.newConnection();176 Channel channel = connection.createChannel();177 channel.exchangeDeclare(RABBIQMQ_TEST_EXCHANGE, "direct", true);178 String queueName = channel.queueDeclare().getQueue();179 channel.queueBind(queueName, RABBIQMQ_TEST_EXCHANGE, RABBITMQ_TEST_ROUTING_KEY);180 // Set up a consumer on the queue181 final boolean[] messageWasReceived = new boolean[1];182 channel.basicConsume(queueName, false, new DefaultConsumer(channel) {183 @Override184 public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {185 messageWasReceived[0] = Arrays.equals(body, RABBITMQ_TEST_MESSAGE.getBytes());186 }187 });188 // post a message189 channel.basicPublish(RABBIQMQ_TEST_EXCHANGE, RABBITMQ_TEST_ROUTING_KEY, null, RABBITMQ_TEST_MESSAGE.getBytes());190 // check the message was received191 assertTrue("The message was received", Unreliables.retryUntilSuccess(5, TimeUnit.SECONDS, () -> {192 if (!messageWasReceived[0]) {193 throw new IllegalStateException("Message not received yet");194 }195 return true;196 }));197 }198 @Test199 public void simpleMongoDbTest() {200 MongoClient mongoClient = new MongoClient(mongo.getHost(), mongo.getMappedPort(MONGO_PORT));201 MongoDatabase database = mongoClient.getDatabase("test");202 MongoCollection<Document> collection = database.getCollection("testCollection");203 Document doc = new Document("name", "foo")204 .append("value", 1);205 collection.insertOne(doc);206 Document doc2 = collection.find(new Document("name", "foo")).first();207 assertEquals("A record can be inserted into and retrieved from MongoDB", 1, doc2.get("value"));208 }209 @Test210 public void environmentAndCustomCommandTest() throws IOException {211 String line = getReaderForContainerPort80(alpineEnvVar).readLine();212 assertEquals("An environment variable can be passed into a command", "42", line);213 }214 @Test215 public void environmentFromMapTest() throws IOException {216 String line = getReaderForContainerPort80(alpineEnvVarFromMap).readLine();217 assertEquals("Environment variables can be passed into a command from a map", "42 and 50", line);218 }219 @Test220 public void customLabelTest() {221 try (final GenericContainer alpineCustomLabel = new GenericContainer<>(ALPINE_IMAGE)222 .withLabel("our.custom", "label")223 .withCommand("top")) {224 alpineCustomLabel.start();225 Map<String, String> labels = alpineCustomLabel.getCurrentContainerInfo().getConfig().getLabels();226 assertTrue("org.testcontainers label is present", labels.containsKey("org.testcontainers"));227 assertTrue("our.custom label is present", labels.containsKey("our.custom"));228 assertEquals("our.custom label value is label", labels.get("our.custom"), "label");229 }230 }231 @Test232 public void exceptionThrownWhenTryingToOverrideTestcontainersLabels() {233 assertThrows("When trying to overwrite an 'org.testcontainers' label, withLabel() throws an exception",234 IllegalArgumentException.class,235 () -> {236 new GenericContainer<>(ALPINE_IMAGE)237 .withLabel("org.testcontainers.foo", "false");238 }239 );240 }241 @Test242 public void customClasspathResourceMappingTest() throws IOException {243 // Note: This functionality doesn't work if you are running your build inside a Docker container;244 // in that case this test will fail.245 String line = getReaderForContainerPort80(alpineClasspathResource).readLine();246 assertEquals("Resource on the classpath can be mapped using calls to withClasspathResourceMapping", "FOOBAR", line);247 }248 @Test249 public void customClasspathResourceMappingWithSelinuxTest() throws IOException {250 String line = getReaderForContainerPort80(alpineClasspathResourceSelinux).readLine();251 assertEquals("Resource on the classpath can be mapped using calls to withClasspathResourceMappingSelinux", "FOOBAR", line);252 }253 @Test254 public void exceptionThrownWhenMappedPortNotFound() {255 assertThrows("When the requested port is not mapped, getMappedPort() throws an exception",256 IllegalArgumentException.class,257 () -> {258 return redis.getMappedPort(666);259 });260 }261 protected static void writeStringToFile(File contentFolder, String filename, String string) throws FileNotFoundException {262 File file = new File(contentFolder, filename);263 PrintStream printStream = new PrintStream(new FileOutputStream(file));264 printStream.println(string);265 printStream.close();266 }267 @Test @Ignore //TODO investigate intermittent failures268 public void failFastWhenContainerHaltsImmediately() {269 long startingTimeMs = System.currentTimeMillis();270 final GenericContainer failsImmediately = new GenericContainer<>(ALPINE_IMAGE)271 .withCommand("/bin/sh", "-c", "return false")272 .withMinimumRunningDuration(Duration.ofMillis(100));273 try {274 assertThrows(275 "When we start a container that halts immediately, an exception is thrown",...
writeStringToFile
Using AI Code Generation
1 public static void main(String[] args) throws IOException {2 String filePath = "/tmp/test.txt";3 String content = "test";4 GenericContainerRuleTest genericContainerRuleTest = new GenericContainerRuleTest();5 genericContainerRuleTest.writeStringToFile(filePath, content);6 }7 public static void main(String[] args) throws IOException {8 String filePath = "/tmp/test.txt";9 String content = "test";10 GenericContainerRuleTest genericContainerRuleTest = new GenericContainerRuleTest();11 genericContainerRuleTest.writeStringToFile(filePath, content);12 }13 public static void main(String[] args) throws IOException {14 String filePath = "/tmp/test.txt";15 String content = "test";16 GenericContainerRuleTest genericContainerRuleTest = new GenericContainerRuleTest();17 genericContainerRuleTest.writeStringToFile(filePath, content);18 }19 public static void main(String[] args) throws IOException {20 String filePath = "/tmp/test.txt";21 String content = "test";22 GenericContainerRuleTest genericContainerRuleTest = new GenericContainerRuleTest();23 genericContainerRuleTest.writeStringToFile(filePath, content);24 }25 public static void main(String[] args) throws IOException {26 String filePath = "/tmp/test.txt";27 String content = "test";28 GenericContainerRuleTest genericContainerRuleTest = new GenericContainerRuleTest();29 genericContainerRuleTest.writeStringToFile(filePath, content);30 }31 public static void main(String[] args) throws IOException {32 String filePath = "/tmp/test.txt";33 String content = "test";34 GenericContainerRuleTest genericContainerRuleTest = new GenericContainerRuleTest();35 genericContainerRuleTest.writeStringToFile(filePath, content);36 }37 public static void main(String[] args) throws IOException {38 String filePath = "/tmp/test.txt";39 String content = "test";
writeStringToFile
Using AI Code Generation
1public class GenericContainerRuleTest {2 public GenericContainerRule genericContainerRule = new GenericContainerRule("postgres:9.4");3 public void testWriteStringToFile() throws IOException {4 File file = new File("file.txt");5 String content = "Hello World!";6 genericContainerRule.writeStringToFile(file, content);7 try (BufferedReader reader = new BufferedReader(new FileReader(file))) {8 assertEquals(content, reader.readLine());9 }10 }11}12GenericContainerRule#writeFileToContainer()13Syntax: writeFileToContainer(File file, String containerPath)14public class GenericContainerRuleTest {15 public GenericContainerRule genericContainerRule = new GenericContainerRule("postgres:9.4");16 public void testWriteFileToContainer() throws IOException {17 File file = new File("file.txt");18 genericContainerRule.writeStringToFile(file, "Hello World!");19 genericContainerRule.writeFileToContainer(file, "/file.txt");20 genericContainerRule.execInContainer("cat", "/file.txt");21 }22}23GenericContainerRule#copyFileToContainer()24Syntax: copyFileToContainer(MountableFile mountableFile, String containerPath)25public class GenericContainerRuleTest {26 public GenericContainerRule genericContainerRule = new GenericContainerRule("postgres:9.4");
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!!