Как решить вызов метода Bsh? - PullRequest
0 голосов
/ 29 марта 2019

Я пытаюсь прочитать файл CSV, используя Beah Shell Assertion.ниже мой скрипт оболочки bean

       import java.io.BufferedReader;
       import java.io.FileNotFoundException;
       import java.io.FileReader;
       import java.io.IOException;

       String csvFile = 
      "C:/Workspace/JmeterProjects/JMeterOutput_${__time(MM-dd-yyyy)}.csv";
       BufferedReader bufferedReader = null;
       String line = "";
       String SEPARATOR = ",";

     try {
         bufferedReader = new BufferedReader(new FileReader(csvFile));

              int counter = 1;
       while ((line = bufferedReader.readLine()) != null) 
          {
               String[] items = line.split(SEPARATOR);
        print("--------------------LOGGING STARTS-----------------------");
   for(int i = 0; i < items.length; i++)
       {        
           log.info(items[i]);
       }   
        print("--------------------LOGGING ENDS-------------------------");
       }

       } 
       catch (FileNotFoundException e) 
       {
                 e.printStackTrace();
      } 
      catch (IOException e) 
      {
                 e.printStackTrace();
      } 
      finally {
            if (bufferedReader != null) {
               try {
                    bufferedReader.close();
                   } catch (IOException e) {
                          e.printStackTrace();
                    }
               }

        }

Но у меня есть ошибка:

ОШИБКА oajuBeanShellInterpreter: Ошибка при вызове метода bsh: eval Источник файла: встроенная оценка: `` importjava.io.BufferedReader;import java.io.FileNotFoundException;импорт Java.,,'' Ошибка разбора токена: Лексическая ошибка в строке 6, столбец 22. Обнаружено: "W" (87), после: "\" C: \ "

Я не уверен, что может быть ошибкойза этим

Ответы [ 2 ]

0 голосов
/ 29 марта 2019
  1. Не используйте Beanshell для написания сценариев, поскольку в JMeter 3.1 вы должны использовать элементы тестирования JSR223 и язык Groovy
  2. Не встраивать функции JMeter в сценарии, вместо этого используйте основанные на коде эквиваленты

Groovy эквивалент будет выглядеть примерно так:

new File('C:\Workspace\JmeterProjects/JMeterOutput_' + new Date().format('MM-dd-yyyy') + '.csv').readLines().each { line ->
    line.split(',').each { entry ->
        log.info(entry)
    }
}

Демо-версия:

enter image description here

Дополнительная информация: Сценарии утверждений JMeter в Groovy - учебное пособие

0 голосов
/ 29 марта 2019

Обновленный код, которым вы поделились, работает нормально при тех же условиях, включая путь к файлу в моей системе Windows.Только содержимое файла отличается.Пожалуйста, найдите ниже выход.Если вы все еще видите исходную ошибку с обновленным кодом, пожалуйста, поделитесь дополнительной информацией, такой как журналы и т. Д.

2019-03-29 12:04:34,123 INFO o.a.j.t.JMeterThread: Thread started: Thread Group 1-1
2019-03-29 12:04:34,137 INFO o.a.j.u.BeanShellTestElement: col1
2019-03-29 12:04:34,137 INFO o.a.j.u.BeanShellTestElement: col2
2019-03-29 12:04:34,138 INFO o.a.j.u.BeanShellTestElement: col3
2019-03-29 12:04:34,138 INFO o.a.j.u.BeanShellTestElement: col4
2019-03-29 12:04:34,138 INFO o.a.j.u.BeanShellTestElement: col5
2019-03-29 12:04:34,138 INFO o.a.j.u.BeanShellTestElement: col6
2019-03-29 12:04:34,138 INFO o.a.j.u.BeanShellTestElement: col7
2019-03-29 12:04:34,138 INFO o.a.j.u.BeanShellTestElement: col8
2019-03-29 12:04:34,138 INFO o.a.j.u.BeanShellTestElement: col9
2019-03-29 12:04:34,138 INFO o.a.j.u.BeanShellTestElement: col10
.
.
.
2019-03-29 12:04:34,170 INFO o.a.j.u.BeanShellTestElement: val25





<?xml version="1.0" encoding="UTF-8"?>
<jmeterTestPlan version="1.2" properties="5.0" jmeter="5.0 r1840935">
  <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.tearDown_on_shutdown">true</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="Thread Group" enabled="true">
        <stringProp name="ThreadGroup.on_sample_error">continue</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">1</stringProp>
        <stringProp name="ThreadGroup.ramp_time">1</stringProp>
        <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>
              <url>true</url>
              <threadCounts>true</threadCounts>
              <idleTime>true</idleTime>
              <connectTime>true</connectTime>
            </value>
          </objProp>
          <stringProp name="filename"></stringProp>
        </ResultCollector>
        <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>
          <BeanShellAssertion guiclass="BeanShellAssertionGui" testclass="BeanShellAssertion" testname="BeanShell Assertion" enabled="true">
            <stringProp name="BeanShellAssertion.query">      import java.io.BufferedReader;
       import java.io.FileNotFoundException;
       import java.io.FileReader;
       import java.io.IOException;

       String csvFile = 
      &quot;C:/Workspace/JmeterProjects/JMeterOutput_${__time(MM-dd-yyyy)}.csv&quot;;
       BufferedReader bufferedReader = null;
       String line = &quot;&quot;;
       String SEPARATOR = &quot;,&quot;;

     try {
         bufferedReader = new BufferedReader(new FileReader(csvFile));

              int counter = 1;
       while ((line = bufferedReader.readLine()) != null) 
          {
               String[] items = line.split(SEPARATOR);
        print(&quot;--------------------LOGGING STARTS-----------------------&quot;);
   for(int i = 0; i &lt; items.length; i++)
       {        
           log.info(items[i]);
       }   
        print(&quot;--------------------LOGGING ENDS-------------------------&quot;);
       }

       } 
       catch (FileNotFoundException e) 
       {
                 e.printStackTrace();
      } 
      catch (IOException e) 
      {
                 e.printStackTrace();
      } 
      finally {
            if (bufferedReader != null) {
               try {
                    bufferedReader.close();
                   } catch (IOException e) {
                          e.printStackTrace();
                    }
               }

        }</stringProp>
            <stringProp name="BeanShellAssertion.filename"></stringProp>
            <stringProp name="BeanShellAssertion.parameters"></stringProp>
            <boolProp name="BeanShellAssertion.resetInterpreter">false</boolProp>
          </BeanShellAssertion>
          <hashTree/>
        </hashTree>
      </hashTree>
    </hashTree>
  </hashTree>
</jmeterTestPlan>
...