package org.bench4q.agent.test.scenario;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import static org.junit.Assert.*;

import org.bench4q.agent.plugin.basic.csvprovider.CsvProvider;
import org.bench4q.agent.scenario.Scenario;
import org.bench4q.agent.scenario.behavior.Behavior;
import org.bench4q.agent.scenario.engine.VUser;
import org.bench4q.agent.test.TestBase;
import org.bench4q.share.helper.TestHelper;
import org.bench4q.share.models.agent.ParameterModel;
import org.bench4q.share.models.agent.RunScenarioModel;
import org.bench4q.share.models.agent.scriptrecord.BehaviorModel;
import org.bench4q.share.models.agent.scriptrecord.UsePluginModel;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:application-context.xml" })
public class Test_VUser extends TestBase {
	static final String TEST_CASE = "${csvProvider0:userName}$#okOrNot${file.separator}";

	@Test
	public void test_reassamblyParameters() throws Exception {
		UUID testId = UUID.randomUUID();
		final String paramKey = "userName";
		final String fileName = "param1";
		final String fieldNames = paramKey + ", password";
		createFileAndWriteContent(testId, fileName,
				"chen, 123" + System.getProperty("line.separator") + "kkk, 321");
		final BehaviorModel behaviorModel = BehaviorModel.UserBehaviorBuilder(
				1, "beh1", "http", new ArrayList<ParameterModel>() {
					private static final long serialVersionUID = 1L;
					{
						add(ParameterModel.createParameter(paramKey, TEST_CASE));
					}
				});
		RunScenarioModel runScenarioModel = buildRunScenarioModelWith(
				new ArrayList<UsePluginModel>() {
					private static final long serialVersionUID = 1L;
					{
						add(buildCsvProviderWith("csvProvider0", fileName,
								fieldNames));
					}
				}, behaviorModel);
		Scenario scenario = Scenario
				.scenarioBuilderWithCompile(runScenarioModel);
		VUser vUser = createVUser(scenario, testId);
		Map<String, Object> plugins = new HashMap<String, Object>();
		TestHelper
				.invokePrivate(vUser, "preparePlugins", new Class<?>[] {
						Scenario.class, Map.class }, new Object[] { scenario,
						plugins });
		assertEquals(2, plugins.size());
		assertTrue(plugins.containsKey("csvProvider0"));
		CsvProvider csvProvider = (CsvProvider) plugins.get("csvProvider0");
		csvProvider.doNext();
		@SuppressWarnings("unchecked")
		Map<String, String> params = (Map<String, String>) TestHelper
				.invokePrivate(vUser, "reassamblyParameters", new Class<?>[] {
						Behavior.class, Map.class }, new Object[] {
						scenario.getAllBehaviors().get(0), plugins });
		assertEquals(1, params.size());
		assertTrue(params.containsKey(paramKey));
		assertEquals("chen1okOrNot\\", params.get(paramKey));
		dropFiles(testId);
	}
}
