Как отправить HTTP-запросы из многих CSV-файлов в JMeter - PullRequest
0 голосов
/ 17 сентября 2018

У меня есть набор файлов CSV, каждый из которых содержит URL.Я хотел бы прочитать все эти файлы, используя JMeter, и просмотреть URL-адреса для отправки HTTP-запросов.

TLDR : я хочу знать, как отправлять данные HTTP-запроса и ответа наAPI JMeter, использующий BeanShell, чтобы у слушателей JMeter был доступ к даннымИли, если есть лучший способ, который включает конфигурацию CVS и / или сэмплер HTTP Request.

Количество файлов не согласовано.Сегодня может быть 5 и 7 на следующей неделе.В настоящее время я использую скрипт бобовой оболочки, чтобы прочитать файлы в каталоге, выбрать те, которые я хочу, и сохранить их в переменных потока.Пока это работает.Затем я попытался прочитать файл CSV, используя сэмплер CSV Config и контроллер forLoop.Путь указан в переменной, поэтому я подумал, что это сработает, но, похоже, сэмплер CSV Config работает только с переменными, установленными в начале выполнения.Поскольку мои переменные устанавливаются после чтения каталога, это слишком поздно для Sampler, и я получаю сообщение об ошибке, что переменная либо не существует, либо пуста.

Итак, то, что у меня сейчас не работает, создано ещеСкрипт бобовой оболочки в контроллере forLoop.Скрипт прочитает цикл через каждый файл и отправит HTTP-запрос на строку.

Моя проблема в том, что я не уверен, как передать результаты в API JMeter, чтобы слушатели могли получить доступ к данным запроса / ответа.

Вот мой файл JMX

<?xml version="1.0" encoding="UTF-8"?>
<jmeterTestPlan version="1.2" properties="4.0" jmeter="4.0 r1823414">
<hashTree>
    <TestPlan guiclass="TestPlanGui" testclass="TestPlan" testname="Test Plan" enabled="true">
    <stringProp name="TestPlan.comments"></stringProp>
    <boolProp name="TestPlan.functional_mode">false</boolProp>
    <boolProp name="TestPlan.serialize_threadgroups">false</boolProp>
    <elementProp name="TestPlan.user_defined_variables" elementType="Arguments" guiclass="ArgumentsPanel" testclass="Arguments" testname="User Defined Variables" enabled="true">
        <collectionProp name="Arguments.arguments"/>
    </elementProp>
    <stringProp name="TestPlan.user_define_classpath"></stringProp>
    </TestPlan>
    <hashTree>
    <ThreadGroup guiclass="ThreadGroupGui" testclass="ThreadGroup" testname="Get Requests - Thread Group" enabled="true">
        <stringProp name="ThreadGroup.on_sample_error">stopthread</stringProp>
        <elementProp name="ThreadGroup.main_controller" elementType="LoopController" guiclass="LoopControlPanel" testclass="LoopController" testname="Loop Controller" enabled="true">
        <boolProp name="LoopController.continue_forever">false</boolProp>
        <stringProp name="LoopController.loops">1</stringProp>
        </elementProp>
        <stringProp name="ThreadGroup.num_threads">50</stringProp>
        <stringProp name="ThreadGroup.ramp_time">15</stringProp>
        <longProp name="ThreadGroup.start_time">1503347655000</longProp>
        <longProp name="ThreadGroup.end_time">1503347655000</longProp>
        <boolProp name="ThreadGroup.scheduler">false</boolProp>
        <stringProp name="ThreadGroup.duration"></stringProp>
        <stringProp name="ThreadGroup.delay"></stringProp>
    </ThreadGroup>
    <hashTree>
        <ResultCollector guiclass="ViewResultsFullVisualizer" testclass="ResultCollector" testname="View Results Tree" enabled="true">
        <boolProp name="ResultCollector.error_logging">false</boolProp>
        <objProp>
            <name>saveConfig</name>
            <value class="SampleSaveConfiguration">
            <time>true</time>
            <latency>true</latency>
            <timestamp>true</timestamp>
            <success>true</success>
            <label>true</label>
            <code>true</code>
            <message>true</message>
            <threadName>true</threadName>
            <dataType>true</dataType>
            <encoding>false</encoding>
            <assertions>true</assertions>
            <subresults>true</subresults>
            <responseData>false</responseData>
            <samplerData>false</samplerData>
            <xml>false</xml>
            <fieldNames>true</fieldNames>
            <responseHeaders>false</responseHeaders>
            <requestHeaders>false</requestHeaders>
            <responseDataOnError>false</responseDataOnError>
            <saveAssertionResultsFailureMessage>true</saveAssertionResultsFailureMessage>
            <assertionsResultsToSave>0</assertionsResultsToSave>
            <bytes>true</bytes>
            <sentBytes>true</sentBytes>
            <threadCounts>true</threadCounts>
            <idleTime>true</idleTime>
            <connectTime>true</connectTime>
            </value>
        </objProp>
        <stringProp name="filename"></stringProp>
        </ResultCollector>
        <hashTree/>
        <BeanShellSampler guiclass="BeanShellSamplerGui" testclass="BeanShellSampler" testname="BeanShell Sampler" enabled="true">
        <stringProp name="BeanShellSampler.query">File folder = new File(&quot;Legacy/LB tests/&quot;);
