org.apache.jmeter.samplers.SampleResult Java Examples

The following examples show how to use org.apache.jmeter.samplers.SampleResult. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: UpperCaseTest.java    From jmeter-plugins with Apache License 2.0 6 votes vote down vote up
/**
 * Test of execute method, of class UpperCase.
 */
@Test
public void testExecute() throws Exception {
    System.out.println("execute");
    Collection<CompoundVariable> parameters = new ArrayList<>();
    parameters.add(new CompoundVariable("abc"));
    parameters.add(new CompoundVariable("var"));

    SampleResult previousResult = null;
    Sampler currentSampler = null;
    UpperCase instance = new UpperCase();
    instance.setParameters(parameters);
    String expResult = "ABC";
    String result = instance.execute(null, null);
    Assert.assertEquals(expResult, result);
    Assert.assertEquals(expResult, JMeterContextService.getContext().getVariables().get("var"));
}
 
Example #2
Source File: LowerCaseTest.java    From jmeter-plugins with Apache License 2.0 6 votes vote down vote up
/**
 * Test of execute method, of class LowerCase.
 */
@Test
public void testExecute() throws Exception {
    System.out.println("execute");
    Collection<CompoundVariable> parameters = new ArrayList<CompoundVariable>();
    parameters.add(new CompoundVariable("ABC"));
    parameters.add(new CompoundVariable("var"));

    SampleResult previousResult = null;
    Sampler currentSampler = null;
    LowerCase instance = new LowerCase();
    instance.setParameters(parameters);
    String expResult = "abc";
    String result = instance.execute(previousResult, currentSampler);
    Assert.assertEquals(expResult, result);
    Assert.assertEquals(expResult, JMeterContextService.getContext().getVariables().get("var"));
}
 
Example #3
Source File: SetTest.java    From jmeter-cassandra with Apache License 2.0 6 votes vote down vote up
@Test
public void testInsertPreparedthesetle() {
    CassandraSampler cs = new CassandraSampler();

    cs.setProperty("sessionName",TESTSESSION);
    cs.setProperty("consistencyLevel", AbstractCassandaTestElement.ONE);
    cs.setProperty("resultVariable","rv");
    cs.setProperty("queryType", AbstractCassandaTestElement.PREPARED);
    cs.setProperty("queryArguments", "\"" + EXPECTED + "\"");
    cs.setProperty("query", "INSERT INTO " + TABLE + " (key,theset) VALUES (2, ?)");

    TestBeanHelper.prepare(cs);

    SampleResult res = cs.sample(new Entry());
    assertTrue(res.isSuccessful(), res.getResponseMessage());

    // See if the value matches
    Row row = session.execute("select theset from " + KEYSPACE + "." + TABLE + " where key = 2").one();
    Set<String> theSet = row.getSet(0, String.class);
    assertTrue(theSet.contains("one"));
    assertTrue(theSet.contains("two"));
    assertTrue(theSet.contains("three"));
    assertEquals(3, theSet.size());
}
 
Example #4
Source File: ResponseTimesPercentilesGui.java    From jmeter-plugins with Apache License 2.0 6 votes vote down vote up
@Override
public void add(SampleResult res) {
    if (!isSampleIncluded(res)) {
        return;
    }
    String label = res.getSampleLabel();
    String aggregateLabel = "Overall Response Times";
    GraphRowPercentiles row = (GraphRowPercentiles) model.get(label);
    GraphRowPercentiles rowAgg = (GraphRowPercentiles) modelAggregate.get(label);

    if (row == null) {
        row = (GraphRowPercentiles) getNewRow(model, AbstractGraphRow.ROW_PERCENTILES, label, AbstractGraphRow.MARKER_SIZE_NONE, false, false, false, true, false);
    }

    if (rowAgg == null) {
        rowAgg = (GraphRowPercentiles) getNewRow(modelAggregate, AbstractGraphRow.ROW_PERCENTILES, aggregateLabel, AbstractGraphRow.MARKER_SIZE_NONE, false, false, false, true, Color.RED, false);
    }

    row.add(res.getTime(), 1);
    rowAgg.add(res.getTime(), 1);
    updateGui(null);
}
 
