Add more null annotations (#2742)

* Add more null annotations
* Fix mock name

Adds null annotations to most of the tests as well as a few other classes.
Also fixes a few other SAT findings.
Fixes ~300 SAT findings in total.


Signed-off-by: Wouter Born <github@maindrain.net>
This commit is contained in:
Wouter Born 2022-02-14 11:33:50 +01:00 committed by GitHub
parent b5bf0b0157
commit ad936cd83f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
296 changed files with 2864 additions and 2314 deletions

View File

@ -21,6 +21,8 @@ import java.util.Locale;
import java.util.Map;
import java.util.Random;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.core.addon.Addon;
import org.openhab.core.addon.AddonEventFactory;
import org.openhab.core.addon.AddonService;
@ -40,26 +42,23 @@ import org.osgi.service.component.annotations.Reference;
* @author Kai Kreuzer - Initial contribution
*/
@Component
@NonNullByDefault
public class SampleAddonService implements AddonService {
private static final String LOREM_IPSUM = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.";
private static final String[] COLOR_VALUES = new String[] { "80", "C8", "FF" };
private EventPublisher eventPublisher;
private final EventPublisher eventPublisher;
List<AddonType> types = new ArrayList<>(3);
Map<String, Addon> extensions = new HashMap<>(30);
private List<AddonType> types = new ArrayList<>(3);
private Map<String, Addon> extensions = new HashMap<>(30);
@Reference
protected void setEventPublisher(EventPublisher eventPublisher) {
@Activate
public SampleAddonService(final @Reference EventPublisher eventPublisher) {
this.eventPublisher = eventPublisher;
}
protected void unsetEventPublisher(EventPublisher eventPublisher) {
this.eventPublisher = null;
}
@Activate
protected void activate() {
types.add(new AddonType("binding", "Bindings"));
@ -149,36 +148,32 @@ public class SampleAddonService implements AddonService {
}
@Override
public List<Addon> getAddons(Locale locale) {
public List<Addon> getAddons(@Nullable Locale locale) {
return new ArrayList<>(extensions.values());
}
@Override
public Addon getAddon(String id, Locale locale) {
public @Nullable Addon getAddon(String id, @Nullable Locale locale) {
return extensions.get(id);
}
@Override
public List<AddonType> getTypes(Locale locale) {
public List<AddonType> getTypes(@Nullable Locale locale) {
return types;
}
@Override
public String getAddonId(URI extensionURI) {
public @Nullable String getAddonId(URI extensionURI) {
return null;
}
private void postInstalledEvent(String extensionId) {
if (eventPublisher != null) {
Event event = AddonEventFactory.createAddonInstalledEvent(extensionId);
eventPublisher.post(event);
}
Event event = AddonEventFactory.createAddonInstalledEvent(extensionId);
eventPublisher.post(event);
}
private void postUninstalledEvent(String extensionId) {
if (eventPublisher != null) {
Event event = AddonEventFactory.createAddonUninstalledEvent(extensionId);
eventPublisher.post(event);
}
Event event = AddonEventFactory.createAddonUninstalledEvent(extensionId);
eventPublisher.post(event);
}
}

View File

@ -17,6 +17,7 @@ import static java.util.Comparator.comparing;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
@ -170,7 +171,8 @@ public class AudioConsoleCommandExtension extends AbstractConsoleCommandExtensio
try {
audioManager.playFile(fileName, sinkId, volume);
} catch (AudioException e) {
console.println(e.getMessage());
console.println(Objects.requireNonNullElse(e.getMessage(),
String.format("An error occurred while playing '%s' on sink '%s'", fileName, sinkId)));
}
}
@ -197,7 +199,8 @@ public class AudioConsoleCommandExtension extends AbstractConsoleCommandExtensio
try {
audioManager.stream(url, sinkId);
} catch (AudioException e) {
console.println(e.getMessage());
console.println(Objects.requireNonNullElse(e.getMessage(),
String.format("An error occurred while streaming '%s' to sink '%s'", url, sinkId)));
}
}
}

View File

@ -35,7 +35,7 @@ public class AudioWaveUtils {
/**
* This "magic" packet marks the beginning of the read data
*/
private final static int DATA_MAGIC = 0x64617461;
private static final int DATA_MAGIC = 0x64617461;
private static final AudioFormat DEFAULT_WAVE_AUDIO_FORMAT = new AudioFormat(AudioFormat.CONTAINER_WAVE,
AudioFormat.CODEC_PCM_SIGNED, false, 16, 705600, 44100L, 1);

View File

@ -16,6 +16,8 @@ import static org.junit.jupiter.api.Assertions.fail;
import java.util.concurrent.CompletableFuture;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Request;
@ -45,22 +47,21 @@ import org.osgi.service.http.HttpService;
*/
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.WARN)
@NonNullByDefault
public abstract class AbstractAudioServletTest extends JavaTest {
protected AudioServlet audioServlet;
private int port;
private TestServer server;
private static final String AUDIO_SERVLET_PROTOCOL = "http";
private static final String AUDIO_SERVLET_HOSTNAME = "localhost";
private CompletableFuture<Boolean> serverStarted;
protected @NonNullByDefault({}) AudioServlet audioServlet;
private HttpClient httpClient;
private int port;
private @NonNullByDefault({}) TestServer server;
private @NonNullByDefault({}) HttpClient httpClient;
private @NonNullByDefault({}) CompletableFuture<Boolean> serverStarted;
private @Mock HttpService httpServiceMock;
private @Mock HttpContext httpContextMock;
private @Mock @NonNullByDefault({}) HttpService httpServiceMock;
private @Mock @NonNullByDefault({}) HttpContext httpContextMock;
@BeforeEach
public void setupServerAndClient() {
@ -115,7 +116,7 @@ public abstract class AbstractAudioServletTest extends JavaTest {
return httpClient.newRequest(url).method(HttpMethod.GET);
}
protected String serveStream(AudioStream stream, Integer timeInterval) throws Exception {
protected String serveStream(AudioStream stream, @Nullable Integer timeInterval) throws Exception {
serverStarted.get(); // wait for the server thread to be started
String path;

View File

@ -20,6 +20,7 @@ import java.io.File;
import java.io.IOException;
import java.util.Locale;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@ -41,19 +42,16 @@ import org.openhab.core.io.console.Console;
* @author Christoph Weitkamp - Added parameter to adjust the volume
* @author Wouter Born - Migrate tests from Groovy to Java
*/
@NonNullByDefault
public class AudioConsoleTest extends AbstractAudioServletTest {
private BundledSoundFileHandler fileHandler;
private AudioConsoleCommandExtension audioConsoleCommandExtension;
private AudioManagerImpl audioManager;
private AudioSinkFake audioSink;
private @NonNullByDefault({}) AudioConsoleCommandExtension audioConsoleCommandExtension;
private @NonNullByDefault({}) AudioManagerImpl audioManager;
private @NonNullByDefault({}) AudioSinkFake audioSink;
private @NonNullByDefault({}) String consoleOutput;
private @NonNullByDefault({}) BundledSoundFileHandler fileHandler;
private final byte[] testByteArray = new byte[] { 0, 1, 2 };
private String consoleOutput;
private final Console consoleMock = new Console() {
@Override

View File

@ -18,6 +18,7 @@ import static org.hamcrest.MatcherAssert.assertThat;
import java.util.HashSet;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
import org.openhab.core.audio.AudioFormat;
@ -27,6 +28,7 @@ import org.openhab.core.audio.AudioFormat;
* @author Petar Valchev - Initial contribution
* @author Wouter Born - Migrate tests from Groovy to Java
*/
@NonNullByDefault
public class AudioFormatTest {
private final String testContainer = AudioFormat.CONTAINER_WAVE;
private final String testCodec = AudioFormat.CODEC_PCM_SIGNED;

View File

@ -15,6 +15,8 @@ package org.openhab.core.audio.internal;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openhab.core.audio.AudioFormat;
@ -31,11 +33,11 @@ import org.openhab.core.audio.internal.fake.AudioSinkFake;
* @author Wouter Born - Migrate tests from Groovy to Java
* @author Henning Treu - extract servlet tests
*/
@NonNullByDefault
public class AudioManagerServletTest extends AbstractAudioServletTest {
private AudioManagerImpl audioManager;
private AudioSinkFake audioSink;
private @NonNullByDefault({}) AudioManagerImpl audioManager;
private @NonNullByDefault({}) AudioSinkFake audioSink;
@BeforeEach
public void setup() {
@ -62,7 +64,7 @@ public class AudioManagerServletTest extends AbstractAudioServletTest {
assertServedStream(streamTimeout);
}
private void assertServedStream(Integer timeInterval) throws Exception {
private void assertServedStream(@Nullable Integer timeInterval) throws Exception {
AudioStream audioStream = getByteArrayAudioStream(AudioFormat.CONTAINER_WAVE, AudioFormat.CODEC_PCM_SIGNED);
String url = serveStream(audioStream, timeInterval);

View File

@ -25,8 +25,10 @@ import java.util.Collection;
import java.util.Collections;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.function.BiFunction;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@ -50,14 +52,13 @@ import org.openhab.core.library.types.PercentType;
* @author Wouter Born - Migrate tests from Groovy to Java
* @author Henning Treu - Convert to plain java tests
*/
@NonNullByDefault
public class AudioManagerTest {
private BundledSoundFileHandler fileHandler;
private AudioManagerImpl audioManager;
private AudioSinkFake audioSink;
private AudioSource audioSource;
private @NonNullByDefault({}) AudioManagerImpl audioManager;
private @NonNullByDefault({}) AudioSinkFake audioSink;
private @NonNullByDefault({}) AudioSource audioSource;
private @NonNullByDefault({}) BundledSoundFileHandler fileHandler;
@BeforeEach
public void setup() throws IOException {
@ -283,12 +284,12 @@ public class AudioManagerTest {
case AudioManagerImpl.CONFIG_DEFAULT_SINK:
audioManager.addAudioSink(audioSink);
id = audioSink.getId();
label = audioSink.getLabel(locale);
label = Objects.requireNonNull(audioSink.getLabel(locale));
break;
case AudioManagerImpl.CONFIG_DEFAULT_SOURCE:
audioManager.addAudioSource(audioSource);
id = audioSource.getId();
label = audioSource.getLabel(locale);
label = Objects.requireNonNull(audioSource.getLabel(locale));
break;
default:
fail("The parameter must be either default sink or default source");

View File

@ -18,6 +18,7 @@ import static org.hamcrest.Matchers.*;
import java.io.File;
import java.util.concurrent.TimeUnit;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.http.HttpStatus;
import org.junit.jupiter.api.Test;
@ -32,6 +33,7 @@ import org.openhab.core.audio.internal.utils.BundledSoundFileHandler;
* @author Petar Valchev - Initial contribution
* @author Wouter Born - Migrate tests from Groovy to Java
*/
@NonNullByDefault
public class AudioServletTest extends AbstractAudioServletTest {
private static final String MEDIA_TYPE_AUDIO_WAV = "audio/wav";

View File

@ -22,6 +22,7 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.core.OpenHAB;
import org.openhab.core.audio.internal.AudioManagerTest;
import org.slf4j.Logger;
@ -32,6 +33,7 @@ import org.slf4j.LoggerFactory;
*
* @author Markus Rathgeb - Initial contribution
*/
@NonNullByDefault
public class BundledSoundFileHandler implements Closeable {
private static final String MP3_FILE_NAME = "mp3AudioFile.mp3";
private static final String WAV_FILE_NAME = "wavAudioFile.wav";

View File

@ -256,7 +256,6 @@ public class ScriptFileWatcher extends AbstractWatchService implements ReadyServ
} else {
logger.error("Script loading error, ignoring file: {}", fileName);
}
} catch (IOException e) {
logger.error("Failed to load file '{}': {}", ref.getScriptFileURL().getFile(), e.getMessage());
}

View File

@ -12,6 +12,8 @@
*/
package org.openhab.core.automation;
import org.eclipse.jdt.annotation.NonNullByDefault;
/**
* Marker interface for RuleActions
*
@ -19,6 +21,7 @@ package org.openhab.core.automation;
*
* @author Stefan Triller - Initial contribution
*/
@NonNullByDefault
public interface AnnotatedActions {
}

View File

@ -12,6 +12,8 @@
*/
package org.openhab.core.automation;
import org.eclipse.jdt.annotation.NonNullByDefault;
/**
* This enumeration is used to present the main status of a {@link Rule}.
* <table>
@ -73,6 +75,7 @@ package org.openhab.core.automation;
* @author Kai Kreuzer - Refactored to match ThingStatus implementation
* @author Ana Dimova - add java doc
*/
@NonNullByDefault
public enum RuleStatus {
UNINITIALIZED(1),
INITIALIZING(2),

View File

@ -12,6 +12,8 @@
*/
package org.openhab.core.automation;
import org.eclipse.jdt.annotation.NonNullByDefault;
/**
* This enumeration is used to represent a detail of a {@link RuleStatus}. It can be considered as a sub-status.
* It shows the specific reasons why the status of the rule is like as is.
@ -81,6 +83,7 @@ package org.openhab.core.automation;
* @author Kai Kreuzer - Refactored to match ThingStatusDetail implementation
* @author Ana Dimova - add java doc
*/
@NonNullByDefault
public enum RuleStatusDetail {
NONE(0),
HANDLER_MISSING_ERROR(1),

View File

@ -12,6 +12,7 @@
*/
package org.openhab.core.automation;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.core.automation.template.Template;
import org.openhab.core.automation.type.ModuleType;
@ -20,6 +21,7 @@ import org.openhab.core.automation.type.ModuleType;
*
* @author Yordan Mihaylov - Initial contribution
*/
@NonNullByDefault
public enum Visibility {
/**
* The UI has always to show an object with such visibility.

View File

@ -16,11 +16,13 @@ import static org.junit.jupiter.api.Assertions.*;
import java.util.regex.Pattern;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
/**
* @author Ana Dimova - Initial contribution
*/
@NonNullByDefault
public class ConnectionValidatorTest {
@Test

View File

@ -14,6 +14,7 @@ package org.openhab.core.automation.internal;
import static org.junit.jupiter.api.Assertions.*;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
import org.openhab.core.automation.RulePredicates;
@ -22,6 +23,7 @@ import org.openhab.core.automation.RulePredicates;
*
* @author Victor Toni - Initial contribution
*/
@NonNullByDefault
public class RulePrefixTest {
private static final String TESTING_PREFIX = "Testing";

View File

@ -14,7 +14,7 @@ package org.openhab.core.automation.internal.module.provider;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import static org.mockito.Mockito.when;
import java.util.Collection;
import java.util.HashMap;
@ -22,8 +22,12 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.openhab.core.OpenHAB;
import org.openhab.core.automation.AnnotatedActions;
import org.openhab.core.automation.Visibility;
@ -46,6 +50,8 @@ import org.openhab.core.test.java.JavaTest;
*
* @author Stefan Triller - Initial contribution
*/
@ExtendWith(MockitoExtension.class)
@NonNullByDefault
public class AnnotationActionModuleTypeProviderTest extends JavaTest {
private static final String TEST_ACTION_TYPE_ID = "binding.test.testMethod";
@ -67,24 +73,20 @@ public class AnnotationActionModuleTypeProviderTest extends JavaTest {
private static final String ACTION_OUTPUT2 = "output2";
private static final String ACTION_OUTPUT2_TYPE = "java.lang.String";
private ModuleTypeI18nService moduleTypeI18nService;
private @Mock @NonNullByDefault({}) ModuleTypeI18nService moduleTypeI18nServiceMock;
private AnnotatedActions actionProviderConf1;
private AnnotatedActions actionProviderConf2;
private AnnotatedActions actionProviderConf1 = new TestActionProvider();
private AnnotatedActions actionProviderConf2 = new TestActionProvider();
@BeforeEach
public void setUp() {
actionProviderConf1 = new TestActionProvider();
actionProviderConf2 = new TestActionProvider();
moduleTypeI18nService = mock(ModuleTypeI18nService.class);
when(moduleTypeI18nService.getModuleTypePerLocale(any(ModuleType.class), any(), any()))
when(moduleTypeI18nServiceMock.getModuleTypePerLocale(any(ModuleType.class), any(), any()))
.thenAnswer(i -> i.getArguments()[0]);
}
@Test
public void testMultiServiceAnnotationActions() {
AnnotatedActionModuleTypeProvider prov = new AnnotatedActionModuleTypeProvider(moduleTypeI18nService);
AnnotatedActionModuleTypeProvider prov = new AnnotatedActionModuleTypeProvider(moduleTypeI18nServiceMock);
Map<String, Object> properties1 = new HashMap<>();
properties1.put(OpenHAB.SERVICE_CONTEXT, "conf1");

View File

@ -14,7 +14,7 @@ package org.openhab.core.automation.thingsupport;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.*;
import static org.mockito.Mockito.when;
import java.util.Collection;
import java.util.HashMap;
@ -22,9 +22,13 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.openhab.core.automation.Visibility;
import org.openhab.core.automation.annotation.ActionInput;
import org.openhab.core.automation.annotation.ActionOutput;
@ -49,6 +53,8 @@ import org.openhab.core.thing.binding.builder.ThingBuilder;
*
* @author Christoph Weitkamp - Initial contribution
*/
@ExtendWith(MockitoExtension.class)
@NonNullByDefault
public class AnnotatedThingActionModuleTypeProviderTest extends JavaTest {
private static final ThingTypeUID TEST_THING_TYPE_UID = new ThingTypeUID("binding", "thing-type");
@ -72,36 +78,33 @@ public class AnnotatedThingActionModuleTypeProviderTest extends JavaTest {
private static final String ACTION_OUTPUT2 = "output2";
private static final String ACTION_OUTPUT2_TYPE = "java.lang.String";
private ModuleTypeI18nService moduleTypeI18nService;
private @Mock @NonNullByDefault({}) ModuleTypeI18nService moduleTypeI18nServiceMock;
private @Mock @NonNullByDefault({}) ThingHandler handler1Mock;
private @Mock @NonNullByDefault({}) ThingHandler handler2Mock;
private ThingHandler mockHandler1;
private ThingHandler mockHandler2;
private ThingActions actionProviderConf1;
private ThingActions actionProviderConf2;
private ThingActions actionProviderConf1 = new TestThingActionProvider();
private ThingActions actionProviderConf2 = new TestThingActionProvider();
@BeforeEach
public void setUp() {
mockHandler1 = mock(ThingHandler.class);
when(mockHandler1.getThing()).thenReturn(ThingBuilder.create(TEST_THING_TYPE_UID, "test1").build());
when(handler1Mock.getThing()).thenReturn(ThingBuilder.create(TEST_THING_TYPE_UID, "test1").build());
actionProviderConf1 = new TestThingActionProvider();
actionProviderConf1.setThingHandler(mockHandler1);
actionProviderConf1.setThingHandler(handler1Mock);
mockHandler2 = mock(ThingHandler.class);
when(mockHandler2.getThing()).thenReturn(ThingBuilder.create(TEST_THING_TYPE_UID, "test2").build());
when(handler2Mock.getThing()).thenReturn(ThingBuilder.create(TEST_THING_TYPE_UID, "test2").build());
actionProviderConf2 = new TestThingActionProvider();
actionProviderConf2.setThingHandler(mockHandler2);
actionProviderConf2.setThingHandler(handler2Mock);
moduleTypeI18nService = mock(ModuleTypeI18nService.class);
when(moduleTypeI18nService.getModuleTypePerLocale(any(ModuleType.class), any(), any()))
when(moduleTypeI18nServiceMock.getModuleTypePerLocale(any(ModuleType.class), any(), any()))
.thenAnswer(i -> i.getArguments()[0]);
}
@Test
public void testMultiServiceAnnotationActions() {
AnnotatedThingActionModuleTypeProvider prov = new AnnotatedThingActionModuleTypeProvider(moduleTypeI18nService);
AnnotatedThingActionModuleTypeProvider prov = new AnnotatedThingActionModuleTypeProvider(
moduleTypeI18nServiceMock);
prov.addAnnotatedThingActions(actionProviderConf1);

View File

@ -19,6 +19,8 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.junit.jupiter.api.Test;
import org.openhab.core.automation.Module;
import org.openhab.core.config.core.Configuration;
@ -28,6 +30,7 @@ import org.slf4j.LoggerFactory;
/**
* @author Vasil Ilchev - Initial contribution
*/
@NonNullByDefault
public class ReferenceResolverUtilTest {
private static final String CONTEXT_PROPERTY1 = "contextProperty1";
private static final String CONTEXT_PROPERTY2 = "contextProperty2";
@ -36,9 +39,9 @@ public class ReferenceResolverUtilTest {
private static final Map<String, Object> CONTEXT = new HashMap<>();
private static final Map<String, Object> MODULE_CONFIGURATION = new HashMap<>();
private static final Map<String, Object> EXPECTED_MODULE_CONFIGURATION = new HashMap<>();
private static final Map<String, @Nullable Object> EXPECTED_MODULE_CONFIGURATION = new HashMap<>();
private static final Map<String, String> COMPOSITE_CHILD_MODULE_INPUTS_REFERENCES = new HashMap<>();
private static final Map<String, Object> EXPECTED_COMPOSITE_CHILD_MODULE_CONTEXT = new HashMap<>();
private static final Map<String, @Nullable Object> EXPECTED_COMPOSITE_CHILD_MODULE_CONTEXT = new HashMap<>();
private final Logger logger = LoggerFactory.getLogger(ReferenceResolverUtilTest.class);

View File

@ -19,6 +19,7 @@ import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import java.net.URI;
import java.util.List;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openhab.core.config.core.ConfigDescriptionParameter.Type;
@ -28,6 +29,7 @@ import org.openhab.core.config.core.ConfigDescriptionParameter.Type;
*
* @author Christoph Weitkamp - Initial contribution
*/
@NonNullByDefault
public class ConfigDescriptionBuilderTest {
private static final URI CONFIG_URI = URI.create("system:ephemeris");
@ -39,7 +41,7 @@ public class ConfigDescriptionBuilderTest {
.create("TEST GROUP 1").withLabel("Test Group 1").build();
private static final ConfigDescriptionParameterGroup GROUP2 = ConfigDescriptionParameterGroupBuilder
.create("TEST GROUP 2").withAdvanced(Boolean.TRUE).withLabel("Test Group 2").build();
private ConfigDescriptionBuilder builder;
private @NonNullByDefault({}) ConfigDescriptionBuilder builder;
@BeforeEach
public void setup() {

View File

@ -19,6 +19,7 @@ import static org.junit.jupiter.api.Assertions.*;
import java.math.BigDecimal;
import java.util.List;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
import org.openhab.core.config.core.ConfigDescriptionParameter.Type;
@ -27,6 +28,7 @@ import org.openhab.core.config.core.ConfigDescriptionParameter.Type;
*
* @author Christoph Knauf - Initial contribution
*/
@NonNullByDefault
public class ConfigDescriptionParameterBuilderTest {
@Test

View File

@ -22,11 +22,13 @@ import java.net.URISyntaxException;
import java.util.List;
import java.util.Map;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
/**
* @author Simon Kaufmann - Initial contribution
*/
@NonNullByDefault
public class ConfigUtilTest {
private final URI configUri = URI.create("system:ephemeris");

View File

@ -18,6 +18,7 @@ import static org.hamcrest.MatcherAssert.assertThat;
import java.net.URI;
import java.util.Locale;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.hamcrest.collection.IsEmptyCollection;
import org.junit.jupiter.api.Test;
import org.openhab.core.config.core.ParameterOption;
@ -27,6 +28,7 @@ import org.openhab.core.config.core.ParameterOption;
*
* @author Simon Kaufmann - Initial contribution
*/
@NonNullByDefault
public class I18nConfigOptionsProviderTest {
private final I18nConfigOptionsProvider provider = new I18nConfigOptionsProvider();

View File

@ -22,6 +22,7 @@ import java.util.Collection;
import java.util.List;
import java.util.Locale;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ -43,6 +44,7 @@ import org.openhab.core.test.java.JavaTest;
*/
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.WARN)
@NonNullByDefault
public class MetadataConfigDescriptionProviderImplTest extends JavaTest {
private static final String LIBERAL = "liberal";
@ -53,34 +55,34 @@ public class MetadataConfigDescriptionProviderImplTest extends JavaTest {
private static final URI URI_RESTRICTED_DIMMER = URI.create(SCHEME + SEPARATOR + RESTRICTED + SEPARATOR + "dimmer");
private @Mock MetadataConfigDescriptionProvider mockProviderRestricted;
private @Mock MetadataConfigDescriptionProvider mockProviderLiberal;
private @Mock @NonNullByDefault({}) MetadataConfigDescriptionProvider providerRestrictedMock;
private @Mock @NonNullByDefault({}) MetadataConfigDescriptionProvider providerLiberalMock;
private MetadataConfigDescriptionProviderImpl service;
private MetadataConfigDescriptionProviderImpl service = new MetadataConfigDescriptionProviderImpl();
@BeforeEach
public void setup() {
service = new MetadataConfigDescriptionProviderImpl();
when(mockProviderRestricted.getNamespace()).thenReturn(RESTRICTED);
when(mockProviderRestricted.getDescription(any())).thenReturn("Restricted");
when(mockProviderRestricted.getParameterOptions(any())).thenReturn(List.of( //
when(providerRestrictedMock.getNamespace()).thenReturn(RESTRICTED);
when(providerRestrictedMock.getDescription(any())).thenReturn("Restricted");
when(providerRestrictedMock.getParameterOptions(any())).thenReturn(List.of( //
new ParameterOption("dimmer", "Dimmer"), //
new ParameterOption("switch", "Switch") //
));
when(mockProviderRestricted.getParameters(eq("dimmer"), any())).thenReturn(List.of( //
when(providerRestrictedMock.getParameters(eq("dimmer"), any())).thenReturn(List.of( //
ConfigDescriptionParameterBuilder.create("width", Type.INTEGER).build(), //
ConfigDescriptionParameterBuilder.create("height", Type.INTEGER).build() //
));
when(mockProviderLiberal.getNamespace()).thenReturn(LIBERAL);
when(mockProviderLiberal.getDescription(any())).thenReturn("Liberal");
when(mockProviderLiberal.getParameterOptions(any())).thenReturn(null);
when(providerLiberalMock.getNamespace()).thenReturn(LIBERAL);
when(providerLiberalMock.getDescription(any())).thenReturn("Liberal");
when(providerLiberalMock.getParameterOptions(any())).thenReturn(null);
}
@Test
public void testGetConfigDescriptionsNoOptions() {
service.addMetadataConfigDescriptionProvider(mockProviderLiberal);
service.addMetadataConfigDescriptionProvider(providerLiberalMock);
Collection<ConfigDescription> res = service.getConfigDescriptions(Locale.ENGLISH);
assertNotNull(res);
@ -98,7 +100,7 @@ public class MetadataConfigDescriptionProviderImplTest extends JavaTest {
@Test
public void testGetConfigDescriptionsWithOptions() {
service.addMetadataConfigDescriptionProvider(mockProviderRestricted);
service.addMetadataConfigDescriptionProvider(providerRestrictedMock);
Collection<ConfigDescription> res = service.getConfigDescriptions(Locale.ENGLISH);
assertNotNull(res);
@ -118,16 +120,16 @@ public class MetadataConfigDescriptionProviderImplTest extends JavaTest {
@Test
public void testGetConfigDescriptionWrongScheme() {
service.addMetadataConfigDescriptionProvider(mockProviderRestricted);
service.addMetadataConfigDescriptionProvider(mockProviderLiberal);
service.addMetadataConfigDescriptionProvider(providerRestrictedMock);
service.addMetadataConfigDescriptionProvider(providerLiberalMock);
assertNull(service.getConfigDescription(URI.create("some:nonsense"), null));
}
@Test
public void testGetConfigDescriptionValueDescription() {
service.addMetadataConfigDescriptionProvider(mockProviderRestricted);
service.addMetadataConfigDescriptionProvider(mockProviderLiberal);
service.addMetadataConfigDescriptionProvider(providerRestrictedMock);
service.addMetadataConfigDescriptionProvider(providerLiberalMock);
ConfigDescription desc = service.getConfigDescription(URI_LIBERAL, null);
assertNotNull(desc);
@ -142,8 +144,8 @@ public class MetadataConfigDescriptionProviderImplTest extends JavaTest {
@Test
public void testGetConfigDescriptionValueDescriptionNonExistingNamespace() {
service.addMetadataConfigDescriptionProvider(mockProviderRestricted);
service.addMetadataConfigDescriptionProvider(mockProviderLiberal);
service.addMetadataConfigDescriptionProvider(providerRestrictedMock);
service.addMetadataConfigDescriptionProvider(providerLiberalMock);
ConfigDescription desc = service.getConfigDescription(URI.create("metadata:nonsense"), null);
assertNull(desc);
@ -151,8 +153,8 @@ public class MetadataConfigDescriptionProviderImplTest extends JavaTest {
@Test
public void testGetConfigDescriptionPropertiesDescription() {
service.addMetadataConfigDescriptionProvider(mockProviderRestricted);
service.addMetadataConfigDescriptionProvider(mockProviderLiberal);
service.addMetadataConfigDescriptionProvider(providerRestrictedMock);
service.addMetadataConfigDescriptionProvider(providerLiberalMock);
ConfigDescription desc = service.getConfigDescription(URI_RESTRICTED_DIMMER, null);
assertNotNull(desc);
@ -168,8 +170,8 @@ public class MetadataConfigDescriptionProviderImplTest extends JavaTest {
@Test
public void testGetConfigDescriptionPropertiesDescriptionNonExistingNamespace() {
service.addMetadataConfigDescriptionProvider(mockProviderRestricted);
service.addMetadataConfigDescriptionProvider(mockProviderLiberal);
service.addMetadataConfigDescriptionProvider(providerRestrictedMock);
service.addMetadataConfigDescriptionProvider(providerLiberalMock);
ConfigDescription desc = service.getConfigDescription(URI.create("metadata:nonsense:nonsense"), null);
assertNull(desc);
@ -177,8 +179,8 @@ public class MetadataConfigDescriptionProviderImplTest extends JavaTest {
@Test
public void testGetConfigDescriptionPropertiesDescriptionNonExistingValue() {
service.addMetadataConfigDescriptionProvider(mockProviderRestricted);
service.addMetadataConfigDescriptionProvider(mockProviderLiberal);
service.addMetadataConfigDescriptionProvider(providerRestrictedMock);
service.addMetadataConfigDescriptionProvider(providerLiberalMock);
ConfigDescription desc = service.getConfigDescription(URI.create("metadata:foo:nonsense"), null);
assertNull(desc);

View File

@ -21,6 +21,7 @@ import java.util.List;
import java.util.TreeSet;
import java.util.stream.Stream;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
import org.openhab.core.config.core.ConfigDescriptionParameter;
import org.openhab.core.config.core.ConfigDescriptionParameterBuilder;
@ -29,6 +30,7 @@ import org.openhab.core.config.core.ConfigDescriptionParameterBuilder;
* @author Simon Kaufmann - Initial contribution
* @author Wouter Born - Migrate tests from Groovy to Java
*/
@NonNullByDefault
public class NormalizerTest {
@Test

View File

@ -22,6 +22,7 @@ import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
@ -36,6 +37,7 @@ import org.osgi.framework.Bundle;
* @author Thomas Höfer - Initial contribution
* @author Wouter Born - Migrate tests from Groovy to Java
*/
@NonNullByDefault
public class ConfigValidationExceptionTest {
private static final String PARAM1 = "param1";
@ -67,7 +69,7 @@ public class ConfigValidationExceptionTest {
private static final TranslationProvider TRANSLATION_PROVIDER = new TranslationProvider() {
@Override
public @Nullable String getText(@Nullable Bundle bundle, @Nullable String key, @Nullable String defaultText,
@Nullable Locale locale, @Nullable Object... arguments) {
@Nullable Locale locale, @Nullable Object @Nullable... arguments) {
return getText(bundle, key, defaultText, locale);
}

View File

@ -12,6 +12,8 @@
*/
package org.openhab.core.config.discovery;
import org.eclipse.jdt.annotation.NonNullByDefault;
/**
* The {@link DiscoveryResultFlag} class specifies a list of flags
* which a {@link DiscoveryResult} object can take.
@ -20,6 +22,7 @@ package org.openhab.core.config.discovery;
*
* @see DiscoveryResult
*/
@NonNullByDefault
public enum DiscoveryResultFlag {
/**

View File

@ -17,6 +17,7 @@ import static org.openhab.core.config.discovery.inbox.InboxPredicates.*;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import org.eclipse.jdt.annotation.NonNullByDefault;
@ -80,7 +81,8 @@ public class InboxConsoleCommandExtension extends AbstractConsoleCommandExtensio
}
inbox.approve(thingUID, label, newThingId);
} catch (IllegalArgumentException e) {
console.println(e.getMessage());
console.println(Objects.requireNonNullElse(e.getMessage(),
String.format("An error occurred while approving '%s'", args[1])));
}
} else {
console.println("Specify thing id to approve: inbox approve <thingUID> <label> [<newThingID>]");

View File

@ -22,7 +22,7 @@ import java.util.Locale;
import java.util.Map;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.junit.jupiter.api.Test;
import org.openhab.core.i18n.LocaleProvider;
@ -36,6 +36,7 @@ import org.osgi.framework.Bundle;
*
* @author Laurent Garnier - Initial contribution
*/
@NonNullByDefault
public class AbstractDiscoveryServiceTest implements DiscoveryListener {
private static final String BINDING_ID = "bindingId";
@ -64,7 +65,7 @@ public class AbstractDiscoveryServiceTest implements DiscoveryListener {
private TranslationProvider i18nProvider = new TranslationProvider() {
@Override
public @Nullable String getText(@Nullable Bundle bundle, @Nullable String key, @Nullable String defaultText,
@Nullable Locale locale, @Nullable Object... arguments) {
@Nullable Locale locale, @Nullable Object @Nullable... arguments) {
if (Locale.ENGLISH.equals(locale)) {
if ("test".equals(key)) {
return PROPERTY_LABEL1;
@ -87,7 +88,7 @@ public class AbstractDiscoveryServiceTest implements DiscoveryListener {
private LocaleProvider localeProvider = new LocaleProvider() {
@Override
public @NonNull Locale getLocale() {
public Locale getLocale() {
return Locale.ENGLISH;
}
};
@ -133,10 +134,8 @@ public class AbstractDiscoveryServiceTest implements DiscoveryListener {
}
};
private TestDiscoveryService discoveryService;
@Override
public void thingDiscovered(@NonNull DiscoveryService source, @NonNull DiscoveryResult result) {
public void thingDiscovered(DiscoveryService source, DiscoveryResult result) {
assertThat(result.getThingTypeUID(), is(THING_TYPE_UID));
assertThat(result.getBindingId(), is(BINDING_ID));
assertThat(result.getProperties().size(), is(2));
@ -161,18 +160,18 @@ public class AbstractDiscoveryServiceTest implements DiscoveryListener {
}
@Override
public void thingRemoved(@NonNull DiscoveryService source, @NonNull ThingUID thingUID) {
public void thingRemoved(DiscoveryService source, ThingUID thingUID) {
}
@Override
public @Nullable Collection<@NonNull ThingUID> removeOlderResults(@NonNull DiscoveryService source, long timestamp,
@Nullable Collection<@NonNull ThingTypeUID> thingTypeUIDs, @Nullable ThingUID bridgeUID) {
public @Nullable Collection<ThingUID> removeOlderResults(DiscoveryService source, long timestamp,
@Nullable Collection<ThingTypeUID> thingTypeUIDs, @Nullable ThingUID bridgeUID) {
return null;
}
@Test
public void testDiscoveryResults() {
discoveryService = new TestDiscoveryService(i18nProvider, localeProvider);
TestDiscoveryService discoveryService = new TestDiscoveryService(i18nProvider, localeProvider);
discoveryService.addDiscoveryListener(this);
discoveryService.startScan();
}

View File

@ -21,6 +21,7 @@ import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
@ -32,6 +33,7 @@ import org.openhab.core.thing.ThingUID;
*
* @author Christoph Weitkamp - Initial contribution
*/
@NonNullByDefault
public class DiscoveryResultBuilderTest {
private static final String BINDING_ID = "bindingId";
@ -49,8 +51,8 @@ public class DiscoveryResultBuilderTest {
put(KEY2, VALUE2);
}
};
private DiscoveryResultBuilder builder;
private DiscoveryResult discoveryResult;
private @NonNullByDefault({}) DiscoveryResultBuilder builder;
private @NonNullByDefault({}) DiscoveryResult discoveryResult;
@BeforeEach
public void setup() {

View File

@ -21,6 +21,7 @@ import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openhab.core.config.discovery.DiscoveryResult;
@ -35,6 +36,7 @@ import org.openhab.core.thing.ThingUID;
*
* @author Andre Fuechsel - Initial contribution
*/
@NonNullByDefault
public class InboxPredicatesTest {
private static final String BINDING_ID1 = "bindingId1";

View File

@ -15,6 +15,7 @@ package org.openhab.core.config.discovery.inbox.events;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
import org.openhab.core.config.discovery.DiscoveryResult;
import org.openhab.core.config.discovery.DiscoveryResultBuilder;
@ -31,6 +32,7 @@ import com.google.gson.Gson;
* @author Stefan Bußweiler - Initial contribution
* @author Wouter Born - Migrate tests from Groovy to Java
*/
@NonNullByDefault
public class InboxEventFactoryTest {
private static final ThingTypeUID THING_TYPE_UID = new ThingTypeUID("binding", "type");

View File

@ -26,6 +26,7 @@ import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
@ -63,6 +64,7 @@ import org.openhab.core.thing.type.ThingTypeRegistry;
*/
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.WARN)
@NonNullByDefault
public class AutomaticInboxProcessorTest {
private static final String DEVICE_ID = "deviceId";
@ -92,60 +94,60 @@ public class AutomaticInboxProcessorTest {
private static final Configuration CONFIG = new Configuration(Map.of(CONFIG_KEY, CONFIG_VALUE));
private AutomaticInboxProcessor automaticInboxProcessor;
private PersistentInbox inbox;
private @NonNullByDefault({}) AutomaticInboxProcessor automaticInboxProcessor;
private @NonNullByDefault({}) PersistentInbox inbox;
private @Mock ThingRegistry thingRegistry;
private @Mock ThingTypeRegistry thingTypeRegistry;
private @Mock Thing thing;
private @Mock Thing thing2;
private @Mock Thing thing3;
private @Mock ThingStatusInfoChangedEvent thingStatusInfoChangedEvent;
private @Mock ConfigDescriptionRegistry configDescriptionRegistry;
private @Mock ThingHandlerFactory thingHandlerFactory;
private @Mock ManagedThingProvider thingProvider;
private @Mock @NonNullByDefault({}) ThingRegistry thingRegistryMock;
private @Mock @NonNullByDefault({}) ThingTypeRegistry thingTypeRegistryMock;
private @Mock @NonNullByDefault({}) Thing thingMock;
private @Mock @NonNullByDefault({}) Thing thing2Mock;
private @Mock @NonNullByDefault({}) Thing thing3Mock;
private @Mock @NonNullByDefault({}) ThingStatusInfoChangedEvent thingStatusInfoChangedEventMock;
private @Mock @NonNullByDefault({}) ConfigDescriptionRegistry configDescriptionRegistryMock;
private @Mock @NonNullByDefault({}) ThingHandlerFactory thingHandlerFactoryMock;
private @Mock @NonNullByDefault({}) ManagedThingProvider thingProviderMock;
@BeforeEach
public void setUp() {
when(thing.getConfiguration()).thenReturn(CONFIG);
when(thing.getThingTypeUID()).thenReturn(THING_TYPE_UID);
when(thing.getProperties()).thenReturn(THING_PROPERTIES);
when(thing.getStatus()).thenReturn(ThingStatus.ONLINE);
when(thing.getUID()).thenReturn(THING_UID);
when(thingMock.getConfiguration()).thenReturn(CONFIG);
when(thingMock.getThingTypeUID()).thenReturn(THING_TYPE_UID);
when(thingMock.getProperties()).thenReturn(THING_PROPERTIES);
when(thingMock.getStatus()).thenReturn(ThingStatus.ONLINE);
when(thingMock.getUID()).thenReturn(THING_UID);
when(thing2.getConfiguration()).thenReturn(CONFIG);
when(thing2.getThingTypeUID()).thenReturn(THING_TYPE_UID);
when(thing2.getProperties()).thenReturn(THING_PROPERTIES);
when(thing2.getStatus()).thenReturn(ThingStatus.ONLINE);
when(thing2.getUID()).thenReturn(THING_UID2);
when(thing2Mock.getConfiguration()).thenReturn(CONFIG);
when(thing2Mock.getThingTypeUID()).thenReturn(THING_TYPE_UID);
when(thing2Mock.getProperties()).thenReturn(THING_PROPERTIES);
when(thing2Mock.getStatus()).thenReturn(ThingStatus.ONLINE);
when(thing2Mock.getUID()).thenReturn(THING_UID2);
when(thing3.getConfiguration()).thenReturn(CONFIG);
when(thing3.getThingTypeUID()).thenReturn(THING_TYPE_UID3);
when(thing3.getProperties()).thenReturn(OTHER_THING_PROPERTIES);
when(thing3.getStatus()).thenReturn(ThingStatus.ONLINE);
when(thing3.getUID()).thenReturn(THING_UID3);
when(thing3Mock.getConfiguration()).thenReturn(CONFIG);
when(thing3Mock.getThingTypeUID()).thenReturn(THING_TYPE_UID3);
when(thing3Mock.getProperties()).thenReturn(OTHER_THING_PROPERTIES);
when(thing3Mock.getStatus()).thenReturn(ThingStatus.ONLINE);
when(thing3Mock.getUID()).thenReturn(THING_UID3);
when(thingRegistry.stream()).thenReturn(Stream.empty());
when(thingRegistryMock.stream()).thenReturn(Stream.empty());
when(thingTypeRegistry.getThingType(THING_TYPE_UID)).thenReturn(THING_TYPE);
when(thingTypeRegistry.getThingType(THING_TYPE_UID2)).thenReturn(THING_TYPE2);
when(thingTypeRegistry.getThingType(THING_TYPE_UID3)).thenReturn(THING_TYPE3);
when(thingTypeRegistryMock.getThingType(THING_TYPE_UID)).thenReturn(THING_TYPE);
when(thingTypeRegistryMock.getThingType(THING_TYPE_UID2)).thenReturn(THING_TYPE2);
when(thingTypeRegistryMock.getThingType(THING_TYPE_UID3)).thenReturn(THING_TYPE3);
when(thingHandlerFactory.supportsThingType(eq(THING_TYPE_UID))).thenReturn(true);
when(thingHandlerFactory.supportsThingType(eq(THING_TYPE_UID3))).thenReturn(true);
when(thingHandlerFactory.createThing(any(ThingTypeUID.class), any(Configuration.class), any(ThingUID.class),
when(thingHandlerFactoryMock.supportsThingType(eq(THING_TYPE_UID))).thenReturn(true);
when(thingHandlerFactoryMock.supportsThingType(eq(THING_TYPE_UID3))).thenReturn(true);
when(thingHandlerFactoryMock.createThing(any(ThingTypeUID.class), any(Configuration.class), any(ThingUID.class),
nullable(ThingUID.class)))
.then(invocation -> ThingBuilder
.create((ThingTypeUID) invocation.getArguments()[0],
(ThingUID) invocation.getArguments()[2])
.withConfiguration((Configuration) invocation.getArguments()[1]).build());
inbox = new PersistentInbox(new VolatileStorageService(), mock(DiscoveryServiceRegistry.class), thingRegistry,
thingProvider, thingTypeRegistry, configDescriptionRegistry);
inbox.addThingHandlerFactory(thingHandlerFactory);
inbox = new PersistentInbox(new VolatileStorageService(), mock(DiscoveryServiceRegistry.class),
thingRegistryMock, thingProviderMock, thingTypeRegistryMock, configDescriptionRegistryMock);
inbox.addThingHandlerFactory(thingHandlerFactoryMock);
inbox.activate();
automaticInboxProcessor = new AutomaticInboxProcessor(thingTypeRegistry, thingRegistry, inbox);
automaticInboxProcessor = new AutomaticInboxProcessor(thingTypeRegistryMock, thingRegistryMock, inbox);
automaticInboxProcessor.activate(null);
}
@ -175,11 +177,11 @@ public class AutomaticInboxProcessorTest {
// Now a thing with thing type THING_TYPE_UID3 goes online, with representation property value being also the
// device id
when(thingRegistry.get(THING_UID3)).thenReturn(thing3);
when(thingStatusInfoChangedEvent.getStatusInfo())
when(thingRegistryMock.get(THING_UID3)).thenReturn(thing3Mock);
when(thingStatusInfoChangedEventMock.getStatusInfo())
.thenReturn(new ThingStatusInfo(ThingStatus.ONLINE, ThingStatusDetail.NONE, null));
when(thingStatusInfoChangedEvent.getThingUID()).thenReturn(THING_UID3);
automaticInboxProcessor.receive(thingStatusInfoChangedEvent);
when(thingStatusInfoChangedEventMock.getThingUID()).thenReturn(THING_UID3);
automaticInboxProcessor.receive(thingStatusInfoChangedEventMock);
// Then there should still be the NEW discovery result, but no IGNORED discovery result
results = inbox.stream().filter(withFlag(DiscoveryResultFlag.NEW)).collect(Collectors.toList());
@ -192,8 +194,8 @@ public class AutomaticInboxProcessorTest {
@Test
public void testThingWithOtherBindingIDButSameRepresentationPropertyIsDiscovered() {
// insert thing with thing type THING_TYPE_UID3 and representation property value DEVICE_ID in registry
when(thingRegistry.get(THING_UID)).thenReturn(thing);
when(thingRegistry.stream()).thenReturn(Stream.of(thing));
when(thingRegistryMock.get(THING_UID)).thenReturn(thingMock);
when(thingRegistryMock.stream()).thenReturn(Stream.of(thingMock));
// Add discovery result with thing type THING_TYPE_UID3 and representation property value DEVICE_ID
inbox.add(DiscoveryResultBuilder.create(THING_UID3).withProperty(DEVICE_ID_KEY, DEVICE_ID)
@ -220,11 +222,11 @@ public class AutomaticInboxProcessorTest {
assertThat(results.size(), is(1));
assertThat(results.get(0).getThingUID(), is(equalTo(THING_UID)));
when(thingRegistry.get(THING_UID)).thenReturn(thing);
when(thingStatusInfoChangedEvent.getStatusInfo())
when(thingRegistryMock.get(THING_UID)).thenReturn(thingMock);
when(thingStatusInfoChangedEventMock.getStatusInfo())
.thenReturn(new ThingStatusInfo(ThingStatus.ONLINE, ThingStatusDetail.NONE, null));
when(thingStatusInfoChangedEvent.getThingUID()).thenReturn(THING_UID);
automaticInboxProcessor.receive(thingStatusInfoChangedEvent);
when(thingStatusInfoChangedEventMock.getThingUID()).thenReturn(THING_UID);
automaticInboxProcessor.receive(thingStatusInfoChangedEventMock);
results = inbox.stream().filter(withFlag(DiscoveryResultFlag.NEW)).collect(Collectors.toList());
assertThat(results.size(), is(0));
@ -248,11 +250,11 @@ public class AutomaticInboxProcessorTest {
assertThat(results.size(), is(1));
assertThat(results.get(0).getThingUID(), is(equalTo(THING_UID)));
when(thing.getProperties()).thenReturn(Collections.emptyMap());
when(thingStatusInfoChangedEvent.getStatusInfo())
when(thingMock.getProperties()).thenReturn(Collections.emptyMap());
when(thingStatusInfoChangedEventMock.getStatusInfo())
.thenReturn(new ThingStatusInfo(ThingStatus.ONLINE, ThingStatusDetail.NONE, null));
when(thingStatusInfoChangedEvent.getThingUID()).thenReturn(THING_UID);
automaticInboxProcessor.receive(thingStatusInfoChangedEvent);
when(thingStatusInfoChangedEventMock.getThingUID()).thenReturn(THING_UID);
automaticInboxProcessor.receive(thingStatusInfoChangedEventMock);
results = inbox.stream().filter(withFlag(DiscoveryResultFlag.IGNORED)).collect(Collectors.toList());
assertThat(results.size(), is(0));
@ -263,8 +265,8 @@ public class AutomaticInboxProcessorTest {
inbox.stream().map(DiscoveryResult::getThingUID).forEach(t -> inbox.remove(t));
assertThat(inbox.getAll().size(), is(0));
when(thingRegistry.get(THING_UID)).thenReturn(thing);
when(thingRegistry.stream()).thenReturn(Stream.of(thing));
when(thingRegistryMock.get(THING_UID)).thenReturn(thingMock);
when(thingRegistryMock.stream()).thenReturn(Stream.of(thingMock));
inbox.add(DiscoveryResultBuilder.create(THING_UID2).withProperty(DEVICE_ID_KEY, DEVICE_ID)
.withRepresentationProperty(DEVICE_ID_KEY).build());
@ -288,7 +290,7 @@ public class AutomaticInboxProcessorTest {
assertThat(results.size(), is(1));
assertThat(results.get(0).getThingUID(), is(equalTo(THING_UID)));
automaticInboxProcessor.removed(thing);
automaticInboxProcessor.removed(thingMock);
results = inbox.getAll();
assertThat(results.size(), is(0));
@ -308,7 +310,7 @@ public class AutomaticInboxProcessorTest {
.collect(Collectors.toList());
assertThat(results.size(), is(2));
automaticInboxProcessor.removed(thing);
automaticInboxProcessor.removed(thingMock);
results = inbox.getAll();
assertThat(results.size(), is(1));
@ -325,11 +327,11 @@ public class AutomaticInboxProcessorTest {
assertThat(results.size(), is(1));
assertThat(results.get(0).getThingUID(), is(equalTo(THING_UID2)));
when(thingRegistry.get(THING_UID2)).thenReturn(thing2);
when(thingStatusInfoChangedEvent.getStatusInfo())
when(thingRegistryMock.get(THING_UID2)).thenReturn(thing2Mock);
when(thingStatusInfoChangedEventMock.getStatusInfo())
.thenReturn(new ThingStatusInfo(ThingStatus.ONLINE, ThingStatusDetail.NONE, null));
when(thingStatusInfoChangedEvent.getThingUID()).thenReturn(THING_UID2);
automaticInboxProcessor.receive(thingStatusInfoChangedEvent);
when(thingStatusInfoChangedEventMock.getThingUID()).thenReturn(THING_UID2);
automaticInboxProcessor.receive(thingStatusInfoChangedEventMock);
results = inbox.stream().filter(withFlag(DiscoveryResultFlag.NEW)).collect(Collectors.toList());
assertThat(results.size(), is(0));
@ -343,8 +345,8 @@ public class AutomaticInboxProcessorTest {
inbox.stream().map(DiscoveryResult::getThingUID).forEach(t -> inbox.remove(t));
assertThat(inbox.getAll().size(), is(0));
when(thingRegistry.get(THING_UID2)).thenReturn(thing2);
when(thingRegistry.stream()).thenReturn(Stream.of(thing2));
when(thingRegistryMock.get(THING_UID2)).thenReturn(thing2Mock);
when(thingRegistryMock.stream()).thenReturn(Stream.of(thing2Mock));
inbox.add(DiscoveryResultBuilder.create(THING_UID).withProperty(OTHER_KEY, OTHER_VALUE)
.withRepresentationProperty(OTHER_KEY).build());
@ -368,7 +370,7 @@ public class AutomaticInboxProcessorTest {
assertThat(results.size(), is(1));
assertThat(results.get(0).getThingUID(), is(equalTo(THING_UID2)));
automaticInboxProcessor.removed(thing2);
automaticInboxProcessor.removed(thing2Mock);
results = inbox.getAll();
assertThat(results.size(), is(0));
@ -381,11 +383,11 @@ public class AutomaticInboxProcessorTest {
// The following discovery result is automatically approved, as it has matching thing type UID
inbox.add(DiscoveryResultBuilder.create(THING_UID).build());
verify(thingRegistry, times(1)).add(argThat(thing -> THING_UID.equals(thing.getUID())));
verify(thingRegistryMock, times(1)).add(argThat(thing -> THING_UID.equals(thing.getUID())));
// The following discovery result is not automatically approved, as it does not have matching thing type UID
inbox.add(DiscoveryResultBuilder.create(THING_UID3).build());
verify(thingRegistry, never()).add(argThat(thing -> THING_UID3.equals(thing.getUID())));
verify(thingRegistryMock, never()).add(argThat(thing -> THING_UID3.equals(thing.getUID())));
}
@Test
@ -399,18 +401,18 @@ public class AutomaticInboxProcessorTest {
automaticInboxProcessor.addInboxAutoApprovePredicate(
discoveryResult -> THING_TYPE_UID.equals(discoveryResult.getThingTypeUID()));
verify(thingRegistry, times(1)).add(argThat(thing -> THING_UID.equals(thing.getUID())));
verify(thingRegistry, times(1)).add(argThat(thing -> THING_UID2.equals(thing.getUID())));
verify(thingRegistry, never()).add(argThat(thing -> THING_UID3.equals(thing.getUID())));
verify(thingRegistryMock, times(1)).add(argThat(thing -> THING_UID.equals(thing.getUID())));
verify(thingRegistryMock, times(1)).add(argThat(thing -> THING_UID2.equals(thing.getUID())));
verify(thingRegistryMock, never()).add(argThat(thing -> THING_UID3.equals(thing.getUID())));
// Adding this inboxAutoApprovePredicate will auto-approve the third discovery results as it has matching
// thing type UID.
automaticInboxProcessor.addInboxAutoApprovePredicate(
discoveryResult -> THING_TYPE_UID3.equals(discoveryResult.getThingTypeUID()));
verify(thingRegistry, times(1)).add(argThat(thing -> THING_UID.equals(thing.getUID())));
verify(thingRegistry, times(1)).add(argThat(thing -> THING_UID2.equals(thing.getUID())));
verify(thingRegistry, times(1)).add(argThat(thing -> THING_UID3.equals(thing.getUID())));
verify(thingRegistryMock, times(1)).add(argThat(thing -> THING_UID.equals(thing.getUID())));
verify(thingRegistryMock, times(1)).add(argThat(thing -> THING_UID2.equals(thing.getUID())));
verify(thingRegistryMock, times(1)).add(argThat(thing -> THING_UID3.equals(thing.getUID())));
}
@Test
@ -418,18 +420,18 @@ public class AutomaticInboxProcessorTest {
// Before setting the always auto approve property, existing inbox results are not approved
inbox.add(DiscoveryResultBuilder.create(THING_UID).build());
verify(thingRegistry, never()).add(argThat(thing -> THING_UID.equals(thing.getUID())));
verify(thingRegistryMock, never()).add(argThat(thing -> THING_UID.equals(thing.getUID())));
// After setting the always auto approve property, all existing inbox results are approved.
Map<String, Object> configProperties = new HashMap<>();
configProperties.put(AutomaticInboxProcessor.ALWAYS_AUTO_APPROVE_CONFIG_PROPERTY, true);
automaticInboxProcessor.activate(configProperties);
verify(thingRegistry, times(1)).add(argThat(thing -> THING_UID.equals(thing.getUID())));
verify(thingRegistryMock, times(1)).add(argThat(thing -> THING_UID.equals(thing.getUID())));
// Newly added inbox results are also approved.
inbox.add(DiscoveryResultBuilder.create(THING_UID2).build());
verify(thingRegistry, times(1)).add(argThat(thing -> THING_UID2.equals(thing.getUID())));
verify(thingRegistryMock, times(1)).add(argThat(thing -> THING_UID2.equals(thing.getUID())));
}
@Test
@ -446,6 +448,6 @@ public class AutomaticInboxProcessorTest {
// The discovery result is auto-approved in the presence of the evil predicates
inbox.add(DiscoveryResultBuilder.create(THING_UID).build());
verify(thingRegistry, times(1)).add(argThat(thing -> THING_UID.equals(thing.getUID())));
verify(thingRegistryMock, times(1)).add(argThat(thing -> THING_UID.equals(thing.getUID())));
}
}

View File

@ -17,6 +17,7 @@ import static org.junit.jupiter.api.Assertions.*;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
import org.openhab.core.config.discovery.DiscoveryResult;
import org.openhab.core.config.discovery.DiscoveryResultFlag;
@ -31,6 +32,7 @@ import org.openhab.core.thing.ThingUID;
* @author Thomas Höfer - Added representation
* @author Wouter Born - Migrate tests from Groovy to Java
*/
@NonNullByDefault
public class DiscoveryResultImplTest {
private static final int DEFAULT_TTL = 60;

View File

@ -25,6 +25,8 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ -64,6 +66,7 @@ import org.openhab.core.thing.type.ThingTypeRegistry;
*/
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.WARN)
@NonNullByDefault
public class PersistentInboxTest {
private static final String THING_OTHER_ID = "other";
@ -72,33 +75,34 @@ public class PersistentInboxTest {
private static final ThingUID THING_UID = new ThingUID(THING_TYPE_UID, "test");
private static final ThingUID THING_OTHER_UID = new ThingUID(THING_TYPE_UID, THING_OTHER_ID);
private PersistentInbox inbox;
private Thing lastAddedThing = null;
private @NonNullByDefault({}) PersistentInbox inbox;
private @Nullable Thing lastAddedThing;
private @Mock ThingRegistry thingRegistry;
private @Mock StorageService storageService;
private @Mock Storage<Object> storage;
private @Mock ManagedThingProvider thingProvider;
private @Mock ThingTypeRegistry thingTypeRegistry;
private @Mock ConfigDescriptionRegistry configDescriptionRegistry;
private @Mock ThingHandlerFactory thingHandlerFactory;
private @Mock @NonNullByDefault({}) ThingRegistry thingRegistryMock;
private @Mock @NonNullByDefault({}) StorageService storageServiceMock;
private @Mock @NonNullByDefault({}) Storage<Object> storageMock;
private @Mock @NonNullByDefault({}) ManagedThingProvider thingProviderMock;
private @Mock @NonNullByDefault({}) ThingTypeRegistry thingTypeRegistryMock;
private @Mock @NonNullByDefault({}) ConfigDescriptionRegistry configDescriptionRegistryMock;
private @Mock @NonNullByDefault({}) ThingHandlerFactory thingHandlerFactoryMock;
@BeforeEach
public void setup() {
when(storageService.getStorage(any(String.class), any(ClassLoader.class))).thenReturn(storage);
doAnswer(invocation -> lastAddedThing = (Thing) invocation.getArguments()[0]).when(thingRegistry)
when(storageServiceMock.getStorage(any(String.class), any(ClassLoader.class))).thenReturn(storageMock);
doAnswer(invocation -> lastAddedThing = (Thing) invocation.getArguments()[0]).when(thingRegistryMock)
.add(any(Thing.class));
when(thingHandlerFactory.supportsThingType(eq(THING_TYPE_UID))).thenReturn(true);
when(thingHandlerFactory.createThing(eq(THING_TYPE_UID), any(Configuration.class), eq(THING_UID), any()))
when(thingHandlerFactoryMock.supportsThingType(eq(THING_TYPE_UID))).thenReturn(true);
when(thingHandlerFactoryMock.createThing(eq(THING_TYPE_UID), any(Configuration.class), eq(THING_UID), any()))
.then(invocation -> ThingBuilder.create(THING_TYPE_UID, "test")
.withConfiguration((Configuration) invocation.getArguments()[1]).build());
when(thingHandlerFactory.createThing(eq(THING_TYPE_UID), any(Configuration.class), eq(THING_OTHER_UID), any()))
.then(invocation -> ThingBuilder.create(THING_TYPE_UID, THING_OTHER_ID)
.withConfiguration((Configuration) invocation.getArguments()[1]).build());
when(thingHandlerFactoryMock
.createThing(eq(THING_TYPE_UID), any(Configuration.class), eq(THING_OTHER_UID), any()))
.then(invocation -> ThingBuilder.create(THING_TYPE_UID, THING_OTHER_ID)
.withConfiguration((Configuration) invocation.getArguments()[1]).build());
inbox = new PersistentInbox(storageService, mock(DiscoveryServiceRegistry.class), thingRegistry, thingProvider,
thingTypeRegistry, configDescriptionRegistry);
inbox.addThingHandlerFactory(thingHandlerFactory);
inbox = new PersistentInbox(storageServiceMock, mock(DiscoveryServiceRegistry.class), thingRegistryMock,
thingProviderMock, thingTypeRegistryMock, configDescriptionRegistryMock);
inbox.addThingHandlerFactory(thingHandlerFactoryMock);
}
@Test
@ -108,7 +112,7 @@ public class PersistentInboxTest {
Configuration config = new Configuration(props);
Thing thing = ThingBuilder.create(THING_TYPE_UID, THING_UID).withConfiguration(config).build();
when(thingRegistry.get(eq(THING_UID))).thenReturn(thing);
when(thingRegistryMock.get(eq(THING_UID))).thenReturn(thing);
assertTrue(thing.getConfiguration().get("foo") instanceof BigDecimal);
@ -126,7 +130,7 @@ public class PersistentInboxTest {
Configuration config = new Configuration(props);
Thing thing = ThingBuilder.create(THING_TYPE_UID, THING_UID).withConfiguration(config).build();
configureConfigDescriptionRegistryMock("foo", Type.TEXT);
when(thingRegistry.get(eq(THING_UID))).thenReturn(thing);
when(thingRegistryMock.get(eq(THING_UID))).thenReturn(thing);
assertTrue(thing.getConfiguration().get("foo") instanceof String);
@ -141,7 +145,7 @@ public class PersistentInboxTest {
public void testApproveNormalization() throws URISyntaxException {
DiscoveryResult result = DiscoveryResultBuilder.create(THING_UID).withProperty("foo", 3).build();
configureConfigDescriptionRegistryMock("foo", Type.TEXT);
when(storage.getValues()).thenReturn(List.of(result));
when(storageMock.getValues()).thenReturn(List.of(result));
inbox.activate();
inbox.approve(THING_UID, "Test", null);
@ -155,7 +159,7 @@ public class PersistentInboxTest {
public void testApproveWithThingId() throws URISyntaxException {
DiscoveryResult result = DiscoveryResultBuilder.create(THING_UID).withProperty("foo", 3).build();
configureConfigDescriptionRegistryMock("foo", Type.TEXT);
when(storage.getValues()).thenReturn(List.of(result));
when(storageMock.getValues()).thenReturn(List.of(result));
inbox.activate();
inbox.approve(THING_UID, "Test", THING_OTHER_ID);
@ -169,7 +173,7 @@ public class PersistentInboxTest {
public void testApproveWithInvalidThingId() throws URISyntaxException {
DiscoveryResult result = DiscoveryResultBuilder.create(THING_UID).withProperty("foo", 3).build();
configureConfigDescriptionRegistryMock("foo", Type.TEXT);
when(storage.getValues()).thenReturn(List.of(result));
when(storageMock.getValues()).thenReturn(List.of(result));
inbox.activate();
Exception exception = assertThrows(IllegalArgumentException.class, () -> {
@ -190,7 +194,7 @@ public class PersistentInboxTest {
EventPublisher eventPublisher = mock(EventPublisher.class);
inbox.setEventPublisher(eventPublisher);
when(storage.get(THING_UID.toString())) //
when(storageMock.get(THING_UID.toString())) //
.thenReturn(null) //
.thenReturn(DiscoveryResultBuilder.create(THING_UID).withProperty("foo", "bar").build());
@ -200,7 +204,7 @@ public class PersistentInboxTest {
// 1st call checks existence of the result in the storage (returns null)
// 2nd call retrieves the stored instance before the event gets emitted
// (modified due to storage mock configuration)
verify(storage, times(2)).get(THING_UID.toString());
verify(storageMock, times(2)).get(THING_UID.toString());
ArgumentCaptor<InboxAddedEvent> eventCaptor = ArgumentCaptor.forClass(InboxAddedEvent.class);
verify(eventPublisher).post(eventCaptor.capture());
@ -214,7 +218,7 @@ public class PersistentInboxTest {
EventPublisher eventPublisher = mock(EventPublisher.class);
inbox.setEventPublisher(eventPublisher);
when(storage.get(THING_UID.toString())) //
when(storageMock.get(THING_UID.toString())) //
.thenReturn(result) //
.thenReturn(DiscoveryResultBuilder.create(THING_UID).withProperty("foo", "bar").build());
@ -224,7 +228,7 @@ public class PersistentInboxTest {
// 1st call checks existence of the result in the storage (returns the original result)
// 2nd call retrieves the stored instance before the event gets emitted
// (modified due to storage mock configuration)
verify(storage, times(2)).get(THING_UID.toString());
verify(storageMock, times(2)).get(THING_UID.toString());
ArgumentCaptor<InboxUpdatedEvent> eventCaptor = ArgumentCaptor.forClass(InboxUpdatedEvent.class);
verify(eventPublisher).post(eventCaptor.capture());
@ -238,7 +242,7 @@ public class PersistentInboxTest {
ConfigDescription configDesc = ConfigDescriptionBuilder.create(configDescriptionURI)
.withParameter(ConfigDescriptionParameterBuilder.create(paramName, type).build()).build();
when(thingTypeRegistry.getThingType(THING_TYPE_UID)).thenReturn(thingType);
when(configDescriptionRegistry.getConfigDescription(eq(configDescriptionURI))).thenReturn(configDesc);
when(thingTypeRegistryMock.getThingType(THING_TYPE_UID)).thenReturn(thingType);
when(configDescriptionRegistryMock.getConfigDescription(eq(configDescriptionURI))).thenReturn(configDesc);
}
}

View File

@ -20,6 +20,7 @@ import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchEvent.Kind;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@ -31,15 +32,16 @@ import org.mockito.junit.jupiter.MockitoExtension;
* @author Stefan Triller - Initial contribution
*/
@ExtendWith(MockitoExtension.class)
@NonNullByDefault
public class ConfigDispatcherFileWatcherTest {
private TestConfigDispatcherFileWatcher configDispatcherFileWatcher;
private @NonNullByDefault({}) TestConfigDispatcherFileWatcher configDispatcherFileWatcher;
private @Mock ConfigDispatcher configDispatcher;
private @Mock @NonNullByDefault({}) ConfigDispatcher configDispatcherMock;
@BeforeEach
public void setUp() throws Exception {
configDispatcherFileWatcher = new TestConfigDispatcherFileWatcher(configDispatcher);
configDispatcherFileWatcher = new TestConfigDispatcherFileWatcher(configDispatcherMock);
}
@Test
@ -48,7 +50,7 @@ public class ConfigDispatcherFileWatcherTest {
configDispatcherFileWatcher.processWatchEvent(new TestWatchEvent(), StandardWatchEventKinds.ENTRY_CREATE,
new File(path).toPath());
verify(configDispatcher).processConfigFile(new File(path));
verify(configDispatcherMock).processConfigFile(new File(path));
}
@Test
@ -57,7 +59,7 @@ public class ConfigDispatcherFileWatcherTest {
configDispatcherFileWatcher.processWatchEvent(new TestWatchEvent(), StandardWatchEventKinds.ENTRY_MODIFY,
new File(path).toPath());
verify(configDispatcher).processConfigFile(new File(path));
verify(configDispatcherMock).processConfigFile(new File(path));
}
@Test
@ -66,7 +68,7 @@ public class ConfigDispatcherFileWatcherTest {
configDispatcherFileWatcher.processWatchEvent(new TestWatchEvent(), StandardWatchEventKinds.ENTRY_CREATE,
new File(path).toPath());
verifyNoInteractions(configDispatcher);
verifyNoInteractions(configDispatcherMock);
}
@Test
@ -75,7 +77,7 @@ public class ConfigDispatcherFileWatcherTest {
configDispatcherFileWatcher.processWatchEvent(new TestWatchEvent(), StandardWatchEventKinds.ENTRY_MODIFY,
new File(path).toPath());
verifyNoInteractions(configDispatcher);
verifyNoInteractions(configDispatcherMock);
}
@Test
@ -84,7 +86,7 @@ public class ConfigDispatcherFileWatcherTest {
configDispatcherFileWatcher.processWatchEvent(new TestWatchEvent(), StandardWatchEventKinds.ENTRY_DELETE,
new File(path).toPath());
verify(configDispatcher).fileRemoved(new File(path).getAbsolutePath());
verify(configDispatcherMock).fileRemoved(new File(path).getAbsolutePath());
}
@Test
@ -93,7 +95,7 @@ public class ConfigDispatcherFileWatcherTest {
configDispatcherFileWatcher.processWatchEvent(new TestWatchEvent(), StandardWatchEventKinds.ENTRY_DELETE,
new File(path).toPath());
verifyNoInteractions(configDispatcher);
verifyNoInteractions(configDispatcherMock);
}
public static class TestConfigDispatcherFileWatcher extends ConfigDispatcherFileWatcher {
@ -107,10 +109,10 @@ public class ConfigDispatcherFileWatcherTest {
}
}
private static class TestWatchEvent implements WatchEvent<Path> {
private static class TestWatchEvent implements WatchEvent<@Nullable Path> {
@Override
public Kind<Path> kind() {
public Kind<@Nullable Path> kind() {
return StandardWatchEventKinds.ENTRY_CREATE;
}

View File

@ -19,6 +19,7 @@ import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
import org.openhab.core.OpenHAB;
@ -26,6 +27,7 @@ import org.openhab.core.OpenHAB;
* @author Kai Kreuzer - Initial contribution
* @author Wouter Born - Migrate tests from Groovy to Java
*/
@NonNullByDefault
public class InstanceUUIDTest {
@Test

View File

@ -18,6 +18,7 @@ import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
import com.google.gson.JsonObject;
@ -27,6 +28,7 @@ import com.google.gson.JsonObject;
*
* @author Pauli Anttila - Initial contribution
*/
@NonNullByDefault
public class Bin2JsonTest {
@Test

View File

@ -12,6 +12,7 @@
*/
package org.openhab.core.io.console.eclipse.internal;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.osgi.framework.console.CommandInterpreter;
import org.openhab.core.io.console.Console;
@ -20,6 +21,7 @@ import org.openhab.core.io.console.Console;
* @author Kai Kreuzer - Initial contribution
* @author Markus Rathgeb - Split to separate file
*/
@NonNullByDefault
public class OSGiConsole implements Console {
private final String baseCommand;

View File

@ -12,12 +12,14 @@
*/
package org.openhab.core.io.console.karaf.internal;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.core.io.console.Console;
/**
*
* @author Markus Rathgeb - Initial contribution
*/
@NonNullByDefault
public class OSGiConsole implements Console {
private final String scope;

View File

@ -14,6 +14,7 @@ package org.openhab.core.io.console.rfc147.internal;
import java.util.Arrays;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.core.io.console.ConsoleInterpreter;
import org.openhab.core.io.console.extensions.ConsoleCommandExtension;
@ -21,6 +22,7 @@ import org.openhab.core.io.console.extensions.ConsoleCommandExtension;
*
* @author Markus Rathgeb - Initial contribution
*/
@NonNullByDefault
public class CommandWrapper {
private final ConsoleCommandExtension command;

View File

@ -14,12 +14,14 @@ package org.openhab.core.io.console.rfc147.internal;
import java.util.Collection;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.core.io.console.extensions.ConsoleCommandExtension;
/**
*
* @author Markus Rathgeb - Initial contribution
*/
@NonNullByDefault
public interface ConsoleCommandsContainer {
public Collection<ConsoleCommandExtension> getConsoleCommandExtensions();

View File

@ -21,6 +21,8 @@ import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.core.io.console.extensions.ConsoleCommandExtension;
import org.openhab.core.io.console.rfc147.internal.extension.HelpConsoleCommandExtension;
import org.osgi.framework.BundleContext;
@ -43,6 +45,7 @@ import org.slf4j.LoggerFactory;
*
* @author Markus Rathgeb - Initial contribution
*/
@NonNullByDefault
@Component(immediate = true, service = {})
public class ConsoleSupportRfc147 implements ConsoleCommandsContainer {
@ -59,7 +62,7 @@ public class ConsoleSupportRfc147 implements ConsoleCommandsContainer {
private final HelpConsoleCommandExtension helpCommand = new HelpConsoleCommandExtension();
private BundleContext bc;
private @Nullable BundleContext bundleContext;
/*
* This map will contain all console command extensions.
@ -67,7 +70,7 @@ public class ConsoleSupportRfc147 implements ConsoleCommandsContainer {
* The value is set to null, if the console command extension is not registered, yet (e.g. the bundle context is not
* known). Otherwise it stores the registered service reference, so we could unregister the command extension later.
*/
private final Map<ConsoleCommandExtension, ServiceRegistration<?>> commands = Collections
private final Map<ConsoleCommandExtension, @Nullable ServiceRegistration<?>> commands = Collections
.synchronizedMap(new HashMap<>());
public ConsoleSupportRfc147() {
@ -78,13 +81,13 @@ public class ConsoleSupportRfc147 implements ConsoleCommandsContainer {
@Activate
public void activate(ComponentContext ctx) {
// Save bundle context to register services.
this.bc = ctx.getBundleContext();
this.bundleContext = ctx.getBundleContext();
/*
* The bundle context is available.
* Register all console command extensions that are not registered before.
*/
for (Map.Entry<ConsoleCommandExtension, ServiceRegistration<?>> entry : commands.entrySet()) {
for (Map.Entry<ConsoleCommandExtension, @Nullable ServiceRegistration<?>> entry : commands.entrySet()) {
if (entry.getValue() == null) {
entry.setValue(registerCommand(entry.getKey()));
}
@ -102,15 +105,16 @@ public class ConsoleSupportRfc147 implements ConsoleCommandsContainer {
/*
* De-register all previously registered command extensions.
*/
for (Map.Entry<ConsoleCommandExtension, ServiceRegistration<?>> entry : commands.entrySet()) {
if (entry.getValue() != null) {
unregisterCommand(entry.getValue());
for (Map.Entry<ConsoleCommandExtension, @Nullable ServiceRegistration<?>> entry : commands.entrySet()) {
ServiceRegistration<?> value = entry.getValue();
if (value != null) {
unregisterCommand(value);
entry.setValue(null);
}
}
// Remove bundle context reference.
this.bc = null;
this.bundleContext = null;
}
@Reference(cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC)
@ -143,9 +147,10 @@ public class ConsoleSupportRfc147 implements ConsoleCommandsContainer {
* @param cmd the console command extension that should be registered.
* @return the service registration reference on success, null if the registration was not successful.
*/
private ServiceRegistration<?> registerCommand(final ConsoleCommandExtension cmd) {
private @Nullable ServiceRegistration<?> registerCommand(final ConsoleCommandExtension cmd) {
// We could only register the service if the bundle context is known.
if (this.bc == null) {
BundleContext bundleContext = this.bundleContext;
if (bundleContext == null) {
return null;
}
@ -155,7 +160,8 @@ public class ConsoleSupportRfc147 implements ConsoleCommandsContainer {
try {
final ServiceRegistration<?> serviceRegistration;
serviceRegistration = bc.registerService(CommandWrapper.class.getName(), new CommandWrapper(cmd), props);
serviceRegistration = bundleContext.registerService(CommandWrapper.class.getName(), new CommandWrapper(cmd),
props);
return serviceRegistration;
} catch (final IllegalStateException ex) {
logger.trace("Registration failed.");
@ -181,7 +187,7 @@ public class ConsoleSupportRfc147 implements ConsoleCommandsContainer {
final Set<ConsoleCommandExtension> set = new HashSet<>();
// Fill set with registered commands only.
for (Map.Entry<ConsoleCommandExtension, ServiceRegistration<?>> entry : commands.entrySet()) {
for (Map.Entry<ConsoleCommandExtension, @Nullable ServiceRegistration<?>> entry : commands.entrySet()) {
if (entry.getValue() != null) {
set.add(entry.getKey());
}

View File

@ -12,12 +12,14 @@
*/
package org.openhab.core.io.console.rfc147.internal;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.core.io.console.Console;
/**
*
* @author Markus Rathgeb - Initial contribution
*/
@NonNullByDefault
public class OSGiConsole implements Console {
private final String base;

View File

@ -14,6 +14,8 @@ package org.openhab.core.io.console.rfc147.internal.extension;
import java.util.List;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.core.io.console.Console;
import org.openhab.core.io.console.ConsoleInterpreter;
import org.openhab.core.io.console.extensions.AbstractConsoleCommandExtension;
@ -24,15 +26,16 @@ import org.openhab.core.io.console.rfc147.internal.ConsoleSupportRfc147;
*
* @author Markus Rathgeb - Initial contribution
*/
@NonNullByDefault
public class HelpConsoleCommandExtension extends AbstractConsoleCommandExtension {
private ConsoleCommandsContainer commandsContainer;
private @Nullable ConsoleCommandsContainer commandsContainer;
public HelpConsoleCommandExtension() {
super("help", "Get help for all available commands.");
}
public void setConsoleCommandsContainer(final ConsoleCommandsContainer commandsContainer) {
public void setConsoleCommandsContainer(final @Nullable ConsoleCommandsContainer commandsContainer) {
this.commandsContainer = commandsContainer;
}
@ -43,9 +46,10 @@ public class HelpConsoleCommandExtension extends AbstractConsoleCommandExtension
@Override
public void execute(String[] args, Console console) {
if (this.commandsContainer != null) {
ConsoleCommandsContainer commandsContainer = this.commandsContainer;
if (commandsContainer != null) {
ConsoleInterpreter.printHelp(console, ConsoleSupportRfc147.CONSOLE.getBase(), ":",
this.commandsContainer.getConsoleCommandExtensions());
commandsContainer.getConsoleCommandExtensions());
}
}

View File

@ -12,12 +12,15 @@
*/
package org.openhab.core.io.console;
import org.eclipse.jdt.annotation.NonNullByDefault;
/**
* This interface must be implemented by consoles which want to use the {@link ConsoleInterpreter}.
* It allows basic output commands.
*
* @author Kai Kreuzer - Initial contribution
*/
@NonNullByDefault
public interface Console {
default void printf(String format, Object... args) {

View File

@ -16,6 +16,7 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.core.io.console.extensions.ConsoleCommandExtension;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -26,6 +27,7 @@ import org.slf4j.LoggerFactory;
* @author Kai Kreuzer - Initial contribution
* @author Markus Rathgeb - Change interface
*/
@NonNullByDefault
public class ConsoleInterpreter {
public static String getHelp(final String base, final String separator,

View File

@ -16,6 +16,7 @@ import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.*;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ -30,46 +31,47 @@ import org.osgi.service.http.HttpContext;
* @author Łukasz Dywicki - Initial contribution
*/
@ExtendWith(MockitoExtension.class)
@NonNullByDefault
public class HttpContextFactoryServiceImplTest {
private static final String RESOURCE = "resource";
private HttpContextFactoryServiceImpl httpContextFactoryService;
private @NonNullByDefault({}) HttpContextFactoryServiceImpl httpContextFactoryService;
private @Mock Bundle bundle;
private @Mock WrappingHttpContext httpContext;
private @Mock @NonNullByDefault({}) Bundle bundleMock;
private @Mock @NonNullByDefault({}) WrappingHttpContext httpContextMock;
@BeforeEach
public void setup() {
httpContextFactoryService = new HttpContextFactoryServiceImpl();
httpContextFactoryService.setHttpContext(httpContext);
httpContextFactoryService.setHttpContext(httpContextMock);
when(httpContext.wrap(bundle)).thenReturn(new BundleHttpContext(httpContext, bundle));
when(httpContextMock.wrap(bundleMock)).thenReturn(new BundleHttpContext(httpContextMock, bundleMock));
}
@Test
public void shouldCreateHttpContext() {
HttpContext context = httpContextFactoryService.createDefaultHttpContext(bundle);
HttpContext context = httpContextFactoryService.createDefaultHttpContext(bundleMock);
assertThat(context, is(notNullValue()));
verify(httpContext).wrap(bundle);
verify(httpContextMock).wrap(bundleMock);
}
@Test
public void httpContextShouldCallgetResourceOnBundle() {
HttpContext context = httpContextFactoryService.createDefaultHttpContext(bundle);
HttpContext context = httpContextFactoryService.createDefaultHttpContext(bundleMock);
context.getResource(RESOURCE);
verify(httpContext).wrap(bundle);
verify(bundle).getResource(RESOURCE);
verify(httpContextMock).wrap(bundleMock);
verify(bundleMock).getResource(RESOURCE);
}
@Test
public void httpContextShouldCallgetResourceOnBundleWithoutLeadingSlash() {
HttpContext context = httpContextFactoryService.createDefaultHttpContext(bundle);
HttpContext context = httpContextFactoryService.createDefaultHttpContext(bundleMock);
context.getResource("/" + RESOURCE);
verify(httpContext).wrap(bundle);
verify(bundle).getResource(RESOURCE);
verify(httpContextMock).wrap(bundleMock);
verify(bundleMock).getResource(RESOURCE);
}
}

View File

@ -16,6 +16,7 @@ import static org.junit.jupiter.api.Assertions.*;
import java.time.Duration;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
/**
@ -23,6 +24,7 @@ import org.junit.jupiter.api.Test;
*
* @author Christoph Weitkamp - Initial contribution
*/
@NonNullByDefault
public class ExecUtilTest {
@Test

View File

@ -18,6 +18,7 @@ import static org.mockito.Mockito.when;
import java.lang.reflect.Field;
import java.util.concurrent.TimeUnit;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.client.api.Request;
@ -37,13 +38,15 @@ import org.mockito.quality.Strictness;
*/
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.WARN)
@NonNullByDefault
public abstract class BaseHttpUtilTest {
static final String URL = "http://example.org/test";
protected @Mock HttpClientFactory clientFactoryMock;
protected @Mock HttpClient httpClientMock;
protected @Mock Request requestMock;
protected @Mock ContentResponse contentResponseMock;
protected @Mock @NonNullByDefault({}) HttpClientFactory clientFactoryMock;
protected @Mock @NonNullByDefault({}) HttpClient httpClientMock;
protected @Mock @NonNullByDefault({}) Request requestMock;
protected @Mock @NonNullByDefault({}) ContentResponse contentResponseMock;
@BeforeEach
public void setUp() throws Exception {

View File

@ -21,6 +21,7 @@ import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jetty.client.api.ContentProvider;
import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.http.HttpStatus;
@ -33,6 +34,7 @@ import org.mockito.ArgumentMatchers;
*
* @author Martin van Wingerden & Wouter Born - Initial contribution
*/
@NonNullByDefault
public class HttpRequestBuilderTest extends BaseHttpUtilTest {
@Test

View File

@ -17,6 +17,7 @@ import static org.mockito.Mockito.*;
import java.util.concurrent.TimeUnit;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jetty.http.HttpHeader;
import org.eclipse.jetty.http.HttpMethod;
import org.eclipse.jetty.http.HttpStatus;
@ -28,6 +29,7 @@ import org.junit.jupiter.api.Test;
* @author Thomas Eichstaedt-Engelen - Initial contribution
* @author Martin van Wingerden - Added tests based on HttpClientFactory
*/
@NonNullByDefault
public class HttpUtilTest extends BaseHttpUtilTest {
@Test

View File

@ -29,6 +29,7 @@ import javax.net.ssl.SSLEngine;
import javax.net.ssl.X509ExtendedTrustManager;
import javax.security.auth.x500.X500Principal;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ -45,128 +46,129 @@ import org.openhab.core.io.net.http.TlsTrustManagerProvider;
*/
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.WARN)
@NonNullByDefault
public class ExtensibleTrustManagerImplTest {
private X509Certificate[] chain;
private ExtensibleTrustManagerImpl subject;
private @NonNullByDefault({}) X509Certificate[] chain;
private @NonNullByDefault({}) ExtensibleTrustManagerImpl subject;
private @Mock TlsTrustManagerProvider trustmanagerProvider;
private @Mock TlsTrustManagerProvider trustmanagerProviderHostPort;
private @Mock X509ExtendedTrustManager trustmanager;
private @Mock X509ExtendedTrustManager trustmanager2;
private @Mock X509ExtendedTrustManager defaultTrustManager;
private @Mock SSLEngine sslEngine;
private @Mock X509Certificate topOfChain;
private @Mock X509Certificate bottomOfChain;
private @Mock @NonNullByDefault({}) TlsTrustManagerProvider trustmanagerProviderMock;
private @Mock @NonNullByDefault({}) TlsTrustManagerProvider trustmanagerProviderHostPortMock;
private @Mock @NonNullByDefault({}) X509ExtendedTrustManager trustmanagerMock;
private @Mock @NonNullByDefault({}) X509ExtendedTrustManager trustmanager2Mock;
private @Mock @NonNullByDefault({}) X509ExtendedTrustManager defaultTrustManagerMock;
private @Mock @NonNullByDefault({}) SSLEngine sslEngineMock;
private @Mock @NonNullByDefault({}) X509Certificate topOfChainMock;
private @Mock @NonNullByDefault({}) X509Certificate bottomOfChainMock;
@BeforeEach
public void setup() {
when(trustmanagerProvider.getHostName()).thenReturn("example.org");
when(trustmanagerProvider.getTrustManager()).thenReturn(trustmanager);
when(trustmanagerProviderMock.getHostName()).thenReturn("example.org");
when(trustmanagerProviderMock.getTrustManager()).thenReturn(trustmanagerMock);
when(trustmanagerProviderHostPort.getHostName()).thenReturn("example.org:443");
when(trustmanagerProviderHostPort.getTrustManager()).thenReturn(trustmanager2);
when(trustmanagerProviderHostPortMock.getHostName()).thenReturn("example.org:443");
when(trustmanagerProviderHostPortMock.getTrustManager()).thenReturn(trustmanager2Mock);
subject = new ExtensibleTrustManagerImpl();
subject.addTlsTrustManagerProvider(trustmanagerProvider);
subject.addTlsTrustManagerProvider(trustmanagerProviderHostPort);
subject.addTlsTrustManagerProvider(trustmanagerProviderMock);
subject.addTlsTrustManagerProvider(trustmanagerProviderHostPortMock);
chain = new X509Certificate[] { topOfChain, bottomOfChain };
chain = new X509Certificate[] { topOfChainMock, bottomOfChainMock };
}
@Test
public void shouldForwardCallsToMockForMatchingCN() throws CertificateException {
when(topOfChain.getSubjectX500Principal())
when(topOfChainMock.getSubjectX500Principal())
.thenReturn(new X500Principal("CN=example.org, OU=Core, O=openHAB, C=DE"));
subject.checkServerTrusted(chain, "just");
verify(trustmanager).checkServerTrusted(chain, "just", (Socket) null);
verifyNoMoreInteractions(trustmanager, trustmanager2);
verify(trustmanagerMock).checkServerTrusted(chain, "just", (Socket) null);
verifyNoMoreInteractions(trustmanagerMock, trustmanager2Mock);
}
@Test
public void shouldForwardCallsToMockForMatchingHost() throws CertificateException {
when(sslEngine.getPeerHost()).thenReturn("example.org");
when(sslEngine.getPeerPort()).thenReturn(443);
when(sslEngineMock.getPeerHost()).thenReturn("example.org");
when(sslEngineMock.getPeerPort()).thenReturn(443);
subject.checkServerTrusted(chain, "just", sslEngine);
subject.checkServerTrusted(chain, "just", sslEngineMock);
verify(trustmanager2).checkServerTrusted(chain, "just", sslEngine);
verifyNoMoreInteractions(trustmanager, trustmanager2);
verify(trustmanager2Mock).checkServerTrusted(chain, "just", sslEngineMock);
verifyNoMoreInteractions(trustmanagerMock, trustmanager2Mock);
}
@Test
public void shouldForwardCallsToMockForMatchingAlternativeNames() throws CertificateException {
when(topOfChain.getSubjectX500Principal())
when(topOfChainMock.getSubjectX500Principal())
.thenReturn(new X500Principal("CN=example.com, OU=Core, O=openHAB, C=DE"));
when(topOfChain.getSubjectAlternativeNames())
when(topOfChainMock.getSubjectAlternativeNames())
.thenReturn(constructAlternativeNames("example1.com", "example.org"));
subject.checkClientTrusted(chain, "just");
verify(trustmanager).checkClientTrusted(chain, "just", (Socket) null);
verifyNoMoreInteractions(trustmanager);
verify(trustmanagerMock).checkClientTrusted(chain, "just", (Socket) null);
verifyNoMoreInteractions(trustmanagerMock);
}
@Test
public void shouldBeResilientAgainstNullSubjectAlternativeNames()
throws CertificateException, IllegalAccessException, NoSuchFieldException, SecurityException {
writeField(subject, "defaultTrustManager", defaultTrustManager, true);
writeField(subject, "defaultTrustManager", defaultTrustManagerMock, true);
when(topOfChain.getSubjectX500Principal())
when(topOfChainMock.getSubjectX500Principal())
.thenReturn(new X500Principal("CN=example.com, OU=Core, O=openHAB, C=DE"));
when(topOfChain.getSubjectAlternativeNames()).thenReturn(null);
when(topOfChainMock.getSubjectAlternativeNames()).thenReturn(null);
subject.checkClientTrusted(chain, "just");
verify(defaultTrustManager).checkClientTrusted(chain, "just", (Socket) null);
verifyNoMoreInteractions(trustmanager);
verify(defaultTrustManagerMock).checkClientTrusted(chain, "just", (Socket) null);
verifyNoMoreInteractions(trustmanagerMock);
}
@Test
public void shouldBeResilientAgainstMissingCommonNames() throws CertificateException, IllegalAccessException,
NoSuchFieldException, SecurityException, IllegalArgumentException {
writeField(subject, "defaultTrustManager", defaultTrustManager, true);
writeField(subject, "defaultTrustManager", defaultTrustManagerMock, true);
when(topOfChain.getSubjectX500Principal()).thenReturn(new X500Principal("OU=Core, O=openHAB, C=DE"));
when(topOfChainMock.getSubjectX500Principal()).thenReturn(new X500Principal("OU=Core, O=openHAB, C=DE"));
subject.checkClientTrusted(chain, "just");
verify(defaultTrustManager).checkClientTrusted(chain, "just", (Socket) null);
verifyNoMoreInteractions(trustmanager);
verify(defaultTrustManagerMock).checkClientTrusted(chain, "just", (Socket) null);
verifyNoMoreInteractions(trustmanagerMock);
}
@Test
public void shouldBeResilientAgainstInvalidCertificates() throws CertificateException, IllegalAccessException,
NoSuchFieldException, SecurityException, IllegalArgumentException {
writeField(subject, "defaultTrustManager", defaultTrustManager, true);
writeField(subject, "defaultTrustManager", defaultTrustManagerMock, true);
when(topOfChain.getSubjectX500Principal())
when(topOfChainMock.getSubjectX500Principal())
.thenReturn(new X500Principal("CN=example.com, OU=Core, O=openHAB, C=DE"));
when(topOfChain.getSubjectAlternativeNames())
when(topOfChainMock.getSubjectAlternativeNames())
.thenThrow(new CertificateParsingException("Invalid certificate!!!"));
subject.checkClientTrusted(chain, "just");
verify(defaultTrustManager).checkClientTrusted(chain, "just", (Socket) null);
verifyNoMoreInteractions(trustmanager);
verify(defaultTrustManagerMock).checkClientTrusted(chain, "just", (Socket) null);
verifyNoMoreInteractions(trustmanagerMock);
}
@Test
public void shouldNotForwardCallsToMockForDifferentCN() throws CertificateException, IllegalAccessException,
NoSuchFieldException, SecurityException, IllegalArgumentException {
writeField(subject, "defaultTrustManager", defaultTrustManager, true);
mockSubjectForCertificate(topOfChain, "CN=example.com, OU=Core, O=openHAB, C=DE");
mockIssuerForCertificate(topOfChain, "CN=openHAB, OU=Core, O=openHAB, C=DE");
mockSubjectForCertificate(bottomOfChain, "CN=openHAB, OU=Core, O=openHAB, C=DE");
mockIssuerForCertificate(bottomOfChain, "");
when(topOfChain.getEncoded()).thenReturn(new byte[0]);
writeField(subject, "defaultTrustManager", defaultTrustManagerMock, true);
mockSubjectForCertificate(topOfChainMock, "CN=example.com, OU=Core, O=openHAB, C=DE");
mockIssuerForCertificate(topOfChainMock, "CN=openHAB, OU=Core, O=openHAB, C=DE");
mockSubjectForCertificate(bottomOfChainMock, "CN=openHAB, OU=Core, O=openHAB, C=DE");
mockIssuerForCertificate(bottomOfChainMock, "");
when(topOfChainMock.getEncoded()).thenReturn(new byte[0]);
subject.checkServerTrusted(chain, "just");
verify(defaultTrustManager).checkServerTrusted(chain, "just", (Socket) null);
verifyNoInteractions(trustmanager);
verify(defaultTrustManagerMock).checkServerTrusted(chain, "just", (Socket) null);
verifyNoInteractions(trustmanagerMock);
}
private Collection<List<?>> constructAlternativeNames(String... alternatives) {

View File

@ -33,6 +33,7 @@ import java.util.concurrent.TimeoutException;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLHandshakeException;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.websocket.client.WebSocketClient;
@ -50,17 +51,18 @@ import org.mockito.junit.jupiter.MockitoExtension;
* @author Kai Kreuzer - Initial contribution
*/
@ExtendWith(MockitoExtension.class)
@NonNullByDefault
public class WebClientFactoryImplTest {
private WebClientFactoryImpl webClientFactory;
private @NonNullByDefault({}) WebClientFactoryImpl webClientFactory;
private static final String TEST_URL = "https://www.eclipse.org/";
private @Mock ExtensibleTrustManagerImpl extensibleTrustManager;
private @Mock @NonNullByDefault({}) ExtensibleTrustManagerImpl extensibleTrustManagerMock;
@BeforeEach
public void setup() {
webClientFactory = new WebClientFactoryImpl(extensibleTrustManager);
webClientFactory = new WebClientFactoryImpl(extensibleTrustManagerMock);
webClientFactory.activate(createConfigMap(4, 200, 60, 2, 10, 60));
}
@ -95,9 +97,9 @@ public class WebClientFactoryImplTest {
fail("Statuscode != 200");
}
verify(extensibleTrustManager).checkServerTrusted(certificateChainCaptor.capture(), anyString(),
verify(extensibleTrustManagerMock).checkServerTrusted(certificateChainCaptor.capture(), anyString(),
sslEngineCaptor.capture());
verifyNoMoreInteractions(extensibleTrustManager);
verifyNoMoreInteractions(extensibleTrustManagerMock);
assertThat(sslEngineCaptor.getValue().getPeerHost(), is("www.eclipse.org"));
assertThat(sslEngineCaptor.getValue().getPeerPort(), is(443));
assertThat(certificateChainCaptor.getValue()[0].getSubjectX500Principal().getName(),
@ -107,7 +109,7 @@ public class WebClientFactoryImplTest {
@Disabled("connecting to the outside world makes this test flaky")
@Test
public void testCommonClientUsesExtensibleTrustManagerFailure() throws Exception {
doThrow(new CertificateException()).when(extensibleTrustManager).checkServerTrusted(
doThrow(new CertificateException()).when(extensibleTrustManagerMock).checkServerTrusted(
ArgumentMatchers.any(X509Certificate[].class), anyString(), ArgumentMatchers.any(SSLEngine.class));
HttpClient httpClient = webClientFactory.getCommonHttpClient();

View File

@ -19,6 +19,7 @@ import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import java.net.URI;
import java.util.List;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
import org.openhab.core.config.core.ConfigDescription;
import org.openhab.core.config.core.ConfigDescriptionBuilder;
@ -31,6 +32,7 @@ import org.openhab.core.config.core.dto.ConfigDescriptionParameterDTO;
/**
* @author Christoph Weitkamp - Initial contribution
*/
@NonNullByDefault
public class EnrichedConfigDescriptionDTOMapperTest {
private static final URI CONFIG_URI = URI.create("system:ephemeris");

View File

@ -23,6 +23,7 @@ import java.util.Set;
import javax.ws.rs.core.Response;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.hamcrest.core.IsIterableContaining;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@ -43,26 +44,27 @@ import org.openhab.core.thing.type.ChannelTypeUID;
* @author Henning Treu - Initial contribution
*/
@ExtendWith(MockitoExtension.class)
@NonNullByDefault
public class ChannelTypeResourceTest {
private ChannelTypeResource channelTypeResource;
private @NonNullByDefault({}) ChannelTypeResource channelTypeResource;
private @Mock ChannelTypeRegistry channelTypeRegistry;
private @Mock ConfigDescriptionRegistry configDescriptionRegistry;
private @Mock LocaleServiceImpl localeService;
private @Mock ProfileTypeRegistry profileTypeRegistry;
private @Mock @NonNullByDefault({}) ChannelTypeRegistry channelTypeRegistryMock;
private @Mock @NonNullByDefault({}) ConfigDescriptionRegistry configDescriptionRegistryMock;
private @Mock @NonNullByDefault({}) LocaleServiceImpl localeServiceMock;
private @Mock @NonNullByDefault({}) ProfileTypeRegistry profileTypeRegistryMock;
@BeforeEach
public void setup() {
channelTypeResource = new ChannelTypeResource(channelTypeRegistry, configDescriptionRegistry, localeService,
profileTypeRegistry);
channelTypeResource = new ChannelTypeResource(channelTypeRegistryMock, configDescriptionRegistryMock,
localeServiceMock, profileTypeRegistryMock);
}
@Test
public void getAllShouldRetrieveAllChannelTypes() throws Exception {
when(localeService.getLocale(null)).thenReturn(Locale.ENGLISH);
when(localeServiceMock.getLocale(null)).thenReturn(Locale.ENGLISH);
channelTypeResource.getAll(null, null);
verify(channelTypeRegistry).getChannelTypes(Locale.ENGLISH);
verify(channelTypeRegistryMock).getChannelTypes(Locale.ENGLISH);
}
@SuppressWarnings("unchecked")
@ -71,18 +73,18 @@ public class ChannelTypeResourceTest {
ChannelTypeUID channelTypeUID = new ChannelTypeUID("binding", "ct");
ChannelType channelType = ChannelTypeBuilder.trigger(channelTypeUID, "Label").build();
when(channelTypeRegistry.getChannelType(channelTypeUID)).thenReturn(channelType);
when(channelTypeRegistryMock.getChannelType(channelTypeUID)).thenReturn(channelType);
TriggerProfileType profileType = mock(TriggerProfileType.class);
when(profileType.getSupportedChannelTypeUIDs()).thenReturn(List.of(channelTypeUID));
when(profileType.getSupportedItemTypes()).thenReturn(List.of(CoreItemFactory.SWITCH, CoreItemFactory.DIMMER));
when(profileTypeRegistry.getProfileTypes()).thenReturn(List.of(profileType));
when(profileTypeRegistryMock.getProfileTypes()).thenReturn(List.of(profileType));
Response response = channelTypeResource.getLinkableItemTypes(channelTypeUID.getAsString());
verify(channelTypeRegistry).getChannelType(channelTypeUID);
verify(profileTypeRegistry).getProfileTypes();
verify(channelTypeRegistryMock).getChannelType(channelTypeUID);
verify(profileTypeRegistryMock).getProfileTypes();
assertThat(response.getStatus(), is(200));
assertThat((Set<String>) response.getEntity(),
IsIterableContaining.hasItems(CoreItemFactory.SWITCH, CoreItemFactory.DIMMER));

View File

@ -26,6 +26,7 @@ import java.util.List;
import javax.ws.rs.core.Response;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ -45,6 +46,7 @@ import org.openhab.core.io.rest.LocaleService;
*/
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.WARN)
@NonNullByDefault
public class ConfigDescriptionResourceTest {
private static final String PARAM_NAME = "name";
@ -53,10 +55,10 @@ public class ConfigDescriptionResourceTest {
private static final String CONFIG_DESCRIPTION_SYSTEM_I18N_URI = "system:i18n";
private ConfigDescriptionResource resource;
private @NonNullByDefault({}) ConfigDescriptionResource resource;
private @Mock ConfigDescriptionRegistry mockedConfigDescriptionRegistry;
private @Mock LocaleService mockedLocaleService;
private @Mock @NonNullByDefault({}) ConfigDescriptionRegistry configDescriptionRegistryMock;
private @Mock @NonNullByDefault({}) LocaleService localeServiceMock;
@BeforeEach
public void beforeEach() throws URISyntaxException {
@ -67,11 +69,11 @@ public class ConfigDescriptionResourceTest {
.build();
final ConfigDescription systemEphemeris = ConfigDescriptionBuilder.create(new URI("system:ephemeris"))
.withParameter(ConfigDescriptionParameterBuilder.create(PARAM_COUNTRY, Type.TEXT).build()).build();
when(mockedConfigDescriptionRegistry.getConfigDescriptions(any()))
when(configDescriptionRegistryMock.getConfigDescriptions(any()))
.thenReturn(List.of(systemI18n, systemEphemeris));
when(mockedConfigDescriptionRegistry.getConfigDescription(eq(systemI18nURI), any())).thenReturn(systemI18n);
when(configDescriptionRegistryMock.getConfigDescription(eq(systemI18nURI), any())).thenReturn(systemI18n);
resource = new ConfigDescriptionResource(mockedConfigDescriptionRegistry, mockedLocaleService);
resource = new ConfigDescriptionResource(configDescriptionRegistryMock, localeServiceMock);
}
@Test

View File

@ -23,6 +23,7 @@ import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ -41,22 +42,23 @@ import org.openhab.core.items.MetadataRegistry;
*/
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.WARN)
@NonNullByDefault
public class MetadataSelectorMatcherTest {
private MetadataSelectorMatcher matcher;
private @NonNullByDefault({}) MetadataSelectorMatcher matcher;
private @Mock MetadataRegistry metadataRegistry;
private @Mock @NonNullByDefault({}) MetadataRegistry metadataRegistryMock;
@BeforeEach
public void setup() throws Exception {
when(metadataRegistry.getAll())
when(metadataRegistryMock.getAll())
.thenReturn(List.of(new Metadata(new MetadataKey("magic", "test_item"), "test", Map.of()),
new Metadata(new MetadataKey("magic2", "test_item"), "test", Map.of()),
new Metadata(new MetadataKey("homekit", "test_item"), "test", Map.of()),
new Metadata(new MetadataKey("alexa", "test_item"), "test", Map.of())));
when(metadataRegistry.isInternalNamespace(anyString())).thenReturn(false);
when(metadataRegistryMock.isInternalNamespace(anyString())).thenReturn(false);
matcher = new MetadataSelectorMatcher(metadataRegistry);
matcher = new MetadataSelectorMatcher(metadataRegistryMock);
}
@Test

View File

@ -24,6 +24,7 @@ import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ -46,21 +47,23 @@ import org.openhab.core.types.State;
* @author Stefan Triller - Initial contribution
*/
@ExtendWith(MockitoExtension.class)
@NonNullByDefault
public class PersistenceResourceTest {
private static final String PERSISTENCE_SERVICE_ID = "TestServiceID";
private PersistenceResource pResource;
private List<HistoricItem> items;
private @NonNullByDefault({}) PersistenceResource pResource;
private @NonNullByDefault({}) List<HistoricItem> items;
private @Mock ItemRegistry itemRegistry;
private @Mock LocaleService localeService;
private @Mock PersistenceServiceRegistry persistenceServiceRegistry;
private @Mock TimeZoneProvider timeZoneProvider;
private @Mock @NonNullByDefault({}) ItemRegistry itemRegistryMock;
private @Mock @NonNullByDefault({}) LocaleService localeServiceMock;
private @Mock @NonNullByDefault({}) PersistenceServiceRegistry persistenceServiceRegistryMock;
private @Mock @NonNullByDefault({}) TimeZoneProvider timeZoneProviderMock;
@BeforeEach
public void beforeEach() {
pResource = new PersistenceResource(itemRegistry, localeService, persistenceServiceRegistry, timeZoneProvider);
pResource = new PersistenceResource(itemRegistryMock, localeServiceMock, persistenceServiceRegistryMock,
timeZoneProviderMock);
int startValue = 2016;
int endValue = 2018;
@ -92,8 +95,8 @@ public class PersistenceResourceTest {
QueryablePersistenceService pService = mock(QueryablePersistenceService.class);
when(pService.query(any())).thenReturn(items);
when(persistenceServiceRegistry.get(PERSISTENCE_SERVICE_ID)).thenReturn(pService);
when(timeZoneProvider.getTimeZone()).thenReturn(ZoneId.systemDefault());
when(persistenceServiceRegistryMock.get(PERSISTENCE_SERVICE_ID)).thenReturn(pService);
when(timeZoneProviderMock.getTimeZone()).thenReturn(ZoneId.systemDefault());
}
@Test

View File

@ -16,7 +16,7 @@ import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import org.junit.jupiter.api.BeforeEach;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
import org.openhab.core.items.GenericItem;
import org.openhab.core.items.GroupItem;
@ -26,17 +26,13 @@ import org.openhab.core.test.java.JavaTest;
/**
* @author Kai Kreuzer - Initial contribution
*/
@NonNullByDefault
public class EnrichedItemDTOMapperTest extends JavaTest {
private CoreItemFactory itemFactory;
@BeforeEach
public void setup() {
itemFactory = new CoreItemFactory();
}
@Test
public void testFiltering() {
CoreItemFactory itemFactory = new CoreItemFactory();
GroupItem group = new GroupItem("TestGroup");
GroupItem subGroup = new GroupItem("TestSubGroup");
GenericItem switchItem = itemFactory.createItem(CoreItemFactory.SWITCH, "TestSwitch");

View File

@ -25,6 +25,7 @@ import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.hamcrest.CoreMatchers;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@ -45,6 +46,7 @@ import org.openhab.core.thing.firmware.dto.FirmwareStatusDTO;
* @author Henning Treu - Initial contribution
*/
@ExtendWith(MockitoExtension.class)
@NonNullByDefault
public class EnrichedThingDTOMapperTest {
private static final String ITEM_TYPE = "itemType";
@ -53,42 +55,43 @@ public class EnrichedThingDTOMapperTest {
private static final String THING_LABEL = "label";
private static final String LOCATION = "location";
private @Mock Thing thing;
private @Mock ThingStatusInfo thingStatusInfo;
private @Mock FirmwareStatusDTO firmwareStatus;
private @Mock Map<String, Set<String>> linkedItemsMap;
private @Mock Configuration configuration;
private @Mock Map<String, String> properties;
private @Mock @NonNullByDefault({}) Thing thingMock;
private @Mock @NonNullByDefault({}) ThingStatusInfo thingStatusInfoMock;
private @Mock @NonNullByDefault({}) FirmwareStatusDTO firmwareStatusMock;
private @Mock @NonNullByDefault({}) Map<String, Set<String>> linkedItemsMapMock;
private @Mock @NonNullByDefault({}) Configuration configurationMock;
private @Mock @NonNullByDefault({}) Map<String, String> propertiesMock;
@BeforeEach
public void setup() {
when(thing.getThingTypeUID()).thenReturn(new ThingTypeUID(THING_TYPE_UID));
when(thing.getUID()).thenReturn(new ThingUID(UID));
when(thing.getLabel()).thenReturn(THING_LABEL);
when(thing.getChannels()).thenReturn(mockChannels());
when(thing.getConfiguration()).thenReturn(configuration);
when(thing.getProperties()).thenReturn(properties);
when(thing.getLocation()).thenReturn(LOCATION);
when(thingMock.getThingTypeUID()).thenReturn(new ThingTypeUID(THING_TYPE_UID));
when(thingMock.getUID()).thenReturn(new ThingUID(UID));
when(thingMock.getLabel()).thenReturn(THING_LABEL);
when(thingMock.getChannels()).thenReturn(mockChannels());
when(thingMock.getConfiguration()).thenReturn(configurationMock);
when(thingMock.getProperties()).thenReturn(propertiesMock);
when(thingMock.getLocation()).thenReturn(LOCATION);
}
@Test
public void shouldMapEnrichedThingDTO() {
when(linkedItemsMap.get("1")).thenReturn(Stream.of("linkedItem1", "linkedItem2").collect(Collectors.toSet()));
when(linkedItemsMapMock.get("1"))
.thenReturn(Stream.of("linkedItem1", "linkedItem2").collect(Collectors.toSet()));
EnrichedThingDTO enrichedThingDTO = EnrichedThingDTOMapper.map(thing, thingStatusInfo, firmwareStatus,
linkedItemsMap, true);
EnrichedThingDTO enrichedThingDTO = EnrichedThingDTOMapper.map(thingMock, thingStatusInfoMock,
firmwareStatusMock, linkedItemsMapMock, true);
assertThat(enrichedThingDTO.editable, is(true));
assertThat(enrichedThingDTO.firmwareStatus, is(equalTo(firmwareStatus)));
assertThat(enrichedThingDTO.statusInfo, is(equalTo(thingStatusInfo)));
assertThat(enrichedThingDTO.thingTypeUID, is(equalTo(thing.getThingTypeUID().getAsString())));
assertThat(enrichedThingDTO.firmwareStatus, is(equalTo(firmwareStatusMock)));
assertThat(enrichedThingDTO.statusInfo, is(equalTo(thingStatusInfoMock)));
assertThat(enrichedThingDTO.thingTypeUID, is(equalTo(thingMock.getThingTypeUID().getAsString())));
assertThat(enrichedThingDTO.label, is(equalTo(THING_LABEL)));
assertThat(enrichedThingDTO.bridgeUID, is(CoreMatchers.nullValue()));
assertChannels(enrichedThingDTO);
assertThat(enrichedThingDTO.configuration.values(), is(empty()));
assertThat(enrichedThingDTO.properties, is(equalTo(properties)));
assertThat(enrichedThingDTO.properties, is(equalTo(propertiesMock)));
assertThat(enrichedThingDTO.location, is(equalTo(LOCATION)));
}
@ -96,7 +99,7 @@ public class EnrichedThingDTOMapperTest {
assertThat(enrichedThingDTO.channels, hasSize(2));
assertThat(enrichedThingDTO.channels.get(0), is(instanceOf(EnrichedChannelDTO.class)));
EnrichedChannelDTO channel1 = (EnrichedChannelDTO) enrichedThingDTO.channels.get(0);
EnrichedChannelDTO channel1 = enrichedThingDTO.channels.get(0);
assertThat(channel1.linkedItems, hasSize(2));
}

View File

@ -12,12 +12,15 @@
*/
package org.openhab.core.io.rest.log.internal;
import org.eclipse.jdt.annotation.NonNullByDefault;
/**
* The {@link LogConstants} class defines common constants, which are
* used across the whole module.
*
* @author Sebastian Janzen - Initial contribution
*/
@NonNullByDefault
public class LogConstants {
// Log and response message to express, that the log severity addressed is not handled.

View File

@ -33,6 +33,7 @@ import javax.ws.rs.core.UriInfo;
import org.eclipse.emf.common.util.BasicEList;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ -64,6 +65,7 @@ import org.openhab.core.ui.items.ItemUIRegistry;
*/
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.WARN)
@NonNullByDefault
public class SitemapResourceTest extends JavaTest {
private static final int STATE_UPDATE_WAIT_TIME = 100;
@ -83,56 +85,56 @@ public class SitemapResourceTest extends JavaTest {
private static final String WIDGET2_ID = "01";
private static final String CLIENT_IP = "127.0.0.1";
private SitemapResource sitemapResource;
private @NonNullByDefault({}) SitemapResource sitemapResource;
private @Mock HttpHeaders headers;
private @Mock Sitemap defaultSitemap;
private @Mock ItemUIRegistry itemUIRegistry;
private @Mock LocaleService localeService;
private @Mock HttpServletRequest request;
private @Mock SitemapProvider sitemapProvider;
private @Mock SitemapSubscriptionService subscriptions;
private @Mock UriInfo uriInfo;
private @NonNullByDefault({}) GenericItem item;
private @NonNullByDefault({}) GenericItem visibilityRuleItem;
private @NonNullByDefault({}) GenericItem labelColorItem;
private @NonNullByDefault({}) GenericItem valueColorItem;
private GenericItem item;
private GenericItem visibilityRuleItem;
private GenericItem labelColorItem;
private GenericItem valueColorItem;
private @Mock @NonNullByDefault({}) HttpHeaders headersMock;
private @Mock @NonNullByDefault({}) Sitemap defaultSitemapMock;
private @Mock @NonNullByDefault({}) ItemUIRegistry itemUIRegistryMock;
private @Mock @NonNullByDefault({}) LocaleService localeServiceMock;
private @Mock @NonNullByDefault({}) HttpServletRequest requestMock;
private @Mock @NonNullByDefault({}) SitemapProvider sitemapProviderMock;
private @Mock @NonNullByDefault({}) SitemapSubscriptionService subscriptionsMock;
private @Mock @NonNullByDefault({}) UriInfo uriInfoMock;
private EList<Widget> widgets;
private EList<Widget> widgets = new BasicEList<>();
@BeforeEach
public void setup() throws Exception {
sitemapResource = new SitemapResource(itemUIRegistry, localeService, subscriptions);
sitemapResource = new SitemapResource(itemUIRegistryMock, localeServiceMock, subscriptionsMock);
when(uriInfo.getAbsolutePathBuilder()).thenReturn(UriBuilder.fromPath(SITEMAP_PATH));
when(uriInfo.getBaseUriBuilder()).thenReturn(UriBuilder.fromPath(SITEMAP_PATH));
sitemapResource.uriInfo = uriInfo;
when(uriInfoMock.getAbsolutePathBuilder()).thenReturn(UriBuilder.fromPath(SITEMAP_PATH));
when(uriInfoMock.getBaseUriBuilder()).thenReturn(UriBuilder.fromPath(SITEMAP_PATH));
sitemapResource.uriInfo = uriInfoMock;
when(request.getRemoteAddr()).thenReturn(CLIENT_IP);
sitemapResource.request = request;
when(requestMock.getRemoteAddr()).thenReturn(CLIENT_IP);
sitemapResource.request = requestMock;
item = new TestItem(ITEM_NAME);
visibilityRuleItem = new TestItem(VISIBILITY_RULE_ITEM_NAME);
labelColorItem = new TestItem(LABEL_COLOR_ITEM_NAME);
valueColorItem = new TestItem(VALUE_COLOR_ITEM_NAME);
when(localeService.getLocale(null)).thenReturn(Locale.US);
when(localeServiceMock.getLocale(null)).thenReturn(Locale.US);
configureSitemapProviderMock();
configureSitemapMock();
sitemapResource.addSitemapProvider(sitemapProvider);
sitemapResource.addSitemapProvider(sitemapProviderMock);
widgets = initSitemapWidgets();
configureItemUIRegistry(PercentType.HUNDRED, OnOffType.ON);
// Disable long polling
when(headers.getRequestHeader(HTTP_HEADER_X_ATMOSPHERE_TRANSPORT)).thenReturn(null);
when(headersMock.getRequestHeader(HTTP_HEADER_X_ATMOSPHERE_TRANSPORT)).thenReturn(null);
}
@Test
public void whenNoSitemapProvidersAreSetShouldReturnEmptyList() {
sitemapResource.removeSitemapProvider(sitemapProvider);
sitemapResource.removeSitemapProvider(sitemapProviderMock);
Response sitemaps = sitemapResource.getSitemaps();
assertThat(sitemaps.getEntity(), instanceOf(Collection.class));
@ -163,9 +165,10 @@ public class SitemapResourceTest extends JavaTest {
}).start();
// non-null is sufficient here.
when(headers.getRequestHeader(HTTP_HEADER_X_ATMOSPHERE_TRANSPORT)).thenReturn(List.of());
when(headersMock.getRequestHeader(HTTP_HEADER_X_ATMOSPHERE_TRANSPORT)).thenReturn(List.of());
Response response = sitemapResource.getPageData(headers, null, SITEMAP_MODEL_NAME, SITEMAP_NAME, null, false);
Response response = sitemapResource.getPageData(headersMock, null, SITEMAP_MODEL_NAME, SITEMAP_NAME, null,
false);
PageDTO pageDTO = (PageDTO) response.getEntity();
assertThat(pageDTO.timeout, is(false)); // assert that the item state change did trigger the blocking method to
@ -184,9 +187,10 @@ public class SitemapResourceTest extends JavaTest {
}).start();
// non-null is sufficient here.
when(headers.getRequestHeader(HTTP_HEADER_X_ATMOSPHERE_TRANSPORT)).thenReturn(List.of());
when(headersMock.getRequestHeader(HTTP_HEADER_X_ATMOSPHERE_TRANSPORT)).thenReturn(List.of());
Response response = sitemapResource.getPageData(headers, null, SITEMAP_MODEL_NAME, SITEMAP_NAME, null, false);
Response response = sitemapResource.getPageData(headersMock, null, SITEMAP_MODEL_NAME, SITEMAP_NAME, null,
false);
PageDTO pageDTO = (PageDTO) response.getEntity();
assertThat(pageDTO.timeout, is(false)); // assert that the item state change did trigger the blocking method to
@ -205,9 +209,10 @@ public class SitemapResourceTest extends JavaTest {
}).start();
// non-null is sufficient here.
when(headers.getRequestHeader(HTTP_HEADER_X_ATMOSPHERE_TRANSPORT)).thenReturn(List.of());
when(headersMock.getRequestHeader(HTTP_HEADER_X_ATMOSPHERE_TRANSPORT)).thenReturn(List.of());
Response response = sitemapResource.getPageData(headers, null, SITEMAP_MODEL_NAME, SITEMAP_NAME, null, false);
Response response = sitemapResource.getPageData(headersMock, null, SITEMAP_MODEL_NAME, SITEMAP_NAME, null,
false);
PageDTO pageDTO = (PageDTO) response.getEntity();
assertThat(pageDTO.timeout, is(false)); // assert that the item state change did trigger the blocking method to
@ -226,9 +231,10 @@ public class SitemapResourceTest extends JavaTest {
}).start();
// non-null is sufficient here.
when(headers.getRequestHeader(HTTP_HEADER_X_ATMOSPHERE_TRANSPORT)).thenReturn(List.of());
when(headersMock.getRequestHeader(HTTP_HEADER_X_ATMOSPHERE_TRANSPORT)).thenReturn(List.of());
Response response = sitemapResource.getPageData(headers, null, SITEMAP_MODEL_NAME, SITEMAP_NAME, null, false);
Response response = sitemapResource.getPageData(headersMock, null, SITEMAP_MODEL_NAME, SITEMAP_NAME, null,
false);
PageDTO pageDTO = (PageDTO) response.getEntity();
assertThat(pageDTO.timeout, is(false)); // assert that the item state change did trigger the blocking method to
@ -241,9 +247,10 @@ public class SitemapResourceTest extends JavaTest {
configureItemUIRegistry(item.getState(), OnOffType.ON);
// Disable long polling
when(headers.getRequestHeader(HTTP_HEADER_X_ATMOSPHERE_TRANSPORT)).thenReturn(null);
when(headersMock.getRequestHeader(HTTP_HEADER_X_ATMOSPHERE_TRANSPORT)).thenReturn(null);
Response response = sitemapResource.getPageData(headers, null, SITEMAP_MODEL_NAME, SITEMAP_NAME, null, false);
Response response = sitemapResource.getPageData(headersMock, null, SITEMAP_MODEL_NAME, SITEMAP_NAME, null,
false);
PageDTO pageDTO = (PageDTO) response.getEntity();
assertThat(pageDTO.id, is(SITEMAP_NAME));
@ -274,27 +281,27 @@ public class SitemapResourceTest extends JavaTest {
}
private void configureItemUIRegistry(State state1, State state2) throws ItemNotFoundException {
when(itemUIRegistry.getChildren(defaultSitemap)).thenReturn(widgets);
when(itemUIRegistry.getItem(ITEM_NAME)).thenReturn(item);
when(itemUIRegistry.getItem(VISIBILITY_RULE_ITEM_NAME)).thenReturn(visibilityRuleItem);
when(itemUIRegistry.getItem(LABEL_COLOR_ITEM_NAME)).thenReturn(labelColorItem);
when(itemUIRegistry.getItem(VALUE_COLOR_ITEM_NAME)).thenReturn(valueColorItem);
when(itemUIRegistryMock.getChildren(defaultSitemapMock)).thenReturn(widgets);
when(itemUIRegistryMock.getItem(ITEM_NAME)).thenReturn(item);
when(itemUIRegistryMock.getItem(VISIBILITY_RULE_ITEM_NAME)).thenReturn(visibilityRuleItem);
when(itemUIRegistryMock.getItem(LABEL_COLOR_ITEM_NAME)).thenReturn(labelColorItem);
when(itemUIRegistryMock.getItem(VALUE_COLOR_ITEM_NAME)).thenReturn(valueColorItem);
when(itemUIRegistry.getWidgetId(widgets.get(0))).thenReturn(WIDGET1_ID);
when(itemUIRegistry.getCategory(widgets.get(0))).thenReturn("");
when(itemUIRegistry.getLabel(widgets.get(0))).thenReturn(WIDGET1_LABEL);
when(itemUIRegistry.getVisiblity(widgets.get(0))).thenReturn(true);
when(itemUIRegistry.getLabelColor(widgets.get(0))).thenReturn("GREEN");
when(itemUIRegistry.getValueColor(widgets.get(0))).thenReturn("BLUE");
when(itemUIRegistry.getState(widgets.get(0))).thenReturn(state1);
when(itemUIRegistryMock.getWidgetId(widgets.get(0))).thenReturn(WIDGET1_ID);
when(itemUIRegistryMock.getCategory(widgets.get(0))).thenReturn("");
when(itemUIRegistryMock.getLabel(widgets.get(0))).thenReturn(WIDGET1_LABEL);
when(itemUIRegistryMock.getVisiblity(widgets.get(0))).thenReturn(true);
when(itemUIRegistryMock.getLabelColor(widgets.get(0))).thenReturn("GREEN");
when(itemUIRegistryMock.getValueColor(widgets.get(0))).thenReturn("BLUE");
when(itemUIRegistryMock.getState(widgets.get(0))).thenReturn(state1);
when(itemUIRegistry.getWidgetId(widgets.get(1))).thenReturn(WIDGET2_ID);
when(itemUIRegistry.getCategory(widgets.get(1))).thenReturn("");
when(itemUIRegistry.getLabel(widgets.get(1))).thenReturn(WIDGET2_LABEL);
when(itemUIRegistry.getVisiblity(widgets.get(1))).thenReturn(true);
when(itemUIRegistry.getLabelColor(widgets.get(1))).thenReturn(null);
when(itemUIRegistry.getValueColor(widgets.get(1))).thenReturn(null);
when(itemUIRegistry.getState(widgets.get(1))).thenReturn(state2);
when(itemUIRegistryMock.getWidgetId(widgets.get(1))).thenReturn(WIDGET2_ID);
when(itemUIRegistryMock.getCategory(widgets.get(1))).thenReturn("");
when(itemUIRegistryMock.getLabel(widgets.get(1))).thenReturn(WIDGET2_LABEL);
when(itemUIRegistryMock.getVisiblity(widgets.get(1))).thenReturn(true);
when(itemUIRegistryMock.getLabelColor(widgets.get(1))).thenReturn(null);
when(itemUIRegistryMock.getValueColor(widgets.get(1))).thenReturn(null);
when(itemUIRegistryMock.getState(widgets.get(1))).thenReturn(state2);
}
private EList<Widget> initSitemapWidgets() {
@ -352,14 +359,14 @@ public class SitemapResourceTest extends JavaTest {
}
private void configureSitemapMock() {
when(defaultSitemap.getName()).thenReturn(SITEMAP_NAME);
when(defaultSitemap.getLabel()).thenReturn(SITEMAP_TITLE);
when(defaultSitemap.getIcon()).thenReturn("");
when(defaultSitemapMock.getName()).thenReturn(SITEMAP_NAME);
when(defaultSitemapMock.getLabel()).thenReturn(SITEMAP_TITLE);
when(defaultSitemapMock.getIcon()).thenReturn("");
}
private void configureSitemapProviderMock() {
when(sitemapProvider.getSitemapNames()).thenReturn(Set.of(SITEMAP_MODEL_NAME));
when(sitemapProvider.getSitemap(SITEMAP_MODEL_NAME)).thenReturn(defaultSitemap);
when(sitemapProviderMock.getSitemapNames()).thenReturn(Set.of(SITEMAP_MODEL_NAME));
when(sitemapProviderMock.getSitemap(SITEMAP_MODEL_NAME)).thenReturn(defaultSitemapMock);
}
private class TestItem extends GenericItem {

View File

@ -17,12 +17,14 @@ import static org.hamcrest.MatcherAssert.assertThat;
import java.util.List;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
/**
* @author Dennis Nobel - Initial contribution
* @author Wouter Born - Migrate tests from Groovy to Java
*/
@NonNullByDefault
public class SseUtilTest {
@Test

View File

@ -12,11 +12,14 @@
*/
package org.openhab.core.io.rest;
import org.eclipse.jdt.annotation.NonNullByDefault;
/**
* Public constants for the REST API
*
* @author Kai Kreuzer - Initial contribution
*/
@NonNullByDefault
public class RESTConstants {
@Deprecated

View File

@ -19,6 +19,7 @@ import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.stream.Stream;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.core.library.types.DateTimeType;
import com.google.gson.Gson;
@ -32,6 +33,7 @@ import com.google.gson.GsonBuilder;
*
* @author Henning Treu - Initial contribution
*/
@NonNullByDefault
public class Stream2JSONInputStream extends InputStream implements JSONInputStream {
private final Iterator<String> iterator;
@ -46,13 +48,8 @@ public class Stream2JSONInputStream extends InputStream implements JSONInputStre
* Creates a new {@link Stream2JSONInputStream} backed by the given {@link Stream} source.
*
* @param source the {@link Stream} backing this input stream. Must not be null.
* @throws IllegalArgumentException in case the source is null.
*/
public Stream2JSONInputStream(Stream<?> source) {
if (source == null) {
throw new IllegalArgumentException("The source must not be null!");
}
iterator = source.map(e -> gson.toJson(e)).iterator();
jsonElementStream = new ByteArrayInputStream(new byte[0]);
firstIteratorElement = true;

View File

@ -28,6 +28,7 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
import com.google.gson.JsonObject;
@ -37,6 +38,7 @@ import com.google.gson.JsonObject;
*
* @author Henning Treu - Initial contribution
*/
@NonNullByDefault
public class JSONResponseTest {
private static final String ENTITY_VALUE = "entityValue";

View File

@ -14,7 +14,6 @@ package org.openhab.core.io.rest;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.io.IOException;
import java.io.InputStream;
@ -23,6 +22,7 @@ import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
import com.google.gson.Gson;
@ -33,21 +33,15 @@ import com.google.gson.GsonBuilder;
*
* @author Henning Treu - Initial contribution
*/
@NonNullByDefault
public class Stream2JSONInputStreamTest {
private Stream2JSONInputStream collection2InputStream;
private static final Gson GSON = new GsonBuilder().create();
@Test
public void shouldFailForNullSource() throws IOException {
assertThrows(IllegalArgumentException.class, () -> new Stream2JSONInputStream(null).close());
}
@Test
public void shouldReturnForEmptyStream() throws Exception {
List<Object> emptyList = Collections.emptyList();
collection2InputStream = new Stream2JSONInputStream(emptyList.stream());
Stream2JSONInputStream collection2InputStream = new Stream2JSONInputStream(emptyList.stream());
assertThat(inputStreamToString(collection2InputStream), is(GSON.toJson(emptyList)));
}
@ -56,7 +50,7 @@ public class Stream2JSONInputStreamTest {
public void shouldStreamSingleObjectToJSON() throws Exception {
DummyObject dummyObject = new DummyObject("demoKey", "demoValue");
List<DummyObject> dummyList = List.of(dummyObject);
collection2InputStream = new Stream2JSONInputStream(Stream.of(dummyObject));
Stream2JSONInputStream collection2InputStream = new Stream2JSONInputStream(Stream.of(dummyObject));
assertThat(inputStreamToString(collection2InputStream), is(GSON.toJson(dummyList)));
}
@ -66,7 +60,7 @@ public class Stream2JSONInputStreamTest {
DummyObject dummyObject1 = new DummyObject("demoKey1", "demoValue1");
DummyObject dummyObject2 = new DummyObject("demoKey2", "demoValue2");
List<DummyObject> dummyCollection = List.of(dummyObject1, dummyObject2);
collection2InputStream = new Stream2JSONInputStream(dummyCollection.stream());
Stream2JSONInputStream collection2InputStream = new Stream2JSONInputStream(dummyCollection.stream());
assertThat(inputStreamToString(collection2InputStream), is(GSON.toJson(dummyCollection)));
}

View File

@ -28,6 +28,8 @@ import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ -44,6 +46,7 @@ import org.mockito.quality.Strictness;
*/
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.WARN)
@NonNullByDefault
public class CorsFilterTest {
private static final String CONTENT_TYPE_HEADER = HttpHeaders.CONTENT_TYPE;
@ -55,11 +58,11 @@ public class CorsFilterTest {
private static final String VARY_HEADER_VALUE = "Content-Type";
private static final String REQUEST_HEADERS = "X-Custom, X-Mine";
private CorsFilter filter;
private @NonNullByDefault({}) CorsFilter filter;
private MultivaluedMap<String, String> responseHeaders = new MultivaluedHashMap<>();
private @Mock ContainerRequestContext requestContext;
private @Mock ContainerResponseContext responseContext;
private @Mock @NonNullByDefault({}) ContainerRequestContext requestContextMock;
private @Mock @NonNullByDefault({}) ContainerResponseContext responseContextMock;
@BeforeEach
public void setUp() {
@ -72,7 +75,7 @@ public class CorsFilterTest {
setupRequestContext(HTTP_OPTIONS_METHOD, null, null, null);
setupResponseContext(null);
filter.filter(requestContext, responseContext);
filter.filter(requestContextMock, responseContextMock);
// Not a CORS request, thus no CORS headers should be added.
assertResponseWithoutHeader(ACCESS_CONTROL_ALLOW_METHODS_HEADER);
@ -86,7 +89,7 @@ public class CorsFilterTest {
setupRequestContext(HTTP_GET_METHOD, null, null, null);
setupResponseContext(null);
filter.filter(requestContext, responseContext);
filter.filter(requestContextMock, responseContextMock);
// Not a CORS request, thus no CORS headers should be added.
assertResponseWithoutHeader(ACCESS_CONTROL_ALLOW_METHODS_HEADER);
@ -100,7 +103,7 @@ public class CorsFilterTest {
setupRequestContext(HTTP_OPTIONS_METHOD, ECLIPSE_ORIGIN, HTTP_GET_METHOD, REQUEST_HEADERS);
setupResponseContext(VARY_HEADER_VALUE);
filter.filter(requestContext, responseContext);
filter.filter(requestContextMock, responseContextMock);
assertResponseHasHeader(ACCESS_CONTROL_ALLOW_METHODS_HEADER, ACCEPTED_HTTP_METHODS);
assertResponseHasHeader(ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, ECLIPSE_ORIGIN);
@ -114,7 +117,7 @@ public class CorsFilterTest {
setupRequestContext(HTTP_OPTIONS_METHOD, ECLIPSE_ORIGIN, null, REQUEST_HEADERS);
setupResponseContext(VARY_HEADER_VALUE);
filter.filter(requestContext, responseContext);
filter.filter(requestContextMock, responseContextMock);
// Since the requestMethod header is not present in the request, it is not a valid Preflight CORS request.
// Thus, no CORS header should be added to the response.
@ -129,7 +132,7 @@ public class CorsFilterTest {
setupRequestContext(HTTP_OPTIONS_METHOD, ECLIPSE_ORIGIN, HTTP_GET_METHOD, null);
setupResponseContext(VARY_HEADER_VALUE);
filter.filter(requestContext, responseContext);
filter.filter(requestContextMock, responseContextMock);
// Since the requestMethod header is not present in the request, it is not a valid Preflight CORS request.
// Thus, no CORS header should be added to the response.
@ -144,7 +147,7 @@ public class CorsFilterTest {
setupRequestContext(HTTP_GET_METHOD, ECLIPSE_ORIGIN, null, null);
setupResponseContext(null);
filter.filter(requestContext, responseContext);
filter.filter(requestContextMock, responseContextMock);
// Not a CORS request, thus no CORS headers should be added.
assertResponseWithoutHeader(ACCESS_CONTROL_ALLOW_METHODS_HEADER);
@ -162,8 +165,8 @@ public class CorsFilterTest {
assertTrue(responseHeaders.get(header).contains(value));
}
private void setupRequestContext(String methodValue, String originValue, final String requestMethodValue,
String requestHeadersValue) {
private void setupRequestContext(String methodValue, @Nullable String originValue,
@Nullable String requestMethodValue, @Nullable String requestHeadersValue) {
MultivaluedMap<String, String> headers = new MultivaluedHashMap<>();
if (originValue != null) {
headers.put(ORIGIN_HEADER, List.of(originValue));
@ -175,17 +178,18 @@ public class CorsFilterTest {
headers.put(ACCESS_CONTROL_REQUEST_HEADERS, List.of(requestHeadersValue));
}
when(requestContext.getHeaders()).thenReturn(headers);
when(requestContext.getMethod()).thenReturn(methodValue);
when(requestContextMock.getHeaders()).thenReturn(headers);
when(requestContextMock.getMethod()).thenReturn(methodValue);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private void setupResponseContext(String varyHeaderValue) {
if (varyHeaderValue != null) {
responseHeaders.put(VARY_HEADER, Stream.of(varyHeaderValue).collect(toList()));
private void setupResponseContext(@Nullable String varyHeaderValue) {
String localVaryHeaderValue = varyHeaderValue;
if (localVaryHeaderValue != null) {
responseHeaders.put(VARY_HEADER, Stream.of(localVaryHeaderValue).collect(toList()));
}
when(responseContext.getHeaders()).thenReturn((MultivaluedHashMap) responseHeaders);
when(responseContext.getStringHeaders()).thenReturn(responseHeaders);
when(responseContextMock.getHeaders()).thenReturn((MultivaluedHashMap) responseHeaders);
when(responseContextMock.getStringHeaders()).thenReturn(responseHeaders);
}
}

View File

@ -26,6 +26,8 @@ import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ -42,16 +44,17 @@ import org.mockito.quality.Strictness;
*/
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.WARN)
@NonNullByDefault
public class ProxyFilterTest {
private final ProxyFilter filter = new ProxyFilter();
private @Mock ContainerRequestContext context;
private @Mock UriInfo uriInfo;
private @Mock @NonNullByDefault({}) ContainerRequestContext contextMock;
private @Mock @NonNullByDefault({}) UriInfo uriInfoMock;
@BeforeEach
public void before() {
when(context.getUriInfo()).thenReturn(uriInfo);
when(contextMock.getUriInfo()).thenReturn(uriInfoMock);
}
@Test
@ -62,11 +65,11 @@ public class ProxyFilterTest {
setupContextHeaders("https", "eclipse.org");
filter.filter(context);
filter.filter(contextMock);
URI newBaseURI = new URI("https://eclipse.org/rest");
URI newRequestURI = new URI("https://eclipse.org/rest/test");
verify(context).setRequestUri(eq(newBaseURI), eq(newRequestURI));
verify(contextMock).setRequestUri(eq(newBaseURI), eq(newRequestURI));
}
@Test
@ -77,11 +80,11 @@ public class ProxyFilterTest {
setupContextHeaders("http", "eclipse.org:8081");
filter.filter(context);
filter.filter(contextMock);
URI newBaseURI = new URI("http://eclipse.org:8081/rest");
URI newRequestURI = new URI("http://eclipse.org:8081/rest/test");
verify(context).setRequestUri(eq(newBaseURI), eq(newRequestURI));
verify(contextMock).setRequestUri(eq(newBaseURI), eq(newRequestURI));
}
@Test
@ -92,9 +95,9 @@ public class ProxyFilterTest {
setupContextHeaders(null, null);
filter.filter(context);
filter.filter(contextMock);
verify(context, never()).setRequestUri(any(URI.class), any(URI.class));
verify(contextMock, never()).setRequestUri(any(URI.class), any(URI.class));
}
@Test
@ -105,11 +108,11 @@ public class ProxyFilterTest {
setupContextHeaders("https", null);
filter.filter(context);
filter.filter(contextMock);
URI newBaseURI = new URI("https://localhost:8080/rest");
URI newRequestURI = new URI("https://localhost:8080/rest/test");
verify(context).setRequestUri(eq(newBaseURI), eq(newRequestURI));
verify(contextMock).setRequestUri(eq(newBaseURI), eq(newRequestURI));
}
@Test
@ -120,11 +123,11 @@ public class ProxyFilterTest {
setupContextHeaders("https", null);
filter.filter(context);
filter.filter(contextMock);
URI newBaseURI = new URI("https://localhost/rest");
URI newRequestURI = new URI("https://localhost/rest/test");
verify(context).setRequestUri(eq(newBaseURI), eq(newRequestURI));
verify(contextMock).setRequestUri(eq(newBaseURI), eq(newRequestURI));
}
@Test
@ -135,11 +138,11 @@ public class ProxyFilterTest {
setupContextHeaders(null, "eclipse.org:8081");
filter.filter(context);
filter.filter(contextMock);
URI newBaseURI = new URI("http://eclipse.org:8081/rest");
URI newRequestURI = new URI("http://eclipse.org:8081/rest/test");
verify(context).setRequestUri(eq(newBaseURI), eq(newRequestURI));
verify(contextMock).setRequestUri(eq(newBaseURI), eq(newRequestURI));
}
@Test
@ -150,23 +153,23 @@ public class ProxyFilterTest {
setupContextHeaders("https", "://sometext\\\\///");
filter.filter(context);
filter.filter(contextMock);
verify(context, never()).setRequestUri(any(URI.class), any(URI.class));
verify(contextMock, never()).setRequestUri(any(URI.class), any(URI.class));
}
private void setupContextURIs(String baseURI, String requestURI) {
try {
when(uriInfo.getBaseUri()).thenReturn(new URI(baseURI));
when(uriInfo.getBaseUriBuilder()).thenReturn(UriBuilder.fromUri(baseURI));
when(uriInfo.getRequestUri()).thenReturn(new URI(requestURI));
when(uriInfo.getRequestUriBuilder()).thenReturn(UriBuilder.fromUri(requestURI));
when(uriInfoMock.getBaseUri()).thenReturn(new URI(baseURI));
when(uriInfoMock.getBaseUriBuilder()).thenReturn(UriBuilder.fromUri(baseURI));
when(uriInfoMock.getRequestUri()).thenReturn(new URI(requestURI));
when(uriInfoMock.getRequestUriBuilder()).thenReturn(UriBuilder.fromUri(requestURI));
} catch (URISyntaxException e) {
throw new IllegalStateException("Error while setting up context mock", e);
}
}
private void setupContextHeaders(String protoHeader, String hostHeader) {
private void setupContextHeaders(@Nullable String protoHeader, @Nullable String hostHeader) {
MultivaluedMap<String, String> headers = new MultivaluedHashMap<>();
if (protoHeader != null) {
headers.put(PROTO_PROXY_HEADER, List.of(protoHeader));
@ -174,6 +177,6 @@ public class ProxyFilterTest {
if (hostHeader != null) {
headers.put(HOST_PROXY_HEADER, List.of(hostHeader));
}
when(context.getHeaders()).thenReturn(headers);
when(contextMock.getHeaders()).thenReturn(headers);
}
}

View File

@ -12,11 +12,14 @@
*/
package org.openhab.core.io.transport.modbus;
import org.eclipse.jdt.annotation.NonNullByDefault;
/**
* Modbus read function codes supported by this transport
*
* @author Sami Salonen - Initial contribution
*/
@NonNullByDefault
public enum ModbusReadFunctionCode {
READ_COILS,
READ_INPUT_DISCRETES,

View File

@ -14,7 +14,7 @@ package org.openhab.core.io.transport.modbus;
import java.util.stream.Stream;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.NonNullByDefault;
import net.wimpi.modbus.Modbus;
@ -23,6 +23,7 @@ import net.wimpi.modbus.Modbus;
*
* @author Sami Salonen - Initial contribution
*/
@NonNullByDefault
public enum ModbusWriteFunctionCode {
WRITE_COIL(Modbus.WRITE_COIL),
WRITE_MULTIPLE_COILS(Modbus.WRITE_MULTIPLE_COILS),
@ -51,8 +52,7 @@ public enum ModbusWriteFunctionCode {
* @return {@link ModbusWriteFunctionCode} matching the numeric function code
* @throws IllegalArgumentException with unsupported functions
*/
@SuppressWarnings("null")
public static @NonNull ModbusWriteFunctionCode fromFunctionCode(int functionCode) throws IllegalArgumentException {
public static ModbusWriteFunctionCode fromFunctionCode(int functionCode) throws IllegalArgumentException {
return Stream.of(ModbusWriteFunctionCode.values()).filter(v -> v.getFunctionCode() == functionCode).findFirst()
.orElseThrow(() -> new IllegalArgumentException("Invalid functionCode"));
}

View File

@ -23,7 +23,6 @@ import org.eclipse.jdt.annotation.Nullable;
*/
@NonNullByDefault
public interface ModbusSlaveEndpointVisitor<R> {
@Nullable
R visit(ModbusTCPSlaveEndpoint endpoint);

View File

@ -12,6 +12,7 @@
*/
package org.openhab.core.io.transport.modbus.test;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;
import org.openhab.core.io.transport.modbus.ModbusWriteFunctionCode;
@ -20,6 +21,7 @@ import org.openhab.core.io.transport.modbus.ModbusWriteRequestBlueprint;
/**
* @author Sami Salonen - Initial contribution
*/
@NonNullByDefault
abstract class AbstractRequestComparer<T extends ModbusWriteRequestBlueprint> extends TypeSafeMatcher<T> {
private int expectedUnitId;
@ -36,7 +38,7 @@ abstract class AbstractRequestComparer<T extends ModbusWriteRequestBlueprint> ex
}
@Override
public void describeTo(Description description) {
public void describeTo(@NonNullByDefault({}) Description description) {
description.appendText("should return request with");
description.appendText(" unitID=");
description.appendValue(expectedUnitId);

View File

@ -16,12 +16,14 @@ import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
import org.openhab.core.io.transport.modbus.BitArray;
/**
* @author Sami Salonen - Initial contribution
*/
@NonNullByDefault
public class BasicBitArrayTest {
@Test

View File

@ -14,6 +14,7 @@ package org.openhab.core.io.transport.modbus.test;
import static org.junit.jupiter.api.Assertions.*;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
import org.openhab.core.io.transport.modbus.ModbusBitUtilities;
@ -23,6 +24,7 @@ import org.openhab.core.io.transport.modbus.ModbusBitUtilities;
*
* @author Sami Salonen - Initial contribution
*/
@NonNullByDefault
public class BitUtilitiesExtractBitTest {
@Test

View File

@ -16,6 +16,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import java.nio.ByteBuffer;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
import org.openhab.core.io.transport.modbus.ModbusBitUtilities;
@ -27,6 +28,7 @@ import org.openhab.core.io.transport.modbus.ModbusBitUtilities;
*
* @author Sami Salonen - Initial contribution
*/
@NonNullByDefault
public class BitUtilitiesExtractFloat32Test {
/**

View File

@ -23,6 +23,7 @@ import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.Stream.Builder;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
@ -34,6 +35,7 @@ import org.openhab.core.library.types.DecimalType;
/**
* @author Sami Salonen - Initial contribution
*/
@NonNullByDefault
public class BitUtilitiesExtractIndividualMethodsTest {
public static Collection<Object[]> data() {

View File

@ -14,6 +14,7 @@ package org.openhab.core.io.transport.modbus.test;
import static org.junit.jupiter.api.Assertions.*;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
import org.openhab.core.io.transport.modbus.ModbusBitUtilities;
@ -23,6 +24,7 @@ import org.openhab.core.io.transport.modbus.ModbusBitUtilities;
*
* @author Sami Salonen - Initial contribution
*/
@NonNullByDefault
public class BitUtilitiesExtractInt8Test {
@Test

View File

@ -22,7 +22,7 @@ import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.openhab.core.io.transport.modbus.ModbusBitUtilities;
@ -33,6 +33,7 @@ import org.openhab.core.library.types.DecimalType;
/**
* @author Sami Salonen - Initial contribution
*/
@NonNullByDefault
public class BitUtilitiesExtractStateFromRegistersTest {
private static ModbusRegisterArray shortArrayToRegisterArray(int... arr) {
@ -364,12 +365,11 @@ public class BitUtilitiesExtractStateFromRegistersTest {
return;
}
Optional<@NonNull DecimalType> actualState = ModbusBitUtilities.extractStateFromRegisters(registers, index,
type);
Optional<DecimalType> actualState = ModbusBitUtilities.extractStateFromRegisters(registers, index, type);
// Wrap given expectedResult to Optional, if necessary
Optional<@NonNull DecimalType> expectedStateWrapped = expectedResult instanceof DecimalType
Optional<DecimalType> expectedStateWrapped = expectedResult instanceof DecimalType
? Optional.of((DecimalType) expectedResult)
: (Optional<@NonNull DecimalType>) expectedResult;
: (Optional<DecimalType>) expectedResult;
assertThat(String.format("registers=%s, index=%d, type=%s", registers, index, type), actualState,
is(equalTo(expectedStateWrapped)));
}

View File

@ -22,6 +22,7 @@ import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.Stream.Builder;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.openhab.core.io.transport.modbus.ModbusBitUtilities;
@ -30,6 +31,7 @@ import org.openhab.core.io.transport.modbus.ModbusRegisterArray;
/**
* @author Sami Salonen - Initial contribution
*/
@NonNullByDefault
public class BitUtilitiesExtractStringTest {
private static ModbusRegisterArray shortArrayToRegisterArray(int... arr) {

View File

@ -17,6 +17,7 @@ import static org.hamcrest.MatcherAssert.assertThat;
import java.util.Optional;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
import org.openhab.core.io.transport.modbus.ModbusBitUtilities;
import org.openhab.core.library.types.DecimalType;
@ -27,6 +28,7 @@ import org.openhab.core.library.types.OpenClosedType;
/**
* @author Sami Salonen - Initial contribution
*/
@NonNullByDefault
public class BitUtilitiesTranslateCommand2BooleanTest {
@Test

View File

@ -16,6 +16,7 @@ import java.util.Arrays;
import java.util.Objects;
import java.util.stream.StreamSupport;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.hamcrest.Description;
import org.openhab.core.io.transport.modbus.ModbusWriteCoilRequestBlueprint;
import org.openhab.core.io.transport.modbus.ModbusWriteFunctionCode;
@ -23,6 +24,7 @@ import org.openhab.core.io.transport.modbus.ModbusWriteFunctionCode;
/**
* @author Sami Salonen - Initial contribution
*/
@NonNullByDefault
class CoilMatcher extends AbstractRequestComparer<ModbusWriteCoilRequestBlueprint> {
private Boolean[] expectedCoils;
@ -34,7 +36,7 @@ class CoilMatcher extends AbstractRequestComparer<ModbusWriteCoilRequestBlueprin
}
@Override
public void describeTo(Description description) {
public void describeTo(@NonNullByDefault({}) Description description) {
super.describeTo(description);
description.appendText(" coils=");
description.appendValue(Arrays.toString(expectedCoils));

View File

@ -27,6 +27,7 @@ import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.function.LongSupplier;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
@ -68,6 +69,7 @@ import net.wimpi.modbus.util.SerialParameters;
*/
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.WARN)
@NonNullByDefault
public class IntegrationTestSupport extends JavaTest {
private final Logger logger = LoggerFactory.getLogger(IntegrationTestSupport.class);
@ -125,18 +127,18 @@ public class IntegrationTestSupport extends JavaTest {
protected @Spy UDPSlaveTerminalFactory udpTerminalFactory = new UDPSlaveTerminalFactoryImpl();
protected @Spy SerialConnectionFactory serialConnectionFactory = new SerialConnectionFactoryImpl();
protected ResultCaptor<ModbusRequest> modbustRequestCaptor;
protected @NonNullByDefault({}) ResultCaptor<ModbusRequest> modbustRequestCaptor;
protected ModbusTCPListener tcpListener;
protected ModbusUDPListener udpListener;
protected ModbusSerialListener serialListener;
protected SimpleProcessImage spi;
protected @NonNullByDefault({}) ModbusTCPListener tcpListener;
protected @NonNullByDefault({}) ModbusUDPListener udpListener;
protected @NonNullByDefault({}) ModbusSerialListener serialListener;
protected @NonNullByDefault({}) SimpleProcessImage spi;
protected int tcpModbusPort = -1;
protected int udpModbusPort = -1;
protected ServerType serverType = ServerType.TCP;
protected long artificialServerWait = 0;
protected NonOSGIModbusManager modbusManager;
protected @NonNullByDefault({}) NonOSGIModbusManager modbusManager;
private Thread serialServerThread = new Thread("ModbusTransportTestsSerialServer") {
@Override
@ -282,7 +284,7 @@ public class IntegrationTestSupport extends JavaTest {
public class SpyingModbusTCPTransportFactory extends ModbusTCPTransportFactory {
@Override
public ModbusTransport create(Socket socket) {
public ModbusTransport create(@NonNullByDefault({}) Socket socket) {
ModbusTransport transport = spy(super.create(socket));
// Capture requests produced by our server transport
try {
@ -297,7 +299,7 @@ public class IntegrationTestSupport extends JavaTest {
public class SpyingModbusUDPTransportFactory extends ModbusUDPTransportFactoryImpl {
@Override
public ModbusTransport create(UDPTerminal terminal) {
public ModbusTransport create(@NonNullByDefault({}) UDPTerminal terminal) {
ModbusTransport transport = spy(super.create(terminal));
// Capture requests produced by our server transport
try {
@ -312,7 +314,7 @@ public class IntegrationTestSupport extends JavaTest {
public class TCPSlaveConnectionFactoryImpl implements TCPSlaveConnectionFactory {
@Override
public TCPSlaveConnection create(Socket socket) {
public TCPSlaveConnection create(@NonNullByDefault({}) Socket socket) {
return new TCPSlaveConnection(socket, new SpyingModbusTCPTransportFactory());
}
}
@ -320,7 +322,7 @@ public class IntegrationTestSupport extends JavaTest {
public class UDPSlaveTerminalFactoryImpl implements UDPSlaveTerminalFactory {
@Override
public UDPSlaveTerminal create(InetAddress interfac, int port) {
public UDPSlaveTerminal create(@NonNullByDefault({}) InetAddress interfac, int port) {
UDPSlaveTerminal terminal = new UDPSlaveTerminal(interfac, new SpyingModbusUDPTransportFactory(), 1);
terminal.setLocalPort(port);
return terminal;
@ -329,7 +331,7 @@ public class IntegrationTestSupport extends JavaTest {
public class SerialConnectionFactoryImpl implements SerialConnectionFactory {
@Override
public SerialConnection create(SerialParameters parameters) {
public SerialConnection create(@NonNullByDefault({}) SerialParameters parameters) {
SerialConnection serialConnection = new SerialConnection(parameters) {
@Override
public ModbusTransport getModbusTransport() {

View File

@ -14,6 +14,7 @@ package org.openhab.core.io.transport.modbus.test;
import static org.junit.jupiter.api.Assertions.*;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
import org.openhab.core.io.transport.modbus.endpoint.ModbusSerialSlaveEndpoint;
import org.openhab.core.io.transport.modbus.endpoint.ModbusTCPSlaveEndpoint;
@ -25,6 +26,7 @@ import net.wimpi.modbus.Modbus;
/**
* @author Sami Salonen - Initial contribution
*/
@NonNullByDefault
public class ModbusSlaveEndpointTestCase {
@Test

View File

@ -14,6 +14,7 @@ package org.openhab.core.io.transport.modbus.test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
import org.openhab.core.io.transport.modbus.internal.ModbusSlaveErrorResponseExceptionImpl;
@ -22,6 +23,7 @@ import net.wimpi.modbus.ModbusSlaveException;
/**
* @author Sami Salonen - Initial contribution
*/
@NonNullByDefault
public class ModbusSlaveErrorResponseExceptionImplTest {
@Test

View File

@ -17,6 +17,7 @@ import java.util.Objects;
import java.util.stream.IntStream;
import java.util.stream.StreamSupport;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.hamcrest.Description;
import org.openhab.core.io.transport.modbus.ModbusRegisterArray;
import org.openhab.core.io.transport.modbus.ModbusWriteFunctionCode;
@ -25,6 +26,7 @@ import org.openhab.core.io.transport.modbus.ModbusWriteRegisterRequestBlueprint;
/**
* @author Sami Salonen - Initial contribution
*/
@NonNullByDefault
class RegisterMatcher extends AbstractRequestComparer<ModbusWriteRegisterRequestBlueprint> {
private Integer[] expectedRegisterValues;
@ -36,7 +38,7 @@ class RegisterMatcher extends AbstractRequestComparer<ModbusWriteRegisterRequest
}
@Override
public void describeTo(Description description) {
public void describeTo(@NonNullByDefault({}) Description description) {
super.describeTo(description);
description.appendText(" registers=");
description.appendValue(Arrays.toString(expectedRegisterValues));

View File

@ -13,8 +13,11 @@
package org.openhab.core.io.transport.modbus.test;
import java.util.ArrayList;
import java.util.List;
import java.util.function.LongSupplier;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
@ -23,22 +26,23 @@ import org.mockito.stubbing.Answer;
*
* @param <T>
*/
@NonNullByDefault
public class ResultCaptor<T> implements Answer<T> {
private ArrayList<T> results = new ArrayList<>();
private List<T> results = new ArrayList<>();
private LongSupplier longSupplier;
public ResultCaptor(LongSupplier longSupplier) {
this.longSupplier = longSupplier;
}
public ArrayList<T> getAllReturnValues() {
public List<T> getAllReturnValues() {
return results;
}
@SuppressWarnings("unchecked")
@Override
public T answer(InvocationOnMock invocationOnMock) throws Throwable {
public @Nullable T answer(InvocationOnMock invocationOnMock) throws Throwable {
T result = (T) invocationOnMock.callRealMethod();
synchronized (this.results) {
results.add(result);

View File

@ -29,6 +29,7 @@ import java.net.SocketOption;
import java.net.StandardSocketOptions;
import java.net.UnknownHostException;
import java.util.BitSet;
import java.util.Objects;
import java.util.Optional;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
@ -37,7 +38,7 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openhab.core.io.transport.modbus.BitArray;
@ -67,6 +68,7 @@ import net.wimpi.modbus.util.BitVector;
/**
* @author Sami Salonen - Initial contribution
*/
@NonNullByDefault
public class SmokeTest extends IntegrationTestSupport {
private static final int COIL_EVERY_N_TRUE = 2;
@ -257,7 +259,7 @@ public class SmokeTest extends IntegrationTestSupport {
try (ModbusCommunicationInterface comms = modbusManager.newModbusCommunicationInterface(endpoint, null)) {
comms.submitOneTimePoll(new ModbusReadRequestBlueprint(SLAVE_UNIT_ID, functionCode, offset, count, 1),
result -> {
Optional<@NonNull BitArray> bitsOptional = result.getBits();
Optional<BitArray> bitsOptional = result.getBits();
if (bitsOptional.isPresent()) {
lastData.set(bitsOptional.get());
} else {
@ -356,7 +358,7 @@ public class SmokeTest extends IntegrationTestSupport {
try (ModbusCommunicationInterface comms = modbusManager.newModbusCommunicationInterface(endpoint, null)) {
comms.submitOneTimePoll(new ModbusReadRequestBlueprint(SLAVE_UNIT_ID,
ModbusReadFunctionCode.READ_MULTIPLE_REGISTERS, 1, 15, 1), result -> {
Optional<@NonNull ModbusRegisterArray> registersOptional = result.getRegisters();
Optional<ModbusRegisterArray> registersOptional = result.getRegisters();
if (registersOptional.isPresent()) {
lastData.set(registersOptional.get());
} else {
@ -391,7 +393,7 @@ public class SmokeTest extends IntegrationTestSupport {
try (ModbusCommunicationInterface comms = modbusManager.newModbusCommunicationInterface(endpoint, null)) {
comms.submitOneTimePoll(new ModbusReadRequestBlueprint(SLAVE_UNIT_ID,
ModbusReadFunctionCode.READ_INPUT_REGISTERS, 1, 15, 1), result -> {
Optional<@NonNull ModbusRegisterArray> registersOptional = result.getRegisters();
Optional<ModbusRegisterArray> registersOptional = result.getRegisters();
if (registersOptional.isPresent()) {
lastData.set(registersOptional.get());
} else {
@ -585,7 +587,7 @@ public class SmokeTest extends IntegrationTestSupport {
comms.registerRegularPoll(
new ModbusReadRequestBlueprint(SLAVE_UNIT_ID, ModbusReadFunctionCode.READ_COILS, 1, 15, 1), 150, 0,
result -> {
Optional<@NonNull BitArray> bitsOptional = result.getBits();
Optional<BitArray> bitsOptional = result.getBits();
if (bitsOptional.isPresent()) {
BitArray bits = bitsOptional.get();
dataReceived.incrementAndGet();
@ -630,7 +632,7 @@ public class SmokeTest extends IntegrationTestSupport {
try (ModbusCommunicationInterface comms = modbusManager.newModbusCommunicationInterface(endpoint, null)) {
comms.registerRegularPoll(new ModbusReadRequestBlueprint(SLAVE_UNIT_ID,
ModbusReadFunctionCode.READ_MULTIPLE_REGISTERS, 1, 15, 1), 150, 0, result -> {
Optional<@NonNull ModbusRegisterArray> registersOptional = result.getRegisters();
Optional<ModbusRegisterArray> registersOptional = result.getRegisters();
if (registersOptional.isPresent()) {
ModbusRegisterArray registers = registersOptional.get();
dataReceived.incrementAndGet();
@ -667,7 +669,7 @@ public class SmokeTest extends IntegrationTestSupport {
try (ModbusCommunicationInterface comms = modbusManager.newModbusCommunicationInterface(endpoint, null)) {
comms.registerRegularPoll(new ModbusReadRequestBlueprint(SLAVE_UNIT_ID,
ModbusReadFunctionCode.READ_MULTIPLE_REGISTERS, 1, 15, 1), 150, 0, result -> {
Optional<@NonNull ModbusRegisterArray> registersOptional = result.getRegisters();
Optional<ModbusRegisterArray> registersOptional = result.getRegisters();
if (registersOptional.isPresent()) {
ModbusRegisterArray registers = registersOptional.get();
dataReceived.incrementAndGet();
@ -730,7 +732,7 @@ public class SmokeTest extends IntegrationTestSupport {
try (ModbusCommunicationInterface comms = modbusManager.newModbusCommunicationInterface(endpoint, null)) {
comms.registerRegularPoll(new ModbusReadRequestBlueprint(SLAVE_UNIT_ID,
ModbusReadFunctionCode.READ_MULTIPLE_REGISTERS, 1, 15, 1), 200, 0, result -> {
Optional<@NonNull ModbusRegisterArray> registersOptional = result.getRegisters();
Optional<ModbusRegisterArray> registersOptional = result.getRegisters();
if (registersOptional.isPresent()) {
expectedReceived.incrementAndGet();
successfulCountDownLatch.countDown();
@ -774,7 +776,7 @@ public class SmokeTest extends IntegrationTestSupport {
try (ModbusCommunicationInterface comms = modbusManager.newModbusCommunicationInterface(endpoint, null)) {
PollTask task = comms.registerRegularPoll(new ModbusReadRequestBlueprint(SLAVE_UNIT_ID,
ModbusReadFunctionCode.READ_MULTIPLE_REGISTERS, 1, 15, 1), 200, 0, result -> {
Optional<@NonNull ModbusRegisterArray> registersOptional = result.getRegisters();
Optional<ModbusRegisterArray> registersOptional = result.getRegisters();
if (registersOptional.isPresent()) {
expectedReceived.incrementAndGet();
} else {
@ -991,7 +993,7 @@ public class SmokeTest extends IntegrationTestSupport {
try {
Constructor<?> constructor = socksSocketImplClass.getDeclaredConstructor();
constructor.setAccessible(true);
return (SocketImpl) constructor.newInstance();
return (SocketImpl) Objects.requireNonNull(constructor.newInstance());
} catch (NoSuchMethodException e) {
// Newer Javas (Java 14->) do not have default constructor 'SocksSocketImpl()'
// Instead we use "static SocketImpl.createPlatformSocketImpl" and "SocksSocketImpl(SocketImpl)
@ -1004,7 +1006,7 @@ public class SmokeTest extends IntegrationTestSupport {
Constructor<?> socksSocketImplConstructor = socksSocketImplClass
.getDeclaredConstructor(socketImplClass);
socksSocketImplConstructor.setAccessible(true);
return (SocketImpl) socksSocketImplConstructor.newInstance(socketImpl);
return (SocketImpl) Objects.requireNonNull(socksSocketImplConstructor.newInstance(socketImpl));
}
} catch (Exception e) {
throw new RuntimeException(e);

View File

@ -17,12 +17,14 @@ import static org.junit.jupiter.api.Assertions.*;
import java.nio.BufferOverflowException;
import java.nio.InvalidMarkException;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.Test;
import org.openhab.core.io.transport.modbus.ValueBuffer;
/**
* @author Sami Salonen - Initial contribution
*/
@NonNullByDefault
public class ValueBufferTest {
@Test

View File

@ -23,7 +23,7 @@ import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.hamcrest.Matcher;
import org.junit.jupiter.api.Test;
import org.openhab.core.io.transport.modbus.ModbusWriteFunctionCode;
@ -33,6 +33,7 @@ import org.openhab.core.io.transport.modbus.json.WriteRequestJsonUtilities;
/**
* @author Sami Salonen - Initial contribution
*/
@NonNullByDefault
public class WriteRequestJsonUtilitiesTest {
private static final List<String> MAX_REGISTERS = IntStream.range(0, MAX_REGISTERS_WRITE_COUNT).mapToObj(i -> "1")
@ -128,7 +129,7 @@ public class WriteRequestJsonUtilitiesTest {
@Test
public void testFC16MultipleRegistersMaxRegisters() {
Collection<@NonNull ModbusWriteRequestBlueprint> writes = WriteRequestJsonUtilities.fromJson(55, "[{"//
Collection<ModbusWriteRequestBlueprint> writes = WriteRequestJsonUtilities.fromJson(55, "[{"//
+ "\"functionCode\": 16,"//
+ "\"address\": 5412,"//
+ "\"value\": [" + String.join(",", MAX_REGISTERS) + "]"//
@ -192,7 +193,7 @@ public class WriteRequestJsonUtilitiesTest {
@Test
public void testFC15MultipleCoilsMaxCoils() {
Collection<@NonNull ModbusWriteRequestBlueprint> writes = WriteRequestJsonUtilities.fromJson(55, "[{"//
Collection<ModbusWriteRequestBlueprint> writes = WriteRequestJsonUtilities.fromJson(55, "[{"//
+ "\"functionCode\": 15,"//
+ "\"address\": 5412,"//
+ "\"value\": [" + String.join(",", MAX_COILS) + "]"//

View File

@ -16,6 +16,7 @@ import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.when;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ -44,6 +45,7 @@ import org.openhab.core.io.transport.upnp.UpnpIOParticipant;
*/
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.WARN)
@NonNullByDefault
public class UpnpIOServiceTest {
private static final String UDN_1_STRING = "UDN";
@ -56,18 +58,18 @@ public class UpnpIOServiceTest {
private static final String DEVICE_TYPE = "deviceType";
private static final String SERVICE_TYPE = "serviceType";
private @Mock UpnpIOParticipant upnpIoParticipant;
private @Mock UpnpIOParticipant upnpIoParticipant2;
private @Mock Registry upnpRegistry;
private @Mock ControlPoint controlPoint;
private @Mock UpnpService upnpServiceMock;
private @Mock @NonNullByDefault({}) UpnpIOParticipant upnpIoParticipantMock;
private @Mock @NonNullByDefault({}) UpnpIOParticipant upnpIoParticipant2Mock;
private @Mock @NonNullByDefault({}) Registry upnpRegistryMock;
private @Mock @NonNullByDefault({}) ControlPoint controlPointMock;
private @Mock @NonNullByDefault({}) UpnpService upnpServiceMock;
private UpnpIOServiceImpl upnpIoService;
private @NonNullByDefault({}) UpnpIOServiceImpl upnpIoService;
@BeforeEach
public void setup() throws Exception {
when(upnpIoParticipant.getUDN()).thenReturn(UDN_1_STRING);
when(upnpIoParticipant2.getUDN()).thenReturn(UDN_2_STRING);
when(upnpIoParticipantMock.getUDN()).thenReturn(UDN_1_STRING);
when(upnpIoParticipant2Mock.getUDN()).thenReturn(UDN_2_STRING);
DeviceIdentity deviceIdentity = new DeviceIdentity(UDN_1);
DeviceType deviceType = new DeviceType(UDAServiceId.DEFAULT_NAMESPACE, DEVICE_TYPE, 1);
@ -81,31 +83,31 @@ public class UpnpIOServiceTest {
LocalService<?> service2 = new LocalService<>(serviceType, serviceId2, null, null);
LocalDevice device2 = new LocalDevice(deviceIdentity, deviceType, (DeviceDetails) null, service2);
when(upnpRegistry.getDevice(eq(UDN_1), anyBoolean())).thenReturn(device);
when(upnpRegistry.getDevice(eq(UDN_2), anyBoolean())).thenReturn(device2);
when(upnpRegistryMock.getDevice(eq(UDN_1), anyBoolean())).thenReturn(device);
when(upnpRegistryMock.getDevice(eq(UDN_2), anyBoolean())).thenReturn(device2);
when(upnpServiceMock.getRegistry()).thenReturn(upnpRegistry);
when(upnpServiceMock.getControlPoint()).thenReturn(controlPoint);
when(upnpServiceMock.getRegistry()).thenReturn(upnpRegistryMock);
when(upnpServiceMock.getControlPoint()).thenReturn(controlPointMock);
upnpIoService = new UpnpIOServiceImpl(upnpServiceMock);
}
@Test
public void testIsRegistered() {
assertTrue(upnpIoService.isRegistered(upnpIoParticipant));
assertTrue(upnpIoService.isRegistered(upnpIoParticipantMock));
}
@Test
public void testIsRegisteredEverythingEmptyInitially() {
assertTrue(upnpIoService.isRegistered(upnpIoParticipant));
assertTrue(upnpIoService.isRegistered(upnpIoParticipantMock));
assertThatEverythingIsEmpty();
}
@Test
public void testRegisterParticipant() {
upnpIoService.registerParticipant(upnpIoParticipant);
upnpIoService.registerParticipant(upnpIoParticipantMock);
assertEquals(1, upnpIoService.participants.size());
assertTrue(upnpIoService.participants.contains(upnpIoParticipant));
assertTrue(upnpIoService.participants.contains(upnpIoParticipantMock));
assertTrue(upnpIoService.pollingJobs.keySet().isEmpty());
assertTrue(upnpIoService.currentStates.keySet().isEmpty());
assertTrue(upnpIoService.subscriptionCallbacks.keySet().isEmpty());
@ -113,45 +115,45 @@ public class UpnpIOServiceTest {
@Test
public void testAddStatusListener() {
upnpIoService.addStatusListener(upnpIoParticipant, SERVICE_ID, ACTION_ID, 60);
upnpIoService.addStatusListener(upnpIoParticipantMock, SERVICE_ID, ACTION_ID, 60);
assertEquals(1, upnpIoService.participants.size());
assertTrue(upnpIoService.participants.contains(upnpIoParticipant));
assertTrue(upnpIoService.participants.contains(upnpIoParticipantMock));
assertEquals(1, upnpIoService.pollingJobs.keySet().size());
assertTrue(upnpIoService.pollingJobs.containsKey(upnpIoParticipant));
assertTrue(upnpIoService.pollingJobs.containsKey(upnpIoParticipantMock));
assertEquals(1, upnpIoService.currentStates.keySet().size());
assertTrue(upnpIoService.currentStates.containsKey(upnpIoParticipant));
assertTrue(upnpIoService.currentStates.containsKey(upnpIoParticipantMock));
assertTrue(upnpIoService.subscriptionCallbacks.keySet().isEmpty());
upnpIoService.removeStatusListener(upnpIoParticipant);
upnpIoService.removeStatusListener(upnpIoParticipantMock);
assertThatEverythingIsEmpty();
}
@Test
public void testAddSubscription() {
upnpIoService.addSubscription(upnpIoParticipant, SERVICE_ID, 60);
upnpIoService.addSubscription(upnpIoParticipantMock, SERVICE_ID, 60);
assertEquals(1, upnpIoService.participants.size());
assertTrue(upnpIoService.participants.contains(upnpIoParticipant));
assertTrue(upnpIoService.participants.contains(upnpIoParticipantMock));
assertTrue(upnpIoService.pollingJobs.keySet().isEmpty());
assertTrue(upnpIoService.currentStates.keySet().isEmpty());
assertEquals(1, upnpIoService.subscriptionCallbacks.size());
upnpIoService.addSubscription(upnpIoParticipant2, SERVICE_ID_2, 60);
upnpIoService.addSubscription(upnpIoParticipant2Mock, SERVICE_ID_2, 60);
assertEquals(2, upnpIoService.participants.size());
assertTrue(upnpIoService.participants.contains(upnpIoParticipant));
assertTrue(upnpIoService.participants.contains(upnpIoParticipantMock));
assertTrue(upnpIoService.pollingJobs.keySet().isEmpty());
assertTrue(upnpIoService.currentStates.keySet().isEmpty());
assertEquals(2, upnpIoService.subscriptionCallbacks.size());
upnpIoService.removeSubscription(upnpIoParticipant, SERVICE_ID);
upnpIoService.unregisterParticipant(upnpIoParticipant);
upnpIoService.removeSubscription(upnpIoParticipantMock, SERVICE_ID);
upnpIoService.unregisterParticipant(upnpIoParticipantMock);
assertEquals(1, upnpIoService.participants.size());
assertTrue(upnpIoService.participants.contains(upnpIoParticipant2));
assertTrue(upnpIoService.participants.contains(upnpIoParticipant2Mock));
assertTrue(upnpIoService.pollingJobs.keySet().isEmpty());
assertTrue(upnpIoService.currentStates.keySet().isEmpty());
assertEquals(1, upnpIoService.subscriptionCallbacks.size());
upnpIoService.removeSubscription(upnpIoParticipant2, SERVICE_ID_2);
upnpIoService.unregisterParticipant(upnpIoParticipant2);
upnpIoService.removeSubscription(upnpIoParticipant2Mock, SERVICE_ID_2);
upnpIoService.unregisterParticipant(upnpIoParticipant2Mock);
assertThatEverythingIsEmpty();
}

View File

@ -20,6 +20,8 @@ import java.util.Collection;
import java.util.List;
import org.eclipse.emf.common.util.URI;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
@ -29,10 +31,11 @@ import org.junit.jupiter.params.provider.MethodSource;
*
* @author Simon Kaufmann - Initial contribution
*/
@NonNullByDefault
public class MappingUriExtensionsTest {
public @TempDir File folder;
private File confFolder;
public @TempDir @NonNullByDefault({}) File folder;
private @NonNullByDefault({}) File confFolder;
public static Collection<Object[]> data() {
return List.of(new Object[][] { //
@ -102,7 +105,7 @@ public class MappingUriExtensionsTest {
private MappingUriExtensions createMapper(String conf) {
return new MappingUriExtensions(conf) {
@Override
protected String calcServerLocation(String configFolder) {
protected String calcServerLocation(@Nullable String configFolder) {
// ensure test execution is independent from the current working directory
return removeTrailingSlash(confFolder.toPath().toUri().toString());
}

View File

@ -12,10 +12,11 @@
*/
package org.openhab.core.model.script.extension;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.Objects;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.core.io.console.Console;
import org.openhab.core.io.console.extensions.AbstractConsoleCommandExtension;
import org.openhab.core.io.console.extensions.ConsoleCommandExtension;
@ -32,10 +33,11 @@ import org.osgi.service.component.annotations.ReferencePolicy;
*
* @author Oliver Libutzki - Initial contribution
*/
@NonNullByDefault
@Component(service = ConsoleCommandExtension.class)
public class ScriptEngineConsoleCommandExtension extends AbstractConsoleCommandExtension {
private ScriptEngine scriptEngine;
private @Nullable ScriptEngine scriptEngine;
public ScriptEngineConsoleCommandExtension() {
super("script", "Execute scripts");
@ -43,11 +45,11 @@ public class ScriptEngineConsoleCommandExtension extends AbstractConsoleCommandE
@Override
public void execute(String[] args, Console console) {
ScriptEngine scriptEngine = this.scriptEngine;
if (scriptEngine != null) {
String scriptString = Arrays.stream(args).collect(Collectors.joining(" "));
Script script;
String scriptString = String.join(" ", args);
try {
script = scriptEngine.newScriptFromString(scriptString);
Script script = scriptEngine.newScriptFromString(scriptString);
Object result = script.execute();
if (result != null) {
@ -56,9 +58,11 @@ public class ScriptEngineConsoleCommandExtension extends AbstractConsoleCommandE
console.println("OK");
}
} catch (ScriptParsingException e) {
console.println(e.getMessage());
console.println(
Objects.requireNonNullElse(e.getMessage(), "An error occurred while parsing the script"));
} catch (ScriptExecutionException e) {
console.println(e.getMessage());
console.println(
Objects.requireNonNullElse(e.getMessage(), "An error occurred while executing the script"));
}
} else {
console.println("Script engine is not available.");

View File

@ -26,6 +26,7 @@ import java.util.stream.IntStream;
import javax.measure.quantity.Temperature;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
@ -54,34 +55,35 @@ import org.openhab.core.persistence.PersistenceServiceRegistry;
*/
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.WARN)
@NonNullByDefault
public class PersistenceExtensionsTest {
public static final String TEST_NUMBER = "testNumber";
public static final String TEST_QUANTITY_NUMBER = "testQuantityNumber";
public static final String TEST_SWITCH = "testSwitch";
private @Mock UnitProvider unitProvider;
private @Mock ItemRegistry mockedItemRegistry;
private @Mock @NonNullByDefault({}) ItemRegistry itemRegistryMock;
private @Mock @NonNullByDefault({}) UnitProvider unitProviderMock;
private GenericItem numberItem, quantityItem, switchItem;
private @NonNullByDefault({}) GenericItem numberItem, quantityItem, switchItem;
@BeforeEach
public void setUp() {
when(unitProvider.getUnit(Temperature.class)).thenReturn(SIUnits.CELSIUS);
when(unitProviderMock.getUnit(Temperature.class)).thenReturn(SIUnits.CELSIUS);
CoreItemFactory itemFactory = new CoreItemFactory();
numberItem = itemFactory.createItem(CoreItemFactory.NUMBER, TEST_NUMBER);
quantityItem = itemFactory.createItem(CoreItemFactory.NUMBER + ItemUtil.EXTENSION_SEPARATOR + "Temperature",
TEST_QUANTITY_NUMBER);
quantityItem.setUnitProvider(unitProvider);
quantityItem.setUnitProvider(unitProviderMock);
switchItem = itemFactory.createItem(CoreItemFactory.SWITCH, TEST_SWITCH);
when(mockedItemRegistry.get(TEST_NUMBER)).thenReturn(numberItem);
when(mockedItemRegistry.get(TEST_QUANTITY_NUMBER)).thenReturn(quantityItem);
when(mockedItemRegistry.get(TEST_SWITCH)).thenReturn(switchItem);
when(itemRegistryMock.get(TEST_NUMBER)).thenReturn(numberItem);
when(itemRegistryMock.get(TEST_QUANTITY_NUMBER)).thenReturn(quantityItem);
when(itemRegistryMock.get(TEST_SWITCH)).thenReturn(switchItem);
new PersistenceExtensions(new PersistenceServiceRegistry() {
private final PersistenceService testPersistenceService = new TestPersistenceService(mockedItemRegistry);
private final PersistenceService testPersistenceService = new TestPersistenceService(itemRegistryMock);
@Override
public @Nullable String getDefaultId() {

View File

@ -16,6 +16,7 @@ import static org.junit.jupiter.api.Assertions.*;
import java.util.Locale;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openhab.core.items.GenericItem;
@ -31,11 +32,12 @@ import org.openhab.core.semantics.model.property.Temperature;
/**
* @author Kai Kreuzer - Initial contribution
*/
@NonNullByDefault
public class SemanticTagsTest {
private GroupItem locationItem;
private GroupItem equipmentItem;
private GenericItem pointItem;
private @NonNullByDefault({}) GroupItem locationItem;
private @NonNullByDefault({}) GroupItem equipmentItem;
private @NonNullByDefault({}) GenericItem pointItem;
@BeforeEach
public void setup() {

View File

@ -14,6 +14,7 @@ package org.openhab.core.semantics;
import static org.junit.jupiter.api.Assertions.*;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openhab.core.items.GenericItem;
@ -27,11 +28,12 @@ import org.openhab.core.semantics.model.property.Temperature;
*
* @author Christoph Weitkamp - Initial contribution
*/
@NonNullByDefault
public class SemanticsPredicatesTest {
private GroupItem locationItem;
private GroupItem equipmentItem;
private GenericItem pointItem;
private @NonNullByDefault({}) GroupItem locationItem;
private @NonNullByDefault({}) GroupItem equipmentItem;
private @NonNullByDefault({}) GenericItem pointItem;
@BeforeEach
public void setup() {

View File

@ -19,6 +19,7 @@ import java.util.Locale;
import java.util.Set;
import java.util.stream.Stream;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ -37,16 +38,17 @@ import org.openhab.core.semantics.model.location.LivingRoom;
* @author Kai Kreuzer - Initial contribution
*/
@ExtendWith(MockitoExtension.class)
@NonNullByDefault
public class SemanticsServiceImplTest {
private @Mock ItemRegistry itemRegistry;
private @Mock MetadataRegistry metadataRegistry;
private @Mock @NonNullByDefault({}) ItemRegistry itemRegistryMock;
private @Mock @NonNullByDefault({}) MetadataRegistry metadataRegistryMock;
private GroupItem locationItem;
private GroupItem equipmentItem;
private GenericItem pointItem;
private @NonNullByDefault({}) GroupItem locationItem;
private @NonNullByDefault({}) GroupItem equipmentItem;
private @NonNullByDefault({}) GenericItem pointItem;
private SemanticsServiceImpl service;
private @NonNullByDefault({}) SemanticsServiceImpl service;
@BeforeEach
public void setup() throws Exception {
@ -65,11 +67,11 @@ public class SemanticsServiceImplTest {
pointItem.addGroupName(locationItem.getName());
locationItem.addMember(pointItem);
when(itemRegistry.stream()).thenReturn(Stream.of(locationItem, equipmentItem, pointItem))
when(itemRegistryMock.stream()).thenReturn(Stream.of(locationItem, equipmentItem, pointItem))
.thenReturn(Stream.of(locationItem, equipmentItem, pointItem))
.thenReturn(Stream.of(locationItem, equipmentItem, pointItem));
service = new SemanticsServiceImpl(itemRegistry, metadataRegistry);
service = new SemanticsServiceImpl(itemRegistryMock, metadataRegistryMock);
}
@Test

View File

@ -28,6 +28,7 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openhab.core.config.core.Configuration;
@ -44,10 +45,11 @@ import com.google.gson.reflect.TypeToken;
* @author Stefan Triller - Initial contribution
* @author Samie Salonen - test for ensuring ordering of keys in json
*/
@NonNullByDefault
public class JsonStorageTest extends JavaTest {
private JsonStorage<DummyObject> objectStorage;
private File tmpFile;
private @NonNullByDefault({}) JsonStorage<DummyObject> objectStorage;
private @NonNullByDefault({}) File tmpFile;
@BeforeEach
public void setUp() throws IOException {

Some files were not shown because too many files have changed in this diff Show More