/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.execution.resourceGroups;

import com.facebook.presto.resourceGroups.ResourceGroupManagerPlugin;
import com.facebook.presto.spi.resourceGroups.ResourceGroupId;
import com.facebook.presto.tests.DistributedQueryRunner;
import com.google.common.collect.ImmutableMap;
import org.testng.annotations.Test;

import java.util.concurrent.TimeUnit;

import static com.facebook.presto.tests.tpch.TpchQueryRunner.createQueryRunner;

public class TestResourceGroupIntegration
{
    @Test(timeOut = 60_000)
    public void testMemoryFraction()
            throws Exception
    {
        try (DistributedQueryRunner queryRunner = createQueryRunner(ImmutableMap.of(), ImmutableMap.of("experimental.resource-groups-enabled", "true"))) {
            queryRunner.installPlugin(new ResourceGroupManagerPlugin());
            queryRunner.getCoordinator().getResourceGroupManager().get().setConfigurationManager("file", ImmutableMap.of("resource-groups.config-file", getResourceFilePath("resource_groups_memory_percentage.json")));

            queryRunner.execute("SELECT COUNT(*), clerk FROM orders GROUP BY clerk");
            while (true) {
                TimeUnit.SECONDS.sleep(1);
                ResourceGroupInfo global = queryRunner.getCoordinator().getResourceGroupManager().get().getResourceGroupInfo(new ResourceGroupId("global"));
                if (global.getSoftMemoryLimit().toBytes() > 0) {
                    break;
                }
            }
        }
    }

    private String getResourceFilePath(String fileName)
    {
        return this.getClass().getClassLoader().getResource(fileName).getPath();
    }
}

@@ -888,47 +888,8 @@
 t;%0A%0A
-import java.util.concurrent.TimeUnit;%0A%0A
 impo
@@ -963,16 +963,181 @@
 yRunner;
+%0Aimport static io.airlift.testing.Assertions.assertLessThan;%0Aimport static io.airlift.units.Duration.nanosSince;%0Aimport static java.util.concurrent.TimeUnit.SECONDS;
 %0A%0Apublic
@@ -1187,26 +1187,8 @@
 Test
-(timeOut = 60_000)
 %0A   
@@ -1788,16 +1788,64 @@
 lerk%22);%0A
+            long startTime = System.nanoTime();%0A
         
@@ -1879,25 +1879,16 @@
         
-TimeUnit.
 SECONDS.
@@ -2156,32 +2156,109 @@
               %7D%0A
+                assertLessThan(nanosSince(startTime).roundTo(SECONDS), 60L);%0A
             %7D%0A  

Make resource group test insensitive to startup time