]> git.basschouten.com Git - openhab-addons.git/blob
58a47cb098488f20d5e281b0933a5bcc573427cd
[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.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.mockito.Mock;
38 import org.mockito.Mockito;
39 import org.mockito.MockitoAnnotations;
40 import org.openhab.core.events.EventPublisher;
41 import org.openhab.core.items.MetadataRegistry;
42 import org.openhab.core.net.NetworkAddressService;
43 import org.openhab.core.storage.Storage;
44 import org.openhab.core.storage.StorageService;
45 import org.openhab.io.hueemulation.internal.ConfigStore;
46 import org.openhab.io.hueemulation.internal.rest.mocks.ConfigStoreWithoutMetadata;
47 import org.openhab.io.hueemulation.internal.rest.mocks.DummyMetadataRegistry;
48 import org.openhab.io.hueemulation.internal.rest.mocks.DummyUsersStorage;
49 import org.osgi.service.cm.ConfigurationAdmin;
50
51 /**
52  * We have no OSGi framework in the background. This class resolves
53  * dependencies between the different classes and mocks common services like the configAdmin.
54  * <p>
55  * The {@link UserManagement} rest components is always
56  * setup and started in this common test setup, because all other rest components require
57  * user authentication.
58  *
59  * @author David Graeff - Initial contribution
60  */
61 public class CommonSetup {
62
63     public String basePath;
64     public Client client;
65     public ConfigStore cs;
66     public HttpServer server;
67
68     UserManagement userManagement;
69
70     AutoCloseable mocksCloseable;
71
72     @Mock
73     EventPublisher eventPublisher;
74
75     @Mock
76     ConfigurationAdmin configAdmin;
77
78     @Mock
79     ScheduledExecutorService scheduler;
80
81     @Mock
82     org.osgi.service.cm.Configuration configAdminConfig;
83
84     @Mock
85     NetworkAddressService networkAddressService;
86
87     MetadataRegistry metadataRegistry = new DummyMetadataRegistry();
88
89     StorageService storageService = new StorageService() {
90         @Override
91         public <T> Storage<T> getStorage(String name, ClassLoader classLoader) {
92             return getStorage(name);
93         }
94
95         @SuppressWarnings("unchecked")
96         @Override
97         public <T> Storage<T> getStorage(String name) {
98             if ("hueEmulationUsers".equals(name)) {
99                 return (Storage<T>) new DummyUsersStorage();
100             }
101             throw new IllegalStateException();
102         }
103     };
104
105     public CommonSetup(boolean withMetadata) throws IOException {
106         mocksCloseable = MockitoAnnotations.openMocks(this);
107
108         when(configAdmin.getConfiguration(anyString())).thenReturn(configAdminConfig);
109         when(configAdmin.getConfiguration(anyString(), any())).thenReturn(configAdminConfig);
110         Dictionary<String, Object> mockProperties = new Hashtable<>();
111         when(configAdminConfig.getProperties()).thenReturn(mockProperties);
112         when(networkAddressService.getPrimaryIpv4HostAddress()).thenReturn("127.0.0.1");
113
114         // If anything is scheduled, immediately run it instead
115         when(scheduler.schedule(any(Runnable.class), anyLong(), any())).thenAnswer(answer -> {
116             ((Runnable) answer.getArgument(0)).run();
117             return null;
118         });
119
120         if (withMetadata) {
121             cs = new ConfigStore(networkAddressService, configAdmin, metadataRegistry, scheduler);
122         } else {
123             cs = new ConfigStoreWithoutMetadata(networkAddressService, configAdmin, scheduler);
124         }
125         cs.activate(Collections.singletonMap("uuid", "a668dc9b-7172-49c3-832f-acb07dda2a20"));
126         cs.switchFilter = Collections.singleton("Switchable");
127         cs.whiteFilter = Collections.singleton("Switchable");
128         cs.colorFilter = Collections.singleton("ColorLighting");
129
130         userManagement = Mockito.spy(new UserManagement(storageService, cs));
131
132         try (ServerSocket serverSocket = new ServerSocket()) {
133             serverSocket.bind(new InetSocketAddress(0));
134             basePath = "http://localhost:" + serverSocket.getLocalPort() + "/api";
135         }
136     }
137
138     /**
139      * Start the http server to serve all registered jax-rs resources. Also setup a client for testing, see
140      * {@link #client}.
141      *
142      * @param rc A resource config. Add objects and object instance resources to your needs. Example:
143      *            "new ResourceConfig().registerInstances(configurationAccess)"
144      */
145     public void start(ResourceConfig resourceConfig) {
146         ResourceConfig rc = resourceConfig.registerInstances(userManagement).register(new LoggingFeature(
147                 Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME), Level.OFF, Verbosity.HEADERS_ONLY, 10));
148
149         Logger log2 = Logger.getLogger("org.glassfish");
150         log2.setLevel(Level.OFF);
151
152         server = GrizzlyHttpServerFactory.createHttpServer(URI.create(basePath), rc);
153         client = ClientBuilder.newClient();
154     }
155
156     public void dispose() throws Exception {
157         if (client != null) {
158             client.close();
159         }
160         if (server != null) {
161             server.shutdownNow();
162         }
163
164         mocksCloseable.close();
165     }
166 }