@Test public void testProcess_list() { System.out.println("process list"); JMeterContext context = JMeterContextService.getContext(); SampleResult res = new SampleResult(); res.setResponseData("{\"myval\": [{\"test\":1},{\"test\":2},{\"test\":null}]}".getBytes()); context.setPreviousResult(res); JSONPathExtractor instance = new JSONPathExtractor(); instance.setDefaultValue("DEFAULT"); instance.setVar("test"); instance.setJsonPath("$.myval[*].test"); instance.process(); JMeterVariables vars = context.getVariables(); assertEquals("[1,2,null]", vars.get("test")); assertEquals("1", vars.get("test_1")); assertEquals("2", vars.get("test_2")); assertEquals("null", vars.get("test_3")); // test for cleaning prev vars res.setResponseData("{\"myval\": [{\"test\":1},{\"test\":2}]}".getBytes()); instance.process(); assertEquals("[1,2]", vars.get("test")); assertEquals("1", vars.get("test_1")); assertEquals("2", vars.get("test_2")); assertEquals(null, vars.get("test_3")); }
public void process() { JMeterVariables vars = JMeterContextService.getContext().getVariables(); String threadId = vars.getObject(THREAD_ID).toString(); SampleResult previousResult = JMeterContextService.getContext().getPreviousResult(); Map<String, String> map = (Map<String, String>) vars.getObject(mapName); map.put(threadId, previousResult.getResponseDataAsString()); }
public void process() { Sampler sampler = JMeterContextService.getContext().getCurrentSampler(); SampleResult responseText = JMeterContextService.getContext().getPreviousResult(); if (responseText == null) { return; } initRegex(getArgumentName()); String text = new String(responseText.getResponseData()); Perl5Matcher matcher = JMeterUtils.getMatcher(); String value = ""; if (matcher.contains(text, case1)) { MatchResult result = matcher.getMatch(); value = result.group(1); } else if (matcher.contains(text, case2)) { MatchResult result = matcher.getMatch(); value = result.group(1); } else if (matcher.contains(text, case3)) { MatchResult result = matcher.getMatch(); value = result.group(1); } else if (matcher.contains(text, case4)) { MatchResult result = matcher.getMatch(); value = result.group(1); } modify((HTTPSampler) sampler, value); }
@Test public void testAdd() { System.out.println("add"); SampleResult res = new SampleResult(); res.setAllThreads(1); res.setThreadName("test 1-2"); res.setStampAndTime(System.currentTimeMillis(), 1000); ResponseTimesDistributionGui instance = new ResponseTimesDistributionGui(); instance.add(res); }
/** * ********************************************************** !ToDoo (Method description) * * @param response !ToDo (Parameter description) * @return !ToDo (Return description) ********************************************************* */ public AssertionResult getResult(SampleResult response) { AssertionResult result; if (!response.isSuccessful()) { result = new AssertionResult(); result.setError(true); result.setFailureMessage(new String((byte[]) response.getResponseData())); return result; } result = evaluateResponse(response); return result; }
/** {@inheritDoc} */ @Override public SampleResult sample(Entry entry) { SampleResult result = new SampleResult(); result.sampleStart(); boolean success = false; if (!check(result)) { return result; } success = doDisconnect(); setupResult(result, disconnectCode, success); return result; }
/** * 結果の作成補助関数 * * @param result resultオブジェクト * @param reason 文字列の結果データ * @param success 成功したかどうかフラグ */ protected void setupResult(SampleResult result, String reason, boolean success) { // サンプル動作完了 result.sampleEnd(); StringBuilder str = new StringBuilder(); str.append(getName()); str.append("["); str.append(Thread.currentThread().getName()); str.append("]"); result.setSampleLabel(str.toString()); result.setSuccessful(success); result.setResponseData(reason.getBytes()); result.setDataType(SampleResult.TEXT); }
/** Test of getCurrentThreadCount method, of class AbstractVsThreadVisualizer. */ @Test public void testGetCurrentThreadCount() { System.out.println("getCurrentThreadCount"); long now = System.currentTimeMillis(); SampleResult sample = new SampleResult(); sample.setAllThreads(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); }
/** {@inheritDoc} */ public void renderResult(SampleResult sampleResult) { if (!sampleResult.getContentType().equals("application/x-amf")) { xmlDataField.setText( AmfResources.getResString("invalid_amf_content_type") + sampleResult.getContentType()); } else if (sampleResult.getResponseData().length == 0) { xmlDataField.setText(AmfResources.getResString("empty_response")); } else if (sampleResult.getResponseData().length > MAX_RESPONSE_SIZE * 1024) { xmlDataField.setText( AmfResources.getResString("response_too_large") + MAX_RESPONSE_SIZE + "k"); } else { String xml = AmfXmlConverter.convertAmfMessageToXml(sampleResult.getResponseData()); xmlDataField.setText(xml); } xmlDataField.setCaretPosition(0); }
@Override public void add(final SampleResult res) { final String sampleLabel = res.getSampleLabel(useGroupName.isSelected()); JMeterUtils.runSafe( new Runnable() { @Override public void run() { Calculator row = null; synchronized (lock) { row = tableRows.get(sampleLabel); if (row == null) { row = new Calculator(sampleLabel); tableRows.put(row.getLabel(), row); model.insertRow(row, model.getRowCount() - 1); } } /* * Synch is needed because multiple threads can update the counts. */ synchronized (row) { row.addSample(res); } Calculator tot = tableRows.get(TOTAL_ROW_LABEL); synchronized (tot) { tot.addSample(res); } model.fireTableDataChanged(); } }); }
public void run() { ResponseAssertion assertion = new ResponseAssertion(RESPONSE_DATA, CONTAINS, TEST_PATTERN); SampleResult response = new SampleResult(); response.setResponseData(TEST_STRING.getBytes()); for (int i = 0; i < 100; i++) { AssertionResult result; result = assertion.evaluateResponse(response); if (result.isFailure() || result.isError()) { failed++; } } synchronized (Test.this) { threadsRunning--; Test.this.notify(); } }
@Override public void add(final SampleResult res) { final String sampleLabel = res.getSampleLabel(); // Sampler selection if (columnSelection.isSelected() && pattern != null) { matcher = pattern.matcher(sampleLabel); } if ((matcher == null) || (matcher.find())) { JMeterUtils.runSafe( new Runnable() { @Override public void run() { SamplingStatCalculator row = null; synchronized (lock) { row = tableRows.get(sampleLabel); if (row == null) { row = new SamplingStatCalculator(sampleLabel); tableRows.put(row.getLabel(), row); model.insertRow(row, model.getRowCount() - 1); } } row.addSample(res); tableRows.get(TOTAL_ROW_LABEL).addSample(res); model.fireTableDataChanged(); } }); } }
@Test public void testReported1_3() { 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[?(@.name==Avtovaz)].id"); instance.setDefaultValue("NOTFOUND"); instance.process(); JMeterVariables vars = context.getVariables(); assertEquals("NOTFOUND", vars.get("GroupID")); }
@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")); }
@Test public void testProcess() { System.out.println("process"); JMeterContext context = JMeterContextService.getContext(); SampleResult res = new SampleResult(); res.setResponseData(json.getBytes()); context.setPreviousResult(res); JSONPathExtractor instance = new JSONPathExtractor(); instance.setDefaultValue("DEFAULT"); instance.setVar("test"); instance.setJsonPath("$.store.book[*].author"); instance.process(); JMeterVariables vars = context.getVariables(); assertEquals( "[\"Nigel Rees\",\"Evelyn Waugh\",\"Herman Melville\",\"J. R. R. Tolkien\"]", vars.get("test")); }
private ByteArrayOutputStream readResponse(SampleResult res) throws IOException { ByteArrayOutputStream response = new ByteArrayOutputStream(); int cnt = 0; ByteBuffer recvBuf = getRecvBuf(); recvBuf.clear(); if ((cnt = channel.read(recvBuf)) != -1) { res.latencyEnd(); // log.debug("Read " + recvBuf.toString()); recvBuf.flip(); byte[] bytes = new byte[cnt]; recvBuf.get(bytes); response.write(bytes); recvBuf.clear(); } res.sampleEnd(); res.setBytes(response.size()); return response; }
@Ignore @Test // FIXME: we need to solve this one day public void testReported2() { System.out.println("process reported"); JMeterContext context = JMeterContextService.getContext(); SampleResult res = new SampleResult(); res.setResponseData(json3.getBytes()); context.setPreviousResult(res); JSONPathExtractor instance = new JSONPathExtractor(); instance.setVar("var"); instance.setJsonPath("$.data[?(@.attr.value>0)][0].attr"); instance.setDefaultValue("NOTFOUND"); instance.process(); JMeterVariables vars = context.getVariables(); assertNotEquals("NOTFOUND", vars.get("var")); assertEquals("{value=1}", vars.get("var")); }
public SampleResult runTest(JavaSamplerContext arg0) { log.info("<<<发送地址:" + conf.getBaseUri() + conf.getApiUri()); log.info("<<<发送数据:" + sb.toString()); try { HttpSend.doPost(conf, headMsg, sb.toString(), log); } catch (Exception e) { log.info("ERROR...", e); } results.setSuccessful(true); return results; }
/** * Executes a the given command inside a short-lived channel in the session. * * <p>Performance could be likely improved by reusing a single channel, though the gains would be * minimal compared to sharing the Session. * * @param session Session in which to create the channel * @return All standard output from the command * @throws JSchException * @throws SftpException * @throws IOException */ private String doFileTransfer(Session session, String src, String dst, SampleResult res) throws JSchException, SftpException, IOException { StringBuilder sb = new StringBuilder(); ChannelSftp channel = (ChannelSftp) session.openChannel("sftp"); res.sampleStart(); channel.connect(); if (SFTP_COMMAND_GET.equals(action)) { if (!printFile) { channel.get(src, dst); } else { BufferedReader br = new BufferedReader(new InputStreamReader(channel.get(src))); for (String line = br.readLine(); line != null; line = br.readLine()) { sb.append(line); sb.append("\n"); } } } else if (SFTP_COMMAND_PUT.equals(action)) { channel.put(src, dst); } else if (SFTP_COMMAND_LS.equals(action)) { List<ChannelSftp.LsEntry> ls = channel.ls(src); for (ChannelSftp.LsEntry line : ls) { sb.append(line.getLongname()); sb.append("\n"); } } else if (SFTP_COMMAND_RM.equals(action)) { channel.rm(src); } else if (SFTP_COMMAND_RMDIR.equals(action)) { channel.rmdir(src); } else if (SFTP_COMMAND_RENAME.equals(action)) { channel.rename(src, dst); } res.sampleEnd(); channel.disconnect(); return sb.toString(); }
/** * Make sure the response satisfies the specified assertion requirements. * * @param response an instance of SampleResult * @return an instance of AssertionResult */ private AssertionResult evaluateResponse(SampleResult response) { boolean pass = true; boolean not = (NOT & getTestType()) > 0; AssertionResult result = new AssertionResult(); if (response.getResponseData() == null) { return setResultForNull(result); } String responseString = new String(response.getResponseData()); try { // Get the Matcher for this thread Perl5Matcher localMatcher = (Perl5Matcher) matcher.get(); PropertyIterator iter = getTestStrings().iterator(); while (iter.hasNext()) { String stringPattern = iter.next().getStringValue(); Pattern pattern = patternCache.getPattern(stringPattern, Perl5Compiler.READ_ONLY_MASK); boolean found; if ((CONTAINS & getTestType()) > 0) { found = localMatcher.contains(responseString, pattern); } else { found = localMatcher.matches(responseString, pattern); } pass = not ? !found : found; if (!pass) { result.setFailure(true); result.setFailureMessage( "Test Failed, expected " + notMessage + failMessage + stringPattern); break; } } if (pass) { result.setFailure(false); } result.setError(false); } catch (MalformedCachePatternException e) { result.setError(true); result.setFailure(false); result.setFailureMessage("Bad test configuration" + e); } return result; }
// @Override public SampleResult runTest(JavaSamplerContext arg0) { JMeterVariables vars = JMeterContextService.getContext().getVariables(); vars.put("demo", "demoVariableContent"); setupValues(arg0); SampleResult sampleResult = new SampleResult(); sampleResult.sampleStart(); System.out.println("/level/du/parents: " + level + ", " + du + ", " + parents); // JUnitCore junit = new JUnitCore(); // Result result = junit.run(AuthenticationTest.class); // if (result.getFailureCount() > 0) { // sampleResult.setSuccessful(false); // sampleResult.setResponseCode("301"); // sampleResult.setResponseMessage("FailureCount: " // + result.getFailureCount()); // } else { sampleResult.setSuccessful(true); sampleResult.setResponseCodeOK(); sampleResult.setResponseMessageOK(); // } sampleResult.sampleEnd(); return sampleResult; }
@Override protected byte[] processIO(SampleResult res) throws Exception { if (channel == null || !channel.isOpen()) { try { channel = (DatagramChannel) getChannel(); } catch (IOException ex) { log.error("Cannot open channel", ex); } } ByteBuffer sendBuf = encoder.encode(getRequestData()); while (sendBuf.remaining() > 0) { channel.write(sendBuf); } if (!isWaitResponse()) { res.latencyEnd(); res.sampleEnd(); if (isCloseChannel()) { channel.close(); } return new byte[0]; } try { ByteArrayOutputStream response = readResponse(res); if (isCloseChannel()) { channel.close(); } return encoder.decode(response.toByteArray()); } catch (IOException ex) { channel.close(); throw ex; } }
public void testGrabSessionId4() throws Exception { String html = "href='index.html;%24sid%24KQNq3AAADQZoEQAxlkX8uQV5bjqVBPbT'"; response = new SampleResult(); response.setResponseData(html.getBytes()); URLRewritingModifier mod = new URLRewritingModifier(); mod.setArgumentName("%24sid%24"); mod.setPathExtension(true); mod.setPathExtensionNoEquals(true); HTTPSampler sampler = createSampler(); context.setCurrentSampler(sampler); context.setPreviousResult(response); mod.process(); Arguments args = sampler.getArguments(); assertEquals("index.html;%24sid%24KQNq3AAADQZoEQAxlkX8uQV5bjqVBPbT", sampler.getPath()); }
public void testGrabSessionId3() throws Exception { String html = "href='index.html?session_id=jfdkjdkfjddkfdfjkdjfdf'"; response = new SampleResult(); response.setResponseData(html.getBytes()); URLRewritingModifier mod = new URLRewritingModifier(); mod.setArgumentName("session_id"); HTTPSampler sampler = createSampler(); context.setCurrentSampler(sampler); context.setPreviousResult(response); mod.process(); Arguments args = sampler.getArguments(); assertEquals( "jfdkjdkfjddkfdfjkdjfdf", ((Argument) args.getArguments().get(0).getObjectValue()).getValue()); }
protected void showRenderedResponse(String response, SampleResult res, boolean embedded) { if (response == null) { results.setText(""); return; } int htmlIndex = response.indexOf("<HTML"); // could be <HTML lang=""> // $NON-NLS-1$ // Look for a case variation if (htmlIndex < 0) { htmlIndex = response.indexOf("<html"); // ditto // $NON-NLS-1$ } // If we still can't find it, just try using all of the text if (htmlIndex < 0) { htmlIndex = 0; } String html = response.substring(htmlIndex); /* * To disable downloading and rendering of images and frames, enable the * editor-kit. The Stream property can then be */ // Must be done before setContentType results.setEditorKitForContentType(TEXT_HTML, embedded ? defaultHtmlEditor : customisedEditor); results.setContentType(TEXT_HTML); if (embedded) { // Allow JMeter to render frames (and relative images) // Must be done after setContentType [Why?] results.getDocument().putProperty(Document.StreamDescriptionProperty, res.getURL()); } /* * Get round problems parsing <META http-equiv='content-type' * content='text/html; charset=utf-8'> See * http://issues.apache.org/bugzilla/show_bug.cgi?id=23315 * * Is this due to a bug in Java? */ results.getDocument().putProperty("IgnoreCharsetDirective", Boolean.TRUE); // $NON-NLS-1$ results.setText(html); results.setCaretPosition(0); resultsScrollPane.setViewportView(results); }
public void testGrabSessionId() throws Exception { String html = "location: http://server.com/index.html?session_id=jfdkjdkf%20jddkfdfjkdjfdf%22;"; response = new SampleResult(); response.setResponseData(html.getBytes()); URLRewritingModifier mod = new URLRewritingModifier(); mod.setArgumentName("session_id"); HTTPSampler sampler = createSampler(); sampler.addArgument("session_id", "adfasdfdsafasdfasd"); context.setCurrentSampler(sampler); context.setPreviousResult(response); mod.process(); Arguments args = sampler.getArguments(); assertEquals( "jfdkjdkf jddkfdfjkdjfdf\"", ((Argument) args.getArguments().get(0).getObjectValue()).getValue()); assertEquals( "http://server.com/index.html?session_id=jfdkjdkf+jddkfdfjkdjfdf%22", sampler.toString()); }
@Override public AssertionResult getResult(SampleResult samplerResult) { AssertionResult result = new AssertionResult(getName()); byte[] responseData = samplerResult.getResponseData(); if (responseData.length == 0) { return result.setResultForNull(); } if (isJsonValidationBool()) { try { if (checkJSONPathWithValidation( new String(responseData, "UTF-8"), getJsonPath(), getExpectedValue())) { result.setFailure(false); result.setFailureMessage(""); } } catch (ParseException e) { result.setFailure(true); result.setFailureMessage(e.getClass().toString() + " - " + e.getMessage()); } catch (Exception e) { result.setFailure(true); result.setFailureMessage(e.getMessage()); } } if (!isJsonValidationBool()) { try { if (checkJSONPathWithoutValidation(new String(responseData), getJsonPath())) { result.setFailure(false); result.setFailureMessage(""); } } catch (ParseException e) { result.setFailure(true); result.setFailureMessage(e.getClass().toString() + " - " + e.getMessage()); } catch (Exception e) { result.setFailure(true); result.setFailureMessage(e.getMessage()); } } return result; }
private String getInputString(SampleResult result) { String inputString = useUrl() ? result.getUrlAsString() // Bug 39707 : useHeaders() ? result.getResponseHeaders() : useRequestHeaders() ? result.getRequestHeaders() : useCode() ? result.getResponseCode() // Bug 43451 : useMessage() ? result.getResponseMessage() // Bug 43451 : useUnescapedBody() ? StringEscapeUtils.unescapeHtml4(result.getResponseDataAsString()) : useBodyAsDocument() ? Document.getTextFromDocument(result.getResponseData()) : result.getResponseDataAsString() // Bug 36898 ; if (log.isDebugEnabled()) { log.debug("Input = " + inputString); } return inputString; }
/* * @param response @return */ public AssertionResult getResult(SampleResult response) { AssertionResult result = new AssertionResult(getName()); result.setFailure(false); byte[] resultData = response.getResponseData(); if (resultData.length == 0) { result.setError(false); result.setFailure(true); result.setFailureMessage("Response was null"); return result; } // no point in checking if we don't have anything to compare against if (getAllowedMD5Hex().equals("")) { result.setError(false); result.setFailure(true); result.setFailureMessage("MD5Hex to test against is empty"); return result; } String md5Result = baMD5Hex(resultData); // String md5Result = DigestUtils.md5Hex(resultData); if (!md5Result.equalsIgnoreCase(getAllowedMD5Hex())) { result.setFailure(true); Object[] arguments = {md5Result, getAllowedMD5Hex()}; String message = MessageFormat.format( JMeterUtils.getResString("md5hex_assertion_failure"), arguments); // $NON-NLS-1$ result.setFailureMessage(message); } return result; }
@Override public SampleResult runTest(JavaSamplerContext arg0) { SampleResult results = new SampleResult(); results.setSamplerData(String.valueOf(da)); results.setSamplerData(String.valueOf(db)); results.sampleStart(); // Random rand = new Random(); for (int i = 0; i < 1; i++) { // System.out.println("da=" + da + ",db=" + db); double d = compute(); // System.out.println("result="+ d); results.setSamplerData(String.valueOf(d)); // compute(rand.nextDouble(), rand.nextDouble()); } results.sampleEnd(); results.setSuccessful(true); return results; }