KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > jmeter > assertions > ResponseAssertion


1 // $Header: /home/cvs/jakarta-jmeter/src/components/org/apache/jmeter/assertions/ResponseAssertion.java,v 1.16.2.3 2004/06/11 11:04:45 sebb Exp $
2
/*
3  * Copyright 2001-2004 The Apache Software Foundation.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17 */

18
19 package org.apache.jmeter.assertions;
20 import java.io.Serializable JavaDoc;
21 import java.util.ArrayList JavaDoc;
22
23 import org.apache.jmeter.samplers.SampleResult;
24 import org.apache.jmeter.testelement.AbstractTestElement;
25 import org.apache.jmeter.testelement.property.CollectionProperty;
26 import org.apache.jmeter.testelement.property.IntegerProperty;
27 import org.apache.jmeter.testelement.property.JMeterProperty;
28 import org.apache.jmeter.testelement.property.NullProperty;
29 import org.apache.jmeter.testelement.property.PropertyIterator;
30 import org.apache.jmeter.testelement.property.StringProperty;
31 import org.apache.jorphan.util.JOrphanUtils;
32 import org.apache.oro.text.MalformedCachePatternException;
33 import org.apache.oro.text.PatternCacheLRU;
34 import org.apache.oro.text.regex.Pattern;
35 import org.apache.oro.text.regex.Perl5Compiler;
36 import org.apache.oro.text.regex.Perl5Matcher;
37
38 /**
39  *
40  * @version $Revision: 1.16.2.3 $ Last Updated: $Date: 2004/06/11 11:04:45 $
41 */

