├── .gitignore
├── LICENSE.txt
├── README.md
├── core
├── pom.xml
└── src
│ ├── main
│ └── java
│ │ └── net
│ │ └── javacrumbs
│ │ └── mocksocket
│ │ ├── MockSocket.java
│ │ ├── MockSocketException.java
│ │ ├── connection
│ │ ├── AbstractMockConnectionFactory.java
│ │ ├── Connection.java
│ │ ├── ConnectionFactory.java
│ │ ├── ConnectionFactoryMockSocketImpl.java
│ │ ├── DefaultConnection.java
│ │ ├── RequestRecorder.java
│ │ ├── StaticConnectionFactory.java
│ │ ├── StringUtils.java
│ │ ├── UniversalMockConnectionFactory.java
│ │ ├── UniversalMockRecorder.java
│ │ ├── data
│ │ │ ├── DefaultSocketData.java
│ │ │ ├── OutputSocketData.java
│ │ │ ├── RequestSocketData.java
│ │ │ └── SocketData.java
│ │ ├── matcher
│ │ │ ├── MatcherBasedMockConnectionFactory.java
│ │ │ ├── MatcherBasedMockRecorder.java
│ │ │ └── MatcherBasedMockResultRecorder.java
│ │ └── sequential
│ │ │ ├── SequentialMockConnectionFactory.java
│ │ │ └── SequentialMockRecorder.java
│ │ ├── matchers
│ │ ├── AbstractSocketMatcher.java
│ │ ├── AddressMatcher.java
│ │ └── DataMatcher.java
│ │ ├── socket
│ │ ├── AbstractMockSocketImpl.java
│ │ └── MockSocketImplFactory.java
│ │ └── util
│ │ └── Utils.java
│ └── test
│ └── java
│ └── net
│ └── javacrumbs
│ └── mocksocket
│ ├── MockSocketTest.java
│ ├── SampleTest.java
│ └── connection
│ └── StaticConnectionFactoryTest.java
├── header.txt
├── http
├── pom.xml
└── src
│ ├── main
│ └── java
│ │ └── net
│ │ └── javacrumbs
│ │ └── mocksocket
│ │ └── http
│ │ ├── HttpGeneratorException.java
│ │ ├── HttpMockSocket.java
│ │ ├── HttpParser.java
│ │ ├── HttpRequest.java
│ │ ├── HttpResponseGenerator.java
│ │ └── matchers
│ │ ├── AbstractHttpMatcher.java
│ │ ├── ContentMatcher.java
│ │ ├── ContentTypeMatcher.java
│ │ ├── HeaderMatcher.java
│ │ ├── MethodMatcher.java
│ │ ├── StatusMatcher.java
│ │ └── UriMatcher.java
│ └── test
│ └── java
│ └── net
│ └── javacrumbs
│ └── mocksocket
│ └── http
│ ├── HttpMatchersTest.java
│ ├── HttpParserTest.java
│ ├── HttpResponseGeneratorTest.java
│ └── SampleTest.java
└── pom.xml
/.gitignore:
--------------------------------------------------------------------------------
1 | target
2 | .settings
3 | .classpath
4 | .project
5 | *.iml
6 | .idea
7 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | Mock Socket
2 | ===========
3 |
4 | **This project is effectively dead. If you need HTTP mocking, I can recommend [Jadler](http://jadler.net)**
5 |
6 | Mock Socket project is here to help you with testing of your Java Socket related code. It has two parts
7 |
8 | * [Core](https://github.com/lukas-krecan/mock-socket/wiki/Core-API) - code for mocking of general Java sockets
9 | * [HTTP](https://github.com/lukas-krecan/mock-socket/wiki/HTTP) - support for text based HTTP socket testing
10 |
--------------------------------------------------------------------------------
/core/pom.xml:
--------------------------------------------------------------------------------
1 |
2 | 4.0.0
3 |
4 |
5 | net.javacrumbs
6 | mock-socket-parent
7 | 0.9.1-SNAPSHOT
8 |
9 |
10 | net.javacrumbs
11 | mock-socket-core
12 | 0.9.1-SNAPSHOT
13 | mock-socket-core
14 |
15 |
16 |
17 | org.hamcrest
18 | hamcrest-core
19 | 1.2.1
20 |
21 |
22 | org.apache.httpcomponents
23 | httpclient
24 | 4.1.1
25 | test
26 |
27 |
28 | org.mockito
29 | mockito-all
30 | 1.8.5
31 | test
32 |
33 |
34 | commons-io
35 | commons-io
36 | 2.0.1
37 |
38 |
39 |
40 |
--------------------------------------------------------------------------------
/core/src/main/java/net/javacrumbs/mocksocket/MockSocket.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2005-2010 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.javacrumbs.mocksocket;
18 |
19 | import static org.hamcrest.CoreMatchers.is;
20 |
21 | import java.io.InputStream;
22 | import java.util.List;
23 |
24 | import net.javacrumbs.mocksocket.connection.ConnectionFactory;
25 | import net.javacrumbs.mocksocket.connection.StaticConnectionFactory;
26 | import net.javacrumbs.mocksocket.connection.StringUtils;
27 | import net.javacrumbs.mocksocket.connection.UniversalMockRecorder;
28 | import net.javacrumbs.mocksocket.connection.data.DefaultSocketData;
29 | import net.javacrumbs.mocksocket.connection.data.RequestSocketData;
30 | import net.javacrumbs.mocksocket.connection.data.SocketData;
31 | import net.javacrumbs.mocksocket.matchers.AddressMatcher;
32 | import net.javacrumbs.mocksocket.matchers.DataMatcher;
33 | import net.javacrumbs.mocksocket.util.Utils;
34 |
35 | import org.hamcrest.Matcher;
36 | import org.hamcrest.core.CombinableMatcher;
37 |
38 |
39 | /**
40 | * Main class of mock socket to be statically imported tou your test.
41 | * @author Lukas Krecan
42 | *
43 | */
44 | public class MockSocket {
45 | protected MockSocket()
46 | {
47 |
48 | }
49 |
50 | /**
51 | * Prepares mock socket to be trained.
52 | * @return
53 | */
54 | public static UniversalMockRecorder expectCall() {
55 | return StaticConnectionFactory.expectCall();
56 | }
57 |
58 | /**
59 | * To be called after each test.
60 | */
61 | public static void reset()
62 | {
63 | StaticConnectionFactory.reset();
64 | }
65 |
66 | /**
67 | * Returns request data.
68 | * @return
69 | */
70 | public static List recordedConnections()
71 | {
72 | return StaticConnectionFactory.getRequestRecorder().requestData();
73 | }
74 |
75 |
76 |
77 | /**
78 | * Empty response.
79 | * @return
80 | */
81 | public static SocketData emptyResponse()
82 | {
83 | return new DefaultSocketData(new byte[0]);
84 | }
85 |
86 | /**
87 | * Response with given data.
88 | * @return
89 | */
90 | public static SocketData data(byte[] data)
91 | {
92 | return new DefaultSocketData(data);
93 | }
94 |
95 | /**
96 | * Matcher that can compare data. To be used in {@link UniversalMockRecorder#andWhenRequest} method.
97 | * @param dataMatcher
98 | * @return
99 | */
100 | public static Matcher data(Matcher dataMatcher)
101 | {
102 | return new CombinableMatcher(new DataMatcher(dataMatcher));
103 | }
104 |
105 | /**
106 | * Matcher that can compare data. To be used in {@link UniversalMockRecorder#andWhenRequest} method.
107 | * @param dataMatcher
108 | * @return
109 | */
110 | public static Matcher withData(InputStream data)
111 | {
112 | return data(is(Utils.toByteArray(data)));
113 | }
114 |
115 | /**
116 | * Matcher that can compare address. To be used in {@link UniversalMockRecorder#andWhenRequest} method.
117 | * @param addressMatcher
118 | * @return
119 | */
120 | public static Matcher address(Matcher addressMatcher)
121 | {
122 | return new CombinableMatcher(new AddressMatcher(addressMatcher));
123 | }
124 |
125 | /**
126 | * Matcher that can compare data. To be used in request assertions.
127 | * @param dataMatcher
128 | * @return
129 | */
130 | public static Matcher dataAre(InputStream data)
131 | {
132 | return new CombinableMatcher(new DataMatcher(is(Utils.toByteArray(data))));
133 | }
134 | /**
135 | * Matcher that can compare data. To be used in request assertions.
136 | * @param dataMatcher
137 | * @return
138 | */
139 | public static Matcher dataAre(SocketData data)
140 | {
141 | return dataAre(data.getData());
142 | }
143 |
144 |
145 | /**
146 | * Sets custom connection factory.
147 | * @param connectionFactory
148 | */
149 | public static void useConnectionFactory(ConnectionFactory connectionFactory) {
150 | StaticConnectionFactory.useConnectionFactory(connectionFactory);
151 | }
152 |
153 | public static boolean isPrintDataAsString() {
154 | return StringUtils.isPrintDataAsString();
155 | }
156 |
157 | /**
158 | * Should be data printed as string or as byte array.
159 | * @param printDataAsString
160 | */
161 | public static void setPrintDataAsString(boolean printDataAsString) {
162 | StringUtils.setPrintDataAsString(printDataAsString);
163 | }
164 |
165 | public static String getDefaultEncoding() {
166 | return StringUtils.getDefaultEncoding();
167 | }
168 |
169 | /**
170 | * Default encoding for byte[] -> String conversion.
171 | * @param defaultEncoding
172 | */
173 | public static void setDefaultEncoding(String defaultEncoding) {
174 | StringUtils.setDefaultEncoding(defaultEncoding);
175 | }
176 | }
177 |
--------------------------------------------------------------------------------
/core/src/main/java/net/javacrumbs/mocksocket/MockSocketException.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2005-2010 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.javacrumbs.mocksocket;
18 |
19 | /**
20 | * Exception thrown when mock-socket fails.
21 | * @author Lukas Krecan
22 | *
23 | */
24 | public class MockSocketException extends RuntimeException {
25 | private static final long serialVersionUID = -6476984055059688027L;
26 |
27 | public MockSocketException(String message, Throwable cause) {
28 | super(message, cause);
29 | }
30 |
31 | public MockSocketException(String message) {
32 | super(message);
33 | }
34 |
35 | public MockSocketException(Throwable cause) {
36 | super(cause);
37 | }
38 |
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/core/src/main/java/net/javacrumbs/mocksocket/connection/AbstractMockConnectionFactory.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2009-2011 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package net.javacrumbs.mocksocket.connection;
17 |
18 | import java.io.InputStream;
19 | import java.util.ArrayList;
20 | import java.util.List;
21 |
22 | import net.javacrumbs.mocksocket.connection.data.OutputSocketData;
23 | import net.javacrumbs.mocksocket.connection.data.RequestSocketData;
24 |
25 |
26 | /**
27 | * Common code for creating MockConnections.
28 | * @author Lukas Krecan
29 | *
30 | */
31 | public abstract class AbstractMockConnectionFactory implements RequestRecorder, ConnectionFactory {
32 |
33 | private final List requestData = new ArrayList();
34 | private int actualConnection = -1;
35 |
36 | public synchronized Connection createConnection(String address) {
37 | actualConnection++;
38 | requestData.add(createRequestSocket(address));
39 |
40 | return new DefaultConnection(createInputStream(), getRequestSocketData().getOutputStream());
41 | }
42 |
43 | protected OutputSocketData createRequestSocket(String address) {
44 | return new OutputSocketData(address);
45 | }
46 |
47 | protected abstract InputStream createInputStream();
48 |
49 | protected synchronized OutputSocketData getRequestSocketData() {
50 | return requestData.get(actualConnection);
51 | }
52 |
53 | public synchronized List requestData() {
54 | return new ArrayList(requestData);
55 | }
56 |
57 | protected synchronized int getActualConnection() {
58 | return actualConnection;
59 | }
60 | }
--------------------------------------------------------------------------------
/core/src/main/java/net/javacrumbs/mocksocket/connection/Connection.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2009-2011 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package net.javacrumbs.mocksocket.connection;
17 |
18 | import java.io.IOException;
19 | import java.io.InputStream;
20 | import java.io.OutputStream;
21 |
22 | /**
23 | * Mock socket connection.
24 | * @author Lukas Krecan
25 | *
26 | */
27 | public interface Connection {
28 |
29 | InputStream getInputStream() throws IOException;
30 |
31 | OutputStream getOutputStream() throws IOException;
32 |
33 | }
34 |
--------------------------------------------------------------------------------
/core/src/main/java/net/javacrumbs/mocksocket/connection/ConnectionFactory.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2009-2011 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package net.javacrumbs.mocksocket.connection;
17 |
18 | /**
19 | * Creates mock socket connection.
20 | * @author Lukas Krecan
21 | *
22 | */
23 | public interface ConnectionFactory {
24 |
25 | Connection createConnection(String address);
26 |
27 | }
28 |
--------------------------------------------------------------------------------
/core/src/main/java/net/javacrumbs/mocksocket/connection/ConnectionFactoryMockSocketImpl.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2009-2011 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package net.javacrumbs.mocksocket.connection;
17 |
18 | import java.io.IOException;
19 | import java.io.InputStream;
20 | import java.io.OutputStream;
21 |
22 | import net.javacrumbs.mocksocket.socket.AbstractMockSocketImpl;
23 |
24 | /**
25 | * MockSocket impl that uses a {@link ConnectionFactory}.
26 | * @author Lukas Krecan
27 | *
28 | */
29 | public class ConnectionFactoryMockSocketImpl extends AbstractMockSocketImpl {
30 | private final ConnectionFactory connectionFactory;
31 | private Connection connection;
32 |
33 | public ConnectionFactoryMockSocketImpl(ConnectionFactory connectionFactory) {
34 | this.connectionFactory = connectionFactory;
35 | }
36 |
37 | @Override
38 | protected void onConnect(String address) {
39 | connection = connectionFactory.createConnection(address);
40 | }
41 |
42 | @Override
43 | protected InputStream getInputStream() throws IOException {
44 | assertConnection();
45 | return connection.getInputStream();
46 | }
47 |
48 | @Override
49 | protected OutputStream getOutputStream() throws IOException {
50 | assertConnection();
51 | return connection.getOutputStream();
52 | }
53 |
54 | private void assertConnection() {
55 | if (connection == null)
56 | {
57 | throw new IllegalStateException("Connection is not open");
58 | }
59 |
60 | }
61 |
62 | }
63 |
--------------------------------------------------------------------------------
/core/src/main/java/net/javacrumbs/mocksocket/connection/DefaultConnection.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2005-2010 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.javacrumbs.mocksocket.connection;
18 |
19 | import java.io.IOException;
20 | import java.io.InputStream;
21 | import java.io.OutputStream;
22 |
23 | /**
24 | * Default connection implementation.
25 | * @author Lukas Krecan
26 | *
27 | */
28 | public class DefaultConnection implements Connection {
29 |
30 | private final InputStream inputStream;
31 |
32 | private final OutputStream outputStream;
33 |
34 | public DefaultConnection(InputStream inputStream, OutputStream outputStream) {
35 | this.inputStream = inputStream;
36 | this.outputStream = outputStream;
37 | }
38 |
39 | public InputStream getInputStream() throws IOException {
40 | return inputStream;
41 | }
42 |
43 | public OutputStream getOutputStream() throws IOException {
44 | return outputStream;
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/core/src/main/java/net/javacrumbs/mocksocket/connection/RequestRecorder.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2009-2011 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package net.javacrumbs.mocksocket.connection;
17 |
18 | import java.util.List;
19 |
20 | import net.javacrumbs.mocksocket.connection.data.RequestSocketData;
21 |
22 | public interface RequestRecorder {
23 | public List requestData();
24 | }
25 |
--------------------------------------------------------------------------------
/core/src/main/java/net/javacrumbs/mocksocket/connection/StaticConnectionFactory.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2009-2011 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package net.javacrumbs.mocksocket.connection;
17 |
18 | import java.io.IOException;
19 | import java.net.Socket;
20 | import java.net.SocketImplFactory;
21 |
22 | import net.javacrumbs.mocksocket.MockSocketException;
23 | import net.javacrumbs.mocksocket.socket.MockSocketImplFactory;
24 |
25 |
26 | /**
27 | * Stores connections in a static field. It is NOT threads safe so you can not execute multiple tests in parallel.
28 | * You also can not use it if there is a {@link SocketImplFactory} already set.
29 | * @author Lukas Krecan
30 | * @see Socket#setSocketImplFactory(SocketImplFactory)
31 | */
32 | public class StaticConnectionFactory implements ConnectionFactory {
33 | private static ConnectionFactory connectionFactory;
34 |
35 | static
36 | {
37 | bootstrap();
38 | }
39 |
40 | static void bootstrap()
41 | {
42 | try {
43 | Socket.setSocketImplFactory(new MockSocketImplFactory(new StaticConnectionFactory()));
44 | } catch (IOException e) {
45 | throw new IllegalStateException("Can not bootstrap the connection factory",e);
46 | }
47 | }
48 |
49 | public synchronized Connection createConnection(String address) {
50 | if (connectionFactory==null)
51 | {
52 | throw new IllegalStateException("Connection not expected. You have to call expectCall() or useConnectionFactory() first.");
53 | }
54 | return connectionFactory.createConnection(address);
55 | }
56 |
57 | public synchronized static UniversalMockRecorder expectCall() {
58 | if (getConnectionFactory()==null)
59 | {
60 | UniversalMockConnectionFactory mockConnection = new UniversalMockConnectionFactory();
61 | useConnectionFactory(mockConnection);
62 | return mockConnection;
63 | }
64 | else
65 | {
66 | throw new IllegalArgumentException("Can not call expectCall twice. You have to call reset before each test. If you need simulate multiple requests, please call andReturn several times.");
67 | }
68 | }
69 |
70 | public synchronized static void reset()
71 | {
72 | connectionFactory = null;
73 | }
74 |
75 |
76 | public static void useConnectionFactory(ConnectionFactory connectionFactory) {
77 | StaticConnectionFactory.connectionFactory = connectionFactory;
78 | }
79 |
80 | protected synchronized static ConnectionFactory getConnectionFactory() {
81 | return connectionFactory;
82 | }
83 | public synchronized static RequestRecorder getRequestRecorder() {
84 | if (connectionFactory instanceof RequestRecorder)
85 | {
86 | return (RequestRecorder)connectionFactory;
87 | }
88 | else if (connectionFactory!=null)
89 | {
90 | throw new MockSocketException("Connection factory "+connectionFactory.getClass()+" is not instance of "+RequestRecorder.class);
91 | }
92 | else
93 | {
94 | throw new IllegalStateException("Connection factory is not set.");
95 | }
96 | }
97 | }
98 |
--------------------------------------------------------------------------------
/core/src/main/java/net/javacrumbs/mocksocket/connection/StringUtils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2005-2010 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.javacrumbs.mocksocket.connection;
18 |
19 | import java.io.UnsupportedEncodingException;
20 | import java.util.Arrays;
21 |
22 | public class StringUtils {
23 | private static boolean printDataAsString = true;
24 |
25 | private static String defaultEncoding = "UTF-8";
26 |
27 | public static synchronized boolean isPrintDataAsString() {
28 | return printDataAsString;
29 | }
30 |
31 | /**
32 | * Should be data printed as string or as byte array.
33 | * @param printDataAsString
34 | */
35 | public static synchronized void setPrintDataAsString(boolean printDataAsString) {
36 | StringUtils.printDataAsString = printDataAsString;
37 | }
38 |
39 | public static synchronized String getDefaultEncoding() {
40 | return defaultEncoding;
41 | }
42 |
43 | public static synchronized void setDefaultEncoding(String defaultEncoding) {
44 | StringUtils.defaultEncoding = defaultEncoding;
45 | }
46 |
47 | public static String convertDataToString(byte[] data) {
48 | if (printDataAsString)
49 | {
50 | try {
51 | return new String(data, defaultEncoding);
52 | } catch (UnsupportedEncodingException e) {
53 | return new String(data);
54 | }
55 | }
56 | else
57 | {
58 | return Arrays.toString(data);
59 | }
60 | }
61 | }
62 |
--------------------------------------------------------------------------------
/core/src/main/java/net/javacrumbs/mocksocket/connection/UniversalMockConnectionFactory.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2009-2011 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package net.javacrumbs.mocksocket.connection;
17 |
18 | import java.util.List;
19 |
20 | import net.javacrumbs.mocksocket.connection.data.RequestSocketData;
21 | import net.javacrumbs.mocksocket.connection.data.SocketData;
22 | import net.javacrumbs.mocksocket.connection.matcher.MatcherBasedMockConnectionFactory;
23 | import net.javacrumbs.mocksocket.connection.matcher.MatcherBasedMockResultRecorder;
24 | import net.javacrumbs.mocksocket.connection.sequential.SequentialMockConnectionFactory;
25 | import net.javacrumbs.mocksocket.connection.sequential.SequentialMockRecorder;
26 |
27 | import org.hamcrest.Matcher;
28 |
29 | /**
30 | * Mock connection that creates and wraps either {@link SequentialMockConnectionFactory} or {@link MatcherBasedMockConnectionFactory}.
31 | * @author Lukas Krecan
32 | *
33 | */
34 | public class UniversalMockConnectionFactory implements UniversalMockRecorder, RequestRecorder, ConnectionFactory {
35 | private AbstractMockConnectionFactory wrappedConnection;
36 |
37 | public SequentialMockRecorder andReturn(SocketData data) {
38 | SequentialMockConnectionFactory connection = createSequentialConnection();
39 | wrappedConnection = connection;
40 | connection.andReturn(data);
41 | return connection;
42 | }
43 |
44 | protected SequentialMockConnectionFactory createSequentialConnection() {
45 | return new SequentialMockConnectionFactory();
46 | }
47 |
48 | public MatcherBasedMockResultRecorder andWhenRequest(Matcher matcher) {
49 | MatcherBasedMockConnectionFactory connection = createMatcherBasedConnection();
50 | connection.andWhenRequest(matcher);
51 | wrappedConnection = connection;
52 | return connection;
53 | }
54 |
55 | protected MatcherBasedMockConnectionFactory createMatcherBasedConnection() {
56 | return new MatcherBasedMockConnectionFactory();
57 | }
58 |
59 | public Connection createConnection(String address) {
60 | return wrappedConnection.createConnection(address);
61 | }
62 |
63 | public List requestData() {
64 | return wrappedConnection.requestData();
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/core/src/main/java/net/javacrumbs/mocksocket/connection/UniversalMockRecorder.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2009-2011 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package net.javacrumbs.mocksocket.connection;
17 |
18 | import net.javacrumbs.mocksocket.connection.data.RequestSocketData;
19 | import net.javacrumbs.mocksocket.connection.data.SocketData;
20 | import net.javacrumbs.mocksocket.connection.matcher.MatcherBasedMockResultRecorder;
21 | import net.javacrumbs.mocksocket.connection.sequential.SequentialMockRecorder;
22 |
23 | import org.hamcrest.Matcher;
24 |
25 | /**
26 | * Can record both sequential and matcher based mocks.
27 | * @author Lukas Krecan
28 | *
29 | */
30 | public interface UniversalMockRecorder {
31 | public SequentialMockRecorder andReturn(SocketData data);
32 |
33 | public MatcherBasedMockResultRecorder andWhenRequest(Matcher matcher);
34 | }
35 |
--------------------------------------------------------------------------------
/core/src/main/java/net/javacrumbs/mocksocket/connection/data/DefaultSocketData.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2005-2010 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.javacrumbs.mocksocket.connection.data;
18 |
19 | import java.io.ByteArrayInputStream;
20 | import java.io.InputStream;
21 |
22 | import net.javacrumbs.mocksocket.connection.StringUtils;
23 |
24 | /**
25 | * Wraps socket data.
26 | * @author Lukas Krecan
27 | *
28 | */
29 | public class DefaultSocketData implements SocketData
30 | {
31 |
32 | protected final byte[] data;
33 |
34 |
35 | public DefaultSocketData(byte[] data) {
36 | this.data = data.clone();
37 | }
38 |
39 | public InputStream getData() {
40 | return new ByteArrayInputStream(data);
41 | }
42 |
43 | @Override
44 | public String toString() {
45 | return StringUtils.convertDataToString(data);
46 | }
47 | }
--------------------------------------------------------------------------------
/core/src/main/java/net/javacrumbs/mocksocket/connection/data/OutputSocketData.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2005-2010 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.javacrumbs.mocksocket.connection.data;
18 |
19 | import java.io.ByteArrayInputStream;
20 | import java.io.ByteArrayOutputStream;
21 | import java.io.InputStream;
22 | import java.io.OutputStream;
23 |
24 | import net.javacrumbs.mocksocket.connection.StringUtils;
25 |
26 | public class OutputSocketData implements RequestSocketData {
27 |
28 | private final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
29 |
30 | private final String address;
31 |
32 | public OutputSocketData(String address) {
33 | this.address = address;
34 | }
35 |
36 | public InputStream getData() {
37 | return new ByteArrayInputStream(getDataAsBytes());
38 | }
39 |
40 | protected byte[] getDataAsBytes()
41 | {
42 | return outputStream.toByteArray();
43 | }
44 |
45 | public OutputStream getOutputStream() {
46 | return outputStream;
47 | }
48 |
49 | public String getAddress() {
50 | return address;
51 | }
52 |
53 | @Override
54 | public String toString() {
55 | return StringUtils.convertDataToString(getDataAsBytes());
56 | }
57 |
58 | }
59 |
--------------------------------------------------------------------------------
/core/src/main/java/net/javacrumbs/mocksocket/connection/data/RequestSocketData.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2005-2010 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.javacrumbs.mocksocket.connection.data;
18 |
19 |
20 | /**
21 | * Socket data.
22 | * @author Lukas Krecan
23 | *
24 | */
25 | public interface RequestSocketData extends SocketData{
26 |
27 | public String getAddress();
28 | }
--------------------------------------------------------------------------------
/core/src/main/java/net/javacrumbs/mocksocket/connection/data/SocketData.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2005-2010 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.javacrumbs.mocksocket.connection.data;
18 |
19 | import java.io.InputStream;
20 |
21 |
22 | /**
23 | * Socket data.
24 | * @author Lukas Krecan
25 | *
26 | */
27 | public interface SocketData {
28 |
29 | public InputStream getData();
30 | }
--------------------------------------------------------------------------------
/core/src/main/java/net/javacrumbs/mocksocket/connection/matcher/MatcherBasedMockConnectionFactory.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2009-2011 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package net.javacrumbs.mocksocket.connection.matcher;
17 |
18 | import java.io.IOException;
19 | import java.io.InputStream;
20 | import java.util.ArrayList;
21 | import java.util.List;
22 |
23 | import net.javacrumbs.mocksocket.MockSocketException;
24 | import net.javacrumbs.mocksocket.connection.AbstractMockConnectionFactory;
25 | import net.javacrumbs.mocksocket.connection.RequestRecorder;
26 | import net.javacrumbs.mocksocket.connection.data.RequestSocketData;
27 | import net.javacrumbs.mocksocket.connection.data.SocketData;
28 |
29 | import org.hamcrest.Matcher;
30 |
31 | /**
32 | * Mock connection that is based on {@link Matcher}s.
33 | * @author Lukas Krecan
34 | *
35 | */
36 | public class MatcherBasedMockConnectionFactory extends AbstractMockConnectionFactory implements RequestRecorder, MatcherBasedMockResultRecorder, MatcherBasedMockRecorder {
37 |
38 | private final List matchers = new ArrayList();
39 |
40 | protected InputStream createInputStream() {
41 | return new RedirectingInputStream(getRequestSocketData());
42 | }
43 |
44 | public MatcherBasedMockRecorder thenReturn(SocketData data) {
45 | matchers.get(matchers.size()-1).addData(data);
46 | return this;
47 | }
48 |
49 |
50 | public MatcherBasedMockResultRecorder andWhenRequest(Matcher matcher) {
51 | matchers.add(new MatcherWithData(matcher));
52 | return this;
53 | }
54 |
55 | /**
56 | * Input stream that redirects to actual InputStread based on OutputStreamData. Has to be done this way since InputStram could be created before
57 | * OutputStream data are written.
58 | * @author Lukas Krecan
59 | *
60 | */
61 | class RedirectingInputStream extends InputStream
62 | {
63 | private final RequestSocketData requestSocketData;
64 | private InputStream wrappedInputStream;
65 |
66 | public RedirectingInputStream(RequestSocketData requestSocketData)
67 | {
68 | this.requestSocketData = requestSocketData;
69 | }
70 |
71 | @Override
72 | public int read() throws IOException {
73 | if (wrappedInputStream==null)
74 | {
75 | wrappedInputStream = findInputStream();
76 | }
77 | return wrappedInputStream.read();
78 | }
79 |
80 | private InputStream findInputStream() throws IOException, MockSocketException {
81 | for (MatcherWithData matcher : matchers) {
82 | if (matcher.getMatcher().matches(requestSocketData))
83 | {
84 | return matcher.getResponse();
85 | }
86 | }
87 | throw new MockSocketException("No matcher matches request "+requestSocketData+". Do not know which response to return.");
88 | }
89 | }
90 |
91 | protected class MatcherWithData
92 | {
93 | private final Matcher matcher;
94 | private final List responseData = new ArrayList();
95 | private int actualResponse = 0;
96 |
97 | public MatcherWithData(Matcher matcher) {
98 | this.matcher = matcher;
99 | }
100 |
101 | public InputStream getResponse() {
102 | if (responseData.size()>actualResponse)
103 | {
104 | return responseData.get(actualResponse++).getData();
105 | }
106 | else
107 | {
108 | throw new MockSocketException("No more connections expected for request matching matcher: "+matcher+". Requests recorded so far are: "+requestData());
109 | }
110 | }
111 |
112 | public void addData(SocketData data)
113 | {
114 | responseData.add(data);
115 | }
116 |
117 | public Matcher getMatcher() {
118 | return matcher;
119 | }
120 |
121 |
122 | }
123 |
124 | }
125 |
--------------------------------------------------------------------------------
/core/src/main/java/net/javacrumbs/mocksocket/connection/matcher/MatcherBasedMockRecorder.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2009-2011 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package net.javacrumbs.mocksocket.connection.matcher;
17 |
18 | import net.javacrumbs.mocksocket.connection.data.RequestSocketData;
19 |
20 | import org.hamcrest.Matcher;
21 |
22 | public interface MatcherBasedMockRecorder extends MatcherBasedMockResultRecorder{
23 | MatcherBasedMockResultRecorder andWhenRequest(Matcher matcher);
24 | }
25 |
--------------------------------------------------------------------------------
/core/src/main/java/net/javacrumbs/mocksocket/connection/matcher/MatcherBasedMockResultRecorder.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2009-2011 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package net.javacrumbs.mocksocket.connection.matcher;
17 |
18 | import net.javacrumbs.mocksocket.connection.data.SocketData;
19 |
20 | public interface MatcherBasedMockResultRecorder {
21 |
22 | /**
23 | * When the condition is met, return this data.
24 | * @param data
25 | * @return
26 | */
27 | MatcherBasedMockRecorder thenReturn(SocketData data);
28 | }
29 |
--------------------------------------------------------------------------------
/core/src/main/java/net/javacrumbs/mocksocket/connection/sequential/SequentialMockConnectionFactory.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2009-2011 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package net.javacrumbs.mocksocket.connection.sequential;
17 |
18 | import java.io.InputStream;
19 | import java.util.ArrayList;
20 | import java.util.List;
21 |
22 | import net.javacrumbs.mocksocket.MockSocketException;
23 | import net.javacrumbs.mocksocket.connection.AbstractMockConnectionFactory;
24 | import net.javacrumbs.mocksocket.connection.RequestRecorder;
25 | import net.javacrumbs.mocksocket.connection.data.SocketData;
26 |
27 | /**
28 | * Mock connection. Can simulate multiple requests to the same address.
29 | * @author Lukas Krecan
30 | *
31 | */
32 | public class SequentialMockConnectionFactory extends AbstractMockConnectionFactory implements RequestRecorder, SequentialMockRecorder{
33 | private final List responseData = new ArrayList();
34 | public SequentialMockConnectionFactory() {
35 | }
36 |
37 | public SequentialMockRecorder andReturn(SocketData data) {
38 | this.responseData.add(data);
39 | return this;
40 | }
41 |
42 | protected InputStream createInputStream() {
43 | int actualConnection = getActualConnection();
44 | if (responseData.size()>actualConnection )
45 | {
46 | return responseData.get(actualConnection).getData();
47 | }
48 | else
49 | {
50 | throw new MockSocketException("No more connections expected. Requests recorded so far are: "+requestData());
51 | }
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/core/src/main/java/net/javacrumbs/mocksocket/connection/sequential/SequentialMockRecorder.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2009-2011 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package net.javacrumbs.mocksocket.connection.sequential;
17 |
18 | import net.javacrumbs.mocksocket.connection.data.SocketData;
19 |
20 | /**
21 | * Records calls in sequence.
22 | * @author Lukas Krecan
23 | *
24 | */
25 | public interface SequentialMockRecorder {
26 | public SequentialMockRecorder andReturn(SocketData data);
27 | }
28 |
--------------------------------------------------------------------------------
/core/src/main/java/net/javacrumbs/mocksocket/matchers/AbstractSocketMatcher.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2009-2011 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package net.javacrumbs.mocksocket.matchers;
17 |
18 | import net.javacrumbs.mocksocket.connection.data.SocketData;
19 |
20 | import org.hamcrest.BaseMatcher;
21 | import org.hamcrest.Matcher;
22 |
23 | public abstract class AbstractSocketMatcher extends BaseMatcher {
24 |
25 | private final Matcher> wrappedMatcher;
26 |
27 | public AbstractSocketMatcher(Matcher> wrappedMatcher) {
28 | this.wrappedMatcher = wrappedMatcher;
29 | }
30 |
31 | protected Matcher> getWrappedMatcher() {
32 | return wrappedMatcher;
33 | }
34 |
35 |
36 | }
--------------------------------------------------------------------------------
/core/src/main/java/net/javacrumbs/mocksocket/matchers/AddressMatcher.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2005-2010 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.javacrumbs.mocksocket.matchers;
18 |
19 | import net.javacrumbs.mocksocket.connection.data.RequestSocketData;
20 |
21 | import org.hamcrest.Description;
22 | import org.hamcrest.Matcher;
23 |
24 | public class AddressMatcher extends AbstractSocketMatcher {
25 |
26 | public AddressMatcher(Matcher wrappedMatcher) {
27 | super(wrappedMatcher);
28 | }
29 |
30 | public void describeTo(Description description) {
31 | description.appendText("address ").appendDescriptionOf(getWrappedMatcher());
32 | }
33 |
34 | public boolean matches(Object item) {
35 | if (item instanceof RequestSocketData) {
36 | return getWrappedMatcher().matches(((RequestSocketData) item).getAddress());
37 | }
38 | return false;
39 | }
40 |
41 |
42 | }
43 |
--------------------------------------------------------------------------------
/core/src/main/java/net/javacrumbs/mocksocket/matchers/DataMatcher.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2005-2010 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.javacrumbs.mocksocket.matchers;
18 |
19 | import net.javacrumbs.mocksocket.connection.data.SocketData;
20 | import net.javacrumbs.mocksocket.util.Utils;
21 |
22 | import org.hamcrest.Description;
23 | import org.hamcrest.Matcher;
24 |
25 | public class DataMatcher extends AbstractSocketMatcher {
26 |
27 |
28 | public DataMatcher(Matcher wrappedMatcher) {
29 | super(wrappedMatcher);
30 | }
31 |
32 | public void describeTo(Description description) {
33 | description.appendText("data ").appendDescriptionOf(getWrappedMatcher());
34 | }
35 |
36 | public boolean matches(Object item) {
37 | if (item instanceof SocketData) {
38 | return getWrappedMatcher().matches(Utils.toByteArray(((SocketData) item).getData()));
39 | }
40 | return false;
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/core/src/main/java/net/javacrumbs/mocksocket/socket/AbstractMockSocketImpl.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2009-2011 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package net.javacrumbs.mocksocket.socket;
17 |
18 | import java.io.IOException;
19 | import java.net.InetAddress;
20 | import java.net.InetSocketAddress;
21 | import java.net.SocketAddress;
22 | import java.net.SocketException;
23 | import java.net.SocketImpl;
24 |
25 | public abstract class AbstractMockSocketImpl extends SocketImpl {
26 |
27 | /**
28 | * Invoked on a connect method call.
29 | * @param address host:port
30 | */
31 | protected abstract void onConnect(String address);
32 |
33 | public void setOption(int optID, Object value) throws SocketException {
34 |
35 | }
36 |
37 | public Object getOption(int optID) throws SocketException {
38 | return null;
39 | }
40 |
41 | @Override
42 | protected void create(boolean stream) throws IOException {
43 |
44 | }
45 |
46 | @Override
47 | protected void connect(String host, int port) throws IOException {
48 | onConnect(host+":"+port);
49 | }
50 |
51 |
52 |
53 | @Override
54 | protected void connect(InetAddress address, int port) throws IOException {
55 | connect(address.getHostAddress(), port);
56 | }
57 |
58 | @Override
59 | protected void connect(SocketAddress address, int timeout) throws IOException {
60 | if (address instanceof InetSocketAddress)
61 | {
62 | InetSocketAddress inetSocketAddress = (InetSocketAddress) address;
63 | connect(inetSocketAddress.getHostName(), inetSocketAddress.getPort());
64 | }
65 | else
66 | {
67 | onConnect(address.toString());
68 | }
69 | }
70 |
71 | @Override
72 | protected void bind(InetAddress host, int port) throws IOException {
73 |
74 | }
75 |
76 | @Override
77 | protected void listen(int backlog) throws IOException {
78 |
79 | }
80 |
81 | @Override
82 | protected void accept(SocketImpl s) throws IOException {
83 |
84 | }
85 |
86 |
87 | @Override
88 | protected int available() throws IOException {
89 | return 0;
90 | }
91 |
92 | @Override
93 | protected void sendUrgentData(int data) throws IOException {
94 |
95 | }
96 |
97 | @Override
98 | protected void close() throws IOException {
99 |
100 | }
101 |
102 | }
103 |
--------------------------------------------------------------------------------
/core/src/main/java/net/javacrumbs/mocksocket/socket/MockSocketImplFactory.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2009-2011 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package net.javacrumbs.mocksocket.socket;
17 |
18 | import java.net.SocketImpl;
19 | import java.net.SocketImplFactory;
20 |
21 | import net.javacrumbs.mocksocket.connection.ConnectionFactory;
22 | import net.javacrumbs.mocksocket.connection.ConnectionFactoryMockSocketImpl;
23 |
24 | public class MockSocketImplFactory implements SocketImplFactory {
25 | private final ConnectionFactory connectionFactory;
26 |
27 | public MockSocketImplFactory(ConnectionFactory connectionFactory) {
28 | this.connectionFactory = connectionFactory;
29 | }
30 |
31 | public SocketImpl createSocketImpl() {
32 | return new ConnectionFactoryMockSocketImpl(connectionFactory);
33 | }
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/core/src/main/java/net/javacrumbs/mocksocket/util/Utils.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2005-2010 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.javacrumbs.mocksocket.util;
18 |
19 | import java.io.IOException;
20 | import java.io.InputStream;
21 |
22 | import net.javacrumbs.mocksocket.MockSocketException;
23 |
24 | import org.apache.commons.io.IOUtils;
25 |
26 | public class Utils {
27 | private Utils()
28 | {
29 | //empty
30 | }
31 |
32 | public static final byte[] toByteArray(InputStream stream)
33 | {
34 | try
35 | {
36 | return IOUtils.toByteArray(stream);
37 | }
38 | catch (IOException e)
39 | {
40 | throw new MockSocketException("Can not read data.",e);
41 | }
42 | finally
43 | {
44 | IOUtils.closeQuietly(stream);
45 | }
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/core/src/test/java/net/javacrumbs/mocksocket/MockSocketTest.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2009-2011 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package net.javacrumbs.mocksocket;
17 |
18 | import static org.junit.Assert.assertEquals;
19 | import static net.javacrumbs.mocksocket.MockSocket.*;
20 |
21 | import java.io.BufferedReader;
22 | import java.io.IOException;
23 | import java.io.InputStream;
24 | import java.io.InputStreamReader;
25 | import java.net.URL;
26 |
27 | import net.javacrumbs.mocksocket.connection.StaticConnectionFactory;
28 | import net.javacrumbs.mocksocket.connection.data.DefaultSocketData;
29 |
30 | import org.apache.http.HttpResponse;
31 | import org.apache.http.client.ClientProtocolException;
32 | import org.apache.http.client.HttpClient;
33 | import org.apache.http.client.methods.HttpGet;
34 | import org.apache.http.impl.client.DefaultHttpClient;
35 | import org.junit.After;
36 | import org.junit.Test;
37 |
38 | public class MockSocketTest {
39 | private static final String ADDRESS = "http://localhost/";
40 |
41 | @After
42 | public void reset()
43 | {
44 | StaticConnectionFactory.reset();
45 | }
46 |
47 | @Test
48 | public void testHttpClient() throws ClientProtocolException, IOException {
49 | expectCall().andReturn(new DefaultSocketData("HTTP/1.0 200 OK\n\nTest".getBytes()));
50 |
51 | HttpClient httpclient = new DefaultHttpClient();
52 | HttpGet httpget = new HttpGet(ADDRESS);
53 | HttpResponse response = httpclient.execute(httpget);
54 | assertEquals("Test", printStream(response.getEntity().getContent()));
55 | }
56 |
57 | @Test
58 | public void testUrl() throws ClientProtocolException, IOException {
59 | expectCall().andReturn(new DefaultSocketData("HTTP/1.0 200 OK\n\nTest".getBytes()));
60 | URL url = new URL(ADDRESS);
61 | assertEquals("Test", printStream(url.openStream()));
62 | }
63 |
64 | private String printStream(InputStream stream) throws IOException {
65 | return new BufferedReader(new InputStreamReader(stream)).readLine();
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/core/src/test/java/net/javacrumbs/mocksocket/SampleTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2005-2010 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.javacrumbs.mocksocket;
18 |
19 | import static net.javacrumbs.mocksocket.MockSocket.address;
20 | import static net.javacrumbs.mocksocket.MockSocket.data;
21 | import static net.javacrumbs.mocksocket.MockSocket.emptyResponse;
22 | import static net.javacrumbs.mocksocket.MockSocket.expectCall;
23 | import static net.javacrumbs.mocksocket.MockSocket.recordedConnections;
24 | import static net.javacrumbs.mocksocket.MockSocket.reset;
25 | import static org.hamcrest.CoreMatchers.is;
26 | import static org.junit.Assert.assertThat;
27 |
28 | import java.net.Socket;
29 |
30 | import javax.net.SocketFactory;
31 |
32 | import org.apache.commons.io.IOUtils;
33 | import org.junit.After;
34 | import org.junit.Test;
35 |
36 | public class SampleTest {
37 |
38 | @Test
39 | public void testResponse() throws Exception
40 | {
41 | byte[] mockData = new byte[]{1,2,3,4};
42 | expectCall().andReturn(data(mockData));
43 |
44 | Socket socket = SocketFactory.getDefault().createSocket("example.org", 1234);
45 | byte[] data = IOUtils.toByteArray(socket.getInputStream());
46 | socket.close();
47 | assertThat(data, is(mockData));
48 | }
49 |
50 | @Test
51 | public void testMultiple() throws Exception
52 | {
53 | byte[] mockData1 = new byte[]{1,2,3,4};
54 | byte[] mockData2 = new byte[]{1,2,3,4};
55 | expectCall().andReturn(data(mockData1)).andReturn(data(mockData2));
56 |
57 | Socket socket1 = SocketFactory.getDefault().createSocket("example.org", 1234);
58 | byte[] data1 = IOUtils.toByteArray(socket1.getInputStream());
59 | socket1.close();
60 | assertThat(data1, is(mockData1));
61 |
62 | Socket socket2 = SocketFactory.getDefault().createSocket("example.org", 1234);
63 | byte[] data2 = IOUtils.toByteArray(socket2.getInputStream());
64 | socket2.close();
65 | assertThat(data2, is(mockData2));
66 | }
67 |
68 | @Test
69 | public void testConditionalAddress() throws Exception
70 | {
71 | byte[] mockData = new byte[]{1,2,3,4};
72 | expectCall().andWhenRequest(address(is("example.org:1234"))).thenReturn(data(mockData));
73 |
74 | Socket socket = SocketFactory.getDefault().createSocket("example.org", 1234);
75 | byte[] data = IOUtils.toByteArray(socket.getInputStream());
76 | socket.close();
77 | assertThat(data, is(mockData));
78 | }
79 |
80 | @Test
81 | public void testConditionalData() throws Exception
82 | {
83 | byte[] dataToWrite = new byte[]{5,4,3,2};
84 | byte[] mockData = new byte[]{1,2,3,4};
85 | expectCall().andWhenRequest(data(is(dataToWrite))).thenReturn(data(mockData));
86 |
87 | Socket socket = SocketFactory.getDefault().createSocket("example.org", 1234);
88 | IOUtils.write(dataToWrite, socket.getOutputStream());
89 | byte[] data = IOUtils.toByteArray(socket.getInputStream());
90 | socket.close();
91 | assertThat(data, is(mockData));
92 | }
93 |
94 | @Test
95 | public void testRequest() throws Exception
96 | {
97 | //prepare mock
98 | byte[] dataToWrite = new byte[]{5,4,3,2};
99 | expectCall().andReturn(emptyResponse());
100 |
101 | //do test
102 | Socket socket = SocketFactory.getDefault().createSocket("example.org", 1234);
103 | IOUtils.write(dataToWrite, socket.getOutputStream());
104 | socket.close();
105 |
106 | //verify data sent
107 | assertThat(recordedConnections().get(0), data(is(dataToWrite)));
108 | assertThat(recordedConnections().get(0), address(is("example.org:1234")));
109 | }
110 |
111 |
112 | @After
113 | public void tearDown()
114 | {
115 | reset();
116 | }
117 | }
118 |
--------------------------------------------------------------------------------
/core/src/test/java/net/javacrumbs/mocksocket/connection/StaticConnectionFactoryTest.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2009-2011 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package net.javacrumbs.mocksocket.connection;
17 |
18 |
19 | import static net.javacrumbs.mocksocket.MockSocket.address;
20 | import static net.javacrumbs.mocksocket.MockSocket.dataAre;
21 | import static net.javacrumbs.mocksocket.MockSocket.withData;
22 | import static org.hamcrest.CoreMatchers.is;
23 | import static org.hamcrest.CoreMatchers.startsWith;
24 | import static org.junit.Assert.assertEquals;
25 | import static org.junit.Assert.assertNotNull;
26 | import static org.junit.Assert.assertSame;
27 | import static org.junit.Assert.assertThat;
28 | import static org.junit.Assert.assertTrue;
29 | import static org.junit.Assert.fail;
30 |
31 | import java.io.IOException;
32 |
33 | import net.javacrumbs.mocksocket.MockSocket;
34 | import net.javacrumbs.mocksocket.MockSocketException;
35 | import net.javacrumbs.mocksocket.connection.data.DefaultSocketData;
36 | import net.javacrumbs.mocksocket.connection.data.SocketData;
37 |
38 | import org.apache.commons.io.IOUtils;
39 | import org.junit.After;
40 | import org.junit.Before;
41 | import org.junit.Test;
42 |
43 |
44 | public class StaticConnectionFactoryTest {
45 |
46 | private static final String ADDRESS1 = "localhost:1111";
47 | private static final String ADDRESS2 = "localhost:2222";
48 | private static final SocketData DATA1 = new DefaultSocketData(new byte[]{1,1,1,1});
49 | private static final SocketData DATA2 = new DefaultSocketData(new byte[]{2,2,2,2});
50 | private static final SocketData DATA3 = new DefaultSocketData(new byte[]{3,3,3,3});
51 | private static final SocketData DATA4 = new DefaultSocketData(new byte[]{4,4,4,4});
52 | private StaticConnectionFactory connectionFactory = new StaticConnectionFactory();
53 |
54 | @Before
55 | public void printAsBytes()
56 | {
57 | MockSocket.setPrintDataAsString(false);
58 | }
59 |
60 | @After
61 | public void resetConnection()
62 | {
63 | StaticConnectionFactory.reset();
64 | MockSocket.setPrintDataAsString(true);
65 | }
66 |
67 | @Test
68 | public void testExpectOne() throws IOException
69 | {
70 | StaticConnectionFactory.expectCall().andReturn(DATA1);
71 |
72 | checkConnection(ADDRESS1,DATA1, DATA4);
73 |
74 | assertThat(StaticConnectionFactory.getRequestRecorder().requestData().get(0), dataAre(DATA4));
75 | assertThat(StaticConnectionFactory.getRequestRecorder().requestData().size(), is(1));
76 | // assertTrue(StaticConnectionFactory.getConnection().containsRequestThat(is(DATA4)));
77 | // assertFalse(StaticConnectionFactory.getConnection().containsRequestThat(is(DATA3)));
78 | }
79 |
80 | @Test(expected=IllegalStateException.class)
81 | public void testUnknown() throws IOException
82 | {
83 | connectionFactory.createConnection(ADDRESS1);
84 | }
85 | @Test
86 | public void testExpectTwo() throws IOException
87 | {
88 | StaticConnectionFactory.expectCall().andReturn(DATA2).andReturn(DATA1);
89 |
90 | checkConnection(ADDRESS1,DATA2, DATA3);
91 | checkConnection(ADDRESS1,DATA1, DATA4);
92 |
93 | assertThat(StaticConnectionFactory.getRequestRecorder().requestData().get(0), dataAre(DATA3));
94 | assertThat(StaticConnectionFactory.getRequestRecorder().requestData().get(1), dataAre(DATA4));
95 | }
96 | @Test
97 | public void testExpectTwoUniversal() throws IOException
98 | {
99 | StaticConnectionFactory.expectCall().andReturn(DATA2).andReturn(DATA1);
100 |
101 | checkConnection(ADDRESS1,DATA2, DATA3);
102 | checkConnection(ADDRESS1,DATA1, DATA4);
103 |
104 | assertThat(StaticConnectionFactory.getRequestRecorder().requestData().get(0), dataAre(DATA3));
105 | assertThat(StaticConnectionFactory.getRequestRecorder().requestData().get(1), dataAre(DATA4));
106 | }
107 | @Test(expected=IllegalArgumentException.class)
108 | public void testExpectTwice() throws IOException
109 | {
110 | StaticConnectionFactory.expectCall().andReturn(DATA2);
111 | StaticConnectionFactory.expectCall().andReturn(DATA1);
112 | }
113 |
114 | @Test
115 | public void testMoreRequests() throws IOException
116 | {
117 | StaticConnectionFactory.expectCall().andReturn(DATA1);
118 |
119 | checkConnection(ADDRESS1,DATA1);
120 | try
121 | {
122 | connectionFactory.createConnection(ADDRESS1);
123 | fail();
124 | }
125 | catch(MockSocketException e)
126 | {
127 | assertThat(e.getMessage(), startsWith("No more connections expected."));
128 | }
129 | }
130 |
131 | @Test
132 | public void testMultipleGetInputStream() throws IOException
133 | {
134 | StaticConnectionFactory.expectCall().andReturn(DATA1);
135 |
136 | Connection connection = connectionFactory.createConnection(ADDRESS1);
137 | assertSame(connection.getInputStream(), connection.getInputStream());
138 | assertSame(connection.getOutputStream(), connection.getOutputStream());
139 | }
140 |
141 |
142 | @Test
143 | public void testWithPayload() throws IOException
144 | {
145 | StaticConnectionFactory.expectCall()
146 | .andWhenRequest(withData(DATA4.getData())).thenReturn(DATA1)
147 | .andWhenRequest(withData(DATA3.getData())).thenReturn(DATA2);
148 |
149 | checkConnection(ADDRESS1,DATA1, DATA4);
150 | checkConnection(ADDRESS1,DATA2, DATA3);
151 |
152 | assertThat(StaticConnectionFactory.getRequestRecorder().requestData().get(0), dataAre(DATA4));
153 |
154 | }
155 | @Test
156 | public void testWithAddress() throws IOException
157 | {
158 | StaticConnectionFactory.expectCall()
159 | .andWhenRequest(address(is(ADDRESS1))).thenReturn(DATA1)
160 | .andWhenRequest(address(is(ADDRESS2))).thenReturn(DATA2);
161 |
162 | checkConnection(ADDRESS1,DATA1, DATA4);
163 | checkConnection(ADDRESS2,DATA2, DATA3);
164 |
165 | assertThat(StaticConnectionFactory.getRequestRecorder().requestData().get(0), dataAre(DATA4.getData()));
166 |
167 | }
168 | @Test
169 | public void testWithPayloadMultiple() throws IOException
170 | {
171 | StaticConnectionFactory.expectCall()
172 | .andWhenRequest(withData(DATA4.getData())).thenReturn(DATA1).thenReturn(DATA3)
173 | .andWhenRequest(withData(DATA3.getData())).thenReturn(DATA2);
174 |
175 | checkConnection(ADDRESS1,DATA1, DATA4);
176 | checkConnection(ADDRESS1,DATA2, DATA3);
177 | checkConnection(ADDRESS1,DATA3, DATA4);
178 |
179 | assertThat(StaticConnectionFactory.getRequestRecorder().requestData().get(0), dataAre(DATA4.getData()));
180 |
181 | }
182 | @Test
183 | public void testUnexpected() throws IOException
184 | {
185 | StaticConnectionFactory.expectCall()
186 | .andWhenRequest(withData(DATA4.getData())).thenReturn(DATA1);
187 | checkConnection(ADDRESS1,DATA1, DATA4);
188 | Connection connection = connectionFactory.createConnection(ADDRESS1);
189 | IOUtils.copy(DATA3.getData(), connection.getOutputStream());
190 | try
191 | {
192 | connection.getInputStream().read();
193 | fail("Exception expected");
194 | }
195 | catch(MockSocketException e)
196 | {
197 | assertEquals("No matcher matches request [3, 3, 3, 3]. Do not know which response to return.", e.getMessage());
198 | }
199 | }
200 | @Test
201 | public void testUnexpectedMultiple() throws IOException
202 | {
203 | StaticConnectionFactory.expectCall().andWhenRequest(withData(DATA4.getData())).thenReturn(DATA1);
204 | checkConnection(ADDRESS1,DATA1, DATA4);
205 | Connection connection = connectionFactory.createConnection(ADDRESS1);
206 | IOUtils.copy(DATA4.getData(), connection.getOutputStream());
207 | try
208 | {
209 | connection.getInputStream().read();
210 | fail("Exception expected");
211 | }
212 | catch(MockSocketException e)
213 | {
214 | assertTrue(e.getMessage().startsWith("No more connections expected for request matching matcher: "));
215 | }
216 | }
217 |
218 | private void checkConnection(String address, SocketData outData) throws IOException {
219 | checkConnection(address, outData, null);
220 | }
221 | private void checkConnection(String address, SocketData outData, SocketData inData) throws IOException {
222 | Connection connection = connectionFactory.createConnection(address);
223 | assertNotNull(connection);
224 | if (inData!=null)
225 | {
226 | IOUtils.copy(inData.getData(), connection.getOutputStream());
227 | }
228 | byte[] actualOutData = IOUtils.toByteArray(connection.getInputStream());
229 | assertThat(actualOutData, is(IOUtils.toByteArray(outData.getData())));
230 | }
231 | }
232 |
--------------------------------------------------------------------------------
/header.txt:
--------------------------------------------------------------------------------
1 | Copyright 2009-2011 the original author or authors.
2 |
3 | Licensed under the Apache License, Version 2.0 (the "License");
4 | you may not use this file except in compliance with the License.
5 | You may obtain a copy of the License at
6 |
7 | http://www.apache.org/licenses/LICENSE-2.0
8 |
9 | Unless required by applicable law or agreed to in writing, software
10 | distributed under the License is distributed on an "AS IS" BASIS,
11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 | See the License for the specific language governing permissions and
13 | limitations under the License.
14 |
--------------------------------------------------------------------------------
/http/pom.xml:
--------------------------------------------------------------------------------
1 |
2 | 4.0.0
3 |
4 |
5 | net.javacrumbs
6 | mock-socket-parent
7 | 0.9.1-SNAPSHOT
8 |
9 |
10 | net.javacrumbs
11 | mock-socket-http
12 | 0.9.1-SNAPSHOT
13 | mock-socket-http
14 |
15 |
16 |
17 | org.eclipse.jetty
18 | test-jetty-servlet
19 | 7.4.2.v20110526
20 |
21 |
22 | org.hamcrest
23 | hamcrest-core
24 | 1.2.1
25 |
26 |
27 | net.javacrumbs
28 | mock-socket-core
29 | 0.9.1-SNAPSHOT
30 |
31 |
32 | org.apache.httpcomponents
33 | httpclient
34 | 4.5.6
35 | test
36 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/http/src/main/java/net/javacrumbs/mocksocket/http/HttpGeneratorException.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2005-2010 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.javacrumbs.mocksocket.http;
18 |
19 | public class HttpGeneratorException extends RuntimeException {
20 |
21 | private static final long serialVersionUID = 8538152722978567179L;
22 |
23 |
24 | public HttpGeneratorException(String message) {
25 | super(message);
26 | }
27 |
28 | public HttpGeneratorException(Throwable cause) {
29 | super(cause);
30 | }
31 |
32 | public HttpGeneratorException(String message, Throwable cause) {
33 | super(message, cause);
34 | }
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/http/src/main/java/net/javacrumbs/mocksocket/http/HttpMockSocket.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2009-2011 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package net.javacrumbs.mocksocket.http;
17 |
18 | import net.javacrumbs.mocksocket.MockSocket;
19 | import net.javacrumbs.mocksocket.connection.data.RequestSocketData;
20 | import net.javacrumbs.mocksocket.http.matchers.ContentMatcher;
21 | import net.javacrumbs.mocksocket.http.matchers.HeaderMatcher;
22 | import net.javacrumbs.mocksocket.http.matchers.MethodMatcher;
23 | import net.javacrumbs.mocksocket.http.matchers.StatusMatcher;
24 | import net.javacrumbs.mocksocket.http.matchers.UriMatcher;
25 |
26 | import org.hamcrest.Matcher;
27 | import org.hamcrest.core.CombinableMatcher;
28 |
29 | public class HttpMockSocket extends MockSocket{
30 |
31 | protected HttpMockSocket()
32 | {
33 | }
34 |
35 | public static HttpResponseGenerator response()
36 | {
37 | return new HttpResponseGenerator();
38 | }
39 |
40 | public static HttpRequest request(int index)
41 | {
42 | return new HttpParser(recordedConnections().get(index));
43 | }
44 |
45 | public static CombinableMatcher status(Matcher statusMatcher) {
46 | return new CombinableMatcher(new StatusMatcher(statusMatcher));
47 | }
48 |
49 | public static CombinableMatcher header(String header, Matcher headerMatcher) {
50 | return new CombinableMatcher(new HeaderMatcher(header, headerMatcher));
51 | }
52 |
53 | public static CombinableMatcher content(Matcher contentMatcher) {
54 | return new CombinableMatcher(new ContentMatcher(contentMatcher));
55 | }
56 |
57 | public static CombinableMatcher method(Matcher methodMatcher) {
58 | return new CombinableMatcher(new MethodMatcher(methodMatcher));
59 | }
60 |
61 | public static CombinableMatcher uri(Matcher uriMatcher) {
62 | return new CombinableMatcher(new UriMatcher(uriMatcher));
63 | }
64 |
65 |
66 | }
67 |
--------------------------------------------------------------------------------
/http/src/main/java/net/javacrumbs/mocksocket/http/HttpParser.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2005-2010 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.javacrumbs.mocksocket.http;
18 |
19 | import java.io.IOException;
20 | import java.io.InputStream;
21 | import java.util.Collections;
22 | import java.util.List;
23 |
24 | import net.javacrumbs.mocksocket.connection.data.OutputSocketData;
25 | import net.javacrumbs.mocksocket.connection.data.SocketData;
26 | import net.javacrumbs.mocksocket.util.Utils;
27 |
28 | import org.eclipse.jetty.http.HttpHeaders;
29 | import org.eclipse.jetty.http.MimeTypes;
30 | import org.eclipse.jetty.io.Buffer;
31 | import org.eclipse.jetty.io.ByteArrayBuffer;
32 | import org.eclipse.jetty.io.View;
33 | import org.eclipse.jetty.testing.HttpTester;
34 | import org.eclipse.jetty.util.ByteArrayOutputStream2;
35 |
36 | public class HttpParser implements HttpRequest {
37 | private final HttpTester httpTester;
38 |
39 | private final SocketData socketData;
40 |
41 | public HttpParser(SocketData data) {
42 | httpTester = createTester(data.getData());
43 | this.socketData = data;
44 | }
45 |
46 | private HttpTester createTester(InputStream data) {
47 | ExtendedHttpTester httpTester = new ExtendedHttpTester();
48 | try {
49 | httpTester.parse(data);
50 | return httpTester;
51 | } catch (IOException e) {
52 | throw new IllegalArgumentException("Can not parse data",e);
53 | }
54 | }
55 |
56 | public String getMethod() {
57 | return httpTester.getMethod();
58 | }
59 |
60 | public String getReason() {
61 | return httpTester.getReason();
62 | }
63 |
64 | public int getStatus() {
65 | return httpTester.getStatus();
66 | }
67 |
68 | public String getURI() {
69 | return httpTester.getURI();
70 | }
71 |
72 | public String getVersion() {
73 | return httpTester.getVersion();
74 | }
75 |
76 | public String getContentType() {
77 | return httpTester.getContentType();
78 | }
79 |
80 | public String getCharacterEncoding() {
81 | return httpTester.getCharacterEncoding();
82 | }
83 |
84 | public long getDateHeader(String name) {
85 | return httpTester.getDateHeader(name);
86 | }
87 |
88 | @SuppressWarnings("unchecked")
89 | public List getHeaderNames() {
90 | return Collections.list(httpTester.getHeaderNames());
91 | }
92 |
93 | public long getLongHeader(String name) throws NumberFormatException {
94 | return httpTester.getLongHeader(name);
95 | }
96 |
97 | public String getHeader(String name) {
98 | return httpTester.getHeader(name);
99 | }
100 |
101 | @SuppressWarnings("unchecked")
102 | public List getHeaderValues(String name) {
103 | return Collections.list(httpTester.getHeaderValues(name));
104 | }
105 |
106 | public String getContent() {
107 | return httpTester.getContent();
108 | }
109 |
110 | public InputStream getData() {
111 | return socketData.getData();
112 | }
113 |
114 | /**
115 | * Returns address to which the request was sent to or null.
116 | */
117 | public String getAddress() {
118 | if (socketData instanceof OutputSocketData)
119 | {
120 | return ((OutputSocketData) socketData).getAddress();
121 | }
122 | else
123 | {
124 | return null;
125 | }
126 | }
127 | /**
128 | * HttpTester that can parse byte[].
129 | * @author Lukas Krecan
130 | *
131 | */
132 | private static class ExtendedHttpTester extends HttpTester
133 | {
134 | private String _charset;
135 |
136 |
137 | public String parse(InputStream data) throws IOException {
138 | Buffer buf = new ByteArrayBuffer(Utils.toByteArray(data));
139 | View view = new View(buf);
140 | org.eclipse.jetty.http.HttpParser parser = new org.eclipse.jetty.http.HttpParser(view,new PH());
141 | parser.parse();
142 | return getString(view.asArray());
143 | }
144 |
145 | private String getString(Buffer buffer)
146 | {
147 | return getString(buffer.asArray());
148 | }
149 |
150 | private String getString(byte[] b)
151 | {
152 | if(_charset==null)
153 | return new String(b);
154 | try
155 | {
156 | return new String(b, _charset);
157 | }
158 | catch(Exception e)
159 | {
160 | return new String(b);
161 | }
162 | }
163 | @Override
164 | public String getContentType() {
165 | return getString(_fields.get(HttpHeaders.CONTENT_TYPE_BUFFER));
166 | }
167 |
168 | public String getContent()
169 | {
170 | if (_parsedContent!=null)
171 | return getString(_parsedContent.toByteArray());
172 | if (_genContent!=null)
173 | return getString(_genContent);
174 | return null;
175 | }
176 |
177 | private class PH extends org.eclipse.jetty.http.HttpParser.EventHandler
178 | {
179 | public void startRequest(Buffer method, Buffer url, Buffer version) throws IOException
180 | {
181 | reset();
182 | _method=getString(method);
183 | _uri=getString(url);
184 | _version=getString(version);
185 | }
186 |
187 | public void startResponse(Buffer version, int status, Buffer reason) throws IOException
188 | {
189 | reset();
190 | _version=getString(version);
191 | _status=status;
192 | _reason=getString(reason);
193 | }
194 |
195 | public void parsedHeader(Buffer name, Buffer value) throws IOException
196 | {
197 | _fields.add(name,value);
198 | }
199 |
200 | public void headerComplete() throws IOException
201 | {
202 | Buffer contentType = _fields.get(HttpHeaders.CONTENT_TYPE_BUFFER);
203 | if(contentType!=null)
204 | {
205 | String charset = MimeTypes.getCharsetFromContentType(contentType);
206 | if(charset!=null)
207 | {
208 | _charset = charset;
209 | }
210 | }
211 | }
212 |
213 | public void messageComplete(long contextLength) throws IOException
214 | {
215 | }
216 |
217 | public void content(Buffer ref) throws IOException
218 | {
219 | if (_parsedContent==null)
220 | _parsedContent=new ByteArrayOutputStream2();
221 | _parsedContent.write(ref.asArray());
222 | }
223 | }
224 |
225 | }
226 |
227 | }
228 |
--------------------------------------------------------------------------------
/http/src/main/java/net/javacrumbs/mocksocket/http/HttpRequest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2005-2010 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.javacrumbs.mocksocket.http;
18 |
19 | import java.util.List;
20 |
21 | import net.javacrumbs.mocksocket.connection.data.SocketData;
22 |
23 | /**
24 | * HTTP request wrapper.
25 | * @author Lukas Krecan
26 | *
27 | */
28 | public interface HttpRequest extends SocketData{
29 |
30 | public abstract String getMethod();
31 |
32 | public abstract String getAddress();
33 |
34 | public abstract String getURI();
35 |
36 | public abstract String getVersion();
37 |
38 | public abstract String getContentType();
39 |
40 | public abstract String getCharacterEncoding();
41 |
42 | public abstract long getDateHeader(String name);
43 |
44 | public abstract List getHeaderNames();
45 |
46 | public abstract long getLongHeader(String name) throws NumberFormatException;
47 |
48 | public abstract String getHeader(String name);
49 |
50 | public abstract List getHeaderValues(String name);
51 |
52 | public abstract String getContent();
53 | }
--------------------------------------------------------------------------------
/http/src/main/java/net/javacrumbs/mocksocket/http/HttpResponseGenerator.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2005-2010 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.javacrumbs.mocksocket.http;
18 |
19 | import java.io.ByteArrayInputStream;
20 | import java.io.ByteArrayOutputStream;
21 | import java.io.IOException;
22 | import java.io.InputStream;
23 | import java.util.Date;
24 |
25 | import net.javacrumbs.mocksocket.connection.data.SocketData;
26 |
27 | import org.eclipse.jetty.http.HttpFields;
28 | import org.eclipse.jetty.http.HttpHeaders;
29 | import org.eclipse.jetty.http.HttpStatus;
30 | import org.eclipse.jetty.http.MimeTypes;
31 | import org.eclipse.jetty.io.Buffer;
32 | import org.eclipse.jetty.io.ByteArrayBuffer;
33 | import org.eclipse.jetty.io.SimpleBuffers;
34 | import org.eclipse.jetty.io.bio.StreamEndPoint;
35 |
36 | /**
37 | * Genrates HTTP response.
38 | * @author Lukas Krecan
39 | *
40 | */
41 | public class HttpResponseGenerator implements SocketData{
42 | private static final String DEFAULT_ENCODING = "UTF-8";
43 |
44 | private final HttpFields httpFields = new HttpFields();
45 | private int status = 200;
46 | private String content = "";
47 |
48 |
49 | public HttpResponseGenerator withStatus(int status) {
50 | this.status = status;
51 | return this;
52 | }
53 |
54 | public HttpResponseGenerator withContent(String content) {
55 | this.content = content;
56 | return this;
57 | }
58 |
59 | public HttpResponseGenerator withHeader(String name, String value) {
60 | httpFields.add(name, value);
61 | return this;
62 | }
63 |
64 | public HttpResponseGenerator withDateHeader(String name, Date value) {
65 | httpFields.addDateField(name, value.getTime());
66 | return this;
67 | }
68 |
69 | public byte[] generate() {
70 | try {
71 | String charset = getCharset();
72 | byte[] byteContent = content.getBytes(charset);
73 | Buffer bb=new ByteArrayBuffer(32*1024 + byteContent.length);
74 | Buffer sb=new ByteArrayBuffer(4*1024);
75 | ByteArrayOutputStream out = new ByteArrayOutputStream();
76 | StreamEndPoint endpoint = new StreamEndPoint(new ByteArrayInputStream(new byte[0]), out);
77 | org.eclipse.jetty.http.HttpGenerator generator = new org.eclipse.jetty.http.HttpGenerator(new SimpleBuffers(sb,bb),endpoint);
78 | generator.setResponse(status, HttpStatus.getMessage(status));
79 | generator.addContent(new ByteArrayBuffer(byteContent), true);
80 | generator.completeHeader(httpFields, true);
81 | generator.complete();
82 | generator.flushBuffer();
83 | return out.toByteArray();
84 | } catch (IOException e) {
85 | throw new HttpGeneratorException(e);
86 | }
87 | }
88 |
89 | public InputStream getData() {
90 | return new ByteArrayInputStream(generate());
91 | }
92 |
93 | private String getCharset() {
94 | Buffer contentType = httpFields.get(HttpHeaders.CONTENT_TYPE_BUFFER);
95 | if(contentType!=null)
96 | {
97 | String charset = MimeTypes.getCharsetFromContentType(contentType);
98 | if(charset!=null)
99 | {
100 | return charset;
101 | }
102 | }
103 | return DEFAULT_ENCODING;
104 | }
105 | }
106 |
--------------------------------------------------------------------------------
/http/src/main/java/net/javacrumbs/mocksocket/http/matchers/AbstractHttpMatcher.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2009-2011 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package net.javacrumbs.mocksocket.http.matchers;
17 |
18 | import net.javacrumbs.mocksocket.connection.data.SocketData;
19 | import net.javacrumbs.mocksocket.http.HttpParser;
20 |
21 | import org.hamcrest.BaseMatcher;
22 | import org.hamcrest.Description;
23 | import org.hamcrest.Matcher;
24 |
25 | public abstract class AbstractHttpMatcher extends BaseMatcher {
26 |
27 |
28 | private final Matcher> wrappedMatcher;
29 |
30 | public AbstractHttpMatcher(Matcher> wrappedMatcher) {
31 | this.wrappedMatcher = wrappedMatcher;
32 | }
33 |
34 | public boolean matches(Object item) {
35 | if (item instanceof SocketData) {
36 | return doMatch(createHttpParser((SocketData)item));
37 | }
38 | return false;
39 | }
40 |
41 | protected boolean doMatch(HttpParser tester) throws AssertionError {
42 | return wrappedMatcher.matches(getValue(tester));
43 | }
44 |
45 |
46 | protected Object describeValue(HttpParser httpTester) {
47 | return getValue(httpTester);
48 | }
49 |
50 | protected abstract Object getValue(HttpParser httpParser);
51 |
52 | public void describeMismatch(Object item, Description description) {
53 | description.appendText("was ").appendValue(describeValue(createHttpParser((SocketData)item)));
54 | }
55 |
56 |
57 | protected HttpParser createHttpParser(SocketData http) {
58 | HttpParser parser = new HttpParser(http);
59 | return parser;
60 |
61 | }
62 |
63 | protected Matcher> getWrappedMatcher() {
64 | return wrappedMatcher;
65 | }
66 |
67 |
68 | }
--------------------------------------------------------------------------------
/http/src/main/java/net/javacrumbs/mocksocket/http/matchers/ContentMatcher.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2009-2011 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package net.javacrumbs.mocksocket.http.matchers;
17 |
18 | import net.javacrumbs.mocksocket.http.HttpParser;
19 |
20 | import org.hamcrest.Description;
21 | import org.hamcrest.Matcher;
22 |
23 | public class ContentMatcher extends AbstractHttpMatcher {
24 |
25 | public ContentMatcher(Matcher wrappedMatcher) {
26 | super(wrappedMatcher);
27 | }
28 | @Override
29 | protected Object getValue(HttpParser httpParser) {
30 | return httpParser.getContent();
31 | }
32 |
33 | public void describeTo(Description description) {
34 | description.appendText("content ").appendDescriptionOf(getWrappedMatcher());
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/http/src/main/java/net/javacrumbs/mocksocket/http/matchers/ContentTypeMatcher.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2009-2011 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package net.javacrumbs.mocksocket.http.matchers;
17 |
18 | import net.javacrumbs.mocksocket.http.HttpParser;
19 |
20 | import org.hamcrest.Description;
21 | import org.hamcrest.Matcher;
22 |
23 | public class ContentTypeMatcher extends AbstractHttpMatcher {
24 |
25 | public ContentTypeMatcher(Matcher wrappedMatcher) {
26 | super(wrappedMatcher);
27 | }
28 |
29 | @Override
30 | protected Object getValue(HttpParser httpParser) {
31 | return httpParser.getContentType();
32 | }
33 |
34 | public void describeTo(Description description) {
35 | description.appendText("contentType ").appendDescriptionOf(getWrappedMatcher());
36 | }
37 |
38 | }
39 |
--------------------------------------------------------------------------------
/http/src/main/java/net/javacrumbs/mocksocket/http/matchers/HeaderMatcher.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2009-2011 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package net.javacrumbs.mocksocket.http.matchers;
17 |
18 | import net.javacrumbs.mocksocket.http.HttpParser;
19 |
20 | import org.hamcrest.Description;
21 | import org.hamcrest.Matcher;
22 |
23 | public class HeaderMatcher extends AbstractHttpMatcher {
24 |
25 | private final String header;
26 |
27 | public HeaderMatcher(String header, Matcher wrappedMatcher) {
28 | super(wrappedMatcher);
29 | this.header = header;
30 | }
31 |
32 | @Override
33 | protected Object getValue(HttpParser httpParser) {
34 | return httpParser.getHeader(header);
35 | }
36 |
37 | public void describeTo(Description description) {
38 | description.appendText("header "+header+" ").appendDescriptionOf(getWrappedMatcher());
39 | }
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/http/src/main/java/net/javacrumbs/mocksocket/http/matchers/MethodMatcher.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2009-2011 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package net.javacrumbs.mocksocket.http.matchers;
17 |
18 | import net.javacrumbs.mocksocket.http.HttpParser;
19 |
20 | import org.hamcrest.Description;
21 | import org.hamcrest.Matcher;
22 |
23 | public class MethodMatcher extends AbstractHttpMatcher {
24 |
25 | public MethodMatcher(Matcher wrappedMatcher) {
26 | super(wrappedMatcher);
27 | }
28 |
29 | @Override
30 | protected Object getValue(HttpParser httpParser) {
31 | return httpParser.getMethod();
32 | }
33 |
34 |
35 | public void describeTo(Description description) {
36 | description.appendText("method ").appendDescriptionOf(getWrappedMatcher());
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/http/src/main/java/net/javacrumbs/mocksocket/http/matchers/StatusMatcher.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2009-2011 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package net.javacrumbs.mocksocket.http.matchers;
17 |
18 | import net.javacrumbs.mocksocket.http.HttpParser;
19 |
20 | import org.hamcrest.Description;
21 | import org.hamcrest.Matcher;
22 |
23 | public class StatusMatcher extends AbstractHttpMatcher {
24 |
25 | public StatusMatcher(Matcher wrappedMatcher) {
26 | super(wrappedMatcher);
27 | }
28 |
29 | @Override
30 | protected Object getValue(HttpParser httpParser) {
31 | return httpParser.getStatus();
32 | }
33 |
34 |
35 | public void describeTo(Description description) {
36 | description.appendText("status ").appendDescriptionOf(getWrappedMatcher());
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/http/src/main/java/net/javacrumbs/mocksocket/http/matchers/UriMatcher.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2009-2011 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package net.javacrumbs.mocksocket.http.matchers;
17 |
18 | import net.javacrumbs.mocksocket.http.HttpParser;
19 |
20 | import org.hamcrest.Description;
21 | import org.hamcrest.Matcher;
22 |
23 | public class UriMatcher extends AbstractHttpMatcher {
24 |
25 | public UriMatcher(Matcher wrappedMatcher) {
26 | super(wrappedMatcher);
27 | }
28 |
29 | @Override
30 | protected Object getValue(HttpParser httpParser) {
31 | return httpParser.getURI();
32 | }
33 |
34 |
35 | public void describeTo(Description description) {
36 | description.appendText("uri ").appendDescriptionOf(getWrappedMatcher());
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/http/src/test/java/net/javacrumbs/mocksocket/http/HttpMatchersTest.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2009-2011 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package net.javacrumbs.mocksocket.http;
17 |
18 | import static net.javacrumbs.mocksocket.http.HttpMockSocket.content;
19 | import static net.javacrumbs.mocksocket.http.HttpMockSocket.header;
20 | import static net.javacrumbs.mocksocket.http.HttpMockSocket.status;
21 | import static org.hamcrest.CoreMatchers.is;
22 | import static org.hamcrest.MatcherAssert.assertThat;
23 |
24 | import java.io.ByteArrayInputStream;
25 | import java.io.InputStream;
26 |
27 | import net.javacrumbs.mocksocket.connection.data.RequestSocketData;
28 |
29 | import org.junit.Test;
30 |
31 |
32 | public class HttpMatchersTest {
33 | private static final RequestSocketData REQUEST = new RequestSocketData() {
34 |
35 | public InputStream getData() {
36 | return new ByteArrayInputStream("HTTP/1.0 200 OK\nLast-Modified: Wed, 10 Mar 2010 19:11:49 GMT\n\nTest".getBytes());
37 | }
38 |
39 | public String getAddress() {
40 | return "localhost:1111";
41 | }
42 | };
43 |
44 | @Test
45 | public void testMatchStatus()
46 | {
47 | assertThat(REQUEST, status(is(200)));
48 | }
49 | @Test(expected=AssertionError.class)
50 | public void testDoNotMatchStatus()
51 | {
52 | assertThat(REQUEST, status(is(300)));
53 | }
54 | @Test
55 | public void testMatchHeader()
56 | {
57 | assertThat(REQUEST, header("Last-Modified", is("Wed, 10 Mar 2010 19:11:49 GMT")));
58 | }
59 | @Test(expected=AssertionError.class)
60 | public void testDoMatchHeader()
61 | {
62 | assertThat(REQUEST, header("Last-Modified", is("Tue, 10 Mar 2010 19:11:49 GMT")));
63 | }
64 | @Test(expected=AssertionError.class)
65 | public void testDoMatchHeaderNotPresent()
66 | {
67 | assertThat(REQUEST, header("Expires", is("Tue, 10 Mar 2010 19:11:49 GMT")));
68 | }
69 | @Test
70 | public void testMatchContent()
71 | {
72 | assertThat(REQUEST, content(is("Test")));
73 | }
74 | @Test(expected=AssertionError.class)
75 | public void testDoMatchContent()
76 | {
77 | assertThat(REQUEST, content(is("Test2")));
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/http/src/test/java/net/javacrumbs/mocksocket/http/HttpParserTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2005-2010 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.javacrumbs.mocksocket.http;
18 |
19 | import static org.junit.Assert.assertEquals;
20 | import net.javacrumbs.mocksocket.connection.data.DefaultSocketData;
21 |
22 | import org.junit.Test;
23 |
24 |
25 | public class HttpParserTest {
26 |
27 | @Test
28 | public void testCharset() throws Exception
29 | {
30 | String data = "GET http://localhost HTTP/1.1\n" +
31 | "Content-type: text/plain;charset=ISO-8859-2\n" +
32 | "Content-Length: 9\n" +
33 | "\n" +
34 | "ěščřžýáíé";
35 | HttpRequest parser = new HttpParser(new DefaultSocketData(data.getBytes("ISO-8859-2")));
36 | assertEquals("ěščřžýáíé", parser.getContent());
37 | }
38 | }
39 |
--------------------------------------------------------------------------------
/http/src/test/java/net/javacrumbs/mocksocket/http/HttpResponseGeneratorTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2005-2010 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 |
17 | package net.javacrumbs.mocksocket.http;
18 |
19 | import static org.junit.Assert.assertEquals;
20 |
21 | import java.io.UnsupportedEncodingException;
22 | import java.util.Date;
23 |
24 | import org.junit.Test;
25 |
26 |
27 | public class HttpResponseGeneratorTest {
28 |
29 | @Test
30 | public void testGenerateResponse()
31 | {
32 | HttpResponseGenerator generator = new HttpResponseGenerator();
33 | generator
34 | .withStatus(200)
35 | .withContent("Some not interesting content")
36 | .withHeader("Content-type","text/plain")
37 | .withDateHeader("Expires", new Date(1308384530297L));
38 | String response = new String(generator.generate());
39 | assertEquals("HTTP/1.1 200 OK\r\n" +
40 | "Content-type: text/plain\r\n" +
41 | "Expires: Sat, 18 Jun 2011 08:08:50 GMT\r\n" +
42 | "Content-Length: 28\r\n" +
43 | "\r\n" +
44 | "Some not interesting content", response);
45 | }
46 | @Test
47 | public void testGenerateEncoding() throws UnsupportedEncodingException
48 | {
49 | HttpResponseGenerator generator = new HttpResponseGenerator();
50 | generator
51 | .withStatus(200)
52 | .withContent("ěščřžýáíé")
53 | .withHeader("Content-type","text/plain;charset=utf-8")
54 | .withDateHeader("Expires", new Date(1308384530297L));
55 | String response = new String(generator.generate(),"UTF-8");
56 | assertEquals("HTTP/1.1 200 OK\r\n" +
57 | "Content-type: text/plain;charset=utf-8\r\n" +
58 | "Expires: Sat, 18 Jun 2011 08:08:50 GMT\r\n" +
59 | "Content-Length: 18\r\n" +
60 | "\r\n" +
61 | "ěščřžýáíé", response);
62 | }
63 | @Test
64 | public void testGenerateEncoding2() throws UnsupportedEncodingException
65 | {
66 | HttpResponseGenerator generator = new HttpResponseGenerator();
67 | generator
68 | .withStatus(200)
69 | .withContent("ěščřžýáíé")
70 | .withHeader("Content-type","text/plain;charset=iso-8859-2")
71 | .withDateHeader("Expires", new Date(1308384530297L));
72 | String response = new String(generator.generate(),"iso-8859-2");
73 | assertEquals("HTTP/1.1 200 OK\r\n" +
74 | "Content-type: text/plain;charset=iso-8859-2\r\n" +
75 | "Expires: Sat, 18 Jun 2011 08:08:50 GMT\r\n" +
76 | "Content-Length: 9\r\n" +
77 | "\r\n" +
78 | "ěščřžýáíé", response);
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/http/src/test/java/net/javacrumbs/mocksocket/http/SampleTest.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright 2009-2011 the original author or authors.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package net.javacrumbs.mocksocket.http;
17 |
18 | import static net.javacrumbs.mocksocket.MockSocket.address;
19 | import static net.javacrumbs.mocksocket.MockSocket.recordedConnections;
20 | import static net.javacrumbs.mocksocket.http.HttpMockSocket.expectCall;
21 | import static net.javacrumbs.mocksocket.http.HttpMockSocket.header;
22 | import static net.javacrumbs.mocksocket.http.HttpMockSocket.method;
23 | import static net.javacrumbs.mocksocket.http.HttpMockSocket.request;
24 | import static net.javacrumbs.mocksocket.http.HttpMockSocket.response;
25 | import static net.javacrumbs.mocksocket.http.HttpMockSocket.uri;
26 | import static org.hamcrest.CoreMatchers.is;
27 | import static org.hamcrest.MatcherAssert.assertThat;
28 | import static org.junit.matchers.JUnitMatchers.hasItem;
29 |
30 | import java.io.ByteArrayOutputStream;
31 | import java.io.IOException;
32 |
33 | import net.javacrumbs.mocksocket.MockSocketException;
34 |
35 | import org.apache.http.HttpResponse;
36 | import org.apache.http.client.ClientProtocolException;
37 | import org.apache.http.client.HttpClient;
38 | import org.apache.http.client.methods.HttpGet;
39 | import org.apache.http.client.methods.HttpPost;
40 | import org.apache.http.impl.client.DefaultHttpClient;
41 | import org.junit.After;
42 | import org.junit.Test;
43 |
44 | public class SampleTest {
45 | private static final String ADDRESS = "http://localhost/";
46 |
47 | @After
48 | public void reset()
49 | {
50 | HttpMockSocket.reset();
51 | }
52 |
53 | @Test
54 | public void testHttpClientMethod() throws ClientProtocolException, IOException {
55 | expectCall()
56 | .andWhenRequest(method(is("POST")).and(address(is("localhost:80")))).thenReturn(response().withStatus(404))
57 | .andWhenRequest(method(is("GET"))).thenReturn(response().withStatus(200).withContent("Text"));
58 |
59 | HttpClient httpclient = new DefaultHttpClient();
60 |
61 | HttpGet httpget = new HttpGet(ADDRESS);
62 | httpget.addHeader("Accept","text/plain");
63 | HttpResponse getResponse = httpclient.execute(httpget);
64 | assertThat(getResponse.getStatusLine().getStatusCode(), is(200));
65 |
66 | assertThat(recordedConnections(), hasItem(header("Accept", is("text/plain"))));
67 | assertThat(recordedConnections().get(0), method(is("GET")));
68 | assertThat(request(0).getMethod(), is("GET"));
69 | assertThat(request(0).getAddress(), is("localhost:80"));
70 |
71 | ByteArrayOutputStream outstream = new ByteArrayOutputStream();
72 | getResponse.getEntity().writeTo(outstream);
73 | assertThat(new String(outstream.toByteArray()), is("Text"));
74 | httpget.abort();
75 |
76 | HttpPost httppost = new HttpPost(ADDRESS);
77 | HttpResponse postResponse = httpclient.execute(httppost);
78 | assertThat(postResponse.getStatusLine().getStatusCode(), is(404));
79 | httppost.abort();
80 | }
81 |
82 | @Test
83 | public void testHttpClientUri() throws ClientProtocolException, IOException {
84 | expectCall()
85 | .andWhenRequest(uri(is("/test/something.do"))).thenReturn(response().withStatus(404))
86 | .andWhenRequest(uri(is("/test/other.do"))).thenReturn(response().withContent("Text")).thenReturn(response().withContent("Text"));
87 |
88 | HttpClient httpclient = new DefaultHttpClient();
89 |
90 | doGet(httpclient);
91 | doGet(httpclient);
92 |
93 | HttpPost httppost = new HttpPost(ADDRESS+"test/something.do");
94 | HttpResponse postResponse = httpclient.execute(httppost);
95 | assertThat(postResponse.getStatusLine().getStatusCode(), is(404));
96 | httppost.abort();
97 | }
98 |
99 | private void doGet(HttpClient httpclient) throws IOException, ClientProtocolException {
100 | HttpGet httpget = new HttpGet(ADDRESS+"test/other.do");
101 | httpget.addHeader("Accept","text/plain");
102 | HttpResponse getResponse = httpclient.execute(httpget);
103 | assertThat(getResponse.getStatusLine().getStatusCode(), is(200));
104 |
105 | assertThat(recordedConnections(), hasItem(header("Accept", is("text/plain"))));
106 | assertThat(recordedConnections().get(0), method(is("GET")));
107 | assertThat(request(0).getMethod(), is("GET"));
108 | assertThat(request(0).getAddress(), is("localhost:80"));
109 |
110 | ByteArrayOutputStream outstream = new ByteArrayOutputStream();
111 | getResponse.getEntity().writeTo(outstream);
112 | assertThat(new String(outstream.toByteArray()), is("Text"));
113 | httpget.abort();
114 | }
115 |
116 | @Test(expected=MockSocketException.class)
117 | public void testSequentialError() throws ClientProtocolException, IOException {
118 | expectCall().andReturn(response().withStatus(200).withContent("Text"));
119 |
120 | HttpClient httpclient = new DefaultHttpClient();
121 |
122 | HttpGet httpget = new HttpGet(ADDRESS);
123 | httpget.addHeader("Accept","text/plain");
124 | HttpResponse getResponse = httpclient.execute(httpget);
125 | assertThat(getResponse.getStatusLine().getStatusCode(), is(200));
126 |
127 | assertThat(recordedConnections(), hasItem(header("Accept", is("text/plain"))));
128 | assertThat(recordedConnections().get(0), method(is("GET")));
129 | assertThat(request(0).getMethod(), is("GET"));
130 | assertThat(request(0).getAddress(), is("localhost:80"));
131 |
132 | ByteArrayOutputStream outstream = new ByteArrayOutputStream();
133 | getResponse.getEntity().writeTo(outstream);
134 | assertThat(new String(outstream.toByteArray()), is("Text"));
135 | httpget.abort();
136 |
137 | HttpPost httppost = new HttpPost(ADDRESS);
138 | httpclient.execute(httppost);
139 | }
140 | @Test
141 | public void testHttpClientSequential() throws ClientProtocolException, IOException {
142 | expectCall()
143 | .andReturn(response().withContent("Test"))
144 | .andReturn(response().withStatus(404));
145 |
146 | HttpClient httpclient = new DefaultHttpClient();
147 |
148 | HttpGet httpget = new HttpGet(ADDRESS);
149 | httpget.addHeader("Accept","text/plain");
150 | HttpResponse getResponse = httpclient.execute(httpget);
151 | assertThat(getResponse.getStatusLine().getStatusCode(), is(200));
152 |
153 | assertThat(recordedConnections(), hasItem(header("Accept", is("text/plain"))));
154 | httpget.abort();
155 |
156 | HttpPost httppost = new HttpPost(ADDRESS);
157 | HttpResponse postResponse = httpclient.execute(httppost);
158 | assertThat(postResponse.getStatusLine().getStatusCode(), is(404));
159 | httppost.abort();
160 | }
161 | }
162 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 | 4.0.0
3 |
4 | net.javacrumbs
5 | mock-socket-parent
6 | 0.9.1-SNAPSHOT
7 | pom
8 | mock-socket-parent
9 |
10 |
11 | org.sonatype.oss
12 | oss-parent
13 | 9
14 |
15 |
16 |
17 | core
18 | http
19 |
20 |
21 |
22 |
23 |
24 | lukas
25 | Lukas Krecan
26 | lukas@krecan.net
27 |
28 |
29 |
30 |
31 |
32 | junit
33 | junit
34 | 4.8.2
35 | test
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 | maven-compiler-plugin
44 | 2.3.2
45 |
46 | 1.7
47 | 1.7
48 |
49 |
50 |
51 | com.mycila.maven-license-plugin
52 | maven-license-plugin
53 | 1.9.0
54 |
55 |
56 |
57 | **/src/test/resources/**
58 | **/*.xml
59 | LICENSE.txt
60 |
61 |
62 |
63 |
64 |
65 | maven-release-plugin
66 |
67 | forked-path
68 |
69 |
70 |
71 | maven-eclipse-plugin
72 | 2.8
73 |
74 | true
75 |
76 | org.springframework.ide.eclipse.core.springnature
77 |
78 |
79 |
80 | org.springframework.ide.eclipse.core.springbuilder
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 | The Apache Software License, Version 2.0
91 | LICENSE.txt
92 |
93 |
94 |
95 |
96 | release-sign-artifacts
97 |
98 |
99 | performRelease
100 | true
101 |
102 |
103 |
104 |
105 |
106 | org.apache.maven.plugins
107 | maven-gpg-plugin
108 |
109 | 572516F4
110 |
111 | 1.0
112 |
113 |
114 | sign-artifacts
115 | verify
116 |
117 | sign
118 |
119 |
120 |
121 |
122 |
123 |
124 |
125 |
126 |
127 |
128 |
129 | org.apache.maven.plugins
130 | maven-jxr-plugin
131 | 2.2
132 |
133 |
134 | org.codehaus.mojo
135 | cobertura-maven-plugin
136 | 2.5.1
137 |
138 |
139 | org.codehaus.mojo
140 | findbugs-maven-plugin
141 | 2.3.2
142 |
143 |
144 |
145 |
146 |
147 | scm:git:git@github.com:lukas-krecan/mock-socket.git
148 | scm:git:git@github.com:lukas-krecan/mock-socket.git
149 | scm:git:git@github.com:lukas-krecan/mock-socket.git
150 |
151 |
152 |
153 |
154 | sonatype-nexus-staging
155 | Nexus Release Repository
156 | http://oss.sonatype.org/service/local/staging/deploy/maven2/
157 |
158 |
159 |
160 |
161 | sonatype-nexus-snapshots
162 | Sonatype Nexus Snapshots
163 | http://oss.sonatype.org/content/repositories/snapshots
164 |
165 |
166 |
167 |
--------------------------------------------------------------------------------