2 * Copyright (c) 2010-2023 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.*;
16 import static org.mockito.Mockito.*;
18 import java.nio.ByteBuffer;
19 import java.nio.charset.StandardCharsets;
20 import java.util.concurrent.TimeUnit;
22 import org.eclipse.jdt.annotation.NonNullByDefault;
23 import org.eclipse.jdt.annotation.Nullable;
24 import org.eclipse.jetty.client.api.ContentProvider;
25 import org.eclipse.jetty.client.api.ContentResponse;
26 import org.eclipse.jetty.client.api.Request;
31 * @author Gregor Roth - Initial contribution
36 public static Request mockRequest(@Nullable String requestContent, String responseContent) throws Exception {
37 return mockRequest(requestContent, responseContent, 200, 200);
40 public static Request mockRequest(@Nullable String requestContent, String responseContent, int getResponse,
41 int postResponse) throws Exception {
42 var request = mock(Request.class);
44 // GET request -> request.timeout(30, TimeUnit.SECONDS).send();
45 var getRequest = mock(Request.class);
46 var getContentResponse = mock(ContentResponse.class);
47 when(getContentResponse.getStatus()).thenReturn(getResponse);
48 when(getContentResponse.getContentAsString()).thenReturn(responseContent);
49 when(getRequest.send()).thenReturn(getContentResponse);
50 when(getRequest.accept("application/json")).thenReturn(getRequest);
51 when(request.timeout(30, TimeUnit.SECONDS)).thenReturn(getRequest);
53 // POST request -> request.method("PUT").content(new StringContentProvider(json)).timeout(30,
54 // TimeUnit.SECONDS).send();
55 if (requestContent != null) {
56 var postRequest = mock(Request.class);
57 when(postRequest.content(argThat((ContentProvider content) -> bufToString(content).equals(requestContent)),
58 eq("application/json"))).thenReturn(postRequest);
59 when(postRequest.timeout(30, TimeUnit.SECONDS)).thenReturn(postRequest);
61 var postContentResponse = mock(ContentResponse.class);
62 when(postContentResponse.getStatus()).thenReturn(postResponse);
63 when(postRequest.send()).thenReturn(postContentResponse);
64 when(request.method("PUT")).thenReturn(postRequest);
69 private static String bufToString(Iterable<ByteBuffer> data) {
71 for (var byteBuffer : data) {
72 result += StandardCharsets.UTF_8.decode(byteBuffer).toString();