Search in sources :

Example 36 with JMeterVariables

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

the class Groovy method execute.

/**
 * {@inheritDoc}
 */
@Override
public synchronized String execute(SampleResult previousResult, Sampler currentSampler) throws InvalidVariableException {
    Bindings bindings = scriptEngine.createBindings();
    populateBindings(bindings);
    String script = ((CompoundVariable) values[0]).execute();
    // $NON-NLS-1$
    String varName = "";
    if (values.length > 1) {
        varName = ((CompoundVariable) values[1]).execute().trim();
    }
    // $NON-NLS-1$
    String resultStr = "";
    try {
        // Pass in some variables
        if (currentSampler != null) {
            // $NON-NLS-1$
            bindings.put("sampler", currentSampler);
        }
        if (previousResult != null) {
            // $NON-NLS-1$
            bindings.put("prev", previousResult);
        }
        // $NON-NLS-1$ (this name is fixed)
        bindings.put("log", log);
        // Add variables for access to context and variables
        bindings.put("threadName", Thread.currentThread().getName());
        JMeterContext jmctx = JMeterContextService.getContext();
        // $NON-NLS-1$ (this name is fixed)
        bindings.put("ctx", jmctx);
        JMeterVariables vars = jmctx.getVariables();
        // $NON-NLS-1$ (this name is fixed)
        bindings.put("vars", vars);
        Properties props = JMeterUtils.getJMeterProperties();
        // $NON-NLS-1$ (this name is fixed)
        bindings.put("props", props);
        // For use in debugging:
        // $NON-NLS-1$ (this name is fixed)
        bindings.put("OUT", System.out);
        // Execute the script
        Object out = scriptEngine.eval(script, bindings);
        if (out != null) {
            resultStr = out.toString();
        }
        if (varName.length() > 0 && vars != null) {
            // vars will be null on TestPlan
            vars.put(varName, resultStr);
        }
    } catch (// Mainly for bsh.EvalError
    Exception ex) {
        log.warn("Error running groovy script", ex);
    }
    log.debug("__groovy({},{})={}", script, varName, resultStr);
    return resultStr;
}
Also used : CompoundVariable(org.apache.jmeter.engine.util.CompoundVariable) JMeterVariables(org.apache.jmeter.threads.JMeterVariables) JMeterContext(org.apache.jmeter.threads.JMeterContext) Properties(java.util.Properties) Bindings(javax.script.Bindings)

Example 37 with JMeterVariables

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

the class IterationCounter method execute.

/**
 * {@inheritDoc}
 */
@Override
public String execute(SampleResult previousResult, Sampler currentSampler) throws InvalidVariableException {
    JMeterVariables vars = getVariables();
    boolean perThread = Boolean.parseBoolean(((CompoundVariable) variables[0]).execute());
    // $NON-NLS-1$
    String varName = "";
    if (variables.length >= 2) {
        // Ensure variable has been provided
        varName = ((CompoundVariable) variables[1]).execute().trim();
    }
    // $NON-NLS-1$
    String counterString = "";
    if (perThread) {
        counterString = String.valueOf(perThreadInt.get().addAndGet(1));
    } else {
        counterString = String.valueOf(globalCounter.addAndGet(1));
    }
    // vars will be null on Test Plan
    if (vars != null && varName.length() > 0) {
        vars.put(varName, counterString);
    }
    return counterString;
}
Also used : CompoundVariable(org.apache.jmeter.engine.util.CompoundVariable) JMeterVariables(org.apache.jmeter.threads.JMeterVariables)

Example 38 with JMeterVariables

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

the class RandomString method execute.

/**
 * {@inheritDoc}
 */
@Override
public String execute(SampleResult previousResult, Sampler currentSampler) throws InvalidVariableException {
    int length = Integer.parseInt(values[0].execute());
    // means no restriction
    String charsToUse = null;
    if (values.length >= CHARS) {
        charsToUse = values[CHARS - 1].execute().trim();
        if (charsToUse.length() <= 0) {
            // empty chars, return to null
            charsToUse = null;
        }
    }
    // $NON-NLS-1$
    String myName = "";
    if (values.length >= PARAM_NAME) {
        myName = values[PARAM_NAME - 1].execute().trim();
    }
    String myValue = null;
    if (StringUtils.isEmpty(charsToUse)) {
        myValue = RandomStringUtils.random(length);
    } else {
        myValue = RandomStringUtils.random(length, charsToUse);
    }
    if (myName.length() > 0) {
        JMeterVariables vars = getVariables();
        if (vars != null) {
            // Can be null if called from Config item testEnded() method
            vars.put(myName, myValue);
        }
    }
    if (log.isDebugEnabled()) {
        // $NON-NLS-1$
        log.debug("{} name:{} value:{}", Thread.currentThread().getName(), myName, myValue);
    }
    return myValue;
}
Also used : JMeterVariables(org.apache.jmeter.threads.JMeterVariables)

Example 39 with JMeterVariables

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

the class RegexFunction method execute.

/**
 * {@inheritDoc}
 */