Example #5
Source File: WebDriverSamplerTest.java    From jmeter-plugins-webdriver with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnSuccessfulSampleResultWhenEvalScriptCompletes() throws MalformedURLException {
    sampler.setName("name");
    sampler.setScript("var x = 'hello';");
    final SampleResult sampleResult = sampler.sample(null);

    assertThat(sampleResult.isResponseCodeOK(), is(true));
    assertThat(sampleResult.getResponseMessage(), is("OK"));
    assertThat(sampleResult.isSuccessful(), is(true));
    assertThat(sampleResult.getContentType(), is("text/plain"));
    assertThat(sampleResult.getDataType(), is(SampleResult.TEXT));
    assertThat(sampleResult.getSampleLabel(), is("name"));
    assertThat(sampleResult.getResponseDataAsString(), is("page source"));
    assertThat(sampleResult.getURL(), is(new URL("http://google.com.au")));

    verify(browser, times(1)).getPageSource();
    verify(browser, times(1)).getCurrentUrl();
}
 
Example #6
Source File: UDTTest.java    From jmeter-cassandra with Apache License 2.0 6 votes vote down vote up
@Test
public void testSelectUDT() {
    CassandraSampler cs = new CassandraSampler();

    cs.setProperty("sessionName",TESTSESSION);
    cs.setProperty("consistencyLevel", AbstractCassandaTestElement.ONE);
    cs.setProperty("resultVariable","rv");
    cs.setProperty("queryType", AbstractCassandaTestElement.SIMPLE);
    cs.setProperty("query", "SELECT * FROM " + TABLE + " WHERE key = 1");

    TestBeanHelper.prepare(cs);

    SampleResult res = cs.sample(new Entry());
    assertTrue(res.isSuccessful(), res.getResponseMessage());

    String rowdata = new String(res.getResponseData());
    logger.info(rowdata);
    assertEquals(rowdata, "key\tudt\n" + "1" + "\t" + EXPECTED + "\n");

}
 
Example #7
Source File: WebDriverSampler.java    From jmeter-plugins-webdriver with Apache License 2.0 6 votes vote down vote up
ScriptEngine createScriptEngineWith(SampleResult sampleResult) {
    final ScriptEngine scriptEngine = scriptEngineManager.getEngineByName(this.getScriptLanguage());
    Bindings engineBindings = new SimpleBindings();
    WebDriverScriptable scriptable = new WebDriverScriptable();
    scriptable.setName(getName());
    scriptable.setParameters(getParameters());
    JMeterContext context = JMeterContextService.getContext();
    scriptable.setVars(context.getVariables());
    scriptable.setProps(JMeterUtils.getJMeterProperties());
    scriptable.setCtx(context);
    scriptable.setLog(LOGGER);
    scriptable.setSampleResult(sampleResult);
    scriptable.setBrowser(getWebDriver());
    engineBindings.put("WDS", scriptable);
    scriptEngine.setBindings(engineBindings, ScriptContext.ENGINE_SCOPE);
    return scriptEngine;
}
 
Example #8
Source File: TupleTest.java    From jmeter-cassandra with Apache License 2.0 6 votes vote down vote up
@Test
public void testInsertPreparedTuple() {
    CassandraSampler cs = new CassandraSampler();

    cs.setProperty("sessionName",TESTSESSION);
    cs.setProperty("consistencyLevel", AbstractCassandaTestElement.ONE);
    cs.setProperty("resultVariable","rv");
    cs.setProperty("queryType", AbstractCassandaTestElement.PREPARED);
    cs.setProperty("queryArguments", "\"" + EXPECTED + "\"");
    cs.setProperty("query", "INSERT INTO " + TABLE + " (key,tup) VALUES (2, ?)");

    TestBeanHelper.prepare(cs);

    SampleResult res = cs.sample(new Entry());
    assertTrue(res.isSuccessful(), res.getResponseMessage());

    // See if the value matches
    String val = session.execute("select tup from " + KEYSPACE + "." + TABLE + " where key = 2").one().getTupleValue(0).toString();
    assertEquals(EXPECTED, val);
}
 
Example #9
Source File: JSONPathExtractorTest.java    From jmeter-plugins with Apache License 2.0 6 votes vote down vote up
@Test
public void testYamlExtractor3() throws IOException {
    File test = new File(getClass().getResource("/test.yml").getPath());
    String response = FileUtils.readFileToString(test);

    JMeterContext context = JMeterContextService.getContext();
    JMeterVariables vars = context.getVariables();

    SampleResult samplerResult = new SampleResult();
    samplerResult.setResponseData(response.getBytes());
    context.setPreviousResult(samplerResult);

    JSONPathExtractor instance = new JSONPathExtractor();
    instance.setInputFormat(JSONPathExtractor.INPUT_YAML);
    instance.setDefaultValue("DEFAULT");
    instance.setVar("developers");
    instance.setJsonPath("$.developers");
    instance.process();

    assertEquals("[\"rultor\",\"salikjan\",\"sherif\"]", vars.get("developers"));
    assertEquals("3", vars.get("developers_matchNr"));
}
 