42 public class ResponseAssertion
43    extends AbstractTestElement
44    implements Serializable JavaDoc, Assertion
45 {
46    public final static String JavaDoc TEST_FIELD = "Assertion.test_field";
47    // Values for TEST_FIELD
48
public final static String JavaDoc SAMPLE_LABEL = "Assertion.sample_label";
49    public final static String JavaDoc RESPONSE_DATA = "Assertion.response_data";
50    public final static String JavaDoc RESPONSE_CODE = "Assertion.response_code";
51    public final static String JavaDoc RESPONSE_MESSAGE = "Assertion.response_message";
52    public final static String JavaDoc ASSUME_SUCCESS = "Assertion.assume_success";
53
54    public final static String JavaDoc TEST_STRINGS = "Asserion.test_strings";
55
56    public final static String JavaDoc TEST_TYPE = "Assertion.test_type";
57    /*
58     * Mask values for TEST_TYPE
59     * TODO: remove either MATCH or CONTAINS - they are mutually exckusive
60     */

61    private final static int MATCH = 1 << 0;
62    private final static int CONTAINS = 1 << 1;
63    private final static int NOT = 1 << 2;
64
65    private static ThreadLocal JavaDoc matcher = new ThreadLocal JavaDoc()
66    {
67       protected Object JavaDoc initialValue()
68       {
69          return new Perl5Matcher();
70       }
71    };
72    private static PatternCacheLRU patternCache =
73       new PatternCacheLRU(1000, new Perl5Compiler());
74    /************************************************************
75     * !ToDo (Constructor description)
76     ***********************************************************/

77    public ResponseAssertion()
78    {
79       setProperty(new CollectionProperty(TEST_STRINGS, new ArrayList JavaDoc()));
80    }
81    /************************************************************
82     * !ToDo (Constructor description)
83     *
84     *@param field !ToDo (Parameter description)
85     *@param type !ToDo (Parameter description)
86     *@param string !ToDo (Parameter description)
87     ***********************************************************/

88    public ResponseAssertion(String JavaDoc field, int type, String JavaDoc string)
89    {
90       this();
91       setTestField(field);
92       setTestType(type);
93       getTestStrings().addProperty(new StringProperty(string,string));
94    }
95    
96    public void clear()
97    {
98        super.clear();
99        setProperty(new CollectionProperty(TEST_STRINGS, new ArrayList JavaDoc()));
100    }
101    
102    /************************************************************
103     * !ToDo (Method description)
104     *
105     *@param testField !ToDo (Parameter description)
106     ***********************************************************/

107    public void setTestField(String JavaDoc testField)
108    {
109       setProperty(TEST_FIELD, testField);
110    }
111    /************************************************************
112     * !ToDo (Method description)
113     *
114     *@param testType !ToDo (Parameter description)
115     ***********************************************************/

116    public void setTestType(int testType)
117    {
118       setProperty(new IntegerProperty(TEST_TYPE, testType));
119    }
120
121    /************************************************************
122     * !ToDo (Method description)
123     *
124     *@param testString !ToDo (Parameter description)
125     ***********************************************************/

126    public void addTestString(String JavaDoc testString)
127    {
128       getTestStrings().addProperty(new StringProperty(testString,testString));
129    }
130    public void setTestString(String JavaDoc testString, int index)//NOTUSED?
131
{
132       getTestStrings().set(index, testString);
133    }
134    public void removeTestString(String JavaDoc testString)//NOTUSED?
135
{
136       getTestStrings().remove(testString);
137    }
138    public void removeTestString(int index)//NOTUSED?
139
{
140       getTestStrings().remove(index);
141    }
142    public void clearTestStrings()
143    {
144       getTestStrings().clear();
145    }
146    /************************************************************
147     * !ToDoo (Method description)
148     *
149     *@param response !ToDo (Parameter description)
150     *@return !ToDo (Return description)
151     ***********************************************************/

152    public AssertionResult getResult(SampleResult response)
153    {
154       AssertionResult result;
155
156 // None of the other Assertions check the response status, so remove this check
157
// for the time being, at least...
158
// if (!response.isSuccessful())
159
// {
160
// result = new AssertionResult();
161
// result.setError(true);
162
// byte [] ba = response.getResponseData();
163
// result.setFailureMessage(
164
// ba == null ? "Unknown Error (responseData is empty)" : new String(ba)
165
// );
166
// return result;
167
// }
168

169       result = evaluateResponse(response);
170       return result;
171    }
172    /************************************************************
173     * !ToDoo (Method description)
174     *
175     *@return !ToDo (Return description)
176     ***********************************************************/

177    public String JavaDoc getTestField()
178    {
179       return getPropertyAsString(TEST_FIELD);
180    }
181    /************************************************************
182     * !ToDoo (Method description)
183     *
184     *@return !ToDo (Return description)
185     ***********************************************************/

186    public int getTestType()
187    {
188       JMeterProperty type = getProperty(TEST_TYPE);
189       if (type instanceof NullProperty)
190       {
191          return CONTAINS;
192       }
193       else
194       {
195          return type.getIntValue();
196       }
197    }
198    /************************************************************
199     * !ToDoo (Method description)
200     *
201     *@return !ToDo (Return description)
202     ***********************************************************/

203    public CollectionProperty getTestStrings()
204    {
205       return (CollectionProperty) getProperty(TEST_STRINGS);
206    }
207    public boolean isContainsType()
208    {
209       return (getTestType() & CONTAINS) > 0;
210    }
211    public boolean isMatchType()
212    {
213       return (getTestType() & MATCH) > 0;
214    }
215    public boolean isNotType()
216    {
217       return (getTestType() & NOT) > 0;
218    }
219    public void setToContainsType()
220    {
221       setTestType(
222          (getTestType() | CONTAINS) & (~ MATCH));
223    }
224    public void setToMatchType()
225    {
226       setTestType(
227          (getTestType() | MATCH) & (~ CONTAINS));
228    }
229    public void setToNotType()
230    {
231       setTestType((getTestType() | NOT));
232    }
233    public void unsetNotType()
234    {
235       setTestType(getTestType() & ~ NOT);
236    }
237    public boolean getAssumeSuccess()
238    {
239     return getPropertyAsBoolean(ASSUME_SUCCESS,false);
240    }
241    public void setAssumeSuccess(boolean b)
242    {
243       setProperty(ASSUME_SUCCESS,JOrphanUtils.booleanToString(b));
244    }
245    /**
246     * Make sure the response satisfies the specified assertion requirements.
247     *
248     * @param response an instance of SampleResult
249     * @return an instance of AssertionResult
250     */

251    private AssertionResult evaluateResponse(SampleResult response)
252    {
253       boolean pass = true;
254       boolean not = (NOT & getTestType()) > 0;
255       AssertionResult result = new AssertionResult();
256       String JavaDoc toCheck=""; // The string to check (Url or data)
257

258       if (getAssumeSuccess())
259       {
260         response.setSuccessful(true);// Allow testing of failure codes
261
}
262
263       // What are we testing against?
264
if (ResponseAssertion.RESPONSE_DATA.equals(getTestField()))
265       {
266         toCheck = new StringBuffer JavaDoc(response.getResponseHeaders()).append(new String JavaDoc(response.responseDataAsBA())).toString();
267       }
268       else if (ResponseAssertion.RESPONSE_CODE.equals(getTestField()))
269       {
270         toCheck=response.getResponseCode();
271       }
272       else if (ResponseAssertion.RESPONSE_MESSAGE.equals(getTestField()))
273       {
274         toCheck=response.getResponseMessage();
275       }
276       else
277       { // Assume it is the URL
278
toCheck=response.getSamplerData();
279         if (toCheck == null) toCheck = "";
280       }
281
282       if(toCheck.length()==0)
283       {
284           return setResultForNull(result);
285       }
286
287       try
288       {
289          // Get the Matcher for this thread
290
Perl5Matcher localMatcher = (Perl5Matcher) matcher.get();
291          PropertyIterator iter = getTestStrings().iterator();
292          while (iter.hasNext())
293          {
294             String JavaDoc stringPattern = iter.next().getStringValue();
295             Pattern pattern =
296                patternCache.getPattern(
297                   stringPattern,
298                   Perl5Compiler.READ_ONLY_MASK);
299             boolean found;
300             if ((CONTAINS & getTestType()) > 0)
301             {
302                found = localMatcher.contains(toCheck, pattern);
303             }
304             else
305             {
306                found = localMatcher.matches(toCheck, pattern);
307             }
308             pass = not ? !found : found;
309             if (!pass)
310             {
311                result.setFailure(true);
312                result.setFailureMessage(getFailText(stringPattern));
313                break;
314             }
315          }
316          if (pass)
317          {
318             result.setFailure(false);
319          }
320          result.setError(false);
321       }
322       catch (MalformedCachePatternException e)
323       {
324          result.setError(true);
325          result.setFailure(false);
326          result.setFailureMessage("Bad test configuration" + e);
327       }
328       return result;
329    }
330    
331 /**
332  * Generate the failure reason from the TestType
333  *
334  * @param stringPattern
335  * @return the message for the assertion report
336  * TODO strings ought to be made resources
337  */

338 private String JavaDoc getFailText(String JavaDoc stringPattern) {
339     String JavaDoc text;
340     String JavaDoc what;
341     if (ResponseAssertion.RESPONSE_DATA.equals(getTestField()))
342     {
343         what="text";
344     }
345     else if (ResponseAssertion.RESPONSE_CODE.equals(getTestField()))
346     {
347         what="code";
348     }
349     else if (ResponseAssertion.RESPONSE_MESSAGE.equals(getTestField()))
350     {
351         what="message";
352     }
353     else // Assume it is the URL
354
{
355         what="URL";
356     }
357     switch(getTestType()){
358         case CONTAINS:
359             text = " expected to contain ";
360             break;
361         case NOT | CONTAINS:
362             text = " expected not to contain ";
363             break;
364         case MATCH:
365             text = " expected to match ";
366             break;
367         case NOT | MATCH:
368             text = " expected not to match ";
369             break;
370         default:// should never happen...
371
text = " expected something using ";
372     }
373
374     return "Test failed, " + what + text + "/" + stringPattern + "/";
375 }
376 protected AssertionResult setResultForNull(AssertionResult result)
377 {
378     result.setError(false);
379       result.setFailure(true);
380       result.setFailureMessage("Response (or URL) was null");
381       return result;
382 }
383    public static class Test extends junit.framework.TestCase
384    {
385       int threadsRunning;
386       int failed;
387       public Test(String JavaDoc name)
388       {
389          super(name);
390       }
391       public void testThreadSafety() throws Exception JavaDoc
392       {
393          Thread JavaDoc[] threads = new Thread JavaDoc[100];
394          for (int i = 0; i < threads.length; i++)
395          {
396             threads[i] = new TestThread();
397          }
398          failed = 0;
399          for (int i = 0; i < threads.length; i++)
400          {
401             threads[i].start();
402             threadsRunning++;
403          }
404          synchronized (this)
405          {
406             while (threadsRunning > 0)
407             {
408                wait();
409             }
410          }
411          assertEquals(failed, 0);
412       }
413       class TestThread extends Thread JavaDoc
414       {
415          static final String JavaDoc TEST_STRING = "DAbale arroz a la zorra el abad.";
416            // Used to be 'dábale', but caused trouble on Gump. Reasons unknown.
417
static final String JavaDoc TEST_PATTERN = ".*A.*\\.";
418          public void run()
419          {
420             ResponseAssertion assertion =
421                new ResponseAssertion(RESPONSE_DATA, CONTAINS, TEST_PATTERN);
422             SampleResult response = new SampleResult();
423             response.setResponseData(TEST_STRING.getBytes());
424             for (int i = 0; i < 100; i++)
425             {
426                AssertionResult result;
427                result = assertion.evaluateResponse(response);
428                if (result.isFailure() || result.isError())
429                {
430                   failed++;
431                }
432             }
433             synchronized (Test.this)
434             {
435                threadsRunning--;
436                Test.this.notifyAll();
437             }
438          }
439       }
440    }
441 }
442
Popular Tags