View Javadoc
1   /*
2    * Copyright (C) 2018 Matthias Sohn <matthias.sohn@sap.com> and others
3    *
4    * This program and the accompanying materials are made available under the
5    * terms of the Eclipse Distribution License v. 1.0 which is available at
6    * https://www.eclipse.org/org/documents/edl-v10.php.
7    *
8    * SPDX-License-Identifier: BSD-3-Clause
9    */
10  package org.eclipse.jgit.transport.http;
11  
12  import static java.util.Arrays.asList;
13  import static org.junit.Assert.assertTrue;
14  import static org.junit.Assert.fail;
15  import static org.mockito.Mockito.mock;
16  import static org.mockito.Mockito.when;
17  
18  import java.net.HttpURLConnection;
19  import java.util.Collections;
20  import java.util.HashMap;
21  import java.util.LinkedList;
22  import java.util.List;
23  import java.util.Map;
24  
25  import org.junit.Before;
26  import org.junit.Test;
27  
28  public class JDKHttpConnectionTest {
29  
30  	private Map<String, List<String>> headers = new HashMap<>();
31  
32  	private HttpURLConnection u;
33  
34  	private JDKHttpConnection c;
35  
36  	@Before
37  	public void setup() {
38  		u = mock(HttpURLConnection.class);
39  		c = new JDKHttpConnection(u);
40  		headers.put("ABC", asList("x"));
41  	}
42  
43  	@Test
44  	public void testSingle() {
45  		when(u.getHeaderFields()).thenReturn(headers);
46  		assertValues("AbC", "x");
47  	}
48  
49  	@Test
50  	public void testMultiple1() {
51  		headers.put("abc", asList("a"));
52  		headers.put("aBC", asList("d", "e"));
53  		headers.put("ABc", Collections.emptyList());
54  		headers.put("AbC", (List<String>) null);
55  		when(u.getHeaderFields()).thenReturn(headers);
56  		assertValues("AbC", "a", "d", "e", "x");
57  	}
58  
59  	@Test
60  	public void testMultiple2() {
61  		headers.put("ab", asList("y", "z", "z"));
62  		when(u.getHeaderFields()).thenReturn(headers);
63  		assertValues("ab", "z", "y", "z");
64  		assertValues("abc", "x");
65  		assertValues("aBc", "x");
66  		assertValues("AbCd");
67  	}
68  
69  	@Test
70  	public void testCommaSeparatedList() {
71  		headers.put("abc", asList("a,b,c", "d"));
72  		when(u.getHeaderFields()).thenReturn(headers);
73  		assertValues("Abc", "a,b,c", "x", "d");
74  	}
75  
76  	private void assertValues(String key, String... values) {
77  		List<String> l = new LinkedList<>();
78  		List<String> hf = c.getHeaderFields(key);
79  		if (hf != null) {
80  			l.addAll(hf);
81  		}
82  		for (String v : values) {
83  			if (!l.remove(v)) {
84  				fail("value " + v + " not found");
85  			}
86  		}
87  		assertTrue("found unexpected entries " + l, l.isEmpty());
88  	}
89  
90  }