Search in sources :

Example 21 with JMeterVariables

use of org.apache.jmeter.threads.JMeterVariables in project jmeter-plugins by undera.

the class JSONPathExtractorTest method testProcess.

@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"));
}
Also used : JMeterVariables(org.apache.jmeter.threads.JMeterVariables) JMeterContext(org.apache.jmeter.threads.JMeterContext) SampleResult(org.apache.jmeter.samplers.SampleResult) Test(org.junit.Test)

Example 22 with JMeterVariables

use of org.apache.jmeter.threads.JMeterVariables in project jmeter-plugins by undera.

the class HtmlUnitDriverConfigTest method createConfig.

@Before
public void createConfig() {
    config = new HtmlUnitDriverConfig();
    variables = new JMeterVariables();
    JMeterContextService.getContext().setVariables(variables);
}
Also used : JMeterVariables(org.apache.jmeter.threads.JMeterVariables) Before(org.junit.Before)

Example 23 with JMeterVariables

use of org.apache.jmeter.threads.JMeterVariables in project jmeter-plugins by undera.

the class ParameterizedController method processVariables.

private void processVariables() {
    final Arguments args1 = (Arguments) this.getUserDefinedVariablesAsProperty().getObjectValue();
    Arguments args = (Arguments) args1.clone();
    final JMeterVariables vars = JMeterContextService.getContext().getVariables();
    Iterator<Entry<String, String>> it = args.getArgumentsAsMap().entrySet().iterator();
    Entry<String, String> var;
    while (it.hasNext()) {
        var = it.next();
        log.debug("Setting " + var.getKey() + "=" + var.getValue());
        vars.put(var.getKey(), var.getValue());
    }
}
Also used : JMeterVariables(org.apache.jmeter.threads.JMeterVariables) Entry(java.util.Map.Entry) Arguments(org.apache.jmeter.config.Arguments)

Example 24 with JMeterVariables

use of org.apache.jmeter.threads.JMeterVariables in project jmeter-plugins by undera.

the class RedisDataSet method iterationStart.

@Override
public void iterationStart(LoopIterationEvent event) {
    Jedis connection = null;
    try {
        connection = pool.getResource();
        String line = null;
        if (getMode.equals(GetMode.RANDOM_REMOVE)) {
            line = connection.lpop(redisKey);
        } else {
            line = connection.srandmember(redisKey);
        }
        if (line == null) {
            // i.e. no more data (nil)
            throw new JMeterStopThreadException("End of redis data detected, thread will exit");
        }
        final String names = variableNames;
        if (vars == null) {
            vars = JOrphanUtils.split(names, ",");
        }
        final JMeterContext context = getThreadContext();
        JMeterVariables threadVars = context.getVariables();
        String[] values = JOrphanUtils.split(line, delimiter, false);
        for (int a = 0; a < vars.length && a < values.length; a++) {
            threadVars.put(vars[a], values[a]);
        }
    } finally {
        pool.returnResource(connection);
    }
}
Also used : JMeterStopThreadException(org.apache.jorphan.util.JMeterStopThreadException) Jedis(redis.clients.jedis.Jedis) JMeterVariables(org.apache.jmeter.threads.JMeterVariables) JMeterContext(org.apache.jmeter.threads.JMeterContext)

Example 25 with JMeterVariables

use of org.apache.jmeter.threads.JMeterVariables in project jmeter by apache.

the class HTTPHC4Impl method sample.

