File: HttpServletRequestTest.java

package info (click to toggle)
httpunit 1.7%2Bdfsg-10
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 3,416 kB
  • ctags: 6,394
  • sloc: java: 33,504; xml: 483; sh: 68; makefile: 11
file content (800 lines) | stat: -rw-r--r-- 38,660 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
package com.meterware.servletunit;
/********************************************************************************************************************
* $Id: HttpServletRequestTest.java 918 2008-04-15 17:51:21Z wolfgang_fahl $
*
* Copyright (c) 2000-2008 by Russell Gold
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
* to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
* THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*******************************************************************************************************************/
import java.util.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.Servlet;
import javax.servlet.ServletException;

import com.meterware.httpunit.*;
import com.meterware.httpunit.cookies.CookieProperties;

import junit.framework.Test;
import junit.framework.TestSuite;

/**
 * Tests the ServletUnitHttpRequest class.
 *
 * @author <a href="mailto:russgold@httpunit.org">Russell Gold</a>
 **/
public class HttpServletRequestTest extends ServletUnitTest {

    private ServletUnitContext _context;


    public static void main(String args[]) {
        junit.textui.TestRunner.run( suite() );
    }


    public static Test suite() {
        return new TestSuite( HttpServletRequestTest.class );
    }


    public HttpServletRequestTest( String name ) {
        super( name );
    }


    protected void setUp() throws Exception {
        super.setUp();
        _context = new ServletUnitContext( null, null, new SessionListenerDispatcher() {
            public void sendSessionCreated( HttpSession session ) {}
            public void sendSessionDestroyed( HttpSession session ) {}
            public void sendAttributeAdded( HttpSession session, String name, Object value ) {}
            public void sendAttributeReplaced( HttpSession session, String name, Object oldValue ) {}
            public void sendAttributeRemoved( HttpSession session, String name, Object oldValue ) {}
        } );

    }


    public void testHeaderAccess() throws Exception {
        WebRequest wr = new GetMethodWebRequest( "http://localhost/simple" );
        wr.setHeaderField( "sample", "value" );
        HttpServletRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, _context, new Hashtable(), NO_MESSAGE_BODY );
        assertEquals( "sample header value", "value", request.getHeader( "sample") );

