package generic;

import org.junit.Rule;
import org.junit.Test;
import org.testcontainers.containers.Container;
import org.testcontainers.containers.GenericContainer;
import org.testcontainers.utility.DockerImageName;

import java.io.IOException;

import static org.junit.Assert.assertEquals;

public class CmdModifierTest {

    // hostname {
    @Rule
    public GenericContainer theCache = new GenericContainer<>(DockerImageName.parse("redis:3.0.2"))
            .withCreateContainerCmdModifier(cmd -> cmd.withHostName("the-cache"));
    // }

    // memory {
    private long memoryInBytes = 32 * 1024 * 1024;
    private long memorySwapInBytes = 64 * 1024 * 1024;

    @Rule
    public GenericContainer memoryLimitedRedis = new GenericContainer<>(DockerImageName.parse("redis:3.0.2"))
            .withCreateContainerCmdModifier(cmd -> cmd.getHostConfig()
                .withMemory(memoryInBytes)
                .withMemorySwap(memorySwapInBytes)
            );
    // }


    @Test
    public void testHostnameModified() throws IOException, InterruptedException {
        final Container.ExecResult execResult = theCache.execInContainer("hostname");
        assertEquals("the-cache", execResult.getStdout().trim());
    }

    @Test
    public void testMemoryLimitModified() throws IOException, InterruptedException {
        final Container.ExecResult execResult = memoryLimitedRedis.execInContainer("cat", "/sys/fs/cgroup/memory/memory.limit_in_bytes");
        assertEquals(String.valueOf(memoryInBytes), execResult.getStdout().trim());
    }
}

@@ -22,45 +22,184 @@
 ort 
-org.junit.Rule;%0Aimport org.junit.Test
+com.github.dockerjava.api.DockerClient;%0Aimport com.github.dockerjava.api.model.Info;%0Aimport org.junit.Rule;%0Aimport org.junit.Test;%0Aimport org.testcontainers.DockerClientFactory
 ;%0Aim
@@ -378,16 +378,42 @@
 ception;
+%0Aimport java.util.Objects;
 %0A%0Aimport
@@ -1579,53 +1579,32 @@
 t%22, 
-%22/sys/fs/cgroup/memory/m
+getM
 emory
-.l
+L
 imit
-_in_bytes%22
+FilePath()
 );%0A 
@@ -1691,11 +1691,470 @@
 );%0A    %7D
+%0A%0A    private String getMemoryLimitFilePath() %7B%0A        DockerClient dockerClient = DockerClientFactory.instance().client();%0A        Info info = dockerClient.infoCmd().exec();%0A        Object cgroupVersion = info.getRawValues().get(%22CgroupVersion%22);%0A        boolean cgroup2 = Objects.equals(%222%22, cgroupVersion);%0A        if (cgroup2) %7B%0A            return %22/sys/fs/cgroup/memory.max%22;%0A        %7D%0A        return %22/sys/fs/cgroup/memory/memory.limit_in_bytes%22;%0A    %7D
 %0A%7D%0A

Fix `CmdModifierTest#testMemoryLimitModified` in cgroup2 environment. (#4375)