@Override
protected HTTPSampleResult sample(URL url, String method, boolean areFollowingRedirect, int frameDepth) {
    if (log.isDebugEnabled()) {
        log.debug("Start : sample {} method {} followingRedirect {} depth {}", url, method, areFollowingRedirect, frameDepth);
    }
    JMeterVariables jMeterVariables = JMeterContextService.getContext().getVariables();
    HTTPSampleResult res = createSampleResult(url, method);
    CloseableHttpClient httpClient = null;
    HttpRequestBase httpRequest = null;
    HttpContext localContext = new BasicHttpContext();
    HttpClientContext clientContext = HttpClientContext.adapt(localContext);
    clientContext.setAttribute(CONTEXT_ATTRIBUTE_AUTH_MANAGER, getAuthManager());
    HttpClientKey key = createHttpClientKey(url);
    MutableTriple<CloseableHttpClient, AuthState, PoolingHttpClientConnectionManager> triple;
    try {
        triple = setupClient(key, jMeterVariables, clientContext);
        httpClient = triple.getLeft();
        URI uri = url.toURI();
        httpRequest = createHttpRequest(uri, method, areFollowingRedirect);
        // can throw IOException
        setupRequest(url, httpRequest, res);
    } catch (Exception e) {
        res.sampleStart();
        res.sampleEnd();
        errorResult(e, res);
        return res;
    }
    setupClientContextBeforeSample(jMeterVariables, localContext);
    res.sampleStart();
    final CacheManager cacheManager = getCacheManager();
    if (cacheManager != null && HTTPConstants.GET.equalsIgnoreCase(method) && cacheManager.inCache(url, httpRequest.getAllHeaders())) {
        return updateSampleResultForResourceInCache(res);
    }
    CloseableHttpResponse httpResponse = null;
    try {
        currentRequest = httpRequest;
        handleMethod(method, res, httpRequest, localContext);
        // store the SampleResult in LocalContext to compute connect time
        localContext.setAttribute(CONTEXT_ATTRIBUTE_SAMPLER_RESULT, res);
        // perform the sample
        httpResponse = executeRequest(httpClient, httpRequest, localContext, url);
        saveProxyAuth(triple, localContext);
        if (log.isDebugEnabled()) {
            log.debug("Headers in request before:{}", Arrays.asList(httpRequest.getAllHeaders()));
        }
        // Needs to be done after execute to pick up all the headers
        final HttpRequest request = (HttpRequest) localContext.getAttribute(HttpCoreContext.HTTP_REQUEST);
        if (log.isDebugEnabled()) {
            log.debug("Headers in request after:{}, in localContext#request:{}", Arrays.asList(httpRequest.getAllHeaders()), Arrays.asList(request.getAllHeaders()));
        }
        extractClientContextAfterSample(jMeterVariables, localContext);
        // We've finished with the request, so we can add the LocalAddress to it for display
        if (localAddress != null) {
            request.addHeader(HEADER_LOCAL_ADDRESS, localAddress.toString());
        }
        res.setRequestHeaders(getAllHeadersExceptCookie(request));
        Header contentType = httpResponse.getLastHeader(HTTPConstants.HEADER_CONTENT_TYPE);
        if (contentType != null) {
            String ct = contentType.getValue();
            res.setContentType(ct);
            res.setEncodingAndType(ct);
        }
        HttpEntity entity = httpResponse.getEntity();
        if (entity != null) {
            res.setResponseData(readResponse(res, entity.getContent(), entity.getContentLength()));
        }
        // Done with the sampling proper.
        res.sampleEnd();
        currentRequest = null;
        // Now collect the results into the HTTPSampleResult:
        StatusLine statusLine = httpResponse.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        res.setResponseCode(Integer.toString(statusCode));
        res.setResponseMessage(statusLine.getReasonPhrase());
        res.setSuccessful(isSuccessCode(statusCode));
        res.setResponseHeaders(getResponseHeaders(httpResponse));
        if (res.isRedirect()) {
            final Header headerLocation = httpResponse.getLastHeader(HTTPConstants.HEADER_LOCATION);
            if (headerLocation == null) {
                // HTTP protocol violation, but avoids NPE
                throw new IllegalArgumentException("Missing location header in redirect for " + httpRequest.getRequestLine());
            }
            String redirectLocation = headerLocation.getValue();
            res.setRedirectLocation(redirectLocation);
        }
        // record some sizes to allow HTTPSampleResult.getBytes() with different options
        long headerBytes = // condensed length (without \r)
        (long) res.getResponseHeaders().length() + // Add \r for each header
        (long) httpResponse.getAllHeaders().length + // Add \r for initial header
        1L + // final \r\n before data
        2L;
        HttpConnectionMetrics metrics = (HttpConnectionMetrics) localContext.getAttribute(CONTEXT_ATTRIBUTE_METRICS);
        long totalBytes = metrics.getReceivedBytesCount();
        res.setHeadersSize((int) headerBytes);
        res.setBodySize(totalBytes - headerBytes);
        res.setSentBytes((Long) localContext.getAttribute(CONTEXT_ATTRIBUTE_SENT_BYTES));
        if (log.isDebugEnabled()) {
            long total = res.getHeadersSize() + res.getBodySizeAsLong();
            log.debug("ResponseHeadersSize={} Content-Length={} Total={}", res.getHeadersSize(), res.getBodySizeAsLong(), total);
        }
        // If we redirected automatically, the URL may have changed
        if (getAutoRedirects()) {
            HttpUriRequest req = (HttpUriRequest) localContext.getAttribute(HttpCoreContext.HTTP_REQUEST);
            HttpHost target = (HttpHost) localContext.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
            URI redirectURI = req.getURI();
            if (redirectURI.isAbsolute()) {
                res.setURL(redirectURI.toURL());
            } else {
                res.setURL(new URL(new URL(target.toURI()), redirectURI.toString()));
            }
        }
        // Store any cookies received in the cookie manager:
        saveConnectionCookies(httpResponse, res.getURL(), getCookieManager());
        // Save cache information
        if (cacheManager != null) {
            cacheManager.saveDetails(httpResponse, res);
        }
        // Follow redirects and download page resources if appropriate:
        res = resultProcessing(areFollowingRedirect, frameDepth, res);
        if (!isSuccessCode(statusCode)) {
            EntityUtils.consumeQuietly(httpResponse.getEntity());
        }
    } catch (IOException e) {
        log.debug("IOException", e);
        if (res.getEndTime() == 0) {
            res.sampleEnd();
        }
        // pick up headers if failed to execute the request
        if (res.getRequestHeaders() != null) {
            log.debug("Overwriting request old headers: {}", res.getRequestHeaders());
        }
        res.setRequestHeaders(getAllHeadersExceptCookie((HttpRequest) localContext.getAttribute(HttpCoreContext.HTTP_REQUEST)));
        errorResult(e, res);
        return res;
    } catch (RuntimeException e) {
        log.debug("RuntimeException", e);
        if (res.getEndTime() == 0) {
            res.sampleEnd();
        }
        errorResult(e, res);
        return res;
    } finally {
        JOrphanUtils.closeQuietly(httpResponse);
        currentRequest = null;
        JMeterContextService.getContext().getSamplerContext().remove(CONTEXT_ATTRIBUTE_PARENT_SAMPLE_CLIENT_STATE);
    }
    return res;
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) HttpEntity(org.apache.http.HttpEntity) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) URI(java.net.URI) URL(java.net.URL) HttpConnectionMetrics(org.apache.http.HttpConnectionMetrics) JMeterVariables(org.apache.jmeter.threads.JMeterVariables) HttpHost(org.apache.http.HttpHost) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) CacheManager(org.apache.jmeter.protocol.http.control.CacheManager) HttpRequest(org.apache.http.HttpRequest) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpContext(org.apache.http.protocol.HttpContext) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) HttpClientContext(org.apache.http.client.protocol.HttpClientContext) IOException(java.io.IOException) GeneralSecurityException(java.security.GeneralSecurityException) HttpException(org.apache.http.HttpException) PrivilegedActionException(java.security.PrivilegedActionException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) MalformedURLException(java.net.MalformedURLException) PoolingHttpClientConnectionManager(org.apache.http.impl.conn.PoolingHttpClientConnectionManager) StatusLine(org.apache.http.StatusLine) Header(org.apache.http.Header) BufferedHeader(org.apache.http.message.BufferedHeader) AuthState(org.apache.http.auth.AuthState)

Aggregations

JMeterVariables (org.apache.jmeter.threads.JMeterVariables)193 SampleResult (org.apache.jmeter.samplers.SampleResult)71 JMeterContext (org.apache.jmeter.threads.JMeterContext)64 BeforeEach (org.junit.jupiter.api.BeforeEach)46 CompoundVariable (org.apache.jmeter.engine.util.CompoundVariable)27 Test (org.junit.jupiter.api.Test)24 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)19 Test (org.junit.Test)16 JSONPostProcessor (org.apache.jmeter.extractor.json.jsonpath.JSONPostProcessor)11 Before (org.junit.Before)10 MethodSource (org.junit.jupiter.params.provider.MethodSource)9 IOException (java.io.IOException)8 ArrayList (java.util.ArrayList)8 TestSampler (org.apache.jmeter.junit.stubs.TestSampler)6 TestPlan (org.apache.jmeter.testelement.TestPlan)6 HashMap (java.util.HashMap)5 ValueReplacer (org.apache.jmeter.engine.util.ValueReplacer)5 URL (java.net.URL)4 Arguments (org.apache.jmeter.config.Arguments)4 DebugSampler (org.apache.jmeter.sampler.DebugSampler)4