<commit_before>package brooklyn.entity.webapp.tomcat

import static java.util.concurrent.TimeUnit.*
import static org.junit.Assert.*

import java.util.Map

import org.junit.After
import org.junit.Before
import org.junit.Test
import org.slf4j.Logger
import org.slf4j.LoggerFactory

import brooklyn.entity.Application
import brooklyn.entity.basic.AbstractApplication
import brooklyn.location.basic.SshMachineLocation
import brooklyn.util.internal.TimeExtras

/**
 * This tests the operation of the {@link TomcatNode} entity.
 */
class TomcatNodeTest {
	private static final Logger logger = LoggerFactory.getLogger(TomcatNodeTest.class)

	static {
        TimeExtras.init()
    }
	
	/** don't use 8080 since that is commonly used by testing software */
	static int DEFAULT_HTTP_PORT = 7880
	
//	@InheritConstructors
	static class TestApplication extends AbstractApplication {
        public TestApplication(Map properties=[:]) {
            super(properties)
        }
    }

	static boolean httpPortLeftOpen = false;

	@Before
	public void fail_if_http_port_in_use() {
		if (isPortInUse(DEFAULT_HTTP_PORT)) {
			httpPortLeftOpen = true;
			fail "someone is already listening on port $DEFAULT_HTTP_PORT; tests assume that port $DEFAULT_HTTP_PORT is free on localhost"
		}
	}
	@After
	//can't fail because that swallows the original exception, grrr!
	public void moan_if_http_port_in_use() {
		if (!httpPortLeftOpen && isPortInUse(DEFAULT_HTTP_PORT, 1000))
			logger.warn "port $DEFAULT_HTTP_PORT still running after test"
	}
	private int oldHttpPort=-1;
	@Before
	public void changeDefaultHttpPort() {
		oldHttpPort = Tomcat7SshSetup.DEFAULT_FIRST_HTTP_PORT;
		Tomcat7SshSetup.DEFAULT_FIRST_HTTP_PORT = DEFAULT_HTTP_PORT
	}
	@After
	public void changeDefaultHttpPortBack() {
		if (oldHttpPort>0)
			Tomcat7SshSetup.DEFAULT_FIRST_HTTP_PORT = oldHttpPort
	}
	
    @Before
    public void patchInSimulator() {
        TomcatNode.metaClass.startInLocation = { SimulatedLocation loc ->
            TomcatSimulator sim = new TomcatSimulator(loc, delegate)
            delegate.simulator = sim
            sim.start()
        }
        TomcatNode.metaClass.shutdownInLocation { SimulatedLocation loc ->
            TomcatSimulator sim = delegate.simulator
            assertEquals loc, sim.location
            sim.shutdown()
        }
    }

	public boolean isPortInUse(int port, long retryAfterMillis=0) {
		try {
			def s = new Socket("localhost", port)
			s.close()
			if (retryAfterMillis>0) {
				logger.debug "port $port still open, waiting 1s for it to really close"
				//give it 1s to close
				Thread.sleep retryAfterMillis
				s = new Socket("localhost", port)
				s.close()
			}
			logger.debug "port $port still open (conclusive)"
			return true
		} catch (ConnectException e) {
			return false
		}
	}
	
	@Test
	public void testTomcatLifecycle() {
		Application app = new TestApplication(httpPort: DEFAULT_HTTP_PORT);
		TomcatNode tc = new TomcatNode(owner: app);
		
		try { 
			tc.start(location: new SimulatedLocation());
			try { tc.shutdown() } catch (Exception e) { 
				throw new Exception("tomcat is throwing exceptions when shutting down; this will break most tests", e) }
		} catch (Exception e) {
			throw new Exception("tomcat is throwing exceptions when starting; this will break most tests", e)
		}
	}
	
	@Test
	public void detectTomcatCascadeStartFailure() {
		Application app = new TestApplication(httpPort: DEFAULT_HTTP_PORT);
		TomcatNode tc1 = new TomcatNode(owner: app);
		TomcatNode tc2 = new TomcatNode(owner: app);
		
		try {
			tc1.start(location: new SimulatedLocation());
			tc1.shutdown()
		} catch (Exception e) {} //NOOP
		
		try { 
			tc2.start(location: new SimulatedLocation())
		} catch (IllegalStateException e) {
			throw new Exception("tomcat should clean up after itself in case of failure; this will break most tests", e)
		} finally {
			try { tc2.shutdown() } catch (Exception e) {} //NOOP
		}
	}
	