File[] files = folder.listFiles();
int counter = 1;

for (File file : files) {
//  s = String.valueOf(file.getAbsolutePath());
//  end = s.length() -4;
//  extension = s.substring(end);

//  if (extension.toLowerCase().equals(&quot;.csv&quot;)) {

        String csv_file = String.valueOf(file.getAbsolutePath());
        log.info(&quot;CSV: &quot; + csv_file);
        String file_path = csv_file;
        String[] parts = file_path.split(&quot;/&quot;);
        String csv_file_name = parts[parts.length - 1];

        if(String.valueOf(csv_file_name).length() &gt; 12) {
            log.info(&quot;MY FILE: &quot; + csv_file_name.substring(0,11));
            if(csv_file_name.substring(0,11).toLowerCase().equals(&quot;persons_get&quot;)) {

                log.info(&quot;File added: &quot; + csv_file);
                vars.put(&quot;file_&quot; + counter, csv_file);
                    print(vars);
                    counter++;
            }
        }

//      }
//  }

    print(vars);
}</stringProp>
        <stringProp name="BeanShellSampler.filename"></stringProp>
        <stringProp name="BeanShellSampler.parameters"></stringProp>
        <boolProp name="BeanShellSampler.resetInterpreter">false</boolProp>
        </BeanShellSampler>
        <hashTree/>
        <ForeachController guiclass="ForeachControlPanel" testclass="ForeachController" testname="ForEach Controller" enabled="true">
        <stringProp name="ForeachController.inputVal">file</stringProp>
        <stringProp name="ForeachController.returnVal">current_file</stringProp>
        <boolProp name="ForeachController.useSeparator">true</boolProp>
        <stringProp name="ForeachController.startIndex">0</stringProp>
        </ForeachController>
        <hashTree>
        <BeanShellAssertion guiclass="BeanShellAssertionGui" testclass="BeanShellAssertion" testname="BeanShell Assertion" enabled="true">
            <stringProp name="BeanShellAssertion.query">import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.entity.StringEntity;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;

BufferedReader reader;

try {
    reader = new BufferedReader(new FileReader(new File(vars.get(&quot;current_file&quot;))));
} catch (Exception e) {
    log.info(e.printStackTrace());
}

int counter = 1;        
String [] tokens;