Example #10
Source File: AbstractVsThreadVisualizerTest.java    From jmeter-plugins with Apache License 2.0 6 votes vote down vote up
/**
 * Test of getCurrentThreadCount method, of class AbstractVsThreadVisualizer.
 */
@Test
public void testGetCurrentThreadCount()
{
    System.out.println("getCurrentThreadCount");
    long now = System.currentTimeMillis();
    SampleResult sample = new SampleResult();
    sample.setGroupThreads(3);
    sample.setThreadName("test_tg");
    sample.setStampAndTime(now, 300);
    AbstractVsThreadVisualizer instance = new AbstractVsThreadVisualizerImpl();
    instance.add(sample);
    int expResult = 3;
    int result = instance.getCurrentThreadCount(sample);
    assertEquals(expResult, result);
}
 
Example #11
Source File: RotatingResultCollectorTest.java    From jmeter-bzm-plugins with Apache License 2.0 6 votes vote down vote up
@Test
public void testFlowWithNumberExtension() throws Exception {
    RotatingResultCollector te = new RotatingResultCollector();
    te.setMaxSamplesCount("ZXC");
    assertEquals(Integer.MAX_VALUE, te.getMaxSamplesCountAsInt());

    File f = File.createTempFile("rotating", ".9");
    f.deleteOnExit();
    te.setFilename(f.getAbsolutePath());
    te.setMaxSamplesCount("3");
    te.testStarted();

    for (int n = 0; n < 10; n++) {
        SampleResult result = new SampleResult();
        result.setSampleLabel("#" + n);
        te.sampleOccurred(new SampleEvent(result, ""));
    }

    te.testEnded();
    assertTrue(te.filename, te.filename.endsWith(".3.9"));
}
 
Example #12
Source File: AbstractUpdaterTest.java    From jmeter-prometheus-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void testKeywords() {
	BaseCollectorConfig base = TestUtilities.simpleCounterCfg();
	base.setLabels(new String[] {"label","code"});
	ListenerCollectorConfig cfg = new ListenerCollectorConfig(base);
	
	TestUpdater u = new TestUpdater(cfg);
	
	SampleResult res = new SampleResult();
	res.setSampleLabel("test_label");
	res.setResponseCode("204");
	SampleEvent event = new SampleEvent(res,"test_tg", new JMeterVariables());
	
	String[] labels = u.labelValues(event);
	

	Assert.assertTrue(labels.length == 2);
	Assert.assertArrayEquals(new String[] {"test_label", "204"}, labels);
}
 
Example #13
Source File: SimpleQueryTest.java    From jmeter-cassandra with Apache License 2.0 6 votes vote down vote up
@Test(dataProvider = "provideQueries")
public void testPreparedSetQuery(String table, String expected, Object nothing) {

    CassandraSampler cs = new CassandraSampler();
    cs.setProperty("sessionName",TESTSESSION);
    cs.setProperty("consistencyLevel", AbstractCassandaTestElement.ONE);
    cs.setProperty("resultVariable","rv");
    cs.setProperty("queryType", AbstractCassandaTestElement.PREPARED);
    cs.setProperty("queryArguments", expected );
    cs.setProperty("query", "SELECT * FROM set_" + table + " WHERE K = ?");
    TestBeanHelper.prepare(cs);

    SampleResult res = cs.sample(new Entry());
    assertTrue(res.isSuccessful(), res.getResponseMessage());

    String rowdata = new String(res.getResponseData());
    logger.debug(rowdata);
    assertEquals(rowdata, "k\tv\n"+ expected +"\t{"+ expected +"}\n");
}
 
Example #14
Source File: LoadosophiaClient.java    From jmeter-bzm-plugins with Apache License 2.0 6 votes vote down vote up
@Override
public void handleSampleResults(List<SampleResult> list, BackendListenerContext backendListenerContext) {
    if (list != null && isOnlineInitiated) {
        try {
            JSONArray array = getDataToSend(list);
            log.info(array.toString());
            apiClient.sendOnlineData(array);
        } catch (IOException ex) {
            log.warn("Failed to send active test data", ex);
        }
        try {
            Thread.sleep(delay);
        } catch (InterruptedException e) {
            log.warn("Backend listener client thread was interrupted");
        }
    }
}
 
