]> git.basschouten.com Git - openhab-addons.git/blob
761749291d8bf7820b8fd076091663b3d0a275c6
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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.ScheduledExecutorService;
26 import java.util.logging.Level;
27 import java.util.logging.Logger;
28
29 import javax.ws.rs.client.Client;
30 import javax.ws.rs.client.ClientBuilder;
31
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;
53
54 /**
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.
57  * <p>
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.
61  *
62  * @author David Graeff - Initial contribution
63  */
64 @ExtendWith(MockitoExtension.class)
65 @MockitoSettings(strictness = Strictness.WARN)
66 public class CommonSetup {
67
68     public UserManagement userManagement;
69
70     public @Mock EventPublisher eventPublisher;
71
72     public ConfigStore cs;
73
74     @Mock
75     ConfigurationAdmin configAdmin;
76
77     @Mock
78     ScheduledExecutorService scheduler;
79
80     @Mock
81     org.osgi.service.cm.Configuration configAdminConfig;
82
83     @Mock
84     NetworkAddressService networkAddressService;
85
86     MetadataRegistry metadataRegistry = new DummyMetadataRegistry();
87
88     StorageService storageService = new StorageService() {
89         @Override
90         public <T> Storage<T> getStorage(String name, ClassLoader classLoader) {
91             return getStorage(name);
92         }
93
94         @SuppressWarnings("unchecked")
95         @Override
96         public <T> Storage<T> getStorage(String name) {
97             if (name.equals("hueEmulationUsers")) {
98                 return (Storage<T>) new DummyUsersStorage();
99             }
100             throw new IllegalStateException();
101         }
102     };
103
104     public Client client;
105     public HttpServer server;
106     public String basePath;
107
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");
114
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();
118             return null;
119         });
120
121         if (withMetadata) {
122             cs = new ConfigStore(networkAddressService, configAdmin, metadataRegistry, scheduler);
123         } else {
124             cs = new ConfigStoreWithoutMetadata(networkAddressService, configAdmin, scheduler);
125         }
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");
130
131         userManagement = Mockito.spy(new UserManagement(storageService, cs));
132
133         try (ServerSocket serverSocket = new ServerSocket()) {
134             serverSocket.bind(new InetSocketAddress(0));
135             basePath = "http://localhost:" + serverSocket.getLocalPort() + "/api";
136         }
137     }
138
139     /**
140      * Start the http server to serve all registered jax-rs resources. Also setup a client for testing, see
141      * {@link #client}.
142      *
143      * @param rc A resource config. Add objects and object instance resources to your needs. Example:
144      *            "new ResourceConfig().registerInstances(configurationAccess)"
145      */
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));
149
150         Logger log2 = Logger.getLogger("org.glassfish");
151         log2.setLevel(Level.OFF);
152
153         server = GrizzlyHttpServerFactory.createHttpServer(URI.create(basePath), rc);
154         client = ClientBuilder.newClient();
155     }
156
157     public void dispose() {
158         if (client != null) {
159             client.close();
160         }
161         if (server != null) {
162             server.shutdownNow();
163         }
164     }
165 }