]> git.basschouten.com Git - openhab-addons.git/blob
5a62abdf8becb26e503cf456b467f236375e51bf
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.io.hueemulation.internal.rest;
14
15 import static org.mockito.ArgumentMatchers.*;
16 import static org.mockito.Mockito.when;
17
18 import java.io.IOException;
19 import java.net.InetSocketAddress;
20 import java.net.ServerSocket;
21 import java.net.URI;
22 import java.util.Collections;
23 import java.util.Dictionary;
24 import java.util.Hashtable;
25 import java.util.concurrent.ExecutionException;
26 import java.util.concurrent.ScheduledExecutorService;
27 import java.util.concurrent.TimeoutException;
28 import java.util.logging.Level;
29 import java.util.logging.Logger;
30
31 import org.eclipse.jetty.client.HttpClient;
32 import org.eclipse.jetty.client.api.ContentResponse;
33 import org.eclipse.jetty.client.util.StringContentProvider;
34 import org.eclipse.jetty.http.HttpHeader;
35 import org.eclipse.jetty.http.HttpMethod;
36 import org.glassfish.grizzly.http.server.HttpServer;
37 import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
38 import org.glassfish.jersey.logging.LoggingFeature;
39 import org.glassfish.jersey.logging.LoggingFeature.Verbosity;
40 import org.glassfish.jersey.server.ResourceConfig;
41 import org.mockito.Mock;
42 import org.mockito.Mockito;
43 import org.mockito.MockitoAnnotations;
44 import org.openhab.core.events.EventPublisher;
45 import org.openhab.core.items.MetadataRegistry;
46 import org.openhab.core.net.NetworkAddressService;
47 import org.openhab.core.storage.Storage;
48 import org.openhab.core.storage.StorageService;
49 import org.openhab.io.hueemulation.internal.ConfigStore;
50 import org.openhab.io.hueemulation.internal.rest.mocks.ConfigStoreWithoutMetadata;
51 import org.openhab.io.hueemulation.internal.rest.mocks.DummyMetadataRegistry;
52 import org.openhab.io.hueemulation.internal.rest.mocks.DummyUsersStorage;
53 import org.osgi.service.cm.ConfigurationAdmin;
54
55 /**
56  * We have no OSGi framework in the background. This class resolves
57  * dependencies between the different classes and mocks common services like the configAdmin.
58  * <p>
59  * The {@link UserManagement} rest components is always
60  * setup and started in this common test setup, because all other rest components require
61  * user authentication.
62  *
63  * @author David Graeff - Initial contribution
64  */
65 public class CommonSetup {
66
67     public String basePath;
68     public HttpClient client;
69     public ConfigStore cs;
70     public HttpServer server;
71
72     UserManagement userManagement;
73
74     AutoCloseable mocksCloseable;
75
76     @Mock
77     EventPublisher eventPublisher;
78
79     @Mock
80     ConfigurationAdmin configAdmin;
81
82     @Mock
83     ScheduledExecutorService scheduler;
84
85     @Mock
86     org.osgi.service.cm.Configuration configAdminConfig;
87
88     @Mock
89     NetworkAddressService networkAddressService;
90
91     MetadataRegistry metadataRegistry = new DummyMetadataRegistry();
92
93     StorageService storageService = new StorageService() {
94         @Override
95         public <T> Storage<T> getStorage(String name, ClassLoader classLoader) {
96             return getStorage(name);
97         }
98
99         @SuppressWarnings("unchecked")
100         @Override
101         public <T> Storage<T> getStorage(String name) {
102             if ("hueEmulationUsers".equals(name)) {
103                 return (Storage<T>) new DummyUsersStorage();
104             }
105             throw new IllegalStateException();
106         }
107     };
108
109     public CommonSetup(boolean withMetadata) throws IOException {
110         mocksCloseable = MockitoAnnotations.openMocks(this);
111
112         when(configAdmin.getConfiguration(anyString())).thenReturn(configAdminConfig);
113         when(configAdmin.getConfiguration(anyString(), any())).thenReturn(configAdminConfig);
114         Dictionary<String, Object> mockProperties = new Hashtable<>();
115         when(configAdminConfig.getProperties()).thenReturn(mockProperties);
116         when(networkAddressService.getPrimaryIpv4HostAddress()).thenReturn("127.0.0.1");
117
118         // If anything is scheduled, immediately run it instead
119         when(scheduler.schedule(any(Runnable.class), anyLong(), any())).thenAnswer(answer -> {
120             ((Runnable) answer.getArgument(0)).run();
121             return null;
122         });
123
124         if (withMetadata) {
125             cs = new ConfigStore(networkAddressService, configAdmin, metadataRegistry, scheduler);
126         } else {
127             cs = new ConfigStoreWithoutMetadata(networkAddressService, configAdmin, scheduler);
128         }
129         cs.activate(Collections.singletonMap("uuid", "a668dc9b-7172-49c3-832f-acb07dda2a20"));
130         cs.switchFilter = Collections.singleton("Switchable");
131         cs.whiteFilter = Collections.singleton("Switchable");
132         cs.colorFilter = Collections.singleton("ColorLighting");
133
134         userManagement = Mockito.spy(new UserManagement(storageService, cs));
135
136         try (ServerSocket serverSocket = new ServerSocket()) {
137             serverSocket.bind(new InetSocketAddress(0));
138             basePath = "http://localhost:" + serverSocket.getLocalPort() + "/api";
139         }
140     }
141
142     /**
143      * Start the http server to serve all registered jax-rs resources. Also setup a client for testing, see
144      * {@link #client}.
145      *
146      * @param rc A resource config. Add objects and object instance resources to your needs. Example:
147      *            "new ResourceConfig().registerInstances(configurationAccess)"
148      */
149     public void start(ResourceConfig resourceConfig) {
150         ResourceConfig rc = resourceConfig.registerInstances(userManagement).register(new LoggingFeature(
151                 Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME), Level.OFF, Verbosity.HEADERS_ONLY, 10));
152
153         Logger log2 = Logger.getLogger("org.glassfish");
154         log2.setLevel(Level.OFF);
155
156         server = GrizzlyHttpServerFactory.createHttpServer(URI.create(basePath), rc);
157         client = new HttpClient();
158         try {
159             client.start();
160         } catch (Exception e) {
161             throw new IllegalStateException("Failed to start HttpClient", e);
162         }
163     }
164
165     public void dispose() throws Exception {
166         if (client != null) {
167             client.stop();
168         }
169         if (server != null) {
170             server.shutdownNow();
171         }
172
173         mocksCloseable.close();
174     }
175
176     public ContentResponse sendDelete(String path) throws InterruptedException, TimeoutException, ExecutionException {
177         return client.newRequest(basePath + path).method(HttpMethod.DELETE).send();
178     }
179
180     public ContentResponse sendGet() throws InterruptedException, TimeoutException, ExecutionException {
181         return client.newRequest(basePath).method(HttpMethod.GET).send();
182     }
183
184     public ContentResponse sendGet(String path) throws InterruptedException, TimeoutException, ExecutionException {
185         return client.newRequest(basePath + path).method(HttpMethod.GET).send();
186     }
187
188     public ContentResponse sendPost(String content) throws InterruptedException, TimeoutException, ExecutionException {
189         return client.newRequest(basePath).method(HttpMethod.POST).header(HttpHeader.CONTENT_TYPE, "application/json")
190                 .content(new StringContentProvider(content)).send();
191     }
192
193     public ContentResponse sendPost(String path, String content)
194             throws InterruptedException, TimeoutException, ExecutionException {
195         return client.newRequest(basePath + path).method(HttpMethod.POST)
196                 .header(HttpHeader.CONTENT_TYPE, "application/json").content(new StringContentProvider(content)).send();
197     }
198
199     public ContentResponse sendPut(String path, String content)
200             throws InterruptedException, TimeoutException, ExecutionException {
201         return client.newRequest(basePath + path).method(HttpMethod.PUT)
202                 .header(HttpHeader.CONTENT_TYPE, "application/json").content(new StringContentProvider(content)).send();
203     }
204 }