@Override
public String execute(SampleResult previousResult, Sampler currentSampler) throws InvalidVariableException {
    // $NON-NLS-1$
    String valueIndex = "";
    // $NON-NLS-1$
    String defaultValue = "";
    // $NON-NLS-1$
    String between = "";
    // $NON-NLS-1$
    String name = "";
    // $NON-NLS-1$
    String inputVariable = "";
    Pattern searchPattern;
    Object[] tmplt;
    try {
        searchPattern = JMeterUtils.getPatternCache().getPattern(((CompoundVariable) values[0]).execute(), Perl5Compiler.READ_ONLY_MASK);
        tmplt = generateTemplate(((CompoundVariable) values[1]).execute());
        if (values.length > 2) {
            valueIndex = ((CompoundVariable) values[2]).execute();
        }
        if (valueIndex.length() == 0) {
            // $NON-NLS-1$
            valueIndex = "1";
        }
        if (values.length > 3) {
            between = ((CompoundVariable) values[3]).execute();
        }
        if (values.length > 4) {
            String dv = ((CompoundVariable) values[4]).execute();
            if (dv.length() != 0) {
                defaultValue = dv;
            }
        }
        if (values.length > 5) {
            name = ((CompoundVariable) values[5]).execute();
        }
        if (values.length > 6) {
            inputVariable = ((CompoundVariable) values[6]).execute();
        }
    } catch (MalformedCachePatternException e) {
        log.error("Malformed cache pattern:{}", values[0], e);
        throw new InvalidVariableException("Malformed cache pattern:" + values[0], e);
    }
    // Relatively expensive operation, so do it once
    JMeterVariables vars = getVariables();
    if (vars == null) {
        // Can happen if called during test closedown
        return defaultValue;
    }
    if (name.length() > 0) {
        vars.put(name, defaultValue);
    }
    String textToMatch = null;
    if (inputVariable.length() > 0) {
        textToMatch = vars.get(inputVariable);
    } else if (previousResult != null) {
        textToMatch = previousResult.getResponseDataAsString();
    }
    if (textToMatch == null || textToMatch.length() == 0) {
        return defaultValue;
    }
    List<MatchResult> collectAllMatches = new ArrayList<>();
    try {
        PatternMatcher matcher = JMeterUtils.getMatcher();
        PatternMatcherInput input = new PatternMatcherInput(textToMatch);
        while (matcher.contains(input, searchPattern)) {
            MatchResult match = matcher.getMatch();
            if (match != null) {
                collectAllMatches.add(match);
            }
        }
    } finally {
        if (name.length() > 0) {
            // $NON-NLS-1$
            vars.put(name + "_matchNr", Integer.toString(collectAllMatches.size()));
        }
    }
    if (collectAllMatches.isEmpty()) {
        return defaultValue;
    }
    if (valueIndex.equals(ALL)) {
        StringBuilder value = new StringBuilder();
        Iterator<MatchResult> it = collectAllMatches.iterator();
        boolean first = true;
        while (it.hasNext()) {
            if (!first) {
                value.append(between);
            } else {
                first = false;
            }
            value.append(generateResult(it.next(), name, tmplt, vars));
        }
        return value.toString();
    } else if (valueIndex.equals(RAND)) {
        MatchResult result = collectAllMatches.get(ThreadLocalRandom.current().nextInt(collectAllMatches.size()));
        return generateResult(result, name, tmplt, vars);
    } else {
        try {
            int index = Integer.parseInt(valueIndex) - 1;
            if (index >= collectAllMatches.size()) {
                return defaultValue;
            }
            MatchResult result = collectAllMatches.get(index);
            return generateResult(result, name, tmplt, vars);
        } catch (NumberFormatException e) {
            float ratio = Float.parseFloat(valueIndex);
            MatchResult result = collectAllMatches.get((int) (collectAllMatches.size() * ratio + .5) - 1);
            return generateResult(result, name, tmplt, vars);
        }
    }
}
Also used : CompoundVariable(org.apache.jmeter.engine.util.CompoundVariable) Pattern(org.apache.oro.text.regex.Pattern) MalformedCachePatternException(org.apache.oro.text.MalformedCachePatternException) ArrayList(java.util.ArrayList) MatchResult(org.apache.oro.text.regex.MatchResult) JMeterVariables(org.apache.jmeter.threads.JMeterVariables) PatternMatcherInput(org.apache.oro.text.regex.PatternMatcherInput) PatternMatcher(org.apache.oro.text.regex.PatternMatcher)

Example 40 with JMeterVariables

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

the class SplitFunction method execute.

/**
 * {@inheritDoc}
 */
@Override
public String execute(SampleResult previousResult, Sampler currentSampler) throws InvalidVariableException {
    JMeterVariables vars = getVariables();
    String stringToSplit = ((CompoundVariable) values[0]).execute();
    String varNamePrefix = ((CompoundVariable) values[1]).execute().trim();
    String splitString = ",";
    if (values.length > 2) {
        // Split string provided
        String newSplitString = ((CompoundVariable) values[2]).execute();
        splitString = newSplitString.length() > 0 ? newSplitString : splitString;
    }
    log.debug("Split {} using {} into {}", stringToSplit, splitString, varNamePrefix);
    // $NON-NLS-1$
    String[] parts = JOrphanUtils.split(stringToSplit, splitString, "?");
    vars.put(varNamePrefix, stringToSplit);
    // $NON-NLS-1$
    vars.put(varNamePrefix + "_n", Integer.toString(parts.length));
    for (int i = 1; i <= parts.length; i++) {
        if (log.isDebugEnabled()) {
            log.debug(parts[i - 1]);
        }
        // $NON-NLS-1$
        vars.put(varNamePrefix + "_" + i, parts[i - 1]);
    }
    vars.remove(varNamePrefix + "_" + (parts.length + 1));
    return stringToSplit;
}
Also used : CompoundVariable(org.apache.jmeter.engine.util.CompoundVariable) JMeterVariables(org.apache.jmeter.threads.JMeterVariables)

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