Java Code Examples for org.apache.jmeter.samplers.SampleResult

The following examples show how to use org.apache.jmeter.samplers.SampleResult. These examples are extracted from open source projects. 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 Project: jmeter-cassandra   Source File: SetTest.java    License: 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 2
@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 3
Source Project: jmeter-cassandra   Source File: TupleTest.java    License: 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 4
Source Project: jmeter-cassandra   Source File: UDTTest.java    License: 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 5
Source Project: jmeter-plugins-webdriver   Source File: WebDriverSampler.java    License: 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 6
@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 7
Source Project: jmeter-plugins   Source File: LowerCaseTest.java    License: 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 8
Source Project: jmeter-plugins   Source File: JSONPathExtractorTest.java    License: 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 9
/**
 * 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 10
@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 11
@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 12
Source Project: jmeter-cassandra   Source File: SimpleQueryTest.java    License: 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 13
Source Project: jmeter-bzm-plugins   Source File: LoadosophiaClient.java    License: 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 14
Source Project: jmeter-plugins   Source File: JSONPathExtractorTest.java    License: 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 15
Source Project: jmeter-plugins   Source File: ConsoleStatusLogger.java    License: 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 Project: jmeter-plugins   Source File: FifoSizeTest.java    License: 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
@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 Project: jmeter-plugins   Source File: StrReplace.java    License: 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 Project: jmeter-cassandra   Source File: SetTest.java    License: 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 Project: jmeter-bzm-plugins   Source File: RosterAction.java    License: 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 Project: jmeter-plugins   Source File: JSONPathAssertionTest.java    License: 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 Project: jmeter-plugins   Source File: Base64Decode.java    License: 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
/**
 * 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 Project: jmeter-bzm-plugins   Source File: SendMessage.java    License: 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 Project: jmeter-bzm-plugins   Source File: SendMessageTest.java    License: 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
/**
 * 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 Project: jmeter-plugins   Source File: UpperCaseTest.java    License: 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 28
Source Project: jmeter-plugins   Source File: HTTPRawSampler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public SampleResult sample(Entry entry) {
    SampleResult res = super.sample(entry);
    if (isParseResult()) {
        parseResponse(res);
    }
    return res;
}
 
Example 29
/**
 * Description of the Method
 *
 * @param samplerContext Description of the Parameter
 * @return Description of the Return Value
 */
public SampleResult runTest( JavaSamplerContext samplerContext )
{
    SampleResult sampleResult = new SampleResult();
    try
    {
        sampleResult.sampleStart();
        //String message = "FT CreateSession TID: " + getThreadId() + " UID:" + userId + " CTR:" + ctr++;
        //LOG.info( message );
        //System.out.println( message );
        assertNotNull( accessMgr );
        Session session;
        User user = new User();
        // positive test case:
        user.setUserId( userId );
        user.setPassword( "secret" );
        session = accessMgr.createSession( user, false );
        assertNotNull( session );
        assertTrue( session.isAuthenticated() );
        sampleResult.sampleEnd();
        sampleResult.setBytes(1);
        sampleResult.setResponseMessage("test completed TID: " + getThreadId() + " UID: " + userId);
        sampleResult.setSuccessful(true);
    }
    catch ( org.apache.directory.fortress.core.SecurityException se )
    {
        System.out.println( "ThreadId:" + getThreadId() + "Error running test: " + se );
        se.printStackTrace();
        sampleResult.setSuccessful( false );
    }

    return sampleResult;
}
 
Example 30
Source Project: jmeter-plugins   Source File: CompositeGraphGui.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void add(SampleResult sr) {
    super.add(sr);
    long time = System.currentTimeMillis();

    if (time > lastUpdate + 1000) {
        lastUpdate = time;
        updateGui();
    }
}