Example #15
Source File: ConsoleStatusLogger.java    From jmeter-plugins with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized void sampleOccurred(SampleEvent se) {
    // TODO: make the interval configurable
    long sec = System.currentTimeMillis() / 1000;
    if (sec != cur && count > 0) {
        if (cur == 0) {
            begin = sec;
        }

        log.debug(cur + " " + begin);
        flush(sec - begin);
        cur = sec;
    }
    SampleResult res = se.getResult();

    count++;
    sumRTime += res.getTime();
    sumLatency += res.getLatency();
    errors += res.isSuccessful() ? 0 : 1;
    threads = res.getAllThreads();
}
 
Example #16
Source File: FifoSizeTest.java    From jmeter-plugins with Apache License 2.0 6 votes vote down vote up
/**
 * Test of execute method, of class FifoSize.
 */
@Test
public void testExecute() throws Exception {
    System.out.println("execute");
    SampleResult previousResult = null;
    Sampler currentSampler = null;
    LinkedList<CompoundVariable> list;
    list = new LinkedList<>();
    list.add(new CompoundVariable("test"));
    list.add(new CompoundVariable("test"));
    FifoSize instance = new FifoSize();
    instance.setParameters(list);
    String expResult = "0";
    String result = instance.execute(null, null);
    Assert.assertEquals(expResult, result);
}
 
Example #17
Source File: LoadosophiaUploaderTest.java    From jmeter-bzm-plugins with Apache License 2.0 6 votes vote down vote up
@Test
public void testOnlineProcessor() throws InterruptedException {
    System.out.println("onlineProcessor");
    LoadosophiaUploader instance = new LoadosophiaUploaderEmul();
    instance.resetTest();
    instance.setUseOnline(true);
    instance.setStoreDir(TestJMeterUtils.getTempDir());
    instance.testStarted("");
    for (int i = 0; i < 100; i++) {
        SampleResult res = new SampleResult();
        res.setThreadName("test " + i);
        SampleEvent event = new SampleEvent(res, "test " + i);
        instance.sampleOccurred(event);
    }
    Thread.sleep(10);
    instance.testEnded("");
}
 
Example #18
Source File: StrReplace.java    From jmeter-plugins with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized String execute(SampleResult previousResult, Sampler currentSampler)
        throws InvalidVariableException {

    String totalString = getParameter(0).replace(getParameter(1), getParameter(2));

    JMeterVariables vars = getVariables();

    if (values.length > 3) {
        String varName = getParameter(3);
        if (vars != null && varName != null && varName.length() > 0) {// vars will be null on TestPlan
            vars.put(varName, totalString);
        }
    }

    return totalString;
}
 
Example #19
Source File: SetTest.java    From jmeter-cassandra with Apache License 2.0 6 votes vote down vote up
@Test
public void testSelectthesetle() {
    CassandraSampler cs = new CassandraSampler();

    cs.setProperty("sessionName",TESTSESSION);
    cs.setProperty("consistencyLevel", AbstractCassandaTestElement.ONE);
    cs.setProperty("resultVariable","rv");
    cs.setProperty("queryType", AbstractCassandaTestElement.SIMPLE);
    cs.setProperty("query", "SELECT * FROM " + TABLE + " WHERE key = 1");

    TestBeanHelper.prepare(cs);

    SampleResult res = cs.sample(new Entry());
    assertTrue(res.isSuccessful(), res.getResponseMessage());

    String rowdata = new String(res.getResponseData());
    logger.info(rowdata);
    assertEquals(rowdata, "key\ttheset\n" + "1" + "\t" + "{one,three,two}" + "\n");

}
 
Example #20
Source File: RosterAction.java    From jmeter-bzm-plugins with Apache License 2.0 6 votes vote down vote up
@Override
public SampleResult perform(JMeterXMPPSampler sampler, SampleResult res) throws Exception {
    Action action = Action.valueOf(sampler.getPropertyAsString(ACTION, Action.get_roster.toString()));
    Roster roster = sampler.getXMPPConnection().getRoster();
    String entry = sampler.getPropertyAsString(ENTRY);
    res.setSamplerData(action.toString() + ": " + entry);
    if (action == Action.get_roster) {
        res.setResponseData(rosterToString(roster).getBytes());
    } else if (action == Action.add_item) {
        roster.createEntry(entry, entry, new String[0]);
    } else if (action == Action.delete_item) {
        RosterEntry rosterEntry = roster.getEntry(entry);
        if (rosterEntry != null) {
            roster.removeEntry(rosterEntry);
        }
    }

    return res;
}
 
