package org.bench4q.master.integrated;

import static org.junit.Assert.*;

import java.util.Set;

import org.bench4q.master.domain.entity.RunningAgentDB;
import org.bench4q.master.domain.entity.TestPlan;
import org.bench4q.master.domain.factory.TestPlanFactory;
import org.bench4q.master.domain.valueobject.transaction.impl.TestPlanLoadApplication;
import org.bench4q.master.unitTest.TestBase_MakeUpTestPlan;
import org.bench4q.share.enums.master.TestPlanStatus;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:service-test-context.xml" })
public class Test_LoadDistribute extends TestBase_MakeUpTestPlan {
	private TestPlanFactory testPlanFactory;

	private TestPlanFactory getTestPlanFactory() {
		return testPlanFactory;
	}

	@Autowired
	private void setTestPlanFactory(TestPlanFactory testPlanFactory) {
		this.testPlanFactory = testPlanFactory;
	}

	@Before
	public void prepare() {
		prepareForTestPlanRunning();
		submitATestPlanWithOneScript();
	}

	@After
	public void cleanUp() {
		for (RunningAgentDB runningAgentDB : this.getTestPlanRepository()
				.getTestPlanInDomainBy(getTestPlanRunIdUuid())
				.extracSpecifiedScript(getScriptId()).getRunningAgentsDB()) {
			this.getAgentMessenger().stop(runningAgentDB.getAgent(),
					runningAgentDB.getAgentRunId());
		}
		this.getTestPlanRepository().detach(
				getTestPlanRepository().getTestPlanInDomainBy(
						getTestPlanRunIdUuid()).getId());
	}

	/**
	 * This need a agent could be found
	 * 
	 * @throws Exception
	 */
	@Test
	public void test_applyForLoad() throws Exception {
		TestPlan testPlanInDomain = this.getTestPlanRepository()
				.getTestPlanInDomainBy(getTestPlanRunIdUuid());
		testPlanInDomain = this.getTestPlanFactory().convertToDomain(
				testPlanInDomain);
		assertEquals(TestPlanStatus.InRunning, new TestPlanLoadApplication(
				testPlanInDomain).execute());
		assertEquals(EACH_SCRIPT_LOAD_SMALLSCALE,
				testPlanInDomain.getRequiredLoad());
		testPlanInDomain = this.getTestPlanRepository().getTestPlanInDomainBy(
				getTestPlanRunIdUuid());
		Set<RunningAgentDB> runningAgentsAfterRefetch = testPlanInDomain
				.extracSpecifiedScript(getScriptId()).getRunningAgentsDB();
		assertTrue(runningAgentsAfterRefetch.size() > 0);
		for (RunningAgentDB runningAgentDB : runningAgentsAfterRefetch) {
			assertNotNull(runningAgentDB);
		}
	}

}
