2 * Copyright (c) 2010-2020 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.io.hueemulation.internal.rest;
15 import static org.mockito.ArgumentMatchers.*;
16 import static org.mockito.Mockito.when;
18 import java.io.IOException;
19 import java.net.InetSocketAddress;
20 import java.net.ServerSocket;
22 import java.util.Collections;
23 import java.util.Dictionary;
24 import java.util.Hashtable;
25 import java.util.concurrent.ScheduledExecutorService;
26 import java.util.logging.Level;
27 import java.util.logging.Logger;
29 import javax.ws.rs.client.Client;
30 import javax.ws.rs.client.ClientBuilder;
32 import org.glassfish.grizzly.http.server.HttpServer;
33 import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
34 import org.glassfish.jersey.logging.LoggingFeature;
35 import org.glassfish.jersey.logging.LoggingFeature.Verbosity;
36 import org.glassfish.jersey.server.ResourceConfig;
37 import org.junit.jupiter.api.extension.ExtendWith;
38 import org.mockito.Mock;
39 import org.mockito.Mockito;
40 import org.mockito.junit.jupiter.MockitoExtension;
41 import org.mockito.junit.jupiter.MockitoSettings;
42 import org.mockito.quality.Strictness;
43 import org.openhab.core.events.EventPublisher;
44 import org.openhab.core.items.MetadataRegistry;
45 import org.openhab.core.net.NetworkAddressService;
46 import org.openhab.core.storage.Storage;
47 import org.openhab.core.storage.StorageService;
48 import org.openhab.io.hueemulation.internal.ConfigStore;
49 import org.openhab.io.hueemulation.internal.rest.mocks.ConfigStoreWithoutMetadata;
50 import org.openhab.io.hueemulation.internal.rest.mocks.DummyMetadataRegistry;
51 import org.openhab.io.hueemulation.internal.rest.mocks.DummyUsersStorage;
52 import org.osgi.service.cm.ConfigurationAdmin;
55 * We have no OSGi framework in the background. This class resolves
56 * dependencies between the different classes and mocks common services like the configAdmin.
58 * The {@link UserManagement} rest components is always
59 * setup and started in this common test setup, because all other rest components require
60 * user authentication.
62 * @author David Graeff - Initial contribution
64 @ExtendWith(MockitoExtension.class)
65 @MockitoSettings(strictness = Strictness.WARN)
66 public class CommonSetup {
68 public UserManagement userManagement;
70 public @Mock EventPublisher eventPublisher;
72 public ConfigStore cs;
75 ConfigurationAdmin configAdmin;
78 ScheduledExecutorService scheduler;
81 org.osgi.service.cm.Configuration configAdminConfig;
84 NetworkAddressService networkAddressService;
86 MetadataRegistry metadataRegistry = new DummyMetadataRegistry();
88 StorageService storageService = new StorageService() {
90 public <T> Storage<T> getStorage(String name, ClassLoader classLoader) {
91 return getStorage(name);
94 @SuppressWarnings("unchecked")
96 public <T> Storage<T> getStorage(String name) {
97 if (name.equals("hueEmulationUsers")) {
98 return (Storage<T>) new DummyUsersStorage();
100 throw new IllegalStateException();
104 public Client client;
105 public HttpServer server;
106 public String basePath;
108 public CommonSetup(boolean withMetadata) throws IOException {
109 when(configAdmin.getConfiguration(anyString())).thenReturn(configAdminConfig);
110 when(configAdmin.getConfiguration(anyString(), any())).thenReturn(configAdminConfig);
111 Dictionary<String, Object> mockProperties = new Hashtable<>();
112 when(configAdminConfig.getProperties()).thenReturn(mockProperties);
113 when(networkAddressService.getPrimaryIpv4HostAddress()).thenReturn("127.0.0.1");
115 // If anything is scheduled, immediately run it instead
116 when(scheduler.schedule(any(Runnable.class), anyLong(), any())).thenAnswer(answer -> {
117 ((Runnable) answer.getArgument(0)).run();
122 cs = new ConfigStore(networkAddressService, configAdmin, metadataRegistry, scheduler);
124 cs = new ConfigStoreWithoutMetadata(networkAddressService, configAdmin, scheduler);
126 cs.activate(Collections.singletonMap("uuid", "demouuid"));
127 cs.switchFilter = Collections.singleton("Switchable");
128 cs.whiteFilter = Collections.singleton("Switchable");
129 cs.colorFilter = Collections.singleton("ColorLighting");
131 userManagement = Mockito.spy(new UserManagement(storageService, cs));
133 try (ServerSocket serverSocket = new ServerSocket()) {
134 serverSocket.bind(new InetSocketAddress(0));
135 basePath = "http://localhost:" + serverSocket.getLocalPort() + "/api";
140 * Start the http server to serve all registered jax-rs resources. Also setup a client for testing, see
143 * @param rc A resource config. Add objects and object instance resources to your needs. Example:
144 * "new ResourceConfig().registerInstances(configurationAccess)"
146 public void start(ResourceConfig resourceConfig) {
147 ResourceConfig rc = resourceConfig.registerInstances(userManagement).register(new LoggingFeature(
148 Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME), Level.OFF, Verbosity.HEADERS_ONLY, 10));
150 Logger log2 = Logger.getLogger("org.glassfish");
151 log2.setLevel(Level.OFF);
153 server = GrizzlyHttpServerFactory.createHttpServer(URI.create(basePath), rc);
154 client = ClientBuilder.newClient();
157 public void dispose() {
158 if (client != null) {
161 if (server != null) {
162 server.shutdownNow();