        assertContains( "Header names", "sample", request.getHeaderNames() );
        Enumeration e = request.getHeaders( "Sample" );
        assertNotNull( "No header enumeration returned", e );
        assertTrue( "Enumeration is empty", e.hasMoreElements() );
        assertEquals( "first header", "value", e.nextElement() );
        assertFalse( "Enumeration has spurious header value", e.hasMoreElements() );
    }
    
    /**
     * test getting a date header;
     * @throws Exception
     */
    public void testDateHeaderAccess() throws Exception {
      WebRequest wr = new GetMethodWebRequest( "http://localhost/simple" );
      String dateStr="Mon, 26 Jul 1997 05:00:00 GMT";
      Date testDate=new Date(dateStr);
      wr.setHeaderField( "Expires", dateStr );
      HttpServletRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, _context, new Hashtable(), NO_MESSAGE_BODY );
      String dateStrRequest=request.getHeader("Expires");
      assertTrue("Expires header field",dateStrRequest.equals(dateStr));
      // invalid date headers return -1 
      long requestDate=request.getDateHeader("invalid");
      assertTrue("invalid date header field",requestDate==-1);
      // valid date header field return the millisecs
      requestDate=request.getDateHeader("Expires");
      assertTrue("Expires date header field",requestDate==testDate.getTime());
    }  


    private void assertContains( String comment, String string, Enumeration headerNames ) {
        while (headerNames != null && headerNames.hasMoreElements()) {
            String name = (String) headerNames.nextElement();
            if (name.equalsIgnoreCase( string )) return;
        }
        fail( comment + " does not contain " + string );
    }


    public void testGetDefaultProperties() throws Exception {
        WebRequest wr = new GetMethodWebRequest( "http://localhost/simple" );
        HttpServletRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, _context, new Hashtable(), NO_MESSAGE_BODY );
        assertNull( "Authorization incorrectly specified", request.getAuthType() );
        assertNull( "Character encoding incorrectly specified", request.getCharacterEncoding() );
        assertEquals( "Parameters unexpectedly specified", "", request.getQueryString() );
        assertNotNull( "No input stream available", request.getInputStream() );
    }


    public void testSetSingleValuedParameter() throws Exception {
        WebRequest wr = new GetMethodWebRequest( "http://localhost/simple" );
        wr.setParameter( "age", "12" );
        wr.setParameter( "color", new String[] { "red", "blue" } );
        HttpServletRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, _context, new Hashtable(), NO_MESSAGE_BODY );

        assertEquals( "age parameter", "12", request.getParameter( "age" ) );
        assertNull( "unset parameter should be null", request.getParameter( "unset" ) );
    }


    public void testSetMultiValuedParameter() throws Exception {
        WebRequest wr = new GetMethodWebRequest( "http://localhost/simple" );
        wr.setParameter( "age", "12" );
        wr.setParameter( "color", new String[] { "red", "blue" } );
        HttpServletRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, _context, new Hashtable(), NO_MESSAGE_BODY );

        assertMatchingSet( "age parameter", new String[] { "12" }, request.getParameterValues( "age" ) );
        assertMatchingSet( "color parameter", new String[] { "red", "blue" }, request.getParameterValues( "color" ) );
        assertNull( "unset parameter should be null", request.getParameterValues( "unset" ) );
    }
    
    /**
     * test for bug report [ 1143757 ] encoding of Special charcters broken with 1.6
     * by Klaus Halfmann
     * test for bug report [ 1159810 ] URL encoding problem with ServletUnit
     * by Sven Helmberger 
     */
    public void testParameterWithSpacesAndAt() throws Exception {
      WebRequest wr = new GetMethodWebRequest( "http://localhost/simple" );
      String pValueWithSpaces="This Input is to long";
      String pValueWithAt="@user@example.org";
      wr.setParameter("age" ,pValueWithSpaces);
      String result=wr.getParameter("age");
      // according to Klaus Halfman as of 2005-02-18 / version 1.6 results in "This+Input+is+to+long"
      // System.err.println(result);
      assertEquals("spaces should survive",pValueWithSpaces,result);
      wr.setParameter("age" ,pValueWithAt);
      result=wr.getParameter("age");
      assertEquals("@ should survive",pValueWithAt,result);
    }   

    /**
     */
    public void testParameterWithAt() throws Exception {
      WebRequest wr = new GetMethodWebRequest( "http://localhost/simple" );
      String pValueWithSpaces="This Input is to long";
      wr.setParameter("age" ,pValueWithSpaces);
      String result=wr.getParameter("age");
      // according to Klaus Halfman as of 2005-02-18 / version 1.6 results in "This+Input+is+to+long"
      // System.err.println(result);
      assertEquals("spaces should survive",pValueWithSpaces,result);
    }   

    public void testParameterMap() throws Exception {
        WebRequest wr = new GetMethodWebRequest( "http://localhost/simple" );
        wr.setParameter( "age", "12" );
        wr.setParameter( "color", new String[] { "red", "blue" } );
        HttpServletRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, _context, new Hashtable(), NO_MESSAGE_BODY );

        Map map = request.getParameterMap();
        assertMatchingSet( "age parameter", new String[] { "12" }, (Object[]) map.get( "age" ) );
        assertMatchingSet( "color parameter", new String[] { "red", "blue" }, (Object[]) map.get( "color" ) );
        assertNull( "unset parameter should be null", map.get( "unset" ) );
    }


    public void testSetQueryString() throws Exception {
        WebRequest wr = new GetMethodWebRequest( "http://localhost/simple" );
        wr.setParameter( "age", "12" );
        wr.setParameter( "color", new String[] { "red", "blue" } );
        HttpServletRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, _context, new Hashtable(), NO_MESSAGE_BODY );

        assertEquals( "query string", "color=red&color=blue&age=12", request.getQueryString() );
    }


    /**
     * test Bug report 1212204
     * by Brian Bonner
     * @throws Exception
     */
    public void testBug1212204() throws Exception {
    	WebRequest request = new
    	GetMethodWebRequest("http://localhost/pathinfo?queryString");
    	//assertEquals("queryString", request.getQueryString());
    	request = new
    	GetMethodWebRequest("http://localhost/pathinfo?queryString");
    	request.setParameter("queryString","");
    	assertEquals("queryString=", request.getQueryString());
    	request = new
    	GetMethodWebRequest("http://localhost/pathinfo?queryString");
    	request.setParameter("queryString",(String)null);
    	assertEquals("queryString", request.getQueryString());
    	WebRequest wr = new
    		GetMethodWebRequest("http://localhost?wsdl");
    			wr.setParameter("abc","def");		
    			wr.setParameter("def","");
    			wr.setParameter("test",(String)null);
    			wr.setParameter("wsdl", (String)null);		
    	
    			assertEquals("wsdl&abc=def&def=&test",wr.getQueryString());
    }	


    public void testInlineSingleValuedParameter() throws Exception {
        WebRequest wr = new GetMethodWebRequest( "http://localhost/simple?color=red&color=blue&age=12" );
        HttpServletRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, _context, new Hashtable(), NO_MESSAGE_BODY );

        assertEquals( "age parameter", "12", request.getParameter( "age" ) );
        assertNull( "unset parameter should be null", request.getParameter( "unset" ) );
    }


    public void testInlineParameterWithEmbeddedSpace() throws Exception {
        WebRequest wr = new GetMethodWebRequest( "http://localhost/simple?color=dark+red&age=12" );
        HttpServletRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, _context, new Hashtable(), NO_MESSAGE_BODY );

        assertEquals( "age parameter", "12", request.getParameter( "age" ) );
        assertEquals( "color parameter", "dark red", request.getParameter( "color" ) );
    }


    public void testInlineMultiValuedParameter() throws Exception {
        WebRequest wr = new GetMethodWebRequest( "http://localhost/simple?color=red&color=blue&age=12" );
        HttpServletRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, _context, new Hashtable(), NO_MESSAGE_BODY );

        assertMatchingSet( "age parameter", new String[] { "12" }, request.getParameterValues( "age" ) );
        assertMatchingSet( "color parameter", new String[] { "red", "blue" }, request.getParameterValues( "color" ) );
        assertNull( "unset parameter should be null", request.getParameterValues( "unset" ) );
    }

    
    /**
     * test patch for
     * [ 1705925 ] Bug in URL-decoding of GET-Request-Parameters
     * http://sourceforge.net/tracker/index.php?func=detail&aid=1705925&group_id=6550&atid=106550
     * @throws Exception
     */
    
    public void    testGetMethodRequestParametersEncodedWithDefaultCharacterSet_Hebrew()  throws Exception {
    	String hebrewValue = "\u05d0\u05d1\u05d2\u05d3";
    	String paramString = "param1=red&param2=%E0%E1%E2%E3"; // use iso-8859-8 to encode the data, then string is URL encoded
    	HttpUnitOptions.setDefaultCharacterSet("ISO-8859-8");
    	WebRequest wr = new GetMethodWebRequest( "http://localhost/simple");
    	wr.setParameter("param1", "red");
    	wr.setParameter("param2", hebrewValue);
    	ServletUnitHttpRequest request = new  ServletUnitHttpRequest(NULL_SERVLET_REQUEST, wr, _context, new Hashtable(), new byte[0]);
    	assertEquals( "param1 value", "red", request.getParameter("param1") );
    	assertEquals( "param2 value", hebrewValue, request.getParameter("param2") );
    }

    /**
     * test patch for
     * [ 1705925 ] Bug in URL-decoding of GET-Request-Parameters
     * http://sourceforge.net/tracker/index.php?func=detail&aid=1705925&group_id=6550&atid=106550
     * @throws Exception
     */
    public void testGetMethodRequestParametersEncodedWithDefaultCharacterSet_UTF8() throws  Exception {
    	String hebrewValue = "\u05d0\u05d1\u05d2\u05d3";
    	String paramString = "param1=red&param2=%E0%E1%E2%E3"; // use utf-8 to encode the data, then string is URL encoded
    	HttpUnitOptions.setDefaultCharacterSet("UTF-8");
    	WebRequest wr = new GetMethodWebRequest( "http://localhost/simple");
    	wr.setParameter("param1", "red");
    	wr.setParameter("param2", hebrewValue);
    	ServletUnitHttpRequest request = new  ServletUnitHttpRequest(NULL_SERVLET_REQUEST, wr, _context, new Hashtable(), new byte[0]);
    	assertEquals( "param1 value", "red", request.getParameter("param1") );
    	assertEquals( "param2 value", hebrewValue, request.getParameter("param2") );
    }

    public void notestInlineQueryString() throws Exception {     // TODO make this work
        WebRequest wr = new GetMethodWebRequest( "http://localhost/simple?color=red&color=blue&age=12" );
        HttpServletRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, _context, new Hashtable(), NO_MESSAGE_BODY );

        assertEquals( "query string", "color=red&color=blue&age=12", request.getQueryString() );
    }


    public void testRequestMessageBody() throws Exception {
        String body = "12345678901234567890";
        InputStream stream = new ByteArrayInputStream( body.getBytes( "UTF-8" ) );
        WebRequest wr = new PutMethodWebRequest( "http://localhost/simple", stream, "text/plain" );
        HttpServletRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, _context, new Hashtable(), body.getBytes() );

        assertEquals( "Request content length", body.length(), request.getContentLength() );
        BufferedInputStream bis = new BufferedInputStream( request.getInputStream() );
        byte[] buffer = new byte[ request.getContentLength() ];
        bis.read( buffer );
        assertEquals( "Request content", body, new String( buffer ) );
    }


    public void testDefaultAttributes() throws Exception {
        WebRequest wr = new GetMethodWebRequest( "http://localhost/simple" );
        HttpServletRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, _context, new Hashtable(), NO_MESSAGE_BODY );

        assertNull( "attribute should not be defined yet", request.getAttribute( "unset" ) );
        assertTrue( "attribute enumeration should be empty", !request.getAttributeNames().hasMoreElements() );
    }


    public void testNonDefaultAttributes() throws Exception {
        WebRequest wr = new GetMethodWebRequest( "http://localhost/simple" );
        HttpServletRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, _context, new Hashtable(), NO_MESSAGE_BODY );
        Object value = new Integer(1);

        request.setAttribute( "one", value );

        assertEquals( "attribute one", value, request.getAttribute( "one" ) );

        Enumeration names = request.getAttributeNames();
        assertTrue( "attribute enumeration should not be empty", names.hasMoreElements() );
        assertEquals( "contents in enumeration", "one", names.nextElement() );
        assertTrue( "attribute enumeration should now be empty", !names.hasMoreElements() );
    }


    public void testDuplicateAttributes() throws Exception {
        WebRequest wr = new GetMethodWebRequest( "http://localhost/simple" );
        HttpServletRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, _context, new Hashtable(), NO_MESSAGE_BODY );

        request.setAttribute( "one", new Integer(1) );
        request.setAttribute( "one", "One" );
        assertEquals( "Revised attribute value", "One", request.getAttribute( "one" ) );
    }


    public void testNullAttributeValue() throws Exception {
        WebRequest wr = new GetMethodWebRequest( "http://localhost/simple" );
        HttpServletRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, _context, new Hashtable(), NO_MESSAGE_BODY );

        request.setAttribute( "one", "One" );
        assertEquals( "Initial attribute value", "One", request.getAttribute( "one" ) );
        request.setAttribute( "one", null );
        assertNull( "Attribute 'one' should have been removed", request.getAttribute( "one" ) );
    }


    public void testDefaultCookies() throws Exception {
        WebRequest wr = new GetMethodWebRequest( "http://localhost/simple" );
        HttpServletRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, _context, new Hashtable(), NO_MESSAGE_BODY );
        Cookie[] cookies = request.getCookies();
        assertNull( "Unexpected cookies found", cookies );
    }


    public void testSetCookieViaRequestHeader() throws Exception {
        WebRequest wr = new GetMethodWebRequest( "http://localhost/simple" );
        wr.setHeaderField( "Cookie", "flavor=vanilla,variety=sandwich");
        ServletUnitHttpRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, _context, new Hashtable(), NO_MESSAGE_BODY );

        Cookie[] cookies = request.getCookies();
        assertNotNull( "No cookies found", cookies );
        assertEquals( "Num cookies found", 2, cookies.length );
        assertEquals( "Cookie 1 name", "flavor", cookies[0].getName() );
        assertEquals( "Cookie 1 value", "vanilla", cookies[0].getValue() );
        assertEquals( "Cookie 2 name", "variety", cookies[1].getName() );
        assertEquals( "Cookie 2 value", "sandwich", cookies[1].getValue() );
    }


    public void testGetSessionForFirstTime() throws MalformedURLException {
        WebRequest wr = new GetMethodWebRequest( "http://localhost/simple" );
        ServletUnitContext context = _context;
        assertEquals( "Initial number of sessions in context", 0, context.getSessionIDs().size() );

        ServletUnitHttpRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, context, new Hashtable(), NO_MESSAGE_BODY );
        assertNull( "New request should not have a request session ID", request.getRequestedSessionId() );
        assertNull( "New request should not have a session", request.getSession( /* create */ false ) );
        assertEquals( "Number of sessions in the context after request.getSession(false)", 0, context.getSessionIDs().size() );

        HttpSession session = request.getSession();
        assertNotNull( "No session created", session );
        assertTrue( "Session not marked as new", session.isNew() );
        assertEquals( "Number of sessions in context after request.getSession()", 1, context.getSessionIDs().size() );
        assertSame( "Session with ID", session, context.getSession( session.getId() ) );
        assertNull( "New request should still not have a request session ID", request.getRequestedSessionId() );
    }

    /**
     * Test recognition of cookies defined on the client.
     * is test case for [ 1151277 ] httpunit 1.6 breaks Cookie handling for ServletUnitClient
     * by Michael Corum
     */
    public void testGetUserCookies() throws Exception {
        String FIRST_COOKIE = "RANDOM_COOKIE";
        String SECOND_COOKIE = "ANOTHER_COOKIE";
        String FIRST_COOKIE_VALUE = "cookie1";
        String SECOND_COOKIE_VALUE = "cookie2";

        ServletRunner sr = new ServletRunner();
        sr.registerServlet( "testServlet", "ServletName" );
        ServletUnitClient m_sc = sr.newClient();
        m_sc.putCookie( FIRST_COOKIE, FIRST_COOKIE_VALUE );
        m_sc.putCookie( SECOND_COOKIE, SECOND_COOKIE_VALUE );

        InvocationContext invocation = m_sc.newInvocation( "http://localhost/testServlet" );
        HttpServletRequest requ = invocation.getRequest();

        Cookie[] cookies = requ.getCookies();
        assertEquals( 2, cookies.length );
        Cookie firstActualCookie = cookies[0];
        Cookie secondActualCookie = cookies[1];

        assertEquals( FIRST_COOKIE, firstActualCookie.getName() );
        assertEquals( SECOND_COOKIE, secondActualCookie.getName() );

        assertEquals( FIRST_COOKIE_VALUE, firstActualCookie.getValue() );
        assertEquals( SECOND_COOKIE_VALUE, secondActualCookie.getValue() );
    }
    

    /**
     * Verifies that even when session creation is not explicitly requested, the inclusion of a session cookie
     * will cause a session to be made available.
     */
    public void testRetrieveSession() throws Exception {
        ServletUnitContext context = _context;
        final ServletUnitHttpSession session = context.newSession();
        final String sessionID = session.getId();

        WebRequest wr = new GetMethodWebRequest( "http://localhost/simple" );
        wr.setHeaderField( "Cookie", ServletUnitHttpSession.SESSION_COOKIE_NAME + '=' + sessionID);

        ServletUnitHttpRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, context, new Hashtable(), NO_MESSAGE_BODY );
        assertEquals( "Requested session ID defined in request", sessionID, request.getRequestedSessionId() );

        assertSame( "Session returned when creation not requested", session, request.getSession( /* create */ false ) );
        assertSame( "Session returned when creation requested", session, request.getSession( true ) );
    }


    public void testAccessForbiddenToInvalidSession() throws Exception {
        ServletUnitContext context = _context;

        HttpSession session = context.newSession();
        session.setAttribute( "Initial", new Integer( 1 ) );
        Enumeration attributeNames = session.getAttributeNames();
        assertTrue( attributeNames.hasMoreElements() );
        assertEquals( "Initial", attributeNames.nextElement() );

        session.invalidate();

        try {
            session.getAttributeNames().hasMoreElements();
            fail( "Should not be able to access an invalid session's attributes" );
        } catch (IllegalStateException ex) {
        }

        try {
            session.getAttribute( "Initial" );
            fail( "Should not be able to access an invalid session's attributes" );
        } catch (IllegalStateException ex) {
        }
    }


    /**
     * Verifies that a request for a session when the current one is invalid will result in a new session.
     *
     * Obtains a new session, invalidates it, and verifies that
     */
    public void testSessionInvalidation() throws Exception {
        ServletUnitContext context = _context;
        HttpSession originalSession = context.newSession();
        String originalID = originalSession.getId();

        WebRequest wr = new GetMethodWebRequest( "http://localhost/simple" );
        wr.setHeaderField( "Cookie", ServletUnitHttpSession.SESSION_COOKIE_NAME + '=' + originalID);

        ServletUnitHttpRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, context, new Hashtable(), NO_MESSAGE_BODY );
        originalSession.setAttribute( "Initial", new Integer( 1 ) );
        Enumeration attributeNames = originalSession.getAttributeNames();
        assertTrue( attributeNames.hasMoreElements() );
        assertEquals( "Initial", attributeNames.nextElement() );

        originalSession.invalidate();

        assertNull( "Invalidated session returned", request.getSession( false ) );

        HttpSession newSession = request.getSession( true );
        assertNotNull( "getSession(true) did not return a session", newSession );
        assertNotSame( "getSession(true) returned the original invalidated session", originalSession, newSession );
        assertSame( "session returned by getSession(false)", newSession, request.getSession( false ) );
        assertSame( "Session in context with new ID", newSession, context.getSession( newSession.getId() ) );
    }


    /**
     * Verifies that a request with a bad session ID causes a new session to be generated only when explicitly requested.
     */
    public void testGetSessionWithBadCookie() throws Exception {
        ServletUnitContext context = _context;
        HttpSession originalSession = context.newSession();
        String originalID = originalSession.getId();

        WebRequest wr = new GetMethodWebRequest( "http://localhost/simple" );
        wr.setHeaderField( "Cookie", ServletUnitHttpSession.SESSION_COOKIE_NAME + '=' + originalID);

        ServletUnitHttpRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, context, new Hashtable(), NO_MESSAGE_BODY );
        request.getSession();

        wr.setHeaderField( "Cookie", ServletUnitHttpSession.SESSION_COOKIE_NAME + '=' + (originalID + "BAD"));
        request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, context, new Hashtable(), NO_MESSAGE_BODY );

        assertNull( "Unexpected session returned for bad cookie", request.getSession( false ) );
        assertNotNull( "Should have returned session when asked", request.getSession( true ));
        assertNotSame( "Created session", originalSession, request.getSession( true ) );
    }


    public void testGetRequestURI() throws Exception {
        ServletUnitContext context = _context;
        WebRequest wr = new GetMethodWebRequest( "http://localhost/simple" );

        ServletUnitHttpRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, context, new Hashtable(), NO_MESSAGE_BODY );
        assertEquals("/simple", request.getRequestURI());
        assertEquals( "http://localhost/simple", request.getRequestURL().toString() );

        wr = new GetMethodWebRequest( "http://localhost/simple?foo=bar" );
        request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, context, new Hashtable(), NO_MESSAGE_BODY );
        assertEquals("/simple", request.getRequestURI());
        assertEquals( "http://localhost/simple", request.getRequestURL().toString() );
    }


    public void testDefaultLocale() throws Exception {
        WebRequest wr = new GetMethodWebRequest( "http://localhost/simple");

        ServletUnitHttpRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, _context, new Hashtable(), NO_MESSAGE_BODY );
        Locale[] expectedLocales = new Locale[] { Locale.getDefault() };
        verifyLocales( request, expectedLocales );

    }


    /**
     * verify the secure property and scheme http/https 
     * extended test for bug report [ 1165454 ] ServletUnitHttpRequest.getScheme() returns "http" for secure
     * by Jeff Mills
     * @throws Exception
     */
    public void testSecureProperty() throws Exception {
        WebRequest wr = new GetMethodWebRequest( "http://localhost/simple");
        ServletUnitHttpRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, _context, new Hashtable(), NO_MESSAGE_BODY );
        assertFalse( "Incorrectly noted request as secure", request.isSecure() );
        assertEquals("http",request.getScheme(),"http");

        WebRequest secureReq = new GetMethodWebRequest( "https://localhost/simple");
        request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, secureReq, _context, new Hashtable(), NO_MESSAGE_BODY );
        assertTrue( "Request not marked as secure", request.isSecure() );
        assertEquals("https",request.getScheme(),"https");
        
        wr = new GetMethodWebRequest( "ftp://localhost/simple");
        request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, _context, new Hashtable(), NO_MESSAGE_BODY );
        assertFalse( "Incorrectly noted request as secure", request.isSecure() );
        assertEquals("ftp",request.getScheme(),"ftp");
        
        secureReq = new GetMethodWebRequest( "ftps://localhost/simple");
        try {
        	request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, secureReq, _context, new Hashtable(), NO_MESSAGE_BODY );
          assertTrue( "Request not marked as secure", request.isSecure() );
          assertEquals("ftps",request.getScheme(),"ftps");
        } catch (java.net.MalformedURLException mue) {
        	// as of 2008-03 this happends - I'm not sure whether that should be expected WF
        	String msg=mue.getMessage();
        	// System.err.println(msg);
          assertTrue("ftps is not a known protocol",msg.indexOf("unknown protocol: ftps")>=0);
    		} 
    }


    private void verifyLocales( ServletUnitHttpRequest request, Locale[] expectedLocales ) {
        assertNotNull( "No default locale found", request.getLocale() );
        assertEquals( "default locale", expectedLocales[0], request.getLocale() );

        final Enumeration locales = request.getLocales();
        assertNotNull( "local enumeration not returned", locales );
        for (int i = 0; i < expectedLocales.length; i++) {
            assertTrue( "Expected " + expectedLocales.length + " locales, only found " + i, locales.hasMoreElements() );
            assertEquals( "Locale #" + (i+1), expectedLocales[i], locales.nextElement() );
        }
        assertFalse( "Too many locales returned", locales.hasMoreElements() );
    }


    public void testSpecifiedLocales() throws Exception {
        WebRequest wr = new GetMethodWebRequest( "http://localhost/simple");
        wr.setHeaderField( "Accept-language", "fr, en;q=0.6, en-us;q=0.7" );

        ServletUnitHttpRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, _context, new Hashtable(), NO_MESSAGE_BODY );
        verifyLocales( request, new Locale[] { Locale.FRENCH, Locale.US, Locale.ENGLISH } );
    }
  
  /*
   * Test for patch [ 1246438 ] For issue 1221537; ServletUnitHttpRequest.getReader not impl
   * by Tim
   */
  public void testGetInputStreamSameObject() throws Exception {
      byte[] bytes = new byte[0];
      InputStream stream = new ByteArrayInputStream( bytes );
      WebRequest wr = new PostMethodWebRequest( "http://localhost/simple", stream, "text/plain" );
      HttpServletRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, _context, new Hashtable(), bytes );

      InputStream first = request.getInputStream();
      InputStream second = request.getInputStream();
      assertSame("Different InputStreams", first, second);
  }


  public void testGetInputStreamAfterGetReader() throws Exception {
      byte[] bytes = new byte[0];
      InputStream stream = new ByteArrayInputStream( bytes );
      WebRequest wr = new PostMethodWebRequest( "http://localhost/simple", stream, "text/plain" );
      HttpServletRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, _context, new Hashtable(), bytes );
      
      request.getReader();
      try {
          request.getInputStream();
          fail("Expected IllegalStateException");
      } catch (IllegalStateException e) {
          // Expected
      }
  }


  public void testGetInputStream() throws Exception {
      String body = "12345678901234567890";
      InputStream stream = new ByteArrayInputStream( body.getBytes( "UTF-8" ) );
      WebRequest wr = new PostMethodWebRequest( "http://localhost/simple", stream, "text/plain" );
      HttpServletRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, _context, new Hashtable(), body.getBytes() );

      BufferedInputStream bis = new BufferedInputStream( request.getInputStream() );
      byte[] buffer = new byte[ request.getContentLength() ];
      bis.read( buffer );
      assertEquals( "Request content", body, new String( buffer, "UTF-8" ) );
  }


  public void testGetReaderSameObject() throws Exception {
      byte[] bytes = new byte[0];
      InputStream stream = new ByteArrayInputStream( bytes );
      WebRequest wr = new PostMethodWebRequest( "http://localhost/simple", stream, "text/plain" );
      HttpServletRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, _context, new Hashtable(), bytes );

      BufferedReader first = request.getReader();
      BufferedReader second = request.getReader();
      assertSame("Different Readers", first, second);
  }


  public void testGetReaderAfterGetInputStream() throws Exception {
      byte[] bytes = new byte[0];
      InputStream stream = new ByteArrayInputStream( bytes );
      WebRequest wr = new PostMethodWebRequest( "http://localhost/simple", stream, "text/plain" );
      HttpServletRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, _context, new Hashtable(), bytes );

      request.getInputStream();
      try {
          request.getReader();
          fail("Expected IllegalStateException");
      } catch (IllegalStateException e) {
          // Expected
      }
  }


  public void testGetReaderDefaultCharset() throws Exception {
      String body = "12345678901234567890";
      InputStream stream = new ByteArrayInputStream( body.getBytes( HttpUnitUtils.DEFAULT_CHARACTER_SET ) );
      WebRequest wr = new PostMethodWebRequest( "http://localhost/simple", stream, "text/plain" );
      HttpServletRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, _context, new Hashtable(), body.getBytes() );

      char[] buffer = new char[body.length()];
      request.getReader().read(buffer);
      assertEquals( "Request content", body, new String( buffer) );
  }


  /**
   * test the reader with a Specific Character set (here UTF-8)
   * @throws Exception
   * TODO make work an switch back on
   */
  public void xtestGetReaderSpecificCharset() throws Exception {
      //String body = "東京";
      String body = "\u05d0\u05d1\u05d2\u05d3";
      InputStream stream = new ByteArrayInputStream( body.getBytes( "UTF-8" ) );
      WebRequest wr = new PostMethodWebRequest( "http://localhost/simple", stream, "text/plain; charset=UTF-8" );
      HttpServletRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, _context, new Hashtable(), body.getBytes() );

      char[] buffer = new char[body.length()];
      request.getReader().read(buffer);
      assertEquals( "Request content", body, new String( buffer) );
  }


  /**
   * test the specific character encoding
   * (here hebrew)
   * @throws Exception
   */
   public void testSpecifiedCharEncoding() throws Exception {   
        String hebrewValue = "\u05d0\u05d1\u05d2\u05d3";
        String paramString = "param1=red&param2=%E0%E1%E2%E3";  // use iso-8859-8 to encode the data
        WebRequest wr = new PostMethodWebRequest( "http://localhost/simple" );
        wr.setHeaderField( "Content-Type", "application/x-www-form-urlencoded; charset=ISO-8859-8" );
        ServletUnitHttpRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, _context, new Hashtable(), paramString.getBytes( "iso-8859-1" ) );
        assertEquals( "param1 value", "red", request.getParameter( "param1") );
        assertEquals( "param2 value", hebrewValue, request.getParameter( "param2") );
    }


    public void testSpecifiedCharEncoding2() throws Exception {
        String hebrewValue = "\u05d0\u05d1\u05d2\u05d3";
        HttpUnitOptions.setDefaultCharacterSet( "iso-8859-8" );
        WebRequest wr = new PostMethodWebRequest( "http://localhost/simple" );
        wr.setParameter( "param1", "red" );
        wr.setParameter( "param2", hebrewValue );
        wr.setHeaderField( "Content-Type", "application/x-www-form-urlencoded; charset=ISO-8859-8" );
        ServletUnitClient client = ServletUnitClient.newClient( null );
        ByteArrayOutputStream messageBody = client.getMessageBody( wr );
        ServletUnitHttpRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, _context, new Hashtable(), messageBody.toByteArray() );
        String parameter = request.getParameter( "param2");
        assertEquals( "param2 value", hebrewValue, parameter );
        assertEquals( "param1 value", "red", request.getParameter( "param1") );
    }


    public void testSuppliedCharEncoding() throws Exception {   // xxx turn this back on
        String hebrewValue = "\u05d0\u05d1\u05d2\u05d3";
        String paramString = "param1=red&param2=%E0%E1%E2%E3";  // use iso-8859-8 to encode the data, then string is URL encoded
        WebRequest wr = new PostMethodWebRequest( "http://localhost/simple" );
        ServletUnitHttpRequest request = new ServletUnitHttpRequest( NULL_SERVLET_REQUEST, wr, _context, new Hashtable(), paramString.getBytes( "ISO-8859-1" ) );
        request.setCharacterEncoding( "ISO-8859-8" );
        assertEquals( "param1 value", "red", request.getParameter( "param1") );
        assertEquals( "param2 value", hebrewValue, request.getParameter( "param2") );
    }


    private final static byte[] NO_MESSAGE_BODY = new byte[0];

    private final static ServletMetaData NULL_SERVLET_REQUEST = new ServletMetaData() {

        public Servlet getServlet() throws ServletException {
            return null;
        }


        public String getServletPath() {
            return null;
        }


        public String getPathInfo() {
            return null;
        }


        public FilterMetaData[] getFilters() {
            return null;
        }
    };
}