]> git.basschouten.com Git - openhab-addons.git/blob
40b3e3526fdf56b607f95254ea6a309d654c3b2a
[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.openhab.core.events.EventPublisher;
33 import org.openhab.core.items.MetadataRegistry;
34 import org.openhab.core.net.NetworkAddressService;
35 import org.openhab.core.storage.Storage;
36 import org.openhab.core.storage.StorageService;
37 import org.glassfish.grizzly.http.server.HttpServer;
38 import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
39 import org.glassfish.jersey.logging.LoggingFeature;
40 import org.glassfish.jersey.logging.LoggingFeature.Verbosity;
41 import org.glassfish.jersey.server.ResourceConfig;
42 import org.mockito.Mock;
43 import org.mockito.Mockito;
44 import org.mockito.MockitoAnnotations;
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 UserManagement userManagement;
64
65     @Mock
66     public EventPublisher eventPublisher;
67
68     public ConfigStore cs;
69
70     @Mock
71     ConfigurationAdmin configAdmin;
72
73     @Mock
74     ScheduledExecutorService scheduler;
75
76     @Mock
77     org.osgi.service.cm.Configuration configAdminConfig;
78
79     @Mock
80     NetworkAddressService networkAddressService;
81
82     MetadataRegistry metadataRegistry = new DummyMetadataRegistry();
83
84     StorageService storageService = new StorageService() {
85         @Override
86         public <T> Storage<T> getStorage(String name, ClassLoader classLoader) {
87             return getStorage(name);
88         }
89
90         @SuppressWarnings("unchecked")
91         @Override
92         public <T> Storage<T> getStorage(String name) {
93             if (name.equals("hueEmulationUsers")) {
94                 return (Storage<T>) new DummyUsersStorage();
95             }
96             throw new IllegalStateException();
97         }
98     };
99
100     public Client client;
101     public HttpServer server;
102     public String basePath;
103
104     public CommonSetup(boolean withMetadata) throws IOException {
105         MockitoAnnotations.initMocks(this);
106         when(configAdmin.getConfiguration(anyString())).thenReturn(configAdminConfig);
107         when(configAdmin.getConfiguration(anyString(), any())).thenReturn(configAdminConfig);
108         Dictionary<String, Object> mockProperties = new Hashtable<>();
109         when(configAdminConfig.getProperties()).thenReturn(mockProperties);
110         when(networkAddressService.getPrimaryIpv4HostAddress()).thenReturn("127.0.0.1");
111
112         // If anything is scheduled, immediately run it instead
113         when(scheduler.schedule(any(Runnable.class), anyLong(), any())).thenAnswer(answer -> {
114             ((Runnable) answer.getArgument(0)).run();
115             return null;
116         });
117
118         if (withMetadata) {
119             cs = new ConfigStore(networkAddressService, configAdmin, metadataRegistry, scheduler);
120         } else {
121             cs = new ConfigStoreWithoutMetadata(networkAddressService, configAdmin, scheduler);
122         }
123         cs.activate(Collections.singletonMap("uuid", "demouuid"));
124         cs.switchFilter = Collections.singleton("Switchable");
125         cs.whiteFilter = Collections.singleton("Switchable");
126         cs.colorFilter = Collections.singleton("ColorLighting");
127
128         userManagement = Mockito.spy(new UserManagement(storageService, cs));
129
130         try (ServerSocket serverSocket = new ServerSocket()) {
131             serverSocket.bind(new InetSocketAddress(0));
132             basePath = "http://localhost:" + serverSocket.getLocalPort() + "/api";
133         }
134     }
135
136     /**
137      * Start the http server to serve all registered jax-rs resources. Also setup a client for testing, see
138      * {@link #client}.
139      *
140      * @param rc A resource config. Add objects and object instance resources to your needs. Example:
141      *            "new ResourceConfig().registerInstances(configurationAccess)"
142      */
143     public void start(ResourceConfig resourceConfig) {
144         ResourceConfig rc = resourceConfig.registerInstances(userManagement).register(new LoggingFeature(
145                 Logger.getLogger(LoggingFeature.DEFAULT_LOGGER_NAME), Level.OFF, Verbosity.HEADERS_ONLY, 10));
146
147         Logger log2 = Logger.getLogger("org.glassfish");
148         log2.setLevel(Level.OFF);
149
150         server = GrizzlyHttpServerFactory.createHttpServer(URI.create(basePath), rc);
151         client = ClientBuilder.newClient();
152     }
153
154     public void dispose() {
155         if (client != null) {
156             client.close();
157         }
158         if (server != null) {
159             server.shutdownNow();
160         }
161     }
162 }