for(String line; (line = reader.readLine()) != null; ) {
    tokens = line.split(&quot;,&quot;);
//  vars.put(&quot;url_&quot; + counter, tokens[0]);
    counter++;

    Failure = false;

    HttpClient httpClient = HttpClientBuilder.create().build();
    try{

    log.info(&quot;Request: &quot; + tokens[0]);
    HttpGet request = new HttpGet(tokens[0]);
    //request.addHeader(&quot;content-type&quot;, &quot;application/json&quot;);
    //request.setEntity(params);
    HttpResponse response = httpClient.execute(request);
    log.info(&quot;response :&quot; +response);
    }catch(Exception e){
    log.info(&quot;ExceptionKPI :&quot; +e);
    }
} 
</stringProp>
            <stringProp name="BeanShellAssertion.filename"></stringProp>
            <stringProp name="BeanShellAssertion.parameters"></stringProp>
            <boolProp name="BeanShellAssertion.resetInterpreter">false</boolProp>
        </BeanShellAssertion>
        <hashTree/>
        <ForeachController guiclass="ForeachControlPanel" testclass="ForeachController" testname="ForEach Controller" enabled="false">
            <stringProp name="ForeachController.inputVal">url</stringProp>
            <stringProp name="ForeachController.returnVal">current_line</stringProp>
            <boolProp name="ForeachController.useSeparator">true</boolProp>
            <stringProp name="ForeachController.startIndex">0</stringProp>
        </ForeachController>
        <hashTree>
            <HTTPSamplerProxy guiclass="HttpTestSampleGui" testclass="HTTPSamplerProxy" testname="HTTP Request" enabled="true">
            <elementProp name="HTTPsampler.Arguments" elementType="Arguments" guiclass="HTTPArgumentsPanel" testclass="Arguments" testname="User Defined Variables" enabled="true">
                <collectionProp name="Arguments.arguments"/>
            </elementProp>
            <stringProp name="HTTPSampler.domain"></stringProp>
            <stringProp name="HTTPSampler.port"></stringProp>
            <stringProp name="HTTPSampler.protocol"></stringProp>
            <stringProp name="HTTPSampler.contentEncoding"></stringProp>
            <stringProp name="HTTPSampler.path">${current_line}</stringProp>
            <stringProp name="HTTPSampler.method">GET</stringProp>
            <boolProp name="HTTPSampler.follow_redirects">true</boolProp>
            <boolProp name="HTTPSampler.auto_redirects">false</boolProp>
            <boolProp name="HTTPSampler.use_keepalive">true</boolProp>
            <boolProp name="HTTPSampler.DO_MULTIPART_POST">false</boolProp>
            <stringProp name="HTTPSampler.embedded_url_re"></stringProp>
            <stringProp name="HTTPSampler.connect_timeout"></stringProp>
            <stringProp name="HTTPSampler.response_timeout"></stringProp>
            </HTTPSamplerProxy>
            <hashTree/>
        </hashTree>
        </hashTree>
        <DebugSampler guiclass="TestBeanGUI" testclass="DebugSampler" testname="Debug Sampler" enabled="true">
        <boolProp name="displayJMeterProperties">false</boolProp>
        <boolProp name="displayJMeterVariables">true</boolProp>
        <boolProp name="displaySystemProperties">false</boolProp>
        </DebugSampler>
        <hashTree/>
        <ResultCollector guiclass="TableVisualizer" testclass="ResultCollector" testname="View Results in Table" enabled="true">
        <boolProp name="ResultCollector.error_logging">false</boolProp>
        <objProp>
            <name>saveConfig</name>
            <value class="SampleSaveConfiguration">
            <time>true</time>
            <latency>true</latency>
            <timestamp>true</timestamp>
            <success>true</success>
            <label>true</label>
            <code>true</code>
            <message>true</message>
            <threadName>true</threadName>
            <dataType>true</dataType>
            <encoding>false</encoding>
            <assertions>true</assertions>
            <subresults>true</subresults>
            <responseData>false</responseData>
            <samplerData>false</samplerData>
            <xml>false</xml>
            <fieldNames>true</fieldNames>
            <responseHeaders>false</responseHeaders>
            <requestHeaders>false</requestHeaders>
            <responseDataOnError>false</responseDataOnError>
            <saveAssertionResultsFailureMessage>true</saveAssertionResultsFailureMessage>
            <assertionsResultsToSave>0</assertionsResultsToSave>
            <bytes>true</bytes>
            <sentBytes>true</sentBytes>
            <threadCounts>true</threadCounts>
            <idleTime>true</idleTime>
            <connectTime>true</connectTime>
            </value>
        </objProp>
        <stringProp name="filename"></stringProp>
        </ResultCollector>
        <hashTree/>
        <ResultCollector guiclass="SummaryReport" testclass="ResultCollector" testname="Summary Report" enabled="true">
        <boolProp name="ResultCollector.error_logging">false</boolProp>
        <objProp>
            <name>saveConfig</name>
            <value class="SampleSaveConfiguration">
            <time>true</time>
            <latency>true</latency>
            <timestamp>true</timestamp>
            <success>true</success>
            <label>true</label>
            <code>true</code>
            <message>true</message>
            <threadName>true</threadName>
            <dataType>true</dataType>
            <encoding>false</encoding>
            <assertions>true</assertions>
            <subresults>true</subresults>
            <responseData>false</responseData>
            <samplerData>false</samplerData>
            <xml>false</xml>
            <fieldNames>true</fieldNames>
            <responseHeaders>false</responseHeaders>
            <requestHeaders>false</requestHeaders>
            <responseDataOnError>false</responseDataOnError>
            <saveAssertionResultsFailureMessage>true</saveAssertionResultsFailureMessage>
            <assertionsResultsToSave>0</assertionsResultsToSave>
            <bytes>true</bytes>
            <sentBytes>true</sentBytes>
            <threadCounts>true</threadCounts>
            <idleTime>true</idleTime>
            <connectTime>true</connectTime>
            </value>
        </objProp>
        <stringProp name="filename"></stringProp>
        </ResultCollector>
        <hashTree/>
    </hashTree>
    </hashTree>
</hashTree>
</jmeterTestPlan>
...