	@Test
	public void detectEarlyDeathOfTomcatProcess() {
		Application app = new TestApplication(httpPort: DEFAULT_HTTP_PORT);
		TomcatNode tc1 = new TomcatNode(owner: app);
		TomcatNode tc2 = new TomcatNode(owner: app);
		tc1.start(location: new SimulatedLocation())
		try {
			tc2.start(location: new SimulatedLocation())
			tc2.shutdown()
			fail "should have detected that $tc2 didn't start since tomcat was already running"<commit_msg>Rename a couple of the test methods<commit_after>package brooklyn.entity.webapp.tomcat

import static java.util.concurrent.TimeUnit.*
import static org.junit.Assert.*

import java.util.Map

import org.junit.After
import org.junit.Before
import org.junit.Test
import org.slf4j.Logger
import org.slf4j.LoggerFactory

import brooklyn.entity.Application
import brooklyn.entity.basic.AbstractApplication
import brooklyn.location.basic.SshMachineLocation
import brooklyn.util.internal.TimeExtras

/**
 * This tests the operation of the {@link TomcatNode} entity.
 */
class TomcatNodeTest {
	private static final Logger logger = LoggerFactory.getLogger(TomcatNodeTest.class)

	static {
        TimeExtras.init()
    }
	
	/** don't use 8080 since that is commonly used by testing software */
	static int DEFAULT_HTTP_PORT = 7880
	
//	@InheritConstructors
	static class TestApplication extends AbstractApplication {
        public TestApplication(Map properties=[:]) {
            super(properties)
        }
    }

	static boolean httpPortLeftOpen = false;

	@Before
	public void fail_if_http_port_in_use() {
		if (isPortInUse(DEFAULT_HTTP_PORT)) {
			httpPortLeftOpen = true;
			fail "someone is already listening on port $DEFAULT_HTTP_PORT; tests assume that port $DEFAULT_HTTP_PORT is free on localhost"
		}
	}
	@After
	//can't fail because that swallows the original exception, grrr!
	public void moan_if_http_port_in_use() {
		if (!httpPortLeftOpen && isPortInUse(DEFAULT_HTTP_PORT, 1000))
			logger.warn "port $DEFAULT_HTTP_PORT still running after test"
	}
	private int oldHttpPort=-1;
	@Before
	public void changeDefaultHttpPort() {
		oldHttpPort = Tomcat7SshSetup.DEFAULT_FIRST_HTTP_PORT;
		Tomcat7SshSetup.DEFAULT_FIRST_HTTP_PORT = DEFAULT_HTTP_PORT
	}
	@After
	public void changeDefaultHttpPortBack() {
		if (oldHttpPort>0)
			Tomcat7SshSetup.DEFAULT_FIRST_HTTP_PORT = oldHttpPort
	}
	
    @Before
    public void patchInSimulator() {
        TomcatNode.metaClass.startInLocation = { SimulatedLocation loc ->
            TomcatSimulator sim = new TomcatSimulator(loc, delegate)
            delegate.simulator = sim
            sim.start()
        }
        TomcatNode.metaClass.shutdownInLocation { SimulatedLocation loc ->
            TomcatSimulator sim = delegate.simulator
            assertEquals loc, sim.location
            sim.shutdown()
        }
    }

	public boolean isPortInUse(int port, long retryAfterMillis=0) {
		try {
			def s = new Socket("localhost", port)
			s.close()
			if (retryAfterMillis>0) {
				logger.debug "port $port still open, waiting 1s for it to really close"
				//give it 1s to close
				Thread.sleep retryAfterMillis
				s = new Socket("localhost", port)
				s.close()
			}
			logger.debug "port $port still open (conclusive)"
			return true
		} catch (ConnectException e) {
			return false
		}
	}
	
	@Test
	public void ensureNodeCanStartAndShutdown() {
		Application app = new TestApplication(httpPort: DEFAULT_HTTP_PORT);
		TomcatNode tc = new TomcatNode(owner: app);
		
		try { 
			tc.start(location: new SimulatedLocation());
			try { tc.shutdown() } catch (Exception e) { 
				throw new Exception("tomcat is throwing exceptions when shutting down; this will break most tests", e) }
		} catch (Exception e) {
			throw new Exception("tomcat is throwing exceptions when starting; this will break most tests", e)
		}
	}
	
	@Test
	public void ensureNodeShutdownCleansUp() {
		Application app = new TestApplication(httpPort: DEFAULT_HTTP_PORT);
		TomcatNode tc1 = new TomcatNode(owner: app);
		TomcatNode tc2 = new TomcatNode(owner: app);
		
		try {
			tc1.start(location: new SimulatedLocation());
			tc1.shutdown()
		} catch (Exception e) {} //NOOP
		
		try { 
			tc2.start(location: new SimulatedLocation())
		} catch (IllegalStateException e) {
			throw new Exception("tomcat should clean up after itself in case of failure; this will break most tests", e)
		} finally {
			try { tc2.shutdown() } catch (Exception e) {} //NOOP
		}
	}
	
	@Test
	public void detectEarlyDeathOfTomcatProcess() {
		Application app = new TestApplication(httpPort: DEFAULT_HTTP_PORT);
		TomcatNode tc1 = new TomcatNode(owner: app);
		TomcatNode tc2 = new TomcatNode(owner: app);
		tc1.start(location: new SimulatedLocation())
		try {
			tc2.start(location: new SimulatedLocation())
			tc2.shutdown()
			fail "should have detected that $tc2 didn't start since tomcat was already running"
{'fraction_non_alphanumeric': 0.08783706906360222, 'fraction_numerical': 0.007964501080896575, 'mean_word_length': 3.790190735694823, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6962366', 'n_tokens_mistral': 2920, 'n_tokens_neox': 2663, 'n_words': 757}