2 * Copyright (c) 2010-2021 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.webthing.internal.client;
15 import static org.mockito.ArgumentMatchers.argThat;
16 import static org.mockito.ArgumentMatchers.eq;
17 import static org.mockito.Mockito.mock;
18 import static org.mockito.Mockito.when;
20 import java.nio.ByteBuffer;
21 import java.nio.charset.StandardCharsets;
22 import java.util.concurrent.*;
24 import org.eclipse.jdt.annotation.NonNullByDefault;
25 import org.eclipse.jdt.annotation.Nullable;
26 import org.eclipse.jetty.client.api.ContentProvider;
27 import org.eclipse.jetty.client.api.ContentResponse;
28 import org.eclipse.jetty.client.api.Request;
33 * @author Gregor Roth - Initial contribution
38 public static Request mockRequest(@Nullable String requestContent, String responseContent) throws Exception {
39 return mockRequest(requestContent, responseContent, 200, 200);
42 public static Request mockRequest(@Nullable String requestContent, String responseContent, int getResponse,
43 int postResponse) throws Exception {
44 var request = mock(Request.class);
46 // GET request -> request.timeout(30, TimeUnit.SECONDS).send();
47 var getRequest = mock(Request.class);
48 var getContentResponse = mock(ContentResponse.class);
49 when(getContentResponse.getStatus()).thenReturn(getResponse);
50 when(getContentResponse.getContentAsString()).thenReturn(responseContent);
51 when(getRequest.send()).thenReturn(getContentResponse);
52 when(getRequest.accept("application/json")).thenReturn(getRequest);
53 when(request.timeout(30, TimeUnit.SECONDS)).thenReturn(getRequest);
55 // POST request -> request.method("PUT").content(new StringContentProvider(json)).timeout(30,
56 // TimeUnit.SECONDS).send();
57 if (requestContent != null) {
58 var postRequest = mock(Request.class);
59 when(postRequest.content(argThat((ContentProvider content) -> bufToString(content).equals(requestContent)),
60 eq("application/json"))).thenReturn(postRequest);
61 when(postRequest.timeout(30, TimeUnit.SECONDS)).thenReturn(postRequest);
63 var postContentResponse = mock(ContentResponse.class);
64 when(postContentResponse.getStatus()).thenReturn(postResponse);
65 when(postRequest.send()).thenReturn(postContentResponse);
66 when(request.method("PUT")).thenReturn(postRequest);
71 private static String bufToString(Iterable<ByteBuffer> data) {
73 for (var byteBuffer : data) {
74 result += StandardCharsets.UTF_8.decode(byteBuffer).toString();