100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
Test overhaul (removed GWT tests and now share container between tests when config and services are the same - improves test suite run time)
Rich Turnere4025888842d
diff --git a/test/src/main/groovy/org/openremote/test/BlockingWebsocketEndpoint.groovy b/test/src/main/groovy/org/openremote/test/BlockingWebsocketEndpoint.groovydeleted file mode 100644index 65c3131d2..000000000--- a/test/src/main/groovy/org/openremote/test/BlockingWebsocketEndpoint.groovy+++ /dev/null@@ -1,108 +0,0 @@-/*- * Copyright 2016, OpenRemote Inc.- *- * See the CONTRIBUTORS.txt file in the distribution for a- * full listing of individual contributors.- *- * This program is free software: you can redistribute it and/or modify- * it under the terms of the GNU Affero General Public License as- * published by the Free Software Foundation, either version 3 of the- * License, or (at your option) any later version.- *- * This program is distributed in the hope that it will be useful,- * but WITHOUT ANY WARRANTY without even the implied warranty of- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the- * GNU Affero General Public License for more details.- *- * You should have received a copy of the GNU Affero General Public License- * along with this program. If not, see <http://www.gnu.org/licenses/>.- */-package org.openremote.test--import javax.websocket.CloseReason-import javax.websocket.Endpoint-import javax.websocket.EndpointConfig-import javax.websocket.MessageHandler-import javax.websocket.Session-import java.util.concurrent.TimeoutException--class BlockingWebsocketEndpoint extends Endpoint {-- static final def DEFAULT_TIMEOUT_MILLIS = 5000-- def startTime- def session- List<String> messages = []-- protected int timeoutMillis- protected int expectedMessageCount-- BlockingWebsocketEndpoint(int expectedMessageCount) {- this(expectedMessageCount, DEFAULT_TIMEOUT_MILLIS)- }-- BlockingWebsocketEndpoint(int expectedMessageCount, int timeoutMillis) {- this.expectedMessageCount = expectedMessageCount- this.timeoutMillis = timeoutMillis- }-- @Override- void onOpen(Session session, EndpointConfig config) {- this.session = session- session.addMessageHandler new MessageHandler.Whole<String>() {- @Override- void onMessage(String message) {- BlockingWebsocketEndpoint.this.messages << message- }- }- }-- @Override- void onClose(Session session, CloseReason closeReason) {- this.session = null- }-- def reset(int expectedMessageCount) {- this.expectedMessageCount = expectedMessageCount- this.messages = []- this.startTime = 0- }-- def awaitMessagesAndCloseOnCompletion() {- awaitMessages(true)- }-- def awaitMessages(boolean closeSessionOnCompletion) {- startTime = System.currentTimeMillis()- try {- while (!messages || messages.size() < expectedMessageCount) {- if (isTimeout()) {- throw new TimeoutException(- "Timeout while waiting for expected websocket messages ("- + expectedMessageCount- + "), received: " + messages- )- }- Thread.sleep 250- }- } finally {- if (session && closeSessionOnCompletion) {- session.close()- // Give the server a chance to end the session properly, we clear the member in onClose()- Thread.sleep 250- startTime = System.currentTimeMillis()- while (session) {- if (isTimeout()) {- throw new TimeoutException("Timeout while waiting for session to close")- }- Thread.sleep 250- }- }- }- }-- def isTimeout() {- System.currentTimeMillis() > (startTime + timeoutMillis)- }--}diff --git a/test/src/main/groovy/org/openremote/test/ClientEventService.groovy b/test/src/main/groovy/org/openremote/test/ClientEventService.groovydeleted file mode 100644index b6928f50a..000000000--- a/test/src/main/groovy/org/openremote/test/ClientEventService.groovy+++ /dev/null@@ -1,158 +0,0 @@-/*- * Copyright 2017, OpenRemote Inc.- *- * See the CONTRIBUTORS.txt file in the distribution for a- * full listing of individual contributors.- *- * This program is free software: you can redistribute it and/or modify- * it under the terms of the GNU Affero General Public License as- * published by the Free Software Foundation, either version 3 of the- * License, or (at your option) any later version.- *- * This program is distributed in the hope that it will be useful,- * but WITHOUT ANY WARRANTY without even the implied warranty of- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the- * GNU Affero General Public License for more details.- *- * You should have received a copy of the GNU Affero General Public License- * along with this program. If not, see <http://www.gnu.org/licenses/>.- */-package org.openremote.test--import com.fasterxml.jackson.databind.ObjectMapper-import org.openremote.app.client.event.SubscriptionFailureEvent-import org.openremote.app.client.event.EventService-import org.openremote.model.event.Event-import org.openremote.model.event.TriggeredEventSubscription-import org.openremote.model.event.bus.EventBus-import org.openremote.model.event.shared.*--import javax.websocket.*--/**- * Does the same job as {@link org.openremote.app.client.event.EventServiceImpl}.- */-class ClientEventService implements EventService {-- final protected EventBus eventBus- final protected ObjectMapper objectMapper- final protected EventBusWebsocketEndpoint endpoint-- class EventBusWebsocketEndpoint extends Endpoint {-- Session session-- @Override- void onOpen(Session session, EndpointConfig config) {- this.session = session- session.addMessageHandler new MessageHandler.Whole<String>() {- @Override- void onMessage(String data) {- if (data == null || data.length() == 0)- return- try {- if (data.startsWith(UnauthorizedEventSubscription.MESSAGE_PREFIX)) {- data = data.substring(UnauthorizedEventSubscription.MESSAGE_PREFIX.length())- UnauthorizedEventSubscription failure = objectMapper.readValue(data, UnauthorizedEventSubscription.class)- eventBus.dispatch(new SubscriptionFailureEvent(failure.subscription.getEventType()))- } else if (data.startsWith(TriggeredEventSubscription.MESSAGE_PREFIX)) {- data = data.substring(TriggeredEventSubscription.MESSAGE_PREFIX.length())-- if (data.startsWith("{")) {- TriggeredEventSubscription event = objectMapper.readValue(data, TriggeredEventSubscription.class)- if (event.events != null) {- event.events.forEach{ Event evt -> eventBus.dispatch(evt)}- }- }- } else if (data.startsWith(SharedEvent.MESSAGE_PREFIX)) {- data = data.substring(SharedEvent.MESSAGE_PREFIX.length())-- if (data.startsWith("[")) {- // Handle array of events- SharedEvent[] events = objectMapper.readValue(data, SharedEvent[].class)- for (SharedEvent event : events) {- eventBus.dispatch(event)- }- }- }- } catch (Throwable t) {- // We don't see problems in tests if we don't log it here- System.err.println t- t.printStackTrace(System.err)- }- }- }- }-- @Override- void onClose(Session session, CloseReason closeReason) {- this.session = null- }-- void send(SharedEvent sharedEvent) {- if (session == null || !session.isOpen())- throw new IllegalStateException("Session not open")- session.basicRemote.sendText(SharedEvent.MESSAGE_PREFIX + objectMapper.writeValueAsString(sharedEvent))- }-- void sendSubscription(EventSubscription subscription) {- if (session == null || !session.isOpen())- throw new IllegalStateException("Session not open")- final String data = EventSubscription.SUBSCRIBE_MESSAGE_PREFIX + objectMapper.writeValueAsString(subscription)- session.basicRemote.sendText(data)- }-- void sendCancelSubscription(CancelEventSubscription cancelSubscription) {- if (session == null || !session.isOpen())- throw new IllegalStateException("Session not open")- final String data = CancelEventSubscription.MESSAGE_PREFIX + objectMapper.writeValueAsString(cancelSubscription)- session.basicRemote.sendText(data)- }-- void close() {- if (session && session.isOpen()) {- session.close()- Thread.sleep 250 // Give the server a chance to end the session before we move on to the next test- }- }- }-- ClientEventService(EventBus eventBus, ObjectMapper objectMapper) {- this.eventBus = eventBus- this.objectMapper = objectMapper- this.endpoint = new EventBusWebsocketEndpoint()- }-- EventBusWebsocketEndpoint getEndpoint() {- return endpoint- }-- @Override- <E extends SharedEvent> void subscribe(Class<E> eventClass) {- endpoint.sendSubscription(new EventSubscription(eventClass))- }-- @Override- <E extends SharedEvent> void subscribe(Class<E> eventClass, EventFilter<E> filter) {- endpoint.sendSubscription(new EventSubscription(eventClass, filter))- }-- @Override- <E extends SharedEvent> void unsubscribe(Class<E> eventClass) {- endpoint.sendCancelSubscription(new CancelEventSubscription(eventClass))- }-- @Override- void dispatch(SharedEvent sharedEvent) {- endpoint.send(sharedEvent)- }-- @Override- void stop() {- close()- }-- void close() {- endpoint.close()- }-}diff --git a/test/src/main/groovy/org/openremote/test/ClientObjectMapper.java b/test/src/main/groovy/org/openremote/test/ClientObjectMapper.javadeleted file mode 100644index 340679747..000000000--- a/test/src/main/groovy/org/openremote/test/ClientObjectMapper.java+++ /dev/null@@ -1,77 +0,0 @@-/*- * Copyright 2016, OpenRemote Inc.- *- * See the CONTRIBUTORS.txt file in the distribution for a- * full listing of individual contributors.- *- * This program is free software: you can redistribute it and/or modify- * it under the terms of the GNU Affero General Public License as- * published by the Free Software Foundation, either version 3 of the- * License, or (at your option) any later version.- *- * This program is distributed in the hope that it will be useful,- * but WITHOUT ANY WARRANTY; without even the implied warranty of- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the- * GNU Affero General Public License for more details.- *- * You should have received a copy of the GNU Affero General Public License- * along with this program. If not, see <http://www.gnu.org/licenses/>.- */-package org.openremote.test;--import com.fasterxml.jackson.core.JsonProcessingException;-import com.github.nmorel.gwtjackson.client.JsonDeserializationContext;-import com.github.nmorel.gwtjackson.client.JsonSerializationContext;-import com.github.nmorel.gwtjackson.client.ObjectMapper;-import com.github.nmorel.gwtjackson.client.exception.JsonDeserializationException;-import com.github.nmorel.gwtjackson.client.exception.JsonSerializationException;--import java.io.IOException;-import java.util.logging.Logger;--/**- * Simulate GWT Jackson by using regular Jackson mapper.- */-public class ClientObjectMapper<T> implements ObjectMapper<T> {-- private static final Logger LOG = Logger.getLogger(ClientObjectMapper.class.getName());-- final protected com.fasterxml.jackson.databind.ObjectMapper jsonMapper;- final Class<T> type;-- public ClientObjectMapper(com.fasterxml.jackson.databind.ObjectMapper jsonMapper, Class<T> type) {- this.jsonMapper = jsonMapper;- this.type = type;- }-- @Override- public T read(String input) throws JsonDeserializationException {- try {- LOG.info("Reading JSON string as '" + type + "': " + input);- return jsonMapper.readValue(input, type);- } catch (IOException ex) {- throw new JsonDeserializationException(ex);- }- }-- @Override- public T read(String input, JsonDeserializationContext ctx) throws JsonDeserializationException {- throw new UnsupportedOperationException("Not implemented");- }-- @Override- public String write(T value) throws JsonSerializationException {- try {- LOG.info("Writing JSON string of: " + value);- return jsonMapper.writeValueAsString(value);- } catch (JsonProcessingException ex) {- throw new JsonSerializationException(ex);- }- }-- @Override- public String write(T value, JsonSerializationContext ctx) throws JsonSerializationException {- throw new UnsupportedOperationException("Not implemented");- }--}diff --git a/test/src/main/groovy/org/openremote/test/ClientPlaceHistoryMapper.java b/test/src/main/groovy/org/openremote/test/ClientPlaceHistoryMapper.javadeleted file mode 100644index 2bb5467b1..000000000--- a/test/src/main/groovy/org/openremote/test/ClientPlaceHistoryMapper.java+++ /dev/null@@ -1,91 +0,0 @@-/*- * Copyright 2016, OpenRemote Inc.- *- * See the CONTRIBUTORS.txt file in the distribution for a- * full listing of individual contributors.- *- * This program is free software: you can redistribute it and/or modify- * it under the terms of the GNU Affero General Public License as- * published by the Free Software Foundation, either version 3 of the- * License, or (at your option) any later version.- *- * This program is distributed in the hope that it will be useful,- * but WITHOUT ANY WARRANTY; without even the implied warranty of- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the- * GNU Affero General Public License for more details.- *- * You should have received a copy of the GNU Affero General Public License- * along with this program. If not, see <http://www.gnu.org/licenses/>.- */-package org.openremote.test;--import com.google.gwt.place.shared.*;--import java.lang.reflect.ParameterizedType;-import java.lang.reflect.Type;-import java.util.HashMap;-import java.util.Map;--/**- * Do the same job as the GWT generated code.- */-public class ClientPlaceHistoryMapper implements PlaceHistoryMapper {-- final protected Map<String, PlaceTokenizer<Place>> byPrefix= new HashMap<>();- final protected Map<Class, PlaceTokenizer<Place>> byPlaceType = new HashMap<>();- final protected Map<PlaceTokenizer<Place>, String> toPrefix= new HashMap<>();-- public ClientPlaceHistoryMapper(WithTokenizers withTokenizers) {- if (withTokenizers == null)- return;- for (Class<? extends PlaceTokenizer<?>> tokenizerType : withTokenizers.value()) {- Prefix prefixAnnotation;- if ((prefixAnnotation = tokenizerType.getAnnotation(Prefix.class)) != null) {- String prefix = prefixAnnotation.value();- Type[] genericInterfaces = tokenizerType.getGenericInterfaces();- Class placeType = (Class)((ParameterizedType)genericInterfaces[0]).getActualTypeArguments()[0];- try {- @SuppressWarnings("unchecked")- PlaceTokenizer<Place> tokenizer = (PlaceTokenizer<Place>) tokenizerType.newInstance();- byPrefix.put(prefix, tokenizer);- toPrefix.put(tokenizer, prefix);- byPlaceType.put(placeType, tokenizer);- } catch (Exception ex) {- throw new RuntimeException(ex);- }- }- }- }--- @Override- public Place getPlace(String token) {- if (token == null)- return null;- String prefix;- String remaining;- int separatorIndex = token.indexOf(":");- if (separatorIndex >= 0) {- prefix = token.substring(0, separatorIndex);- remaining = token.substring(separatorIndex+1, token.length());- } else {- prefix = token;- remaining = "";- }- return byPrefix.containsKey(prefix) ? byPrefix.get(prefix).getPlace(remaining) : null;- }--- @Override- public String getToken(Place place) {- Class placeType = place.getClass();- if (byPlaceType.containsKey(placeType)) {- PlaceTokenizer<Place> tokenizer = byPlaceType.get(placeType);- if (toPrefix.containsKey(tokenizer)) {- return toPrefix.get(tokenizer) + ":" + tokenizer.getToken(place);- }- return null;- }- return null;- }-}diff --git a/test/src/main/groovy/org/openremote/test/ContainerTrait.groovy b/test/src/main/groovy/org/openremote/test/ContainerTrait.groovyindex 83aaa1f8c..2bd18f7b7 100644--- a/test/src/main/groovy/org/openremote/test/ContainerTrait.groovy+++ b/test/src/main/groovy/org/openremote/test/ContainerTrait.groovy@@ -26,40 +26,240 @@ import org.jboss.resteasy.client.jaxrs.ResteasyClientimport org.jboss.resteasy.client.jaxrs.ResteasyClientBuilderimport org.jboss.resteasy.client.jaxrs.ResteasyWebTargetimport org.keycloak.representations.AccessTokenResponse+import org.openremote.agent.protocol.AbstractProtocolimport org.openremote.container.Containerimport org.openremote.container.ContainerServiceimport org.openremote.container.message.MessageBrokerService-import org.openremote.container.security.PasswordAuthForm+import org.openremote.container.persistence.PersistenceServiceimport org.openremote.container.security.IdentityService+import org.openremote.container.security.PasswordAuthFormimport org.openremote.container.security.keycloak.KeycloakIdentityProvider+import org.openremote.container.util.MapAccessimport org.openremote.container.web.DefaultWebsocketComponentimport org.openremote.container.web.WebClient+import org.openremote.manager.agent.AgentService+import org.openremote.manager.asset.AssetStorageService+import org.openremote.manager.rules.RulesService+import org.openremote.manager.rules.RulesetStorageService+import org.openremote.manager.setup.SetupServiceimport org.openremote.manager.web.ManagerWebServiceimport org.openremote.model.Constants+import org.openremote.model.asset.Asset+import org.openremote.model.asset.UserAsset+import org.openremote.model.query.AssetQuery+import org.openremote.model.query.RulesetQuery+import org.openremote.model.rules.AssetRuleset+import org.openremote.model.rules.GlobalRuleset+import org.openremote.model.rules.Ruleset+import org.openremote.model.rules.TenantRulesetimport javax.websocket.ClientEndpointConfigimport javax.websocket.Endpointimport javax.websocket.Sessionimport javax.websocket.WebSocketContainerimport javax.ws.rs.core.UriBuilder+import java.util.logging.Handler+import java.util.stream.Collectors+import java.util.stream.IntStreamimport static java.util.concurrent.TimeUnit.SECONDS+import static org.openremote.container.security.keycloak.KeycloakIdentityProvider.IDENTITY_NETWORK_WEBSERVER_PORT+import static org.openremote.container.web.WebService.WEBSERVER_LISTEN_PORTtrait ContainerTrait {- private static Container container+ Container startContainer(Map<String, String> config, Iterable<ContainerService> services) {++ if (container != null) {+ // Compare config and services+ def configsMatch = false+ def servicesMatch = false+ def currentConfig = container.getConfig()+ if (currentConfig == config) {+ configsMatch = true+ } else {+ if (currentConfig.size() == config.size()) {+ configsMatch = currentConfig.entrySet().stream().allMatch{entry ->+ // ignore webserver port config+ if (entry.key == WEBSERVER_LISTEN_PORT || entry.key == IDENTITY_NETWORK_WEBSERVER_PORT) {+ return true+ }+ entry.value == config.get(entry.key)+ }+ }+ }++ def currentServiceList = new ArrayList<ContainerService>()+ currentServiceList.addAll(container.getServices())+ currentServiceList.removeIf{it instanceof Handler} // Exclude log handlers as they are loaded by JUL+ def serviceList = services.asList()+ if (serviceList.size() == currentServiceList.size()) {+ servicesMatch = IntStream.range(0, serviceList.size()).allMatch { i ->+ serviceList.get(i).class == currentServiceList.get(i).class+ }+ }++ if (configsMatch && servicesMatch) {++ println("Services and config matches already running container so checking state")++// // Crude way is to restart some services to reset the system but this isn't super fast+// currentServiceList.find {it instanceof PersistenceService},+// currentServiceList.find {it instanceof SetupService},+// currentServiceList.find {it instanceof IdentityService},+// currentServiceList.find {it instanceof AgentService},+// currentServiceList.find {it instanceof RulesService}++ // Reset rulesets+ if (container.hasService(RulesetStorageService.class) && container.hasService(RulesService.class)) {+ def globalRulesets = getRulesets(GlobalRuleset.class)+ def tenantRulesets = getRulesets(TenantRuleset.class)+ def assetRulesets = getRulesets(AssetRuleset.class)+ def rulesService = container.getService(RulesService.class)+ def rulesetStorageService = container.getService(RulesetStorageService.class)++ if (!globalRulesets.isEmpty()) {+ println("Purging ${globalRulesets.size()} global ruleset(s)")+ globalRulesets.forEach { rulesetStorageService.delete(GlobalRuleset.class, it.id) }+ }+ if (!tenantRulesets.isEmpty()) {+ println("Purging ${tenantRulesets.size()} tenant ruleset(s)")+ tenantRulesets.forEach { rulesetStorageService.delete(TenantRuleset.class, it.id) }+ }+ if (!assetRulesets.isEmpty()) {+ println("Purging ${assetRulesets.size()} asset ruleset(s)")+ assetRulesets.forEach { rulesetStorageService.delete(AssetRuleset.class, it.id) }+ }+ // Wait for all rule engines to stop and be removed+ def enginesStopped = false+ while (!enginesStopped) {+ enginesStopped = rulesService.globalEngine == null && rulesService.tenantEngines.isEmpty() && rulesService.assetEngines.isEmpty()+ Thread.sleep(100)+ }+ if (!TestFixture.assetRulesets.isEmpty()) {+ println("Re-inserting ${TestFixture.assetRulesets.size()} asset ruleset(s)")+ TestFixture.assetRulesets.forEach { rulesetStorageService.merge(it) }+ }+ if (!TestFixture.tenantRulesets.isEmpty()) {+ println("Re-inserting ${TestFixture.tenantRulesets.size()} tenant ruleset(s)")+ TestFixture.tenantRulesets.forEach { rulesetStorageService.merge(it) }+ }+ if (!TestFixture.globalRulesets.isEmpty()) {+ println("Re-inserting ${TestFixture.globalRulesets.size()} global ruleset(s)")+ TestFixture.globalRulesets.forEach { rulesetStorageService.merge(it) }+ }+ }++ // Reset assets+ if (container.hasService(AgentService.class) && container.hasService(AssetStorageService.class)) {+ def currentAssets = getAssets().collect { it.getId() }+ def assetStorageService = container.getService(AssetStorageService.class)- static Container startContainer(Map<String, String> config, Iterable<ContainerService> services) {- container = new Container(config, services)+ if (!currentAssets.isEmpty()) {+ println("Purging ${currentAssets.size()} asset(s)")+ assetStorageService.delete(currentAssets, true)+ }++ // Wait for all assets to be unlinked from protocols+ def agentsRemoved = false+ while (!agentsRemoved) {+ agentsRemoved = container.getService(AgentService.class).agentMap.isEmpty()+ }+ if (!TestFixture.assets.isEmpty()) {+ println("Re-inserting ${TestFixture.assets.size()} asset(s)")+ TestFixture.assets.forEach { a ->+ a.version = 0+ assetStorageService.merge(a, true)+ }+ }+ if (!TestFixture.userAssets.isEmpty()) {+ println("Re-linking ${TestFixture.userAssets.size()} user asset(s)")+ TestFixture.userAssets.forEach { ua ->+ assetStorageService.storeUserAsset(ua)+ }+ }+ }++ return container+ } else {+ System.out.println("Request to start container with different config and/or services as already running container so restarting")+ stopContainer()+ }+ }+ TestFixture.container = new Container(config, services)container.startBackground()++ // Block until container is actually running to aid in testing but also to record some state info+ while (!container.isRunning()) {+ Thread.sleep(100)+ }++ // Track rules (very basic)+ TestFixture.globalRulesets = getRulesets(GlobalRuleset.class)+ TestFixture.tenantRulesets = getRulesets(TenantRuleset.class)+ TestFixture.assetRulesets = getRulesets(AssetRuleset.class)++ // Track assets+ TestFixture.assets = getAssets()+ TestFixture.userAssets = getUserAssets()+container}- static boolean isContainerRunning() {+ List<Ruleset> getRulesets(Class<? extends Ruleset> clazz) {+ if (!container.hasService(RulesetStorageService.class)) {+ return Collections.emptyList()+ }+ RulesetStorageService rulesetStorageService = container.getService(RulesetStorageService.class)+ return rulesetStorageService.findAll(clazz, new RulesetQuery().setFullyPopulate(true))+ }++ List<TenantRuleset> getTenantRulesets() {+ if (!container.hasService(RulesService.class)) {+ return Collections.emptyList()+ }+ RulesService rulesService = container.getService(RulesService.class)+ return rulesService.tenantEngines.values().collect {it.deployments.values()}.flatten {it.ruleset}+ }++ List<AssetRuleset> getAssetRulesets() {+ if (!container.hasService(RulesService.class)) {+ return Collections.emptyList()+ }+ RulesService rulesService = container.getService(RulesService.class)+ return rulesService.tenantEngines.values().collect {it.deployments.values()}.flatten {it.ruleset}+ }++ List<Asset> getAssets() {+ if (!container.hasService(AssetStorageService.class)) {+ return Collections.emptyList()+ }+ container.getService(AssetStorageService.class).findAll(new AssetQuery())+ }++ List<UserAsset> getUserAssets() {+ if (!container.hasService(AssetStorageService.class)) {+ return Collections.emptyList()+ }+ container.getService(AssetStorageService.class).findUserAssets(null, null, null)+ }++ Container getContainer() {+ return TestFixture.container+ }++ int getServerPort() {+ if (container != null) {+ return MapAccess.getInteger(container.getConfig(), WEBSERVER_LISTEN_PORT, 0)+ }+ return 0+ }++ boolean isContainerRunning() {container.running}- static ResteasyClientBuilder createClient() {+ ResteasyClientBuilder createClient() {ResteasyClientBuilder clientBuilder =new ResteasyClientBuilder().establishConnectionTimeout(2, SECONDS)@@ -68,66 +268,66 @@ trait ContainerTrait {return WebClient.registerDefaults(clientBuilder)}- static UriBuilder serverUri(int serverPort) {+ UriBuilder serverUri(int serverPort) {UriBuilder.fromUri("").scheme("http").host("localhost").port(serverPort)}- static void stopContainer(Container container) {+ void stopContainer() {if (container != null) {container.stop()}}- static ResteasyWebTarget getClientTarget(UriBuilder serverUri, String accessToken) {+ ResteasyWebTarget getClientTarget(UriBuilder serverUri, String accessToken) {WebClient.getTarget(createClient().build(), serverUri.build(), accessToken, null, null)}- static ResteasyWebTarget getClientApiTarget(UriBuilder serverUri, String realm) {+ ResteasyWebTarget getClientApiTarget(UriBuilder serverUri, String realm) {WebClient.getTarget(createClient().build(), serverUri.clone().replacePath(ManagerWebService.API_PATH).path(realm).build(), null, null, null)}- static ResteasyWebTarget getClientApiTarget(UriBuilder serverUri, String realm, String accessToken) {+ ResteasyWebTarget getClientApiTarget(UriBuilder serverUri, String realm, String accessToken) {WebClient.getTarget(createClient().build(), serverUri.clone().replacePath(ManagerWebService.API_PATH).path(realm).build(), accessToken, null, null)}- static ResteasyWebTarget getClientApiTarget(UriBuilder serverUri, String realm, String path, String accessToken) {+ ResteasyWebTarget getClientApiTarget(UriBuilder serverUri, String realm, String path, String accessToken) {WebClient.getTarget(createClient().build(), serverUri.clone().replacePath(ManagerWebService.API_PATH).path(realm).path(path).build(), accessToken, null, null)}- static ResteasyWebTarget getClientApiTarget(ResteasyClient client, UriBuilder serverUri, String realm, String accessToken) {+ ResteasyWebTarget getClientApiTarget(ResteasyClient client, UriBuilder serverUri, String realm, String accessToken) {WebClient.getTarget(client, serverUri.clone().replacePath(ManagerWebService.API_PATH).path(realm).build(), accessToken, null, null)}- static ResteasyWebTarget getClientApiTarget(ResteasyClient client, UriBuilder serverUri, String realm, String path, String accessToken) {+ ResteasyWebTarget getClientApiTarget(ResteasyClient client, UriBuilder serverUri, String realm, String path, String accessToken) {WebClient.getTarget(client, serverUri.clone().replacePath(ManagerWebService.API_PATH).path(realm).path(path).build(), accessToken, null, null)}- static int findEphemeralPort() {+ int findEphemeralPort() {ServerSocket socket = new ServerSocket(0, 0, Inet4Address.getLoopbackAddress())- int port = socket.getLocalPort()socket.close()+ int port = socket.getLocalPort()return port}- static AccessTokenResponse authenticate(Container container, String realm, String clientId, String username, String password) {+ AccessTokenResponse authenticate(Container container, String realm, String clientId, String username, String password) {((KeycloakIdentityProvider)container.getService(IdentityService.class).getIdentityProvider()).getKeycloak().getAccessToken(realm, new PasswordAuthForm(clientId, username, password))}- static ProducerTemplate getMessageProducerTemplate(Container container) {+ ProducerTemplate getMessageProducerTemplate(Container container) {return container.getService(MessageBrokerService.class).getContext().createProducerTemplate()}- static void addRoutes(Container container, RouteBuilder routeBuilder) {+ void addRoutes(RouteBuilder routeBuilder) {container.getService(MessageBrokerService.class).getContext().addRoutes(routeBuilder)}- static WebSocketContainer createWebsocketClient() {+ WebSocketContainer createWebsocketClient() {return ClientManager.createClient()}- static getWebsocketServerUrl(UriBuilder uriBuilder, String endpointPath, String realm, String accessToken) {+ UriBuilder getWebsocketServerUrl(UriBuilder uriBuilder, String endpointPath, String realm, String accessToken) {uriBuilder.clone().scheme("ws").replacePath(DefaultWebsocketComponent.WEBSOCKET_PATH)@@ -136,7 +336,7 @@ trait ContainerTrait {.queryParam("Authorization", "Bearer " + accessToken)}- static Session connect(WebSocketContainer websocketContainer, Endpoint endpoint, UriBuilder serverUri, String endpointPath, String realm, String accessToken) {+ Session connect(WebSocketContainer websocketContainer, Endpoint endpoint, UriBuilder serverUri, String endpointPath, String realm, String accessToken) {def websocketUrl = getWebsocketServerUrl(serverUri, endpointPath, realm, accessToken)def config = ClientEndpointConfig.Builder.create().build()websocketContainer.connectToServer(endpoint, config, websocketUrl.build())diff --git a/test/src/main/groovy/org/openremote/test/GwtClientTrait.groovy b/test/src/main/groovy/org/openremote/test/GwtClientTrait.groovydeleted file mode 100644index ca51eb2c8..000000000--- a/test/src/main/groovy/org/openremote/test/GwtClientTrait.groovy+++ /dev/null@@ -1,214 +0,0 @@-/*- * Copyright 2016, OpenRemote Inc.- *- * See the CONTRIBUTORS.txt file in the distribution for a- * full listing of individual contributors.- *- * This program is free software: you can redistribute it and/or modify- * it under the terms of the GNU Affero General Public License as- * published by the Free Software Foundation, either version 3 of the- * License, or (at your option) any later version.- *- * This program is distributed in the hope that it will be useful,- * but WITHOUT ANY WARRANTY; without even the implied warranty of- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the- * GNU Affero General Public License for more details.- *- * You should have received a copy of the GNU Affero General Public License- * along with this program. If not, see <http://www.gnu.org/licenses/>.- */-package org.openremote.test--import com.fasterxml.jackson.databind.ObjectMapper-import com.google.gwt.event.logical.shared.ValueChangeHandler-import com.google.gwt.event.shared.HandlerRegistration-import com.google.gwt.place.shared.*-import com.google.gwt.place.shared.PlaceHistoryHandler.Historian-import com.google.gwt.user.client.Window-import com.google.gwt.user.client.ui.AcceptsOneWidget-import com.google.web.bindery.event.shared.SimpleEventBus-import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget-import org.openremote.app.client.mvp.AppActivityManager-import org.openremote.app.client.mvp.AppActivityMapper-import org.openremote.app.client.mvp.AppPlaceController-import org.openremote.model.event.Event-import org.openremote.model.event.bus.EventBus-import org.openremote.model.event.bus.EventListener-import org.openremote.model.event.shared.SharedEvent-import org.openremote.model.http.Request-import org.openremote.model.http.RequestParams-import org.openremote.model.http.SuccessStatusCode-import org.openremote.model.value.Value-import org.spockframework.mock.IMockMethod--import javax.ws.rs.ClientErrorException-import javax.ws.rs.Produces-import javax.ws.rs.core.Response-import java.lang.reflect.Method--import static javax.ws.rs.core.MediaType.APPLICATION_JSON--trait GwtClientTrait {-- static class UnsupportedXMLHttpRequest implements Request.XMLHttpRequest {- @Override- String getResponseHeader(String header) {- throw new UnsupportedOperationException("Can't access response headers in test framework")- }- }-- static class ResponseWrapperXMLHttpRequest implements Request.XMLHttpRequest {- final Response response-- ResponseWrapperXMLHttpRequest(Response response) {- this.response = response- }-- @Override- String getResponseHeader(String header) {- return response.getHeaderString(header)- }- }-- protected static class MockPlaceControllerDelegate implements PlaceController.Delegate {- // TODO: Do we need this?- @Override- HandlerRegistration addWindowClosingHandler(Window.ClosingHandler handler) {- return null- }-- @Override- boolean confirm(String message) {- return false- }- }-- protected static class MockHistorian implements Historian {- // TODO: Do we need this?- @Override- HandlerRegistration addValueChangeHandler(ValueChangeHandler<String> valueChangeHandler) {- return null- }-- @Override- String getToken() {- return null- }-- @Override- void newItem(String token, boolean issueEvent) {-- }- }-- static EventBus createEventBus() {- new EventBus()- }-- static class CollectingEventListener implements EventListener<Event> {- List<SharedEvent> collectedEvents-- CollectingEventListener(List<SharedEvent> collectedEvents) {- this.collectedEvents = collectedEvents- }-- @Override- void on(Event event) {- collectedEvents << event- }- }-- static EventBus createEventBus(List<SharedEvent> collectedEvents) {- def eventBus = new EventBus()- eventBus.register(null, new CollectingEventListener(collectedEvents))- return eventBus- }-- static AppPlaceController createPlaceController(EventBus eventBus) {- def legacyEventBus = new SimpleEventBus()- def placeControllerDelegate = new MockPlaceControllerDelegate()- return new AppPlaceController(eventBus, legacyEventBus, placeControllerDelegate)-- }-- static PlaceHistoryMapper createPlaceHistoryMapper(WithTokenizers withTokenizers) {- return new ClientPlaceHistoryMapper(withTokenizers)- }-- static PlaceHistoryHandler createPlaceHistoryHandler(AppPlaceController placeController, PlaceHistoryMapper placeHistoryMapper, Place defaultPlace) {- def placeHistoryHandler = new PlaceHistoryHandler(placeHistoryMapper, new MockHistorian())- placeHistoryHandler.register(placeController, placeController.getLegacyEventBus(), defaultPlace)- return placeHistoryHandler- }-- static void startActivityManager(AcceptsOneWidget activityDisplay, AppActivityMapper activityMapper, EventBus eventBus) {- def activityManager = new AppActivityManager("Test ActivityManager", activityMapper, eventBus)- activityManager.setDisplay(activityDisplay)- }-- // This emulates how a GWT client calls a REST service, we intercept and route through Resteasy Client proxy- static void callResourceProxy(ObjectMapper jsonMapper, ResteasyWebTarget clientTarget, mockInvocation) {- // If the first parameter of the method we want to call is RequestParams- List<Object> args = mockInvocation.getArguments()- if (!(args[0] instanceof RequestParams)) {- throw new UnsupportedOperationException("Don't know how to handle service API: " + mockInvocation.getMethod)- }-- RequestParams requestParams = (RequestParams) args[0]- IMockMethod mockMethod = mockInvocation.getMethod()-- // Get a Resteasy client proxy for the resource- Class mockedResourceType = mockInvocation.getMockObject().getType()- Method mockedResourceMethod = mockedResourceType.getDeclaredMethod(- mockMethod.name,- mockMethod.parameterTypes.toArray(new Class[mockMethod.parameterTypes.size()])- )- def resourceProxy = clientTarget.proxy(mockedResourceType)-- // Try to find out what the expected success status code is- SuccessStatusCode successStatusCode =- mockedResourceMethod.getDeclaredAnnotation(SuccessStatusCode.class)- int statusCode = successStatusCode != null ? successStatusCode.value() : 200-- // Call the proxy- Object result- boolean resultPassthrough = false- // Fake an XMLHttpRequest for later (we want to access headers if there is an exception...)- Request.XMLHttpRequest xmlHttpRequest = new UnsupportedXMLHttpRequest()- try {- result = resourceProxy."$mockMethod.name"(args)- } catch (ClientErrorException ex) {- statusCode = ex.getResponse().getStatus()- xmlHttpRequest = new ResponseWrapperXMLHttpRequest(ex.getResponse())- try {- result = ex.getResponse().readEntity(String.class)- } catch (IllegalStateException ise) {- // Ignore, this happens when the response is closed already- }- resultPassthrough = true- }-- String responseText = null-- if (result != null) {- // If the method produces JSON, we need to turn whatever the proxy delivered back into JSON string- Produces producesAnnotation = mockedResourceMethod.getDeclaredAnnotation(Produces.class)- if (!resultPassthrough- && producesAnnotation != null- && Arrays.asList(producesAnnotation.value()).contains(APPLICATION_JSON)) {- // Handle elemental JsonValue special, don't use Jackson- if (result instanceof Value) {- Value value = (Value) result- responseText = value.toJson()- } else {- responseText = jsonMapper.writeValueAsString(result)- }- } else {- responseText = result.toString()- }- }-- // Pass the result to the callback, so it looks asynchronous for client code- requestParams.callback.call(statusCode, xmlHttpRequest, responseText)- }-}diff --git a/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy b/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovyindex 39d73aef7..d0cfbdd3d 100644--- a/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy+++ b/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy@@ -1,5 +1,6 @@package org.openremote.test+import com.google.common.collect.Listsimport org.apache.camel.spi.BrowsableEndpointimport org.openremote.container.Containerimport org.openremote.container.ContainerService@@ -11,89 +12,57 @@ import spock.util.concurrent.PollingConditionsimport java.util.concurrent.TimeUnitimport java.util.stream.Collectors-import static java.util.stream.StreamSupport.stream-import static org.openremote.container.security.IdentityService.IDENTITY_NETWORK_WEBSERVER_PORT+import static org.openremote.container.security.keycloak.KeycloakIdentityProvider.IDENTITY_NETWORK_WEBSERVER_PORTimport static org.openremote.container.timer.TimerService.Clock.PSEUDO+import static org.openremote.container.timer.TimerService.Clock.REALimport static org.openremote.container.timer.TimerService.TIMER_CLOCK_TYPEimport static org.openremote.container.web.WebService.WEBSERVER_LISTEN_PORTimport static org.openremote.manager.setup.SetupTasks.*trait ManagerContainerTrait extends ContainerTrait {- static Map<String, String> defaultConfig(int serverPort) {+ Map<String, String> defaultConfig(Integer serverPort) {+ if (serverPort == null) {+ serverPort = findEphemeralPort()+ }[(WEBSERVER_LISTEN_PORT) : Integer.toString(serverPort),(IDENTITY_NETWORK_WEBSERVER_PORT): Integer.toString(serverPort),+ (SETUP_IMPORT_DEMO_ASSETS) : "true",+ (SETUP_IMPORT_DEMO_USERS) : "true",(SETUP_IMPORT_DEMO_SCENES) : "false",- (SETUP_IMPORT_DEMO_RULES) : "false"+ (SETUP_IMPORT_DEMO_RULES) : "false",+ (TIMER_CLOCK_TYPE) : PSEUDO.name()]}- static Iterable<ContainerService> defaultServices(Iterable<ContainerService> additionalServices) {+ Iterable<ContainerService> defaultServices(Iterable<ContainerService> additionalServices) {[- *stream(ServiceLoader.load(ContainerService.class).spliterator(), false)- .sorted(Comparator.comparingInt{it.getPriority()})- .collect(Collectors.toList()),- *additionalServices- ] as Iterable<ContainerService>-// [-// new TimerService(),-// new ManagerExecutorService(),-// new I18NService(),-// new ManagerPersistenceService(),-// new MessageBrokerSetupService(),-// new ManagerIdentityService(),-// new SetupService(),-// new ClientEventService(),-// new RulesetStorageService(),-// new RulesService(),-// new AssetStorageService(),-// new AssetDatapointService(),-// new AssetAttributeLinkingService(),-// new AssetProcessingService(),-// new MessageBrokerService(),-// *Lists.newArrayList(ServiceLoader.load(Protocol.class)),-// new AgentService(),-// new SimulatorService(),-// new MapService(),-// new NotificationService(),-// new ConsoleAppService(),-// new ManagerWebService(),-// new HealthStatusService(),-// *additionalServices-//-// ] as Iterable<ContainerService>+ *Lists.newArrayList(ServiceLoader.load(ContainerService.class)),+ *additionalServices+ ].stream()+ .sorted(Comparator.comparingInt{it.getPriority()})+ .collect(Collectors.toList()) as Iterable<ContainerService>}- static Iterable<ContainerService> defaultServices(ContainerService... additionalServices) {+ Iterable<ContainerService> defaultServices(ContainerService... additionalServices) {defaultServices(Arrays.asList(additionalServices))}- static Container startContainerNoDemoAssets(Map<String, String> config, Iterable<ContainerService> services) {- config << [(SETUP_IMPORT_DEMO_ASSETS): "false"]- startContainer(config, services)- }-- static Container startContainerWithDemoScenesAndRules(Map<String, String> config, Iterable<ContainerService> services) {+ Container startContainerWithDemoScenesAndRules(Map<String, String> config, Iterable<ContainerService> services) {config << [(SETUP_IMPORT_DEMO_SCENES): "true"]config << [(SETUP_IMPORT_DEMO_RULES): "true"]startContainer(config, services)}- static Container startContainerNoDemoImport(Map<String, String> config, Iterable<ContainerService> services) {- config << [(SETUP_IMPORT_DEMO_ASSETS): "false"]- config << [(SETUP_IMPORT_DEMO_USERS): "false"]- startContainer(config, services)- }-/**- * Use pseudo clock instead of wall clock.+ * Use wall clock instead of pseudo clock.*/- static Container startContainerWithPseudoClock(Map<String, String> config, Iterable<ContainerService> services) {- startContainer(config << [(TIMER_CLOCK_TYPE): PSEUDO.name()], services)+ Container startContainerWithoutPseudoClock(Map<String, String> config, Iterable<ContainerService> services) {+ startContainer(config << [(TIMER_CLOCK_TYPE): REAL.name()], services)}- static boolean noEventProcessedIn(AssetProcessingService assetProcessingService, int milliseconds) {+ boolean noEventProcessedIn(AssetProcessingService assetProcessingService, int milliseconds) {return (assetProcessingService.lastProcessedEventTimestamp > 0&& assetProcessingService.lastProcessedEventTimestamp + milliseconds < System.currentTimeMillis())}@@ -101,19 +70,19 @@ trait ManagerContainerTrait extends ContainerTrait {/*** Execute pseudo clock operations in Container.*/- static void withClockOf(Container container, Closure<TimerService.Clock> clockConsumer) {+ void withClockOf(Container container, Closure<TimerService.Clock> clockConsumer) {clockConsumer.call(container.getService(TimerService.class).getClock())}- static long getClockTimeOf(Container container) {+ long getClockTimeOf(Container container) {container.getService(TimerService.class).getClock().getCurrentTimeMillis()}- static void advancePseudoClock(long amount, TimeUnit unit, Container container) {+ void advancePseudoClock(long amount, TimeUnit unit, Container container) {withClockOf(container) { it.advanceTime(amount, unit) }}- static void noPendingExchangesOnMessageEndpoint(Container container, String... endpointName) {+ void noPendingExchangesOnMessageEndpoint(Container container, String... endpointName) {for (String name : endpointName) {def endpoint = container.getService(MessageBrokerService.class).getContext().getEndpoint(name)if (!endpoint) {diff --git a/test/src/main/groovy/org/openremote/test/MockVelbusClient.java b/test/src/main/groovy/org/openremote/test/MockVelbusClient.javaindex 686bb27eb..2e0cfe10d 100644--- a/test/src/main/groovy/org/openremote/test/MockVelbusClient.java+++ b/test/src/main/groovy/org/openremote/test/MockVelbusClient.java@@ -53,7 +53,7 @@ public class MockVelbusClient implements IoClient<VelbusPacket> {public void sendMessage(VelbusPacket message) {sentMessages.add(message);- // If a mcck packet mapping exists for this then return the result+ // If a mock packet mapping exists for this then return the resultif (mockPackets != null) {List<String> mappings = mockPackets.get(message.toString());if (mappings != null) {diff --git a/test/src/main/groovy/org/openremote/test/TestAppSecurity.java b/test/src/main/groovy/org/openremote/test/TestAppSecurity.javadeleted file mode 100644index 93b906b64..000000000--- a/test/src/main/groovy/org/openremote/test/TestAppSecurity.java+++ /dev/null@@ -1,128 +0,0 @@-/*- * Copyright 2017, OpenRemote Inc.- *- * See the CONTRIBUTORS.txt file in the distribution for a- * full listing of individual contributors.- *- * This program is free software: you can redistribute it and/or modify- * it under the terms of the GNU Affero General Public License as- * published by the Free Software Foundation, either version 3 of the- * License, or (at your option) any later version.- *- * This program is distributed in the hope that it will be useful,- * but WITHOUT ANY WARRANTY; without even the implied warranty of- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the- * GNU Affero General Public License for more details.- *- * You should have received a copy of the GNU Affero General Public License- * along with this program. If not, see <http://www.gnu.org/licenses/>.- */-package org.openremote.test;--import groovy.lang.Closure;-import org.keycloak.adapters.KeycloakDeployment;-import org.keycloak.adapters.rotation.AdapterTokenVerifier;-import org.keycloak.representations.AccessToken;-import org.openremote.app.client.AppSecurity;-import org.openremote.model.Constants;-import org.openremote.model.http.RequestParams;-import org.openremote.model.interop.Consumer;-import org.openremote.model.interop.Runnable;--/**- * Does the same job as or-app-security.- */-public class TestAppSecurity implements AppSecurity {-- final protected KeycloakDeployment keycloakDeployment;- final protected Closure<String> accessTokenClosure;-- protected String token;- protected AccessToken accessToken;-- public TestAppSecurity(KeycloakDeployment keycloakDeployment, Closure<String> accessTokenClosure) {- this.keycloakDeployment = keycloakDeployment;- this.accessTokenClosure = accessTokenClosure;- }-- protected void updateAccessToken() {- token = accessTokenClosure.call();- try {- accessToken = AdapterTokenVerifier.verifyToken(token, keycloakDeployment);- } catch (Exception ex) {- throw new RuntimeException(ex);- }- }-- @Override- public String getUser() {- updateAccessToken();- return accessToken.getPreferredUsername();- }-- @Override- public boolean isAuthenticated() {- return accessToken != null;- }-- @Override- public String getFullName() {- updateAccessToken();- return accessToken.getName();- }-- @Override- public void logout() {- throw new UnsupportedOperationException();- }-- @Override- public boolean isSuperUser() {- return keycloakDeployment.getRealm().equals(Constants.MASTER_REALM) && hasRealmRole(Constants.REALM_ADMIN_ROLE);- }-- @Override- public boolean hasRealmRole(String role) {- updateAccessToken();- return accessToken.getRealmAccess().isUserInRole(role);- }-- @Override- public boolean hasResourceRole(String role, String resource) {- updateAccessToken();- return accessToken.getResourceAccess().containsKey(resource)- && accessToken.getResourceAccess().get(resource).isUserInRole(role);- }-- @Override- public boolean hasResourceRoleOrIsSuperUser(String role, String resource) {- return hasResourceRole(role, resource) || isSuperUser();- }-- @Override- public String getRealm() {- return keycloakDeployment.getRealm();- }-- @Override- public void authorizeRequestParams(RequestParams requestParams, Runnable onComplete) {- requestParams.withBearerAuth(getToken());- onComplete.run();- }-- @Override- public void authorizeUrl(String serviceUrl, Consumer<String> onComplete) {- serviceUrl = serviceUrl + "?Auth-Realm=" + getRealm() + "&Authorization=Bearer " + getToken();- onComplete.accept(serviceUrl);- }-- @Override- public boolean isUserTenantAdminEnabled() {- return true;- }-- protected String getToken() {- updateAccessToken();- return token;- }-}diff --git a/test/src/main/groovy/org/openremote/test/TestFixture.java b/test/src/main/groovy/org/openremote/test/TestFixture.javanew file mode 100644index 000000000..8981477a8--- /dev/null+++ b/test/src/main/groovy/org/openremote/test/TestFixture.java@@ -0,0 +1,49 @@+/*+ * Copyright 2020, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.test;++import org.openremote.container.Container;+import org.openremote.model.asset.Asset;+import org.openremote.model.asset.UserAsset;+import org.openremote.model.rules.Ruleset;+import org.spockframework.runtime.extension.AbstractGlobalExtension;++import java.util.List;++/**+ * Used to store state for tests to help improve test performance+ */+public class TestFixture extends AbstractGlobalExtension {++ // Store the container here to allow stopping it after all tests run+ protected static Container container;+ public static List<Ruleset> globalRulesets;+ public static List<Ruleset> tenantRulesets;+ public static List<Ruleset> assetRulesets;+ public static List<Asset> assets;+ public static List<UserAsset> userAssets;++ @Override+ public void stop() {+ if (container != null) {+ container.stop();+ }+ }+}diff --git a/test/src/main/groovy/org/openremote/test/TestOpenRemoteApp.java b/test/src/main/groovy/org/openremote/test/TestOpenRemoteApp.javadeleted file mode 100644index 2639163ca..000000000--- a/test/src/main/groovy/org/openremote/test/TestOpenRemoteApp.java+++ /dev/null@@ -1,75 +0,0 @@-/*- * Copyright 2017, OpenRemote Inc.- *- * See the CONTRIBUTORS.txt file in the distribution for a- * full listing of individual contributors.- *- * This program is free software: you can redistribute it and/or modify- * it under the terms of the GNU Affero General Public License as- * published by the Free Software Foundation, either version 3 of the- * License, or (at your option) any later version.- *- * This program is distributed in the hope that it will be useful,- * but WITHOUT ANY WARRANTY; without even the implied warranty of- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the- * GNU Affero General Public License for more details.- *- * You should have received a copy of the GNU Affero General Public License- * along with this program. If not, see <http://www.gnu.org/licenses/>.- */-package org.openremote.test;--import groovy.lang.Closure;-import org.keycloak.adapters.KeycloakDeployment;-import org.openremote.app.client.AppSecurity;-import org.openremote.app.client.OpenRemoteApp;-import org.openremote.app.client.rest.Requests;-import org.openremote.container.Container;-import org.openremote.model.http.ConstraintViolationReport;-import org.openremote.model.security.Tenant;--/**- * Does the same job as or-app.- */-public class TestOpenRemoteApp extends OpenRemoteApp {-- final TestAppSecurity security;-- final Tenant tenant;-- final Requests requests;-- public TestOpenRemoteApp(KeycloakDeployment keycloakDeployment, Tenant tenant, Closure<String> accessTokenClosure) {- this.security = new TestAppSecurity(keycloakDeployment, accessTokenClosure);- this.tenant = tenant;-- ClientObjectMapper<ConstraintViolationReport> constraintViolationReportMapper = new ClientObjectMapper<>(Container.JSON, ConstraintViolationReport.class);-- this.requests = new Requests(- security::authorizeRequestParams,- () -> {- },- () -> {- },- (e) -> {- throw new RuntimeException(e.toString());- },- constraintViolationReportMapper::read- );- }-- @Override- public AppSecurity getSecurity() {- return security;- }-- @Override- public Tenant getTenant() {- return tenant;- }-- @Override- public Requests getRequests() {- return requests;- }-}diff --git a/test/src/test/groovy/org/openremote/test/admin/AdminTenantsActivityTest.groovy b/test/src/test/groovy/org/openremote/test/admin/AdminTenantsActivityTest.groovydeleted file mode 100644index 96410c965..000000000--- a/test/src/test/groovy/org/openremote/test/admin/AdminTenantsActivityTest.groovy+++ /dev/null@@ -1,448 +0,0 @@-package org.openremote.test.admin--import com.google.gwt.junit.GWTMockUtilities-import com.google.gwt.place.shared.WithTokenizers-import com.google.gwt.user.client.ui.AcceptsOneWidget-import com.google.gwt.user.client.ui.Widget-import org.openremote.app.client.Environment-import org.openremote.app.client.ManagerActivityMapper-import org.openremote.app.client.ManagerHistoryMapper-import org.openremote.app.client.TenantMapper-import org.openremote.app.client.admin.AdminView-import org.openremote.app.client.admin.TenantArrayMapper-import org.openremote.app.client.admin.navigation.AdminNavigation-import org.openremote.app.client.admin.navigation.AdminNavigationPresenter-import org.openremote.app.client.admin.tenant.*-import org.openremote.app.client.event.GoToPlaceEvent-import org.openremote.app.client.event.ShowSuccessEvent-import org.openremote.app.client.event.WillGoToPlaceEvent-import org.openremote.app.client.i18n.ManagerMessages-import org.openremote.app.client.event.EventService-import org.openremote.app.client.style.WidgetStyle-import org.openremote.manager.security.ManagerIdentityService-import org.openremote.manager.setup.AbstractKeycloakSetup-import org.openremote.manager.setup.SetupService-import org.openremote.model.event.Event-import org.openremote.model.event.bus.EventListener-import org.openremote.model.security.Tenant-import org.openremote.model.security.TenantResource-import org.openremote.test.ClientObjectMapper-import org.openremote.test.GwtClientTrait-import org.openremote.test.ManagerContainerTrait-import org.openremote.test.TestOpenRemoteApp-import spock.lang.Specification-import spock.util.concurrent.PollingConditions--import static org.openremote.container.util.MapAccess.getString-import static org.openremote.manager.security.ManagerIdentityProvider.SETUP_ADMIN_PASSWORD-import static org.openremote.manager.security.ManagerIdentityProvider.SETUP_ADMIN_PASSWORD_DEFAULT-import static org.openremote.model.Constants.*--class AdminTenantsActivityTest extends Specification implements ManagerContainerTrait, GwtClientTrait {-- def "List all, create, update, delete tenant"() {-- given: "The server container is started"- def serverPort = findEphemeralPort()- def container = startContainerNoDemoAssets(defaultConfig(serverPort), defaultServices())- def identityService = container.getService(ManagerIdentityService.class)- def keycloakProvider = container.getService(SetupService.class).getTaskOfType(AbstractKeycloakSetup.class).keycloakProvider-- and: "expected results"- def conditions = new PollingConditions(timeout: 10)- def resultEvents = []- def resultTenants = []- def resultCreateTenantHistoryToken = null-- and: "an authenticated user"- def realm = MASTER_REALM- def accessToken = {- authenticate(- container,- realm,- KEYCLOAK_CLIENT_ID,- MASTER_REALM_ADMIN_USER,- getString(container.getConfig(), SETUP_ADMIN_PASSWORD, SETUP_ADMIN_PASSWORD_DEFAULT)- ).token- }-- and: "a test client app"- def testApp = new TestOpenRemoteApp(- keycloakProvider.getKeycloakDeployment(realm, KEYCLOAK_CLIENT_ID),- identityService.getIdentityProvider().getTenant(realm),- accessToken- )-- and: "the server resources to call from client"- def clientTarget = getClientApiTarget(serverUri(serverPort), realm)- def tenantResource = Stub(TenantResource) {- _(*_) >> { callResourceProxy(container.JSON, clientTarget, getDelegate()) }- }-- and: "The fake client MVP environment"- GWTMockUtilities.disarm()- def managerMessages = Mock(ManagerMessages) {- tenantCreated(_) >> {- "TestMessageTenantCreated:" + it[0]- }- tenantUpdated(_) >> {- "TestMessageTenantUpdated:" + it[0]- }- tenantDeleted(_) >> {- "TestMessageTenantDeleted:" + it[0]- }- requestFailed(_) >> {- "TestMessageRequestFailed:" + it[0]- }- conflictRequest() >> {- "TestMessageConflictRequest"- }- }- def eventBus = createEventBus()- eventBus.register(null, new EventListener<Event>() {- @Override- void on(Event event) {- resultEvents << event- }- })- def placeHistoryMapper = createPlaceHistoryMapper(ManagerHistoryMapper.getAnnotation(WithTokenizers.class))- def placeController = createPlaceController(eventBus)- def environment = Environment.create(- testApp,- Mock(EventService),- placeController,- placeHistoryMapper,- eventBus,- managerMessages,- new WidgetStyle()- )-- and: "The views and activities to test"- def adminViewWidget = Mock(Widget)- def adminView = Mock(AdminView) {- asWidget() >> {- adminViewWidget- }- }-- def adminNavigationView = Mock(AdminNavigation)- def adminNavigationPresenter = new AdminNavigationPresenter(environment, adminNavigationView)-- def adminTenantsView = Mock(AdminTenants) {- setTenants(_) >> {- resultTenants = it[0]- }- setCreateTenantHistoryToken(_) >> {- resultCreateTenantHistoryToken = it[0]- }- }- def tenantArrayMapper = new ClientObjectMapper(container.JSON, Tenant[].class) as TenantArrayMapper- AdminTenantsActivity adminTenantsActivity-- def adminTenantView = Mock(AdminTenant)- def tenantMapper = new ClientObjectMapper(container.JSON, Tenant.class) as TenantMapper- AdminTenantActivity adminTenantActivity-- and: "An activity management configuration"- def activityDisplay = Mock(AcceptsOneWidget)- def activityMapper = new ManagerActivityMapper(- testApp,- eventBus,- managerMessages,- {},- {},- {},- {},- {},- {},- {},- {},- {},- {},- {},- {},- {},- {- adminTenantsActivity = new AdminTenantsActivity(- environment, adminView, adminNavigationPresenter, adminTenantsView, tenantResource, tenantArrayMapper- )- return adminTenantsActivity- },- {- adminTenantActivity = new AdminTenantActivity(- environment, adminView, adminNavigationPresenter, adminTenantView, tenantResource, tenantMapper- )- return adminTenantActivity- },- {},- {},- {},- {},- )- startActivityManager(activityDisplay, activityMapper, eventBus)-- when: "Navigating to a default place"- def placeHistoryHandler = createPlaceHistoryHandler(placeController, placeHistoryMapper, new AdminTenantsPlace())- placeHistoryHandler.handleCurrentHistory()-- then: "The admin navigation view should have the right place set"- 1 * adminNavigationView.onPlaceChange(_ as AdminTenantsPlace)-- and: "The activity display should be set to admin view"- 1 * activityDisplay.setWidget(adminViewWidget)-- and: "The admin view should have content set"- 1 * adminView.setContent(adminTenantsView)-- and: "The admin tenants view should have the right activity set as presenter"- 1 * adminTenantsView.setPresenter(_ as AdminTenantsActivity)-- and: "The view should have received the tenants"- conditions.eventually {- assert resultTenants.length == 3- }-- when: "The user clicks Create Tenant"- placeController.goTo(placeHistoryMapper.getPlace(resultCreateTenantHistoryToken))-- then: "The activity should be stopped"- 1 * adminTenantsView.setPresenter(null)- 1 * adminView.setContent(null)-- and: "The admin navigation view should have the right place set"- 1 * adminNavigationView.onPlaceChange(_ as AdminTenantPlace)-- and: "The activity display should be set to admin view"- 1 * activityDisplay.setWidget(adminViewWidget)-- and: "The admin view should have content set"- 1 * adminView.setContent(adminTenantView)-- and: "The admin tenant view should have the right activity set as presenter"- 1 * adminTenantView.setPresenter(_ as AdminTenantActivity)-- and: "The admin tenant form should be cleared"- 1 * adminTenantView.clearFormMessages()- 1 * adminTenantView.setTenantDisplayNameError(false)- 1 * adminTenantView.setTenantRealmError(false)- 1 * adminTenantView.setTenantEnabledError(false)- 1 * adminTenantView.enableCreate(false)- 1 * adminTenantView.enableUpdate(false)- 1 * adminTenantView.enableDelete(false)- 1 * adminTenantView.setTenantDisplayName(null)- 1 * adminTenantView.setTenantRealm(null)- 1 * adminTenantView.setTenantEnabled(null)- 1 * adminTenantView.enableCreate(true)-- when: "The user clicks the Create button"- resultEvents = []- adminTenantActivity != null- adminTenantActivity.create()-- then: "The activity reads the tenant form"- 1 * adminTenantView.setFormBusy(true)- 1 * adminTenantView.clearFormMessages()- 1 * adminTenantView.setTenantDisplayNameError(false)- 1 * adminTenantView.setTenantRealmError(false)- 1 * adminTenantView.setTenantEnabledError(false)- 1 * adminTenantView.getTenantDisplayName() >> {- "Test Name"- }- 1 * adminTenantView.getTenantRealm() >> {- return null // This will cause a constraint violation- }- 1 * adminTenantView.getTenantEnabled() >> {- return true- }-- and: "The form errors should be shown"- 1 * adminTenantView.addFormMessageError("Tenant realm can not be empty.")- 1 * adminTenantView.setTenantRealmError(true)- 1 * adminTenantView.setFormBusy(false)-- when: "The user clicks the Create button"- resultEvents = []- adminTenantActivity.create()-- then: "The activity reads the tenant form"- 1 * adminTenantView.setFormBusy(true)- 1 * adminTenantView.clearFormMessages()- 1 * adminTenantView.setTenantDisplayNameError(false)- 1 * adminTenantView.setTenantRealmError(false)- 1 * adminTenantView.setTenantEnabledError(false)- 1 * adminTenantView.getTenantDisplayName() >> {- "Test Name"- }- 1 * adminTenantView.getTenantRealm() >> {- "testrealm"- }- 1 * adminTenantView.getTenantEnabled() >> {- true- }-- and: "The success toast should be shown"- conditions.eventually {- assert resultEvents[0] instanceof ShowSuccessEvent- assert resultEvents[0].text == "TestMessageTenantCreated:Test Name"- }-- and: "The form should be cleared the activity stopped"- 1 * adminTenantView.setFormBusy(false)- 1 * adminTenantView.setPresenter(null)- 1 * adminTenantView.clearFormMessages()- 1 * adminTenantView.setTenantDisplayNameError(false)- 1 * adminTenantView.setTenantRealmError(false)- 1 * adminTenantView.setTenantEnabledError(false)-- and: "The admin tenants activity should be shown"- conditions.eventually {- assert resultEvents[1] instanceof WillGoToPlaceEvent- assert resultEvents[1].place instanceof AdminTenantsPlace- assert resultEvents[2] instanceof GoToPlaceEvent- assert resultEvents[2].place instanceof AdminTenantsPlace- }-- and: "The view should have received the tenants"- conditions.eventually {- assert resultTenants.length == 4- }-- when: "The new tenant is selected"- resultEvents = []- def selectedTenant- resultTenants.each {- if (it.realm == "testrealm") {- selectedTenant = it- return- }- }- adminTenantsActivity.onTenantSelected(selectedTenant)-- then: "The admin tenant activity should be shown"- conditions.eventually {- assert resultEvents[0] instanceof WillGoToPlaceEvent- assert resultEvents[0].place instanceof AdminTenantPlace- assert resultEvents[1] instanceof GoToPlaceEvent- assert resultEvents[1].place instanceof AdminTenantPlace- assert resultEvents[1].place.realm == "testrealm"- }-- and: "The admin tenant form should be cleared"- 1 * adminTenantView.clearFormMessages()- 1 * adminTenantView.setTenantDisplayNameError(false)- 1 * adminTenantView.setTenantRealmError(false)- 1 * adminTenantView.setTenantEnabledError(false)- 1 * adminTenantView.enableCreate(false)- 1 * adminTenantView.enableUpdate(false)- 1 * adminTenantView.enableDelete(false)-- and: "The tenant should be loaded"- 1 * adminTenantView.setTenantDisplayName("Test Name")- 1 * adminTenantView.setTenantRealm("testrealm")- 1 * adminTenantView.setTenantEnabled(true)- 1 * adminTenantView.setFormBusy(false)- 1 * adminTenantView.enableCreate(false)- 1 * adminTenantView.enableUpdate(true)- 1 * adminTenantView.enableDelete(true)-- when: "The user clicks the Update button"- resultEvents = []- adminTenantActivity.update()-- then: "The activity reads the tenant form"- 1 * adminTenantView.setFormBusy(true)- 1 * adminTenantView.clearFormMessages()- 1 * adminTenantView.setTenantDisplayNameError(false)- 1 * adminTenantView.setTenantRealmError(false)- 1 * adminTenantView.setTenantEnabledError(false)- 1 * adminTenantView.getTenantDisplayName() >> {- "Test Name2"- }- 1 * adminTenantView.getTenantRealm() >> {- return "master" // This will cause a conflict constraint violation- }- 1 * adminTenantView.getTenantEnabled() >> {- return true- }-- and: "The form errors should be shown"- 1 * adminTenantView.addFormMessageError("TestMessageConflictRequest")- 1 * adminTenantView.setTenantRealmError(true)- 1 * adminTenantView.setFormBusy(false)-- when: "The user clicks the Update button"- resultEvents = []- adminTenantActivity.update()-- then: "The activity reads the tenant form"- 1 * adminTenantView.setFormBusy(true)- 1 * adminTenantView.clearFormMessages()- 1 * adminTenantView.setTenantDisplayNameError(false)- 1 * adminTenantView.setTenantRealmError(false)- 1 * adminTenantView.setTenantEnabledError(false)- 1 * adminTenantView.getTenantDisplayName() >> {- "Test Name2"- }- 1 * adminTenantView.getTenantRealm() >> {- return "testrealm2"- }- 1 * adminTenantView.getTenantEnabled() >> {- return true- }-- and: "The form success should be shown"- 1 * adminTenantView.setFormBusy(false)-- and: "The success toast should be shown"- conditions.eventually {- assert resultEvents[0] instanceof ShowSuccessEvent- assert resultEvents[0].text == "TestMessageTenantUpdated:Test Name2"- }-- when: "The user clicks the Delete button"- resultEvents = []- adminTenantActivity.delete()-- then: "The activity shows a confirmation dialog"- 1 * adminTenantView.showConfirmation(_, _, !null) >> {- it[2].run()- }-- and: "The activity clears the tenant form messages"- 1 * adminTenantView.setFormBusy(true)- 1 * adminTenantView.clearFormMessages()- 1 * adminTenantView.setTenantDisplayNameError(false)- 1 * adminTenantView.setTenantRealmError(false)- 1 * adminTenantView.setTenantEnabledError(false)-- and: "The success toast should be shown"- conditions.eventually {- assert resultEvents[0] instanceof ShowSuccessEvent- assert resultEvents[0].text == "TestMessageTenantDeleted:Test Name2"- }-- and: "The form should be cleared the activity stopped"- 1 * adminTenantView.setFormBusy(false)- 1 * adminTenantView.setPresenter(null)- 1 * adminTenantView.clearFormMessages()- 1 * adminTenantView.setTenantDisplayNameError(false)- 1 * adminTenantView.setTenantRealmError(false)- 1 * adminTenantView.setTenantEnabledError(false)-- and: "The admin tenants activity should be shown"- conditions.eventually {- assert resultEvents[1] instanceof WillGoToPlaceEvent- assert resultEvents[1].place instanceof AdminTenantsPlace- assert resultEvents[2] instanceof GoToPlaceEvent- assert resultEvents[2].place instanceof AdminTenantsPlace- }-- and: "The view should have received the tenants"- conditions.eventually {- resultTenants.length == 3- }-- cleanup: "The server should be stopped"- stopContainer(container)- }-}diff --git a/test/src/test/groovy/org/openremote/test/admin/AdminUsersActivityTest.groovy b/test/src/test/groovy/org/openremote/test/admin/AdminUsersActivityTest.groovydeleted file mode 100644index 1b932c838..000000000--- a/test/src/test/groovy/org/openremote/test/admin/AdminUsersActivityTest.groovy+++ /dev/null@@ -1,669 +0,0 @@-package org.openremote.test.admin--import com.google.gwt.junit.GWTMockUtilities-import com.google.gwt.place.shared.WithTokenizers-import com.google.gwt.user.client.ui.AcceptsOneWidget-import com.google.gwt.user.client.ui.Widget-import org.openremote.app.client.Environment-import org.openremote.app.client.ManagerActivityMapper-import org.openremote.app.client.ManagerHistoryMapper-import org.openremote.app.client.admin.*-import org.openremote.app.client.admin.navigation.AdminNavigation-import org.openremote.app.client.admin.navigation.AdminNavigationPresenter-import org.openremote.app.client.admin.users.AbstractAdminUsersPlace-import org.openremote.app.client.admin.users.AdminUsers-import org.openremote.app.client.admin.users.AdminUsersActivity-import org.openremote.app.client.admin.users.AdminUsersPlace-import org.openremote.app.client.admin.users.edit.AdminUserEdit-import org.openremote.app.client.admin.users.edit.AdminUserEditActivity-import org.openremote.app.client.admin.users.edit.AdminUserEditPlace-import org.openremote.app.client.event.GoToPlaceEvent-import org.openremote.app.client.event.ShowSuccessEvent-import org.openremote.app.client.event.WillGoToPlaceEvent-import org.openremote.app.client.i18n.ManagerMessages-import org.openremote.app.client.event.EventService-import org.openremote.app.client.style.WidgetStyle-import org.openremote.manager.security.ManagerIdentityService-import org.openremote.manager.setup.AbstractKeycloakSetup-import org.openremote.manager.setup.SetupService-import org.openremote.model.event.Event-import org.openremote.model.event.bus.EventListener-import org.openremote.model.notification.NotificationResource-import org.openremote.model.security.*-import org.openremote.test.ClientObjectMapper-import org.openremote.test.GwtClientTrait-import org.openremote.test.ManagerContainerTrait-import org.openremote.test.TestOpenRemoteApp-import spock.lang.Specification-import spock.util.concurrent.BlockingVariables-import spock.util.concurrent.PollingConditions--import static org.openremote.container.util.MapAccess.getString-import static org.openremote.manager.security.ManagerIdentityProvider.SETUP_ADMIN_PASSWORD-import static org.openremote.manager.security.ManagerIdentityProvider.SETUP_ADMIN_PASSWORD_DEFAULT-import static org.openremote.model.Constants.*--class AdminUsersActivityTest extends Specification implements ManagerContainerTrait, GwtClientTrait {-- def "List all, create, update, delete user"() {-- given: "The server container is started"- def serverPort = findEphemeralPort()- def container = startContainerNoDemoAssets(defaultConfig(serverPort), defaultServices())- def identityService = container.getService(ManagerIdentityService.class)- def keycloakProvider = container.getService(SetupService.class).getTaskOfType(AbstractKeycloakSetup.class).keycloakProvider-- and: "expected results"- def conditions = new PollingConditions(timeout: 10)- def blockingResult = new BlockingVariables(10)- def resultEvents = []- def resultTenants = []- def resultUsers = []- def resultSelectedRealm = null-- and: "an authenticated user"- def realm = MASTER_REALM- def accessToken = {- authenticate(- container,- realm,- KEYCLOAK_CLIENT_ID,- MASTER_REALM_ADMIN_USER,- getString(container.getConfig(), SETUP_ADMIN_PASSWORD, SETUP_ADMIN_PASSWORD_DEFAULT)- ).token- }-- and: "a test client app"- def testApp = new TestOpenRemoteApp(- keycloakProvider.getKeycloakDeployment(realm, KEYCLOAK_CLIENT_ID),- identityService.getIdentityProvider().getTenant(realm),- accessToken- )-- and: "the server resources to call from client"- def clientTarget = getClientApiTarget(serverUri(serverPort), realm)- def tenantResource = Stub(TenantResource) {- _(*_) >> { callResourceProxy(container.JSON, clientTarget, getDelegate()) }- }- def userResource = Stub(UserResource) {- _(*_) >> { callResourceProxy(container.JSON, clientTarget, getDelegate()) }- }- def notificationResource = Stub(NotificationResource) {- _(*_) >> { callResourceProxy(container.JSON, clientTarget, getDelegate()) }- }-- and: "The fake client MVP environment"- GWTMockUtilities.disarm()- def managerMessages = Mock(ManagerMessages) {- userCreated(_) >> {- "TestMessageUserCreated:" + it[0]- }- userUpdated(_) >> {- "TestMessageUserUpdated:" + it[0]- }- userDeleted(_) >> {- "TestMessageUserDeleted:" + it[0]- }- roleLabel(_) >> {- "RoleLabel:" + it[0]- }- passwordsMustMatch() >> {- "TestMessagePasswordsMustMatch"- }- passwordUpdated() >> {- "TestMessagePasswordUpdated"- }-- requestFailed(_) >> {- "TestMessageRequestFailed:" + it[0]- }- conflictRequest() >> {- "TestMessageConflictRequest"- }- }- def eventBus = createEventBus()- eventBus.register(null, new EventListener<Event>() {- @Override- void on(Event event) {- resultEvents << event- }- })- def placeHistoryMapper = createPlaceHistoryMapper(ManagerHistoryMapper.getAnnotation(WithTokenizers.class))- def placeController = createPlaceController(eventBus)- def environment = Environment.create(- testApp,- Mock(EventService),- placeController,- placeHistoryMapper,- eventBus,- managerMessages,- new WidgetStyle()- )-- and: "The views and activities to test"- def adminViewWidget = Mock(Widget)- def adminView = Mock(AdminView) {- asWidget() >> {- adminViewWidget- }- }-- def adminNavigationView = Mock(AdminNavigation)- def adminNavigationPresenter = new AdminNavigationPresenter(environment, adminNavigationView)-- def adminUsersView = Mock(AdminUsers) {- setTenants(_, _) >> { Tenant[] tenants, String selectedRealm ->- resultTenants = tenants- resultSelectedRealm = selectedRealm- }- setUsers(_) >> {- resultUsers = it[0]- }- }- def tenantArrayMapper = new ClientObjectMapper(container.JSON, Tenant[].class) as TenantArrayMapper- def userArrayMapper = new ClientObjectMapper(container.JSON, User[].class) as UserArrayMapper- AdminUsersActivity adminUsersActivity-- def adminUserView = Mock(AdminUserEdit)- def userMapper = new ClientObjectMapper(container.JSON, User.class) as UserMapper- def credentialMapper = new ClientObjectMapper(container.JSON, Credential.class) as CredentialMapper- def roleArrayMapper = new ClientObjectMapper(container.JSON, Role[].class) as RoleArrayMapper- AdminUserEditActivity adminUserActivity-- and: "An activity management configuration"- def activityDisplay = Mock(AcceptsOneWidget)- def activityMapper = new ManagerActivityMapper(- testApp,- eventBus,- managerMessages,- {},- {},- {},- {},- {},- {},- {},- {},- {},- {},- {},- {},- {},- {},- {},- {- adminUsersActivity = new AdminUsersActivity(- environment, adminView, adminNavigationPresenter, adminUsersView, tenantResource, tenantArrayMapper, userResource, userArrayMapper- )- return adminUsersActivity- },- {- adminUserActivity = new AdminUserEditActivity(- environment, adminView, adminNavigationPresenter, adminUserView, userResource, userMapper, credentialMapper, roleArrayMapper, notificationResource- )- return adminUserActivity- },- {},- {}- )- startActivityManager(activityDisplay, activityMapper, eventBus)-- when: "Navigating to a default place"- def placeHistoryHandler = createPlaceHistoryHandler(placeController, placeHistoryMapper, new AdminUsersPlace())- placeHistoryHandler.handleCurrentHistory()-- then: "The admin navigation view should have the right place set"- 1 * adminNavigationView.onPlaceChange(_ as AdminUsersPlace)-- and: "The activity display should be set to admin view"- 1 * activityDisplay.setWidget(adminViewWidget)-- and: "The admin view should have content set"- 1 * adminView.setContent(adminUsersView)-- and: "The admin users view should have the right activity set as presenter"- 1 * adminUsersView.setPresenter(_ as AdminUsersActivity)-- and: "The view should have received the tenants and selected realm"- conditions.eventually {- assert resultTenants.length == 3- assert resultSelectedRealm == null- }-- when: "The master tenant is selected"- resultEvents = []- resultTenants = []- resultUsers = []- resultSelectedRealm = null- adminUsersActivity != null- adminUsersActivity.onTenantSelected(MASTER_REALM)-- then: "The activity should be stopped"- 1 * adminUsersView.setPresenter(null)- 1 * adminView.setContent(null)-- and: "The admin users activity should be shown with the selected realm"- resultEvents[0] instanceof WillGoToPlaceEvent- resultEvents[0].place instanceof AdminUsersPlace- resultEvents[1] instanceof GoToPlaceEvent- resultEvents[1].place instanceof AdminUsersPlace- resultEvents[1].place.realm == MASTER_REALM-- and: "The view should have received the tenants, selected realm, and users"- conditions.eventually {- assert resultTenants.length == 3- assert resultSelectedRealm == MASTER_REALM- assert resultUsers.length == 2- }-- when: "The user clicks Create User"- def place = new AdminUserEditPlace(resultEvents[1].place)- resultEvents = []- resultTenants = []- resultUsers = []- resultSelectedRealm = null- placeController.goTo(place)-- then: "The activity should be stopped"- 1 * adminUsersView.setPresenter(null)- 1 * adminView.setContent(null)-- and: "The admin user activity should be shown with the selected realm"- conditions.eventually {- assert resultEvents[0] instanceof WillGoToPlaceEvent- assert resultEvents[0].place instanceof AdminUserEditPlace- assert resultEvents[1] instanceof GoToPlaceEvent- assert resultEvents[1].place instanceof AdminUserEditPlace- assert resultEvents[1].place.realm == MASTER_REALM- }-- and: "The admin navigation view should have the right place set"- 1 * adminNavigationView.onPlaceChange(_ as AdminUserEditPlace)-- and: "The activity display should be set to admin view"- 1 * activityDisplay.setWidget(adminViewWidget)-- and: "The admin view should have content set"- 1 * adminView.setContent(adminUserView)-- and: "The admin user view should have the right activity set as presenter"- 1 * adminUserView.setPresenter(_ as AdminUserEditActivity)-- and: "The admin user form should be cleared"- 1 * adminUserView.clearRoles()- 1 * adminUserView.clearFormMessages()- 1 * adminUserView.setUsernameError(false)- 1 * adminUserView.setFirstNameError(false)- 1 * adminUserView.setLastNameError(false)- 1 * adminUserView.setEmailError(false)- 1 * adminUserView.setUserEnabledError(false)- 1 * adminUserView.setPasswordError(false)- 1 * adminUserView.enableCreate(false)- 1 * adminUserView.enableUpdate(false)- 1 * adminUserView.enableDelete(false)- 1 * adminUserView.enableResetPassword(false)- 1 * adminUserView.enableRoles(false)- 1 * adminUserView.setEditMode(false)- 1 * adminUserView.setUsername(null)- 1 * adminUserView.setFirstName(null)- 1 * adminUserView.setLastName(null)- 1 * adminUserView.setEmail(null)- 1 * adminUserView.setUserEnabled(null)- 1 * adminUserView.enableCreate(true)-- when: "The user clicks the Create button"- resultEvents = []- resultTenants = []- resultUsers = []- resultSelectedRealm = null- adminUserActivity != null- adminUserActivity.create()-- then: "The activity reads the form"- 1 * adminUserView.setFormBusy(true)- 1 * adminUserView.clearFormMessages()- 1 * adminUserView.setUsernameError(false)- 1 * adminUserView.setFirstNameError(false)- 1 * adminUserView.setLastNameError(false)- 1 * adminUserView.setEmailError(false)- 1 * adminUserView.setUserEnabledError(false)- 1 * adminUserView.setPasswordError(false)- 1 * adminUserView.getUsername() >> {- "testuser"- }- 1 * adminUserView.getFirstName() >> {- return "Foo"- }- 1 * adminUserView.getLastName() >> {- return "Bar"- }- 1 * adminUserView.getEmail() >> {- return "invalidemail" // This will cause a constraint violation- }- 1 * adminUserView.getUserEnabled() >> {- return true- }-- and: "The form errors should be shown"- 1 * adminUserView.addFormMessageError("Please provide a valid email address.")- 1 * adminUserView.setEmailError(true)- 1 * adminUserView.setFormBusy(false)-- when: "The user clicks the Create button"- resultEvents = []- resultTenants = []- resultUsers = []- resultSelectedRealm = null- adminUserActivity.create()-- then: "The activity reads the form"- 1 * adminUserView.setFormBusy(true)- 1 * adminUserView.clearFormMessages()- 1 * adminUserView.setUsernameError(false)- 1 * adminUserView.setFirstNameError(false)- 1 * adminUserView.setLastNameError(false)- 1 * adminUserView.setEmailError(false)- 1 * adminUserView.setUserEnabledError(false)- 1 * adminUserView.setPasswordError(false)- 1 * adminUserView.getUsername() >> {- "testuser"- }- 1 * adminUserView.getFirstName() >> {- return "Foo"- }- 1 * adminUserView.getLastName() >> {- return "Bar"- }- 1 * adminUserView.getEmail() >> {- return "[email protected]"- }- 1 * adminUserView.getUserEnabled() >> {- return true- }-- and: "The success toast should be shown"- conditions.eventually {- assert resultEvents[0] instanceof ShowSuccessEvent- assert resultEvents[0].text == "TestMessageUserCreated:testuser"- }-- and: "The form should be cleared, the activity stopped"- 1 * adminUserView.setFormBusy(false)- 1 * adminUserView.setPresenter(null)- 1 * adminUserView.clearRoles()- 1 * adminUserView.clearFormMessages()- 1 * adminUserView.setUsernameError(false)- 1 * adminUserView.setFirstNameError(false)- 1 * adminUserView.setLastNameError(false)- 1 * adminUserView.setEmailError(false)- 1 * adminUserView.setUserEnabledError(false)- 1 * adminUserView.setPasswordError(false)-- and: "The admin users activity should be shown"- conditions.eventually {- assert resultEvents[1] instanceof WillGoToPlaceEvent- assert resultEvents[1].place instanceof AdminUsersPlace- assert resultEvents[2] instanceof GoToPlaceEvent- assert resultEvents[2].place instanceof AdminUsersPlace- assert resultEvents[2].place.realm == MASTER_REALM- }-- and: "The view should have received the users"- conditions.eventually {- assert resultUsers.length == 3- }-- when: "The new user is selected"- resultEvents = []- resultTenants = []- resultSelectedRealm = null- def selectedUser- resultUsers.each {- if (it.username == "testuser") {- selectedUser = it- return- }- }- selectedUser != null- adminUsersActivity.onUserSelected(selectedUser)-- then: "The admin user activity should be shown"- conditions.eventually {- assert resultEvents[0] instanceof WillGoToPlaceEvent- assert resultEvents[0].place instanceof AbstractAdminUsersPlace- assert resultEvents[1] instanceof GoToPlaceEvent- assert resultEvents[1].place instanceof AbstractAdminUsersPlace- assert resultEvents[1].place.realm == MASTER_REALM- assert resultEvents[1].place.userId == selectedUser.id- }-- and: "The admin user form should be cleared"- 1 * adminUserView.clearRoles()- 1 * adminUserView.clearFormMessages()- 1 * adminUserView.setUsernameError(false)- 1 * adminUserView.setFirstNameError(false)- 1 * adminUserView.setLastNameError(false)- 1 * adminUserView.setEmailError(false)- 1 * adminUserView.setUserEnabledError(false)- 1 * adminUserView.setPasswordError(false)- 1 * adminUserView.enableCreate(false)- 1 * adminUserView.enableUpdate(false)- 1 * adminUserView.enableDelete(false)- 1 * adminUserView.enableResetPassword(false)- 1 * adminUserView.enableRoles(false)- 1 * adminUserView.setEditMode(false)- 1 * adminUserView.setEditMode(true)-- and: "The user should be loaded"- 1 * adminUserView.enableRoles(true)- 1 * adminUserView.setUsername("testuser")- 1 * adminUserView.setFirstName("Foo")- 1 * adminUserView.setLastName("Bar")- 1 * adminUserView.setEmail("[email protected]")- 1 * adminUserView.setUserEnabled(true)-- then: "The roles should be added in the right order"- 1 * adminUserView.addRole(!null, "RoleLabel:read", true, false) >> {- blockingResult.readRoleId = it[0]- }-- then: "The roles should be added in the right order"- 1 * adminUserView.addRole(!null, "RoleLabel:read-assets", false, false) >> {- blockingResult.readAssetsRoleId = it[0]- }-- then: "The roles should be added in the right order"- 1 * adminUserView.addRole(!null, "RoleLabel:read-map", false, false) >> {- blockingResult.readMapRoleId = it[0]- }-- then: "The roles should be added in the right order"- 1 * adminUserView.addRole(!null, "RoleLabel:write", true, false)-- then: "The roles should be added in the right order"- 1 * adminUserView.addRole(!null, "RoleLabel:write-assets", false, false)-- and: "The form should be enabled"- 1 * adminUserView.setFormBusy(false)- 1 * adminUserView.enableCreate(false)- 1 * adminUserView.enableUpdate(true)- 1 * adminUserView.enableDelete(true)- 1 * adminUserView.enableResetPassword(true)-- when: "The user selects a composite role"- adminUserActivity.onRoleAssigned(blockingResult.readRoleId, true)-- then: "The other roles must be assigned"- 1 * adminUserView.toggleRoleAssigned(blockingResult.readAssetsRoleId, true)- 1 * adminUserView.toggleRoleAssigned(blockingResult.readMapRoleId, true)-- when: "The user deselects a composite role"- adminUserActivity.onRoleAssigned(blockingResult.readRoleId, false)-- then: "The other roles must be unassigned"- 1 * adminUserView.toggleRoleAssigned(blockingResult.readAssetsRoleId, false)- 1 * adminUserView.toggleRoleAssigned(blockingResult.readMapRoleId, false)-- when: "The user selects a composite role and then deselects one of its component roles"- adminUserActivity.onRoleAssigned(blockingResult.readRoleId, true)- adminUserActivity.onRoleAssigned(blockingResult.readMapRoleId, false)-- then: "The composite role must be unassigned"- 1 * adminUserView.toggleRoleAssigned(blockingResult.readRoleId, false)-- when: "The user clicks the Update button"- resultEvents = []- resultTenants = []- resultUsers = []- resultSelectedRealm = null- adminUserActivity.update()-- then: "The activity reads the tenant form"- 1 * adminUserView.getUsername() >> {- "testuser"- }- 1 * adminUserView.getFirstName() >> {- return "Foo"- }- 1 * adminUserView.getLastName() >> {- return "Bar"- }- 1 * adminUserView.getEmail() >> {- return "[email protected]"- }- 1 * adminUserView.getUserEnabled() >> {- return true- }-- and: "The form success should be shown"- 1 * adminUserView.addFormMessageSuccess("TestMessageUserUpdated:testuser")-- when: "The user clicks the Update button"- resultEvents = []- resultTenants = []- resultUsers = []- resultSelectedRealm = null- adminUserActivity.update()-- then: "The activity reads the tenant form (with invalid passwords)"- 1 * adminUserView.getUsername() >> {- "testuser"- }- 1 * adminUserView.getFirstName() >> {- return "Foo"- }- 1 * adminUserView.getLastName() >> {- return "Bar"- }- 1 * adminUserView.getEmail() >> {- return "[email protected]"- }- 1 * adminUserView.getUserEnabled() >> {- return true- }- 1 * adminUserView.getPassword() >> {- return "secret123"- }- 1 * adminUserView.getPasswordControl() >> {- return "secret456"- }-- and: "The form errors should be shown"- 1 * adminUserView.addFormMessageError("TestMessagePasswordsMustMatch")- 1 * adminUserView.setPasswordError(true)- 1 * adminUserView.addFormMessageSuccess("TestMessageUserUpdated:testuser")-- when: "The user clicks the Update button"- resultEvents = []- resultTenants = []- resultUsers = []- resultSelectedRealm = null- adminUserActivity.update()-- then: "The activity reads the tenant form (with matching passwords)"- 1 * adminUserView.getUsername() >> {- "testuser"- }- 1 * adminUserView.getFirstName() >> {- return "Foo"- }- 1 * adminUserView.getLastName() >> {- return "Bar"- }- 1 * adminUserView.getEmail() >> {- return "[email protected]"- }- 1 * adminUserView.getUserEnabled() >> {- return true- }- 1 * adminUserView.getPassword() >> {- return "secret123"- }- 1 * adminUserView.getPasswordControl() >> {- return "secret123"- }-- and: "The form success should be shown"- 1 * adminUserView.addFormMessageSuccess("TestMessagePasswordUpdated")- 1 * adminUserView.addFormMessageSuccess("TestMessageUserUpdated:testuser")-- when: "The user clicks the Delete button"- resultEvents = []- resultTenants = []- resultUsers = []- resultSelectedRealm = null- adminUserActivity.delete()-- then: "The activity shows a confirmation dialog"- 1 * adminUserView.showConfirmation(_, _, !null) >> {- it[2].run()- }-- and: "The activity clears the form messages"- 1 * adminUserView.setFormBusy(true)- 1 * adminUserView.clearFormMessages()- 1 * adminUserView.setUsernameError(false)- 1 * adminUserView.setFirstNameError(false)- 1 * adminUserView.setLastNameError(false)- 1 * adminUserView.setEmailError(false)- 1 * adminUserView.setUserEnabledError(false)- 1 * adminUserView.setPasswordError(false)-- and: "The success toast should be shown"- conditions.eventually {- assert resultEvents[0] instanceof ShowSuccessEvent- assert resultEvents[0].text == "TestMessageUserDeleted:testuser"- }-- and: "The form should be cleared, the activity stopped"- 1 * adminUserView.setFormBusy(false)- 1 * adminUserView.setPresenter(null)- 1 * adminUserView.clearRoles()- 1 * adminUserView.clearFormMessages()- 1 * adminUserView.setUsernameError(false)- 1 * adminUserView.setFirstNameError(false)- 1 * adminUserView.setLastNameError(false)- 1 * adminUserView.setEmailError(false)- 1 * adminUserView.setUserEnabledError(false)- 1 * adminUserView.setPasswordError(false)-- and: "The admin tenants activity should be shown"- conditions.eventually {- assert resultEvents[1] instanceof WillGoToPlaceEvent- assert resultEvents[1].place instanceof AdminUsersPlace- assert resultEvents[2] instanceof GoToPlaceEvent- assert resultEvents[2].place instanceof AdminUsersPlace- assert resultEvents[2].place.realm == MASTER_REALM- }-- and: "The view should have received the tenants and users"- conditions.eventually {- assert resultTenants.length == 3- assert resultSelectedRealm == MASTER_REALM- assert resultUsers.length == 2- }-- cleanup: "The server should be stopped"- stopContainer(container)- }-}diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetAttributeLinkingTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetAttributeLinkingTest.groovyindex 82715a8b4..61c7450f4 100644--- a/test/src/test/groovy/org/openremote/test/assets/AssetAttributeLinkingTest.groovy+++ b/test/src/test/groovy/org/openremote/test/assets/AssetAttributeLinkingTest.groovy@@ -15,23 +15,23 @@ import org.openremote.test.ManagerContainerTraitimport spock.lang.Specificationimport spock.util.concurrent.PollingConditions+import java.util.concurrent.TimeUnit+class AssetAttributeLinkingTest extends Specification implements ManagerContainerTrait {def "Check processing of asset attributes that are linked to other attributes"() {given: "expected conditions"- def conditions = new PollingConditions(timeout: 10, delay: 1)+ def conditions = new PollingConditions(timeout: 10, delay: 0.2)when: "the container is started"- def serverPort = findEphemeralPort()- def container = startContainerNoDemoImport(defaultConfig(serverPort), defaultServices())+ def container = startContainer(defaultConfig(), defaultServices())def assetStorageService = container.getService(AssetStorageService.class)def assetProcessingService = container.getService(AssetProcessingService.class)- then: "the container should be running and initialised"+ then: "the system should settle down"conditions.eventually {- container.isRunning()- assert noEventProcessedIn(assetProcessingService, 500)+ assert noEventProcessedIn(assetProcessingService, 300)}when: "assets are created"@@ -81,7 +81,7 @@ class AssetAttributeLinkingTest extends Specification implements ManagerContainenew AttributeState(new AttributeRef(asset1.id, "button"), Values.create("PRESSED")))assetProcessingService.sendAttributeEvent(buttonPressed)- Thread.sleep(10)+ advancePseudoClock(1, TimeUnit.SECONDS, container)def buttonReleased = new AttributeEvent(new AttributeState(new AttributeRef(asset1.id, "button"), Values.create("RELEASED")))@@ -98,7 +98,7 @@ class AssetAttributeLinkingTest extends Specification implements ManagerContainenew AttributeState(new AttributeRef(asset1.id, "button"), Values.create("PRESSED")))assetProcessingService.sendAttributeEvent(buttonPressed)- Thread.sleep(10)+ advancePseudoClock(1, TimeUnit.SECONDS, container)buttonReleased = new AttributeEvent(new AttributeState(new AttributeRef(asset1.id, "button"), Values.create("RELEASED")))@@ -114,7 +114,7 @@ class AssetAttributeLinkingTest extends Specification implements ManagerContainenew AttributeState(new AttributeRef(asset1.id, "button"), Values.create("LONG_PRESSED")))assetProcessingService.sendAttributeEvent(buttonLongPressed)- Thread.sleep(10)+ advancePseudoClock(1, TimeUnit.SECONDS, container)buttonReleased = new AttributeEvent(new AttributeState(new AttributeRef(asset1.id, "button"), Values.create("RELEASED")))@@ -124,7 +124,7 @@ class AssetAttributeLinkingTest extends Specification implements ManagerContaineconditions.eventually {asset2 = assetStorageService.find(asset2.id, true)assert !asset2.getAttribute("lightOnOff").get().getValueAsBoolean().get()- assert noEventProcessedIn(assetProcessingService, 1000)+ assert noEventProcessedIn(assetProcessingService, 500)}// Need to reset counter due to synchronisation issues (ideally counter would still be at 0 as@@ -201,8 +201,5 @@ class AssetAttributeLinkingTest extends Specification implements ManagerContaineasset2 = assetStorageService.find(asset2.id, true)assert !asset2.getAttribute("item2Prop1").get().getValueAsBoolean().orElse(true)}-- cleanup: "the server should be stopped"- stopContainer(container)}}diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetBrowserPresenterTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetBrowserPresenterTest.groovydeleted file mode 100644index b63ab0d3c..000000000--- a/test/src/test/groovy/org/openremote/test/assets/AssetBrowserPresenterTest.groovy+++ /dev/null@@ -1,529 +0,0 @@-package org.openremote.test.assets--import com.google.gwt.junit.GWTMockUtilities-import com.google.gwt.place.shared.WithTokenizers-import com.google.gwt.user.client.ui.Widget-import com.google.gwt.view.client.HasData-import org.openremote.app.client.Environment-import org.openremote.app.client.ManagerHistoryMapper-import org.openremote.app.client.admin.TenantArrayMapper-import org.openremote.app.client.assets.AssetArrayMapper-import org.openremote.app.client.assets.AssetMapper-import org.openremote.app.client.assets.AssetQueryMapper-import org.openremote.app.client.assets.browser.*-import org.openremote.app.client.event.SubscriptionFailureEvent-import org.openremote.app.client.i18n.ManagerMessages-import org.openremote.app.client.style.WidgetStyle-import org.openremote.manager.asset.AssetStorageService--import org.openremote.manager.security.ManagerIdentityService-import org.openremote.manager.setup.AbstractKeycloakSetup-import org.openremote.manager.setup.SetupService-import org.openremote.manager.setup.builtin.KeycloakDemoSetup-import org.openremote.manager.setup.builtin.ManagerDemoSetup-import org.openremote.model.asset.*-import org.openremote.model.event.shared.SharedEvent-import org.openremote.model.event.shared.TenantFilter-import org.openremote.model.query.AssetQuery-import org.openremote.model.security.Tenant-import org.openremote.model.security.TenantResource-import org.openremote.test.*-import spock.lang.Specification-import spock.util.concurrent.PollingConditions--import static org.openremote.container.util.MapAccess.getString-import static org.openremote.manager.event.ClientEventService.WEBSOCKET_EVENTS-import static org.openremote.manager.security.ManagerIdentityProvider.SETUP_ADMIN_PASSWORD-import static org.openremote.manager.security.ManagerIdentityProvider.SETUP_ADMIN_PASSWORD_DEFAULT-import static org.openremote.model.Constants.*--class AssetBrowserPresenterTest extends Specification implements ManagerContainerTrait, GwtClientTrait {-- def "Browse assets as superuser"() {-- given: "The server container is started"- def serverPort = findEphemeralPort()- def container = startContainer(defaultConfig(serverPort), defaultServices())- def identityService = container.getService(ManagerIdentityService.class)- def keycloakProvider = container.getService(SetupService.class).getTaskOfType(AbstractKeycloakSetup.class).keycloakProvider- def assetStorageService = container.getService(AssetStorageService.class)- def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)- def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)-- and: "an authenticated user"- def realm = MASTER_REALM- def accessToken = {- authenticate(- container,- realm,- KEYCLOAK_CLIENT_ID,- MASTER_REALM_ADMIN_USER,- getString(container.getConfig(), SETUP_ADMIN_PASSWORD, SETUP_ADMIN_PASSWORD_DEFAULT)- ).token- }-- and: "a test client app"- def testApp = new TestOpenRemoteApp(- keycloakProvider.getKeycloakDeployment(realm, KEYCLOAK_CLIENT_ID),- identityService.getIdentityProvider().getTenant(realm),- accessToken- )-- and: "a client websocket connection and attached event bus and service"- List<SharedEvent> collectedSharedEvents = []- def eventBus = createEventBus(collectedSharedEvents)- def clientEventService = new ClientEventService(eventBus, container.JSON)- connect(createWebsocketClient(), clientEventService.endpoint, serverUri(serverPort), WEBSOCKET_EVENTS, realm, accessToken.call())-- and: "the server resources to call from client"- def clientTarget = getClientApiTarget(serverUri(serverPort), realm)- def assetResource = Stub(AssetResource) {- _(*_) >> { callResourceProxy(container.JSON, clientTarget, getDelegate()) }- }- def tenantResource = Stub(TenantResource) {- _(*_) >> { callResourceProxy(container.JSON, clientTarget, getDelegate()) }- }-- and: "the data mappers for client/server calls"- def assetMapper = new ClientObjectMapper(container.JSON, Asset.class) as AssetMapper- def assetQueryMapper = new ClientObjectMapper(container.JSON, AssetQuery.class) as AssetQueryMapper- def assetArrayMapper = new ClientObjectMapper(container.JSON, Asset[].class) as AssetArrayMapper- def tenantArrayMapper = new ClientObjectMapper(container.JSON, Tenant[].class) as TenantArrayMapper-- and: "The expected result"- def conditions = new PollingConditions(initialDelay: 1, timeout: 10)-- and: "The fake client MVP environment"- GWTMockUtilities.disarm()- def managerMessages = Mock(ManagerMessages) {- loadingAssets() >> {- "TestMessageLoadingAssets"- }- requestFailed(_) >> {- "TestMessageRequestFailed:" + it[0]- }- }- def placeController = createPlaceController(eventBus)- def placeHistoryMapper = createPlaceHistoryMapper(ManagerHistoryMapper.getAnnotation(WithTokenizers.class))- def environment = Environment.create(- testApp,- clientEventService,- placeController,- placeHistoryMapper,- eventBus,- managerMessages,- new WidgetStyle()- )-- and: "The view and presenter to test"- def assetBrowserWidget = Mock(Widget)- def assetBrowser = Mock(AssetBrowser) {- asWidget() >> {- assetBrowserWidget- }- }- def rootTreeNode = new RootTreeNode()- List<BrowserTreeNode> treeDisplayRowData = null- HasData<BrowserTreeNode> treeDisplay = Mock(HasData)- def assetBrowserPresenter = new AssetBrowserPresenter(- environment,- assetBrowser,- assetResource,- assetMapper,- assetQueryMapper,- assetArrayMapper,- tenantResource,- tenantArrayMapper- )-- when: "the view is attached"- assetBrowserPresenter.onViewAttached()-- and: "the asset tree is created"- assetBrowserPresenter.loadNodeChildren(rootTreeNode, treeDisplay)-- then: "the loading message should be displayed"- 1 * treeDisplay.setRowData(*_) >> { arguments ->- assert arguments[0] == 0- def rowData = arguments[1]- treeDisplayRowData = rowData- assert rowData.size() == 1- assert rowData[0] instanceof LabelTreeNode- assert rowData[0].label == "TestMessageLoadingAssets"- }- 1 * treeDisplay.setRowCount(1, true)-- then: "the tenants should be displayed"- 1 * treeDisplay.setRowData(*_) >> { arguments ->- assert arguments[0] == 0- def rowData = arguments[1]- treeDisplayRowData = rowData- assert rowData.size() == 3- assert rowData[0] instanceof TenantTreeNode- assert rowData[0].label == "Master"- assert rowData[0].icon == "group"- assert rowData[0].id == keycloakDemoSetup.masterTenant.realm- assert rowData[1] instanceof TenantTreeNode- assert rowData[1].label == "Building"- assert rowData[1].id == keycloakDemoSetup.tenantBuilding.realm- assert rowData[2] instanceof TenantTreeNode- assert rowData[2].label == "Smart City"- assert rowData[2].id == keycloakDemoSetup.tenantCity.realm- }- 1 * treeDisplay.setRowCount(3, true)-- when: "a tenant tree node is expanded"- assetBrowserPresenter.loadNodeChildren(treeDisplayRowData[0], treeDisplay)-- then: "the assets should be displayed"- 1 * treeDisplay.setRowData(*_) >> { arguments ->- assert arguments[0] == 0- def rowData = arguments[1]- treeDisplayRowData = rowData- assert rowData.size() == 1- assert rowData[0] instanceof AssetTreeNode- assert rowData[0].label == "Smart Office"- assert rowData[0].asset.id == managerDemoSetup.smartOfficeId- }- 1 * treeDisplay.setRowCount(1, true)-- when: "an asset is modified in the database"- def asset = assetStorageService.find(managerDemoSetup.smartOfficeId)- asset.setName("Testname123")- assetStorageService.merge(asset)-- then: "a tree modified event should be received from the server"- conditions.eventually {- assert collectedSharedEvents.size() == 1- assert collectedSharedEvents[0] instanceof AssetTreeModifiedEvent- assert collectedSharedEvents[0].realm == keycloakDemoSetup.masterTenant.realm- assert collectedSharedEvents[0].assetId == managerDemoSetup.smartOfficeId- }-- then: "the asset tree should be refreshed"- 1 * assetBrowser.refresh(managerDemoSetup.smartOfficeId)-- when: "an asset is created in the database"- collectedSharedEvents.clear()- asset = new Asset("My Test Asset", AssetType.THING, asset)- asset = assetStorageService.merge(asset)-- then: "a tree modified event should be received from the server"- conditions.eventually {- assert collectedSharedEvents.size() == 2- // The inserted new asset- assert collectedSharedEvents.any {- (it instanceof AssetTreeModifiedEvent- && it.realm == keycloakDemoSetup.masterTenant.realm- && it.assetId == asset.id- && !it.newAssetChildren)- }- // The parent which has a new child asset- assert collectedSharedEvents.any {- (it instanceof AssetTreeModifiedEvent- && it.realm == keycloakDemoSetup.masterTenant.realm- && it.assetId == managerDemoSetup.smartOfficeId- && it.newAssetChildren)- }- }-- then: "the asset tree should be refreshed"- 1 * assetBrowser.refresh(asset.id, managerDemoSetup.smartOfficeId)-- cleanup: "the client should be stopped"- if (clientEventService != null) clientEventService.close()-- and: "the server should be stopped"- stopContainer(container)- }-- def "Browse assets as testuser1"() {-- given: "The server container is started"- def serverPort = findEphemeralPort()- def container = startContainer(defaultConfig(serverPort), defaultServices())- def identityService = container.getService(ManagerIdentityService.class)- def keycloakProvider = container.getService(SetupService.class).getTaskOfType(AbstractKeycloakSetup.class).keycloakProvider- def assetStorageService = container.getService(AssetStorageService.class)- def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)- def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)-- and: "an authenticated user"- def realm = MASTER_REALM- def accessToken = {- authenticate(- container,- realm,- KEYCLOAK_CLIENT_ID,- "testuser1",- "testuser1"- ).token- }-- and: "a test client app"- def testApp = new TestOpenRemoteApp(- keycloakProvider.getKeycloakDeployment(realm, KEYCLOAK_CLIENT_ID),- identityService.getIdentityProvider().getTenant(realm),- accessToken- )-- and: "a client websocket connection and attached event bus and service"- List<SharedEvent> collectedSharedEvents = []- def eventBus = createEventBus(collectedSharedEvents)- def clientEventService = new ClientEventService(eventBus, container.JSON)- connect(createWebsocketClient(), clientEventService.endpoint, serverUri(serverPort), WEBSOCKET_EVENTS, realm, accessToken.call())-- and: "the server resources to call from client"- def clientTarget = getClientApiTarget(serverUri(serverPort), realm)- def assetResource = Stub(AssetResource) {- _(*_) >> { callResourceProxy(container.JSON, clientTarget, getDelegate()) }- }- def tenantResource = Stub(TenantResource) {- _(*_) >> { callResourceProxy(container.JSON, clientTarget, getDelegate()) }- }-- and: "the data mappers for client/server calls"- def assetMapper = new ClientObjectMapper(container.JSON, Asset.class) as AssetMapper- def assetQueryMapper = new ClientObjectMapper(container.JSON, AssetQuery.class) as AssetQueryMapper- def assetArrayMapper = new ClientObjectMapper(container.JSON, Asset[].class) as AssetArrayMapper- def tenantArrayMapper = new ClientObjectMapper(container.JSON, Tenant[].class) as TenantArrayMapper-- and: "The expected result"- def conditions = new PollingConditions(initialDelay: 1, timeout: 10)-- and: "The fake client MVP environment"- GWTMockUtilities.disarm()- def managerMessages = Mock(ManagerMessages) {- loadingAssets() >> {- "TestMessageLoadingAssets"- }- requestFailed(_) >> {- "TestMessageRequestFailed:" + it[0]- }- }- def placeController = createPlaceController(eventBus)- def placeHistoryMapper = createPlaceHistoryMapper(ManagerHistoryMapper.getAnnotation(WithTokenizers.class))- def environment = Environment.create(- testApp,- clientEventService,- placeController,- placeHistoryMapper,- eventBus,- managerMessages,- new WidgetStyle()- )-- and: "The view and presenter to test"- def assetBrowserWidget = Mock(Widget)- def assetBrowser = Mock(AssetBrowser) {- asWidget() >> {- assetBrowserWidget- }- }- def rootTreeNode = new RootTreeNode()- List<BrowserTreeNode> treeDisplayRowData = null- HasData<BrowserTreeNode> treeDisplay = Mock(HasData)- def assetBrowserPresenter = new AssetBrowserPresenter(- environment,- assetBrowser,- assetResource,- assetMapper,- assetQueryMapper,- assetArrayMapper,- tenantResource,- tenantArrayMapper- )-- when: "the view is attached"- assetBrowserPresenter.onViewAttached()-- and: "the asset tree is created"- assetBrowserPresenter.loadNodeChildren(rootTreeNode, treeDisplay)-- then: "the loading message should be displayed"- 1 * treeDisplay.setRowData(*_) >> { arguments ->- assert arguments[0] == 0- def rowData = arguments[1]- treeDisplayRowData = rowData- assert rowData.size() == 1- assert rowData[0] instanceof LabelTreeNode- assert rowData[0].label == "TestMessageLoadingAssets"- }- 1 * treeDisplay.setRowCount(1, true)-- then: "the root assets of the realm should be displayed"- 1 * treeDisplay.setRowData(*_) >> { arguments ->- assert arguments[0] == 0- def rowData = arguments[1]- treeDisplayRowData = rowData- assert rowData.size() == 1- assert rowData[0] instanceof AssetTreeNode- assert rowData[0].label == "Smart Office"- assert rowData[0].icon == "office-building"- assert rowData[0].asset.id == managerDemoSetup.smartOfficeId- }- 1 * treeDisplay.setRowCount(1, true)-- when: "an asset tree node is expanded"- assetBrowserPresenter.loadNodeChildren(treeDisplayRowData[0], treeDisplay)-- then: "the assets should be displayed"- 1 * treeDisplay.setRowData(*_) >> { arguments ->- assert arguments[0] == 0- def rowData = arguments[1]- treeDisplayRowData = rowData- assert rowData.size() == 1- assert rowData[0] instanceof AssetTreeNode- assert rowData[0].label == "Ground Floor"- assert rowData[0].icon == "stairs"- assert rowData[0].asset.id == managerDemoSetup.groundFloorId- }- 1 * treeDisplay.setRowCount(1, true)-- when: "an asset is modified in the database"- def asset = assetStorageService.find(managerDemoSetup.groundFloorId)- asset.setName("Testname123")- assetStorageService.merge(asset)-- then: "a tree modified event should be received from the server"- conditions.eventually {- assert collectedSharedEvents.size() == 1- assert collectedSharedEvents[0] instanceof AssetTreeModifiedEvent- assert collectedSharedEvents[0].realm == keycloakDemoSetup.masterTenant.realm- assert collectedSharedEvents[0].assetId == managerDemoSetup.groundFloorId- }-- then: "the asset tree should be refreshed"- 1 * assetBrowser.refresh(managerDemoSetup.groundFloorId)-- when: "the client tries to subscribe to events in a foreign realm"- collectedSharedEvents.clear()- clientEventService.subscribe(- AssetTreeModifiedEvent.class,- new TenantFilter(keycloakDemoSetup.tenantBuilding.realm)- )-- then: "the server should return a failure"- conditions.eventually {- assert collectedSharedEvents.size() == 1- assert collectedSharedEvents[0] instanceof SubscriptionFailureEvent- assert collectedSharedEvents[0].failedEventType == AssetTreeModifiedEvent.getEventType(AssetTreeModifiedEvent.class)- }-- cleanup: "the client should be stopped"- if (clientEventService != null) clientEventService.close()-- and: "the server should be stopped"- stopContainer(container)- }-- def "Browse assets as testuser3"() {-- given: "The server container is started"- def serverPort = findEphemeralPort()- def container = startContainer(defaultConfig(serverPort), defaultServices())- def identityService = container.getService(ManagerIdentityService.class)- def keycloakProvider = container.getService(SetupService.class).getTaskOfType(AbstractKeycloakSetup.class).keycloakProvider- def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)-- and: "an authenticated user"- def realm = keycloakDemoSetup.tenantBuilding.realm- def accessToken = {- authenticate(- container,- realm,- KEYCLOAK_CLIENT_ID,- "testuser3",- "testuser3"- ).token- }-- and: "a test client app"- def testApp = new TestOpenRemoteApp(- keycloakProvider.getKeycloakDeployment(realm, KEYCLOAK_CLIENT_ID),- identityService.getIdentityProvider().getTenant(realm),- accessToken- )-- and: "a client websocket connection and attached event bus and service"- List<SharedEvent> collectedSharedEvents = []- def eventBus = createEventBus(collectedSharedEvents)- def clientEventService = new ClientEventService(eventBus, container.JSON)- connect(createWebsocketClient(), clientEventService.endpoint, serverUri(serverPort), WEBSOCKET_EVENTS, realm, accessToken.call())-- and: "the server resources to call from client"- def clientTarget = getClientApiTarget(serverUri(serverPort), realm)- def assetResource = Stub(AssetResource) {- _(*_) >> { callResourceProxy(container.JSON, clientTarget, getDelegate()) }- }- def tenantResource = Stub(TenantResource) {- _(*_) >> { callResourceProxy(container.JSON, clientTarget, getDelegate()) }- }-- and: "the data mappers for client/server calls"- def assetMapper = new ClientObjectMapper(container.JSON, Asset.class) as AssetMapper- def assetQueryMapper = new ClientObjectMapper(container.JSON, AssetQuery.class) as AssetQueryMapper- def assetArrayMapper = new ClientObjectMapper(container.JSON, Asset[].class) as AssetArrayMapper- def tenantArrayMapper = new ClientObjectMapper(container.JSON, Tenant[].class) as TenantArrayMapper-- and: "The expected result"- def conditions = new PollingConditions(initialDelay: 1, timeout: 10)-- and: "The fake client MVP environment"- GWTMockUtilities.disarm()- def managerMessages = Mock(ManagerMessages) {- loadingAssets() >> {- "TestMessageLoadingAssets"- }- requestFailed(_) >> {- "TestMessageRequestFailed:" + it[0]- }- }- def placeController = createPlaceController(eventBus)- def placeHistoryMapper = createPlaceHistoryMapper(ManagerHistoryMapper.getAnnotation(WithTokenizers.class))- def environment = Environment.create(- testApp,- clientEventService,- placeController,- placeHistoryMapper,- eventBus,- managerMessages,- new WidgetStyle()- )-- and: "The view and presenter to test"- def assetBrowserWidget = Mock(Widget)- def assetBrowser = Mock(AssetBrowser) {- asWidget() >> {- assetBrowserWidget- }- }- def assetBrowserPresenter = new AssetBrowserPresenter(- environment,- assetBrowser,- assetResource,- assetMapper,- assetQueryMapper,- assetArrayMapper,- tenantResource,- tenantArrayMapper- )-- when: "the view is attached"- assetBrowserPresenter.onViewAttached()-- // TODO Need to render asset list for restricted users without trees and subscribing to tree mods- then: "the server should return a subscription failure"- conditions.eventually {- assert collectedSharedEvents.size() == 1- assert collectedSharedEvents[0] instanceof SubscriptionFailureEvent- assert collectedSharedEvents[0].failedEventType == AssetTreeModifiedEvent.getEventType(AssetTreeModifiedEvent.class)- }-- cleanup: "the client should be stopped"- if (clientEventService != null) clientEventService.close()-- and: "the server should be stopped"- stopContainer(container)- }-}diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovyindex 2616b0d7e..6719e0ffc 100644--- a/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovy+++ b/test/src/test/groovy/org/openremote/test/assets/AssetDatapointTest.groovy@@ -15,9 +15,11 @@ import spock.util.concurrent.PollingConditionsimport java.time.Instantimport java.util.concurrent.TimeUnit+import static java.util.concurrent.TimeUnit.DAYSimport static java.util.concurrent.TimeUnit.HOURSimport static java.util.concurrent.TimeUnit.SECONDSimport static org.openremote.manager.datapoint.AssetDatapointService.DATA_POINTS_MAX_AGE_DAYS+import static org.openremote.manager.datapoint.AssetDatapointService.DATA_POINTS_MAX_AGE_DAYS_DEFAULTimport static org.openremote.manager.setup.builtin.ManagerDemoSetup.thingLightToggleAttributeNameclass AssetDatapointTest extends Specification implements ManagerContainerTrait {@@ -25,11 +27,11 @@ class AssetDatapointTest extends Specification implements ManagerContainerTraitdef "Test number and toggle attribute storage, retrieval and purging"() {given: "expected conditions"- def conditions = new PollingConditions(timeout: 10, initialDelay: 1, delay: 1)+ def conditions = new PollingConditions(timeout: 10, delay: 0.2)- when: "the demo agent and thing have been deployed with a DATA_POINTS_MAX_AGE_DAYS value of 1"- def serverPort = findEphemeralPort()- def container = startContainerWithPseudoClock defaultConfig(serverPort) << [(DATA_POINTS_MAX_AGE_DAYS): "1"], defaultServices()+ when: "the demo agent and thing have been deployed"+ def datapointPurgeDays = DATA_POINTS_MAX_AGE_DAYS_DEFAULT+ def container = startContainer(defaultConfig(), defaultServices())def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)def simulatorProtocol = container.getService(SimulatorProtocol.class)def assetStorageService = container.getService(AssetStorageService.class)@@ -41,8 +43,16 @@ class AssetDatapointTest extends Specification implements ManagerContainerTraitassert Values.getNumber(state.orElse(null)).orElse(null) == 12.345d}- when: "a simulated sensor receives a new value"+ when: "a simulated sensor receives some values"+ advancePseudoClock(10, SECONDS, container)+ simulatorProtocol.putValue(managerDemoSetup.thingId, "light1PowerConsumption", Values.create(13.3d))advancePseudoClock(10, SECONDS, container)+ simulatorProtocol.putValue(managerDemoSetup.thingId, "light1PowerConsumption", Values.create(13.3d))+ advancePseudoClock(10, SECONDS, container)+ simulatorProtocol.putValue(managerDemoSetup.thingId, "light1PowerConsumption", Values.create(13.3d))++ and: "we move forward in time more than purge days and a simulated sensor receives a new value"+ advancePseudoClock(datapointPurgeDays, DAYS, container)def datapoint1ExpectedTimestamp = getClockTimeOf(container)simulatorProtocol.putValue(managerDemoSetup.thingId, "light1PowerConsumption", Values.create(13.3d))@@ -87,7 +97,7 @@ class AssetDatapointTest extends Specification implements ManagerContainerTraitexpect: "the datapoints to be stored"conditions.eventually {def datapoints = assetDatapointService.getDatapoints(new AttributeRef(managerDemoSetup.thingId, "light1PowerConsumption"))- assert datapoints.size() > 3+ assert datapoints.size() == 3// Note that the "No value" sensor update should not have created a datapoint, the first// datapoint is the last sensor update with an actual value@@ -182,8 +192,8 @@ class AssetDatapointTest extends Specification implements ManagerContainerTrait// Test purging of data points// ------------------------------------- when: "time moves forward by more than a day"- advancePseudoClock(26, HOURS, container)+ when: "time moves forward by more than purge days"+ advancePseudoClock(datapointPurgeDays + 1, DAYS, container)and: "the power sensor with default max age receives a new value"def datapoint4ExpectedTimestamp = getClockTimeOf(container)@@ -197,7 +207,7 @@ class AssetDatapointTest extends Specification implements ManagerContainerTraitdef powerDatapoints = assetDatapointService.getDatapoints(new AttributeRef(managerDemoSetup.thingId, "light1PowerConsumption"))def toggleDatapoints = assetDatapointService.getDatapoints(new AttributeRef(managerDemoSetup.thingId, thingLightToggleAttributeName))- assert powerDatapoints.size() > 4+ assert powerDatapoints.size() == 4assert Values.getNumber(powerDatapoints.get(0).value).orElse(null) == 17.5dassert powerDatapoints.get(0).timestamp == datapoint4ExpectedTimestamp@@ -206,12 +216,13 @@ class AssetDatapointTest extends Specification implements ManagerContainerTraitassert toggleDatapoints.get(0).timestamp == datapoint4ExpectedTimestamp}- when: "the daily data point purge routine executes the next day"- // Move clock to next days purge runtime+ when: "the clock advances to the next days purge routine execution time"advancePseudoClock(assetDatapointService.getFirstRunMillis(Instant.ofEpochMilli(getClockTimeOf(container))), TimeUnit.MILLISECONDS, container)++ and: "the purge routine runs"assetDatapointService.purgeDataPoints()- then: "data points older than 1 day should be purged for the power sensor"+ then: "data points older than purge days should be purged for the power sensor"conditions.eventually {def datapoints = assetDatapointService.getDatapoints(new AttributeRef(managerDemoSetup.thingId, "light1PowerConsumption"))assert datapoints.size() == 1@@ -227,8 +238,10 @@ class AssetDatapointTest extends Specification implements ManagerContainerTraitassert datapoints.get(0).timestamp == datapoint4ExpectedTimestamp}- when: "the daily data point purge routine executes 3 days later"- advancePseudoClock(3, TimeUnit.DAYS, container)+ when: "the clock advances 3 times the purge duration"+ advancePseudoClock(3*datapointPurgeDays, DAYS, container)++ and: "the purge routine runs"assetDatapointService.purgeDataPoints()then: "all data points should be purged for power sensor"@@ -245,8 +258,10 @@ class AssetDatapointTest extends Specification implements ManagerContainerTraitassert datapoints.get(0).timestamp == datapoint4ExpectedTimestamp}- when: "the daily data point purge routine executes 3 days later"- advancePseudoClock(3, TimeUnit.DAYS, container)+ when: "the clock advances 3 times the purge duration"+ advancePseudoClock(3*datapointPurgeDays, DAYS, container)++ and: "the purge routine runs"assetDatapointService.purgeDataPoints()then: "data points older than 7 days should have been purged for the toggle sensor"@@ -257,8 +272,10 @@ class AssetDatapointTest extends Specification implements ManagerContainerTraitassert datapoints.get(0).timestamp == datapoint4ExpectedTimestamp}- when: "the daily data point purge routine executes 1 day later"- advancePseudoClock(1, TimeUnit.DAYS, container)+ when: "the clock advances by the purge duration"+ advancePseudoClock(datapointPurgeDays, DAYS, container)++ and: "the purge routine runs"assetDatapointService.purgeDataPoints()then: "all data points should have been purged for the toggle sensor"@@ -266,8 +283,5 @@ class AssetDatapointTest extends Specification implements ManagerContainerTraitdef datapoints = assetDatapointService.getDatapoints(new AttributeRef(managerDemoSetup.thingId, thingLightToggleAttributeName))assert datapoints.isEmpty()}-- cleanup: "the server should be stopped"- stopContainer(container)}}diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovyindex 50a5ed1c7..59407910c 100644--- a/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy+++ b/test/src/test/groovy/org/openremote/test/assets/AssetIntegrityTest.groovy@@ -24,8 +24,7 @@ class AssetIntegrityTest extends Specification implements ManagerContainerTraitdef "Test asset changes as superuser"() {given: "the server container is started"- def serverPort = findEphemeralPort()- def container = startContainer(defaultConfig(serverPort), defaultServices())+ def container = startContainer(defaultConfig(), defaultServices())def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)@@ -80,7 +79,7 @@ class AssetIntegrityTest extends Specification implements ManagerContainerTraitassetResource.writeAttributeValue(null, testAsset.getId(), "foo", "\"bar2\"")then: "the attribute value should match"- new PollingConditions(delay: 1, timeout: 5).eventually {+ new PollingConditions(timeout: 5, delay: 0.2).eventually {def asset = assetResource.get(null, testAsset.getId())assert asset.getAttribute("foo").get().getValueAsString().get() == "bar2"}@@ -89,7 +88,7 @@ class AssetIntegrityTest extends Specification implements ManagerContainerTraitassetResource.writeAttributeValue(null, testAsset.getId(), "foo", "null")then: "the attribute value should match"- new PollingConditions(delay: 1, timeout: 5).eventually {+ new PollingConditions(timeout: 5, delay: 0.2).eventually {def asset = assetResource.get(null, testAsset.getId())assert !asset.getAttribute("foo").get().getValue().isPresent()}@@ -144,8 +143,5 @@ class AssetIntegrityTest extends Specification implements ManagerContainerTraitthen: "the request should be bad"ex = thrown()ex.response.status == 400-- cleanup: "the server should be stopped"- stopContainer(container)}}diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetModelResourceTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetModelResourceTest.groovyindex c6a1fbdee..9e40d013a 100644--- a/test/src/test/groovy/org/openremote/test/assets/AssetModelResourceTest.groovy+++ b/test/src/test/groovy/org/openremote/test/assets/AssetModelResourceTest.groovy@@ -19,7 +19,6 @@*/package org.openremote.test.assets-import org.openremote.container.Containerimport org.openremote.model.asset.AssetModelResourceimport org.openremote.model.asset.AssetTypeimport org.openremote.model.attribute.AttributeType@@ -49,27 +48,17 @@ import static org.openremote.model.asset.AssetType.THINGclass AssetModelResourceTest extends Specification implements ManagerContainerTrait {- @Shared- static Container container@Sharedstatic AssetModelResource assetModelResourcedef setupSpec() {- given: "the server container is started"- def serverPort = findEphemeralPort()- container = startContainer(defaultConfig(serverPort), defaultServices())+ def container = startContainer(defaultConfig(), defaultServices())assetModelResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM).proxy(AssetModelResource.class)}- def cleanupSpec() {- given: "the server should be stopped"- stopContainer(container)- }-def "Request types"() {when: "a request for Asset types is made"-def assetDescriptors = assetModelResource.getAssetDescriptors(null)then: "the default asset types should be present"@@ -92,7 +81,6 @@ class AssetModelResourceTest extends Specification implements ManagerContainerTrassetDescriptors.any{it.name == THING.name}when: "a request for Attribute types is made"-def attributeTypeDescriptors = assetModelResource.getAttributeDescriptors(null)then: "the default types should be present"diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetModelTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetModelTest.groovyindex ac80bd2a0..931026fcd 100644--- a/test/src/test/groovy/org/openremote/test/assets/AssetModelTest.groovy+++ b/test/src/test/groovy/org/openremote/test/assets/AssetModelTest.groovy@@ -138,5 +138,4 @@ class AssetModelTest extends Specification {then: "they should be the same"addedOrModifiedAttributes.size() == 0}-}diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovyindex 31b4bfc31..eea022e9a 100644--- a/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy+++ b/test/src/test/groovy/org/openremote/test/assets/AssetPermissionsTest.groovy@@ -34,11 +34,10 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraidef "Access assets as superuser"() {given: "the server container is started"- def serverPort = findEphemeralPort()- def container = startContainer(defaultConfig(serverPort), defaultServices())+ def container = startContainer(defaultConfig(), defaultServices())def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)- def conditions = new PollingConditions(delay: 1, timeout: 5)+ def conditions = new PollingConditions(delay: 0.2, timeout: 5)and: "an authenticated admin user"def accessToken = authenticate(@@ -215,19 +214,15 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraiassert asset.getAttribute(AttributeType.GEO_STREET).get().getValue().isPresent()assert asset.getAttribute(AttributeType.GEO_STREET).get().getValue().get().toJson() == Values.create("Teststreet 456").toJson()}-- cleanup: "the server should be stopped"- stopContainer(container)}def "Access assets as testuser1"() {given: "the server container is started"- def serverPort = findEphemeralPort()- def container = startContainer(defaultConfig(serverPort), defaultServices())+ def container = startContainer(defaultConfig(), defaultServices())def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)- def conditions = new PollingConditions(delay: 1, timeout: 10)+ def conditions = new PollingConditions(delay: 0.2, timeout: 10)and: "an authenticated test user"def accessToken = authenticate(@@ -386,15 +381,11 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraithen: "access should be forbidden"ex = thrown()ex.response.status == 403-- cleanup: "the server should be stopped"- stopContainer(container)}def "Access assets as testuser2"() {given: "the server container is started"- def serverPort = findEphemeralPort()- def container = startContainer(defaultConfig(serverPort), defaultServices())+ def container = startContainer(defaultConfig(), defaultServices())def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)@@ -529,18 +520,14 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraithen: "access should be forbidden"ex = thrown()ex.response.status == 403-- cleanup: "the server should be stopped"- stopContainer(container)}def "Access assets as testuser3"() {given: "the server container is started"- def serverPort = findEphemeralPort()- def container = startContainer(defaultConfig(serverPort), defaultServices())+ def container = startContainer(defaultConfig(), defaultServices())def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)- def conditions = new PollingConditions(delay: 1, timeout: 5)+ def conditions = new PollingConditions(delay: 0.2, timeout: 5)and: "an authenticated test user"def accessToken = authenticate(@@ -895,8 +882,5 @@ class AssetPermissionsTest extends Specification implements ManagerContainerTraiassert testAsset.getAttribute("myCustomAttribute").get().getMetaItems(LABEL.getUrn())[0].getValue().get() == Values.create("Label1")assert testAsset.getAttribute("myCustomAttribute").get().getMetaItems(LABEL.getUrn())[1].getValue().get() == Values.create("Label2")assert testAsset.getAttribute("myCustomAttribute").get().getMetaItems(LABEL.getUrn())[2].getValue().get() == Values.create("Label3")-- cleanup: "the server should be stopped"- stopContainer(container)}}diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetProcessingTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetProcessingTest.groovyindex e8641daf1..d7bb06758 100644--- a/test/src/test/groovy/org/openremote/test/assets/AssetProcessingTest.groovy+++ b/test/src/test/groovy/org/openremote/test/assets/AssetProcessingTest.groovy@@ -29,7 +29,7 @@ class AssetProcessingTest extends Specification implements ManagerContainerTraitdef "Check processing of asset updates through the processing chain"() {given: "expected conditions"- def conditions = new PollingConditions(timeout: 10, delay: 1)+ def conditions = new PollingConditions(timeout: 10, delay: 0.2)and: "a mock protocol"def mockProtocolName = "urn:myCustom:mockProtocol"@@ -144,8 +144,7 @@ class AssetProcessingTest extends Specification implements ManagerContainerTrait}when: "the container is started with the mock protocol and consumers"- def serverPort = findEphemeralPort()- def container = startContainer(defaultConfig(serverPort), defaultServices(mockProtocol))+ def container = startContainer(defaultConfig(), defaultServices(mockProtocol))def assetStorageService = container.getService(AssetStorageService.class)def assetProcessingService = container.getService(AssetProcessingService.class)def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)@@ -302,7 +301,5 @@ class AssetProcessingTest extends Specification implements ManagerContainerTraitassert sendToActuatorEvents.size() == 0}- cleanup: "the server should be stopped"- stopContainer(container)}}diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetPublicQueryTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetPublicQueryTest.groovyindex a53f6a46b..ea7559c92 100644--- a/test/src/test/groovy/org/openremote/test/assets/AssetPublicQueryTest.groovy+++ b/test/src/test/groovy/org/openremote/test/assets/AssetPublicQueryTest.groovy@@ -25,8 +25,6 @@ import static org.openremote.model.query.AssetQuery.Selectclass AssetPublicQueryTest extends Specification implements ManagerContainerTrait {- @Shared- static Container container@Sharedstatic ManagerDemoSetup managerDemoSetup@Shared@@ -42,8 +40,7 @@ class AssetPublicQueryTest extends Specification implements ManagerContainerTraidef setupSpec() {given: "the server container is started"- def serverPort = findEphemeralPort()- container = startContainer(defaultConfig(serverPort), defaultServices())+ def container = startContainer(defaultConfig(), defaultServices())managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)assetStorageService = container.getService(AssetStorageService.class)@@ -70,11 +67,6 @@ class AssetPublicQueryTest extends Specification implements ManagerContainerTrai}}- def cleanupSpec() {- given: "the server should be stopped"- stopContainer(container)- }-def "Query public assets"() {expect: "10 public assets to have been created"diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovyindex e13b2def4..95c566c82 100644--- a/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy+++ b/test/src/test/groovy/org/openremote/test/assets/AssetQueryTest.groovy@@ -1,6 +1,6 @@package org.openremote.test.assets-import org.openremote.container.Container+import org.openremote.container.persistence.PersistenceServiceimport org.openremote.manager.asset.AssetProcessingServiceimport org.openremote.manager.asset.AssetStorageService@@ -44,8 +44,6 @@ import static org.openremote.model.query.AssetQuery.Select.selectExcludePathAndAclass AssetQueryTest extends Specification implements ManagerContainerTrait {- @Shared- static Container container@Sharedstatic ManagerDemoSetup managerDemoSetup@Shared@@ -59,8 +57,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {def setupSpec() {given: "the server container is started"- def serverPort = findEphemeralPort()- container = startContainer(defaultConfig(serverPort), defaultServices())+ def container = startContainer(defaultConfig(), defaultServices())managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)assetStorageService = container.getService(AssetStorageService.class)@@ -68,11 +65,6 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {persistenceService = container.getService(PersistenceService.class)}- def cleanupSpec() {- given: "the server should be stopped"- stopContainer(container)- }-def "Query assets 1"() {when: "an agent filtering query is executed"@@ -172,37 +164,36 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {then: "result should contain only basic info and attribute names"assets.size() == 13- assets[0].id == managerDemoSetup.smartBuildingId- assets[0].name == "Smart Building"- assets[1].id == managerDemoSetup.apartment1Id- assets[1].name == "Apartment 1"- assets[1].type == AssetType.RESIDENCE.getType()- assets[1].createdOn != null- assets[1].parentId == managerDemoSetup.smartBuildingId- assets[1].parentName == null- assets[1].parentType == null- assets[1].realm == managerDemoSetup.realmBuildingTenant- assets[1].path == null- assets[1].getAttributesList().size() == 7- assets[1].getAttribute("ventilationAuto").isPresent()- assets[1].getAttribute("ventilationLevel").isPresent()- assets[1].getAttribute("alarmEnabled").isPresent()- assets[1].getAttribute("vacationUntil").isPresent()- assets[1].getAttribute("lastExecutedScene").isPresent()- assets[1].getAttribute("presenceDetected").isPresent()- assets[1].getAttribute("location").isPresent()- assets[1].getAttribute("alarmEnabled").get().meta.size() == 0- assets[2].id == managerDemoSetup.apartment1ServiceAgentId- assets[3].id == managerDemoSetup.apartment1LivingroomId- assets[4].id == managerDemoSetup.apartment1KitchenId- assets[5].id == managerDemoSetup.apartment1HallwayId- assets[6].id == managerDemoSetup.apartment1Bedroom1Id- assets[7].id == managerDemoSetup.apartment1BathroomId- assets[8].id == managerDemoSetup.apartment2Id- assets[9].id == managerDemoSetup.apartment2LivingroomId- assets[10].id == managerDemoSetup.apartment2BathroomId- assets[11].id == managerDemoSetup.apartment3Id- assets[12].id == managerDemoSetup.apartment3LivingroomId+ assets.find {it.id == managerDemoSetup.smartBuildingId}.name == "Smart Building"+ def apartment1 = assets.find {it.id == managerDemoSetup.apartment1Id}+ apartment1.name == "Apartment 1"+ apartment1.type == AssetType.RESIDENCE.getType()+ apartment1.createdOn != null+ apartment1.parentId == managerDemoSetup.smartBuildingId+ apartment1.parentName == null+ apartment1.parentType == null+ apartment1.realm == managerDemoSetup.realmBuildingTenant+ apartment1.path == null+ apartment1.getAttributesList().size() == 7+ apartment1.getAttribute("ventilationAuto").isPresent()+ apartment1.getAttribute("ventilationLevel").isPresent()+ apartment1.getAttribute("alarmEnabled").isPresent()+ apartment1.getAttribute("vacationUntil").isPresent()+ apartment1.getAttribute("lastExecutedScene").isPresent()+ apartment1.getAttribute("presenceDetected").isPresent()+ apartment1.getAttribute("location").isPresent()+ apartment1.getAttribute("alarmEnabled").get().meta.size() == 0+ assets.find {it.id == managerDemoSetup.apartment1ServiceAgentId} != null+ assets.find {it.id == managerDemoSetup.apartment1LivingroomId} != null+ assets.find {it.id == managerDemoSetup.apartment1KitchenId} != null+ assets.find {it.id == managerDemoSetup.apartment1HallwayId} != null+ assets.find {it.id == managerDemoSetup.apartment1Bedroom1Id} != null+ assets.find {it.id == managerDemoSetup.apartment1BathroomId} != null+ assets.find {it.id == managerDemoSetup.apartment2Id} != null+ assets.find {it.id == managerDemoSetup.apartment2LivingroomId} != null+ assets.find {it.id == managerDemoSetup.apartment2BathroomId} != null+ assets.find {it.id == managerDemoSetup.apartment3Id} != null+ assets.find {it.id == managerDemoSetup.apartment3LivingroomId} != nullwhen: "an asset is loaded by identifier through JPA"def asset = persistenceService.doReturningTransaction(new Function<EntityManager, Asset>() {@@ -214,7 +205,6 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {then: "result should match (and some values should be empty because we need an AssetQuery to get them)"asset.id == managerDemoSetup.apartment1Id- asset.version == 1asset.createdOn.time < System.currentTimeMillis()asset.name == "Apartment 1"asset.wellKnownType == AssetType.RESIDENCE@@ -236,7 +226,6 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {then: "result should match"asset.id == managerDemoSetup.smartOfficeId- asset.version == 0asset.createdOn.time < System.currentTimeMillis()asset.name == "Smart Office"asset.wellKnownType == AssetType.BUILDING@@ -255,7 +244,6 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {then: "result should match"asset.id == managerDemoSetup.smartOfficeId- asset.version == 0asset.createdOn.time < System.currentTimeMillis()asset.name == "Smart Office"asset.wellKnownType == AssetType.BUILDING@@ -278,7 +266,6 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {then: "result should match"assets.size() == 1assets.get(0).id == managerDemoSetup.smartOfficeId- assets.get(0).version == 0assets.get(0).createdOn.time < System.currentTimeMillis()assets.get(0).name == "Smart Office"assets.get(0).wellKnownType == AssetType.BUILDING@@ -299,7 +286,6 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {then: "result should match"assets.size() == 1assets.get(0).id == managerDemoSetup.smartOfficeId- assets.get(0).version == 0assets.get(0).createdOn.time < System.currentTimeMillis()assets.get(0).name == "Smart Office"assets.get(0).wellKnownType == AssetType.BUILDING@@ -382,13 +368,13 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {then: "result should match"assets.size() == 7- assets.get(0).id == managerDemoSetup.apartment1Id- assets.get(1).id == managerDemoSetup.apartment1ServiceAgentId- assets.get(2).id == managerDemoSetup.apartment1LivingroomId- assets.get(3).id == managerDemoSetup.apartment1KitchenId- assets.get(4).id == managerDemoSetup.apartment1HallwayId- assets.get(5).id == managerDemoSetup.apartment1Bedroom1Id- assets.get(6).id == managerDemoSetup.apartment1BathroomId+ assets.find {it.id == managerDemoSetup.apartment1Id} != null+ assets.find {it.id == managerDemoSetup.apartment1ServiceAgentId} != null+ assets.find {it.id == managerDemoSetup.apartment1LivingroomId} != null+ assets.find {it.id == managerDemoSetup.apartment1KitchenId} != null+ assets.find {it.id == managerDemoSetup.apartment1HallwayId} != null+ assets.find {it.id == managerDemoSetup.apartment1Bedroom1Id} != null+ assets.find {it.id == managerDemoSetup.apartment1BathroomId} != nullwhen: "a query is executed"assets = assetStorageService.findAll(@@ -400,11 +386,11 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {then: "result should match"assets.size() == 5- assets.get(0).id == managerDemoSetup.apartment1LivingroomId- assets.get(1).id == managerDemoSetup.apartment1KitchenId- assets.get(2).id == managerDemoSetup.apartment1HallwayId- assets.get(3).id == managerDemoSetup.apartment1Bedroom1Id- assets.get(4).id == managerDemoSetup.apartment1BathroomId+ assets.find {it.id == managerDemoSetup.apartment1LivingroomId} != null+ assets.find {it.id == managerDemoSetup.apartment1KitchenId} != null+ assets.find {it.id == managerDemoSetup.apartment1HallwayId} != null+ assets.find {it.id == managerDemoSetup.apartment1Bedroom1Id} != null+ assets.find {it.id == managerDemoSetup.apartment1BathroomId} != nullwhen: "a query is executed"assets = assetStorageService.findAll(@@ -415,17 +401,18 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {then: "result should match"assets.size() == 6- assets.get(0).id == managerDemoSetup.apartment1Id- assets.get(1).id == managerDemoSetup.apartment1LivingroomId- assets.get(1).getAttributesList().size() == 7- !assets.get(1).getAttribute("currentTemperature").get().getValue().isPresent()- assets.get(1).getAttribute("currentTemperature").get().meta.size() == 7- !assets.get(1).getAttribute("targetTemperature").get().getValue().isPresent()- assets.get(1).getAttribute("targetTemperature").get().meta.size() == 6- assets.get(2).id == managerDemoSetup.apartment1KitchenId- assets.get(3).id == managerDemoSetup.apartment1HallwayId- assets.get(4).id == managerDemoSetup.apartment1Bedroom1Id- assets.get(5).id == managerDemoSetup.apartment1BathroomId+ assets.find {it.id == managerDemoSetup.apartment1Id} != null+ def livingroom = assets.find {it.id == managerDemoSetup.apartment1LivingroomId}+ livingroom != null+ livingroom.getAttributesList().size() == 7+ !livingroom.getAttribute("currentTemperature").get().getValue().isPresent()+ livingroom.getAttribute("currentTemperature").get().meta.size() == 7+ !livingroom.getAttribute("targetTemperature").get().getValue().isPresent()+ livingroom.getAttribute("targetTemperature").get().meta.size() == 6+ assets.find {it.id == managerDemoSetup.apartment1KitchenId} != null+ assets.find {it.id == managerDemoSetup.apartment1HallwayId} != null+ assets.find {it.id == managerDemoSetup.apartment1Bedroom1Id} != null+ assets.find {it.id == managerDemoSetup.apartment1BathroomId} != nullwhen: "a query is executed"assets = assetStorageService.findAll(@@ -461,9 +448,9 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {then: "result should match"assets.size() == 3- assets.get(0).id == managerDemoSetup.agentId- assets.get(1).id == managerDemoSetup.apartment1ServiceAgentId- assets.get(2).id == managerDemoSetup.smartCityServiceAgentId+ assets.find {it.id == managerDemoSetup.agentId} != null+ assets.find {it.id == managerDemoSetup.apartment1ServiceAgentId} != null+ assets.find {it.id == managerDemoSetup.smartCityServiceAgentId} != nullwhen: "a query is executed"assets = assetStorageService.findAll(@@ -627,7 +614,6 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {then: "result should match"asset.id == managerDemoSetup.apartment1LivingroomId- asset.version == 0asset.createdOn.time < System.currentTimeMillis()asset.name == "Living Room 1"asset.wellKnownType == AssetType.ROOM@@ -654,7 +640,6 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {then: "result should contain only matches that are protected"asset.id == managerDemoSetup.apartment1LivingroomId- asset.version == 0asset.createdOn.time < System.currentTimeMillis()asset.name == "Living Room 1"asset.wellKnownType == AssetType.ROOM@@ -757,7 +742,7 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {def "Location queries"() {given: "polling conditions"- def conditions = new PollingConditions(timeout: 10, delay: 1)+ def conditions = new PollingConditions(timeout: 10, delay: 0.2)when: "a location filtering query is executed"def assets = assetStorageService.findAll(@@ -770,16 +755,11 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {then: "assets in the queried region should be retrieved"assets.size() == 5- assets[0].id == managerDemoSetup.agentId- assets[0].name == "Demo Agent"- assets[1].id == managerDemoSetup.thingId- assets[1].name == "Demo Thing"- assets[2].id == managerDemoSetup.groundFloorId- assets[2].name == "Ground Floor"- assets[3].id == managerDemoSetup.lobbyId- assets[3].name == "Lobby"- assets[4].id == managerDemoSetup.smartOfficeId- assets[4].name == "Smart Office"+ assets.find {it.id == managerDemoSetup.agentId}.name == "Demo Agent"+ assets.find {it.id == managerDemoSetup.thingId}.name == "Demo Thing"+ assets.find {it.id == managerDemoSetup.groundFloorId}.name == "Ground Floor"+ assets.find {it.id == managerDemoSetup.lobbyId}.name == "Lobby"+ assets.find {it.id == managerDemoSetup.smartOfficeId}.name == "Smart Office"when: "one of the assets in the region is moved"def lobby = assetStorageService.find(managerDemoSetup.lobbyId, true)@@ -815,16 +795,11 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {then: "all 5 assets should be returned"assets.size() == 5- assets[0].id == managerDemoSetup.agentId- assets[0].name == "Demo Agent"- assets[1].id == managerDemoSetup.thingId- assets[1].name == "Demo Thing"- assets[2].id == managerDemoSetup.groundFloorId- assets[2].name == "Ground Floor"- assets[3].id == managerDemoSetup.lobbyId- assets[3].name == "Lobby"- assets[4].id == managerDemoSetup.smartOfficeId- assets[4].name == "Smart Office"+ assets.find {it.id == managerDemoSetup.agentId}.name == "Demo Agent"+ assets.find {it.id == managerDemoSetup.thingId}.name == "Demo Thing"+ assets.find {it.id == managerDemoSetup.groundFloorId}.name == "Ground Floor"+ assets.find {it.id == managerDemoSetup.lobbyId}.name == "Lobby"+ assets.find {it.id == managerDemoSetup.smartOfficeId}.name == "Smart Office"when: "a rectangular region is used that doesn't cover any assets"assets = assetStorageService.findAll(@@ -849,21 +824,16 @@ class AssetQueryTest extends Specification implements ManagerContainerTrait {then: "all 5 realm assets should be returned"assets.size() == 5- assets[0].id == managerDemoSetup.agentId- assets[0].name == "Demo Agent"- assets[1].id == managerDemoSetup.thingId- assets[1].name == "Demo Thing"- assets[2].id == managerDemoSetup.groundFloorId- assets[2].name == "Ground Floor"- assets[3].id == managerDemoSetup.lobbyId- assets[3].name == "Lobby"- assets[4].id == managerDemoSetup.smartOfficeId- assets[4].name == "Smart Office"+ assets.find {it.id == managerDemoSetup.agentId}.name == "Demo Agent"+ assets.find {it.id == managerDemoSetup.thingId}.name == "Demo Thing"+ assets.find {it.id == managerDemoSetup.groundFloorId}.name == "Ground Floor"+ assets.find {it.id == managerDemoSetup.lobbyId}.name == "Lobby"+ assets.find {it.id == managerDemoSetup.smartOfficeId}.name == "Smart Office"}def "Calendar queries"() {given: "polling conditions"- def conditions = new PollingConditions(timeout: 10, delay: 1)+ def conditions = new PollingConditions(timeout: 10, delay: 0.2)when: "an asset is given a calendar event configuration attribute"def lobby = assetStorageService.find(managerDemoSetup.lobbyId, true)diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetUserLinkingTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetUserLinkingTest.groovyindex 11d707691..90c02f26f 100644--- a/test/src/test/groovy/org/openremote/test/assets/AssetUserLinkingTest.groovy+++ b/test/src/test/groovy/org/openremote/test/assets/AssetUserLinkingTest.groovy@@ -21,8 +21,7 @@ class AssetUserLinkingTest extends Specification implements ManagerContainerTraidef "Link assets and users as superuser"() {given: "the server container is started"- def serverPort = findEphemeralPort()- def container = startContainer(defaultConfig(serverPort), defaultServices())+ def container = startContainer(defaultConfig(), defaultServices())def timerService = container.getService(TimerService.class)def identityService = container.getService(ManagerIdentityService.class)def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)@@ -171,7 +170,7 @@ class AssetUserLinkingTest extends Specification implements ManagerContainerTraiit.assetName == "Apartment 2" &&it.parentAssetName == "Smart Building" &&it.userFullName == "testuser2 (DemoA2 DemoLast)" &&- it.createdOn.time < timerService.currentTimeMillis+ it.createdOn.time <= timerService.currentTimeMillis}when: "an asset link is deleted"@@ -180,9 +179,6 @@ class AssetUserLinkingTest extends Specification implements ManagerContainerTraithen: "result should match"userAssets.length == 0-- cleanup: "the server should be stopped"- stopContainer(container)}}diff --git a/test/src/test/groovy/org/openremote/test/assets/AssetsActivityTest.groovy b/test/src/test/groovy/org/openremote/test/assets/AssetsActivityTest.groovydeleted file mode 100644index 381f7e34a..000000000--- a/test/src/test/groovy/org/openremote/test/assets/AssetsActivityTest.groovy+++ /dev/null@@ -1,70 +0,0 @@-package org.openremote.test.assets--class AssetsActivityTest-{/* TODO remove outdated test- extends Specification implements ContainerTrait {-- def "Send/receive hello messages"() {- given: "The fake client environment"- def placeController = Mock(PlaceController)- def activityContainer = Mock(AcceptsOneWidget)- def activityBus = new EventBus()- def activityRegistrations = []- def result = new BlockingVariables(5)-- and: "the server container is started"- def serverPort = findEphemeralPort();- def container = startContainer(defaultConfig(serverPort), defaultServices())-- and: "an authenticated user"- def realm = MASTER_REALM;- def accessTokenResponse = authenticate(container, realm, MANAGER_CLIENT_ID, "test", "test")-- and: "a test client target"- def client = createClient(container).build();- def serverUri = serverUri(serverPort).build();- def websocketContainer = createWebsocketContainer();- def clientTarget = WebClient.getTarget(client, serverUri);-- and: "a connected messaging client"- def eventEndpoint = new ContainerTrait.EventEndpoint(activityBus, container.JSON);- connect(- websocketContainer,- eventEndpoint,- clientTarget,- realm,- accessTokenResponse.getToken(),- EventService.WEBSOCKET_EVENTS- )-- and: "the view, resource, and activity"- def assetDetailView = Mock(AssetsView) {- setMessageText(_) >> { String value ->- result.messageText = value;- }- }-- def assetDetailActivity = new AssetsActivity(- assetDetailView, placeController, activityBus- )-- when: "the activity is started"- assetDetailActivity.start(activityContainer, activityBus, activityRegistrations)-- then: "the view should have the activity set as presenter"- 1 * assetDetailView.setPresenter(assetDetailActivity)-- when: "the client sends a message"- assetDetailActivity.sendMessage()-- then: "the server should send a message"- result.messageText.startsWith("Hello from server, the time is")-- and: "the messaging should be closed so we don't get an ugly termination exception on the server"- eventEndpoint.close()-- and: "the server should be stopped"- stopContainer(container);- }-*/-}diff --git a/test/src/test/groovy/org/openremote/test/console/ConsoleTest.groovy b/test/src/test/groovy/org/openremote/test/console/ConsoleTest.groovyindex 03841bd89..07f53aff4 100644--- a/test/src/test/groovy/org/openremote/test/console/ConsoleTest.groovy+++ b/test/src/test/groovy/org/openremote/test/console/ConsoleTest.groovy@@ -1,9 +1,10 @@package org.openremote.test.console-import com.google.common.collect.Lists+import com.google.firebase.messaging.Messageimport org.openremote.container.util.UniqueIdentifierGeneratorimport org.openremote.manager.asset.AssetStorageService+import org.openremote.manager.notification.NotificationServiceimport org.openremote.manager.notification.PushNotificationHandlerimport org.openremote.manager.rules.RulesEngineimport org.openremote.manager.rules.RulesService@@ -36,9 +37,10 @@ import spock.lang.Specificationimport spock.util.concurrent.PollingConditionsimport javax.ws.rs.WebApplicationException+import java.util.concurrent.TimeUnitimport java.util.stream.IntStream-import static org.openremote.manager.setup.builtin.ManagerDemoSetup.DEMO_RULE_STATES_CUSTOMER_A+import static org.openremote.manager.setup.builtin.ManagerDemoSetup.DEMO_RULE_STATES_SMART_BUILDINGimport static org.openremote.manager.setup.builtin.ManagerDemoSetup.SMART_BUILDING_LOCATIONimport static org.openremote.model.Constants.KEYCLOAK_CLIENT_IDimport static org.openremote.model.asset.AssetResource.Util.WRITE_ATTRIBUTE_HTTP_METHOD@@ -57,11 +59,23 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {def targetIds = []def messages = []- given: "a mock push notification handler"- PushNotificationHandler mockPushNotificationHandler = Spy(PushNotificationHandler) {- isValid() >> true+ given: "the container environment is started"+ def conditions = new PollingConditions(timeout: 20, delay: 0.2)+ ORConsoleGeofenceAssetAdapter.NOTIFY_ASSETS_DEBOUNCE_MILLIS = 100+ ORConsoleGeofenceAssetAdapter.NOTIFY_ASSETS_BATCH_MILLIS = 200+ def container = startContainer(defaultConfig(), defaultServices())+ def pushNotificationHandler = container.getService(PushNotificationHandler.class)+ def notificationService = container.getService(NotificationService.class)+ def assetStorageService = container.getService(AssetStorageService.class)+ def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)+ def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)+ def rulesService = container.getService(RulesService.class)+ def rulesetStorageService = container.getService(RulesetStorageService.class)- sendMessage(_ as Long, _ as Notification.Source, _ as String, _ as Notification.Target, _ as AbstractNotificationMessage) >> {+ and: "a mock push notification handler is injected"+ PushNotificationHandler mockPushNotificationHandler = Spy(pushNotificationHandler)+ mockPushNotificationHandler.isValid() >> true+ mockPushNotificationHandler.sendMessage(_ as Long, _ as Notification.Source, _ as String, _ as Notification.Target, _ as AbstractNotificationMessage) >> {id, source, sourceId, target, message ->notificationIds << idtargetTypes << target.type@@ -69,26 +83,12 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {messages << messagecallRealMethod()}-- // Assume sent to FCM- sendMessage(_ as Message) >> {+ // Assume sent to FCM+ mockPushNotificationHandler.sendMessage(_ as Message) >> {message -> return NotificationSendResult.success()}- }+ notificationService.notificationHandlerMap.put(pushNotificationHandler.getTypeName(), mockPushNotificationHandler)- and: "the container environment is started with the mock handler"- def conditions = new PollingConditions(timeout: 20, delay: 1)- def serverPort = findEphemeralPort()- ORConsoleGeofenceAssetAdapter.NOTIFY_ASSETS_DEBOUNCE_MILLIS = 100- ORConsoleGeofenceAssetAdapter.NOTIFY_ASSETS_BATCH_MILLIS = 200- def services = Lists.newArrayList(defaultServices())- services.replaceAll{it instanceof PushNotificationHandler ? mockPushNotificationHandler : it}- def container = startContainer(defaultConfig(serverPort), services)- def assetStorageService = container.getService(AssetStorageService.class)- def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)- def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)- def rulesService = container.getService(RulesService.class)- def rulesetStorageService = container.getService(RulesetStorageService.class)def geofenceAdapter = (ORConsoleGeofenceAssetAdapter) rulesService.geofenceAssetAdapters.find {it.name == "ORConsole"}@@ -107,7 +107,7 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {def tenantBuildingEngine = rulesService.tenantEngines.get(keycloakDemoSetup.tenantBuilding.realm)assert tenantBuildingEngine != nullassert tenantBuildingEngine.isRunning()- assert tenantBuildingEngine.assetStates.size() == DEMO_RULE_STATES_CUSTOMER_A+ assert tenantBuildingEngine.assetStates.size() == DEMO_RULE_STATES_SMART_BUILDING}and: "an authenticated user"@@ -389,7 +389,10 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {timestamp = asset.getAttribute(LOCATION.attributeName).flatMap { it.valueTimestamp }.orElse(Long.MAX_VALUE)}- when: "a console's location is updated to be at the Smart Building again"+ when: "time advances"+ advancePseudoClock(1, TimeUnit.SECONDS, container)++ and: "a console's location is updated to be at the Smart Building again"authenticatedAssetResource.writeAttributeValue(null, testUser3Console2.id, LOCATION.attributeName, SMART_BUILDING_LOCATION.toValue().toJson())then: "no more alerts should have been sent"@@ -401,7 +404,10 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {assert notificationIds.size() == 1}- when: "a console's location is updated to be null"+ when: "time advances"+ advancePseudoClock(1, TimeUnit.SECONDS, container)++ and: "a console's location is updated to be null"authenticatedAssetResource.writeAttributeValue(null, testUser3Console2.id, LOCATION.attributeName, "null")then: "no more alerts should have been sent and the welcome reset rule should have fired on the tenant rule engine"@@ -416,7 +422,11 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {assert !tenantBuildingEngine.facts.getOptional("welcomeHome_${testUser3Console2.id}").isPresent()}- when: "a console's location is updated to be at the Smart Building again"++ when: "time advances"+ advancePseudoClock(1, TimeUnit.SECONDS, container)++ and: "a console's location is updated to be at the Smart Building again"authenticatedAssetResource.writeAttributeValue(null, testUser3Console2.id, LOCATION.attributeName, SMART_BUILDING_LOCATION.toValue().toJson())then: "another alert should have been sent"@@ -671,7 +681,7 @@ class ConsoleTest extends Specification implements ManagerContainerTrait {assert geofences.size() == 0}- cleanup: "the server should be stopped"- stopContainer(container)+ cleanup: "the mock is removed"+ notificationService.notificationHandlerMap.put(pushNotificationHandler.getTypeName(), pushNotificationHandler)}}diff --git a/test/src/test/groovy/org/openremote/test/event/ClientEventTest.groovy b/test/src/test/groovy/org/openremote/test/event/ClientEventTest.groovydeleted file mode 100644index 73a5d02ca..000000000--- a/test/src/test/groovy/org/openremote/test/event/ClientEventTest.groovy+++ /dev/null@@ -1,236 +0,0 @@-/*- * Copyright 2017, OpenRemote Inc.- *- * See the CONTRIBUTORS.txt file in the distribution for a- * full listing of individual contributors.- *- * This program is free software: you can redistribute it and/or modify- * it under the terms of the GNU Affero General Public License as- * published by the Free Software Foundation, either version 3 of the- * License, or (at your option) any later version.- *- * This program is distributed in the hope that it will be useful,- * but WITHOUT ANY WARRANTY; without even the implied warranty of- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the- * GNU Affero General Public License for more details.- *- * You should have received a copy of the GNU Affero General Public License- * along with this program. If not, see <http://www.gnu.org/licenses/>.- */-package org.openremote.test.event--import org.openremote.manager.agent.AgentService-import org.openremote.manager.asset.AssetProcessingService-import org.openremote.manager.asset.AssetStorageService-import org.openremote.manager.setup.SetupService-import org.openremote.manager.setup.builtin.ManagerDemoSetup-import org.openremote.model.asset.AssetFilter-import org.openremote.model.attribute.MetaItemType-import org.openremote.model.asset.agent.AgentStatusEvent-import org.openremote.model.asset.agent.ConnectionStatus-import org.openremote.model.attribute.AttributeEvent-import org.openremote.model.attribute.AttributeRef-import org.openremote.model.attribute.MetaItem-import org.openremote.model.event.shared.EventSubscription-import org.openremote.model.event.shared.SharedEvent-import org.openremote.model.geo.GeoJSONPoint-import org.openremote.model.value.Values-import org.openremote.test.ClientEventService-import org.openremote.test.GwtClientTrait-import org.openremote.test.ManagerContainerTrait-import spock.lang.Specification-import spock.util.concurrent.PollingConditions--import static org.openremote.container.util.MapAccess.getString-import static org.openremote.manager.event.ClientEventService.CLIENT_EVENT_QUEUE-import static org.openremote.manager.event.ClientEventService.WEBSOCKET_EVENTS-import static org.openremote.manager.security.ManagerIdentityProvider.SETUP_ADMIN_PASSWORD-import static org.openremote.manager.security.ManagerIdentityProvider.SETUP_ADMIN_PASSWORD_DEFAULT-import static org.openremote.model.Constants.*-import static org.openremote.model.attribute.MetaItem.isMetaNameEqualTo--/**- * This tests client event subscription and publishing.- */-// TODO: Add publishing tests-class ClientEventTest extends Specification implements ManagerContainerTrait, GwtClientTrait {-- def "Event subscription"() {-- given: "expected conditions"- def conditions = new PollingConditions(timeout: 10, delay: 1)-- and: "the container is started"- def serverPort = findEphemeralPort()- def container = startContainer(defaultConfig(serverPort), defaultServices())- def assetStorageService = container.getService(AssetStorageService.class)- def assetProcessingService = container.getService(AssetProcessingService.class)- def agentService = container.getService(AgentService.class)- def internalClientEventService = container.getService(org.openremote.manager.event.ClientEventService.class)- def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)-- expect: "all client events happening during startup to be consumed"- noPendingExchangesOnMessageEndpoint(container, CLIENT_EVENT_QUEUE)-- when: "a client websocket connection and attached event bus and service"- def accessToken = {- authenticate(- container,- MASTER_REALM,- KEYCLOAK_CLIENT_ID,- MASTER_REALM_ADMIN_USER,- getString(container.getConfig(), SETUP_ADMIN_PASSWORD, SETUP_ADMIN_PASSWORD_DEFAULT)- ).token- }- List<SharedEvent> collectedSharedEvents = []- def eventBus = createEventBus(collectedSharedEvents)- def clientEventService = new ClientEventService(eventBus, container.JSON)- def websocketSession = connect(createWebsocketClient(), clientEventService.endpoint, serverUri(serverPort), WEBSOCKET_EVENTS, MASTER_REALM, accessToken.call())-- and: "a subscription is made to the agent status event"- clientEventService.subscribe(AgentStatusEvent.class)-- and: "an existing protocol configuration is disabled"- def agent = assetStorageService.find(managerDemoSetup.agentId, true)- agent.getAttribute(managerDemoSetup.agentProtocolConfigName).get().addMeta(- new MetaItem(MetaItemType.DISABLED)- )- agent = assetStorageService.merge(agent)-- then: "the agent status change event should have been received"- conditions.eventually {- assert collectedSharedEvents.size() == 3- assert collectedSharedEvents[0] instanceof AgentStatusEvent- assert (collectedSharedEvents[0] as AgentStatusEvent).protocolConfiguration.entityId == managerDemoSetup.agentId- assert (collectedSharedEvents[0] as AgentStatusEvent).protocolConfiguration.attributeName == managerDemoSetup.agentProtocolConfigName- assert (collectedSharedEvents[0] as AgentStatusEvent).connectionStatus == ConnectionStatus.DISCONNECTED- assert collectedSharedEvents[1] instanceof AgentStatusEvent- assert (collectedSharedEvents[1] as AgentStatusEvent).protocolConfiguration.entityId == managerDemoSetup.agentId- assert (collectedSharedEvents[1] as AgentStatusEvent).protocolConfiguration.attributeName == managerDemoSetup.agentProtocolConfigName- assert (collectedSharedEvents[1] as AgentStatusEvent).connectionStatus == ConnectionStatus.WAITING- assert collectedSharedEvents[2] instanceof AgentStatusEvent- assert (collectedSharedEvents[2] as AgentStatusEvent).protocolConfiguration.entityId == managerDemoSetup.agentId- assert (collectedSharedEvents[2] as AgentStatusEvent).protocolConfiguration.attributeName == managerDemoSetup.agentProtocolConfigName- assert (collectedSharedEvents[2] as AgentStatusEvent).connectionStatus == ConnectionStatus.DISABLED- }-- when: "the subscription is removed"- clientEventService.unsubscribe(AgentStatusEvent.class)- collectedSharedEvents.clear()-- and: "the existing protocol configuration is re-enabled"- agent.getAttribute(managerDemoSetup.agentProtocolConfigName).get().getMeta().removeIf(- isMetaNameEqualTo(MetaItemType.DISABLED)- )- agent = assetStorageService.merge(agent)-- then: "the protocol should be CONNECTED but no new events should have been received"- conditions.eventually {- assert agentService.getProtocolConnectionStatus(- new AttributeRef(managerDemoSetup.agentId, managerDemoSetup.agentProtocolConfigName)- ) == ConnectionStatus.CONNECTED- assert collectedSharedEvents.isEmpty()- }-- when: "a subscription is made to the attribute event"- clientEventService.subscribe(AttributeEvent.class, new AssetFilter().setAssetIds(managerDemoSetup.thingId))-- and: "an assets location is changed"- def asset = assetStorageService.find(managerDemoSetup.thingId, true)- asset.setCoordinates(new GeoJSONPoint(120.1d, 50.43d))- asset = assetStorageService.merge(asset)-- then: "the attribute event should have been received"- conditions.eventually {- assert collectedSharedEvents.size() == 1- assert collectedSharedEvents[0] instanceof AttributeEvent- assert (collectedSharedEvents[0] as AttributeEvent).entityId == managerDemoSetup.thingId- assert (collectedSharedEvents[0] as AttributeEvent).value.flatMap{GeoJSONPoint.fromValue(it)}.map{it.x}.orElse(null) == 120.1d- assert (collectedSharedEvents[0] as AttributeEvent).value.flatMap{GeoJSONPoint.fromValue(it)}.map{it.y}.orElse(null) == 50.43d- }-- when: "the assets location is set to null"- asset.setCoordinates(null)- asset = assetStorageService.merge(asset)-- then: "the attribute event should have been received with null coordinates"- conditions.eventually {- assert collectedSharedEvents.size() == 2- assert collectedSharedEvents[1] instanceof AttributeEvent- assert (collectedSharedEvents[1] as AttributeEvent).entityId == managerDemoSetup.thingId- assert !(collectedSharedEvents[1] as AttributeEvent).value.isPresent()- }-- when: "the location is changed"- asset.setCoordinates(new GeoJSONPoint(-10.11d, -50.233d))- asset = assetStorageService.merge(asset)-- then: "the attribute event should have been received"- conditions.eventually {- assert collectedSharedEvents.size() == 3- assert collectedSharedEvents[2] instanceof AttributeEvent- assert (collectedSharedEvents[2] as AttributeEvent).entityId == managerDemoSetup.thingId- assert (collectedSharedEvents[2] as AttributeEvent).value.flatMap{GeoJSONPoint.fromValue(it)}.map{it.x}.orElse(null) == -10.11d- assert (collectedSharedEvents[2] as AttributeEvent).value.flatMap{GeoJSONPoint.fromValue(it)}.map{it.y}.orElse(null) == -50.233d- }-- when: "the location is set with the same value"- asset.setCoordinates(new GeoJSONPoint(-10.11d, -50.233d))- asset = assetStorageService.merge(asset)-- then: "no location event should have been received"- Thread.sleep(300)- assert collectedSharedEvents.size() == 3-- when: "the subscription is removed"- clientEventService.unsubscribe(AttributeEvent.class)- collectedSharedEvents.clear()-- and: "a new attribute event subscription is added"- clientEventService.subscribe(AttributeEvent.class, new AssetFilter().setAssetIds(managerDemoSetup.thingId))-- and: "an internal attribute event subscription is made"- List<AttributeEvent> internalReceivedEvents = []- internalClientEventService.getEventSubscriptions().createOrUpdate(- ClientEventTest.class.getName(),- false,- new EventSubscription<>(- AttributeEvent.class,- new AssetFilter().setAssetIds(managerDemoSetup.thingId),- { triggeredEventSubscription ->- internalReceivedEvents.add(triggeredEventSubscription.events[0] as AttributeEvent)- }- ))-- and: "the subscribed asset is modified"- def currentValue = asset.getAttribute(managerDemoSetup.thingLightToggleAttributeName).get().getValueAsBoolean().get()- assetProcessingService.sendAttributeEvent(new AttributeEvent(- managerDemoSetup.thingId,- managerDemoSetup.thingLightToggleAttributeName,- Values.create(!currentValue)))-- // TODO: Only 1 attribute event should reach the subscribers below- then: "an attribute event should have been received by the internal subscriber"- conditions.eventually {- assert internalReceivedEvents.size() == 1- assert internalReceivedEvents[0].entityId == managerDemoSetup.thingId- assert internalReceivedEvents[0].attributeName == managerDemoSetup.thingLightToggleAttributeName- assert Values.getBoolean(internalReceivedEvents[0].value.get()).get() == !currentValue- }-- and: "an attribute event should have been received by the external subscriber"- conditions.eventually {- assert collectedSharedEvents.size() == 1- assert collectedSharedEvents[0] instanceof AttributeEvent- assert (collectedSharedEvents[0] as AttributeEvent).entityId == managerDemoSetup.thingId- assert (collectedSharedEvents[0] as AttributeEvent).attributeName == managerDemoSetup.thingLightToggleAttributeName- assert Values.getBoolean((collectedSharedEvents[0] as AttributeEvent).value.get()).get() == !currentValue- }-- cleanup: "the client should be stopped"- if (clientEventService != null) clientEventService.close()-- and: "the server should be stopped"- stopContainer(container)- }-}\ No newline at end of filediff --git a/test/src/test/groovy/org/openremote/test/failure/RulesExecutionFailureTest.groovy b/test/src/test/groovy/org/openremote/test/failure/RulesExecutionFailureTest.groovyindex f172f1517..414cebb7e 100644--- a/test/src/test/groovy/org/openremote/test/failure/RulesExecutionFailureTest.groovy+++ b/test/src/test/groovy/org/openremote/test/failure/RulesExecutionFailureTest.groovy@@ -21,9 +21,8 @@ class RulesExecutionFailureTest extends Specification implements ManagerContainedef "Rule condition invalid return"() {given: "the container environment is started"- def conditions = new PollingConditions(timeout: 20, delay: 1)- def serverPort = findEphemeralPort()- def container = startContainerWithPseudoClock(defaultConfig(serverPort), defaultServices())+ def conditions = new PollingConditions(timeout: 20, delay: 0.2)+ def container = startContainer(defaultConfig(), defaultServices())def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)def rulesService = container.getService(RulesService.class)def rulesetStorageService = container.getService(RulesetStorageService.class)@@ -48,17 +47,13 @@ class RulesExecutionFailureTest extends Specification implements ManagerContaineassert apartment2Engine.deployments[ruleset.id].error instanceof IllegalArgumentExceptionassert apartment2Engine.deployments[ruleset.id].error.message == "Error evaluating condition of rule 'The when condition is illegal, it's returning an Optional instead of a boolean': result is not boolean but Optional.empty"}-- cleanup: "stop the container"- stopContainer(container)}def "Rule condition throws exception"() {given: "the container environment is started"- def conditions = new PollingConditions(timeout: 20, delay: 1)- def serverPort = findEphemeralPort()- def container = startContainerWithPseudoClock(defaultConfig(serverPort), defaultServices())+ def conditions = new PollingConditions(timeout: 20, delay: 0.2)+ def container = startContainer(defaultConfig(), defaultServices())def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)def rulesService = container.getService(RulesService.class)def rulesetStorageService = container.getService(RulesetStorageService.class)@@ -83,17 +78,13 @@ class RulesExecutionFailureTest extends Specification implements ManagerContaineassert apartment2Engine.getError() instanceof RuntimeExceptionassert apartment2Engine.getError().message.startsWith("Ruleset deployments have errors, failed compilation: 0, failed execution: 1")}-- cleanup: "stop the container"- stopContainer(container)}def "Rule action throws exception"() {given: "the container environment is started"- def conditions = new PollingConditions(timeout: 20, delay: 1)- def serverPort = findEphemeralPort()- def container = startContainerWithPseudoClock(defaultConfig(serverPort), defaultServices())+ def conditions = new PollingConditions(timeout: 20, delay: 0.2)+ def container = startContainer(defaultConfig(), defaultServices())def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)def rulesService = container.getService(RulesService.class)def rulesetStorageService = container.getService(RulesetStorageService.class)@@ -118,17 +109,13 @@ class RulesExecutionFailureTest extends Specification implements ManagerContaineassert apartment2Engine.getError() instanceof RuntimeExceptionassert apartment2Engine.getError().message.startsWith("Ruleset deployments have errors, failed compilation: 0, failed execution: 1")}-- cleanup: "stop the container"- stopContainer(container)}def "Rule condition loops"() {given: "the container environment is started"- def conditions = new PollingConditions(timeout: 20, delay: 1)- def serverPort = findEphemeralPort()- def container = startContainerWithPseudoClock(defaultConfig(serverPort), defaultServices())+ def conditions = new PollingConditions(timeout: 20, delay: 0.2)+ def container = startContainer(defaultConfig(), defaultServices())def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)def rulesService = container.getService(RulesService.class)def rulesetStorageService = container.getService(RulesetStorageService.class)@@ -155,8 +142,5 @@ class RulesExecutionFailureTest extends Specification implements ManagerContaineassert apartment2Engine.getError().message.startsWith("Ruleset deployments have errors, failed compilation: 0, failed execution: 1")assert apartment2Engine.facts.triggerCount == 0 // Ensure trigger count is reset after execution}-- cleanup: "stop the container"- stopContainer(container)}}diff --git a/test/src/test/groovy/org/openremote/test/gateway/GatewayTest.groovy b/test/src/test/groovy/org/openremote/test/gateway/GatewayTest.groovyindex 19cb45076..73cd88f82 100644--- a/test/src/test/groovy/org/openremote/test/gateway/GatewayTest.groovy+++ b/test/src/test/groovy/org/openremote/test/gateway/GatewayTest.groovy@@ -4,12 +4,13 @@ import com.google.common.collect.Listsimport io.netty.channel.ChannelHandlerimport org.apache.http.client.utils.URIBuilderimport org.openremote.agent.protocol.http.HttpClientProtocol-import org.openremote.container.web.OAuthClientCredentialsGrantimport org.openremote.agent.protocol.io.AbstractNettyIoClientimport org.openremote.agent.protocol.simulator.SimulatorProtocolimport org.openremote.agent.protocol.websocket.WebsocketIoClientimport org.openremote.container.Container+import org.openremote.container.timer.TimerServiceimport org.openremote.container.util.UniqueIdentifierGenerator+import org.openremote.container.web.OAuthClientCredentialsGrantimport org.openremote.manager.asset.AssetProcessingServiceimport org.openremote.manager.asset.AssetStorageServiceimport org.openremote.manager.concurrent.ManagerExecutorService@@ -23,7 +24,6 @@ import org.openremote.manager.setup.builtin.ManagerDemoSetupimport org.openremote.model.asset.*import org.openremote.model.asset.agent.ConnectionStatusimport org.openremote.model.attribute.*-import org.openremote.model.event.Eventimport org.openremote.model.event.shared.EventRequestResponseWrapperimport org.openremote.model.event.shared.SharedEventimport org.openremote.model.gateway.GatewayClientResource@@ -36,6 +36,7 @@ import spock.lang.Specificationimport spock.util.concurrent.PollingConditionsimport java.util.concurrent.ScheduledFuture+import java.util.concurrent.TimeUnitimport java.util.concurrent.atomic.AtomicReferenceimport java.util.stream.Collectorsimport java.util.stream.IntStream@@ -51,20 +52,19 @@ class GatewayTest extends Specification implements ManagerContainerTrait {def "Gateway asset provisioning and local manager logic test"() {given: "the container environment is started"- def conditions = new PollingConditions(timeout: 10, delay: 1)- def serverPort = findEphemeralPort()- def container = startContainer(defaultConfig(serverPort), defaultServices())+ def conditions = new PollingConditions(timeout: 10, delay: 0.2)+ def container = startContainer(defaultConfig(), defaultServices())def assetProcessingService = container.getService(AssetProcessingService.class)def executorService = container.getService(ManagerExecutorService.class)+ def timerService = container.getService(TimerService.class)def assetStorageService = container.getService(AssetStorageService.class)def gatewayService = container.getService(GatewayService.class)def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)def identityProvider = container.getService(ManagerIdentityService.class).identityProvider as ManagerKeycloakIdentityProviderdef httpClientProtocol = container.getService(HttpClientProtocol.class)- expect: "the container should be running and initialised"+ expect: "the system should settle down"conditions.eventually {- assert container.isRunning()assert noEventProcessedIn(assetProcessingService, 300)}@@ -158,7 +158,7 @@ class GatewayTest extends Specification implements ManagerContainerTrait {new Asset(agentAssetIds[i-1],0L,- new Date(),+ Date.from(timerService.getNow()),"Test Agent $i",AssetType.AGENT.type,false,@@ -174,7 +174,7 @@ class GatewayTest extends Specification implements ManagerContainerTrait {new MetaItem(HttpClientProtocol.META_PROTOCOL_BASE_URI, Values.create("https://google.co.uk")),new MetaItem(HttpClientProtocol.META_PROTOCOL_PING_PATH, Values.create(""))),- new AssetAttribute(AttributeType.SURFACE_AREA, Values.create(1000), new Date().getTime())+ new AssetAttribute(AttributeType.SURFACE_AREA, Values.create(1000))))@@ -188,7 +188,7 @@ class GatewayTest extends Specification implements ManagerContainerTrait {new Asset(assetIds[(i-1)*5+j],0L,- new Date(),+ Date.from(timerService.getNow()),"Test Building $i Room $j",AssetType.ROOM.type,false,@@ -198,16 +198,16 @@ class GatewayTest extends Specification implements ManagerContainerTrait {"master",(String[])[assetIds[(i-1)*5+j], assetIds[(i-1)*5]].toArray(new String[0]),null).addAttributes(- new AssetAttribute(AttributeType.LOCATION, new GeoJSONPoint(10,11).toValue(), new Date().getTime())+ new AssetAttribute(AttributeType.LOCATION, new GeoJSONPoint(10,11).toValue()).addMeta(MetaItemType.ACCESS_PUBLIC_READ),- new AssetAttribute("temp", AttributeValueType.TEMPERATURE, null, new Date().getTime())+ new AssetAttribute("temp", AttributeValueType.TEMPERATURE, null).addMeta(new MetaItem(MetaItemType.AGENT_LINK, new AttributeRef(agentAssetIds[i-1], "protocolConfig").toArrayValue()),new MetaItem(HttpClientProtocol.META_ATTRIBUTE_PATH, Values.create(""))),- new AssetAttribute("tempSetpoint", AttributeValueType.TEMPERATURE, null, new Date().getTime())+ new AssetAttribute("tempSetpoint", AttributeValueType.TEMPERATURE, null).addMeta(new MetaItem(MetaItemType.AGENT_LINK, new AttributeRef(agentAssetIds[i-1], "protocolConfig").toArrayValue()),new MetaItem(HttpClientProtocol.META_ATTRIBUTE_PATH, Values.create(""))@@ -220,7 +220,7 @@ class GatewayTest extends Specification implements ManagerContainerTrait {new Asset(assetIds[(i-1)*5],0L,- new Date(),+ Date.from(timerService.getNow()),"Test Building $i",AssetType.BUILDING.type,false,@@ -230,11 +230,11 @@ class GatewayTest extends Specification implements ManagerContainerTrait {"master",(String[])[assetIds[(i-1)*5]].toArray(new String[0]),null).addAttributes(- new AssetAttribute(AttributeType.LOCATION, new GeoJSONPoint(10,11).toValue(), new Date().getTime())+ new AssetAttribute(AttributeType.LOCATION, new GeoJSONPoint(10,11).toValue()).addMeta(MetaItemType.ACCESS_PUBLIC_READ),- new AssetAttribute(AttributeType.SURFACE_AREA, Values.create(1000), new Date().getTime())+ new AssetAttribute(AttributeType.SURFACE_AREA, Values.create(1000))))}@@ -356,7 +356,7 @@ class GatewayTest extends Specification implements ManagerContainerTrait {assert assetStorageService.findAll(new AssetQuery().parents(gateway.getId()).recursive(true)).size() == agentAssets.size() + assets.size()and: "the http client protocol of the gateway agents should not have been linked to the central manager"- Thread.sleep(2000)+ Thread.sleep(500)conditions.eventually {assert !httpClientProtocol.clientMap.containsKey(new AttributeRef(agentAssetIds[0], "protocolConfig"))assert !httpClientProtocol.clientMap.containsKey(new AttributeRef(agentAssetIds[4], "protocolConfig"))@@ -365,6 +365,9 @@ class GatewayTest extends Specification implements ManagerContainerTrait {when: "the previously received messages are cleared"clientReceivedMessages.clear()+ and: "time advances"+ advancePseudoClock(1, TimeUnit.SECONDS, container)+and: "an attribute event for a gateway descendant asset (building 1 room 1) is sent to the local manager"assetProcessingService.sendAttributeEvent(new AttributeEvent(assetIds[1], "tempSetpoint", Values.create(20d)))@@ -389,7 +392,7 @@ class GatewayTest extends Specification implements ManagerContainerTrait {def building1Room5Asset = new Asset(building1Room5AssetId,0L,- new Date(),+ Date.from(timerService.getNow()),"Test Building 1 Room 5",AssetType.ROOM.type,false,@@ -399,16 +402,16 @@ class GatewayTest extends Specification implements ManagerContainerTrait {"master",(String[])[building1Room5AssetId, assetIds[0]].toArray(new String[0]),null).addAttributes(- new AssetAttribute(AttributeType.LOCATION, new GeoJSONPoint(10,11).toValue(), new Date().getTime())+ new AssetAttribute(AttributeType.LOCATION, new GeoJSONPoint(10,11).toValue()).addMeta(MetaItemType.ACCESS_PUBLIC_READ),- new AssetAttribute("temp", AttributeValueType.TEMPERATURE, null, new Date().getTime())+ new AssetAttribute("temp", AttributeValueType.TEMPERATURE, null).addMeta(new MetaItem(MetaItemType.AGENT_LINK, new AttributeRef(agentAssetIds[0], "protocolConfig").toArrayValue()),new MetaItem(HttpClientProtocol.META_ATTRIBUTE_PATH, Values.create(""))),- new AssetAttribute("tempSetpoint", AttributeValueType.TEMPERATURE, null, new Date().getTime())+ new AssetAttribute("tempSetpoint", AttributeValueType.TEMPERATURE, null).addMeta(new MetaItem(MetaItemType.AGENT_LINK, new AttributeRef(agentAssetIds[0], "protocolConfig").toArrayValue()),new MetaItem(HttpClientProtocol.META_ATTRIBUTE_PATH, Values.create(""))@@ -431,7 +434,7 @@ class GatewayTest extends Specification implements ManagerContainerTrait {building1Room5Asset.setName("Test Building 1 Room 5 Updated")building1Room5Asset.setVersion(1)building1Room5Asset.addAttributes(- new AssetAttribute("co2Level", AttributeValueType.CO2, Values.create(500), new Date().getTime())+ new AssetAttribute("co2Level", AttributeValueType.CO2, Values.create(500)).addMeta(new MetaItem(MetaItemType.AGENT_LINK, new AttributeRef(agentAssetIds[0], "protocolConfig").toArrayValue()),new MetaItem(HttpClientProtocol.META_ATTRIBUTE_PATH, Values.create(""))@@ -531,7 +534,10 @@ class GatewayTest extends Specification implements ManagerContainerTrait {assert assetStorageService.find(building1Room5AssetId) == null}- when: "the gateway asset is marked as disabled"+ when: "time advances"+ advancePseudoClock(1, TimeUnit.SECONDS, container)++ and: "the gateway asset is marked as disabled"assetProcessingService.sendAttributeEvent(new AttributeEvent(gateway.getId(), "disabled", Values.create(true)))then: "the gateway asset status should become disabled"@@ -557,7 +563,7 @@ class GatewayTest extends Specification implements ManagerContainerTrait {def failedAsset = new Asset(UniqueIdentifierGenerator.generateId("Failed asset"),0L,- new Date(),+ Date.from(timerService.getNow()),"Failed Asset",AssetType.BUILDING.type,false,@@ -567,11 +573,11 @@ class GatewayTest extends Specification implements ManagerContainerTrait {managerDemoSetup.realmBuildingTenant,(String[])[UniqueIdentifierGenerator.generateId("Failed asset")].toArray(new String[0]),null).addAttributes(- new AssetAttribute(AttributeType.LOCATION, new GeoJSONPoint(10,11).toValue(), new Date().getTime())+ new AssetAttribute(AttributeType.LOCATION, new GeoJSONPoint(10,11).toValue()).addMeta(MetaItemType.ACCESS_PUBLIC_READ),- new AssetAttribute(AttributeType.SURFACE_AREA, Values.create(1000), new Date().getTime())+ new AssetAttribute(AttributeType.SURFACE_AREA, Values.create(1000)))assetStorageService.merge(failedAsset)@@ -581,12 +587,15 @@ class GatewayTest extends Specification implements ManagerContainerTrait {when: "gateway assets are modified whilst the gateway is disconnected (building1Room5 re-added, building5 and descendants removed and building1 modified and building1Room1 attribute updated)"assets[4].setName("Test Building 1 Updated")assets[4].setVersion(2L)- assets[0].getAttribute("temp").ifPresent{it.setValue(Values.create(10), new Date().getTime())}+ assets[0].getAttribute("temp").ifPresent{it.setValue(Values.create(10))}assets = assets.subList(0, 20)and: "the client received messages are cleared"clientReceivedMessages.clear()+ and: "time advances"+ advancePseudoClock(1, TimeUnit.SECONDS, container)+and: "the gateway is enabled again"assetProcessingService.sendAttributeEvent(new AttributeEvent(gateway.getId(), "disabled", Values.create(false)))@@ -652,7 +661,7 @@ class GatewayTest extends Specification implements ManagerContainerTrait {def building2Room5Asset = new Asset(UniqueIdentifierGenerator.generateId("Test Building 2 Room 5"),0L,- new Date(),+ Date.from(timerService.getNow()),"Test Building 2 Room 5",AssetType.ROOM.type,false,@@ -662,16 +671,16 @@ class GatewayTest extends Specification implements ManagerContainerTrait {"master",(String[])[UniqueIdentifierGenerator.generateId("Test Building 2 Room 5"), assetIds[5]].toArray(new String[0]),null).addAttributes(- new AssetAttribute(AttributeType.LOCATION, new GeoJSONPoint(10,11).toValue(), new Date().getTime())+ new AssetAttribute(AttributeType.LOCATION, new GeoJSONPoint(10,11).toValue()).addMeta(MetaItemType.ACCESS_PUBLIC_READ),- new AssetAttribute("temp", AttributeValueType.TEMPERATURE, null, new Date().getTime())+ new AssetAttribute("temp", AttributeValueType.TEMPERATURE, null).addMeta(new MetaItem(MetaItemType.AGENT_LINK, new AttributeRef(agentAssetIds[1], "protocolConfig").toArrayValue()),new MetaItem(HttpClientProtocol.META_ATTRIBUTE_PATH, Values.create(""))),- new AssetAttribute("tempSetpoint", AttributeValueType.TEMPERATURE, null, new Date().getTime())+ new AssetAttribute("tempSetpoint", AttributeValueType.TEMPERATURE, null).addMeta(new MetaItem(MetaItemType.AGENT_LINK, new AttributeRef(agentAssetIds[1], "protocolConfig").toArrayValue()),new MetaItem(HttpClientProtocol.META_ATTRIBUTE_PATH, Values.create(""))@@ -736,9 +745,6 @@ class GatewayTest extends Specification implements ManagerContainerTrait {conditions.eventually {assert identityProvider.getClient(managerDemoSetup.realmBuildingTenant, GatewayService.GATEWAY_CLIENT_ID_PREFIX + gateway.getId()) == null}-- cleanup: "the server should be stopped"- stopContainer(container)}def "Verify gateway client service"() {@@ -833,11 +839,10 @@ class GatewayTest extends Specification implements ManagerContainerTrait {}and: "the container environment is started with the spy gateway client service"- def conditions = new PollingConditions(timeout: 10, delay: 1)- def serverPort = findEphemeralPort()+ def conditions = new PollingConditions(timeout: 10, delay: 0.2)def services = Lists.newArrayList(defaultServices())services.replaceAll{it instanceof GatewayClientService ? spyGatewayClientService : it}- def container = startContainer(defaultConfig(serverPort), services)+ def container = startContainer(defaultConfig(), services)def assetProcessingService = container.getService(AssetProcessingService.class)def assetStorageService = container.getService(AssetStorageService.class)def gatewayService = container.getService(GatewayService.class)@@ -857,9 +862,8 @@ class GatewayTest extends Specification implements ManagerContainerTrait {and: "the gateway client resource"def gatewayClientResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(GatewayClientResource.class)- expect: "the container should be running and initialised"+ expect: "the system should settle down"conditions.eventually {- assert container.isRunning()assert noEventProcessedIn(assetProcessingService, 300)}@@ -972,7 +976,10 @@ class GatewayTest extends Specification implements ManagerContainerTrait {assert mirroredMicrophone2.getAttribute("test").flatMap{it.getValueAsString()}.orElse("") == "newValue"}- when: "a mirrored asset attribute is updated"+ when: "time advances"+ advancePseudoClock(1, TimeUnit.SECONDS, container)++ and: "a mirrored asset attribute is updated"assetProcessingService.sendAttributeEvent(new AttributeEvent(realIdToFakeIdMap.get(microphone2.id), "test", Values.create("newerValue")))then: "the attribute should be updated on the gateway client and the mirrored asset"@@ -993,8 +1000,5 @@ class GatewayTest extends Specification implements ManagerContainerTrait {conditions.eventually {assert assetStorageService.find(realIdToFakeIdMap.get(managerDemoSetup.microphone1Id)) == null}-- cleanup: "the server should be stopped"- stopContainer(container)}}diff --git a/test/src/test/groovy/org/openremote/test/map/MapActivityTest.groovy b/test/src/test/groovy/org/openremote/test/map/MapActivityTest.groovydeleted file mode 100644index 705906c0f..000000000--- a/test/src/test/groovy/org/openremote/test/map/MapActivityTest.groovy+++ /dev/null@@ -1,78 +0,0 @@-package org.openremote.test.map-// TODO Fix this when we do Asset testing-class MapActivityTest { /* extends Specification implements ContainerTrait, GwtClientTrait {-- def "Initialize map"() {- given: "The fake client environment"- def placeController = Mock(PlaceController)- def activityContainer = Mock(AcceptsOneWidget)- def activityBus = Mock(EventBus)- def managerMessages = Mock(ManagerMessages)- def activityRegistrations = []- def constraintViolationReader = Mock(EntityReader)-- and: "the server container is started"- def serverPort = findEphemeralPort();- def container = startContainerWithoutDemoRules(defaultConfig(serverPort), defaultServices())-- and: "An authenticated user"- def realm = MASTER_REALM;- def accessToken = authenticate(- container,- realm,- KEYCLOAK_CLIENT_ID,- MASTER_REALM_ADMIN_USER,- getString(container.getConfig(), DEMO_ADMIN_PASSWORD, DEMO_ADMIN_PASSWORD_DEFAULT)- ).token- def securityService = Stub(SecurityService) {- getRealm() >> realm- getToken() >> accessToken- updateToken(_, _, _) >> { int minValiditySeconds, Consumer<Boolean> successFn, Runnable errorFn ->- successFn.accept(true)- };- getXsrfToken() >> "TODO: NOT ENABLED" // TODO- }- def requestService = new RequestServiceImpl(securityService, constraintViolationReader)-- and: "a test client target"- def clientTarget = getClientApiTarget(serverUri(serverPort), realm);-- and: "The map view, resource, and activity"- def mapView = Mock(MapView) {- isMapInitialised() >> false- }- def assetBrowserPresenter = Mock(AssetBrowser.Presenter)- def mapResource = Stub(MapResource) {- // This matches all methods with any parameters, of the MapResource class- _(*_) >> { callResourceProxy(container.JSON, clientTarget, getDelegate()) }- }-- def jsonObjectMapper = new JsonObjectMapper();-- def mapActivity = new MapActivity(- assetBrowserPresenter, mapView, mapResource, managerMessages, requestService, placeController, jsonObjectMapper- )-- and: "The expected map settings"- JsonObject mapSettings;-- when: "The activity is started"- mapActivity.start(activityContainer, activityBus, activityRegistrations)-- then: "The view should have the activity set as presenter"- 1 * mapView.setPresenter(mapActivity)-- and: "The view should have been initialized"- 1 * mapView.initialiseMap(!null) >> { mapSettings = it[0] }-- and: "The correct map settings must be used"- mapSettings.getArray("center").length() == 2;- mapSettings.getArray("maxBounds").length() == 4;- mapSettings.getNumber("maxZoom") == 18;- mapSettings.getObject("style") != null;-- cleanup: "the server should be stopped"- stopContainer(container);- }- */-}diff --git a/test/src/test/groovy/org/openremote/test/map/MapResourceTest.groovy b/test/src/test/groovy/org/openremote/test/map/MapResourceTest.groovyindex f3c0a31d9..667546ae8 100644--- a/test/src/test/groovy/org/openremote/test/map/MapResourceTest.groovy+++ b/test/src/test/groovy/org/openremote/test/map/MapResourceTest.groovy@@ -13,8 +13,7 @@ class MapResourceTest extends Specification implements ManagerContainerTrait {def "Retrieve map settings"() {given: "the server container is started"- def serverPort = findEphemeralPort()- def container = startContainerNoDemoImport(defaultConfig(serverPort), defaultServices())+ def container = startContainer(defaultConfig(), defaultServices())and: "an authenticated user"def realm = MASTER_REALM@@ -46,8 +45,5 @@ class MapResourceTest extends Specification implements ManagerContainerTrait {json.options.default.bounds.size() == 4json.sources != nulljson.layers.size() > 0-- cleanup: "the server should be stopped"- stopContainer(container)}}diff --git a/test/src/test/groovy/org/openremote/test/mqtt/MqttTest.groovy b/test/src/test/groovy/org/openremote/test/mqtt/MqttBrokerTest.groovysimilarity index 97%rename from test/src/test/groovy/org/openremote/test/mqtt/MqttTest.groovyrename to test/src/test/groovy/org/openremote/test/mqtt/MqttBrokerTest.groovyindex fa8778fd5..47b7164a0 100644--- a/test/src/test/groovy/org/openremote/test/mqtt/MqttTest.groovy+++ b/test/src/test/groovy/org/openremote/test/mqtt/MqttBrokerTest.groovy@@ -2,6 +2,7 @@ package org.openremote.test.mqttimport com.google.common.collect.Listsimport io.moquette.BrokerConstants+import org.openremote.container.timer.TimerServiceimport org.openremote.container.util.UniqueIdentifierGeneratorimport org.openremote.manager.asset.AssetProcessingServiceimport org.openremote.manager.asset.AssetStorageService@@ -15,12 +16,14 @@ import org.openremote.test.RawClientimport spock.lang.Specificationimport spock.util.concurrent.PollingConditions+import java.util.concurrent.TimeUnit+import static org.openremote.container.util.MapAccess.*import static org.openremote.manager.mqtt.KeycloakAuthenticator.MQTT_CLIENT_ID_SEPARATORimport static org.openremote.manager.mqtt.MqttBrokerService.MQTT_SERVER_LISTEN_HOSTimport static org.openremote.manager.mqtt.MqttBrokerService.MQTT_SERVER_LISTEN_PORT-class MqttTest extends Specification implements ManagerContainerTrait {+class MqttBrokerTest extends Specification implements ManagerContainerTrait {def "Mqtt broker test"() {given: "the container environment is started"@@ -39,11 +42,10 @@ class MqttTest extends Specification implements ManagerContainerTrait {}}- def conditions = new PollingConditions(timeout: 10, delay: 1)- def serverPort = findEphemeralPort()+ def conditions = new PollingConditions(timeout: 10, delay: 0.2)def services = Lists.newArrayList(defaultServices())services.replaceAll { it instanceof MqttBrokerService ? spyMqttBrokerService : it }- def container = startContainer(defaultConfig(serverPort), services)+ def container = startContainer(defaultConfig(), services)def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)def mqttBrokerService = container.getService(MqttBrokerService.class)def assetProcessingService = container.getService(AssetProcessingService.class)@@ -55,11 +57,6 @@ class MqttTest extends Specification implements ManagerContainerTrait {def mqttHost = getString(container.getConfig(), MQTT_SERVER_LISTEN_HOST, BrokerConstants.HOST);def mqttPort = getInteger(container.getConfig(), MQTT_SERVER_LISTEN_PORT, BrokerConstants.PORT);- expect: "the container should be running and initialised"- conditions.eventually {- assert container.isRunning()- }-when: "a mqtt client connects with wrong credentials"def payloadLength = "client1".size() + clientId.size() + clientSecret.size()def remainingLength = 16 + payloadLength@@ -298,6 +295,9 @@ class MqttTest extends Specification implements ManagerContainerTrait {.write(0x01) // QoS level 1.flush()+ and: "time advances"+ advancePseudoClock(1, TimeUnit.SECONDS, container)+and: "that attribute changed"attributeEvent = new AttributeEvent(managerDemoSetup.apartment1HallwayId, "motionSensor", Values.create(30))assetProcessingService.sendAttributeEvent(attributeEvent)@@ -353,6 +353,9 @@ class MqttTest extends Specification implements ManagerContainerTrait {.write(0x01) // QoS level 1.flush()+ and: "time advances"+ advancePseudoClock(1, TimeUnit.SECONDS, container)+and: "that attribute changed"attributeEvent = new AttributeEvent(managerDemoSetup.apartment1HallwayId, "motionSensor", Values.create(40))assetProcessingService.sendAttributeEvent(attributeEvent)@@ -391,8 +394,5 @@ class MqttTest extends Specification implements ManagerContainerTrait {conditions.eventually {assert mqttBrokerService.mqttConnectionMap.get(mqttClientId).assetAttributeValueSubscriptions.size() == 0}-- cleanup: "the server should be stopped"- stopContainer(container)}}diff --git a/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy b/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovyindex 941bec426..3057b27a5 100644--- a/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy+++ b/test/src/test/groovy/org/openremote/test/notification/NotificationTest.groovy@@ -5,7 +5,6 @@ import com.google.firebase.messaging.Messageimport org.openremote.container.web.WebServiceimport org.openremote.manager.asset.AssetStorageServiceimport org.openremote.manager.asset.console.ConsoleResourceImpl-import org.openremote.manager.gateway.GatewayClientServiceimport org.openremote.manager.notification.EmailNotificationHandlerimport org.openremote.manager.notification.NotificationServiceimport org.openremote.manager.notification.PushNotificationHandler@@ -48,11 +47,18 @@ class NotificationTest extends Specification implements ManagerContainerTrait {def notificationTargetIds = []def notificationMessages = []- given: "a mock push notification handler"- PushNotificationHandler mockPushNotificationHandler = Spy(PushNotificationHandler) {- isValid() >> true+ given: "the container environment is started with the mock handler"+ def container = startContainer(defaultConfig(), defaultServices())+ def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)+ def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)+ def notificationService = container.getService(NotificationService.class)+ def pushNotificationHandler = container.getService(PushNotificationHandler.class)+ def consoleResource = (ConsoleResourceImpl)container.getService(WebService.class).getApiSingletons().find {it instanceof ConsoleResourceImpl}- sendMessage(_ as Long, _ as Notification.Source, _ as String, _ as Notification.Target, _ as AbstractNotificationMessage) >> {+ and: "a mock push notification handler"+ PushNotificationHandler mockPushNotificationHandler = Spy(pushNotificationHandler)+ mockPushNotificationHandler.isValid() >> true+ mockPushNotificationHandler.sendMessage(_ as Long, _ as Notification.Source, _ as String, _ as Notification.Target, _ as AbstractNotificationMessage) >> {id, source, sourceId, target, message ->notificationIds << idnotificationTargetTypes << target.type@@ -60,22 +66,12 @@ class NotificationTest extends Specification implements ManagerContainerTrait {notificationMessages << messagecallRealMethod()}-- // Assume sent to FCM- sendMessage(_ as Message) >> {+ // Assume sent to FCM+ mockPushNotificationHandler.sendMessage(_ as Message) >> {message -> return NotificationSendResult.success()}- }- and: "the container environment is started with the mock handler"- def serverPort = findEphemeralPort()- def services = Lists.newArrayList(defaultServices())- services.replaceAll{it instanceof PushNotificationHandler ? mockPushNotificationHandler : it}- def container = startContainerWithPseudoClock(defaultConfig(serverPort), services)- def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)- def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)- def notificationService = container.getService(NotificationService.class)- def consoleResource = (ConsoleResourceImpl)container.getService(WebService.class).getApiSingletons().find {it instanceof ConsoleResourceImpl}+ notificationService.notificationHandlerMap.put(pushNotificationHandler.getTypeName(), mockPushNotificationHandler)and: "an authenticated test user"def realm = keycloakDemoSetup.tenantBuilding.realm@@ -254,7 +250,7 @@ class NotificationTest extends Specification implements ManagerContainerTrait {notificationService.sendNotification(notification, Notification.Source.ASSET_RULESET, consoleResource.getConsoleParentAssetId(realm))then: "the notification should have been sent"- new PollingConditions(timeout: 10).eventually {+ new PollingConditions(timeout: 10, delay: 0.2).eventually {assert notificationIds.size() == 17}@@ -524,8 +520,8 @@ class NotificationTest extends Specification implements ManagerContainerTrait {then: "only the relevant notifications should have been returned"assert notifications.size() == 8- cleanup: "the server should be stopped"- stopContainer(container)+ cleanup: "the mock is removed"+ notificationService.notificationHandlerMap.put(pushNotificationHandler.getTypeName(), pushNotificationHandler)}def "Check email notification functionality"() {@@ -536,41 +532,36 @@ class NotificationTest extends Specification implements ManagerContainerTrait {def notificationMessages = []def toAddresses = []- given: "a mock email notification handler"- EmailNotificationHandler mockEmailNotificationHandler = Spy(EmailNotificationHandler) {- isValid() >> true-- sendMessage(_ as Long, _ as Notification.Source, _ as String, _ as Notification.Target, _ as AbstractNotificationMessage) >> {- id, source, sourceId, target, message ->- notificationIds << id- notificationTargetTypes << target.type- notificationTargetIds << target.id- notificationMessages << message- callRealMethod()- }-- sendMessage(_ as Email) >> {- email ->- if (email instanceof List) {- def e = ((List)email).get(0) as Email- e.recipients.forEach {toAddresses.add(it.address)}- return NotificationSendResult.success()- }- }- }-- and: "the container environment is started with the mock handler"- def serverPort = findEphemeralPort()- def services = Lists.newArrayList(defaultServices())- services.replaceAll{it instanceof EmailNotificationHandler ? mockEmailNotificationHandler : it}- def conditions = new PollingConditions(timeout: 10)- def container = startContainer(defaultConfig(serverPort), services)+ given: "the container environment is started with the mock handler"+ def conditions = new PollingConditions(timeout: 10, delay: 0.2)+ def container = startContainer(defaultConfig(), defaultServices())def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)def notificationService = container.getService(NotificationService.class)+ def emailNotificationHandler = container.getService(EmailNotificationHandler.class)def assetStorageService = container.getService(AssetStorageService.class)- expect: "the container to be running"- container.isRunning()+ and: "a mock email notification handler"+ EmailNotificationHandler mockEmailNotificationHandler = Spy(emailNotificationHandler)+ mockEmailNotificationHandler.isValid() >> true+ mockEmailNotificationHandler.sendMessage(_ as Long, _ as Notification.Source, _ as String, _ as Notification.Target, _ as AbstractNotificationMessage) >> {+ id, source, sourceId, target, message ->+ notificationIds << id+ notificationTargetTypes << target.type+ notificationTargetIds << target.id+ notificationMessages << message+ callRealMethod()+ }++ // Assume sent to FCM+ mockEmailNotificationHandler.sendMessage(_ as Email) >> {+ email ->+ if (email instanceof List) {+ def e = ((List)email).get(0) as Email+ e.recipients.forEach {toAddresses.add(it.address)}+ return NotificationSendResult.success()+ }+ }+ notificationService.notificationHandlerMap.put(emailNotificationHandler.getTypeName(), mockEmailNotificationHandler)when: "an email notification is sent to a tenant through same mechanism as rules"def notification = new Notification(@@ -586,11 +577,9 @@ class NotificationTest extends Specification implements ManagerContainerTrait {assert ((EmailNotificationMessage) notificationMessages.get(0)).getSubject() == "Test"assert ((EmailNotificationMessage) notificationMessages.get(1)).getText() == "Hello world!"assert ((EmailNotificationMessage) notificationMessages.get(1)).getSubject() == "Test"- assert toAddresses.size() == 4assert toAddresses.any { it == "[email protected]" }assert toAddresses.any { it == "[email protected]" }assert toAddresses.any { it == "[email protected]" }- assert toAddresses.any { ((String) it).startsWith("service-account") } //mqtt service account}when: "an email attribute is added to an asset"@@ -609,7 +598,7 @@ class NotificationTest extends Specification implements ManagerContainerTrait {assert toAddresses.any { it == "[email protected]" }}- cleanup: "the server should be stopped"- stopContainer(container)+ cleanup: "the mock is removed"+ notificationService.notificationHandlerMap.put(emailNotificationHandler.getTypeName(), emailNotificationHandler)}}diff --git a/test/src/test/groovy/org/openremote/test/protocol/BasicProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/BasicProtocolTest.groovyindex 53e77cf21..8f51e3439 100644--- a/test/src/test/groovy/org/openremote/test/protocol/BasicProtocolTest.groovy+++ b/test/src/test/groovy/org/openremote/test/protocol/BasicProtocolTest.groovy@@ -35,22 +35,23 @@ import org.openremote.model.value.RegexValueFilterimport org.openremote.model.value.SubStringValueFilterimport org.openremote.model.value.Valueimport org.openremote.model.value.Values-import org.openremote.test.GwtClientTraitimport org.openremote.test.ManagerContainerTraitimport spock.lang.Specificationimport spock.util.concurrent.PollingConditions+import java.util.concurrent.TimeUnit+import static org.openremote.model.Constants.MASTER_REALM/*** This tests the basic protocol interface and abstract protocol implementation.*/-class BasicProtocolTest extends Specification implements ManagerContainerTrait, GwtClientTrait {+class BasicProtocolTest extends Specification implements ManagerContainerTrait {def "Check abstract protocol linking/un-linking"() {given: "expected conditions"- def conditions = new PollingConditions(timeout: 10, delay: 1)+ def conditions = new PollingConditions(timeout: 10, delay: 0.2)and: "a mock protocol"def mockProtocolName = "urn:myCustom:mockProtocol"@@ -72,10 +73,12 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait,// Assume we've pushed the update to the actual device and it responded with OK// so now we want to cause a sensor update that will go through the processing// chain.+ advancePseudoClock(1, TimeUnit.SECONDS, container)updateLinkedAttribute(state)}protected void updateAttribute(AttributeState state) {+ advancePseudoClock(1, TimeUnit.SECONDS, container)sendAttributeEvent(state)}@@ -167,8 +170,7 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait,}and: "the container is started with the mock protocol"- def serverPort = findEphemeralPort()- def container = startContainerNoDemoImport(defaultConfig(serverPort), defaultServices(mockProtocol))+ def container = startContainer(defaultConfig(), defaultServices(mockProtocol))def assetStorageService = container.getService(AssetStorageService.class)def agentService = container.getService(AgentService.class)def assetProcessingService = container.getService(AssetProcessingService.class)@@ -522,8 +524,5 @@ class BasicProtocolTest extends Specification implements ManagerContainerTrait,assert protocolMethodCalls[1] == "LINK_ATTRIBUTE"assert protocolMethodCalls[2] == "LINK_ATTRIBUTE"}-- cleanup: "the server should be stopped"- stopContainer(container)}}diff --git a/test/src/test/groovy/org/openremote/test/protocol/KNXImportTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/KNXImportTest.groovyindex c5ac1f798..8737221c4 100644--- a/test/src/test/groovy/org/openremote/test/protocol/KNXImportTest.groovy+++ b/test/src/test/groovy/org/openremote/test/protocol/KNXImportTest.groovy@@ -55,11 +55,10 @@ class KNXImportTest extends Specification implements ManagerContainerTrait {def "Check KNX protocol import"() {given: "expected conditions"- def conditions = new PollingConditions(timeout: 10, initialDelay: 1, delay: 1)+ def conditions = new PollingConditions(timeout: 10, delay: 0.2)and: "the container is started"- def serverPort = findEphemeralPort()- def container = startContainerNoDemoImport(defaultConfig(serverPort), defaultServices())+ def container = startContainer(defaultConfig(), defaultServices())def assetStorageService = container.getService(AssetStorageService.class)def agentService = container.getService(AgentService.class)def assetProcessingService = container.getService(AssetProcessingService.class)@@ -92,9 +91,6 @@ class KNXImportTest extends Specification implements ManagerContainerTrait {and: "the agent resource"def agentResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(AgentResource.class)- and: "the container is running"- container.isRunning()-then: "the container should settle down and the agent should be deployed"conditions.eventually {assert agentService.getAgents().containsKey(knxAgent.id)@@ -141,10 +137,5 @@ class KNXImportTest extends Specification implements ManagerContainerTrait {def metaItem3 = attribute.getMetaItem(KNXProtocol.META_KNX_DPT).get()metaItem3 != nullmetaItem3.getValueAsString().get() == "9.001"--- cleanup: "the server should be stopped"- stopContainer(container)-}-}\ No newline at end of file+}diff --git a/test/src/test/groovy/org/openremote/test/protocol/KNXProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/KNXProtocolTest.groovyindex 71632bbbd..e0691b1d0 100644--- a/test/src/test/groovy/org/openremote/test/protocol/KNXProtocolTest.groovy+++ b/test/src/test/groovy/org/openremote/test/protocol/KNXProtocolTest.groovy@@ -52,7 +52,7 @@ class KNXProtocolTest extends Specification implements ManagerContainerTrait {def "Check KNX protocol"() {given: "expected conditions"- def conditions = new PollingConditions(timeout: 10, initialDelay: 1, delay: 1)+ def conditions = new PollingConditions(timeout: 10, delay: 0.2)and: "the KNX emulation server is started"def configFile = SystemUtils.IS_OS_MAC ? "/org/openremote/test/protocol/knx/knx-server-config-mac.xml" : "/org/openremote/test/protocol/knx/knx-server-config.xml"@@ -80,8 +80,7 @@ class KNXProtocolTest extends Specification implements ManagerContainerTrait {def knxTestingNetwork = KNXTestingNetworkLink.getInstance()and: "the container is started"- def serverPort = findEphemeralPort()- def container = startContainerNoDemoImport(defaultConfig(serverPort), defaultServices())+ def container = startContainer(defaultConfig(), defaultServices())def assetStorageService = container.getService(AssetStorageService.class)def agentService = container.getService(AgentService.class)def assetProcessingService = container.getService(AssetProcessingService.class)@@ -161,8 +160,5 @@ class KNXProtocolTest extends Specification implements ManagerContainerTrait {if (knxEmulationServer != null) {knxEmulationServer.quit()}- stopContainer(container)--}-}\ No newline at end of file+}diff --git a/test/src/test/groovy/org/openremote/test/protocol/MacroProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/MacroProtocolTest.groovyindex dd89ada80..faa40b5c4 100644--- a/test/src/test/groovy/org/openremote/test/protocol/MacroProtocolTest.groovy+++ b/test/src/test/groovy/org/openremote/test/protocol/MacroProtocolTest.groovy@@ -1,5 +1,6 @@package org.openremote.test.protocol+import org.openremote.container.timer.TimerServiceimport org.openremote.manager.asset.AssetProcessingServiceimport org.openremote.manager.asset.AssetStorageServiceimport org.openremote.manager.setup.SetupService@@ -11,6 +12,8 @@ import org.openremote.test.ManagerContainerTraitimport spock.lang.Specificationimport spock.util.concurrent.PollingConditions+import java.util.concurrent.TimeUnit+class MacroProtocolTest extends Specification implements ManagerContainerTrait {def "Check macro agent and device asset deployment"() {@@ -18,8 +21,7 @@ class MacroProtocolTest extends Specification implements ManagerContainerTrait {def conditions = new PollingConditions(timeout: 15, initialDelay: 0)when: "the container starts"- def serverPort = findEphemeralPort()- def container = startContainerWithDemoScenesAndRules(defaultConfig(serverPort), defaultServices())+ def container = startContainerWithDemoScenesAndRules(defaultConfig(), defaultServices())def assetStorageService = container.getService(AssetStorageService.class)def assetProcessingService = container.getService(AssetProcessingService.class)def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)@@ -56,7 +58,10 @@ class MacroProtocolTest extends Specification implements ManagerContainerTrait {assert apartment1.getAttribute("morningScene").get().getValueAsString().orElse("") == AttributeExecuteStatus.COMPLETED.toString()}- when: "Apartment 1 away scene is executed"+ when: "time advances"+ advancePseudoClock(1, TimeUnit.SECONDS, container)++ and: "Apartment 1 away scene is executed"macroExecute = new AttributeEvent(managerDemoSetup.apartment1Id, "dayScene", AttributeExecuteStatus.REQUEST_START.asValue())assetProcessingService.sendAttributeEvent(macroExecute)@@ -75,7 +80,10 @@ class MacroProtocolTest extends Specification implements ManagerContainerTrait {assert apartment1.getAttribute("dayScene").get().getValueAsString().orElse("") == AttributeExecuteStatus.COMPLETED.toString()}- when: "The target temperature of the home scene is modified via the apartment attribute"+ when: "time advances"+ advancePseudoClock(1, TimeUnit.SECONDS, container)++ and: "The target temperature of the home scene is modified via the apartment attribute"def updateTargetTemp = new AttributeEvent(managerDemoSetup.apartment1Id, "morningSceneTargetTemperature", Values.create(10d))assetProcessingService.sendAttributeEvent(updateTargetTemp)@@ -87,7 +95,10 @@ class MacroProtocolTest extends Specification implements ManagerContainerTrait {assert !apartment1.getAttribute("morningSceneAlarmEnabled").get().getValueAsBoolean().orElse(true)}- when: "Apartment 1 home scene is executed"+ when: "time advances"+ advancePseudoClock(1, TimeUnit.SECONDS, container)++ and: "Apartment 1 home scene is executed"macroExecute = new AttributeEvent(managerDemoSetup.apartment1Id, "morningScene", AttributeExecuteStatus.REQUEST_START.asValue())assetProcessingService.sendAttributeEvent(macroExecute)@@ -105,8 +116,5 @@ class MacroProtocolTest extends Specification implements ManagerContainerTrait {def apartment1 = assetStorageService.find(managerDemoSetup.apartment1Id, true)assert apartment1.getAttribute("morningScene").get().getValueAsString().orElse("") == AttributeExecuteStatus.COMPLETED.toString()}-- cleanup: "the server should be stopped"- stopContainer(container)}-}\ No newline at end of file+}diff --git a/test/src/test/groovy/org/openremote/test/protocol/TcpClientTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/TcpClientTest.groovyindex f6ff3c213..2b03032e8 100644--- a/test/src/test/groovy/org/openremote/test/protocol/TcpClientTest.groovy+++ b/test/src/test/groovy/org/openremote/test/protocol/TcpClientTest.groovy@@ -41,11 +41,10 @@ class TcpClientTest extends Specification implements ManagerContainerTrait {def "Check client"() {given: "expected conditions"- def conditions = new PollingConditions(timeout: 10, delay: 1)+ def conditions = new PollingConditions(timeout: 10, delay: 0.2)and: "the container is started"- def serverPort = findEphemeralPort()- def container = startContainer(defaultConfig(serverPort), Collections.singletonList(new ManagerExecutorService()))+ def container = startContainer(defaultConfig(), Collections.singletonList(new ManagerExecutorService()))def protocolExecutorService = container.getService(ManagerExecutorService.class)and: "a simple TCP echo server"@@ -191,6 +190,5 @@ class TcpClientTest extends Specification implements ManagerContainerTrait {cleanup: "the server should be stopped"client.disconnect()echoServer.stop()- stopContainer(container)}}diff --git a/test/src/test/groovy/org/openremote/test/protocol/TimerProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/TimerProtocolTest.groovyindex e8dc85285..082b7fc78 100644--- a/test/src/test/groovy/org/openremote/test/protocol/TimerProtocolTest.groovy+++ b/test/src/test/groovy/org/openremote/test/protocol/TimerProtocolTest.groovy@@ -30,8 +30,7 @@ class TimerProtocolTest extends Specification implements ManagerContainerTrait {def conditions = new PollingConditions(timeout: 10, initialDelay: 0)when: "the container starts"- def serverPort = findEphemeralPort()- def container = startContainerWithDemoScenesAndRules(defaultConfig(serverPort), defaultServices())+ def container = startContainerWithDemoScenesAndRules(defaultConfig(), defaultServices())def assetStorageService = container.getService(AssetStorageService.class)def assetProcessingService = container.getService(AssetProcessingService.class)def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)@@ -194,8 +193,5 @@ class TimerProtocolTest extends Specification implements ManagerContainerTrait {assert jobDetail == nullassert triggers.isEmpty()}-- cleanup: "the server should be stopped"- stopContainer(container)}-}\ No newline at end of file+}diff --git a/test/src/test/groovy/org/openremote/test/protocol/controller/ControllerProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/controller/ControllerProtocolTest.groovyindex c70a6c6d6..dc120d243 100644--- a/test/src/test/groovy/org/openremote/test/protocol/controller/ControllerProtocolTest.groovy+++ b/test/src/test/groovy/org/openremote/test/protocol/controller/ControllerProtocolTest.groovy@@ -170,19 +170,13 @@ class ControllerProtocolTest extends Specification implements ManagerContainerTrand: "expected conditions"def conditions = new PollingConditions(timeout: 20, initialDelay: 1)- when: "the container starts"- def serverPort = findEphemeralPort()- def container = startContainerNoDemoImport(defaultConfig(serverPort), defaultServices())+ and: "the container starts"+ def container = startContainer(defaultConfig(), defaultServices())def controllerProtocol = container.getService(ControllerProtocol.class)def assetStorageService = container.getService(AssetStorageService.class)def assetProcessingService = container.getService(AssetProcessingService.class)def agentService = container.getService(AgentService.class)- then: "the container should be running"- conditions.eventually {- assert container.isRunning()- }-when: "the web target builder is configured to use the mock server"if (!controllerProtocol.client.configuration.isRegistered(mockController)) {controllerProtocol.client.register(mockController, Integer.MAX_VALUE)@@ -347,8 +341,5 @@ class ControllerProtocolTest extends Specification implements ManagerContainerTrassert mockController.commandCount == 2assert true}-- cleanup: "the server should be stopped"- stopContainer(container)}-}\ No newline at end of file+}diff --git a/test/src/test/groovy/org/openremote/test/protocol/http/HttpClientProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/http/HttpClientProtocolTest.groovyindex ae2c0cac3..bfc964ebc 100644--- a/test/src/test/groovy/org/openremote/test/protocol/http/HttpClientProtocolTest.groovy+++ b/test/src/test/groovy/org/openremote/test/protocol/http/HttpClientProtocolTest.groovy@@ -284,19 +284,13 @@ class HttpClientProtocolTest extends Specification implements ManagerContainerTrHttpClientProtocol.MIN_POLLING_MILLIS = 10HttpClientProtocol.MIN_PING_MILLIS = 10- when: "the container starts"- def serverPort = findEphemeralPort()- def container = startContainerNoDemoImport(defaultConfig(serverPort), defaultServices())+ and: "the container starts"+ def container = startContainer(defaultConfig(), defaultServices())def httpClientProtocol = container.getService(HttpClientProtocol.class)def assetStorageService = container.getService(AssetStorageService.class)def assetProcessingService = container.getService(AssetProcessingService.class)def agentService = container.getService(AgentService.class)- then: "the container should be running"- conditions.eventually {- assert container.isRunning()- }-when: "the web target builder is configured to use the mock server"if (!httpClientProtocol.client.configuration.isRegistered(mockServer)) {httpClientProtocol.client.register(mockServer, Integer.MAX_VALUE)@@ -808,8 +802,5 @@ class HttpClientProtocolTest extends Specification implements ManagerContainerTrconditions.eventually {assert mockServer.successFailureCount == count + 1}-- cleanup: "the server should be stopped"- stopContainer(container)}}diff --git a/test/src/test/groovy/org/openremote/test/protocol/http/HttpServerProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/http/HttpServerProtocolTest.groovyindex 73929a7b6..e52b6415a 100644--- a/test/src/test/groovy/org/openremote/test/protocol/http/HttpServerProtocolTest.groovy+++ b/test/src/test/groovy/org/openremote/test/protocol/http/HttpServerProtocolTest.groovy@@ -271,9 +271,8 @@ class HttpServerProtocolTest extends Specification implements ManagerContainerTrdef conditions = new PollingConditions(timeout: 10, initialDelay: 1)and: "the container starts with the test http server protocol"- def serverPort = findEphemeralPort()def testServerProtocol = new TestHttpServerProtocol()- def container = startContainerNoDemoImport(defaultConfig(serverPort), defaultServices(testServerProtocol))+ def container = startContainer(defaultConfig(), defaultServices(testServerProtocol))def httpClientProtocol = container.getService(HttpClientProtocol.class)def assetStorageService = container.getService(AssetStorageService.class)def assetProcessingService = container.getService(AssetProcessingService.class)@@ -430,11 +429,8 @@ class HttpServerProtocolTest extends Specification implements ManagerContainerTr}then: "the asset should not have been posted"- new PollingConditions(initialDelay: 3).eventually {+ new PollingConditions(timeout: 5, initialDelay: 3).eventually {assert testServerProtocol.resource1.postedAssets.size() == 2}-- cleanup: "the server should be stopped"- stopContainer(container)}}diff --git a/test/src/test/groovy/org/openremote/test/protocol/udp/UdpClientProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/udp/UdpClientProtocolTest.groovyindex a96274b8e..fb362a9dd 100644--- a/test/src/test/groovy/org/openremote/test/protocol/udp/UdpClientProtocolTest.groovy+++ b/test/src/test/groovy/org/openremote/test/protocol/udp/UdpClientProtocolTest.groovy@@ -53,20 +53,19 @@ class UdpClientProtocolTest extends Specification implements ManagerContainerTradef "Check UDP client protocol configuration and linked attribute deployment"() {given: "expected conditions"- def conditions = new PollingConditions(timeout: 10, delay: 1)+ def conditions = new PollingConditions(timeout: 10, delay: 0.2)- when: "the container starts"- def serverPort = findEphemeralPort()- def container = startContainerNoDemoImport(defaultConfig(serverPort), defaultServices())+ and: "the container starts"+ def container = startContainer(defaultConfig(), defaultServices())def protocolExecutorService = container.getService(ProtocolExecutorService.class)def udpClientProtocol = container.getService(UdpClientProtocol.class)def assetStorageService = container.getService(AssetStorageService.class)def assetProcessingService = container.getService(AssetProcessingService.class)def agentService = container.getService(AgentService.class)- then: "the container should be running"+ expect: "the system settles down"conditions.eventually {- assert container.isRunning()+ noEventProcessedIn(assetProcessingService, 300)}when: "a simple UDP echo server is started"@@ -200,7 +199,7 @@ class UdpClientProtocolTest extends Specification implements ManagerContainerTrareceivedMessages.clear()then: "after a while no more messages should be received by the server"- new PollingConditions(initialDelay: 1, timeout: 2).eventually {+ new PollingConditions(timeout: 5, initialDelay: 1).eventually {assert receivedMessages.isEmpty()}@@ -274,6 +273,12 @@ class UdpClientProtocolTest extends Specification implements ManagerContainerTraassert udpClientProtocol.linkedAttributes.get(new AttributeRef(asset.getId(), "echoHello")).getMetaItem(UdpClientProtocol.META_ATTRIBUTE_WRITE_VALUE).flatMap{it.getValueAsString()}.orElse(null) == '"abcdef"'}+ and: "the protocol should become CONNECTED"+ conditions.eventually {+ def status = agentService.getProtocolConnectionStatus(new AttributeRef(agent.id, "protocolConfig"))+ assert status == ConnectionStatus.CONNECTED+ }+when: "the hello linked attribute is executed"attributeEvent = new AttributeEvent(asset.id,"echoHello",@@ -293,6 +298,5 @@ class UdpClientProtocolTest extends Specification implements ManagerContainerTraif (echoServer != null) {echoServer.stop()}- stopContainer(container)}}diff --git a/test/src/test/groovy/org/openremote/test/protocol/udp/UdpClientTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/udp/UdpClientTest.groovyindex 3a406cdda..0317fe1c4 100644--- a/test/src/test/groovy/org/openremote/test/protocol/udp/UdpClientTest.groovy+++ b/test/src/test/groovy/org/openremote/test/protocol/udp/UdpClientTest.groovy@@ -44,12 +44,11 @@ class UdpClientTest extends Specification implements ManagerContainerTrait {def "Check client"() {given: "expected conditions"- def conditions = new PollingConditions(timeout: 10, delay: 1)+ def conditions = new PollingConditions(timeout: 10, delay: 0.2)and: "the container is started"- def serverPort = findEphemeralPort()def clientPort = findEphemeralPort()- def container = startContainer(defaultConfig(serverPort), Collections.singletonList(new ManagerExecutorService()))+ def container = startContainer(defaultConfig(), Collections.singletonList(new ManagerExecutorService()))def protocolExecutorService = container.getService(ProtocolExecutorService.class)and: "a simple UDP echo server"@@ -169,6 +168,5 @@ class UdpClientTest extends Specification implements ManagerContainerTrait {cleanup: "the server should be stopped"client.disconnect()echoServer.stop()- stopContainer(container)}}diff --git a/test/src/test/groovy/org/openremote/test/protocol/velbus/VelbusBasicTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/velbus/VelbusBasicTest.groovyindex adc91af6c..4b628845b 100644--- a/test/src/test/groovy/org/openremote/test/protocol/velbus/VelbusBasicTest.groovy+++ b/test/src/test/groovy/org/openremote/test/protocol/velbus/VelbusBasicTest.groovy@@ -19,27 +19,23 @@*/package org.openremote.test.protocol.velbus-import org.openremote.model.asset.agent.ConnectionStatusimport org.openremote.agent.protocol.velbus.VelbusNetworkimport org.openremote.agent.protocol.velbus.VelbusPacketimport org.openremote.agent.protocol.velbus.device.*-import org.openremote.container.Container+import org.openremote.container.concurrent.ContainerScheduledExecutorimport org.openremote.manager.concurrent.ManagerExecutorService+import org.openremote.model.asset.agent.ConnectionStatusimport org.openremote.model.value.ValueTypeimport org.openremote.model.value.Values-import org.openremote.test.ManagerContainerTraitimport org.openremote.test.MockVelbusClientimport spock.lang.Sharedimport spock.lang.Specificationimport spock.util.concurrent.PollingConditions+import static org.openremote.container.util.MapAccess.getIntegerimport static spock.util.matcher.HamcrestMatchers.closeTo-class VelbusBasicTest extends Specification implements ManagerContainerTrait {-- @Shared- def static Container container-+class VelbusBasicTest extends Specification {@Shareddef static VelbusNetwork network@@ -47,7 +43,7 @@ class VelbusBasicTest extends Specification implements ManagerContainerTrait {def static MockVelbusClient messageProcessor = new MockVelbusClient()@Shared- def static PollingConditions conditions = new PollingConditions(timeout: 15)+ def static PollingConditions conditions = new PollingConditions(timeout: 15, delay: 0.2)static loadDevicePackets(MockVelbusClient messageProcessor) {messageProcessor.mockPackets = [@@ -805,9 +801,6 @@ class VelbusBasicTest extends Specification implements ManagerContainerTrait {}def setupSpec() {- def serverPort = findEphemeralPort()- container = startContainer(defaultConfig(serverPort), Collections.singletonList(new ManagerExecutorService()))- def protocolExecutorService = container.getService(ManagerExecutorService.class)VelbusNetwork.DELAY_BETWEEN_PACKET_WRITES_MILLISECONDS = 1; // Minimal delay for simulated network// Uncomment and configure the below lines to communicate with an actual VELBUS network@@ -816,7 +809,8 @@ class VelbusBasicTest extends Specification implements ManagerContainerTrait {// def client = new VelbusSerialMessageProcessor("COM6", 38400, protocolExecutorService);// VelbusNetwork.DELAY_BETWEEN_PACKET_WRITES_MILLISECONDS = 100;- network = new VelbusNetwork(messageProcessor, protocolExecutorService, null)+ def scheduledTasksExecutor = new ContainerScheduledExecutor("Scheduled task", ManagerExecutorService.SCHEDULED_TASKS_THREADS_MAX_DEFAULT)+ network = new VelbusNetwork(messageProcessor, scheduledTasksExecutor, null)loadDevicePackets(VelbusBasicTest.messageProcessor)}@@ -825,7 +819,6 @@ class VelbusBasicTest extends Specification implements ManagerContainerTrait {if (network != null) {network.close()}- stopContainer(container)}def setup() {@@ -2871,4 +2864,4 @@ class VelbusBasicTest extends Specification implements ManagerContainerTrait {assert device.getPropertyValue("TEMP_STATE").getPropertyValue() == ThermostatProcessor.TemperatureState.NORMAL}}-}\ No newline at end of file+}diff --git a/test/src/test/groovy/org/openremote/test/protocol/velbus/VelbusProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/velbus/VelbusProtocolTest.groovyindex b365f3302..46d240e4d 100644--- a/test/src/test/groovy/org/openremote/test/protocol/velbus/VelbusProtocolTest.groovy+++ b/test/src/test/groovy/org/openremote/test/protocol/velbus/VelbusProtocolTest.groovy@@ -90,11 +90,10 @@ class VelbusProtocolTest extends Specification implements ManagerContainerTraitdef "Check VELBUS agent and device asset deployment"() {given: "expected conditions"- def conditions = new PollingConditions(timeout: 20, initialDelay: 1, delay: 1)+ def conditions = new PollingConditions(timeout: 20, delay: 0.2)when: "the container starts"- def serverPort = findEphemeralPort()- def container = startContainerNoDemoImport(defaultConfig(serverPort), defaultServices(velbusProtocol))+ def container = startContainer(defaultConfig(), defaultServices(velbusProtocol))def assetStorageService = container.getService(AssetStorageService.class)and: "a VELBUS agent is created"@@ -138,16 +137,17 @@ class VelbusProtocolTest extends Specification implements ManagerContainerTraitassert asset.getAttribute("ch1State").flatMap { it.getValueAsString() }.orElse(null) == "RELEASED"}- cleanup: "the server should be stopped"- stopContainer(container)+ cleanup: "remove agent"+ if (agent != null) {+ assetStorageService.delete(Collections.singletonList(agent.id))+ }}def "Check linked attribute import"() {given: "the server container is started"- def conditions = new PollingConditions(timeout: 10, delay: 1)- def serverPort = findEphemeralPort()- def container = startContainer(defaultConfig(serverPort), defaultServices())+ def conditions = new PollingConditions(timeout: 10, delay: 0.2)+ def container = startContainer(defaultConfig(), defaultServices())def assetStorageService = container.getService(AssetStorageService.class)def agentService = container.getService(AgentService.class)def assetProcessingService = container.getService(AssetProcessingService.class)@@ -183,13 +183,10 @@ class VelbusProtocolTest extends Specification implements ManagerContainerTraitand: "the agent resource"def agentResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(AgentResource.class)- when: "the container is running"- container.isRunning()-- then: "the container should settle down and the agent should be deployed"+ expect: "the system should settle down"conditions.eventually {assert agentService.getAgents().containsKey(agent.id)- assert noEventProcessedIn(assetProcessingService, 500)+ assert noEventProcessedIn(assetProcessingService, 300)}when: "discovery is requested with a VELBUS project file"@@ -219,7 +216,9 @@ class VelbusProtocolTest extends Specification implements ManagerContainerTraitassert memoTextAttribute != nullassert VelbusConfiguration.getVelbusDeviceAddress(memoTextAttribute) == 24- cleanup: "the server should be stopped"- stopContainer(container)+ cleanup: "remove agent"+ if (agent != null) {+ assetStorageService.delete(Collections.singletonList(agent.id))+ }}}diff --git a/test/src/test/groovy/org/openremote/test/protocol/websocket/WebsocketClientProtocolTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/websocket/WebsocketClientProtocolTest.groovyindex f2499575d..9911eabd6 100644--- a/test/src/test/groovy/org/openremote/test/protocol/websocket/WebsocketClientProtocolTest.groovy+++ b/test/src/test/groovy/org/openremote/test/protocol/websocket/WebsocketClientProtocolTest.groovy@@ -106,11 +106,10 @@ class WebsocketClientProtocolTest extends Specification implements ManagerContaidef "Check websocket client protocol configuration and linked attribute deployment"() {given: "expected conditions"- def conditions = new PollingConditions(timeout: 10, delay: 1)+ def conditions = new PollingConditions(timeout: 10, delay: 0.2)- when: "the container starts"- def serverPort = findEphemeralPort()- def container = startContainer(defaultConfig(serverPort), defaultServices())+ and: "the container starts"+ def container = startContainer(defaultConfig(), defaultServices())def websocketClientProtocol = container.getService(WebsocketClientProtocol.class)def simulatorProtocol = container.getService(SimulatorProtocol.class)def assetStorageService = container.getService(AssetStorageService.class)@@ -118,11 +117,6 @@ class WebsocketClientProtocolTest extends Specification implements ManagerContaidef agentService = container.getService(AgentService.class)def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)- then: "the container should be running"- conditions.eventually {- assert container.isRunning()- }-when: "the web target builder is configured to use the mock HTTP server (to test subscriptions)"if (!websocketClientProtocol.client.configuration.isRegistered(mockServer)) {websocketClientProtocol.client.register(mockServer, Integer.MAX_VALUE)@@ -287,8 +281,5 @@ class WebsocketClientProtocolTest extends Specification implements ManagerContaiasset = assetStorageService.find(asset.getId(), true)assert asset.getAttribute("readCo2Level").flatMap{it.getValueAsNumber()}.orElse(null) == 600d}-- cleanup: "the server should be stopped"- stopContainer(container)}}diff --git a/test/src/test/groovy/org/openremote/test/protocol/websocket/WebsocketClientTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/websocket/WebsocketClientTest.groovyindex 8d146c674..7356386f7 100644--- a/test/src/test/groovy/org/openremote/test/protocol/websocket/WebsocketClientTest.groovy+++ b/test/src/test/groovy/org/openremote/test/protocol/websocket/WebsocketClientTest.groovy@@ -21,45 +21,76 @@ package org.openremote.test.protocol.websocketimport io.netty.channel.ChannelHandlerimport org.apache.http.client.utils.URIBuilder+import org.openremote.container.timer.TimerServiceimport org.openremote.container.web.OAuthPasswordGrantimport org.openremote.agent.protocol.io.AbstractNettyIoClientimport org.openremote.agent.protocol.websocket.WebsocketIoClientimport org.openremote.container.Container+import org.openremote.manager.agent.AgentServiceimport org.openremote.manager.asset.AssetProcessingService+import org.openremote.manager.asset.AssetStorageServiceimport org.openremote.manager.concurrent.ManagerExecutorServiceimport org.openremote.manager.setup.SetupServiceimport org.openremote.manager.setup.builtin.ManagerDemoSetupimport org.openremote.model.asset.AssetFilter+import org.openremote.model.asset.agent.AgentStatusEventimport org.openremote.model.asset.agent.ConnectionStatusimport org.openremote.model.attribute.AttributeEvent+import org.openremote.model.attribute.AttributeRef+import org.openremote.model.attribute.MetaItem+import org.openremote.model.attribute.MetaItemTypeimport org.openremote.model.event.TriggeredEventSubscription+import org.openremote.model.event.shared.CancelEventSubscriptionimport org.openremote.model.event.shared.EventSubscriptionimport org.openremote.model.value.Valuesimport org.openremote.test.ManagerContainerTraitimport spock.lang.Specificationimport spock.util.concurrent.PollingConditions+import java.util.concurrent.TimeUnit+import static org.openremote.container.util.MapAccess.getStringimport static org.openremote.manager.security.ManagerIdentityProvider.SETUP_ADMIN_PASSWORDimport static org.openremote.manager.security.ManagerIdentityProvider.SETUP_ADMIN_PASSWORD_DEFAULTimport static org.openremote.model.Constants.KEYCLOAK_CLIENT_IDimport static org.openremote.model.Constants.MASTER_REALM_ADMIN_USER+import static org.openremote.model.attribute.MetaItem.isMetaNameEqualTo/**- * This tests the {@link WebsocketIoClient} by connecting to the manager web socket+ * This tests the {@link WebsocketIoClient} by connecting to the manager web socket API which means it also tests+ * the API itself*/class WebsocketClientTest extends Specification implements ManagerContainerTrait {+ protected static <T> T messageFromString(String message, String prefix, Class<T> clazz) {+ try {+ message = message.substring(prefix.length())+ return Container.JSON.readValue(message, clazz)+ } catch (Exception e) {+ throw new IllegalArgumentException("Unable to parse message")+ }+ }++ protected static String messageToString(String prefix, Object message) {+ try {+ String str = Container.JSON.writeValueAsString(message);+ return prefix + str;+ } catch (Exception e) {+ throw new IllegalArgumentException("Unable to serialise message");+ }+ }+def "Check client"() {given: "expected conditions"- def conditions = new PollingConditions(timeout: 10, delay: 1)+ def conditions = new PollingConditions(timeout: 10, delay: 0.2)and: "the container is started"- def serverPort = findEphemeralPort()- def container = startContainer(defaultConfig(serverPort), defaultServices())+ def container = startContainer(defaultConfig(), defaultServices())def protocolExecutorService = container.getService(ManagerExecutorService.class)def assetProcessingService = container.getService(AssetProcessingService.class)+ def assetStorageService = container.getService(AssetStorageService.class)+ def agentService = container.getService(AgentService.class)def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)and: "a simple Websocket client"@@ -79,14 +110,17 @@ class WebsocketClientTest extends Specification implements ManagerContainerTraitand: "we add callback consumers to the client"def connectionStatus = client.getConnectionStatus()- String lastMessage+ List<String> receivedMessages = []client.addMessageConsumer({- message -> lastMessage = message+ message -> receivedMessages.add(message)})client.addConnectionStatusConsumer({status -> connectionStatus = status})+ and: "the system settles down"+ noEventProcessedIn(assetProcessingService, 500)+when: "we call connect on the client"client.connect()@@ -96,8 +130,8 @@ class WebsocketClientTest extends Specification implements ManagerContainerTraitassert connectionStatus == ConnectionStatus.CONNECTED}- when: "we subscribe to events produced by the server"- client.sendMessage(EventSubscription.SUBSCRIBE_MESSAGE_PREFIX + Container.JSON.writeValueAsString(+ when: "we subscribe to attribute events produced by the server"+ client.sendMessage(messageToString(EventSubscription.SUBSCRIBE_MESSAGE_PREFIX,new EventSubscription(AttributeEvent.class,new AssetFilter<AttributeEvent>().setAssetIds(managerDemoSetup.apartment1LivingroomId),@@ -106,20 +140,20 @@ class WebsocketClientTest extends Specification implements ManagerContainerTraitthen: "the server should return a subscribed event"conditions.eventually {- assert lastMessage != null- assert lastMessage.indexOf(EventSubscription.SUBSCRIBED_MESSAGE_PREFIX) == 0- def subscription = Container.JSON.readValue(lastMessage.substring(EventSubscription.SUBSCRIBED_MESSAGE_PREFIX.length()), EventSubscription.class)+ assert receivedMessages.size() == 1+ def subscription = messageFromString(receivedMessages[0], EventSubscription.SUBSCRIBED_MESSAGE_PREFIX, EventSubscription.class)+ assert subscription != nullassert subscription.subscriptionId == "1"}- when: "when an event occurs that should be sent to the client"+ when: "when apartment 1 living room temp changes"+ receivedMessages.clear()assetProcessingService.sendAttributeEvent(new AttributeEvent(managerDemoSetup.apartment1LivingroomId, "targetTemperature", Values.create(5)))then: "the client receives the event"conditions.eventually {- assert lastMessage != null- assert lastMessage.indexOf(TriggeredEventSubscription.MESSAGE_PREFIX) == 0- def triggeredEvent = Container.JSON.readValue(lastMessage.substring(TriggeredEventSubscription.MESSAGE_PREFIX.length()), TriggeredEventSubscription.class)+ assert receivedMessages.size() == 1+ def triggeredEvent = messageFromString(receivedMessages[0], TriggeredEventSubscription.MESSAGE_PREFIX, TriggeredEventSubscription.class)assert triggeredEvent.subscriptionId == "1"assert triggeredEvent.events.size() == 1assert ((AttributeEvent)triggeredEvent.events[0]).entityId == managerDemoSetup.apartment1LivingroomId@@ -127,10 +161,128 @@ class WebsocketClientTest extends Specification implements ManagerContainerTraitassert ((AttributeEvent)triggeredEvent.events[0]).value.flatMap{Values.getNumber(it)}.orElse(0) == 5}+ when: "time advances"+ advancePseudoClock(1, TimeUnit.SECONDS, container)++ and: "when apartment 1 living room temp is set to the same value again"+ receivedMessages.clear()+ assetProcessingService.sendAttributeEvent(new AttributeEvent(managerDemoSetup.apartment1LivingroomId, "targetTemperature", Values.create(5)))++ then: "the client should receive the event"+ conditions.eventually {+ assert receivedMessages.size() == 1+ def triggeredEvent = messageFromString(receivedMessages[0], TriggeredEventSubscription.MESSAGE_PREFIX, TriggeredEventSubscription.class)+ assert triggeredEvent.subscriptionId == "1"+ assert triggeredEvent.events.size() == 1+ assert ((AttributeEvent)triggeredEvent.events[0]).entityId == managerDemoSetup.apartment1LivingroomId+ assert ((AttributeEvent)triggeredEvent.events[0]).attributeName == "targetTemperature"+ assert ((AttributeEvent)triggeredEvent.events[0]).value.flatMap{Values.getNumber(it)}.orElse(0) == 5+ }++ when: "time advances"+ advancePseudoClock(1, TimeUnit.SECONDS, container)++ and: "when apartment 1 living room temp is set to null"+ receivedMessages.clear()+ assetProcessingService.sendAttributeEvent(new AttributeEvent(managerDemoSetup.apartment1LivingroomId, "targetTemperature", null))++ then: "the client receives the event"+ conditions.eventually {+ assert receivedMessages.size() == 1+ def triggeredEvent = messageFromString(receivedMessages[0], TriggeredEventSubscription.MESSAGE_PREFIX, TriggeredEventSubscription.class)+ assert triggeredEvent.subscriptionId == "1"+ assert triggeredEvent.events.size() == 1+ assert ((AttributeEvent)triggeredEvent.events[0]).entityId == managerDemoSetup.apartment1LivingroomId+ assert ((AttributeEvent)triggeredEvent.events[0]).attributeName == "targetTemperature"+ assert !((AttributeEvent)triggeredEvent.events[0]).value.isPresent()+ }++ when: "time advances"+ advancePseudoClock(1, TimeUnit.SECONDS, container)++ and: "when apartment 1 bathroom temp changes"+ receivedMessages.clear()+ assetProcessingService.sendAttributeEvent(new AttributeEvent(managerDemoSetup.apartment1BathroomId, "targetTemperature", Values.create(10)))++ then: "the bathroom target temp should have changed"+ conditions.eventually {+ def bathroom = assetStorageService.find(managerDemoSetup.apartment1BathroomId)+ assert bathroom.getAttribute("targetTemperature").flatMap{it.getValueAsNumber()}.orElse(0d) == 10d+ }++ and: "the client should not have received the event"+ conditions.eventually {+ assert receivedMessages.isEmpty()+ }+++ when: "a subscription is made to the agent status event"+ receivedMessages.clear()+ client.sendMessage(messageToString(EventSubscription.SUBSCRIBE_MESSAGE_PREFIX,+ new EventSubscription(+ AgentStatusEvent.class,+ null,+ "2",+ null)))++ then: "a subscribed event should have been received"+ conditions.eventually {+ assert receivedMessages.size() == 1+ def subscribedEvent = messageFromString(receivedMessages[0], EventSubscription.SUBSCRIBED_MESSAGE_PREFIX, EventSubscription.class)+ assert subscribedEvent.subscriptionId == "2"+ }++ when: "an existing protocol configuration is disabled"+ receivedMessages.clear()+ def agent = assetStorageService.find(managerDemoSetup.agentId, true)+ agent.getAttribute(managerDemoSetup.agentProtocolConfigName).get().addMeta(+ new MetaItem(MetaItemType.DISABLED)+ )+ agent = assetStorageService.merge(agent)++ then: "the agent status change event should have been received"+ conditions.eventually {+ assert receivedMessages.size() == 2+ def waitingEvent = messageFromString(receivedMessages[0], TriggeredEventSubscription.MESSAGE_PREFIX, TriggeredEventSubscription.class)+ def disabledEvent = messageFromString(receivedMessages[1], TriggeredEventSubscription.MESSAGE_PREFIX, TriggeredEventSubscription.class)+ assert waitingEvent.subscriptionId == "2"+ assert waitingEvent.events.size() == 1+ assert waitingEvent.events[0] instanceof AgentStatusEvent+ assert (waitingEvent.events[0] as AgentStatusEvent).protocolConfiguration.entityId == managerDemoSetup.agentId+ assert (waitingEvent.events[0] as AgentStatusEvent).protocolConfiguration.attributeName == managerDemoSetup.agentProtocolConfigName+ assert (waitingEvent.events[0] as AgentStatusEvent).connectionStatus == ConnectionStatus.WAITING+ assert disabledEvent.subscriptionId == "2"+ assert disabledEvent.events.size() == 1+ assert disabledEvent.events[0] instanceof AgentStatusEvent+ assert (disabledEvent.events[0] as AgentStatusEvent).protocolConfiguration.entityId == managerDemoSetup.agentId+ assert (disabledEvent.events[0] as AgentStatusEvent).protocolConfiguration.attributeName == managerDemoSetup.agentProtocolConfigName+ assert (disabledEvent.events[0] as AgentStatusEvent).connectionStatus == ConnectionStatus.DISABLED+ }++ when: "the agent status subscription is removed"+ receivedMessages.clear()+ client.sendMessage(CancelEventSubscription.MESSAGE_PREFIX + Container.JSON.writeValueAsString(+ new CancelEventSubscription(+ AgentStatusEvent.class,+ "2")))++ and: "the existing protocol configuration is re-enabled"+ agent.getAttribute(managerDemoSetup.agentProtocolConfigName).get().getMeta().removeIf(+ isMetaNameEqualTo(MetaItemType.DISABLED)+ )+ agent = assetStorageService.merge(agent)++ then: "the protocol should be CONNECTED but no new events should have been received"+ conditions.eventually {+ assert agentService.getProtocolConnectionStatus(+ new AttributeRef(managerDemoSetup.agentId, managerDemoSetup.agentProtocolConfigName)+ ) == ConnectionStatus.CONNECTED+ assert receivedMessages.isEmpty()+ }+cleanup: "the server should be stopped"if (client != null) {client.disconnect()}- stopContainer(container)}}diff --git a/test/src/test/groovy/org/openremote/test/rules/BasicRulesDeploymentTest.groovy b/test/src/test/groovy/org/openremote/test/rules/BasicRulesDeploymentTest.groovyindex f381f61f2..c13e2793b 100644--- a/test/src/test/groovy/org/openremote/test/rules/BasicRulesDeploymentTest.groovy+++ b/test/src/test/groovy/org/openremote/test/rules/BasicRulesDeploymentTest.groovy@@ -31,11 +31,10 @@ class BasicRulesDeploymentTest extends Specification implements ManagerContainerdef "Check basic rules engine deployment"() {given: "expected conditions"- def conditions = new PollingConditions(timeout: 10)+ def conditions = new PollingConditions(timeout: 10, delay: 0.2)and: "the container is started"- def serverPort = findEphemeralPort()- def container = startContainer(defaultConfig(serverPort), defaultServices())+ def container = startContainer(defaultConfig(), defaultServices())def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)def rulesService = container.getService(RulesService.class)@@ -55,7 +54,7 @@ class BasicRulesDeploymentTest extends Specification implements ManagerContainer).tokenexpect: "the rules engines to be ready"- new PollingConditions(initialDelay: 3, timeout: 10, delay: 1).eventually {+ new PollingConditions(timeout: 10, delay: 0.2).eventually {rulesImport.assertEnginesReady(rulesService, keycloakDemoSetup, managerDemoSetup)}@@ -147,16 +146,12 @@ class BasicRulesDeploymentTest extends Specification implements ManagerContainerthen: "the apartment rules engine should be removed"conditions.eventually {- assert rulesService.assetEngines.size() == 2+ assert rulesService.assetEngines.size() == 1def apartment2Engine = rulesService.assetEngines.get(managerDemoSetup.apartment2Id)def apartment3Engine = rulesService.assetEngines.get(managerDemoSetup.apartment3Id)- def peopleCounter3Engine = rulesService.assetEngines.get(managerDemoSetup.peopleCounter3AssetId)assert apartment2Engine == nullassert apartment3Engine != nullassert apartment3Engine.isRunning()- assert peopleCounter3Engine != null- assert peopleCounter3Engine.isRunning()-}when: "a broken rule definition is added to the global rules engine"@@ -209,16 +204,13 @@ class BasicRulesDeploymentTest extends Specification implements ManagerContainerand: "other rule engines should be unaffected"conditions.eventually {assert rulesService.tenantEngines.size() == 2- assert rulesService.assetEngines.size() == 1+ assert rulesService.assetEngines.size() == 0def masterEngine = rulesService.tenantEngines.get(keycloakDemoSetup.masterTenant.realm)def cityEngine = rulesService.tenantEngines.get(keycloakDemoSetup.tenantCity.realm)- def peopleCounter3Engine = rulesService.assetEngines.get(managerDemoSetup.peopleCounter3AssetId)assert masterEngine != nullassert masterEngine.isRunning()assert cityEngine != nullassert cityEngine.isRunning()- assert peopleCounter3Engine != null- assert peopleCounter3Engine.isRunning()}when: "the disabled tenant is re-enabled"@@ -230,7 +222,7 @@ class BasicRulesDeploymentTest extends Specification implements ManagerContainertenantBuildingEngine = rulesService.tenantEngines.get(keycloakDemoSetup.tenantBuilding.realm)apartment3Engine = rulesService.assetEngines.get(managerDemoSetup.apartment3Id)assert rulesService.tenantEngines.size() == 3- assert rulesService.assetEngines.size() == 2+ assert rulesService.assetEngines.size() == 1assert tenantBuildingEngine != nullassert tenantBuildingEngine.isRunning()assert tenantBuildingEngine.deployments.size() == 2@@ -309,8 +301,5 @@ class BasicRulesDeploymentTest extends Specification implements ManagerContainer// assert tenantCity != null// assert tenantCity.isRunning()// }-- cleanup: "the server should be stopped"- stopContainer(container)}}diff --git a/test/src/test/groovy/org/openremote/test/rules/BasicRulesImport.groovy b/test/src/test/groovy/org/openremote/test/rules/BasicRulesImport.groovyindex d1a11117c..d505ba837 100644--- a/test/src/test/groovy/org/openremote/test/rules/BasicRulesImport.groovy+++ b/test/src/test/groovy/org/openremote/test/rules/BasicRulesImport.groovy@@ -123,7 +123,7 @@ class BasicRulesImport {def tenantCityEngine = rulesService.tenantEngines.get(keycloakDemoSetup.tenantCity.realm)assert tenantCityEngine == null- assert rulesService.assetEngines.size() == 3+ assert rulesService.assetEngines.size() == 2apartment1Engine = rulesService.assetEngines.get(managerDemoSetup.apartment1Id)assert apartment1Engine == nullapartment2Engine = rulesService.assetEngines.get(managerDemoSetup.apartment2Id)@@ -140,13 +140,6 @@ class BasicRulesImport {assert apartment3Engine.deployments.size() == 1assert apartment3Engine.deployments.values().iterator().next().name == "Some apartment 3 demo rules"assert apartment3Engine.deployments.values().iterator().next().status == DEPLOYED- def peopleCounter3Engine = rulesService.assetEngines.get(managerDemoSetup.peopleCounter3AssetId)- assert peopleCounter3Engine != null- peopleCounter3Engine.disableTemporaryFactExpiration = true- assert peopleCounter3Engine.isRunning()- assert peopleCounter3Engine.deployments.size() == 1- assert peopleCounter3Engine.deployments.values().iterator().next().name == "PeopleCounter 3 Rules"- assert peopleCounter3Engine.deployments.values().iterator().next().status == DEPLOYEDreturn true}diff --git a/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy b/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovyindex ab9d9e687..31e1e526c 100644--- a/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy+++ b/test/src/test/groovy/org/openremote/test/rules/BasicRulesProcessingTest.groovy@@ -1,5 +1,6 @@package org.openremote.test.rules+import org.openremote.container.timer.TimerServiceimport org.openremote.manager.asset.AssetProcessingServiceimport org.openremote.manager.asset.AssetStorageServiceimport org.openremote.manager.rules.RulesEngine@@ -24,6 +25,8 @@ import org.openremote.test.ManagerContainerTraitimport spock.lang.Specificationimport spock.util.concurrent.PollingConditions+import java.util.concurrent.TimeUnit+import static org.openremote.model.rules.RulesetStatus.*import static org.openremote.manager.setup.builtin.ManagerDemoSetup.*import static org.openremote.test.rules.BasicRulesImport.assertRulesFired@@ -32,11 +35,10 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerdef "Check firing when deploying a new ruleset"() {given: "expected conditions"- def conditions = new PollingConditions(timeout: 10, initialDelay: 0.5, delay: 0.5)+ def conditions = new PollingConditions(timeout: 10, delay: 0.2)and: "the container is started"- def serverPort = findEphemeralPort()- def container = startContainer(defaultConfig(serverPort), defaultServices())+ def container = startContainer(defaultConfig(), defaultServices())def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)def rulesService = container.getService(RulesService.class)@@ -56,7 +58,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerassert rulesService.assetStates.size() == DEMO_RULE_STATES_GLOBALassert rulesImport.globalEngine.assetStates.size() == DEMO_RULE_STATES_GLOBALassert rulesImport.masterEngine.assetStates.size() == DEMO_RULE_STATES_SMART_OFFICE- assert rulesImport.tenantBuildingEngine.assetStates.size() == DEMO_RULE_STATES_CUSTOMER_A+ assert rulesImport.tenantBuildingEngine.assetStates.size() == DEMO_RULE_STATES_SMART_BUILDINGassert rulesImport.apartment2Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_2assert rulesImport.apartment3Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_3}@@ -114,18 +116,14 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerassertRulesFired(smartHomeEngine, 8)assertRulesFired(smartHomeEngine, ["Living Room All", "Kitchen All", "Kitchen Number Attributes", "Parent Type Residence", "Asset Type Room", "Boolean Attributes", "String attributes", "Number value types"])}-- cleanup: "the server should be stopped"- stopContainer(container)}def "Handle attribute event with no meta, asset create, update, delete"() {given: "expected conditions"- def conditions = new PollingConditions(timeout: 15, initialDelay: 0.5, delay: 0.5)+ def conditions = new PollingConditions(timeout: 15, delay: 0.2)and: "the container is started"- def serverPort = findEphemeralPort()- def container = startContainer(defaultConfig(serverPort), defaultServices())+ def container = startContainer(defaultConfig(), defaultServices())def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)def rulesService = container.getService(RulesService.class)@@ -170,7 +168,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerassert rulesService.assetStates.size() == DEMO_RULE_STATES_GLOBAL + 1assert rulesImport.globalEngine.assetStates.size() == DEMO_RULE_STATES_GLOBAL + 1assert rulesImport.masterEngine.assetStates.size() == DEMO_RULE_STATES_SMART_OFFICE- assert rulesImport.tenantBuildingEngine.assetStates.size() == DEMO_RULE_STATES_CUSTOMER_A + 1+ assert rulesImport.tenantBuildingEngine.assetStates.size() == DEMO_RULE_STATES_SMART_BUILDING + 1assert rulesImport.apartment2Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_2 + 1assert rulesImport.apartment3Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_3assertRulesFired(rulesImport.globalEngine, 1)@@ -184,7 +182,10 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerassertRulesFired(rulesImport.apartment3Engine, 0)}- when: "an attribute event is pushed into the system for an attribute with no RULE_STATE meta"+ when: "time advances"+ advancePseudoClock(1, TimeUnit.SECONDS, container)++ and: "an attribute event is pushed into the system for an attribute with no RULE_STATE meta"def globalLastFireTimestamp = rulesImport.globalEngine.lastFireTimestampdef masterLastFireTimestamp = rulesImport.masterEngine.lastFireTimestampdef tenantALastFireTimestamp = rulesImport.tenantBuildingEngine.lastFireTimestamp@@ -210,7 +211,10 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerassert rulesImport.apartment3Engine.lastFireTimestamp == apartment3LastFireTimestamp}- when: "the Kitchen room asset is modified to add a new attribute but RULE_STATE = true meta is not changed"+ when: "time advances"+ advancePseudoClock(1, TimeUnit.SECONDS, container)++ and: "the Kitchen room asset is modified to add a new attribute but RULE_STATE = true meta is not changed"globalLastFireTimestamp = rulesImport.globalEngine.lastFireTimestampmasterLastFireTimestamp = rulesImport.masterEngine.lastFireTimestamptenantALastFireTimestamp = rulesImport.tenantBuildingEngine.lastFireTimestamp@@ -240,7 +244,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerassert rulesService.assetStates.size() == DEMO_RULE_STATES_GLOBAL + 1assert rulesImport.globalEngine.assetStates.size() == DEMO_RULE_STATES_GLOBAL + 1assert rulesImport.masterEngine.assetStates.size() == DEMO_RULE_STATES_SMART_OFFICE- assert rulesImport.tenantBuildingEngine.assetStates.size() == DEMO_RULE_STATES_CUSTOMER_A + 1+ assert rulesImport.tenantBuildingEngine.assetStates.size() == DEMO_RULE_STATES_SMART_BUILDING + 1assert rulesImport.apartment2Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_2 + 1assert rulesImport.apartment3Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_3assertRulesFired(rulesImport.globalEngine, 1)@@ -267,7 +271,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerassert rulesService.assetStates.size() == DEMO_RULE_STATES_GLOBALassert rulesImport.globalEngine.assetStates.size() == DEMO_RULE_STATES_GLOBALassert rulesImport.masterEngine.assetStates.size() == DEMO_RULE_STATES_SMART_OFFICE- assert rulesImport.tenantBuildingEngine.assetStates.size() == DEMO_RULE_STATES_CUSTOMER_A+ assert rulesImport.tenantBuildingEngine.assetStates.size() == DEMO_RULE_STATES_SMART_BUILDINGassert rulesImport.apartment2Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_2assert rulesImport.apartment3Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_3assertRulesFired(rulesImport.globalEngine, 1)@@ -299,7 +303,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerassert rulesService.assetStates.size() == DEMO_RULE_STATES_GLOBAL + 2assert rulesImport.globalEngine.assetStates.size() == DEMO_RULE_STATES_GLOBAL + 2assert rulesImport.masterEngine.assetStates.size() == DEMO_RULE_STATES_SMART_OFFICE- assert rulesImport.tenantBuildingEngine.assetStates.size() == DEMO_RULE_STATES_CUSTOMER_A + 2+ assert rulesImport.tenantBuildingEngine.assetStates.size() == DEMO_RULE_STATES_SMART_BUILDING + 2assert rulesImport.apartment2Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_2 + 2assert rulesImport.apartment3Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_3assertRulesFired(rulesImport.globalEngine, 1)@@ -320,7 +324,7 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerassert rulesService.assetStates.size() == DEMO_RULE_STATES_GLOBALassert rulesImport.globalEngine.assetStates.size() == DEMO_RULE_STATES_GLOBALassert rulesImport.masterEngine.assetStates.size() == DEMO_RULE_STATES_SMART_OFFICE- assert rulesImport.tenantBuildingEngine.assetStates.size() == DEMO_RULE_STATES_CUSTOMER_A+ assert rulesImport.tenantBuildingEngine.assetStates.size() == DEMO_RULE_STATES_SMART_BUILDINGassert rulesImport.apartment2Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_2assert rulesImport.apartment3Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_3assertRulesFired(rulesImport.globalEngine, 1)@@ -331,18 +335,14 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerassertRulesFired(rulesImport.apartment2Engine, ["All"])assertRulesFired(rulesImport.apartment3Engine, 0)}-- cleanup: "the server should be stopped"- stopContainer(container)}def "Stop processing when engine in error state"() {given: "expected conditions"- def conditions = new PollingConditions(timeout: 10, delay: 0.5)+ def conditions = new PollingConditions(timeout: 10, delay: 0.2)and: "the container is started"- def serverPort = findEphemeralPort()- def container = startContainer(defaultConfig(serverPort), defaultServices())+ def container = startContainer(defaultConfig(), defaultServices())def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)def rulesService = container.getService(RulesService.class)@@ -397,8 +397,5 @@ class BasicRulesProcessingTest extends Specification implements ManagerContainerassert rulesImport.apartment2Engine.lastFireTimestamp > apartment2LastFireTimestampassert rulesImport.apartment3Engine.lastFireTimestamp > apartment3LastFireTimestamp}-- cleanup: "the server should be stopped"- stopContainer(container)}}diff --git a/test/src/test/groovy/org/openremote/test/rules/BasicRulesTimedExecutionTest.groovy b/test/src/test/groovy/org/openremote/test/rules/BasicRulesTimedExecutionTest.groovyindex 68a5136cb..e74405a74 100644--- a/test/src/test/groovy/org/openremote/test/rules/BasicRulesTimedExecutionTest.groovy+++ b/test/src/test/groovy/org/openremote/test/rules/BasicRulesTimedExecutionTest.groovy@@ -26,11 +26,10 @@ class BasicRulesTimedExecutionTest extends Specification implements ManagerContadef "Check firing of timer rules with realtime clock"() {given: "expected conditions"- def conditions = new PollingConditions(timeout: 30)+ def conditions = new PollingConditions(timeout: 30, delay: 0.2)and: "the container is started"- def serverPort = findEphemeralPort()- def container = startContainer(defaultConfig(serverPort), defaultServices())+ def container = startContainer(defaultConfig(), defaultServices())def rulesService = container.getService(RulesService.class)def rulesetStorageService = container.getService(RulesetStorageService.class)@@ -62,17 +61,13 @@ class BasicRulesTimedExecutionTest extends Specification implements ManagerContaassert globalEngineFiredRules.size() > 10assert globalEngineFiredRules.containsAll(expectedFiredRules)}-- cleanup: "the server should be stopped"- stopContainer(container)}def "Check firing of timer rules with pseudo clock"() {given: "the container environment is started"- def conditions = new PollingConditions(timeout: 30, delay: 1)- def serverPort = findEphemeralPort()- def container = startContainerWithPseudoClock(defaultConfig(serverPort), defaultServices())+ def conditions = new PollingConditions(timeout: 30, delay: 0.2)+ def container = startContainer(defaultConfig(), defaultServices())def rulesService = container.getService(RulesService.class)def rulesetStorageService = container.getService(RulesetStorageService.class)@@ -99,24 +94,21 @@ class BasicRulesTimedExecutionTest extends Specification implements ManagerConta}and: "after a few seconds the rule engines should not have fired any rules"- new PollingConditions(initialDelay: 3).eventually {+ new PollingConditions(timeout: 5, initialDelay: 3).eventually {assert globalEngineFiredRules.size() == 0}when: "the clock is advanced by a few seconds"- advancePseudoClock(100, SECONDS, container, globalEngine)+ advancePseudoClock(100, SECONDS, container)// TODO Weird behavior of timer rules, pseudo clock, and active mode: More than 5 seconds is needed to fire rule twice// even more strange it stops at 2 even when advanced for more time. The same problems are with timer(cron: )// realtime clock seems to be OKthen: "the rule engines should have fired the timed execution rule in the background"- new PollingConditions(initialDelay: 3).eventually {+ new PollingConditions(timeout: 5,initialDelay: 3).eventually {def expectedFiredRules = ["Log something every 2 seconds"]assert globalEngineFiredRules.size() > 1assert globalEngineFiredRules.containsAll(expectedFiredRules)}-- cleanup: "the server should be stopped"- stopContainer(container)}}diff --git a/test/src/test/groovy/org/openremote/test/rules/BasicRulesetResourceTest.groovy b/test/src/test/groovy/org/openremote/test/rules/BasicRulesetResourceTest.groovyindex 4835773c0..cc99f918c 100644--- a/test/src/test/groovy/org/openremote/test/rules/BasicRulesetResourceTest.groovy+++ b/test/src/test/groovy/org/openremote/test/rules/BasicRulesetResourceTest.groovy@@ -26,8 +26,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainerdef "Access rules as superuser"() {given: "the server container is started"- def serverPort = findEphemeralPort()- def container = startContainer(defaultConfig(serverPort), defaultServices())+ def container = startContainer(defaultConfig(), defaultServices())def rulesetStorageService = container.getService(RulesetStorageService.class)def rulesService = container.getService(RulesService.class)def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)@@ -49,7 +48,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainerdef rulesetResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(RulesResource.class)expect: "the rules engines to be ready"- new PollingConditions(initialDelay: 2, timeout: 10, delay: 1).eventually {+ new PollingConditions(timeout: 10, delay: 0.2).eventually {rulesImport.assertEnginesReady(rulesService, keycloakDemoSetup, managerDemoSetup)}@@ -293,16 +292,12 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainerassetRuleset.name == "Test asset definition"assetRuleset.rules == "SomeRulesCode"assetRuleset.assetId == managerDemoSetup.apartment2Id-- cleanup: "the server should be stopped"- stopContainer(container)}def "Access rules as testuser1"() {given: "the server container is started"- def serverPort = findEphemeralPort()- def container = startContainer(defaultConfig(serverPort), defaultServices())+ def container = startContainer(defaultConfig(), defaultServices())def rulesetStorageService = container.getService(RulesetStorageService.class)def rulesService = container.getService(RulesService.class)def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)@@ -324,7 +319,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainerdef rulesetResource = getClientApiTarget(serverUri(serverPort), MASTER_REALM, accessToken).proxy(RulesResource.class)expect: "the rules engines to be ready"- new PollingConditions(initialDelay: 3, timeout: 20, delay: 1).eventually {+ new PollingConditions(timeout: 10, delay: 0.2).eventually {rulesImport.assertEnginesReady(rulesService, keycloakDemoSetup, managerDemoSetup)}@@ -523,16 +518,12 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainerthen: "access should be forbidden"ex = thrown()ex.response.status == 403-- cleanup: "the server should be stopped"- stopContainer(container)}def "Access rules as testuser2"() {given: "the server container is started"- def serverPort = findEphemeralPort()- def container = startContainer(defaultConfig(serverPort), defaultServices())+ def container = startContainer(defaultConfig(), defaultServices())def rulesetStorageService = container.getService(RulesetStorageService.class)def rulesService = container.getService(RulesService.class)def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)@@ -554,7 +545,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainerdef rulesetResource = getClientApiTarget(serverUri(serverPort), keycloakDemoSetup.tenantBuilding.realm, accessToken).proxy(RulesResource.class)expect: "the rules engines to be ready"- new PollingConditions(initialDelay: 3, timeout: 20, delay: 1).eventually {+ new PollingConditions(timeout: 10, delay: 0.2).eventually {rulesImport.assertEnginesReady(rulesService, keycloakDemoSetup, managerDemoSetup)}@@ -669,16 +660,12 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainerthen: "access should be forbidden"ex = thrown()ex.response.status == 403-- cleanup: "the server should be stopped"- stopContainer(container)}def "Access rules as testuser3"() {given: "the server container is started"- def serverPort = findEphemeralPort()- def container = startContainer(defaultConfig(serverPort), defaultServices())+ def container = startContainer(defaultConfig(), defaultServices())def rulesetStorageService = container.getService(RulesetStorageService.class)def rulesService = container.getService(RulesService.class)def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)@@ -700,7 +687,7 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainerdef rulesetResource = getClientApiTarget(serverUri(serverPort), keycloakDemoSetup.tenantBuilding.realm, accessToken).proxy(RulesResource.class)expect: "the rules engines to be ready"- new PollingConditions(initialDelay: 3, timeout: 20, delay: 1).eventually {+ new PollingConditions(timeout: 10, delay: 0.2).eventually {rulesImport.assertEnginesReady(rulesService, keycloakDemoSetup, managerDemoSetup)}@@ -885,8 +872,5 @@ class BasicRulesetResourceTest extends Specification implements ManagerContainerthen: "access should be forbidden"ex = thrown()ex.response.status == 403-- cleanup: "the server should be stopped"- stopContainer(container)}}diff --git a/test/src/test/groovy/org/openremote/test/rules/residence/FlowRulesTest.groovy b/test/src/test/groovy/org/openremote/test/rules/residence/FlowRulesTest.groovyindex 025ec9346..c9e09055f 100644--- a/test/src/test/groovy/org/openremote/test/rules/residence/FlowRulesTest.groovy+++ b/test/src/test/groovy/org/openremote/test/rules/residence/FlowRulesTest.groovy@@ -1,39 +1,44 @@package org.openremote.test.rules.residence+import org.openremote.container.timer.TimerServiceimport org.openremote.manager.asset.AssetProcessingServiceimport org.openremote.manager.asset.AssetStorageServiceimport org.openremote.manager.rules.FlowRulesBuilder+import org.openremote.manager.rules.RulesEngineimport org.openremote.manager.rules.RulesServiceimport org.openremote.manager.rules.RulesetStorageService+import org.openremote.manager.rules.geofence.ORConsoleGeofenceAssetAdapterimport org.openremote.manager.setup.SetupServiceimport org.openremote.manager.setup.builtin.ManagerDemoSetupimport org.openremote.model.attribute.AttributeEventimport org.openremote.model.rules.GlobalRulesetimport org.openremote.model.rules.Ruleset+import org.openremote.model.rules.TemporaryFactimport org.openremote.model.rules.flow.NodeCollectionimport org.openremote.model.value.Valuesimport org.openremote.test.ManagerContainerTraitimport spock.lang.Specificationimport spock.util.concurrent.PollingConditions+import java.util.concurrent.TimeUnit+import static org.openremote.model.rules.RulesetStatus.DEPLOYEDclass FlowRulesTest extends Specification implements ManagerContainerTrait {- private FlowRulesBuilder builder;+ private FlowRulesBuilder builderdef "Execute flow rules"() {given: "expected conditions"- def conditions = new PollingConditions(timeout: 15)+ def conditions = new PollingConditions(timeout: 10, delay: 0.2)and: "the container is started"- def serverPort = findEphemeralPort()- def container = startContainer(defaultConfig(serverPort), defaultServices())+ def container = startContainer(defaultConfig(), defaultServices())def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)def rulesService = container.getService(RulesService.class)def rulesetStorageService = container.getService(RulesetStorageService.class)def assetStorageService = container.getService(AssetStorageService.class)def assetProcessingService = container.getService(AssetProcessingService.class)- def startTemperature = 25;+ def startTemperature = 25and: "relevant attributes have been populated"assetProcessingService.sendAttributeEvent(new AttributeEvent(@@ -41,6 +46,7 @@ class FlowRulesTest extends Specification implements ManagerContainerTrait {"targetTemperature",Values.create(startTemperature)))+assetProcessingService.sendAttributeEvent(new AttributeEvent(managerDemoSetup.apartment1Bedroom1Id,"targetTemperature",@@ -51,7 +57,6 @@ class FlowRulesTest extends Specification implements ManagerContainerTrait {String json = getClass().getResource("/org/openremote/test/rules/BasicFlowRules.json").textjson = json.replaceAll("%LIVING ROOM ID%", managerDemoSetup.apartment1LivingroomId)json = json.replaceAll("%BEDROOM ID%", managerDemoSetup.apartment1Bedroom1Id)- println(json);NodeCollection realCollection = container.JSON.readValue(json, NodeCollection.class)def ruleset = (new GlobalRuleset(realCollection.name,@@ -59,6 +64,7 @@ class FlowRulesTest extends Specification implements ManagerContainerTrait {json))rulesetStorageService.merge(ruleset)+then: "the flow should be deployed"conditions.eventually {assert rulesService.globalEngine != null@@ -66,19 +72,12 @@ class FlowRulesTest extends Specification implements ManagerContainerTrait {assert rulesService.globalEngine.deployments.values().any({ it.name == realCollection.name && it.status == DEPLOYED})}- println(assetStorageService.- find(managerDemoSetup.apartment1Bedroom1Id).getAttribute("targetTemperature").get().getValue().present);-and: "the flow should be executed correctly"conditions.eventually {def bedroomTargetTemp = assetStorageService.find(managerDemoSetup.apartment1Bedroom1Id).getAttribute("targetTemperature").get().getValueAsNumber().get()- println(bedroomTargetTemp)assert bedroomTargetTemp.intValue() == (startTemperature.intValue() + 10) : ("it was actually " + bedroomTargetTemp.intValue())//convert to int considering floating point inaccuracy}-- cleanup: "the container is stopped"- container.stop()}}diff --git a/test/src/test/groovy/org/openremote/test/rules/residence/JsonRulesTest.groovy b/test/src/test/groovy/org/openremote/test/rules/residence/JsonRulesTest.groovyindex dca9546a5..e917305fc 100644--- a/test/src/test/groovy/org/openremote/test/rules/residence/JsonRulesTest.groovy+++ b/test/src/test/groovy/org/openremote/test/rules/residence/JsonRulesTest.groovy@@ -1,12 +1,13 @@package org.openremote.test.rules.residence-import com.google.common.collect.Lists+import com.google.firebase.messaging.Messageimport org.openremote.container.Containerimport org.openremote.container.timer.TimerServiceimport org.openremote.manager.asset.AssetProcessingServiceimport org.openremote.manager.asset.AssetStorageServiceimport org.openremote.manager.notification.EmailNotificationHandler+import org.openremote.manager.notification.NotificationServiceimport org.openremote.manager.notification.PushNotificationHandlerimport org.openremote.manager.rules.RulesEngineimport org.openremote.manager.rules.RulesService@@ -41,8 +42,9 @@ import spock.util.concurrent.PollingConditionsimport java.time.Instantimport java.time.temporal.ChronoUnit-import static java.util.concurrent.TimeUnit.*-import static org.openremote.manager.setup.builtin.ManagerDemoSetup.DEMO_RULE_STATES_CUSTOMER_A+import static java.util.concurrent.TimeUnit.HOURS+import static java.util.concurrent.TimeUnit.MILLISECONDS+import static org.openremote.manager.setup.builtin.ManagerDemoSetup.DEMO_RULE_STATES_SMART_BUILDINGimport static org.openremote.model.Constants.KEYCLOAK_CLIENT_IDimport static org.openremote.model.attribute.AttributeType.LOCATIONimport static org.openremote.model.value.Values.parse@@ -56,42 +58,7 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {List<Notification.Target> targets = []List<Notification.Target> emailTargets = []- given: "a mock push notification handler"- PushNotificationHandler mockPushNotificationHandler = Spy(PushNotificationHandler) {- isValid() >> true-- sendMessage(_ as Long, _ as Notification.Source, _ as String, _ as Notification.Target, _ as AbstractNotificationMessage) >> {- id, source, sourceId, target, message ->- notificationMessages << message- targets << target- callRealMethod()- }-- // Assume sent to FCM- sendMessage(_ as Message) >> {- message -> return NotificationSendResult.success()- }- }-- and: "a mock email notification handler"- EmailNotificationHandler mockEmailNotificationHandler = Spy(EmailNotificationHandler) {- isValid() >> true-- sendMessage(_ as Long, _ as Notification.Source, _ as String, _ as Notification.Target, _ as AbstractNotificationMessage) >> {- id, source, sourceId, target, message ->- emailTargets << target- callRealMethod()- }-- // Assume sent to FCM- sendMessage(_ as Email) >> {- email ->- emailMessages << email.get(0)- return NotificationSendResult.success()- }- }-- and: "the geofence notifier debounce is set to a small value for testing"+ given: "the geofence notifier debounce is set to a small value for testing"def originalDebounceMillis = ORConsoleGeofenceAssetAdapter.NOTIFY_ASSETS_DEBOUNCE_MILLISORConsoleGeofenceAssetAdapter.NOTIFY_ASSETS_DEBOUNCE_MILLIS = 100@@ -100,12 +67,11 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {TemporaryFact.GUARANTEED_MIN_EXPIRATION_MILLIS = 100and: "the container environment is started with the mock handler"- def conditions = new PollingConditions(timeout: 15, delay: 1)- def serverPort = findEphemeralPort()- def services = Lists.newArrayList(defaultServices())- services.replaceAll{it instanceof PushNotificationHandler ? mockPushNotificationHandler : it}- services.replaceAll{it instanceof EmailNotificationHandler ? mockEmailNotificationHandler : it}- def container = startContainerWithPseudoClock(defaultConfig(serverPort), services)+ def conditions = new PollingConditions(timeout: 15, delay: 0.2)+ def container = startContainer(defaultConfig(), defaultServices())+ def pushNotificationHandler = container.getService(PushNotificationHandler.class)+ def emailNotificationHandler = container.getService(EmailNotificationHandler.class)+ def notificationService = container.getService(NotificationService.class)def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)def keycloakDemoSetup = container.getService(SetupService.class).getTaskOfType(KeycloakDemoSetup.class)def rulesService = container.getService(RulesService.class)@@ -115,6 +81,38 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {def assetProcessingService = container.getService(AssetProcessingService.class)RulesEngine tenantBuildingEngine+ and: "a mock push notification handler"+ PushNotificationHandler mockPushNotificationHandler = Spy(pushNotificationHandler)+ mockPushNotificationHandler.isValid() >> true+ mockPushNotificationHandler.sendMessage(_ as Long, _ as Notification.Source, _ as String, _ as Notification.Target, _ as AbstractNotificationMessage) >> {+ id, source, sourceId, target, message ->+ notificationMessages << message+ targets << target+ callRealMethod()+ }+ // Assume sent to FCM+ mockPushNotificationHandler.sendMessage(_ as Message) >> {+ message -> return NotificationSendResult.success()+ }+ notificationService.notificationHandlerMap.put(pushNotificationHandler.getTypeName(), mockPushNotificationHandler)++ and: "a mock email notification handler"+ EmailNotificationHandler mockEmailNotificationHandler = Spy(emailNotificationHandler)+ mockEmailNotificationHandler.isValid() >> true+ mockEmailNotificationHandler.sendMessage(_ as Long, _ as Notification.Source, _ as String, _ as Notification.Target, _ as AbstractNotificationMessage) >> {+ id, source, sourceId, target, message ->+ emailTargets << target+ callRealMethod()+ }++ // Assume sent to FCM+ mockEmailNotificationHandler.sendMessage(_ as Email) >> {+ email ->+ emailMessages << email.get(0)+ return NotificationSendResult.success()+ }+ notificationService.notificationHandlerMap.put(emailNotificationHandler.getTypeName(), mockEmailNotificationHandler)+and: "some rules"Ruleset ruleset = new TenantRuleset(keycloakDemoSetup.tenantBuilding.realm,@@ -128,7 +126,7 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {tenantBuildingEngine = rulesService.tenantEngines.get(keycloakDemoSetup.tenantBuilding.realm)assert tenantBuildingEngine != nullassert tenantBuildingEngine.isRunning()- assert tenantBuildingEngine.assetStates.size() == DEMO_RULE_STATES_CUSTOMER_A+ assert tenantBuildingEngine.assetStates.size() == DEMO_RULE_STATES_SMART_BUILDINGassert !tenantBuildingEngine.trackLocationPredicates}@@ -243,7 +241,7 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {}and: "after a few seconds the rule should not have fired again"- new PollingConditions(initialDelay: 1).eventually {+ new PollingConditions(timeout: 5, initialDelay: 1).eventually {assert notificationMessages.findAll {it.title == "Test title"}.size() == 1}@@ -271,7 +269,7 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {assetProcessingService.sendAttributeEvent(attributeEvent, AttributeEvent.Source.CLIENT)then: "after a few seconds the rule should not have fired again"- new PollingConditions(initialDelay: 1).eventually {+ new PollingConditions(timeout: 5, initialDelay: 1).eventually {assert notificationMessages.findAll {it.title == "Test title"}.size() == 2}@@ -308,7 +306,7 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {assetProcessingService.sendAttributeEvent(attributeEvent, AttributeEvent.Source.CLIENT)then: "after a few seconds the rule should not have fired again"- new PollingConditions(initialDelay: 1).eventually {+ new PollingConditions(timeout: 5, initialDelay: 1).eventually {assert notificationMessages.findAll {it.title == "Test title"}.size() == 3}@@ -464,11 +462,12 @@ class JsonRulesTest extends Specification implements ManagerContainerTrait {assert tenantBuildingEngine.deployments.find{it.key == ruleset.id}.value.status == RulesetStatus.EXPIRED}- cleanup: "stop the container"+ cleanup: "static variables are reset and the mock is removed"RulesEngine.PAUSE_SCHEDULER = originalPauseRulesEngine.UNPAUSE_SCHEDULER = originalUnpauseORConsoleGeofenceAssetAdapter.NOTIFY_ASSETS_DEBOUNCE_MILLIS = originalDebounceMillisTemporaryFact.GUARANTEED_MIN_EXPIRATION_MILLIS = originalExpirationMillis- stopContainer(container)+ notificationService.notificationHandlerMap.put(emailNotificationHandler.getTypeName(), emailNotificationHandler)+ notificationService.notificationHandlerMap.put(pushNotificationHandler.getTypeName(), pushNotificationHandler)}}diff --git a/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceAllLightsOffTest.groovy b/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceAllLightsOffTest.groovyindex f3a531fe1..81147649c 100644--- a/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceAllLightsOffTest.groovy+++ b/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceAllLightsOffTest.groovy@@ -23,9 +23,8 @@ class ResidenceAllLightsOffTest extends Specification implements ManagerContainedef "Turn all lights off"() {given: "the container environment is started"- def conditions = new PollingConditions(timeout: 10, delay: 1)- def serverPort = findEphemeralPort()- def container = startContainerWithPseudoClock(defaultConfig(serverPort), defaultServices())+ def conditions = new PollingConditions(timeout: 10, delay: 0.2)+ def container = startContainer(defaultConfig(), defaultServices())def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)def rulesService = container.getService(RulesService.class)def rulesetStorageService = container.getService(RulesetStorageService.class)@@ -86,14 +85,11 @@ class ResidenceAllLightsOffTest extends Specification implements ManagerContaine)then: "the light should still be on after a few seconds (the all lights off event expires after 3 seconds)"- new PollingConditions(initialDelay: 3).eventually {+ new PollingConditions(timeout: 5, initialDelay: 3).eventually {assert apartment2Engine.assetStates.size() == DEMO_RULE_STATES_APARTMENT_2assert apartment2Engine.assetEvents.size() == 0def livingroomAsset = assetStorageService.find(managerDemoSetup.apartment2LivingroomId, true)assert livingroomAsset.getAttribute("lightSwitch").get().valueAsBoolean.get()}-- cleanup: "stop the container"- stopContainer(container)}}diff --git a/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceAutoVentilationTest.groovy b/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceAutoVentilationTest.groovyindex defdab81f..fd9792e86 100644--- a/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceAutoVentilationTest.groovy+++ b/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceAutoVentilationTest.groovy@@ -26,9 +26,8 @@ class ResidenceAutoVentilationTest extends Specification implements ManagerContadef "Auto ventilation with CO2 detection"() {given: "the container environment is started"- def conditions = new PollingConditions(timeout: 20, delay: 1)- def serverPort = findEphemeralPort()- def container = startContainerWithPseudoClock(defaultConfig(serverPort), defaultServices())+ def conditions = new PollingConditions(timeout: 20, delay: 0.2)+ def container = startContainer(defaultConfig(), defaultServices())def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)def rulesService = container.getService(RulesService.class)def assetStorageService = container.getService(AssetStorageService.class)@@ -186,9 +185,6 @@ class ResidenceAutoVentilationTest extends Specification implements ManagerContadef apartment = assetStorageService.find(managerDemoSetup.apartment1Id, true)assert apartment.getAttribute("ventilationLevel").get().getValueAsNumber().get() == 64d}-- cleanup: "the server should be stopped"- stopContainer(container)}}diff --git a/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceNotifyAlarmTriggerTest.groovy b/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceNotifyAlarmTriggerTest.groovyindex 476fa6199..ada7901f9 100644--- a/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceNotifyAlarmTriggerTest.groovy+++ b/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceNotifyAlarmTriggerTest.groovy@@ -1,9 +1,10 @@package org.openremote.test.rules.residence-import com.google.common.collect.Lists+import com.google.firebase.messaging.Messageimport org.openremote.manager.asset.AssetProcessingServiceimport org.openremote.manager.asset.AssetStorageService+import org.openremote.manager.notification.NotificationServiceimport org.openremote.manager.notification.PushNotificationHandlerimport org.openremote.manager.rules.RulesEngineimport org.openremote.manager.rules.RulesService@@ -45,36 +46,34 @@ class ResidenceNotifyAlarmTriggerTest extends Specification implements ManagerCodef targetIds = []def messages = []- given: "a mock push notification handler"- PushNotificationHandler mockPushNotificationHandler = Spy(PushNotificationHandler) {- isValid() >> true-- sendMessage(_ as Long, _ as Notification.Source, _ as String, _ as Notification.Target, _ as AbstractNotificationMessage) >> {- id, source, sourceId, target, message ->- notificationIds << id- targetTypes << target.type- targetIds << target.id- messages << message- callRealMethod()- }-- // Assume sent to FCM- sendMessage(_ as Message) >> {- message -> return NotificationSendResult.success()- }- }-- and: "the container environment is started with the mock handler"- def conditions = new PollingConditions(timeout: 20, delay: 1)- def serverPort = findEphemeralPort()- def services = Lists.newArrayList(defaultServices())- services.replaceAll{it instanceof PushNotificationHandler ? mockPushNotificationHandler : it}- def container = startContainerWithPseudoClock(defaultConfig(serverPort), services)+ given: "the container environment is started with the mock handler"+ def conditions = new PollingConditions(timeout: 20, delay: 0.2)+ def container = startContainer(defaultConfig(), defaultServices())def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)def rulesService = container.getService(RulesService.class)+ def notificationService = container.getService(NotificationService.class)+ def pushNotificationHandler = container.getService(PushNotificationHandler.class)def assetProcessingService = container.getService(AssetProcessingService.class)def assetStorageService = container.getService(AssetStorageService.class)def rulesetStorageService = container.getService(RulesetStorageService.class)++ and: "a mock push notification handler is injected"+ PushNotificationHandler mockPushNotificationHandler = Spy(pushNotificationHandler)+ mockPushNotificationHandler.isValid() >> true+ mockPushNotificationHandler.sendMessage(_ as Long, _ as Notification.Source, _ as String, _ as Notification.Target, _ as AbstractNotificationMessage) >> {+ id, source, sourceId, target, message ->+ notificationIds << id+ targetTypes << target.type+ targetIds << target.id+ messages << message+ callRealMethod()+ }+ // Assume sent to FCM+ mockPushNotificationHandler.sendMessage(_ as Message) >> {+ message -> return NotificationSendResult.success()+ }+ notificationService.notificationHandlerMap.put(pushNotificationHandler.getTypeName(), mockPushNotificationHandler)+RulesEngine apartment1Engineand: "some rules"@@ -231,8 +230,7 @@ class ResidenceNotifyAlarmTriggerTest extends Specification implements ManagerCoassert notificationIds.size() == 2}- cleanup: "the server should be stopped"- stopContainer(container)+ cleanup: "the mock is removed"+ notificationService.notificationHandlerMap.put(pushNotificationHandler.getTypeName(), pushNotificationHandler)}--}\ No newline at end of file+}diff --git a/test/src/test/groovy/org/openremote/test/rules/residence/ResidencePresenceDetectionTest.groovy b/test/src/test/groovy/org/openremote/test/rules/residence/ResidencePresenceDetectionTest.groovyindex 1ff3e527b..46b9b83bc 100644--- a/test/src/test/groovy/org/openremote/test/rules/residence/ResidencePresenceDetectionTest.groovy+++ b/test/src/test/groovy/org/openremote/test/rules/residence/ResidencePresenceDetectionTest.groovy@@ -25,9 +25,8 @@ class ResidencePresenceDetectionTest extends Specification implements ManagerCondef "Presence detection with motion sensor"() {given: "the container environment is started"- def conditions = new PollingConditions(timeout: 30, delay: 1)- def serverPort = findEphemeralPort()- def container = startContainerWithPseudoClock(defaultConfig(serverPort), defaultServices())+ def conditions = new PollingConditions(timeout: 30, delay: 0.2)+ def container = startContainer(defaultConfig(), defaultServices())def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)def rulesService = container.getService(RulesService.class)def assetStorageService = container.getService(AssetStorageService.class)@@ -149,17 +148,13 @@ class ResidencePresenceDetectionTest extends Specification implements ManagerConassert !hallway.getAttribute("presenceDetected").get().getValueAsBoolean().get()assert hallway.getAttribute("lastPresenceDetected").get().getValueAsNumber().get() == expectedLastPresenceDetected}-- cleanup: "the server should be stopped"- stopContainer(container)}def "Presence detection with motion sensor and confirmation with CO2 level"() {given: "the container environment is started"- def conditions = new PollingConditions(timeout: 20, delay: 1)- def serverPort = findEphemeralPort()- def container = startContainerWithPseudoClock(defaultConfig(serverPort), defaultServices())+ def conditions = new PollingConditions(timeout: 20, delay: 0.2)+ def container = startContainer(defaultConfig(), defaultServices())def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)def rulesService = container.getService(RulesService.class)def assetProcessingService = container.getService(AssetProcessingService.class)@@ -279,18 +274,14 @@ class ResidencePresenceDetectionTest extends Specification implements ManagerConassert !roomAsset.getAttribute("presenceDetected").get().getValueAsBoolean().get()assert roomAsset.getAttribute("lastPresenceDetected").get().getValueAsNumber().get() == expectedLastPresenceDetected}-- cleanup: "the server should be stopped"- stopContainer(container)}/* TODO Migrate to JS, didn't compile even with Droolsdef "Presence prediction rules compilation"() {given: "the container environment is started"- def conditions = new PollingConditions(timeout: 100, delay: 1)- def serverPort = findEphemeralPort()- def container = startContainerWithPseudoClock(defaultConfig(serverPort), defaultServices())+ def conditions = new PollingConditions(timeout: 100, delay: 0.2)+ def container = startContainer(defaultConfig(), defaultServices())def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)def rulesService = container.getService(RulesService.class)def assetStorageService = container.getService(AssetStorageService.class)@@ -313,9 +304,6 @@ class ResidencePresenceDetectionTest extends Specification implements ManagerConassert apartment1Engine.isRunning()// assert apartment1Engine.knowledgeSession.factCount == DEMO_RULE_STATES_APARTMENT_1}-- cleanup: "the server should be stopped"- stopContainer(container)}*/diff --git a/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceSmartSwitchTest.groovy b/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceSmartSwitchTest.groovyindex 9d7c2b39b..5ca9a5582 100644--- a/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceSmartSwitchTest.groovy+++ b/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceSmartSwitchTest.groovy@@ -25,9 +25,8 @@ class ResidenceSmartSwitchTest extends Specification implements ManagerContainerdef "Set mode ON_AT and begin/end cycle time in future"() {given: "the container environment is started"- def conditions = new PollingConditions(timeout: 10, delay: 1)- def serverPort = findEphemeralPort()- def container = startContainerWithPseudoClock(defaultConfig(serverPort), defaultServices())+ def conditions = new PollingConditions(timeout: 10, delay: 0.2)+ def container = startContainer(defaultConfig(), defaultServices())def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)def rulesService = container.getService(RulesService.class)def assetStorageService = container.getService(AssetStorageService.class)@@ -146,17 +145,13 @@ class ResidenceSmartSwitchTest extends Specification implements ManagerContainerassert !kitchen.getAttribute("smartSwitchStopTimeC").get().getValue().isPresent()assert !kitchen.getAttribute("smartSwitchEnabledC").get().getValue().isPresent()}-- cleanup: "the server should be stopped"- stopContainer(container)}def "Set mode ON_AT and begin/end cycle time in past"() {given: "the container environment is started"- def conditions = new PollingConditions(timeout: 10, delay: 1)- def serverPort = findEphemeralPort()- def container = startContainerWithPseudoClock(defaultConfig(serverPort), defaultServices())+ def conditions = new PollingConditions(timeout: 10, delay: 0.2)+ def container = startContainer(defaultConfig(), defaultServices())def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)def rulesService = container.getService(RulesService.class)def assetStorageService = container.getService(AssetStorageService.class)@@ -243,17 +238,13 @@ class ResidenceSmartSwitchTest extends Specification implements ManagerContainerassert !kitchen.getAttribute("smartSwitchStopTimeC").get().getValue().isPresent()assert !kitchen.getAttribute("smartSwitchEnabledC").get().getValue().isPresent()}-- cleanup: "the server should be stopped"- stopContainer(container)}def "Set mode READY_AT and begin/end cycle time in future"() {given: "the container environment is started"- def conditions = new PollingConditions(timeout: 10, delay: 1)- def serverPort = findEphemeralPort()- def container = startContainerWithPseudoClock(defaultConfig(serverPort), defaultServices())+ def conditions = new PollingConditions(timeout: 10, delay: 0.2)+ def container = startContainer(defaultConfig(), defaultServices())def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)def rulesService = container.getService(RulesService.class)def assetStorageService = container.getService(AssetStorageService.class)@@ -364,17 +355,13 @@ class ResidenceSmartSwitchTest extends Specification implements ManagerContainerassert !kitchen.getAttribute("smartSwitchStopTimeC").get().getValue().isPresent()assert !kitchen.getAttribute("smartSwitchEnabledC").get().getValue().isPresent()}-- cleanup: "the server should be stopped"- stopContainer(container)}def "Set mode READY_AT and begin/end cycle time in past"() {given: "the container environment is started"- def conditions = new PollingConditions(timeout: 10, delay: 1)- def serverPort = findEphemeralPort()- def container = startContainerWithPseudoClock(defaultConfig(serverPort), defaultServices())+ def conditions = new PollingConditions(timeout: 10, delay: 0.2)+ def container = startContainer(defaultConfig(), defaultServices())def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)def rulesService = container.getService(RulesService.class)def assetStorageService = container.getService(AssetStorageService.class)@@ -462,17 +449,13 @@ class ResidenceSmartSwitchTest extends Specification implements ManagerContainerassert !kitchen.getAttribute("smartSwitchStopTimeC").get().getValue().isPresent()assert !kitchen.getAttribute("smartSwitchEnabledC").get().getValue().isPresent()}-- cleanup: "the server should be stopped"- stopContainer(container)}def "Set mode READY_AT and insufficient begin/end cycle time"() {given: "the container environment is started"- def conditions = new PollingConditions(timeout: 10, delay: 1)- def serverPort = findEphemeralPort()- def container = startContainerWithPseudoClock(defaultConfig(serverPort), defaultServices())+ def conditions = new PollingConditions(timeout: 10, delay: 0.2)+ def container = startContainer(defaultConfig(), defaultServices())def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)def rulesService = container.getService(RulesService.class)def assetStorageService = container.getService(AssetStorageService.class)@@ -560,9 +543,6 @@ class ResidenceSmartSwitchTest extends Specification implements ManagerContainerassert !kitchen.getAttribute("smartSwitchStopTimeC").get().getValue().isPresent()assert !kitchen.getAttribute("smartSwitchEnabledC").get().getValue().isPresent()}-- cleanup: "the server should be stopped"- stopContainer(container)}}diff --git a/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceVacationModeTest.groovy b/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceVacationModeTest.groovyindex fdb6140cb..30aa7c777 100644--- a/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceVacationModeTest.groovy+++ b/test/src/test/groovy/org/openremote/test/rules/residence/ResidenceVacationModeTest.groovy@@ -20,7 +20,6 @@ import java.time.DayOfWeekimport static java.util.concurrent.TimeUnit.DAYSimport static java.util.concurrent.TimeUnit.HOURS-import static org.openremote.manager.setup.SetupTasks.SETUP_IMPORT_DEMO_SCENESimport static org.openremote.manager.setup.builtin.ManagerDemoSetup.DEMO_RULE_STATES_APARTMENT_1_WITH_SCENESclass ResidenceVacationModeTest extends Specification implements ManagerContainerTrait {@@ -28,9 +27,8 @@ class ResidenceVacationModeTest extends Specification implements ManagerContainedef "Start and end vacation mode"() {given: "the container environment is started"- def conditions = new PollingConditions(timeout: 20, delay: 1)- def serverPort = findEphemeralPort()- def container = startContainerWithPseudoClock(defaultConfig(serverPort) << [(SETUP_IMPORT_DEMO_SCENES): "true"], defaultServices())+ def conditions = new PollingConditions(timeout: 20, delay: 0.2)+ def container = startContainer(defaultConfig(), defaultServices())def managerDemoSetup = container.getService(SetupService.class).getTaskOfType(ManagerDemoSetup.class)def rulesService = container.getService(RulesService.class)def assetProcessingService = container.getService(AssetProcessingService.class)@@ -38,6 +36,17 @@ class ResidenceVacationModeTest extends Specification implements ManagerContainedef rulesetStorageService = container.getService(RulesetStorageService.class)RulesEngine apartment1Engine+ and: "scenes are added to apartment1 rooms"+ def apartment1 = assetStorageService.find(managerDemoSetup.apartment1Id)+ def apartment1Livingroom = assetStorageService.find(managerDemoSetup.apartment1LivingroomId)+ def apartment1Kitchen = assetStorageService.find(managerDemoSetup.apartment1KitchenId)+ def apartment1Hallway = assetStorageService.find(managerDemoSetup.apartment1HallwayId)+ ManagerDemoSetup.createDemoApartmentScenes(+ assetStorageService,+ apartment1,+ ManagerDemoSetup.DEMO_APARTMENT_SCENES,+ apartment1Livingroom, apartment1Kitchen, apartment1Hallway)+and: "some rules"Ruleset ruleset = new AssetRuleset(managerDemoSetup.apartment1Id,@@ -114,8 +123,5 @@ class ResidenceVacationModeTest extends Specification implements ManagerContaineassert asset.getAttribute("nightSceneEnabled" + it.name()).get().getValueAsBoolean().get()}}-- cleanup: "the server should be stopped"- stopContainer(container)}}diff --git a/test/src/test/resources/META-INF/services/org.spockframework.runtime.extension.IGlobalExtension b/test/src/test/resources/META-INF/services/org.spockframework.runtime.extension.IGlobalExtensionnew file mode 100644index 000000000..97b04e672--- /dev/null+++ b/test/src/test/resources/META-INF/services/org.spockframework.runtime.extension.IGlobalExtension@@ -0,0 +1 @@+org.openremote.test.TestFixture