Example #21
Source File: JSONPathAssertionTest.java    From jmeter-plugins with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetResult_not_regexp() {
    System.out.println("not regexp");
    SampleResult samplerResult = new SampleResult();
    samplerResult.setResponseData("{\"myval\": \"some complicated value\"}".getBytes());

    JSONPathAssertion instance = new JSONPathAssertion();
    instance.setJsonPath("$.myval");
    instance.setJsonValidationBool(true);
    instance.setExpectedValue("some.+");
    AssertionResult result = instance.getResult(samplerResult);
    assertFalse(result.isFailure());

    instance.setIsRegex(false);
    AssertionResult result2 = instance.getResult(samplerResult);
    assertTrue(result2.isFailure());
}
 
Example #22
Source File: Base64Decode.java    From jmeter-plugins with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized String execute(SampleResult previousResult, Sampler currentSampler)
        throws InvalidVariableException {
    String sourceString = values[0].execute();

    String decodedValue = new String(Base64.decodeBase64(sourceString));
    if (values.length > 1) {
        String variableName = values[1].execute();
        if (variableName.length() > 0) {// Allow for empty name
            final JMeterVariables variables = getVariables();
            if (variables != null) {
                variables.put(variableName, decodedValue);
            }
        }
    }
    return decodedValue;
}
 
Example #23
Source File: TransactionsPerSecondGuiTest.java    From jmeter-plugins with Apache License 2.0 6 votes vote down vote up
/**
 * Test of add method, of class TransactionsPerSecondGui.
 */
@Test
public void testAdd()
{
    System.out.println("add");

    SampleResult res = new SampleResult();
    res.setAllThreads(1);
    res.setThreadName("test 1-2");
    TransactionsPerSecondGui instance = new TransactionsPerSecondGui();
    instance.add(res);
    res.sampleStart();
    try
    {
        Thread.sleep(10);
    } catch (InterruptedException ex)
    {
    }
    res.sampleEnd();
    instance.add(res);
}
 
Example #24
Source File: SendMessage.java    From jmeter-bzm-plugins with Apache License 2.0 6 votes vote down vote up
private SampleResult waitResponse(SampleResult res, String recipient) throws InterruptedException, SmackException {
    long time = 0;
    do {
        Iterator<Message> packets = responseMessages.iterator();
        Thread.sleep(conn.getPacketReplyTimeout() / 100); // optimistic
        while (packets.hasNext()) {
            Packet packet = packets.next();
            Message response = (Message) packet;
            if (XmppStringUtils.parseBareAddress(response.getFrom()).equals(recipient)) {
                packets.remove();
                res.setResponseData(response.toXML().toString().getBytes());
                if (response.getError() != null) {
                    res.setSuccessful(false);
                    res.setResponseCode("500");
                    res.setResponseMessage(response.getError().toString());
                }
                return res;
            }
        }
        time += conn.getPacketReplyTimeout() / 10;
        Thread.sleep(conn.getPacketReplyTimeout() / 10);
    } while (time < conn.getPacketReplyTimeout());
    throw new SmackException.NoResponseException();
}
 
Example #25
Source File: SendMessageTest.java    From jmeter-bzm-plugins with Apache License 2.0 6 votes vote down vote up
@Test
public void perform() throws Exception {
    SendMessage action = new SendMessage();
    XMPPConnectionMock connection = new XMPPConnectionMock();
    action.connected(connection);
    Message resp = new Message();
    resp.setFrom("[email protected]");
    resp.setBody(SendMessage.RESPONSE_MARKER);
    action.processPacket(resp);
    JMeterXMPPSampler sampler = new JMeterXMPPSamplerMock();
    sampler.getXMPPConnection().setFromMode(XMPPConnection.FromMode.USER);
    sampler.setProperty(SendMessage.RECIPIENT, "[email protected]");
    sampler.setProperty(SendMessage.WAIT_RESPONSE, true);
    SampleResult res = new SampleResult();
    action.perform(sampler, res);
    Assert.assertTrue(res.getResponseDataAsString().contains(SendMessage.RESPONSE_MARKER));
    Assert.assertTrue(res.getSamplerData().contains("from"));
}
 
Example #26
Source File: ResponseCodesPerSecondGuiTest.java    From jmeter-plugins with Apache License 2.0 6 votes vote down vote up
/**
 * Test of add method, of class ResponseCodesPerSecondGui.
 */
@Test
public void testAdd()
{
    System.out.println("add");
    SampleResult res = new SampleResult();
    res.setAllThreads(1);
    res.setThreadName("test 1-2");
    res.setResponseCode("200");
    ResponseCodesPerSecondGui instance = new ResponseCodesPerSecondGui();
    instance.add(res);
    res.sampleStart();
    try
    {
        Thread.sleep(10);
    } catch (InterruptedException ex)
    {
    }
    res.sampleEnd();
    instance.add(res);
}
 
Example #27
Source File: JSONPathExtractorTest.java    From jmeter-plugins with Apache License 2.0 6 votes vote down vote up
@Test
public void testReported1_1() {
    System.out.println("process reported");
    JMeterContext context = JMeterContextService.getContext();
    SampleResult res = new SampleResult();
    res.setResponseData(json2.getBytes());
    context.setPreviousResult(res);

    JSONPathExtractor instance = new JSONPathExtractor();
    instance.setVar("GroupID");
    instance.setJsonPath("$.data.groups[*].id");
    instance.setDefaultValue("NOTFOUND");
    instance.process();
    JMeterVariables vars = context.getVariables();
    assertNotEquals("NOTFOUND", vars.get("GroupID"));
    assertEquals("e02991f4-a95d-43dd-8eb0-fbc44349e238", vars.get("GroupID_1"));
}
 
Example #28
Source File: JSONPathAssertionTest.java    From jmeter-plugins with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetResult_list_negative() {
    System.out.println("getResult list-neg");
    SampleResult samplerResult = new SampleResult();
    samplerResult.setResponseData("{\"myval\": [{\"test\":1},{\"test\":2},{\"test\":3}]}".getBytes());

    JSONPathAssertion instance = new JSONPathAssertion();
    instance.setJsonPath("$.myval[*].test");
    instance.setJsonValidationBool(true);
    instance.setExpectedValue("5");
    AssertionResult expResult = new AssertionResult("");
    AssertionResult result = instance.getResult(samplerResult);
    assertEquals(expResult.getName(), result.getName());
    assertTrue(result.isFailure());
}
 
Example #29
Source File: AbstractIPSamplerTest.java    From jmeter-plugins with Apache License 2.0 5 votes vote down vote up
/**
 * Test of processIO method, of class AbstractIPSampler.
 */
@Test
public void testProcessIO() throws Exception {
    System.out.println("processIO");
    SampleResult res = null;
    AbstractIPSampler instance = new AbstractIPSamplerImpl();
    byte[] expResult = null;
    byte[] result = instance.processIO(res);
    assertEquals(expResult, result);
}
 
Example #30
Source File: BlazemeterAPIClientTest.java    From jmeter-bzm-plugins with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void testUserFlow() throws Exception {

    URL url = BlazemeterAPIClientTest.class.getResource("/responses.json");
    JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON(FileUtils.readFileToString(new File(url.getPath())), new JsonConfig());


    StatusNotifierCallbackTest.StatusNotifierCallbackImpl notifier = new StatusNotifierCallbackTest.StatusNotifierCallbackImpl();
    BlazeMeterReport report = new BlazeMeterReport();
    report.setShareTest(true);
    report.setProject("New project");
    report.setTitle("New test");
    report.setToken("123456");

    BlazeMeterHttpUtilsEmul emul = new BlazeMeterHttpUtilsEmul(notifier, "https://a.blazemeter.com/", "data_address", new BlazeMeterReport());
    for (Object resp : jsonArray) {
        emul.addEmul((JSON) resp);
    }
    BlazeMeterAPIClient apiClient = new BlazeMeterAPIClient(emul, notifier, report);
    apiClient.prepare();

    // if share user test
    String linkPublic = apiClient.startOnline();
    System.out.println(linkPublic);
    assertFalse(linkPublic.isEmpty());
    assertEquals("https://a.blazemeter.com//app/?public-token=public_test_token#/masters/master_id/summary", linkPublic);

    // if private user test
    report.setShareTest(false);
    String linkPrivate = apiClient.startOnline();
    System.out.println(linkPrivate);
    assertFalse(linkPrivate.isEmpty());
    assertEquals("https://a.blazemeter.com//app/#/masters/master_id", linkPrivate);


    List<SampleResult> sampleResults = generateResults();
    apiClient.sendOnlineData(JSONConverter.convertToJSON(sampleResults, sampleResults));
    apiClient.endOnline();
}