diff options
author | Bjørn Christian Seime <bjorncs@yahooinc.com> | 2022-07-28 14:44:47 +0200 |
---|---|---|
committer | Bjørn Christian Seime <bjorncs@yahooinc.com> | 2022-07-28 14:51:35 +0200 |
commit | 695209a356ecae42536fd394189a98cf5274518e (patch) | |
tree | fff14a30ce9efde18a83d15ff08bbdb672119477 /config-model/src/test/java/com | |
parent | 9dab1e67022884f6644b3d8c9b02c6b3c466a879 (diff) |
Convert config-model to junit5
Diffstat (limited to 'config-model/src/test/java/com')
320 files changed, 6074 insertions, 6208 deletions
diff --git a/config-model/src/test/java/com/yahoo/config/model/ApplicationDeployTest.java b/config-model/src/test/java/com/yahoo/config/model/ApplicationDeployTest.java index ec5850b95b9..c1dd62316db 100644 --- a/config-model/src/test/java/com/yahoo/config/model/ApplicationDeployTest.java +++ b/config-model/src/test/java/com/yahoo/config/model/ApplicationDeployTest.java @@ -18,10 +18,9 @@ import com.yahoo.schema.Schema; import com.yahoo.vespa.config.ConfigDefinition; import com.yahoo.vespa.config.ConfigDefinitionKey; import com.yahoo.vespa.model.VespaModel; -import org.junit.After; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.xml.sax.SAXException; import java.io.File; @@ -36,22 +35,18 @@ import java.util.Map; import java.util.Set; import java.util.jar.JarEntry; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; public class ApplicationDeployTest { private static final String TESTDIR = "src/test/cfg/application/"; private static final String TEST_SCHEMAS_DIR = TESTDIR + "app1/schemas/"; - @Rule - public TemporaryFolder tmpFolder = new TemporaryFolder(); + @TempDir + public File tmpFolder; @Test - public void testVespaModel() throws SAXException, IOException { + void testVespaModel() throws SAXException, IOException { ApplicationPackageTester tester = ApplicationPackageTester.create(TESTDIR + "app1"); new VespaModel(tester.app()); List<Schema> schemas = tester.getSchemas(); @@ -72,11 +67,11 @@ public class ApplicationDeployTest { } } assertEquals(Set.of(new File(TEST_SCHEMAS_DIR + "laptop.sd"), - new File(TEST_SCHEMAS_DIR + "music.sd"), - new File(TEST_SCHEMAS_DIR + "pc.sd"), - new File(TEST_SCHEMAS_DIR + "product.sd"), - new File(TEST_SCHEMAS_DIR + "sock.sd")), - new HashSet<>(tester.app().getSearchDefinitionFiles())); + new File(TEST_SCHEMAS_DIR + "music.sd"), + new File(TEST_SCHEMAS_DIR + "pc.sd"), + new File(TEST_SCHEMAS_DIR + "product.sd"), + new File(TEST_SCHEMAS_DIR + "sock.sd")), + new HashSet<>(tester.app().getSearchDefinitionFiles())); List<FilesApplicationPackage.Component> components = tester.app().getComponents(); assertEquals(1, components.size()); @@ -104,7 +99,7 @@ public class ApplicationDeployTest { } @Test - public void testGetFile() throws IOException { + void testGetFile() throws IOException { ApplicationPackageTester tester = ApplicationPackageTester.create(TESTDIR + "app1"); try (Reader foo = tester.app().getFile(Path.fromString("files/foo.json")).createReader()) { assertEquals(IOUtils.readAll(foo), "foo : foo\n"); @@ -128,7 +123,7 @@ public class ApplicationDeployTest { } @Test - public void include_dirs_are_included() { + void include_dirs_are_included() { ApplicationPackageTester tester = ApplicationPackageTester.create(TESTDIR + "include_dirs"); Set<String> includeDirs = new HashSet<>(tester.app().getUserIncludeDirs()); @@ -136,12 +131,12 @@ public class ApplicationDeployTest { } @Test - public void non_existent_include_dir_is_not_allowed() throws Exception { - File appDir = tmpFolder.newFolder("non-existent-include"); + void non_existent_include_dir_is_not_allowed() throws Exception { + File appDir = newFolder(tmpFolder, "non-existent-include"); String services = "<services version='1.0'>" + - " <include dir='non-existent' />" + - "</services>\n"; + " <include dir='non-existent' />" + + "</services>\n"; IOUtils.writeFile(new File(appDir, "services.xml"), services, false); try { @@ -149,13 +144,13 @@ public class ApplicationDeployTest { fail("Expected exception due to non-existent include dir"); } catch (IllegalArgumentException e) { assertEquals("Cannot include directory 'non-existent', as it does not exist. Directory must reside in application package, and path must be given relative to application package.", - e.getMessage()); + e.getMessage()); } } @Test - public void testThatModelIsRebuiltWhenSearchDefinitionIsAdded() throws IOException { - File tmpDir = tmpFolder.getRoot(); + void testThatModelIsRebuiltWhenSearchDefinitionIsAdded() throws IOException { + File tmpDir = tmpFolder; IOUtils.copyDirectory(new File(TESTDIR, "app1"), tmpDir); ApplicationPackageTester tester = ApplicationPackageTester.create(tmpDir.getAbsolutePath()); assertEquals(5, tester.getSchemas().size()); @@ -166,55 +161,57 @@ public class ApplicationDeployTest { } @Test - public void testThatAppWithDeploymentXmlIsValid() throws IOException { - File tmpDir = tmpFolder.getRoot(); + void testThatAppWithDeploymentXmlIsValid() throws IOException { + File tmpDir = tmpFolder; IOUtils.copyDirectory(new File(TESTDIR, "app1"), tmpDir); ApplicationPackageTester.create(tmpDir.getAbsolutePath()); } - @Test(expected = IllegalArgumentException.class) - public void testThatAppWithIllegalDeploymentXmlIsNotValid() throws IOException { - File tmpDir = tmpFolder.getRoot(); - IOUtils.copyDirectory(new File(TESTDIR, "app_invalid_deployment_xml"), tmpDir); - ApplicationPackageTester.create(tmpDir.getAbsolutePath()); + @Test + void testThatAppWithIllegalDeploymentXmlIsNotValid() throws IOException { + assertThrows(IllegalArgumentException.class, () -> { + File tmpDir = tmpFolder; + IOUtils.copyDirectory(new File(TESTDIR, "app_invalid_deployment_xml"), tmpDir); + ApplicationPackageTester.create(tmpDir.getAbsolutePath()); + }); } @Test - public void testComplicatedDeploymentSpec() throws IOException { - File tmpDir = tmpFolder.getRoot(); + void testComplicatedDeploymentSpec() throws IOException { + File tmpDir = tmpFolder; IOUtils.copyDirectory(new File(TESTDIR, "app_complicated_deployment_spec"), tmpDir); ApplicationPackageTester.create(tmpDir.getAbsolutePath()); } @Test - public void testAppWithEmptyProdRegion() throws IOException { - File tmpDir = tmpFolder.getRoot(); + void testAppWithEmptyProdRegion() throws IOException { + File tmpDir = tmpFolder; IOUtils.copyDirectory(new File(TESTDIR, "empty_prod_region_in_deployment_xml"), tmpDir); ApplicationPackageTester.create(tmpDir.getAbsolutePath()); } @Test - public void testThatAppWithInvalidParallelDeploymentFails() throws IOException { + void testThatAppWithInvalidParallelDeploymentFails() throws IOException { String expectedMessage = "4: <staging/>\n" + - "5: <prod global-service-id=\"query\">\n" + - "6: <parallel>\n" + - "7: <instance id=\"hello\" />\n" + - "8: </parallel>\n" + - "9: </prod>\n" + - "10:</deployment>\n"; - File tmpDir = tmpFolder.getRoot(); + "5: <prod global-service-id=\"query\">\n" + + "6: <parallel>\n" + + "7: <instance id=\"hello\" />\n" + + "8: </parallel>\n" + + "9: </prod>\n" + + "10:</deployment>\n"; + File tmpDir = tmpFolder; IOUtils.copyDirectory(new File(TESTDIR, "invalid_parallel_deployment_xml"), tmpDir); try { ApplicationPackageTester.create(tmpDir.getAbsolutePath()); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("Invalid XML according to XML schema, error in deployment.xml: element \"instance\" not allowed here; expected the element end-tag or element \"delay\", \"region\", \"steps\" or \"test\" [7:30], input:\n" + expectedMessage, - e.getMessage()); + e.getMessage()); } } @Test - public void testConfigDefinitionsFromJars() { + void testConfigDefinitionsFromJars() { String appName = "src/test/cfg//application/app1"; FilesApplicationPackage app = FilesApplicationPackage.fromFile(new File(appName), false); Map<ConfigDefinitionKey, UnparsedConfigDefinition> defs = app.getAllExistingConfigDefs(); @@ -222,25 +219,25 @@ public class ApplicationDeployTest { } @Test - public void testMetaData() throws IOException { + void testMetaData() throws IOException { File tmp = Files.createTempDir(); String appPkg = TESTDIR + "app1"; IOUtils.copyDirectory(new File(appPkg), tmp); ApplicationId applicationId = ApplicationId.from("tenant1", "application1", "instance1"); DeployData deployData = new DeployData("bar", - applicationId, - 13L, - false, - 1337L, - 3L); + applicationId, + 13L, + false, + 1337L, + 3L); FilesApplicationPackage app = FilesApplicationPackage.fromFileWithDeployData(tmp, deployData); app.writeMetaData(); FilesApplicationPackage newApp = FilesApplicationPackage.fromFileWithDeployData(tmp, deployData); ApplicationMetaData meta = newApp.getMetaData(); assertEquals("bar", meta.getDeployPath()); assertEquals(applicationId, meta.getApplicationId()); - assertEquals(13L, (long)meta.getDeployTimestamp()); - assertEquals(1337L, (long)meta.getGeneration()); + assertEquals(13L, (long) meta.getDeployTimestamp()); + assertEquals(1337L, (long) meta.getGeneration()); assertEquals(3L, meta.getPreviousActiveGeneration()); String checksum = meta.getChecksum(); assertNotNull(checksum); @@ -257,7 +254,7 @@ public class ApplicationDeployTest { } @Test - public void testGetJarEntryName() { + void testGetJarEntryName() { JarEntry e = new JarEntry("/schemas/foo.sd"); assertEquals(ApplicationPackage.getFileName(e), "foo.sd"); e = new JarEntry("bar"); @@ -267,7 +264,7 @@ public class ApplicationDeployTest { } @Test - public void testGetJarEntryNameForLegacyPath() { + void testGetJarEntryNameForLegacyPath() { JarEntry e = new JarEntry("/searchdefinitions/foo.sd"); assertEquals(ApplicationPackage.getFileName(e), "foo.sd"); e = new JarEntry("bar"); @@ -276,7 +273,7 @@ public class ApplicationDeployTest { assertEquals(ApplicationPackage.getFileName(e), ""); } - @After + @AfterEach public void cleanDirs() { IOUtils.recursiveDeleteDir(new File(TESTDIR + "app1/myDir")); IOUtils.recursiveDeleteDir(new File(TESTDIR + "app1/searchdefinitions/myDir2")); @@ -284,7 +281,7 @@ public class ApplicationDeployTest { } @SuppressWarnings("ResultOfMethodCallIgnored") - @After + @AfterEach public void cleanFiles() { new File(new File(TESTDIR + "app1"),"foo.txt").delete(); new File(new File(TESTDIR + "app1"),"searchdefinitions/bar.text").delete(); @@ -295,13 +292,13 @@ public class ApplicationDeployTest { * Tests that an invalid jar is identified as not being a jar file */ @Test - public void testInvalidJar() { + void testInvalidJar() { try { FilesApplicationPackage.getComponents(new File("src/test/cfg/application/validation/invalidjar_app")); fail(); } catch (IllegalArgumentException e) { assertEquals("Error opening jar file 'invalid.jar'. Please check that this is a valid jar file", - e.getMessage()); + e.getMessage()); } } @@ -312,7 +309,7 @@ public class ApplicationDeployTest { * definition without version in file name */ @Test - public void testConfigDefinitionsAndNamespaces() { + void testConfigDefinitionsAndNamespaces() { final File appDir = new File("src/test/cfg/application/configdeftest"); FilesApplicationPackage app = FilesApplicationPackage.fromFile(appDir); @@ -330,10 +327,21 @@ public class ApplicationDeployTest { assertEquals("bar", def.getName()); } - @Test(expected=IllegalArgumentException.class) - public void testDifferentNameOfSdFileAndSearchName() { - ApplicationPackageTester tester = ApplicationPackageTester.create(TESTDIR + "sdfilenametest"); - new DeployState.Builder().applicationPackage(tester.app()).build(); + @Test + void testDifferentNameOfSdFileAndSearchName() { + assertThrows(IllegalArgumentException.class, () -> { + ApplicationPackageTester tester = ApplicationPackageTester.create(TESTDIR + "sdfilenametest"); + new DeployState.Builder().applicationPackage(tester.app()).build(); + }); + } + + private static File newFolder(File root, String... subDirs) throws IOException { + String subFolder = String.join("/", subDirs); + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + root); + } + return result; } } diff --git a/config-model/src/test/java/com/yahoo/config/model/ConfigModelBuilderTest.java b/config-model/src/test/java/com/yahoo/config/model/ConfigModelBuilderTest.java index e5909091534..11de928c14c 100644 --- a/config-model/src/test/java/com/yahoo/config/model/ConfigModelBuilderTest.java +++ b/config-model/src/test/java/com/yahoo/config/model/ConfigModelBuilderTest.java @@ -3,14 +3,14 @@ package com.yahoo.config.model; import com.yahoo.config.model.builder.xml.ConfigModelBuilder; import com.yahoo.config.model.builder.xml.ConfigModelId; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.w3c.dom.Element; import java.util.ArrayList; import java.util.List; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; /** * @author Ulf Lilleengen @@ -18,33 +18,33 @@ import static org.junit.Assert.assertTrue; */ public class ConfigModelBuilderTest { @Test - public void testEquals() { + void testEquals() { ConfigModelBuilder<?> ba = new A.Builder(); ConfigModelBuilder<?> ba2 = new A2.Builder(); ConfigModelBuilder<?> bb = new B.Builder(); - ConfigModelBuilder <?>bb2 = new B2.Builder(); + ConfigModelBuilder<?> bb2 = new B2.Builder(); - assertTrue(ba.equals(ba)); - assertTrue(ba.equals(ba2)); - assertFalse(ba.equals(bb)); - assertFalse(ba.equals(bb2)); + assertEquals(ba, ba); + assertEquals(ba, ba2); + assertNotEquals(ba, bb); + assertNotEquals(ba, bb2); - assertTrue(ba2.equals(ba)); - assertTrue(ba2.equals(ba2)); - assertFalse(ba2.equals(bb)); - assertFalse(ba2.equals(bb2)); + assertEquals(ba2, ba); + assertEquals(ba2, ba2); + assertNotEquals(ba2, bb); + assertNotEquals(ba2, bb2); - assertFalse(bb.equals(ba)); - assertFalse(bb.equals(ba2)); - assertTrue(bb.equals(bb)); - assertFalse(bb.equals(bb2)); + assertNotEquals(bb, ba); + assertNotEquals(bb, ba2); + assertEquals(bb, bb); + assertNotEquals(bb, bb2); - assertFalse(bb2.equals(ba)); - assertFalse(bb2.equals(ba2)); - assertFalse(bb2.equals(bb)); - assertTrue(bb2.equals(bb2)); + assertNotEquals(bb2, ba); + assertNotEquals(bb2, ba2); + assertNotEquals(bb2, bb); + assertEquals(bb2, bb2); - assertFalse(ba.equals(new ArrayList<>())); + assertNotEquals(ba, new ArrayList<>()); } private static class A extends ConfigModel { diff --git a/config-model/src/test/java/com/yahoo/config/model/ConfigModelContextTest.java b/config-model/src/test/java/com/yahoo/config/model/ConfigModelContextTest.java index 532c446ec6f..55fe909e70d 100644 --- a/config-model/src/test/java/com/yahoo/config/model/ConfigModelContextTest.java +++ b/config-model/src/test/java/com/yahoo/config/model/ConfigModelContextTest.java @@ -7,10 +7,10 @@ import com.yahoo.config.model.deploy.DeployState; import com.yahoo.config.model.producer.AbstractConfigProducer; import com.yahoo.config.model.test.MockApplicationPackage; import com.yahoo.config.model.test.MockRoot; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; /** * @author Ulf Lilleengen @@ -18,7 +18,7 @@ import static org.junit.Assert.assertNotEquals; public class ConfigModelContextTest { @Test - public void testConfigModelContext() { + void testConfigModelContext() { MockRoot root = new MockRoot(); String id = "foobar"; ApplicationPackage pkg = new MockApplicationPackage.Builder() diff --git a/config-model/src/test/java/com/yahoo/config/model/ConfigModelUtilsTest.java b/config-model/src/test/java/com/yahoo/config/model/ConfigModelUtilsTest.java index 325361e0127..3db4948c8c3 100644 --- a/config-model/src/test/java/com/yahoo/config/model/ConfigModelUtilsTest.java +++ b/config-model/src/test/java/com/yahoo/config/model/ConfigModelUtilsTest.java @@ -2,13 +2,13 @@ package com.yahoo.config.model; import com.yahoo.config.model.application.provider.Bundle; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.File; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Ulf Lilleengen @@ -19,38 +19,38 @@ public class ConfigModelUtilsTest { public static final String INVALID_TEST_BUNDLE = "src/test/cfg/application/validation/invalidjar_app/components"; @Test - public void all_def_files_in_correct_directory_are_handled_and_files_outside_are_ignored() { + void all_def_files_in_correct_directory_are_handled_and_files_outside_are_ignored() { List<Bundle> bundles = Bundle.getBundles(new File(VALID_TEST_BUNDLE)); assertEquals(1, bundles.size()); assertEquals(5, bundles.get(0).getDefEntries().size()); } @Test - public void def_file_with_namespace_is_handled() { + void def_file_with_namespace_is_handled() { Bundle.DefEntry defEntry = getDefEntry("test-namespace"); assertEquals("config", defEntry.defNamespace); } @Test - public void def_file_with_namespace_and_namespace_in_filename_is_handled() { + void def_file_with_namespace_and_namespace_in_filename_is_handled() { Bundle.DefEntry defEntry = getDefEntry("namespace-in-filename"); assertEquals("a.b", defEntry.defNamespace); } @Test - public void def_file_with_package_is_handled() { + void def_file_with_package_is_handled() { Bundle.DefEntry defEntry = getDefEntry("test-package"); assertEquals("com.mydomain.mypackage", defEntry.defNamespace); } @Test - public void def_file_with_package_and_pacakage_in_filename_is_handled() { + void def_file_with_package_and_pacakage_in_filename_is_handled() { Bundle.DefEntry defEntry = getDefEntry("package-in-filename"); assertEquals("com.mydomain.mypackage", defEntry.defNamespace); } @Test - public void def_file_with_both_package_and_namespace_gets_package_as_namespace() { + void def_file_with_both_package_and_namespace_gets_package_as_namespace() { Bundle.DefEntry defEntry = getDefEntry("namespace-and-package"); assertEquals("com.mydomain.mypackage", defEntry.defNamespace); } @@ -66,7 +66,7 @@ public class ConfigModelUtilsTest { } @Test - public void invalid_jar_file_fails_to_load() { + void invalid_jar_file_fails_to_load() { try { Bundle.getBundles(new File(INVALID_TEST_BUNDLE)); fail(); diff --git a/config-model/src/test/java/com/yahoo/config/model/MapConfigModelRegistryTest.java b/config-model/src/test/java/com/yahoo/config/model/MapConfigModelRegistryTest.java index e5e61459b44..84c1d66a507 100644 --- a/config-model/src/test/java/com/yahoo/config/model/MapConfigModelRegistryTest.java +++ b/config-model/src/test/java/com/yahoo/config/model/MapConfigModelRegistryTest.java @@ -3,14 +3,14 @@ package com.yahoo.config.model; import com.yahoo.config.model.builder.xml.ConfigModelBuilder; import com.yahoo.config.model.builder.xml.ConfigModelId; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.w3c.dom.Element; import java.util.Collection; import java.util.Collections; import java.util.List; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; /** * @author Ulf Lilleengen @@ -19,7 +19,7 @@ import static org.junit.Assert.*; public class MapConfigModelRegistryTest { @Test - public void require_that_registry_finds_components() { + void require_that_registry_finds_components() { ModelABuilder ba = new ModelABuilder(); ModelBBuilder bb = new ModelBBuilder(); ConfigModelRegistry registry = MapConfigModelRegistry.createFromList(ba, bb); @@ -31,7 +31,7 @@ public class MapConfigModelRegistryTest { } @Test - public void require_all_builders_for_a_tag() { + void require_all_builders_for_a_tag() { ModelBBuilder b1 = new ModelBBuilder(); ModelB2Builder b2 = new ModelB2Builder(); ConfigModelRegistry registry = MapConfigModelRegistry.createFromList(b1, b2); diff --git a/config-model/src/test/java/com/yahoo/config/model/QrserverAndGatewayPortAllocationTest.java b/config-model/src/test/java/com/yahoo/config/model/QrserverAndGatewayPortAllocationTest.java index a06da645e17..5e696682e98 100644 --- a/config-model/src/test/java/com/yahoo/config/model/QrserverAndGatewayPortAllocationTest.java +++ b/config-model/src/test/java/com/yahoo/config/model/QrserverAndGatewayPortAllocationTest.java @@ -5,11 +5,11 @@ import com.yahoo.vespa.model.VespaModel; import com.yahoo.vespa.model.container.Container; import com.yahoo.vespa.model.container.ApplicationContainer; import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithFilePkg; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.List; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests that qrserver is assigned port Defaults.getDefaults().vespaWebServicePort() even if there is a HTTP gateway configured earlier in @@ -20,7 +20,7 @@ import static org.junit.Assert.assertEquals; public class QrserverAndGatewayPortAllocationTest { @Test - public void testPorts() { + void testPorts() { String appDir = "src/test/cfg/application/app_qrserverandgw/"; VespaModelCreatorWithFilePkg creator = new VespaModelCreatorWithFilePkg(appDir); VespaModel vespaModel = creator.create(); diff --git a/config-model/src/test/java/com/yahoo/config/model/application/provider/SchemaValidatorTest.java b/config-model/src/test/java/com/yahoo/config/model/application/provider/SchemaValidatorTest.java index 1bf8c834586..7d3e6e81cd0 100644 --- a/config-model/src/test/java/com/yahoo/config/model/application/provider/SchemaValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/config/model/application/provider/SchemaValidatorTest.java @@ -3,14 +3,15 @@ package com.yahoo.config.model.application.provider; import com.yahoo.component.Version; import com.yahoo.vespa.config.VespaVersion; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; import java.io.StringReader; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * @author hmusum */ @@ -41,44 +42,43 @@ public class SchemaValidatorTest { " </admin>\n" + "</services>\n"; - @SuppressWarnings("deprecation") - @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Test - public void testXMLParse() throws IOException { + void testXMLParse() throws IOException { SchemaValidator validator = createValidator(); validator.validate(new StringReader(okServices)); } @Test - public void testXMLParseError() throws IOException { - SchemaValidator validator = createValidator(); - expectedException.expect(RuntimeException.class); - expectedException.expectMessage(expectedErrorMessage("input")); - validator.validate(new StringReader(invalidServices)); + void testXMLParseError() throws IOException { + Throwable exception = assertThrows(RuntimeException.class, () -> { + SchemaValidator validator = createValidator(); + validator.validate(new StringReader(invalidServices)); + }); + assertTrue(exception.getMessage().contains(expectedErrorMessage("input"))); } @Test - public void testXMLParseWithReader() throws IOException { + void testXMLParseWithReader() throws IOException { SchemaValidator validator = createValidator(); validator.validate(new StringReader(okServices)); } @Test - public void testXMLParseErrorWithReader() throws IOException { - SchemaValidator validator = createValidator(); - expectedException.expect(RuntimeException.class); - expectedException.expectMessage(expectedErrorMessage("input")); - validator.validate(new StringReader(invalidServices)); + void testXMLParseErrorWithReader() throws IOException { + Throwable exception = assertThrows(RuntimeException.class, () -> { + SchemaValidator validator = createValidator(); + validator.validate(new StringReader(invalidServices)); + }); + assertTrue(exception.getMessage().contains(expectedErrorMessage("input"))); } @Test - public void testXMLParseErrorFromFile() throws IOException { - SchemaValidator validator = createValidator(); - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage(expectedErrorMessage("services.xml")); - validator.validate(new File("src/test/cfg/application/invalid-services-syntax/services.xml")); + void testXMLParseErrorFromFile() throws IOException { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + SchemaValidator validator = createValidator(); + validator.validate(new File("src/test/cfg/application/invalid-services-syntax/services.xml")); + }); + assertTrue(exception.getMessage().contains(expectedErrorMessage("services.xml"))); } private SchemaValidator createValidator() { diff --git a/config-model/src/test/java/com/yahoo/config/model/builder/xml/ConfigModelIdTest.java b/config-model/src/test/java/com/yahoo/config/model/builder/xml/ConfigModelIdTest.java index 931768b6fd9..b1354446d1f 100644 --- a/config-model/src/test/java/com/yahoo/config/model/builder/xml/ConfigModelIdTest.java +++ b/config-model/src/test/java/com/yahoo/config/model/builder/xml/ConfigModelIdTest.java @@ -2,12 +2,9 @@ package com.yahoo.config.model.builder.xml; import com.yahoo.component.Version; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * @author Ulf Lilleengen @@ -16,7 +13,7 @@ import static org.junit.Assert.assertTrue; public class ConfigModelIdTest { @Test - public void require_that_element_gets_correct_name() { + void require_that_element_gets_correct_name() { ConfigModelId id = ConfigModelId.fromName("foo"); assertEquals("foo", id.getName()); assertEquals(Version.fromString("1"), id.getVersion()); @@ -26,7 +23,7 @@ public class ConfigModelIdTest { } @Test - public void test_toString() { + void test_toString() { ConfigModelId id = ConfigModelId.fromNameAndVersion("bar", "1.0"); assertEquals("bar.1", id.toString()); id = ConfigModelId.fromNameAndVersion("foo", "1.1.3"); @@ -36,7 +33,7 @@ public class ConfigModelIdTest { } @Test - public void test_equality() { + void test_equality() { ConfigModelId a1 = ConfigModelId.fromName("a"); ConfigModelId a2 = ConfigModelId.fromName("a"); ConfigModelId b = ConfigModelId.fromName("b"); @@ -52,18 +49,18 @@ public class ConfigModelIdTest { } @Test - public void test_compare() { + void test_compare() { ConfigModelId a1 = ConfigModelId.fromName("a"); ConfigModelId a2 = ConfigModelId.fromName("a"); ConfigModelId b = ConfigModelId.fromName("b"); - assertTrue(a1.compareTo(a2) == 0); - assertTrue(a2.compareTo(a1) == 0); + assertEquals(a1.compareTo(a2), 0); + assertEquals(a2.compareTo(a1), 0); assertFalse(a1.compareTo(b) > 0); assertFalse(a2.compareTo(b) > 0); assertFalse(b.compareTo(a1) < 0); assertFalse(b.compareTo(a2) < 0); - assertTrue(a1.compareTo(a1) == 0); - assertTrue(a2.compareTo(a2) == 0); - assertTrue(b.compareTo(b) == 0); + assertEquals(a1.compareTo(a1), 0); + assertEquals(a2.compareTo(a2), 0); + assertEquals(b.compareTo(b), 0); } } diff --git a/config-model/src/test/java/com/yahoo/config/model/builder/xml/XmlErrorHandlingTest.java b/config-model/src/test/java/com/yahoo/config/model/builder/xml/XmlErrorHandlingTest.java index ee616f59d04..a19bc2347d4 100644 --- a/config-model/src/test/java/com/yahoo/config/model/builder/xml/XmlErrorHandlingTest.java +++ b/config-model/src/test/java/com/yahoo/config/model/builder/xml/XmlErrorHandlingTest.java @@ -1,11 +1,11 @@ // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.config.model.builder.xml; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.xml.sax.InputSource; import java.io.FileReader; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author hmusum @@ -13,24 +13,24 @@ import static org.junit.Assert.assertEquals; public class XmlErrorHandlingTest { @Test - public void requireExceptionWithSourceAndFilenameAndLineNumber() { + void requireExceptionWithSourceAndFilenameAndLineNumber() { try { XmlHelper.getDocument(new FileReader("src/test/cfg/application/invalid-services-syntax/services.xml"), "services.xml"); } catch (Exception e) { assertEquals("Invalid XML in services.xml: The element type \"config\" must be terminated by the matching end-tag \"</config>\". [7:5]", - e.getMessage()); + e.getMessage()); } } @Test - public void requireExceptionWithLineNumber() { + void requireExceptionWithLineNumber() { try { XmlHelper.getDocumentBuilder().parse( new InputSource(new FileReader("src/test/cfg/application/invalid-services-syntax/services.xml"))); } catch (Exception e) { assertEquals("Invalid XML (unknown source): The element type \"config\" must be terminated by the matching end-tag \"</config>\". [7:5]", - e.getMessage()); + e.getMessage()); } } diff --git a/config-model/src/test/java/com/yahoo/config/model/builder/xml/test/DomBuilderTest.java b/config-model/src/test/java/com/yahoo/config/model/builder/xml/test/DomBuilderTest.java index 393522b4e33..29a842d8945 100644 --- a/config-model/src/test/java/com/yahoo/config/model/builder/xml/test/DomBuilderTest.java +++ b/config-model/src/test/java/com/yahoo/config/model/builder/xml/test/DomBuilderTest.java @@ -2,8 +2,8 @@ package com.yahoo.config.model.builder.xml.test; import com.yahoo.config.model.test.TestUtil; +import org.junit.jupiter.api.BeforeEach; import com.yahoo.config.model.test.MockRoot; -import org.junit.Before; import org.w3c.dom.Element; /** @@ -22,7 +22,7 @@ abstract public class DomBuilderTest { protected MockRoot root; - @Before + @BeforeEach public void setup() { root = new MockRoot(); } diff --git a/config-model/src/test/java/com/yahoo/config/model/deploy/DeployStateTest.java b/config-model/src/test/java/com/yahoo/config/model/deploy/DeployStateTest.java index 64870ff8e49..f0b729a718c 100644 --- a/config-model/src/test/java/com/yahoo/config/model/deploy/DeployStateTest.java +++ b/config-model/src/test/java/com/yahoo/config/model/deploy/DeployStateTest.java @@ -14,7 +14,7 @@ import com.yahoo.config.provision.ApplicationId; import com.yahoo.vespa.config.ConfigDefinition; import com.yahoo.vespa.config.ConfigDefinitionKey; import com.yahoo.vespa.model.VespaModel; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.xml.sax.SAXException; import java.io.File; @@ -25,9 +25,7 @@ import java.util.Map; import java.util.Optional; import java.util.Set; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * @author Ulf Lilleengen @@ -35,7 +33,7 @@ import static org.junit.Assert.assertTrue; public class DeployStateTest { @Test - public void testProvisionerIsSet() { + void testProvisionerIsSet() { DeployState.Builder builder = new DeployState.Builder(); HostProvisioner provisioner = new InMemoryProvisioner(true, false, "foo.yahoo.com"); builder.modelHostProvisioner(provisioner); @@ -44,7 +42,7 @@ public class DeployStateTest { } @Test - public void testBuilder() { + void testBuilder() { DeployState.Builder builder = new DeployState.Builder(); ApplicationPackage app = MockApplicationPackage.createEmpty(); builder.permanentApplicationPackage(Optional.of(app)); @@ -53,20 +51,20 @@ public class DeployStateTest { } @Test - public void testPreviousModelIsProvided() throws IOException, SAXException { + void testPreviousModelIsProvided() throws IOException, SAXException { VespaModel prevModel = new VespaModel(MockApplicationPackage.createEmpty()); DeployState.Builder builder = new DeployState.Builder(); assertEquals(prevModel, builder.previousModel(prevModel).build().getPreviousModel().get()); } @Test - public void testProperties() { + void testProperties() { DeployState.Builder builder = new DeployState.Builder(); DeployState state = builder.build(); assertEquals(ApplicationId.defaultId(), state.getProperties().applicationId()); ApplicationId customId = new ApplicationId.Builder() - .tenant("bar") - .applicationName("foo").instanceName("quux").build(); + .tenant("bar") + .applicationName("foo").instanceName("quux").build(); ModelContext.Properties properties = new TestProperties().setApplicationId(customId); builder.properties(properties); state = builder.build(); @@ -74,11 +72,11 @@ public class DeployStateTest { } @Test - public void testDefinitionRepoIsUsed() { + void testDefinitionRepoIsUsed() { Map<ConfigDefinitionKey, com.yahoo.vespa.config.buildergen.ConfigDefinition> defs = new LinkedHashMap<>(); defs.put(new ConfigDefinitionKey("foo", "bar"), new com.yahoo.vespa.config.buildergen.ConfigDefinition("foo", new String[]{"namespace=bar", "foo int default=0"})); defs.put(new ConfigDefinitionKey("test2", "a.b"), - new com.yahoo.vespa.config.buildergen.ConfigDefinition("namespace-in-filename", new String[]{"namespace=a.b", "doubleVal double default=1.0"})); + new com.yahoo.vespa.config.buildergen.ConfigDefinition("namespace-in-filename", new String[]{"namespace=a.b", "doubleVal double default=1.0"})); ApplicationPackage app = FilesApplicationPackage.fromFile(new File("src/test/cfg//application/app1")); DeployState state = createDeployState(app, defs); @@ -91,7 +89,7 @@ public class DeployStateTest { } @Test - public void testGetConfigDefinition() { + void testGetConfigDefinition() { Map<ConfigDefinitionKey, com.yahoo.vespa.config.buildergen.ConfigDefinition> defs = new LinkedHashMap<>(); defs.put(new ConfigDefinitionKey("test2", "a.b"), new com.yahoo.vespa.config.buildergen.ConfigDefinition("test2", new String[]{"namespace=a.b", "doubleVal double default=1.0"})); //defs.put(new ConfigDefinitionKey("test2", "c.d"), new com.yahoo.vespa.config.buildergen.ConfigDefinition("test2", new String[]{"namespace=c.d", "doubleVal double default=1.0"})); @@ -108,7 +106,7 @@ public class DeployStateTest { } @Test - public void testContainerEndpoints() { + void testContainerEndpoints() { assertTrue(new DeployState.Builder().endpoints(Set.of()).build().getEndpoints().isEmpty()); var endpoints = Set.of(new ContainerEndpoint("c1", ApplicationClusterEndpoint.Scope.global, List.of("c1.example.com", "c1-alias.example.com"))); assertEquals(endpoints, new DeployState.Builder().endpoints(endpoints).build().getEndpoints()); diff --git a/config-model/src/test/java/com/yahoo/config/model/deploy/SystemModelTestCase.java b/config-model/src/test/java/com/yahoo/config/model/deploy/SystemModelTestCase.java index 70b9fc54882..a9f97d95b74 100644 --- a/config-model/src/test/java/com/yahoo/config/model/deploy/SystemModelTestCase.java +++ b/config-model/src/test/java/com/yahoo/config/model/deploy/SystemModelTestCase.java @@ -16,16 +16,13 @@ import com.yahoo.vespa.model.test.ApiConfigModel; import com.yahoo.vespa.model.test.SimpleConfigModel; import com.yahoo.vespa.model.test.SimpleService; import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithFilePkg; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Iterator; import java.util.Map; import java.util.Set; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; /** * @author bratseth @@ -53,21 +50,21 @@ public class SystemModelTestCase { } @Test - public void testMetrics() { + void testMetrics() { VespaModel vespaModel = getVespaModelDoNotValidateXml(TESTDIR + "metricsconfig"); - SimpleService service0 = (SimpleService)vespaModel.getConfigProducer("simple/simpleservice.0").get(); + SimpleService service0 = (SimpleService) vespaModel.getConfigProducer("simple/simpleservice.0").get(); vespaModel.getConfigProducer("simple/simpleservice.1"); assertEquals("testClusterName", service0.getDefaultMetricDimensions().get("clustername")); } @Test - public void testVespaModel() { + void testVespaModel() { VespaModel vespaModel = getVespaModelDoNotValidateXml(TESTDIR + "simpleconfig/"); assertNotNull(vespaModel); - assertEquals("There are two instances of the simple model + Routing and AdminModel (set up implicitly)", 4, vespaModel.configModelRepo().asMap().size()); - assertNotNull("One gets the default name as there is no explicit id", vespaModel.configModelRepo().asMap().get("simple")); - assertNotNull("The other gets the explicit id as name", vespaModel.configModelRepo().asMap().get("second")); + assertEquals(4, vespaModel.configModelRepo().asMap().size(), "There are two instances of the simple model + Routing and AdminModel (set up implicitly)"); + assertNotNull(vespaModel.configModelRepo().asMap().get("simple"), "One gets the default name as there is no explicit id"); + assertNotNull(vespaModel.configModelRepo().asMap().get("second"), "The other gets the explicit id as name"); ApplicationConfigProducerRoot root = vespaModel.getVespa(); assertNotNull(root); @@ -108,7 +105,7 @@ public class SystemModelTestCase { } @Test - public void testHostSystem() { + void testHostSystem() { VespaModel vespaModel = getVespaModelDoNotValidateXml(TESTDIR + "simpleconfig/"); HostSystem hostSystem = vespaModel.hostSystem(); @@ -129,7 +126,7 @@ public class SystemModelTestCase { } @Test - public void testBasePorts() { + void testBasePorts() { VespaModel vespaModel = getVespaModelDoNotValidateXml(TESTDIR + "simpleconfig"); assertNotNull(vespaModel); @@ -142,7 +139,7 @@ public class SystemModelTestCase { * Be sure to update it as well if you change this. */ @Test - public void testPlugins() { + void testPlugins() { VespaModel vespaModel = getVespaModelDoNotValidateXml(TESTDIR + "plugins"); assertNotNull(vespaModel); @@ -169,14 +166,14 @@ public class SystemModelTestCase { assertEquals("routing", plugin.getId()); assertEquals(vespaModel.getConfig(StandardConfig.class, "api/apiservice.0").astring(), "apiservice"); - + assertEquals(vespaModel.getConfig(StandardConfig.class, "simple/simpleservice.0").astring(), "simpleservice"); assertEquals(vespaModel.getConfig(StandardConfig.class, "simple/simpleservice.1").astring(), "simpleservice"); assertEquals(vespaModel.getConfig(StandardConfig.class, "simple2/simpleservice.0").astring(), "simpleservice"); } @Test - public void testEqualPlugins() { + void testEqualPlugins() { try { getVespaModelDoNotValidateXml(TESTDIR + "doubleconfig"); fail("No exception upon two plugins with the same name"); diff --git a/config-model/src/test/java/com/yahoo/config/model/graph/ModelGraphTest.java b/config-model/src/test/java/com/yahoo/config/model/graph/ModelGraphTest.java index da8ce7fd425..753f4b11f9f 100644 --- a/config-model/src/test/java/com/yahoo/config/model/graph/ModelGraphTest.java +++ b/config-model/src/test/java/com/yahoo/config/model/graph/ModelGraphTest.java @@ -3,16 +3,11 @@ package com.yahoo.config.model.graph; import com.yahoo.config.model.ConfigModelContext; import com.yahoo.config.model.test.MockRoot; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; import java.util.List; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.*; /** * @author Ulf Lilleengen @@ -30,7 +25,7 @@ public class ModelGraphTest { } @Test - public void require_that_dependencies_are_correctly_set() { + void require_that_dependencies_are_correctly_set() { ModelGraphBuilder builder = new ModelGraphBuilder(); builder.addBuilder(new GraphMock.BC()).addBuilder(new GraphMock.BB()).addBuilder(new GraphMock.BA()); ModelGraph graph = builder.build(); @@ -45,22 +40,24 @@ public class ModelGraphTest { } @Test - public void require_that_dependencies_are_correctly_sorted() { + void require_that_dependencies_are_correctly_sorted() { ModelGraph graph = new ModelGraphBuilder().addBuilder(new GraphMock.BC()).addBuilder(new GraphMock.BB()).addBuilder(new GraphMock.BA()).build(); assertOrdering(graph, "ABC"); } - @Test(expected = IllegalArgumentException.class) - public void require_that_cycles_are_detected() { - ModelGraph graph = new ModelGraphBuilder().addBuilder(new GraphMock.BD()).addBuilder(new GraphMock.BE()).build(); - assertEquals(2, graph.getNodes().size()); - assertTrue(graph.getNodes().get(0).dependsOn(graph.getNodes().get(1))); - assertTrue(graph.getNodes().get(1).dependsOn(graph.getNodes().get(0))); - graph.topologicalSort(); + @Test + void require_that_cycles_are_detected() { + assertThrows(IllegalArgumentException.class, () -> { + ModelGraph graph = new ModelGraphBuilder().addBuilder(new GraphMock.BD()).addBuilder(new GraphMock.BE()).build(); + assertEquals(2, graph.getNodes().size()); + assertTrue(graph.getNodes().get(0).dependsOn(graph.getNodes().get(1))); + assertTrue(graph.getNodes().get(1).dependsOn(graph.getNodes().get(0))); + graph.topologicalSort(); + }); } @Test - public void require_that_instance_can_be_created() { + void require_that_instance_can_be_created() { ModelGraph graph = new ModelGraphBuilder().addBuilder(new GraphMock.BC()).addBuilder(new GraphMock.BB()).addBuilder(new GraphMock.BA()).build(); List<ModelNode> nodes = graph.topologicalSort(); MockRoot root = new MockRoot(); @@ -83,30 +80,28 @@ public class ModelGraphTest { assertTrue(c.b.contains(b2)); } - @SuppressWarnings("deprecation") - @Rule - public ExpectedException expectedEx = ExpectedException.none(); - @Test - public void require_that_context_must_be_first_ctor_param() { - expectedEx.expect(IllegalArgumentException.class); - expectedEx.expectMessage("Constructor for " + GraphMock.Bad.class.getName() + " must have as its first argument a " + ConfigModelContext.class.getName()); - ModelNode node = new ModelNode(new GraphMock.Bad.Builder()); - MockRoot root = new MockRoot(); - node.createModel(ConfigModelContext.create(root.getDeployState(), null, null, root, "foo")); + void require_that_context_must_be_first_ctor_param() { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + ModelNode node = new ModelNode(new GraphMock.Bad.Builder()); + MockRoot root = new MockRoot(); + node.createModel(ConfigModelContext.create(root.getDeployState(), null, null, root, "foo")); + }); + assertTrue(exception.getMessage().contains("Constructor for " + GraphMock.Bad.class.getName() + " must have as its first argument a " + ConfigModelContext.class.getName())); } @Test - public void require_that_ctor_arguments_must_be_models_or_collections_of_models() { - expectedEx.expect(IllegalArgumentException.class); - expectedEx.expectMessage("Unable to find constructor argument class java.lang.String for com.yahoo.config.model.graph.GraphMock$Bad2"); - ModelNode node = new ModelNode(new GraphMock.Bad2.Builder()); - MockRoot root = new MockRoot(); - node.createModel(ConfigModelContext.create(root.getDeployState(), null, null, root, "foo")); + void require_that_ctor_arguments_must_be_models_or_collections_of_models() { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + ModelNode node = new ModelNode(new GraphMock.Bad2.Builder()); + MockRoot root = new MockRoot(); + node.createModel(ConfigModelContext.create(root.getDeployState(), null, null, root, "foo")); + }); + assertTrue(exception.getMessage().contains("Unable to find constructor argument class java.lang.String for com.yahoo.config.model.graph.GraphMock$Bad2")); } @Test - public void require_that_collections_can_be_empty() { + void require_that_collections_can_be_empty() { ModelGraph graph = new ModelGraphBuilder().addBuilder(new GraphMock.BC()).addBuilder(new GraphMock.BA()).build(); List<ModelNode> nodes = graph.topologicalSort(); MockRoot root = new MockRoot(); diff --git a/config-model/src/test/java/com/yahoo/config/model/producer/AbstractConfigProducerTest.java b/config-model/src/test/java/com/yahoo/config/model/producer/AbstractConfigProducerTest.java index 04ae4c76f27..763b9c25072 100644 --- a/config-model/src/test/java/com/yahoo/config/model/producer/AbstractConfigProducerTest.java +++ b/config-model/src/test/java/com/yahoo/config/model/producer/AbstractConfigProducerTest.java @@ -2,10 +2,10 @@ package com.yahoo.config.model.producer; import com.yahoo.cloud.config.log.LogdConfig; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * Verifies some of the logic in the abstract config producer that is not tested in other classes. @@ -16,7 +16,7 @@ import static org.junit.Assert.assertEquals; public class AbstractConfigProducerTest { @Test - public void require_that_interface_is_found_if_directly_implemented() throws ReflectiveOperationException { + void require_that_interface_is_found_if_directly_implemented() throws ReflectiveOperationException { MockLogdProducer producer = new MockLogdProducer("mocky"); ClassLoader loader = producer.getConfigClassLoader(LogdConfig.Producer.class.getName()); assertNotNull(loader); @@ -29,7 +29,7 @@ public class AbstractConfigProducerTest { } @Test - public void require_that_interface_is_found_if_inherited() throws ReflectiveOperationException { + void require_that_interface_is_found_if_inherited() throws ReflectiveOperationException { MockLogdProducerSubclass producer = new MockLogdProducerSubclass("mocky"); ClassLoader loader = producer.getConfigClassLoader(LogdConfig.Producer.class.getName()); assertNotNull(loader); diff --git a/config-model/src/test/java/com/yahoo/config/model/provision/HostSpecTest.java b/config-model/src/test/java/com/yahoo/config/model/provision/HostSpecTest.java index 810e2c643f3..e678aaa673a 100644 --- a/config-model/src/test/java/com/yahoo/config/model/provision/HostSpecTest.java +++ b/config-model/src/test/java/com/yahoo/config/model/provision/HostSpecTest.java @@ -2,15 +2,15 @@ package com.yahoo.config.model.provision; import com.yahoo.config.provision.HostSpec; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; /** * @author Ulf Lilleengen @@ -18,31 +18,31 @@ import static org.junit.Assert.assertTrue; public class HostSpecTest { @Test - public void testEquals() { + void testEquals() { HostSpec h1 = new HostSpec("foo", List.of(), Optional.empty()); HostSpec h2 = new HostSpec("foo", List.of(), Optional.empty()); HostSpec h3 = new HostSpec("foo", List.of("my", "alias"), Optional.empty()); HostSpec h4 = new HostSpec("bar", List.of(), Optional.empty()); - assertTrue(h1.equals(h1)); - assertTrue(h1.equals(h2)); - assertTrue(h1.equals(h3)); - assertFalse(h1.equals(h4)); - - assertTrue(h2.equals(h1)); - assertTrue(h2.equals(h2)); - assertTrue(h2.equals(h3)); - assertFalse(h2.equals(h4)); - - assertTrue(h3.equals(h1)); - assertTrue(h3.equals(h2)); - assertTrue(h3.equals(h3)); - assertFalse(h3.equals(h4)); - - assertFalse(h4.equals(h1)); - assertFalse(h4.equals(h2)); - assertFalse(h4.equals(h3)); - assertTrue(h4.equals(h4)); + assertEquals(h1, h1); + assertEquals(h1, h2); + assertEquals(h1, h3); + assertNotEquals(h1, h4); + + assertEquals(h2, h1); + assertEquals(h2, h2); + assertEquals(h2, h3); + assertNotEquals(h2, h4); + + assertEquals(h3, h1); + assertEquals(h3, h2); + assertEquals(h3, h3); + assertNotEquals(h3, h4); + + assertNotEquals(h4, h1); + assertNotEquals(h4, h2); + assertNotEquals(h4, h3); + assertEquals(h4, h4); } } diff --git a/config-model/src/test/java/com/yahoo/config/model/provision/HostsXmlProvisionerTest.java b/config-model/src/test/java/com/yahoo/config/model/provision/HostsXmlProvisionerTest.java index 558e61fc1c2..9721e85c71d 100644 --- a/config-model/src/test/java/com/yahoo/config/model/provision/HostsXmlProvisionerTest.java +++ b/config-model/src/test/java/com/yahoo/config/model/provision/HostsXmlProvisionerTest.java @@ -3,7 +3,7 @@ package com.yahoo.config.model.provision; import com.yahoo.config.provision.HostSpec; import com.yahoo.vespa.model.container.Container; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.StringReader; import java.util.ArrayList; @@ -15,8 +15,7 @@ import java.util.List; import java.util.Map; import java.util.Set; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * @author hmusum @@ -46,7 +45,7 @@ public class HostsXmlProvisionerTest { "</hosts>"; @Test - public void require_basic_works() { + void require_basic_works() { HostsXmlProvisioner hostProvisioner = createProvisioner(threeHosts); // 4 services, 2 host aliases, mapping to 2 host. @@ -71,14 +70,16 @@ public class HostsXmlProvisionerTest { assertEquals(3, map.size()); assertCorrectNumberOfHosts(map, 3); assertTrue(map.keySet().containsAll(aliases)); - + assertEquals("", System.getProperty("zookeeper.vespa.clients")); } - @Test(expected = IllegalArgumentException.class) - public void require_exception_when_unknown_hosts_alias() { - HostsXmlProvisioner hostProvisioner = createProvisioner(oneHost); - hostProvisioner.allocateHost("unknown"); + @Test + void require_exception_when_unknown_hosts_alias() { + assertThrows(IllegalArgumentException.class, () -> { + HostsXmlProvisioner hostProvisioner = createProvisioner(oneHost); + hostProvisioner.allocateHost("unknown"); + }); } private void assertCorrectNumberOfHosts(Map<String, HostSpec> hostToServiceMap, int expectedHostCount) { @@ -117,7 +118,7 @@ public class HostsXmlProvisionerTest { } @Test - public void require_singlenode_HostAlias_is_used_if_hosts_xml() { + void require_singlenode_HostAlias_is_used_if_hosts_xml() { HostsXmlProvisioner hostProvisioner = createProvisioner(oneHost); HostSpec hostSpec = hostProvisioner.allocateHost(Container.SINGLENODE_CONTAINER_SERVICESPEC); assertEquals("test1.yahoo.com", hostSpec.hostname()); diff --git a/config-model/src/test/java/com/yahoo/config/model/provision/ModelProvisioningTest.java b/config-model/src/test/java/com/yahoo/config/model/provision/ModelProvisioningTest.java index 03ab4f46c60..30b848da7f1 100644 --- a/config-model/src/test/java/com/yahoo/config/model/provision/ModelProvisioningTest.java +++ b/config-model/src/test/java/com/yahoo/config/model/provision/ModelProvisioningTest.java @@ -38,7 +38,8 @@ import com.yahoo.vespa.model.search.SearchNode; import com.yahoo.vespa.model.test.VespaModelTester; import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithMockPkg; import com.yahoo.yolean.Exceptions; -import org.junit.Test; +import org.junit.jupiter.api.Test; + import java.io.StringReader; import java.util.ArrayList; import java.util.List; @@ -57,12 +58,13 @@ import static com.yahoo.vespa.defaults.Defaults.getDefaults; import static com.yahoo.vespa.model.search.NodeResourcesTuning.GB; import static com.yahoo.vespa.model.search.NodeResourcesTuning.reservedMemoryGb; import static com.yahoo.vespa.model.test.utils.ApplicationPackageUtils.generateSchemas; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * Test cases for provisioning nodes to entire Vespa models. @@ -219,10 +221,10 @@ public class ModelProvisioningTest { tester.addHosts(8); VespaModel model = tester.createModel(xmlWithNodes, true); - assertEquals("Nodes in content1", 2, model.getContentClusters().get("content1").getRootGroup().getNodes().size()); - assertEquals("Nodes in container1", 1, model.getContainerClusters().get("container1").getContainers().size()); - assertEquals("Nodes in cluster without ID", 2, model.getContentClusters().get("content").getRootGroup().getNodes().size()); - assertEquals("Heap size for container", 70, physicalMemoryPercentage(model.getContainerClusters().get("container1"))); + assertEquals(2, model.getContentClusters().get("content1").getRootGroup().getNodes().size(), "Nodes in content1"); + assertEquals(1, model.getContainerClusters().get("container1").getContainers().size(), "Nodes in container1"); + assertEquals(2, model.getContentClusters().get("content").getRootGroup().getNodes().size(), "Nodes in cluster without ID"); + assertEquals(70, physicalMemoryPercentage(model.getContainerClusters().get("container1")), "Heap size for container"); assertProvisioned(2, ClusterSpec.Id.from("content1"), ClusterSpec.Type.content, model); assertProvisioned(1, ClusterSpec.Id.from("container1"), ClusterSpec.Type.container, model); assertProvisioned(2, ClusterSpec.Id.from("content"), ClusterSpec.Type.content, model); @@ -272,13 +274,11 @@ public class ModelProvisioningTest { tester.addHosts(5); TestLogger logger = new TestLogger(); VespaModel model = tester.createModel(xmlWithNodes, true, new DeployState.Builder().deployLogger(logger)); - assertEquals("Nodes in content1", 2, model.getContentClusters().get("content1").getRootGroup().getNodes().size()); - assertEquals("Nodes in container1", 2, model.getContainerClusters().get("container1").getContainers().size()); - assertEquals("Heap size is lowered with combined clusters", - 18, physicalMemoryPercentage(model.getContainerClusters().get("container1"))); - assertEquals("Memory for proton is lowered to account for the jvm heap", - (long) ((3 - reservedMemoryGb) * (Math.pow(1024, 3)) * (1 - 0.18)), protonMemorySize(model.getContentClusters() - .get("content1"))); + assertEquals(2, model.getContentClusters().get("content1").getRootGroup().getNodes().size(), "Nodes in content1"); + assertEquals(2, model.getContainerClusters().get("container1").getContainers().size(), "Nodes in container1"); + assertEquals(18, physicalMemoryPercentage(model.getContainerClusters().get("container1")), "Heap size is lowered with combined clusters"); + assertEquals((long) ((3 - reservedMemoryGb) * (Math.pow(1024, 3)) * (1 - 0.18)), protonMemorySize(model.getContentClusters() + .get("content1")), "Memory for proton is lowered to account for the jvm heap"); assertProvisioned(0, ClusterSpec.Id.from("container1"), ClusterSpec.Type.container, model); assertProvisioned(2, ClusterSpec.Id.from("content1"), ClusterSpec.Id.from("container1"), ClusterSpec.Type.combined, model); assertEquals(1, logger.msgs().size()); @@ -311,13 +311,11 @@ public class ModelProvisioningTest { VespaModelTester tester = new VespaModelTester(); tester.addHosts(5); VespaModel model = tester.createModel(xmlWithNodes, true); - assertEquals("Nodes in content1", 2, model.getContentClusters().get("content1").getRootGroup().getNodes().size()); - assertEquals("Nodes in container1", 2, model.getContainerClusters().get("container1").getContainers().size()); - assertEquals("Heap size is lowered with combined clusters", - 30, physicalMemoryPercentage(model.getContainerClusters().get("container1"))); - assertEquals("Memory for proton is lowered to account for the jvm heap", - (long) ((3 - reservedMemoryGb) * (Math.pow(1024, 3)) * (1 - 0.30)), protonMemorySize(model.getContentClusters() - .get("content1"))); + assertEquals(2, model.getContentClusters().get("content1").getRootGroup().getNodes().size(), "Nodes in content1"); + assertEquals(2, model.getContainerClusters().get("container1").getContainers().size(), "Nodes in container1"); + assertEquals(30, physicalMemoryPercentage(model.getContainerClusters().get("container1")), "Heap size is lowered with combined clusters"); + assertEquals((long) ((3 - reservedMemoryGb) * (Math.pow(1024, 3)) * (1 - 0.30)), protonMemorySize(model.getContentClusters() + .get("content1")), "Memory for proton is lowered to account for the jvm heap"); assertProvisioned(0, ClusterSpec.Id.from("container1"), ClusterSpec.Type.container, model); assertProvisioned(2, ClusterSpec.Id.from("content1"), ClusterSpec.Id.from("container1"), ClusterSpec.Type.combined, model); } @@ -345,12 +343,10 @@ public class ModelProvisioningTest { VespaModelTester tester = new VespaModelTester(); tester.addHosts(7); VespaModel model = tester.createModel(xmlWithNodes, true); - assertEquals("Nodes in content1", 2, model.getContentClusters().get("content1").getRootGroup().getNodes().size()); - assertEquals("Nodes in container1", 2, model.getContainerClusters().get("container1").getContainers().size()); - assertEquals("Heap size is normal", - 70, physicalMemoryPercentage(model.getContainerClusters().get("container1"))); - assertEquals("Memory for proton is normal", - (long) ((3 - reservedMemoryGb) * (Math.pow(1024, 3))), protonMemorySize(model.getContentClusters().get("content1"))); + assertEquals(2, model.getContentClusters().get("content1").getRootGroup().getNodes().size(), "Nodes in content1"); + assertEquals(2, model.getContainerClusters().get("container1").getContainers().size(), "Nodes in container1"); + assertEquals(70, physicalMemoryPercentage(model.getContainerClusters().get("container1")), "Heap size is normal"); + assertEquals((long) ((3 - reservedMemoryGb) * (Math.pow(1024, 3))), protonMemorySize(model.getContentClusters().get("content1")), "Memory for proton is normal"); } @Test @@ -376,8 +372,8 @@ public class ModelProvisioningTest { tester.addHosts(5); VespaModel model = tester.createModel(xmlWithNodes, true); - assertEquals("Nodes in content1", 2, model.getContentClusters().get("content1").getRootGroup().getNodes().size()); - assertEquals("Nodes in container1", 2, model.getContainerClusters().get("container1").getContainers().size()); + assertEquals(2, model.getContentClusters().get("content1").getRootGroup().getNodes().size(), "Nodes in content1"); + assertEquals(2, model.getContainerClusters().get("container1").getContainers().size(), "Nodes in container1"); for (Container container : model.getContainerClusters().get("container1").getContainers()) assertTrue(container.getJvmOptions().contains("testoption")); } @@ -412,10 +408,10 @@ public class ModelProvisioningTest { tester.addHosts(8); VespaModel model = tester.createModel(xmlWithNodes, true); - assertEquals("Nodes in content1", 2, model.getContentClusters().get("content1").getRootGroup().getNodes().size()); - assertEquals("Nodes in container1", 2, model.getContainerClusters().get("container1").getContainers().size()); - assertEquals("Nodes in content2", 3, model.getContentClusters().get("content2").getRootGroup().getNodes().size()); - assertEquals("Nodes in container2", 3, model.getContainerClusters().get("container2").getContainers().size()); + assertEquals(2, model.getContentClusters().get("content1").getRootGroup().getNodes().size(), "Nodes in content1"); + assertEquals(2, model.getContainerClusters().get("container1").getContainers().size(), "Nodes in container1"); + assertEquals(3, model.getContentClusters().get("content2").getRootGroup().getNodes().size(), "Nodes in content2"); + assertEquals(3, model.getContainerClusters().get("container2").getContainers().size(), "Nodes in container2"); } @Test @@ -535,10 +531,10 @@ public class ModelProvisioningTest { .stream().map(cc -> cc.getHostResource()).collect(Collectors.toSet()); Set<HostResource> slobrokHosts = admin.getSlobroks().stream().map(Slobrok::getHost).collect(Collectors.toSet()); assertEquals(3, slobrokHosts.size()); - assertTrue("Slobroks are assigned on cluster controller nodes", clusterControllerHosts.containsAll(slobrokHosts)); - assertTrue("Logserver is assigned from container nodes", containerHosts.contains(admin.getLogserver().getHost())); - assertEquals("No in-cluster config servers in a hosted environment", 0, admin.getConfigservers().size()); - assertEquals("Dedicated admin cluster controllers when hosted", 3, admin.getClusterControllers().getContainers().size()); + assertTrue(clusterControllerHosts.containsAll(slobrokHosts), "Slobroks are assigned on cluster controller nodes"); + assertTrue(containerHosts.contains(admin.getLogserver().getHost()), "Logserver is assigned from container nodes"); + assertEquals(0, admin.getConfigservers().size(), "No in-cluster config servers in a hosted environment"); + assertEquals(3, admin.getClusterControllers().getContainers().size(), "Dedicated admin cluster controllers when hosted"); // Check content clusters ContentCluster cluster = model.getContentClusters().get("bar"); @@ -626,10 +622,10 @@ public class ModelProvisioningTest { Admin admin = model.getAdmin(); Set<HostResource> slobrokHosts = admin.getSlobroks().stream().map(Slobrok::getHost).collect(Collectors.toSet()); assertEquals(3, slobrokHosts.size()); - assertTrue("Slobroks are assigned from container nodes", - containerHosts.containsAll(slobrokHosts)); - assertTrue("Logserver is assigned from container nodes", containerHosts.contains(admin.getLogserver().getHost())); - assertEquals("No in-cluster config servers in a hosted environment", 0, admin.getConfigservers().size()); + assertTrue(containerHosts.containsAll(slobrokHosts), + "Slobroks are assigned from container nodes"); + assertTrue(containerHosts.contains(admin.getLogserver().getHost()), "Logserver is assigned from container nodes"); + assertEquals(0, admin.getConfigservers().size(), "No in-cluster config servers in a hosted environment"); } @Test @@ -676,9 +672,9 @@ public class ModelProvisioningTest { .stream().map(cc -> cc.getHostResource()).collect(Collectors.toSet()); Set<HostResource> slobrokHosts = admin.getSlobroks().stream().map(Slobrok::getHost).collect(Collectors.toSet()); assertEquals(3, slobrokHosts.size()); - assertTrue("Slobroks are assigned on cluster controller nodes", clusterControllerHosts.containsAll(slobrokHosts)); - assertTrue("Logserver is assigned from container nodes", containerHosts.contains(admin.getLogserver().getHost())); - assertEquals("No in-cluster config servers in a hosted environment", 0, admin.getConfigservers().size()); + assertTrue(clusterControllerHosts.containsAll(slobrokHosts), "Slobroks are assigned on cluster controller nodes"); + assertTrue(containerHosts.contains(admin.getLogserver().getHost()), "Logserver is assigned from container nodes"); + assertEquals(0, admin.getConfigservers().size(), "No in-cluster config servers in a hosted environment"); assertEquals(3, admin.getClusterControllers().getContainers().size()); // Check content clusters @@ -814,11 +810,11 @@ public class ModelProvisioningTest { assertEquals(numberOfHosts, model.getRoot().hostSystem().getHosts().size()); // Check slobroks clusters - assertEquals("Includes retired node", 1+3, model.getAdmin().getSlobroks().size()); + assertEquals(1+3, model.getAdmin().getSlobroks().size(), "Includes retired node"); assertEquals("node-1-3-50-11", model.getAdmin().getSlobroks().get(0).getHostName()); assertEquals("node-1-3-50-10", model.getAdmin().getSlobroks().get(1).getHostName()); assertEquals("node-1-3-50-08", model.getAdmin().getSlobroks().get(2).getHostName()); - assertEquals("Included in addition because it is retired", "node-1-3-50-09", model.getAdmin().getSlobroks().get(3).getHostName()); + assertEquals("node-1-3-50-09", model.getAdmin().getSlobroks().get(3).getHostName(), "Included in addition because it is retired"); } @Test @@ -839,12 +835,12 @@ public class ModelProvisioningTest { assertEquals(10+2, model.getRoot().hostSystem().getHosts().size()); // Check slobroks clusters - assertEquals("Includes retired node", 3+2, model.getAdmin().getSlobroks().size()); + assertEquals(3+2, model.getAdmin().getSlobroks().size(), "Includes retired node"); assertEquals("node-1-3-50-12", model.getAdmin().getSlobroks().get(0).getHostName()); assertEquals("node-1-3-50-11", model.getAdmin().getSlobroks().get(1).getHostName()); assertEquals("node-1-3-50-10", model.getAdmin().getSlobroks().get(2).getHostName()); - assertEquals("Included in addition because it is retired", "node-1-3-50-04", model.getAdmin().getSlobroks().get(3).getHostName()); - assertEquals("Included in addition because it is retired", "node-1-3-50-03", model.getAdmin().getSlobroks().get(4).getHostName()); + assertEquals("node-1-3-50-04", model.getAdmin().getSlobroks().get(3).getHostName(), "Included in addition because it is retired"); + assertEquals("node-1-3-50-03", model.getAdmin().getSlobroks().get(4).getHostName(), "Included in addition because it is retired"); } @Test @@ -869,14 +865,14 @@ public class ModelProvisioningTest { // Check slobroks clusters // ... from cluster default - assertEquals("Includes retired node", 7, model.getAdmin().getSlobroks().size()); + assertEquals(7, model.getAdmin().getSlobroks().size(), "Includes retired node"); assertEquals("node-1-3-50-16", model.getAdmin().getSlobroks().get(0).getHostName()); assertEquals("node-1-3-50-14", model.getAdmin().getSlobroks().get(1).getHostName()); - assertEquals("Included in addition because it is retired", "node-1-3-50-15", model.getAdmin().getSlobroks().get(2).getHostName()); + assertEquals("node-1-3-50-15", model.getAdmin().getSlobroks().get(2).getHostName(), "Included in addition because it is retired"); // ... from cluster bar assertEquals("node-1-3-50-03", model.getAdmin().getSlobroks().get(3).getHostName()); - assertEquals("Included in addition because it is retired", "node-1-3-50-05", model.getAdmin().getSlobroks().get(5).getHostName()); - assertEquals("Included in addition because it is retired", "node-1-3-50-04", model.getAdmin().getSlobroks().get(6).getHostName()); + assertEquals("node-1-3-50-05", model.getAdmin().getSlobroks().get(5).getHostName(), "Included in addition because it is retired"); + assertEquals("node-1-3-50-04", model.getAdmin().getSlobroks().get(6).getHostName(), "Included in addition because it is retired"); } @Test @@ -1255,44 +1251,48 @@ public class ModelProvisioningTest { assertEquals("bar/storage/0", cluster.getRootGroup().getNodes().get(0).getConfigId()); } - @Test(expected = IllegalArgumentException.class) + @Test public void testRequiringMoreNodesThanAreAvailable() { - String services = - "<?xml version='1.0' encoding='utf-8' ?>\n" + - "<services>" + - " <content version='1.0' id='bar'>" + - " <redundancy>1</redundancy>" + - " <documents>" + - " <document type='type1' mode='index'/>" + - " </documents>" + - " <nodes count='3' required='true'/>" + - " </content>" + - "</services>"; - - int numberOfHosts = 2; - VespaModelTester tester = new VespaModelTester(); - tester.addHosts(numberOfHosts); - tester.createModel(services, false); + assertThrows(IllegalArgumentException.class, () -> { + String services = + "<?xml version='1.0' encoding='utf-8' ?>\n" + + "<services>" + + " <content version='1.0' id='bar'>" + + " <redundancy>1</redundancy>" + + " <documents>" + + " <document type='type1' mode='index'/>" + + " </documents>" + + " <nodes count='3' required='true'/>" + + " </content>" + + "</services>"; + + int numberOfHosts = 2; + VespaModelTester tester = new VespaModelTester(); + tester.addHosts(numberOfHosts); + tester.createModel(services, false); + }); } - @Test(expected = IllegalArgumentException.class) + @Test public void testRequiredNodesAndDedicatedClusterControllers() { - String services = - "<?xml version='1.0' encoding='utf-8' ?>\n" + - "<services>" + - " <content version='1.0' id='foo'>" + - " <redundancy>1</redundancy>" + - " <documents>" + - " <document type='type1' mode='index'/>" + - " </documents>" + - " <nodes count='2' required='true'/>" + - " </content>" + - "</services>"; - - int numberOfHosts = 4; // needs 2 for foo and 3 for cluster controllers. - VespaModelTester tester = new VespaModelTester(); - tester.addHosts(numberOfHosts); - tester.createModel(services, false); + assertThrows(IllegalArgumentException.class, () -> { + String services = + "<?xml version='1.0' encoding='utf-8' ?>\n" + + "<services>" + + " <content version='1.0' id='foo'>" + + " <redundancy>1</redundancy>" + + " <documents>" + + " <document type='type1' mode='index'/>" + + " </documents>" + + " <nodes count='2' required='true'/>" + + " </content>" + + "</services>"; + + int numberOfHosts = 4; // needs 2 for foo and 3 for cluster controllers. + VespaModelTester tester = new VespaModelTester(); + tester.addHosts(numberOfHosts); + tester.createModel(services, false); + }); } @Test @@ -1654,7 +1654,7 @@ public class ModelProvisioningTest { tester.setHosted(true); tester.addHosts(4); VespaModel model = tester.createModel(new Zone(Environment.dev, RegionName.from("us-central-1")), services, true); - assertEquals("We get 1 node per cluster and no admin node apart from the dedicated cluster controller", 3, model.getHosts().size()); + assertEquals(3, model.getHosts().size(), "We get 1 node per cluster and no admin node apart from the dedicated cluster controller"); assertEquals(1, model.getContainerClusters().size()); assertEquals(1, model.getContainerClusters().get("foo").getContainers().size()); assertEquals(1, model.getContentClusters().get("bar").getRootGroup().countNodes(true)); @@ -1715,10 +1715,12 @@ public class ModelProvisioningTest { tester.addHosts(3); VespaModel model = tester.createModel(services, true); - assertEquals("Nodes in container cluster", 1, - model.getContainerClusters().get("container1").getContainers().size()); - assertEquals("Nodes in content cluster (downscaled)", 1, - model.getContentClusters().get("content").getRootGroup().getNodes().size()); + assertEquals(1, + model.getContainerClusters().get("container1").getContainers().size(), + "Nodes in container cluster"); + assertEquals(1, + model.getContentClusters().get("content").getRootGroup().getNodes().size(), + "Nodes in content cluster (downscaled)"); assertEquals(1, model.getAdmin().getSlobroks().size()); @@ -1771,10 +1773,12 @@ public class ModelProvisioningTest { tester.addHosts(3); VespaModel model = tester.createModel(services, hosts, true); - assertEquals("Nodes in container cluster", 1, - model.getContainerClusters().get("container1").getContainers().size()); - assertEquals("Nodes in content cluster (downscaled)", 1, - model.getContentClusters().get("content").getRootGroup().getNodes().size()); + assertEquals(1, + model.getContainerClusters().get("container1").getContainers().size(), + "Nodes in container cluster"); + assertEquals(1, + model.getContentClusters().get("content").getRootGroup().getNodes().size(), + "Nodes in content cluster (downscaled)"); assertEquals(1, model.getAdmin().getSlobroks().size()); @@ -2111,10 +2115,10 @@ public class ModelProvisioningTest { .collect(Collectors.groupingBy(h -> h.spec().membership().get().cluster().id().value())); tests.forEach((clusterId, stateful) -> { List<HostResource> hosts = hostsByCluster.getOrDefault(clusterId, List.of()); - assertFalse("Hosts are provisioned for '" + clusterId + "'", hosts.isEmpty()); - assertEquals("Hosts in cluster '" + clusterId + "' are " + (stateful ? "" : "not ") + "stateful", - stateful, - hosts.stream().allMatch(h -> h.spec().membership().get().cluster().isStateful())); + assertFalse(hosts.isEmpty(), "Hosts are provisioned for '" + clusterId + "'"); + assertEquals(stateful, + hosts.stream().allMatch(h -> h.spec().membership().get().cluster().isStateful()), + "Hosts in cluster '" + clusterId + "' are " + (stateful ? "" : "not ") + "stateful"); }); } @@ -2156,7 +2160,7 @@ public class ModelProvisioningTest { ZookeeperServerConfig.Builder config = new ZookeeperServerConfig.Builder(); cluster.getContainers().forEach(c -> c.getConfig(config)); cluster.getConfig(config); - assertTrue("Initial servers are not joining", config.build().server().stream().noneMatch(ZookeeperServerConfig.Server::joining)); + assertTrue(config.build().server().stream().noneMatch(ZookeeperServerConfig.Server::joining), "Initial servers are not joining"); } { VespaModel nextModel = tester.createModel(Zone.defaultZone(), servicesXml.apply(3), true, false, false, 0, Optional.of(model), new DeployState.Builder(), "node-1-3-50-04", "node-1-3-50-03"); @@ -2164,22 +2168,22 @@ public class ModelProvisioningTest { ZookeeperServerConfig.Builder config = new ZookeeperServerConfig.Builder(); cluster.getContainers().forEach(c -> c.getConfig(config)); cluster.getConfig(config); - assertEquals("New nodes are joining", - Map.of(0, false, + assertEquals(Map.of(0, false, 1, false, 2, false, 3, true, 4, true), config.build().server().stream().collect(Collectors.toMap(ZookeeperServerConfig.Server::id, - ZookeeperServerConfig.Server::joining))); - assertEquals("Retired nodes are retired", - Map.of(0, false, + ZookeeperServerConfig.Server::joining)), + "New nodes are joining"); + assertEquals(Map.of(0, false, 1, true, 2, true, 3, false, 4, false), config.build().server().stream().collect(Collectors.toMap(ZookeeperServerConfig.Server::id, - ZookeeperServerConfig.Server::retired))); + ZookeeperServerConfig.Server::retired)), + "Retired nodes are retired"); } } @@ -2322,11 +2326,12 @@ public class ModelProvisioningTest { private static void assertProvisioned(int nodeCount, ClusterSpec.Id id, ClusterSpec.Id combinedId, ClusterSpec.Type type, VespaModel model) { - assertEquals("Nodes in cluster " + id + " with type " + type + (combinedId != null ? ", combinedId " + combinedId : ""), nodeCount, + assertEquals(nodeCount, model.hostSystem().getHosts().stream() .map(h -> h.spec().membership().get().cluster()) .filter(spec -> spec.id().equals(id) && spec.type().equals(type) && spec.combinedId().equals(Optional.ofNullable(combinedId))) - .count()); + .count(), + "Nodes in cluster " + id + " with type " + type + (combinedId != null ? ", combinedId " + combinedId : "")); } private static void assertProvisioned(int nodeCount, ClusterSpec.Id id, ClusterSpec.Type type, VespaModel model) { diff --git a/config-model/src/test/java/com/yahoo/config/model/provision/SingleNodeProvisionerTest.java b/config-model/src/test/java/com/yahoo/config/model/provision/SingleNodeProvisionerTest.java index 446350a734f..00acc715a39 100644 --- a/config-model/src/test/java/com/yahoo/config/model/provision/SingleNodeProvisionerTest.java +++ b/config-model/src/test/java/com/yahoo/config/model/provision/SingleNodeProvisionerTest.java @@ -6,7 +6,7 @@ import com.yahoo.config.model.api.HostProvisioner; import com.yahoo.config.model.test.MockApplicationPackage; import com.yahoo.config.provision.HostSpec; import com.yahoo.vespa.model.VespaModel; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.xml.sax.SAXException; import java.io.IOException; @@ -21,7 +21,7 @@ import java.util.Set; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author hmusum @@ -29,7 +29,7 @@ import static org.junit.Assert.assertTrue; public class SingleNodeProvisionerTest { @Test - public void require_basic_works() { + void require_basic_works() { SingleNodeProvisioner hostProvisioner = new SingleNodeProvisioner(); // 4 services, 2 host aliases, mapping to 2 host. @@ -56,16 +56,16 @@ public class SingleNodeProvisionerTest { } @Test - public void require_allocate_clustermembership_works() throws IOException, SAXException { + void require_allocate_clustermembership_works() throws IOException, SAXException { String servicesXml = "<services version='1.0'>" - + " <admin version='3.0'>" - + " <nodes count='1' />" - + " </admin>" - + " <container version='1.0'>" - + " <search />" - + " <nodes count='1' />" - + " </container>" - + "</services>"; + + " <admin version='3.0'>" + + " <nodes count='1' />" + + " </admin>" + + " <container version='1.0'>" + + " <search />" + + " <nodes count='1' />" + + " </container>" + + "</services>"; ApplicationPackage app = new MockApplicationPackage.Builder().withServices(servicesXml).build(); VespaModel model = new VespaModel(app); assertThat(model.getHosts().size(), is(1)); diff --git a/config-model/src/test/java/com/yahoo/document/test/SDDocumentTypeTestCase.java b/config-model/src/test/java/com/yahoo/document/test/SDDocumentTypeTestCase.java index 4a3d85c6a76..f484a92e341 100644 --- a/config-model/src/test/java/com/yahoo/document/test/SDDocumentTypeTestCase.java +++ b/config-model/src/test/java/com/yahoo/document/test/SDDocumentTypeTestCase.java @@ -10,12 +10,12 @@ import com.yahoo.schema.document.SDDocumentType; import com.yahoo.schema.document.SDField; import com.yahoo.schema.parser.ParseException; import com.yahoo.vespa.model.test.utils.DeployLoggerStub; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Iterator; import static com.yahoo.config.model.test.TestUtil.joinLines; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; /** * @author Thomas Gundersen @@ -25,7 +25,7 @@ public class SDDocumentTypeTestCase extends AbstractSchemaTestCase { // Verify that we can register and retrieve fields. @Test - public void testSetGet() { + void testSetGet() { SDDocumentType docType = new SDDocumentType("testdoc"); docType.addField("Bongle", DataType.STRING); docType.addField("nalle", DataType.INT); @@ -36,7 +36,7 @@ public class SDDocumentTypeTestCase extends AbstractSchemaTestCase { } @Test - public void testInheritance() { + void testInheritance() { SDDocumentType child = new SDDocumentType("child"); Iterator<SDDocumentType> inherited = child.getInheritedTypes().iterator(); assertTrue(inherited.hasNext()); @@ -102,23 +102,23 @@ public class SDDocumentTypeTestCase extends AbstractSchemaTestCase { } @Test - public void testStructInheritance() throws ParseException { + void testStructInheritance() throws ParseException { String schemaLines = joinLines( "schema test {" + - " document test {" + - " struct parent_struct {" + - " field parent_struct_field_1 type string {}" + - " }" + - " struct child_struct inherits parent_struct {" + - " field child_struct_field_1 type string {}" + - " }" + - " field child_array type array<child_struct> {" + - " indexing: summary\n" + - " struct-field child_struct_field_1 { indexing: attribute }" + - " struct-field parent_struct_field_1 { indexing: attribute }" + - " }" + - " }" + - "}"); + " document test {" + + " struct parent_struct {" + + " field parent_struct_field_1 type string {}" + + " }" + + " struct child_struct inherits parent_struct {" + + " field child_struct_field_1 type string {}" + + " }" + + " field child_array type array<child_struct> {" + + " indexing: summary\n" + + " struct-field child_struct_field_1 { indexing: attribute }" + + " struct-field parent_struct_field_1 { indexing: attribute }" + + " }" + + " }" + + "}"); ApplicationBuilder builder = new ApplicationBuilder(new DeployLoggerStub()); builder.addSchema(schemaLines); diff --git a/config-model/src/test/java/com/yahoo/document/test/SDFieldTestCase.java b/config-model/src/test/java/com/yahoo/document/test/SDFieldTestCase.java index 6a8645195a5..6a9565d4d16 100644 --- a/config-model/src/test/java/com/yahoo/document/test/SDFieldTestCase.java +++ b/config-model/src/test/java/com/yahoo/document/test/SDFieldTestCase.java @@ -4,9 +4,9 @@ package com.yahoo.document.test; import com.yahoo.document.DataType; import com.yahoo.schema.AbstractSchemaTestCase; import com.yahoo.schema.document.SDDocumentType; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Thomas Gundersen @@ -14,7 +14,7 @@ import static org.junit.Assert.fail; public class SDFieldTestCase extends AbstractSchemaTestCase { @Test - public void testIdSettingConflict() { + void testIdSettingConflict() { SDDocumentType doc = new SDDocumentType("testdoc"); doc.addField("one", DataType.STRING, 60); @@ -30,7 +30,7 @@ public class SDFieldTestCase extends AbstractSchemaTestCase { } @Test - public void testSettingReservedId() { + void testSettingReservedId() { SDDocumentType doc = new SDDocumentType("testdoc"); try { doc.addField("one", DataType.STRING, 127); diff --git a/config-model/src/test/java/com/yahoo/schema/AnnotationReferenceTestCase.java b/config-model/src/test/java/com/yahoo/schema/AnnotationReferenceTestCase.java index dbe827ed67f..18ff1fd8536 100644 --- a/config-model/src/test/java/com/yahoo/schema/AnnotationReferenceTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/AnnotationReferenceTestCase.java @@ -7,11 +7,11 @@ import com.yahoo.document.Field; import com.yahoo.document.annotation.AnnotationReferenceDataType; import com.yahoo.schema.document.SDDocumentType; import com.yahoo.config.model.deploy.TestProperties; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static com.yahoo.config.model.test.TestUtil.joinLines; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author arnej @@ -38,9 +38,9 @@ public class AnnotationReferenceTestCase { " }", " }", "}"); - + @Test - public void noAnnotationReferenceInDocument() throws Exception { + void noAnnotationReferenceInDocument() throws Exception { var builder = new ApplicationBuilder(new TestProperties()); builder.addSchema(sd); builder.build(true); @@ -49,7 +49,7 @@ public class AnnotationReferenceTestCase { var complex = doc.findAnnotation("complex"); var dt = complex.getDataType(); assertTrue(dt instanceof StructDataType); - var struct = (StructDataType)dt; + var struct = (StructDataType) dt; var field = struct.getField("owner"); assertTrue(field.getDataType() instanceof AnnotationReferenceDataType); } diff --git a/config-model/src/test/java/com/yahoo/schema/ArraysTestCase.java b/config-model/src/test/java/com/yahoo/schema/ArraysTestCase.java index aab79617556..a03bf3bf8de 100644 --- a/config-model/src/test/java/com/yahoo/schema/ArraysTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/ArraysTestCase.java @@ -6,12 +6,12 @@ import com.yahoo.document.CollectionDataType; import com.yahoo.document.DataType; import com.yahoo.schema.document.SDField; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * tests importing of document containing array type fields @@ -21,15 +21,15 @@ import static org.junit.Assert.assertTrue; public class ArraysTestCase extends AbstractSchemaTestCase { @Test - public void testArrayImporting() throws IOException, ParseException { + void testArrayImporting() throws IOException, ParseException { Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/arrays.sd"); SDField tags = (SDField) schema.getDocument().getField("tags"); - assertEquals(DataType.STRING, ((CollectionDataType)tags.getDataType()).getNestedType()); + assertEquals(DataType.STRING, ((CollectionDataType) tags.getDataType()).getNestedType()); SDField ratings = (SDField) schema.getDocument().getField("ratings"); assertTrue(ratings.getDataType() instanceof ArrayDataType); - assertEquals(DataType.INT, ((ArrayDataType)ratings.getDataType()).getNestedType()); + assertEquals(DataType.INT, ((ArrayDataType) ratings.getDataType()).getNestedType()); } } diff --git a/config-model/src/test/java/com/yahoo/schema/ArraysWeightedSetsTestCase.java b/config-model/src/test/java/com/yahoo/schema/ArraysWeightedSetsTestCase.java index 57331bea6bd..7d72cce1401 100644 --- a/config-model/src/test/java/com/yahoo/schema/ArraysWeightedSetsTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/ArraysWeightedSetsTestCase.java @@ -6,10 +6,10 @@ import com.yahoo.document.CollectionDataType; import com.yahoo.document.DataType; import com.yahoo.document.WeightedSetDataType; import com.yahoo.schema.document.SDField; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * tests importing of document containing array type fields and weighted set type fields, new syntax. @@ -18,24 +18,24 @@ import static org.junit.Assert.assertTrue; */ public class ArraysWeightedSetsTestCase extends AbstractSchemaTestCase { @Test - public void testArrayWeightedSetsImporting() throws java.io.IOException, com.yahoo.schema.parser.ParseException { + void testArrayWeightedSetsImporting() throws java.io.IOException, com.yahoo.schema.parser.ParseException { Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/arraysweightedsets.sd"); SDField tags = (SDField) schema.getDocument().getField("tags"); assertTrue(tags.getDataType() instanceof ArrayDataType); - assertEquals(DataType.STRING, ((CollectionDataType)tags.getDataType()).getNestedType()); + assertEquals(DataType.STRING, ((CollectionDataType) tags.getDataType()).getNestedType()); SDField ratings = (SDField) schema.getDocument().getField("ratings"); assertTrue(ratings.getDataType() instanceof ArrayDataType); - assertEquals(DataType.INT, ((CollectionDataType)ratings.getDataType()).getNestedType()); + assertEquals(DataType.INT, ((CollectionDataType) ratings.getDataType()).getNestedType()); SDField flags = (SDField) schema.getDocument().getField("flags"); assertTrue(flags.getDataType() instanceof WeightedSetDataType); - assertEquals(DataType.STRING, ((CollectionDataType)flags.getDataType()).getNestedType()); + assertEquals(DataType.STRING, ((CollectionDataType) flags.getDataType()).getNestedType()); SDField banners = (SDField) schema.getDocument().getField("banners"); assertTrue(banners.getDataType() instanceof WeightedSetDataType); - assertEquals(DataType.INT, ((CollectionDataType)banners.getDataType()).getNestedType()); + assertEquals(DataType.INT, ((CollectionDataType) banners.getDataType()).getNestedType()); } } diff --git a/config-model/src/test/java/com/yahoo/schema/AttributeSettingsTestCase.java b/config-model/src/test/java/com/yahoo/schema/AttributeSettingsTestCase.java index 885cc385dfa..54fb6b0fb52 100644 --- a/config-model/src/test/java/com/yahoo/schema/AttributeSettingsTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/AttributeSettingsTestCase.java @@ -10,16 +10,12 @@ import com.yahoo.schema.parser.ParseException; import com.yahoo.tensor.TensorType; import com.yahoo.vespa.config.search.AttributesConfig; import com.yahoo.vespa.configdefinition.IlscriptsConfig; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; /** * Attribute settings @@ -29,10 +25,10 @@ import static org.junit.Assert.fail; public class AttributeSettingsTestCase extends AbstractSchemaTestCase { @Test - public void testAttributeSettings() throws IOException, ParseException { + void testAttributeSettings() throws IOException, ParseException { Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/attributesettings.sd"); - SDField f1=(SDField) schema.getDocument().getField("f1"); + SDField f1 = (SDField) schema.getDocument().getField("f1"); assertEquals(1, f1.getAttributes().size()); Attribute a1 = f1.getAttributes().get(f1.getName()); assertEquals(Attribute.Type.LONG, a1.getType()); @@ -42,7 +38,7 @@ public class AttributeSettingsTestCase extends AbstractSchemaTestCase { assertFalse(a1.isRemoveIfZero()); assertFalse(a1.isCreateIfNonExistent()); - SDField f2=(SDField) schema.getDocument().getField("f2"); + SDField f2 = (SDField) schema.getDocument().getField("f2"); assertEquals(1, f2.getAttributes().size()); Attribute a2 = f2.getAttributes().get(f2.getName()); assertEquals(Attribute.Type.LONG, a2.getType()); @@ -52,7 +48,7 @@ public class AttributeSettingsTestCase extends AbstractSchemaTestCase { assertFalse(a2.isRemoveIfZero()); assertFalse(a2.isCreateIfNonExistent()); assertEquals("f2", f2.getAliasToName().get("f2alias")); - SDField f3=(SDField) schema.getDocument().getField("f3"); + SDField f3 = (SDField) schema.getDocument().getField("f3"); assertEquals(1, f3.getAttributes().size()); assertEquals("f3", f3.getAliasToName().get("f3alias")); @@ -103,7 +99,7 @@ public class AttributeSettingsTestCase extends AbstractSchemaTestCase { } @Test - public void requireThatFastAccessCanBeSet() throws IOException, ParseException { + void requireThatFastAccessCanBeSet() throws IOException, ParseException { Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/attributesettings.sd"); SDField field = (SDField) schema.getDocument().getField("fast_access"); assertEquals(1, field.getAttributes().size()); @@ -125,7 +121,7 @@ public class AttributeSettingsTestCase extends AbstractSchemaTestCase { } @Test - public void requireThatPagedIsDefaultOff() throws ParseException { + void requireThatPagedIsDefaultOff() throws ParseException { Attribute attr = getAttributeF( "search test {\n" + " document test { \n" + @@ -136,8 +132,9 @@ public class AttributeSettingsTestCase extends AbstractSchemaTestCase { "}\n"); assertFalse(attr.isPaged()); } + @Test - public void requireThatPagedCanBeSet() throws ParseException { + void requireThatPagedCanBeSet() throws ParseException { Attribute attr = getAttributeF( "search test {\n" + " document test { \n" + @@ -151,29 +148,29 @@ public class AttributeSettingsTestCase extends AbstractSchemaTestCase { } @Test - public void requireThatMutableIsDefaultOff() throws ParseException { + void requireThatMutableIsDefaultOff() throws ParseException { Attribute attr = getAttributeF( "search test {\n" + - " document test { \n" + - " field f type int { \n" + - " indexing: attribute \n" + - " }\n" + - " }\n" + - "}\n"); + " document test { \n" + + " field f type int { \n" + + " indexing: attribute \n" + + " }\n" + + " }\n" + + "}\n"); assertFalse(attr.isMutable()); } @Test - public void requireThatMutableCanNotbeSetInDocument() throws ParseException { + void requireThatMutableCanNotbeSetInDocument() throws ParseException { try { getSchema("search test {\n" + - " document test {\n" + - " field f type int {\n" + - " indexing: attribute\n" + - " attribute: mutable\n" + - " }\n" + - " }\n" + - "}\n"); + " document test {\n" + + " field f type int {\n" + + " indexing: attribute\n" + + " attribute: mutable\n" + + " }\n" + + " }\n" + + "}\n"); fail(); } catch (IllegalArgumentException e) { assertEquals("Field 'f' in 'test' can not be marked mutable as it is inside the document clause.", e.getMessage()); @@ -181,7 +178,7 @@ public class AttributeSettingsTestCase extends AbstractSchemaTestCase { } @Test - public void requireThatMutableExtraFieldCanBeSet() throws ParseException { + void requireThatMutableExtraFieldCanBeSet() throws ParseException { Attribute attr = getAttributeF( "search test {\n" + " document test { \n" + @@ -216,7 +213,7 @@ public class AttributeSettingsTestCase extends AbstractSchemaTestCase { } @Test - public void requireThatMutableConfigIsProperlyPropagated() throws ParseException { + void requireThatMutableConfigIsProperlyPropagated() throws ParseException { AttributeFields attributes = new AttributeFields(getSearchWithMutables()); AttributesConfig.Builder builder = new AttributesConfig.Builder(); attributes.getConfig(builder, AttributeFields.FieldSet.ALL, 13333, true); @@ -232,7 +229,7 @@ public class AttributeSettingsTestCase extends AbstractSchemaTestCase { } @Test - public void requireMaxUnCommittedMemoryIsProperlyPropagated() throws ParseException { + void requireMaxUnCommittedMemoryIsProperlyPropagated() throws ParseException { AttributeFields attributes = new AttributeFields(getSearchWithMutables()); AttributesConfig.Builder builder = new AttributesConfig.Builder(); attributes.getConfig(builder, AttributeFields.FieldSet.ALL, 13333, true); @@ -260,7 +257,7 @@ public class AttributeSettingsTestCase extends AbstractSchemaTestCase { } @Test - public void requireEnableBitVectorsIsProperlyPropagated() throws ParseException { + void requireEnableBitVectorsIsProperlyPropagated() throws ParseException { Schema schema = getSchema( "search test {\n" + " document test { \n" + @@ -278,7 +275,7 @@ public class AttributeSettingsTestCase extends AbstractSchemaTestCase { } @Test - public void requireThatMutableIsAllowedThroughIndexing() throws ParseException { + void requireThatMutableIsAllowedThroughIndexing() throws ParseException { IndexingScript script = new IndexingScript(getSearchWithMutables()); IlscriptsConfig.Builder builder = new IlscriptsConfig.Builder(); script.getConfig(builder); @@ -293,7 +290,7 @@ public class AttributeSettingsTestCase extends AbstractSchemaTestCase { } @Test - public void attribute_convert_to_array_copies_internal_state() { + void attribute_convert_to_array_copies_internal_state() { StructDataType refType = new StructDataType("my_struct"); Attribute single = new Attribute("foo", Attribute.Type.STRING, Attribute.CollectionType.SINGLE, Optional.of(TensorType.fromSpec("tensor(x{})")), Optional.of(refType)); diff --git a/config-model/src/test/java/com/yahoo/schema/CommentTestCase.java b/config-model/src/test/java/com/yahoo/schema/CommentTestCase.java index 4df4ead171b..ca726d8cd57 100644 --- a/config-model/src/test/java/com/yahoo/schema/CommentTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/CommentTestCase.java @@ -3,11 +3,11 @@ package com.yahoo.schema; import com.yahoo.schema.document.SDField; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests comment handling @@ -17,11 +17,11 @@ import static org.junit.Assert.assertEquals; public class CommentTestCase extends AbstractSchemaTestCase { @Test - public void testComments() throws IOException, ParseException { + void testComments() throws IOException, ParseException { Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/comment.sd"); SDField field = schema.getConcreteField("a"); assertEquals("{ input a | tokenize normalize stem:\"BEST\" | summary a | index a; }", - field.getIndexingScript().toString()); + field.getIndexingScript().toString()); } } diff --git a/config-model/src/test/java/com/yahoo/schema/DiversityTestCase.java b/config-model/src/test/java/com/yahoo/schema/DiversityTestCase.java index 482bc877081..06b38224c37 100644 --- a/config-model/src/test/java/com/yahoo/schema/DiversityTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/DiversityTestCase.java @@ -3,17 +3,17 @@ package com.yahoo.schema; import com.yahoo.search.query.ranking.Diversity; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; -import static org.junit.Assert.fail; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author baldersheim */ public class DiversityTestCase { @Test - public void testDiversity() throws ParseException { + void testDiversity() throws ParseException { RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry); builder.addSchema( @@ -58,8 +58,9 @@ public class DiversityTestCase { private static String getMessagePrefix() { return "In search definition 'test', rank-profile 'parent': diversity attribute 'b' "; } + @Test - public void requireSingleNumericOrString() throws ParseException { + void requireSingleNumericOrString() throws ParseException { ApplicationBuilder builder = getSearchBuilder("field b type predicate { indexing: attribute }"); try { @@ -71,7 +72,7 @@ public class DiversityTestCase { } @Test - public void requireSingle() throws ParseException { + void requireSingle() throws ParseException { ApplicationBuilder builder = getSearchBuilder("field b type array<int> { indexing: attribute }"); try { diff --git a/config-model/src/test/java/com/yahoo/schema/DocumentGraphValidatorTest.java b/config-model/src/test/java/com/yahoo/schema/DocumentGraphValidatorTest.java index ef4d8e05540..ccfa5c51a16 100644 --- a/config-model/src/test/java/com/yahoo/schema/DocumentGraphValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/schema/DocumentGraphValidatorTest.java @@ -6,9 +6,7 @@ import com.yahoo.documentmodel.NewDocumentReferenceDataType; import com.yahoo.schema.document.SDDocumentType; import com.yahoo.schema.document.SDField; import com.yahoo.schema.document.TemporarySDField; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Collections; @@ -17,20 +15,15 @@ import java.util.List; import java.util.Map; import static java.util.stream.Collectors.toList; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; /** * @author bjorncs */ public class DocumentGraphValidatorTest { - @SuppressWarnings("deprecation") - @Rule - public final ExpectedException exceptionRule = ExpectedException.none(); - @Test - public void simple_ref_dag_is_allowed() { + void simple_ref_dag_is_allowed() { Schema advertiserSchema = createSearchWithName("advertiser"); Schema campaignSchema = createSearchWithName("campaign"); Schema adSchema = createSearchWithName("ad"); @@ -42,7 +35,7 @@ public class DocumentGraphValidatorTest { } @Test - public void simple_inheritance_dag_is_allowed() { + void simple_inheritance_dag_is_allowed() { Schema grandfather = createSearchWithName("grandfather"); Schema father = createSearchWithName("father", grandfather); Schema son = createSearchWithName("son", father); @@ -52,7 +45,7 @@ public class DocumentGraphValidatorTest { } @Test - public void complex_dag_is_allowed() { + void complex_dag_is_allowed() { Schema grandfather = createSearchWithName("grandfather"); Schema father = createSearchWithName("father", grandfather); Schema mother = createSearchWithName("mother", grandfather); @@ -70,55 +63,59 @@ public class DocumentGraphValidatorTest { } @Test - public void ref_cycle_is_forbidden() { - Schema schema1 = createSearchWithName("doc1"); - Schema schema2 = createSearchWithName("doc2"); - Schema schema3 = createSearchWithName("doc3"); - createDocumentReference(schema1, schema2, "ref_2"); - createDocumentReference(schema2, schema3, "ref_3"); - createDocumentReference(schema3, schema1, "ref_1"); - - DocumentGraphValidator validator = new DocumentGraphValidator(); - exceptionRule.expect(DocumentGraphValidator.DocumentGraphException.class); - exceptionRule.expectMessage("Document dependency cycle detected: doc1->doc2->doc3->doc1."); - validator.validateDocumentGraph(documentListOf(schema1, schema2, schema3)); + void ref_cycle_is_forbidden() { + Throwable exception = assertThrows(DocumentGraphValidator.DocumentGraphException.class, () -> { + Schema schema1 = createSearchWithName("doc1"); + Schema schema2 = createSearchWithName("doc2"); + Schema schema3 = createSearchWithName("doc3"); + createDocumentReference(schema1, schema2, "ref_2"); + createDocumentReference(schema2, schema3, "ref_3"); + createDocumentReference(schema3, schema1, "ref_1"); + + DocumentGraphValidator validator = new DocumentGraphValidator(); + validator.validateDocumentGraph(documentListOf(schema1, schema2, schema3)); + }); + assertTrue(exception.getMessage().contains("Document dependency cycle detected: doc1->doc2->doc3->doc1.")); } @Test - public void inherit_cycle_is_forbidden() { - Schema schema1 = createSearchWithName("doc1"); - Schema schema2 = createSearchWithName("doc2", schema1); - Schema schema3 = createSearchWithName("doc3", schema2); - schema1.getDocument().inherit(schema3.getDocument()); - - DocumentGraphValidator validator = new DocumentGraphValidator(); - exceptionRule.expect(DocumentGraphValidator.DocumentGraphException.class); - exceptionRule.expectMessage("Document dependency cycle detected: doc1->doc3->doc2->doc1."); - validator.validateDocumentGraph(documentListOf(schema1, schema2, schema3)); + void inherit_cycle_is_forbidden() { + Throwable exception = assertThrows(DocumentGraphValidator.DocumentGraphException.class, () -> { + Schema schema1 = createSearchWithName("doc1"); + Schema schema2 = createSearchWithName("doc2", schema1); + Schema schema3 = createSearchWithName("doc3", schema2); + schema1.getDocument().inherit(schema3.getDocument()); + + DocumentGraphValidator validator = new DocumentGraphValidator(); + validator.validateDocumentGraph(documentListOf(schema1, schema2, schema3)); + }); + assertTrue(exception.getMessage().contains("Document dependency cycle detected: doc1->doc3->doc2->doc1.")); } @Test - public void combined_inherit_and_ref_cycle_is_forbidden() { - Schema schema1 = createSearchWithName("doc1"); - Schema schema2 = createSearchWithName("doc2", schema1); - Schema schema3 = createSearchWithName("doc3", schema2); - createDocumentReference(schema1, schema3, "ref_1"); - - DocumentGraphValidator validator = new DocumentGraphValidator(); - exceptionRule.expect(DocumentGraphValidator.DocumentGraphException.class); - exceptionRule.expectMessage("Document dependency cycle detected: doc1->doc3->doc2->doc1."); - validator.validateDocumentGraph(documentListOf(schema1, schema2, schema3)); + void combined_inherit_and_ref_cycle_is_forbidden() { + Throwable exception = assertThrows(DocumentGraphValidator.DocumentGraphException.class, () -> { + Schema schema1 = createSearchWithName("doc1"); + Schema schema2 = createSearchWithName("doc2", schema1); + Schema schema3 = createSearchWithName("doc3", schema2); + createDocumentReference(schema1, schema3, "ref_1"); + + DocumentGraphValidator validator = new DocumentGraphValidator(); + validator.validateDocumentGraph(documentListOf(schema1, schema2, schema3)); + }); + assertTrue(exception.getMessage().contains("Document dependency cycle detected: doc1->doc3->doc2->doc1.")); } @Test - public void self_reference_is_forbidden() { - Schema adSchema = createSearchWithName("ad"); - createDocumentReference(adSchema, adSchema, "ad_ref"); + void self_reference_is_forbidden() { + Throwable exception = assertThrows(DocumentGraphValidator.DocumentGraphException.class, () -> { + Schema adSchema = createSearchWithName("ad"); + createDocumentReference(adSchema, adSchema, "ad_ref"); - DocumentGraphValidator validator = new DocumentGraphValidator(); - exceptionRule.expect(DocumentGraphValidator.DocumentGraphException.class); - exceptionRule.expectMessage("Document dependency cycle detected: ad->ad."); - validator.validateDocumentGraph(documentListOf(adSchema)); + DocumentGraphValidator validator = new DocumentGraphValidator(); + validator.validateDocumentGraph(documentListOf(adSchema)); + }); + assertTrue(exception.getMessage().contains("Document dependency cycle detected: ad->ad.")); } /** @@ -126,7 +123,7 @@ public class DocumentGraphValidatorTest { * produces a stack overflow before getting to graph validation. */ @Test - public void self_inheritance_forbidden() { + void self_inheritance_forbidden() { try { Schema adSchema = createSearchWithName("ad"); SDDocumentType document = adSchema.getDocument(); diff --git a/config-model/src/test/java/com/yahoo/schema/DocumentReferenceResolverTest.java b/config-model/src/test/java/com/yahoo/schema/DocumentReferenceResolverTest.java index 1592060f466..bcf8c6045b3 100644 --- a/config-model/src/test/java/com/yahoo/schema/DocumentReferenceResolverTest.java +++ b/config-model/src/test/java/com/yahoo/schema/DocumentReferenceResolverTest.java @@ -6,17 +6,13 @@ import com.yahoo.document.DataType; import com.yahoo.documentmodel.NewDocumentReferenceDataType; import com.yahoo.schema.document.SDDocumentType; import com.yahoo.schema.document.SDField; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; import java.util.Map; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * @author bjorncs @@ -25,12 +21,9 @@ public class DocumentReferenceResolverTest { private static final String BAR = "bar"; private static final String FOO = "foo"; - @SuppressWarnings("deprecation") - @Rule - public final ExpectedException exceptionRule = ExpectedException.none(); @Test - public void reference_from_one_document_to_another_is_resolved() { + void reference_from_one_document_to_another_is_resolved() { // Create bar document with no fields Schema barSchema = new Schema(BAR, MockApplicationPackage.createEmpty()); SDDocumentType barDocument = new SDDocumentType(BAR, barSchema); @@ -40,7 +33,7 @@ public class DocumentReferenceResolverTest { Schema fooSchema = new Schema(FOO, MockApplicationPackage.createEmpty()); SDDocumentType fooDocument = new SDDocumentType("foo", fooSchema); SDField fooRefToBarField = new SDField - (fooDocument, "bar_ref", new NewDocumentReferenceDataType(barDocument.getDocumentType())); + (fooDocument, "bar_ref", new NewDocumentReferenceDataType(barDocument.getDocumentType())); AttributeUtils.addAttributeAspect(fooRefToBarField); SDField irrelevantField = new SDField(fooDocument, "irrelevant_stuff", DataType.INT); fooDocument.addField(fooRefToBarField); @@ -59,45 +52,44 @@ public class DocumentReferenceResolverTest { @SuppressWarnings("deprecation") @Test - public void throws_user_friendly_exception_if_referenced_document_does_not_exist() { - // Create foo document with document reference to non-existing document bar - Schema fooSchema = new Schema(FOO, MockApplicationPackage.createEmpty()); - SDDocumentType fooDocument = new SDDocumentType("foo", fooSchema); - SDField fooRefToBarField = new SDField( - fooDocument, - "bar_ref", NewDocumentReferenceDataType.forDocumentName("bar")); - AttributeUtils.addAttributeAspect(fooRefToBarField); - fooDocument.addField(fooRefToBarField); - fooSchema.addDocument(fooDocument); - - DocumentReferenceResolver resolver = new DocumentReferenceResolver(singletonList(fooSchema)); - - exceptionRule.expect(IllegalArgumentException.class); - exceptionRule.expectMessage( - "Invalid document reference 'bar_ref': Could not find document type 'bar'"); - resolver.resolveReferences(fooDocument); + void throws_user_friendly_exception_if_referenced_document_does_not_exist() { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + // Create foo document with document reference to non-existing document bar + Schema fooSchema = new Schema(FOO, MockApplicationPackage.createEmpty()); + SDDocumentType fooDocument = new SDDocumentType("foo", fooSchema); + SDField fooRefToBarField = new SDField( + fooDocument, + "bar_ref", NewDocumentReferenceDataType.forDocumentName("bar")); + AttributeUtils.addAttributeAspect(fooRefToBarField); + fooDocument.addField(fooRefToBarField); + fooSchema.addDocument(fooDocument); + + DocumentReferenceResolver resolver = new DocumentReferenceResolver(singletonList(fooSchema)); + resolver.resolveReferences(fooDocument); + }); + assertTrue(exception.getMessage().contains("Invalid document reference 'bar_ref': Could not find document type 'bar'")); } @Test - public void throws_exception_if_reference_is_not_an_attribute() { - // Create bar document with no fields - Schema barSchema = new Schema(BAR, MockApplicationPackage.createEmpty()); - SDDocumentType barDocument = new SDDocumentType("bar", barSchema); - barSchema.addDocument(barDocument); - - // Create foo document with document reference to bar - Schema fooSchema = new Schema(FOO, MockApplicationPackage.createEmpty()); - SDDocumentType fooDocument = new SDDocumentType("foo", fooSchema); - SDField fooRefToBarField = new SDField - (fooDocument, "bar_ref", new NewDocumentReferenceDataType(barDocument.getDocumentType())); - fooDocument.addField(fooRefToBarField); - fooSchema.addDocument(fooDocument); - - DocumentReferenceResolver resolver = new DocumentReferenceResolver(asList(fooSchema, barSchema)); - exceptionRule.expect(IllegalArgumentException.class); - exceptionRule.expectMessage( - "The field 'bar_ref' is an invalid document reference. The field must be an attribute."); - resolver.resolveReferences(fooDocument); + void throws_exception_if_reference_is_not_an_attribute() { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + // Create bar document with no fields + Schema barSchema = new Schema(BAR, MockApplicationPackage.createEmpty()); + SDDocumentType barDocument = new SDDocumentType("bar", barSchema); + barSchema.addDocument(barDocument); + + // Create foo document with document reference to bar + Schema fooSchema = new Schema(FOO, MockApplicationPackage.createEmpty()); + SDDocumentType fooDocument = new SDDocumentType("foo", fooSchema); + SDField fooRefToBarField = new SDField + (fooDocument, "bar_ref", new NewDocumentReferenceDataType(barDocument.getDocumentType())); + fooDocument.addField(fooRefToBarField); + fooSchema.addDocument(fooDocument); + + DocumentReferenceResolver resolver = new DocumentReferenceResolver(asList(fooSchema, barSchema)); + resolver.resolveReferences(fooDocument); + }); + assertTrue(exception.getMessage().contains("The field 'bar_ref' is an invalid document reference. The field must be an attribute.")); } } diff --git a/config-model/src/test/java/com/yahoo/schema/FeatureNamesTestCase.java b/config-model/src/test/java/com/yahoo/schema/FeatureNamesTestCase.java index bff4b434408..0bfd1b1e201 100644 --- a/config-model/src/test/java/com/yahoo/schema/FeatureNamesTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/FeatureNamesTestCase.java @@ -1,15 +1,13 @@ // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.schema; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import java.util.function.Function; import java.util.regex.Pattern; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * Tests rank feature names. @@ -19,7 +17,7 @@ import static org.junit.Assert.assertTrue; public class FeatureNamesTestCase { @Test - public void testArgument() { + void testArgument() { assertFalse(FeatureNames.argumentOf("foo(bar)").isPresent()); assertFalse(FeatureNames.argumentOf("foo(bar.baz)").isPresent()); assertEquals("bar", FeatureNames.argumentOf("query(bar)").get()); @@ -31,25 +29,25 @@ public class FeatureNamesTestCase { } @Test - public void testConstantFeature() { + void testConstantFeature() { assertEquals("constant(foo)", - FeatureNames.asConstantFeature("foo").toString()); + FeatureNames.asConstantFeature("foo").toString()); } @Test - public void testAttributeFeature() { + void testAttributeFeature() { assertEquals("attribute(foo)", - FeatureNames.asAttributeFeature("foo").toString()); + FeatureNames.asAttributeFeature("foo").toString()); } @Test - public void testQueryFeature() { + void testQueryFeature() { assertEquals("query(\"foo.bar\")", - FeatureNames.asQueryFeature("foo.bar").toString()); + FeatureNames.asQueryFeature("foo.bar").toString()); } @Test - public void testLegalFeatureNames() { + void testLegalFeatureNames() { assertTrue(FeatureNames.notNeedQuotes("_")); assertFalse(FeatureNames.notNeedQuotes("-")); assertTrue(FeatureNames.notNeedQuotes("_-")); @@ -57,15 +55,15 @@ public class FeatureNamesTestCase { assertFalse(FeatureNames.notNeedQuotes("0_-azAZxy98-_+")); } - @Test - @Ignore /* * Unignore to verify performance * 2021/09/05 performance was a factor of 5.25 * 'Identifier handcoded validity check took 4301ms * Identifier regexp validity check took 22609ms' */ - public void benchMarkPatternMatching() { + @Test + @Disabled + void benchMarkPatternMatching() { Pattern identifierRegexp = Pattern.compile("[A-Za-z0-9_][A-Za-z0-9_-]*"); String[] strings = new String[1000]; for (int i = 0; i < strings.length; i++) { diff --git a/config-model/src/test/java/com/yahoo/schema/FieldOfTypeDocumentTestCase.java b/config-model/src/test/java/com/yahoo/schema/FieldOfTypeDocumentTestCase.java index 4a590288d53..ed4cb70c3c7 100644 --- a/config-model/src/test/java/com/yahoo/schema/FieldOfTypeDocumentTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/FieldOfTypeDocumentTestCase.java @@ -8,13 +8,14 @@ import com.yahoo.document.DocumentTypeManagerConfigurer; import com.yahoo.document.Field; import com.yahoo.document.config.DocumentmanagerConfig; import com.yahoo.schema.derived.Deriver; -import org.junit.Test; +import org.junit.jupiter.api.Test; + import java.io.IOException; import java.util.ArrayList; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; /** * @author Einar M R Rosenvinge @@ -22,14 +23,14 @@ import static org.junit.Assert.assertSame; public class FieldOfTypeDocumentTestCase extends AbstractSchemaTestCase { @Test - public void testDocument() throws IOException { + void testDocument() throws IOException { List<String> sds = new ArrayList<>(); sds.add("src/test/examples/music.sd"); sds.add("src/test/examples/fieldoftypedocument.sd"); DocumentmanagerConfig.Builder value = Deriver.getDocumentManagerConfig(sds); assertConfigFile("src/test/examples/fieldoftypedocument.cfg", - new DocumentmanagerConfig(value).toString() + "\n"); + new DocumentmanagerConfig(value).toString() + "\n"); DocumentTypeManager manager = new DocumentTypeManager(); DocumentTypeManagerConfigurer.configure(manager, "raw:" + new DocumentmanagerConfig(value).toString()); diff --git a/config-model/src/test/java/com/yahoo/schema/ImportedFieldsEnumeratorTest.java b/config-model/src/test/java/com/yahoo/schema/ImportedFieldsEnumeratorTest.java index 92d11b3a18a..092891f1ea1 100644 --- a/config-model/src/test/java/com/yahoo/schema/ImportedFieldsEnumeratorTest.java +++ b/config-model/src/test/java/com/yahoo/schema/ImportedFieldsEnumeratorTest.java @@ -6,18 +6,18 @@ import com.yahoo.document.DataType; import com.yahoo.schema.document.SDDocumentType; import com.yahoo.schema.document.SDField; import com.yahoo.schema.document.TemporaryImportedField; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.HashSet; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; public class ImportedFieldsEnumeratorTest { @Test - public void imported_fields_are_enumerated_and_copied_from_correct_search_instance() { + void imported_fields_are_enumerated_and_copied_from_correct_search_instance() { String PARENT = "parent"; Schema parentSchema = new Schema(PARENT, MockApplicationPackage.createEmpty()); SDDocumentType parentDocument = new SDDocumentType(PARENT, parentSchema); diff --git a/config-model/src/test/java/com/yahoo/schema/IncorrectRankingExpressionFileRefTestCase.java b/config-model/src/test/java/com/yahoo/schema/IncorrectRankingExpressionFileRefTestCase.java index 87e168adb66..d70abbd6d3f 100644 --- a/config-model/src/test/java/com/yahoo/schema/IncorrectRankingExpressionFileRefTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/IncorrectRankingExpressionFileRefTestCase.java @@ -5,12 +5,12 @@ import com.yahoo.search.query.profile.QueryProfileRegistry; import com.yahoo.schema.derived.DerivedConfiguration; import com.yahoo.schema.parser.ParseException; import com.yahoo.yolean.Exceptions; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author bratseth @@ -18,12 +18,12 @@ import static org.junit.Assert.fail; public class IncorrectRankingExpressionFileRefTestCase extends AbstractSchemaTestCase { @Test - public void testIncorrectRef() throws IOException, ParseException { + void testIncorrectRef() throws IOException, ParseException { try { RankProfileRegistry registry = new RankProfileRegistry(); Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/incorrectrankingexpressionfileref.sd", - registry, - new QueryProfileRegistry()); + registry, + new QueryProfileRegistry()); new DerivedConfiguration(schema, registry); // cause rank profile parsing fail("parsing should have failed"); } catch (IllegalArgumentException e) { diff --git a/config-model/src/test/java/com/yahoo/schema/IncorrectSummaryTypesTestCase.java b/config-model/src/test/java/com/yahoo/schema/IncorrectSummaryTypesTestCase.java index e58cce6472a..acc872f6798 100644 --- a/config-model/src/test/java/com/yahoo/schema/IncorrectSummaryTypesTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/IncorrectSummaryTypesTestCase.java @@ -2,10 +2,11 @@ package com.yahoo.schema; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; /** * Tests importing a search definition with conflicting summary types * @@ -13,20 +14,20 @@ import static org.junit.Assert.fail; */ public class IncorrectSummaryTypesTestCase extends AbstractSchemaTestCase { @Test - public void testImportingIncorrect() throws ParseException { + void testImportingIncorrect() throws ParseException { try { ApplicationBuilder.createFromString( "search incorrectsummarytypes {\n" + - " document incorrectsummarytypes {\n" + - " field somestring type string {\n" + - " indexing: summary\n" + - " }\n" + - " }\n" + - " document-summary incorrect {\n" + - " summary somestring type int {\n" + - " }\n" + - " }\n" + - "}\n"); + " document incorrectsummarytypes {\n" + + " field somestring type string {\n" + + " indexing: summary\n" + + " }\n" + + " }\n" + + " document-summary incorrect {\n" + + " summary somestring type int {\n" + + " }\n" + + " }\n" + + "}\n"); fail("processing should have failed"); } catch (RuntimeException e) { assertEquals("'summary somestring type string' in 'destinations(default )' is inconsistent with 'summary somestring type int' in 'destinations(incorrect )': All declarations of the same summary field must have the same type", e.getMessage()); diff --git a/config-model/src/test/java/com/yahoo/schema/IndexSettingsTestCase.java b/config-model/src/test/java/com/yahoo/schema/IndexSettingsTestCase.java index 6082372b428..b1d502dec36 100644 --- a/config-model/src/test/java/com/yahoo/schema/IndexSettingsTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/IndexSettingsTestCase.java @@ -4,13 +4,13 @@ package com.yahoo.schema; import com.yahoo.schema.document.SDField; import com.yahoo.schema.document.Stemming; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import static com.yahoo.config.model.test.TestUtil.joinLines; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Rank settings @@ -20,24 +20,24 @@ import static org.junit.Assert.assertTrue; public class IndexSettingsTestCase extends AbstractSchemaTestCase { @Test - public void testStemmingSettings() throws IOException, ParseException { + void testStemmingSettings() throws IOException, ParseException { Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/indexsettings.sd"); - SDField usingDefault=(SDField) schema.getDocument().getField("usingdefault"); - assertEquals(Stemming.SHORTEST,usingDefault.getStemming(schema)); + SDField usingDefault = (SDField) schema.getDocument().getField("usingdefault"); + assertEquals(Stemming.SHORTEST, usingDefault.getStemming(schema)); - SDField notStemmed=(SDField) schema.getDocument().getField("notstemmed"); - assertEquals(Stemming.NONE,notStemmed.getStemming(schema)); + SDField notStemmed = (SDField) schema.getDocument().getField("notstemmed"); + assertEquals(Stemming.NONE, notStemmed.getStemming(schema)); - SDField allStemmed=(SDField) schema.getDocument().getField("allstemmed"); - assertEquals(Stemming.SHORTEST,allStemmed.getStemming(schema)); + SDField allStemmed = (SDField) schema.getDocument().getField("allstemmed"); + assertEquals(Stemming.SHORTEST, allStemmed.getStemming(schema)); - SDField multiStemmed=(SDField) schema.getDocument().getField("multiplestems"); + SDField multiStemmed = (SDField) schema.getDocument().getField("multiplestems"); assertEquals(Stemming.MULTIPLE, multiStemmed.getStemming(schema)); } @Test - public void requireThatInterlavedFeaturesAreSetOnExtraField() throws ParseException { + void requireThatInterlavedFeaturesAreSetOnExtraField() throws ParseException { ApplicationBuilder builder = ApplicationBuilder.createFromString(joinLines( "search test {", " document test {", diff --git a/config-model/src/test/java/com/yahoo/schema/IndexingParsingTestCase.java b/config-model/src/test/java/com/yahoo/schema/IndexingParsingTestCase.java index 6a51000fffe..fcbea179810 100644 --- a/config-model/src/test/java/com/yahoo/schema/IndexingParsingTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/IndexingParsingTestCase.java @@ -2,9 +2,9 @@ package com.yahoo.schema; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * Tests that indexing statements are parsed correctly. @@ -14,12 +14,12 @@ import static org.junit.Assert.assertNotNull; public class IndexingParsingTestCase extends AbstractSchemaTestCase { @Test - public void requireThatIndexingExpressionsCanBeParsed() throws Exception { + void requireThatIndexingExpressionsCanBeParsed() throws Exception { assertNotNull(ApplicationBuilder.buildFromFile("src/test/examples/indexing.sd")); } @Test - public void requireThatParseExceptionPositionIsCorrect() throws Exception { + void requireThatParseExceptionPositionIsCorrect() throws Exception { try { ApplicationBuilder.buildFromFile("src/test/examples/indexing_invalid_expression.sd"); } catch (ParseException e) { diff --git a/config-model/src/test/java/com/yahoo/schema/MultipleSummariesTestCase.java b/config-model/src/test/java/com/yahoo/schema/MultipleSummariesTestCase.java index 6d6249dc372..fb3257bf4b4 100644 --- a/config-model/src/test/java/com/yahoo/schema/MultipleSummariesTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/MultipleSummariesTestCase.java @@ -3,7 +3,7 @@ package com.yahoo.schema; import com.yahoo.config.model.deploy.TestProperties; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; @@ -15,7 +15,7 @@ import java.io.IOException; public class MultipleSummariesTestCase extends AbstractSchemaTestCase { @Test - public void testArrayImporting() throws IOException, ParseException { + void testArrayImporting() throws IOException, ParseException { var builder = new ApplicationBuilder(new TestProperties()); builder.addSchemaFile("src/test/examples/multiplesummaries.sd"); builder.build(true); diff --git a/config-model/src/test/java/com/yahoo/schema/NameFieldCheckTestCase.java b/config-model/src/test/java/com/yahoo/schema/NameFieldCheckTestCase.java index 9b4b6864309..8de95945a18 100644 --- a/config-model/src/test/java/com/yahoo/schema/NameFieldCheckTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/NameFieldCheckTestCase.java @@ -1,11 +1,9 @@ // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.schema; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; /** * Tests that "name" is not allowed as name for a field. @@ -17,20 +15,20 @@ import static org.junit.Assert.fail; public class NameFieldCheckTestCase extends AbstractSchemaTestCase { @Test - public void testNameField() { + void testNameField() { try { ApplicationBuilder.createFromString( "search simple {\n" + - " document name-check {\n" + - " field title type string {\n" + - " indexing: summary | index\n" + - " }\n" + - " # reserved name, should trigger error\n" + - " field sddocname type string {\n" + - " indexing: index\n" + - " }\n" + - " }\n" + - "}"); + " document name-check {\n" + + " field title type string {\n" + + " indexing: summary | index\n" + + " }\n" + + " # reserved name, should trigger error\n" + + " field sddocname type string {\n" + + " indexing: index\n" + + " }\n" + + " }\n" + + "}"); fail("Should throw exception."); } catch (Exception expected) { // Success @@ -38,39 +36,39 @@ public class NameFieldCheckTestCase extends AbstractSchemaTestCase { } @Test - public void testDuplicateNamesInSearchDifferentType() { + void testDuplicateNamesInSearchDifferentType() { try { ApplicationBuilder.createFromString( "search duplicatenamesinsearch {\n" + - " document {\n" + - " field grpphotoids64 type string { }\n" + - " }\n" + - " field grpphotoids64 type array<long> {\n" + - " indexing: input grpphotoids64 | split \" \" | for_each {\n" + - " base64decode } | attribute\n" + - " }\n" + - "}"); + " document {\n" + + " field grpphotoids64 type string { }\n" + + " }\n" + + " field grpphotoids64 type array<long> {\n" + + " indexing: input grpphotoids64 | split \" \" | for_each {\n" + + " base64decode } | attribute\n" + + " }\n" + + "}"); fail("Should throw exception."); } catch (Exception e) { assertEquals("For schema 'duplicatenamesinsearch', field 'grpphotoids64': " + - "Incompatible types. Expected Array<long> for index field 'grpphotoids64', got string.", e.getMessage()); + "Incompatible types. Expected Array<long> for index field 'grpphotoids64', got string.", e.getMessage()); } } @Test - public void testDuplicateNamesInDoc() { + void testDuplicateNamesInDoc() { try { ApplicationBuilder.createFromString( "search duplicatenamesindoc {\n" + - " document {\n" + - " field foo type int {\n" + - " indexing: attribute\n" + - " }\n" + - " field fOo type string {\n" + - " indexing: index\n" + - " }\n" + - " }\n" + - "}"); + " document {\n" + + " field foo type int {\n" + + " indexing: attribute\n" + + " }\n" + + " field fOo type string {\n" + + " indexing: index\n" + + " }\n" + + " }\n" + + "}"); fail("Should throw exception."); } catch (Exception e) { assertTrue(e.getMessage().matches(".*Duplicate.*")); diff --git a/config-model/src/test/java/com/yahoo/schema/OutsideTestCase.java b/config-model/src/test/java/com/yahoo/schema/OutsideTestCase.java index 0c0684e23e3..8509c1972a8 100644 --- a/config-model/src/test/java/com/yahoo/schema/OutsideTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/OutsideTestCase.java @@ -2,12 +2,13 @@ package com.yahoo.schema; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * Tests settings outside the document * @@ -16,16 +17,16 @@ import static org.junit.Assert.assertTrue; public class OutsideTestCase extends AbstractSchemaTestCase { @Test - public void testOutsideIndex() throws IOException, ParseException { + void testOutsideIndex() throws IOException, ParseException { Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/outsidedoc.sd"); - Index defaultIndex= schema.getIndex("default"); + Index defaultIndex = schema.getIndex("default"); assertTrue(defaultIndex.isPrefix()); - assertEquals("default.default",defaultIndex.aliasIterator().next()); + assertEquals("default.default", defaultIndex.aliasIterator().next()); } @Test - public void testOutsideSummary() throws IOException, ParseException { + void testOutsideSummary() throws IOException, ParseException { ApplicationBuilder.buildFromFile("src/test/examples/outsidesummary.sd"); } diff --git a/config-model/src/test/java/com/yahoo/schema/PredicateDataTypeTestCase.java b/config-model/src/test/java/com/yahoo/schema/PredicateDataTypeTestCase.java index dbea8fb8aeb..f59938e9a41 100644 --- a/config-model/src/test/java/com/yahoo/schema/PredicateDataTypeTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/PredicateDataTypeTestCase.java @@ -2,17 +2,12 @@ package com.yahoo.schema; import com.yahoo.schema.document.ImmutableSDField; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; import com.yahoo.document.DataType; import com.yahoo.schema.parser.ParseException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; /** * @author Lester Solbakken @@ -52,25 +47,21 @@ public class PredicateDataTypeTestCase { return "upper-bound: " + bound + "\n"; } - @SuppressWarnings("deprecation") - @Rule - public ExpectedException exception = ExpectedException.none(); - @Test - public void requireThatBuilderSetsIndexParametersCorrectly() throws ParseException { + void requireThatBuilderSetsIndexParametersCorrectly() throws ParseException { int arity = 2; long lowerBound = -100; long upperBound = 100; String sd = searchSd( - predicateFieldSd( - attributeFieldSd( - arityParameter(arity) + - lowerBoundParameter(lowerBound) + - upperBoundParameter(upperBound)))); + predicateFieldSd( + attributeFieldSd( + arityParameter(arity) + + lowerBoundParameter(lowerBound) + + upperBoundParameter(upperBound)))); ApplicationBuilder sb = ApplicationBuilder.createFromString(sd); for (ImmutableSDField field : sb.getSchema().allConcreteFields()) { - if (field.getDataType() == DataType.PREDICATE) { + if (field.getDataType() == DataType.PREDICATE) { for (Index index : field.getIndices().values()) { assertTrue(index.getBooleanIndexDefiniton().hasArity()); assertEquals(arity, index.getBooleanIndexDefiniton().getArity()); @@ -84,20 +75,20 @@ public class PredicateDataTypeTestCase { } @Test - public void requireThatBuilderHandlesLongValues() throws ParseException { + void requireThatBuilderHandlesLongValues() throws ParseException { int arity = 2; long lowerBound = -100000000000000000L; long upperBound = 1000000000000000000L; String sd = searchSd( - predicateFieldSd( - attributeFieldSd( - arityParameter(arity) + - "lower-bound: -100000000000000000L\n" + // +'L' - upperBoundParameter(upperBound)))); + predicateFieldSd( + attributeFieldSd( + arityParameter(arity) + + "lower-bound: -100000000000000000L\n" + // +'L' + upperBoundParameter(upperBound)))); ApplicationBuilder sb = ApplicationBuilder.createFromString(sd); for (ImmutableSDField field : sb.getSchema().allConcreteFields()) { - if (field.getDataType() == DataType.PREDICATE) { + if (field.getDataType() == DataType.PREDICATE) { for (Index index : field.getIndices().values()) { assertEquals(arity, index.getBooleanIndexDefiniton().getArity()); assertEquals(lowerBound, index.getBooleanIndexDefiniton().getLowerBound()); @@ -108,11 +99,11 @@ public class PredicateDataTypeTestCase { } @Test - public void requireThatBuilderHandlesMissingParameters() throws ParseException { + void requireThatBuilderHandlesMissingParameters() throws ParseException { String sd = searchSd( - predicateFieldSd( - attributeFieldSd( - arityParameter(2)))); + predicateFieldSd( + attributeFieldSd( + arityParameter(2)))); ApplicationBuilder sb = ApplicationBuilder.createFromString(sd); for (ImmutableSDField field : sb.getSchema().allConcreteFields()) { if (field.getDataType() == DataType.PREDICATE) { @@ -126,74 +117,74 @@ public class PredicateDataTypeTestCase { } @Test - public void requireThatBuilderFailsIfNoArityValue() throws ParseException { - String sd = searchSd(predicateFieldSd(attributeFieldSd(""))); - - exception.expect(IllegalArgumentException.class); - exception.expectMessage("Missing arity value in predicate field."); - ApplicationBuilder.createFromString(sd); - fail(); + void requireThatBuilderFailsIfNoArityValue() throws ParseException { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + String sd = searchSd(predicateFieldSd(attributeFieldSd(""))); + ApplicationBuilder.createFromString(sd); + fail(); + }); + assertTrue(exception.getMessage().contains("Missing arity value in predicate field.")); } @Test - public void requireThatBuilderFailsIfBothIndexAndAttribute() throws ParseException { - String sd = searchSd(predicateFieldSd("indexing: summary | index | attribute\nindex { arity: 2 }")); - - exception.expect(IllegalArgumentException.class); - exception.expectMessage("For schema 'p', field 'pf': Use 'attribute' instead of 'index'. This will require a refeed if you have upgraded."); - ApplicationBuilder.createFromString(sd); + void requireThatBuilderFailsIfBothIndexAndAttribute() throws ParseException { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + String sd = searchSd(predicateFieldSd("indexing: summary | index | attribute\nindex { arity: 2 }")); + ApplicationBuilder.createFromString(sd); + }); + assertTrue(exception.getMessage().contains("For schema 'p', field 'pf': Use 'attribute' instead of 'index'. This will require a refeed if you have upgraded.")); } @Test - public void requireThatBuilderFailsIfIndex() throws ParseException { - String sd = searchSd(predicateFieldSd("indexing: summary | index \nindex { arity: 2 }")); - - exception.expect(IllegalArgumentException.class); - exception.expectMessage("For schema 'p', field 'pf': Use 'attribute' instead of 'index'. This will require a refeed if you have upgraded."); - ApplicationBuilder.createFromString(sd); + void requireThatBuilderFailsIfIndex() throws ParseException { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + String sd = searchSd(predicateFieldSd("indexing: summary | index \nindex { arity: 2 }")); + ApplicationBuilder.createFromString(sd); + }); + assertTrue(exception.getMessage().contains("For schema 'p', field 'pf': Use 'attribute' instead of 'index'. This will require a refeed if you have upgraded.")); } @Test - public void requireThatBuilderFailsIfIllegalArityValue() throws ParseException { - String sd = searchSd(predicateFieldSd(attributeFieldSd(arityParameter(0)))); - - exception.expect(IllegalArgumentException.class); - exception.expectMessage("Invalid arity value in predicate field, must be greater than 1."); - ApplicationBuilder.createFromString(sd); + void requireThatBuilderFailsIfIllegalArityValue() throws ParseException { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + String sd = searchSd(predicateFieldSd(attributeFieldSd(arityParameter(0)))); + ApplicationBuilder.createFromString(sd); + }); + assertTrue(exception.getMessage().contains("Invalid arity value in predicate field, must be greater than 1.")); } @Test - public void requireThatBuilderFailsIfArityParameterExistButNotPredicateField() throws ParseException { - String sd = searchSd(stringFieldSd(attributeFieldSd(arityParameter(2)))); - - exception.expect(IllegalArgumentException.class); - exception.expectMessage("Arity parameter is used only for predicate type fields."); - ApplicationBuilder.createFromString(sd); + void requireThatBuilderFailsIfArityParameterExistButNotPredicateField() throws ParseException { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + String sd = searchSd(stringFieldSd(attributeFieldSd(arityParameter(2)))); + ApplicationBuilder.createFromString(sd); + }); + assertTrue(exception.getMessage().contains("Arity parameter is used only for predicate type fields.")); } @Test - public void requireThatBuilderFailsIfBoundParametersExistButNotPredicateField() throws ParseException { - String sd = searchSd( - stringFieldSd( + void requireThatBuilderFailsIfBoundParametersExistButNotPredicateField() throws ParseException { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + String sd = searchSd( + stringFieldSd( attributeFieldSd( lowerBoundParameter(100) + upperBoundParameter(1000)))); - - exception.expect(IllegalArgumentException.class); - exception.expectMessage("Parameters lower-bound and upper-bound are used only for predicate type fields."); - ApplicationBuilder.createFromString(sd); + ApplicationBuilder.createFromString(sd); + }); + assertTrue(exception.getMessage().contains("Parameters lower-bound and upper-bound are used only for predicate type fields.")); } @Test - public void requireThatArrayOfPredicateFails() throws ParseException { - String sd = searchSd( - arrayPredicateFieldSd( - attributeFieldSd( - arityParameter(1)))); - - exception.expect(IllegalArgumentException.class); - exception.expectMessage("Collections of predicates are not allowed."); - ApplicationBuilder.createFromString(sd); + void requireThatArrayOfPredicateFails() throws ParseException { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + String sd = searchSd( + arrayPredicateFieldSd( + attributeFieldSd( + arityParameter(1)))); + ApplicationBuilder.createFromString(sd); + }); + assertTrue(exception.getMessage().contains("Collections of predicates are not allowed.")); } } diff --git a/config-model/src/test/java/com/yahoo/schema/RankProfileRegistryTest.java b/config-model/src/test/java/com/yahoo/schema/RankProfileRegistryTest.java index de061defb87..b73f5412bba 100644 --- a/config-model/src/test/java/com/yahoo/schema/RankProfileRegistryTest.java +++ b/config-model/src/test/java/com/yahoo/schema/RankProfileRegistryTest.java @@ -8,13 +8,11 @@ import com.yahoo.config.model.test.TestRoot; import com.yahoo.searchlib.rankingexpression.ExpressionFunction; import com.yahoo.searchlib.rankingexpression.RankingExpression; import com.yahoo.vespa.config.search.RankProfilesConfig; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.File; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.*; /** * @author Ulf Lilleengen @@ -24,7 +22,7 @@ public class RankProfileRegistryTest { private static final String TESTDIR = "src/test/cfg/search/data/v2/inherited_rankprofiles"; @Test - public void testRankProfileInheritance() { + void testRankProfileInheritance() { TestRoot root = new TestDriver().buildModel(FilesApplicationPackage.fromFile(new File(TESTDIR))); RankProfilesConfig left = root.getConfig(RankProfilesConfig.class, "inherit/search/cluster.inherit/left"); RankProfilesConfig right = root.getConfig(RankProfilesConfig.class, "inherit/search/cluster.inherit/right"); @@ -32,17 +30,19 @@ public class RankProfileRegistryTest { assertEquals(2, right.rankprofile().size()); } - @Test(expected = IllegalArgumentException.class) - public void testRankProfileDuplicateNameIsIllegal() { - Schema schema = new Schema("foo", MockApplicationPackage.createEmpty()); - RankProfileRegistry rankProfileRegistry = RankProfileRegistry.createRankProfileRegistryWithBuiltinRankProfiles(schema); - RankProfile barRankProfile = new RankProfile("bar", schema, rankProfileRegistry); - rankProfileRegistry.add(barRankProfile); - rankProfileRegistry.add(barRankProfile); + @Test + void testRankProfileDuplicateNameIsIllegal() { + assertThrows(IllegalArgumentException.class, () -> { + Schema schema = new Schema("foo", MockApplicationPackage.createEmpty()); + RankProfileRegistry rankProfileRegistry = RankProfileRegistry.createRankProfileRegistryWithBuiltinRankProfiles(schema); + RankProfile barRankProfile = new RankProfile("bar", schema, rankProfileRegistry); + rankProfileRegistry.add(barRankProfile); + rankProfileRegistry.add(barRankProfile); + }); } @Test - public void testRankProfileDuplicateNameLegalForOverridableRankProfiles() { + void testRankProfileDuplicateNameLegalForOverridableRankProfiles() { Schema schema = new Schema("foo", MockApplicationPackage.createEmpty()); RankProfileRegistry rankProfileRegistry = RankProfileRegistry.createRankProfileRegistryWithBuiltinRankProfiles(schema); diff --git a/config-model/src/test/java/com/yahoo/schema/RankProfileTestCase.java b/config-model/src/test/java/com/yahoo/schema/RankProfileTestCase.java index c66d44556ca..ddca13a2984 100644 --- a/config-model/src/test/java/com/yahoo/schema/RankProfileTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/RankProfileTestCase.java @@ -24,17 +24,13 @@ import ai.vespa.rankingexpression.importer.configmodelview.ImportedMlModels; import static com.yahoo.config.model.test.TestUtil.joinLines; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Iterator; import java.util.List; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; /** * Tests rank profiles @@ -44,7 +40,7 @@ import static org.junit.Assert.fail; public class RankProfileTestCase extends AbstractSchemaTestCase { @Test - public void testRankProfileInheritance() { + void testRankProfileInheritance() { Schema schema = new Schema("test", MockApplicationPackage.createEmpty()); RankProfileRegistry rankProfileRegistry = RankProfileRegistry.createRankProfileRegistryWithBuiltinRankProfiles(schema); SDDocumentType document = new SDDocumentType("test"); @@ -68,7 +64,7 @@ public class RankProfileTestCase extends AbstractSchemaTestCase { } @Test - public void requireThatIllegalInheritanceIsChecked() throws ParseException { + void requireThatIllegalInheritanceIsChecked() throws ParseException { try { RankProfileRegistry registry = new RankProfileRegistry(); ApplicationBuilder builder = new ApplicationBuilder(registry, setupQueryProfileTypes()); @@ -85,7 +81,7 @@ public class RankProfileTestCase extends AbstractSchemaTestCase { } @Test - public void requireThatSelfInheritanceIsIllegal() throws ParseException { + void requireThatSelfInheritanceIsIllegal() throws ParseException { try { RankProfileRegistry registry = new RankProfileRegistry(); ApplicationBuilder builder = new ApplicationBuilder(registry, setupQueryProfileTypes()); @@ -102,7 +98,7 @@ public class RankProfileTestCase extends AbstractSchemaTestCase { } @Test - public void requireThatSelfInheritanceIsLegalWhenOverloading() throws ParseException { + void requireThatSelfInheritanceIsLegalWhenOverloading() throws ParseException { RankProfileRegistry registry = new RankProfileRegistry(); ApplicationBuilder builder = new ApplicationBuilder(registry, setupQueryProfileTypes()); builder.addSchema(joinLines( @@ -119,7 +115,7 @@ public class RankProfileTestCase extends AbstractSchemaTestCase { } @Test - public void requireThatSidewaysInheritanceIsImpossible() throws ParseException { + void requireThatSidewaysInheritanceIsImpossible() throws ParseException { RankProfileRegistry registry = new RankProfileRegistry(); ApplicationBuilder builder = new ApplicationBuilder(registry, setupQueryProfileTypes()); builder.addSchema(joinLines( @@ -172,7 +168,7 @@ public class RankProfileTestCase extends AbstractSchemaTestCase { } @Test - public void requireThatDefaultInheritingDefaultIsIgnored() throws ParseException { + void requireThatDefaultInheritingDefaultIsIgnored() throws ParseException { RankProfileRegistry registry = new RankProfileRegistry(); ApplicationBuilder builder = new ApplicationBuilder(registry, setupQueryProfileTypes()); builder.addSchema(joinLines( @@ -184,7 +180,7 @@ public class RankProfileTestCase extends AbstractSchemaTestCase { } @Test - public void requireThatCyclicInheritanceIsIllegal() throws ParseException { + void requireThatCyclicInheritanceIsIllegal() throws ParseException { try { RankProfileRegistry registry = new RankProfileRegistry(); ApplicationBuilder builder = new ApplicationBuilder(registry, setupQueryProfileTypes()); @@ -203,7 +199,7 @@ public class RankProfileTestCase extends AbstractSchemaTestCase { } @Test - public void requireThatRankProfilesCanInheritNotYetSeenProfiles() throws ParseException + void requireThatRankProfilesCanInheritNotYetSeenProfiles() throws ParseException { RankProfileRegistry registry = new RankProfileRegistry(); ApplicationBuilder builder = new ApplicationBuilder(registry, setupQueryProfileTypes()); @@ -214,9 +210,9 @@ public class RankProfileTestCase extends AbstractSchemaTestCase { " rank-profile not_yet_defined {}", "}")); builder.build(true); - assertNotNull(registry.get("test","p1")); - assertTrue(registry.get("test","p1").inherits("not_yet_defined")); - assertNotNull(registry.get("test","not_yet_defined")); + assertNotNull(registry.get("test", "p1")); + assertTrue(registry.get("test", "p1").inherits("not_yet_defined")); + assertNotNull(registry.get("test", "not_yet_defined")); } private String createSD(Double termwiseLimit) { @@ -239,7 +235,7 @@ public class RankProfileTestCase extends AbstractSchemaTestCase { } @Test - public void testTermwiseLimitWithDeployOverride() throws ParseException { + void testTermwiseLimitWithDeployOverride() throws ParseException { verifyTermwiseLimitAndSomeMoreIncludingInheritance(new TestProperties(), createSD(null), null); verifyTermwiseLimitAndSomeMoreIncludingInheritance(new TestProperties(), createSD(0.78), 0.78); verifyTermwiseLimitAndSomeMoreIncludingInheritance(new TestProperties().setDefaultTermwiseLimit(0.09), createSD(null), 0.09); @@ -279,7 +275,7 @@ public class RankProfileTestCase extends AbstractSchemaTestCase { } @Test - public void requireThatConfigIsDerivedForAttributeTypeSettings() throws ParseException { + void requireThatConfigIsDerivedForAttributeTypeSettings() throws ParseException { RankProfileRegistry registry = new RankProfileRegistry(); ApplicationBuilder builder = new ApplicationBuilder(registry); builder.addSchema(joinLines( @@ -303,7 +299,7 @@ public class RankProfileTestCase extends AbstractSchemaTestCase { } @Test - public void requireThatDenseDimensionsMustBeBound() throws ParseException { + void requireThatDenseDimensionsMustBeBound() throws ParseException { try { ApplicationBuilder builder = new ApplicationBuilder(new RankProfileRegistry()); builder.addSchema(joinLines( @@ -316,7 +312,7 @@ public class RankProfileTestCase extends AbstractSchemaTestCase { } catch (IllegalArgumentException e) { assertEquals("Illegal type in field a type tensor(x[]): Dense tensor dimensions must have a size", - e.getMessage()); + e.getMessage()); } } @@ -332,7 +328,7 @@ public class RankProfileTestCase extends AbstractSchemaTestCase { } @Test - public void requireThatConfigIsDerivedForQueryFeatureTypeSettings() throws ParseException { + void requireThatConfigIsDerivedForQueryFeatureTypeSettings() throws ParseException { RankProfileRegistry registry = new RankProfileRegistry(); ApplicationBuilder builder = new ApplicationBuilder(registry, setupQueryProfileTypes()); builder.addSchema(joinLines( @@ -386,7 +382,7 @@ public class RankProfileTestCase extends AbstractSchemaTestCase { } @Test - public void approximate_nearest_neighbor_threshold_settings_are_configurable() throws ParseException { + void approximate_nearest_neighbor_threshold_settings_are_configurable() throws ParseException { verifyApproximateNearestNeighborThresholdSettings(0.7, null); verifyApproximateNearestNeighborThresholdSettings(null, 0.3); verifyApproximateNearestNeighborThresholdSettings(0.7, 0.3); diff --git a/config-model/src/test/java/com/yahoo/schema/RankPropertiesTestCase.java b/config-model/src/test/java/com/yahoo/schema/RankPropertiesTestCase.java index c3595717220..06fa63707c0 100644 --- a/config-model/src/test/java/com/yahoo/schema/RankPropertiesTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/RankPropertiesTestCase.java @@ -8,12 +8,12 @@ import com.yahoo.schema.derived.AttributeFields; import com.yahoo.schema.derived.RawRankProfile; import com.yahoo.schema.parser.ParseException; import ai.vespa.rankingexpression.importer.configmodelview.ImportedMlModels; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.List; import static com.yahoo.config.model.test.TestUtil.joinLines; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author bratseth @@ -21,7 +21,7 @@ import static org.junit.Assert.assertEquals; public class RankPropertiesTestCase extends AbstractSchemaTestCase { @Test - public void testRankPropertyInheritance() throws ParseException { + void testRankPropertyInheritance() throws ParseException { RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry); builder.addSchema(joinLines( @@ -69,16 +69,17 @@ public class RankPropertiesTestCase extends AbstractSchemaTestCase { // Check derived model RawRankProfile rawChild = new RawRankProfile(rankProfileRegistry.get(schema, "child"), - new LargeRankExpressions(new MockFileRegistry()), - new QueryProfileRegistry(), - new ImportedMlModels(), - attributeFields, - new TestProperties()); + new LargeRankExpressions(new MockFileRegistry()), + new QueryProfileRegistry(), + new ImportedMlModels(), + attributeFields, + new TestProperties()); assertEquals("(query(a), 2000)", rawChild.configProperties().get(0).toString()); } } + @Test - public void testRankProfileMutate() throws ParseException { + void testRankProfileMutate() throws ParseException { RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry); builder.addSchema(joinLines( diff --git a/config-model/src/test/java/com/yahoo/schema/RankingConstantTest.java b/config-model/src/test/java/com/yahoo/schema/RankingConstantTest.java index 883e6b50abb..c963f086ac4 100644 --- a/config-model/src/test/java/com/yahoo/schema/RankingConstantTest.java +++ b/config-model/src/test/java/com/yahoo/schema/RankingConstantTest.java @@ -2,28 +2,20 @@ package com.yahoo.schema; import com.yahoo.schema.parser.ParseException; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; import java.util.Iterator; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; import static com.yahoo.config.model.test.TestUtil.joinLines; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; /** * @author gjoranv */ public class RankingConstantTest { - @SuppressWarnings("deprecation") - @Rule - public ExpectedException thrown = ExpectedException.none(); - @Test - public void tensor_constant_properties_are_set() throws Exception { + void tensor_constant_properties_are_set() throws Exception { final String TENSOR_NAME = "my_global_tensor"; final String TENSOR_FILE = "path/my-tensor-file.json"; final String TENSOR_TYPE = "tensor(x{})"; @@ -57,39 +49,41 @@ public class RankingConstantTest { } @Test - public void tensor_constant_must_have_a_type() throws Exception { - RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); - ApplicationBuilder schemaBuilder = new ApplicationBuilder(rankProfileRegistry); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("must have a type"); - schemaBuilder.addSchema(joinLines( - "schema test {", - " document test { }", - " constant foo {", - " file: bar.baz", - " }", - "}" - )); + void tensor_constant_must_have_a_type() throws Exception { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); + ApplicationBuilder schemaBuilder = new ApplicationBuilder(rankProfileRegistry); + schemaBuilder.addSchema(joinLines( + "schema test {", + " document test { }", + " constant foo {", + " file: bar.baz", + " }", + "}" + )); + }); + assertTrue(exception.getMessage().contains("must have a type")); } @Test - public void tensor_constant_must_have_a_file() throws Exception { - RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); - ApplicationBuilder schemaBuilder = new ApplicationBuilder(rankProfileRegistry); - thrown.expect(IllegalArgumentException.class); - thrown.expectMessage("must have a file"); - schemaBuilder.addSchema(joinLines( - "schema test {", - " document test { }", - " constant foo {", - " type: tensor(x[])", - " }", - "}" - )); + void tensor_constant_must_have_a_file() throws Exception { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); + ApplicationBuilder schemaBuilder = new ApplicationBuilder(rankProfileRegistry); + schemaBuilder.addSchema(joinLines( + "schema test {", + " document test { }", + " constant foo {", + " type: tensor(x[])", + " }", + "}" + )); + }); + assertTrue(exception.getMessage().contains("must have a file")); } @Test - public void constant_file_does_not_need_path_or_ending() throws Exception { + void constant_file_does_not_need_path_or_ending() throws Exception { RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); ApplicationBuilder schemaBuilder = new ApplicationBuilder(rankProfileRegistry); schemaBuilder.addSchema(joinLines( @@ -108,7 +102,7 @@ public class RankingConstantTest { } @Test - public void constant_uri_is_allowed() throws Exception { + void constant_uri_is_allowed() throws Exception { RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); ApplicationBuilder schemaBuilder = new ApplicationBuilder(rankProfileRegistry); schemaBuilder.addSchema(joinLines( @@ -128,7 +122,7 @@ public class RankingConstantTest { } @Test - public void constant_https_uri_is_allowed() throws Exception { + void constant_https_uri_is_allowed() throws Exception { RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); ApplicationBuilder schemaBuilder = new ApplicationBuilder(rankProfileRegistry); schemaBuilder.addSchema(joinLines( @@ -148,7 +142,7 @@ public class RankingConstantTest { } @Test - public void constant_uri_with_port_is_allowed() throws Exception { + void constant_uri_with_port_is_allowed() throws Exception { RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); ApplicationBuilder schemaBuilder = new ApplicationBuilder(rankProfileRegistry); schemaBuilder.addSchema(joinLines( @@ -168,7 +162,7 @@ public class RankingConstantTest { } @Test - public void constant_uri_no_dual_slashes_is_allowed() throws Exception { + void constant_uri_no_dual_slashes_is_allowed() throws Exception { RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); ApplicationBuilder schemaBuilder = new ApplicationBuilder(rankProfileRegistry); schemaBuilder.addSchema(joinLines( @@ -188,7 +182,7 @@ public class RankingConstantTest { } @Test - public void constant_uri_only_supports_http_and_https() { + void constant_uri_only_supports_http_and_https() { RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); ApplicationBuilder schemaBuilder = new ApplicationBuilder(rankProfileRegistry); String expectedMessage = "Encountered \" <IDENTIFIER> \"ftp\"\" at line 5, column 10.\n\n" + @@ -205,7 +199,7 @@ public class RankingConstantTest { "}" )); } catch (ParseException e) { - if (! e.getMessage().startsWith(expectedMessage)) + if (!e.getMessage().startsWith(expectedMessage)) fail("Expected exception with message starting with:\n'" + expectedMessage + "\nBut got:\n'" + e.getMessage()); } } diff --git a/config-model/src/test/java/com/yahoo/schema/RankingExpressionConstantsTestCase.java b/config-model/src/test/java/com/yahoo/schema/RankingExpressionConstantsTestCase.java index bd0bd65295c..c915a85a4cf 100644 --- a/config-model/src/test/java/com/yahoo/schema/RankingExpressionConstantsTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/RankingExpressionConstantsTestCase.java @@ -10,11 +10,12 @@ import com.yahoo.yolean.Exceptions; import com.yahoo.schema.derived.AttributeFields; import com.yahoo.schema.derived.RawRankProfile; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.List; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author bratseth @@ -22,7 +23,7 @@ import static org.junit.Assert.*; public class RankingExpressionConstantsTestCase extends AbstractSchemaTestCase { @Test - public void testConstants() throws ParseException { + void testConstants() throws ParseException { RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); QueryProfileRegistry queryProfileRegistry = new QueryProfileRegistry(); ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry); @@ -89,7 +90,7 @@ public class RankingExpressionConstantsTestCase extends AbstractSchemaTestCase { } @Test - public void testNameCollision() throws ParseException { + void testNameCollision() throws ParseException { RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry); builder.addSchema( @@ -118,12 +119,12 @@ public class RankingExpressionConstantsTestCase extends AbstractSchemaTestCase { } catch (IllegalArgumentException e) { assertEquals("Rank profile 'test' is invalid: Cannot have both a constant and function named 'c'", - Exceptions.toMessageString(e)); + Exceptions.toMessageString(e)); } } @Test - public void testNegativeLiteralArgument() throws ParseException { + void testNegativeLiteralArgument() throws ParseException { RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry); builder.addSchema( @@ -148,7 +149,7 @@ public class RankingExpressionConstantsTestCase extends AbstractSchemaTestCase { } @Test - public void testNegativeConstantArgument() throws ParseException { + void testNegativeConstantArgument() throws ParseException { RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry); builder.addSchema( @@ -174,11 +175,11 @@ public class RankingExpressionConstantsTestCase extends AbstractSchemaTestCase { RankProfile profile = rankProfileRegistry.get(s, "test"); assertEquals("safeLog(popShareSlowDecaySignal,myValue)", profile.getFunctions().get("POP_SLOW_SCORE").function().getBody().getRoot().toString()); assertEquals("safeLog(popShareSlowDecaySignal,-9.21034037)", - profile.compile(new QueryProfileRegistry(), new ImportedMlModels()).getFunctions().get("POP_SLOW_SCORE").function().getBody().getRoot().toString()); + profile.compile(new QueryProfileRegistry(), new ImportedMlModels()).getFunctions().get("POP_SLOW_SCORE").function().getBody().getRoot().toString()); } @Test - public void testConstantDivisorInFunction() throws ParseException { + void testConstantDivisorInFunction() throws ParseException { RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry); builder.addSchema( @@ -197,11 +198,11 @@ public class RankingExpressionConstantsTestCase extends AbstractSchemaTestCase { Schema s = builder.getSchema(); RankProfile profile = rankProfileRegistry.get(s, "test"); assertEquals("k1 + (k2 + k3) / 1.0E8", - profile.compile(new QueryProfileRegistry(), new ImportedMlModels()).getFunctions().get("rank_default").function().getBody().getRoot().toString()); + profile.compile(new QueryProfileRegistry(), new ImportedMlModels()).getFunctions().get("rank_default").function().getBody().getRoot().toString()); } @Test - public void test3() throws ParseException { + void test3() throws ParseException { RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry); builder.addSchema( @@ -223,7 +224,7 @@ public class RankingExpressionConstantsTestCase extends AbstractSchemaTestCase { Schema s = builder.getSchema(); RankProfile profile = rankProfileRegistry.get(s, "test"); assertEquals("0.5 + 50 * (attribute(rating_yelp) - 3)", - profile.compile(new QueryProfileRegistry(), new ImportedMlModels()).getFunctions().get("rank_default").function().getBody().getRoot().toString()); + profile.compile(new QueryProfileRegistry(), new ImportedMlModels()).getFunctions().get("rank_default").function().getBody().getRoot().toString()); } } diff --git a/config-model/src/test/java/com/yahoo/schema/RankingExpressionInliningTestCase.java b/config-model/src/test/java/com/yahoo/schema/RankingExpressionInliningTestCase.java index 79c803e007c..789c4ac5577 100644 --- a/config-model/src/test/java/com/yahoo/schema/RankingExpressionInliningTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/RankingExpressionInliningTestCase.java @@ -11,15 +11,13 @@ import com.yahoo.schema.derived.AttributeFields; import com.yahoo.schema.derived.RawRankProfile; import com.yahoo.schema.parser.ParseException; import ai.vespa.rankingexpression.importer.configmodelview.ImportedMlModels; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Optional; import java.util.logging.Level; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; /** * @author bratseth @@ -27,11 +25,11 @@ import static org.junit.Assert.fail; public class RankingExpressionInliningTestCase extends AbstractSchemaTestCase { @Test - public void testFunctionInliningPreserveArithmeticOrdering() throws ParseException { + void testFunctionInliningPreserveArithmeticOrdering() throws ParseException { RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry); builder.addSchema( - "search test {\n" + + "search test {\n" + " document test { \n" + " field a type double { \n" + " indexing: attribute \n" + @@ -71,14 +69,14 @@ public class RankingExpressionInliningTestCase extends AbstractSchemaTestCase { RankProfile parent = rankProfileRegistry.get(s, "parent").compile(new QueryProfileRegistry(), new ImportedMlModels()); assertEquals("7.0 * (3 + attribute(a) + attribute(b) * (attribute(a) * 3 + if (7.0 < attribute(a), 1, 2) == 0))", - parent.getFirstPhaseRanking().getRoot().toString()); + parent.getFirstPhaseRanking().getRoot().toString()); RankProfile child = rankProfileRegistry.get(s, "child").compile(new QueryProfileRegistry(), new ImportedMlModels()); assertEquals("7.0 * (9 + attribute(a))", - child.getFirstPhaseRanking().getRoot().toString()); + child.getFirstPhaseRanking().getRoot().toString()); } @Test - public void testConstants() throws ParseException { + void testConstants() throws ParseException { RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry); builder.addSchema( @@ -149,7 +147,7 @@ public class RankingExpressionInliningTestCase extends AbstractSchemaTestCase { } @Test - public void testNonTopLevelInlining() throws ParseException { + void testNonTopLevelInlining() throws ParseException { RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry); builder.addSchema( @@ -192,31 +190,31 @@ public class RankingExpressionInliningTestCase extends AbstractSchemaTestCase { } @Test - public void testFunctionRedefinitionIsIllegal() throws ParseException { + void testFunctionRedefinitionIsIllegal() throws ParseException { try { RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); MockDeployLogger deployLogger = new MockDeployLogger(); ApplicationBuilder builder = new ApplicationBuilder(MockApplicationPackage.createEmpty(), - new MockFileRegistry(), - deployLogger, - new TestProperties(), - rankProfileRegistry, - new QueryProfileRegistry()); + new MockFileRegistry(), + deployLogger, + new TestProperties(), + rankProfileRegistry, + new QueryProfileRegistry()); builder.addSchema( "search test {\n" + - " document test { }\n" + - " rank-profile test {\n" + - " first-phase {\n" + - " expression: foo\n" + - " }\n" + - " function foo(x) {\n" + - " expression: x + x\n" + - " }\n" + - " function inline foo() {\n" + - " expression: foo(2)\n" + - " }\n" + - " }\n" + - "}\n"); + " document test { }\n" + + " rank-profile test {\n" + + " first-phase {\n" + + " expression: foo\n" + + " }\n" + + " function foo(x) {\n" + + " expression: x + x\n" + + " }\n" + + " function inline foo() {\n" + + " expression: foo(2)\n" + + " }\n" + + " }\n" + + "}\n"); builder.build(true); fail("Expected failure"); } diff --git a/config-model/src/test/java/com/yahoo/schema/RankingExpressionLoopDetectionTestCase.java b/config-model/src/test/java/com/yahoo/schema/RankingExpressionLoopDetectionTestCase.java index dd69fb6c591..302fda9d3d7 100644 --- a/config-model/src/test/java/com/yahoo/schema/RankingExpressionLoopDetectionTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/RankingExpressionLoopDetectionTestCase.java @@ -3,10 +3,10 @@ package com.yahoo.schema; import com.yahoo.schema.parser.ParseException; import com.yahoo.yolean.Exceptions; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author bratseth @@ -14,232 +14,232 @@ import static org.junit.Assert.fail; public class RankingExpressionLoopDetectionTestCase { @Test - public void testSelfLoop() throws ParseException { + void testSelfLoop() throws ParseException { RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry); builder.addSchema( "search test {\n" + - " document test { \n" + - " field a type string { \n" + - " indexing: index \n" + - " }\n" + - " }\n" + - " \n" + - " rank-profile test {\n" + - " first-phase {\n" + - " expression: foo\n" + - " }\n" + - " function foo() {\n" + - " expression: foo\n" + - " }\n" + - " }\n" + - "\n" + - "}\n"); + " document test { \n" + + " field a type string { \n" + + " indexing: index \n" + + " }\n" + + " }\n" + + " \n" + + " rank-profile test {\n" + + " first-phase {\n" + + " expression: foo\n" + + " }\n" + + " function foo() {\n" + + " expression: foo\n" + + " }\n" + + " }\n" + + "\n" + + "}\n"); try { builder.build(true); fail("Excepted exception"); } catch (IllegalArgumentException e) { assertEquals("In schema 'test', rank profile 'test': The function 'foo' is invalid: foo is invalid: Invocation loop: foo -> foo", - Exceptions.toMessageString(e)); + Exceptions.toMessageString(e)); } } @Test - public void testNestedLoop() throws ParseException { + void testNestedLoop() throws ParseException { RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry); builder.addSchema( "search test {\n" + - " document test { \n" + - " field a type string { \n" + - " indexing: index \n" + - " }\n" + - " }\n" + - " \n" + - " rank-profile test {\n" + - " first-phase {\n" + - " expression: foo\n" + - " }\n" + - " function foo() {\n" + - " expression: arg(5)\n" + - " }\n" + - " function arg(a1) {\n" + - " expression: foo + a1*2\n" + - " }\n" + - " }\n" + - "\n" + - "}\n"); + " document test { \n" + + " field a type string { \n" + + " indexing: index \n" + + " }\n" + + " }\n" + + " \n" + + " rank-profile test {\n" + + " first-phase {\n" + + " expression: foo\n" + + " }\n" + + " function foo() {\n" + + " expression: arg(5)\n" + + " }\n" + + " function arg(a1) {\n" + + " expression: foo + a1*2\n" + + " }\n" + + " }\n" + + "\n" + + "}\n"); try { builder.build(true); fail("Excepted exception"); } catch (IllegalArgumentException e) { assertEquals("In schema 'test', rank profile 'test': The function 'foo' is invalid: arg(5) is invalid: foo is invalid: arg(5) is invalid: Invocation loop: arg(5) -> foo -> arg(5)", - Exceptions.toMessageString(e)); + Exceptions.toMessageString(e)); } } @Test - public void testSelfArgumentLoop() throws ParseException { + void testSelfArgumentLoop() throws ParseException { RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry); builder.addSchema( "search test {\n" + - " document test { \n" + - " field a type string { \n" + - " indexing: index \n" + - " }\n" + - " }\n" + - " \n" + - " rank-profile test {\n" + - " first-phase {\n" + - " expression: foo\n" + - " }\n" + - " function foo() {\n" + - " expression: arg(foo)\n" + - " }\n" + - " function arg(a1) {\n" + - " expression: a1*2\n" + - " }\n" + - " }\n" + - "\n" + - "}\n"); + " document test { \n" + + " field a type string { \n" + + " indexing: index \n" + + " }\n" + + " }\n" + + " \n" + + " rank-profile test {\n" + + " first-phase {\n" + + " expression: foo\n" + + " }\n" + + " function foo() {\n" + + " expression: arg(foo)\n" + + " }\n" + + " function arg(a1) {\n" + + " expression: a1*2\n" + + " }\n" + + " }\n" + + "\n" + + "}\n"); try { builder.build(true); fail("Excepted exception"); } catch (IllegalArgumentException e) { assertEquals("In schema 'test', rank profile 'test': The function 'foo' is invalid: arg(foo) is invalid: a1 is invalid: foo is invalid: arg(foo) is invalid: Invocation loop: arg(foo) -> foo -> arg(foo)", - Exceptions.toMessageString(e)); + Exceptions.toMessageString(e)); } } @Test - public void testNoLoopWithSameLocalArgument() throws ParseException { + void testNoLoopWithSameLocalArgument() throws ParseException { RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry); builder.addSchema( "search test {\n" + - " document test { \n" + - " field a type string { \n" + - " indexing: index \n" + - " }\n" + - " }\n" + - " \n" + - " rank-profile test {\n" + - " first-phase {\n" + - " expression: foo(3)\n" + - " }\n" + - " function foo(a1) {\n" + - " expression: bar(3)\n" + - " }\n" + - " function bar(a1) {\n" + - " expression: a1*2\n" + - " }\n" + - " }\n" + - "\n" + - "}\n"); + " document test { \n" + + " field a type string { \n" + + " indexing: index \n" + + " }\n" + + " }\n" + + " \n" + + " rank-profile test {\n" + + " first-phase {\n" + + " expression: foo(3)\n" + + " }\n" + + " function foo(a1) {\n" + + " expression: bar(3)\n" + + " }\n" + + " function bar(a1) {\n" + + " expression: a1*2\n" + + " }\n" + + " }\n" + + "\n" + + "}\n"); builder.build(true); } @Test - public void testNoLoopWithMultipleInvocations() throws ParseException { + void testNoLoopWithMultipleInvocations() throws ParseException { RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry); builder.addSchema( "search test {\n" + - " document test { \n" + - " field a type string { \n" + - " indexing: index \n" + - " }\n" + - " }\n" + - " \n" + - " rank-profile test {\n" + - " first-phase {\n" + - " expression: foo(3)\n" + - " }\n" + - " function foo(a1) {\n" + - " expression: bar(3) + bar(a1)\n" + - " }\n" + - " function bar(a1) {\n" + - " expression: a1*2\n" + - " }\n" + - " }\n" + - "\n" + - "}\n"); + " document test { \n" + + " field a type string { \n" + + " indexing: index \n" + + " }\n" + + " }\n" + + " \n" + + " rank-profile test {\n" + + " first-phase {\n" + + " expression: foo(3)\n" + + " }\n" + + " function foo(a1) {\n" + + " expression: bar(3) + bar(a1)\n" + + " }\n" + + " function bar(a1) {\n" + + " expression: a1*2\n" + + " }\n" + + " }\n" + + "\n" + + "}\n"); builder.build(true); } @Test - public void testNoLoopWithBoundIdentifiers() throws ParseException { + void testNoLoopWithBoundIdentifiers() throws ParseException { RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry); builder.addSchema( "search test {\n" + - " document test { \n" + - " }\n" + - " rank-profile test {\n" + - " first-phase {\n" + - " expression: foo(bar(2))\n" + - " }\n" + - " function foo(x) {\n" + - " expression: x * x\n" + - " }\n" + - " function bar(x) {\n" + - " expression: x + x\n" + - " }\n" + - " }\n" + - "}\n"); + " document test { \n" + + " }\n" + + " rank-profile test {\n" + + " first-phase {\n" + + " expression: foo(bar(2))\n" + + " }\n" + + " function foo(x) {\n" + + " expression: x * x\n" + + " }\n" + + " function bar(x) {\n" + + " expression: x + x\n" + + " }\n" + + " }\n" + + "}\n"); builder.build(true); } @Test - public void testNoLoopWithTheSameNestedIdentifierWhichIsUnbound() throws ParseException { + void testNoLoopWithTheSameNestedIdentifierWhichIsUnbound() throws ParseException { RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry); builder.addSchema( "search test {\n" + - " document test { \n" + - " }\n" + - " rank-profile test {\n" + - " first-phase {\n" + - " expression: foo()\n" + - " }\n" + - " function foo() {\n" + - " expression: bar(x)\n" + - " }\n" + - " function bar(x) {\n" + - " expression: x + x\n" + - " }\n" + - " }\n" + - "}\n"); + " document test { \n" + + " }\n" + + " rank-profile test {\n" + + " first-phase {\n" + + " expression: foo()\n" + + " }\n" + + " function foo() {\n" + + " expression: bar(x)\n" + + " }\n" + + " function bar(x) {\n" + + " expression: x + x\n" + + " }\n" + + " }\n" + + "}\n"); builder.build(true); } @Test - public void testNoLoopWithTheSameAlternatingNestedIdentifierWhichIsUnbound() throws ParseException { + void testNoLoopWithTheSameAlternatingNestedIdentifierWhichIsUnbound() throws ParseException { RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry); builder.addSchema( "search test {\n" + - " document test { \n" + - " }\n" + - " rank-profile test {\n" + - " first-phase {\n" + - " expression: foo()\n" + - " }\n" + - " function foo() {\n" + - " expression: bar(x)\n" + - " }\n" + - " function bar(y) {\n" + - " expression: baz(y)\n" + - " }\n" + - " function baz(x) {\n" + - " expression: x + x\n" + - " }\n" + - " }\n" + - "}\n"); + " document test { \n" + + " }\n" + + " rank-profile test {\n" + + " first-phase {\n" + + " expression: foo()\n" + + " }\n" + + " function foo() {\n" + + " expression: bar(x)\n" + + " }\n" + + " function bar(y) {\n" + + " expression: baz(y)\n" + + " }\n" + + " function baz(x) {\n" + + " expression: x + x\n" + + " }\n" + + " }\n" + + "}\n"); builder.build(true); } diff --git a/config-model/src/test/java/com/yahoo/schema/RankingExpressionShadowingTestCase.java b/config-model/src/test/java/com/yahoo/schema/RankingExpressionShadowingTestCase.java index 250879b1570..33bbdb2fd6f 100644 --- a/config-model/src/test/java/com/yahoo/schema/RankingExpressionShadowingTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/RankingExpressionShadowingTestCase.java @@ -12,11 +12,11 @@ import com.yahoo.schema.derived.AttributeFields; import com.yahoo.schema.derived.RawRankProfile; import com.yahoo.schema.parser.ParseException; import ai.vespa.rankingexpression.importer.configmodelview.ImportedMlModels; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.List; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author lesters @@ -24,7 +24,7 @@ import static org.junit.Assert.assertEquals; public class RankingExpressionShadowingTestCase extends AbstractSchemaTestCase { @Test - public void testBasicFunctionShadowing() throws ParseException { + void testBasicFunctionShadowing() throws ParseException { RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry); builder.addSchema( @@ -52,14 +52,14 @@ public class RankingExpressionShadowingTestCase extends AbstractSchemaTestCase { assertEquals("(rankingExpression(sin@).rankingScript, 2 * 2)", censorBindingHash(testRankProperties.get(0).toString())); assertEquals("(rankingExpression(sin).rankingScript, x * x)", - testRankProperties.get(1).toString()); + testRankProperties.get(1).toString()); assertEquals("(vespa.rank.firstphase, rankingExpression(sin@))", - censorBindingHash(testRankProperties.get(2).toString())); + censorBindingHash(testRankProperties.get(2).toString())); } @Test - public void testMultiLevelFunctionShadowing() throws ParseException { + void testMultiLevelFunctionShadowing() throws ParseException { RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry); builder.addSchema( @@ -97,21 +97,21 @@ public class RankingExpressionShadowingTestCase extends AbstractSchemaTestCase { assertEquals("(rankingExpression(sin@).rankingScript, rankingExpression(cos@))", censorBindingHash(testRankProperties.get(2).toString())); assertEquals("(rankingExpression(tan).rankingScript, x * x)", - testRankProperties.get(3).toString()); + testRankProperties.get(3).toString()); assertEquals("(rankingExpression(tan@).rankingScript, x * x)", - censorBindingHash(testRankProperties.get(4).toString())); + censorBindingHash(testRankProperties.get(4).toString())); assertEquals("(rankingExpression(cos).rankingScript, rankingExpression(tan@))", - censorBindingHash(testRankProperties.get(5).toString())); + censorBindingHash(testRankProperties.get(5).toString())); assertEquals("(rankingExpression(cos@).rankingScript, rankingExpression(tan@))", censorBindingHash(testRankProperties.get(6).toString())); assertEquals("(rankingExpression(sin).rankingScript, rankingExpression(cos@))", - censorBindingHash(testRankProperties.get(7).toString())); + censorBindingHash(testRankProperties.get(7).toString())); assertEquals("(vespa.rank.firstphase, rankingExpression(sin@))", - censorBindingHash(testRankProperties.get(8).toString())); + censorBindingHash(testRankProperties.get(8).toString())); } @Test - public void testFunctionShadowingArguments() throws ParseException { + void testFunctionShadowingArguments() throws ParseException { RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry); builder.addSchema( @@ -141,15 +141,15 @@ public class RankingExpressionShadowingTestCase extends AbstractSchemaTestCase { assertEquals("(rankingExpression(sin@).rankingScript, cos(5.0) * cos(5.0))", censorBindingHash(testRankProperties.get(1).toString())); assertEquals("(rankingExpression(sin).rankingScript, x * x)", - testRankProperties.get(2).toString()); + testRankProperties.get(2).toString()); assertEquals("(vespa.rank.firstphase, rankingExpression(firstphase))", - censorBindingHash(testRankProperties.get(3).toString())); + censorBindingHash(testRankProperties.get(3).toString())); assertEquals("(rankingExpression(firstphase).rankingScript, cos(rankingExpression(sin@)) + rankingExpression(sin@))", - censorBindingHash(testRankProperties.get(4).toString())); + censorBindingHash(testRankProperties.get(4).toString())); } @Test - public void testNeuralNetworkSetup() throws ParseException { + void testNeuralNetworkSetup() throws ParseException { // Note: the type assigned to query profile and constant tensors here is not the correct type RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); QueryProfileRegistry queryProfiles = queryProfileWith("query(q)", "tensor(input[1])"); diff --git a/config-model/src/test/java/com/yahoo/schema/RankingExpressionValidationTestCase.java b/config-model/src/test/java/com/yahoo/schema/RankingExpressionValidationTestCase.java index e42acee9bed..099b44bd6dd 100644 --- a/config-model/src/test/java/com/yahoo/schema/RankingExpressionValidationTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/RankingExpressionValidationTestCase.java @@ -4,17 +4,18 @@ package com.yahoo.schema; import com.yahoo.schema.derived.DerivedConfiguration; import com.yahoo.schema.parser.ParseException; import com.yahoo.yolean.Exceptions; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; /** * @author bratseth */ public class RankingExpressionValidationTestCase extends AbstractSchemaTestCase { @Test - public void testInvalidExpressionProducesException() throws ParseException { + void testInvalidExpressionProducesException() throws ParseException { assertFailsExpression("&/%(/%&"); assertFailsExpression("if(a==b,b)"); } diff --git a/config-model/src/test/java/com/yahoo/schema/ReservedWordsAsFieldNamesTestCase.java b/config-model/src/test/java/com/yahoo/schema/ReservedWordsAsFieldNamesTestCase.java index df9d4a63650..10cb4e60e0b 100644 --- a/config-model/src/test/java/com/yahoo/schema/ReservedWordsAsFieldNamesTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/ReservedWordsAsFieldNamesTestCase.java @@ -2,11 +2,11 @@ package com.yahoo.schema; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author bratseth @@ -14,7 +14,7 @@ import static org.junit.Assert.assertNotNull; public class ReservedWordsAsFieldNamesTestCase extends AbstractSchemaTestCase { @Test - public void testIt() throws IOException, ParseException { + void testIt() throws IOException, ParseException { Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/reserved_words_as_field_names.sd"); assertNotNull(schema.getDocument().getField("inline")); assertNotNull(schema.getDocument().getField("constants")); diff --git a/config-model/src/test/java/com/yahoo/schema/SchemaImporterTestCase.java b/config-model/src/test/java/com/yahoo/schema/SchemaImporterTestCase.java index 929c407215a..8245119ffd7 100644 --- a/config-model/src/test/java/com/yahoo/schema/SchemaImporterTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/SchemaImporterTestCase.java @@ -13,17 +13,12 @@ import com.yahoo.schema.parser.ParseException; import com.yahoo.schema.processing.MakeAliases; import com.yahoo.vespa.documentmodel.SummaryTransform; import com.yahoo.vespa.model.container.search.QueryProfiles; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Iterator; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; /** * Tests importing of search definitions @@ -34,7 +29,7 @@ public class SchemaImporterTestCase extends AbstractSchemaTestCase { @Test @SuppressWarnings("deprecation") - public void testSimpleImporting() throws IOException, ParseException { + void testSimpleImporting() throws IOException, ParseException { RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); ApplicationBuilder sb = new ApplicationBuilder(rankProfileRegistry, new QueryProfileRegistry()); sb.addSchemaFile("src/test/examples/simple.sd"); @@ -62,7 +57,7 @@ public class SchemaImporterTestCase extends AbstractSchemaTestCase { assertEquals("aliaz", titleAliases.next()); assertEquals("analias.totitle", titleAliases.next()); assertEquals("analias.todefault", - schema.getIndex("default").aliasIterator().next()); + schema.getIndex("default").aliasIterator().next()); assertEquals(RankType.IDENTITY, field.getRankType()); assertEquals(0, field.getAttributes().size()); assertNull(field.getStemming()); @@ -72,9 +67,9 @@ public class SchemaImporterTestCase extends AbstractSchemaTestCase { field = (SDField) document.getField("description"); assertEquals(RankType.ABOUT, field.getRankType()); assertEquals(SummaryTransform.NONE, - field.getSummaryField("description").getTransform()); + field.getSummaryField("description").getTransform()); assertEquals(SummaryTransform.DYNAMICTEASER, - field.getSummaryField("dyndesc").getTransform()); + field.getSummaryField("dyndesc").getTransform()); assertNull(field.getStemming()); assertTrue(field.getNormalizing().doRemoveAccents()); assertEquals("hallo", schema.getIndex("description").aliasIterator().next()); @@ -94,7 +89,7 @@ public class SchemaImporterTestCase extends AbstractSchemaTestCase { // Fifth field field = (SDField) document.getField("popularity"); assertEquals("{ input popularity | attribute popularity; }", - field.getIndexingScript().toString()); + field.getIndexingScript().toString()); // Sixth field field = (SDField) document.getField("measurement"); @@ -105,17 +100,17 @@ public class SchemaImporterTestCase extends AbstractSchemaTestCase { // Seventh field field = schema.getConcreteField("categories"); assertEquals("{ input categories_src | lowercase | normalize | tokenize normalize stem:\"BEST\" | index categories; }", - field.getIndexingScript().toString()); + field.getIndexingScript().toString()); // Eight field - field= schema.getConcreteField("categoriesagain"); + field = schema.getConcreteField("categoriesagain"); assertEquals("{ input categoriesagain_src | lowercase | normalize | tokenize normalize stem:\"BEST\" | index categoriesagain; }", - field.getIndexingScript().toString()); + field.getIndexingScript().toString()); // Ninth field - field= schema.getConcreteField("exactemento"); + field = schema.getConcreteField("exactemento"); assertEquals("{ input exactemento_src | lowercase | tokenize normalize stem:\"BEST\" | index exactemento | summary exactemento; }", - field.getIndexingScript().toString()); + field.getIndexingScript().toString()); // Tenth field field = schema.getConcreteField("category_arr"); @@ -140,12 +135,12 @@ public class SchemaImporterTestCase extends AbstractSchemaTestCase { assertTrue(profile.inheritedNames().isEmpty()); assertNull(profile.getDeclaredRankSetting("measurement", RankProfile.RankSetting.Type.RANKTYPE)); assertEquals(RankType.EMPTY, - profile.getRankSetting("measurement", RankProfile.RankSetting.Type.RANKTYPE).getValue()); + profile.getRankSetting("measurement", RankProfile.RankSetting.Type.RANKTYPE).getValue()); profile = rankProfileRegistry.get(schema, "experimental"); assertNotNull(profile); assertEquals("default", profile.inheritedNames().get(0)); assertEquals(RankType.IDENTITY, - profile.getDeclaredRankSetting("measurement", RankProfile.RankSetting.Type.RANKTYPE).getValue()); + profile.getDeclaredRankSetting("measurement", RankProfile.RankSetting.Type.RANKTYPE).getValue()); profile = rankProfileRegistry.get(schema, "other"); assertNotNull(profile); @@ -153,17 +148,17 @@ public class SchemaImporterTestCase extends AbstractSchemaTestCase { // The extra-document field SDField exact = schema.getConcreteField("exact"); - assertNotNull("Extra field was parsed", exact); + assertNotNull(exact, "Extra field was parsed"); assertEquals("exact", exact.getName()); assertEquals(Stemming.NONE, exact.getStemming()); assertFalse(exact.getNormalizing().doRemoveAccents()); assertEquals("{ input title . \" \" . input category | tokenize | summary exact | index exact; }", - exact.getIndexingScript().toString()); + exact.getIndexingScript().toString()); assertEquals(RankType.IDENTITY, exact.getRankType()); } @Test - public void testDocumentImporting() throws IOException, ParseException { + void testDocumentImporting() throws IOException, ParseException { try { // Having two documents in one sd-file is illegal. ApplicationBuilder.buildFromFile("src/test/examples/documents.sd"); @@ -173,9 +168,9 @@ public class SchemaImporterTestCase extends AbstractSchemaTestCase { } @Test - public void testIdImporting() throws IOException, ParseException { + void testIdImporting() throws IOException, ParseException { Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/strange.sd"); - SDField idecidemyide = (SDField)schema.getDocument().getField("idecidemyide"); + SDField idecidemyide = (SDField) schema.getDocument().getField("idecidemyide"); assertEquals(5, idecidemyide.getId()); SDField sodoi = (SDField) schema.getDocument().getField("sodoi"); assertEquals(7, sodoi.getId()); diff --git a/config-model/src/test/java/com/yahoo/schema/SchemaParsingTestCase.java b/config-model/src/test/java/com/yahoo/schema/SchemaParsingTestCase.java index 8fe691db802..c8657df23ce 100644 --- a/config-model/src/test/java/com/yahoo/schema/SchemaParsingTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/SchemaParsingTestCase.java @@ -5,9 +5,10 @@ import java.io.IOException; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; /** * Tests that search definitions are parsed correctly and that correct line number is reported in @@ -18,23 +19,23 @@ import static org.junit.Assert.*; public class SchemaParsingTestCase extends AbstractSchemaTestCase { @Test - public void requireThatIndexingExpressionsCanBeParsed() throws Exception { + void requireThatIndexingExpressionsCanBeParsed() throws Exception { assertNotNull(ApplicationBuilder.buildFromFile("src/test/examples/simple.sd")); } @Test - public void requireThatParseExceptionPositionIsCorrect() throws Exception { + void requireThatParseExceptionPositionIsCorrect() throws Exception { try { ApplicationBuilder.buildFromFile("src/test/examples/invalid_sd_construct.sd"); } catch (ParseException e) { - if ( ! e.getMessage().contains("at line 5, column 36.")) { + if (!e.getMessage().contains("at line 5, column 36.")) { throw e; } } } @Test - public void requireThatParserHandlesLexicalError() throws Exception { + void requireThatParserHandlesLexicalError() throws Exception { try { ApplicationBuilder.buildFromFile("src/test/examples/invalid_sd_lexical_error.sd"); } catch (ParseException e) { @@ -45,7 +46,7 @@ public class SchemaParsingTestCase extends AbstractSchemaTestCase { } @Test - public void requireErrorWhenJunkAfterSearchBlock() throws IOException, ParseException { + void requireErrorWhenJunkAfterSearchBlock() throws IOException, ParseException { try { ApplicationBuilder.buildFromFile("src/test/examples/invalid_sd_junk_at_end.sd"); fail("Illegal junk at end of SD passed"); @@ -57,7 +58,7 @@ public class SchemaParsingTestCase extends AbstractSchemaTestCase { } @Test - public void requireErrorWhenMissingClosingSearchBracket() throws IOException, ParseException { + void requireErrorWhenMissingClosingSearchBracket() throws IOException, ParseException { try { ApplicationBuilder.buildFromFile("src/test/examples/invalid_sd_no_closing_bracket.sd"); fail("SD without closing bracket passed"); @@ -69,12 +70,12 @@ public class SchemaParsingTestCase extends AbstractSchemaTestCase { } @Test - public void illegalSearchDefinitionName() throws IOException, ParseException { + void illegalSearchDefinitionName() throws IOException, ParseException { try { ApplicationBuilder.buildFromFile("src/test/examples/invalid-name.sd"); fail("Name with dash passed"); } catch (ParseException e) { - if ( ! e.getMessage().contains("invalid-name")) { + if (!e.getMessage().contains("invalid-name")) { throw e; } } diff --git a/config-model/src/test/java/com/yahoo/schema/SchemaTestCase.java b/config-model/src/test/java/com/yahoo/schema/SchemaTestCase.java index 67d8ce4ff78..54e47dea6bb 100644 --- a/config-model/src/test/java/com/yahoo/schema/SchemaTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/SchemaTestCase.java @@ -7,13 +7,10 @@ import com.yahoo.schema.processing.ImportedFieldsResolver; import com.yahoo.schema.processing.OnnxModelTypeResolver; import com.yahoo.vespa.documentmodel.DocumentSummary; import com.yahoo.vespa.model.test.utils.DeployLoggerStub; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static com.yahoo.config.model.test.TestUtil.joinLines; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; /** * Schema tests that don't depend on files. @@ -23,17 +20,17 @@ import static org.junit.Assert.fail; public class SchemaTestCase { @Test - public void testValidationOfInheritedSchema() throws ParseException { + void testValidationOfInheritedSchema() throws ParseException { try { String schema = joinLines( "schema test inherits nonesuch {" + - " document test inherits nonesuch {" + - " }" + - "}"); + " document test inherits nonesuch {" + + " }" + + "}"); DeployLoggerStub logger = new DeployLoggerStub(); ApplicationBuilder.createFromStrings(logger, schema); assertEquals("schema 'test' inherits 'nonesuch', but this schema does not exist", - logger.entries.get(0).message); + logger.entries.get(0).message); fail("Expected exception"); } catch (IllegalArgumentException e) { @@ -42,129 +39,129 @@ public class SchemaTestCase { } @Test - public void testValidationOfSchemaAndDocumentInheritanceConsistency() throws ParseException { + void testValidationOfSchemaAndDocumentInheritanceConsistency() throws ParseException { try { String parent = joinLines( "schema parent {" + - " document parent {" + - " field pf1 type string {" + - " indexing: summary" + - " }" + - " }" + - "}"); + " document parent {" + + " field pf1 type string {" + + " indexing: summary" + + " }" + + " }" + + "}"); String child = joinLines( "schema child inherits parent {" + - " document child {" + - " field cf1 type string {" + - " indexing: summary" + - " }" + - " }" + - "}"); + " document child {" + + " field cf1 type string {" + + " indexing: summary" + + " }" + + " }" + + "}"); ApplicationBuilder.createFromStrings(new DeployLoggerStub(), parent, child); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("schema 'child' inherits 'parent', " + - "but its document type does not inherit the parent's document type" - , e.getMessage()); + "but its document type does not inherit the parent's document type" + , e.getMessage()); } } @Test - public void testSchemaInheritance() throws ParseException { + void testSchemaInheritance() throws ParseException { String parentLines = joinLines( "schema parent {" + - " document parent {" + - " field pf1 type string {" + - " indexing: summary" + - " }" + - " }" + - " fieldset parent_set {" + - " fields: pf1" + - " }" + - " stemming: none" + - " index parent_index {" + - " stemming: best" + - " }" + - " field parent_field type string {" + - " indexing: input pf1 | lowercase | index | attribute | summary" + - " }" + - " rank-profile parent_profile {" + - " }" + - " constant parent_constant {" + - " file: constants/my_constant_tensor_file.json" + - " type: tensor<float>(x{},y{})" + - " }" + - " onnx-model parent_model {" + - " file: models/my_model.onnx" + - " }" + - " document-summary parent_summary {" + - " summary pf1 type string {}" + - " }" + - " import field parentschema_ref.name as parent_imported {}" + - " raw-as-base64-in-summary" + - "}"); + " document parent {" + + " field pf1 type string {" + + " indexing: summary" + + " }" + + " }" + + " fieldset parent_set {" + + " fields: pf1" + + " }" + + " stemming: none" + + " index parent_index {" + + " stemming: best" + + " }" + + " field parent_field type string {" + + " indexing: input pf1 | lowercase | index | attribute | summary" + + " }" + + " rank-profile parent_profile {" + + " }" + + " constant parent_constant {" + + " file: constants/my_constant_tensor_file.json" + + " type: tensor<float>(x{},y{})" + + " }" + + " onnx-model parent_model {" + + " file: models/my_model.onnx" + + " }" + + " document-summary parent_summary {" + + " summary pf1 type string {}" + + " }" + + " import field parentschema_ref.name as parent_imported {}" + + " raw-as-base64-in-summary" + + "}"); String child1Lines = joinLines( "schema child1 inherits parent {" + - " document child1 inherits parent {" + - " field c1f1 type string {" + - " indexing: summary" + - " }" + - " }" + - " fieldset child1_set {" + - " fields: c1f1, pf1" + - " }" + - " stemming: shortest" + - " index child1_index {" + - " stemming: shortest" + - " }" + - " field child1_field type string {" + - " indexing: input pf1 | lowercase | index | attribute | summary" + - " }" + - " rank-profile child1_profile inherits parent_profile {" + - " constants {" + - " child1_constant tensor<float>(x{},y{}): file:constants/my_constant_tensor_file.json" + - " }" + - " }" + - " onnx-model child1_model {" + - " file: models/my_model.onnx" + - " }" + - " document-summary child1_summary inherits parent_summary {" + - " summary c1f1 type string {}" + - " }" + - " import field parentschema_ref.name as child1_imported {}" + - "}"); + " document child1 inherits parent {" + + " field c1f1 type string {" + + " indexing: summary" + + " }" + + " }" + + " fieldset child1_set {" + + " fields: c1f1, pf1" + + " }" + + " stemming: shortest" + + " index child1_index {" + + " stemming: shortest" + + " }" + + " field child1_field type string {" + + " indexing: input pf1 | lowercase | index | attribute | summary" + + " }" + + " rank-profile child1_profile inherits parent_profile {" + + " constants {" + + " child1_constant tensor<float>(x{},y{}): file:constants/my_constant_tensor_file.json" + + " }" + + " }" + + " onnx-model child1_model {" + + " file: models/my_model.onnx" + + " }" + + " document-summary child1_summary inherits parent_summary {" + + " summary c1f1 type string {}" + + " }" + + " import field parentschema_ref.name as child1_imported {}" + + "}"); String child2Lines = joinLines( "schema child2 inherits parent {" + - " document child2 inherits parent {" + - " field c2f1 type string {" + - " indexing: summary" + - " }" + - " }" + - " fieldset child2_set {" + - " fields: c2f1, pf1" + - " }" + - " stemming: shortest" + - " index child2_index {" + - " stemming: shortest" + - " }" + - " field child2_field type string {" + - " indexing: input pf1 | lowercase | index | attribute | summary" + - " }" + - " rank-profile child2_profile inherits parent_profile {" + - " }" + - " constant child2_constant {" + - " file: constants/my_constant_tensor_file.json" + - " type: tensor<float>(x{},y{})" + - " }" + - " onnx-model child2_model {" + - " file: models/my_model.onnx" + - " }" + - " document-summary child2_summary inherits parent_summary {" + - " summary c2f1 type string {}" + - " }" + - " import field parentschema_ref.name as child2_imported {}" + - "}"); + " document child2 inherits parent {" + + " field c2f1 type string {" + + " indexing: summary" + + " }" + + " }" + + " fieldset child2_set {" + + " fields: c2f1, pf1" + + " }" + + " stemming: shortest" + + " index child2_index {" + + " stemming: shortest" + + " }" + + " field child2_field type string {" + + " indexing: input pf1 | lowercase | index | attribute | summary" + + " }" + + " rank-profile child2_profile inherits parent_profile {" + + " }" + + " constant child2_constant {" + + " file: constants/my_constant_tensor_file.json" + + " type: tensor<float>(x{},y{})" + + " }" + + " onnx-model child2_model {" + + " file: models/my_model.onnx" + + " }" + + " document-summary child2_summary inherits parent_summary {" + + " summary c2f1 type string {}" + + " }" + + " import field parentschema_ref.name as child2_imported {}" + + "}"); ApplicationBuilder builder = new ApplicationBuilder(new DeployLoggerStub()); builder.processorsToSkip().add(OnnxModelTypeResolver.class); // Avoid discovering the Onnx model referenced does not exist @@ -259,55 +256,55 @@ public class SchemaTestCase { } @Test - public void testSchemaInheritanceEmptyChildren() throws ParseException { + void testSchemaInheritanceEmptyChildren() throws ParseException { String parentLines = joinLines( "schema parent {" + - " document parent {" + - " field pf1 type string {" + - " indexing: summary" + - " }" + - " }" + - " fieldset parent_set {" + - " fields: pf1" + - " }" + - " stemming: none" + - " index parent_index {" + - " stemming: best" + - " }" + - " field parent_field type string {" + - " indexing: input pf1 | lowercase | index | attribute | summary" + - " }" + - " rank-profile parent_profile {" + - " }" + - " constant parent_constant {" + - " file: constants/my_constant_tensor_file.json" + - " type: tensor<float>(x{},y{})" + - " }" + - " onnx-model parent_model {" + - " file: models/my_model.onnx" + - " }" + - " document-summary parent_summary {" + - " summary pf1 type string {}" + - " }" + - " import field parentschema_ref.name as parent_imported {}" + - " raw-as-base64-in-summary" + - "}"); + " document parent {" + + " field pf1 type string {" + + " indexing: summary" + + " }" + + " }" + + " fieldset parent_set {" + + " fields: pf1" + + " }" + + " stemming: none" + + " index parent_index {" + + " stemming: best" + + " }" + + " field parent_field type string {" + + " indexing: input pf1 | lowercase | index | attribute | summary" + + " }" + + " rank-profile parent_profile {" + + " }" + + " constant parent_constant {" + + " file: constants/my_constant_tensor_file.json" + + " type: tensor<float>(x{},y{})" + + " }" + + " onnx-model parent_model {" + + " file: models/my_model.onnx" + + " }" + + " document-summary parent_summary {" + + " summary pf1 type string {}" + + " }" + + " import field parentschema_ref.name as parent_imported {}" + + " raw-as-base64-in-summary" + + "}"); String childLines = joinLines( "schema child inherits parent {" + - " document child inherits parent {" + - " field cf1 type string {" + - " indexing: summary" + - " }" + - " }" + - "}"); + " document child inherits parent {" + + " field cf1 type string {" + + " indexing: summary" + + " }" + + " }" + + "}"); String grandchildLines = joinLines( "schema grandchild inherits child {" + - " document grandchild inherits child {" + - " field gf1 type string {" + - " indexing: summary" + - " }" + - " }" + - "}"); + " document grandchild inherits child {" + + " field gf1 type string {" + + " indexing: summary" + + " }" + + " }" + + "}"); ApplicationBuilder builder = new ApplicationBuilder(new DeployLoggerStub()); builder.processorsToSkip().add(OnnxModelTypeResolver.class); // Avoid discovering the Onnx model referenced does not exist @@ -323,100 +320,100 @@ public class SchemaTestCase { } @Test - public void testInheritingMultipleRankProfilesWithOverlappingConstructsIsDisallowed1() throws ParseException { + void testInheritingMultipleRankProfilesWithOverlappingConstructsIsDisallowed1() throws ParseException { try { String profile = joinLines( "schema test {" + - " document test {" + - " field title type string {" + - " indexing: summary" + - " }" + - " }" + - " rank-profile r1 {" + - " first-phase {" + - " expression: fieldMatch(title)" + - " }" + - " }" + - " rank-profile r2 {" + - " first-phase {" + - " expression: fieldMatch(title)" + - " }" + - " }" + - " rank-profile r3 inherits r1, r2 {" + - " }" + - "}"); + " document test {" + + " field title type string {" + + " indexing: summary" + + " }" + + " }" + + " rank-profile r1 {" + + " first-phase {" + + " expression: fieldMatch(title)" + + " }" + + " }" + + " rank-profile r2 {" + + " first-phase {" + + " expression: fieldMatch(title)" + + " }" + + " }" + + " rank-profile r3 inherits r1, r2 {" + + " }" + + "}"); ApplicationBuilder.createFromStrings(new DeployLoggerStub(), profile); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("Only one of the profiles inherited by rank profile 'r3' can contain first-phase expression, but it is present in multiple", - e.getMessage()); + e.getMessage()); } } @Test - public void testInheritingMultipleRankProfilesWithOverlappingConstructsIsAllowedWhenDefinedInChild() throws ParseException { + void testInheritingMultipleRankProfilesWithOverlappingConstructsIsAllowedWhenDefinedInChild() throws ParseException { String profile = joinLines( "schema test {" + - " document test {" + - " field title type string {" + - " indexing: summary" + - " }" + - " field myFilter type string {" + - " indexing: attribute\n" + - " rank: filter" + - " }" + - " }" + - " rank-profile r1 {" + - " first-phase {" + - " expression: fieldMatch(title)" + - " }" + - " }" + - " rank-profile r2 {" + - " first-phase {" + - " expression: fieldMatch(title)" + - " }" + - " }" + - " rank-profile r3 inherits r1, r2 {" + - " first-phase {" + // Redefined here so this does not cause failure - " expression: nativeRank" + - " }" + - " }" + - "}"); + " document test {" + + " field title type string {" + + " indexing: summary" + + " }" + + " field myFilter type string {" + + " indexing: attribute\n" + + " rank: filter" + + " }" + + " }" + + " rank-profile r1 {" + + " first-phase {" + + " expression: fieldMatch(title)" + + " }" + + " }" + + " rank-profile r2 {" + + " first-phase {" + + " expression: fieldMatch(title)" + + " }" + + " }" + + " rank-profile r3 inherits r1, r2 {" + + " first-phase {" + // Redefined here so this does not cause failure + " expression: nativeRank" + + " }" + + " }" + + "}"); var builder = ApplicationBuilder.createFromStrings(new DeployLoggerStub(), profile); var r3 = builder.getRankProfileRegistry().resolve(builder.application().schemas().get("test").getDocument(), "r3"); assertEquals(1, r3.allFilterFields().size()); } @Test - public void testInheritingMultipleRankProfilesWithOverlappingConstructsIsDisallowed2() throws ParseException { + void testInheritingMultipleRankProfilesWithOverlappingConstructsIsDisallowed2() throws ParseException { try { String profile = joinLines( "schema test {" + - " document test {" + - " field title type string {" + - " indexing: summary" + - " }" + - " }" + - " rank-profile r1 {" + - " function f1() {" + - " expression: fieldMatch(title)" + - " }" + - " }" + - " rank-profile r2 {" + - " function f1() {" + - " expression: fieldMatch(title)" + - " }" + - " }" + - " rank-profile r3 inherits r1, r2 {" + - " }" + - "}"); + " document test {" + + " field title type string {" + + " indexing: summary" + + " }" + + " }" + + " rank-profile r1 {" + + " function f1() {" + + " expression: fieldMatch(title)" + + " }" + + " }" + + " rank-profile r2 {" + + " function f1() {" + + " expression: fieldMatch(title)" + + " }" + + " }" + + " rank-profile r3 inherits r1, r2 {" + + " }" + + "}"); ApplicationBuilder.createFromStrings(new DeployLoggerStub(), profile); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("rank profile 'r3' inherits rank profile 'r2' which contains function 'f1', but this function is already defined in another profile this inherits", - e.getMessage()); + e.getMessage()); } } diff --git a/config-model/src/test/java/com/yahoo/schema/StemmingSettingTestCase.java b/config-model/src/test/java/com/yahoo/schema/StemmingSettingTestCase.java index 5dd75166783..e0f1f8dfa1c 100644 --- a/config-model/src/test/java/com/yahoo/schema/StemmingSettingTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/StemmingSettingTestCase.java @@ -4,12 +4,12 @@ package com.yahoo.schema; import com.yahoo.schema.document.SDField; import com.yahoo.schema.document.Stemming; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; /** * Stemming settings test @@ -19,7 +19,7 @@ import static org.junit.Assert.assertNull; public class StemmingSettingTestCase extends AbstractSchemaTestCase { @Test - public void testStemmingSettings() throws IOException, ParseException { + void testStemmingSettings() throws IOException, ParseException { Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/stemmingsetting.sd"); SDField artist = (SDField) schema.getDocument().getField("artist"); @@ -42,7 +42,7 @@ public class StemmingSettingTestCase extends AbstractSchemaTestCase { } @Test - public void requireThatStemmingIsDefaultBest() throws IOException, ParseException { + void requireThatStemmingIsDefaultBest() throws IOException, ParseException { Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/stemmingdefault.sd"); assertNull(schema.getConcreteField("my_str").getStemming()); assertEquals(Stemming.BEST, schema.getConcreteField("my_str").getStemming(schema)); diff --git a/config-model/src/test/java/com/yahoo/schema/StructTestCase.java b/config-model/src/test/java/com/yahoo/schema/StructTestCase.java index b140892ed5e..087ce6ee935 100755 --- a/config-model/src/test/java/com/yahoo/schema/StructTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/StructTestCase.java @@ -6,10 +6,12 @@ import com.yahoo.document.config.DocumenttypesConfig; import com.yahoo.document.config.DocumentmanagerConfig; import com.yahoo.schema.derived.Deriver; import com.yahoo.schema.parser.ParseException; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + import java.io.IOException; -import static org.junit.Assert.fail; + +import static org.junit.jupiter.api.Assertions.fail; /** * Tests importing of document containing array type fields @@ -19,25 +21,25 @@ import static org.junit.Assert.fail; public class StructTestCase extends AbstractSchemaTestCase { @Test - public void testStruct() throws IOException { + void testStruct() throws IOException { assertConfigFile("src/test/examples/structresult.cfg", - new DocumentmanagerConfig(Deriver.getDocumentManagerConfig("src/test/examples/struct.sd")) + "\n"); + new DocumentmanagerConfig(Deriver.getDocumentManagerConfig("src/test/examples/struct.sd")) + "\n"); } @Test - public void testBadStruct() throws IOException { + void testBadStruct() throws IOException { try { ApplicationBuilder.buildFromFile("src/test/examples/badstruct.sd"); fail("Should throw exception."); - } catch (IllegalArgumentException|ParseException expected) { - System.err.println("As expected, with message: "+expected.getMessage()); + } catch (IllegalArgumentException | ParseException expected) { + System.err.println("As expected, with message: " + expected.getMessage()); // success } } @Test - @Ignore - public void testStructAndDocumentWithSameNames() { + @Disabled + void testStructAndDocumentWithSameNames() { try { DocumenttypesConfig.Builder dt = Deriver.getDocumentTypesConfig("src/test/examples/structanddocumentwithsamenames.sd"); // while the above line may work, the config generated will fail. @@ -51,7 +53,7 @@ public class StructTestCase extends AbstractSchemaTestCase { * Declaring a struct before a document should work */ @Test - public void testStructOutsideDocumentLegal() throws IOException, ParseException { + void testStructOutsideDocumentLegal() throws IOException, ParseException { new ApplicationBuilder().addSchemaFile("src/test/examples/structoutsideofdocument.sd"); } diff --git a/config-model/src/test/java/com/yahoo/schema/SummaryTestCase.java b/config-model/src/test/java/com/yahoo/schema/SummaryTestCase.java index 0fab9b381fc..f33dc46f29b 100644 --- a/config-model/src/test/java/com/yahoo/schema/SummaryTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/SummaryTestCase.java @@ -5,7 +5,8 @@ import com.yahoo.schema.parser.ParseException; import com.yahoo.vespa.documentmodel.DocumentSummary; import com.yahoo.vespa.model.test.utils.DeployLoggerStub; import com.yahoo.vespa.objects.FieldBase; -import org.junit.Test; +import org.junit.jupiter.api.Test; + import static com.yahoo.config.model.test.TestUtil.joinLines; import java.util.Collection; @@ -14,9 +15,7 @@ import java.util.Optional; import java.util.logging.Level; import java.util.stream.Collectors; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; /** * Tests summary validation @@ -26,7 +25,7 @@ import static org.junit.Assert.fail; public class SummaryTestCase { @Test - public void testMemorySummary() throws ParseException { + void testMemorySummary() throws ParseException { String sd = joinLines( "schema memorysummary {", " document memorysummary {", @@ -44,7 +43,7 @@ public class SummaryTestCase { } @Test - public void testDiskSummary() throws ParseException { + void testDiskSummary() throws ParseException { String sd = joinLines( "schema disksummary {", " document-summary foobar {", @@ -65,13 +64,13 @@ public class SummaryTestCase { assertEquals(1, logger.entries.size()); assertEquals(Level.WARNING, logger.entries.get(0).level); assertEquals("summary field 'foo2' in document summary 'foobar' references source field 'ondisk', " + - "which is not an attribute: Using this summary will cause disk accesses. " + - "Set 'from-disk' on this summary class to silence this warning.", - logger.entries.get(0).message); + "which is not an attribute: Using this summary will cause disk accesses. " + + "Set 'from-disk' on this summary class to silence this warning.", + logger.entries.get(0).message); } @Test - public void testDiskSummaryExplicit() throws ParseException { + void testDiskSummaryExplicit() throws ParseException { String sd = joinLines( "schema disksummary {", " document disksummary {", @@ -94,7 +93,7 @@ public class SummaryTestCase { } @Test - public void testStructMemorySummary() throws ParseException { + void testStructMemorySummary() throws ParseException { String sd = joinLines( "schema structmemorysummary {", " document structmemorysummary {", @@ -125,7 +124,7 @@ public class SummaryTestCase { } @Test - public void testInheritance() throws Exception { + void testInheritance() throws Exception { String sd = joinLines( "schema music {", " document music {", @@ -174,17 +173,17 @@ public class SummaryTestCase { ); tests.forEach(testValue -> { var actualFields = testValue.summary.getSummaryFields().values().stream() - .map(FieldBase::getName) - .collect(Collectors.toList()); - assertEquals(testValue.summary.getName() + (testValue.parent == null ? " does not inherit anything" : " inherits " + testValue.parent.getName()), - Optional.ofNullable(testValue.parent), - testValue.summary.inherited()); - assertEquals("Summary " + testValue.summary.getName() + " has expected fields", testValue.fields, actualFields); + .map(FieldBase::getName) + .collect(Collectors.toList()); + assertEquals(Optional.ofNullable(testValue.parent), + testValue.summary.inherited(), + testValue.summary.getName() + (testValue.parent == null ? " does not inherit anything" : " inherits " + testValue.parent.getName())); + assertEquals(testValue.fields, actualFields, "Summary " + testValue.summary.getName() + " has expected fields"); }); } @Test - public void testRedeclaringInheritedFieldFails() throws Exception { + void testRedeclaringInheritedFieldFails() throws Exception { String sd = joinLines( "schema music {", " document music {", @@ -212,25 +211,25 @@ public class SummaryTestCase { fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("For schema 'music', summary class 'title2', summary field 'title': Can not use " + - "source 'title_short' for this summary field, an equally named field in summary class 'title' " + - "uses a different source: 'title'.", e.getMessage()); + "source 'title_short' for this summary field, an equally named field in summary class 'title' " + + "uses a different source: 'title'.", e.getMessage()); } } @Test - public void testValidationOfInheritedSummary() throws ParseException { + void testValidationOfInheritedSummary() throws ParseException { try { String schema = joinLines( "schema test {" + - " document test {" + - " }" + - " document-summary test_summary inherits nonesuch {" + - " }" + - "}"); + " document test {" + + " }" + + " document-summary test_summary inherits nonesuch {" + + " }" + + "}"); DeployLoggerStub logger = new DeployLoggerStub(); ApplicationBuilder.createFromStrings(logger, schema); assertEquals("document summary 'test_summary' inherits nonesuch but this is not present in schema 'test'", - logger.entries.get(0).message); + logger.entries.get(0).message); // fail("Expected failure"); } catch (IllegalArgumentException e) { @@ -240,29 +239,29 @@ public class SummaryTestCase { } @Test - public void testInheritingParentSummary() throws ParseException { + void testInheritingParentSummary() throws ParseException { String parent = joinLines( "schema parent {" + - " document parent {" + - " field pf1 type string {" + - " indexing: summary" + - " }" + - " }" + - " document-summary parent_summary {" + - " summary pf1 type string {}" + - " }" + - "}"); + " document parent {" + + " field pf1 type string {" + + " indexing: summary" + + " }" + + " }" + + " document-summary parent_summary {" + + " summary pf1 type string {}" + + " }" + + "}"); String child = joinLines( "schema child inherits parent {" + - " document child inherits parent {" + - " field cf1 type string {" + - " indexing: summary" + - " }" + - " }" + - " document-summary child_summary inherits parent_summary {" + - " summary cf1 type string {}" + - " }" + - "}"); + " document child inherits parent {" + + " field cf1 type string {" + + " indexing: summary" + + " }" + + " }" + + " document-summary child_summary inherits parent_summary {" + + " summary cf1 type string {}" + + " }" + + "}"); DeployLoggerStub logger = new DeployLoggerStub(); ApplicationBuilder.createFromStrings(logger, parent, child); logger.entries.forEach(e -> System.out.println(e)); diff --git a/config-model/src/test/java/com/yahoo/schema/UrlFieldValidationTestCase.java b/config-model/src/test/java/com/yahoo/schema/UrlFieldValidationTestCase.java index 83bb0d4548c..1509ca0bf9b 100644 --- a/config-model/src/test/java/com/yahoo/schema/UrlFieldValidationTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/UrlFieldValidationTestCase.java @@ -3,10 +3,10 @@ package com.yahoo.schema; import com.yahoo.schema.parser.ParseException; import com.yahoo.yolean.Exceptions; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author bratseth @@ -14,20 +14,20 @@ import static org.junit.Assert.fail; public class UrlFieldValidationTestCase { @Test - public void requireThatInheritedRiseFieldsStillCanBeInConflictButDontThrowException() throws ParseException { + void requireThatInheritedRiseFieldsStillCanBeInConflictButDontThrowException() throws ParseException { ApplicationBuilder builder = new ApplicationBuilder(); builder.addSchema("search test {" + - " document test { " + - " field a type uri { indexing: attribute | summary }" + - " }" + - "}"); + " document test { " + + " field a type uri { indexing: attribute | summary }" + + " }" + + "}"); try { builder.build(true); fail("Should have caused an exception"); // success } catch (IllegalArgumentException e) { assertEquals("Error in field 'a' in schema 'test': uri type fields cannot be attributes", - Exceptions.toMessageString(e)); + Exceptions.toMessageString(e)); } } diff --git a/config-model/src/test/java/com/yahoo/schema/derived/AnnotationsTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/AnnotationsTestCase.java index 60867261f93..e17634467ac 100755 --- a/config-model/src/test/java/com/yahoo/schema/derived/AnnotationsTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/AnnotationsTestCase.java @@ -2,7 +2,7 @@ package com.yahoo.schema.derived; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; @@ -12,47 +12,47 @@ import java.io.IOException; public class AnnotationsTestCase extends AbstractExportingTestCase { @Test - public void requireThatStructRegistersIfOnlyUsedByAnnotation() throws IOException, ParseException { + void requireThatStructRegistersIfOnlyUsedByAnnotation() throws IOException, ParseException { assertCorrectDeriving("annotationsstruct"); } @Test - public void requireThatStructRegistersIfOnlyUsedAsArrayByAnnotation() throws IOException, ParseException { + void requireThatStructRegistersIfOnlyUsedAsArrayByAnnotation() throws IOException, ParseException { assertCorrectDeriving("annotationsstructarray"); } @Test - public void testSimpleAnnotationDeriving() throws IOException, ParseException { + void testSimpleAnnotationDeriving() throws IOException, ParseException { assertCorrectDeriving("annotationssimple"); } @Test - public void testAnnotationDerivingWithImplicitStruct() throws IOException, ParseException { + void testAnnotationDerivingWithImplicitStruct() throws IOException, ParseException { assertCorrectDeriving("annotationsimplicitstruct"); } @Test - public void testAnnotationDerivingInheritance() throws IOException, ParseException { + void testAnnotationDerivingInheritance() throws IOException, ParseException { assertCorrectDeriving("annotationsinheritance"); } @Test - public void testAnnotationDerivingInheritance2() throws IOException, ParseException { + void testAnnotationDerivingInheritance2() throws IOException, ParseException { assertCorrectDeriving("annotationsinheritance2"); } @Test - public void testSimpleReference() throws IOException, ParseException { + void testSimpleReference() throws IOException, ParseException { assertCorrectDeriving("annotationsreference"); } @Test - public void testAdvancedReference() throws IOException, ParseException { + void testAdvancedReference() throws IOException, ParseException { assertCorrectDeriving("annotationsreference2"); } @Test - public void testAnnotationsPolymorphy() throws IOException, ParseException { + void testAnnotationsPolymorphy() throws IOException, ParseException { assertCorrectDeriving("annotationspolymorphy"); } @@ -60,7 +60,7 @@ public class AnnotationsTestCase extends AbstractExportingTestCase { * An annotation declared before document {} should work. */ @Test - public void testAnnotationOutsideOfDocumentNew() throws IOException, ParseException { + void testAnnotationOutsideOfDocumentNew() throws IOException, ParseException { assertCorrectDeriving("annotationsoutsideofdocument"); } } diff --git a/config-model/src/test/java/com/yahoo/schema/derived/ArraysTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/ArraysTestCase.java index 5b138413a7a..a1b7e40d21b 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/ArraysTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/ArraysTestCase.java @@ -2,7 +2,7 @@ package com.yahoo.schema.derived; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; @@ -16,7 +16,7 @@ import java.io.IOException; public class ArraysTestCase extends AbstractExportingTestCase { @Test - public void testDocumentDeriving() throws IOException, ParseException { + void testDocumentDeriving() throws IOException, ParseException { assertCorrectDeriving("arrays"); } diff --git a/config-model/src/test/java/com/yahoo/schema/derived/AttributeListTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/AttributeListTestCase.java index 1c51d3ec365..c0886597de7 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/AttributeListTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/AttributeListTestCase.java @@ -6,14 +6,14 @@ import com.yahoo.schema.ApplicationBuilder; import com.yahoo.schema.AbstractSchemaTestCase; import com.yahoo.schema.document.Attribute; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Iterator; import static com.yahoo.config.model.test.TestUtil.joinLines; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; /** * Tests attribute deriving @@ -23,7 +23,7 @@ import static org.junit.Assert.assertFalse; public class AttributeListTestCase extends AbstractSchemaTestCase { @Test - public void testDeriving() throws IOException, ParseException { + void testDeriving() throws IOException, ParseException { // Test attribute importing Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/simple.sd"); @@ -31,37 +31,37 @@ public class AttributeListTestCase extends AbstractSchemaTestCase { AttributeFields attributeFields = new AttributeFields(schema); Iterator attributes = attributeFields.attributeIterator(); Attribute attribute; - attribute = (Attribute)attributes.next(); + attribute = (Attribute) attributes.next(); assertEquals("popularity", attribute.getName()); assertEquals(Attribute.Type.INTEGER, attribute.getType()); assertEquals(Attribute.CollectionType.SINGLE, attribute.getCollectionType()); - attribute = (Attribute)attributes.next(); + attribute = (Attribute) attributes.next(); assertEquals("measurement", attribute.getName()); assertEquals(Attribute.Type.INTEGER, attribute.getType()); assertEquals(Attribute.CollectionType.SINGLE, attribute.getCollectionType()); - attribute = (Attribute)attributes.next(); + attribute = (Attribute) attributes.next(); assertEquals("smallattribute", attribute.getName()); assertEquals(Attribute.Type.BYTE, attribute.getType()); assertEquals(Attribute.CollectionType.ARRAY, attribute.getCollectionType()); - attribute = (Attribute)attributes.next(); + attribute = (Attribute) attributes.next(); assertEquals("access", attribute.getName()); assertEquals(Attribute.Type.BYTE, attribute.getType()); assertEquals(Attribute.CollectionType.SINGLE, attribute.getCollectionType()); - attribute = (Attribute)attributes.next(); + attribute = (Attribute) attributes.next(); assertEquals("category_arr", attribute.getName()); assertEquals(Attribute.Type.STRING, attribute.getType()); assertEquals(Attribute.CollectionType.ARRAY, attribute.getCollectionType()); - attribute = (Attribute)attributes.next(); + attribute = (Attribute) attributes.next(); assertEquals("measurement_arr", attribute.getName()); assertEquals(Attribute.Type.INTEGER, attribute.getType()); assertEquals(Attribute.CollectionType.ARRAY, attribute.getCollectionType()); - attribute = (Attribute)attributes.next(); + attribute = (Attribute) attributes.next(); assertEquals("popsiness", attribute.getName()); assertEquals(Attribute.Type.INTEGER, attribute.getType()); assertEquals(Attribute.CollectionType.SINGLE, attribute.getCollectionType()); @@ -70,7 +70,7 @@ public class AttributeListTestCase extends AbstractSchemaTestCase { } @Test - public void fields_in_array_of_struct_are_derived_into_array_attributes() throws IOException, ParseException { + void fields_in_array_of_struct_are_derived_into_array_attributes() throws IOException, ParseException { Schema schema = ApplicationBuilder.buildFromFile("src/test/derived/array_of_struct_attribute/test.sd"); Iterator<Attribute> attributes = new AttributeFields(schema).attributeIterator(); @@ -80,7 +80,7 @@ public class AttributeListTestCase extends AbstractSchemaTestCase { } @Test - public void fields_in_map_of_struct_are_derived_into_array_attributes() throws IOException, ParseException { + void fields_in_map_of_struct_are_derived_into_array_attributes() throws IOException, ParseException { Schema schema = ApplicationBuilder.buildFromFile("src/test/derived/map_of_struct_attribute/test.sd"); Iterator<Attribute> attributes = new AttributeFields(schema).attributeIterator(); @@ -100,15 +100,15 @@ public class AttributeListTestCase extends AbstractSchemaTestCase { } @Test - public void only_zcurve_attribute_is_derived_from_array_of_position_field() throws ParseException { + void only_zcurve_attribute_is_derived_from_array_of_position_field() throws ParseException { Schema schema = ApplicationBuilder.createFromString( joinLines("search test {", - " document test {", - " field pos_array type array<position> {", - " indexing: attribute", - " }", - " }", - "}")).getSchema(); + " document test {", + " field pos_array type array<position> {", + " indexing: attribute", + " }", + " }", + "}")).getSchema(); Iterator<Attribute> attributes = new AttributeFields(schema).attributeIterator(); assertAttribute("pos_array_zcurve", Attribute.Type.LONG, Attribute.CollectionType.ARRAY, true, attributes.next()); @@ -116,7 +116,7 @@ public class AttributeListTestCase extends AbstractSchemaTestCase { } @Test - public void fields_in_map_of_primitive_are_derived_into_array_attributes() throws IOException, ParseException { + void fields_in_map_of_primitive_are_derived_into_array_attributes() throws IOException, ParseException { Schema schema = ApplicationBuilder.buildFromFile("src/test/derived/map_attribute/test.sd"); Iterator<Attribute> attributes = new AttributeFields(schema).attributeIterator(); diff --git a/config-model/src/test/java/com/yahoo/schema/derived/AttributesTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/AttributesTestCase.java index 3d08805acdf..f8b66c8f41b 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/AttributesTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/AttributesTestCase.java @@ -2,7 +2,7 @@ package com.yahoo.schema.derived; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; @@ -14,22 +14,22 @@ import java.io.IOException; public class AttributesTestCase extends AbstractExportingTestCase { @Test - public void testDocumentDeriving() throws IOException, ParseException { + void testDocumentDeriving() throws IOException, ParseException { assertCorrectDeriving("attributes"); } @Test - public void testArrayOfStructAttribute() throws IOException, ParseException { + void testArrayOfStructAttribute() throws IOException, ParseException { assertCorrectDeriving("array_of_struct_attribute"); } @Test - public void testMapOfStructAttribute() throws IOException, ParseException { + void testMapOfStructAttribute() throws IOException, ParseException { assertCorrectDeriving("map_of_struct_attribute"); } @Test - public void testMapOfPrimitiveAttribute() throws IOException, ParseException { + void testMapOfPrimitiveAttribute() throws IOException, ParseException { assertCorrectDeriving("map_attribute"); } diff --git a/config-model/src/test/java/com/yahoo/schema/derived/CasingTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/CasingTestCase.java index 80ebcb825f4..1ee0aa76126 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/CasingTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/CasingTestCase.java @@ -5,11 +5,11 @@ import com.yahoo.schema.Schema; import com.yahoo.schema.ApplicationBuilder; import com.yahoo.schema.AbstractSchemaTestCase; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Correct casing for derived attributes @@ -19,7 +19,7 @@ import static org.junit.Assert.assertEquals; public class CasingTestCase extends AbstractSchemaTestCase { @Test - public void testCasing() throws IOException, ParseException { + void testCasing() throws IOException, ParseException { Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/casing.sd"); assertEquals(schema.getIndex("color").getName(), "color"); assertEquals(schema.getIndex("Foo").getName(), "Foo"); diff --git a/config-model/src/test/java/com/yahoo/schema/derived/CombinedAttributeAndIndexSchemaTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/CombinedAttributeAndIndexSchemaTestCase.java index 542320d9670..3e984ade647 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/CombinedAttributeAndIndexSchemaTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/CombinedAttributeAndIndexSchemaTestCase.java @@ -2,7 +2,7 @@ package com.yahoo.schema.derived; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; @@ -14,7 +14,7 @@ import java.io.IOException; public class CombinedAttributeAndIndexSchemaTestCase extends AbstractExportingTestCase { @Test - public void testMultipleSummaries() throws IOException, ParseException { + void testMultipleSummaries() throws IOException, ParseException { assertCorrectDeriving("combinedattributeandindexsearch"); } diff --git a/config-model/src/test/java/com/yahoo/schema/derived/DeriverTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/DeriverTestCase.java index 422f4522b26..55767e8f8c0 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/DeriverTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/DeriverTestCase.java @@ -5,11 +5,11 @@ import com.yahoo.document.DataType; import com.yahoo.document.DocumentTypeManager; import com.yahoo.document.config.DocumentmanagerConfig; import com.yahoo.schema.AbstractSchemaTestCase; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.List; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests deriving using the Deriver facade @@ -19,7 +19,7 @@ import static org.junit.Assert.assertEquals; public class DeriverTestCase extends AbstractSchemaTestCase { @Test - public void testDeriveDocManager() { + void testDeriveDocManager() { DocumentTypeManager dtm = new DocumentTypeManager(new DocumentmanagerConfig( Deriver.getDocumentManagerConfig(List.of( "src/test/derived/deriver/child.sd", diff --git a/config-model/src/test/java/com/yahoo/schema/derived/DuplicateStructTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/DuplicateStructTestCase.java index 7915a1d7763..7287de68f2f 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/DuplicateStructTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/DuplicateStructTestCase.java @@ -2,7 +2,7 @@ package com.yahoo.schema.derived; import com.yahoo.config.model.deploy.TestProperties; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * @author arnej @@ -10,10 +10,10 @@ import org.junit.Test; public class DuplicateStructTestCase extends AbstractExportingTestCase { @Test - public void exact_duplicate_struct_works() throws Exception { + void exact_duplicate_struct_works() throws Exception { assertCorrectDeriving("duplicate_struct", "foobar", - new TestProperties(), - new TestableDeployLogger()); + new TestProperties(), + new TestableDeployLogger()); } } diff --git a/config-model/src/test/java/com/yahoo/schema/derived/EmptyRankProfileTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/EmptyRankProfileTestCase.java index c3195d1a626..a1df845c97d 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/EmptyRankProfileTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/EmptyRankProfileTestCase.java @@ -10,7 +10,7 @@ import com.yahoo.schema.ApplicationBuilder; import com.yahoo.schema.AbstractSchemaTestCase; import com.yahoo.schema.document.SDDocumentType; import com.yahoo.schema.document.SDField; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests deriving rank for files from search definitions @@ -20,7 +20,7 @@ import org.junit.Test; public class EmptyRankProfileTestCase extends AbstractSchemaTestCase { @Test - public void testDeriving() { + void testDeriving() { Schema schema = new Schema("test", MockApplicationPackage.createEmpty()); RankProfileRegistry rankProfileRegistry = RankProfileRegistry.createRankProfileRegistryWithBuiltinRankProfiles(schema); SDDocumentType doc = new SDDocumentType("test"); diff --git a/config-model/src/test/java/com/yahoo/schema/derived/ExactMatchTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/ExactMatchTestCase.java index 13a0a8201fb..6b7e8bb714d 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/ExactMatchTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/ExactMatchTestCase.java @@ -2,7 +2,7 @@ package com.yahoo.schema.derived; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; @@ -11,7 +11,7 @@ import java.io.IOException; */ public class ExactMatchTestCase extends AbstractExportingTestCase { @Test - public void testExactString() throws IOException, ParseException { + void testExactString() throws IOException, ParseException { assertCorrectDeriving("exactmatch"); } } diff --git a/config-model/src/test/java/com/yahoo/schema/derived/ExportingTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/ExportingTestCase.java index dc10004a631..b5b075ae260 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/ExportingTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/ExportingTestCase.java @@ -4,11 +4,11 @@ package com.yahoo.schema.derived; import com.yahoo.config.model.deploy.TestProperties; import com.yahoo.schema.ApplicationBuilder; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests exporting @@ -18,144 +18,144 @@ import static org.junit.Assert.assertEquals; public class ExportingTestCase extends AbstractExportingTestCase { @Test - public void testIndexInfoLowerCase() throws IOException, ParseException { + void testIndexInfoLowerCase() throws IOException, ParseException { assertCorrectDeriving("indexinfo_lowercase"); } @Test - public void testPositionArray() throws IOException, ParseException { + void testPositionArray() throws IOException, ParseException { assertCorrectDeriving("position_array", - new TestProperties().setUseV8GeoPositions(true)); + new TestProperties().setUseV8GeoPositions(true)); } @Test - public void testPositionAttribute() throws IOException, ParseException { + void testPositionAttribute() throws IOException, ParseException { assertCorrectDeriving("position_attribute", - new TestProperties().setUseV8GeoPositions(true)); + new TestProperties().setUseV8GeoPositions(true)); } @Test - public void testPositionExtra() throws IOException, ParseException { + void testPositionExtra() throws IOException, ParseException { assertCorrectDeriving("position_extra", - new TestProperties().setUseV8GeoPositions(true)); + new TestProperties().setUseV8GeoPositions(true)); } @Test - public void testPositionNoSummary() throws IOException, ParseException { + void testPositionNoSummary() throws IOException, ParseException { assertCorrectDeriving("position_nosummary", - new TestProperties().setUseV8GeoPositions(true)); + new TestProperties().setUseV8GeoPositions(true)); } @Test - public void testPositionSummary() throws IOException, ParseException { + void testPositionSummary() throws IOException, ParseException { assertCorrectDeriving("position_summary", - new TestProperties().setUseV8GeoPositions(true)); + new TestProperties().setUseV8GeoPositions(true)); } @Test - public void testUriArray() throws IOException, ParseException { + void testUriArray() throws IOException, ParseException { assertCorrectDeriving("uri_array"); } @Test - public void testUriWSet() throws IOException, ParseException { + void testUriWSet() throws IOException, ParseException { assertCorrectDeriving("uri_wset"); } @Test - public void testMusic() throws IOException, ParseException { + void testMusic() throws IOException, ParseException { assertCorrectDeriving("music"); } @Test - public void testComplexPhysicalExporting() throws IOException, ParseException { + void testComplexPhysicalExporting() throws IOException, ParseException { assertCorrectDeriving("complex"); } @Test - public void testAttributePrefetch() throws IOException, ParseException { + void testAttributePrefetch() throws IOException, ParseException { assertCorrectDeriving("attributeprefetch"); } @Test - public void testAdvancedIL() throws IOException, ParseException { + void testAdvancedIL() throws IOException, ParseException { assertCorrectDeriving("advanced"); } @Test - public void testEmptyDefaultIndex() throws IOException, ParseException { + void testEmptyDefaultIndex() throws IOException, ParseException { assertCorrectDeriving("emptydefault"); } @Test - public void testIndexSwitches() throws IOException, ParseException { + void testIndexSwitches() throws IOException, ParseException { assertCorrectDeriving("indexswitches"); } @Test - public void testRankTypes() throws IOException, ParseException { + void testRankTypes() throws IOException, ParseException { assertCorrectDeriving("ranktypes"); } @Test - public void testAttributeRank() throws IOException, ParseException { + void testAttributeRank() throws IOException, ParseException { assertCorrectDeriving("attributerank"); } @Test - public void testNewRank() throws IOException, ParseException { + void testNewRank() throws IOException, ParseException { assertCorrectDeriving("newrank"); } @Test - public void testRankingExpression() throws IOException, ParseException { + void testRankingExpression() throws IOException, ParseException { assertCorrectDeriving("rankingexpression"); } @Test - public void testAvoidRenamingRankingExpression() throws IOException, ParseException { + void testAvoidRenamingRankingExpression() throws IOException, ParseException { assertCorrectDeriving("renamedfeatures", "foo", - new TestProperties(), - new TestableDeployLogger()); + new TestProperties(), + new TestableDeployLogger()); } @Test - public void testMlr() throws IOException, ParseException { + void testMlr() throws IOException, ParseException { assertCorrectDeriving("mlr"); } @Test - public void testMusic3() throws IOException, ParseException { + void testMusic3() throws IOException, ParseException { assertCorrectDeriving("music3"); } @Test - public void testIndexSchema() throws IOException, ParseException { + void testIndexSchema() throws IOException, ParseException { assertCorrectDeriving("indexschema"); } @Test - public void testIndexinfoFieldsets() throws IOException, ParseException { + void testIndexinfoFieldsets() throws IOException, ParseException { assertCorrectDeriving("indexinfo_fieldsets"); } @Test - public void testStreamingJuniper() throws IOException, ParseException { + void testStreamingJuniper() throws IOException, ParseException { assertCorrectDeriving("streamingjuniper"); } @Test - public void testPredicateAttribute() throws IOException, ParseException { + void testPredicateAttribute() throws IOException, ParseException { assertCorrectDeriving("predicate_attribute"); } @Test - public void testTensor() throws IOException, ParseException { + void testTensor() throws IOException, ParseException { assertCorrectDeriving("tensor"); } @Test - public void testTensor2() throws IOException, ParseException { + void testTensor2() throws IOException, ParseException { String dir = "src/test/derived/tensor2/"; ApplicationBuilder builder = new ApplicationBuilder(); builder.addSchemaFile(dir + "first.sd"); @@ -166,29 +166,29 @@ public class ExportingTestCase extends AbstractExportingTestCase { } @Test - public void testHnswIndex() throws IOException, ParseException { + void testHnswIndex() throws IOException, ParseException { assertCorrectDeriving("hnsw_index"); } @Test - public void testRankProfileInheritance() throws IOException, ParseException { + void testRankProfileInheritance() throws IOException, ParseException { assertCorrectDeriving("rankprofileinheritance", "child", new TestableDeployLogger()); } @Test - public void testLanguage() throws IOException, ParseException { + void testLanguage() throws IOException, ParseException { TestableDeployLogger logger = new TestableDeployLogger(); assertCorrectDeriving("language", logger); assertEquals(0, logger.warnings.size()); } @Test - public void testRankProfileModularity() throws IOException, ParseException { + void testRankProfileModularity() throws IOException, ParseException { assertCorrectDeriving("rankprofilemodularity"); } @Test - public void testStructAndFieldSet() throws IOException, ParseException { + void testStructAndFieldSet() throws IOException, ParseException { assertCorrectDeriving("structandfieldset"); } diff --git a/config-model/src/test/java/com/yahoo/schema/derived/ExpressionsAsArgsTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/ExpressionsAsArgsTestCase.java index d2020305bc1..31dfd240538 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/ExpressionsAsArgsTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/ExpressionsAsArgsTestCase.java @@ -2,7 +2,7 @@ package com.yahoo.schema.derived; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; @@ -14,7 +14,7 @@ import java.io.IOException; public class ExpressionsAsArgsTestCase extends AbstractExportingTestCase { @Test - public void testDocumentDeriving() throws IOException, ParseException { + void testDocumentDeriving() throws IOException, ParseException { assertCorrectDeriving("function_arguments"); assertCorrectDeriving("function_arguments_with_expressions"); } diff --git a/config-model/src/test/java/com/yahoo/schema/derived/FieldsetTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/FieldsetTestCase.java index fdab49c9fff..c223152e3da 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/FieldsetTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/FieldsetTestCase.java @@ -2,14 +2,14 @@ package com.yahoo.schema.derived; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; public class FieldsetTestCase extends AbstractExportingTestCase { @Test - public void testRankProfiles() throws IOException, ParseException { + void testRankProfiles() throws IOException, ParseException { assertCorrectDeriving("fieldset"); } diff --git a/config-model/src/test/java/com/yahoo/schema/derived/GeminiTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/GeminiTestCase.java index 5531fb65942..3a809d190bc 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/GeminiTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/GeminiTestCase.java @@ -3,21 +3,22 @@ package com.yahoo.schema.derived; import com.yahoo.collections.Pair; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; -import static org.junit.Assert.assertEquals; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; +import static org.junit.jupiter.api.Assertions.assertEquals; + /** * @author bratseth */ public class GeminiTestCase extends AbstractExportingTestCase { @Test - public void testRanking2() throws IOException, ParseException { + void testRanking2() throws IOException, ParseException { DerivedConfiguration c = assertCorrectDeriving("gemini2"); RawRankProfile p = c.getRankProfileList().getRankProfiles().get("test"); Map<String, String> ranking = removePartKeySuffixes(asMap(p.configProperties())); diff --git a/config-model/src/test/java/com/yahoo/schema/derived/IdTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/IdTestCase.java index 1e57d52e3b0..f2614e9e85b 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/IdTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/IdTestCase.java @@ -10,12 +10,12 @@ import com.yahoo.schema.document.SDDocumentType; import com.yahoo.schema.document.SDField; import com.yahoo.schema.processing.Processing; import com.yahoo.vespa.model.container.search.QueryProfiles; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Set; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; /** * Tests that documents ids are treated as they should @@ -25,7 +25,7 @@ import static org.junit.Assert.assertNull; public class IdTestCase extends AbstractExportingTestCase { @Test - public void testExplicitUpperCaseIdField() { + void testExplicitUpperCaseIdField() { Schema schema = new Schema("test", MockApplicationPackage.createEmpty()); SDDocumentType document = new SDDocumentType("test"); schema.addDocument(document); @@ -34,7 +34,7 @@ public class IdTestCase extends AbstractExportingTestCase { document.addField(uri); new Processing().process(schema, new BaseDeployLogger(), new RankProfileRegistry(), new QueryProfiles(), - true, false, Set.of()); + true, false, Set.of()); assertNull(document.getField("uri")); assertNull(document.getField("Uri")); @@ -42,7 +42,7 @@ public class IdTestCase extends AbstractExportingTestCase { } @Test - public void testCompleteDeriving() throws Exception { + void testCompleteDeriving() throws Exception { assertCorrectDeriving("id"); } diff --git a/config-model/src/test/java/com/yahoo/schema/derived/ImportedFieldsTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/ImportedFieldsTestCase.java index 5578a1a602b..fb87137cc2e 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/ImportedFieldsTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/ImportedFieldsTestCase.java @@ -3,7 +3,7 @@ package com.yahoo.schema.derived; import com.yahoo.config.model.deploy.TestProperties; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; @@ -13,29 +13,29 @@ import java.io.IOException; public class ImportedFieldsTestCase extends AbstractExportingTestCase { @Test - public void configs_for_imported_fields_are_derived() throws IOException, ParseException { + void configs_for_imported_fields_are_derived() throws IOException, ParseException { assertCorrectDeriving("importedfields", "child", new TestableDeployLogger()); } @Test - public void configs_for_imported_struct_fields_are_derived() throws IOException, ParseException { + void configs_for_imported_struct_fields_are_derived() throws IOException, ParseException { assertCorrectDeriving("imported_struct_fields", "child", - new TestProperties(), - new TestableDeployLogger()); + new TestProperties(), + new TestableDeployLogger()); } @Test - public void configs_for_imported_position_field_are_derived() throws IOException, ParseException { + void configs_for_imported_position_field_are_derived() throws IOException, ParseException { assertCorrectDeriving("imported_position_field", "child", new TestableDeployLogger()); } @Test - public void configs_for_imported_position_field_summary_are_derived() throws IOException, ParseException { + void configs_for_imported_position_field_summary_are_derived() throws IOException, ParseException { assertCorrectDeriving("imported_position_field_summary", "child", new TestableDeployLogger()); } @Test - public void derives_configs_for_imported_fields_when_reference_fields_are_inherited() throws IOException, ParseException { + void derives_configs_for_imported_fields_when_reference_fields_are_inherited() throws IOException, ParseException { assertCorrectDeriving("imported_fields_inherited_reference", "child_c", new TestableDeployLogger()); } diff --git a/config-model/src/test/java/com/yahoo/schema/derived/IndexSchemaTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/IndexSchemaTestCase.java index 1f40c6bcb50..39d436f6676 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/IndexSchemaTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/IndexSchemaTestCase.java @@ -4,15 +4,15 @@ package com.yahoo.schema.derived; import com.yahoo.document.DataType; import com.yahoo.document.Field; import com.yahoo.document.StructDataType; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Simon Thoresen Hult @@ -20,7 +20,7 @@ import static org.junit.Assert.fail; public class IndexSchemaTestCase { @Test - public void requireThatPrimitiveIsNotFlattened() { + void requireThatPrimitiveIsNotFlattened() { assertFlat(new Field("foo", DataType.BYTE), new Field("foo", DataType.BYTE)); assertFlat(new Field("foo", DataType.DOUBLE), new Field("foo", DataType.DOUBLE)); assertFlat(new Field("foo", DataType.FLOAT), new Field("foo", DataType.FLOAT)); @@ -33,29 +33,29 @@ public class IndexSchemaTestCase { } @Test - public void requireThatArrayOfPrimitiveIsNotFlattened() { + void requireThatArrayOfPrimitiveIsNotFlattened() { assertFlat(new Field("foo", DataType.getArray(DataType.BYTE)), - new Field("foo", DataType.getArray(DataType.BYTE))); + new Field("foo", DataType.getArray(DataType.BYTE))); assertFlat(new Field("foo", DataType.getArray(DataType.DOUBLE)), - new Field("foo", DataType.getArray(DataType.DOUBLE))); + new Field("foo", DataType.getArray(DataType.DOUBLE))); assertFlat(new Field("foo", DataType.getArray(DataType.FLOAT)), - new Field("foo", DataType.getArray(DataType.FLOAT))); + new Field("foo", DataType.getArray(DataType.FLOAT))); assertFlat(new Field("foo", DataType.getArray(DataType.INT)), - new Field("foo", DataType.getArray(DataType.INT))); + new Field("foo", DataType.getArray(DataType.INT))); assertFlat(new Field("foo", DataType.getArray(DataType.LONG)), - new Field("foo", DataType.getArray(DataType.LONG))); + new Field("foo", DataType.getArray(DataType.LONG))); assertFlat(new Field("foo", DataType.getArray(DataType.RAW)), - new Field("foo", DataType.getArray(DataType.RAW))); + new Field("foo", DataType.getArray(DataType.RAW))); assertFlat(new Field("foo", DataType.getArray(DataType.STRING)), - new Field("foo", DataType.getArray(DataType.STRING))); + new Field("foo", DataType.getArray(DataType.STRING))); assertFlat(new Field("foo", DataType.getArray(DataType.URI)), - new Field("foo", DataType.getArray(DataType.URI))); + new Field("foo", DataType.getArray(DataType.URI))); assertFlat(new Field("foo", DataType.getArray(DataType.PREDICATE)), - new Field("foo", DataType.getArray(DataType.PREDICATE))); + new Field("foo", DataType.getArray(DataType.PREDICATE))); } @Test - public void requireThatStructIsFlattened() { + void requireThatStructIsFlattened() { StructDataType type = new StructDataType("my_struct"); type.addField(new Field("my_byte", DataType.BYTE)); type.addField(new Field("my_double", DataType.DOUBLE)); @@ -67,18 +67,18 @@ public class IndexSchemaTestCase { type.addField(new Field("my_uri", DataType.URI)); assertFlat(new Field("foo", type), - new Field("foo.my_byte", DataType.BYTE), - new Field("foo.my_double", DataType.DOUBLE), - new Field("foo.my_float", DataType.FLOAT), - new Field("foo.my_int", DataType.INT), - new Field("foo.my_long", DataType.LONG), - new Field("foo.my_raw", DataType.RAW), - new Field("foo.my_string", DataType.STRING), - new Field("foo.my_uri", DataType.URI)); + new Field("foo.my_byte", DataType.BYTE), + new Field("foo.my_double", DataType.DOUBLE), + new Field("foo.my_float", DataType.FLOAT), + new Field("foo.my_int", DataType.INT), + new Field("foo.my_long", DataType.LONG), + new Field("foo.my_raw", DataType.RAW), + new Field("foo.my_string", DataType.STRING), + new Field("foo.my_uri", DataType.URI)); } @Test - public void requireThatArrayOfStructIsFlattened() { + void requireThatArrayOfStructIsFlattened() { StructDataType type = new StructDataType("my_struct"); type.addField(new Field("my_byte", DataType.BYTE)); type.addField(new Field("my_double", DataType.DOUBLE)); @@ -90,18 +90,18 @@ public class IndexSchemaTestCase { type.addField(new Field("my_uri", DataType.URI)); assertFlat(new Field("foo", DataType.getArray(type)), - new Field("foo.my_byte", DataType.getArray(DataType.BYTE)), - new Field("foo.my_double", DataType.getArray(DataType.DOUBLE)), - new Field("foo.my_float", DataType.getArray(DataType.FLOAT)), - new Field("foo.my_int", DataType.getArray(DataType.INT)), - new Field("foo.my_long", DataType.getArray(DataType.LONG)), - new Field("foo.my_raw", DataType.getArray(DataType.RAW)), - new Field("foo.my_string", DataType.getArray(DataType.STRING)), - new Field("foo.my_uri", DataType.getArray(DataType.URI))); + new Field("foo.my_byte", DataType.getArray(DataType.BYTE)), + new Field("foo.my_double", DataType.getArray(DataType.DOUBLE)), + new Field("foo.my_float", DataType.getArray(DataType.FLOAT)), + new Field("foo.my_int", DataType.getArray(DataType.INT)), + new Field("foo.my_long", DataType.getArray(DataType.LONG)), + new Field("foo.my_raw", DataType.getArray(DataType.RAW)), + new Field("foo.my_string", DataType.getArray(DataType.STRING)), + new Field("foo.my_uri", DataType.getArray(DataType.URI))); } @Test - public void requireThatArrayOfArrayOfStructIsFlattened() { + void requireThatArrayOfArrayOfStructIsFlattened() { StructDataType type = new StructDataType("my_struct"); type.addField(new Field("my_byte", DataType.BYTE)); type.addField(new Field("my_double", DataType.DOUBLE)); @@ -113,18 +113,18 @@ public class IndexSchemaTestCase { type.addField(new Field("my_uri", DataType.URI)); assertFlat(new Field("foo", DataType.getArray(DataType.getArray(type))), - new Field("foo.my_byte", DataType.getArray(DataType.getArray(DataType.BYTE))), - new Field("foo.my_double", DataType.getArray(DataType.getArray(DataType.DOUBLE))), - new Field("foo.my_float", DataType.getArray(DataType.getArray(DataType.FLOAT))), - new Field("foo.my_int", DataType.getArray(DataType.getArray(DataType.INT))), - new Field("foo.my_long", DataType.getArray(DataType.getArray(DataType.LONG))), - new Field("foo.my_raw", DataType.getArray(DataType.getArray(DataType.RAW))), - new Field("foo.my_string", DataType.getArray(DataType.getArray(DataType.STRING))), - new Field("foo.my_uri", DataType.getArray(DataType.getArray(DataType.URI)))); + new Field("foo.my_byte", DataType.getArray(DataType.getArray(DataType.BYTE))), + new Field("foo.my_double", DataType.getArray(DataType.getArray(DataType.DOUBLE))), + new Field("foo.my_float", DataType.getArray(DataType.getArray(DataType.FLOAT))), + new Field("foo.my_int", DataType.getArray(DataType.getArray(DataType.INT))), + new Field("foo.my_long", DataType.getArray(DataType.getArray(DataType.LONG))), + new Field("foo.my_raw", DataType.getArray(DataType.getArray(DataType.RAW))), + new Field("foo.my_string", DataType.getArray(DataType.getArray(DataType.STRING))), + new Field("foo.my_uri", DataType.getArray(DataType.getArray(DataType.URI)))); } @Test - public void requireThatStructWithArrayFieldIsFlattened() { + void requireThatStructWithArrayFieldIsFlattened() { StructDataType type = new StructDataType("my_struct"); type.addField(new Field("my_byte", DataType.getArray(DataType.BYTE))); type.addField(new Field("my_double", DataType.getArray(DataType.DOUBLE))); @@ -136,18 +136,18 @@ public class IndexSchemaTestCase { type.addField(new Field("my_uri", DataType.getArray(DataType.URI))); assertFlat(new Field("foo", type), - new Field("foo.my_byte", DataType.getArray(DataType.BYTE)), - new Field("foo.my_double", DataType.getArray(DataType.DOUBLE)), - new Field("foo.my_float", DataType.getArray(DataType.FLOAT)), - new Field("foo.my_int", DataType.getArray(DataType.INT)), - new Field("foo.my_long", DataType.getArray(DataType.LONG)), - new Field("foo.my_raw", DataType.getArray(DataType.RAW)), - new Field("foo.my_string", DataType.getArray(DataType.STRING)), - new Field("foo.my_uri", DataType.getArray(DataType.URI))); + new Field("foo.my_byte", DataType.getArray(DataType.BYTE)), + new Field("foo.my_double", DataType.getArray(DataType.DOUBLE)), + new Field("foo.my_float", DataType.getArray(DataType.FLOAT)), + new Field("foo.my_int", DataType.getArray(DataType.INT)), + new Field("foo.my_long", DataType.getArray(DataType.LONG)), + new Field("foo.my_raw", DataType.getArray(DataType.RAW)), + new Field("foo.my_string", DataType.getArray(DataType.STRING)), + new Field("foo.my_uri", DataType.getArray(DataType.URI))); } @Test - public void requireThatStructWithArrayOfArrayFieldIsFlattened() { + void requireThatStructWithArrayOfArrayFieldIsFlattened() { StructDataType type = new StructDataType("my_struct"); type.addField(new Field("my_byte", DataType.getArray(DataType.getArray(DataType.BYTE)))); type.addField(new Field("my_double", DataType.getArray(DataType.getArray(DataType.DOUBLE)))); @@ -159,18 +159,18 @@ public class IndexSchemaTestCase { type.addField(new Field("my_uri", DataType.getArray(DataType.getArray(DataType.URI)))); assertFlat(new Field("foo", type), - new Field("foo.my_byte", DataType.getArray(DataType.getArray(DataType.BYTE))), - new Field("foo.my_double", DataType.getArray(DataType.getArray(DataType.DOUBLE))), - new Field("foo.my_float", DataType.getArray(DataType.getArray(DataType.FLOAT))), - new Field("foo.my_int", DataType.getArray(DataType.getArray(DataType.INT))), - new Field("foo.my_long", DataType.getArray(DataType.getArray(DataType.LONG))), - new Field("foo.my_raw", DataType.getArray(DataType.getArray(DataType.RAW))), - new Field("foo.my_string", DataType.getArray(DataType.getArray(DataType.STRING))), - new Field("foo.my_uri", DataType.getArray(DataType.getArray(DataType.URI)))); + new Field("foo.my_byte", DataType.getArray(DataType.getArray(DataType.BYTE))), + new Field("foo.my_double", DataType.getArray(DataType.getArray(DataType.DOUBLE))), + new Field("foo.my_float", DataType.getArray(DataType.getArray(DataType.FLOAT))), + new Field("foo.my_int", DataType.getArray(DataType.getArray(DataType.INT))), + new Field("foo.my_long", DataType.getArray(DataType.getArray(DataType.LONG))), + new Field("foo.my_raw", DataType.getArray(DataType.getArray(DataType.RAW))), + new Field("foo.my_string", DataType.getArray(DataType.getArray(DataType.STRING))), + new Field("foo.my_uri", DataType.getArray(DataType.getArray(DataType.URI)))); } @Test - public void requireThatArrayOfStructWithArrayFieldIsFlattened() { + void requireThatArrayOfStructWithArrayFieldIsFlattened() { StructDataType type = new StructDataType("my_struct"); type.addField(new Field("my_byte", DataType.getArray(DataType.BYTE))); type.addField(new Field("my_double", DataType.getArray(DataType.DOUBLE))); @@ -182,14 +182,14 @@ public class IndexSchemaTestCase { type.addField(new Field("my_uri", DataType.getArray(DataType.URI))); assertFlat(new Field("foo", DataType.getArray(type)), - new Field("foo.my_byte", DataType.getArray(DataType.getArray(DataType.BYTE))), - new Field("foo.my_double", DataType.getArray(DataType.getArray(DataType.DOUBLE))), - new Field("foo.my_float", DataType.getArray(DataType.getArray(DataType.FLOAT))), - new Field("foo.my_int", DataType.getArray(DataType.getArray(DataType.INT))), - new Field("foo.my_long", DataType.getArray(DataType.getArray(DataType.LONG))), - new Field("foo.my_raw", DataType.getArray(DataType.getArray(DataType.RAW))), - new Field("foo.my_string", DataType.getArray(DataType.getArray(DataType.STRING))), - new Field("foo.my_uri", DataType.getArray(DataType.getArray(DataType.URI)))); + new Field("foo.my_byte", DataType.getArray(DataType.getArray(DataType.BYTE))), + new Field("foo.my_double", DataType.getArray(DataType.getArray(DataType.DOUBLE))), + new Field("foo.my_float", DataType.getArray(DataType.getArray(DataType.FLOAT))), + new Field("foo.my_int", DataType.getArray(DataType.getArray(DataType.INT))), + new Field("foo.my_long", DataType.getArray(DataType.getArray(DataType.LONG))), + new Field("foo.my_raw", DataType.getArray(DataType.getArray(DataType.RAW))), + new Field("foo.my_string", DataType.getArray(DataType.getArray(DataType.STRING))), + new Field("foo.my_uri", DataType.getArray(DataType.getArray(DataType.URI)))); } private static void assertFlat(Field fieldToFlatten, Field... expectedFields) { @@ -202,7 +202,7 @@ public class IndexSchemaTestCase { fail("Unexpected field: " + field); } } - assertTrue("Missing fields: " + expected, expected.isEmpty()); + assertTrue(expected.isEmpty(), "Missing fields: " + expected); } } diff --git a/config-model/src/test/java/com/yahoo/schema/derived/InheritanceTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/InheritanceTestCase.java index 1c433237fd8..66833233341 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/InheritanceTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/InheritanceTestCase.java @@ -12,19 +12,15 @@ import com.yahoo.schema.document.SDDocumentType; import com.yahoo.schema.document.SDField; import com.yahoo.schema.parser.ParseException; import com.yahoo.vespa.configmodel.producers.DocumentManager; -import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.List; -import org.junit.rules.TemporaryFolder; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.*; /** * Tests inheritance @@ -33,11 +29,11 @@ import static org.junit.Assert.assertNull; */ public class InheritanceTestCase extends AbstractExportingTestCase { - @Rule - public TemporaryFolder tmpDir = new TemporaryFolder(); + @TempDir + public File tmpDir; @Test - public void requireThatIndexedStructFieldCanBeInherited() throws IOException, ParseException { + void requireThatIndexedStructFieldCanBeInherited() throws IOException, ParseException { String dir = "src/test/derived/inheritstruct/"; ApplicationBuilder builder = new ApplicationBuilder(); builder.addSchemaFile(dir + "parent.sd"); @@ -48,7 +44,7 @@ public class InheritanceTestCase extends AbstractExportingTestCase { } @Test - public void requireThatInheritFromNullIsCaught() throws IOException, ParseException { + void requireThatInheritFromNullIsCaught() throws IOException, ParseException { try { assertCorrectDeriving("inheritfromnull"); } catch (IllegalArgumentException e) { @@ -57,7 +53,7 @@ public class InheritanceTestCase extends AbstractExportingTestCase { } @Test - public void requireThatStructTypesAreInheritedThroughDiamond() throws IOException, ParseException { + void requireThatStructTypesAreInheritedThroughDiamond() throws IOException, ParseException { String dir = "src/test/derived/inheritdiamond/"; { ApplicationBuilder builder = new ApplicationBuilder(); @@ -70,7 +66,7 @@ public class InheritanceTestCase extends AbstractExportingTestCase { assertCorrectConfigFiles("inheritdiamond"); } List<String> files = Arrays.asList("grandparent.sd", "mother.sd", "father.sd", "child.sd"); - File outDir = tmpDir.newFolder("out"); + File outDir = newFolder(tmpDir, "out"); for (int startIdx = 0; startIdx < files.size(); ++startIdx) { var builder = new ApplicationBuilder(new TestProperties()); for (int fileIdx = startIdx; fileIdx < startIdx + files.size(); ++fileIdx) { @@ -80,7 +76,7 @@ public class InheritanceTestCase extends AbstractExportingTestCase { builder.build(true); DocumentmanagerConfig.Builder b = new DocumentmanagerConfig.Builder(); DerivedConfiguration.exportDocuments(new DocumentManager(). - produce(builder.getModel(), b), outDir.getPath()); + produce(builder.getModel(), b), outDir.getPath()); DocumentmanagerConfig dc = b.build(); assertEquals(5, dc.doctype().size()); @@ -120,9 +116,9 @@ public class InheritanceTestCase extends AbstractExportingTestCase { } return null; } - + @Test - public void requireThatStructTypesAreInheritedFromParent() throws IOException, ParseException { + void requireThatStructTypesAreInheritedFromParent() throws IOException, ParseException { String dir = "src/test/derived/inheritfromparent/"; ApplicationBuilder builder = new ApplicationBuilder(); builder.addSchemaFile(dir + "parent.sd"); @@ -133,7 +129,7 @@ public class InheritanceTestCase extends AbstractExportingTestCase { } @Test - public void requireThatStructTypesAreInheritedFromGrandParent() throws IOException, ParseException { + void requireThatStructTypesAreInheritedFromGrandParent() throws IOException, ParseException { String dir = "src/test/derived/inheritfromgrandparent/"; ApplicationBuilder builder = new ApplicationBuilder(); builder.addSchemaFile(dir + "grandparent.sd"); @@ -145,7 +141,7 @@ public class InheritanceTestCase extends AbstractExportingTestCase { } @Test - public void testInheritance() throws IOException, ParseException { + void testInheritance() throws IOException, ParseException { String dir = "src/test/derived/inheritance/"; ApplicationBuilder builder = new ApplicationBuilder(); builder.addSchemaFile(dir + "grandparent.sd"); @@ -158,7 +154,7 @@ public class InheritanceTestCase extends AbstractExportingTestCase { } @Test - public void testIndexSettingInheritance() { + void testIndexSettingInheritance() { SDDocumentType parent = new SDDocumentType("parent"); Schema parentSchema = new Schema("parent", MockApplicationPackage.createEmpty()); parentSchema.addDocument(parent); @@ -171,13 +167,13 @@ public class InheritanceTestCase extends AbstractExportingTestCase { Schema childSchema = new Schema("child", MockApplicationPackage.createEmpty()); childSchema.addDocument(child); - prefixed = (SDField)child.getField("prefixed"); + prefixed = (SDField) child.getField("prefixed"); assertNotNull(prefixed); assertEquals(new Index("prefixed", true), childSchema.getIndex("prefixed")); } @Test - public void testInheritStructDiamondNew() throws IOException, ParseException { + void testInheritStructDiamondNew() throws IOException, ParseException { String dir = "src/test/derived/declstruct/"; List<String> files = Arrays.asList("common.sd", "foo.sd", "bar.sd", "foobar.sd"); var builder = new ApplicationBuilder(new TestProperties()); @@ -189,4 +185,13 @@ public class InheritanceTestCase extends AbstractExportingTestCase { assertCorrectConfigFiles("declstruct"); } + private static File newFolder(File root, String... subDirs) throws IOException { + String subFolder = String.join("/", subDirs); + File result = new File(root, subFolder); + if (!result.mkdirs()) { + throw new IOException("Couldn't create folders " + root); + } + return result; + } + } diff --git a/config-model/src/test/java/com/yahoo/schema/derived/IntegerAttributeToStringIndexTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/IntegerAttributeToStringIndexTestCase.java index b5f222673ab..8a77bd714fd 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/IntegerAttributeToStringIndexTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/IntegerAttributeToStringIndexTestCase.java @@ -2,7 +2,7 @@ package com.yahoo.schema.derived; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; @@ -11,7 +11,7 @@ import java.io.IOException; */ public class IntegerAttributeToStringIndexTestCase extends AbstractExportingTestCase { @Test - public void testIt() throws IOException, ParseException { + void testIt() throws IOException, ParseException { assertCorrectDeriving("integerattributetostringindex"); } } diff --git a/config-model/src/test/java/com/yahoo/schema/derived/LiteralBoostTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/LiteralBoostTestCase.java index c5090c88a1b..c32f5f2b3a4 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/LiteralBoostTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/LiteralBoostTestCase.java @@ -13,13 +13,13 @@ import com.yahoo.schema.document.SDDocumentType; import com.yahoo.schema.document.SDField; import com.yahoo.schema.processing.Processing; import com.yahoo.vespa.model.container.search.QueryProfiles; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Set; import static com.yahoo.schema.processing.AssertIndexingScript.assertIndexing; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author bratseth @@ -30,7 +30,7 @@ public class LiteralBoostTestCase extends AbstractExportingTestCase { * Tests adding of literal boost constructs */ @Test - public void testLiteralBoost() { + void testLiteralBoost() { Schema schema = new Schema("literalboost", MockApplicationPackage.createEmpty()); RankProfileRegistry rankProfileRegistry = RankProfileRegistry.createRankProfileRegistryWithBuiltinRankProfiles(schema); SDDocumentType document = new SDDocumentType("literalboost"); @@ -43,7 +43,7 @@ public class LiteralBoostTestCase extends AbstractExportingTestCase { other.addRankSetting(new RankProfile.RankSetting("a", RankProfile.RankSetting.Type.LITERALBOOST, 333)); new Processing().process(schema, new BaseDeployLogger(), rankProfileRegistry, new QueryProfiles(), - true, false, Set.of()); + true, false, Set.of()); DerivedConfiguration derived = new DerivedConfiguration(schema, rankProfileRegistry); // Check attribute fields @@ -51,8 +51,8 @@ public class LiteralBoostTestCase extends AbstractExportingTestCase { // Check il script addition assertIndexing(Arrays.asList("clear_state | guard { input a | tokenize normalize stem:\"BEST\" | index a; }", - "clear_state | guard { input a | tokenize | index a_literal; }"), - schema); + "clear_state | guard { input a | tokenize | index a_literal; }"), + schema); // Check index info addition IndexInfo indexInfo = derived.getIndexInfo(); @@ -63,7 +63,7 @@ public class LiteralBoostTestCase extends AbstractExportingTestCase { * Tests adding a literal boost in a non-default rank profile only */ @Test - public void testNonDefaultRankLiteralBoost() { + void testNonDefaultRankLiteralBoost() { Schema schema = new Schema("literalboost", MockApplicationPackage.createEmpty()); RankProfileRegistry rankProfileRegistry = RankProfileRegistry.createRankProfileRegistryWithBuiltinRankProfiles(schema); SDDocumentType document = new SDDocumentType("literalboost"); @@ -79,17 +79,17 @@ public class LiteralBoostTestCase extends AbstractExportingTestCase { // Check il script addition assertIndexing(Arrays.asList("clear_state | guard { input a | tokenize normalize stem:\"BEST\" | index a; }", - "clear_state | guard { input a | tokenize | index a_literal; }"), - schema); + "clear_state | guard { input a | tokenize | index a_literal; }"), + schema); // Check index info addition IndexInfo indexInfo = derived.getIndexInfo(); - assertTrue(indexInfo.hasCommand("a","literal-boost")); + assertTrue(indexInfo.hasCommand("a", "literal-boost")); } /** Tests literal boosts in two fields going to the same index */ @Test - public void testTwoLiteralBoostFields() { + void testTwoLiteralBoostFields() { Schema schema = new Schema("msb", MockApplicationPackage.createEmpty()); RankProfileRegistry rankProfileRegistry = RankProfileRegistry.createRankProfileRegistryWithBuiltinRankProfiles(schema); SDDocumentType document = new SDDocumentType("msb"); @@ -104,10 +104,10 @@ public class LiteralBoostTestCase extends AbstractExportingTestCase { schema = ApplicationBuilder.buildFromRawSchema(schema, rankProfileRegistry, new QueryProfileRegistry()); new DerivedConfiguration(schema, rankProfileRegistry); assertIndexing(Arrays.asList("clear_state | guard { input title | tokenize normalize stem:\"BEST\" | summary title | index title; }", - "clear_state | guard { input body | tokenize normalize stem:\"BEST\" | summary body | index body; }", - "clear_state | guard { input title | tokenize | index title_literal; }", - "clear_state | guard { input body | tokenize | index body_literal; }"), - schema); + "clear_state | guard { input body | tokenize normalize stem:\"BEST\" | summary body | index body; }", + "clear_state | guard { input title | tokenize | index title_literal; }", + "clear_state | guard { input body | tokenize | index body_literal; }"), + schema); } } diff --git a/config-model/src/test/java/com/yahoo/schema/derived/LowercaseTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/LowercaseTestCase.java index f234a9cc324..198de997f94 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/LowercaseTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/LowercaseTestCase.java @@ -2,7 +2,7 @@ package com.yahoo.schema.derived; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; @@ -12,7 +12,7 @@ import java.io.IOException; public class LowercaseTestCase extends AbstractExportingTestCase { @Test - public void testDeriving() throws IOException, ParseException { + void testDeriving() throws IOException, ParseException { assertCorrectDeriving("lowercase"); } diff --git a/config-model/src/test/java/com/yahoo/schema/derived/MailTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/MailTestCase.java index c48c44554ed..48aca401694 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/MailTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/MailTestCase.java @@ -3,7 +3,8 @@ package com.yahoo.schema.derived; import com.yahoo.schema.ApplicationBuilder; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; + import java.io.IOException; /** @@ -14,7 +15,7 @@ import java.io.IOException; public class MailTestCase extends AbstractExportingTestCase { @Test - public void testMail() throws IOException, ParseException { + void testMail() throws IOException, ParseException { String dir = "src/test/derived/mail/"; ApplicationBuilder sb = new ApplicationBuilder(); sb.addSchemaFile(dir + "mail.sd"); diff --git a/config-model/src/test/java/com/yahoo/schema/derived/MatchSettingsResolvingTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/MatchSettingsResolvingTestCase.java index a7df862134a..ea79766ed8a 100755 --- a/config-model/src/test/java/com/yahoo/schema/derived/MatchSettingsResolvingTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/MatchSettingsResolvingTestCase.java @@ -3,7 +3,7 @@ package com.yahoo.schema.derived; import com.yahoo.config.model.deploy.TestProperties; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; @@ -13,49 +13,49 @@ import java.io.IOException; public class MatchSettingsResolvingTestCase extends AbstractExportingTestCase { @Test - public void testSimpleDefaults() throws IOException, ParseException { + void testSimpleDefaults() throws IOException, ParseException { assertCorrectDeriving("matchsettings_simple_def", new TestProperties()); } @Test - public void testSimpleWithStructSettings() throws IOException, ParseException { + void testSimpleWithStructSettings() throws IOException, ParseException { assertCorrectDeriving("matchsettings_simple_wss", - new TestProperties()); + new TestProperties()); } @Test - public void testSimpleWithFieldSettings() throws IOException, ParseException { + void testSimpleWithFieldSettings() throws IOException, ParseException { assertCorrectDeriving("matchsettings_simple_wfs", new TestProperties()); } @Test - public void testSimpleStructAndFieldSettings() throws IOException, ParseException { + void testSimpleStructAndFieldSettings() throws IOException, ParseException { assertCorrectDeriving("matchsettings_simple_wss_wfs", new TestProperties()); } @Test - public void testMapDefaults() throws IOException, ParseException { + void testMapDefaults() throws IOException, ParseException { assertCorrectDeriving("matchsettings_map_def", new TestProperties()); } @Test - public void testMapWithStructSettings() throws IOException, ParseException { + void testMapWithStructSettings() throws IOException, ParseException { assertCorrectDeriving("matchsettings_map_wss", new TestProperties()); } @Test - public void testMapWithFieldSettings() throws IOException, ParseException { + void testMapWithFieldSettings() throws IOException, ParseException { assertCorrectDeriving("matchsettings_map_wfs", new TestProperties()); } @Test - public void testMapAfter() throws IOException, ParseException { + void testMapAfter() throws IOException, ParseException { assertCorrectDeriving("matchsettings_map_after", new TestProperties()); } @Test - public void testMapInStruct() throws IOException, ParseException { + void testMapInStruct() throws IOException, ParseException { assertCorrectDeriving("matchsettings_map_in_struct", new TestProperties()); } diff --git a/config-model/src/test/java/com/yahoo/schema/derived/MultiStructTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/MultiStructTestCase.java index 66b3698b38c..7276a5be445 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/MultiStructTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/MultiStructTestCase.java @@ -4,7 +4,7 @@ package com.yahoo.schema.derived; import com.yahoo.config.model.deploy.TestProperties; import com.yahoo.config.model.application.provider.MockFileRegistry; import com.yahoo.schema.ApplicationBuilder; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests deriving a configuration with structs in multiple .sd files @@ -14,11 +14,11 @@ import org.junit.Test; public class MultiStructTestCase extends AbstractExportingTestCase { @Test - public void testDocTypeConfigs() throws Exception { + void testDocTypeConfigs() throws Exception { var logger = new TestableDeployLogger(); var props = new TestProperties(); ApplicationBuilder builder = ApplicationBuilder.createFromDirectory - ("src/test/derived/multi_struct/", new MockFileRegistry(), logger, props); + ("src/test/derived/multi_struct/", new MockFileRegistry(), logger, props); derive("multi_struct", builder, builder.getSchema("shop")); assertCorrectConfigFiles("multi_struct"); } diff --git a/config-model/src/test/java/com/yahoo/schema/derived/MultipleSummariesTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/MultipleSummariesTestCase.java index d434673e43a..8642c45f16d 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/MultipleSummariesTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/MultipleSummariesTestCase.java @@ -3,7 +3,7 @@ package com.yahoo.schema.derived; import com.yahoo.config.model.deploy.TestProperties; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; @@ -15,7 +15,7 @@ import java.io.IOException; public class MultipleSummariesTestCase extends AbstractExportingTestCase { @Test - public void testMultipleSummariesNew() throws IOException, ParseException { + void testMultipleSummariesNew() throws IOException, ParseException { assertCorrectDeriving("multiplesummaries", new TestProperties()); } diff --git a/config-model/src/test/java/com/yahoo/schema/derived/NameCollisionTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/NameCollisionTestCase.java index 689ff9814cc..260dc9e4fdd 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/NameCollisionTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/NameCollisionTestCase.java @@ -5,8 +5,7 @@ package com.yahoo.schema.derived; import com.yahoo.config.model.deploy.TestProperties; import com.yahoo.document.DocumentTypeManager; -import org.junit.Test; -import static org.junit.Assert.assertThrows; +import org.junit.jupiter.api.Test; /** * Verifies that a struct in a document type is preferred over another document type @@ -17,10 +16,10 @@ import static org.junit.Assert.assertThrows; public class NameCollisionTestCase extends AbstractExportingTestCase { @Test - public void testNameCollision() throws Exception { + void testNameCollision() throws Exception { assertCorrectDeriving("namecollision", "collisionstruct", - new TestProperties(), - new TestableDeployLogger()); + new TestProperties(), + new TestableDeployLogger()); DocumentTypeManager.fromFile("temp/namecollision/documentmanager.cfg"); } diff --git a/config-model/src/test/java/com/yahoo/schema/derived/NativeRankTypeDefinitionsTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/NativeRankTypeDefinitionsTestCase.java index f628420556a..c51567b6629 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/NativeRankTypeDefinitionsTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/NativeRankTypeDefinitionsTestCase.java @@ -3,11 +3,11 @@ package com.yahoo.schema.derived; import com.yahoo.schema.AbstractSchemaTestCase; import com.yahoo.schema.document.RankType; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Iterator; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; /** * Testing stuff related to native rank type definitions @@ -16,15 +16,16 @@ import static org.junit.Assert.*; */ public class NativeRankTypeDefinitionsTestCase extends AbstractSchemaTestCase { @Test - public void testTables() { + void testTables() { assertEquals(NativeTable.Type.FIRST_OCCURRENCE.getName(), "firstOccurrenceTable"); assertEquals(NativeTable.Type.OCCURRENCE_COUNT.getName(), "occurrenceCountTable"); assertEquals(NativeTable.Type.PROXIMITY.getName(), "proximityTable"); assertEquals(NativeTable.Type.REVERSE_PROXIMITY.getName(), "reverseProximityTable"); assertEquals(NativeTable.Type.WEIGHT.getName(), "weightTable"); } + @Test - public void testDefinitions() { + void testDefinitions() { NativeRankTypeDefinitionSet defs = new NativeRankTypeDefinitionSet("default"); NativeRankTypeDefinition rank; diff --git a/config-model/src/test/java/com/yahoo/schema/derived/NearestNeighborTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/NearestNeighborTestCase.java index 2f3ad7cfc69..b3a0b8d4558 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/NearestNeighborTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/NearestNeighborTestCase.java @@ -6,24 +6,25 @@ import com.yahoo.search.Query; import com.yahoo.search.query.profile.compiled.CompiledQueryProfileRegistry; import com.yahoo.schema.parser.ParseException; import com.yahoo.vespa.model.container.search.QueryProfiles; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; public class NearestNeighborTestCase extends AbstractExportingTestCase { @Test - public void testNearestNeighbor() throws IOException, ParseException { + void testNearestNeighbor() throws IOException, ParseException { try { ComponentId.resetGlobalCountersForTests(); DerivedConfiguration c = assertCorrectDeriving("nearestneighbor"); - CompiledQueryProfileRegistry queryProfiles = CompiledQueryProfileRegistry.fromConfig(new QueryProfiles(c.getQueryProfiles(), (level, message) -> {}).getConfig()); + CompiledQueryProfileRegistry queryProfiles = CompiledQueryProfileRegistry.fromConfig(new QueryProfiles(c.getQueryProfiles(), (level, message) -> { + }).getConfig()); Query q = new Query("?ranking.features.query(q_vec)=[1,2,3,4,5,6]", // length is 6, not 5 - queryProfiles.getComponent("default")); + queryProfiles.getComponent("default")); fail("This should fail when q_vec is parsed as a tensor"); } catch (IllegalArgumentException e) { // success diff --git a/config-model/src/test/java/com/yahoo/schema/derived/NeuralNetTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/NeuralNetTestCase.java index 56248c02a51..18dddff3984 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/NeuralNetTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/NeuralNetTestCase.java @@ -6,27 +6,28 @@ import com.yahoo.search.query.profile.compiled.CompiledQueryProfile; import com.yahoo.search.query.profile.compiled.CompiledQueryProfileRegistry; import com.yahoo.schema.parser.ParseException; import com.yahoo.vespa.model.container.search.QueryProfiles; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import com.yahoo.component.ComponentId; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class NeuralNetTestCase extends AbstractExportingTestCase { @Test - public void testNeuralNet() throws IOException, ParseException { + void testNeuralNet() throws IOException, ParseException { ComponentId.resetGlobalCountersForTests(); DerivedConfiguration c = assertCorrectDeriving("neuralnet"); // Verify that query profiles end up correct when passed through the same intermediate forms as a full system - CompiledQueryProfileRegistry queryProfiles = CompiledQueryProfileRegistry.fromConfig(new QueryProfiles(c.getQueryProfiles(), (level, message) -> {}).getConfig()); + CompiledQueryProfileRegistry queryProfiles = CompiledQueryProfileRegistry.fromConfig(new QueryProfiles(c.getQueryProfiles(), (level, message) -> { + }).getConfig()); assertNeuralNetQuery(c, queryProfiles.getComponent("default")); } @Test - public void testNeuralNet_noQueryProfiles() throws IOException, ParseException { + void testNeuralNet_noQueryProfiles() throws IOException, ParseException { ComponentId.resetGlobalCountersForTests(); DerivedConfiguration c = assertCorrectDeriving("neuralnet_noqueryprofile"); } diff --git a/config-model/src/test/java/com/yahoo/schema/derived/NuwaTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/NuwaTestCase.java index 210c8a9bdd4..4f30169713a 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/NuwaTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/NuwaTestCase.java @@ -2,8 +2,8 @@ package com.yahoo.schema.derived; import com.yahoo.schema.parser.ParseException; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import java.io.IOException; @@ -15,8 +15,8 @@ import java.io.IOException; public class NuwaTestCase extends AbstractExportingTestCase { @Test - @Ignore - public void testNuwa() throws IOException, ParseException { + @Disabled + void testNuwa() throws IOException, ParseException { System.gc(); long freeBytesBefore = Runtime.getRuntime().freeMemory(); long totalBytesBefore = Runtime.getRuntime().totalMemory(); @@ -27,7 +27,7 @@ public class NuwaTestCase extends AbstractExportingTestCase { long freeBytesAfter = Runtime.getRuntime().freeMemory(); long totalBytesAfter = Runtime.getRuntime().totalMemory(); long additionalAllocated = totalBytesAfter - totalBytesBefore; - System.out.println("Consumed " + ((freeBytesBefore - (freeBytesAfter - additionalAllocated) ) / 1000000) + " Mb"); + System.out.println("Consumed " + ((freeBytesBefore - (freeBytesAfter - additionalAllocated)) / 1000000) + " Mb"); } } diff --git a/config-model/src/test/java/com/yahoo/schema/derived/OrderIlscriptsTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/OrderIlscriptsTestCase.java index 8af0d0a21d3..741f1fd7e02 100755 --- a/config-model/src/test/java/com/yahoo/schema/derived/OrderIlscriptsTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/OrderIlscriptsTestCase.java @@ -2,7 +2,7 @@ package com.yahoo.schema.derived; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; @@ -12,7 +12,7 @@ import java.io.IOException; public class OrderIlscriptsTestCase extends AbstractExportingTestCase { @Test - public void testOrderIlscripts() throws IOException, ParseException { + void testOrderIlscripts() throws IOException, ParseException { assertCorrectDeriving("orderilscripts"); } diff --git a/config-model/src/test/java/com/yahoo/schema/derived/PrefixExactAttributeTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/PrefixExactAttributeTestCase.java index fdcb71432e4..7faea410da2 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/PrefixExactAttributeTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/PrefixExactAttributeTestCase.java @@ -2,7 +2,7 @@ package com.yahoo.schema.derived; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; @@ -14,7 +14,7 @@ import java.io.IOException; public class PrefixExactAttributeTestCase extends AbstractExportingTestCase { @Test - public void testTypes() throws IOException, ParseException { + void testTypes() throws IOException, ParseException { assertCorrectDeriving("prefixexactattribute"); } diff --git a/config-model/src/test/java/com/yahoo/schema/derived/RankProfilesTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/RankProfilesTestCase.java index a83db0caf5a..5c24b32e275 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/RankProfilesTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/RankProfilesTestCase.java @@ -3,7 +3,7 @@ package com.yahoo.schema.derived; import com.yahoo.config.model.deploy.TestProperties; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; @@ -14,7 +14,7 @@ import java.io.IOException; */ public class RankProfilesTestCase extends AbstractExportingTestCase { @Test - public void testRankProfiles() throws IOException, ParseException { + void testRankProfiles() throws IOException, ParseException { assertCorrectDeriving("rankprofiles", null, new TestProperties(), new TestableDeployLogger()); } } diff --git a/config-model/src/test/java/com/yahoo/schema/derived/RankPropertiesTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/RankPropertiesTestCase.java index 8db880e56fe..c46cd5e53c6 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/RankPropertiesTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/RankPropertiesTestCase.java @@ -2,7 +2,7 @@ package com.yahoo.schema.derived; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; @@ -12,7 +12,7 @@ import java.io.IOException; public class RankPropertiesTestCase extends AbstractExportingTestCase { @Test - public void testRankProperties() throws IOException, ParseException { + void testRankProperties() throws IOException, ParseException { assertCorrectDeriving("rankproperties"); } diff --git a/config-model/src/test/java/com/yahoo/schema/derived/ReferenceFieldsTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/ReferenceFieldsTestCase.java index 99d0cf8bf6d..2d9487d4a5e 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/ReferenceFieldsTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/ReferenceFieldsTestCase.java @@ -2,7 +2,7 @@ package com.yahoo.schema.derived; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; @@ -12,7 +12,7 @@ import java.io.IOException; public class ReferenceFieldsTestCase extends AbstractExportingTestCase { @Test - public void configs_related_to_reference_fields_are_derived() throws IOException, ParseException { + void configs_related_to_reference_fields_are_derived() throws IOException, ParseException { assertCorrectDeriving("reference_fields", "ad", new TestableDeployLogger()); } } diff --git a/config-model/src/test/java/com/yahoo/schema/derived/ReferenceFromSeveralTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/ReferenceFromSeveralTestCase.java index ff4506a7f57..caa5bf1b4a9 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/ReferenceFromSeveralTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/ReferenceFromSeveralTestCase.java @@ -4,7 +4,7 @@ package com.yahoo.schema.derived; import com.yahoo.config.model.deploy.TestProperties; import com.yahoo.config.model.application.provider.MockFileRegistry; import com.yahoo.schema.ApplicationBuilder; -import org.junit.Test; +import org.junit.jupiter.api.Test; /** * Tests deriving a configuration with references from multiple .sd files @@ -14,11 +14,11 @@ import org.junit.Test; public class ReferenceFromSeveralTestCase extends AbstractExportingTestCase { @Test - public void testDocManConfigs() throws Exception { + void testDocManConfigs() throws Exception { var logger = new TestableDeployLogger(); var props = new TestProperties(); ApplicationBuilder builder = ApplicationBuilder.createFromDirectory - ("src/test/derived/reference_from_several/", new MockFileRegistry(), logger, props); + ("src/test/derived/reference_from_several/", new MockFileRegistry(), logger, props); derive("reference_from_several", builder, builder.getSchema("foo")); assertCorrectConfigFiles("reference_from_several"); } diff --git a/config-model/src/test/java/com/yahoo/schema/derived/SchemaInheritanceTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/SchemaInheritanceTestCase.java index 1b5d55158b5..f115f69cc8f 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/SchemaInheritanceTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/SchemaInheritanceTestCase.java @@ -6,7 +6,7 @@ import com.yahoo.config.model.deploy.TestProperties; import com.yahoo.io.IOUtils; import com.yahoo.schema.ApplicationBuilder; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; @@ -17,12 +17,12 @@ import java.io.IOException; public class SchemaInheritanceTestCase extends AbstractExportingTestCase { @Test - public void testIt() throws IOException, ParseException { + void testIt() throws IOException, ParseException { try { ApplicationBuilder builder = ApplicationBuilder.createFromDirectory("src/test/derived/schemainheritance/", - new MockFileRegistry(), - new TestableDeployLogger(), - new TestProperties()); + new MockFileRegistry(), + new TestableDeployLogger(), + new TestProperties()); derive("schemainheritance", builder, builder.getSchema("child")); assertCorrectConfigFiles("schemainheritance"); } diff --git a/config-model/src/test/java/com/yahoo/schema/derived/SchemaOrdererTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/SchemaOrdererTestCase.java index 4683bccb0ad..16001d3912d 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/SchemaOrdererTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/SchemaOrdererTestCase.java @@ -10,7 +10,7 @@ import com.yahoo.schema.AbstractSchemaTestCase; import com.yahoo.schema.document.SDDocumentType; import com.yahoo.schema.document.SDField; import com.yahoo.schema.document.TemporarySDField; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.HashMap; @@ -20,7 +20,7 @@ import java.util.Objects; import static java.util.Collections.emptyMap; import static java.util.stream.Collectors.toList; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author bratseth @@ -102,45 +102,45 @@ public class SchemaOrdererTestCase extends AbstractSchemaTestCase { @Test - public void testPerfectOrderingIsKept() { + void testPerfectOrderingIsKept() { assertOrder(Arrays.asList("alone", "grandParent", "mother", "father", "daughter", "product", "pc", "son"), - Arrays.asList("grandParent", "mother", "father", "daughter", "son", "product", "pc", "alone")); + Arrays.asList("grandParent", "mother", "father", "daughter", "son", "product", "pc", "alone")); } @Test - public void testOneLevelReordering() { + void testOneLevelReordering() { assertOrder(Arrays.asList("alone", "grandParent", "mother", "father", "daughter", "product", "pc", "son"), - Arrays.asList("grandParent", "daughter", "son", "mother", "father", "pc", "product", "alone")); + Arrays.asList("grandParent", "daughter", "son", "mother", "father", "pc", "product", "alone")); } @Test - public void testMultiLevelReordering() { + void testMultiLevelReordering() { assertOrder(Arrays.asList("alone", "grandParent", "mother", "father", "daughter", "product", "pc", "son"), - Arrays.asList("daughter", "son", "mother", "father", "grandParent", "pc", "product", "alone")); + Arrays.asList("daughter", "son", "mother", "father", "grandParent", "pc", "product", "alone")); } @Test - public void testAloneIsKeptInPlaceWithMultiLevelReordering() { + void testAloneIsKeptInPlaceWithMultiLevelReordering() { assertOrder(Arrays.asList("alone", "grandParent", "mother", "father", "daughter", "product", "pc", "son"), - Arrays.asList("alone", "daughter", "son", "mother", "father", "grandParent", "pc", "product")); + Arrays.asList("alone", "daughter", "son", "mother", "father", "grandParent", "pc", "product")); } @Test - public void testPartialMultiLevelReordering() { + void testPartialMultiLevelReordering() { assertOrder(Arrays.asList("alone", "grandParent", "mother", "father", "daughter", "product", "pc", "son"), - Arrays.asList("daughter", "grandParent", "mother", "son", "father", "product", "pc", "alone")); + Arrays.asList("daughter", "grandParent", "mother", "son", "father", "product", "pc", "alone")); } @Test - public void testMultilevelReorderingAccrossHierarchies() { + void testMultilevelReorderingAccrossHierarchies() { assertOrder(Arrays.asList("alone", "grandParent", "mother", "father", "daughter", "product", "pc", "son"), - Arrays.asList("daughter", "pc", "son", "mother", "grandParent", "father", "product", "alone")); + Arrays.asList("daughter", "pc", "son", "mother", "grandParent", "father", "product", "alone")); } @Test - public void referees_are_ordered_before_referrer() { + void referees_are_ordered_before_referrer() { assertOrder(Arrays.asList("alone", "grandParent", "mother", "father", "daughter", "product", "pc", "accessory-pc", "son"), - Arrays.asList("accessory-pc", "daughter", "pc", "son", "mother", "grandParent", "father", "product", "alone")); + Arrays.asList("accessory-pc", "daughter", "pc", "son", "mother", "grandParent", "father", "product", "alone")); } diff --git a/config-model/src/test/java/com/yahoo/schema/derived/SimpleInheritTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/SimpleInheritTestCase.java index d8b39bfd978..e5b95e8a6ca 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/SimpleInheritTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/SimpleInheritTestCase.java @@ -4,7 +4,7 @@ package com.yahoo.schema.derived; import com.yahoo.schema.Schema; import com.yahoo.schema.ApplicationBuilder; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; @@ -15,7 +15,7 @@ import java.io.IOException; public class SimpleInheritTestCase extends AbstractExportingTestCase { @Test - public void testEmptyChild() throws IOException, ParseException { + void testEmptyChild() throws IOException, ParseException { String name = "emptychild"; final String expectedResultsDirName = "src/test/derived/" + name + "/"; diff --git a/config-model/src/test/java/com/yahoo/schema/derived/SliceTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/SliceTestCase.java index 2aad47dae6c..9ef664bd287 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/SliceTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/SliceTestCase.java @@ -3,19 +3,17 @@ package com.yahoo.schema.derived; import com.yahoo.component.ComponentId; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.assertEquals; - /** * @author bratseth */ public class SliceTestCase extends AbstractExportingTestCase { @Test - public void testSlice() throws IOException, ParseException { + void testSlice() throws IOException, ParseException { ComponentId.resetGlobalCountersForTests(); DerivedConfiguration c = assertCorrectDeriving("slice"); } diff --git a/config-model/src/test/java/com/yahoo/schema/derived/SortingTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/SortingTestCase.java index 0c091a7a367..a4590075a79 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/SortingTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/SortingTestCase.java @@ -3,7 +3,7 @@ package com.yahoo.schema.derived; import com.yahoo.config.model.deploy.TestProperties; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; @@ -15,7 +15,7 @@ import java.io.IOException; public class SortingTestCase extends AbstractExportingTestCase { @Test - public void testDocumentDerivingNewParser() throws IOException, ParseException { + void testDocumentDerivingNewParser() throws IOException, ParseException { assertCorrectDeriving("sorting", new TestProperties()); } diff --git a/config-model/src/test/java/com/yahoo/schema/derived/StreamingStructTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/StreamingStructTestCase.java index 6f27930e239..1524801bad7 100755 --- a/config-model/src/test/java/com/yahoo/schema/derived/StreamingStructTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/StreamingStructTestCase.java @@ -2,7 +2,7 @@ package com.yahoo.schema.derived; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; @@ -14,12 +14,12 @@ import java.io.IOException; public class StreamingStructTestCase extends AbstractExportingTestCase { @Test - public void testStreamingStruct() throws IOException, ParseException { + void testStreamingStruct() throws IOException, ParseException { assertCorrectDeriving("streamingstruct"); } @Test - public void testStreamingStructExplicitDefaultSummaryClass() throws IOException, ParseException { + void testStreamingStructExplicitDefaultSummaryClass() throws IOException, ParseException { assertCorrectDeriving("streamingstructdefault"); } diff --git a/config-model/src/test/java/com/yahoo/schema/derived/StructAnyOrderTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/StructAnyOrderTestCase.java index 865b5da87cf..9a1bba88cc6 100755 --- a/config-model/src/test/java/com/yahoo/schema/derived/StructAnyOrderTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/StructAnyOrderTestCase.java @@ -2,7 +2,7 @@ package com.yahoo.schema.derived; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; @@ -11,7 +11,7 @@ import java.io.IOException; */ public class StructAnyOrderTestCase extends AbstractExportingTestCase { @Test - public void testStructAnyOrder() throws IOException, ParseException { + void testStructAnyOrder() throws IOException, ParseException { assertCorrectDeriving("structanyorder"); } } diff --git a/config-model/src/test/java/com/yahoo/schema/derived/StructInheritanceTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/StructInheritanceTestCase.java index 092e64420e8..60be9dc9016 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/StructInheritanceTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/StructInheritanceTestCase.java @@ -5,14 +5,14 @@ package com.yahoo.schema.derived; import com.yahoo.schema.ApplicationBuilder; import com.yahoo.schema.parser.ParseException; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import java.io.File; import java.io.IOException; - -import org.junit.rules.TemporaryFolder; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Tests struct inheritance @@ -21,15 +21,11 @@ import org.junit.rules.TemporaryFolder; */ public class StructInheritanceTestCase extends AbstractExportingTestCase { - @Rule - public TemporaryFolder tmpDir = new TemporaryFolder(); - - @SuppressWarnings("deprecation") - @Rule - public final ExpectedException exceptionRule = ExpectedException.none(); + @TempDir + public File tmpDir; @Test - public void requireThatStructCanInherit() throws IOException, ParseException { + void requireThatStructCanInherit() throws IOException, ParseException { String dir = "src/test/derived/structinheritance/"; ApplicationBuilder builder = new ApplicationBuilder(); builder.addSchemaFile(dir + "simple.sd"); @@ -39,14 +35,15 @@ public class StructInheritanceTestCase extends AbstractExportingTestCase { } @Test - public void requireThatRedeclareIsNotAllowed() throws IOException, ParseException { - exceptionRule.expect(IllegalArgumentException.class); - exceptionRule.expectMessage("cannot inherit from base and redeclare field name"); - String dir = "src/test/derived/structinheritance/"; - ApplicationBuilder builder = new ApplicationBuilder(); - builder.addSchemaFile(dir + "bad.sd"); - builder.build(true); - derive("structinheritance", builder, builder.getSchema("bad")); + void requireThatRedeclareIsNotAllowed() throws IOException, ParseException { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + String dir = "src/test/derived/structinheritance/"; + ApplicationBuilder builder = new ApplicationBuilder(); + builder.addSchemaFile(dir + "bad.sd"); + builder.build(true); + derive("structinheritance", builder, builder.getSchema("bad")); + }); + assertTrue(exception.getMessage().contains("cannot inherit from base and redeclare field name")); } } diff --git a/config-model/src/test/java/com/yahoo/schema/derived/SummaryMapTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/SummaryMapTestCase.java index 23cd7952626..577bcf6efcc 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/SummaryMapTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/SummaryMapTestCase.java @@ -12,16 +12,15 @@ import com.yahoo.schema.parser.ParseException; import com.yahoo.schema.processing.Processing; import com.yahoo.vespa.documentmodel.SummaryTransform; import com.yahoo.vespa.model.container.search.QueryProfiles; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Iterator; import java.util.Set; import static com.yahoo.config.model.test.TestUtil.joinLines; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; + /** * Tests summary map extraction * @@ -29,7 +28,7 @@ import static org.junit.Assert.assertTrue; */ public class SummaryMapTestCase extends AbstractSchemaTestCase { @Test - public void testDeriving() throws IOException, ParseException { + void testDeriving() throws IOException, ParseException { Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/simple.sd"); SummaryMap summaryMap = new SummaryMap(schema); @@ -76,8 +75,9 @@ public class SummaryMapTestCase extends AbstractSchemaTestCase { assertFalse(transforms.hasNext()); } + @Test - public void testPositionDeriving() { + void testPositionDeriving() { Schema schema = new Schema("store", MockApplicationPackage.createEmpty()); SDDocumentType document = new SDDocumentType("store"); schema.addDocument(document); @@ -85,7 +85,7 @@ public class SummaryMapTestCase extends AbstractSchemaTestCase { SDField field = document.addField(fieldName, PositionDataType.INSTANCE); field.parseIndexingScript("{ attribute | summary }"); new Processing().process(schema, new BaseDeployLogger(), new RankProfileRegistry(), new QueryProfiles(), - true, false, Set.of()); + true, false, Set.of()); SummaryMap summaryMap = new SummaryMap(schema); Iterator<FieldResultTransform> transforms = summaryMap.resultTransforms().values().iterator(); @@ -105,18 +105,18 @@ public class SummaryMapTestCase extends AbstractSchemaTestCase { transform = transforms.next(); assertEquals("location_zcurve", transform.getFieldName()); - assertEquals(SummaryTransform.ATTRIBUTE,transform.getTransform()); + assertEquals(SummaryTransform.ATTRIBUTE, transform.getTransform()); transform = transforms.next(); assertEquals("documentid", transform.getFieldName()); - assertEquals(SummaryTransform.DOCUMENT_ID,transform.getTransform()); + assertEquals(SummaryTransform.DOCUMENT_ID, transform.getTransform()); assertFalse(transforms.hasNext()); SummarymapConfig.Builder scb = new SummarymapConfig.Builder(); summaryMap.getConfig(scb); SummarymapConfig c = scb.build(); - + assertEquals(-1, c.defaultoutputclass()); assertEquals(c.override().size(), 5); @@ -127,7 +127,7 @@ public class SummaryMapTestCase extends AbstractSchemaTestCase { assertEquals(c.override(1).field(), "rankfeatures"); assertEquals(c.override(1).command(), "rankfeatures"); assertEquals(c.override(1).arguments(), ""); - + assertEquals(c.override(2).field(), "summaryfeatures"); assertEquals(c.override(2).command(), "summaryfeatures"); assertEquals(c.override(2).arguments(), ""); @@ -138,7 +138,7 @@ public class SummaryMapTestCase extends AbstractSchemaTestCase { } @Test - public void testFailOnSummaryFieldSourceCollision() { + void testFailOnSummaryFieldSourceCollision() { try { ApplicationBuilder.buildFromFile("src/test/examples/summaryfieldcollision.sd"); } catch (Exception e) { @@ -147,7 +147,7 @@ public class SummaryMapTestCase extends AbstractSchemaTestCase { } @Test - public void source_field_is_passed_as_argument_in_matched_elements_filter_transforms() throws ParseException { + void source_field_is_passed_as_argument_in_matched_elements_filter_transforms() throws ParseException { assertOverride(joinLines("field my_field type map<string, string> {", " indexing: summary", " summary: matched-elements-only", @@ -163,7 +163,7 @@ public class SummaryMapTestCase extends AbstractSchemaTestCase { } @Test - public void commands_that_are_dynamic_and_require_the_query() { + void commands_that_are_dynamic_and_require_the_query() { assertTrue(SummaryMap.isDynamicCommand("dynamicteaser")); assertTrue(SummaryMap.isDynamicCommand(SummaryTransform.MATCHED_ELEMENTS_FILTER.getName())); assertTrue(SummaryMap.isDynamicCommand(SummaryTransform.MATCHED_ATTRIBUTE_ELEMENTS_FILTER.getName())); @@ -171,7 +171,7 @@ public class SummaryMapTestCase extends AbstractSchemaTestCase { } @Test - public void documentid_summary_field_has_corresponding_summary_transform() throws ParseException { + void documentid_summary_field_has_corresponding_summary_transform() throws ParseException { var schema = buildSchema("field foo type string { indexing: summary }", joinLines("document-summary bar {", " summary documentid type string {}", @@ -180,7 +180,7 @@ public class SummaryMapTestCase extends AbstractSchemaTestCase { } @Test - public void documentid_summary_transform_requires_disk_access() { + void documentid_summary_transform_requires_disk_access() { assertFalse(SummaryTransform.DOCUMENT_ID.isInMemory()); } diff --git a/config-model/src/test/java/com/yahoo/schema/derived/SummaryTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/SummaryTestCase.java index 73713319cfe..a9a230c94a2 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/SummaryTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/SummaryTestCase.java @@ -7,15 +7,14 @@ import com.yahoo.schema.ApplicationBuilder; import com.yahoo.schema.AbstractSchemaTestCase; import com.yahoo.schema.parser.ParseException; import com.yahoo.vespa.config.search.SummaryConfig; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Iterator; import static com.yahoo.config.model.test.TestUtil.joinLines; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; /** * Tests summary extraction @@ -25,7 +24,7 @@ import static org.junit.Assert.assertTrue; public class SummaryTestCase extends AbstractSchemaTestCase { @Test - public void deriveRawAsBase64() throws ParseException { + void deriveRawAsBase64() throws ParseException { String sd = joinLines( "schema s {", " document s {", @@ -40,7 +39,7 @@ public class SummaryTestCase extends AbstractSchemaTestCase { } @Test - public void deriveRawAsLegacy() throws ParseException { + void deriveRawAsLegacy() throws ParseException { String sd = joinLines( "schema s {", " raw-as-base64-in-summary: false", @@ -56,7 +55,7 @@ public class SummaryTestCase extends AbstractSchemaTestCase { } @Test - public void testDeriving() throws IOException, ParseException { + void testDeriving() throws IOException, ParseException { Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/simple.sd"); SummaryClass summary = new SummaryClass(schema, schema.getSummary("default"), new BaseDeployLogger()); assertEquals("default", summary.getName()); @@ -121,7 +120,7 @@ public class SummaryTestCase extends AbstractSchemaTestCase { } @Test - public void reference_fields_can_be_part_of_summary_classes() throws ParseException { + void reference_fields_can_be_part_of_summary_classes() throws ParseException { Schema adSchema = buildCampaignAdModel(); SummaryClass defaultClass = new SummaryClass(adSchema, adSchema.getSummary("default"), new BaseDeployLogger()); @@ -154,7 +153,7 @@ public class SummaryTestCase extends AbstractSchemaTestCase { } @Test - public void omit_summary_features_specified_for_document_summary() throws ParseException { + void omit_summary_features_specified_for_document_summary() throws ParseException { String sd = joinLines( "schema test {", " document test {", diff --git a/config-model/src/test/java/com/yahoo/schema/derived/TokenizationTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/TokenizationTestCase.java index ac6acf172e9..c8a2279a407 100755 --- a/config-model/src/test/java/com/yahoo/schema/derived/TokenizationTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/TokenizationTestCase.java @@ -2,7 +2,7 @@ package com.yahoo.schema.derived; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; @@ -12,7 +12,7 @@ import java.io.IOException; public class TokenizationTestCase extends AbstractExportingTestCase { @Test - public void testTokenizationScripts() throws IOException, ParseException { + void testTokenizationScripts() throws IOException, ParseException { assertCorrectDeriving("tokenization"); } diff --git a/config-model/src/test/java/com/yahoo/schema/derived/TwoStreamingStructsTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/TwoStreamingStructsTestCase.java index 72411fa1770..5db9a00ce69 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/TwoStreamingStructsTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/TwoStreamingStructsTestCase.java @@ -3,7 +3,7 @@ package com.yahoo.schema.derived; import com.yahoo.schema.ApplicationBuilder; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; @@ -15,7 +15,7 @@ import java.io.IOException; public class TwoStreamingStructsTestCase extends AbstractExportingTestCase { @Test - public void testTwoStreamingStructsExporting() throws ParseException, IOException { + void testTwoStreamingStructsExporting() throws ParseException, IOException { String root = "src/test/derived/twostreamingstructs"; ApplicationBuilder builder = new ApplicationBuilder(); diff --git a/config-model/src/test/java/com/yahoo/schema/derived/TypeConversionTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/TypeConversionTestCase.java index 84a561924ca..fd9f2164b86 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/TypeConversionTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/TypeConversionTestCase.java @@ -11,11 +11,12 @@ import com.yahoo.schema.document.SDDocumentType; import com.yahoo.schema.document.SDField; import com.yahoo.schema.processing.Processing; import com.yahoo.vespa.model.container.search.QueryProfiles; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Set; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertFalse; + /** * Tests automatic type conversion using multifield indices * @@ -25,7 +26,7 @@ public class TypeConversionTestCase extends AbstractSchemaTestCase { /** Tests that exact-string stuff is not spilled over to the default index */ @Test - public void testExactStringToStringTypeConversion() { + void testExactStringToStringTypeConversion() { Schema schema = new Schema("test", MockApplicationPackage.createEmpty()); RankProfileRegistry rankProfileRegistry = RankProfileRegistry.createRankProfileRegistryWithBuiltinRankProfiles(schema); SDDocumentType document = new SDDocumentType("test"); @@ -35,7 +36,7 @@ public class TypeConversionTestCase extends AbstractSchemaTestCase { document.addField(a); new Processing().process(schema, new BaseDeployLogger(), rankProfileRegistry, new QueryProfiles(), - true, false, Set.of()); + true, false, Set.of()); DerivedConfiguration derived = new DerivedConfiguration(schema, rankProfileRegistry); IndexInfo indexInfo = derived.getIndexInfo(); assertFalse(indexInfo.hasCommand("default", "compact-to-term")); diff --git a/config-model/src/test/java/com/yahoo/schema/derived/TypesTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/TypesTestCase.java index 7443ef01c95..348d156a5f9 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/TypesTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/TypesTestCase.java @@ -2,7 +2,7 @@ package com.yahoo.schema.derived; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; @@ -14,7 +14,7 @@ import java.io.IOException; public class TypesTestCase extends AbstractExportingTestCase { @Test - public void testTypes() throws IOException, ParseException { + void testTypes() throws IOException, ParseException { assertCorrectDeriving("types"); } diff --git a/config-model/src/test/java/com/yahoo/schema/derived/VsmFieldsTestCase.java b/config-model/src/test/java/com/yahoo/schema/derived/VsmFieldsTestCase.java index c59f82a2c12..4b478d7da35 100644 --- a/config-model/src/test/java/com/yahoo/schema/derived/VsmFieldsTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/derived/VsmFieldsTestCase.java @@ -10,9 +10,9 @@ import com.yahoo.schema.document.SDDocumentType; import com.yahoo.schema.document.SDField; import com.yahoo.schema.document.TemporarySDField; import com.yahoo.vespa.config.search.vsm.VsmfieldsConfig; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author geirst @@ -21,7 +21,7 @@ public class VsmFieldsTestCase { @SuppressWarnings("deprecation") @Test - public void reference_type_field_is_unsearchable() { + void reference_type_field_is_unsearchable() { Schema schema = new Schema("test", MockApplicationPackage.createEmpty(), new MockFileRegistry(), new TestableDeployLogger(), new TestProperties()); var sdoc = new SDDocumentType("test"); schema.addDocument(sdoc); diff --git a/config-model/src/test/java/com/yahoo/schema/document/ComplexAttributeFieldUtilsTestCase.java b/config-model/src/test/java/com/yahoo/schema/document/ComplexAttributeFieldUtilsTestCase.java index ea3f207df91..7a89f52268f 100644 --- a/config-model/src/test/java/com/yahoo/schema/document/ComplexAttributeFieldUtilsTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/document/ComplexAttributeFieldUtilsTestCase.java @@ -4,11 +4,11 @@ package com.yahoo.schema.document; import com.yahoo.schema.Schema; import com.yahoo.schema.ApplicationBuilder; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static com.yahoo.config.model.test.TestUtil.joinLines; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ComplexAttributeFieldUtilsTestCase { @@ -77,7 +77,7 @@ public class ComplexAttributeFieldUtilsTestCase { } @Test - public void array_of_struct_with_only_struct_field_attributes_is_tagged_as_such() throws ParseException { + void array_of_struct_with_only_struct_field_attributes_is_tagged_as_such() throws ParseException { Fixture f = new Fixture("elem_array", joinLines("field elem_array type array<elem> {", " indexing: summary", @@ -90,7 +90,7 @@ public class ComplexAttributeFieldUtilsTestCase { } @Test - public void array_of_struct_with_some_struct_field_attributes_is_tagged_as_such() throws ParseException { + void array_of_struct_with_some_struct_field_attributes_is_tagged_as_such() throws ParseException { Fixture f = new Fixture("elem_array", joinLines("field elem_array type array<elem> {", " indexing: summary", @@ -102,7 +102,7 @@ public class ComplexAttributeFieldUtilsTestCase { } @Test - public void map_of_struct_with_only_struct_field_attributes_is_tagged_as_such() throws ParseException { + void map_of_struct_with_only_struct_field_attributes_is_tagged_as_such() throws ParseException { Fixture f = new Fixture("elem_map", joinLines("field elem_map type map<string, elem> {", " indexing: summary", @@ -117,7 +117,7 @@ public class ComplexAttributeFieldUtilsTestCase { } @Test - public void map_of_struct_with_some_struct_field_attributes_is_tagged_as_such() throws ParseException { + void map_of_struct_with_some_struct_field_attributes_is_tagged_as_such() throws ParseException { { Fixture f = new Fixture("elem_map", joinLines("field elem_map type map<int, elem> {", @@ -145,7 +145,7 @@ public class ComplexAttributeFieldUtilsTestCase { } @Test - public void map_of_primitive_type_with_only_struct_field_attributes_is_tagged_as_such() throws ParseException { + void map_of_primitive_type_with_only_struct_field_attributes_is_tagged_as_such() throws ParseException { Fixture f = new Fixture("str_map", joinLines("field str_map type map<string, string> {", " indexing: summary", @@ -159,7 +159,7 @@ public class ComplexAttributeFieldUtilsTestCase { } @Test - public void map_of_primitive_type_with_some_struct_field_attributes_is_tagged_as_such() throws ParseException { + void map_of_primitive_type_with_some_struct_field_attributes_is_tagged_as_such() throws ParseException { { Fixture f = new Fixture("int_map", joinLines("field int_map type map<int, int> {", @@ -185,7 +185,7 @@ public class ComplexAttributeFieldUtilsTestCase { } @Test - public void unsupported_complex_field_is_tagged_as_such() throws ParseException { + void unsupported_complex_field_is_tagged_as_such() throws ParseException { { ComplexFixture f = new ComplexFixture("elem_array", joinLines("field elem_array type array<elem> {", @@ -214,7 +214,7 @@ public class ComplexAttributeFieldUtilsTestCase { } @Test - public void only_struct_field_attributes_are_considered_when_tagging_a_complex_field() throws ParseException { + void only_struct_field_attributes_are_considered_when_tagging_a_complex_field() throws ParseException { { ComplexFixture f = new ComplexFixture("elem_array", joinLines("field elem_array type array<elem> {", diff --git a/config-model/src/test/java/com/yahoo/schema/document/HnswIndexParamsTestCase.java b/config-model/src/test/java/com/yahoo/schema/document/HnswIndexParamsTestCase.java index 8ef51369ecb..51affaa0cc4 100644 --- a/config-model/src/test/java/com/yahoo/schema/document/HnswIndexParamsTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/document/HnswIndexParamsTestCase.java @@ -3,7 +3,7 @@ package com.yahoo.schema.document; import java.util.Optional; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static org.hamcrest.core.Is.is; import static org.hamcrest.MatcherAssert.assertThat; @@ -11,7 +11,7 @@ import static org.hamcrest.MatcherAssert.assertThat; public class HnswIndexParamsTestCase { @Test - public void override_from() throws Exception { + void override_from() throws Exception { var empty = new HnswIndexParams(); var builder = new HnswIndexParams.Builder(); builder.setMaxLinksPerNode(7); diff --git a/config-model/src/test/java/com/yahoo/schema/parser/ConvertIntermediateTestCase.java b/config-model/src/test/java/com/yahoo/schema/parser/ConvertIntermediateTestCase.java index 516c259013f..8f9f8032054 100644 --- a/config-model/src/test/java/com/yahoo/schema/parser/ConvertIntermediateTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/parser/ConvertIntermediateTestCase.java @@ -4,10 +4,10 @@ package com.yahoo.schema.parser; import com.yahoo.document.DocumentTypeManager; import static com.yahoo.config.model.test.TestUtil.joinLines; -import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertThrows; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author arnej @@ -15,12 +15,12 @@ import static org.junit.Assert.assertThrows; public class ConvertIntermediateTestCase { @Test - public void can_convert_minimal_schema() throws Exception { + void can_convert_minimal_schema() throws Exception { String input = joinLines - ("schema foo {", - " document foo {", - " }", - "}"); + ("schema foo {", + " document foo {", + " }", + "}"); var collection = new IntermediateCollection(); ParsedSchema schema = collection.addSchemaFromString(input); assertEquals("foo", schema.getDocument().name()); @@ -32,7 +32,7 @@ public class ConvertIntermediateTestCase { } @Test - public void can_convert_schema_files() throws Exception { + void can_convert_schema_files() throws Exception { var collection = new IntermediateCollection(); collection.addSchemaFromFile("src/test/derived/deriver/child.sd"); collection.addSchemaFromFile("src/test/derived/deriver/grandparent.sd"); @@ -50,7 +50,7 @@ public class ConvertIntermediateTestCase { } @Test - public void can_convert_structs_and_annotations() throws Exception { + void can_convert_structs_and_annotations() throws Exception { var collection = new IntermediateCollection(); collection.addSchemaFromFile("src/test/converter/child.sd"); collection.addSchemaFromFile("src/test/converter/other.sd"); @@ -62,34 +62,34 @@ public class ConvertIntermediateTestCase { var dt = docMan.getDocumentType("child"); assertTrue(dt != null); for (var parent : dt.getInheritedTypes()) { - System.err.println("dt "+dt.getName()+" inherits from "+parent.getName()); + System.err.println("dt " + dt.getName() + " inherits from " + parent.getName()); } for (var field : dt.fieldSetAll()) { - System.err.println("dt "+dt.getName()+" contains field "+field.getName()+" of type "+field.getDataType()); + System.err.println("dt " + dt.getName() + " contains field " + field.getName() + " of type " + field.getDataType()); } dt = docMan.getDocumentType("parent"); assertTrue(dt != null); for (var parent : dt.getInheritedTypes()) { - System.err.println("dt "+dt.getName()+" inherits from "+parent.getName()); + System.err.println("dt " + dt.getName() + " inherits from " + parent.getName()); } for (var field : dt.fieldSetAll()) { - System.err.println("dt "+dt.getName()+" contains field "+field.getName()+" of type "+field.getDataType()); + System.err.println("dt " + dt.getName() + " contains field " + field.getName() + " of type " + field.getDataType()); } dt = docMan.getDocumentType("grandparent"); assertTrue(dt != null); for (var parent : dt.getInheritedTypes()) { - System.err.println("dt "+dt.getName()+" inherits from "+parent.getName()); + System.err.println("dt " + dt.getName() + " inherits from " + parent.getName()); } for (var field : dt.fieldSetAll()) { - System.err.println("dt "+dt.getName()+" contains field "+field.getName()+" of type "+field.getDataType()); + System.err.println("dt " + dt.getName() + " contains field " + field.getName() + " of type " + field.getDataType()); } dt = docMan.getDocumentType("other"); assertTrue(dt != null); for (var parent : dt.getInheritedTypes()) { - System.err.println("dt "+dt.getName()+" inherits from "+parent.getName()); + System.err.println("dt " + dt.getName() + " inherits from " + parent.getName()); } for (var field : dt.fieldSetAll()) { - System.err.println("dt "+dt.getName()+" contains field "+field.getName()+" of type "+field.getDataType()); + System.err.println("dt " + dt.getName() + " contains field " + field.getName() + " of type " + field.getDataType()); } } } diff --git a/config-model/src/test/java/com/yahoo/schema/parser/IntermediateCollectionTestCase.java b/config-model/src/test/java/com/yahoo/schema/parser/IntermediateCollectionTestCase.java index c4ee1d27c8c..6ebfea41d84 100644 --- a/config-model/src/test/java/com/yahoo/schema/parser/IntermediateCollectionTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/parser/IntermediateCollectionTestCase.java @@ -10,10 +10,9 @@ import java.io.File; import java.io.FileReader; import java.util.List; -import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertThrows; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; /** * @author arnej @@ -21,12 +20,12 @@ import static org.junit.Assert.assertThrows; public class IntermediateCollectionTestCase { @Test - public void can_add_minimal_schema() throws Exception { + void can_add_minimal_schema() throws Exception { String input = joinLines - ("schema foo {", - " document foo {", - " }", - "}"); + ("schema foo {", + " document foo {", + " }", + "}"); var collection = new IntermediateCollection(); ParsedSchema schema = collection.addSchemaFromString(input); assertEquals("foo", schema.name()); @@ -35,12 +34,12 @@ public class IntermediateCollectionTestCase { } @Test - public void names_may_differ() throws Exception { + void names_may_differ() throws Exception { String input = joinLines - ("schema foo_search {", - " document foo {", - " }", - "}"); + ("schema foo_search {", + " document foo {", + " }", + "}"); var collection = new IntermediateCollection(); ParsedSchema schema = collection.addSchemaFromString(input); assertEquals("foo_search", schema.name()); @@ -49,7 +48,7 @@ public class IntermediateCollectionTestCase { } @Test - public void can_add_schema_files() throws Exception { + void can_add_schema_files() throws Exception { var collection = new IntermediateCollection(); collection.addSchemaFromFile("src/test/derived/deriver/child.sd"); collection.addSchemaFromFile("src/test/derived/deriver/grandparent.sd"); @@ -75,7 +74,7 @@ public class IntermediateCollectionTestCase { } @Test - public void can_add_schemas() throws Exception { + void can_add_schemas() throws Exception { var collection = new IntermediateCollection(); collection.addSchemaFromReader(readerOf("src/test/derived/deriver/child.sd")); collection.addSchemaFromReader(readerOf("src/test/derived/deriver/grandparent.sd")); @@ -101,7 +100,7 @@ public class IntermediateCollectionTestCase { } @Test - public void can_add_extra_rank_profiles() throws Exception { + void can_add_extra_rank_profiles() throws Exception { var collection = new IntermediateCollection(); collection.addSchemaFromFile("src/test/derived/rankprofilemodularity/test.sd"); collection.addRankProfileFile("test", "src/test/derived/rankprofilemodularity/test/outside_schema1.profile"); @@ -128,32 +127,32 @@ public class IntermediateCollectionTestCase { } @Test - public void name_mismatch_throws() throws Exception { + void name_mismatch_throws() throws Exception { var collection = new IntermediateCollection(); var ex = assertThrows(IllegalArgumentException.class, () -> - collection.addSchemaFromReader(readerOf("src/test/cfg/application/sdfilenametest/schemas/notmusic.sd"))); + collection.addSchemaFromReader(readerOf("src/test/cfg/application/sdfilenametest/schemas/notmusic.sd"))); assertEquals("The file containing schema 'music' must be named 'music.sd', was 'notmusic.sd'", - ex.getMessage()); + ex.getMessage()); } @Test - public void bad_parse_throws() throws Exception { + void bad_parse_throws() throws Exception { var collection = new IntermediateCollection(); var ex = assertThrows(ParseException.class, () -> - collection.addSchemaFromFile("src/test/examples/badparse.sd")); + collection.addSchemaFromFile("src/test/examples/badparse.sd")); assertTrue(ex.getMessage().startsWith("Failed parsing schema from src/test/examples/badparse.sd: Encountered")); ex = assertThrows(ParseException.class, () -> - collection.addSchemaFromReader(readerOf("src/test/examples/badparse.sd"))); + collection.addSchemaFromReader(readerOf("src/test/examples/badparse.sd"))); assertTrue(ex.getMessage().startsWith("Failed parsing schema from src/test/examples/badparse.sd: Encountered")); collection.addSchemaFromFile("src/test/derived/rankprofilemodularity/test.sd"); collection.addRankProfileFile("test", "src/test/derived/rankprofilemodularity/test/outside_schema1.profile"); ex = assertThrows(ParseException.class, () -> - collection.addRankProfileFile("test", "src/test/examples/badparse.sd")); + collection.addRankProfileFile("test", "src/test/examples/badparse.sd")); assertTrue(ex.getMessage().startsWith("Failed parsing rank-profile from src/test/examples/badparse.sd: Encountered")); } @Test - public void can_resolve_document_inheritance() throws Exception { + void can_resolve_document_inheritance() throws Exception { var collection = new IntermediateCollection(); collection.addSchemaFromFile("src/test/derived/deriver/child.sd"); collection.addSchemaFromFile("src/test/derived/deriver/grandparent.sd"); @@ -172,63 +171,63 @@ public class IntermediateCollectionTestCase { } @Test - public void can_detect_schema_inheritance_cycles() throws Exception { + void can_detect_schema_inheritance_cycles() throws Exception { var collection = new IntermediateCollection(); collection.addSchemaFromString("schema foo inherits bar { document foo {} }"); collection.addSchemaFromString("schema bar inherits qux { document bar {} }"); collection.addSchemaFromString("schema qux inherits foo { document qux {} }"); assertEquals(collection.getParsedSchemas().size(), 3); var ex = assertThrows(IllegalArgumentException.class, () -> - collection.resolveInternalConnections()); + collection.resolveInternalConnections()); assertTrue(ex.getMessage().startsWith("Inheritance/reference cycle for schemas: ")); } @Test - public void can_detect_document_inheritance_cycles() throws Exception { + void can_detect_document_inheritance_cycles() throws Exception { var collection = new IntermediateCollection(); collection.addSchemaFromString("schema foo { document foo inherits bar {} }"); collection.addSchemaFromString("schema bar { document bar inherits qux {} }"); collection.addSchemaFromString("schema qux { document qux inherits foo {} }"); assertEquals(collection.getParsedSchemas().size(), 3); var ex = assertThrows(IllegalArgumentException.class, () -> - collection.resolveInternalConnections()); - System.err.println("ex: "+ex.getMessage()); + collection.resolveInternalConnections()); + System.err.println("ex: " + ex.getMessage()); assertTrue(ex.getMessage().startsWith("Inheritance/reference cycle for documents: ")); } @Test - public void can_detect_missing_doc() throws Exception { + void can_detect_missing_doc() throws Exception { var collection = new IntermediateCollection(); collection.addSchemaFromString("schema foo { document foo inherits bar {} }"); collection.addSchemaFromString("schema qux { document qux inherits foo {} }"); assertEquals(collection.getParsedSchemas().size(), 2); var ex = assertThrows(IllegalArgumentException.class, () -> - collection.resolveInternalConnections()); + collection.resolveInternalConnections()); assertEquals("document foo inherits from unavailable document bar", ex.getMessage()); } @Test - public void can_detect_document_reference_cycle() throws Exception { + void can_detect_document_reference_cycle() throws Exception { var collection = new IntermediateCollection(); collection.addSchemaFromString("schema foo { document foo { field oneref type reference<bar> {} } }"); collection.addSchemaFromString("schema bar { document bar { field tworef type reference<foo> {} } }"); assertEquals(collection.getParsedSchemas().size(), 2); var ex = assertThrows(IllegalArgumentException.class, () -> - collection.resolveInternalConnections()); - System.err.println("ex: "+ex.getMessage()); + collection.resolveInternalConnections()); + System.err.println("ex: " + ex.getMessage()); assertTrue(ex.getMessage().startsWith("Inheritance/reference cycle for documents: ")); } @Test - public void can_detect_cycles_with_reference() throws Exception { + void can_detect_cycles_with_reference() throws Exception { var collection = new IntermediateCollection(); collection.addSchemaFromString("schema foo { document foodoc inherits bardoc {} }"); collection.addSchemaFromString("schema bar { document bardoc { field myref type reference<qux> { } } }"); collection.addSchemaFromString("schema qux inherits foo { document qux inherits foodoc {} }"); assertEquals(collection.getParsedSchemas().size(), 3); var ex = assertThrows(IllegalArgumentException.class, () -> - collection.resolveInternalConnections()); - System.err.println("ex: "+ex.getMessage()); + collection.resolveInternalConnections()); + System.err.println("ex: " + ex.getMessage()); assertTrue(ex.getMessage().startsWith("Inheritance/reference cycle for documents: ")); } diff --git a/config-model/src/test/java/com/yahoo/schema/parser/ParsedDocumentTestCase.java b/config-model/src/test/java/com/yahoo/schema/parser/ParsedDocumentTestCase.java index 9245b64b09e..a594f9ae535 100644 --- a/config-model/src/test/java/com/yahoo/schema/parser/ParsedDocumentTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/parser/ParsedDocumentTestCase.java @@ -1,9 +1,10 @@ // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.schema.parser; -import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThrows; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; /** * @author arnej @@ -11,7 +12,7 @@ import static org.junit.Assert.assertThrows; public class ParsedDocumentTestCase { @Test - public void fields_can_be_added_once() throws Exception { + void fields_can_be_added_once() throws Exception { var doc = new ParsedDocument("foo"); var stringType = ParsedType.fromName("string"); doc.addField(new ParsedField("bar1", stringType)); @@ -19,11 +20,11 @@ public class ParsedDocumentTestCase { doc.addField(new ParsedField("bar2", stringType)); doc.addField(new ParsedField("bar3", stringType)); var e = assertThrows(IllegalArgumentException.class, () -> - doc.addField(new ParsedField("zap", stringType))); - System.err.println("As expected: "+e); + doc.addField(new ParsedField("zap", stringType))); + System.err.println("As expected: " + e); assertEquals("document 'foo' error: Duplicate (case insensitively) field 'zap' in document type 'foo'", e.getMessage()); e = assertThrows(IllegalArgumentException.class, () -> - doc.addField(new ParsedField("ZAP", stringType))); + doc.addField(new ParsedField("ZAP", stringType))); assertEquals("document 'foo' error: Duplicate (case insensitively) field 'ZAP' in document type 'foo'", e.getMessage()); } diff --git a/config-model/src/test/java/com/yahoo/schema/parser/SchemaParserTestCase.java b/config-model/src/test/java/com/yahoo/schema/parser/SchemaParserTestCase.java index 77d1b55019d..150c237bbba 100644 --- a/config-model/src/test/java/com/yahoo/schema/parser/SchemaParserTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/parser/SchemaParserTestCase.java @@ -8,12 +8,9 @@ import static com.yahoo.config.model.test.TestUtil.joinLines; import java.io.File; -import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertThrows; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; /** * @author arnej @@ -38,12 +35,12 @@ public class SchemaParserTestCase { } @Test - public void minimal_schema_can_be_parsed() throws Exception { + void minimal_schema_can_be_parsed() throws Exception { String input = joinLines - ("schema foo {", - " document foo {", - " }", - "}"); + ("schema foo {", + " document foo {", + " }", + "}"); ParsedSchema schema = parseString(input); assertEquals("foo", schema.name()); assertTrue(schema.hasDocument()); @@ -51,10 +48,10 @@ public class SchemaParserTestCase { } @Test - public void document_only_can_be_parsed() throws Exception { + void document_only_can_be_parsed() throws Exception { String input = joinLines - ("document bar {", - "}"); + ("document bar {", + "}"); ParsedSchema schema = parseString(input); assertEquals("bar", schema.name()); assertTrue(schema.hasDocument()); @@ -62,28 +59,28 @@ public class SchemaParserTestCase { } @Test - public void multiple_documents_disallowed() { + void multiple_documents_disallowed() { String input = joinLines ("schema foo {", - " document foo {", - " }", - " document foo2 {", - " }", - "}"); + " document foo {", + " }", + " document foo2 {", + " }", + "}"); var e = assertThrows(IllegalArgumentException.class, () -> parseString(input)); assertEquals("schema 'foo' error: already has document 'foo' so cannot add document 'foo2'", e.getMessage()); } @Test - public void backwards_path_is_disallowed() { + void backwards_path_is_disallowed() { assertEquals("'..' is not allowed in path", - assertThrows(IllegalArgumentException.class, - () -> parseString("schema foo {\n" + - " constant my_constant_tensor {\n" + - " file: foo/../bar\n" + - " type: tensor<float>(x{},y{})\n" + - " }\n" + - "}\n")).getMessage()); + assertThrows(IllegalArgumentException.class, + () -> parseString("schema foo {\n" + + " constant my_constant_tensor {\n" + + " file: foo/../bar\n" + + " type: tensor<float>(x{},y{})\n" + + " }\n" + + "}\n")).getMessage()); } void checkFileParses(String fileName) throws Exception { @@ -95,7 +92,7 @@ public class SchemaParserTestCase { // TODO: Many (all)? of the files below are parsed from other tests and can be removed from here @Test - public void parse_various_old_sdfiles() throws Exception { + void parse_various_old_sdfiles() throws Exception { checkFileParses("src/test/cfg/search/data/travel/schemas/TTData.sd"); checkFileParses("src/test/cfg/search/data/travel/schemas/TTEdge.sd"); checkFileParses("src/test/cfg/search/data/travel/schemas/TTPOI.sd"); diff --git a/config-model/src/test/java/com/yahoo/schema/processing/AddAttributeTransformToSummaryOfImportedFieldsTest.java b/config-model/src/test/java/com/yahoo/schema/processing/AddAttributeTransformToSummaryOfImportedFieldsTest.java index 0d64dd5c953..fe7edf5e433 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/AddAttributeTransformToSummaryOfImportedFieldsTest.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/AddAttributeTransformToSummaryOfImportedFieldsTest.java @@ -17,11 +17,11 @@ import com.yahoo.schema.document.SDField; import com.yahoo.vespa.documentmodel.DocumentSummary; import com.yahoo.vespa.documentmodel.SummaryField; import com.yahoo.vespa.documentmodel.SummaryTransform; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Collections; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author bjorncs @@ -33,7 +33,7 @@ public class AddAttributeTransformToSummaryOfImportedFieldsTest { private static final String SUMMARY_NAME = "mysummary"; @Test - public void attribute_summary_transform_applied_to_summary_field_of_imported_field() { + void attribute_summary_transform_applied_to_summary_field_of_imported_field() { Schema schema = createSearchWithDocument(DOCUMENT_NAME); schema.setImportedFields(createSingleImportedField(IMPORTED_FIELD_NAME)); schema.addSummary(createDocumentSummary(IMPORTED_FIELD_NAME, schema)); diff --git a/config-model/src/test/java/com/yahoo/schema/processing/AdjustPositionSummaryFieldsTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/AdjustPositionSummaryFieldsTestCase.java index 103d08b39a8..06d6e347f29 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/AdjustPositionSummaryFieldsTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/AdjustPositionSummaryFieldsTestCase.java @@ -7,19 +7,14 @@ import com.yahoo.schema.Schema; import com.yahoo.vespa.documentmodel.DocumentSummary; import com.yahoo.vespa.documentmodel.SummaryField; import com.yahoo.vespa.documentmodel.SummaryTransform; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.*; public class AdjustPositionSummaryFieldsTestCase { @Test - public void test_pos_summary() { + void test_pos_summary() { SearchModel model = new SearchModel(false); model.addSummaryField("my_pos", PositionDataType.INSTANCE, null, "pos"); model.resolve(); @@ -29,7 +24,7 @@ public class AdjustPositionSummaryFieldsTestCase { } @Test - public void test_imported_pos_summary() { + void test_imported_pos_summary() { SearchModel model = new SearchModel(); model.addSummaryField("my_pos", PositionDataType.INSTANCE, null, null); model.resolve(); @@ -39,7 +34,7 @@ public class AdjustPositionSummaryFieldsTestCase { } @Test - public void test_imported_pos_summary_bad_source() { + void test_imported_pos_summary_bad_source() { SearchModel model = new SearchModel(); model.addSummaryField("my_pos", PositionDataType.INSTANCE, null, "pos"); model.resolve(); @@ -50,7 +45,7 @@ public class AdjustPositionSummaryFieldsTestCase { } @Test - public void test_imported_pos_summary_bad_datatype() { + void test_imported_pos_summary_bad_datatype() { SearchModel model = new SearchModel(); model.addSummaryField("my_pos", DataType.getArray(PositionDataType.INSTANCE), null, "pos"); model.resolve(); @@ -60,7 +55,7 @@ public class AdjustPositionSummaryFieldsTestCase { } @Test - public void test_pos_summary_no_attr_no_rename() { + void test_pos_summary_no_attr_no_rename() { SearchModel model = new SearchModel(false, false, false); model.addSummaryField("pos", PositionDataType.INSTANCE, null, "pos"); model.resolve(); @@ -70,14 +65,14 @@ public class AdjustPositionSummaryFieldsTestCase { } @Test - public void test_pos_default_summary_no_attr_no_rename() { + void test_pos_default_summary_no_attr_no_rename() { SearchModel model = new SearchModel(false, false, false); model.resolve(); assertNull(model.childSchema.getSummary("default")); // ImplicitSummaries processing not run in this test } @Test - public void test_pos_summary_no_rename() { + void test_pos_summary_no_rename() { SearchModel model = new SearchModel(false, true, false); model.addSummaryField("pos", PositionDataType.INSTANCE, null, "pos"); model.resolve(); @@ -86,79 +81,82 @@ public class AdjustPositionSummaryFieldsTestCase { model.assertSummaryField("pos.distance", DataType.INT, SummaryTransform.DISTANCE, "pos_zcurve"); } - @SuppressWarnings("deprecation") - @Rule - public final ExpectedException exceptionRule = ExpectedException.none(); - @Test - public void test_pos_summary_no_attr() { - exceptionRule.expect(IllegalArgumentException.class); - exceptionRule.expectMessage("For schema 'child', field 'my_pos': No position attribute 'pos_zcurve'"); - SearchModel model = new SearchModel(false, false, false); - model.addSummaryField("my_pos", PositionDataType.INSTANCE, null, "pos"); - model.resolve(); + void test_pos_summary_no_attr() { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + SearchModel model = new SearchModel(false, false, false); + model.addSummaryField("my_pos", PositionDataType.INSTANCE, null, "pos"); + model.resolve(); + }); + assertTrue(exception.getMessage().contains("For schema 'child', field 'my_pos': No position attribute 'pos_zcurve'")); } @Test - public void test_pos_summary_bad_attr() { - exceptionRule.expect(IllegalArgumentException.class); - exceptionRule.expectMessage("For schema 'child', field 'my_pos': No position attribute 'pos_zcurve'"); - SearchModel model = new SearchModel(false, false, true); - model.addSummaryField("my_pos", PositionDataType.INSTANCE, null, "pos"); - model.resolve(); + void test_pos_summary_bad_attr() { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + SearchModel model = new SearchModel(false, false, true); + model.addSummaryField("my_pos", PositionDataType.INSTANCE, null, "pos"); + model.resolve(); + }); + assertTrue(exception.getMessage().contains("For schema 'child', field 'my_pos': No position attribute 'pos_zcurve'")); } @Test - public void test_imported_pos_summary_no_attr() { - exceptionRule.expect(IllegalArgumentException.class); - exceptionRule.expectMessage("For schema 'child', import field 'my_pos_zcurve': " - + "Field 'pos_zcurve' via reference field 'ref': Not found"); - SearchModel model = new SearchModel(true, false, false); - model.addSummaryField("my_pos", PositionDataType.INSTANCE, null, null); - model.resolve(); + void test_imported_pos_summary_no_attr() { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + SearchModel model = new SearchModel(true, false, false); + model.addSummaryField("my_pos", PositionDataType.INSTANCE, null, null); + model.resolve(); + }); + assertTrue(exception.getMessage().contains("For schema 'child', import field 'my_pos_zcurve': " + + "Field 'pos_zcurve' via reference field 'ref': Not found")); } @Test - public void test_imported_pos_summary_bad_attr() { - exceptionRule.expect(IllegalArgumentException.class); - exceptionRule.expectMessage("For schema 'child', field 'my_pos': " - + "No position attribute 'my_pos_zcurve'"); - SearchModel model = new SearchModel(true, false, true); - model.addSummaryField("my_pos", PositionDataType.INSTANCE, null, null); - model.resolve(); + void test_imported_pos_summary_bad_attr() { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + SearchModel model = new SearchModel(true, false, true); + model.addSummaryField("my_pos", PositionDataType.INSTANCE, null, null); + model.resolve(); + }); + assertTrue(exception.getMessage().contains("For schema 'child', field 'my_pos': " + + "No position attribute 'my_pos_zcurve'")); } @Test - public void test_my_pos_position_summary_bad_datatype() { - exceptionRule.expect(IllegalArgumentException.class); - exceptionRule.expectMessage("For schema 'child', field 'my_pos.position': " - + "exists with type 'datatype string (code: 2)', should be of type 'datatype Array<string> (code: -1486737430)"); - SearchModel model = new SearchModel(); - model.addSummaryField("my_pos", PositionDataType.INSTANCE, null, null); - model.addSummaryField("my_pos.position", DataType.STRING, null, "pos"); - model.resolve(); + void test_my_pos_position_summary_bad_datatype() { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + SearchModel model = new SearchModel(); + model.addSummaryField("my_pos", PositionDataType.INSTANCE, null, null); + model.addSummaryField("my_pos.position", DataType.STRING, null, "pos"); + model.resolve(); + }); + assertTrue(exception.getMessage().contains("For schema 'child', field 'my_pos.position': " + + "exists with type 'datatype string (code: 2)', should be of type 'datatype Array<string> (code: -1486737430)")); } @Test - public void test_my_pos_position_summary_bad_transform() { - exceptionRule.expect(IllegalArgumentException.class); - exceptionRule.expectMessage("For schema 'child', field 'my_pos.position': " - + "has summary transform 'none', should have transform 'positions'"); - SearchModel model = new SearchModel(); - model.addSummaryField("my_pos", PositionDataType.INSTANCE, null, null); - model.addSummaryField("my_pos.position", DataType.getArray(DataType.STRING), null, "pos"); - model.resolve(); + void test_my_pos_position_summary_bad_transform() { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + SearchModel model = new SearchModel(); + model.addSummaryField("my_pos", PositionDataType.INSTANCE, null, null); + model.addSummaryField("my_pos.position", DataType.getArray(DataType.STRING), null, "pos"); + model.resolve(); + }); + assertTrue(exception.getMessage().contains("For schema 'child', field 'my_pos.position': " + + "has summary transform 'none', should have transform 'positions'")); } @Test - public void test_my_pos_position_summary_bad_source() { - exceptionRule.expect(IllegalArgumentException.class); - exceptionRule.expectMessage("For schema 'child', field 'my_pos.position': " - + "has source '[source field 'pos']', should have source 'source field 'my_pos_zcurve''"); - SearchModel model = new SearchModel(); - model.addSummaryField("my_pos", PositionDataType.INSTANCE, null, null); - model.addSummaryField("my_pos.position", DataType.getArray(DataType.STRING), SummaryTransform.POSITIONS, "pos"); - model.resolve(); + void test_my_pos_position_summary_bad_source() { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + SearchModel model = new SearchModel(); + model.addSummaryField("my_pos", PositionDataType.INSTANCE, null, null); + model.addSummaryField("my_pos.position", DataType.getArray(DataType.STRING), SummaryTransform.POSITIONS, "pos"); + model.resolve(); + }); + assertTrue(exception.getMessage().contains("For schema 'child', field 'my_pos.position': " + + "has source '[source field 'pos']', should have source 'source field 'my_pos_zcurve''")); } static class SearchModel extends ParentChildSearchModel { diff --git a/config-model/src/test/java/com/yahoo/schema/processing/AssertIndexingScript.java b/config-model/src/test/java/com/yahoo/schema/processing/AssertIndexingScript.java index 82650598f29..f9c1e992347 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/AssertIndexingScript.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/AssertIndexingScript.java @@ -9,8 +9,8 @@ import com.yahoo.vespa.indexinglanguage.parser.ParseException; import java.util.LinkedList; import java.util.List; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Simon Thoresen Hult @@ -36,8 +36,8 @@ public abstract class AssertIndexingScript { } for (Expression actualExp : actual) { String str = actualExp.toString(); - assertTrue("Unexpected: " + str, parsedExpected.remove(str)); + assertTrue(parsedExpected.remove(str), "Unexpected: " + str); } - assertTrue("Missing: " + parsedExpected.toString(), parsedExpected.isEmpty()); + assertTrue(parsedExpected.isEmpty(), "Missing: " + parsedExpected.toString()); } } diff --git a/config-model/src/test/java/com/yahoo/schema/processing/AssertSearchBuilder.java b/config-model/src/test/java/com/yahoo/schema/processing/AssertSearchBuilder.java index 0b4d7c3a2b6..12da3f0797b 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/AssertSearchBuilder.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/AssertSearchBuilder.java @@ -6,7 +6,7 @@ import com.yahoo.schema.parser.ParseException; import java.io.IOException; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; /** * @author Simon Thoresen Hult diff --git a/config-model/src/test/java/com/yahoo/schema/processing/AttributesExactMatchTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/AttributesExactMatchTestCase.java index 40ebe458c74..a01aa11264b 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/AttributesExactMatchTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/AttributesExactMatchTestCase.java @@ -6,12 +6,13 @@ import com.yahoo.schema.ApplicationBuilder; import com.yahoo.schema.AbstractSchemaTestCase; import com.yahoo.schema.document.MatchType; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + /** * Attributes should be implicitly exact-match in some cases * @author vegardh @@ -19,7 +20,7 @@ import static org.junit.Assert.assertFalse; */ public class AttributesExactMatchTestCase extends AbstractSchemaTestCase { @Test - public void testAttributesExactMatch() throws IOException, ParseException { + void testAttributesExactMatch() throws IOException, ParseException { Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/attributesexactmatch.sd"); assertEquals(schema.getConcreteField("color").getMatching().getType(), MatchType.EXACT); assertEquals(schema.getConcreteField("artist").getMatching().getType(), MatchType.WORD); @@ -28,12 +29,12 @@ public class AttributesExactMatchTestCase extends AbstractSchemaTestCase { assertEquals(schema.getConcreteField("saxophonist_arr").getMatching().getType(), MatchType.WORD); assertEquals(schema.getConcreteField("flutist").getMatching().getType(), MatchType.TEXT); - assertFalse(schema.getConcreteField("genre").getMatching().getType().equals(MatchType.EXACT)); - assertFalse(schema.getConcreteField("title").getMatching().getType().equals(MatchType.EXACT)); - assertFalse(schema.getConcreteField("trumpetist").getMatching().getType().equals(MatchType.EXACT)); - assertFalse(schema.getConcreteField("genre").getMatching().getType().equals(MatchType.WORD)); - assertFalse(schema.getConcreteField("title").getMatching().getType().equals(MatchType.WORD)); - assertFalse(schema.getConcreteField("trumpetist").getMatching().getType().equals(MatchType.WORD)); + assertNotEquals(schema.getConcreteField("genre").getMatching().getType(), MatchType.EXACT); + assertNotEquals(schema.getConcreteField("title").getMatching().getType(), MatchType.EXACT); + assertNotEquals(schema.getConcreteField("trumpetist").getMatching().getType(), MatchType.EXACT); + assertNotEquals(schema.getConcreteField("genre").getMatching().getType(), MatchType.WORD); + assertNotEquals(schema.getConcreteField("title").getMatching().getType(), MatchType.WORD); + assertNotEquals(schema.getConcreteField("trumpetist").getMatching().getType(), MatchType.WORD); } diff --git a/config-model/src/test/java/com/yahoo/schema/processing/BoldingTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/BoldingTestCase.java index c37bc8085c7..fe38ea1f1b1 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/BoldingTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/BoldingTestCase.java @@ -4,10 +4,10 @@ package com.yahoo.schema.processing; import com.yahoo.schema.ApplicationBuilder; import com.yahoo.schema.AbstractSchemaTestCase; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author bratseth @@ -29,13 +29,13 @@ public class BoldingTestCase extends AbstractSchemaTestCase { "}\n"; @Test - public void testBoldOnNonString() throws ParseException { + void testBoldOnNonString() throws ParseException { try { ApplicationBuilder.createFromString(boldonnonstring); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("'bolding: on' for non-text field 'year4' (datatype int (code: 0)) is not allowed", - e.getMessage()); + e.getMessage()); } } @@ -50,13 +50,13 @@ public class BoldingTestCase extends AbstractSchemaTestCase { "}\n"; @Test - public void testBoldOnArray() throws ParseException { + void testBoldOnArray() throws ParseException { try { ApplicationBuilder.createFromString(boldonarray); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("'bolding: on' for non-text field 'myarray' (datatype Array<string> (code: -1486737430)) is not allowed", - e.getMessage()); + e.getMessage()); } } diff --git a/config-model/src/test/java/com/yahoo/schema/processing/BoolAttributeValidatorTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/BoolAttributeValidatorTestCase.java index 287cc6559d1..f19b1f43115 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/BoolAttributeValidatorTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/BoolAttributeValidatorTestCase.java @@ -2,12 +2,12 @@ package com.yahoo.schema.processing; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static com.yahoo.schema.ApplicationBuilder.createFromString; +import static org.junit.jupiter.api.Assertions.assertEquals; import static com.yahoo.config.model.test.TestUtil.joinLines; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * @author geirst @@ -15,19 +15,19 @@ import static org.junit.Assert.fail; public class BoolAttributeValidatorTestCase { @Test - public void array_of_bool_attribute_is_not_supported() throws ParseException { + void array_of_bool_attribute_is_not_supported() throws ParseException { try { createFromString(getSd("field b type array<bool> { indexing: attribute }")); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("For schema 'test', field 'b': Only single value bool attribute fields are supported", - e.getMessage()); + e.getMessage()); } } @Test - public void weigtedset_of_bool_attribute_is_not_supported() throws ParseException { + void weigtedset_of_bool_attribute_is_not_supported() throws ParseException { try { createFromString(getSd("field b type weightedset<bool> { indexing: attribute }")); fail("Expected exception"); diff --git a/config-model/src/test/java/com/yahoo/schema/processing/DictionaryTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/DictionaryTestCase.java index 45a546259ae..ef1716c80e6 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/DictionaryTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/DictionaryTestCase.java @@ -11,11 +11,9 @@ import com.yahoo.schema.document.Dictionary; import com.yahoo.schema.document.ImmutableSDField; import com.yahoo.schema.parser.ParseException; import com.yahoo.vespa.config.search.AttributesConfig; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; /** * Test configuration of dictionary control. @@ -33,19 +31,20 @@ public class DictionaryTestCase { ApplicationBuilder sb = ApplicationBuilder.createFromString(def); return sb.getSchema(); } + @Test - public void testDefaultDictionarySettings() throws ParseException { + void testDefaultDictionarySettings() throws ParseException { String def = TestUtil.joinLines( - "search test {", - " document test {", - " field s1 type string {", - " indexing: attribute | summary", - " }", - " field n1 type int {", - " indexing: summary | attribute", - " }", - " }", - "}"); + "search test {", + " document test {", + " field s1 type string {", + " indexing: attribute | summary", + " }", + " field n1 type int {", + " indexing: summary | attribute", + " }", + " }", + "}"); Schema schema = createSearch(def); assertNull(schema.getAttribute("s1").getDictionary()); assertNull(schema.getAttribute("n1").getDictionary()); @@ -103,64 +102,75 @@ public class DictionaryTestCase { } @Test - public void testCasedBtreeSettings() throws ParseException { + void testCasedBtreeSettings() throws ParseException { verifyDictionaryControl(Dictionary.Type.BTREE, "int", "dictionary:cased"); } @Test - public void testNumericBtreeSettings() throws ParseException { + void testNumericBtreeSettings() throws ParseException { verifyDictionaryControl(Dictionary.Type.BTREE, "int", "dictionary:btree"); } + @Test - public void testNumericHashSettings() throws ParseException { + void testNumericHashSettings() throws ParseException { verifyDictionaryControl(Dictionary.Type.HASH, "int", "dictionary:hash"); } + @Test - public void testNumericBtreeAndHashSettings() throws ParseException { + void testNumericBtreeAndHashSettings() throws ParseException { verifyDictionaryControl(Dictionary.Type.BTREE_AND_HASH, "int", "dictionary:btree", "dictionary:hash"); } + @Test - public void testNumericArrayBtreeAndHashSettings() throws ParseException { + void testNumericArrayBtreeAndHashSettings() throws ParseException { verifyDictionaryControl(Dictionary.Type.BTREE_AND_HASH, "array<int>", "dictionary:btree", "dictionary:hash"); } + @Test - public void testNumericWSetBtreeAndHashSettings() throws ParseException { + void testNumericWSetBtreeAndHashSettings() throws ParseException { verifyDictionaryControl(Dictionary.Type.BTREE_AND_HASH, "weightedset<int>", "dictionary:btree", "dictionary:hash"); } + @Test - public void testStringBtreeSettings() throws ParseException { + void testStringBtreeSettings() throws ParseException { verifyStringDictionaryControl(Dictionary.Type.BTREE, Case.UNCASED, Case.UNCASED, "dictionary:btree"); } + @Test - public void testStringBtreeUnCasedSettings() throws ParseException { + void testStringBtreeUnCasedSettings() throws ParseException { verifyStringDictionaryControl(Dictionary.Type.BTREE, Case.UNCASED, Case.UNCASED, "dictionary { btree\nuncased\n}"); } + @Test - public void testStringBtreeCasedSettings() throws ParseException { + void testStringBtreeCasedSettings() throws ParseException { verifyStringDictionaryControl(Dictionary.Type.BTREE, Case.CASED, Case.CASED, "dictionary { btree\ncased\n}", "match:cased"); } + @Test - public void testStringHashSettings() throws ParseException { + void testStringHashSettings() throws ParseException { try { verifyStringDictionaryControl(Dictionary.Type.HASH, Case.UNCASED, Case.UNCASED, "dictionary:hash"); } catch (IllegalArgumentException e) { assertEquals("For schema 'test', field 'n1': hash dictionary require cased match", e.getMessage()); } } + @Test - public void testStringHashUnCasedSettings() throws ParseException { + void testStringHashUnCasedSettings() throws ParseException { try { verifyStringDictionaryControl(Dictionary.Type.HASH, Case.UNCASED, Case.UNCASED, "dictionary { hash\nuncased\n}"); } catch (IllegalArgumentException e) { assertEquals("For schema 'test', field 'n1': hash dictionary require cased match", e.getMessage()); } } + @Test - public void testStringHashBothCasedSettings() throws ParseException { + void testStringHashBothCasedSettings() throws ParseException { verifyStringDictionaryControl(Dictionary.Type.HASH, Case.CASED, Case.CASED, "dictionary { hash\ncased\n}", "match:cased"); } + @Test - public void testStringHashCasedSettings() throws ParseException { + void testStringHashCasedSettings() throws ParseException { try { verifyStringDictionaryControl(Dictionary.Type.HASH, Case.CASED, Case.CASED, "dictionary { hash\ncased\n}"); fail(); @@ -168,24 +178,28 @@ public class DictionaryTestCase { assertEquals("For schema 'test', field 'n1': Dictionary casing 'CASED' does not match field match casing 'UNCASED'", e.getMessage()); } } + @Test - public void testStringBtreeHashSettings() throws ParseException { + void testStringBtreeHashSettings() throws ParseException { verifyStringDictionaryControl(Dictionary.Type.BTREE_AND_HASH, Case.UNCASED, Case.UNCASED, "dictionary{hash\nbtree\n}"); } + @Test - public void testStringBtreeHashUnCasedSettings() throws ParseException { + void testStringBtreeHashUnCasedSettings() throws ParseException { verifyStringDictionaryControl(Dictionary.Type.BTREE_AND_HASH, Case.UNCASED, Case.UNCASED, "dictionary { hash\nbtree\nuncased\n}"); } + @Test - public void testStringBtreeHashCasedSettings() throws ParseException { + void testStringBtreeHashCasedSettings() throws ParseException { try { verifyStringDictionaryControl(Dictionary.Type.BTREE_AND_HASH, Case.CASED, Case.CASED, "dictionary { btree\nhash\ncased\n}"); } catch (IllegalArgumentException e) { assertEquals("For schema 'test', field 'n1': Dictionary casing 'CASED' does not match field match casing 'UNCASED'", e.getMessage()); } } + @Test - public void testNonNumericFieldsFailsDictionaryControl() throws ParseException { + void testNonNumericFieldsFailsDictionaryControl() throws ParseException { String def = TestUtil.joinLines( "schema test {", " document test {", @@ -202,8 +216,9 @@ public class DictionaryTestCase { assertEquals("For schema 'test', field 'n1': You can only specify 'dictionary:' for numeric or string fields", e.getMessage()); } } + @Test - public void testNonFastSearchNumericFieldsFailsDictionaryControl() throws ParseException { + void testNonFastSearchNumericFieldsFailsDictionaryControl() throws ParseException { String def = TestUtil.joinLines( "schema test {", " document test {", @@ -222,7 +237,7 @@ public class DictionaryTestCase { } @Test - public void testCasingForNonFastSearch() throws ParseException { + void testCasingForNonFastSearch() throws ParseException { String def = TestUtil.joinLines( "schema test {", " document test {", diff --git a/config-model/src/test/java/com/yahoo/schema/processing/DisallowComplexMapAndWsetKeyTypesTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/DisallowComplexMapAndWsetKeyTypesTestCase.java index 64b0a437b1d..4efd20a06f1 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/DisallowComplexMapAndWsetKeyTypesTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/DisallowComplexMapAndWsetKeyTypesTestCase.java @@ -4,41 +4,53 @@ package com.yahoo.schema.processing; import com.yahoo.schema.RankProfileRegistry; import com.yahoo.schema.ApplicationBuilder; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertThrows; /** * @author lesters */ public class DisallowComplexMapAndWsetKeyTypesTestCase { - @Test(expected = IllegalArgumentException.class) - public void requireThatComplexTypesForMapKeysFail() throws ParseException { - testFieldType("map<mystruct,string>"); + @Test + void requireThatComplexTypesForMapKeysFail() throws ParseException { + assertThrows(IllegalArgumentException.class, () -> { + testFieldType("map<mystruct,string>"); + }); } - @Test(expected = IllegalArgumentException.class) - public void requireThatComplexTypesForWsetFail() throws ParseException { - testFieldType("weightedset<mystruct>"); + @Test + void requireThatComplexTypesForWsetFail() throws ParseException { + assertThrows(IllegalArgumentException.class, () -> { + testFieldType("weightedset<mystruct>"); + }); } - @Test(expected = IllegalArgumentException.class) - public void requireThatNestedComplexTypesForMapFail() throws ParseException { - testFieldType("array<map<mystruct,string>>"); + @Test + void requireThatNestedComplexTypesForMapFail() throws ParseException { + assertThrows(IllegalArgumentException.class, () -> { + testFieldType("array<map<mystruct,string>>"); + }); } @Test - public void requireThatNestedComplexValuesForMapSucceed() throws ParseException { + void requireThatNestedComplexValuesForMapSucceed() throws ParseException { testFieldType("array<map<string,mystruct>>"); } - @Test(expected = IllegalArgumentException.class) - public void requireThatNestedComplexTypesForWsetFail() throws ParseException { - testFieldType("array<weightedset<mystruct>>"); + @Test + void requireThatNestedComplexTypesForWsetFail() throws ParseException { + assertThrows(IllegalArgumentException.class, () -> { + testFieldType("array<weightedset<mystruct>>"); + }); } - @Test(expected = IllegalArgumentException.class) - public void requireThatDeepNestedComplexTypesForMapFail() throws ParseException { - testFieldType("map<string,map<mystruct,string>>"); + @Test + void requireThatDeepNestedComplexTypesForMapFail() throws ParseException { + assertThrows(IllegalArgumentException.class, () -> { + testFieldType("map<string,map<mystruct,string>>"); + }); } private void testFieldType(String fieldType) throws ParseException { diff --git a/config-model/src/test/java/com/yahoo/schema/processing/FastAccessValidatorTest.java b/config-model/src/test/java/com/yahoo/schema/processing/FastAccessValidatorTest.java index b249b407c7b..ebf79a4a7d5 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/FastAccessValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/FastAccessValidatorTest.java @@ -5,57 +5,54 @@ import com.yahoo.config.model.test.TestUtil; import com.yahoo.schema.RankProfileRegistry; import com.yahoo.schema.ApplicationBuilder; import com.yahoo.schema.parser.ParseException; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author bjorncs */ public class FastAccessValidatorTest { - @SuppressWarnings("deprecation") - @Rule - public final ExpectedException exceptionRule = ExpectedException.none(); - @Test - public void throws_exception_on_incompatible_use_of_fastaccess() throws ParseException { - ApplicationBuilder builder = new ApplicationBuilder(new RankProfileRegistry()); - builder.addSchema( - TestUtil.joinLines( - "schema parent {", - " document parent {", - " field int_field type int { indexing: attribute }", - " }", - "}")); - builder.addSchema( - TestUtil.joinLines( - "schema test {", - " document test { ", - " field int_attribute type int { ", - " indexing: attribute ", - " attribute: fast-access", - " }", - " field predicate_attribute type predicate {", - " indexing: attribute ", - " attribute: fast-access", - " }", - " field tensor_attribute type tensor(x[5]) {", - " indexing: attribute ", - " attribute: fast-access", - " }", - " field reference_attribute type reference<parent> {", - " indexing: attribute ", - " attribute: fast-access", - " }", - " }", - "}")); - exceptionRule.expect(IllegalArgumentException.class); - exceptionRule.expectMessage( - "For schema 'test': The following attributes have a type that is incompatible " + - "with fast-access: predicate_attribute, tensor_attribute, reference_attribute. " + - "Predicate, tensor and reference attributes are incompatible with fast-access."); - builder.build(true); + void throws_exception_on_incompatible_use_of_fastaccess() throws ParseException { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + ApplicationBuilder builder = new ApplicationBuilder(new RankProfileRegistry()); + builder.addSchema( + TestUtil.joinLines( + "schema parent {", + " document parent {", + " field int_field type int { indexing: attribute }", + " }", + "}")); + builder.addSchema( + TestUtil.joinLines( + "schema test {", + " document test { ", + " field int_attribute type int { ", + " indexing: attribute ", + " attribute: fast-access", + " }", + " field predicate_attribute type predicate {", + " indexing: attribute ", + " attribute: fast-access", + " }", + " field tensor_attribute type tensor(x[5]) {", + " indexing: attribute ", + " attribute: fast-access", + " }", + " field reference_attribute type reference<parent> {", + " indexing: attribute ", + " attribute: fast-access", + " }", + " }", + "}")); + builder.build(true); + }); + assertTrue(exception.getMessage().contains("For schema 'test': The following attributes have a type that is incompatible " + + "with fast-access: predicate_attribute, tensor_attribute, reference_attribute. " + + "Predicate, tensor and reference attributes are incompatible with fast-access.")); } } diff --git a/config-model/src/test/java/com/yahoo/schema/processing/ImplicitSchemaFieldsTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/ImplicitSchemaFieldsTestCase.java index 594124c9500..c758d49f79f 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/ImplicitSchemaFieldsTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/ImplicitSchemaFieldsTestCase.java @@ -7,17 +7,17 @@ import com.yahoo.schema.AbstractSchemaTestCase; import com.yahoo.schema.derived.DerivedConfiguration; import com.yahoo.schema.document.SDDocumentType; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; public class ImplicitSchemaFieldsTestCase extends AbstractSchemaTestCase { @Test - public void testRequireThatExtraFieldsAreIncluded() throws IOException, ParseException { + void testRequireThatExtraFieldsAreIncluded() throws IOException, ParseException { Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/nextgen/extrafield.sd"); assertNotNull(schema); @@ -29,7 +29,7 @@ public class ImplicitSchemaFieldsTestCase extends AbstractSchemaTestCase { } @Test - public void testRequireThatSummaryFieldsAreIncluded() throws IOException, ParseException { + void testRequireThatSummaryFieldsAreIncluded() throws IOException, ParseException { Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/nextgen/summaryfield.sd"); assertNotNull(schema); @@ -44,7 +44,7 @@ public class ImplicitSchemaFieldsTestCase extends AbstractSchemaTestCase { } @Test - public void testRequireThatBoldedSummaryFieldsAreIncluded() throws IOException, ParseException { + void testRequireThatBoldedSummaryFieldsAreIncluded() throws IOException, ParseException { Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/nextgen/boldedsummaryfields.sd"); assertNotNull(schema); @@ -58,7 +58,7 @@ public class ImplicitSchemaFieldsTestCase extends AbstractSchemaTestCase { } @Test - public void testRequireThatUntransformedSummaryFieldsAreIgnored() throws IOException, ParseException { + void testRequireThatUntransformedSummaryFieldsAreIgnored() throws IOException, ParseException { Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/nextgen/untransformedsummaryfields.sd"); assertNotNull(schema); @@ -71,7 +71,7 @@ public class ImplicitSchemaFieldsTestCase extends AbstractSchemaTestCase { } @Test - public void testRequireThatDynamicSummaryFieldsAreIgnored() throws IOException, ParseException { + void testRequireThatDynamicSummaryFieldsAreIgnored() throws IOException, ParseException { Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/nextgen/dynamicsummaryfields.sd"); assertNotNull(schema); @@ -83,7 +83,7 @@ public class ImplicitSchemaFieldsTestCase extends AbstractSchemaTestCase { } @Test - public void testRequireThatDerivedConfigurationWorks() throws IOException, ParseException { + void testRequireThatDerivedConfigurationWorks() throws IOException, ParseException { ApplicationBuilder sb = new ApplicationBuilder(); sb.addSchemaFile("src/test/examples/nextgen/simple.sd"); sb.build(true); diff --git a/config-model/src/test/java/com/yahoo/schema/processing/ImplicitStructTypesTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/ImplicitStructTypesTestCase.java index 111ed266d74..243ec0243c8 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/ImplicitStructTypesTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/ImplicitStructTypesTestCase.java @@ -8,14 +8,15 @@ import com.yahoo.schema.AbstractSchemaTestCase; import com.yahoo.schema.document.SDDocumentType; import com.yahoo.schema.document.SDField; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; + public class ImplicitStructTypesTestCase extends AbstractSchemaTestCase { @Test - public void testRequireThatImplicitStructsAreCreated() throws IOException, ParseException { + void testRequireThatImplicitStructsAreCreated() throws IOException, ParseException { Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/nextgen/toggleon.sd"); assertNotNull(schema); @@ -23,8 +24,9 @@ public class ImplicitStructTypesTestCase extends AbstractSchemaTestCase { assertNotNull(docType); assertStruct(docType, PositionDataType.INSTANCE); } + @Test - public void testRequireThatImplicitStructsAreUsed() throws IOException, ParseException { + void testRequireThatImplicitStructsAreUsed() throws IOException, ParseException { Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/nextgen/implicitstructtypes.sd"); assertNotNull(schema); diff --git a/config-model/src/test/java/com/yahoo/schema/processing/ImplicitSummariesTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/ImplicitSummariesTestCase.java index 50deb5d5b42..37bc064c19e 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/ImplicitSummariesTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/ImplicitSummariesTestCase.java @@ -5,7 +5,7 @@ import com.yahoo.schema.Schema; import com.yahoo.schema.ApplicationBuilder; import com.yahoo.schema.parser.ParseException; import com.yahoo.vespa.documentmodel.SummaryTransform; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.ArrayList; @@ -15,9 +15,7 @@ import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * @author Simon Thoresen Hult @@ -25,7 +23,7 @@ import static org.junit.Assert.assertTrue; public class ImplicitSummariesTestCase { @Test - public void requireThatSummaryFromAttributeDoesNotWarn() throws IOException, ParseException { + void requireThatSummaryFromAttributeDoesNotWarn() throws IOException, ParseException { LogHandler log = new LogHandler(); Logger.getLogger("").addHandler(log); @@ -59,19 +57,19 @@ public class ImplicitSummariesTestCase { } @Test - public void attribute_combiner_transform_is_set_on_array_of_struct_with_only_struct_field_attributes() throws IOException, ParseException { + void attribute_combiner_transform_is_set_on_array_of_struct_with_only_struct_field_attributes() throws IOException, ParseException { Schema schema = ApplicationBuilder.buildFromFile("src/test/derived/array_of_struct_attribute/test.sd"); assertEquals(SummaryTransform.ATTRIBUTECOMBINER, schema.getSummaryField("elem_array").getTransform()); } @Test - public void attribute_combiner_transform_is_set_on_map_of_struct_with_only_struct_field_attributes() throws IOException, ParseException { + void attribute_combiner_transform_is_set_on_map_of_struct_with_only_struct_field_attributes() throws IOException, ParseException { Schema schema = ApplicationBuilder.buildFromFile("src/test/derived/map_of_struct_attribute/test.sd"); assertEquals(SummaryTransform.ATTRIBUTECOMBINER, schema.getSummaryField("str_elem_map").getTransform()); } @Test - public void attribute_combiner_transform_is_not_set_when_map_of_struct_has_some_struct_field_attributes() throws IOException, ParseException { + void attribute_combiner_transform_is_not_set_when_map_of_struct_has_some_struct_field_attributes() throws IOException, ParseException { Schema schema = ApplicationBuilder.buildFromFile("src/test/derived/map_of_struct_attribute/test.sd"); assertEquals(SummaryTransform.NONE, schema.getSummaryField("int_elem_map").getTransform()); } diff --git a/config-model/src/test/java/com/yahoo/schema/processing/ImplicitSummaryFieldsTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/ImplicitSummaryFieldsTestCase.java index f32c9079d36..bc7513b4662 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/ImplicitSummaryFieldsTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/ImplicitSummaryFieldsTestCase.java @@ -6,17 +6,17 @@ import com.yahoo.schema.ApplicationBuilder; import com.yahoo.schema.AbstractSchemaTestCase; import com.yahoo.schema.parser.ParseException; import com.yahoo.vespa.documentmodel.DocumentSummary; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; public class ImplicitSummaryFieldsTestCase extends AbstractSchemaTestCase { @Test - public void testRequireThatImplicitFieldsAreCreated() throws IOException, ParseException { + void testRequireThatImplicitFieldsAreCreated() throws IOException, ParseException { Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/implicitsummaryfields.sd"); assertNotNull(schema); diff --git a/config-model/src/test/java/com/yahoo/schema/processing/ImportedFieldsResolverTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/ImportedFieldsResolverTestCase.java index 5baa64d06d4..853cb1d1a79 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/ImportedFieldsResolverTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/ImportedFieldsResolverTestCase.java @@ -11,24 +11,15 @@ import com.yahoo.schema.document.ImportedFields; import com.yahoo.schema.document.SDField; import com.yahoo.schema.document.TemporarySDField; import com.yahoo.tensor.TensorType; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertSame; +import static org.junit.jupiter.api.Assertions.*; /** * @author geirst */ public class ImportedFieldsResolverTestCase { - @SuppressWarnings("deprecation") - @Rule - public final ExpectedException exceptionRule = ExpectedException.none(); - private void resolve_imported_field(String fieldName, String targetFieldName) { SearchModel model = new SearchModel(); model.addImportedField(fieldName, "ref", targetFieldName).resolve(); @@ -52,54 +43,57 @@ public class ImportedFieldsResolverTestCase { } @Test - public void valid_imported_fields_are_resolved() { + void valid_imported_fields_are_resolved() { resolve_imported_field("my_attribute_field", "attribute_field"); resolve_imported_field("my_tensor_field", "tensor_field"); resolve_imported_field("my_ancient_field", "ancient_field"); } @Test - public void resolver_fails_if_document_reference_is_not_found() { - exceptionRule.expect(IllegalArgumentException.class); - exceptionRule.expectMessage("For schema 'child', import field 'my_attribute_field': " - + "Reference field 'not_ref' not found"); - new SearchModel().addImportedField("my_attribute_field", "not_ref", "budget").resolve(); + void resolver_fails_if_document_reference_is_not_found() { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + new SearchModel().addImportedField("my_attribute_field", "not_ref", "budget").resolve(); + }); + assertTrue(exception.getMessage().contains("For schema 'child', import field 'my_attribute_field': " + + "Reference field 'not_ref' not found")); } @Test - public void resolver_fails_if_referenced_field_is_not_found() { - exceptionRule.expect(IllegalArgumentException.class); - exceptionRule.expectMessage("For schema 'child', import field 'my_attribute_field': " - + "Field 'not_existing' via reference field 'ref': Not found"); - new SearchModel().addImportedField("my_attribute_field", "ref", "not_existing").resolve(); + void resolver_fails_if_referenced_field_is_not_found() { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + new SearchModel().addImportedField("my_attribute_field", "ref", "not_existing").resolve(); + }); + assertTrue(exception.getMessage().contains("For schema 'child', import field 'my_attribute_field': " + + "Field 'not_existing' via reference field 'ref': Not found")); } @Test - public void resolver_fails_if_imported_field_is_not_an_attribute() { - exceptionRule.expect(IllegalArgumentException.class); - exceptionRule.expectMessage("For schema 'child', import field 'my_not_attribute': " - + "Field 'not_attribute' via reference field 'ref': Is not an attribute field. Only attribute fields supported"); - new SearchModel().addImportedField("my_not_attribute", "ref", "not_attribute").resolve(); + void resolver_fails_if_imported_field_is_not_an_attribute() { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + new SearchModel().addImportedField("my_not_attribute", "ref", "not_attribute").resolve(); + }); + assertTrue(exception.getMessage().contains("For schema 'child', import field 'my_not_attribute': " + + "Field 'not_attribute' via reference field 'ref': Is not an attribute field. Only attribute fields supported")); } @Test - public void resolver_fails_if_imported_field_is_indexing() { - exceptionRule.expect(IllegalArgumentException.class); - exceptionRule.expectMessage( - "For schema 'child', import field 'my_attribute_and_index': " + - "Field 'attribute_and_index' via reference field 'ref': Is an index field. Not supported"); - new SearchModel() - .addImportedField("my_attribute_and_index", "ref", "attribute_and_index") - .resolve(); + void resolver_fails_if_imported_field_is_indexing() { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + new SearchModel() + .addImportedField("my_attribute_and_index", "ref", "attribute_and_index") + .resolve(); + }); + assertTrue(exception.getMessage().contains("For schema 'child', import field 'my_attribute_and_index': " + + "Field 'attribute_and_index' via reference field 'ref': Is an index field. Not supported")); } @Test - public void resolver_fails_if_imported_field_is_of_type_predicate() { - exceptionRule.expect(IllegalArgumentException.class); - exceptionRule.expectMessage( - "For schema 'child', import field 'my_predicate_field': " + - "Field 'predicate_field' via reference field 'ref': Is of type 'predicate'. Not supported"); - new SearchModel().addImportedField("my_predicate_field", "ref", "predicate_field").resolve(); + void resolver_fails_if_imported_field_is_of_type_predicate() { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + new SearchModel().addImportedField("my_predicate_field", "ref", "predicate_field").resolve(); + }); + assertTrue(exception.getMessage().contains("For schema 'child', import field 'my_predicate_field': " + + "Field 'predicate_field' via reference field 'ref': Is of type 'predicate'. Not supported")); } static class SearchModel extends ParentChildSearchModel { diff --git a/config-model/src/test/java/com/yahoo/schema/processing/ImportedFieldsTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/ImportedFieldsTestCase.java index ab702154527..6c23d1ecf91 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/ImportedFieldsTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/ImportedFieldsTestCase.java @@ -7,15 +7,10 @@ import com.yahoo.schema.derived.AttributeFields; import com.yahoo.schema.document.ImportedComplexField; import com.yahoo.schema.document.ImportedField; import com.yahoo.schema.parser.ParseException; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; import static com.yahoo.config.model.test.TestUtil.joinLines; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * @author geirst @@ -23,7 +18,7 @@ import static org.junit.Assert.assertTrue; public class ImportedFieldsTestCase { @Test - public void fields_can_be_imported_from_referenced_document_types() throws ParseException { + void fields_can_be_imported_from_referenced_document_types() throws ParseException { Schema schema = buildAdSearch(joinLines( "search ad {", " document ad {", @@ -38,33 +33,31 @@ public class ImportedFieldsTestCase { assertSearchContainsImportedField("my_name", "person_ref", "person", "name", schema); } - @SuppressWarnings("deprecation") - @Rule - public ExpectedException exception = ExpectedException.none(); - @Test - public void field_reference_spec_must_include_dot() throws ParseException { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("Illegal field reference spec 'campaignrefbudget': Does not include a single '.'"); - buildAdSearch(joinLines( - "search ad {", - " document ad {}", - " import field campaignrefbudget as budget {}", - "}")); + void field_reference_spec_must_include_dot() throws ParseException { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + buildAdSearch(joinLines( + "search ad {", + " document ad {}", + " import field campaignrefbudget as budget {}", + "}")); + }); + assertTrue(exception.getMessage().contains("Illegal field reference spec 'campaignrefbudget': Does not include a single '.'")); } @Test - public void fail_duplicate_import() throws ParseException { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("For schema 'ad', import field as 'my_budget': Field already imported"); - Schema schema = buildAdSearch(joinLines( - "schema ad {", - " document ad {", - " field campaign_ref type reference<campaign> { indexing: attribute }", - " }", - " import field campaign_ref.budget as my_budget {}", - " import field campaign_ref.budget as my_budget {}", - "}")); + void fail_duplicate_import() throws ParseException { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + Schema schema = buildAdSearch(joinLines( + "schema ad {", + " document ad {", + " field campaign_ref type reference<campaign> { indexing: attribute }", + " }", + " import field campaign_ref.budget as my_budget {}", + " import field campaign_ref.budget as my_budget {}", + "}")); + }); + assertTrue(exception.getMessage().contains("For schema 'ad', import field as 'my_budget': Field already imported")); } private static Schema buildAdSearch(String sdContent) throws ParseException { @@ -113,52 +106,57 @@ public class ImportedFieldsTestCase { } @Test - public void check_struct_import() throws ParseException { + void check_struct_import() throws ParseException { checkStructImport(new ParentStructSdBuilder()); checkStructImport(new ParentStructSdBuilder().elem_array_weight_attr(false).elem_map_value_weight_attr(false)); checkStructImport(new ParentStructSdBuilder().elem_array_name_attr(false).elem_map_value_name_attr(false)); } @Test - public void check_nested_struct_import() throws ParseException { + void check_nested_struct_import() throws ParseException { checkNestedStructImport(new GrandParentStructSdBuilder()); checkNestedStructImport(new GrandParentStructSdBuilder().elem_array_weight_attr(false).elem_map_value_weight_attr(false)); checkNestedStructImport(new GrandParentStructSdBuilder().elem_array_name_attr(false).elem_map_value_name_attr(false)); } @Test - public void check_illegal_struct_import_missing_array_of_struct_attributes() throws ParseException { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("For schema 'child', import field 'my_elem_array': Field 'elem_array' via reference field 'parent_ref': Is not a struct containing an attribute field."); - checkStructImport(new ParentStructSdBuilder().elem_array_name_attr(false).elem_array_weight_attr(false)); + void check_illegal_struct_import_missing_array_of_struct_attributes() throws ParseException { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + checkStructImport(new ParentStructSdBuilder().elem_array_name_attr(false).elem_array_weight_attr(false)); + }); + assertTrue(exception.getMessage().contains("For schema 'child', import field 'my_elem_array': Field 'elem_array' via reference field 'parent_ref': Is not a struct containing an attribute field.")); } @Test - public void check_illegal_struct_import_missing_map_of_struct_key_attribute() throws ParseException { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("For schema 'child', import field 'my_elem_map' (nested to 'my_elem_map.key'): Field 'elem_map.key' via reference field 'parent_ref': Is not an attribute field. Only attribute fields supported"); - checkStructImport(new ParentStructSdBuilder().elem_map_key_attr(false)); + void check_illegal_struct_import_missing_map_of_struct_key_attribute() throws ParseException { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + checkStructImport(new ParentStructSdBuilder().elem_map_key_attr(false)); + }); + assertTrue(exception.getMessage().contains("For schema 'child', import field 'my_elem_map' (nested to 'my_elem_map.key'): Field 'elem_map.key' via reference field 'parent_ref': Is not an attribute field. Only attribute fields supported")); } @Test - public void check_illegal_struct_import_missing_map_of_struct_value_attributes() throws ParseException { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("For schema 'child', import field 'my_elem_map' (nested to 'my_elem_map.value'): Field 'elem_map.value' via reference field 'parent_ref': Is not a struct containing an attribute field."); - checkStructImport(new ParentStructSdBuilder().elem_map_value_name_attr(false).elem_map_value_weight_attr(false)); + void check_illegal_struct_import_missing_map_of_struct_value_attributes() throws ParseException { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + checkStructImport(new ParentStructSdBuilder().elem_map_value_name_attr(false).elem_map_value_weight_attr(false)); + }); + assertTrue(exception.getMessage().contains("For schema 'child', import field 'my_elem_map' (nested to 'my_elem_map.value'): Field 'elem_map.value' via reference field 'parent_ref': Is not a struct containing an attribute field.")); } @Test - public void check_illegal_struct_import_missing_map_of_primitive_key_attribute() throws ParseException { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("For schema 'child', import field 'my_str_int_map' (nested to 'my_str_int_map.key'): Field 'str_int_map.key' via reference field 'parent_ref': Is not an attribute field. Only attribute fields supported"); - checkStructImport(new ParentStructSdBuilder().str_int_map_key_attr(false)); + void check_illegal_struct_import_missing_map_of_primitive_key_attribute() throws ParseException { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + checkStructImport(new ParentStructSdBuilder().str_int_map_key_attr(false)); + }); + assertTrue(exception.getMessage().contains("For schema 'child', import field 'my_str_int_map' (nested to 'my_str_int_map.key'): Field 'str_int_map.key' via reference field 'parent_ref': Is not an attribute field. Only attribute fields supported")); } @Test - public void check_illegal_struct_import_missing_map_of_primitive_value_attribute() throws ParseException { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("For schema 'child', import field 'my_str_int_map' (nested to 'my_str_int_map.value'): Field 'str_int_map.value' via reference field 'parent_ref': Is not an attribute field. Only attribute fields supported"); - checkStructImport(new ParentStructSdBuilder().str_int_map_value_attr(false)); + void check_illegal_struct_import_missing_map_of_primitive_value_attribute() throws ParseException { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + checkStructImport(new ParentStructSdBuilder().str_int_map_value_attr(false)); + }); + assertTrue(exception.getMessage().contains("For schema 'child', import field 'my_str_int_map' (nested to 'my_str_int_map.value'): Field 'str_int_map.value' via reference field 'parent_ref': Is not an attribute field. Only attribute fields supported")); } private static class NamedSdBuilder { @@ -408,20 +406,21 @@ public class ImportedFieldsTestCase { } @Test - public void check_pos_import() throws ParseException { + void check_pos_import() throws ParseException { checkPosImport(new ParentPosSdBuilder(), new ChildPosSdBuilder()); } @Test - public void check_nested_pos_import() throws ParseException { + void check_nested_pos_import() throws ParseException { checkNestedPosImport(new GrandParentPosSdBuilder(), new ChildPosSdBuilder()); } @Test - public void check_pos_import_after_pos_zcurve_import() throws ParseException { - exception.expect(IllegalArgumentException.class); - exception.expectMessage("For schema 'child', import field 'my_pos_zcurve': Field 'pos_zcurve' via reference field 'parent_ref': Field already imported"); - checkPosImport(new ParentPosSdBuilder(), new ChildPosSdBuilder().import_pos_zcurve_before(true)); + void check_pos_import_after_pos_zcurve_import() throws ParseException { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + checkPosImport(new ParentPosSdBuilder(), new ChildPosSdBuilder().import_pos_zcurve_before(true)); + }); + assertTrue(exception.getMessage().contains("For schema 'child', import field 'my_pos_zcurve': Field 'pos_zcurve' via reference field 'parent_ref': Field already imported")); } private static ImportedField getImportedField(String name, Schema schema) { @@ -466,7 +465,7 @@ public class ImportedFieldsTestCase { } @Test - public void field_with_struct_field_attributes_can_be_imported_from_parents_that_use_inheritance() throws ParseException { + void field_with_struct_field_attributes_can_be_imported_from_parents_that_use_inheritance() throws ParseException { var builder = buildParentsUsingInheritance(); assertParentContainsEntriesAttributes(builder.getSchema("parent_a")); diff --git a/config-model/src/test/java/com/yahoo/schema/processing/IndexingInputsTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/IndexingInputsTestCase.java index 71c79feedc1..893ee3b1ea4 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/IndexingInputsTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/IndexingInputsTestCase.java @@ -2,7 +2,7 @@ package com.yahoo.schema.processing; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; @@ -14,32 +14,32 @@ import static com.yahoo.schema.processing.AssertSearchBuilder.assertBuildFails; public class IndexingInputsTestCase { @Test - public void requireThatExtraFieldInputExtraFieldThrows() throws IOException, ParseException { + void requireThatExtraFieldInputExtraFieldThrows() throws IOException, ParseException { assertBuildFails("src/test/examples/indexing_extra_field_input_extra_field.sd", - "For schema 'indexing_extra_field_input_extra_field', field 'bar': Indexing script refers " + - "to field 'bar' which does not exist in document type " + - "'indexing_extra_field_input_extra_field', and is not a mutable attribute."); + "For schema 'indexing_extra_field_input_extra_field', field 'bar': Indexing script refers " + + "to field 'bar' which does not exist in document type " + + "'indexing_extra_field_input_extra_field', and is not a mutable attribute."); } @Test - public void requireThatExtraFieldInputImplicitThrows() throws IOException, ParseException { + void requireThatExtraFieldInputImplicitThrows() throws IOException, ParseException { assertBuildFails("src/test/examples/indexing_extra_field_input_implicit.sd", - "For schema 'indexing_extra_field_input_implicit', field 'foo': Indexing script refers to " + - "field 'foo' which does not exist in document type 'indexing_extra_field_input_implicit', and is not a mutable attribute."); + "For schema 'indexing_extra_field_input_implicit', field 'foo': Indexing script refers to " + + "field 'foo' which does not exist in document type 'indexing_extra_field_input_implicit', and is not a mutable attribute."); } @Test - public void requireThatExtraFieldInputNullThrows() throws IOException, ParseException { + void requireThatExtraFieldInputNullThrows() throws IOException, ParseException { assertBuildFails("src/test/examples/indexing_extra_field_input_null.sd", - "For schema 'indexing_extra_field_input_null', field 'foo': Indexing script refers to field " + - "'foo' which does not exist in document type 'indexing_extra_field_input_null', and is not a mutable attribute."); + "For schema 'indexing_extra_field_input_null', field 'foo': Indexing script refers to field " + + "'foo' which does not exist in document type 'indexing_extra_field_input_null', and is not a mutable attribute."); } @Test - public void requireThatExtraFieldInputSelfThrows() throws IOException, ParseException { + void requireThatExtraFieldInputSelfThrows() throws IOException, ParseException { assertBuildFails("src/test/examples/indexing_extra_field_input_self.sd", - "For schema 'indexing_extra_field_input_self', field 'foo': Indexing script refers to field " + - "'foo' which does not exist in document type 'indexing_extra_field_input_self', and is not a mutable attribute."); + "For schema 'indexing_extra_field_input_self', field 'foo': Indexing script refers to field " + + "'foo' which does not exist in document type 'indexing_extra_field_input_self', and is not a mutable attribute."); } } diff --git a/config-model/src/test/java/com/yahoo/schema/processing/IndexingOutputsTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/IndexingOutputsTestCase.java index 687549f920e..e707d203381 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/IndexingOutputsTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/IndexingOutputsTestCase.java @@ -2,7 +2,7 @@ package com.yahoo.schema.processing; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; @@ -15,16 +15,16 @@ import static com.yahoo.schema.processing.AssertSearchBuilder.assertBuildFails; public class IndexingOutputsTestCase { @Test - public void requireThatOutputOtherFieldThrows() throws IOException, ParseException { + void requireThatOutputOtherFieldThrows() throws IOException, ParseException { assertBuildFails("src/test/examples/indexing_output_other_field.sd", - "For schema 'indexing_output_other_field', field 'foo': Indexing expression 'index bar' " + - "attempts to write to a field other than 'foo'."); + "For schema 'indexing_output_other_field', field 'foo': Indexing expression 'index bar' " + + "attempts to write to a field other than 'foo'."); } @Test - public void requireThatOutputConflictThrows() throws IOException, ParseException { + void requireThatOutputConflictThrows() throws IOException, ParseException { assertBuildFails("src/test/examples/indexing_output_conflict.sd", - "For schema 'indexing_output_confict', field 'bar': For expression 'index bar': Attempting " + - "to assign conflicting values to field 'bar'."); + "For schema 'indexing_output_confict', field 'bar': For expression 'index bar': Attempting " + + "to assign conflicting values to field 'bar'."); } } diff --git a/config-model/src/test/java/com/yahoo/schema/processing/IndexingScriptRewriterTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/IndexingScriptRewriterTestCase.java index 76cb6a5505c..54a50d2ce93 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/IndexingScriptRewriterTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/IndexingScriptRewriterTestCase.java @@ -16,7 +16,7 @@ import com.yahoo.vespa.documentmodel.SummaryField; import com.yahoo.vespa.documentmodel.SummaryTransform; import com.yahoo.vespa.indexinglanguage.expressions.ScriptExpression; import com.yahoo.vespa.model.container.search.QueryProfiles; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.OptionalDouble; @@ -25,7 +25,7 @@ import java.util.OptionalLong; import java.util.Set; import static com.yahoo.schema.processing.AssertIndexingScript.assertIndexing; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Simon Thoresen Hult @@ -33,108 +33,108 @@ import static org.junit.Assert.assertEquals; public class IndexingScriptRewriterTestCase extends AbstractSchemaTestCase { @Test - public void testSetLanguageRewriting() { + void testSetLanguageRewriting() { assertIndexingScript("{ input test | set_language; }", - createField("test", DataType.STRING, "{ set_language }")); + createField("test", DataType.STRING, "{ set_language }")); } @Test - public void testSummaryRewriting() { + void testSummaryRewriting() { assertIndexingScript("{ input test | summary test; }", - createField("test", DataType.STRING, "{ summary }")); + createField("test", DataType.STRING, "{ summary }")); } @Test - public void testDynamicSummaryRewriting() { + void testDynamicSummaryRewriting() { SDField field = createField("test", DataType.STRING, "{ summary }"); field.addSummaryField(createDynamicSummaryField(field, "dyn")); assertIndexingScript("{ input test | tokenize normalize stem:\"BEST\" | summary dyn; }", field); } @Test - public void testSummaryRewritingWithIndexing() { + void testSummaryRewritingWithIndexing() { assertIndexingScript("{ input test | tokenize normalize stem:\"BEST\" | summary test | index test; }", - createField("test", DataType.STRING, "{ summary | index }")); + createField("test", DataType.STRING, "{ summary | index }")); } @Test - public void testDynamicAndStaticSummariesRewritingWithIndexing() { + void testDynamicAndStaticSummariesRewritingWithIndexing() { SDField field = createField("test", DataType.STRING, "{ summary | index }"); field.addSummaryField(createDynamicSummaryField(field, "dyn")); field.addSummaryField(createStaticSummaryField(field, "test")); field.addSummaryField(createStaticSummaryField(field, "other")); field.addSummaryField(createDynamicSummaryField(field, "dyn2")); assertIndexingScript("{ input test | tokenize normalize stem:\"BEST\" | summary dyn | summary dyn2 | summary other | " + - "summary test | index test; }", field); + "summary test | index test; }", field); } @Test - public void testIntSummaryRewriting() { + void testIntSummaryRewriting() { assertIndexingScript("{ input test | summary test | attribute test; }", - createField("test", DataType.INT, "{ summary | index }")); + createField("test", DataType.INT, "{ summary | index }")); } @Test - public void testStringAttributeSummaryRewriting() { + void testStringAttributeSummaryRewriting() { assertIndexingScript("{ input test | summary test | attribute test; }", - createField("test", DataType.STRING, "{ summary | attribute }")); + createField("test", DataType.STRING, "{ summary | attribute }")); } @Test - public void testMultiblockTokenize() { + void testMultiblockTokenize() { SDField field = createField("test", DataType.STRING, - "{ input test | tokenize | { summary test; }; }"); + "{ input test | tokenize | { summary test; }; }"); assertIndexingScript("{ input test | tokenize | { summary test; }; }", field); } @Test - public void requireThatOutputDefaultsToCurrentField() { + void requireThatOutputDefaultsToCurrentField() { assertIndexingScript("{ input test | attribute test; }", - createField("test", DataType.STRING, "{ attribute; }")); + createField("test", DataType.STRING, "{ attribute; }")); assertIndexingScript("{ input test | tokenize normalize stem:\"BEST\" | index test; }", - createField("test", DataType.STRING, "{ index; }")); + createField("test", DataType.STRING, "{ index; }")); assertIndexingScript("{ input test | summary test; }", - createField("test", DataType.STRING, "{ summary; }")); + createField("test", DataType.STRING, "{ summary; }")); } @Test - public void testTokenizeComparisonDisregardsConfig() { + void testTokenizeComparisonDisregardsConfig() { assertIndexingScript("{ input test | tokenize normalize stem:\"BEST\" | summary test | index test; }", - createField("test", DataType.STRING, "{ summary | tokenize | index; }")); + createField("test", DataType.STRING, "{ summary | tokenize | index; }")); } @Test - public void testDerivingFromSimple() throws Exception { + void testDerivingFromSimple() throws Exception { assertIndexing(Arrays.asList("clear_state | guard { input access | attribute access; }", - "clear_state | guard { input category | split \";\" | attribute category_arr; }", - "clear_state | guard { input category | tokenize | index category; }", - "clear_state | guard { input categories_src | lowercase | normalize | tokenize normalize stem:\"BEST\" | index categories; }", - "clear_state | guard { input categoriesagain_src | lowercase | normalize | tokenize normalize stem:\"BEST\" | index categoriesagain; }", - "clear_state | guard { input chatter | tokenize normalize stem:\"BEST\" | index chatter; }", - "clear_state | guard { input description | tokenize normalize stem:\"BEST\" | summary description | summary dyndesc | index description; }", - "clear_state | guard { input exactemento_src | lowercase | tokenize normalize stem:\"BEST\" | index exactemento | summary exactemento; }", - "clear_state | guard { input longdesc | tokenize normalize stem:\"BEST\" | summary dyndesc2 | summary dynlong | summary longdesc | summary longstat; }", - "clear_state | guard { input measurement | attribute measurement | summary measurement; }", - "clear_state | guard { input measurement | to_array | attribute measurement_arr; }", - "clear_state | guard { input popularity | attribute popularity; }", - "clear_state | guard { input popularity * input measurement | attribute popsiness; }", - "clear_state | guard { input smallattribute | attribute smallattribute; }", - "clear_state | guard { input title | tokenize normalize stem:\"BEST\" | summary title | index title; }", - "clear_state | guard { input title . \" \" . input category | tokenize | summary exact | index exact; }"), - ApplicationBuilder.buildFromFile("src/test/examples/simple.sd")); + "clear_state | guard { input category | split \";\" | attribute category_arr; }", + "clear_state | guard { input category | tokenize | index category; }", + "clear_state | guard { input categories_src | lowercase | normalize | tokenize normalize stem:\"BEST\" | index categories; }", + "clear_state | guard { input categoriesagain_src | lowercase | normalize | tokenize normalize stem:\"BEST\" | index categoriesagain; }", + "clear_state | guard { input chatter | tokenize normalize stem:\"BEST\" | index chatter; }", + "clear_state | guard { input description | tokenize normalize stem:\"BEST\" | summary description | summary dyndesc | index description; }", + "clear_state | guard { input exactemento_src | lowercase | tokenize normalize stem:\"BEST\" | index exactemento | summary exactemento; }", + "clear_state | guard { input longdesc | tokenize normalize stem:\"BEST\" | summary dyndesc2 | summary dynlong | summary longdesc | summary longstat; }", + "clear_state | guard { input measurement | attribute measurement | summary measurement; }", + "clear_state | guard { input measurement | to_array | attribute measurement_arr; }", + "clear_state | guard { input popularity | attribute popularity; }", + "clear_state | guard { input popularity * input measurement | attribute popsiness; }", + "clear_state | guard { input smallattribute | attribute smallattribute; }", + "clear_state | guard { input title | tokenize normalize stem:\"BEST\" | summary title | index title; }", + "clear_state | guard { input title . \" \" . input category | tokenize | summary exact | index exact; }"), + ApplicationBuilder.buildFromFile("src/test/examples/simple.sd")); } @Test - public void testIndexRewrite() throws Exception { + void testIndexRewrite() throws Exception { assertIndexing( Arrays.asList("clear_state | guard { input title_src | lowercase | normalize | " + - " tokenize | index title; }", - "clear_state | guard { input title_src | summary title_s; }"), + " tokenize | index title; }", + "clear_state | guard { input title_src | summary title_s; }"), ApplicationBuilder.buildFromFile("src/test/examples/indexrewrite.sd")); } @Test - public void requireThatPredicateFieldsGetOptimization() { + void requireThatPredicateFieldsGetOptimization() { assertIndexingScript("{ 10 | set_var arity | { input test | optimize_predicate | attribute test; }; }", createPredicateField( "test", DataType.PREDICATE, "{ attribute; }", 10, OptionalLong.empty(), OptionalLong.empty())); @@ -143,7 +143,7 @@ public class IndexingScriptRewriterTestCase extends AbstractSchemaTestCase { "test", DataType.PREDICATE, "{ summary | attribute ; }", 10, OptionalLong.empty(), OptionalLong.empty())); assertIndexingScript( "{ 2 | set_var arity | 0L | set_var lower_bound | 1023L | set_var upper_bound | " + - "{ input test | optimize_predicate | attribute test; }; }", + "{ input test | optimize_predicate | attribute test; }; }", createPredicateField("test", DataType.PREDICATE, "{ attribute; }", 2, OptionalLong.of(0L), OptionalLong.of(1023L))); } diff --git a/config-model/src/test/java/com/yahoo/schema/processing/IndexingValidationTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/IndexingValidationTestCase.java index 4da6880aa26..aa8a2922e8f 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/IndexingValidationTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/IndexingValidationTestCase.java @@ -4,7 +4,7 @@ package com.yahoo.schema.processing; import com.yahoo.schema.ApplicationBuilder; import com.yahoo.schema.derived.AbstractExportingTestCase; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Arrays; @@ -18,59 +18,59 @@ import static com.yahoo.schema.processing.AssertSearchBuilder.assertBuildFails; public class IndexingValidationTestCase extends AbstractExportingTestCase { @Test - public void testAttributeChanged() throws IOException, ParseException { + void testAttributeChanged() throws IOException, ParseException { assertBuildFails("src/test/examples/indexing_attribute_changed.sd", - "For schema 'indexing_attribute_changed', field 'foo': For expression 'attribute foo': " + - "Attempting to assign conflicting values to field 'foo'."); + "For schema 'indexing_attribute_changed', field 'foo': For expression 'attribute foo': " + + "Attempting to assign conflicting values to field 'foo'."); } @Test - public void testAttributeOther() throws IOException, ParseException { + void testAttributeOther() throws IOException, ParseException { assertBuildFails("src/test/examples/indexing_attribute_other.sd", - "For schema 'indexing_attribute_other', field 'foo': Indexing expression 'attribute bar' " + - "attempts to write to a field other than 'foo'."); + "For schema 'indexing_attribute_other', field 'foo': Indexing expression 'attribute bar' " + + "attempts to write to a field other than 'foo'."); } @Test - public void testIndexChanged() throws IOException, ParseException { + void testIndexChanged() throws IOException, ParseException { assertBuildFails("src/test/examples/indexing_index_changed.sd", - "For schema 'indexing_index_changed', field 'foo': For expression 'index foo': " + - "Attempting to assign conflicting values to field 'foo'."); + "For schema 'indexing_index_changed', field 'foo': For expression 'index foo': " + + "Attempting to assign conflicting values to field 'foo'."); } @Test - public void testIndexOther() throws IOException, ParseException { + void testIndexOther() throws IOException, ParseException { assertBuildFails("src/test/examples/indexing_index_other.sd", - "For schema 'indexing_index_other', field 'foo': Indexing expression 'index bar' " + - "attempts to write to a field other than 'foo'."); + "For schema 'indexing_index_other', field 'foo': Indexing expression 'index bar' " + + "attempts to write to a field other than 'foo'."); } @Test - public void testSummaryChanged() throws IOException, ParseException { + void testSummaryChanged() throws IOException, ParseException { assertBuildFails("src/test/examples/indexing_summary_changed.sd", - "For schema 'indexing_summary_fail', field 'foo': For expression 'summary foo': Attempting " + - "to assign conflicting values to field 'foo'."); + "For schema 'indexing_summary_fail', field 'foo': For expression 'summary foo': Attempting " + + "to assign conflicting values to field 'foo'."); } @Test - public void testSummaryOther() throws IOException, ParseException { + void testSummaryOther() throws IOException, ParseException { assertBuildFails("src/test/examples/indexing_summary_other.sd", - "For schema 'indexing_summary_other', field 'foo': Indexing expression 'summary bar' " + - "attempts to write to a field other than 'foo'."); + "For schema 'indexing_summary_other', field 'foo': Indexing expression 'summary bar' " + + "attempts to write to a field other than 'foo'."); } @Test - public void testExtraField() throws IOException, ParseException { + void testExtraField() throws IOException, ParseException { assertIndexing( Arrays.asList("clear_state | guard { input my_index | tokenize normalize stem:\"BEST\" | index my_index | summary my_index }", - "clear_state | guard { input my_input | tokenize normalize stem:\"BEST\" | index my_extra | summary my_extra }"), + "clear_state | guard { input my_input | tokenize normalize stem:\"BEST\" | index my_extra | summary my_extra }"), ApplicationBuilder.buildFromFile("src/test/examples/indexing_extra.sd")); } @Test - public void requireThatMultilineOutputConflictThrows() throws IOException, ParseException { + void requireThatMultilineOutputConflictThrows() throws IOException, ParseException { assertBuildFails("src/test/examples/indexing_multiline_output_conflict.sd", - "For schema 'indexing_multiline_output_confict', field 'cox': For expression 'index cox': " + - "Attempting to assign conflicting values to field 'cox'."); + "For schema 'indexing_multiline_output_confict', field 'cox': For expression 'index cox': " + + "Attempting to assign conflicting values to field 'cox'."); } } diff --git a/config-model/src/test/java/com/yahoo/schema/processing/IndexingValuesTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/IndexingValuesTestCase.java index 2784fe69b28..1f723924db6 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/IndexingValuesTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/IndexingValuesTestCase.java @@ -2,7 +2,7 @@ package com.yahoo.schema.processing; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; @@ -15,16 +15,16 @@ import static com.yahoo.schema.processing.AssertSearchBuilder.assertBuilds; public class IndexingValuesTestCase { @Test - public void requireThatModifyFieldNoOutputDoesNotThrow() throws IOException, ParseException { + void requireThatModifyFieldNoOutputDoesNotThrow() throws IOException, ParseException { assertBuilds("src/test/examples/indexing_modify_field_no_output.sd"); } @Test - public void requireThatInputOtherFieldThrows() throws IOException, ParseException { + void requireThatInputOtherFieldThrows() throws IOException, ParseException { assertBuildFails("src/test/examples/indexing_input_other_field.sd", - "For schema 'indexing_input_other_field', field 'bar': Indexing expression 'input foo' " + - "attempts to modify the value of the document field 'bar'. " + - "Use a field outside the document block instead."); + "For schema 'indexing_input_other_field', field 'bar': Indexing expression 'input foo' " + + "attempts to modify the value of the document field 'bar'. " + + "Use a field outside the document block instead."); } } diff --git a/config-model/src/test/java/com/yahoo/schema/processing/IntegerIndex2AttributeTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/IntegerIndex2AttributeTestCase.java index f36effab146..d3bfe7a8f55 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/IntegerIndex2AttributeTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/IntegerIndex2AttributeTestCase.java @@ -9,13 +9,11 @@ import com.yahoo.schema.AbstractSchemaTestCase; import com.yahoo.schema.document.SDField; import com.yahoo.schema.parser.ParseException; import com.yahoo.vespa.model.container.search.QueryProfiles; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * @author baldersheim @@ -23,7 +21,7 @@ import static org.junit.Assert.assertTrue; public class IntegerIndex2AttributeTestCase extends AbstractSchemaTestCase { @Test - public void testIntegerIndex2Attribute() throws IOException, ParseException { + void testIntegerIndex2Attribute() throws IOException, ParseException { Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/integerindex2attribute.sd"); new IntegerIndex2Attribute(schema, new BaseDeployLogger(), new RankProfileRegistry(), new QueryProfiles()).process(true, false); diff --git a/config-model/src/test/java/com/yahoo/schema/processing/MatchPhaseSettingsValidatorTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/MatchPhaseSettingsValidatorTestCase.java index 530b6a95ce8..cbddea8ea6a 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/MatchPhaseSettingsValidatorTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/MatchPhaseSettingsValidatorTestCase.java @@ -1,7 +1,7 @@ // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.schema.processing; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static com.yahoo.schema.processing.AssertSearchBuilder.assertBuildFails; @@ -12,25 +12,25 @@ public class MatchPhaseSettingsValidatorTestCase { } @Test - public void requireThatAttributeMustExists() throws Exception { + void requireThatAttributeMustExists() throws Exception { assertBuildFails("src/test/examples/matchphase/non_existing_attribute.sd", getMessagePrefix() + "does not exists"); } @Test - public void requireThatAttributeMustBeNumeric() throws Exception { + void requireThatAttributeMustBeNumeric() throws Exception { assertBuildFails("src/test/examples/matchphase/wrong_data_type_attribute.sd", getMessagePrefix() + "must be single value numeric, but it is 'string'"); } @Test - public void requireThatAttributeMustBeSingleValue() throws Exception { + void requireThatAttributeMustBeSingleValue() throws Exception { assertBuildFails("src/test/examples/matchphase/wrong_collection_type_attribute.sd", getMessagePrefix() + "must be single value numeric, but it is 'Array<int>'"); } @Test - public void requireThatAttributeMustHaveFastSearch() throws Exception { + void requireThatAttributeMustHaveFastSearch() throws Exception { assertBuildFails("src/test/examples/matchphase/non_fast_search_attribute.sd", getMessagePrefix() + "must be fast-search, but it is not"); } diff --git a/config-model/src/test/java/com/yahoo/schema/processing/MatchedElementsOnlyResolverTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/MatchedElementsOnlyResolverTestCase.java index c401376ac3a..bd93a70d7cb 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/MatchedElementsOnlyResolverTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/MatchedElementsOnlyResolverTestCase.java @@ -7,24 +7,18 @@ import com.yahoo.schema.ApplicationBuilder; import com.yahoo.schema.parser.ParseException; import com.yahoo.vespa.documentmodel.SummaryField; import com.yahoo.vespa.documentmodel.SummaryTransform; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; import static com.yahoo.config.model.test.TestUtil.joinLines; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.*; /** * @author geirst */ public class MatchedElementsOnlyResolverTestCase { - @SuppressWarnings("deprecation") - @Rule - public final ExpectedException exceptionRule = ExpectedException.none(); - @Test - public void complex_field_with_some_struct_field_attributes_gets_default_transform() throws ParseException { + void complex_field_with_some_struct_field_attributes_gets_default_transform() throws ParseException { assertSummaryField(joinLines("field my_field type map<string, string> {", " indexing: summary", " summary: matched-elements-only", @@ -48,7 +42,7 @@ public class MatchedElementsOnlyResolverTestCase { } @Test - public void complex_field_with_only_struct_field_attributes_gets_attribute_transform() throws ParseException { + void complex_field_with_only_struct_field_attributes_gets_attribute_transform() throws ParseException { assertSummaryField(joinLines("field my_field type map<string, string> {", " indexing: summary", " summary: matched-elements-only", @@ -76,7 +70,7 @@ public class MatchedElementsOnlyResolverTestCase { } @Test - public void explicit_complex_summary_field_can_use_filter_transform_with_reference_to_source_field() throws ParseException { + void explicit_complex_summary_field_can_use_filter_transform_with_reference_to_source_field() throws ParseException { String documentSummary = joinLines("document-summary my_summary {", " summary my_filter_field type map<string, string> {", " source: my_field", @@ -109,7 +103,7 @@ public class MatchedElementsOnlyResolverTestCase { } @Test - public void primitive_array_attribute_field_gets_attribute_transform() throws ParseException { + void primitive_array_attribute_field_gets_attribute_transform() throws ParseException { assertSummaryField(joinLines("field my_field type array<string> {", " indexing: attribute | summary", " summary: matched-elements-only", @@ -118,7 +112,7 @@ public class MatchedElementsOnlyResolverTestCase { } @Test - public void primitive_weighted_set_attribute_field_gets_attribute_transform() throws ParseException { + void primitive_weighted_set_attribute_field_gets_attribute_transform() throws ParseException { assertSummaryField(joinLines("field my_field type weightedset<string> {", " indexing: attribute | summary", " summary: matched-elements-only", @@ -127,7 +121,7 @@ public class MatchedElementsOnlyResolverTestCase { } @Test - public void explicit_summary_field_can_use_filter_transform_with_reference_to_attribute_source_field() throws ParseException { + void explicit_summary_field_can_use_filter_transform_with_reference_to_attribute_source_field() throws ParseException { String documentSummary = joinLines("document-summary my_summary {", " summary my_filter_field type array<string> {", " source: my_field", @@ -147,17 +141,18 @@ public class MatchedElementsOnlyResolverTestCase { } @Test - public void unsupported_field_type_throws() throws ParseException { - exceptionRule.expect(IllegalArgumentException.class); - exceptionRule.expectMessage("For schema 'test', document summary 'default', summary field 'my_field': " + + void unsupported_field_type_throws() throws ParseException { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + buildSearch(joinLines("field my_field type string {", + " indexing: summary", + " summary: matched-elements-only", + "}")); + }); + assertTrue(exception.getMessage().contains("For schema 'test', document summary 'default', summary field 'my_field': " + "'matched-elements-only' is not supported for this field type. " + "Supported field types are: array of primitive, weighted set of primitive, " + "array of simple struct, map of primitive type to simple struct, " + - "and map of primitive type to primitive type"); - buildSearch(joinLines("field my_field type string {", - " indexing: summary", - " summary: matched-elements-only", - "}")); + "and map of primitive type to primitive type")); } private void assertSummaryField(String fieldContent, String fieldName, SummaryTransform expTransform) throws ParseException { diff --git a/config-model/src/test/java/com/yahoo/schema/processing/NGramTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/NGramTestCase.java index 912e6fcf030..c143aa43d53 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/NGramTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/NGramTestCase.java @@ -8,15 +8,12 @@ import com.yahoo.schema.document.MatchType; import com.yahoo.schema.document.SDField; import com.yahoo.schema.document.Stemming; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; /** * @author bratseth @@ -24,7 +21,7 @@ import static org.junit.Assert.fail; public class NGramTestCase extends AbstractSchemaTestCase { @Test - public void testNGram() throws IOException, ParseException { + void testNGram() throws IOException, ParseException { Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/ngram.sd"); assertNotNull(schema); @@ -36,8 +33,8 @@ public class NGramTestCase extends AbstractSchemaTestCase { assertEquals(MatchType.GRAM, gram2.getMatching().getType()); assertEquals(-1, gram2.getMatching().getGramSize()); // Not set explicitly - SDField gram3= schema.getConcreteField("gram_3"); - assertEquals(MatchType.GRAM,gram3.getMatching().getType()); + SDField gram3 = schema.getConcreteField("gram_3"); + assertEquals(MatchType.GRAM, gram3.getMatching().getType()); assertEquals(3, gram3.getMatching().getGramSize()); assertEquals("input gram_1 | ngram 1 | index gram_1 | summary gram_1", gram1.getIndexingScript().iterator().next().toString()); @@ -53,7 +50,7 @@ public class NGramTestCase extends AbstractSchemaTestCase { } @Test - public void testInvalidNGramSetting1() throws IOException, ParseException { + void testInvalidNGramSetting1() throws IOException, ParseException { try { Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/invalidngram1.sd"); fail("Should cause an exception"); @@ -64,7 +61,7 @@ public class NGramTestCase extends AbstractSchemaTestCase { } @Test - public void testInvalidNGramSetting2() throws IOException, ParseException { + void testInvalidNGramSetting2() throws IOException, ParseException { try { Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/invalidngram2.sd"); fail("Should cause an exception"); @@ -75,7 +72,7 @@ public class NGramTestCase extends AbstractSchemaTestCase { } @Test - public void testInvalidNGramSetting3() throws IOException, ParseException { + void testInvalidNGramSetting3() throws IOException, ParseException { try { Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/invalidngram3.sd"); fail("Should cause an exception"); diff --git a/config-model/src/test/java/com/yahoo/schema/processing/PagedAttributeValidatorTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/PagedAttributeValidatorTestCase.java index a291dda24b9..2a3a3ff93e9 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/PagedAttributeValidatorTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/PagedAttributeValidatorTestCase.java @@ -3,27 +3,24 @@ package com.yahoo.schema.processing; import com.yahoo.config.model.application.provider.BaseDeployLogger; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Optional; import static com.yahoo.config.model.test.TestUtil.joinLines; import static com.yahoo.schema.ApplicationBuilder.createFromString; import static com.yahoo.schema.ApplicationBuilder.createFromStrings; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; public class PagedAttributeValidatorTestCase { @Test - public void dense_tensor_attribute_supports_paged_setting() throws ParseException { + void dense_tensor_attribute_supports_paged_setting() throws ParseException { assertPagedSupported("tensor(x[2],y[2])"); } @Test - public void primitive_attribute_types_support_paged_setting() throws ParseException { + void primitive_attribute_types_support_paged_setting() throws ParseException { assertPagedSupported("int"); assertPagedSupported("array<int>"); assertPagedSupported("weightedset<int>"); @@ -34,7 +31,7 @@ public class PagedAttributeValidatorTestCase { } @Test - public void struct_field_attributes_support_paged_setting() throws ParseException { + void struct_field_attributes_support_paged_setting() throws ParseException { var sd = joinLines("schema test {", " document test {", " struct elem {", @@ -68,17 +65,17 @@ public class PagedAttributeValidatorTestCase { } @Test - public void non_dense_tensor_attribute_does_not_support_paged_setting() throws ParseException { + void non_dense_tensor_attribute_does_not_support_paged_setting() throws ParseException { assertPagedSettingNotSupported("tensor(x{},y[2])"); } @Test - public void predicate_attribute_does_not_support_paged_setting() throws ParseException { + void predicate_attribute_does_not_support_paged_setting() throws ParseException { assertPagedSettingNotSupported("predicate"); } @Test - public void reference_attribute_does_not_support_paged_setting() throws ParseException { + void reference_attribute_does_not_support_paged_setting() throws ParseException { assertPagedSettingNotSupported("reference<parent>", Optional.of(getSd("parent", "int"))); } diff --git a/config-model/src/test/java/com/yahoo/schema/processing/PositionTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/PositionTestCase.java index e4f32fff41d..1b950523588 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/PositionTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/PositionTestCase.java @@ -11,12 +11,12 @@ import com.yahoo.schema.document.FieldSet; import com.yahoo.vespa.documentmodel.SummaryField; import com.yahoo.vespa.documentmodel.SummaryTransform; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Iterator; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; /** * Test Position processor. @@ -26,7 +26,7 @@ import static org.junit.Assert.*; public class PositionTestCase { @Test - public void inherited_position_zcurve_field_is_not_added_to_document_fieldset() throws Exception { + void inherited_position_zcurve_field_is_not_added_to_document_fieldset() throws Exception { ApplicationBuilder sb = ApplicationBuilder.createFromFiles(Arrays.asList( "src/test/examples/position_base.sd", "src/test/examples/position_inherited.sd")); @@ -37,7 +37,7 @@ public class PositionTestCase { } @Test - public void requireThatPositionCanBeAttribute() throws Exception { + void requireThatPositionCanBeAttribute() throws Exception { Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/position_attribute.sd"); assertNull(schema.getAttribute("pos")); assertNull(schema.getAttribute("pos.x")); @@ -48,18 +48,18 @@ public class PositionTestCase { } @Test - public void requireThatPositionCanNotBeIndex() throws Exception { + void requireThatPositionCanNotBeIndex() throws Exception { try { ApplicationBuilder.buildFromFile("src/test/examples/position_index.sd"); fail(); } catch (IllegalArgumentException e) { assertEquals("For schema 'position_index', field 'pos': Indexing of data type 'position' is not " + - "supported, replace 'index' statement with 'attribute'.", e.getMessage()); + "supported, replace 'index' statement with 'attribute'.", e.getMessage()); } } @Test - public void requireThatSummaryAloneDoesNotCreateZCurve() throws Exception { + void requireThatSummaryAloneDoesNotCreateZCurve() throws Exception { Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/position_summary.sd"); assertNull(schema.getAttribute("pos")); assertNull(schema.getAttribute("pos.x")); @@ -78,7 +78,7 @@ public class PositionTestCase { } @Test - public void requireThatExtraFieldCanBePositionAttribute() throws Exception { + void requireThatExtraFieldCanBePositionAttribute() throws Exception { Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/position_extra.sd"); assertNull(schema.getAttribute("pos_ext")); assertNull(schema.getAttribute("pos_ext.x")); @@ -89,7 +89,7 @@ public class PositionTestCase { } @Test - public void requireThatPositionArrayIsSupported() throws Exception { + void requireThatPositionArrayIsSupported() throws Exception { Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/position_array.sd"); assertNull(schema.getAttribute("pos")); assertNull(schema.getAttribute("pos.x")); diff --git a/config-model/src/test/java/com/yahoo/schema/processing/RankModifierTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/RankModifierTestCase.java index 69bf62be84b..f49b1df8cea 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/RankModifierTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/RankModifierTestCase.java @@ -5,7 +5,7 @@ import com.yahoo.schema.Schema; import com.yahoo.schema.ApplicationBuilder; import com.yahoo.schema.AbstractSchemaTestCase; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; @@ -16,7 +16,7 @@ import java.io.IOException; */ public class RankModifierTestCase extends AbstractSchemaTestCase { @Test - public void testLiteral() throws IOException, ParseException { + void testLiteral() throws IOException, ParseException { Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/rankmodifier/literal.sd"); } } diff --git a/config-model/src/test/java/com/yahoo/schema/processing/RankProfileSearchFixture.java b/config-model/src/test/java/com/yahoo/schema/processing/RankProfileSearchFixture.java index e380b1ab9af..15fe8250b71 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/RankProfileSearchFixture.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/RankProfileSearchFixture.java @@ -27,7 +27,7 @@ import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Helper class for setting up and asserting over a Search instance with a rank profile given literally diff --git a/config-model/src/test/java/com/yahoo/schema/processing/RankPropertyVariablesTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/RankPropertyVariablesTestCase.java index dab1d9e6e95..077017cc70e 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/RankPropertyVariablesTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/RankPropertyVariablesTestCase.java @@ -9,22 +9,22 @@ import com.yahoo.schema.Schema; import com.yahoo.schema.ApplicationBuilder; import com.yahoo.schema.AbstractSchemaTestCase; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.List; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; public class RankPropertyVariablesTestCase extends AbstractSchemaTestCase { @Test - public void testRankPropVariables() throws IOException, ParseException { + void testRankPropVariables() throws IOException, ParseException { RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/rankpropvars.sd", - new BaseDeployLogger(), - rankProfileRegistry, - new QueryProfileRegistry()); + new BaseDeployLogger(), + rankProfileRegistry, + new QueryProfileRegistry()); assertRankPropEquals(rankProfileRegistry.get(schema, "other").getRankProperties(), "$testvar1", "foo"); assertRankPropEquals(rankProfileRegistry.get(schema, "other").getRankProperties(), "$testvar_2", "bar"); assertRankPropEquals(rankProfileRegistry.get(schema, "other").getRankProperties(), "$testvarOne23", "baz"); diff --git a/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionTypeResolverTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionTypeResolverTestCase.java index f2f2a82b97c..c6d6332b4c0 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionTypeResolverTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionTypeResolverTestCase.java @@ -11,7 +11,7 @@ import com.yahoo.schema.ApplicationBuilder; import com.yahoo.searchlib.rankingexpression.rule.ReferenceNode; import com.yahoo.tensor.TensorType; import com.yahoo.yolean.Exceptions; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; @@ -20,10 +20,7 @@ import java.util.logging.Level; import java.util.stream.Collectors; import static com.yahoo.config.model.test.TestUtil.joinLines; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; /** * @author bratseth @@ -31,7 +28,7 @@ import static org.junit.Assert.fail; public class RankingExpressionTypeResolverTestCase { @Test - public void tensorFirstPhaseMustProduceDouble() throws Exception { + void tensorFirstPhaseMustProduceDouble() throws Exception { try { ApplicationBuilder builder = new ApplicationBuilder(); builder.addSchema(joinLines( @@ -53,13 +50,13 @@ public class RankingExpressionTypeResolverTestCase { } catch (IllegalArgumentException expected) { assertEquals("In schema 'test', rank profile 'my_rank_profile': The first-phase expression must produce a double (a tensor with no dimensions), but produces tensor(x[10],y[3])", - Exceptions.toMessageString(expected)); + Exceptions.toMessageString(expected)); } } @Test - public void tensorFirstPhaseFromConstantMustProduceDouble() throws Exception { + void tensorFirstPhaseFromConstantMustProduceDouble() throws Exception { try { ApplicationBuilder builder = new ApplicationBuilder(); builder.addSchema(joinLines( @@ -95,14 +92,13 @@ public class RankingExpressionTypeResolverTestCase { } catch (IllegalArgumentException expected) { assertEquals("In schema 'test', rank profile 'my_rank_profile': The first-phase expression must produce a double (a tensor with no dimensions), but produces tensor(x{},y{},z{})", - Exceptions.toMessageString(expected)); + Exceptions.toMessageString(expected)); } } - @Test - public void tensorSecondPhaseMustProduceDouble() throws Exception { + void tensorSecondPhaseMustProduceDouble() throws Exception { try { ApplicationBuilder builder = new ApplicationBuilder(); builder.addSchema(joinLines( @@ -127,12 +123,12 @@ public class RankingExpressionTypeResolverTestCase { } catch (IllegalArgumentException expected) { assertEquals("In schema 'test', rank profile 'my_rank_profile': The second-phase expression must produce a double (a tensor with no dimensions), but produces tensor(x[10],y[3])", - Exceptions.toMessageString(expected)); + Exceptions.toMessageString(expected)); } } @Test - public void tensorConditionsMustHaveTypeCompatibleBranches() throws Exception { + void tensorConditionsMustHaveTypeCompatibleBranches() throws Exception { try { ApplicationBuilder schemaBuilder = new ApplicationBuilder(); schemaBuilder.addSchema(joinLines( @@ -157,14 +153,14 @@ public class RankingExpressionTypeResolverTestCase { } catch (IllegalArgumentException expected) { assertEquals("In schema 'test', rank profile 'my_rank_profile': The first-phase expression is invalid: An if expression must produce compatible types in both alternatives, but the 'true' type is tensor(x[10],y[5]) while the 'false' type is tensor(z[10])" + - "\n'true' branch: attribute(a)" + - "\n'false' branch: attribute(b)", - Exceptions.toMessageString(expected)); + "\n'true' branch: attribute(a)" + + "\n'false' branch: attribute(b)", + Exceptions.toMessageString(expected)); } } @Test - public void testFunctionInvocationTypes() throws Exception { + void testFunctionInvocationTypes() throws Exception { RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); ApplicationBuilder builder = new ApplicationBuilder(rankProfileRegistry); builder.addSchema(joinLines( @@ -192,13 +188,13 @@ public class RankingExpressionTypeResolverTestCase { RankProfile profile = builder.getRankProfileRegistry().get(builder.getSchema(), "my_rank_profile"); assertEquals(TensorType.fromSpec("tensor(x[10],y[3])"), - summaryFeatures(profile).get("macro1(a)").type(profile.typeContext(builder.getQueryProfileRegistry()))); + summaryFeatures(profile).get("macro1(a)").type(profile.typeContext(builder.getQueryProfileRegistry()))); assertEquals(TensorType.fromSpec("tensor(z[10])"), - summaryFeatures(profile).get("macro1(b)").type(profile.typeContext(builder.getQueryProfileRegistry()))); + summaryFeatures(profile).get("macro1(b)").type(profile.typeContext(builder.getQueryProfileRegistry()))); } @Test - public void testTensorFunctionInvocationTypes_Nested() throws Exception { + void testTensorFunctionInvocationTypes_Nested() throws Exception { ApplicationBuilder builder = new ApplicationBuilder(); builder.addSchema(joinLines( "search test {", @@ -234,52 +230,52 @@ public class RankingExpressionTypeResolverTestCase { RankProfile profile = builder.getRankProfileRegistry().get(builder.getSchema(), "my_rank_profile"); assertEquals(TensorType.fromSpec("tensor(x[10],y[1])"), - summaryFeatures(profile).get("return_a").type(profile.typeContext(builder.getQueryProfileRegistry()))); + summaryFeatures(profile).get("return_a").type(profile.typeContext(builder.getQueryProfileRegistry()))); assertEquals(TensorType.fromSpec("tensor(z[10])"), - summaryFeatures(profile).get("return_b").type(profile.typeContext(builder.getQueryProfileRegistry()))); + summaryFeatures(profile).get("return_b").type(profile.typeContext(builder.getQueryProfileRegistry()))); } @Test - public void testAttributeInvocationViaBoundIdentifier() throws Exception { + void testAttributeInvocationViaBoundIdentifier() throws Exception { ApplicationBuilder builder = new ApplicationBuilder(); builder.addSchema(joinLines( - "search newsarticle {", - " document newsarticle {", - " field title type string {", - " indexing {", - " input title | index", - " }", - " weight: 30", - " }", - " field usstaticrank type int {", - " indexing: summary | attribute", - " }", - " field eustaticrank type int {", - " indexing: summary | attribute", - " }", - " }", - " rank-profile default {", - " macro newsboost() { ", - " expression: 200 * matches(title)", - " }", - " macro commonboost(mystaticrank) { ", - " expression: attribute(mystaticrank) + newsboost", - " }", - " macro commonfirstphase(mystaticrank) { ", - " expression: nativeFieldMatch(title) + commonboost(mystaticrank) ", - " }", - " first-phase { expression: commonfirstphase(usstaticrank) }", - " }", - " rank-profile eurank inherits default {", - " first-phase { expression: commonfirstphase(eustaticrank) }", - " }", - "}")); + "search newsarticle {", + " document newsarticle {", + " field title type string {", + " indexing {", + " input title | index", + " }", + " weight: 30", + " }", + " field usstaticrank type int {", + " indexing: summary | attribute", + " }", + " field eustaticrank type int {", + " indexing: summary | attribute", + " }", + " }", + " rank-profile default {", + " macro newsboost() { ", + " expression: 200 * matches(title)", + " }", + " macro commonboost(mystaticrank) { ", + " expression: attribute(mystaticrank) + newsboost", + " }", + " macro commonfirstphase(mystaticrank) { ", + " expression: nativeFieldMatch(title) + commonboost(mystaticrank) ", + " }", + " first-phase { expression: commonfirstphase(usstaticrank) }", + " }", + " rank-profile eurank inherits default {", + " first-phase { expression: commonfirstphase(eustaticrank) }", + " }", + "}")); builder.build(true); RankProfile profile = builder.getRankProfileRegistry().get(builder.getSchema(), "eurank"); } @Test - public void testTensorFunctionInvocationTypes_NestedSameName() throws Exception { + void testTensorFunctionInvocationTypes_NestedSameName() throws Exception { ApplicationBuilder builder = new ApplicationBuilder(); builder.addSchema(joinLines( "search test {", @@ -318,35 +314,35 @@ public class RankingExpressionTypeResolverTestCase { RankProfile profile = builder.getRankProfileRegistry().get(builder.getSchema(), "my_rank_profile"); assertEquals(TensorType.fromSpec("tensor(x[10],y[1])"), - summaryFeatures(profile).get("return_a").type(profile.typeContext(builder.getQueryProfileRegistry()))); + summaryFeatures(profile).get("return_a").type(profile.typeContext(builder.getQueryProfileRegistry()))); assertEquals(TensorType.fromSpec("tensor(z[10])"), - summaryFeatures(profile).get("return_b").type(profile.typeContext(builder.getQueryProfileRegistry()))); + summaryFeatures(profile).get("return_b").type(profile.typeContext(builder.getQueryProfileRegistry()))); } @Test - public void testTensorFunctionInvocationTypes_viaFuncWithExpr() throws Exception { + void testTensorFunctionInvocationTypes_viaFuncWithExpr() throws Exception { ApplicationBuilder builder = new ApplicationBuilder(); builder.addSchema(joinLines( - "search test {", - " document test {", - " field t1 type tensor<float>(y{}) { indexing: attribute | summary }", - " field t2 type tensor<float>(x{}) { indexing: attribute | summary }", - " }", - " rank-profile test {", - " function my_func(t) { expression: sum(t, x) + 1 }", - " function test_func_via_func_with_expr() { expression: call_func_with_expr( attribute(t1), attribute(t2) ) }", - " function call_func_with_expr(a, b) { expression: my_func( a * b ) }", - " summary-features { test_func_via_func_with_expr }", - " }", - "}")); + "search test {", + " document test {", + " field t1 type tensor<float>(y{}) { indexing: attribute | summary }", + " field t2 type tensor<float>(x{}) { indexing: attribute | summary }", + " }", + " rank-profile test {", + " function my_func(t) { expression: sum(t, x) + 1 }", + " function test_func_via_func_with_expr() { expression: call_func_with_expr( attribute(t1), attribute(t2) ) }", + " function call_func_with_expr(a, b) { expression: my_func( a * b ) }", + " summary-features { test_func_via_func_with_expr }", + " }", + "}")); builder.build(true); RankProfile profile = builder.getRankProfileRegistry().get(builder.getSchema(), "test"); assertEquals(TensorType.fromSpec("tensor<float>(y{})"), - summaryFeatures(profile).get("test_func_via_func_with_expr").type(profile.typeContext(builder.getQueryProfileRegistry()))); + summaryFeatures(profile).get("test_func_via_func_with_expr").type(profile.typeContext(builder.getQueryProfileRegistry()))); } @Test - public void importedFieldsAreAvailable() throws Exception { + void importedFieldsAreAvailable() throws Exception { ApplicationBuilder builder = new ApplicationBuilder(); builder.addSchema(joinLines( "search parent {", @@ -361,7 +357,7 @@ public class RankingExpressionTypeResolverTestCase { "search child {", " document child { ", " field ref type reference<parent> {", - "indexing: attribute | summary", + "indexing: attribute | summary", " }", " }", " import field ref.a as imported_a {}", @@ -376,14 +372,14 @@ public class RankingExpressionTypeResolverTestCase { } @Test - public void undeclaredQueryFeaturesAreAccepted() throws Exception { + void undeclaredQueryFeaturesAreAccepted() throws Exception { InspectableDeployLogger logger = new InspectableDeployLogger(); ApplicationBuilder builder = new ApplicationBuilder(logger); builder.addSchema(joinLines( "search test {", " document test { ", " field anyfield type double {" + - " indexing: attribute", + " indexing: attribute", " }", " }", " rank-profile my_rank_profile {", @@ -402,7 +398,7 @@ public class RankingExpressionTypeResolverTestCase { } @Test - public void undeclaredQueryFeaturesAreNotAcceptedWhenStrict() throws Exception { + void undeclaredQueryFeaturesAreNotAcceptedWhenStrict() throws Exception { try { InspectableDeployLogger logger = new InspectableDeployLogger(); ApplicationBuilder builder = new ApplicationBuilder(logger); @@ -410,12 +406,12 @@ public class RankingExpressionTypeResolverTestCase { "search test {", " document test { ", " field anyfield type double {" + - " indexing: attribute", + " indexing: attribute", " }", " }", " rank-profile my_rank_profile {", " strict: true" + - " first-phase {", + " first-phase {", " expression: query(foo) + f() + sum(attribute(anyfield))", " }", " function f() {", @@ -428,12 +424,12 @@ public class RankingExpressionTypeResolverTestCase { } catch (IllegalArgumentException e) { assertEquals("In schema 'test', rank profile 'my_rank_profile': rank profile 'my_rank_profile' is strict but is missing a query profile type declaration of features [query(bar), query(baz), query(foo)]", - Exceptions.toMessageString(e)); + Exceptions.toMessageString(e)); } } @Test - public void undeclaredQueryFeaturesAreAcceptedWithWarningWhenUsingTensors() throws Exception { + void undeclaredQueryFeaturesAreAcceptedWithWarningWhenUsingTensors() throws Exception { InspectableDeployLogger logger = new InspectableDeployLogger(); ApplicationBuilder builder = new ApplicationBuilder(logger); builder.addSchema(joinLines( @@ -457,24 +453,24 @@ public class RankingExpressionTypeResolverTestCase { String message = logger.findMessage("The following query features"); assertNotNull(message); assertEquals("WARNING: The following query features used in rank profile 'my_rank_profile' are not declared and " + - "will be interpreted as scalars, not tensors: [query(bar), query(baz), query(foo)]", - message); + "will be interpreted as scalars, not tensors: [query(bar), query(baz), query(foo)]", + message); } @Test - public void noWarningWhenUsingTensorsWhenQueryFeaturesAreDeclared() throws Exception { + void noWarningWhenUsingTensorsWhenQueryFeaturesAreDeclared() throws Exception { InspectableDeployLogger logger = new InspectableDeployLogger(); ApplicationBuilder builder = new ApplicationBuilder(logger); QueryProfileType myType = new QueryProfileType("mytype"); myType.addField(new FieldDescription("rank.feature.query(foo)", - new TensorFieldType(TensorType.fromSpec("tensor(d[2])"))), - builder.getQueryProfileRegistry().getTypeRegistry()); + new TensorFieldType(TensorType.fromSpec("tensor(d[2])"))), + builder.getQueryProfileRegistry().getTypeRegistry()); myType.addField(new FieldDescription("rank.feature.query(bar)", - new TensorFieldType(TensorType.fromSpec("tensor(d[2])"))), - builder.getQueryProfileRegistry().getTypeRegistry()); + new TensorFieldType(TensorType.fromSpec("tensor(d[2])"))), + builder.getQueryProfileRegistry().getTypeRegistry()); myType.addField(new FieldDescription("rank.feature.query(baz)", - new TensorFieldType(TensorType.fromSpec("tensor(d[2])"))), - builder.getQueryProfileRegistry().getTypeRegistry()); + new TensorFieldType(TensorType.fromSpec("tensor(d[2])"))), + builder.getQueryProfileRegistry().getTypeRegistry()); builder.getQueryProfileRegistry().getTypeRegistry().register(myType); builder.addSchema(joinLines( "search test {", diff --git a/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithLightGBMTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithLightGBMTestCase.java index 4df0a09ec2e..50cc12e9b33 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithLightGBMTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithLightGBMTestCase.java @@ -5,8 +5,8 @@ import com.yahoo.config.application.api.ApplicationPackage; import com.yahoo.io.IOUtils; import com.yahoo.path.Path; import com.yahoo.schema.parser.ParseException; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import java.io.IOException; @@ -20,25 +20,25 @@ public class RankingExpressionWithLightGBMTestCase { private final static String lightGBMExpression = "if (!(numerical_2 >= 0.46643291586559305), 2.1594397038037663, if (categorical_2 in [\"k\", \"l\", \"m\"], 2.235297305276056, 2.1792953471546546)) + if (categorical_1 in [\"d\", \"e\"], 0.03070842919354316, if (!(numerical_1 >= 0.5102250691730842), -0.04439151147520909, 0.005117411709368601)) + if (!(numerical_2 >= 0.668665477622446), if (!(numerical_2 >= 0.008118820676863816), -0.15361238490967524, -0.01192330846157292), 0.03499044894987518) + if (!(numerical_1 >= 0.5201391072644542), -0.02141000620783247, if (categorical_1 in [\"a\", \"b\"], -0.004121485787596721, 0.04534090904886873)) + if (categorical_2 in [\"k\", \"l\", \"m\"], if (!(numerical_2 >= 0.27283279016959255), -0.01924803254356527, 0.03643772842347651), -0.02701711918923075)"; - @After + @AfterEach public void removeGeneratedModelFiles() { IOUtils.recursiveDeleteDir(applicationDir.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile()); } @Test - public void testLightGBMReference() { + void testLightGBMReference() { RankProfileSearchFixture search = fixtureWith("lightgbm('regression.json')"); search.assertFirstPhaseExpression(lightGBMExpression, "my_profile"); } @Test - public void testNestedLightGBMReference() { + void testNestedLightGBMReference() { RankProfileSearchFixture search = fixtureWith("5 + sum(lightgbm('regression.json'))"); search.assertFirstPhaseExpression("5 + reduce(" + lightGBMExpression + ", sum)", "my_profile"); } @Test - public void testImportingFromStoredExpressions() throws IOException { + void testImportingFromStoredExpressions() throws IOException { RankProfileSearchFixture search = fixtureWith("lightgbm('regression.json')"); search.assertFirstPhaseExpression(lightGBMExpression, "my_profile"); @@ -47,7 +47,7 @@ public class RankingExpressionWithLightGBMTestCase { try { storedApplicationDirectory.toFile().mkdirs(); IOUtils.copyDirectory(applicationDir.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile(), - storedApplicationDirectory.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile()); + storedApplicationDirectory.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile()); RankingExpressionWithOnnxTestCase.StoringApplicationPackage storedApplication = new RankingExpressionWithOnnxTestCase.StoringApplicationPackage(storedApplicationDirectory); RankProfileSearchFixture searchFromStored = fixtureWith("lightgbm('regression.json')"); searchFromStored.assertFirstPhaseExpression(lightGBMExpression, "my_profile"); diff --git a/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithOnnxModelTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithOnnxModelTestCase.java index 1280895bfc0..22681858fc3 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithOnnxModelTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithOnnxModelTestCase.java @@ -12,23 +12,23 @@ import com.yahoo.vespa.config.search.core.RankingConstantsConfig; import com.yahoo.vespa.model.VespaModel; import com.yahoo.vespa.model.search.DocumentDatabase; import com.yahoo.vespa.model.search.IndexedSearchCluster; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class RankingExpressionWithOnnxModelTestCase { private final Path applicationDir = Path.fromString("src/test/integration/onnx-model/"); - @After + @AfterEach public void removeGeneratedModelFiles() { IOUtils.recursiveDeleteDir(applicationDir.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile()); } @Test - public void testOnnxModelFeature() throws Exception { + void testOnnxModelFeature() throws Exception { VespaModel model = loadModel(applicationDir); assertTransformedFeature(model); assertGeneratedConfig(model); diff --git a/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithOnnxTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithOnnxTestCase.java index bfd0520c62a..83d19b010bb 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithOnnxTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithOnnxTestCase.java @@ -12,8 +12,8 @@ import com.yahoo.schema.FeatureNames; import com.yahoo.schema.parser.ParseException; import com.yahoo.tensor.TensorType; import com.yahoo.yolean.Exceptions; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.FileReader; @@ -23,10 +23,7 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; public class RankingExpressionWithOnnxTestCase { @@ -35,13 +32,13 @@ public class RankingExpressionWithOnnxTestCase { private final static String name = "mnist_softmax"; private final static String vespaExpression = "join(reduce(join(rename(Placeholder, (d0, d1), (d0, d2)), constant(mnist_softmax_layer_Variable), f(a,b)(a * b)), sum, d2) * 1.0, constant(mnist_softmax_layer_Variable_1) * 1.0, f(a,b)(a + b))"; - @After + @AfterEach public void removeGeneratedModelFiles() { IOUtils.recursiveDeleteDir(applicationDir.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile()); } @Test - public void testOnnxReferenceWithConstantFeature() { + void testOnnxReferenceWithConstantFeature() { RankProfileSearchFixture search = fixtureWith("constant(mytensor)", "onnx_vespa('mnist_softmax.onnx')", "constant mytensor { file: ignored\ntype: tensor<float>(d0[1],d1[784]) }", @@ -50,12 +47,12 @@ public class RankingExpressionWithOnnxTestCase { } @Test - public void testOnnxReferenceWithQueryFeature() { + void testOnnxReferenceWithQueryFeature() { String queryProfile = "<query-profile id='default' type='root'/>"; String queryProfileType = "<query-profile-type id='root'>" + - " <field name='query(mytensor)' type='tensor<float>(d0[1],d1[784])'/>" + - "</query-profile-type>"; + " <field name='query(mytensor)' type='tensor<float>(d0[1],d1[784])'/>" + + "</query-profile-type>"; StoringApplicationPackage application = new StoringApplicationPackage(applicationDir, queryProfile, queryProfileType); @@ -69,7 +66,7 @@ public class RankingExpressionWithOnnxTestCase { } @Test - public void testOnnxReferenceWithDocumentFeature() { + void testOnnxReferenceWithDocumentFeature() { StoringApplicationPackage application = new StoringApplicationPackage(applicationDir); RankProfileSearchFixture search = fixtureWith("attribute(mytensor)", "onnx_vespa('mnist_softmax.onnx')", @@ -82,12 +79,12 @@ public class RankingExpressionWithOnnxTestCase { @Test - public void testOnnxReferenceWithFeatureCombination() { + void testOnnxReferenceWithFeatureCombination() { String queryProfile = "<query-profile id='default' type='root'/>"; String queryProfileType = "<query-profile-type id='root'>" + - " <field name='query(mytensor)' type='tensor<float>(d0[1],d1[784],d2[10])'/>" + - "</query-profile-type>"; + " <field name='query(mytensor)' type='tensor<float>(d0[1],d1[784],d2[10])'/>" + + "</query-profile-type>"; StoringApplicationPackage application = new StoringApplicationPackage(applicationDir, queryProfile, queryProfileType); RankProfileSearchFixture search = fixtureWith("sum(query(mytensor) * attribute(mytensor) * constant(mytensor),d2)", "onnx_vespa('mnist_softmax.onnx')", @@ -100,28 +97,28 @@ public class RankingExpressionWithOnnxTestCase { @Test - public void testNestedOnnxReference() { + void testNestedOnnxReference() { RankProfileSearchFixture search = fixtureWith("tensor<float>(d0[1],d1[784])(0.0)", "5 + sum(onnx_vespa('mnist_softmax.onnx'))"); search.assertFirstPhaseExpression("5 + reduce(" + vespaExpression + ", sum)", "my_profile"); } @Test - public void testOnnxReferenceWithSpecifiedOutput() { + void testOnnxReferenceWithSpecifiedOutput() { RankProfileSearchFixture search = fixtureWith("tensor<float>(d0[1],d1[784])(0.0)", "onnx_vespa('mnist_softmax.onnx', 'layer_add')"); search.assertFirstPhaseExpression(vespaExpression, "my_profile"); } @Test - public void testOnnxReferenceWithSpecifiedOutputAndSignature() { + void testOnnxReferenceWithSpecifiedOutputAndSignature() { RankProfileSearchFixture search = fixtureWith("tensor<float>(d0[1],d1[784])(0.0)", "onnx_vespa('mnist_softmax.onnx', 'default.layer_add')"); search.assertFirstPhaseExpression(vespaExpression, "my_profile"); } @Test - public void testOnnxReferenceMissingFunction() throws ParseException { + void testOnnxReferenceMissingFunction() throws ParseException { try { RankProfileSearchFixture search = new RankProfileSearchFixture( new StoringApplicationPackage(applicationDir), @@ -137,15 +134,15 @@ public class RankingExpressionWithOnnxTestCase { } catch (IllegalArgumentException expected) { assertEquals("Rank profile 'my_profile' is invalid: Could not use Onnx model from " + - "onnx_vespa(\"mnist_softmax.onnx\"): " + - "Model refers input 'Placeholder' of type tensor<float>(d0[1],d1[784]) but this function is " + - "not present in rank profile 'my_profile'", + "onnx_vespa(\"mnist_softmax.onnx\"): " + + "Model refers input 'Placeholder' of type tensor<float>(d0[1],d1[784]) but this function is " + + "not present in rank profile 'my_profile'", Exceptions.toMessageString(expected)); } } @Test - public void testOnnxReferenceWithWrongFunctionType() { + void testOnnxReferenceWithWrongFunctionType() { try { RankProfileSearchFixture search = fixtureWith("tensor(d0[1],d5[10])(0.0)", "onnx_vespa('mnist_softmax.onnx')"); @@ -154,15 +151,15 @@ public class RankingExpressionWithOnnxTestCase { } catch (IllegalArgumentException expected) { assertEquals("Rank profile 'my_profile' is invalid: Could not use Onnx model from " + - "onnx_vespa(\"mnist_softmax.onnx\"): " + - "Model refers input 'Placeholder'. The required type of this is tensor<float>(d0[1],d1[784]), " + - "but this function returns tensor(d0[1],d5[10])", + "onnx_vespa(\"mnist_softmax.onnx\"): " + + "Model refers input 'Placeholder'. The required type of this is tensor<float>(d0[1],d1[784]), " + + "but this function returns tensor(d0[1],d5[10])", Exceptions.toMessageString(expected)); } } @Test - public void testOnnxReferenceSpecifyingNonExistingOutput() { + void testOnnxReferenceSpecifyingNonExistingOutput() { try { RankProfileSearchFixture search = fixtureWith("tensor<float>(d0[2],d1[784])(0.0)", "onnx_vespa('mnist_softmax.onnx', 'y')"); @@ -171,14 +168,14 @@ public class RankingExpressionWithOnnxTestCase { } catch (IllegalArgumentException expected) { assertEquals("Rank profile 'my_profile' is invalid: Could not use Onnx model from " + - "onnx_vespa(\"mnist_softmax.onnx\",\"y\"): " + - "No expressions named 'y' in model 'mnist_softmax.onnx'. Available expressions: default.layer_add", - Exceptions.toMessageString(expected)); + "onnx_vespa(\"mnist_softmax.onnx\",\"y\"): " + + "No expressions named 'y' in model 'mnist_softmax.onnx'. Available expressions: default.layer_add", + Exceptions.toMessageString(expected)); } } @Test - public void testImportingFromStoredExpressions() throws IOException { + void testImportingFromStoredExpressions() throws IOException { RankProfileSearchFixture search = fixtureWith("tensor<float>(d0[1],d1[784])(0.0)", "onnx_vespa(\"mnist_softmax.onnx\")"); search.assertFirstPhaseExpression(vespaExpression, "my_profile"); @@ -206,7 +203,7 @@ public class RankingExpressionWithOnnxTestCase { } @Test - public void testImportingFromStoredExpressionsWithFunctionOverridingConstantAndInheritance() throws IOException { + void testImportingFromStoredExpressionsWithFunctionOverridingConstantAndInheritance() throws IOException { String rankProfile = " rank-profile my_profile {\n" + " function Placeholder() {\n" + @@ -230,8 +227,8 @@ public class RankingExpressionWithOnnxTestCase { search.assertFirstPhaseExpression(vespaExpressionWithoutConstant, "my_profile"); search.assertFirstPhaseExpression(vespaExpressionWithoutConstant, "my_profile_child"); - assertNull("Constant overridden by function is not added", - search.search().constants().get(name + "_Variable")); + assertNull(search.search().constants().get(name + "_Variable"), + "Constant overridden by function is not added"); // At this point the expression is stored - copy application to another location which do not have a models dir Path storedApplicationDirectory = applicationDir.getParentPath().append("copy"); @@ -245,18 +242,18 @@ public class RankingExpressionWithOnnxTestCase { searchFromStored.compileRankProfile("my_profile_child", applicationDir.append("models")); searchFromStored.assertFirstPhaseExpression(vespaExpressionWithoutConstant, "my_profile"); searchFromStored.assertFirstPhaseExpression(vespaExpressionWithoutConstant, "my_profile_child"); - assertNull("Constant overridden by function is not added", - searchFromStored.search().constants().get(name + "_Variable")); + assertNull(searchFromStored.search().constants().get(name + "_Variable"), + "Constant overridden by function is not added"); } finally { IOUtils.recursiveDeleteDir(storedApplicationDirectory.toFile()); } } @Test - public void testFunctionGeneration() { + void testFunctionGeneration() { final String name = "small_constants_and_functions"; final String rankProfiles = - " rank-profile my_profile {\n" + + " rank-profile my_profile {\n" + " function input() {\n" + " expression: tensor<float>(d0[3])(0.0)\n" + " }\n" + @@ -275,7 +272,7 @@ public class RankingExpressionWithOnnxTestCase { } @Test - public void testImportingFromStoredExpressionsWithSmallConstantsAndInheritance() throws IOException { + void testImportingFromStoredExpressionsWithSmallConstantsAndInheritance() throws IOException { final String name = "small_constants_and_functions"; final String rankProfiles = " rank-profile my_profile {\n" + diff --git a/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithTensorTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithTensorTestCase.java index 1f065bc7a20..c5bd0821007 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithTensorTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithTensorTestCase.java @@ -2,10 +2,10 @@ package com.yahoo.schema.processing; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author geirst @@ -13,16 +13,16 @@ import static org.junit.Assert.fail; public class RankingExpressionWithTensorTestCase { @Test - public void requireThatSingleLineConstantMappedTensorCanBeParsed() throws ParseException { + void requireThatSingleLineConstantMappedTensorCanBeParsed() throws ParseException { RankProfileSearchFixture f = new RankProfileSearchFixture( " rank-profile my_profile {\n" + - " first-phase {\n" + - " expression: sum(my_tensor)\n" + - " }\n" + - " constants {\n" + - " my_tensor tensor(x{},y{}):{ {x:1,y:2}:1, {x:2,y:1}:2 }\n" + - " }\n" + - " }"); + " first-phase {\n" + + " expression: sum(my_tensor)\n" + + " }\n" + + " constants {\n" + + " my_tensor tensor(x{},y{}):{ {x:1,y:2}:1, {x:2,y:1}:2 }\n" + + " }\n" + + " }"); f.compileRankProfile("my_profile"); f.assertFirstPhaseExpression("reduce(constant(my_tensor), sum)", "my_profile"); f.assertRankProperty("tensor(x{},y{}):{{x:1,y:2}:1.0, {x:2,y:1}:2.0}", "constant(my_tensor).value", "my_profile"); @@ -30,16 +30,16 @@ public class RankingExpressionWithTensorTestCase { } @Test - public void requireThatSingleLineConstantIndexedTensorCanBeParsed() throws ParseException { + void requireThatSingleLineConstantIndexedTensorCanBeParsed() throws ParseException { RankProfileSearchFixture f = new RankProfileSearchFixture( " rank-profile my_profile {\n" + - " first-phase {\n" + - " expression: sum(my_tensor)\n" + - " }\n" + - " constants {\n" + - " my_tensor tensor(x[3]):{ {x:0}:1, {x:1}:2, {x:2}:3 }\n" + - " }\n" + - " }"); + " first-phase {\n" + + " expression: sum(my_tensor)\n" + + " }\n" + + " constants {\n" + + " my_tensor tensor(x[3]):{ {x:0}:1, {x:1}:2, {x:2}:3 }\n" + + " }\n" + + " }"); f.compileRankProfile("my_profile"); f.assertFirstPhaseExpression("reduce(constant(my_tensor), sum)", "my_profile"); f.assertRankProperty("tensor(x[3]):[1.0, 2.0, 3.0]", "constant(my_tensor).value", "my_profile"); @@ -47,16 +47,16 @@ public class RankingExpressionWithTensorTestCase { } @Test - public void requireThatSingleLineConstantIndexedTensorShortFormCanBeParsed() throws ParseException { + void requireThatSingleLineConstantIndexedTensorShortFormCanBeParsed() throws ParseException { RankProfileSearchFixture f = new RankProfileSearchFixture( " rank-profile my_profile {\n" + - " first-phase {\n" + - " expression: sum(my_tensor)\n" + - " }\n" + - " constants {\n" + - " my_tensor tensor(x[3]):[1, 2, 3]\n" + - " }\n" + - " }"); + " first-phase {\n" + + " expression: sum(my_tensor)\n" + + " }\n" + + " constants {\n" + + " my_tensor tensor(x[3]):[1, 2, 3]\n" + + " }\n" + + " }"); f.compileRankProfile("my_profile"); f.assertFirstPhaseExpression("reduce(constant(my_tensor), sum)", "my_profile"); f.assertRankProperty("tensor(x[3]):[1.0, 2.0, 3.0]", "constant(my_tensor).value", "my_profile"); @@ -64,16 +64,16 @@ public class RankingExpressionWithTensorTestCase { } @Test - public void requireConstantTensorCanBeReferredViaConstantFeature() throws ParseException { + void requireConstantTensorCanBeReferredViaConstantFeature() throws ParseException { RankProfileSearchFixture f = new RankProfileSearchFixture( " rank-profile my_profile {\n" + - " first-phase {\n" + - " expression: sum(constant(my_tensor))\n" + - " }\n" + - " constants {\n" + - " my_tensor tensor(x{},y{}):{{x:1,y:2}:1, {x:2,y:1}:2}\n" + - " }\n" + - " }"); + " first-phase {\n" + + " expression: sum(constant(my_tensor))\n" + + " }\n" + + " constants {\n" + + " my_tensor tensor(x{},y{}):{{x:1,y:2}:1, {x:2,y:1}:2}\n" + + " }\n" + + " }"); f.compileRankProfile("my_profile"); f.assertFirstPhaseExpression("reduce(constant(my_tensor), sum)", "my_profile"); f.assertRankProperty("tensor(x{},y{}):{{x:1,y:2}:1.0, {x:2,y:1}:2.0}", "constant(my_tensor).value", "my_profile"); @@ -81,18 +81,18 @@ public class RankingExpressionWithTensorTestCase { } @Test - public void requireThatMultiLineConstantTensorAndTypeCanBeParsed() throws ParseException { + void requireThatMultiLineConstantTensorAndTypeCanBeParsed() throws ParseException { RankProfileSearchFixture f = new RankProfileSearchFixture( " rank-profile my_profile {\n" + - " first-phase {\n" + - " expression: sum(my_tensor)\n" + - " }\n" + - " constants {\n" + - " my_tensor tensor(x{},y{}):\n" + - " { {x:1,y:2}:1,\n" + - " {x:2,y:1}:2 }\n" + - " }\n" + - " }"); + " first-phase {\n" + + " expression: sum(my_tensor)\n" + + " }\n" + + " constants {\n" + + " my_tensor tensor(x{},y{}):\n" + + " { {x:1,y:2}:1,\n" + + " {x:2,y:1}:2 }\n" + + " }\n" + + " }"); f.compileRankProfile("my_profile"); f.assertFirstPhaseExpression("reduce(constant(my_tensor), sum)", "my_profile"); f.assertRankProperty("tensor(x{},y{}):{{x:1,y:2}:1.0, {x:2,y:1}:2.0}", "constant(my_tensor).value", "my_profile"); @@ -100,16 +100,16 @@ public class RankingExpressionWithTensorTestCase { } @Test - public void requireThatConstantTensorsCanBeUsedInSecondPhaseExpression() throws ParseException { + void requireThatConstantTensorsCanBeUsedInSecondPhaseExpression() throws ParseException { RankProfileSearchFixture f = new RankProfileSearchFixture( " rank-profile my_profile {\n" + - " second-phase {\n" + - " expression: sum(my_tensor)\n" + - " }\n" + - " constants {\n" + - " my_tensor tensor(x{}):{ {x:1}:1 }\n" + - " }\n" + - " }"); + " second-phase {\n" + + " expression: sum(my_tensor)\n" + + " }\n" + + " constants {\n" + + " my_tensor tensor(x{}):{ {x:1}:1 }\n" + + " }\n" + + " }"); f.compileRankProfile("my_profile"); f.assertSecondPhaseExpression("reduce(constant(my_tensor), sum)", "my_profile"); f.assertRankProperty("tensor(x{}):{1:1.0}", "constant(my_tensor).value", "my_profile"); @@ -117,20 +117,20 @@ public class RankingExpressionWithTensorTestCase { } @Test - public void requireThatConstantTensorsCanBeUsedInInheritedRankProfile() throws ParseException { + void requireThatConstantTensorsCanBeUsedInInheritedRankProfile() throws ParseException { RankProfileSearchFixture f = new RankProfileSearchFixture( " rank-profile parent {\n" + - " constants {\n" + - " my_tensor {\n" + - " value: { {x:1}:1 }\n" + - " }\n" + - " }\n" + - " }\n" + - " rank-profile my_profile inherits parent {\n" + - " first-phase {\n" + - " expression: sum(my_tensor)\n" + - " }\n" + - " }"); + " constants {\n" + + " my_tensor {\n" + + " value: { {x:1}:1 }\n" + + " }\n" + + " }\n" + + " }\n" + + " rank-profile my_profile inherits parent {\n" + + " first-phase {\n" + + " expression: sum(my_tensor)\n" + + " }\n" + + " }"); f.compileRankProfile("my_profile"); f.assertFirstPhaseExpression("reduce(constant(my_tensor), sum)", "my_profile"); f.assertRankProperty("tensor(x{}):{1:1.0}", "constant(my_tensor).value", "my_profile"); @@ -138,19 +138,19 @@ public class RankingExpressionWithTensorTestCase { } @Test - public void requireThatConstantTensorsCanBeUsedInFunction() throws ParseException { + void requireThatConstantTensorsCanBeUsedInFunction() throws ParseException { RankProfileSearchFixture f = new RankProfileSearchFixture( " rank-profile my_profile {\n" + - " function my_macro() {\n" + - " expression: sum(my_tensor)\n" + - " }\n" + - " first-phase {\n" + - " expression: 5.0 + my_macro\n" + - " }\n" + - " constants {\n" + - " my_tensor tensor(x{}):{ {x:1}:1 }\n" + - " }\n" + - " }"); + " function my_macro() {\n" + + " expression: sum(my_tensor)\n" + + " }\n" + + " first-phase {\n" + + " expression: 5.0 + my_macro\n" + + " }\n" + + " constants {\n" + + " my_tensor tensor(x{}):{ {x:1}:1 }\n" + + " }\n" + + " }"); f.compileRankProfile("my_profile"); f.assertFirstPhaseExpression("5.0 + my_macro", "my_profile"); f.assertFunction("reduce(constant(my_tensor), sum)", "my_macro", "my_profile"); @@ -159,18 +159,18 @@ public class RankingExpressionWithTensorTestCase { } @Test - public void requireThatCombinationOfConstantTensorsAndConstantValuesCanBeUsed() throws ParseException { + void requireThatCombinationOfConstantTensorsAndConstantValuesCanBeUsed() throws ParseException { RankProfileSearchFixture f = new RankProfileSearchFixture( " rank-profile my_profile {\n" + - " first-phase {\n" + - " expression: my_number_1 + sum(my_tensor) + my_number_2\n" + - " }\n" + - " constants {\n" + - " my_number_1 double: 3.0\n" + - " my_tensor tensor(x{}):{ {x:1}:1 }\n" + - " my_number_2 double: 5.0\n" + - " }\n" + - " }"); + " first-phase {\n" + + " expression: my_number_1 + sum(my_tensor) + my_number_2\n" + + " }\n" + + " constants {\n" + + " my_number_1 double: 3.0\n" + + " my_tensor tensor(x{}):{ {x:1}:1 }\n" + + " my_number_2 double: 5.0\n" + + " }\n" + + " }"); f.compileRankProfile("my_profile"); f.assertFirstPhaseExpression("3.0 + reduce(constant(my_tensor), sum) + 5.0", "my_profile"); f.assertRankProperty("tensor(x{}):{1:1.0}", "constant(my_tensor).value", "my_profile"); @@ -178,20 +178,20 @@ public class RankingExpressionWithTensorTestCase { } @Test - public void requireThatInvalidTensorTypeSpecThrowsException() throws ParseException { + void requireThatInvalidTensorTypeSpecThrowsException() throws ParseException { try { RankProfileSearchFixture f = new RankProfileSearchFixture( " rank-profile my_profile {\n" + - " constants {\n" + - " my_tensor tensor(x):{ {x:1}:1 }\n" + - " }\n" + - " }"); + " constants {\n" + + " my_tensor tensor(x):{ {x:1}:1 }\n" + + " }\n" + + " }"); f.compileRankProfile("my_profile"); fail("Expected exception"); } catch (IllegalArgumentException e) { assertStartsWith("Type of constant(my_tensor): Illegal tensor type spec: A tensor type spec must be on the form", - e.getMessage()); + e.getMessage()); } } diff --git a/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithTransformerTokensTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithTransformerTokensTestCase.java index f8086fb3bc6..5c82be0745e 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithTransformerTokensTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithTransformerTokensTestCase.java @@ -17,16 +17,16 @@ import com.yahoo.searchlib.rankingexpression.RankingExpression; import com.yahoo.searchlib.rankingexpression.evaluation.MapContext; import com.yahoo.searchlib.rankingexpression.evaluation.TensorValue; import com.yahoo.tensor.Tensor; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Collections; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class RankingExpressionWithTransformerTokensTestCase { @Test - public void testTokenInputIds() throws Exception { + void testTokenInputIds() throws Exception { String expected = "tensor(d0[1],d1[12]):[101,1,2,102,3,4,5,102,6,7,102,0]"; String a = "tensor(d0[2]):[1,2]"; String b = "tensor(d0[3]):[3,4,5]"; @@ -37,7 +37,7 @@ public class RankingExpressionWithTransformerTokensTestCase { } @Test - public void testTokenTypeIds() throws Exception { + void testTokenTypeIds() throws Exception { String expected = "tensor(d0[1],d1[10]):[0,0,0,0,1,1,1,1,0,0]"; String a = "tensor(d0[2]):[1,2]"; String b = "tensor(d0[3]):[3,4,5]"; @@ -47,7 +47,7 @@ public class RankingExpressionWithTransformerTokensTestCase { } @Test - public void testAttentionMask() throws Exception { + void testAttentionMask() throws Exception { String expected = "tensor(d0[1],d1[10]):[1,1,1,1,1,1,1,1,0,0]"; String a = "tensor(d0[2]):[1,2]"; String b = "tensor(d0[3]):[3,4,5]"; diff --git a/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithXGBoostTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithXGBoostTestCase.java index e1b1473a59a..d01bb1be377 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithXGBoostTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithXGBoostTestCase.java @@ -5,8 +5,8 @@ import com.yahoo.config.application.api.ApplicationPackage; import com.yahoo.io.IOUtils; import com.yahoo.path.Path; import com.yahoo.schema.parser.ParseException; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import java.io.IOException; @@ -22,25 +22,25 @@ public class RankingExpressionWithXGBoostTestCase { "if (f29 < -0.1234567, if (!(f56 >= -0.242398), 1.71218, -1.70044), if (f109 < 0.8723473, -1.94071, 1.85965)) + " + "if (!(f60 >= -0.482947), if (f29 < -4.2387498, 0.784718, -0.96853), -6.23624)"; - @After + @AfterEach public void removeGeneratedModelFiles() { IOUtils.recursiveDeleteDir(applicationDir.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile()); } @Test - public void testXGBoostReference() { + void testXGBoostReference() { RankProfileSearchFixture search = fixtureWith("xgboost('xgboost.2.2.json')"); search.assertFirstPhaseExpression(vespaExpression, "my_profile"); } @Test - public void testNestedXGBoostReference() { + void testNestedXGBoostReference() { RankProfileSearchFixture search = fixtureWith("5 + sum(xgboost('xgboost.2.2.json'))"); search.assertFirstPhaseExpression("5 + reduce(" + vespaExpression + ", sum)", "my_profile"); } @Test - public void testImportingFromStoredExpressions() throws IOException { + void testImportingFromStoredExpressions() throws IOException { RankProfileSearchFixture search = fixtureWith("xgboost('xgboost.2.2.json')"); search.assertFirstPhaseExpression(vespaExpression, "my_profile"); @@ -49,7 +49,7 @@ public class RankingExpressionWithXGBoostTestCase { try { storedApplicationDirectory.toFile().mkdirs(); IOUtils.copyDirectory(applicationDir.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile(), - storedApplicationDirectory.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile()); + storedApplicationDirectory.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile()); RankingExpressionWithOnnxTestCase.StoringApplicationPackage storedApplication = new RankingExpressionWithOnnxTestCase.StoringApplicationPackage(storedApplicationDirectory); RankProfileSearchFixture searchFromStored = fixtureWith("xgboost('xgboost.2.2.json')"); searchFromStored.assertFirstPhaseExpression(vespaExpression, "my_profile"); diff --git a/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionsTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionsTestCase.java index c985d427a5a..526576c9e0b 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionsTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionsTestCase.java @@ -18,15 +18,14 @@ import com.yahoo.schema.derived.RawRankProfile; import com.yahoo.schema.derived.TestableDeployLogger; import com.yahoo.schema.parser.ParseException; import ai.vespa.rankingexpression.importer.configmodelview.ImportedMlModels; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.Map; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class RankingExpressionsTestCase extends AbstractSchemaTestCase { @@ -35,7 +34,7 @@ public class RankingExpressionsTestCase extends AbstractSchemaTestCase { } @Test - public void testFunctions() throws IOException, ParseException { + void testFunctions() throws IOException, ParseException { ModelContext.Properties deployProperties = new TestProperties(); RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); Schema schema = createSearch("src/test/examples/rankingexpressionfunction", deployProperties, rankProfileRegistry); @@ -46,13 +45,13 @@ public class RankingExpressionsTestCase extends AbstractSchemaTestCase { assertEquals("var2", functions.get("titlematch").function().arguments().get(1)); assertEquals("var1 * var2 + 890", functions.get("titlematch").function().getBody().getRoot().toString()); assertEquals("0.8 + 0.2 * titlematch(4,5) + 0.8 * titlematch(7,8) * closeness(distance)", - functionsRankProfile.getFirstPhaseRanking().getRoot().toString()); + functionsRankProfile.getFirstPhaseRanking().getRoot().toString()); assertEquals("78 + closeness(distance)", - functions.get("artistmatch").function().getBody().getRoot().toString()); + functions.get("artistmatch").function().getBody().getRoot().toString()); assertEquals(0, functions.get("artistmatch").function().arguments().size()); RawRankProfile rawRankProfile = new RawRankProfile(functionsRankProfile, new LargeRankExpressions(new MockFileRegistry()), new QueryProfileRegistry(), - new ImportedMlModels(), new AttributeFields(schema), deployProperties); + new ImportedMlModels(), new AttributeFields(schema), deployProperties); List<Pair<String, String>> rankProperties = rawRankProfile.configProperties(); assertEquals(6, rankProperties.size()); @@ -72,11 +71,13 @@ public class RankingExpressionsTestCase extends AbstractSchemaTestCase { assertEquals("4 * 5 + 890", rankProperties.get(0).getSecond()); } - @Test(expected = IllegalArgumentException.class) - public void testThatIncludingFileInSubdirFails() throws IOException, ParseException { - RankProfileRegistry registry = new RankProfileRegistry(); - Schema schema = createSearch("src/test/examples/rankingexpressioninfile", new TestProperties(), registry); - new DerivedConfiguration(schema, registry); // rank profile parsing happens during deriving + @Test + void testThatIncludingFileInSubdirFails() throws IOException, ParseException { + assertThrows(IllegalArgumentException.class, () -> { + RankProfileRegistry registry = new RankProfileRegistry(); + Schema schema = createSearch("src/test/examples/rankingexpressioninfile", new TestProperties(), registry); + new DerivedConfiguration(schema, registry); // rank profile parsing happens during deriving + }); // rank profile parsing happens during deriving } private void verifyProfile(RankProfile profile, List<String> expectedFunctions, List<Pair<String, String>> rankProperties, @@ -114,7 +115,7 @@ public class RankingExpressionsTestCase extends AbstractSchemaTestCase { } @Test - public void testLargeInheritedFunctions() throws IOException, ParseException { + void testLargeInheritedFunctions() throws IOException, ParseException { ModelContext.Properties properties = new TestProperties(); RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); LargeRankExpressions largeExpressions = new LargeRankExpressions(new MockFileRegistry(), 50); diff --git a/config-model/src/test/java/com/yahoo/schema/processing/ReferenceFieldTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/ReferenceFieldTestCase.java index 57b4d928a52..5f26e7b2964 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/ReferenceFieldTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/ReferenceFieldTestCase.java @@ -9,43 +9,35 @@ import com.yahoo.schema.Schema; import com.yahoo.schema.ApplicationBuilder; import com.yahoo.schema.document.SDDocumentType; import com.yahoo.schema.parser.ParseException; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * @author bjorncs */ public class ReferenceFieldTestCase { - @SuppressWarnings("deprecation") - @Rule - public final ExpectedException exceptionRule = ExpectedException.none(); - @Test - public void reference_fields_are_parsed_from_search_definition() throws ParseException { + void reference_fields_are_parsed_from_search_definition() throws ParseException { ApplicationBuilder builder = new ApplicationBuilder(); String campaignSdContent = "schema campaign {\n" + - " document campaign {\n" + - " }\n" + - "}"; + " document campaign {\n" + + " }\n" + + "}"; String salespersonSdContent = "schema salesperson {\n" + - " document salesperson {\n" + - " }\n" + - "}"; + " document salesperson {\n" + + " }\n" + + "}"; String adSdContent = "schema ad {\n" + - " document ad {\n" + - " field campaign_ref type reference<campaign> { indexing: attribute }\n" + - " field salesperson_ref type reference<salesperson> { indexing: attribute }\n" + - " }\n" + - "}"; + " document ad {\n" + + " field campaign_ref type reference<campaign> { indexing: attribute }\n" + + " field salesperson_ref type reference<salesperson> { indexing: attribute }\n" + + " }\n" + + "}"; builder.addSchema(campaignSdContent); builder.addSchema(salespersonSdContent); builder.addSchema(adSdContent); @@ -56,37 +48,38 @@ public class ReferenceFieldTestCase { } @Test - public void cyclic_document_dependencies_are_detected() throws ParseException { - var builder = new ApplicationBuilder(new TestProperties()); - String campaignSdContent = - "schema campaign {\n" + - " document campaign {\n" + - " field ad_ref type reference<ad> { indexing: attribute }\n" + - " }\n" + - "}"; - String adSdContent = - "schema ad {\n" + - " document ad {\n" + - " field campaign_ref type reference<campaign> { indexing: attribute }\n" + - " }\n" + - "}"; - builder.addSchema(campaignSdContent); - builder.addSchema(adSdContent); - exceptionRule.expect(IllegalArgumentException.class); - exceptionRule.expectMessage("reference cycle for documents"); - builder.build(true); + void cyclic_document_dependencies_are_detected() throws ParseException { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + var builder = new ApplicationBuilder(new TestProperties()); + String campaignSdContent = + "schema campaign {\n" + + " document campaign {\n" + + " field ad_ref type reference<ad> { indexing: attribute }\n" + + " }\n" + + "}"; + String adSdContent = + "schema ad {\n" + + " document ad {\n" + + " field campaign_ref type reference<campaign> { indexing: attribute }\n" + + " }\n" + + "}"; + builder.addSchema(campaignSdContent); + builder.addSchema(adSdContent); + builder.build(true); + }); + assertTrue(exception.getMessage().contains("reference cycle for documents")); } private static void assertSearchContainsReferenceField(String expectedFieldname, String referencedDocType, SDDocumentType documentType) { Field field = documentType.getDocumentType().getField(expectedFieldname); - assertNotNull("Field does not exist in document type: " + expectedFieldname, field); + assertNotNull(field, "Field does not exist in document type: " + expectedFieldname); DataType dataType = field.getDataType(); assertTrue(dataType instanceof NewDocumentReferenceDataType); NewDocumentReferenceDataType refField = (NewDocumentReferenceDataType) dataType; assertEquals(referencedDocType, refField.getTargetTypeName()); - assertTrue(! refField.isTemporary()); + assertFalse(refField.isTemporary()); } } diff --git a/config-model/src/test/java/com/yahoo/schema/processing/ReservedDocumentNamesTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/ReservedDocumentNamesTestCase.java index 974d8c261ca..404b8f648cf 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/ReservedDocumentNamesTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/ReservedDocumentNamesTestCase.java @@ -3,12 +3,12 @@ package com.yahoo.schema.processing; import com.yahoo.schema.derived.AbstractExportingTestCase; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Simon Thoresen Hult @@ -16,7 +16,7 @@ import static org.junit.Assert.fail; public class ReservedDocumentNamesTestCase extends AbstractExportingTestCase { @Test - public void requireThatPositionIsAReservedDocumentName() throws IOException, ParseException { + void requireThatPositionIsAReservedDocumentName() throws IOException, ParseException { try { assertCorrectDeriving("reserved_position"); fail(); diff --git a/config-model/src/test/java/com/yahoo/schema/processing/ReservedRankingExpressionFunctionNamesTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/ReservedRankingExpressionFunctionNamesTestCase.java index e405a105f3c..f657efffde7 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/ReservedRankingExpressionFunctionNamesTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/ReservedRankingExpressionFunctionNamesTestCase.java @@ -5,12 +5,12 @@ import com.yahoo.config.application.api.DeployLogger; import com.yahoo.schema.RankProfileRegistry; import com.yahoo.schema.ApplicationBuilder; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.logging.Level; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author lesters @@ -18,7 +18,7 @@ import static org.junit.Assert.assertTrue; public class ReservedRankingExpressionFunctionNamesTestCase { @Test - public void requireThatFunctionsWithReservedNamesIssueAWarning() throws ParseException { + void requireThatFunctionsWithReservedNamesIssueAWarning() throws ParseException { TestDeployLogger deployLogger = new TestDeployLogger(); RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); ApplicationBuilder builder = new ApplicationBuilder(deployLogger, rankProfileRegistry); diff --git a/config-model/src/test/java/com/yahoo/schema/processing/SchemaMustHaveDocumentTest.java b/config-model/src/test/java/com/yahoo/schema/processing/SchemaMustHaveDocumentTest.java index 03f9d7c5960..6e5e17398d9 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/SchemaMustHaveDocumentTest.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/SchemaMustHaveDocumentTest.java @@ -3,11 +3,11 @@ package com.yahoo.schema.processing; import com.yahoo.schema.ApplicationBuilder; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.fail; /** * @author hmusum @@ -15,13 +15,13 @@ import static org.junit.Assert.fail; public class SchemaMustHaveDocumentTest { @Test - public void requireErrorWhenMissingDocument() throws IOException, ParseException { + void requireErrorWhenMissingDocument() throws IOException, ParseException { try { ApplicationBuilder.buildFromFile("src/test/examples/invalid_sd_missing_document.sd"); fail("SD without document"); } catch (IllegalArgumentException e) { if (!e.getMessage() - .contains("For schema 'imageconfig': A search specification must have an equally named document inside of it.")) { + .contains("For schema 'imageconfig': A search specification must have an equally named document inside of it.")) { throw e; } } diff --git a/config-model/src/test/java/com/yahoo/schema/processing/SummaryConsistencyTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/SummaryConsistencyTestCase.java index 76132a4d09f..c5f0fb49946 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/SummaryConsistencyTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/SummaryConsistencyTestCase.java @@ -5,15 +5,15 @@ import com.yahoo.schema.Schema; import com.yahoo.schema.ApplicationBuilder; import com.yahoo.schema.parser.ParseException; import com.yahoo.vespa.documentmodel.SummaryTransform; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static com.yahoo.config.model.test.TestUtil.joinLines; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class SummaryConsistencyTestCase { @Test - public void attribute_combiner_transform_is_set_when_source_is_array_of_struct_with_only_struct_field_attributes() throws ParseException { + void attribute_combiner_transform_is_set_when_source_is_array_of_struct_with_only_struct_field_attributes() throws ParseException { String sd = joinLines( "search structmemorysummary {", " document structmemorysummary {", diff --git a/config-model/src/test/java/com/yahoo/schema/processing/SummaryFieldsMustHaveValidSourceTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/SummaryFieldsMustHaveValidSourceTestCase.java index d94815015d7..22151063eb7 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/SummaryFieldsMustHaveValidSourceTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/SummaryFieldsMustHaveValidSourceTestCase.java @@ -9,17 +9,17 @@ import com.yahoo.schema.ApplicationBuilder; import com.yahoo.schema.AbstractSchemaTestCase; import com.yahoo.schema.parser.ParseException; import com.yahoo.vespa.model.container.search.QueryProfiles; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; public class SummaryFieldsMustHaveValidSourceTestCase extends AbstractSchemaTestCase { @Test - public void requireThatInvalidSourceIsCaught() throws IOException, ParseException { + void requireThatInvalidSourceIsCaught() throws IOException, ParseException { try { ApplicationBuilder.buildFromFile("src/test/examples/invalidsummarysource.sd"); fail("This should throw and never get here"); @@ -29,7 +29,7 @@ public class SummaryFieldsMustHaveValidSourceTestCase extends AbstractSchemaTest } @Test - public void requireThatInvalidImplicitSourceIsCaught() throws IOException, ParseException { + void requireThatInvalidImplicitSourceIsCaught() throws IOException, ParseException { try { ApplicationBuilder.buildFromFile("src/test/examples/invalidimplicitsummarysource.sd"); fail("This should throw and never get here"); @@ -39,7 +39,7 @@ public class SummaryFieldsMustHaveValidSourceTestCase extends AbstractSchemaTest } @Test - public void requireThatInvalidSelfReferingSingleSource() throws IOException, ParseException { + void requireThatInvalidSelfReferingSingleSource() throws IOException, ParseException { try { ApplicationBuilder.buildFromFile("src/test/examples/invalidselfreferringsummary.sd"); fail("This should throw and never get here"); @@ -49,7 +49,7 @@ public class SummaryFieldsMustHaveValidSourceTestCase extends AbstractSchemaTest } @Test - public void requireThatDocumentIdIsAllowedToPass() throws IOException, ParseException { + void requireThatDocumentIdIsAllowedToPass() throws IOException, ParseException { Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/documentidinsummary.sd"); BaseDeployLogger deployLogger = new BaseDeployLogger(); RankProfileRegistry rankProfileRegistry = new RankProfileRegistry(); diff --git a/config-model/src/test/java/com/yahoo/schema/processing/TensorFieldTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/TensorFieldTestCase.java index 9164f361a92..60e1e35fb2e 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/TensorFieldTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/TensorFieldTestCase.java @@ -3,15 +3,12 @@ package com.yahoo.schema.processing; import com.yahoo.schema.document.Attribute; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static com.yahoo.schema.ApplicationBuilder.createFromString; import static com.yahoo.config.model.test.TestUtil.joinLines; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; /** * @author geirst @@ -19,32 +16,32 @@ import static org.junit.Assert.fail; public class TensorFieldTestCase { @Test - public void requireThatTensorFieldCannotBeOfCollectionType() throws ParseException { + void requireThatTensorFieldCannotBeOfCollectionType() throws ParseException { try { createFromString(getSd("field f1 type array<tensor(x{})> {}")); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("For schema 'test', field 'f1': A field with collection type of tensor is not supported. Use simple type 'tensor' instead.", - e.getMessage()); + e.getMessage()); } } @Test - public void requireThatTensorFieldCannotBeIndexField() throws ParseException { + void requireThatTensorFieldCannotBeIndexField() throws ParseException { try { createFromString(getSd("field f1 type tensor(x{}) { indexing: index }")); fail("Expected exception"); } catch (IllegalArgumentException e) { assertEquals("For schema 'test', field 'f1': A tensor of type 'tensor(x{})' does not support having an 'index'. " + - "Currently, only tensors with 1 indexed dimension supports that.", - e.getMessage()); + "Currently, only tensors with 1 indexed dimension supports that.", + e.getMessage()); } } @Test - public void requireThatIndexedTensorAttributeCannotBeFastSearch() throws ParseException { + void requireThatIndexedTensorAttributeCannotBeFastSearch() throws ParseException { try { createFromString(getSd("field f1 type tensor(x[3]) { indexing: attribute \n attribute: fast-search }")); fail("Expected exception"); @@ -55,7 +52,7 @@ public class TensorFieldTestCase { } @Test - public void requireThatIndexedTensorAttributeCannotBeFastRank() throws ParseException { + void requireThatIndexedTensorAttributeCannotBeFastRank() throws ParseException { try { createFromString(getSd("field f1 type tensor(x[3]) { indexing: attribute \n attribute: fast-rank }")); fail("Expected exception"); @@ -66,7 +63,7 @@ public class TensorFieldTestCase { } @Test - public void requireThatIllegalTensorTypeSpecThrowsException() throws ParseException { + void requireThatIllegalTensorTypeSpecThrowsException() throws ParseException { try { createFromString(getSd("field f1 type tensor(invalid) { indexing: attribute }")); fail("Expected exception"); @@ -77,19 +74,19 @@ public class TensorFieldTestCase { } @Test - public void hnsw_index_is_default_turned_off() throws ParseException { + void hnsw_index_is_default_turned_off() throws ParseException { var attr = getAttributeFromSd("field t1 type tensor(x[64]) { indexing: attribute }", "t1"); assertFalse(attr.hnswIndexParams().isPresent()); } @Test - public void hnsw_index_gets_default_parameters_if_not_specified() throws ParseException { + void hnsw_index_gets_default_parameters_if_not_specified() throws ParseException { assertHnswIndexParams("", 16, 200); assertHnswIndexParams("index: hnsw", 16, 200); } @Test - public void hnsw_index_parameters_can_be_specified() throws ParseException { + void hnsw_index_parameters_can_be_specified() throws ParseException { assertHnswIndexParams("index { hnsw { max-links-per-node: 32 } }", 32, 200); assertHnswIndexParams("index { hnsw { neighbors-to-explore-at-insert: 300 } }", 16, 300); assertHnswIndexParams(joinLines("index {", @@ -102,7 +99,7 @@ public class TensorFieldTestCase { } @Test - public void tensor_with_hnsw_index_must_be_an_attribute() throws ParseException { + void tensor_with_hnsw_index_must_be_an_attribute() throws ParseException { try { createFromString(getSd("field t1 type tensor(x[64]) { indexing: index }")); fail("Expected exception"); @@ -113,7 +110,7 @@ public class TensorFieldTestCase { } @Test - public void tensor_with_hnsw_index_parameters_must_be_an_index() throws ParseException { + void tensor_with_hnsw_index_parameters_must_be_an_index() throws ParseException { try { createFromString(getSd(joinLines( "field t1 type tensor(x[64]) {", @@ -132,7 +129,7 @@ public class TensorFieldTestCase { } @Test - public void tensors_with_at_least_one_mapped_dimension_can_be_direct() throws ParseException { + void tensors_with_at_least_one_mapped_dimension_can_be_direct() throws ParseException { assertTrue(getAttributeFromSd( "field t1 type tensor(x{}) { indexing: attribute \n attribute: fast-search }", "t1").isFastSearch()); assertTrue(getAttributeFromSd( @@ -140,7 +137,7 @@ public class TensorFieldTestCase { } @Test - public void tensors_with_at_least_one_mapped_dimension_can_be_fast_rank() throws ParseException { + void tensors_with_at_least_one_mapped_dimension_can_be_fast_rank() throws ParseException { assertTrue(getAttributeFromSd( "field t1 type tensor(x{}) { indexing: attribute \n attribute: fast-rank }", "t1").isFastRank()); assertTrue(getAttributeFromSd( diff --git a/config-model/src/test/java/com/yahoo/schema/processing/TensorTransformTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/TensorTransformTestCase.java index aaf5f381c62..028ad5dea86 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/TensorTransformTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/TensorTransformTestCase.java @@ -20,109 +20,109 @@ import com.yahoo.schema.derived.AttributeFields; import com.yahoo.schema.derived.RawRankProfile; import com.yahoo.schema.parser.ParseException; import ai.vespa.rankingexpression.importer.configmodelview.ImportedMlModels; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; public class TensorTransformTestCase extends AbstractSchemaTestCase { @Test - public void requireThatNormalMaxAndMinAreNotReplaced() throws ParseException { + void requireThatNormalMaxAndMinAreNotReplaced() throws ParseException { assertTransformedExpression("max(1.0,2.0)", - "max(1.0,2.0)"); + "max(1.0,2.0)"); assertTransformedExpression("min(attribute(double_field),x)", - "min(attribute(double_field),x)"); + "min(attribute(double_field),x)"); assertTransformedExpression("max(attribute(double_field),attribute(double_array_field))", - "max(attribute(double_field),attribute(double_array_field))"); + "max(attribute(double_field),attribute(double_array_field))"); assertTransformedExpression("min(attribute(tensor_field_1),attribute(double_field))", - "min(attribute(tensor_field_1),attribute(double_field))"); + "min(attribute(tensor_field_1),attribute(double_field))"); assertTransformedExpression("reduce(max(attribute(tensor_field_1),attribute(tensor_field_2)),sum)", - "reduce(max(attribute(tensor_field_1),attribute(tensor_field_2)),sum)"); + "reduce(max(attribute(tensor_field_1),attribute(tensor_field_2)),sum)"); assertTransformedExpression("min(constant(test_constant_tensor),1.0)", - "min(test_constant_tensor,1.0)"); + "min(test_constant_tensor,1.0)"); assertTransformedExpression("max(constant(base_constant_tensor),1.0)", - "max(base_constant_tensor,1.0)"); + "max(base_constant_tensor,1.0)"); assertTransformedExpression("min(constant(file_constant_tensor),1.0)", - "min(constant(file_constant_tensor),1.0)"); + "min(constant(file_constant_tensor),1.0)"); assertTransformedExpression("max(query(q),1.0)", - "max(query(q),1.0)"); + "max(query(q),1.0)"); assertTransformedExpression("max(query(n),1.0)", - "max(query(n),1.0)"); + "max(query(n),1.0)"); } @Test - public void requireThatMaxAndMinWithTensorAttributesAreReplaced() throws ParseException { + void requireThatMaxAndMinWithTensorAttributesAreReplaced() throws ParseException { assertTransformedExpression("reduce(attribute(tensor_field_1),max,x)", - "max(attribute(tensor_field_1),x)"); + "max(attribute(tensor_field_1),x)"); assertTransformedExpression("1+reduce(attribute(tensor_field_1),max,x)", - "1 + max(attribute(tensor_field_1),x)"); + "1 + max(attribute(tensor_field_1),x)"); assertTransformedExpression("if(attribute(double_field),1+reduce(attribute(tensor_field_1),max,x),reduce(attribute(tensor_field_1),sum,x))", - "if(attribute(double_field),1 + max(attribute(tensor_field_1),x),reduce(attribute(tensor_field_1), sum, x))"); + "if(attribute(double_field),1 + max(attribute(tensor_field_1),x),reduce(attribute(tensor_field_1), sum, x))"); assertTransformedExpression("reduce(max(attribute(tensor_field_1),attribute(tensor_field_2)),max,x)", - "max(max(attribute(tensor_field_1),attribute(tensor_field_2)),x)"); + "max(max(attribute(tensor_field_1),attribute(tensor_field_2)),x)"); assertTransformedExpression("reduce(if(attribute(double_field),attribute(tensor_field_2),attribute(tensor_field_2)),max,x)", - "max(if(attribute(double_field),attribute(tensor_field_2),attribute(tensor_field_2)),x)"); + "max(if(attribute(double_field),attribute(tensor_field_2),attribute(tensor_field_2)),x)"); assertTransformedExpression("max(reduce(attribute(tensor_field_1),max,x),x)", - "max(max(attribute(tensor_field_1),x),x)"); // will result in deploy error. + "max(max(attribute(tensor_field_1),x),x)"); // will result in deploy error. assertTransformedExpression("reduce(reduce(attribute(tensor_field_2),max,x),max,y)", - "max(max(attribute(tensor_field_2),x),y)"); + "max(max(attribute(tensor_field_2),x),y)"); } @Test - public void requireThatMaxAndMinWithConstantTensorsAreReplaced() throws ParseException { + void requireThatMaxAndMinWithConstantTensorsAreReplaced() throws ParseException { assertTransformedExpression("reduce(constant(test_constant_tensor),max,x)", - "max(test_constant_tensor,x)"); + "max(test_constant_tensor,x)"); assertTransformedExpression("reduce(constant(base_constant_tensor),max,x)", - "max(base_constant_tensor,x)"); + "max(base_constant_tensor,x)"); assertTransformedExpression("reduce(constant(file_constant_tensor),min,x)", - "min(constant(file_constant_tensor),x)"); + "min(constant(file_constant_tensor),x)"); } @Test - public void requireThatMaxAndMinWithTensorExpressionsAreReplaced() throws ParseException { + void requireThatMaxAndMinWithTensorExpressionsAreReplaced() throws ParseException { assertTransformedExpression("reduce(attribute(double_field)+attribute(tensor_field_1),min,x)", - "min(attribute(double_field) + attribute(tensor_field_1),x)"); + "min(attribute(double_field) + attribute(tensor_field_1),x)"); assertTransformedExpression("reduce(attribute(tensor_field_1)*attribute(tensor_field_2),min,x)", - "min(attribute(tensor_field_1) * attribute(tensor_field_2),x)"); + "min(attribute(tensor_field_1) * attribute(tensor_field_2),x)"); assertTransformedExpression("reduce(join(attribute(tensor_field_1),attribute(tensor_field_2),f(x,y)(x*y)),min,x)", - "min(join(attribute(tensor_field_1),attribute(tensor_field_2),f(x,y)(x*y)),x)"); + "min(join(attribute(tensor_field_1),attribute(tensor_field_2),f(x,y)(x*y)),x)"); assertTransformedExpression("min(join(tensor_field_1,tensor_field_2,f(x,y)(x*y)),x)", - "min(join(tensor_field_1,tensor_field_2,f(x,y)(x*y)),x)"); // because tensor fields are not in attribute(...) + "min(join(tensor_field_1,tensor_field_2,f(x,y)(x*y)),x)"); // because tensor fields are not in attribute(...) assertTransformedExpression("reduce(join(attribute(tensor_field_1),backend_rank_feature,f(x,y)(x*y)),min,x)", - "min(join(attribute(tensor_field_1),backend_rank_feature,f(x,y)(x*y)),x)"); + "min(join(attribute(tensor_field_1),backend_rank_feature,f(x,y)(x*y)),x)"); } @Test - public void requireThatMaxAndMinWithTensorFromIsReplaced() throws ParseException { + void requireThatMaxAndMinWithTensorFromIsReplaced() throws ParseException { assertTransformedExpression("reduce(tensorFromLabels(attribute(double_array_field)),max,double_array_field)", - "max(tensorFromLabels(attribute(double_array_field)),double_array_field)"); + "max(tensorFromLabels(attribute(double_array_field)),double_array_field)"); assertTransformedExpression("reduce(tensorFromLabels(attribute(double_array_field),x),max,x)", - "max(tensorFromLabels(attribute(double_array_field),x),x)"); + "max(tensorFromLabels(attribute(double_array_field),x),x)"); assertTransformedExpression("reduce(tensorFromWeightedSet(attribute(weightedset_field)),max,weightedset_field)", - "max(tensorFromWeightedSet(attribute(weightedset_field)),weightedset_field)"); + "max(tensorFromWeightedSet(attribute(weightedset_field)),weightedset_field)"); assertTransformedExpression("reduce(tensorFromWeightedSet(attribute(weightedset_field),x),max,x)", - "max(tensorFromWeightedSet(attribute(weightedset_field),x),x)"); + "max(tensorFromWeightedSet(attribute(weightedset_field),x),x)"); } @Test - public void requireThatMaxAndMinWithTensorInQueryIsReplaced() throws ParseException { + void requireThatMaxAndMinWithTensorInQueryIsReplaced() throws ParseException { assertTransformedExpression("reduce(query(q),max,x)", "max(query(q),x)"); assertTransformedExpression("max(query(n),x)", "max(query(n),x)"); } @Test - public void requireThatMaxAndMinWithTensorsReturnedFromFunctionsAreReplaced() throws ParseException { + void requireThatMaxAndMinWithTensorsReturnedFromFunctionsAreReplaced() throws ParseException { assertTransformedExpression("reduce(rankingExpression(returns_tensor),max,x)", - "max(returns_tensor,x)"); + "max(returns_tensor,x)"); assertTransformedExpression("reduce(rankingExpression(wraps_returns_tensor),max,x)", - "max(wraps_returns_tensor,x)"); + "max(wraps_returns_tensor,x)"); assertTransformedExpression("reduce(rankingExpression(tensor_inheriting),max,x)", - "max(tensor_inheriting,x)"); + "max(tensor_inheriting,x)"); assertTransformedExpression("reduce(rankingExpression(returns_tensor_with_arg@),max,x)", - "max(returns_tensor_with_arg(attribute(tensor_field_1)),x)"); + "max(returns_tensor_with_arg(attribute(tensor_field_1)),x)"); } private void assertTransformedExpression(String expected, String original) throws ParseException { diff --git a/config-model/src/test/java/com/yahoo/schema/processing/ValidateFieldTypesTest.java b/config-model/src/test/java/com/yahoo/schema/processing/ValidateFieldTypesTest.java index 87bb2e96042..5f0940f0d2d 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/ValidateFieldTypesTest.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/ValidateFieldTypesTest.java @@ -16,12 +16,13 @@ import com.yahoo.schema.document.SDDocumentType; import com.yahoo.schema.document.SDField; import com.yahoo.vespa.documentmodel.DocumentSummary; import com.yahoo.vespa.documentmodel.SummaryField; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; import java.util.Collections; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * @author bjorncs */ @@ -30,22 +31,18 @@ public class ValidateFieldTypesTest { private static final String IMPORTED_FIELD_NAME = "imported_myfield"; private static final String DOCUMENT_NAME = "my_doc"; - @SuppressWarnings("deprecation") - @Rule - public final ExpectedException exceptionRule = ExpectedException.none(); - @Test - public void throws_exception_if_type_of_document_field_does_not_match_summary_field() { - Schema schema = createSearchWithDocument(DOCUMENT_NAME); - schema.setImportedFields(createSingleImportedField(IMPORTED_FIELD_NAME, DataType.INT)); - schema.addSummary(createDocumentSummary(IMPORTED_FIELD_NAME, DataType.STRING, schema)); + void throws_exception_if_type_of_document_field_does_not_match_summary_field() { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + Schema schema = createSearchWithDocument(DOCUMENT_NAME); + schema.setImportedFields(createSingleImportedField(IMPORTED_FIELD_NAME, DataType.INT)); + schema.addSummary(createDocumentSummary(IMPORTED_FIELD_NAME, DataType.STRING, schema)); - ValidateFieldTypes validator = new ValidateFieldTypes(schema, null, null, null); - exceptionRule.expect(IllegalArgumentException.class); - exceptionRule.expectMessage( - "For schema '" + DOCUMENT_NAME + "', field '" + IMPORTED_FIELD_NAME + "': Incompatible types. " + - "Expected int for summary field '" + IMPORTED_FIELD_NAME + "', got string."); - validator.process(true, false); + ValidateFieldTypes validator = new ValidateFieldTypes(schema, null, null, null); + validator.process(true, false); + }); + assertTrue(exception.getMessage().contains("For schema '" + DOCUMENT_NAME + "', field '" + IMPORTED_FIELD_NAME + "': Incompatible types. " + + "Expected int for summary field '" + IMPORTED_FIELD_NAME + "', got string.")); } private static Schema createSearch(String documentType) { diff --git a/config-model/src/test/java/com/yahoo/schema/processing/VespaMlModelTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/VespaMlModelTestCase.java index 016e30e80af..dc72df9fc78 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/VespaMlModelTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/VespaMlModelTestCase.java @@ -7,13 +7,13 @@ import com.yahoo.path.Path; import com.yahoo.schema.derived.RawRankProfile; import com.yahoo.vespa.model.VespaModel; import com.yahoo.vespa.model.ml.ImportedModelTester; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Optional; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests adding Vespa ranking expression based models in the models/ dir @@ -37,13 +37,13 @@ public class VespaMlModelTestCase { /** The model name */ private final String name = "example"; - @After + @AfterEach public void removeGeneratedModelFiles() { IOUtils.recursiveDeleteDir(applicationDir.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile()); } @Test - public void testGlobalVespaModel() throws IOException { + void testGlobalVespaModel() throws IOException { ImportedModelTester tester = new ImportedModelTester(name, applicationDir); VespaModel model = tester.createVespaModel(); tester.assertLargeConstant("constant1asLarge", model, Optional.of(3L)); @@ -55,7 +55,7 @@ public class VespaMlModelTestCase { storedAppDir.toFile().mkdirs(); IOUtils.copy(applicationDir.append("services.xml").toString(), storedAppDir.append("services.xml").toString()); IOUtils.copyDirectory(applicationDir.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile(), - storedAppDir.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile()); + storedAppDir.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile()); ImportedModelTester storedTester = new ImportedModelTester(name, storedAppDir); VespaModel storedModel = storedTester.createVespaModel(); storedTester.assertLargeConstant("constant1asLarge", model, Optional.of(3L)); diff --git a/config-model/src/test/java/com/yahoo/schema/processing/WeightedSetSummaryToTestCase.java b/config-model/src/test/java/com/yahoo/schema/processing/WeightedSetSummaryToTestCase.java index 2f62228cc3f..95d01946969 100644 --- a/config-model/src/test/java/com/yahoo/schema/processing/WeightedSetSummaryToTestCase.java +++ b/config-model/src/test/java/com/yahoo/schema/processing/WeightedSetSummaryToTestCase.java @@ -5,17 +5,17 @@ import com.yahoo.schema.Schema; import com.yahoo.schema.ApplicationBuilder; import com.yahoo.schema.AbstractSchemaTestCase; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** @author bratseth */ public class WeightedSetSummaryToTestCase extends AbstractSchemaTestCase { @Test - public void testRequireThatImplicitFieldsAreCreated() throws IOException, ParseException { + void testRequireThatImplicitFieldsAreCreated() throws IOException, ParseException { Schema schema = ApplicationBuilder.buildFromFile("src/test/examples/weightedset-summaryto.sd"); assertNotNull(schema); } diff --git a/config-model/src/test/java/com/yahoo/vespa/documentmodel/DocumentModelBuilderImportedFieldsTestCase.java b/config-model/src/test/java/com/yahoo/vespa/documentmodel/DocumentModelBuilderImportedFieldsTestCase.java index faf4b67430c..c4037538252 100644 --- a/config-model/src/test/java/com/yahoo/vespa/documentmodel/DocumentModelBuilderImportedFieldsTestCase.java +++ b/config-model/src/test/java/com/yahoo/vespa/documentmodel/DocumentModelBuilderImportedFieldsTestCase.java @@ -3,7 +3,7 @@ package com.yahoo.vespa.documentmodel; import com.yahoo.schema.ApplicationBuilder; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; @@ -12,17 +12,17 @@ import static com.yahoo.config.model.test.TestUtil.joinLines; public class DocumentModelBuilderImportedFieldsTestCase extends AbstractReferenceFieldTestCase { @Test - public void imported_fields_are_included_in_generated_document_configs() throws ParseException, IOException { + void imported_fields_are_included_in_generated_document_configs() throws ParseException, IOException { assertDocumentConfigs(new TestDocumentModelBuilder().addCampaign().addPerson().build(joinLines( - "search ad {", - " document ad {", - " field campaign_ref type reference<campaign> { indexing: attribute }", - " field person_ref type reference<person> { indexing: attribute }", - " }", - " import field campaign_ref.cool_field as my_cool_field {}", - " import field campaign_ref.swag_field as my_swag_field {}", - " import field person_ref.name as my_name {}", - "}")), + "search ad {", + " document ad {", + " field campaign_ref type reference<campaign> { indexing: attribute }", + " field person_ref type reference<person> { indexing: attribute }", + " }", + " import field campaign_ref.cool_field as my_cool_field {}", + " import field campaign_ref.swag_field as my_swag_field {}", + " import field person_ref.name as my_name {}", + "}")), "multiple_imported_fields"); } diff --git a/config-model/src/test/java/com/yahoo/vespa/documentmodel/DocumentModelBuilderReferenceTypeTestCase.java b/config-model/src/test/java/com/yahoo/vespa/documentmodel/DocumentModelBuilderReferenceTypeTestCase.java index 3c2193ca4df..fdacc777eaf 100644 --- a/config-model/src/test/java/com/yahoo/vespa/documentmodel/DocumentModelBuilderReferenceTypeTestCase.java +++ b/config-model/src/test/java/com/yahoo/vespa/documentmodel/DocumentModelBuilderReferenceTypeTestCase.java @@ -5,12 +5,12 @@ import com.yahoo.documentmodel.NewDocumentReferenceDataType; import com.yahoo.documentmodel.NewDocumentType; import com.yahoo.schema.ApplicationBuilder; import com.yahoo.schema.parser.ParseException; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import static com.yahoo.config.model.test.TestUtil.joinLines; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author geirst @@ -18,31 +18,31 @@ import static org.junit.Assert.assertEquals; public class DocumentModelBuilderReferenceTypeTestCase extends AbstractReferenceFieldTestCase { @Test - public void reference_fields_can_reference_other_document_types() throws ParseException, IOException { + void reference_fields_can_reference_other_document_types() throws ParseException, IOException { assertDocumentConfigs(new TestDocumentModelBuilder().addCampaign().addPerson().build(joinLines( - "search ad {", - " document ad {", - " field campaign_ref type reference<campaign> { indexing: attribute }", - " field person_ref type reference<person> { indexing: attribute }", - " }", - "}")), + "search ad {", + " document ad {", + " field campaign_ref type reference<campaign> { indexing: attribute }", + " field person_ref type reference<person> { indexing: attribute }", + " }", + "}")), "refs_to_other_types"); } @Test - public void reference_fields_can_reference_same_document_type_multiple_times() throws ParseException, IOException { + void reference_fields_can_reference_same_document_type_multiple_times() throws ParseException, IOException { assertDocumentConfigs(new TestDocumentModelBuilder().addCampaign().build(joinLines( - "search ad {", - " document ad {", - " field campaign_ref type reference<campaign> { indexing: attribute }", - " field other_campaign_ref type reference<campaign> { indexing: attribute }", - " }", - "}")), + "search ad {", + " document ad {", + " field campaign_ref type reference<campaign> { indexing: attribute }", + " field other_campaign_ref type reference<campaign> { indexing: attribute }", + " }", + "}")), "refs_to_same_type"); } @Test - public void reference_data_type_has_a_concrete_target_type() throws ParseException { + void reference_data_type_has_a_concrete_target_type() throws ParseException { DocumentModel model = new TestDocumentModelBuilder().addCampaign().build(joinLines( "search ad {", " document ad {", diff --git a/config-model/src/test/java/com/yahoo/vespa/documentmodel/DocumentModelBuilderTestCase.java b/config-model/src/test/java/com/yahoo/vespa/documentmodel/DocumentModelBuilderTestCase.java index d345c776db3..7fe58c93434 100644 --- a/config-model/src/test/java/com/yahoo/vespa/documentmodel/DocumentModelBuilderTestCase.java +++ b/config-model/src/test/java/com/yahoo/vespa/documentmodel/DocumentModelBuilderTestCase.java @@ -8,24 +8,26 @@ import com.yahoo.schema.AbstractSchemaTestCase; import com.yahoo.schema.parser.ParseException; import com.yahoo.vespa.configmodel.producers.DocumentManager; import com.yahoo.vespa.configmodel.producers.DocumentTypes; -import org.junit.Test; +import org.junit.jupiter.api.Test; + import java.io.IOException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; public class DocumentModelBuilderTestCase extends AbstractSchemaTestCase { @Test - public void testDocumentManagerSimple() throws IOException, ParseException { + void testDocumentManagerSimple() throws IOException, ParseException { DocumentModel model = createAndTestModel("src/test/configmodel/types/types.sd"); DocumentmanagerConfig.Builder documentmanagerCfg = new DocumentManager().produce(model, new DocumentmanagerConfig.Builder()); assertConfigFile("src/test/configmodel/types/documentmanager.cfg", new DocumentmanagerConfig(documentmanagerCfg).toString()); } - @Test + // This is ignored as enums in config are not testable in this way. See bug 4748050 - public void testDocumentTypesSimple() throws IOException, ParseException { + @Test + void testDocumentTypesSimple() throws IOException, ParseException { DocumentModel model = createAndTestModel("src/test/configmodel/types/types.sd"); DocumenttypesConfig.Builder documenttypesCfg = new DocumentTypes().produce(model, new DocumenttypesConfig.Builder()); @@ -34,7 +36,7 @@ public class DocumentModelBuilderTestCase extends AbstractSchemaTestCase { } @Test - public void testDocumentTypesWithDocumentField() throws IOException, ParseException { + void testDocumentTypesWithDocumentField() throws IOException, ParseException { ApplicationBuilder search = new ApplicationBuilder(); search.addSchemaFile("src/test/configmodel/types/other_doc.sd"); search.addSchemaFile("src/test/configmodel/types/type_with_doc_field.sd"); @@ -47,7 +49,7 @@ public class DocumentModelBuilderTestCase extends AbstractSchemaTestCase { } @Test - public void testMultipleInheritanceArray() throws IOException, ParseException { + void testMultipleInheritanceArray() throws IOException, ParseException { ApplicationBuilder search = new ApplicationBuilder(); search.addSchemaFile("src/test/cfg/search/data/travel/schemas/TTData.sd"); search.addSchemaFile("src/test/cfg/search/data/travel/schemas/TTEdge.sd"); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/HostPortsTest.java b/config-model/src/test/java/com/yahoo/vespa/model/HostPortsTest.java index 31d089d64db..731aa02fd0b 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/HostPortsTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/HostPortsTest.java @@ -5,13 +5,14 @@ import com.yahoo.config.model.producer.AbstractConfigProducer; import com.yahoo.config.model.test.MockRoot; import com.yahoo.config.provision.NetworkPorts; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.hamcrest.MatcherAssert.assertThat; /** @@ -20,13 +21,13 @@ import static org.hamcrest.MatcherAssert.assertThat; public class HostPortsTest { @Test - public void next_available_baseport_is_BASE_PORT_when_no_ports_have_been_reserved() { + void next_available_baseport_is_BASE_PORT_when_no_ports_have_been_reserved() { HostPorts host = new HostPorts("myhostname"); assertThat(host.nextAvailableBaseport(1), is(HostPorts.BASE_PORT)); } @Test - public void next_available_baseport_is_BASE_PORT_plus_one_when_one_port_has_been_reserved() { + void next_available_baseport_is_BASE_PORT_plus_one_when_one_port_has_been_reserved() { HostPorts host = new HostPorts("myhostname"); MockRoot root = new MockRoot(); host.reservePort(new TestService(root, 1), HostPorts.BASE_PORT, "foo"); @@ -34,7 +35,7 @@ public class HostPortsTest { } @Test - public void no_available_baseport_when_service_requires_more_consecutive_ports_than_available() { + void no_available_baseport_when_service_requires_more_consecutive_ports_than_available() { HostPorts host = new HostPorts("myhostname"); MockRoot root = new MockRoot(); @@ -51,32 +52,36 @@ public class HostPortsTest { } @Test - public void port_above_vespas_port_range_can_be_reserved() { + void port_above_vespas_port_range_can_be_reserved() { HostPorts host = new HostPorts("myhostname"); MockRoot root = new MockRoot(); host.allocatePorts(new TestService(root, 1), HostPorts.BASE_PORT + HostPorts.MAX_PORTS + 1); } - @Test(expected = RuntimeException.class) - public void allocating_same_port_throws_exception() { - HostPorts host = new HostPorts("myhostname"); - MockRoot root = new MockRoot(); - TestService service1 = new TestService(root, 1); - TestService service2 = new TestService(root, 1); - - host.allocatePorts(service1, HostPorts.BASE_PORT); - host.allocatePorts(service2, HostPorts.BASE_PORT); + @Test + void allocating_same_port_throws_exception() { + assertThrows(RuntimeException.class, () -> { + HostPorts host = new HostPorts("myhostname"); + MockRoot root = new MockRoot(); + TestService service1 = new TestService(root, 1); + TestService service2 = new TestService(root, 1); + + host.allocatePorts(service1, HostPorts.BASE_PORT); + host.allocatePorts(service2, HostPorts.BASE_PORT); + }); } - @Test(expected = RuntimeException.class) - public void allocating_overlapping_ports_throws_exception() { - HostPorts host = new HostPorts("myhostname"); - MockRoot root = new MockRoot(); - TestService service2 = new TestService(root, 2); - TestService service1 = new TestService(root, 1); - - host.allocatePorts(service2, HostPorts.BASE_PORT); - host.allocatePorts(service1, HostPorts.BASE_PORT + 1); + @Test + void allocating_overlapping_ports_throws_exception() { + assertThrows(RuntimeException.class, () -> { + HostPorts host = new HostPorts("myhostname"); + MockRoot root = new MockRoot(); + TestService service2 = new TestService(root, 2); + TestService service1 = new TestService(root, 1); + + host.allocatePorts(service2, HostPorts.BASE_PORT); + host.allocatePorts(service1, HostPorts.BASE_PORT + 1); + }); } NetworkPorts emulOldPorts() { @@ -87,7 +92,7 @@ public class HostPortsTest { } @Test - public void use_old_port_when_available() { + void use_old_port_when_available() { HostPorts host = new HostPorts("myhostname"); host.addNetworkPorts(emulOldPorts()); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/HostResourceTest.java b/config-model/src/test/java/com/yahoo/vespa/model/HostResourceTest.java index ea075dc1129..d59d0e51b23 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/HostResourceTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/HostResourceTest.java @@ -7,13 +7,13 @@ import com.yahoo.config.provision.ClusterMembership; import com.yahoo.config.provision.ClusterSpec; import com.yahoo.config.provision.HostSpec; import com.yahoo.config.provision.NodeResources; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Optional; import static com.yahoo.config.provision.ClusterSpec.Type.container; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author gjoranv @@ -21,7 +21,7 @@ import static org.junit.Assert.assertTrue; public class HostResourceTest { @Test - public void require_exception_when_no_matching_hostalias() { + void require_exception_when_no_matching_hostalias() { MockRoot root = new MockRoot(); TestService service = new TestService(root, 1); @@ -34,7 +34,7 @@ public class HostResourceTest { } @Test - public void host_with_membership() { + void host_with_membership() { HostResource host = hostResourceWithMemberships(ClusterMembership.from(clusterSpec(container, "container"), 0)); assertClusterMembership(host, container, "container"); } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/InstanceResolverTest.java b/config-model/src/test/java/com/yahoo/vespa/model/InstanceResolverTest.java index 636bfebaaf5..8440951a06f 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/InstanceResolverTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/InstanceResolverTest.java @@ -7,18 +7,18 @@ import com.yahoo.test.FunctionTestConfig.*; import com.yahoo.test.SimpletypesConfig; import com.yahoo.config.codegen.*; import com.yahoo.text.StringUtilities; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.StringReader; import java.util.ArrayList; import java.util.Arrays; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.*; public class InstanceResolverTest { @Test - public void testApplyDefToBuilder() throws Exception { + void testApplyDefToBuilder() throws Exception { FunctionTestConfig.Builder builder = createVariableAccessBuilder(); InnerCNode targetDef = getDef(FunctionTestConfig.CONFIG_DEF_SCHEMA); @@ -58,7 +58,7 @@ public class InstanceResolverTest { * Values unset on builder, trying to set them from def file, but type mismatches there */ @Test - public void testApplyDefToBuilderMismatches() throws Exception { + void testApplyDefToBuilderMismatches() throws Exception { FunctionTestConfig.Builder builder = createVariableAccessBuilderManyUnset(); InnerCNode targetDef = getDef(FunctionTestConfig.CONFIG_DEF_SCHEMA); @@ -223,7 +223,7 @@ public class InstanceResolverTest { } @Test - public void testExtraFieldsAreIgnored() throws Exception { + void testExtraFieldsAreIgnored() throws Exception { try { SimpletypesConfig.Builder builder = new SimpletypesConfig.Builder(); InnerCNode defWithExtra = new DefParser(SimpletypesConfig.CONFIG_DEF_NAME, new StringReader(StringUtilities.implode(SimpletypesConfig.CONFIG_DEF_SCHEMA, "\n") + "\nnewfield string default=\"foo\"\n")).getTree(); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/RecentLogFilterTest.java b/config-model/src/test/java/com/yahoo/vespa/model/RecentLogFilterTest.java index 4042723856f..0cb1ecf6f5e 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/RecentLogFilterTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/RecentLogFilterTest.java @@ -1,15 +1,15 @@ // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.model; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.LogRecord; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author hmusum @@ -17,7 +17,7 @@ import static org.junit.Assert.assertTrue; public class RecentLogFilterTest { @Test - public void basic() { + void basic() { RecentLogFilter rlf = new RecentLogFilter(); List<LogRecord> logRecords = new ArrayList<>(); for (int i = 0; i < RecentLogFilter.maxMessages + 1; i++) { diff --git a/config-model/src/test/java/com/yahoo/vespa/model/VespaModelFactoryTest.java b/config-model/src/test/java/com/yahoo/vespa/model/VespaModelFactoryTest.java index 104fdea0e40..567b44e9544 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/VespaModelFactoryTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/VespaModelFactoryTest.java @@ -19,16 +19,14 @@ import com.yahoo.config.provision.ClusterSpec; import com.yahoo.config.provision.HostSpec; import com.yahoo.config.provision.NodeResources; import com.yahoo.config.provision.ProvisionLogger; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * @author Ulf Lilleengen @@ -37,13 +35,13 @@ public class VespaModelFactoryTest { private ModelContext testModelContext; - @Before + @BeforeEach public void setupContext() { testModelContext = new MockModelContext(); } @Test - public void testThatFactoryCanBuildModel() { + void testThatFactoryCanBuildModel() { VespaModelFactory modelFactory = VespaModelFactory.createTestFactory(); Model model = modelFactory.createModel(testModelContext); assertNotNull(model); @@ -51,21 +49,25 @@ public class VespaModelFactoryTest { } // Uses an application package that throws IllegalArgumentException when validating - @Test(expected = IllegalArgumentException.class) - public void testThatFactoryModelValidationFailsWithIllegalArgumentException() { - VespaModelFactory modelFactory = VespaModelFactory.createTestFactory(); - modelFactory.createAndValidateModel(new MockModelContext(createApplicationPackageThatFailsWhenValidating()), new ValidationParameters()); + @Test + void testThatFactoryModelValidationFailsWithIllegalArgumentException() { + assertThrows(IllegalArgumentException.class, () -> { + VespaModelFactory modelFactory = VespaModelFactory.createTestFactory(); + modelFactory.createAndValidateModel(new MockModelContext(createApplicationPackageThatFailsWhenValidating()), new ValidationParameters()); + }); } // Uses a MockApplicationPackage that throws throws UnsupportedOperationException (rethrown as RuntimeException) when validating - @Test(expected = RuntimeException.class) - public void testThatFactoryModelValidationFails() { - VespaModelFactory modelFactory = VespaModelFactory.createTestFactory(); - modelFactory.createAndValidateModel(testModelContext, new ValidationParameters()); + @Test + void testThatFactoryModelValidationFails() { + assertThrows(RuntimeException.class, () -> { + VespaModelFactory modelFactory = VespaModelFactory.createTestFactory(); + modelFactory.createAndValidateModel(testModelContext, new ValidationParameters()); + }); } @Test - public void testThatFactoryModelValidationCanBeIgnored() { + void testThatFactoryModelValidationCanBeIgnored() { VespaModelFactory modelFactory = VespaModelFactory.createTestFactory(); ModelCreateResult createResult = modelFactory.createAndValidateModel( new MockModelContext(createApplicationPackageThatFailsWhenValidating()), @@ -76,7 +78,7 @@ public class VespaModelFactoryTest { } @Test - public void hostedVespaZoneApplicationAllocatesNodesFromNodeRepo() { + void hostedVespaZoneApplicationAllocatesNodesFromNodeRepo() { String hostName = "test-host-name"; String routingClusterName = "routing-cluster"; @@ -103,17 +105,17 @@ public class VespaModelFactoryTest { @Override public HostSpec allocateHost(String alias) { return new HostSpec(hostName, - NodeResources.unspecified(), NodeResources.unspecified(), NodeResources.unspecified(), - ClusterMembership.from(ClusterSpec.request(ClusterSpec.Type.admin, new ClusterSpec.Id(routingClusterName)).vespaVersion("6.42").build(), 0), - Optional.empty(), Optional.empty(), Optional.empty()); + NodeResources.unspecified(), NodeResources.unspecified(), NodeResources.unspecified(), + ClusterMembership.from(ClusterSpec.request(ClusterSpec.Type.admin, new ClusterSpec.Id(routingClusterName)).vespaVersion("6.42").build(), 0), + Optional.empty(), Optional.empty(), Optional.empty()); } @Override public List<HostSpec> prepare(ClusterSpec cluster, Capacity capacity, ProvisionLogger logger) { return List.of(new HostSpec(hostName, - NodeResources.unspecified(), NodeResources.unspecified(), NodeResources.unspecified(), - ClusterMembership.from(ClusterSpec.request(ClusterSpec.Type.container, new ClusterSpec.Id(routingClusterName)).vespaVersion("6.42").build(), 0), - Optional.empty(), Optional.empty(), Optional.empty())); + NodeResources.unspecified(), NodeResources.unspecified(), NodeResources.unspecified(), + ClusterMembership.from(ClusterSpec.request(ClusterSpec.Type.container, new ClusterSpec.Id(routingClusterName)).vespaVersion("6.42").build(), 0), + Optional.empty(), Optional.empty(), Optional.empty())); } }; @@ -125,10 +127,10 @@ public class VespaModelFactoryTest { HostInfo hostInfo = allocatedHosts.get(0); assertEquals(hostName, hostInfo.getHostname()); - assertTrue("Routing service should run on host " + hostName, - hostInfo.getServices().stream() - .map(ServiceInfo::getConfigId) - .anyMatch(configId -> configId.contains(routingClusterName))); + assertTrue(hostInfo.getServices().stream() + .map(ServiceInfo::getConfigId) + .anyMatch(configId -> configId.contains(routingClusterName)), + "Routing service should run on host " + hostName); } private ModelContext createMockModelContext(String hosts, String services, HostProvisioner provisionerToOverride) { diff --git a/config-model/src/test/java/com/yahoo/vespa/model/admin/AdminTestCase.java b/config-model/src/test/java/com/yahoo/vespa/model/admin/AdminTestCase.java index 7bdf80706d6..d060fdfd3d2 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/admin/AdminTestCase.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/admin/AdminTestCase.java @@ -22,16 +22,12 @@ import com.yahoo.vespa.model.VespaModel; import com.yahoo.vespa.model.container.ApplicationContainerCluster; import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithFilePkg; import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithMockPkg; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Set; import static com.yahoo.config.model.api.container.ContainerServiceType.METRICS_PROXY_CONTAINER; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; public class AdminTestCase { @@ -46,7 +42,7 @@ public class AdminTestCase { * Test that version 2.0 of adminconfig works as expected. */ @Test - public void testAdmin20() { + void testAdmin20() { VespaModel vespaModel = getVespaModel(TESTDIR + "adminconfig20"); // Verify that the admin plugin has been loaded (always loads routing). @@ -110,7 +106,7 @@ public class AdminTestCase { * adminserver, logserver, configserver and slobroks */ @Test - public void testOnlyAdminserver() { + void testOnlyAdminserver() { VespaModel vespaModel = getVespaModel(TESTDIR + "simpleadminconfig20"); // Verify that the admin plugin has been loaded (always loads routing). @@ -150,7 +146,7 @@ public class AdminTestCase { } @Test - public void testTenantAndAppInSentinelConfig() { + void testTenantAndAppInSentinelConfig() { DeployState state = new DeployState.Builder() .zone(new Zone(Environment.dev, RegionName.from("baz"))) .properties(new TestProperties() @@ -171,7 +167,7 @@ public class AdminTestCase { } @Test - public void testMultipleConfigServers() { + void testMultipleConfigServers() { VespaModel vespaModel = getVespaModel(TESTDIR + "multipleconfigservers"); // Verify that the admin plugin has been loaded (always loads routing). @@ -213,7 +209,7 @@ public class AdminTestCase { } @Test - public void testContainerMetricsSnapshotInterval() { + void testContainerMetricsSnapshotInterval() { VespaModel vespaModel = getVespaModel(TESTDIR + "metricconfig"); ApplicationContainerCluster qrCluster = vespaModel.getContainerClusters().get("container"); @@ -224,7 +220,7 @@ public class AdminTestCase { } @Test - public void testLogForwarding() { + void testLogForwarding() { String hosts = "<hosts>" + " <host name=\"myhost0\">" + " <alias>node0</alias>" @@ -244,7 +240,7 @@ public class AdminTestCase { Set<String> configIds = vespaModel.getConfigIds(); // 1 logforwarder on each host - assertTrue(configIds.toString(), configIds.contains("hosts/myhost0/logforwarder")); + assertTrue(configIds.contains("hosts/myhost0/logforwarder"), configIds.toString()); } } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/admin/ClusterControllerTestCase.java b/config-model/src/test/java/com/yahoo/vespa/model/admin/ClusterControllerTestCase.java index 793064af2dc..0cb97681f13 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/admin/ClusterControllerTestCase.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/admin/ClusterControllerTestCase.java @@ -34,8 +34,8 @@ import com.yahoo.vespa.model.container.PlatformBundles; import com.yahoo.vespa.model.container.component.Component; import com.yahoo.vespa.model.test.utils.ApplicationPackageUtils; import com.yahoo.vespa.model.test.utils.DeployLoggerStub; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.xml.sax.SAXException; import java.io.IOException; @@ -48,10 +48,7 @@ import java.util.Optional; import java.util.Set; import static java.util.stream.Collectors.toSet; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * Test for creating cluster controllers under the admin tag. @@ -60,13 +57,13 @@ public class ClusterControllerTestCase extends DomBuilderTest { private List<String> sds; - @Before + @BeforeEach public void setup() { sds = ApplicationPackageUtils.generateSchemas("type1", "type2"); } @Test - public void testSingleCluster() throws Exception { + void testSingleCluster() throws Exception { String xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" + "<services>\n" + "\n" + @@ -90,7 +87,7 @@ public class ClusterControllerTestCase extends DomBuilderTest { " <tuning>" + " <cluster-controller>\n" + " <init-progress-time>34567s</init-progress-time>" + - " <transition-time>4000ms</transition-time>" + + " <transition-time>4000ms</transition-time>" + " <stable-state-period>1h</stable-state-period>" + " </cluster-controller>" + " </tuning>" + @@ -126,63 +123,67 @@ public class ClusterControllerTestCase extends DomBuilderTest { .noneMatch(unnecessaryBundles::contains)); } - @Test(expected = IllegalArgumentException.class) - public void testSeparateHostsRequired() { - String xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" + - "<services>\n" + - "\n" + - " <admin version=\"2.0\">\n" + - " <adminserver hostalias=\"mockhost\" />\n" + - " <cluster-controllers standalone-zookeeper=\"true\">\n" + - " <cluster-controller hostalias=\"mockhost\"/>" + - " <cluster-controller hostalias=\"mockhost\"/>" + - " <cluster-controller hostalias=\"mockhost\"/>" + - " </cluster-controllers>\n" + - " </admin>\n" + - " <content version='1.0' id='bar'>" + - " <redundancy>1</redundancy>\n" + - " <documents>" + - " </documents>\n" + - " <group>" + - " <node hostalias='mockhost' distribution-key='0' />" + - " </group>" + - " </content>" + - "\n" + - "</services>"; - TestDriver driver = new TestDriver(); - driver.buildModel(xml); + @Test + void testSeparateHostsRequired() { + assertThrows(IllegalArgumentException.class, () -> { + String xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" + + "<services>\n" + + "\n" + + " <admin version=\"2.0\">\n" + + " <adminserver hostalias=\"mockhost\" />\n" + + " <cluster-controllers standalone-zookeeper=\"true\">\n" + + " <cluster-controller hostalias=\"mockhost\"/>" + + " <cluster-controller hostalias=\"mockhost\"/>" + + " <cluster-controller hostalias=\"mockhost\"/>" + + " </cluster-controllers>\n" + + " </admin>\n" + + " <content version='1.0' id='bar'>" + + " <redundancy>1</redundancy>\n" + + " <documents>" + + " </documents>\n" + + " <group>" + + " <node hostalias='mockhost' distribution-key='0' />" + + " </group>" + + " </content>" + + "\n" + + "</services>"; + TestDriver driver = new TestDriver(); + driver.buildModel(xml); + }); } - @Test(expected = IllegalArgumentException.class) - public void testSeparateHostsFromConfigServerRequired() { - String xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" + - "<services>\n" + - "\n" + - " <admin version=\"2.0\">\n" + - " <adminserver hostalias=\"mockhost\" />\n" + - " <configservers>\n" + - " <configserver hostalias=\"mockhost\" />" + - " </configservers>" + - " <cluster-controllers standalone-zookeeper=\"true\">\n" + - " <cluster-controller hostalias=\"mockhost\"/>" + - " </cluster-controllers>\n" + - " </admin>\n" + - " <content version='1.0' id='bar'>" + - " <redundancy>1</redundancy>\n" + - " <documents>" + - " </documents>\n" + - " <group>" + - " <node hostalias='mockhost' distribution-key='0' />" + - " </group>" + - " </content>" + - "\n" + - "</services>"; - TestDriver driver = new TestDriver(); - driver.buildModel(xml); + @Test + void testSeparateHostsFromConfigServerRequired() { + assertThrows(IllegalArgumentException.class, () -> { + String xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" + + "<services>\n" + + "\n" + + " <admin version=\"2.0\">\n" + + " <adminserver hostalias=\"mockhost\" />\n" + + " <configservers>\n" + + " <configserver hostalias=\"mockhost\" />" + + " </configservers>" + + " <cluster-controllers standalone-zookeeper=\"true\">\n" + + " <cluster-controller hostalias=\"mockhost\"/>" + + " </cluster-controllers>\n" + + " </admin>\n" + + " <content version='1.0' id='bar'>" + + " <redundancy>1</redundancy>\n" + + " <documents>" + + " </documents>\n" + + " <group>" + + " <node hostalias='mockhost' distribution-key='0' />" + + " </group>" + + " </content>" + + "\n" + + "</services>"; + TestDriver driver = new TestDriver(); + driver.buildModel(xml); + }); } @Test - public void testStandaloneZooKeeper() { + void testStandaloneZooKeeper() { String xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" + "<services>\n" + "\n" + @@ -258,7 +259,7 @@ public class ClusterControllerTestCase extends DomBuilderTest { } @Test - public void testUnconfigured() throws Exception { + void testUnconfigured() throws Exception { String xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" + "<services>\n" + "\n" + @@ -320,7 +321,7 @@ public class ClusterControllerTestCase extends DomBuilderTest { } @Test - public void testUnconfiguredMultiple() throws Exception { + void testUnconfiguredMultiple() throws Exception { String xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" + "<services>\n" + "\n" + @@ -362,7 +363,7 @@ public class ClusterControllerTestCase extends DomBuilderTest { } @Test - public void testUnconfiguredNoTuning() throws Exception { + void testUnconfiguredNoTuning() throws Exception { String xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" + "<services>\n" + "\n" + @@ -417,7 +418,7 @@ public class ClusterControllerTestCase extends DomBuilderTest { } @Test - public void testUnconfiguredNoContent() throws Exception { + void testUnconfiguredNoContent() throws Exception { String xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" + "<services>\n" + " <admin version=\"2.0\">\n" + @@ -438,7 +439,7 @@ public class ClusterControllerTestCase extends DomBuilderTest { } @Test - public void testUsingOldStyle() throws Exception { + void testUsingOldStyle() throws Exception { String xml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" + "<services>\n" + "\n" + diff --git a/config-model/src/test/java/com/yahoo/vespa/model/admin/DedicatedAdminV4Test.java b/config-model/src/test/java/com/yahoo/vespa/model/admin/DedicatedAdminV4Test.java index eee4d29cc6e..a8ffc625ee6 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/admin/DedicatedAdminV4Test.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/admin/DedicatedAdminV4Test.java @@ -18,7 +18,7 @@ import com.yahoo.vespa.model.VespaModel; import com.yahoo.vespa.model.admin.monitoring.Metric; import com.yahoo.vespa.model.admin.monitoring.MetricsConsumer; import com.yahoo.vespa.model.admin.monitoring.Monitoring; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.xml.sax.SAXException; import java.io.IOException; @@ -29,9 +29,7 @@ import java.util.stream.IntStream; import static com.yahoo.config.model.api.container.ContainerServiceType.LOGSERVER_CONTAINER; import static com.yahoo.config.model.api.container.ContainerServiceType.METRICS_PROXY_CONTAINER; import static com.yahoo.config.model.api.container.ContainerServiceType.CONTAINER; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * @author Ulf Lilleengen @@ -52,7 +50,7 @@ public class DedicatedAdminV4Test { + "</hosts>"; @Test - public void testModelBuilding() throws IOException, SAXException { + void testModelBuilding() throws IOException, SAXException { String services = "<services>" + " <admin version='4.0'>" + " <slobroks><nodes count='2' dedicated='true'/></slobroks>" + @@ -74,12 +72,12 @@ public class DedicatedAdminV4Test { assertEquals(3, model.getHosts().size()); assertHostContainsServices(model, "hosts/myhost0", "slobrok", "logd", - METRICS_PROXY_CONTAINER.serviceName); + METRICS_PROXY_CONTAINER.serviceName); assertHostContainsServices(model, "hosts/myhost1", "slobrok", "logd", - METRICS_PROXY_CONTAINER.serviceName); + METRICS_PROXY_CONTAINER.serviceName); // Note: A logserver container is always added on logserver host assertHostContainsServices(model, "hosts/myhost2", "logserver", "logd", - METRICS_PROXY_CONTAINER.serviceName, LOGSERVER_CONTAINER.serviceName); + METRICS_PROXY_CONTAINER.serviceName, LOGSERVER_CONTAINER.serviceName); Monitoring monitoring = model.getAdmin().getMonitoring(); assertEquals("vespa.routing", monitoring.getClustername()); @@ -93,7 +91,7 @@ public class DedicatedAdminV4Test { } @Test - public void testThatThereAre2SlobroksPerContainerCluster() throws IOException, SAXException { + void testThatThereAre2SlobroksPerContainerCluster() throws IOException, SAXException { String hosts = "<hosts>" + " <host name=\"myhost0\">" + " <alias>node0</alias>" @@ -110,39 +108,39 @@ public class DedicatedAdminV4Test { + "</hosts>"; String servicesWith3JdiscClusters = "<services>" + - " <admin version='4.0'>" + - " <nodes count='1' dedicated='true' />" + - " </admin>" + - " <container id='a' version='1.0'>" + - " <search />" + - " <nodes count='2' dedicated='true' />" + - " </container>" + - " <container id='b' version='1.0'>" + - " <search />" + - " <nodes count='1' dedicated='true' />" + - " </container>" + - " <container id='c' version='1.0'>" + - " <search />" + - " <nodes count='1' dedicated='true' />" + - " </container>" + - "</services>"; + " <admin version='4.0'>" + + " <nodes count='1' dedicated='true' />" + + " </admin>" + + " <container id='a' version='1.0'>" + + " <search />" + + " <nodes count='2' dedicated='true' />" + + " </container>" + + " <container id='b' version='1.0'>" + + " <search />" + + " <nodes count='1' dedicated='true' />" + + " </container>" + + " <container id='c' version='1.0'>" + + " <search />" + + " <nodes count='1' dedicated='true' />" + + " </container>" + + "</services>"; VespaModel model = createModel(hosts, servicesWith3JdiscClusters); assertEquals(4, model.getHosts().size()); // 4 slobroks, 2 per cluster where possible assertHostContainsServices(model, "hosts/myhost0", "slobrok", "logd", "logserver", - METRICS_PROXY_CONTAINER.serviceName, CONTAINER.serviceName); + METRICS_PROXY_CONTAINER.serviceName, CONTAINER.serviceName); assertHostContainsServices(model, "hosts/myhost1", "slobrok", "logd", - METRICS_PROXY_CONTAINER.serviceName, CONTAINER.serviceName); + METRICS_PROXY_CONTAINER.serviceName, CONTAINER.serviceName); assertHostContainsServices(model, "hosts/myhost2", "slobrok", "logd", - METRICS_PROXY_CONTAINER.serviceName, CONTAINER.serviceName); + METRICS_PROXY_CONTAINER.serviceName, CONTAINER.serviceName); assertHostContainsServices(model, "hosts/myhost3", "slobrok", "logd", - METRICS_PROXY_CONTAINER.serviceName, CONTAINER.serviceName); + METRICS_PROXY_CONTAINER.serviceName, CONTAINER.serviceName); } @Test - public void testLogForwarding() throws IOException, SAXException { + void testLogForwarding() throws IOException, SAXException { String services = "<services>" + " <admin version='4.0'>" + " <slobroks><nodes count='2' dedicated='true'/></slobroks>" + @@ -157,16 +155,16 @@ public class DedicatedAdminV4Test { assertEquals(3, model.getHosts().size()); assertHostContainsServices(model, "hosts/myhost0", "logd", "logforwarder", "slobrok", - METRICS_PROXY_CONTAINER.serviceName); + METRICS_PROXY_CONTAINER.serviceName); assertHostContainsServices(model, "hosts/myhost1", "logd", "logforwarder", "slobrok", - METRICS_PROXY_CONTAINER.serviceName); + METRICS_PROXY_CONTAINER.serviceName); // Note: A logserver container is always added on logserver host assertHostContainsServices(model, "hosts/myhost2", "logd", "logforwarder", "logserver", - METRICS_PROXY_CONTAINER.serviceName, LOGSERVER_CONTAINER.serviceName); + METRICS_PROXY_CONTAINER.serviceName, LOGSERVER_CONTAINER.serviceName); Set<String> configIds = model.getConfigIds(); // 1 logforwarder on each host - IntStream.of(0, 1, 2).forEach(i -> assertTrue(configIds.toString(), configIds.contains("hosts/myhost"+i+"/logforwarder"))); + IntStream.of(0, 1, 2).forEach(i -> assertTrue(configIds.contains("hosts/myhost" + i + "/logforwarder"), configIds.toString())); // First forwarder { @@ -194,7 +192,7 @@ public class DedicatedAdminV4Test { } @Test - public void testDedicatedLogserverInHostedVespa() throws IOException, SAXException { + void testDedicatedLogserverInHostedVespa() throws IOException, SAXException { String services = "<services>" + " <admin version='4.0'>" + " <logservers>" + @@ -209,7 +207,7 @@ public class DedicatedAdminV4Test { assertEquals(1, model.getHosts().size()); // Should create a logserver container on the same node as logserver assertHostContainsServices(model, "hosts/myhost0", "slobrok", "logd", "logserver", - METRICS_PROXY_CONTAINER.serviceName , LOGSERVER_CONTAINER.serviceName); + METRICS_PROXY_CONTAINER.serviceName, LOGSERVER_CONTAINER.serviceName); } private Set<String> serviceNames(VespaModel model, String hostname) { diff --git a/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsConsumersTest.java b/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsConsumersTest.java index b5dd4552023..0a1791b3766 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsConsumersTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsConsumersTest.java @@ -6,7 +6,7 @@ import com.yahoo.vespa.model.VespaModel; import com.yahoo.vespa.model.admin.monitoring.Metric; import com.yahoo.vespa.model.admin.monitoring.MetricSet; import com.yahoo.vespa.model.admin.monitoring.MetricsConsumer; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyModelTester.TestMode.hosted; import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyModelTester.TestMode.self_hosted; @@ -22,9 +22,7 @@ import static com.yahoo.vespa.model.admin.monitoring.NetworkMetrics.networkMetri import static com.yahoo.vespa.model.admin.monitoring.SystemMetrics.systemMetricSet; import static com.yahoo.vespa.model.admin.monitoring.VespaMetricSet.vespaMetricSet; import static java.util.Collections.singleton; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; /** * Tests for {@link MetricsProxyContainerCluster} related to metrics consumers. @@ -41,7 +39,7 @@ public class MetricsConsumersTest { private static final int numMetricsForVespaConsumer = numVespaMetrics + numSystemMetrics + numNetworkMetrics; @Test - public void default_public_consumer_is_set_up_for_self_hosted() { + void default_public_consumer_is_set_up_for_self_hosted() { ConsumersConfig config = consumersConfigFromXml(servicesWithAdminOnly(), self_hosted); assertEquals(3, config.consumer().size()); assertEquals(MetricsConsumer.defaultConsumer.id(), config.consumer(2).name()); @@ -50,7 +48,7 @@ public class MetricsConsumersTest { } @Test - public void consumers_are_set_up_for_hosted() { + void consumers_are_set_up_for_hosted() { ConsumersConfig config = consumersConfigFromXml(servicesWithAdminOnly(), hosted); assertEquals(3, config.consumer().size()); assertEquals(MetricsConsumer.vespa.id(), config.consumer(0).name()); @@ -59,14 +57,14 @@ public class MetricsConsumersTest { } @Test - public void vespa_consumer_is_always_present_and_has_all_vespa_metrics_and_all_system_metrics() { + void vespa_consumer_is_always_present_and_has_all_vespa_metrics_and_all_system_metrics() { ConsumersConfig config = consumersConfigFromXml(servicesWithAdminOnly(), self_hosted); assertEquals(MetricsConsumer.vespa.id(), config.consumer(0).name()); assertEquals(numMetricsForVespaConsumer, config.consumer(0).metric().size()); } @Test - public void vespa_consumer_can_be_amended_via_admin_object() { + void vespa_consumer_can_be_amended_via_admin_object() { VespaModel model = getModel(servicesWithAdminOnly(), self_hosted); var additionalMetric = new Metric("additional-metric"); model.getAdmin().setAdditionalDefaultMetrics(new MetricSet("amender-metrics", singleton(additionalMetric))); @@ -75,16 +73,16 @@ public class MetricsConsumersTest { assertEquals(numMetricsForVespaConsumer + 1, config.consumer(0).metric().size()); ConsumersConfig.Consumer vespaConsumer = config.consumer(0); - assertTrue("Did not contain additional metric", checkMetric(vespaConsumer, additionalMetric)); + assertTrue(checkMetric(vespaConsumer, additionalMetric), "Did not contain additional metric"); } @Test - public void vespa_is_a_reserved_consumer_id() { + void vespa_is_a_reserved_consumer_id() { assertReservedConsumerId("Vespa"); } @Test - public void default_is_a_reserved_consumer_id() { + void default_is_a_reserved_consumer_id() { assertReservedConsumerId("default"); } @@ -108,18 +106,18 @@ public class MetricsConsumersTest { } @Test - public void vespa_consumer_id_is_allowed_for_hosted_infrastructure_applications() { + void vespa_consumer_id_is_allowed_for_hosted_infrastructure_applications() { String services = String.join("\n", - "<services application-type='hosted-infrastructure'>", - " <admin version='4.0'>", - " <adminserver hostalias='node1'/>", - " <metrics>", - " <consumer id='Vespa'>", - " <metric id='custom.metric1'/>", - " </consumer>", - " </metrics>", - " </admin>", - "</services>" + "<services application-type='hosted-infrastructure'>", + " <admin version='4.0'>", + " <adminserver hostalias='node1'/>", + " <metrics>", + " <consumer id='Vespa'>", + " <metric id='custom.metric1'/>", + " </consumer>", + " </metrics>", + " </admin>", + "</services>" ); VespaModel hostedModel = getModel(services, hosted); ConsumersConfig config = consumersConfigFromModel(hostedModel); @@ -130,21 +128,21 @@ public class MetricsConsumersTest { assertEquals(numMetricsForVespaConsumer + 1, vespaConsumer.metric().size()); Metric customMetric1 = new Metric("custom.metric1"); - assertTrue("Did not contain metric: " + customMetric1, checkMetric(vespaConsumer, customMetric1)); + assertTrue(checkMetric(vespaConsumer, customMetric1), "Did not contain metric: " + customMetric1); } @Test - public void consumer_id_is_case_insensitive() { + void consumer_id_is_case_insensitive() { String services = String.join("\n", - "<services>", - " <admin version='2.0'>", - " <adminserver hostalias='node1'/>", - " <metrics>", - " <consumer id='A'/>", - " <consumer id='a'/>", - " </metrics>", - " </admin>", - "</services>" + "<services>", + " <admin version='2.0'>", + " <adminserver hostalias='node1'/>", + " <metrics>", + " <consumer id='A'/>", + " <consumer id='a'/>", + " </metrics>", + " </admin>", + "</services>" ); try { @@ -156,18 +154,18 @@ public class MetricsConsumersTest { } @Test - public void non_existent_metric_set_causes_exception() { + void non_existent_metric_set_causes_exception() { String services = String.join("\n", - "<services>", - " <admin version='2.0'>", - " <adminserver hostalias='node1'/>", - " <metrics>", - " <consumer id='consumer-with-non-existent-default-set'>", - " <metric-set id='non-existent'/>", - " </consumer>", - " </metrics>", - " </admin>", - "</services>" + "<services>", + " <admin version='2.0'>", + " <adminserver hostalias='node1'/>", + " <metrics>", + " <consumer id='consumer-with-non-existent-default-set'>", + " <metric-set id='non-existent'/>", + " </consumer>", + " </metrics>", + " </admin>", + "</services>" ); try { consumersConfigFromXml(services, self_hosted); @@ -178,19 +176,19 @@ public class MetricsConsumersTest { } @Test - public void consumer_with_no_metric_set_has_its_own_metrics_plus_system_metrics_plus_default_vespa_metrics() { + void consumer_with_no_metric_set_has_its_own_metrics_plus_system_metrics_plus_default_vespa_metrics() { String services = String.join("\n", - "<services>", - " <admin version='2.0'>", - " <adminserver hostalias='node1'/>", - " <metrics>", - " <consumer id='consumer-with-metrics-only'>", - " <metric id='custom.metric1'/>", - " <metric id='custom.metric2'/>", - " </consumer>", - " </metrics>", - " </admin>", - "</services>" + "<services>", + " <admin version='2.0'>", + " <adminserver hostalias='node1'/>", + " <metrics>", + " <consumer id='consumer-with-metrics-only'>", + " <metric id='custom.metric1'/>", + " <metric id='custom.metric2'/>", + " </consumer>", + " </metrics>", + " </admin>", + "</services>" ); ConsumersConfig.Consumer consumer = getCustomConsumer(services); @@ -198,53 +196,53 @@ public class MetricsConsumersTest { Metric customMetric1 = new Metric("custom.metric1"); Metric customMetric2 = new Metric("custom.metric2"); - assertTrue("Did not contain metric: " + customMetric1, checkMetric(consumer, customMetric1)); - assertTrue("Did not contain metric: " + customMetric2, checkMetric(consumer, customMetric2)); + assertTrue(checkMetric(consumer, customMetric1), "Did not contain metric: " + customMetric1); + assertTrue(checkMetric(consumer, customMetric2), "Did not contain metric: " + customMetric2); } @Test - public void consumer_with_default_metric_set_has_all_its_metrics_plus_all_system_metrics_plus_its_own() { + void consumer_with_default_metric_set_has_all_its_metrics_plus_all_system_metrics_plus_its_own() { String services = String.join("\n", - "<services>", - " <admin version='2.0'>", - " <adminserver hostalias='node1'/>", - " <metrics>", - " <consumer id='consumer-with-public-default-set'>", - " <metric-set id='default'/>", - " <metric id='custom.metric'/>", - " </consumer>", - " </metrics>", - " </admin>", - "</services>" + "<services>", + " <admin version='2.0'>", + " <adminserver hostalias='node1'/>", + " <metrics>", + " <consumer id='consumer-with-public-default-set'>", + " <metric-set id='default'/>", + " <metric id='custom.metric'/>", + " </consumer>", + " </metrics>", + " </admin>", + "</services>" ); ConsumersConfig.Consumer consumer = getCustomConsumer(services); assertEquals(numPublicDefaultMetrics + numSystemMetrics + 1, consumer.metric().size()); Metric customMetric = new Metric("custom.metric"); - assertTrue("Did not contain metric: " + customMetric, checkMetric(consumer, customMetric)); + assertTrue(checkMetric(consumer, customMetric), "Did not contain metric: " + customMetric); } @Test - public void consumer_with_vespa_metric_set_has_all_vespa_metrics_plus_all_system_metrics_plus_its_own() { + void consumer_with_vespa_metric_set_has_all_vespa_metrics_plus_all_system_metrics_plus_its_own() { String services = String.join("\n", - "<services>", - " <admin version='2.0'>", - " <adminserver hostalias='node1'/>", - " <metrics>", - " <consumer id='consumer-with-vespa-set'>", - " <metric-set id='vespa'/>", - " <metric id='my.extra.metric'/>", - " </consumer>", - " </metrics>", - " </admin>", - "</services>" + "<services>", + " <admin version='2.0'>", + " <adminserver hostalias='node1'/>", + " <metrics>", + " <consumer id='consumer-with-vespa-set'>", + " <metric-set id='vespa'/>", + " <metric id='my.extra.metric'/>", + " </consumer>", + " </metrics>", + " </admin>", + "</services>" ); ConsumersConfig.Consumer consumer = getCustomConsumer(services); assertEquals(numVespaMetrics + numSystemMetrics + 1, consumer.metric().size()); Metric customMetric = new Metric("my.extra.metric"); - assertTrue("Did not contain metric: " + customMetric, checkMetric(consumer, customMetric)); + assertTrue(checkMetric(consumer, customMetric), "Did not contain metric: " + customMetric); } } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsProxyContainerClusterTest.java b/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsProxyContainerClusterTest.java index e378440312d..0eb1db1acaa 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsProxyContainerClusterTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsProxyContainerClusterTest.java @@ -18,7 +18,7 @@ import com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyContainerCluster.App import com.yahoo.vespa.model.container.PlatformBundles; import com.yahoo.vespa.model.container.component.Component; import com.yahoo.vespa.model.container.component.Handler; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.nio.file.Path; import java.util.Collection; @@ -39,8 +39,8 @@ import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyModelTester.g import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyModelTester.servicesWithAdminOnly; import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toSet; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author gjoranv @@ -48,15 +48,15 @@ import static org.junit.Assert.assertTrue; public class MetricsProxyContainerClusterTest { @Test - public void metrics_proxy_bundle_is_included_in_bundles_config() { + void metrics_proxy_bundle_is_included_in_bundles_config() { VespaModel model = getModel(servicesWithAdminOnly(), self_hosted); PlatformBundlesConfig config = model.getConfig(PlatformBundlesConfig.class, CLUSTER_CONFIG_ID); assertTrue(config.bundlePaths().stream() - .anyMatch(p -> p.equals(METRICS_PROXY_BUNDLE_FILE.toString()))); + .anyMatch(p -> p.equals(METRICS_PROXY_BUNDLE_FILE.toString()))); } @Test - public void unnecessary_bundles_are_not_installed() { + void unnecessary_bundles_are_not_installed() { VespaModel model = getModel(servicesWithAdminOnly(), self_hosted); PlatformBundlesConfig config = model.getConfig(PlatformBundlesConfig.class, CLUSTER_CONFIG_ID); @@ -67,11 +67,11 @@ public class MetricsProxyContainerClusterTest { ).map(Path::toString).collect(toSet()); assertTrue(config.bundlePaths().stream() - .noneMatch(unnecessaryBundles::contains)); + .noneMatch(unnecessaryBundles::contains)); } @Test - public void cluster_is_prepared_so_that_application_metadata_config_is_produced() { + void cluster_is_prepared_so_that_application_metadata_config_is_produced() { VespaModel model = getModel(servicesWithAdminOnly(), self_hosted); ApplicationMetadataConfig config = model.getConfig(ApplicationMetadataConfig.class, CLUSTER_CONFIG_ID); assertEquals(MockApplicationPackage.APPLICATION_GENERATION, config.generation()); @@ -79,7 +79,7 @@ public class MetricsProxyContainerClusterTest { } @Test - public void http_handlers_are_set_up() { + void http_handlers_are_set_up() { VespaModel model = getModel(servicesWithAdminOnly(), self_hosted); Collection<Handler> handlers = model.getAdmin().getMetricsProxyCluster().getHandlers(); Collection<ComponentSpecification> handlerClasses = handlers.stream().map(Component::getClassId).collect(toList()); @@ -91,7 +91,7 @@ public class MetricsProxyContainerClusterTest { } @Test - public void hosted_application_propagates_application_dimensions() { + void hosted_application_propagates_application_dimensions() { VespaModel hostedModel = getModel(servicesWithAdminOnly(), hosted); ApplicationDimensionsConfig config = getApplicationDimensionsConfig(hostedModel); @@ -105,7 +105,7 @@ public class MetricsProxyContainerClusterTest { } @Test - public void all_nodes_are_included_in_metrics_nodes_config() { + void all_nodes_are_included_in_metrics_nodes_config() { VespaModel hostedModel = getModel(servicesWithTwoNodes(), hosted); MetricsNodesConfig config = getMetricsNodesConfig(hostedModel); assertEquals(2, config.node().size()); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsProxyContainerTest.java b/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsProxyContainerTest.java index 9b1ff54482b..5394b807861 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsProxyContainerTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsProxyContainerTest.java @@ -8,7 +8,7 @@ import ai.vespa.metricsproxy.rpc.RpcConnectorConfig; import ai.vespa.metricsproxy.service.VespaServicesConfig; import com.yahoo.vespa.model.VespaModel; import com.yahoo.vespa.model.test.VespaModelTester; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static com.yahoo.config.model.api.container.ContainerServiceType.METRICS_PROXY_CONTAINER; import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyModelTester.CONTAINER_CONFIG_ID; @@ -20,9 +20,7 @@ import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyModelTester.g import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyModelTester.getNodeDimensionsConfig; import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyModelTester.getRpcConnectorConfig; import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyModelTester.getVespaServicesConfig; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * @author gjoranv @@ -30,7 +28,7 @@ import static org.junit.Assert.assertTrue; public class MetricsProxyContainerTest { @Test - public void one_metrics_proxy_container_is_added_to_every_node() { + void one_metrics_proxy_container_is_added_to_every_node() { var numberOfHosts = 7; var tester = new VespaModelTester(); tester.addHosts(numberOfHosts); @@ -42,14 +40,14 @@ public class MetricsProxyContainerTest { assertNotNull(host.getService(METRICS_PROXY_CONTAINER.serviceName)); long metricsProxies = host.getServices().stream() - .filter(s -> s.getClass().equals(MetricsProxyContainer.class)) - .count(); + .filter(s -> s.getClass().equals(MetricsProxyContainer.class)) + .count(); assertEquals(1, metricsProxies); } } @Test - public void one_metrics_proxy_container_is_added_to_every_node_also_when_dedicated_CCC() { + void one_metrics_proxy_container_is_added_to_every_node_also_when_dedicated_CCC() { var numberOfHosts = 7; var tester = new VespaModelTester(); tester.addHosts(numberOfHosts); @@ -61,16 +59,16 @@ public class MetricsProxyContainerTest { assertNotNull(host.getService(METRICS_PROXY_CONTAINER.serviceName)); long metricsProxies = host.getServices().stream() - .filter(s -> s.getClass().equals(MetricsProxyContainer.class)) - .count(); + .filter(s -> s.getClass().equals(MetricsProxyContainer.class)) + .count(); assertEquals(1, metricsProxies); } } @Test - public void http_server_is_running_on_expected_port() { + void http_server_is_running_on_expected_port() { VespaModel model = getModel(hostedServicesWithContent(), self_hosted); - MetricsProxyContainer container = (MetricsProxyContainer)model.id2producer().get(CONTAINER_CONFIG_ID); + MetricsProxyContainer container = (MetricsProxyContainer) model.id2producer().get(CONTAINER_CONFIG_ID); assertEquals(19092, container.getSearchPort()); assertEquals(19092, container.getHealthPort()); @@ -79,9 +77,9 @@ public class MetricsProxyContainerTest { } @Test - public void metrics_rpc_server_is_running_on_expected_port() { + void metrics_rpc_server_is_running_on_expected_port() { VespaModel model = getModel(hostedServicesWithContent(), self_hosted); - MetricsProxyContainer container = (MetricsProxyContainer)model.id2producer().get(CONTAINER_CONFIG_ID); + MetricsProxyContainer container = (MetricsProxyContainer) model.id2producer().get(CONTAINER_CONFIG_ID); int offset = 3; assertEquals(2, container.getPortsMeta().getTagsAt(offset).size()); @@ -93,9 +91,9 @@ public class MetricsProxyContainerTest { } @Test - public void admin_rpc_server_is_running() { + void admin_rpc_server_is_running() { VespaModel model = getModel(hostedServicesWithContent(), self_hosted); - MetricsProxyContainer container = (MetricsProxyContainer)model.id2producer().get(CONTAINER_CONFIG_ID); + MetricsProxyContainer container = (MetricsProxyContainer) model.id2producer().get(CONTAINER_CONFIG_ID); int offset = 2; assertEquals(2, container.getPortsMeta().getTagsAt(offset).size()); @@ -104,15 +102,15 @@ public class MetricsProxyContainerTest { } @Test - public void preload_is_empty() { + void preload_is_empty() { VespaModel model = getModel(hostedServicesWithContent(), self_hosted); - MetricsProxyContainer container = (MetricsProxyContainer)model.id2producer().get(CONTAINER_CONFIG_ID); + MetricsProxyContainer container = (MetricsProxyContainer) model.id2producer().get(CONTAINER_CONFIG_ID); assertEquals("", container.getPreLoad()); } @Test - public void hosted_application_propagates_node_dimensions() { + void hosted_application_propagates_node_dimensions() { String services = hostedServicesWithContent(); VespaModel hostedModel = getModel(services, hosted); assertEquals(4, hostedModel.getHosts().size()); @@ -124,11 +122,11 @@ public class MetricsProxyContainerTest { } @Test - public void metrics_v2_handler_is_set_up_with_node_info_config() { + void metrics_v2_handler_is_set_up_with_node_info_config() { String services = hostedServicesWithContent(); VespaModel hostedModel = getModel(services, hosted); - var container = (MetricsProxyContainer)hostedModel.id2producer().get(containerConfigId(hostedModel, hosted)); + var container = (MetricsProxyContainer) hostedModel.id2producer().get(containerConfigId(hostedModel, hosted)); var handlers = container.getHandlers().getComponents(); assertEquals(1, handlers.size()); @@ -140,13 +138,13 @@ public class MetricsProxyContainerTest { } @Test - public void vespa_services_config_has_all_services() { + void vespa_services_config_has_all_services() { VespaServicesConfig vespaServicesConfig = getVespaServicesConfig(hostedServicesWithContent()); assertEquals(9, vespaServicesConfig.service().size()); for (var service : vespaServicesConfig.service()) { if (service.configId().equals("admin/cluster-controllers/0")) { - assertEquals("Wrong service name", "container-clustercontroller", service.name()); + assertEquals("container-clustercontroller", service.name(), "Wrong service name"); assertEquals(1, service.dimension().size()); assertEquals("clustername", service.dimension(0).key()); assertEquals("cluster-controllers", service.dimension(0).value()); @@ -155,7 +153,7 @@ public class MetricsProxyContainerTest { } @Test - public void vespa_services_config_has_service_dimensions() { + void vespa_services_config_has_service_dimensions() { VespaServicesConfig vespaServicesConfig = getVespaServicesConfig(hostedServicesWithContent()); for (var service : vespaServicesConfig.service()) { if (service.configId().equals("admin/cluster-controllers/0")) { diff --git a/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MonitoringElementTest.java b/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MonitoringElementTest.java index 734844c9c7c..2109359be91 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MonitoringElementTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MonitoringElementTest.java @@ -3,14 +3,14 @@ package com.yahoo.vespa.model.admin.metricsproxy; import ai.vespa.metricsproxy.core.MonitoringConfig; import com.yahoo.vespa.model.VespaModel; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyModelTester.CLUSTER_CONFIG_ID; import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyModelTester.TestMode.hosted; import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyModelTester.TestMode.self_hosted; import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyModelTester.getModel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author gjoranv @@ -18,7 +18,7 @@ import static org.junit.Assert.fail; public class MonitoringElementTest { @Test - public void monitoring_element_is_disallowed_for_hosted_vespa() { + void monitoring_element_is_disallowed_for_hosted_vespa() { String services = servicesWithMonitoringElement(); try { getModel(services, hosted); @@ -29,20 +29,20 @@ public class MonitoringElementTest { } @Test - public void monitoring_element_is_allowed_for_hosted_infrastructure_apps() { + void monitoring_element_is_allowed_for_hosted_infrastructure_apps() { String services = String.join("\n", - "<services application-type='hosted-infrastructure'>", - " <admin version='4.0'>", - " <monitoring interval='300' systemname='my-system' />", - " </admin>", - "</services>" + "<services application-type='hosted-infrastructure'>", + " <admin version='4.0'>", + " <monitoring interval='300' systemname='my-system' />", + " </admin>", + "</services>" ); VespaModel model = getModel(services, hosted); assertMonitoringConfig(model); } @Test - public void monitoring_element_is_allowed_for_self_hosted_vespa() { + void monitoring_element_is_allowed_for_self_hosted_vespa() { String services = servicesWithMonitoringElement(); VespaModel model = getModel(services, self_hosted); assertMonitoringConfig(model); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/TelegrafTest.java b/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/TelegrafTest.java index 5bd364f4e21..5a6a65b5a82 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/TelegrafTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/TelegrafTest.java @@ -6,15 +6,13 @@ import ai.vespa.metricsproxy.telegraf.TelegrafConfig; import ai.vespa.metricsproxy.telegraf.TelegrafRegistry; import com.yahoo.component.ComponentId; import com.yahoo.vespa.model.VespaModel; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyModelTester.CLUSTER_CONFIG_ID; import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyModelTester.TestMode.hosted; import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyModelTester.TestMode.self_hosted; import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyModelTester.getModel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * @author gjoranv @@ -22,7 +20,7 @@ import static org.junit.Assert.assertTrue; public class TelegrafTest { @Test - public void telegraf_components_are_set_up_when_cloudwatch_is_configured() { + void telegraf_components_are_set_up_when_cloudwatch_is_configured() { String services = servicesWithCloudwatch(); VespaModel hostedModel = getModel(services, hosted); @@ -32,16 +30,16 @@ public class TelegrafTest { } @Test - public void telegraf_components_are_not_set_up_when_no_external_systems_are_added_in_services() { + void telegraf_components_are_not_set_up_when_no_external_systems_are_added_in_services() { String services = String.join("\n", - "<services>", - " <admin version='2.0'>", - " <adminserver hostalias='node1'/>", - " <metrics>", - " <consumer id='foo' />", - " </metrics>", - " </admin>", - "</services>"); + "<services>", + " <admin version='2.0'>", + " <adminserver hostalias='node1'/>", + " <metrics>", + " <consumer id='foo' />", + " </metrics>", + " </admin>", + "</services>"); VespaModel hostedModel = getModel(services, hosted); var clusterComponents = hostedModel.getAdmin().getMetricsProxyCluster().getComponentsMap(); @@ -50,7 +48,7 @@ public class TelegrafTest { } @Test - public void telegraf_config_is_generated_for_cloudwatch_in_services() { + void telegraf_config_is_generated_for_cloudwatch_in_services() { String services = servicesWithCloudwatch(); VespaModel hostedModel = getModel(services, hosted); TelegrafConfig config = hostedModel.getConfig(TelegrafConfig.class, CLUSTER_CONFIG_ID); @@ -85,25 +83,25 @@ public class TelegrafTest { } @Test - public void multiple_cloudwatches_are_allowed_for_the_same_consumer() { + void multiple_cloudwatches_are_allowed_for_the_same_consumer() { String services = String.join("\n", - "<services>", - " <admin version='2.0'>", - " <adminserver hostalias='node1'/>", - " <metrics>", - " <consumer id='cloudwatch-consumer'>", - " <metric id='my-metric'/>", - " <cloudwatch region='us-east-1' namespace='namespace-1' >", - " <credentials access-key-name='access-key-1' ", - " secret-key-name='secret-key-1' />", - " </cloudwatch>", - " <cloudwatch region='us-east-1' namespace='namespace-2' >", - " <shared-credentials profile='profile-2' />", - " </cloudwatch>", - " </consumer>", - " </metrics>", - " </admin>", - "</services>" + "<services>", + " <admin version='2.0'>", + " <adminserver hostalias='node1'/>", + " <metrics>", + " <consumer id='cloudwatch-consumer'>", + " <metric id='my-metric'/>", + " <cloudwatch region='us-east-1' namespace='namespace-1' >", + " <credentials access-key-name='access-key-1' ", + " secret-key-name='secret-key-1' />", + " </cloudwatch>", + " <cloudwatch region='us-east-1' namespace='namespace-2' >", + " <shared-credentials profile='profile-2' />", + " </cloudwatch>", + " </consumer>", + " </metrics>", + " </admin>", + "</services>" ); VespaModel hostedModel = getModel(services, hosted); TelegrafConfig config = hostedModel.getConfig(TelegrafConfig.class, CLUSTER_CONFIG_ID); @@ -126,21 +124,21 @@ public class TelegrafTest { } @Test - public void profile_named_default_is_used_when_no_profile_is_given_in_shared_credentials() { + void profile_named_default_is_used_when_no_profile_is_given_in_shared_credentials() { String services = String.join("\n", - "<services>", - " <admin version='2.0'>", - " <adminserver hostalias='node1'/>", - " <metrics>", - " <consumer id='cloudwatch-consumer'>", - " <metric id='my-metric'/>", - " <cloudwatch region='us-east-1' namespace='foo' >", - " <shared-credentials file='/path/to/file' />", - " </cloudwatch>", - " </consumer>", - " </metrics>", - " </admin>", - "</services>" + "<services>", + " <admin version='2.0'>", + " <adminserver hostalias='node1'/>", + " <metrics>", + " <consumer id='cloudwatch-consumer'>", + " <metric id='my-metric'/>", + " <cloudwatch region='us-east-1' namespace='foo' >", + " <shared-credentials file='/path/to/file' />", + " </cloudwatch>", + " </consumer>", + " </metrics>", + " </admin>", + "</services>" ); VespaModel model = getModel(services, self_hosted); TelegrafConfig config = model.getConfig(TelegrafConfig.class, CLUSTER_CONFIG_ID); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/admin/monitoring/MetricSetTest.java b/config-model/src/test/java/com/yahoo/vespa/model/admin/monitoring/MetricSetTest.java index b78d7b9723f..8a15d87b6c5 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/admin/monitoring/MetricSetTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/admin/monitoring/MetricSetTest.java @@ -4,13 +4,13 @@ package com.yahoo.vespa.model.admin.monitoring; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Sets; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Map; import static java.util.Collections.emptyList; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author gjoranv @@ -18,7 +18,7 @@ import static org.junit.Assert.assertNotNull; public class MetricSetTest { @Test - public void metrics_from_children_are_added() { + void metrics_from_children_are_added() { MetricSet child1 = new MetricSet("child1", ImmutableList.of(new Metric("child1_metric"))); MetricSet child2 = new MetricSet("child2", ImmutableList.of(new Metric("child2_metric"))); MetricSet parent = new MetricSet("parent", emptyList(), ImmutableList.of(child1, child2)); @@ -30,7 +30,7 @@ public class MetricSetTest { } @Test - public void adding_the_same_child_set_twice_has_no_effect() { + void adding_the_same_child_set_twice_has_no_effect() { MetricSet child = new MetricSet("child", ImmutableList.of(new Metric("child_metric"))); MetricSet parent = new MetricSet("parent", emptyList(), ImmutableList.of(child, child)); @@ -40,7 +40,7 @@ public class MetricSetTest { } @Test - public void internal_metrics_take_precedence_over_metrics_from_children() { + void internal_metrics_take_precedence_over_metrics_from_children() { String METRIC_NAME = "metric1"; String COMMON_DIMENSION_KEY = "commonKey"; diff --git a/config-model/src/test/java/com/yahoo/vespa/model/admin/monitoring/MetricTest.java b/config-model/src/test/java/com/yahoo/vespa/model/admin/monitoring/MetricTest.java index efb0f337198..e87bb90c36b 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/admin/monitoring/MetricTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/admin/monitoring/MetricTest.java @@ -2,11 +2,11 @@ package com.yahoo.vespa.model.admin.monitoring; import com.google.common.collect.ImmutableMap; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Map; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author gjoranv @@ -14,7 +14,7 @@ import static org.junit.Assert.assertEquals; public class MetricTest { @Test - public void this_metric_takes_precedence_when_combined_with_another_metric() { + void this_metric_takes_precedence_when_combined_with_another_metric() { String COMMON_DIMENSION_KEY = "commonKey"; Map<String, String> thisDimensions = ImmutableMap.<String, String>builder() diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/AccessControlFilterValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/AccessControlFilterValidatorTest.java index 86d4c527670..d9f0a80e1cb 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/AccessControlFilterValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/AccessControlFilterValidatorTest.java @@ -7,13 +7,13 @@ import com.yahoo.config.model.deploy.DeployState; import com.yahoo.config.model.test.MockApplicationPackage; import com.yahoo.config.model.test.ModelBuilderAddingAccessControlFilter; import com.yahoo.vespa.model.VespaModel; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.xml.sax.SAXException; import java.io.IOException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author bjorncs @@ -34,7 +34,7 @@ public class AccessControlFilterValidatorTest { @Test - public void validator_fails_with_empty_access_control_filter_chain() throws IOException, SAXException { + void validator_fails_with_empty_access_control_filter_chain() throws IOException, SAXException { DeployState deployState = createDeployState(); VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState); @@ -47,7 +47,7 @@ public class AccessControlFilterValidatorTest { } @Test - public void validator_accepts_non_empty_access_control_filter_chain() throws IOException, SAXException { + void validator_accepts_non_empty_access_control_filter_chain() throws IOException, SAXException { DeployState deployState = createDeployState(); VespaModel model = new VespaModel( MapConfigModelRegistry.createFromList(new ModelBuilderAddingAccessControlFilter()), diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/AccessControlValidatorTestBase.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/AccessControlValidatorTestBase.java index 107ee8aef72..8ca973dc59f 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/AccessControlValidatorTestBase.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/AccessControlValidatorTestBase.java @@ -8,7 +8,7 @@ import com.yahoo.config.model.deploy.TestProperties; import com.yahoo.config.model.test.MockApplicationPackage; import com.yahoo.config.provision.Zone; import com.yahoo.vespa.model.VespaModel; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.xml.sax.SAXException; import java.io.IOException; @@ -19,9 +19,7 @@ import java.time.format.DateTimeFormatter; import static com.yahoo.config.model.test.TestUtil.joinLines; import static com.yahoo.config.provision.Environment.prod; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; /** * @author gjoranv @@ -50,7 +48,7 @@ public abstract class AccessControlValidatorTestBase { " </handler>"); @Test - public void cluster_with_protection_passes_validation() throws IOException, SAXException { + void cluster_with_protection_passes_validation() throws IOException, SAXException { DeployState deployState = deployState(servicesXml(true, true)); VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState); @@ -58,7 +56,7 @@ public abstract class AccessControlValidatorTestBase { } @Test - public void cluster_with_no_handlers_passes_validation_without_protection() throws IOException, SAXException{ + void cluster_with_no_handlers_passes_validation_without_protection() throws IOException, SAXException { DeployState deployState = deployState(servicesXml(false, false)); VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState); @@ -66,10 +64,10 @@ public abstract class AccessControlValidatorTestBase { } @Test - public void cluster_without_custom_components_passes_validation_without_protection() throws IOException, SAXException{ + void cluster_without_custom_components_passes_validation_without_protection() throws IOException, SAXException { String servicesXml = joinLines("<services version='1.0'>", - " <container id='default' version='1.0' />", - "</services>"); + " <container id='default' version='1.0' />", + "</services>"); DeployState deployState = deployState(servicesXml); VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState); @@ -77,7 +75,7 @@ public abstract class AccessControlValidatorTestBase { } @Test - public void cluster_with_handler_fails_validation_without_protection() throws IOException, SAXException{ + void cluster_with_handler_fails_validation_without_protection() throws IOException, SAXException { DeployState deployState = deployState(servicesXml(true, false)); VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState); @@ -91,12 +89,12 @@ public abstract class AccessControlValidatorTestBase { } @Test - public void no_http_element_has_same_effect_as_no_write_protection() throws IOException, SAXException{ + void no_http_element_has_same_effect_as_no_write_protection() throws IOException, SAXException { String servicesXml = joinLines("<services version='1.0'>", - " <container id='default' version='1.0'>", - httpHandlerXml, - " </container>", - "</services>"); + " <container id='default' version='1.0'>", + httpHandlerXml, + " </container>", + "</services>"); DeployState deployState = deployState(servicesXml); VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState); @@ -110,14 +108,14 @@ public abstract class AccessControlValidatorTestBase { } @Test - public void cluster_with_mbus_handler_passes_validation_without_write_protection() throws IOException, SAXException{ + void cluster_with_mbus_handler_passes_validation_without_write_protection() throws IOException, SAXException { String servicesXml = joinLines("<services version='1.0'>", - " <container id='default' version='1.0'>", - " <handler id='foo'>", - " <binding>mbus://*/foo</binding>", - " </handler>", - " </container>", - "</services>"); + " <container id='default' version='1.0'>", + " <handler id='foo'>", + " <binding>mbus://*/foo</binding>", + " </handler>", + " </container>", + "</services>"); DeployState deployState = deployState(servicesXml); VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState); @@ -125,12 +123,12 @@ public abstract class AccessControlValidatorTestBase { } @Test - public void write_protection_is_not_required_for_non_default_application_type() throws IOException, SAXException{ + void write_protection_is_not_required_for_non_default_application_type() throws IOException, SAXException { String servicesXml = joinLines("<services version='1.0' application-type='hosted-infrastructure'>", - " <container id='default' version='1.0'>", - httpHandlerXml, - " </container>", - "</services>"); + " <container id='default' version='1.0'>", + httpHandlerXml, + " </container>", + "</services>"); DeployState deployState = deployState(servicesXml); VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState); @@ -138,10 +136,10 @@ public abstract class AccessControlValidatorTestBase { } @Test - public void write_protection_is_not_required_with_validation_override() throws IOException, SAXException{ + void write_protection_is_not_required_with_validation_override() throws IOException, SAXException { DeployState deployState = deployState(servicesXml(true, false), - "<validation-overrides><allow until='2000-01-30'>access-control</allow></validation-overrides>", - LocalDate.parse("2000-01-01", DateTimeFormatter.ISO_DATE).atStartOfDay().atZone(ZoneOffset.UTC).toInstant()); + "<validation-overrides><allow until='2000-01-30'>access-control</allow></validation-overrides>", + LocalDate.parse("2000-01-01", DateTimeFormatter.ISO_DATE).atStartOfDay().atZone(ZoneOffset.UTC).toInstant()); VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState); validator.validate(model, deployState); @@ -164,8 +162,8 @@ public abstract class AccessControlValidatorTestBase { .now(now); final DeployState deployState = builder.build(); - assertTrue("Test must emulate a hosted deployment.", deployState.isHosted()); - assertEquals("Test must emulate a prod environment.", prod, deployState.zone().environment()); + assertTrue(deployState.isHosted(), "Test must emulate a hosted deployment."); + assertEquals(prod, deployState.zone().environment(), "Test must emulate a prod environment."); return deployState; } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/BundleValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/BundleValidatorTest.java index facd3cfdff4..e26a8e8bac6 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/BundleValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/BundleValidatorTest.java @@ -3,10 +3,10 @@ package com.yahoo.vespa.model.application.validation; import com.yahoo.config.application.api.DeployLogger; import com.yahoo.config.model.deploy.DeployState; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; @@ -17,15 +17,15 @@ import java.util.jar.JarOutputStream; import static com.yahoo.yolean.Exceptions.uncheck; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class BundleValidatorTest { - @Rule - public TemporaryFolder tempDir = new TemporaryFolder(); + @TempDir + public File tempDir; @Test - public void basicBundleValidation() throws Exception { + void basicBundleValidation() throws Exception { // Valid jar file JarFile ok = createTemporaryJarFile("ok"); BundleValidator bundleValidator = new BundleValidator(); @@ -42,12 +42,12 @@ public class BundleValidatorTest { bundleValidator.validateJarFile(DeployState.createTestState(), jarFile); assert (false); } catch (IllegalArgumentException e) { - assertEquals(e.getMessage(), exceptionMessage); + assertEquals(exceptionMessage, e.getMessage()); } } @Test - public void require_that_deploying_snapshot_bundle_gives_warning() throws IOException { + void require_that_deploying_snapshot_bundle_gives_warning() throws IOException { final StringBuffer buffer = new StringBuffer(); DeployState state = createDeployState(buffer); @@ -57,7 +57,7 @@ public class BundleValidatorTest { } @Test - public void outputs_deploy_warning_on_import_of_packages_from_deprecated_artifact() throws IOException { + void outputs_deploy_warning_on_import_of_packages_from_deprecated_artifact() throws IOException { final StringBuffer buffer = new StringBuffer(); DeployState state = createDeployState(buffer); BundleValidator validator = new BundleValidator(); @@ -78,7 +78,7 @@ public class BundleValidatorTest { } private JarFile createTemporaryJarFile(String testArtifact) throws IOException { - Path jarFile = tempDir.newFile(testArtifact + ".jar").toPath(); + Path jarFile = Paths.get(tempDir.toString(), testArtifact + ".jar"); Path artifactDirectory = Paths.get("src/test/cfg/application/validation/testjars/" + testArtifact); try (JarOutputStream out = new JarOutputStream(Files.newOutputStream(jarFile))) { Files.walk(artifactDirectory).forEach(path -> { diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/CloudWatchValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/CloudWatchValidatorTest.java index 92aa3151d91..f600900d3cd 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/CloudWatchValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/CloudWatchValidatorTest.java @@ -11,15 +11,13 @@ import com.yahoo.config.provision.RegionName; import com.yahoo.config.provision.SystemName; import com.yahoo.config.provision.Zone; import com.yahoo.vespa.model.VespaModel; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.xml.sax.SAXException; import java.io.IOException; import static com.yahoo.config.provision.Environment.prod; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; /** @@ -28,7 +26,7 @@ import static org.junit.Assert.fail; public class CloudWatchValidatorTest { @Test - public void cloudwatch_in_public_zones_passes_validation() throws IOException, SAXException { + void cloudwatch_in_public_zones_passes_validation() throws IOException, SAXException { DeployState deployState = deployState(servicesWithCloudwatch(), true, true); VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState); @@ -36,7 +34,7 @@ public class CloudWatchValidatorTest { } @Test - public void cloudwatch_passes_validation_for_self_hosted_vespa() throws IOException, SAXException { + void cloudwatch_passes_validation_for_self_hosted_vespa() throws IOException, SAXException { DeployState deployState = deployState(servicesWithCloudwatch(), false, false); VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState); @@ -44,7 +42,7 @@ public class CloudWatchValidatorTest { } @Test - public void cloudwatch_in_non_public_zones_fails_validation() throws IOException, SAXException { + void cloudwatch_in_non_public_zones_fails_validation() throws IOException, SAXException { DeployState deployState = deployState(servicesWithCloudwatch(), true, false); VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState); @@ -72,8 +70,8 @@ public class CloudWatchValidatorTest { final DeployState deployState = builder.build(); if (isHosted) { - assertTrue("Test must emulate a hosted deployment.", deployState.isHosted()); - assertEquals("Test must emulate a prod environment.", prod, deployState.zone().environment()); + assertTrue(deployState.isHosted(), "Test must emulate a hosted deployment."); + assertEquals(prod, deployState.zone().environment(), "Test must emulate a prod environment."); } return deployState; } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/ComplexFieldsValidatorTestCase.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/ComplexFieldsValidatorTestCase.java index a25b2fdda32..c673d5899e8 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/ComplexFieldsValidatorTestCase.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/ComplexFieldsValidatorTestCase.java @@ -10,9 +10,7 @@ import com.yahoo.config.model.deploy.DeployState; import com.yahoo.config.model.test.MockApplicationPackage; import com.yahoo.vespa.model.VespaModel; import com.yahoo.vespa.model.content.utils.ContentClusterBuilder; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; import org.xml.sax.SAXException; import java.io.IOException; @@ -21,56 +19,56 @@ import java.util.logging.Level; import static com.yahoo.config.model.test.TestUtil.joinLines; import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author geirst */ public class ComplexFieldsValidatorTestCase { - @SuppressWarnings("deprecation") - @Rule - public final ExpectedException exceptionRule = ExpectedException.none(); - @Test - public void throws_exception_when_unsupported_complex_fields_have_struct_field_attributes() throws IOException, SAXException { - exceptionRule.expect(IllegalArgumentException.class); - exceptionRule.expectMessage(getExpectedMessage("struct_array (struct_array.f1), struct_map (struct_map.value.f1)")); - createModelAndValidate(joinLines("search test {", - " document test {", - " struct s { field f1 type array<int> {} }", - " field struct_array type array<s> {", - " struct-field f1 { indexing: attribute }", - " }", - " field struct_map type map<string,s> {", - " struct-field key { indexing: attribute }", - " struct-field value.f1 { indexing: attribute }", - " }", - " }", - "}")); + void throws_exception_when_unsupported_complex_fields_have_struct_field_attributes() throws IOException, SAXException { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + createModelAndValidate(joinLines("search test {", + " document test {", + " struct s { field f1 type array<int> {} }", + " field struct_array type array<s> {", + " struct-field f1 { indexing: attribute }", + " }", + " field struct_map type map<string,s> {", + " struct-field key { indexing: attribute }", + " struct-field value.f1 { indexing: attribute }", + " }", + " }", + "}")); + }); + assertTrue(exception.getMessage().contains(getExpectedMessage("struct_array (struct_array.f1), struct_map (struct_map.value.f1)"))); } @Test - public void throws_exception_when_nested_struct_array_is_specified_as_struct_field_attribute() throws IOException, SAXException { - exceptionRule.expect(IllegalArgumentException.class); - exceptionRule.expectMessage(getExpectedMessage("docTopics (docTopics.topics)")); - createModelAndValidate(joinLines( - "schema test {", - "document test {", - "struct topic {", - " field id type string {}", - " field label type string {}", - "}", - "struct docTopic {", - " field id type string {}", - " field topics type array<topic> {}", - "}", - "field docTopics type array<docTopic> {", - " indexing: summary", - " struct-field id { indexing: attribute }", - " struct-field topics { indexing: attribute }", - "}", - "}", - "}")); + void throws_exception_when_nested_struct_array_is_specified_as_struct_field_attribute() throws IOException, SAXException { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + createModelAndValidate(joinLines( + "schema test {", + "document test {", + "struct topic {", + " field id type string {}", + " field label type string {}", + "}", + "struct docTopic {", + " field id type string {}", + " field topics type array<topic> {}", + "}", + "field docTopics type array<docTopic> {", + " indexing: summary", + " struct-field id { indexing: attribute }", + " struct-field topics { indexing: attribute }", + "}", + "}", + "}")); + }); + assertTrue(exception.getMessage().contains(getExpectedMessage("docTopics (docTopics.topics)"))); } private String getExpectedMessage(String unsupportedFields) { @@ -89,7 +87,7 @@ public class ComplexFieldsValidatorTestCase { } @Test - public void logs_warning_when_complex_fields_have_struct_fields_with_index() throws IOException, SAXException { + void logs_warning_when_complex_fields_have_struct_fields_with_index() throws IOException, SAXException { var logger = new MyLogger(); createModelAndValidate(joinLines( "schema test {", @@ -109,13 +107,13 @@ public class ComplexFieldsValidatorTestCase { "}"), logger); assertThat(logger.message.toString().contains( "For cluster 'mycluster', schema 'test': " + - "The following complex fields have struct fields with 'indexing: index' which is not supported and has no effect: " + - "topics (topics.id, topics.label). " + - "Remove setting or change to 'indexing: attribute' if needed for matching.")); + "The following complex fields have struct fields with 'indexing: index' which is not supported and has no effect: " + + "topics (topics.id, topics.label). " + + "Remove setting or change to 'indexing: attribute' if needed for matching.")); } @Test - public void validation_passes_when_only_supported_struct_field_attributes_are_used() throws IOException, SAXException { + void validation_passes_when_only_supported_struct_field_attributes_are_used() throws IOException, SAXException { createModelAndValidate(joinLines("search test {", " document test {", " struct s1 {", diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/ConstantTensorJsonValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/ConstantTensorJsonValidatorTest.java index 3b5c621a581..80643917a58 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/ConstantTensorJsonValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/ConstantTensorJsonValidatorTest.java @@ -2,15 +2,15 @@ package com.yahoo.vespa.model.application.validation; import com.yahoo.tensor.TensorType; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; import java.io.Reader; import java.io.StringReader; import static com.yahoo.test.json.JsonTestHelper.inputJson; import static com.yahoo.vespa.model.application.validation.ConstantTensorJsonValidator.InvalidConstantTensorException; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; public class ConstantTensorJsonValidatorTest { @@ -22,12 +22,8 @@ public class ConstantTensorJsonValidatorTest { new ConstantTensorJsonValidator().validate("dummy.json", tensorType, jsonTensorReader); } - @SuppressWarnings("deprecation") - @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Test - public void ensure_that_unbounded_tensor_works() { + void ensure_that_unbounded_tensor_works() { validateTensorJson( TensorType.fromSpec("tensor(x[], y[])"), inputJsonToReader( @@ -42,7 +38,7 @@ public class ConstantTensorJsonValidatorTest { } @Test - public void ensure_that_bounded_tensor_within_limits_works() { + void ensure_that_bounded_tensor_within_limits_works() { validateTensorJson( TensorType.fromSpec("tensor(x[5], y[10])"), inputJsonToReader( @@ -57,7 +53,7 @@ public class ConstantTensorJsonValidatorTest { } @Test - public void ensure_that_multiple_cells_work() { + void ensure_that_multiple_cells_work() { validateTensorJson( TensorType.fromSpec("tensor(x[], y[])"), inputJsonToReader( @@ -77,7 +73,7 @@ public class ConstantTensorJsonValidatorTest { @Test - public void ensure_that_no_cells_work() { + void ensure_that_no_cells_work() { validateTensorJson( TensorType.fromSpec("tensor(x[], y[])"), inputJsonToReader( @@ -87,25 +83,26 @@ public class ConstantTensorJsonValidatorTest { } @Test - public void ensure_that_bound_tensor_outside_limits_is_disallowed() { - expectedException.expect(InvalidConstantTensorException.class); - expectedException.expectMessage("Index 5 not within limits of bound dimension 'x'"); - - validateTensorJson( - TensorType.fromSpec("tensor(x[5], y[10])"), - inputJsonToReader( - "{", - " 'cells': [", - " {", - " 'address': { 'x': '5', 'y': '2' },", - " 'value': 1e47", - " }", - " ]", - "}")); + void ensure_that_bound_tensor_outside_limits_is_disallowed() { + Throwable exception = assertThrows(InvalidConstantTensorException.class, () -> { + + validateTensorJson( + TensorType.fromSpec("tensor(x[5], y[10])"), + inputJsonToReader( + "{", + " 'cells': [", + " {", + " 'address': { 'x': '5', 'y': '2' },", + " 'value': 1e47", + " }", + " ]", + "}")); + }); + assertTrue(exception.getMessage().contains("Index 5 not within limits of bound dimension 'x'")); } @Test - public void ensure_that_mapped_tensor_works() { + void ensure_that_mapped_tensor_works() { validateTensorJson( TensorType.fromSpec("tensor(x{}, y{})"), inputJsonToReader( @@ -120,162 +117,171 @@ public class ConstantTensorJsonValidatorTest { } @Test - public void ensure_that_non_integer_strings_in_address_points_are_disallowed_unbound() { - expectedException.expect(InvalidConstantTensorException.class); - expectedException.expectMessage("Index 'a' for dimension 'x' is not an integer"); - - validateTensorJson( - TensorType.fromSpec("tensor(x[])"), - inputJsonToReader( - "{", - " 'cells': [", - " {", - " 'address': { 'x': 'a' },", - " 'value': 47.0", - " }", - " ]", - "}")); + void ensure_that_non_integer_strings_in_address_points_are_disallowed_unbound() { + Throwable exception = assertThrows(InvalidConstantTensorException.class, () -> { + + validateTensorJson( + TensorType.fromSpec("tensor(x[])"), + inputJsonToReader( + "{", + " 'cells': [", + " {", + " 'address': { 'x': 'a' },", + " 'value': 47.0", + " }", + " ]", + "}")); + }); + assertTrue(exception.getMessage().contains("Index 'a' for dimension 'x' is not an integer")); } @Test - public void ensure_that_tensor_coordinates_are_strings() { - expectedException.expect(InvalidConstantTensorException.class); - expectedException.expectMessage("Tensor label is not a string (VALUE_NUMBER_INT)"); - - validateTensorJson( - TensorType.fromSpec("tensor(x[])"), - inputJsonToReader( - "{", - " 'cells': [", - " {", - " 'address': { 'x': 47 },", - " 'value': 33.0", - " }", - " ]", - "}")); + void ensure_that_tensor_coordinates_are_strings() { + Throwable exception = assertThrows(InvalidConstantTensorException.class, () -> { + + validateTensorJson( + TensorType.fromSpec("tensor(x[])"), + inputJsonToReader( + "{", + " 'cells': [", + " {", + " 'address': { 'x': 47 },", + " 'value': 33.0", + " }", + " ]", + "}")); + }); + assertTrue(exception.getMessage().contains("Tensor label is not a string (VALUE_NUMBER_INT)")); } @Test - public void ensure_that_non_integer_strings_in_address_points_are_disallowed_bounded() { - expectedException.expect(InvalidConstantTensorException.class); - expectedException.expectMessage("Index 'a' for dimension 'x' is not an integer"); - - validateTensorJson( - TensorType.fromSpec("tensor(x[5])"), - inputJsonToReader( - "{", - " 'cells': [", - " {", - " 'address': { 'x': 'a' },", - " 'value': 41.0", - " }", - " ]", - "}")); + void ensure_that_non_integer_strings_in_address_points_are_disallowed_bounded() { + Throwable exception = assertThrows(InvalidConstantTensorException.class, () -> { + + validateTensorJson( + TensorType.fromSpec("tensor(x[5])"), + inputJsonToReader( + "{", + " 'cells': [", + " {", + " 'address': { 'x': 'a' },", + " 'value': 41.0", + " }", + " ]", + "}")); + }); + assertTrue(exception.getMessage().contains("Index 'a' for dimension 'x' is not an integer")); } @Test - public void ensure_that_missing_coordinates_fail() { - expectedException.expect(InvalidConstantTensorException.class); - expectedException.expectMessage("Tensor address missing dimension(s) y, z"); - - validateTensorJson( - TensorType.fromSpec("tensor(x[], y[], z[])"), - inputJsonToReader( - "{", - " 'cells': [", - " {", - " 'address': { 'x': '3' },", - " 'value': 99.3", - " }", - " ]", - "}")); + void ensure_that_missing_coordinates_fail() { + Throwable exception = assertThrows(InvalidConstantTensorException.class, () -> { + + validateTensorJson( + TensorType.fromSpec("tensor(x[], y[], z[])"), + inputJsonToReader( + "{", + " 'cells': [", + " {", + " 'address': { 'x': '3' },", + " 'value': 99.3", + " }", + " ]", + "}")); + }); + assertTrue(exception.getMessage().contains("Tensor address missing dimension(s) y, z")); } @Test - public void ensure_that_non_number_values_are_disallowed() { - expectedException.expect(InvalidConstantTensorException.class); - expectedException.expectMessage("Tensor value is not a number (VALUE_STRING)"); - - validateTensorJson( - TensorType.fromSpec("tensor(x[])"), - inputJsonToReader( - "{", - " 'cells': [", - " {", - " 'address': { 'x': '3' },", - " 'value': 'fruit'", - " }", - " ]", - "}")); + void ensure_that_non_number_values_are_disallowed() { + Throwable exception = assertThrows(InvalidConstantTensorException.class, () -> { + + validateTensorJson( + TensorType.fromSpec("tensor(x[])"), + inputJsonToReader( + "{", + " 'cells': [", + " {", + " 'address': { 'x': '3' },", + " 'value': 'fruit'", + " }", + " ]", + "}")); + }); + assertTrue(exception.getMessage().contains("Tensor value is not a number (VALUE_STRING)")); } @Test - public void ensure_that_extra_dimensions_are_disallowed() { - expectedException.expect(InvalidConstantTensorException.class); - expectedException.expectMessage("Tensor dimension 'z' does not exist"); - - validateTensorJson( - TensorType.fromSpec("tensor(x[], y[])"), - inputJsonToReader( - "{", - " 'cells': [", - " {", - " 'address': { 'x': '3', 'y': '2', 'z': '4' },", - " 'value': 99.3", - " }", - " ]", - "}")); + void ensure_that_extra_dimensions_are_disallowed() { + Throwable exception = assertThrows(InvalidConstantTensorException.class, () -> { + + validateTensorJson( + TensorType.fromSpec("tensor(x[], y[])"), + inputJsonToReader( + "{", + " 'cells': [", + " {", + " 'address': { 'x': '3', 'y': '2', 'z': '4' },", + " 'value': 99.3", + " }", + " ]", + "}")); + }); + assertTrue(exception.getMessage().contains("Tensor dimension 'z' does not exist")); } @Test - public void ensure_that_duplicate_dimensions_are_disallowed() { - expectedException.expect(InvalidConstantTensorException.class); - expectedException.expectMessage("Duplicate tensor dimension 'y'"); - - validateTensorJson( - TensorType.fromSpec("tensor(x[], y[])"), - inputJsonToReader( - "{", - " 'cells': [", - " {", - " 'address': { 'x': '1', 'y': '2', 'y': '4' },", - " 'value': 88.1", - " }", - " ]", - "}")); + void ensure_that_duplicate_dimensions_are_disallowed() { + Throwable exception = assertThrows(InvalidConstantTensorException.class, () -> { + + validateTensorJson( + TensorType.fromSpec("tensor(x[], y[])"), + inputJsonToReader( + "{", + " 'cells': [", + " {", + " 'address': { 'x': '1', 'y': '2', 'y': '4' },", + " 'value': 88.1", + " }", + " ]", + "}")); + }); + assertTrue(exception.getMessage().contains("Duplicate tensor dimension 'y'")); } @Test - public void ensure_that_invalid_json_fails() { - expectedException.expect(InvalidConstantTensorException.class); - expectedException.expectMessage("Failed to parse JSON stream"); - - validateTensorJson( - TensorType.fromSpec("tensor(x[], y[])"), - inputJsonToReader( - "{", - " cells': [", - " {", - " 'address': { 'x': '3' 'y': '2' }", - " 'value': 2.0", - " }", - " ", - "}")); + void ensure_that_invalid_json_fails() { + Throwable exception = assertThrows(InvalidConstantTensorException.class, () -> { + + validateTensorJson( + TensorType.fromSpec("tensor(x[], y[])"), + inputJsonToReader( + "{", + " cells': [", + " {", + " 'address': { 'x': '3' 'y': '2' }", + " 'value': 2.0", + " }", + " ", + "}")); + }); + assertTrue(exception.getMessage().contains("Failed to parse JSON stream")); } @Test - public void ensure_that_invalid_json_not_in_tensor_format_fails() { - expectedException.expect(InvalidConstantTensorException.class); - expectedException.expectMessage("Expected field name 'cells', got 'stats'"); - - validateTensorJson(TensorType.fromSpec("tensor(x[], y[])"), - inputJsonToReader( - "{", - " 'stats': {", - " '\u30d1\u30fc\u30d7\u30eb\u30b4\u30e0\u88fd\u306e\u30a2\u30d2\u30eb\u306f\u79c1\u3092\u6bba\u3059\u305f\u3081\u306b\u671b\u3093\u3067\u3044\u307e\u3059': true,", - " 'points': 47", - " }", - "}")); + void ensure_that_invalid_json_not_in_tensor_format_fails() { + Throwable exception = assertThrows(InvalidConstantTensorException.class, () -> { + + validateTensorJson(TensorType.fromSpec("tensor(x[], y[])"), + inputJsonToReader( + "{", + " 'stats': {", + " '\u30d1\u30fc\u30d7\u30eb\u30b4\u30e0\u88fd\u306e\u30a2\u30d2\u30eb\u306f\u79c1\u3092\u6bba\u3059\u305f\u3081\u306b\u671b\u3093\u3067\u3044\u307e\u3059': true,", + " 'points': 47", + " }", + "}")); + }); + assertTrue(exception.getMessage().contains("Expected field name 'cells', got 'stats'")); } } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/ConstantValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/ConstantValidatorTest.java index ff45038a051..d3908d19e00 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/ConstantValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/ConstantValidatorTest.java @@ -2,20 +2,20 @@ package com.yahoo.vespa.model.application.validation; import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithFilePkg; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; public class ConstantValidatorTest { @Test - public void ensure_that_valid_ranking_constants_do_not_fail() { + void ensure_that_valid_ranking_constants_do_not_fail() { new VespaModelCreatorWithFilePkg("src/test/cfg/application/validation/ranking_constants_ok/").create(); } @Test - public void ensure_that_failing_ranking_constants_fails() { + void ensure_that_failing_ranking_constants_fails() { try { new VespaModelCreatorWithFilePkg("src/test/cfg/application/validation/ranking_constants_fail/").create(); fail(); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/DeploymentSpecValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/DeploymentSpecValidatorTest.java index ff765af1bd8..dba8205c0e7 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/DeploymentSpecValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/DeploymentSpecValidatorTest.java @@ -5,13 +5,13 @@ import com.yahoo.config.model.NullConfigModelRegistry; import com.yahoo.config.model.deploy.DeployState; import com.yahoo.config.model.test.MockApplicationPackage; import com.yahoo.vespa.model.VespaModel; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.xml.sax.SAXException; import java.io.IOException; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author hmusum @@ -19,7 +19,7 @@ import static org.junit.Assert.fail; public class DeploymentSpecValidatorTest { @Test - public void testDeploymentWithNonExistentGlobalId() { + void testDeploymentWithNonExistentGlobalId() { var deploymentXml = "<?xml version='1.0' encoding='UTF-8'?>" + "<deployment version='1.0'>" + " <test />" + @@ -28,23 +28,23 @@ public class DeploymentSpecValidatorTest { " </prod>" + "</deployment>"; assertValidationError("Attribute 'globalServiceId' in instance default: 'non-existing' specified in " + - "deployment.xml does not match any container cluster ID", deploymentXml); + "deployment.xml does not match any container cluster ID", deploymentXml); } @Test - public void testEndpointNonExistentContainerId() { + void testEndpointNonExistentContainerId() { var deploymentXml = "<?xml version='1.0' encoding='UTF-8'?>" + - "<deployment version='1.0'>" + - " <test />" + - " <prod>" + - " <region active='true'>us-east</region>" + - " </prod>" + - " <endpoints>" + - " <endpoint container-id='non-existing'/>" + - " </endpoints>" + - "</deployment>"; + "<deployment version='1.0'>" + + " <test />" + + " <prod>" + + " <region active='true'>us-east</region>" + + " </prod>" + + " <endpoints>" + + " <endpoint container-id='non-existing'/>" + + " </endpoints>" + + "</deployment>"; assertValidationError("Endpoint 'default' in instance default: 'non-existing' specified in " + - "deployment.xml does not match any container cluster ID", deploymentXml); + "deployment.xml does not match any container cluster ID", deploymentXml); } private static void assertValidationError(String message, String deploymentXml) { diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/EndpointCertificateSecretsValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/EndpointCertificateSecretsValidatorTest.java index 991606a8e32..6d230fae23c 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/EndpointCertificateSecretsValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/EndpointCertificateSecretsValidatorTest.java @@ -12,22 +12,18 @@ import com.yahoo.config.provision.Environment; import com.yahoo.config.provision.RegionName; import com.yahoo.config.provision.Zone; import com.yahoo.vespa.model.VespaModel; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; import java.util.Optional; import static com.yahoo.config.model.test.TestUtil.joinLines; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author andreer */ public class EndpointCertificateSecretsValidatorTest { - @SuppressWarnings("deprecation") - @Rule - public final ExpectedException exceptionRule = ExpectedException.none(); private static String servicesXml() { return joinLines("<services version='1.0'>", @@ -43,18 +39,18 @@ public class EndpointCertificateSecretsValidatorTest { } @Test - public void missing_certificate_fails_validation() throws Exception { - DeployState deployState = deployState(servicesXml(), deploymentXml(), Optional.of(EndpointCertificateSecrets.missing(1))); - VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState); - - exceptionRule.expect(CertificateNotReadyException.class); - exceptionRule.expectMessage("TLS enabled, but could not yet retrieve certificate version 1 for application default:default:default"); + void missing_certificate_fails_validation() throws Exception { + Throwable exception = assertThrows(CertificateNotReadyException.class, () -> { + DeployState deployState = deployState(servicesXml(), deploymentXml(), Optional.of(EndpointCertificateSecrets.missing(1))); + VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState); - new EndpointCertificateSecretsValidator().validate(model, deployState); + new EndpointCertificateSecretsValidator().validate(model, deployState); + }); + assertTrue(exception.getMessage().contains("TLS enabled, but could not yet retrieve certificate version 1 for application default:default:default")); } @Test - public void validation_succeeds_with_certificate() throws Exception { + void validation_succeeds_with_certificate() throws Exception { DeployState deployState = deployState(servicesXml(), deploymentXml(), Optional.of(new EndpointCertificateSecrets("cert", "key"))); VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState); @@ -62,7 +58,7 @@ public class EndpointCertificateSecretsValidatorTest { } @Test - public void validation_succeeds_without_certificate() throws Exception { + void validation_succeeds_without_certificate() throws Exception { DeployState deployState = deployState(servicesXml(), deploymentXml(), Optional.empty()); VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState); @@ -83,7 +79,7 @@ public class EndpointCertificateSecretsValidatorTest { .setEndpointCertificateSecrets(endpointCertificateSecretsSecrets)); final DeployState deployState = builder.build(); - assertTrue("Test must emulate a hosted deployment.", deployState.isHosted()); + assertTrue(deployState.isHosted(), "Test must emulate a hosted deployment."); return deployState; } } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/NoPrefixForIndexesTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/NoPrefixForIndexesTest.java index 5f0296588db..6394d77b67c 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/NoPrefixForIndexesTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/NoPrefixForIndexesTest.java @@ -2,10 +2,10 @@ package com.yahoo.vespa.model.application.validation; import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithFilePkg; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Harald Musum @@ -13,17 +13,17 @@ import static org.junit.Assert.fail; public class NoPrefixForIndexesTest { @Test - public void requireThatPrefixIsSupported() { + void requireThatPrefixIsSupported() { new VespaModelCreatorWithFilePkg("src/test/cfg/application/validation/prefix/").create(); } @Test - public void requireThatPrefixIsSupportedForStreaming() { + void requireThatPrefixIsSupportedForStreaming() { new VespaModelCreatorWithFilePkg("src/test/cfg/application/validation/prefix_streaming/").create(); } @Test - public void requireThatPrefixIsIllegalForIndexField() { + void requireThatPrefixIsIllegalForIndexField() { try { new VespaModelCreatorWithFilePkg("src/test/cfg/application/validation/prefix_index/").create(); fail(); @@ -33,7 +33,7 @@ public class NoPrefixForIndexesTest { } @Test - public void requireThatPrefixIsIllegalForMixedAttributeAndIndexField() { + void requireThatPrefixIsIllegalForMixedAttributeAndIndexField() { try { new VespaModelCreatorWithFilePkg("src/test/cfg/application/validation/prefix_index_and_attribute/").create(); fail(); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/QuotaValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/QuotaValidatorTest.java index 5e746d462b5..ef22f0b2770 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/QuotaValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/QuotaValidatorTest.java @@ -7,12 +7,12 @@ import com.yahoo.config.provision.Environment; import com.yahoo.config.provision.RegionName; import com.yahoo.config.provision.SystemName; import com.yahoo.config.provision.Zone; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.math.BigDecimal; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author ogronnesby @@ -24,13 +24,13 @@ public class QuotaValidatorTest { private final Quota quota = Quota.unlimited().withClusterSize(10).withBudget(BigDecimal.valueOf(1.25)); @Test - public void test_deploy_under_quota() { + void test_deploy_under_quota() { var tester = new ValidationTester(8, false, new TestProperties().setHostedVespa(true).setQuota(quota).setZone(publicZone)); tester.deploy(null, getServices("testCluster", 4), Environment.prod, null); } @Test - public void test_deploy_above_quota_clustersize() { + void test_deploy_above_quota_clustersize() { var tester = new ValidationTester(14, false, new TestProperties().setHostedVespa(true).setQuota(quota).setZone(publicZone)); try { tester.deploy(null, getServices("testCluster", 11), Environment.prod, null); @@ -41,7 +41,7 @@ public class QuotaValidatorTest { } @Test - public void test_deploy_above_quota_budget() { + void test_deploy_above_quota_budget() { var tester = new ValidationTester(13, false, new TestProperties().setHostedVespa(true).setQuota(quota).setZone(publicZone)); try { tester.deploy(null, getServices("testCluster", 10), Environment.prod, null); @@ -52,7 +52,7 @@ public class QuotaValidatorTest { } @Test - public void test_deploy_above_quota_budget_in_publiccd() { + void test_deploy_above_quota_budget_in_publiccd() { var tester = new ValidationTester(13, false, new TestProperties().setHostedVespa(true).setQuota(quota.withBudget(BigDecimal.ONE)).setZone(publicCdZone)); try { tester.deploy(null, getServices("testCluster", 10), Environment.prod, null); @@ -63,7 +63,7 @@ public class QuotaValidatorTest { } @Test - public void test_deploy_max_resources_above_quota() { + void test_deploy_max_resources_above_quota() { var tester = new ValidationTester(13, false, new TestProperties().setHostedVespa(true).setQuota(quota).setZone(publicCdZone)); try { tester.deploy(null, getServices("testCluster", 10), Environment.prod, null); @@ -75,7 +75,7 @@ public class QuotaValidatorTest { } @Test - public void test_deploy_with_negative_budget() { + void test_deploy_with_negative_budget() { var quota = Quota.unlimited().withBudget(BigDecimal.valueOf(-1)); var tester = new ValidationTester(13, false, new TestProperties().setHostedVespa(true).setQuota(quota).setZone(publicZone)); try { diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/SchemaDataTypeValidatorTestCase.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/SchemaDataTypeValidatorTestCase.java index b7b83dbf68c..2327c986be0 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/SchemaDataTypeValidatorTestCase.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/SchemaDataTypeValidatorTestCase.java @@ -2,10 +2,10 @@ package com.yahoo.vespa.model.application.validation; import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithFilePkg; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Simon Thoresen Hult @@ -13,22 +13,22 @@ import static org.junit.Assert.fail; public class SchemaDataTypeValidatorTestCase { @Test - public void requireThatSupportedTypesAreValidated() { + void requireThatSupportedTypesAreValidated() { new VespaModelCreatorWithFilePkg("src/test/cfg/application/validation/search_alltypes/").create(); } @Test - public void requireThatStructsAreLegalInSearchClusters() { + void requireThatStructsAreLegalInSearchClusters() { new VespaModelCreatorWithFilePkg("src/test/cfg/application/validation/search_struct/").create(); } @Test - public void requireThatEmptyContentFieldIsLegalInSearchClusters() { + void requireThatEmptyContentFieldIsLegalInSearchClusters() { new VespaModelCreatorWithFilePkg("src/test/cfg/application/validation/search_empty_content/").create(); } @Test - public void requireThatIndexingMapsInNonStreamingClusterIsIllegal() { + void requireThatIndexingMapsInNonStreamingClusterIsIllegal() { try { new VespaModelCreatorWithFilePkg("src/test/cfg/application/validation/index_struct/").create(); fail(); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/SecretStoreValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/SecretStoreValidatorTest.java index d30de06c459..0072d9b5d51 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/SecretStoreValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/SecretStoreValidatorTest.java @@ -10,20 +10,16 @@ import com.yahoo.config.provision.Environment; import com.yahoo.config.provision.RegionName; import com.yahoo.config.provision.Zone; import com.yahoo.vespa.model.VespaModel; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; import static com.yahoo.config.model.test.TestUtil.joinLines; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author gjoranv */ public class SecretStoreValidatorTest { - @SuppressWarnings("deprecation") - @Rule - public final ExpectedException exceptionRule = ExpectedException.none(); private static String servicesXml() { return joinLines("<services version='1.0'>", @@ -43,7 +39,7 @@ public class SecretStoreValidatorTest { } @Test - public void app_with_athenz_in_deployment_passes_validation() throws Exception { + void app_with_athenz_in_deployment_passes_validation() throws Exception { DeployState deployState = deployState(servicesXml(), deploymentXml(true)); VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState); @@ -51,24 +47,25 @@ public class SecretStoreValidatorTest { } @Test - public void app_without_athenz_in_deployment_fails_validation() throws Exception { - exceptionRule.expect(IllegalArgumentException.class); - exceptionRule.expectMessage( - "Container cluster 'default' uses a secret store, so an Athenz domain and" + - " an Athenz service must be declared in deployment.xml."); + void app_without_athenz_in_deployment_fails_validation() throws Exception { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { - DeployState deployState = deployState(servicesXml(), deploymentXml(false)); - VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState); + DeployState deployState = deployState(servicesXml(), deploymentXml(false)); + VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState); - new SecretStoreValidator().validate(model, deployState); + new SecretStoreValidator().validate(model, deployState); + + }); + assertTrue(exception.getMessage().contains("Container cluster 'default' uses a secret store, so an Athenz domain and" + + " an Athenz service must be declared in deployment.xml.")); } @Test - public void app_without_secret_store_passes_validation_without_athenz_in_deployment() throws Exception { + void app_without_secret_store_passes_validation_without_athenz_in_deployment() throws Exception { String servicesXml = joinLines("<services version='1.0'>", - " <container id='default' version='1.0' />", - "</services>"); + " <container id='default' version='1.0' />", + "</services>"); DeployState deployState = deployState(servicesXml, deploymentXml(false)); VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState); @@ -86,7 +83,7 @@ public class SecretStoreValidatorTest { .properties(new TestProperties().setHostedVespa(true)); final DeployState deployState = builder.build(); - assertTrue("Test must emulate a hosted deployment.", deployState.isHosted()); + assertTrue(deployState.isHosted(), "Test must emulate a hosted deployment."); return deployState; } } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/StreamingValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/StreamingValidatorTest.java index 30a77779347..fd1e6be27fd 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/StreamingValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/StreamingValidatorTest.java @@ -2,25 +2,23 @@ package com.yahoo.vespa.model.application.validation; import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithFilePkg; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author bjorncs */ public class StreamingValidatorTest { - @SuppressWarnings("deprecation") - @Rule - public final ExpectedException exceptionRule = ExpectedException.none(); @Test - public void document_references_are_forbidden_in_streaming_search() { - exceptionRule.expect(IllegalArgumentException.class); - exceptionRule.expectMessage( - "For streaming search cluster 'content.ad': Attribute 'campaign_ref' has type 'Reference<campaign>'. " + - "Document references and imported fields are not allowed in streaming search."); - new VespaModelCreatorWithFilePkg("src/test/cfg/application/validation/document_references_validation/") - .create(); + void document_references_are_forbidden_in_streaming_search() { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + new VespaModelCreatorWithFilePkg("src/test/cfg/application/validation/document_references_validation/") + .create(); + }); + assertTrue(exception.getMessage().contains("For streaming search cluster 'content.ad': Attribute 'campaign_ref' has type 'Reference<campaign>'. " + + "Document references and imported fields are not allowed in streaming search.")); } } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/UriBindingsValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/UriBindingsValidatorTest.java index d106120073d..7c16d3c99cf 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/UriBindingsValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/UriBindingsValidatorTest.java @@ -7,62 +7,63 @@ import com.yahoo.config.model.deploy.DeployState; import com.yahoo.config.model.deploy.TestProperties; import com.yahoo.config.model.test.MockApplicationPackage; import com.yahoo.vespa.model.VespaModel; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Test; import org.xml.sax.SAXException; import java.io.IOException; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * @author bjorncs */ public class UriBindingsValidatorTest { - @SuppressWarnings("deprecation") - @Rule - public ExpectedException exceptionRule = ExpectedException.none(); - @Test - public void fails_on_user_handler_binding_with_port() throws IOException, SAXException { - exceptionRule.expect(IllegalArgumentException.class); - exceptionRule.expectMessage("For binding 'http://*:4443/my-handler': binding with port is not allowed"); - runUriBindingValidator(true, createServicesXmlWithHandler("http://*:4443/my-handler")); + void fails_on_user_handler_binding_with_port() throws IOException, SAXException { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + runUriBindingValidator(true, createServicesXmlWithHandler("http://*:4443/my-handler")); + }); + assertTrue(exception.getMessage().contains("For binding 'http://*:4443/my-handler': binding with port is not allowed")); } @Test - public void fails_on_user_handler_binding_with_hostname() throws IOException, SAXException { - exceptionRule.expect(IllegalArgumentException.class); - exceptionRule.expectMessage("For binding 'http://myhostname/my-handler': only binding with wildcard ('*') for hostname is allowed"); - runUriBindingValidator(true, createServicesXmlWithHandler("http://myhostname/my-handler")); + void fails_on_user_handler_binding_with_hostname() throws IOException, SAXException { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + runUriBindingValidator(true, createServicesXmlWithHandler("http://myhostname/my-handler")); + }); + assertTrue(exception.getMessage().contains("For binding 'http://myhostname/my-handler': only binding with wildcard ('*') for hostname is allowed")); } @Test - public void fails_on_user_handler_binding_with_non_http_scheme() throws IOException, SAXException { - exceptionRule.expect(IllegalArgumentException.class); - exceptionRule.expectMessage("For binding 'ftp://*/my-handler': only 'http' is allowed as scheme"); - runUriBindingValidator(true, createServicesXmlWithHandler("ftp://*/my-handler")); + void fails_on_user_handler_binding_with_non_http_scheme() throws IOException, SAXException { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + runUriBindingValidator(true, createServicesXmlWithHandler("ftp://*/my-handler")); + }); + assertTrue(exception.getMessage().contains("For binding 'ftp://*/my-handler': only 'http' is allowed as scheme")); } @Test - public void fails_on_invalid_filter_binding() throws IOException, SAXException { - exceptionRule.expect(IllegalArgumentException.class); - exceptionRule.expectMessage("For binding 'https://*:4443/my-request-filer-chain': binding with port is not allowed"); - runUriBindingValidator(true, createServicesXmlWithRequestFilterChain("https://*:4443/my-request-filer-chain")); + void fails_on_invalid_filter_binding() throws IOException, SAXException { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + runUriBindingValidator(true, createServicesXmlWithRequestFilterChain("https://*:4443/my-request-filer-chain")); + }); + assertTrue(exception.getMessage().contains("For binding 'https://*:4443/my-request-filer-chain': binding with port is not allowed")); } @Test - public void allows_valid_user_binding() throws IOException, SAXException { + void allows_valid_user_binding() throws IOException, SAXException { runUriBindingValidator(true, createServicesXmlWithHandler("http://*/my-handler")); } @Test - public void allows_user_binding_with_wildcard_port() throws IOException, SAXException { + void allows_user_binding_with_wildcard_port() throws IOException, SAXException { runUriBindingValidator(true, createServicesXmlWithHandler("http://*:*/my-handler")); } @Test - public void only_restricts_user_bindings_on_hosted() throws IOException, SAXException { + void only_restricts_user_bindings_on_hosted() throws IOException, SAXException { runUriBindingValidator(false, createServicesXmlWithRequestFilterChain("https://*:4443/my-request-filer-chain")); } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/ValidationOverridesValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/ValidationOverridesValidatorTest.java index 93d42e07dd8..1a7b51980f7 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/ValidationOverridesValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/ValidationOverridesValidatorTest.java @@ -6,7 +6,7 @@ import com.yahoo.config.model.api.ValidationParameters; import com.yahoo.config.model.deploy.DeployState; import com.yahoo.config.model.test.MockApplicationPackage; import com.yahoo.vespa.model.VespaModel; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.xml.sax.SAXException; import java.io.IOException; @@ -15,8 +15,8 @@ import java.time.Instant; import java.time.ZoneId; import java.time.format.DateTimeFormatter; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author hmusum @@ -27,13 +27,13 @@ public class ValidationOverridesValidatorTest { .withZone(ZoneId.systemDefault()); @Test - public void testValidationOverride() throws IOException, SAXException { + void testValidationOverride() throws IOException, SAXException { String tenDays = dateTimeFormatter.format(Instant.now().plus(Duration.ofDays(10))); var validationOverridesXml = "<?xml version='1.0' encoding='UTF-8'?>\n" + - " <validation-overrides>\n" + - " <allow until='" + tenDays + "'>deployment-removal</allow>\n" + - " </validation-overrides>"; + " <validation-overrides>\n" + + " <allow until='" + tenDays + "'>deployment-removal</allow>\n" + + " </validation-overrides>"; var deployState = createDeployState(validationOverridesXml); VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState); @@ -41,17 +41,17 @@ public class ValidationOverridesValidatorTest { } @Test - public void testFailsWhenValidationOverrideIsTooFarInFuture() { + void testFailsWhenValidationOverrideIsTooFarInFuture() { Instant now = Instant.now(); String sixtyDays = dateTimeFormatter.format(now.plus(Duration.ofDays(60))); String sixtyOneDays = dateTimeFormatter.format(now.plus(Duration.ofDays(61))); var validationOverrides = "<?xml version='1.0' encoding='UTF-8'?>\n" + - "<validation-overrides>\n" + - " <allow until='" + sixtyDays + "'>deployment-removal</allow>\n" + - "</validation-overrides>"; + "<validation-overrides>\n" + + " <allow until='" + sixtyDays + "'>deployment-removal</allow>\n" + + "</validation-overrides>"; assertValidationError("validation-overrides is invalid: allow 'deployment-removal' until " + - sixtyOneDays + "T00:00:00Z is too far in the future: Max 30 days is allowed", validationOverrides); + sixtyOneDays + "T00:00:00Z is too far in the future: Max 30 days is allowed", validationOverrides); } private static void assertValidationError(String message, String validationOverridesXml) { diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ClusterSizeReductionValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ClusterSizeReductionValidatorTest.java index 43841aebd8a..7e172171052 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ClusterSizeReductionValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ClusterSizeReductionValidatorTest.java @@ -7,10 +7,10 @@ import com.yahoo.config.provision.Environment; import com.yahoo.vespa.model.VespaModel; import com.yahoo.vespa.model.application.validation.ValidationTester; import com.yahoo.yolean.Exceptions; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author bratseth @@ -18,7 +18,7 @@ import static org.junit.Assert.fail; public class ClusterSizeReductionValidatorTest { @Test - public void testSizeReductionValidation() { + void testSizeReductionValidation() { ValidationTester tester = new ValidationTester(33); VespaModel previous = tester.deploy(null, getServices(30), Environment.prod, null).getFirst(); @@ -28,15 +28,15 @@ public class ClusterSizeReductionValidatorTest { } catch (IllegalArgumentException expected) { assertEquals("cluster-size-reduction: Size reduction in 'default' is too large: " + - "New min size must be at least 50% of the current min size. " + - "Current size: 30, new size: 14. " + - ValidationOverrides.toAllowMessage(ValidationId.clusterSizeReduction), - Exceptions.toMessageString(expected)); + "New min size must be at least 50% of the current min size. " + + "Current size: 30, new size: 14. " + + ValidationOverrides.toAllowMessage(ValidationId.clusterSizeReduction), + Exceptions.toMessageString(expected)); } } @Test - public void testSizeReductionValidationMinimalDecreaseIsAllowed() { + void testSizeReductionValidationMinimalDecreaseIsAllowed() { ValidationTester tester = new ValidationTester(30); VespaModel previous = tester.deploy(null, getServices(3), Environment.prod, null).getFirst(); @@ -44,7 +44,7 @@ public class ClusterSizeReductionValidatorTest { } @Test - public void testOverridingSizereductionValidation() { + void testOverridingSizereductionValidation() { ValidationTester tester = new ValidationTester(33); VespaModel previous = tester.deploy(null, getServices(30), Environment.prod, null).getFirst(); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ConfigChangeTestUtils.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ConfigChangeTestUtils.java index 00a1ec7e6d8..d975618c1db 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ConfigChangeTestUtils.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ConfigChangeTestUtils.java @@ -10,7 +10,7 @@ import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class ConfigChangeTestUtils { diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ConfigValueChangeValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ConfigValueChangeValidatorTest.java index 567534ba9f6..83672b6452e 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ConfigValueChangeValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ConfigValueChangeValidatorTest.java @@ -18,8 +18,8 @@ import com.yahoo.vespa.model.application.validation.RestartConfigs; import com.yahoo.config.application.api.ValidationOverrides; import com.yahoo.vespa.model.test.utils.DeployLoggerStub; import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithMockPkg; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.time.Instant; import java.util.Arrays; @@ -27,8 +27,7 @@ import java.util.List; import java.util.Map; import java.util.stream.Collectors; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * Testing the validator on both a stub model and a real-life Vespa model. @@ -39,7 +38,7 @@ public class ConfigValueChangeValidatorTest { private DeployLoggerStub logger; - @Before + @BeforeEach public void resetLogger() { logger = new DeployLoggerStub(); } @@ -54,7 +53,7 @@ public class ConfigValueChangeValidatorTest { * This test will to a certain degree ensure that the annotations in the VespaModel is correctly applied. */ @Test - public void requireThatValidatorHandlesVespaModel() { + void requireThatValidatorHandlesVespaModel() { List<ConfigChangeAction> changes = getConfigChanges( createVespaModel(createQrStartConfigSegment(true, 2096)), createVespaModel(createQrStartConfigSegment(false, 2096)) @@ -66,7 +65,7 @@ public class ConfigValueChangeValidatorTest { } @Test - public void requireThatDocumentTypesCanBeAddedWithoutNeedForRestart() { + void requireThatDocumentTypesCanBeAddedWithoutNeedForRestart() { List<ConfigChangeAction> changes = getConfigChanges( createVespaModel("", Arrays.asList("foo")), createVespaModel("", Arrays.asList("foo", "bar"))); @@ -74,7 +73,7 @@ public class ConfigValueChangeValidatorTest { } @Test - public void requireThatValidatorDetectsConfigChangeFromService() { + void requireThatValidatorDetectsConfigChangeFromService() { MockRoot oldRoot = createRootWithChildren(new SimpleConfigProducer("p", 0) .withChildren(new ServiceWithAnnotation("s1", 1), new ServiceWithAnnotation("s2", 2))); MockRoot newRoot = createRootWithChildren(new SimpleConfigProducer("p", 0) @@ -89,7 +88,7 @@ public class ConfigValueChangeValidatorTest { } @Test - public void requireThatValidatorDetectsConfigChangeFromParentProducer() { + void requireThatValidatorDetectsConfigChangeFromParentProducer() { MockRoot oldRoot = createRootWithChildren(new SimpleConfigProducer("p", 1) .withChildren(new ServiceWithAnnotation("s1", 0), new ServiceWithAnnotation("s2", 0))); MockRoot newRoot = createRootWithChildren(new SimpleConfigProducer("p", 2) @@ -102,7 +101,7 @@ public class ConfigValueChangeValidatorTest { } @Test - public void requireThatValidatorHandlesModelsWithDifferentTopology() { + void requireThatValidatorHandlesModelsWithDifferentTopology() { MockRoot oldRoot = createRootWithChildren( new SimpleConfigProducer("p1", 0).withChildren(new ServiceWithAnnotation("s1", 1)), new SimpleConfigProducer("p2", 0).withChildren(new ServiceWithAnnotation("s2", 1))); @@ -117,27 +116,31 @@ public class ConfigValueChangeValidatorTest { assertEmptyLog(); } - @Test(expected = IllegalStateException.class) - public void requireThatAnnotationDoesNotHaveEmtpyConfigList() { - MockRoot root = createRootWithChildren(new EmptyConfigListAnnotationService("")); - getConfigChanges(root, root); + @Test + void requireThatAnnotationDoesNotHaveEmtpyConfigList() { + assertThrows(IllegalStateException.class, () -> { + MockRoot root = createRootWithChildren(new EmptyConfigListAnnotationService("")); + getConfigChanges(root, root); + }); } - @Test(expected = IllegalStateException.class) - public void requireThatConfigHasRestartMethods() { - MockRoot root = createRootWithChildren(new ConfigWithMissingMethodsAnnotatedService("")); - getConfigChanges(root, root); + @Test + void requireThatConfigHasRestartMethods() { + assertThrows(IllegalStateException.class, () -> { + MockRoot root = createRootWithChildren(new ConfigWithMissingMethodsAnnotatedService("")); + getConfigChanges(root, root); + }); } @Test - public void requireThatServicesAnnotatedWithNonRestartConfigProduceWarningInLog() { + void requireThatServicesAnnotatedWithNonRestartConfigProduceWarningInLog() { MockRoot root = createRootWithChildren(new NonRestartConfigAnnotatedService("")); getConfigChanges(root, root); assertEquals(1, logger.entries.size()); } @Test - public void requireThatConfigsFromAnnotatedSuperClassesAreDetected() { + void requireThatConfigsFromAnnotatedSuperClassesAreDetected() { MockRoot oldRoot = createRootWithChildren(new SimpleConfigProducer("p", 1).withChildren( new ChildServiceWithAnnotation("child1", 0), new ChildServiceWithoutAnnotation("child2", 0))); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ContainerRestartValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ContainerRestartValidatorTest.java index 7cad29cc2c4..7d6e243fba4 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ContainerRestartValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ContainerRestartValidatorTest.java @@ -7,15 +7,13 @@ import com.yahoo.vespa.defaults.Defaults; import com.yahoo.vespa.model.VespaModel; import com.yahoo.config.application.api.ValidationOverrides; import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithMockPkg; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.time.Instant; import java.util.Collections; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * @author bjorncs @@ -23,7 +21,7 @@ import static org.junit.Assert.assertTrue; public class ContainerRestartValidatorTest { @Test - public void validator_returns_action_for_containers_with_restart_on_deploy_enabled() { + void validator_returns_action_for_containers_with_restart_on_deploy_enabled() { VespaModel current = createModel(true); VespaModel next = createModel(true); List<ConfigChangeAction> result = validateModel(current, next); @@ -31,7 +29,7 @@ public class ContainerRestartValidatorTest { } @Test - public void validator_returns_empty_list_for_containers_with_restart_on_deploy_disabled() { + void validator_returns_empty_list_for_containers_with_restart_on_deploy_disabled() { VespaModel current = createModel(false); VespaModel next = createModel(false); List<ConfigChangeAction> result = validateModel(current, next); @@ -39,7 +37,7 @@ public class ContainerRestartValidatorTest { } @Test - public void validator_returns_empty_list_for_containers_with_restart_on_deploy_disabled_where_previously_enabled() { + void validator_returns_empty_list_for_containers_with_restart_on_deploy_disabled_where_previously_enabled() { VespaModel current = createModel(true); VespaModel next = createModel(false); List<ConfigChangeAction> result = validateModel(current, next); @@ -47,7 +45,7 @@ public class ContainerRestartValidatorTest { } @Test - public void restart_on_deploy_is_propagated_to_cluster() { + void restart_on_deploy_is_propagated_to_cluster() { VespaModel model1 = createModel(false); assertFalse(model1.getContainerClusters().get("cluster1").getDeferChangesUntilRestart()); assertFalse(model1.getContainerClusters().get("cluster2").getDeferChangesUntilRestart()); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ContentClusterRemovalValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ContentClusterRemovalValidatorTest.java index c0f9e532aa2..25ce7252ea8 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ContentClusterRemovalValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ContentClusterRemovalValidatorTest.java @@ -7,10 +7,10 @@ import com.yahoo.config.provision.Environment; import com.yahoo.vespa.model.VespaModel; import com.yahoo.vespa.model.application.validation.ValidationTester; import com.yahoo.yolean.Exceptions; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author bratseth @@ -20,7 +20,7 @@ public class ContentClusterRemovalValidatorTest { private final ValidationTester tester = new ValidationTester(5); @Test - public void testContentRemovalValidation() { + void testContentRemovalValidation() { VespaModel previous = tester.deploy(null, getServices("contentClusterId"), Environment.prod, null).getFirst(); try { tester.deploy(previous, getServices("newContentClusterId"), Environment.prod, null); @@ -28,13 +28,13 @@ public class ContentClusterRemovalValidatorTest { } catch (IllegalArgumentException expected) { assertEquals("content-cluster-removal: Content cluster 'contentClusterId' is removed. This will cause loss of all data in this cluster. " + - ValidationOverrides.toAllowMessage(ValidationId.contentClusterRemoval), - Exceptions.toMessageString(expected)); + ValidationOverrides.toAllowMessage(ValidationId.contentClusterRemoval), + Exceptions.toMessageString(expected)); } } @Test - public void testOverridingContentRemovalValidation() { + void testOverridingContentRemovalValidation() { VespaModel previous = tester.deploy(null, getServices("contentClusterId"), Environment.prod, null).getFirst(); tester.deploy(previous, getServices("newContentClusterId"), Environment.prod, removalOverride); // Allowed due to override } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ContentTypeRemovalValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ContentTypeRemovalValidatorTest.java index 3827fa9786e..70c2c7704f3 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ContentTypeRemovalValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ContentTypeRemovalValidatorTest.java @@ -7,10 +7,10 @@ import com.yahoo.config.provision.Environment; import com.yahoo.vespa.model.VespaModel; import com.yahoo.vespa.model.application.validation.ValidationTester; import com.yahoo.yolean.Exceptions; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * Tests validation of removal of a document type. @@ -21,7 +21,7 @@ import static org.junit.Assert.fail; public class ContentTypeRemovalValidatorTest { @Test - public void testContentTypeRemovalValidation() { + void testContentTypeRemovalValidation() { ValidationTester tester = new ValidationTester(); VespaModel previous = tester.deploy(null, getServices("music"), Environment.prod, null).getFirst(); @@ -31,14 +31,14 @@ public class ContentTypeRemovalValidatorTest { } catch (IllegalArgumentException expected) { assertEquals("content-type-removal: Type 'music' is removed in content cluster 'test'. " + - "This will cause loss of all data of this type. " + - ValidationOverrides.toAllowMessage(ValidationId.contentTypeRemoval), - Exceptions.toMessageString(expected)); + "This will cause loss of all data of this type. " + + ValidationOverrides.toAllowMessage(ValidationId.contentTypeRemoval), + Exceptions.toMessageString(expected)); } } @Test - public void testOverridingContentTypeRemovalValidation() { + void testOverridingContentTypeRemovalValidation() { ValidationTester tester = new ValidationTester(); VespaModel previous = tester.deploy(null, getServices("music"), Environment.prod, null).getFirst(); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/GlobalDocumentChangeValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/GlobalDocumentChangeValidatorTest.java index f1192dd0f89..fb052e023bb 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/GlobalDocumentChangeValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/GlobalDocumentChangeValidatorTest.java @@ -4,11 +4,9 @@ package com.yahoo.vespa.model.application.validation.change; import com.yahoo.config.provision.Environment; import com.yahoo.vespa.model.VespaModel; import com.yahoo.vespa.model.application.validation.ValidationTester; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.*; /** * Test that global attribute changes are detected by change validator. @@ -16,7 +14,7 @@ import static org.junit.Assert.assertFalse; public class GlobalDocumentChangeValidatorTest { @Test - public void testChangGlobalAttribute() { + void testChangGlobalAttribute() { testChangeGlobalAttribute(true, false, false, null); testChangeGlobalAttribute(true, true, true, null); testChangeGlobalAttribute(false, false, true, null); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/IndexedSchemaClusterChangeValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/IndexedSchemaClusterChangeValidatorTest.java index 7b1474f9754..309ad4094e4 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/IndexedSchemaClusterChangeValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/IndexedSchemaClusterChangeValidatorTest.java @@ -10,7 +10,7 @@ import com.yahoo.config.application.api.ValidationOverrides; import com.yahoo.vespa.model.content.utils.ApplicationPackageBuilder; import com.yahoo.vespa.model.content.utils.ContentClusterBuilder; import com.yahoo.vespa.model.content.utils.SchemaBuilder; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.time.Instant; import java.util.List; @@ -19,7 +19,7 @@ import static com.yahoo.vespa.model.application.validation.change.ConfigChangeTe import static com.yahoo.vespa.model.application.validation.change.ConfigChangeTestUtils.newRefeedAction; import static com.yahoo.vespa.model.application.validation.change.ConfigChangeTestUtils.newRestartAction; import static com.yahoo.vespa.model.application.validation.change.ConfigChangeTestUtils.normalizeServicesInActions; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; public class IndexedSchemaClusterChangeValidatorTest { @@ -99,56 +99,56 @@ public class IndexedSchemaClusterChangeValidatorTest { new ServiceInfo("searchnode2", "null", null, null, "bar/search/cluster.bar/0", "null")); @Test - public void requireThatDocumentDatabaseChangeIsDiscovered() { + void requireThatDocumentDatabaseChangeIsDiscovered() { Fixture.newOneDocFixture(STRING_FIELD, ATTRIBUTE_FIELD). assertValidation(newRestartAction(ClusterSpec.Id.from("test"), - "Document type 'd1': " + ATTRIBUTE_CHANGE_MSG, FOO_SERVICE)); + "Document type 'd1': " + ATTRIBUTE_CHANGE_MSG, FOO_SERVICE)); } @Test - public void requireThatChangeInSeveralDocumentDatabasesAreDiscovered() { + void requireThatChangeInSeveralDocumentDatabasesAreDiscovered() { Fixture.newTwoDocFixture(STRING_FIELD, ATTRIBUTE_FIELD). assertValidation(List.of(newRestartAction(ClusterSpec.Id.from("test"), - "Document type 'd1': " + ATTRIBUTE_CHANGE_MSG, FOO_SERVICE), - newRestartAction(ClusterSpec.Id.from("test"), - "Document type 'd2': " + ATTRIBUTE_CHANGE_MSG, FOO_SERVICE))); + "Document type 'd1': " + ATTRIBUTE_CHANGE_MSG, FOO_SERVICE), + newRestartAction(ClusterSpec.Id.from("test"), + "Document type 'd2': " + ATTRIBUTE_CHANGE_MSG, FOO_SERVICE))); } @Test - public void requireThatChangeInSeveralContentClustersAreDiscovered() { + void requireThatChangeInSeveralContentClustersAreDiscovered() { Fixture.newTwoClusterFixture(STRING_FIELD, ATTRIBUTE_FIELD). assertValidation(List.of(newRestartAction(ClusterSpec.Id.from("test"), - "Document type 'd1': " + ATTRIBUTE_CHANGE_MSG, FOO_SERVICE), - newRestartAction(ClusterSpec.Id.from("test"), - "Document type 'd2': " + ATTRIBUTE_CHANGE_MSG, BAR_SERVICE))); + "Document type 'd1': " + ATTRIBUTE_CHANGE_MSG, FOO_SERVICE), + newRestartAction(ClusterSpec.Id.from("test"), + "Document type 'd2': " + ATTRIBUTE_CHANGE_MSG, BAR_SERVICE))); } @Test - public void requireThatAddingDocumentDatabaseIsOk() { + void requireThatAddingDocumentDatabaseIsOk() { new Fixture(Fixture.newOneDocModel(STRING_FIELD), Fixture.newTwoDocModel(STRING_FIELD, STRING_FIELD)).assertValidation(); } @Test - public void requireThatRemovingDocumentDatabaseIsOk() { + void requireThatRemovingDocumentDatabaseIsOk() { new Fixture(Fixture.newTwoDocModel(STRING_FIELD, STRING_FIELD), Fixture.newOneDocModel(STRING_FIELD)).assertValidation(); } @Test - public void requireThatAddingContentClusterIsOk() { + void requireThatAddingContentClusterIsOk() { new Fixture(Fixture.newOneDocModel(STRING_FIELD), Fixture.newTwoClusterModel(STRING_FIELD, STRING_FIELD)).assertValidation(); } @Test - public void requireThatRemovingContentClusterIsOk() { + void requireThatRemovingContentClusterIsOk() { new Fixture(Fixture.newTwoClusterModel(STRING_FIELD, STRING_FIELD), Fixture.newOneDocModel(STRING_FIELD)).assertValidation(); } @Test - public void requireThatChangingFieldTypeIsDiscovered() { + void requireThatChangingFieldTypeIsDiscovered() { Fixture f = Fixture.newOneDocFixture(STRING_FIELD, INT_FIELD); f.assertValidation(List.of(newRefeedAction(ClusterSpec.Id.from("test"), - ValidationId.fieldTypeChange, - "Document type 'd1': " + FIELD_TYPE_CHANGE_MSG, FOO_SERVICE, "d1"))); + ValidationId.fieldTypeChange, + "Document type 'd1': " + FIELD_TYPE_CHANGE_MSG, FOO_SERVICE, "d1"))); } } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/IndexingModeChangeValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/IndexingModeChangeValidatorTest.java index c7ed8309318..5b06cc28919 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/IndexingModeChangeValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/IndexingModeChangeValidatorTest.java @@ -7,15 +7,13 @@ import com.yahoo.config.model.api.ConfigChangeReindexAction; import com.yahoo.config.provision.Environment; import com.yahoo.vespa.model.VespaModel; import com.yahoo.vespa.model.application.validation.ValidationTester; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.List; import java.util.stream.Collectors; import static java.util.stream.Collectors.joining; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; /** * @author bratseth @@ -24,7 +22,7 @@ import static org.junit.Assert.fail; public class IndexingModeChangeValidatorTest { @Test - public void testChangingIndexModeFromIndexedToStreamingWhenDisallowed() { + void testChangingIndexModeFromIndexedToStreamingWhenDisallowed() { ValidationTester tester = new ValidationTester(); VespaModel oldModel = @@ -36,14 +34,14 @@ public class IndexingModeChangeValidatorTest { } catch (ValidationException e) { assertEquals("indexing-mode-change:\n" + - "\tDocument type 'music' in cluster 'default' changed indexing mode from 'indexed' to 'streaming'\n" + - "To allow this add <allow until='yyyy-mm-dd'>indexing-mode-change</allow> to validation-overrides.xml, see https://docs.vespa.ai/en/reference/validation-overrides.html", - e.getMessage()); + "\tDocument type 'music' in cluster 'default' changed indexing mode from 'indexed' to 'streaming'\n" + + "To allow this add <allow until='yyyy-mm-dd'>indexing-mode-change</allow> to validation-overrides.xml, see https://docs.vespa.ai/en/reference/validation-overrides.html", + e.getMessage()); } } @Test - public void testChangingIndexModeFromIndexedToStreaming() { + void testChangingIndexModeFromIndexedToStreaming() { ValidationTester tester = new ValidationTester(); VespaModel oldModel = @@ -52,12 +50,12 @@ public class IndexingModeChangeValidatorTest { tester.deploy(oldModel, getServices("streaming"), Environment.prod, validationOverrides).getSecond(); assertReindexingChange( // allowed=true due to validation override - "Document type 'music' in cluster 'default' changed indexing mode from 'indexed' to 'streaming'", - changeActions); + "Document type 'music' in cluster 'default' changed indexing mode from 'indexed' to 'streaming'", + changeActions); } @Test - public void testChangingIndexModeFromStoreOnlyToIndexed() { + void testChangingIndexModeFromStoreOnlyToIndexed() { ValidationTester tester = new ValidationTester(); VespaModel oldModel = @@ -66,8 +64,8 @@ public class IndexingModeChangeValidatorTest { tester.deploy(oldModel, getServices("store-only"), Environment.prod, validationOverrides).getSecond(); assertReindexingChange( // allowed=true due to validation override - "Document type 'music' in cluster 'default' changed indexing mode from 'indexed' to 'store-only'", - changeActions); + "Document type 'music' in cluster 'default' changed indexing mode from 'indexed' to 'store-only'", + changeActions); } private void assertReindexingChange(String message, List<ConfigChangeAction> changeActions) { diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/NodeResourceChangeValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/NodeResourceChangeValidatorTest.java index 891418c073f..d0cc4a605bc 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/NodeResourceChangeValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/NodeResourceChangeValidatorTest.java @@ -13,14 +13,14 @@ import com.yahoo.config.provision.HostSpec; import com.yahoo.config.provision.ProvisionLogger; import com.yahoo.vespa.model.VespaModel; import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithMockPkg; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.time.Clock; import java.util.ArrayList; import java.util.List; import java.util.Optional; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author bratseth @@ -28,7 +28,7 @@ import static org.junit.Assert.assertEquals; public class NodeResourceChangeValidatorTest { @Test - public void test_restart_action_count() { + void test_restart_action_count() { assertEquals(0, validate(model(1, 1, 1, 1), model(1, 1, 1, 1)).size()); assertEquals(1, validate(model(1, 1, 1, 1), model(2, 1, 1, 1)).size()); assertEquals(2, validate(model(1, 1, 1, 1), model(1, 2, 1, 1)).size()); @@ -43,7 +43,7 @@ public class NodeResourceChangeValidatorTest { } @Test - public void test_restart_action_details() { + void test_restart_action_details() { ConfigChangeAction containerAction = validate(model(1, 1, 1, 1), model(2, 1, 1, 1)).get(0); assertEquals(ConfigChangeAction.Type.RESTART, containerAction.getType()); assertEquals("service 'container' of type container on host0", containerAction.getServices().get(0).toString()); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/RedundancyIncreaseValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/RedundancyIncreaseValidatorTest.java index 3249b2cd60e..544ec2b841e 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/RedundancyIncreaseValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/RedundancyIncreaseValidatorTest.java @@ -7,10 +7,10 @@ import com.yahoo.config.provision.Environment; import com.yahoo.vespa.model.VespaModel; import com.yahoo.vespa.model.application.validation.ValidationTester; import com.yahoo.yolean.Exceptions; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author bratseth @@ -20,7 +20,7 @@ public class RedundancyIncreaseValidatorTest { private final ValidationTester tester = new ValidationTester(7); @Test - public void testRedundancyIncreaseValidation() { + void testRedundancyIncreaseValidation() { VespaModel previous = tester.deploy(null, getServices(2), Environment.prod, null).getFirst(); try { tester.deploy(previous, getServices(3), Environment.prod, null); @@ -28,15 +28,15 @@ public class RedundancyIncreaseValidatorTest { } catch (IllegalArgumentException expected) { assertEquals("redundancy-increase: " + - "Increasing redundancy from 2 to 3 in 'content cluster 'contentClusterId'. " + - "This is a safe operation but verify that you have room for a 3/2x increase in content size. " + - ValidationOverrides.toAllowMessage(ValidationId.redundancyIncrease), - Exceptions.toMessageString(expected)); + "Increasing redundancy from 2 to 3 in 'content cluster 'contentClusterId'. " + + "This is a safe operation but verify that you have room for a 3/2x increase in content size. " + + ValidationOverrides.toAllowMessage(ValidationId.redundancyIncrease), + Exceptions.toMessageString(expected)); } } @Test - public void testOverridingContentRemovalValidation() { + void testOverridingContentRemovalValidation() { VespaModel previous = tester.deploy(null, getServices(2), Environment.prod, null).getFirst(); tester.deploy(previous, getServices(3), Environment.prod, redundancyIncreaseOverride); // Allowed due to override } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ResourcesReductionValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ResourcesReductionValidatorTest.java index 76398099657..651f87c614b 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ResourcesReductionValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ResourcesReductionValidatorTest.java @@ -9,10 +9,10 @@ import com.yahoo.config.provision.NodeResources; import com.yahoo.vespa.model.VespaModel; import com.yahoo.vespa.model.application.validation.ValidationTester; import com.yahoo.yolean.Exceptions; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author freva @@ -23,54 +23,54 @@ public class ResourcesReductionValidatorTest { private final ValidationTester tester = new ValidationTester(provisioner); @Test - public void fail_when_reduction_by_over_50_percent() { + void fail_when_reduction_by_over_50_percent() { VespaModel previous = tester.deploy(null, getServices(new NodeResources(8, 64, 800, 1)), Environment.prod, null).getFirst(); try { tester.deploy(previous, getServices(new NodeResources(8, 16, 800, 1)), Environment.prod, null); fail("Expected exception due to resources reduction"); } catch (IllegalArgumentException expected) { assertEquals("resources-reduction: Resource reduction in 'default' is too large. " + - "Current memory GB: 64.00, new: 16.00. New min resources must be at least 50% of the current min resources. " + - ValidationOverrides.toAllowMessage(ValidationId.resourcesReduction), + "Current memory GB: 64.00, new: 16.00. New min resources must be at least 50% of the current min resources. " + + ValidationOverrides.toAllowMessage(ValidationId.resourcesReduction), Exceptions.toMessageString(expected)); } } @Test - public void fail_when_reducing_multiple_resources_by_over_50_percent() { + void fail_when_reducing_multiple_resources_by_over_50_percent() { VespaModel previous = tester.deploy(null, getServices(new NodeResources(8, 64, 800, 1)), Environment.prod, null).getFirst(); try { tester.deploy(previous, getServices(new NodeResources(3, 16, 200, 1)), Environment.prod, null); fail("Expected exception due to resources reduction"); } catch (IllegalArgumentException expected) { assertEquals("resources-reduction: Resource reduction in 'default' is too large. " + - "Current vCPU: 8.00, new: 3.00. Current memory GB: 64.00, new: 16.00. Current disk GB: 800.00, new: 200.00. " + - "New min resources must be at least 50% of the current min resources. " + - ValidationOverrides.toAllowMessage(ValidationId.resourcesReduction), + "Current vCPU: 8.00, new: 3.00. Current memory GB: 64.00, new: 16.00. Current disk GB: 800.00, new: 200.00. " + + "New min resources must be at least 50% of the current min resources. " + + ValidationOverrides.toAllowMessage(ValidationId.resourcesReduction), Exceptions.toMessageString(expected)); } } @Test - public void small_resource_decrease_is_allowed() { + void small_resource_decrease_is_allowed() { VespaModel previous = tester.deploy(null, getServices(new NodeResources(1.5, 64, 800, 1)), Environment.prod, null).getFirst(); tester.deploy(previous, getServices(new NodeResources(.5, 48, 600, 1)), Environment.prod, null); } @Test - public void overriding_resource_decrease() { + void overriding_resource_decrease() { VespaModel previous = tester.deploy(null, getServices(new NodeResources(8, 64, 800, 1)), Environment.prod, null).getFirst(); tester.deploy(previous, getServices(new NodeResources(8, 16, 800, 1)), Environment.prod, resourcesReductionOverride); // Allowed due to override } @Test - public void allowed_to_go_to_not_specifying_resources() { + void allowed_to_go_to_not_specifying_resources() { VespaModel previous = tester.deploy(null, getServices(new NodeResources(1.5, 64, 800, 1)), Environment.prod, null).getFirst(); tester.deploy(previous, getServices(null), Environment.prod, null); } @Test - public void allowed_to_go_from_not_specifying_resources() { + void allowed_to_go_from_not_specifying_resources() { VespaModel previous = tester.deploy(null, getServices(null), Environment.prod, null).getFirst(); tester.deploy(previous, getServices(new NodeResources(1.5, 64, 800, 1)), Environment.prod, null); } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/RestartChangesDefersConfigChangesTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/RestartChangesDefersConfigChangesTest.java index 439cb24ba87..cef6f72b94b 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/RestartChangesDefersConfigChangesTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/RestartChangesDefersConfigChangesTest.java @@ -9,10 +9,10 @@ import com.yahoo.container.ComponentsConfig; import com.yahoo.container.QrConfig; import com.yahoo.vespa.model.VespaModel; import com.yahoo.vespa.model.application.validation.ValidationTester; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author bratseth @@ -20,10 +20,10 @@ import static org.junit.Assert.assertTrue; public class RestartChangesDefersConfigChangesTest { @Test - public void changes_requiring_restart_defers_config_changes() { + void changes_requiring_restart_defers_config_changes() { ValidationTester tester = new ValidationTester(new InMemoryProvisioner(5, - new NodeResources(1, 3, 9, 1), - true)); + new NodeResources(1, 3, 9, 1), + true)); VespaModel gen1 = tester.deploy(null, getServices(5, 3), Environment.prod, null).getFirst(); // Change node count - no restart diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/StartupCommandChangeValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/StartupCommandChangeValidatorTest.java index 952b89a6ab1..8d542ce85f3 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/StartupCommandChangeValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/StartupCommandChangeValidatorTest.java @@ -9,18 +9,19 @@ import com.yahoo.vespa.model.AbstractService; import com.yahoo.vespa.model.Host; import com.yahoo.vespa.model.HostResource; import com.yahoo.vespa.model.PortAllocBridge; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class StartupCommandChangeValidatorTest { @Test - public void requireThatDifferentStartupCommandIsDetected() { + void requireThatDifferentStartupCommandIsDetected() { MockRoot oldRoot = createRootWithChildren(new ServiceStub("evilservice", "rm -rf /")); MockRoot newRoot = createRootWithChildren(new ServiceStub("evilservice", "rm -rf *")); List<ConfigChangeAction> changes = getStartupCommandChanges(oldRoot, newRoot); @@ -29,7 +30,7 @@ public class StartupCommandChangeValidatorTest { } @Test - public void requireEmptyResultForEqualStartupCommand() { + void requireEmptyResultForEqualStartupCommand() { MockRoot oldRoot = createRootWithChildren(new ServiceStub("evilservice", "./hax.sh")); MockRoot newRoot = createRootWithChildren(new ServiceStub("evilservice", "./hax.sh")); List<ConfigChangeAction> changes = getStartupCommandChanges(oldRoot, newRoot); @@ -37,7 +38,7 @@ public class StartupCommandChangeValidatorTest { } @Test - public void requireEmptyResultForDifferentServices() { + void requireEmptyResultForDifferentServices() { MockRoot oldRoot = createRootWithChildren(new ServiceStub("evilservice", "./hax.sh")); MockRoot newRoot = createRootWithChildren(new ServiceStub("goodservice", "./hax.sh")); List<ConfigChangeAction> changes = getStartupCommandChanges(oldRoot, newRoot); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/StreamingSchemaClusterChangeValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/StreamingSchemaClusterChangeValidatorTest.java index 2e5b27bee6f..92f2cf61c36 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/StreamingSchemaClusterChangeValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/StreamingSchemaClusterChangeValidatorTest.java @@ -11,7 +11,7 @@ import com.yahoo.vespa.model.content.utils.ApplicationPackageBuilder; import com.yahoo.vespa.model.content.utils.ContentClusterBuilder; import com.yahoo.vespa.model.content.utils.DocType; import com.yahoo.vespa.model.content.utils.SchemaBuilder; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.time.Instant; import java.util.Arrays; @@ -19,7 +19,7 @@ import java.util.List; import static com.yahoo.vespa.model.application.validation.change.ConfigChangeTestUtils.assertEqualActions; import static com.yahoo.vespa.model.application.validation.change.ConfigChangeTestUtils.normalizeServicesInActions; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertTrue; public class StreamingSchemaClusterChangeValidatorTest { @@ -98,13 +98,13 @@ public class StreamingSchemaClusterChangeValidatorTest { new ServiceInfo("searchnode2", "null", null, null, "bar/search/0", "null")); @Test - public void changing_field_type_requires_refeed() { + void changing_field_type_requires_refeed() { Fixture.withOneDocType(STRING_FIELD, INT_FIELD) .assertValidation(createFieldTypeChangeRefeedAction("d1", FOO_SERVICE)); } @Test - public void changes_in_multiple_streaming_clusters_are_discovered() { + void changes_in_multiple_streaming_clusters_are_discovered() { Fixture.withTwoClusters(STRING_FIELD, INT_FIELD) .assertValidation(Arrays.asList( createFieldTypeChangeRefeedAction("d1", FOO_SERVICE), @@ -112,7 +112,7 @@ public class StreamingSchemaClusterChangeValidatorTest { } @Test - public void changes_in_multiple_document_types_are_discovered() { + void changes_in_multiple_document_types_are_discovered() { Fixture.withTwoDocTypes(STRING_FIELD, INT_FIELD) .assertValidation(Arrays.asList( createFieldTypeChangeRefeedAction("d1", FOO_SERVICE), @@ -120,7 +120,7 @@ public class StreamingSchemaClusterChangeValidatorTest { } @Test - public void adding_fast_access_to_an_attribute_requires_restart() { + void adding_fast_access_to_an_attribute_requires_restart() { Fixture.withOneDocType(INT_FIELD, ATTRIBUTE_FAST_ACCESS_INT_FIELD) .assertValidation(createAddFastAccessRestartAction()); @@ -129,7 +129,7 @@ public class StreamingSchemaClusterChangeValidatorTest { } @Test - public void removing_fast_access_from_an_attribute_requires_restart() { + void removing_fast_access_from_an_attribute_requires_restart() { Fixture.withOneDocType(ATTRIBUTE_FAST_ACCESS_INT_FIELD, INT_FIELD) .assertValidation(createRemoveFastAccessRestartAction()); @@ -138,27 +138,27 @@ public class StreamingSchemaClusterChangeValidatorTest { } @Test - public void adding_attribute_field_is_ok() { + void adding_attribute_field_is_ok() { Fixture.withOneDocType(INT_FIELD, ATTRIBUTE_INT_FIELD).assertValidation(); } @Test - public void removing_attribute_field_is_ok() { + void removing_attribute_field_is_ok() { Fixture.withOneDocType(ATTRIBUTE_INT_FIELD, INT_FIELD).assertValidation(); } @Test - public void unchanged_fast_access_attribute_field_is_ok() { + void unchanged_fast_access_attribute_field_is_ok() { Fixture.withOneDocType(ATTRIBUTE_FAST_ACCESS_INT_FIELD, ATTRIBUTE_FAST_ACCESS_INT_FIELD).assertValidation(); } @Test - public void adding_streaming_cluster_is_ok() { + void adding_streaming_cluster_is_ok() { new Fixture(Fixture.createOneDocModel(STRING_FIELD), Fixture.createTwoClusterModel(STRING_FIELD, STRING_FIELD)).assertValidation(); } @Test - public void removing_streaming_cluster_is_ok() { + void removing_streaming_cluster_is_ok() { new Fixture(Fixture.createTwoClusterModel(STRING_FIELD, STRING_FIELD), Fixture.createOneDocModel(STRING_FIELD)).assertValidation(); } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/AttributeChangeValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/AttributeChangeValidatorTest.java index 8d6f05f40e7..076d78912e8 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/AttributeChangeValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/AttributeChangeValidatorTest.java @@ -6,13 +6,13 @@ import com.yahoo.config.application.api.ValidationOverrides; import com.yahoo.config.provision.ClusterSpec; import com.yahoo.test.ManualClock; import com.yahoo.vespa.model.application.validation.change.VespaConfigChangeAction; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.List; import static com.yahoo.vespa.model.application.validation.change.ConfigChangeTestUtils.newRestartAction; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; public class AttributeChangeValidatorTest { @@ -40,181 +40,181 @@ public class AttributeChangeValidatorTest { } @Test - public void adding_attribute_aspect_require_restart() throws Exception { + void adding_attribute_aspect_require_restart() throws Exception { Fixture f = new Fixture("field f1 type string { indexing: summary }", "field f1 type string { indexing: attribute | summary }"); f.assertValidation(newRestartAction(ClusterSpec.Id.from("test"), - "Field 'f1' changed: add attribute aspect")); + "Field 'f1' changed: add attribute aspect")); } @Test - public void removing_attribute_aspect_require_restart() throws Exception { + void removing_attribute_aspect_require_restart() throws Exception { Fixture f = new Fixture("field f1 type string { indexing: attribute | summary }", "field f1 type string { indexing: summary }"); f.assertValidation(newRestartAction(ClusterSpec.Id.from("test"), - "Field 'f1' changed: remove attribute aspect")); + "Field 'f1' changed: remove attribute aspect")); } @Test - public void adding_attribute_field_is_ok() throws Exception { + void adding_attribute_field_is_ok() throws Exception { Fixture f = new Fixture("", "field f1 type string { indexing: attribute | summary \n attribute: fast-search }"); f.assertValidation(); } @Test - public void removing_attribute_field_is_ok() throws Exception { + void removing_attribute_field_is_ok() throws Exception { Fixture f = new Fixture("field f1 type string { indexing: attribute | summary }", ""); f.assertValidation(); } @Test - public void changing_fast_search_require_restart() throws Exception { + void changing_fast_search_require_restart() throws Exception { new Fixture("field f1 type string { indexing: attribute }", "field f1 type string { indexing: attribute \n attribute: fast-search }"). assertValidation(newRestartAction(ClusterSpec.Id.from("test"), - "Field 'f1' changed: add attribute 'fast-search'")); + "Field 'f1' changed: add attribute 'fast-search'")); } @Test - public void changing_fast_rank_require_restart() throws Exception { + void changing_fast_rank_require_restart() throws Exception { new Fixture("field f1 type tensor(x{}) { indexing: attribute }", "field f1 type tensor(x{}) { indexing: attribute \n attribute: fast-rank }"). assertValidation(newRestartAction(ClusterSpec.Id.from("test"), - "Field 'f1' changed: add attribute 'fast-rank'")); + "Field 'f1' changed: add attribute 'fast-rank'")); } @Test - public void changing_btree2hash_require_restart() throws Exception { + void changing_btree2hash_require_restart() throws Exception { new Fixture("field f1 type long { indexing: attribute\n attribute: fast-search\n dictionary: btree}", "field f1 type long { indexing: attribute\n attribute: fast-search\n dictionary: hash }"). assertValidation(newRestartAction(ClusterSpec.Id.from("test"), - "Field 'f1' changed: change property 'dictionary: btree/hash' from 'BTREE' to 'HASH'")); + "Field 'f1' changed: change property 'dictionary: btree/hash' from 'BTREE' to 'HASH'")); } @Test - public void changing_hash2btree_require_restart() throws Exception { + void changing_hash2btree_require_restart() throws Exception { new Fixture("field f1 type long { indexing: attribute\n attribute: fast-search\n dictionary: hash}", "field f1 type long { indexing: attribute\n attribute: fast-search\n dictionary: btree }"). assertValidation(newRestartAction(ClusterSpec.Id.from("test"), - "Field 'f1' changed: change property 'dictionary: btree/hash' from 'HASH' to 'BTREE'")); + "Field 'f1' changed: change property 'dictionary: btree/hash' from 'HASH' to 'BTREE'")); } @Test - public void changing_fast_access_require_restart() throws Exception { + void changing_fast_access_require_restart() throws Exception { new Fixture("field f1 type string { indexing: attribute \n attribute: fast-access }", "field f1 type string { indexing: attribute }"). assertValidation(newRestartAction(ClusterSpec.Id.from("test"), - "Field 'f1' changed: remove attribute 'fast-access'")); + "Field 'f1' changed: remove attribute 'fast-access'")); } @Test - public void changing_uncased2cased_require_restart() throws Exception { + void changing_uncased2cased_require_restart() throws Exception { new Fixture("field f1 type string { indexing: attribute\n attribute: fast-search\n dictionary { btree\ncased}\nmatch:cased}", "field f1 type string { indexing: attribute\n attribute: fast-search\n dictionary{ btree\nuncased}\nmatch:uncased }"). assertValidation(newRestartAction(ClusterSpec.Id.from("test"), - "Field 'f1' changed: change property 'dictionary: cased/uncased' from 'CASED' to 'UNCASED'")); + "Field 'f1' changed: change property 'dictionary: cased/uncased' from 'CASED' to 'UNCASED'")); } @Test - public void changing_dense_posting_list_threshold_require_restart() throws Exception { + void changing_dense_posting_list_threshold_require_restart() throws Exception { new Fixture( "field f1 type predicate { indexing: attribute \n index { arity: 8 \n dense-posting-list-threshold: 0.2 } }", "field f1 type predicate { indexing: attribute \n index { arity: 8 \n dense-posting-list-threshold: 0.4 } }"). assertValidation(newRestartAction(ClusterSpec.Id.from("test"), - "Field 'f1' changed: change property 'dense-posting-list-threshold' from '0.2' to '0.4'")); + "Field 'f1' changed: change property 'dense-posting-list-threshold' from '0.2' to '0.4'")); } @Test - public void removing_attribute_aspect_from_index_field_is_ok() throws Exception { + void removing_attribute_aspect_from_index_field_is_ok() throws Exception { Fixture f = new Fixture("field f1 type string { indexing: index | attribute }", "field f1 type string { indexing: index }"); f.assertValidation(); } @Test - public void removing_attribute_aspect_from_index_and_summary_field_is_ok() throws Exception { + void removing_attribute_aspect_from_index_and_summary_field_is_ok() throws Exception { Fixture f = new Fixture("field f1 type string { indexing: index | attribute | summary }", "field f1 type string { indexing: index | summary }"); f.assertValidation(); } @Test - public void adding_rank_filter_requires_restart() throws Exception { + void adding_rank_filter_requires_restart() throws Exception { new Fixture("field f1 type string { indexing: attribute }", "field f1 type string { indexing: attribute \n rank: filter }"). assertValidation(newRestartAction(ClusterSpec.Id.from("test"), - "Field 'f1' changed: add attribute 'rank: filter'")); + "Field 'f1' changed: add attribute 'rank: filter'")); } @Test - public void removing_rank_filter_requires_restart() throws Exception { + void removing_rank_filter_requires_restart() throws Exception { new Fixture("field f1 type string { indexing: attribute \n rank: filter }", "field f1 type string { indexing: attribute }"). assertValidation(newRestartAction(ClusterSpec.Id.from("test"), - "Field 'f1' changed: remove attribute 'rank: filter'")); + "Field 'f1' changed: remove attribute 'rank: filter'")); } @Test - public void adding_hnsw_index_requires_restart() throws Exception { + void adding_hnsw_index_requires_restart() throws Exception { new Fixture("field f1 type tensor(x[2]) { indexing: attribute }", "field f1 type tensor(x[2]) { indexing: attribute | index \n index { hnsw } }"). assertValidation(newRestartAction(ClusterSpec.Id.from("test"), - "Field 'f1' changed: add attribute 'indexing: index'")); + "Field 'f1' changed: add attribute 'indexing: index'")); } @Test - public void removing_hnsw_index_requres_restart() throws Exception { + void removing_hnsw_index_requres_restart() throws Exception { new Fixture("field f1 type tensor(x[2]) { indexing: attribute | index \n index { hnsw } }", "field f1 type tensor(x[2]) { indexing: attribute }"). assertValidation(newRestartAction(ClusterSpec.Id.from("test"), - "Field 'f1' changed: remove attribute 'indexing: index'")); + "Field 'f1' changed: remove attribute 'indexing: index'")); } @Test - public void changing_distance_metric_without_hnsw_index_enabled_requires_restart() throws Exception { + void changing_distance_metric_without_hnsw_index_enabled_requires_restart() throws Exception { new Fixture("field f1 type tensor(x[2]) { indexing: attribute }", "field f1 type tensor(x[2]) { indexing: attribute \n attribute { " + "distance-metric: geodegrees \n } }"). assertValidation(newRestartAction(ClusterSpec.Id.from("test"), - "Field 'f1' changed: change property " + - "'distance-metric' from 'EUCLIDEAN' to 'GEODEGREES'")); + "Field 'f1' changed: change property " + + "'distance-metric' from 'EUCLIDEAN' to 'GEODEGREES'")); } @Test - public void changing_distance_metric_with_hnsw_index_enabled_requires_restart() throws Exception { + void changing_distance_metric_with_hnsw_index_enabled_requires_restart() throws Exception { new Fixture("field f1 type tensor(x[2]) { indexing: attribute | index \n index { hnsw } }", "field f1 type tensor(x[2]) { indexing: attribute | index \n attribute { " + "distance-metric: geodegrees \n } }"). assertValidation(newRestartAction(ClusterSpec.Id.from("test"), - "Field 'f1' changed: change property " + - "'distance-metric' from 'EUCLIDEAN' to 'GEODEGREES'")); + "Field 'f1' changed: change property " + + "'distance-metric' from 'EUCLIDEAN' to 'GEODEGREES'")); } @Test - public void changing_hnsw_index_property_max_links_per_node_requires_restart() throws Exception { + void changing_hnsw_index_property_max_links_per_node_requires_restart() throws Exception { new Fixture("field f1 type tensor(x[2]) { indexing: attribute | index \n index { hnsw } }", "field f1 type tensor(x[2]) { indexing: attribute | index \n index { " + "hnsw { max-links-per-node: 4 } } }"). assertValidation(newRestartAction(ClusterSpec.Id.from("test"), - "Field 'f1' changed: change hnsw index property " + - "'max-links-per-node' from '16' to '4'")); + "Field 'f1' changed: change hnsw index property " + + "'max-links-per-node' from '16' to '4'")); } @Test - public void changing_hnsw_index_property_neighbors_to_explore_at_insert_requires_restart() throws Exception { + void changing_hnsw_index_property_neighbors_to_explore_at_insert_requires_restart() throws Exception { new Fixture("field f1 type tensor(x[2]) { indexing: attribute | index \n index { hnsw } }", "field f1 type tensor(x[2]) { indexing: attribute | index \n index { " + "hnsw { neighbors-to-explore-at-insert: 100 } } }"). assertValidation(newRestartAction(ClusterSpec.Id.from("test"), - "Field 'f1' changed: change hnsw index property " + - "'neighbors-to-explore-at-insert' from '200' to '100'")); + "Field 'f1' changed: change hnsw index property " + + "'neighbors-to-explore-at-insert' from '200' to '100'")); } @Test - public void removing_paged_requires_override() throws Exception { + void removing_paged_requires_override() throws Exception { try { new Fixture("field f1 type tensor(x[10]) { indexing: attribute \n attribute: paged }", - "field f1 type tensor(x[10]) { indexing: attribute }"). + "field f1 type tensor(x[10]) { indexing: attribute }"). assertValidation(); fail("Expected exception on removal of 'paged'"); } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/ContentClusterFixture.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/ContentClusterFixture.java index 030f1d7d85d..eae7f4f7b41 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/ContentClusterFixture.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/ContentClusterFixture.java @@ -12,8 +12,8 @@ import com.yahoo.vespa.model.search.DocumentDatabase; import java.util.Arrays; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test fixture to setup current and next content clusters used for change validation. diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/DocumentDatabaseChangeValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/DocumentDatabaseChangeValidatorTest.java index aba5c2aa05c..27a90c73725 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/DocumentDatabaseChangeValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/DocumentDatabaseChangeValidatorTest.java @@ -6,7 +6,7 @@ import com.yahoo.config.application.api.ValidationOverrides; import com.yahoo.config.provision.ClusterSpec; import com.yahoo.test.ManualClock; import com.yahoo.vespa.model.application.validation.change.VespaConfigChangeAction; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.time.Instant; import java.util.Arrays; @@ -40,34 +40,34 @@ public class DocumentDatabaseChangeValidatorTest { } @Test - public void requireThatAttributeIndexAndDocumentTypeChangesAreDiscovered() throws Exception { + void requireThatAttributeIndexAndDocumentTypeChangesAreDiscovered() throws Exception { Fixture f = new Fixture("struct s { field s1 type string {} } " + "field f1 type string { indexing: summary } " + "field f2 type string { indexing: summary } " + "field f3 type int { indexing: summary } " + "field f4 type array<s> { } ", "struct s { field s1 type string {} } " + - "field f1 type string { indexing: attribute | summary } " + - "field f2 type string { indexing: index | summary } " + - "field f3 type string { indexing: summary } " + - "field f4 type array<s> { struct-field s1 { indexing: attribute } }"); + "field f1 type string { indexing: attribute | summary } " + + "field f2 type string { indexing: index | summary } " + + "field f3 type string { indexing: summary } " + + "field f4 type array<s> { struct-field s1 { indexing: attribute } }"); Instant.now(); f.assertValidation(Arrays.asList( newRestartAction(ClusterSpec.Id.from("test"), - "Field 'f1' changed: add attribute aspect"), + "Field 'f1' changed: add attribute aspect"), newRestartAction(ClusterSpec.Id.from("test"), - "Field 'f4.s1' changed: add attribute aspect"), + "Field 'f4.s1' changed: add attribute aspect"), newReindexAction(ClusterSpec.Id.from("test"), - ValidationId.indexingChange, - "Field 'f2' changed: add index aspect, indexing script: '{ input f2 | summary f2; }' -> " + + ValidationId.indexingChange, + "Field 'f2' changed: add index aspect, indexing script: '{ input f2 | summary f2; }' -> " + "'{ input f2 | tokenize normalize stem:\"BEST\" | index f2 | summary f2; }'"), newRefeedAction(ClusterSpec.Id.from("test"), ValidationId.fieldTypeChange, "Field 'f3' changed: data type: 'int' -> 'string'"))); } @Test - public void requireThatRemovingAttributeAspectFromIndexFieldIsOk() throws Exception { + void requireThatRemovingAttributeAspectFromIndexFieldIsOk() throws Exception { Fixture f = new Fixture("field f1 type string { indexing: index | attribute }", - "field f1 type string { indexing: index }"); + "field f1 type string { indexing: index }"); f.assertValidation(); } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/DocumentTypeChangeValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/DocumentTypeChangeValidatorTest.java index 859194fae79..639ca820613 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/DocumentTypeChangeValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/DocumentTypeChangeValidatorTest.java @@ -11,7 +11,7 @@ import com.yahoo.documentmodel.NewDocumentType; import com.yahoo.schema.FieldSets; import com.yahoo.vespa.model.application.validation.change.VespaConfigChangeAction; import com.yahoo.vespa.model.application.validation.change.VespaRefeedAction; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.time.Instant; import java.util.Arrays; @@ -20,8 +20,8 @@ import java.util.List; import java.util.Optional; import static com.yahoo.vespa.model.application.validation.change.ConfigChangeTestUtils.newRefeedAction; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test validation of changes between a current and next document type used in a document database. @@ -49,134 +49,134 @@ public class DocumentTypeChangeValidatorTest { } @Test - public void requireThatFieldRemovalIsOK() throws Exception { + void requireThatFieldRemovalIsOK() throws Exception { Fixture f = new Fixture("field f1 type string { indexing: summary }", - "field f2 type string { indexing: summary }"); + "field f2 type string { indexing: summary }"); f.assertValidation(); } @Test - public void requireThatSameDataTypeIsOK() throws Exception { + void requireThatSameDataTypeIsOK() throws Exception { Fixture f = new Fixture("field f1 type string { indexing: summary }", - "field f1 type string { indexing: summary }"); + "field f1 type string { indexing: summary }"); f.assertValidation(); } @Test - public void requireThatDataTypeChangeIsNotOK() throws Exception { + void requireThatDataTypeChangeIsNotOK() throws Exception { Fixture f = new Fixture("field f1 type string { indexing: summary }", - "field f1 type int { indexing: summary }"); + "field f1 type int { indexing: summary }"); Instant.now(); f.assertValidation(newRefeedAction(ClusterSpec.Id.from("test"), ValidationId.fieldTypeChange, "Field 'f1' changed: data type: 'string' -> 'int'")); } @Test - public void requireThatAddingCollectionTypeIsNotOK() throws Exception { + void requireThatAddingCollectionTypeIsNotOK() throws Exception { Fixture f = new Fixture("field f1 type string { indexing: summary }", - "field f1 type array<string> { indexing: summary }"); + "field f1 type array<string> { indexing: summary }"); Instant.now(); f.assertValidation(newRefeedAction(ClusterSpec.Id.from("test"), ValidationId.fieldTypeChange, "Field 'f1' changed: data type: 'string' -> 'Array<string>'")); } @Test - public void requireThatSameNestedDataTypeIsOK() throws Exception { + void requireThatSameNestedDataTypeIsOK() throws Exception { Fixture f = new Fixture("field f1 type array<string> { indexing: summary }", - "field f1 type array<string> { indexing: summary }"); + "field f1 type array<string> { indexing: summary }"); f.assertValidation(); } @Test - public void requireThatNestedDataTypeChangeIsNotOK() throws Exception { + void requireThatNestedDataTypeChangeIsNotOK() throws Exception { Fixture f = new Fixture("field f1 type array<string> { indexing: summary }", - "field f1 type array<int> { indexing: summary }"); + "field f1 type array<int> { indexing: summary }"); Instant.now(); f.assertValidation(newRefeedAction(ClusterSpec.Id.from("test"), ValidationId.fieldTypeChange, "Field 'f1' changed: data type: 'Array<string>' -> 'Array<int>'")); } @Test - public void requireThatChangedCollectionTypeIsNotOK() throws Exception { + void requireThatChangedCollectionTypeIsNotOK() throws Exception { Fixture f = new Fixture("field f1 type array<string> { indexing: summary }", - "field f1 type weightedset<string> { indexing: summary }"); + "field f1 type weightedset<string> { indexing: summary }"); Instant.now(); f.assertValidation(newRefeedAction(ClusterSpec.Id.from("test"), ValidationId.fieldTypeChange, "Field 'f1' changed: data type: 'Array<string>' -> 'WeightedSet<string>'")); } @Test - public void requireThatMultipleDataTypeChangesIsNotOK() throws Exception { - Fixture f = new Fixture("field f1 type string { indexing: summary } field f2 type int { indexing: summary }" , - "field f2 type string { indexing: summary } field f1 type int { indexing: summary }"); + void requireThatMultipleDataTypeChangesIsNotOK() throws Exception { + Fixture f = new Fixture("field f1 type string { indexing: summary } field f2 type int { indexing: summary }", + "field f2 type string { indexing: summary } field f1 type int { indexing: summary }"); Instant.now(); Instant.now(); f.assertValidation(Arrays.asList(newRefeedAction(ClusterSpec.Id.from("test"), ValidationId.fieldTypeChange, "Field 'f1' changed: data type: 'string' -> 'int'"), - newRefeedAction(ClusterSpec.Id.from("test"), ValidationId.fieldTypeChange, "Field 'f2' changed: data type: 'int' -> 'string'"))); + newRefeedAction(ClusterSpec.Id.from("test"), ValidationId.fieldTypeChange, "Field 'f2' changed: data type: 'int' -> 'string'"))); } @Test - public void requireThatSameDataTypeInStructFieldIsOK() throws Exception { + void requireThatSameDataTypeInStructFieldIsOK() throws Exception { Fixture f = new Fixture("struct s1 { field f1 type string {} } field f2 type s1 { indexing: summary }", - "struct s1 { field f1 type string {} } field f2 type s1 { indexing: summary }"); + "struct s1 { field f1 type string {} } field f2 type s1 { indexing: summary }"); f.assertValidation(); } @Test - public void requireThatSameNestedDataTypeChangeInStructFieldIsOK() throws Exception { + void requireThatSameNestedDataTypeChangeInStructFieldIsOK() throws Exception { Fixture f = new Fixture("struct s1 { field f1 type array<string> {} } field f2 type s1 { indexing: summary }", - "struct s1 { field f1 type array<string> {} } field f2 type s1 { indexing: summary }"); + "struct s1 { field f1 type array<string> {} } field f2 type s1 { indexing: summary }"); f.assertValidation(); } @Test - public void requireThatAddingFieldInStructFieldIsOK() throws Exception { + void requireThatAddingFieldInStructFieldIsOK() throws Exception { Fixture f = new Fixture("struct s1 { field f1 type string {} } field f3 type s1 { indexing: summary }", - "struct s1 { field f1 type string {} field f2 type int {} } field f3 type s1 { indexing: summary }"); + "struct s1 { field f1 type string {} field f2 type int {} } field f3 type s1 { indexing: summary }"); f.assertValidation(); } @Test - public void requireThatRemovingFieldInStructFieldIsOK() throws Exception { + void requireThatRemovingFieldInStructFieldIsOK() throws Exception { Fixture f = new Fixture("struct s1 { field f1 type string {} field f2 type int {} } field f3 type s1 { indexing: summary }", - "struct s1 { field f1 type string {} } field f3 type s1 { indexing: summary }"); + "struct s1 { field f1 type string {} } field f3 type s1 { indexing: summary }"); f.assertValidation(); } @Test - public void requireThatDataTypeChangeInStructFieldIsNotOK() throws Exception { + void requireThatDataTypeChangeInStructFieldIsNotOK() throws Exception { Fixture f = new Fixture("struct s1 { field f1 type string {} } field f2 type s1 { indexing: summary }", - "struct s1 { field f1 type int {} } field f2 type s1 { indexing: summary }"); + "struct s1 { field f1 type int {} } field f2 type s1 { indexing: summary }"); Instant.now(); f.assertValidation(newRefeedAction(ClusterSpec.Id.from("test"), ValidationId.fieldTypeChange, "Field 'f2' changed: data type: 's1:{f1:string}' -> 's1:{f1:int}'")); } @Test - public void requireThatNestedDataTypeChangeInStructFieldIsNotOK() throws Exception { + void requireThatNestedDataTypeChangeInStructFieldIsNotOK() throws Exception { Fixture f = new Fixture("struct s1 { field f1 type array<string> {} } field f2 type s1 { indexing: summary }", - "struct s1 { field f1 type array<int> {} } field f2 type s1 { indexing: summary }"); + "struct s1 { field f1 type array<int> {} } field f2 type s1 { indexing: summary }"); Instant.now(); f.assertValidation(newRefeedAction(ClusterSpec.Id.from("test"), ValidationId.fieldTypeChange, "Field 'f2' changed: data type: 's1:{f1:Array<string>}' -> 's1:{f1:Array<int>}'")); } @Test - public void requireThatDataTypeChangeInNestedStructFieldIsNotOK() throws Exception { + void requireThatDataTypeChangeInNestedStructFieldIsNotOK() throws Exception { Fixture f = new Fixture("struct s1 { field f1 type string {} } struct s2 { field f2 type s1 {} } field f3 type s2 { indexing: summary }", - "struct s1 { field f1 type int {} } struct s2 { field f2 type s1 {} } field f3 type s2 { indexing: summary }"); + "struct s1 { field f1 type int {} } struct s2 { field f2 type s1 {} } field f3 type s2 { indexing: summary }"); Instant.now(); f.assertValidation(newRefeedAction(ClusterSpec.Id.from("test"), ValidationId.fieldTypeChange, "Field 'f3' changed: data type: 's2:{s1:{f1:string}}' -> 's2:{s1:{f1:int}}'")); } @Test - public void requireThatMultipleDataTypeChangesInStructFieldIsNotOK() throws Exception { + void requireThatMultipleDataTypeChangesInStructFieldIsNotOK() throws Exception { Fixture f = new Fixture("struct s1 { field f1 type string {} field f2 type int {} } field f3 type s1 { indexing: summary }", - "struct s1 { field f1 type int {} field f2 type string {} } field f3 type s1 { indexing: summary }"); + "struct s1 { field f1 type int {} field f2 type string {} } field f3 type s1 { indexing: summary }"); Instant.now(); f.assertValidation(newRefeedAction(ClusterSpec.Id.from("test"), ValidationId.fieldTypeChange, "Field 'f3' changed: data type: 's1:{f1:string,f2:int}' -> 's1:{f1:int,f2:string}'")); } @Test - public void requireThatChangingTargetTypeOfReferenceFieldIsNotOK() { + void requireThatChangingTargetTypeOfReferenceFieldIsNotOK() { var validator = new DocumentTypeChangeValidator(ClusterSpec.Id.from("test"), - createDocumentTypeWithReferenceField("oldDoc"), - createDocumentTypeWithReferenceField("newDoc")); + createDocumentTypeWithReferenceField("oldDoc"), + createDocumentTypeWithReferenceField("newDoc")); List<VespaConfigChangeAction> result = validator.validate(); assertEquals(1, result.size()); VespaConfigChangeAction action = result.get(0); @@ -189,7 +189,7 @@ public class DocumentTypeChangeValidatorTest { } @Test - public void changing_tensor_type_of_tensor_field_requires_refeed() throws Exception { + void changing_tensor_type_of_tensor_field_requires_refeed() throws Exception { Instant.now(); new Fixture( "field f1 type tensor(x[2]) { indexing: attribute }", diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/IndexingScriptChangeValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/IndexingScriptChangeValidatorTest.java index c2438bd82fc..09385f528fb 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/IndexingScriptChangeValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/IndexingScriptChangeValidatorTest.java @@ -8,14 +8,13 @@ import com.yahoo.vespa.model.application.validation.change.VespaConfigChangeActi import com.yahoo.vespa.model.application.validation.change.VespaReindexAction; import static com.yahoo.config.model.test.TestUtil.joinLines; +import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.List; -import static org.junit.Assert.assertTrue; - public class IndexingScriptChangeValidatorTest { private static class Fixture extends ContentClusterFixture { @@ -72,153 +71,153 @@ public class IndexingScriptChangeValidatorTest { } @Test - public void requireThatAddingIndexAspectRequireReindexing() throws Exception { + void requireThatAddingIndexAspectRequireReindexing() throws Exception { new Fixture(FIELD + " { indexing: summary }", - FIELD + " { indexing: index | summary }"). - assertValidation(expectedReindexingAction("add index aspect", + FIELD + " { indexing: index | summary }"). + assertValidation(expectedReindexingAction("add index aspect", "{ input f1 | summary f1; }", "{ input f1 | tokenize normalize stem:\"BEST\" | index f1 | summary f1; }")); } @Test - public void requireThatRemovingIndexAspectRequireReindexing() throws Exception { + void requireThatRemovingIndexAspectRequireReindexing() throws Exception { new Fixture(FIELD + " { indexing: index | summary }", - FIELD + " { indexing: summary }"). + FIELD + " { indexing: summary }"). assertValidation(expectedReindexingAction("remove index aspect", - "{ input f1 | tokenize normalize stem:\"BEST\" | index f1 | summary f1; }", - "{ input f1 | summary f1; }")); + "{ input f1 | tokenize normalize stem:\"BEST\" | index f1 | summary f1; }", + "{ input f1 | summary f1; }")); } @Test - public void requireThatChangingStemmingRequireReindexing() throws Exception { + void requireThatChangingStemmingRequireReindexing() throws Exception { new Fixture(FIELD + " { indexing: index }", - FIELD + " { indexing: index \n stemming: none }"). + FIELD + " { indexing: index \n stemming: none }"). assertValidation(expectedReindexingAction("stemming: 'best' -> 'none'", - "{ input f1 | tokenize normalize stem:\"BEST\" | index f1; }", - "{ input f1 | tokenize normalize | index f1; }")); + "{ input f1 | tokenize normalize stem:\"BEST\" | index f1; }", + "{ input f1 | tokenize normalize | index f1; }")); } @Test - public void requireThatChangingNormalizingRequireReindexing() throws Exception { + void requireThatChangingNormalizingRequireReindexing() throws Exception { new Fixture(FIELD + " { indexing: index }", - FIELD + " { indexing: index \n normalizing: none }"). + FIELD + " { indexing: index \n normalizing: none }"). assertValidation(expectedReindexingAction("normalizing: 'ACCENT' -> 'NONE'", - "{ input f1 | tokenize normalize stem:\"BEST\" | index f1; }", - "{ input f1 | tokenize stem:\"BEST\" | index f1; }")); + "{ input f1 | tokenize normalize stem:\"BEST\" | index f1; }", + "{ input f1 | tokenize stem:\"BEST\" | index f1; }")); } @Test - public void requireThatChangingMatchingRequireReindexing() throws Exception { + void requireThatChangingMatchingRequireReindexing() throws Exception { new Fixture(FIELD + " { indexing: index \n match: exact }", - FIELD + " { indexing: index \n match { gram \n gram-size: 3 } }"). + FIELD + " { indexing: index \n match { gram \n gram-size: 3 } }"). assertValidation(expectedReindexingAction("matching: 'exact' -> 'gram (size 3)', normalizing: 'LOWERCASE' -> 'CODEPOINT'", - "{ input f1 | exact | index f1; }", - "{ input f1 | ngram 3 | index f1; }")); + "{ input f1 | exact | index f1; }", + "{ input f1 | ngram 3 | index f1; }")); } @Test - public void requireThatSettingDynamicSummaryRequireReindexing() throws Exception { + void requireThatSettingDynamicSummaryRequireReindexing() throws Exception { new Fixture(FIELD + " { indexing: summary }", - FIELD + " { indexing: summary \n summary: dynamic }"). + FIELD + " { indexing: summary \n summary: dynamic }"). assertValidation(expectedReindexingAction("summary field 'f1' transform: 'none' -> 'dynamicteaser'", - "{ input f1 | summary f1; }", - "{ input f1 | tokenize normalize stem:\"BEST\" | summary f1; }")); + "{ input f1 | summary f1; }", + "{ input f1 | tokenize normalize stem:\"BEST\" | summary f1; }")); } @Test - public void requireThatMultipleChangesRequireReindexing() throws Exception { - new Fixture(FIELD + " { indexing: index } " + FIELD_F2 + " { indexing: index }", - FIELD + " { indexing: index \n stemming: none } " + FIELD_F2 + " { indexing: index \n normalizing: none }"). - assertValidation(Arrays.asList(expectedReindexingAction("f1", "stemming: 'best' -> 'none'", - "{ input f1 | tokenize normalize stem:\"BEST\" | index f1; }", - "{ input f1 | tokenize normalize | index f1; }"), - expectedReindexingAction("f2", "normalizing: 'ACCENT' -> 'NONE'", - "{ input f2 | tokenize normalize stem:\"BEST\" | index f2; }", - "{ input f2 | tokenize stem:\"BEST\" | index f2; }"))); + void requireThatMultipleChangesRequireReindexing() throws Exception { + new Fixture(FIELD + " { indexing: index } " + FIELD_F2 + " { indexing: index }", + FIELD + " { indexing: index \n stemming: none } " + FIELD_F2 + " { indexing: index \n normalizing: none }"). + assertValidation(Arrays.asList(expectedReindexingAction("f1", "stemming: 'best' -> 'none'", + "{ input f1 | tokenize normalize stem:\"BEST\" | index f1; }", + "{ input f1 | tokenize normalize | index f1; }"), + expectedReindexingAction("f2", "normalizing: 'ACCENT' -> 'NONE'", + "{ input f2 | tokenize normalize stem:\"BEST\" | index f2; }", + "{ input f2 | tokenize stem:\"BEST\" | index f2; }"))); } @Test - public void requireThatAddingDocumentIndexFieldIsOk() throws Exception { + void requireThatAddingDocumentIndexFieldIsOk() throws Exception { new Fixture("", "field f1 type string { indexing: index | summary }"). assertValidation(); } @Test - public void requireThatRemovingIndexFieldIsOk() throws Exception { + void requireThatRemovingIndexFieldIsOk() throws Exception { new Fixture("field f1 type string { indexing: index | summary }", ""). assertValidation(); } @Test - public void requireThatAddingDocumentFieldIsOk() throws Exception { + void requireThatAddingDocumentFieldIsOk() throws Exception { new Fixture("", FIELD + " { indexing: attribute | summary }"). assertValidation(); } @Test - public void requireThatAddingExtraFieldRequiresReindexing() throws Exception { + void requireThatAddingExtraFieldRequiresReindexing() throws Exception { new Fixture(" field f1 type string { indexing: index }", - " field f1 type string { indexing: index } } " + - " field f2 type string { indexing: input f1 | summary ") + " field f1 type string { indexing: index } } " + + " field f2 type string { indexing: input f1 | summary ") .assertValidation(VespaReindexAction.of(ClusterSpec.Id.from("test"), - null, - "Non-document field 'f2' added; this may be populated by reindexing")); + null, + "Non-document field 'f2' added; this may be populated by reindexing")); } @Test - public void requireThatAddingSummaryAspectIsOk() throws Exception { + void requireThatAddingSummaryAspectIsOk() throws Exception { new Fixture(FIELD + " { indexing: attribute }", - FIELD + " { indexing: attribute | summary }"). + FIELD + " { indexing: attribute | summary }"). assertValidation(); } @Test - public void requireThatSettingDynamicSummaryOnIndexFieldIsOk() throws Exception { + void requireThatSettingDynamicSummaryOnIndexFieldIsOk() throws Exception { new Fixture(FIELD + " { indexing: index | summary }", - FIELD + " { indexing: index | summary \n summary: dynamic }"). + FIELD + " { indexing: index | summary \n summary: dynamic }"). assertValidation(); } @Test - public void requireThatOutputExpressionsAreIgnoredInAdvancedScript() throws Exception { + void requireThatOutputExpressionsAreIgnoredInAdvancedScript() throws Exception { assertTrue(new ScriptFixture("{ input foo | switch { case \"audio\": input bar | index; case \"video\": input baz | index; default: 0 | index; }; }", "{ input foo | switch { case \"audio\": input bar | attribute; case \"video\": input baz | attribute; default: 0 | attribute; }; }"). validate()); } @Test - public void requireThatNormalizeIsOk() throws Exception { + void requireThatNormalizeIsOk() throws Exception { String entireSd = joinLines( - "search test {", - " document test {", - " field inside type array<string> {", - " indexing: summary", - " }", - " }", - " field outside type array<string> {", - " indexing: input inside | for_each { normalize } | index outside", - " }", - "}"); + "search test {", + " document test {", + " field inside type array<string> {", + " indexing: summary", + " }", + " }", + " field outside type array<string> {", + " indexing: input inside | for_each { normalize } | index outside", + " }", + "}"); new Fixture(entireSd).assertValidation(); } @Test - public void requireThatNgramIsOk() throws Exception { + void requireThatNgramIsOk() throws Exception { String entireSd = joinLines( - "search test {", - " document test {", - " field inside type string {", - " indexing: index", - " match {", - " gram", - " gram-size: 3", - " }", - " }", - " }", - " field outside type string {", - " indexing: input inside | ngram 2 | index outside", - " }", - "}"); + "search test {", + " document test {", + " field inside type string {", + " indexing: index", + " match {", + " gram", + " gram-size: 3", + " }", + " }", + " }", + " field outside type string {", + " indexing: input inside | ngram 2 | index outside", + " }", + "}"); new Fixture(entireSd).assertValidation(); } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/StructFieldAttributeChangeValidatorTestCase.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/StructFieldAttributeChangeValidatorTestCase.java index b95d0d05c71..60b681f2960 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/StructFieldAttributeChangeValidatorTestCase.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/StructFieldAttributeChangeValidatorTestCase.java @@ -4,7 +4,7 @@ package com.yahoo.vespa.model.application.validation.change.search; import com.yahoo.config.application.api.ValidationOverrides; import com.yahoo.config.provision.ClusterSpec; import com.yahoo.vespa.model.application.validation.change.VespaConfigChangeAction; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.time.Instant; import java.util.ArrayList; @@ -50,36 +50,36 @@ public class StructFieldAttributeChangeValidatorTestCase { } @Test - public void adding_attribute_aspect_to_struct_field_requires_restart() throws Exception { + void adding_attribute_aspect_to_struct_field_requires_restart() throws Exception { validate(arrayOfStruct(oneFieldStruct(), ""), - arrayOfStruct(oneFieldStruct(), structAttribute("s1")), - newRestartAction(ClusterSpec.Id.from("test"), "Field 'f1.s1' changed: add attribute aspect")); + arrayOfStruct(oneFieldStruct(), structAttribute("s1")), + newRestartAction(ClusterSpec.Id.from("test"), "Field 'f1.s1' changed: add attribute aspect")); validate(mapOfStruct(oneFieldStruct(), ""), - mapOfStruct(oneFieldStruct(), structAttribute("key")), - newRestartAction(ClusterSpec.Id.from("test"), "Field 'f1.key' changed: add attribute aspect")); + mapOfStruct(oneFieldStruct(), structAttribute("key")), + newRestartAction(ClusterSpec.Id.from("test"), "Field 'f1.key' changed: add attribute aspect")); validate(mapOfStruct(oneFieldStruct(), ""), - mapOfStruct(oneFieldStruct(), structAttribute("value.s1")), - newRestartAction(ClusterSpec.Id.from("test"), "Field 'f1.value.s1' changed: add attribute aspect")); + mapOfStruct(oneFieldStruct(), structAttribute("value.s1")), + newRestartAction(ClusterSpec.Id.from("test"), "Field 'f1.value.s1' changed: add attribute aspect")); validate(mapOfPrimitive(""), mapOfPrimitive(structAttribute("key")), - newRestartAction(ClusterSpec.Id.from("test"), "Field 'f1.key' changed: add attribute aspect")); + newRestartAction(ClusterSpec.Id.from("test"), "Field 'f1.key' changed: add attribute aspect")); validate(mapOfPrimitive(""), mapOfPrimitive(structAttribute("value")), - newRestartAction(ClusterSpec.Id.from("test"), "Field 'f1.value' changed: add attribute aspect")); + newRestartAction(ClusterSpec.Id.from("test"), "Field 'f1.value' changed: add attribute aspect")); } @Test - public void removing_attribute_aspect_from_struct_field_is_ok() throws Exception { + void removing_attribute_aspect_from_struct_field_is_ok() throws Exception { validate(arrayOfStruct(oneFieldStruct(), structAttribute("s1")), - arrayOfStruct(oneFieldStruct(), "")); + arrayOfStruct(oneFieldStruct(), "")); validate(mapOfStruct(oneFieldStruct(), structAttribute("key")), - mapOfStruct(oneFieldStruct(), "")); + mapOfStruct(oneFieldStruct(), "")); validate(mapOfStruct(oneFieldStruct(), structAttribute("value.s1")), - mapOfStruct(oneFieldStruct(), "")); + mapOfStruct(oneFieldStruct(), "")); validate(mapOfPrimitive(structAttribute("key")), mapOfPrimitive("")); @@ -87,39 +87,39 @@ public class StructFieldAttributeChangeValidatorTestCase { } @Test - public void adding_struct_field_with_attribute_aspect_is_ok() throws Exception { + void adding_struct_field_with_attribute_aspect_is_ok() throws Exception { validate(arrayOfStruct(oneFieldStruct(), ""), arrayOfStruct(twoFieldStruct(), structAttribute("s2"))); validate(mapOfStruct(oneFieldStruct(), ""), - mapOfStruct(twoFieldStruct(), structAttribute("value.s2"))); + mapOfStruct(twoFieldStruct(), structAttribute("value.s2"))); } @Test - public void removing_struct_field_with_attribute_aspect_is_ok() throws Exception { + void removing_struct_field_with_attribute_aspect_is_ok() throws Exception { validate(arrayOfStruct(twoFieldStruct(), structAttribute("s2")), - arrayOfStruct(oneFieldStruct(), "")); + arrayOfStruct(oneFieldStruct(), "")); validate(mapOfStruct(twoFieldStruct(), structAttribute("value.s2")), - mapOfStruct(oneFieldStruct(), "")); + mapOfStruct(oneFieldStruct(), "")); } @Test - public void adding_struct_field_without_attribute_aspect_is_ok() throws Exception { + void adding_struct_field_without_attribute_aspect_is_ok() throws Exception { validate(arrayOfStruct(oneFieldStruct(), ""), - arrayOfStruct(twoFieldStruct(), "")); + arrayOfStruct(twoFieldStruct(), "")); validate(mapOfStruct(oneFieldStruct(), ""), - mapOfStruct(twoFieldStruct(), "")); + mapOfStruct(twoFieldStruct(), "")); } @Test - public void removing_struct_field_without_attribute_aspect_is_ok() throws Exception { + void removing_struct_field_without_attribute_aspect_is_ok() throws Exception { validate(arrayOfStruct(twoFieldStruct(), ""), - arrayOfStruct(oneFieldStruct(), "")); + arrayOfStruct(oneFieldStruct(), "")); validate(mapOfStruct(twoFieldStruct(), ""), - mapOfStruct(oneFieldStruct(), "")); + mapOfStruct(oneFieldStruct(), "")); } private static String oneFieldStruct() { diff --git a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/first/RedundancyOnFirstDeploymentValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/first/RedundancyOnFirstDeploymentValidatorTest.java index baa880e14af..735adfa9187 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/application/validation/first/RedundancyOnFirstDeploymentValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/application/validation/first/RedundancyOnFirstDeploymentValidatorTest.java @@ -7,10 +7,10 @@ import com.yahoo.config.model.deploy.TestProperties; import com.yahoo.config.provision.Environment; import com.yahoo.vespa.model.application.validation.ValidationTester; import com.yahoo.yolean.Exceptions; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author bratseth @@ -22,22 +22,22 @@ public class RedundancyOnFirstDeploymentValidatorTest { .setHostedVespa(true)); @Test - public void testRedundancyOnFirstDeploymentValidation() { + void testRedundancyOnFirstDeploymentValidation() { try { tester.deploy(null, getServices(1), Environment.prod, null); fail("Expected exception due to redundancy 1"); } catch (IllegalArgumentException expected) { assertEquals("redundancy-one: " + - "content cluster 'contentClusterId' has redundancy 1, which will cause it to lose data if a node fails. " + - "This requires an override on first deployment in a production zone. " + - ValidationOverrides.toAllowMessage(ValidationId.redundancyOne), - Exceptions.toMessageString(expected)); + "content cluster 'contentClusterId' has redundancy 1, which will cause it to lose data if a node fails. " + + "This requires an override on first deployment in a production zone. " + + ValidationOverrides.toAllowMessage(ValidationId.redundancyOne), + Exceptions.toMessageString(expected)); } } @Test - public void testOverridingRedundancyOnFirstDeploymentValidation() { + void testOverridingRedundancyOnFirstDeploymentValidation() { tester.deploy(null, getServices(1), Environment.prod, redundancyOneOverride); // Allowed due to override } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/builder/UserConfigBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/builder/UserConfigBuilderTest.java index 55c10a28a01..da01b6ae9f9 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/builder/UserConfigBuilderTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/builder/UserConfigBuilderTest.java @@ -11,16 +11,14 @@ import com.yahoo.vespa.config.ConfigDefinitionKey; import com.yahoo.vespa.config.ConfigPayload; import com.yahoo.vespa.config.ConfigPayloadBuilder; import com.yahoo.vespa.configdefinition.SpecialtokensConfig; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.w3c.dom.Document; import org.w3c.dom.Element; import java.io.Reader; import java.io.StringReader; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.*; /** * @author Ulf Lilleengen @@ -30,13 +28,13 @@ public class UserConfigBuilderTest { private final ConfigDefinitionStore configDefinitionStore = defKey -> Optional.empty(); @Test - public void require_that_simple_config_is_resolved() { + void require_that_simple_config_is_resolved() { Element configRoot = getDocument("<config name=\"test.simpletypes\">" + - " <intval>13</intval>" + - "</config>" + - "<config name=\"test.simpletypes\" version=\"1\">" + - " <stringval>foolio</stringval>" + - "</config>"); + " <intval>13</intval>" + + "</config>" + + "<config name=\"test.simpletypes\" version=\"1\">" + + " <stringval>foolio</stringval>" + + "</config>"); UserConfigRepo map = UserConfigBuilder.build(configRoot, configDefinitionStore, new BaseDeployLogger()); assertFalse(map.isEmpty()); ConfigDefinitionKey key = new ConfigDefinitionKey("simpletypes", "test"); @@ -51,7 +49,7 @@ public class UserConfigBuilderTest { } @Test - public void require_that_arrays_of_structs_are_resolved() { + void require_that_arrays_of_structs_are_resolved() { Element configRoot = getDocument( " <config name='vespa.configdefinition.specialtokens'>" + " <tokenlist>" + @@ -86,7 +84,7 @@ public class UserConfigBuilderTest { } @Test - public void no_exception_when_config_class_does_not_exist() { + void no_exception_when_config_class_does_not_exist() { Element configRoot = getDocument("<config name=\"is.unknown\">" + " <foo>1</foo>" + "</config>"); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/Bug6068056Test.java b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/Bug6068056Test.java index 53d09bdeac3..af950ea2d31 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/Bug6068056Test.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/Bug6068056Test.java @@ -2,7 +2,9 @@ package com.yahoo.vespa.model.builder.xml.dom; import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithMockPkg; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertThrows; /** * @author <a href="mailto:einarmr@yahoo-inc.com">Einar M R Rosenvinge</a> @@ -43,9 +45,11 @@ public class Bug6068056Test { " </content>" + "</services>"; - @Test(expected = RuntimeException.class) - public void testContainerClusterCalledDocproc() { - VespaModelCreatorWithMockPkg creator = new VespaModelCreatorWithMockPkg(HOSTS, SERVICES); - creator.create(); + @Test + void testContainerClusterCalledDocproc() { + assertThrows(RuntimeException.class, () -> { + VespaModelCreatorWithMockPkg creator = new VespaModelCreatorWithMockPkg(HOSTS, SERVICES); + creator.create(); + }); } } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/ContentBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/ContentBuilderTest.java index a3360278505..7f17f5cdd41 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/ContentBuilderTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/ContentBuilderTest.java @@ -22,47 +22,36 @@ import com.yahoo.vespa.model.search.IndexedSearchCluster; import com.yahoo.vespa.model.search.SearchNode; import com.yahoo.vespa.model.search.StreamingSearchCluster; import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithMockPkg; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.List; import static com.yahoo.config.model.api.container.ContainerServiceType.CLUSTERCONTROLLER_CONTAINER; import static com.yahoo.config.model.api.container.ContainerServiceType.METRICS_PROXY_CONTAINER; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; /** * @author baldersheim */ public class ContentBuilderTest extends DomBuilderTest { - @SuppressWarnings("deprecation") - @Rule - public ExpectedException expectedException = ExpectedException.none(); - @Test - public void handleSingleNonSearchPersistentDummy() { + void handleSingleNonSearchPersistentDummy() { ContentCluster a = createContent( - "<content version =\"1.0\" id=\"a\">"+ - " <redundancy>3</redundancy>"+ - " <documents>" + - " <document type=\"music\" mode=\"store-only\"/>" + - " </documents>" + - " <engine>"+ - " <dummy/>"+ - " </engine>"+ - " <group>"+ - " <node hostalias=\"mockhost\" distribution-key=\"0\"/>"+ - " </group>"+ - "</content>"); + "<content version =\"1.0\" id=\"a\">" + + " <redundancy>3</redundancy>" + + " <documents>" + + " <document type=\"music\" mode=\"store-only\"/>" + + " </documents>" + + " <engine>" + + " <dummy/>" + + " </engine>" + + " <group>" + + " <node hostalias=\"mockhost\" distribution-key=\"0\"/>" + + " </group>" + + "</content>"); ContentSearchCluster s = a.getSearch(); assertFalse(s.hasIndexedCluster()); @@ -72,17 +61,17 @@ public class ContentBuilderTest extends DomBuilderTest { } @Test - public void handleSingleNonSearchPersistentVds() { + void handleSingleNonSearchPersistentVds() { ContentCluster a = createContent( - "<content version =\"1.0\" id=\"a\">"+ - " <redundancy>3</redundancy>"+ - " <documents>" + - " <document type=\"music\" mode=\"store-only\"/>" + - " </documents>" + - " <group>"+ - " <node hostalias=\"mockhost\" distribution-key=\"0\"/>"+ - " </group>"+ - "</content>"); + "<content version =\"1.0\" id=\"a\">" + + " <redundancy>3</redundancy>" + + " <documents>" + + " <document type=\"music\" mode=\"store-only\"/>" + + " </documents>" + + " <group>" + + " <node hostalias=\"mockhost\" distribution-key=\"0\"/>" + + " </group>" + + "</content>"); ContentSearchCluster s = a.getSearch(); assertFalse(s.hasIndexedCluster()); @@ -94,20 +83,20 @@ public class ContentBuilderTest extends DomBuilderTest { } @Test - public void handleSingleNonSearchPersistentProton() { + void handleSingleNonSearchPersistentProton() { ContentCluster a = createContent( - "<content version =\"1.0\" id=\"a\">"+ - " <redundancy>3</redundancy>"+ - " <documents>" + - " <document type=\"music\" mode=\"store-only\"/>" + - " </documents>" + - " <engine>"+ - " <proton/>"+ - " </engine>"+ - " <group>"+ - " <node hostalias=\"mockhost\" distribution-key=\"0\"/>"+ - " </group>"+ - "</content>"); + "<content version =\"1.0\" id=\"a\">" + + " <redundancy>3</redundancy>" + + " <documents>" + + " <document type=\"music\" mode=\"store-only\"/>" + + " </documents>" + + " <engine>" + + " <proton/>" + + " </engine>" + + " <group>" + + " <node hostalias=\"mockhost\" distribution-key=\"0\"/>" + + " </group>" + + "</content>"); ContentSearchCluster s = a.getSearch(); assertFalse(s.hasIndexedCluster()); @@ -119,17 +108,17 @@ public class ContentBuilderTest extends DomBuilderTest { } @Test - public void handleSingleNonSearchNonPersistentCluster() { + void handleSingleNonSearchNonPersistentCluster() { ContentCluster a = createContent( - "<content version =\"1.0\" id=\"a\">"+ - " <redundancy>3</redundancy>"+ - " <documents>" + - " <document type=\"music\" mode=\"store-only\"/>" + - " </documents>" + - " <group>"+ - " <node hostalias=\"mockhost\" distribution-key=\"0\"/>"+ - " </group>"+ - "</content>"); + "<content version =\"1.0\" id=\"a\">" + + " <redundancy>3</redundancy>" + + " <documents>" + + " <document type=\"music\" mode=\"store-only\"/>" + + " </documents>" + + " <group>" + + " <node hostalias=\"mockhost\" distribution-key=\"0\"/>" + + " </group>" + + "</content>"); ContentSearchCluster s = a.getSearch(); assertFalse(s.hasIndexedCluster()); @@ -148,7 +137,7 @@ public class ContentBuilderTest extends DomBuilderTest { } @Test - public void handleIndexedOnlyWithoutPersistence() { + void handleIndexedOnlyWithoutPersistence() { VespaModel m = new VespaModelCreatorWithMockPkg(createAppWithMusic(getHosts(), getBasicServices())).create(); ContentCluster c = CollectionUtil.first(m.getContentClusters().values()); @@ -166,7 +155,7 @@ public class ContentBuilderTest extends DomBuilderTest { assertEquals("clu/storage/0", c.getRootGroup().getNodes().get(0).getConfigId()); // Due to reuse. assertEquals(1, c.getRoot().hostSystem().getHosts().size()); HostResource h = c.getRoot().hostSystem().getHost("mockhost"); - String [] expectedServices = {"configserver", "logserver", "logd", "container-clustercontroller", "metricsproxy-container", "slobrok", "configproxy","config-sentinel", "container", "storagenode", "searchnode", "distributor", "transactionlogserver"}; + String [] expectedServices = {"configserver", "logserver", "logd", "container-clustercontroller", "metricsproxy-container", "slobrok", "configproxy", "config-sentinel", "container", "storagenode", "searchnode", "distributor", "transactionlogserver"}; assertServices(h, expectedServices); assertEquals("clu/storage/0", h.getService("storagenode").getConfigId()); assertEquals("clu/search/cluster.clu/0", h.getService("searchnode").getConfigId()); @@ -174,28 +163,28 @@ public class ContentBuilderTest extends DomBuilderTest { } @Test - public void testMultipleSearchNodesOnSameHost() { + void testMultipleSearchNodesOnSameHost() { String services = getServices("<node hostalias='mockhost' distribution-key='0'/>" + - "<node hostalias='mockhost' distribution-key='1'/>"); + "<node hostalias='mockhost' distribution-key='1'/>"); VespaModel m = new VespaModelCreatorWithMockPkg(createAppWithMusic(getHosts(), services)).create(); IndexedSearchCluster sc = m.getContentClusters().get("clu").getSearch().getIndexed(); assertEquals(2, sc.getSearchNodeCount()); } @Test - public void handleStreamingOnlyWithoutPersistence() { + void handleStreamingOnlyWithoutPersistence() { final String musicClusterId = "music-cluster-id"; ContentCluster cluster = createContent( "<content version='1.0' id='" + musicClusterId + "'>" + - " <redundancy>3</redundancy>"+ - " <documents>"+ - " <document type='music' mode='streaming'/>"+ - " </documents>"+ - " <group>"+ - " <node hostalias=\"mockhost\" distribution-key=\"0\"/>"+ - " </group>"+ - "</content>"); + " <redundancy>3</redundancy>" + + " <documents>" + + " <document type='music' mode='streaming'/>" + + " </documents>" + + " <group>" + + " <node hostalias=\"mockhost\" distribution-key=\"0\"/>" + + " </group>" + + "</content>"); ContentSearchCluster s; s = cluster.getSearch(); @@ -204,7 +193,7 @@ public class ContentBuilderTest extends DomBuilderTest { assertNull(s.getIndexed()); SearchCluster sc = s.getClusters().get(musicClusterId + ".music"); assertEquals(musicClusterId + ".music", sc.getClusterName()); - assertEquals(musicClusterId, ((StreamingSearchCluster)sc).getStorageRouteSpec()); + assertEquals(musicClusterId, ((StreamingSearchCluster) sc).getStorageRouteSpec()); assertTrue(cluster.getPersistence() instanceof ProtonEngine.Factory); assertEquals(1, cluster.getStorageCluster().getChildren().size()); @@ -216,7 +205,7 @@ public class ContentBuilderTest extends DomBuilderTest { HostResource h = cluster.getRoot().hostSystem().getHost("mockhost"); String [] expectedServices = { "logd", "configproxy", "config-sentinel", "configserver", "logserver", - "slobrok", "storagenode", "distributor","searchnode","transactionlogserver", + "slobrok", "storagenode", "distributor", "searchnode", "transactionlogserver", CLUSTERCONTROLLER_CONTAINER.serviceName, METRICS_PROXY_CONTAINER.serviceName }; assertServices(h, expectedServices); @@ -231,20 +220,20 @@ public class ContentBuilderTest extends DomBuilderTest { } @Test - public void requireThatContentStreamingHandlesMultipleSchemas() { + void requireThatContentStreamingHandlesMultipleSchemas() { String musicClusterId = "music-cluster-id"; ContentCluster cluster = createContentWithBooksToo( "<content version='1.0' id='" + musicClusterId + "'>" + - " <redundancy>3</redundancy>"+ - " <documents>"+ - " <document type='music' mode='streaming'/>"+ - " <document type='book' mode='streaming'/>"+ - " </documents>"+ - " <group>"+ - " <node hostalias=\"mockhost\" distribution-key=\"0\"/>"+ - " </group>"+ - "</content>"); + " <redundancy>3</redundancy>" + + " <documents>" + + " <document type='music' mode='streaming'/>" + + " <document type='book' mode='streaming'/>" + + " </documents>" + + " <group>" + + " <node hostalias=\"mockhost\" distribution-key=\"0\"/>" + + " </group>" + + "</content>"); ContentSearchCluster s; s = cluster.getSearch(); @@ -271,17 +260,17 @@ public class ContentBuilderTest extends DomBuilderTest { } @Test - public void handleIndexedWithoutPersistence() { + void handleIndexedWithoutPersistence() { ContentCluster b = createContent( "<content version =\"1.0\" id=\"b\">" + - " <redundancy>3</redundancy>"+ - " <documents>"+ - " <document type='music' mode='index'/>"+ - " </documents>"+ - " <group>"+ - " <node hostalias=\"mockhost\" distribution-key=\"0\"/>"+ - " </group>"+ - "</content>"); + " <redundancy>3</redundancy>" + + " <documents>" + + " <document type='music' mode='index'/>" + + " </documents>" + + " <group>" + + " <node hostalias=\"mockhost\" distribution-key=\"0\"/>" + + " </group>" + + "</content>"); ContentSearchCluster s; s = b.getSearch(); @@ -302,18 +291,18 @@ public class ContentBuilderTest extends DomBuilderTest { } @Test - public void canConfigureMmapNoCoreLimit() { + void canConfigureMmapNoCoreLimit() { ContentCluster b = createContent( "<content version =\"1.0\" id=\"b\">" + - " <redundancy>2</redundancy>" + - " <documents>" + - " <document type='music' mode='index'/>" + - " </documents>" + - " <group mmap-core-limit=\"200000\">" + - " <node hostalias=\"mockhost\" distribution-key=\"0\" />" + - " <node hostalias=\"mockhost\" distribution-key=\"1\" />" + - " </group>" + - "</content>"); + " <redundancy>2</redundancy>" + + " <documents>" + + " <document type='music' mode='index'/>" + + " </documents>" + + " <group mmap-core-limit=\"200000\">" + + " <node hostalias=\"mockhost\" distribution-key=\"0\" />" + + " <node hostalias=\"mockhost\" distribution-key=\"1\" />" + + " </group>" + + "</content>"); ContentSearchCluster s; s = b.getSearch(); @@ -329,7 +318,7 @@ public class ContentBuilderTest extends DomBuilderTest { } @Test - public void canAddEnvironmentVariable() { + void canAddEnvironmentVariable() { ContentCluster b = createContent( "<content version =\"1.0\" id=\"b\">" + " <redundancy>1</redundancy>" + @@ -360,7 +349,7 @@ public class ContentBuilderTest extends DomBuilderTest { } @Test - public void addsEnvironmentVariablesfromFeatureFlag() { + void addsEnvironmentVariablesfromFeatureFlag() { ContentCluster b = createContent( "<content version =\"1.0\" id=\"b\">" + " <redundancy>1</redundancy>" + @@ -385,18 +374,18 @@ public class ContentBuilderTest extends DomBuilderTest { } @Test - public void canConfigureCoreOnOOM() { + void canConfigureCoreOnOOM() { ContentCluster b = createContent( "<content version =\"1.0\" id=\"b\">" + - " <redundancy>2</redundancy>" + - " <documents>" + - " <document type='music' mode='index'/>" + - " </documents>" + - " <group core-on-oom=\"true\">" + - " <node hostalias=\"mockhost\" distribution-key=\"0\" />" + - " <node hostalias=\"mockhost\" distribution-key=\"1\" />" + - " </group>" + - "</content>"); + " <redundancy>2</redundancy>" + + " <documents>" + + " <document type='music' mode='index'/>" + + " </documents>" + + " <group core-on-oom=\"true\">" + + " <node hostalias=\"mockhost\" distribution-key=\"0\" />" + + " <node hostalias=\"mockhost\" distribution-key=\"1\" />" + + " </group>" + + "</content>"); ContentSearchCluster s; s = b.getSearch(); @@ -412,18 +401,18 @@ public class ContentBuilderTest extends DomBuilderTest { } @Test - public void defaultCoreOnOOMIsFalse() { + void defaultCoreOnOOMIsFalse() { ContentCluster b = createContent( "<content version =\"1.0\" id=\"b\">" + - " <redundancy>2</redundancy>" + - " <documents>" + - " <document type='music' mode='index'/>" + - " </documents>" + - " <group>" + - " <node hostalias=\"mockhost\" distribution-key=\"0\" />" + - " <node hostalias=\"mockhost\" distribution-key=\"1\" />" + - " </group>" + - "</content>"); + " <redundancy>2</redundancy>" + + " <documents>" + + " <document type='music' mode='index'/>" + + " </documents>" + + " <group>" + + " <node hostalias=\"mockhost\" distribution-key=\"0\" />" + + " <node hostalias=\"mockhost\" distribution-key=\"1\" />" + + " </group>" + + "</content>"); ContentSearchCluster s = b.getSearch(); assertTrue(s.hasIndexedCluster()); assertNotNull(s.getIndexed()); @@ -436,18 +425,18 @@ public class ContentBuilderTest extends DomBuilderTest { } @Test - public void canConfigureMmapNoCoreLimitPerHost() { + void canConfigureMmapNoCoreLimitPerHost() { ContentCluster b = createContent( "<content version =\"1.0\" id=\"b\">" + - " <redundancy>2</redundancy>" + - " <documents>" + - " <document type='music' mode='index'/>" + - " </documents>" + - " <group>" + - " <node hostalias=\"mockhost\" distribution-key=\"0\" mmap-core-limit=\"200000\"/>" + - " <node hostalias=\"mockhost\" distribution-key=\"1\" />" + - " </group>" + - "</content>"); + " <redundancy>2</redundancy>" + + " <documents>" + + " <document type='music' mode='index'/>" + + " </documents>" + + " <group>" + + " <node hostalias=\"mockhost\" distribution-key=\"0\" mmap-core-limit=\"200000\"/>" + + " <node hostalias=\"mockhost\" distribution-key=\"1\" />" + + " </group>" + + "</content>"); ContentSearchCluster s = b.getSearch(); assertTrue(s.hasIndexedCluster()); assertNotNull(s.getIndexed()); @@ -460,18 +449,18 @@ public class ContentBuilderTest extends DomBuilderTest { } @Test - public void canConfigureCoreOnOOMPerHost() { + void canConfigureCoreOnOOMPerHost() { ContentCluster b = createContent( "<content version =\"1.0\" id=\"b\">" + - " <redundancy>2</redundancy>" + - " <documents>" + - " <document type='music' mode='index'/>" + - " </documents>" + - " <group>" + - " <node hostalias=\"mockhost\" distribution-key=\"0\" core-on-oom=\"true\"/>" + - " <node hostalias=\"mockhost\" distribution-key=\"1\" core-on-oom=\"false\"/>" + - " </group>" + - "</content>"); + " <redundancy>2</redundancy>" + + " <documents>" + + " <document type='music' mode='index'/>" + + " </documents>" + + " <group>" + + " <node hostalias=\"mockhost\" distribution-key=\"0\" core-on-oom=\"true\"/>" + + " <node hostalias=\"mockhost\" distribution-key=\"1\" core-on-oom=\"false\"/>" + + " </group>" + + "</content>"); ContentSearchCluster s = b.getSearch(); assertTrue(s.hasIndexedCluster()); assertNotNull(s.getIndexed()); @@ -484,20 +473,20 @@ public class ContentBuilderTest extends DomBuilderTest { } @Test - public void canConfigureVespaMalloc() { + void canConfigureVespaMalloc() { ContentCluster b = createContent( "<content version =\"1.0\" id=\"b\">" + - " <redundancy>2</redundancy>" + - " <documents>" + - " <document type='music' mode='index'/>" + - " </documents>" + - " <group no-vespamalloc=\"proton\" vespamalloc-debug=\"distributord\" vespamalloc-debug-stacktrace=\"all\" vespamalloc=\"storaged\">" + - " <node hostalias=\"mockhost\" distribution-key=\"0\"/>" + - " <node hostalias=\"mockhost\" distribution-key=\"1\"/>" + - " <node hostalias=\"mockhost\" distribution-key=\"2\"/>" + - " <node hostalias=\"mockhost\" distribution-key=\"3\"/>" + - " </group>" + - "</content>"); + " <redundancy>2</redundancy>" + + " <documents>" + + " <document type='music' mode='index'/>" + + " </documents>" + + " <group no-vespamalloc=\"proton\" vespamalloc-debug=\"distributord\" vespamalloc-debug-stacktrace=\"all\" vespamalloc=\"storaged\">" + + " <node hostalias=\"mockhost\" distribution-key=\"0\"/>" + + " <node hostalias=\"mockhost\" distribution-key=\"1\"/>" + + " <node hostalias=\"mockhost\" distribution-key=\"2\"/>" + + " <node hostalias=\"mockhost\" distribution-key=\"3\"/>" + + " </group>" + + "</content>"); ContentSearchCluster s = b.getSearch(); assertTrue(s.hasIndexedCluster()); assertNotNull(s.getIndexed()); @@ -518,20 +507,20 @@ public class ContentBuilderTest extends DomBuilderTest { } @Test - public void canConfigureVespaMallocPerHost() { + void canConfigureVespaMallocPerHost() { ContentCluster b = createContent( "<content version =\"1.0\" id=\"b\">" + - " <redundancy>2</redundancy>" + - " <documents>" + - " <document type='music' mode='index'/>" + - " </documents>" + - " <group>" + - " <node hostalias=\"mockhost\" distribution-key=\"0\" no-vespamalloc=\"proton\"/>" + - " <node hostalias=\"mockhost\" distribution-key=\"1\" vespamalloc-debug=\"distributord\"/>" + - " <node hostalias=\"mockhost\" distribution-key=\"2\" vespamalloc-debug-stacktrace=\"all\"/>" + - " <node hostalias=\"mockhost\" distribution-key=\"3\" vespamalloc=\"storaged\"/>" + - " </group>" + - "</content>"); + " <redundancy>2</redundancy>" + + " <documents>" + + " <document type='music' mode='index'/>" + + " </documents>" + + " <group>" + + " <node hostalias=\"mockhost\" distribution-key=\"0\" no-vespamalloc=\"proton\"/>" + + " <node hostalias=\"mockhost\" distribution-key=\"1\" vespamalloc-debug=\"distributord\"/>" + + " <node hostalias=\"mockhost\" distribution-key=\"2\" vespamalloc-debug-stacktrace=\"all\"/>" + + " <node hostalias=\"mockhost\" distribution-key=\"3\" vespamalloc=\"storaged\"/>" + + " </group>" + + "</content>"); ContentSearchCluster s = b.getSearch(); assertTrue(s.hasIndexedCluster()); assertNotNull(s.getIndexed()); @@ -549,18 +538,18 @@ public class ContentBuilderTest extends DomBuilderTest { } @Test - public void canConfigureCpuAffinity() { + void canConfigureCpuAffinity() { ContentCluster b = createContent( "<content version =\"1.0\" id=\"b\">" + - " <redundancy>2</redundancy>"+ - " <documents>"+ - " <document type='music' mode='index'/>"+ - " </documents>"+ - " <group>"+ - " <node hostalias=\"mockhost\" distribution-key=\"0\" cpu-socket=\"0\" />"+ - " <node hostalias=\"mockhost\" distribution-key=\"1\" cpu-socket=\"1\" />"+ - " </group>"+ - "</content>"); + " <redundancy>2</redundancy>" + + " <documents>" + + " <document type='music' mode='index'/>" + + " </documents>" + + " <group>" + + " <node hostalias=\"mockhost\" distribution-key=\"0\" cpu-socket=\"0\" />" + + " <node hostalias=\"mockhost\" distribution-key=\"1\" cpu-socket=\"1\" />" + + " </group>" + + "</content>"); ContentSearchCluster s; s = b.getSearch(); @@ -580,22 +569,22 @@ public class ContentBuilderTest extends DomBuilderTest { } @Test - public void canConfigureCpuAffinityAutomatically() { + void canConfigureCpuAffinityAutomatically() { ContentCluster b = createContent( "<content version =\"1.0\" id=\"b\">" + - " <redundancy>2</redundancy>"+ - " <documents>"+ - " <document type='music' mode='index'/>"+ - " </documents>"+ - " <group cpu-socket-affinity=\"true\">"+ - " <node hostalias=\"mockhost\" distribution-key=\"0\" />"+ - " <node hostalias=\"mockhost\" distribution-key=\"1\" />"+ - " <node hostalias=\"mockhost\" distribution-key=\"2\" />"+ - " <node hostalias=\"mockhost2\" distribution-key=\"3\" />"+ - " <node hostalias=\"mockhost2\" distribution-key=\"4\" />"+ - " <node hostalias=\"mockhost3\" distribution-key=\"5\" />"+ - " </group>"+ - "</content>"); + " <redundancy>2</redundancy>" + + " <documents>" + + " <document type='music' mode='index'/>" + + " </documents>" + + " <group cpu-socket-affinity=\"true\">" + + " <node hostalias=\"mockhost\" distribution-key=\"0\" />" + + " <node hostalias=\"mockhost\" distribution-key=\"1\" />" + + " <node hostalias=\"mockhost\" distribution-key=\"2\" />" + + " <node hostalias=\"mockhost2\" distribution-key=\"3\" />" + + " <node hostalias=\"mockhost2\" distribution-key=\"4\" />" + + " <node hostalias=\"mockhost3\" distribution-key=\"5\" />" + + " </group>" + + "</content>"); ContentSearchCluster s; s = b.getSearch(); @@ -635,21 +624,21 @@ public class ContentBuilderTest extends DomBuilderTest { } @Test - public void requireBug5357273() { + void requireBug5357273() { try { createContent( - " <content version='1.0' id='storage'>\n" + - " <redundancy>3</redundancy>\n" + - " <documents>"+ - " <document type='music' mode='index'/>"+ - " </documents>" + - " <group>\n" + - " <node hostalias='mockhost' distribution-key='0' />\n" + - " </group>\n" + - " <engine>\n" + - " <dummy/>\n" + - " </engine>\n" + - " </content>\n"); + " <content version='1.0' id='storage'>\n" + + " <redundancy>3</redundancy>\n" + + " <documents>" + + " <document type='music' mode='index'/>" + + " </documents>" + + " <group>\n" + + " <node hostalias='mockhost' distribution-key='0' />\n" + + " </group>\n" + + " <engine>\n" + + " <dummy/>\n" + + " </engine>\n" + + " </content>\n"); fail(); } catch (Exception e) { @@ -659,39 +648,39 @@ public class ContentBuilderTest extends DomBuilderTest { } @Test - public void handleProtonTuning() { + void handleProtonTuning() { ContentCluster a = createContent( "<content version =\"1.0\" id=\"a\">" + - " <redundancy>3</redundancy>" + - " <engine>" + - " <proton>" + - " <tuning>" + - " <searchnode>" + - " <summary>" + - " <store>" + - " <cache>" + - " <maxsize>8192</maxsize>" + - " <compression>" + - " <type>lz4</type>" + - " <level>8</level>" + - " </compression>" + - " </cache>" + - " </store>" + - " <io>" + - " <read>directio</read>" + - " </io>" + - " </summary>" + - " </searchnode>" + - " </tuning>" + - " </proton>" + - " </engine>" + - " <documents>" + - " <document type='music' mode='index'/>" + - " </documents>" + - " <group>" + - " <node hostalias=\"mockhost\" distribution-key=\"0\"/>" + - " </group>" + - "</content>" + " <redundancy>3</redundancy>" + + " <engine>" + + " <proton>" + + " <tuning>" + + " <searchnode>" + + " <summary>" + + " <store>" + + " <cache>" + + " <maxsize>8192</maxsize>" + + " <compression>" + + " <type>lz4</type>" + + " <level>8</level>" + + " </compression>" + + " </cache>" + + " </store>" + + " <io>" + + " <read>directio</read>" + + " </io>" + + " </summary>" + + " </searchnode>" + + " </tuning>" + + " </proton>" + + " </engine>" + + " <documents>" + + " <document type='music' mode='index'/>" + + " </documents>" + + " <group>" + + " <node hostalias=\"mockhost\" distribution-key=\"0\"/>" + + " </group>" + + "</content>" ); assertTrue(a.getPersistence() instanceof ProtonEngine.Factory); @@ -706,26 +695,26 @@ public class ContentBuilderTest extends DomBuilderTest { } @Test - @Ignore - public void ensureOverrideAppendedOnlyOnce() { + @Disabled + void ensureOverrideAppendedOnlyOnce() { ContentCluster content = createContent( "<content version='1.0' id='search'>" + - " <config name=\"vespa.config.search.core.proton\">" + - " <numthreadspersearch>1</numthreadspersearch>" + - " <search>" + - " <mmap>" + - " <options><item>POPULATE</item></options>" + - " </mmap>" + - " </search>" + - " </config>" + - " <redundancy>2</redundancy>" + - " <documents>" + - " <document type='music' mode='index'/>" + - " </documents>" + - " <group>" + - " <node hostalias='mockhost' distribution-key='0'/>" + - " </group>" + - "</content>"); + " <config name=\"vespa.config.search.core.proton\">" + + " <numthreadspersearch>1</numthreadspersearch>" + + " <search>" + + " <mmap>" + + " <options><item>POPULATE</item></options>" + + " </mmap>" + + " </search>" + + " </config>" + + " <redundancy>2</redundancy>" + + " <documents>" + + " <document type='music' mode='index'/>" + + " </documents>" + + " <group>" + + " <node hostalias='mockhost' distribution-key='0'/>" + + " </group>" + + "</content>"); ProtonConfig.Builder builder = new ProtonConfig.Builder(); content.getSearch().getIndexed().getSearchNode(0).cascadeConfig(builder); content.getSearch().getIndexed().getSearchNode(0).addUserConfig(builder); @@ -745,19 +734,20 @@ public class ContentBuilderTest extends DomBuilderTest { "</content>" + "</services>"; } + @Test - public void ensurePruneRemovedDocumentsAgeForHostedVespa() { + void ensurePruneRemovedDocumentsAgeForHostedVespa() { { ContentCluster contentNonHosted = createContent( "<content version='1.0' id='search'>" + - " <redundancy>1</redundancy>" + - " <documents>" + - " <document type='music' mode='index'/>" + - " </documents>" + - " <nodes>" + - " <node hostalias='mockhost' distribution-key='0'/>" + - " </nodes>" + - "</content>"); + " <redundancy>1</redundancy>" + + " <documents>" + + " <document type='music' mode='index'/>" + + " </documents>" + + " <nodes>" + + " <node hostalias='mockhost' distribution-key='0'/>" + + " </nodes>" + + "</content>"); ProtonConfig configNonHosted = getProtonConfig(contentNonHosted); ProtonConfig defaultConfig = new ProtonConfig(new ProtonConfig.Builder()); assertEquals(defaultConfig.pruneremoveddocumentsage(), configNonHosted.pruneremoveddocumentsage(), 0.001); @@ -768,9 +758,9 @@ public class ContentBuilderTest extends DomBuilderTest { DeployState.Builder deployStateBuilder = new DeployState.Builder().properties(new TestProperties().setHostedVespa(true)); VespaModel model = new VespaModelCreatorWithMockPkg(new MockApplicationPackage.Builder() - .withServices(hostedXml) - .withSearchDefinition(MockApplicationPackage.MUSIC_SCHEMA) - .build()) + .withServices(hostedXml) + .withSearchDefinition(MockApplicationPackage.MUSIC_SCHEMA) + .build()) .create(deployStateBuilder); ProtonConfig config = getProtonConfig(model.getContentClusters().values().iterator().next()); assertEquals(349260.0, config.pruneremoveddocumentsage(), 0.001); @@ -813,7 +803,7 @@ public class ContentBuilderTest extends DomBuilderTest { } @Test - public void ensureFeedSequencerIsControlledByFlag() { + void ensureFeedSequencerIsControlledByFlag() { verifyFeedSequencer("LATENCY", "LATENCY"); verifyFeedSequencer("ADAPTIVE", "ADAPTIVE"); verifyFeedSequencer("THROUGHPUT", "THROUGHPUT", 0); @@ -831,26 +821,27 @@ public class ContentBuilderTest extends DomBuilderTest { } @Test - public void verifyThatFeatureFlagControlsVisibilityDelayDefault() { + void verifyThatFeatureFlagControlsVisibilityDelayDefault() { verifyThatFeatureFlagControlsVisibilityDelayDefault(null, 0.0); verifyThatFeatureFlagControlsVisibilityDelayDefault(0.5, 0.5); verifyThatFeatureFlagControlsVisibilityDelayDefault(0.6, 0.6); } @Test - public void failWhenNoDocumentsElementSpecified() { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("The specified content engine requires the <documents> element to be specified."); - createContent( - "<content version =\"1.0\" id=\"a\">" + - " <redundancy>3</redundancy>" + - " <engine>" + - " <dummy/>" + - " </engine>" + - " <group>" + - " <node hostalias=\"mockhost\" distribution-key=\"0\"/>" + - " </group>" + - "</content>"); + void failWhenNoDocumentsElementSpecified() { + Throwable exception = assertThrows(IllegalArgumentException.class, () -> { + createContent( + "<content version =\"1.0\" id=\"a\">" + + " <redundancy>3</redundancy>" + + " <engine>" + + " <dummy/>" + + " </engine>" + + " <group>" + + " <node hostalias=\"mockhost\" distribution-key=\"0\"/>" + + " </group>" + + "</content>"); + }); + assertTrue(exception.getMessage().contains("The specified content engine requires the <documents> element to be specified.")); } private ProtonConfig getProtonConfig(ContentCluster content) { diff --git a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomAdminV2BuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomAdminV2BuilderTest.java index 072f88602a6..8a2a23a795d 100755 --- a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomAdminV2BuilderTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomAdminV2BuilderTest.java @@ -13,16 +13,14 @@ import com.yahoo.vespa.model.admin.Admin; import com.yahoo.vespa.model.admin.Configserver; import com.yahoo.vespa.model.admin.Slobrok; import com.yahoo.vespa.model.admin.monitoring.Monitoring; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.w3c.dom.Element; import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.*; /** * @author hmusum @@ -31,7 +29,7 @@ public class DomAdminV2BuilderTest extends DomBuilderTest { private static MockRoot root; - @Before + @BeforeEach public void prepareTest() { root = new MockRoot("root"); } @@ -104,7 +102,7 @@ public class DomAdminV2BuilderTest extends DomBuilderTest { } @Test - public void multitenant() { + void multitenant() { List<ConfigServerSpec> configServerSpecs = Arrays.asList( new TestProperties.Spec("test1", 19070, 2181), new TestProperties.Spec("test2", 19070, 2181), @@ -124,13 +122,13 @@ public class DomAdminV2BuilderTest extends DomBuilderTest { * Tests that configservers/configserver works */ @Test - public void adminWithConfigserversElement() { + void adminWithConfigserversElement() { Admin admin = buildAdmin(servicesConfigservers()); assertEquals(1, admin.getConfigservers().size()); } @Test - public void basicYamasNoXml() { + void basicYamasNoXml() { Admin admin = buildAdmin(servicesNoYamas()); Monitoring y = admin.getMonitoring(); assertEquals("vespa", y.getClustername()); @@ -138,13 +136,13 @@ public class DomAdminV2BuilderTest extends DomBuilderTest { } @Test - public void testAdminServerOnly() { + void testAdminServerOnly() { Admin admin = buildAdmin(servicesAdminServerOnly()); assertEquals(1, admin.getSlobroks().size()); } @Test - public void basicYamasXml() { + void basicYamasXml() { Admin admin = buildAdmin(servicesYamas()); Monitoring y = admin.getMonitoring(); assertEquals("foo", y.getClustername()); @@ -152,7 +150,7 @@ public class DomAdminV2BuilderTest extends DomBuilderTest { } @Test - public void yamasWithIntervalOverride() { + void yamasWithIntervalOverride() { Admin admin = buildAdmin(servicesYamasIntervalOverride()); Monitoring y = admin.getMonitoring(); assertEquals("foo", y.getClustername()); @@ -162,18 +160,20 @@ public class DomAdminV2BuilderTest extends DomBuilderTest { /** * Test that illegal yamas interval throws exception */ - @Test(expected = IllegalArgumentException.class) - public void yamasElementInvalid() { - Element servicesYamasIllegalInterval = XML.getDocument( - "<admin version=\"2.0\">" + - " <adminserver hostalias=\"mockhost\"/>" + - " <monitoring interval=\"5\"/>" + - "</admin>").getDocumentElement(); - Admin admin = buildAdmin(servicesYamasIllegalInterval); + @Test + void yamasElementInvalid() { + assertThrows(IllegalArgumentException.class, () -> { + Element servicesYamasIllegalInterval = XML.getDocument( + "<admin version=\"2.0\">" + + " <adminserver hostalias=\"mockhost\"/>" + + " <monitoring interval=\"5\"/>" + + "</admin>").getDocumentElement(); + Admin admin = buildAdmin(servicesYamasIllegalInterval); + }); } @Test - public void configOverridesCanBeUsedInAdmin() { + void configOverridesCanBeUsedInAdmin() { Admin admin = buildAdmin(servicesOverride()); assertEquals(1, admin.getUserConfigs().size()); LogdConfig.Builder logdBuilder = new LogdConfig.Builder(); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomComponentBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomComponentBuilderTest.java index 307cbf292db..ed3073a0ef4 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomComponentBuilderTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomComponentBuilderTest.java @@ -5,11 +5,11 @@ import com.yahoo.component.ComponentId; import com.yahoo.config.model.builder.xml.test.DomBuilderTest; import com.yahoo.container.bundle.BundleInstantiationSpecification; import com.yahoo.vespa.model.container.component.Component; -import org.junit.Test; +import org.junit.jupiter.api.Test; import static com.yahoo.collections.CollectionUtil.first; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author gjoranv @@ -17,7 +17,7 @@ import static org.junit.Assert.assertNotNull; public class DomComponentBuilderTest extends DomBuilderTest { @Test - public void ensureCorrectModel() { + void ensureCorrectModel() { Component<?, ?> handler = new DomComponentBuilder().doBuild(root.getDeployState(), root, parse( "<handler id='theId' class='theClass' bundle='theBundle' />")); @@ -29,7 +29,7 @@ public class DomComponentBuilderTest extends DomBuilderTest { @Test @SuppressWarnings("unchecked") - public void components_can_be_nested() { + void components_can_be_nested() { Component<Component<?, ?>, ?> parent = new DomComponentBuilder().doBuild(root.getDeployState(), root, parse( "<component id='parent'>", " <component id='child' />", diff --git a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomConfigPayloadBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomConfigPayloadBuilderTest.java index c0db0ac9e09..88af584de90 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomConfigPayloadBuilderTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomConfigPayloadBuilderTest.java @@ -10,7 +10,7 @@ import com.yahoo.vespa.config.ConfigDefinitionBuilder; import com.yahoo.vespa.config.ConfigDefinitionKey; import com.yahoo.vespa.config.ConfigPayload; import com.yahoo.vespa.config.ConfigPayloadBuilder; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.w3c.dom.Document; import org.w3c.dom.Element; import java.io.ByteArrayOutputStream; @@ -19,8 +19,7 @@ import java.io.FileReader; import java.io.Reader; import java.io.StringReader; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; /** * Tests for the {@link com.yahoo.vespa.model.builder.xml.dom.DomConfigPayloadBuilder} class. @@ -31,7 +30,7 @@ import static org.junit.Assert.fail; public class DomConfigPayloadBuilderTest { @Test - public void testFunctionTest_DefaultValues() throws FileNotFoundException { + void testFunctionTest_DefaultValues() throws FileNotFoundException { Element configRoot = getDocument(new FileReader("src/test/cfg/admin/userconfigs/functiontest-defaultvalues.xml")); String expected = "" + "{" @@ -57,13 +56,13 @@ public class DomConfigPayloadBuilderTest { // Multi line strings are not tested in 'DefaultValues', so here it is. @Test - public void verifyThatWhitespaceIsPreservedForStrings() throws Exception { + void verifyThatWhitespaceIsPreservedForStrings() throws Exception { Element configRoot = getDocument(new FileReader("src/test/cfg/admin/userconfigs/whitespace-test.xml")); assertPayload("{\"stringVal\":\" This is a string\\n that contains different kinds of whitespace \"}", configRoot); } @Test - public void put_to_leaf_map() { + void put_to_leaf_map() { Reader xmlConfig = new StringReader("<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + "<config name=\"test.foobar\">" + " <intmap>" + @@ -75,7 +74,7 @@ public class DomConfigPayloadBuilderTest { } @Test - public void put_to_inner_map() { + void put_to_inner_map() { Reader xmlConfig = new StringReader("<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + "<config name=\"test.foobar\">" + " <innermap>" + @@ -91,7 +90,7 @@ public class DomConfigPayloadBuilderTest { } @Test - public void put_to_nested_map() { + void put_to_nested_map() { Reader xmlConfig = new StringReader("<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + "<config name=\"test.foobar\">" + " <nestedmap>" + @@ -115,7 +114,7 @@ public class DomConfigPayloadBuilderTest { } @Test - public void camel_case_via_dashes() { + void camel_case_via_dashes() { Reader xmlConfig = new StringReader("<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + "<config name=\"test.function-test\">" + " <some-struct> <any-value>17</any-value> </some-struct>" + @@ -125,7 +124,7 @@ public class DomConfigPayloadBuilderTest { // Verifies that an exception is thrown when the root element is not 'config'. @Test - public void testFailWrongTagName() { + void testFailWrongTagName() { Element configRoot = getDocument(new StringReader("<configs name=\"foo\"/>")); try { new DomConfigPayloadBuilder(null).build(configRoot); @@ -137,7 +136,7 @@ public class DomConfigPayloadBuilderTest { // Verifies that an exception is thrown when the root element is not 'config'. @Test - public void testFailNoNameAttribute() { + void testFailNoNameAttribute() { Element configRoot = getDocument(new StringReader("<config/>")); try { new DomConfigPayloadBuilder(null).build(configRoot); @@ -148,7 +147,7 @@ public class DomConfigPayloadBuilderTest { } @Test - public void testNameParsing() { + void testNameParsing() { Element configRoot = getDocument(new StringReader("<config name=\"test.function-test\" version=\"1\">" + "<int_val>1</int_val> +" + "</config>")); @@ -157,38 +156,42 @@ public class DomConfigPayloadBuilderTest { assertEquals("test", key.getNamespace()); } - @Test(expected = ConfigurationRuntimeException.class) - public void testNameParsingInvalidName() { - Element configRoot = getDocument(new StringReader("<config name=\" function-test\" version=\"1\">" + - "<int_val>1</int_val> +" + - "</config>")); - DomConfigPayloadBuilder.parseConfigName(configRoot); + @Test + void testNameParsingInvalidName() { + assertThrows(ConfigurationRuntimeException.class, () -> { + Element configRoot = getDocument(new StringReader("<config name=\" function-test\" version=\"1\">" + + "<int_val>1</int_val> +" + + "</config>")); + DomConfigPayloadBuilder.parseConfigName(configRoot); + }); } - @Test(expected = ConfigurationRuntimeException.class) - public void testNameParsingInvalidNamespace() { - Element configRoot = getDocument(new StringReader("<config name=\"_foo.function-test\" version=\"1\">" + - "<int_val>1</int_val> +" + - "</config>")); - DomConfigPayloadBuilder.parseConfigName(configRoot); + @Test + void testNameParsingInvalidNamespace() { + assertThrows(ConfigurationRuntimeException.class, () -> { + Element configRoot = getDocument(new StringReader("<config name=\"_foo.function-test\" version=\"1\">" + + "<int_val>1</int_val> +" + + "</config>")); + DomConfigPayloadBuilder.parseConfigName(configRoot); + }); } @Test - public void require_that_item_syntax_works_with_leaf() { + void require_that_item_syntax_works_with_leaf() { Element configRoot = getDocument( "<config name=\"test.arraytypes\" version=\"1\">" + - " <intarr>" + - " <item>13</item>" + - " <item>10</item>" + - " <item>1337</item>" + - " </intarr>" + - "</config>"); + " <intarr>" + + " <item>13</item>" + + " <item>10</item>" + + " <item>1337</item>" + + " </intarr>" + + "</config>"); assertPayload("{\"intarr\":[\"13\",\"10\",\"1337\"]}", configRoot); } @Test - public void require_that_item_syntax_works_with_struct() { + void require_that_item_syntax_works_with_struct() { Element configRoot = getDocument( "<config name=\"test.arraytypes\" version=\"1\">" + " <lolarray>" + @@ -199,42 +202,46 @@ public class DomConfigPayloadBuilderTest { "</config>"); assertPayload("{\"lolarray\":[{\"foo\":\"hei\",\"bar\":\"hei2\"},{\"foo\":\"hoo\",\"bar\":\"hoo2\"},{\"foo\":\"happ\",\"bar\":\"happ2\"}]}", - configRoot); + configRoot); } @Test - public void require_that_item_syntax_works_with_struct_array() { + void require_that_item_syntax_works_with_struct_array() { Element configRoot = getDocument( "<config name=\"test.arraytypes\" version=\"1\">" + - " <lolarray>" + - " <item><fooarray><item>13</item></fooarray></item>" + - " <item><fooarray><item>10</item></fooarray></item>" + - " <item><fooarray><item>1337</item></fooarray></item>" + - " </lolarray>" + - "</config>"); + " <lolarray>" + + " <item><fooarray><item>13</item></fooarray></item>" + + " <item><fooarray><item>10</item></fooarray></item>" + + " <item><fooarray><item>1337</item></fooarray></item>" + + " </lolarray>" + + "</config>"); assertPayload("{\"lolarray\":[{\"fooarray\":[\"13\"]},{\"fooarray\":[\"10\"]},{\"fooarray\":[\"1337\"]}]}", configRoot); } - @Test(expected = ConfigurationRuntimeException.class) - public void require_that_item_is_reserved_in_root() { - Element configRoot = getDocument( - "<config name=\"test.arraytypes\" version=\"1\">" + - " <item>13</item>" + - "</config>"); - new DomConfigPayloadBuilder(null).build(configRoot); + @Test + void require_that_item_is_reserved_in_root() { + assertThrows(ConfigurationRuntimeException.class, () -> { + Element configRoot = getDocument( + "<config name=\"test.arraytypes\" version=\"1\">" + + " <item>13</item>" + + "</config>"); + new DomConfigPayloadBuilder(null).build(configRoot); + }); } - @Test(expected=ConfigurationRuntimeException.class) - public void require_that_exceptions_are_issued() throws FileNotFoundException { - Element configRoot = getDocument( - "<config name=\"test.simpletypes\">" + - "<longval>invalid</longval>" + - "</config>"); - DefParser defParser = new DefParser("simpletypes", - new FileReader("src/test/resources/configdefinitions/test.simpletypes.def")); - ConfigDefinition def = ConfigDefinitionBuilder.createConfigDefinition(defParser.getTree()); - ConfigPayloadBuilder unused = new DomConfigPayloadBuilder(def).build(configRoot); + @Test + void require_that_exceptions_are_issued() throws FileNotFoundException { + assertThrows(ConfigurationRuntimeException.class, () -> { + Element configRoot = getDocument( + "<config name=\"test.simpletypes\">" + + "<longval>invalid</longval>" + + "</config>"); + DefParser defParser = new DefParser("simpletypes", + new FileReader("src/test/resources/configdefinitions/test.simpletypes.def")); + ConfigDefinition def = ConfigDefinitionBuilder.createConfigDefinition(defParser.getTree()); + ConfigPayloadBuilder unused = new DomConfigPayloadBuilder(def).build(configRoot); + }); } private void assertPayload(String expected, Element configRoot) { diff --git a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomSchemaTuningBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomSchemaTuningBuilderTest.java index 4ed355a7dca..41cef783b68 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomSchemaTuningBuilderTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomSchemaTuningBuilderTest.java @@ -5,15 +5,12 @@ import com.yahoo.collections.CollectionUtil; import com.yahoo.vespa.config.search.core.ProtonConfig; import com.yahoo.config.model.builder.xml.test.DomBuilderTest; import com.yahoo.vespa.model.search.Tuning; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.w3c.dom.Element; import java.util.Arrays; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * @author geirst @@ -46,7 +43,7 @@ public class DomSchemaTuningBuilderTest extends DomBuilderTest { } @Test - public void requireThatWeCanParseRequestThreadsTag() { + void requireThatWeCanParseRequestThreadsTag() { Tuning t = createTuning(parseXml("<requestthreads>", "<search>123</search>", "<persearch>34</persearch>", @@ -58,11 +55,11 @@ public class DomSchemaTuningBuilderTest extends DomBuilderTest { assertEquals(cfg.numsearcherthreads(), 123); assertEquals(cfg.numthreadspersearch(), 34); assertEquals(cfg.numsummarythreads(), 456); - } + } @Test - public void requireThatWeCanParseFlushStrategyTag() { - Tuning t = createTuning(parseXml("<flushstrategy>","<native>", + void requireThatWeCanParseFlushStrategyTag() { + Tuning t = createTuning(parseXml("<flushstrategy>", "<native>", "<total>", "<maxmemorygain>900</maxmemorygain>", "<diskbloatfactor>8.7</diskbloatfactor>", @@ -79,7 +76,7 @@ public class DomSchemaTuningBuilderTest extends DomBuilderTest { "<memory-limit-factor>0.6</memory-limit-factor>", "<disk-limit-factor>0.7</disk-limit-factor>", "</conservative>", - "</native>","</flushstrategy>")); + "</native>", "</flushstrategy>")); assertEquals(900, t.searchNode.strategy.totalMaxMemoryGain.longValue()); assertEquals(8.7, t.searchNode.strategy.totalDiskBloatFactor, DELTA); assertEquals(600, t.searchNode.strategy.componentMaxMemoryGain.longValue()); @@ -100,7 +97,7 @@ public class DomSchemaTuningBuilderTest extends DomBuilderTest { } @Test - public void requireThatWeCanParseResizingTag() { + void requireThatWeCanParseResizingTag() { Tuning t = createTuning(parseXml("<resizing>", "<initialdocumentcount>128</initialdocumentcount>", "<amortize-count>13</amortize-count>", @@ -110,14 +107,14 @@ public class DomSchemaTuningBuilderTest extends DomBuilderTest { } @Test - public void requireThatWeCanParseIndexTag() { + void requireThatWeCanParseIndexTag() { Tuning t = createTuning(parseXml("<index>", "<io>", "<write>directio</write>", "<read>normal</read>", "<search>mmap</search>", "</io>", "<warmup>" + - "<time>178</time>", + "<time>178</time>", "<unpack>true</unpack>", "</warmup>", "</index>")); @@ -134,7 +131,7 @@ public class DomSchemaTuningBuilderTest extends DomBuilderTest { } @Test - public void requireThatWeCanPopulateIndex() { + void requireThatWeCanPopulateIndex() { Tuning t = createTuning(parseXml("<index>", "<io>", "<search>populate</search>", "</io>", @@ -150,7 +147,7 @@ public class DomSchemaTuningBuilderTest extends DomBuilderTest { @Test - public void requireThatWeCanParseRemovedDBTag() { + void requireThatWeCanParseRemovedDBTag() { Tuning t = createTuning(parseXml("<removed-db>", "<prune>", "<age>19388</age>", "<interval>193</interval>", @@ -163,7 +160,7 @@ public class DomSchemaTuningBuilderTest extends DomBuilderTest { } @Test - public void requireThatWeCanParseAttributeTag() { + void requireThatWeCanParseAttributeTag() { Tuning t = createTuning(parseXml("<attribute>", "<io>", "<write>directio</write>", "</io>", "</attribute>")); @@ -173,7 +170,7 @@ public class DomSchemaTuningBuilderTest extends DomBuilderTest { } @Test - public void requireThatWeCanParseSummaryTag() { + void requireThatWeCanParseSummaryTag() { Tuning t = createTuning(parseXml("<summary>", "<io>", "<write>directio</write>", @@ -232,7 +229,7 @@ public class DomSchemaTuningBuilderTest extends DomBuilderTest { } @Test - public void requireThatWeCanGiveSummaryCacheSizeInPercentage() { + void requireThatWeCanGiveSummaryCacheSizeInPercentage() { Tuning t = createTuning(parseXml("<summary>", "<store>", "<cache>", @@ -242,14 +239,14 @@ public class DomSchemaTuningBuilderTest extends DomBuilderTest { "</summary>")); assertNull(t.searchNode.summary.store.cache.maxSize); - assertEquals(30.7, t.searchNode.summary.store.cache.maxSizePercent,DELTA); + assertEquals(30.7, t.searchNode.summary.store.cache.maxSizePercent, DELTA); ProtonConfig cfg = getProtonCfg(t); assertEquals(cfg.summary().cache().maxbytes(), -30); } @Test - public void requireThatWeCanPopulateSummary() { + void requireThatWeCanPopulateSummary() { Tuning t = createTuning(parseXml("<summary>", "<io>", "<read>populate</read>", @@ -265,7 +262,7 @@ public class DomSchemaTuningBuilderTest extends DomBuilderTest { @Test - public void requireThatWeCanParseInitializeTag() { + void requireThatWeCanParseInitializeTag() { Tuning t = createTuning(parseXml("<initialize>", "<threads>7</threads>", "</initialize>")); @@ -275,7 +272,7 @@ public class DomSchemaTuningBuilderTest extends DomBuilderTest { } @Test - public void requireThatWeCanParseFeedingTag() { + void requireThatWeCanParseFeedingTag() { Tuning t = createTuning(parseXml("<feeding>", "<concurrency>0.7</concurrency>", "</feeding>")); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/LegacyConfigModelBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/LegacyConfigModelBuilderTest.java index 2bcb1a7459b..1f9cddef028 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/LegacyConfigModelBuilderTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/LegacyConfigModelBuilderTest.java @@ -8,14 +8,13 @@ import com.yahoo.config.model.deploy.DeployState; import com.yahoo.config.model.test.MockApplicationPackage; import com.yahoo.config.model.test.MockRoot; import com.yahoo.text.XML; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.w3c.dom.Element; import java.util.List; import static org.hamcrest.CoreMatchers.is; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThat; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Ulf Lilleengen @@ -23,11 +22,11 @@ import static org.junit.Assert.assertThat; public class LegacyConfigModelBuilderTest { @Test - public void testThatProducerIsInserted() { + void testThatProducerIsInserted() { String services = "<foo><config name=\"bar.foo\"><key>value</key></config></foo>"; ModelBuilder builder = new ModelBuilder(); Model model = builder.build(DeployState.createTestState(new MockApplicationPackage.Builder().withServices(services).build()), - null, null, new MockRoot(), XML.getDocument(services).getDocumentElement()); + null, null, new MockRoot(), XML.getDocument(services).getDocumentElement()); assertEquals(1, model.getContext().getParentProducer().getUserConfigs().size()); } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/VespaDomBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/VespaDomBuilderTest.java index 1a5a7bbe544..a46fafe30c4 100755 --- a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/VespaDomBuilderTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/VespaDomBuilderTest.java @@ -10,13 +10,13 @@ import com.yahoo.vespa.model.HostResource; import com.yahoo.vespa.model.HostSystem; import com.yahoo.vespa.model.VespaModel; import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithMockPkg; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.w3c.dom.Element; import java.io.StringReader; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author gjoranv @@ -68,21 +68,21 @@ public class VespaDomBuilderTest { @Test - public void testUserConfigsWithNamespace() { + void testUserConfigsWithNamespace() { VespaModel model = createModel(hosts, servicesWithNamespace); - GenericConfig.GenericConfigBuilder builder = + GenericConfig.GenericConfigBuilder builder = new GenericConfig.GenericConfigBuilder(new ConfigDefinitionKey("testnamespace", "foo"), new ConfigPayloadBuilder()); model.getConfig(builder, "admin"); assertEquals("{\n" + - " \"basicStruct\": {\n" + - " \"stringVal\": \"default\"\n" + - " }\n" + - "}\n", builder.getPayload().toString()); + " \"basicStruct\": {\n" + + " \"stringVal\": \"default\"\n" + + " }\n" + + "}\n", builder.getPayload().toString()); } @Test - public void testGetElement() { + void testGetElement() { Element e = Xml.getElement(new StringReader("<chain><foo>sdf</foo></chain>")); assertEquals(e.getTagName(), "chain"); assertEquals(XML.getChild(e, "foo").getTagName(), "foo"); @@ -90,7 +90,7 @@ public class VespaDomBuilderTest { } @Test - public void testHostSystem() { + void testHostSystem() { VespaModel model = createModel(hosts, services); HostSystem hostSystem = model.hostSystem(); assertEquals(1, hostSystem.getHosts().size()); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/DependenciesBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/DependenciesBuilderTest.java index bc0df8196b8..7e87ebf782e 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/DependenciesBuilderTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/DependenciesBuilderTest.java @@ -3,12 +3,12 @@ package com.yahoo.vespa.model.builder.xml.dom.chains; import com.yahoo.component.chain.dependencies.Dependencies; import com.yahoo.config.model.builder.xml.test.DomBuilderTest; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.HashSet; import java.util.Set; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Basic tests of DependencyBuilder @@ -24,7 +24,7 @@ public class DependenciesBuilderTest extends DomBuilderTest { } @Test - public void testBuildDependencies() { + void testBuildDependencies() { DependenciesBuilder dependenciesBuilder = new DependenciesBuilder(parse( "<searcher provides='symbol1 symbol2 ' before='p1' after=' s1' >", " <provides> symbol3 </provides>", diff --git a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomFederationSearcherBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomFederationSearcherBuilderTest.java index d68f306c043..38488947db8 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomFederationSearcherBuilderTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomFederationSearcherBuilderTest.java @@ -6,14 +6,12 @@ import com.yahoo.config.model.producer.AbstractConfigProducer; import com.yahoo.search.federation.FederationConfig; import com.yahoo.search.searchchain.model.federation.FederationSearcherModel; import com.yahoo.vespa.model.container.search.searchchain.FederationSearcher; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * Test of DomFederationSearcherBuilder. @@ -23,7 +21,7 @@ import static org.junit.Assert.assertTrue; public class DomFederationSearcherBuilderTest extends DomBuilderTest { @Test - public void ensureCorrectModel() { + void ensureCorrectModel() { FederationSearcher searcher = new DomFederationSearcherBuilder().doBuild(root.getDeployState(), root, parse( "<federation id='theId'>", " <provides>p2</provides>", @@ -41,7 +39,7 @@ public class DomFederationSearcherBuilderTest extends DomBuilderTest { model.bundleInstantiationSpec.classId.stringValue()); assertEquals(2, model.targets.size()); - assertTrue("source-set option was ignored", model.inheritDefaultSources); + assertTrue(model.inheritDefaultSources, "source-set option was ignored"); assertTrue(targetNames(model.targets).containsAll(List.of("source1", "source2"))); } @@ -55,7 +53,7 @@ public class DomFederationSearcherBuilderTest extends DomBuilderTest { } @Test - public void require_that_target_selector_can_be_configured() { + void require_that_target_selector_can_be_configured() { FederationSearcher searcher = new DomFederationSearcherBuilder().doBuild(root.getDeployState(), root, parse( "<federation id='federation-id'>", " <target-selector id='my-id' class='my-class' />", @@ -64,7 +62,7 @@ public class DomFederationSearcherBuilderTest extends DomBuilderTest { String targetSelectorId = "my-id@federation-id"; AbstractConfigProducer<?> targetSelector = searcher.getChildren().get(targetSelectorId); - assertNotNull("No target selector child found", targetSelector); + assertNotNull(targetSelector, "No target selector child found"); FederationConfig.Builder builder = new FederationConfig.Builder(); searcher.getConfig(builder); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomSchemaChainsBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomSchemaChainsBuilderTest.java index 9fb7b58a43c..d470f184340 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomSchemaChainsBuilderTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomSchemaChainsBuilderTest.java @@ -16,8 +16,8 @@ import com.yahoo.vespa.model.container.search.searchchain.Source; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.hamcrest.Matcher; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.w3c.dom.Element; import java.util.Arrays; @@ -28,10 +28,7 @@ import static com.yahoo.container.core.ChainsConfig.Chains; import static com.yahoo.container.core.ChainsConfig.Components; import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; /** * Test of Search chains builder. @@ -70,13 +67,13 @@ public class DomSchemaChainsBuilderTest extends DomBuilderTest { "</search>"); - @Before + @BeforeEach public void createSearchChains() { searchChains = new DomSearchChainsBuilder().build(root.getDeployState(), root, element); } @Test - public void referToFederationAsSearcher() { + void referToFederationAsSearcher() { final Element element = parse( "<search>", " <federation id='federationSearcher'>", @@ -100,14 +97,14 @@ public class DomSchemaChainsBuilderTest extends DomBuilderTest { } @Test - public void ensureSearchChainsExists() { + void ensureSearchChainsExists() { for (String id : Arrays.asList("provider:1", "source:1@provider:1", "default")) { - assertNotNull("Missing search chain " + id, getSearchChain(id)); + assertNotNull(getSearchChain(id), "Missing search chain " + id); } } @Test - public void ensureSearcherExists() { + void ensureSearcherExists() { assertThat(searchChains.allComponents(), hasItem(searcherWithId("searcher:1"))); } @@ -127,7 +124,7 @@ public class DomSchemaChainsBuilderTest extends DomBuilderTest { } @Test - public void checkProviderFederationOptions() { + void checkProviderFederationOptions() { FederationOptions options = getProvider().federationOptions(); assertTrue(options.getOptional()); @@ -135,7 +132,7 @@ public class DomSchemaChainsBuilderTest extends DomBuilderTest { } @Test - public void checkSourceFederationOptions() { + void checkSourceFederationOptions() { FederationOptions options = getSource().federationOptions(); assertTrue(options.getOptional()); //inherited @@ -143,7 +140,7 @@ public class DomSchemaChainsBuilderTest extends DomBuilderTest { } @Test - public void checkDefaultTargets() { + void checkDefaultTargets() { Collection<? extends GenericTarget> defaultTargets = getProvider().defaultFederationTargets(); @@ -152,7 +149,7 @@ public class DomSchemaChainsBuilderTest extends DomBuilderTest { } @Test - public void checkInnerSearcherIdIsNestedInSearchChainId() { + void checkInnerSearcherIdIsNestedInSearchChainId() { ChainsConfig.Builder builder = new ChainsConfig.Builder(); searchChains.getConfig(builder); ChainsConfig config = new ChainsConfig(builder); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomSearcherBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomSearcherBuilderTest.java index af3b4027b1c..933f57c76cd 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomSearcherBuilderTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomSearcherBuilderTest.java @@ -5,9 +5,9 @@ import com.yahoo.component.chain.model.ChainedComponentModel; import com.yahoo.config.model.builder.xml.test.DomBuilderTest; import com.yahoo.container.bundle.BundleInstantiationSpecification; import com.yahoo.vespa.model.container.component.chain.ChainedComponent; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Tony Vaagenes @@ -15,7 +15,7 @@ import static org.junit.Assert.assertEquals; public class DomSearcherBuilderTest extends DomBuilderTest { @Test - public void ensureCorrectModel() { + void ensureCorrectModel() { ChainedComponent<ChainedComponentModel> searcher = new DomSearcherBuilder().doBuild(root.getDeployState(), root, parse( "<searcher id='theId' class='theclassid' bundle='thebundle' provides='p1'>", " <provides>p2</provides>", diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/ContainerClusterTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/ContainerClusterTest.java index 3ff88e22b5d..dbc7d475c27 100755 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/ContainerClusterTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/ContainerClusterTest.java @@ -30,7 +30,7 @@ import com.yahoo.vespa.model.container.component.Component; import com.yahoo.vespa.model.container.docproc.ContainerDocproc; import com.yahoo.vespa.model.container.search.ContainerSearch; import com.yahoo.vespa.model.container.search.searchchain.SearchChains; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.nio.file.Path; import java.nio.file.Paths; @@ -50,9 +50,7 @@ import static com.yahoo.config.model.api.ApplicationClusterEndpoint.Scope.applic import static com.yahoo.config.model.api.ApplicationClusterEndpoint.Scope.global; import static com.yahoo.config.provision.SystemName.cd; import static com.yahoo.config.provision.SystemName.main; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * @author Simon Thoresen Hult @@ -60,7 +58,7 @@ import static org.junit.Assert.assertTrue; public class ContainerClusterTest { @Test - public void requireThatClusterInfoIsPopulated() { + void requireThatClusterInfoIsPopulated() { ApplicationContainerCluster cluster = newContainerCluster(); ClusterInfoConfig config = getClusterInfoConfig(cluster); assertEquals("name", config.clusterId()); @@ -81,7 +79,7 @@ public class ContainerClusterTest { } @Test - public void search_and_docproc_bundles_are_not_installed_for_plain_application_clusters() { + void search_and_docproc_bundles_are_not_installed_for_plain_application_clusters() { ApplicationContainerCluster cluster = newContainerCluster(); var bundleBuilder = new PlatformBundlesConfig.Builder(); @@ -91,7 +89,7 @@ public class ContainerClusterTest { } @Test - public void search_and_docproc_bundles_are_installed_for_application_clusters_with_search() { + void search_and_docproc_bundles_are_installed_for_application_clusters_with_search() { ApplicationContainerCluster cluster = newClusterWithSearch(createRoot(false), false, null); var bundleBuilder = new PlatformBundlesConfig.Builder(); @@ -101,10 +99,10 @@ public class ContainerClusterTest { } @Test - public void requireThatWeCanGetTheZoneConfig() { + void requireThatWeCanGetTheZoneConfig() { DeployState state = new DeployState.Builder().properties(new TestProperties().setHostedVespa(true)) - .zone(new Zone(SystemName.cd, Environment.test, RegionName.from("some-region"))) - .build(); + .zone(new Zone(SystemName.cd, Environment.test, RegionName.from("some-region"))) + .build(); MockRoot root = new MockRoot("foo", state); ContainerCluster<?> cluster = new ApplicationContainerCluster(root, "container0", "container1", state); ConfigserverConfig.Builder builder = new ConfigserverConfig.Builder(); @@ -128,17 +126,17 @@ public class ContainerClusterTest { } @Test - public void requireThatHeapSizeAsPercentageOfPhysicalMemoryForHostedAndNot() { + void requireThatHeapSizeAsPercentageOfPhysicalMemoryForHostedAndNot() { boolean hosted = true; boolean combined = true; // a cluster running on content nodes (only relevant with hosted) - verifyHeapSizeAsPercentageOfPhysicalMemory( hosted, ! combined, null, 70); + verifyHeapSizeAsPercentageOfPhysicalMemory( hosted, !combined, null, 70); verifyHeapSizeAsPercentageOfPhysicalMemory( hosted, combined, null, 18); - verifyHeapSizeAsPercentageOfPhysicalMemory(! hosted, ! combined, null, 0); - + verifyHeapSizeAsPercentageOfPhysicalMemory(!hosted, !combined, null, 0); + // Explicit value overrides all defaults - verifyHeapSizeAsPercentageOfPhysicalMemory( hosted, ! combined, 67, 67); + verifyHeapSizeAsPercentageOfPhysicalMemory( hosted, !combined, 67, 67); verifyHeapSizeAsPercentageOfPhysicalMemory( hosted, combined, 68, 68); - verifyHeapSizeAsPercentageOfPhysicalMemory(! hosted, ! combined, 69, 69); + verifyHeapSizeAsPercentageOfPhysicalMemory(!hosted, !combined, 69, 69); } private void verifyJvmArgs(boolean isHosted, boolean hasDocproc, String expectedArgs, String jvmArgs) { @@ -174,7 +172,7 @@ public class ContainerClusterTest { } @Test - public void testClusterControllerResourceUsage() { + void testClusterControllerResourceUsage() { MockRoot root = createRoot(false); ClusterControllerContainerCluster cluster = createClusterControllerCluster(root); addClusterController(cluster, "host-c1", root.getDeployState()); @@ -194,7 +192,7 @@ public class ContainerClusterTest { } @Test - public void search_and_docproc_bundles_are_not_installed_for_cluster_controllers() { + void search_and_docproc_bundles_are_not_installed_for_cluster_controllers() { MockRoot root = createRoot(false); ClusterControllerContainerCluster cluster = createClusterControllerCluster(root); @@ -205,7 +203,7 @@ public class ContainerClusterTest { } @Test - public void testThatLinguisticsIsExcludedForClusterControllerCluster() { + void testThatLinguisticsIsExcludedForClusterControllerCluster() { MockRoot root = createRoot(false); ClusterControllerContainerCluster cluster = createClusterControllerCluster(root); addClusterController(cluster, "host-c1", root.getDeployState()); @@ -220,7 +218,7 @@ public class ContainerClusterTest { } @Test - public void requireThatJvmArgsControlWorksForHostedAndNot() { + void requireThatJvmArgsControlWorksForHostedAndNot() { verifyJvmArgs(true, false); verifyJvmArgs(true, true); verifyJvmArgs(false, false); @@ -228,7 +226,7 @@ public class ContainerClusterTest { } @Test - public void requireThatJvmOmitStackTraceInFastThrowOptionWorks() { + void requireThatJvmOmitStackTraceInFastThrowOptionWorks() { // Empty option if option not set in property MockRoot root = createRoot(new DeployState.Builder().build()); ApplicationContainerCluster cluster = newClusterWithSearch(root); @@ -246,7 +244,7 @@ public class ContainerClusterTest { } @Test - public void requireThatWeCanHandleNullJvmOptions() { + void requireThatWeCanHandleNullJvmOptions() { MockRoot root = createRoot(false); ApplicationContainerCluster cluster = newClusterWithSearch(root); addContainer(root, cluster, "c1", "host-c1"); @@ -258,7 +256,7 @@ public class ContainerClusterTest { } @Test - public void requireThatNonHostedUsesExpectedDefaultThreadpoolConfiguration() { + void requireThatNonHostedUsesExpectedDefaultThreadpoolConfiguration() { MockRoot root = new MockRoot("foo"); ApplicationContainerCluster cluster = newClusterWithSearch(root); addContainer(root, cluster, "c1", "host-c1"); @@ -270,7 +268,7 @@ public class ContainerClusterTest { } @Test - public void container_cluster_has_default_threadpool_provider() { + void container_cluster_has_default_threadpool_provider() { MockRoot root = new MockRoot("foo"); ApplicationContainerCluster cluster = newClusterWithSearch(root); addContainer(root, cluster, "c1", "host-c1"); @@ -284,7 +282,7 @@ public class ContainerClusterTest { } @Test - public void config_for_default_threadpool_provider_scales_with_node_resources_in_hosted() { + void config_for_default_threadpool_provider_scales_with_node_resources_in_hosted() { MockRoot root = new MockRoot( "foo", new DeployState.Builder() @@ -301,7 +299,7 @@ public class ContainerClusterTest { } @Test - public void jetty_threadpool_scales_with_node_resources_in_hosted() { + void jetty_threadpool_scales_with_node_resources_in_hosted() { MockRoot root = new MockRoot( "foo", new DeployState.Builder() @@ -318,22 +316,22 @@ public class ContainerClusterTest { } @Test - public void requireThatBundlesForTesterApplicationAreInstalled() { + void requireThatBundlesForTesterApplicationAreInstalled() { List<String> expectedOnpremBundles = List.of("vespa-testrunner-components-jar-with-dependencies.jar", "vespa-osgi-testrunner-jar-with-dependencies.jar", "tenant-cd-api-jar-with-dependencies.jar"); verifyTesterApplicationInstalledBundles(Zone.defaultZone(), expectedOnpremBundles); - + List<String> expectedPublicBundles = new ArrayList<>(expectedOnpremBundles); expectedPublicBundles.add("cloud-tenant-cd-jar-with-dependencies.jar"); Zone publicZone = new Zone(SystemName.PublicCd, Environment.dev, RegionName.defaultName()); verifyTesterApplicationInstalledBundles(publicZone, expectedPublicBundles); - + } @Test - public void requireCuratorConfig() { + void requireCuratorConfig() { DeployState state = new DeployState.Builder().build(); MockRoot root = new MockRoot("foo", state); var cluster = new ApplicationContainerCluster(root, "container", "search-cluster", state); @@ -343,12 +341,12 @@ public class ContainerClusterTest { cluster.getConfig(configBuilder); CuratorConfig config = configBuilder.build(); assertEquals(List.of("host-c1", "host-c2"), - config.server().stream().map(CuratorConfig.Server::hostname).collect(Collectors.toList())); + config.server().stream().map(CuratorConfig.Server::hostname).collect(Collectors.toList())); assertTrue(config.zookeeperLocalhostAffinity()); } @Test - public void requireZooKeeperServerConfig() { + void requireZooKeeperServerConfig() { DeployState state = new DeployState.Builder().build(); MockRoot root = new MockRoot("foo", state); var cluster = new ApplicationContainerCluster(root, "container", "search-cluster", state); @@ -365,67 +363,67 @@ public class ContainerClusterTest { cluster.getConfig(configBuilder); assertEquals(0, configBuilder.build().myid()); assertEquals(List.of("host-c1", "host-c2", "host-c3"), - configBuilder.build().server().stream().map(ZookeeperServerConfig.Server::hostname).collect(Collectors.toList())); + configBuilder.build().server().stream().map(ZookeeperServerConfig.Server::hostname).collect(Collectors.toList())); } @Test - public void generatesCorrectRoutingInfo() { + void generatesCorrectRoutingInfo() { // main system: assertNames(main, - ApplicationId.from("t1", "a1", "i1"), - Set.of(), - List.of("search-cluster.i1.a1.t1.endpoint.suffix")); + ApplicationId.from("t1", "a1", "i1"), + Set.of(), + List.of("search-cluster.i1.a1.t1.endpoint.suffix")); assertNames(main, - ApplicationId.from("t1", "a1", "default"), - Set.of(), - List.of("search-cluster.a1.t1.endpoint.suffix")); + ApplicationId.from("t1", "a1", "default"), + Set.of(), + List.of("search-cluster.a1.t1.endpoint.suffix")); assertNames(main, - ApplicationId.from("t1", "default", "default"), - Set.of(), - List.of("search-cluster.default.t1.endpoint.suffix")); + ApplicationId.from("t1", "default", "default"), + Set.of(), + List.of("search-cluster.default.t1.endpoint.suffix")); assertNames(main, - ApplicationId.from("t1", "a1", "default"), - Set.of(new ContainerEndpoint("not-in-this-cluster", global, List.of("foo", "bar"))), - List.of("search-cluster.a1.t1.endpoint.suffix")); + ApplicationId.from("t1", "a1", "default"), + Set.of(new ContainerEndpoint("not-in-this-cluster", global, List.of("foo", "bar"))), + List.of("search-cluster.a1.t1.endpoint.suffix")); assertNames(main, - ApplicationId.from("t1", "a1", "default"), - Set.of(new ContainerEndpoint("search-cluster", global, List.of("rotation-1.x.y.z", "rotation-2.x.y.z"), OptionalInt.empty(), sharedLayer4), - new ContainerEndpoint("search-cluster", application, List.of("app-rotation.x.y.z"), OptionalInt.of(3), sharedLayer4)), - List.of("search-cluster.a1.t1.endpoint.suffix", "rotation-1.x.y.z", "rotation-2.x.y.z", "app-rotation.x.y.z")); + ApplicationId.from("t1", "a1", "default"), + Set.of(new ContainerEndpoint("search-cluster", global, List.of("rotation-1.x.y.z", "rotation-2.x.y.z"), OptionalInt.empty(), sharedLayer4), + new ContainerEndpoint("search-cluster", application, List.of("app-rotation.x.y.z"), OptionalInt.of(3), sharedLayer4)), + List.of("search-cluster.a1.t1.endpoint.suffix", "rotation-1.x.y.z", "rotation-2.x.y.z", "app-rotation.x.y.z")); // cd system: assertNames(cd, - ApplicationId.from("t1", "a1", "i1"), - Set.of(), - List.of("search-cluster.cd.i1.a1.t1.endpoint.suffix")); + ApplicationId.from("t1", "a1", "i1"), + Set.of(), + List.of("search-cluster.cd.i1.a1.t1.endpoint.suffix")); assertNames(cd, - ApplicationId.from("t1", "a1", "default"), - Set.of(), - List.of("search-cluster.cd.a1.t1.endpoint.suffix")); + ApplicationId.from("t1", "a1", "default"), + Set.of(), + List.of("search-cluster.cd.a1.t1.endpoint.suffix")); assertNames(cd, - ApplicationId.from("t1", "default", "default"), - Set.of(), - List.of("search-cluster.cd.default.t1.endpoint.suffix")); + ApplicationId.from("t1", "default", "default"), + Set.of(), + List.of("search-cluster.cd.default.t1.endpoint.suffix")); assertNames(cd, - ApplicationId.from("t1", "a1", "default"), - Set.of(new ContainerEndpoint("not-in-this-cluster", global, List.of("foo", "bar"))), - List.of("search-cluster.cd.a1.t1.endpoint.suffix")); + ApplicationId.from("t1", "a1", "default"), + Set.of(new ContainerEndpoint("not-in-this-cluster", global, List.of("foo", "bar"))), + List.of("search-cluster.cd.a1.t1.endpoint.suffix")); assertNames(cd, - ApplicationId.from("t1", "a1", "default"), - Set.of(new ContainerEndpoint("search-cluster", global, List.of("rotation-1.x.y.z", "rotation-2.x.y.z"), OptionalInt.empty(), sharedLayer4), - new ContainerEndpoint("search-cluster", global, List.of("a.b.x.y.z", "rotation-2.x.y.z"), OptionalInt.empty(), shared), - new ContainerEndpoint("search-cluster", application, List.of("app-rotation.x.y.z"), OptionalInt.of(3), sharedLayer4), - new ContainerEndpoint("not-supported", global, List.of("not.supported"), OptionalInt.empty(), exclusive)), - List.of("search-cluster.cd.a1.t1.endpoint.suffix", "rotation-1.x.y.z", "rotation-2.x.y.z", "app-rotation.x.y.z")); + ApplicationId.from("t1", "a1", "default"), + Set.of(new ContainerEndpoint("search-cluster", global, List.of("rotation-1.x.y.z", "rotation-2.x.y.z"), OptionalInt.empty(), sharedLayer4), + new ContainerEndpoint("search-cluster", global, List.of("a.b.x.y.z", "rotation-2.x.y.z"), OptionalInt.empty(), shared), + new ContainerEndpoint("search-cluster", application, List.of("app-rotation.x.y.z"), OptionalInt.of(3), sharedLayer4), + new ContainerEndpoint("not-supported", global, List.of("not.supported"), OptionalInt.empty(), exclusive)), + List.of("search-cluster.cd.a1.t1.endpoint.suffix", "rotation-1.x.y.z", "rotation-2.x.y.z", "app-rotation.x.y.z")); } @@ -457,7 +455,7 @@ public class ContainerClusterTest { private void assertNames(List<String> expectedNames, List<ApplicationClusterEndpoint> endpoints) { assertEquals(expectedNames.size(), endpoints.size()); - expectedNames.forEach(expected -> assertTrue("Endpoint not matched " + expected + " was: " + endpoints, endpoints.stream().anyMatch(e -> Objects.equals(e.dnsName().value(), expected)))); + expectedNames.forEach(expected -> assertTrue(endpoints.stream().anyMatch(e -> Objects.equals(e.dnsName().value(), expected)), "Endpoint not matched " + expected + " was: " + endpoints)); } private boolean endpointsMatch(ContainerEndpoint configuredEndpoint, List<ApplicationClusterEndpoint> clusterEndpoints) { diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/ContainerIncludeTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/ContainerIncludeTest.java index cb1b84d272a..51c0dd5f898 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/ContainerIncludeTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/ContainerIncludeTest.java @@ -6,15 +6,12 @@ import com.yahoo.vespa.model.container.docproc.DocprocChain; import com.yahoo.vespa.model.container.processing.ProcessingChain; import com.yahoo.vespa.model.container.search.searchchain.SearchChain; import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithFilePkg; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.Map; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; /** * @author Einar M R Rosenvinge @@ -23,7 +20,7 @@ import static org.junit.Assert.fail; public class ContainerIncludeTest { @Test - public void include() { + void include() { VespaModelCreatorWithFilePkg creator = new VespaModelCreatorWithFilePkg("src/test/cfg/container/data/containerinclude/"); VespaModel model = creator.create(); @@ -85,43 +82,51 @@ public class ContainerIncludeTest { assertEquals("com.yahoo.Processor2", processingChainMap.get("processingchain2").getInnerComponents().iterator().next().getComponentId().stringValue()); } - @Test(expected = IllegalArgumentException.class) - public void includeNonExistent() { - VespaModelCreatorWithFilePkg creator = new VespaModelCreatorWithFilePkg("src/test/cfg/container/data/containerinclude2/"); - creator.create(); + @Test + void includeNonExistent() { + assertThrows(IllegalArgumentException.class, () -> { + VespaModelCreatorWithFilePkg creator = new VespaModelCreatorWithFilePkg("src/test/cfg/container/data/containerinclude2/"); + creator.create(); + }); } - @Test(expected = IllegalArgumentException.class) - public void includeAbsolutePath() { - VespaModelCreatorWithFilePkg creator = new VespaModelCreatorWithFilePkg("src/test/cfg/container/data/containerinclude3/"); - creator.create(); + @Test + void includeAbsolutePath() { + assertThrows(IllegalArgumentException.class, () -> { + VespaModelCreatorWithFilePkg creator = new VespaModelCreatorWithFilePkg("src/test/cfg/container/data/containerinclude3/"); + creator.create(); + }); } - @Test(expected = IllegalArgumentException.class) - public void includeNonDirectory() { - VespaModelCreatorWithFilePkg creator = new VespaModelCreatorWithFilePkg("src/test/cfg/container/data/containerinclude4/"); - creator.create(); + @Test + void includeNonDirectory() { + assertThrows(IllegalArgumentException.class, () -> { + VespaModelCreatorWithFilePkg creator = new VespaModelCreatorWithFilePkg("src/test/cfg/container/data/containerinclude4/"); + creator.create(); + }); } - @Test(expected = IllegalArgumentException.class) - public void include_file_with_wrong_root_element_name() { - VespaModelCreatorWithFilePkg creator = new VespaModelCreatorWithFilePkg("src/test/cfg/container/data/containerinclude5/"); - creator.create(); + @Test + void include_file_with_wrong_root_element_name() { + assertThrows(IllegalArgumentException.class, () -> { + VespaModelCreatorWithFilePkg creator = new VespaModelCreatorWithFilePkg("src/test/cfg/container/data/containerinclude5/"); + creator.create(); + }); } @Test - public void include_empty_directory() { + void include_empty_directory() { VespaModelCreatorWithFilePkg creator = new VespaModelCreatorWithFilePkg("src/test/cfg/container/data/containerinclude6/"); creator.create(); } @Test - public void included_file_with_xml_schema_violation() { + void included_file_with_xml_schema_violation() { try { VespaModelCreatorWithFilePkg creator = new VespaModelCreatorWithFilePkg("src/test/cfg/container/data/include_xml_error/"); creator.create(true); fail("Expected exception due to xml schema violation ('zearcer')"); - } catch (IllegalArgumentException e) { + } catch (IllegalArgumentException e) { assertTrue(e.getMessage().contains("Invalid XML according to XML schema")); assertTrue(e.getMessage().contains("zearcer")); } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/component/BindingPatternTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/component/BindingPatternTest.java index ea4ee073915..2cf38e4bc7e 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/component/BindingPatternTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/component/BindingPatternTest.java @@ -1,10 +1,10 @@ // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.model.container.component; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; /** * @author bjorncs @@ -12,7 +12,7 @@ import static org.junit.Assert.assertFalse; public class BindingPatternTest { @Test - public void parses_valid_bindings_correctly() { + void parses_valid_bindings_correctly() { assertBindingParses("http://host:1234/path"); assertBindingParses("http://host/path"); assertBindingParses("http://host/"); @@ -25,7 +25,7 @@ public class BindingPatternTest { } @Test - public void getters_returns_correct_components() { + void getters_returns_correct_components() { { BindingPattern pattern = SystemBindingPattern.fromPattern("http://host:1234/path/*"); assertEquals("http", pattern.scheme()); @@ -46,8 +46,7 @@ public class BindingPatternTest { BindingPattern pattern = SystemBindingPattern.fromPattern(binding); String stringRepresentation = pattern.patternString(); assertEquals( - "Expected string representation of parsed binding to match original binding string", - binding, stringRepresentation); + binding, stringRepresentation, "Expected string representation of parsed binding to match original binding string"); } }
\ No newline at end of file diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/configserver/ConfigserverClusterTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/configserver/ConfigserverClusterTest.java index ada8e2c210b..4bf4cc71890 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/configserver/ConfigserverClusterTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/configserver/ConfigserverClusterTest.java @@ -19,7 +19,7 @@ import com.yahoo.vespa.model.container.ContainerModel; import com.yahoo.vespa.model.container.ContainerModelEvaluation; import com.yahoo.vespa.model.container.configserver.option.CloudConfigOptions; import com.yahoo.vespa.model.container.xml.ConfigServerContainerModelBuilder; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Collections; @@ -28,9 +28,7 @@ import java.util.Optional; import java.util.function.Function; import java.util.stream.Collectors; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * @author Ulf Lilleengen @@ -38,7 +36,7 @@ import static org.junit.Assert.assertTrue; public class ConfigserverClusterTest { @Test - public void zookeeperConfig_default() { + void zookeeperConfig_default() { ZookeeperServerConfig config = getConfig(ZookeeperServerConfig.class); assertZookeeperServerProperty(config.server(), ZookeeperServerConfig.Server::hostname, "localhost"); assertZookeeperServerProperty(config.server(), ZookeeperServerConfig.Server::id, 0); @@ -46,7 +44,7 @@ public class ConfigserverClusterTest { } @Test - public void zookeeperConfig_only_config_servers_set_hosted() { + void zookeeperConfig_only_config_servers_set_hosted() { TestOptions testOptions = createTestOptions(Arrays.asList("cfg1", "localhost", "cfg3"), Collections.emptyList()); ZookeeperServerConfig config = getConfig(ZookeeperServerConfig.class, testOptions); assertZookeeperServerProperty(config.server(), ZookeeperServerConfig.Server::hostname, "cfg1", "localhost", "cfg3"); @@ -56,7 +54,7 @@ public class ConfigserverClusterTest { } @Test - public void zookeeperConfig_with_config_servers_and_zk_ids_hosted() { + void zookeeperConfig_with_config_servers_and_zk_ids_hosted() { TestOptions testOptions = createTestOptions(Arrays.asList("cfg1", "localhost", "cfg3"), Arrays.asList(4, 2, 3)); ZookeeperServerConfig config = getConfig(ZookeeperServerConfig.class, testOptions); assertZookeeperServerProperty(config.server(), ZookeeperServerConfig.Server::hostname, "cfg1", "localhost", "cfg3"); @@ -65,7 +63,7 @@ public class ConfigserverClusterTest { } @Test - public void zookeeperConfig_self_hosted() { + void zookeeperConfig_self_hosted() { final boolean hostedVespa = false; TestOptions testOptions = createTestOptions(Arrays.asList("cfg1", "localhost", "cfg3"), Arrays.asList(4, 2, 3), hostedVespa); ZookeeperServerConfig config = getConfig(ZookeeperServerConfig.class, testOptions); @@ -75,26 +73,30 @@ public class ConfigserverClusterTest { assertEquals("gz", config.snapshotMethod()); } - @Test(expected = IllegalArgumentException.class) - public void zookeeperConfig_uneven_number_of_config_servers_and_zk_ids() { - TestOptions testOptions = createTestOptions(Arrays.asList("cfg1", "localhost", "cfg3"), Collections.singletonList(1)); - getConfig(ZookeeperServerConfig.class, testOptions); + @Test + void zookeeperConfig_uneven_number_of_config_servers_and_zk_ids() { + assertThrows(IllegalArgumentException.class, () -> { + TestOptions testOptions = createTestOptions(Arrays.asList("cfg1", "localhost", "cfg3"), Collections.singletonList(1)); + getConfig(ZookeeperServerConfig.class, testOptions); + }); } - @Test(expected = IllegalArgumentException.class) - public void zookeeperConfig_negative_zk_id() { - TestOptions testOptions = createTestOptions(Arrays.asList("cfg1", "localhost", "cfg3"), Arrays.asList(1, 2, -1)); - getConfig(ZookeeperServerConfig.class, testOptions); + @Test + void zookeeperConfig_negative_zk_id() { + assertThrows(IllegalArgumentException.class, () -> { + TestOptions testOptions = createTestOptions(Arrays.asList("cfg1", "localhost", "cfg3"), Arrays.asList(1, 2, -1)); + getConfig(ZookeeperServerConfig.class, testOptions); + }); } @Test - public void testHealthMonitorConfig() { + void testHealthMonitorConfig() { HealthMonitorConfig config = getConfig(HealthMonitorConfig.class); assertEquals(60, (int) config.snapshot_interval()); } @Test - public void testConfigserverConfig() { + void testConfigserverConfig() { ConfigserverConfig config = getConfig(ConfigserverConfig.class); assertEquals(1, config.configModelPluginDir().size()); assertEquals(Defaults.getDefaults().underVespaHome("lib/jars/config-models"), config.configModelPluginDir().get(0)); @@ -110,7 +112,7 @@ public class ConfigserverClusterTest { } @Test - public void testCuratorConfig() { + void testCuratorConfig() { CuratorConfig config = getConfig(CuratorConfig.class); assertEquals(1, config.server().size()); assertEquals("localhost", config.server().get(0).hostname()); @@ -119,7 +121,7 @@ public class ConfigserverClusterTest { } @Test - public void model_evaluation_bundles_are_not_installed_via_config() { + void model_evaluation_bundles_are_not_installed_via_config() { // These bundles must be pre-installed because they are used by config-model. PlatformBundlesConfig config = getConfig(PlatformBundlesConfig.class); assertFalse(config.bundlePaths().contains(ContainerModelEvaluation.MODEL_INTEGRATION_BUNDLE_FILE.toString())); @@ -177,7 +179,7 @@ public class ConfigserverClusterTest { // Simulate the behaviour of StandaloneContainer List<? extends Container> containers = containerModel.getCluster().getContainers(); - assertEquals("Standalone container", 1, containers.size()); + assertEquals(1, containers.size(), "Standalone container"); HostResource hostResource = root.hostSystem().getHost(Container.SINGLENODE_CONTAINER_SERVICESPEC); containers.get(0).setHostResource(hostResource); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/http/BlockFeedGlobalEndpointsFilterTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/http/BlockFeedGlobalEndpointsFilterTest.java index b17be9eb55e..78d28897bb8 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/http/BlockFeedGlobalEndpointsFilterTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/http/BlockFeedGlobalEndpointsFilterTest.java @@ -5,19 +5,19 @@ package com.yahoo.vespa.model.container.http; import com.yahoo.config.model.api.ApplicationClusterEndpoint; import com.yahoo.config.model.api.ContainerEndpoint; import com.yahoo.vespa.config.jdisc.http.filter.RuleBasedFilterConfig; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.List; import java.util.Set; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; public class BlockFeedGlobalEndpointsFilterTest { @Test - public void setup_blocking_rule_when_endpoints_is_non_empty() { + void setup_blocking_rule_when_endpoints_is_non_empty() { var endpoints = Set.of(new ContainerEndpoint("default", ApplicationClusterEndpoint.Scope.global, List.of("foo", "bar"))); var filter = new BlockFeedGlobalEndpointsFilter(endpoints, true); var config = getConfig(filter); @@ -28,7 +28,7 @@ public class BlockFeedGlobalEndpointsFilterTest { } @Test - public void does_not_setup_blocking_rule_when_endpoints_empty() { + void does_not_setup_blocking_rule_when_endpoints_empty() { var filter = new BlockFeedGlobalEndpointsFilter(Collections.emptySet(), true); var config = getConfig(filter); assertEquals(0, config.rule().size()); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/http/DefaultFilterTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/http/DefaultFilterTest.java index 1624a4754c7..3e80b319e88 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/http/DefaultFilterTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/http/DefaultFilterTest.java @@ -8,7 +8,7 @@ import com.yahoo.jdisc.http.ServerConfig; import com.yahoo.vespa.model.container.component.BindingPattern; import com.yahoo.vespa.model.container.component.UserBindingPattern; import com.yahoo.vespa.model.container.xml.ContainerModelBuilder; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.w3c.dom.Element; import java.util.Set; @@ -27,7 +27,7 @@ public class DefaultFilterTest extends DomBuilderTest { } @Test - public void default_request_and_response_filters_in_services_xml_are_listen_in_server_config() { + void default_request_and_response_filters_in_services_xml_are_listen_in_server_config() { BindingPattern binding = UserBindingPattern.fromHttpPath("/my-chain-binding"); Element xml = parse( "<container version='1.0'>", @@ -40,7 +40,7 @@ public class DefaultFilterTest extends DomBuilderTest { " <binding>" + binding.patternString() + "</binding>", " </response-chain>", " <request-chain id='my-default-request-chain'/>" + - " <response-chain id='my-default-response-chain'/>", + " <response-chain id='my-default-response-chain'/>", " </filtering>", " <server id='server1' port='8000' default-request-chain=\"my-default-request-chain\" default-response-chain=\"my-default-response-chain\"/>", " <server id='server2' port='9000' />", diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/http/FilterBindingsTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/http/FilterBindingsTest.java index 7634a5928e5..787a8255628 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/http/FilterBindingsTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/http/FilterBindingsTest.java @@ -11,12 +11,12 @@ import com.yahoo.vespa.model.container.component.chain.Chain; import com.yahoo.vespa.model.container.http.xml.HttpBuilder; import com.yahoo.vespa.model.container.xml.ContainerModelBuilder; import com.yahoo.vespa.model.container.xml.ContainerModelBuilder.Networking; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.w3c.dom.Element; import static com.yahoo.collections.CollectionUtil.first; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author gjoranv @@ -39,7 +39,7 @@ public class FilterBindingsTest extends DomBuilderTest { } @Test - public void request_chain_binding_is_added_to_http() throws Exception { + void request_chain_binding_is_added_to_http() throws Exception { Element xml = parse( "<http>", " <filtering>", @@ -55,11 +55,11 @@ public class FilterBindingsTest extends DomBuilderTest { assertEquals(MY_CHAIN_BINDING, binding.binding()); Chain<Filter> myChain = http.getFilterChains().allChains().getComponent("my-request-chain"); - assertNotNull("Missing chain", myChain); + assertNotNull(myChain, "Missing chain"); } @Test - public void response_chain_binding_is_added_to_http() throws Exception { + void response_chain_binding_is_added_to_http() throws Exception { Element xml = parse( "<http>", " <filtering>", @@ -75,11 +75,11 @@ public class FilterBindingsTest extends DomBuilderTest { assertEquals(MY_CHAIN_BINDING, binding.binding()); Chain<Filter> myChain = http.getFilterChains().allChains().getComponent("my-response-chain"); - assertNotNull("Missing chain", myChain); + assertNotNull(myChain, "Missing chain"); } @Test - public void bindings_are_added_to_config_for_all_http_servers_with_jetty() { + void bindings_are_added_to_config_for_all_http_servers_with_jetty() { final Element xml = parse( "<container version='1.0'>", " <http>", diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/http/FilterChainsTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/http/FilterChainsTest.java index 6f223afd536..990896acb01 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/http/FilterChainsTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/http/FilterChainsTest.java @@ -5,13 +5,13 @@ import com.yahoo.component.ComponentSpecification; import com.yahoo.config.model.builder.xml.test.DomBuilderTest; import com.yahoo.vespa.model.container.component.chain.Chain; import com.yahoo.vespa.model.container.http.xml.HttpBuilder; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.w3c.dom.Element; import static com.yahoo.collections.CollectionUtil.first; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author gjoranv @@ -21,7 +21,7 @@ import static org.junit.Assert.assertNotNull; public class FilterChainsTest extends DomBuilderTest { private Http http; - @Before + @BeforeEach public void setupFilterChains() { http = new HttpBuilder().build(root.getDeployState(), root, servicesXml()); root.freezeModelTopology(); @@ -40,18 +40,18 @@ public class FilterChainsTest extends DomBuilderTest { } @Test - public void chains_are_built() { + void chains_are_built() { assertNotNull(getChain("myChain")); } @Test - public void filters_outside_chains_are_built() { - Filter outerFilter = (Filter)http.getFilterChains().componentsRegistry().getComponent("outer"); + void filters_outside_chains_are_built() { + Filter outerFilter = (Filter) http.getFilterChains().componentsRegistry().getComponent("outer"); assertNotNull(outerFilter); } @Test - public void filters_in_chains_are_built() { + void filters_in_chains_are_built() { Filter filter = first(getChain("myChain").getInnerComponents()); assertNotNull(filter); assertEquals("inner", filter.getComponentId().getName()); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/http/FilterConfigTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/http/FilterConfigTest.java index e17c5eed242..76a3dcb2788 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/http/FilterConfigTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/http/FilterConfigTest.java @@ -4,15 +4,13 @@ package com.yahoo.vespa.model.container.http; import com.yahoo.config.model.builder.xml.test.DomBuilderTest; import com.yahoo.container.core.http.HttpFilterConfig; import com.yahoo.vespa.model.container.http.xml.HttpBuilder; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.w3c.dom.Element; import static com.yahoo.collections.CollectionUtil.first; import static com.yahoo.vespa.model.container.http.FilterConfigProvider.configProviderId; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * @author gjoranv @@ -22,7 +20,7 @@ public class FilterConfigTest extends DomBuilderTest { private Http http; - @Before + @BeforeEach public void setupFilterChains() { http = new HttpBuilder().build(root.getDeployState(), root, servicesXml()); root.freezeModelTopology(); @@ -54,14 +52,14 @@ public class FilterConfigTest extends DomBuilderTest { } @Test - public void filter_without_config_does_not_have_FilterConfigProvider() { + void filter_without_config_does_not_have_FilterConfigProvider() { Filter noConfigFilter = getOuterFilter("no-config"); assertNull(getProvider(noConfigFilter)); } @Test - public void filterName_is_id_from_component_spec() { + void filterName_is_id_from_component_spec() { Filter emptyConfigFilter = getOuterFilter("empty-config"); HttpFilterConfig config = getHttpFilterConfig(emptyConfigFilter); @@ -69,7 +67,7 @@ public class FilterConfigTest extends DomBuilderTest { } @Test - public void filterClass_is_class_from_component_spec() { + void filterClass_is_class_from_component_spec() { Filter emptyConfigFilter = getOuterFilter("empty-config"); HttpFilterConfig config = getHttpFilterConfig(emptyConfigFilter); @@ -77,7 +75,7 @@ public class FilterConfigTest extends DomBuilderTest { } @Test - public void filter_with_empty_config_has_FilterConfigProvider_with_empty_map() { + void filter_with_empty_config_has_FilterConfigProvider_with_empty_map() { Filter emptyConfigFilter = getOuterFilter("empty-config"); HttpFilterConfig config = getHttpFilterConfig(emptyConfigFilter); @@ -85,7 +83,7 @@ public class FilterConfigTest extends DomBuilderTest { } @Test - public void config_params_are_set_correctly_in_FilterConfigProvider() { + void config_params_are_set_correctly_in_FilterConfigProvider() { Filter configWithParamsFilter = getOuterFilter("config-with-params"); HttpFilterConfig config = getHttpFilterConfig(configWithParamsFilter); @@ -95,7 +93,7 @@ public class FilterConfigTest extends DomBuilderTest { } @Test - public void inner_filter_can_have_filter_config() { + void inner_filter_can_have_filter_config() { Filter innerFilter = first(http.getFilterChains().allChains().getComponent("myChain").getInnerComponents()); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/http/StrictFilteringTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/http/StrictFilteringTest.java index ad81c9a5a4d..effbb4d6fe1 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/http/StrictFilteringTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/http/StrictFilteringTest.java @@ -5,10 +5,10 @@ import com.yahoo.config.model.builder.xml.test.DomBuilderTest; import com.yahoo.config.model.deploy.DeployState; import com.yahoo.jdisc.http.ServerConfig; import com.yahoo.vespa.model.container.xml.ContainerModelBuilder; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.w3c.dom.Element; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author bjorncs @@ -16,7 +16,7 @@ import static org.junit.Assert.assertEquals; public class StrictFilteringTest extends DomBuilderTest { @Test - public void strict_filtering_enabled_if_specified_in_services() { + void strict_filtering_enabled_if_specified_in_services() { Element xml = parse( "<container version='1.0'>", " <http>", @@ -33,7 +33,7 @@ public class StrictFilteringTest extends DomBuilderTest { } @Test - public void strict_filtering_enabled_by_default_if_filter_present() { + void strict_filtering_enabled_by_default_if_filter_present() { Element xml = parse( "<container version='1.0'>", " <http>", @@ -49,7 +49,7 @@ public class StrictFilteringTest extends DomBuilderTest { } @Test - public void strict_filtering_disabled_if_no_filter() { + void strict_filtering_disabled_if_no_filter() { Element xml = parse( "<container version='1.0'>", " <http>", diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/ml/ModelsEvaluatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/ml/ModelsEvaluatorTest.java index 3deeef7f2a2..063f8f3109e 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/ml/ModelsEvaluatorTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/ml/ModelsEvaluatorTest.java @@ -5,10 +5,10 @@ import ai.vespa.modelintegration.evaluator.OnnxEvaluator; import ai.vespa.models.evaluation.FunctionEvaluator; import ai.vespa.models.evaluation.ModelsEvaluator; import com.yahoo.tensor.Tensor; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assume.assumeTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assumptions.assumeTrue; /** * Tests the ModelsEvaluatorTester. @@ -18,7 +18,7 @@ import static org.junit.Assume.assumeTrue; public class ModelsEvaluatorTest { @Test - public void testModelsEvaluator() { + void testModelsEvaluator() { // Assumption fails but test passes on Intel macs // Assumption fails and test fails on ARM64 assumeTrue(OnnxEvaluator.isRuntimeAvailable()); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/processing/test/ProcessingChainsTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/processing/test/ProcessingChainsTest.java index 4ac6129c6ee..bd6400d81e0 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/processing/test/ProcessingChainsTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/processing/test/ProcessingChainsTest.java @@ -7,13 +7,13 @@ import com.yahoo.vespa.model.container.component.chain.ChainedComponent; import com.yahoo.vespa.model.container.component.chain.Chains; import com.yahoo.vespa.model.container.processing.ProcessingChain; import com.yahoo.vespa.model.container.processing.Processor; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.w3c.dom.Element; import java.util.Collection; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author bratseth @@ -23,7 +23,7 @@ public class ProcessingChainsTest extends DomBuilderTest { private Chains<ProcessingChain> processingChains; - @Before + @BeforeEach public void setupProcessingChains() { DomProcessingBuilder processingBuilder = new DomProcessingBuilder(null); processingBuilder.build(root.getDeployState(), root, servicesXml()); @@ -43,7 +43,7 @@ public class ProcessingChainsTest extends DomBuilderTest { } @Test - public void testProcessingChainConfiguration() { + void testProcessingChainConfiguration() { ProcessingChain defaultChain = processingChains.allChains().getComponent("default"); assertEquals("default", defaultChain.getId().stringValue()); assertEquals(1, defaultChain.getInnerComponents().size()); @@ -57,7 +57,7 @@ public class ProcessingChainsTest extends DomBuilderTest { } @Test - public void require_that_processors_have_correct_class() { + void require_that_processors_have_correct_class() { ChainedComponent<?> processor1 = processingChains.getComponentGroup().getComponents().iterator().next(); assertEquals("com.yahoo.test.Processor1", processor1.model.bundleInstantiationSpec.classId.stringValue()); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/search/ImplicitIndexingClusterTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/search/ImplicitIndexingClusterTest.java index d48c397b1f0..1441975110e 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/search/ImplicitIndexingClusterTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/search/ImplicitIndexingClusterTest.java @@ -10,9 +10,9 @@ import com.yahoo.vespa.defaults.Defaults; import com.yahoo.vespa.model.VespaModel; import com.yahoo.vespa.model.container.ContainerCluster; import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithMockPkg; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Tony Vaagenes @@ -21,7 +21,7 @@ import static org.junit.Assert.assertNotNull; public class ImplicitIndexingClusterTest { @Test - public void existing_jdisc_is_used_as_indexing_cluster_when_multitenant() { + void existing_jdisc_is_used_as_indexing_cluster_when_multitenant() { final String servicesXml = "<services version=\"1.0\">\n" + // " <container version=\"1.0\" id=\"jdisc\">\n" + // " <search />\n" + // @@ -42,8 +42,8 @@ public class ImplicitIndexingClusterTest { VespaModel vespaModel = buildMultiTenantVespaModel(servicesXml); ContainerCluster jdisc = vespaModel.getContainerClusters().get("jdisc"); - assertNotNull("Docproc not added to jdisc", jdisc.getDocproc()); - assertNotNull("Indexing chain not added to jdisc", jdisc.getDocprocChains().allChains().getComponent("indexing")); + assertNotNull(jdisc.getDocproc(), "Docproc not added to jdisc"); + assertNotNull(jdisc.getDocprocChains().allChains().getComponent("indexing"), "Indexing chain not added to jdisc"); } private static VespaModel buildMultiTenantVespaModel(String servicesXml) { diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/search/SemanticRulesTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/search/SemanticRulesTest.java index 8d83ec4cc5f..d9e2ae59ef6 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/search/SemanticRulesTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/search/SemanticRulesTest.java @@ -7,10 +7,9 @@ import com.yahoo.prelude.semantics.RuleBase; import com.yahoo.prelude.semantics.RuleImporter; import com.yahoo.prelude.semantics.SemanticRulesConfig; import com.yahoo.prelude.semantics.parser.ParseException; -import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertFalse; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.*; import java.io.File; import java.io.IOException; @@ -25,7 +24,7 @@ public class SemanticRulesTest { private final static String root = "src/test/java/com/yahoo/vespa/model/container/search/semanticrules"; @Test - public void semanticRulesTest() throws ParseException, IOException { + void semanticRulesTest() throws ParseException, IOException { SemanticRuleBuilder ruleBuilder = new SemanticRuleBuilder(); SemanticRules rules = ruleBuilder.build(FilesApplicationPackage.fromFile(new File(root))); SemanticRulesConfig.Builder configBuilder = new SemanticRulesConfig.Builder(); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/Federation2Test.java b/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/Federation2Test.java index ac272301445..22ad6b79a74 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/Federation2Test.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/Federation2Test.java @@ -2,10 +2,10 @@ package com.yahoo.vespa.model.container.search.searchchain; import com.yahoo.test.SimpletypesConfig; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.w3c.dom.Element; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author bratseth @@ -55,15 +55,15 @@ public class Federation2Test extends SchemaChainsTestBase { @Test - public void testProviderConfigs() { + void testProviderConfigs() { //SimpletypesConfig testConfig = root.getConfig(SimpletypesConfig.class, "test/searchchains/chain/chain1/component/com.yahoo.example.TestSearcher"); //assertEquals("testSearcher",testConfig.stringval()); SimpletypesConfig configA = root.getConfig(SimpletypesConfig.class, "searchchains/chain/providerA/source/commonSource/component/com.yahoo.example.AddHitSearcher"); - assertEquals("providerA",configA.stringval()); + assertEquals("providerA", configA.stringval()); SimpletypesConfig configB = root.getConfig(SimpletypesConfig.class, "searchchains/chain/providerB/source/commonSource/component/com.yahoo.example.AddHitSearcher"); - assertEquals("providerB",configB.stringval()); + assertEquals("providerB", configB.stringval()); } } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/FederationSearcherTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/FederationSearcherTest.java index 3f95fb99087..89319877d03 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/FederationSearcherTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/FederationSearcherTest.java @@ -12,8 +12,7 @@ import com.yahoo.search.searchchain.model.federation.FederationSearcherModel; import com.yahoo.search.searchchain.model.federation.FederationSearcherModel.TargetSpec; import com.yahoo.vespa.model.ConfigProducer; import com.yahoo.vespa.model.container.search.searchchain.Source.GroupOption; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.lang.reflect.Method; import java.util.ArrayList; @@ -25,9 +24,7 @@ import static java.util.Collections.emptyList; import static java.util.Collections.emptySet; import static java.util.Collections.singletonList; import static java.util.stream.Collectors.toList; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * @author Tony Vaagenes @@ -71,7 +68,7 @@ public class FederationSearcherTest { } @Test - public void default_providers_are_inherited_when_inheritDefaultSources_is_true() throws Exception { + void default_providers_are_inherited_when_inheritDefaultSources_is_true() throws Exception { FederationFixture f = new FederationFixture(); final String providerId = "providerId"; @@ -83,27 +80,27 @@ public class FederationSearcherTest { FederationConfig.Target target = federationConfig.target(0); assertSame(providerId, target.id()); // by identity - assertTrue("Not used by default", target.searchChain(0).useByDefault()); + assertTrue(target.searchChain(0).useByDefault(), "Not used by default"); } @Test - public void source_groups_are_inherited_when_inheritDefaultSources_is_true() throws Exception { + void source_groups_are_inherited_when_inheritDefaultSources_is_true() throws Exception { FederationFixture f = new ProvidersWithSourceFixture(); FederationConfig federationConfig = getConfig(f.federationSearchWithDefaultSources); - Assert.assertEquals(1, federationConfig.target().size()); + assertEquals(1, federationConfig.target().size()); FederationConfig.Target target = federationConfig.target(0); assertEquals(target.id(), "source"); - assertTrue("Not used by default", target.useByDefault()); + assertTrue(target.useByDefault(), "Not used by default"); assertEquals(2, target.searchChain().size()); assertTrue(target.searchChain().stream() - .map(FederationConfig.Target.SearchChain::providerId) - .collect(toList()).containsAll(List.of("provider1", "provider2"))); + .map(FederationConfig.Target.SearchChain::providerId) + .collect(toList()).containsAll(List.of("provider1", "provider2"))); } @Test - public void source_groups_are_not_inherited_when_inheritDefaultSources_is_false() throws Exception { + void source_groups_are_not_inherited_when_inheritDefaultSources_is_false() throws Exception { FederationFixture f = new ProvidersWithSourceFixture(); FederationSearcher federationSearcherWithoutDefaultSources = newFederationSearcher(false, emptyList()); @@ -114,7 +111,7 @@ public class FederationSearcherTest { } @Test - public void leaders_must_be_the_first_search_chain_in_a_target() throws Exception { + void leaders_must_be_the_first_search_chain_in_a_target() throws Exception { FederationFixture f = new ProvidersWithSourceFixture(); FederationConfig federationConfig = getConfig(f.federationSearchWithDefaultSources); @@ -125,7 +122,7 @@ public class FederationSearcherTest { } @Test - public void manually_specified_targets_overrides_inherited_targets() throws Exception { + void manually_specified_targets_overrides_inherited_targets() throws Exception { FederationFixture f = new FederationFixture(); f.registerProviderWithSources(createProvider(ComponentId.fromString("provider1"))); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/FederationTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/FederationTest.java index 3945a74cf15..ff884d6072f 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/FederationTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/FederationTest.java @@ -2,15 +2,13 @@ package com.yahoo.vespa.model.container.search.searchchain; import com.yahoo.search.federation.FederationConfig; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.w3c.dom.Element; import java.util.List; import static org.assertj.core.api.Fail.fail; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * Test generated config for federation. @@ -52,7 +50,7 @@ public class FederationTest extends SchemaChainsTestBase { @Test - public void validateNativeDefaultTargets() { + void validateNativeDefaultTargets() { FederationConfig.Builder fb = new FederationConfig.Builder(); root.getConfig(fb, "searchchains/chain/native/component/federation"); FederationConfig config = new FederationConfig(fb); @@ -61,9 +59,9 @@ public class FederationTest extends SchemaChainsTestBase { String failMessage = "Failed for target " + target.id(); if (target.id().startsWith("source")) { - assertTrue(failMessage, target.useByDefault()); + assertTrue(target.useByDefault(), failMessage); } else { - assertFalse(failMessage, target.useByDefault()); + assertFalse(target.useByDefault(), failMessage); } } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/SchemaChainsTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/SchemaChainsTest.java index 20345615753..21223974be1 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/SchemaChainsTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/SchemaChainsTest.java @@ -6,11 +6,11 @@ import com.yahoo.container.core.ChainsConfig; import com.yahoo.prelude.cluster.ClusterSearcher; import com.yahoo.search.config.ClusterConfig; import com.yahoo.vespa.defaults.Defaults; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.w3c.dom.Element; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** @@ -23,7 +23,7 @@ public class SchemaChainsTest extends SchemaChainsTestBase { private ClusterConfig clusterConfig; - @Before + @BeforeEach public void subscribe() { ClusterConfig.Builder clusterBuilder = new ClusterConfig.Builder(); clusterBuilder = (ClusterConfig.Builder)root.getConfig(clusterBuilder, "searchchains/chain/cluster2/component/" + ClusterSearcher.class.getName()); @@ -70,13 +70,13 @@ public class SchemaChainsTest extends SchemaChainsTestBase { } @Test - public void require_that_source_chain_spec_id_is_namespaced_in_provider_id() { + void require_that_source_chain_spec_id_is_namespaced_in_provider_id() { Source source = (Source) getSearchChains().allChains().getComponent("source:1@provider:1"); assertEquals(ComponentId.fromString("provider:1"), source.getChainSpecification().componentId.getNamespace()); } @Test - public void validateLocalProviderConfig() { + void validateLocalProviderConfig() { assertEquals(2, clusterConfig.clusterId()); assertEquals("cluster2", clusterConfig.clusterName()); } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/SchemaChainsTest2.java b/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/SchemaChainsTest2.java index 04bda0bce21..661d10b945d 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/SchemaChainsTest2.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/SchemaChainsTest2.java @@ -5,12 +5,12 @@ import com.yahoo.config.model.builder.xml.test.DomBuilderTest; import com.yahoo.config.model.test.MockRoot; import com.yahoo.vespa.model.builder.xml.dom.chains.search.DomSearchChainsBuilder; import com.yahoo.vespa.model.container.xml.ContainerModelBuilderTest; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.w3c.dom.Element; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author gjoranv @@ -19,13 +19,13 @@ public class SchemaChainsTest2 { private MockRoot root; - @Before + @BeforeEach public void prepareTest() { root = new MockRoot("root"); } @Test - public void fail_upon_unresolved_inheritance() { + void fail_upon_unresolved_inheritance() { final Element searchElem = DomBuilderTest.parse( "<search>", " <chain id='default' inherits='nonexistent' />", @@ -37,12 +37,12 @@ public class SchemaChainsTest2 { fail("Expected exception when inheriting a nonexistent search chain."); } catch (Exception e) { assertEquals("Missing chain 'nonexistent'.", - e.getMessage()); + e.getMessage()); } } @Test - public void fail_upon_two_user_declared_chains_with_same_name() { + void fail_upon_two_user_declared_chains_with_same_name() { final Element clusterElem = DomBuilderTest.parse( "<container id='cluster1' version='1.0'>", ContainerModelBuilderTest.nodesXml, @@ -56,12 +56,12 @@ public class SchemaChainsTest2 { fail("Expected exception when declaring chains with duplicate id."); } catch (Exception e) { assertEquals("Both search chain 'same' and search chain 'same' are configured with the id 'same'. All components must have a unique id.", - e.getMessage()); + e.getMessage()); } } @Test - public void fail_upon_user_declared_chain_with_same_id_as_builtin_chain() { + void fail_upon_user_declared_chain_with_same_id_as_builtin_chain() { final Element clusterElem = DomBuilderTest.parse( "<container id='cluster1' version='1.0'>", ContainerModelBuilderTest.nodesXml, @@ -74,7 +74,7 @@ public class SchemaChainsTest2 { fail("Expected exception when taking the id from a builtin chain."); } catch (Exception e) { assertEquals("Both search chain 'vespa' and search chain 'vespa' are configured with the id 'vespa'. All components must have a unique id.", - e.getMessage()); + e.getMessage()); } } } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/SchemaChainsTestBase.java b/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/SchemaChainsTestBase.java index e654f8deee1..a003a91a624 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/SchemaChainsTestBase.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/SchemaChainsTestBase.java @@ -3,7 +3,7 @@ package com.yahoo.vespa.model.container.search.searchchain; import com.yahoo.config.model.builder.xml.test.DomBuilderTest; import com.yahoo.vespa.model.builder.xml.dom.chains.search.DomSearchChainsBuilder; -import org.junit.Before; +import org.junit.jupiter.api.BeforeEach; import org.w3c.dom.Element; /** Creates SearchChains model from xml input. @@ -11,7 +11,7 @@ import org.w3c.dom.Element; */ public abstract class SchemaChainsTestBase extends DomBuilderTest { - @Before + @BeforeEach public void setupSearchChains() { SearchChains searchChains = new DomSearchChainsBuilder().build(root.getDeployState(), root, servicesXml()); searchChains.initialize(MockSearchClusters.twoMockClusterSpecsByName(root)); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/SourceGroupTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/SourceGroupTest.java index 2cb0e8f0ab1..8c564f5cd6f 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/SourceGroupTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/SourceGroupTest.java @@ -5,15 +5,13 @@ import com.yahoo.component.ComponentId; import com.yahoo.component.chain.model.ChainSpecification; import com.yahoo.config.model.test.MockRoot; import com.yahoo.search.searchchain.model.federation.FederationOptions; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.util.List; import java.util.Set; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; /** * @author Tony Vaagenes @@ -22,14 +20,14 @@ public class SourceGroupTest { private MockRoot root; private SearchChains searchChains; - @Before + @BeforeEach public void setUp() { root = new MockRoot(); searchChains = new SearchChains(root, "searchchains"); } @Test - public void report_error_when_no_leader() { + void report_error_when_no_leader() { try { Provider provider = createProvider("p1"); Source source = createSource("s1", Source.GroupOption.participant); @@ -65,7 +63,7 @@ public class SourceGroupTest { } @Test - public void require_that_source_and_provider_id_is_not_allowed_to_be_equal() { + void require_that_source_and_provider_id_is_not_allowed_to_be_equal() { Provider provider = createProvider("sameId"); Provider provider2 = createProvider("ignoredId"); @@ -82,7 +80,7 @@ public class SourceGroupTest { fail("Expected exception"); } catch (Exception e) { assertEquals("Id 'sameId' is used both for a source and another search chain/provider", - e.getMessage()); + e.getMessage()); } } } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/search/test/PageTemplatesTestCase.java b/config-model/src/test/java/com/yahoo/vespa/model/container/search/test/PageTemplatesTestCase.java index 4afdecc3cde..d1c1b357dbd 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/search/test/PageTemplatesTestCase.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/search/test/PageTemplatesTestCase.java @@ -6,14 +6,14 @@ import com.yahoo.io.IOUtils; import com.yahoo.io.reader.NamedReader; import com.yahoo.text.StringUtilities; import com.yahoo.vespa.model.container.search.PageTemplates; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author bratseth @@ -23,8 +23,8 @@ public class PageTemplatesTestCase { private final static String root="src/test/java/com/yahoo/vespa/model/container/search/test/pages"; @Test - public void testExport() throws IOException { - List<NamedReader> pageFiles=new ArrayList<>(2); + void testExport() throws IOException { + List<NamedReader> pageFiles = new ArrayList<>(2); pageFiles.add(new NamedReader(root + "/slottingSerp.xml", IOUtils.createReader(root + "/slottingSerp.xml"))); pageFiles.add(new NamedReader(root + "/richSerp.xml", IOUtils.createReader(root + "/richSerp.xml"))); pageFiles.add(new NamedReader(root + "/footer.xml", IOUtils.createReader(root + "/footer.xml"))); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/search/test/QueryProfileVariantsTestCase.java b/config-model/src/test/java/com/yahoo/vespa/model/container/search/test/QueryProfileVariantsTestCase.java index 4bdb130178f..0098cc921f2 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/search/test/QueryProfileVariantsTestCase.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/search/test/QueryProfileVariantsTestCase.java @@ -6,13 +6,13 @@ import com.yahoo.search.query.profile.QueryProfile; import com.yahoo.search.query.profile.QueryProfileRegistry; import com.yahoo.search.query.profile.config.QueryProfileXMLReader; import com.yahoo.vespa.model.container.search.QueryProfiles; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.logging.Level; import static helpers.CompareConfigTestHelper.assertSerializedConfigFileEquals; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author bratseth @@ -22,45 +22,45 @@ public class QueryProfileVariantsTestCase { private final String root = "src/test/java/com/yahoo/vespa/model/container/search/test/"; @Test - public void testConfigCreation() throws IOException { + void testConfigCreation() throws IOException { QueryProfileRegistry registry = new QueryProfileXMLReader().read(root + "queryprofilevariants"); QueryProfiles profiles = new QueryProfiles(registry, new SilentDeployLogger()); assertSerializedConfigFileEquals(root + "query-profile-variants-configuration.cfg", profiles.getConfig().toString()); } @Test - public void testConfigCreation2() throws IOException { + void testConfigCreation2() throws IOException { QueryProfileRegistry registry = new QueryProfileXMLReader().read("src/test/java/com/yahoo/vespa/model/container/search/test/queryprofilevariants2"); QueryProfiles profiles = new QueryProfiles(registry, new SilentDeployLogger()); assertSerializedConfigFileEquals(root + "query-profile-variants2-configuration.cfg", profiles.getConfig().toString()); } @Test - public void testConfigCreationNewsBESimple() throws IOException { + void testConfigCreationNewsBESimple() throws IOException { QueryProfileRegistry registry = new QueryProfileXMLReader().read(root + "newsbesimple"); QueryProfiles profiles = new QueryProfiles(registry, new SilentDeployLogger()); assertSerializedConfigFileEquals(root + "newsbe-query-profiles-simple.cfg", profiles.getConfig().toString()); } @Test - public void testConfigCreationNewsFESimple() throws IOException { + void testConfigCreationNewsFESimple() throws IOException { QueryProfileRegistry registry = new QueryProfileXMLReader().read(root + "newsfesimple"); QueryProfiles profiles = new QueryProfiles(registry, new SilentDeployLogger()); assertSerializedConfigFileEquals(root + "newsfe-query-profiles-simple.cfg", profiles.getConfig().toString()); } @Test - public void testVariantsOfExplicitCompound() throws IOException { + void testVariantsOfExplicitCompound() throws IOException { QueryProfileRegistry registry = new QueryProfileRegistry(); QueryProfile a1 = new QueryProfile("a1"); a1.set("b", "a1.b", registry); QueryProfile profile = new QueryProfile("test"); - profile.setDimensions(new String[] {"x"}); + profile.setDimensions(new String[]{"x"}); profile.set("a", a1, registry); - profile.set("a.b", "a.b.x1", new String[] {"x1"}, registry); - profile.set("a.b", "a.b.x2", new String[] {"x2"}, registry); + profile.set("a.b", "a.b.x1", new String[]{"x1"}, registry); + profile.set("a.b", "a.b.x2", new String[]{"x2"}, registry); registry.register(a1); registry.register(profile); @@ -70,7 +70,7 @@ public class QueryProfileVariantsTestCase { } @Test - public void testVariantsOfExplicitCompoundWithVariantReference() throws IOException { + void testVariantsOfExplicitCompoundWithVariantReference() throws IOException { QueryProfileRegistry registry = new QueryProfileRegistry(); QueryProfile a1 = new QueryProfile("a1"); @@ -80,11 +80,11 @@ public class QueryProfileVariantsTestCase { a2.set("b", "a2.b", registry); QueryProfile profile = new QueryProfile("test"); - profile.setDimensions(new String[] {"x"}); + profile.setDimensions(new String[]{"x"}); profile.set("a", a1, registry); - profile.set("a", a2, new String[] {"x1"}, registry); - profile.set("a.b", "a.b.x1", new String[] {"x1"}, registry); - profile.set("a.b", "a.b.x2", new String[] {"x2"}, registry); + profile.set("a", a2, new String[]{"x1"}, registry); + profile.set("a.b", "a.b.x1", new String[]{"x1"}, registry); + profile.set("a.b", "a.b.x2", new String[]{"x2"}, registry); registry.register(a1); registry.register(a2); @@ -96,7 +96,7 @@ public class QueryProfileVariantsTestCase { /** For comparison with the above */ @Test - public void testExplicitReferenceOverride() throws IOException { + void testExplicitReferenceOverride() throws IOException { QueryProfileRegistry registry = new QueryProfileRegistry(); QueryProfile a1 = new QueryProfile("a1"); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/search/test/QueryProfilesTestCase.java b/config-model/src/test/java/com/yahoo/vespa/model/container/search/test/QueryProfilesTestCase.java index 03641e95f84..9c2c830c36f 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/search/test/QueryProfilesTestCase.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/search/test/QueryProfilesTestCase.java @@ -17,15 +17,13 @@ import com.yahoo.search.query.profile.types.QueryProfileTypeRegistry; import com.yahoo.schema.derived.TestableDeployLogger; import com.yahoo.vespa.model.container.search.QueryProfiles; import com.yahoo.vespa.model.test.utils.DeployLoggerStub; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.logging.Level; import static helpers.CompareConfigTestHelper.assertSerializedConfigFileEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * Tests generation of config from query profiles (XML reading is tested elsewhere) @@ -37,7 +35,7 @@ public class QueryProfilesTestCase { private final static String root = "src/test/java/com/yahoo/vespa/model/container/search/test/"; @Test - public void testVariantReference() { + void testVariantReference() { QueryProfileRegistry registry = new QueryProfileRegistry(); QueryProfile parent = new QueryProfile("parent"); @@ -46,31 +44,31 @@ public class QueryProfilesTestCase { QueryProfile referenced = new QueryProfile("referenced"); referenced.addInherited(parent); - referenced.setDimensions(new String[] { "d2", "d3" }); + referenced.setDimensions(new String[]{"d2", "d3"}); registry.register(referenced); QueryProfile base = new QueryProfile("base"); - base.setDimensions(new String[] { "d1", "d2", "d3" }); - base.set("a", referenced, new String[] { null, null, "d3-val" }, registry); - base.set("a.b", 1, new String[] { null, null, "d3-val" }, registry); + base.setDimensions(new String[]{"d1", "d2", "d3"}); + base.set("a", referenced, new String[]{ null, null, "d3-val"}, registry); + base.set("a.b", 1, new String[]{ null, null, "d3-val"}, registry); QueryProfileVariant aVariants = base.getVariants().getVariants().get(0); - QueryProfile a = (QueryProfile)aVariants.values().get("a"); + QueryProfile a = (QueryProfile) aVariants.values().get("a"); assertEquals("[d1, d2, d3]", a.getDimensions().toString()); registry.register(base); QueryProfiles profiles = new QueryProfiles(registry, new TestableDeployLogger()); QueryProfileRegistry registryFromConfig = QueryProfileConfigurer.createFromConfig(profiles.getConfig()); var directValue = registry.findQueryProfile("base") - .get("a.b", - new String[] { "default", null, "d3-val"}); + .get("a.b", + new String[]{"default", null, "d3-val"}); var throughConfigValue = registryFromConfig.findQueryProfile("base") - .get("a.b", - new String[] { "default", null, "d3-val"}); + .get("a.b", + new String[]{"default", null, "d3-val"}); assertEquals(directValue.toString(), throughConfigValue.toString()); } @Test - public void testVariants() { + void testVariants() { QueryProfileRegistry registry = new QueryProfileXMLReader().read(root + "variants"); QueryProfiles profiles = new QueryProfiles(registry, new TestableDeployLogger()); QueryProfileRegistry registryFromConfig = QueryProfileConfigurer.createFromConfig(profiles.getConfig()); @@ -84,13 +82,13 @@ public class QueryProfilesTestCase { } @Test - public void testEmpty() throws IOException { + void testEmpty() throws IOException { QueryProfileRegistry reg = new QueryProfileRegistry(); assertConfig("empty.cfg", reg); } @Test - public void testQueryProfiles() throws IOException { + void testQueryProfiles() throws IOException { final boolean mandatory = true; final boolean overridable = true; QueryProfileRegistry registry = new QueryProfileRegistry(); @@ -118,13 +116,13 @@ public class QueryProfilesTestCase { typeRegistry.register(marketType); QueryProfile defaultProfile = new QueryProfile("default"); - defaultProfile.set("ranking","production23", registry); + defaultProfile.set("ranking", "production23", registry); defaultProfile.set("representation.defaultIndex", "title", registry); defaultProfile.setOverridable("representation.defaultIndex", false, DimensionValues.empty); registry.register(defaultProfile); QueryProfile test = new QueryProfile("test"); - test.set("tracelevel",2, registry); + test.set("tracelevel", 2, registry); registry.register(test); QueryProfile genericUser = new QueryProfile("genericUser"); @@ -147,8 +145,8 @@ public class QueryProfilesTestCase { QueryProfile marketUser = new QueryProfile("marketUser"); marketUser.setType(userType); marketUser.addInherited(genericUser); - marketUser.set("ads","none", registry); - marketUser.set("age",25, registry); + marketUser.set("ads", "none", registry); + marketUser.set("age", 25, registry); registry.register(marketUser); QueryProfile market = new QueryProfile("root/market"); @@ -173,7 +171,7 @@ public class QueryProfilesTestCase { } @Test - public void testValidation() { + void testValidation() { QueryProfileRegistry registry = new QueryProfileRegistry(); QueryProfileTypeRegistry typeRegistry = registry.getTypeRegistry(); @@ -184,13 +182,13 @@ public class QueryProfilesTestCase { new QueryProfiles(registry, logger); assertEquals(1, logger.entries.size()); assertEquals("This application define query profile types, but has no query profiles referencing them " + - "so they have no effect. " + - "See https://docs.vespa.ai/en/query-profiles.html", - logger.entries.get(0).message); + "so they have no effect. " + + "See https://docs.vespa.ai/en/query-profiles.html", + logger.entries.get(0).message); } @Test - public void testValidationWithTensorFields() { + void testValidationWithTensorFields() { QueryProfileRegistry registry = new QueryProfileRegistry(); QueryProfileTypeRegistry typeRegistry = registry.getTypeRegistry(); @@ -203,10 +201,10 @@ public class QueryProfilesTestCase { new QueryProfiles(registry, logger); assertEquals(1, logger.entries.size()); assertEquals("This application define query profile types, but has no query profiles referencing them " + - "so they have no effect. " + - "In particular, the tensors (vector, matrix) will be interpreted as strings, not tensors if sent in requests. " + - "See https://docs.vespa.ai/en/query-profiles.html", - logger.entries.get(0).message); + "so they have no effect. " + + "In particular, the tensors (vector, matrix) will be interpreted as strings, not tensors if sent in requests. " + + "See https://docs.vespa.ai/en/query-profiles.html", + logger.entries.get(0).message); } protected void assertConfig(String correctFileName, QueryProfileRegistry check) throws IOException { diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/AccessControlTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/AccessControlTest.java index 2f962855470..faeac12f508 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/AccessControlTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/AccessControlTest.java @@ -24,11 +24,11 @@ import com.yahoo.vespa.model.container.http.FilterChains; import com.yahoo.vespa.model.container.http.Http; import com.yahoo.vespa.model.container.http.ssl.HostedSslConnectorFactory; import org.hamcrest.Matchers; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.w3c.dom.Element; +import java.io.File; import java.io.StringReader; import java.time.Duration; import java.util.ArrayList; @@ -40,10 +40,7 @@ import java.util.stream.Collectors; import static com.yahoo.vespa.defaults.Defaults.getDefaults; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsInAnyOrder; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; /** * @author gjoranv @@ -52,11 +49,11 @@ import static org.junit.Assert.fail; */ public class AccessControlTest extends ContainerModelBuilderTestBase { - @Rule - public TemporaryFolder applicationFolder = new TemporaryFolder(); + @TempDir + public File applicationFolder; @Test - public void access_control_filter_chains_are_set_up() { + void access_control_filter_chains_are_set_up() { Http http = createModelAndGetHttp( " <http>", " <filtering>", @@ -71,7 +68,7 @@ public class AccessControlTest extends ContainerModelBuilderTestBase { } @Test - public void properties_are_set_from_xml() { + void properties_are_set_from_xml() { Http http = createModelAndGetHttp( " <http>", " <filtering>", @@ -81,12 +78,12 @@ public class AccessControlTest extends ContainerModelBuilderTestBase { AccessControl accessControl = http.getAccessControl().get(); - assertEquals("Wrong domain.", "my-tenant-domain", accessControl.domain); + assertEquals("my-tenant-domain", accessControl.domain, "Wrong domain."); } @Test - public void access_control_excluded_filter_chain_has_all_bindings_from_excluded_handlers() { + void access_control_excluded_filter_chain_has_all_bindings_from_excluded_handlers() { Http http = createModelAndGetHttp( " <http>", " <filtering>", @@ -108,7 +105,7 @@ public class AccessControlTest extends ContainerModelBuilderTestBase { } @Test - public void access_control_excluded_chain_does_not_contain_any_bindings_from_access_control_chain() { + void access_control_excluded_chain_does_not_contain_any_bindings_from_access_control_chain() { Http http = createModelAndGetHttp( " <http>", " <filtering>", @@ -126,7 +123,7 @@ public class AccessControlTest extends ContainerModelBuilderTestBase { @Test - public void access_control_excluded_filter_chain_has_user_provided_excluded_bindings() { + void access_control_excluded_filter_chain_has_user_provided_excluded_bindings() { Http http = createModelAndGetHttp( " <http>", " <handler id='custom.Handler'>", @@ -147,7 +144,7 @@ public class AccessControlTest extends ContainerModelBuilderTestBase { } @Test - public void hosted_connector_for_port_4443_uses_access_control_filter_chain_as_default_request_filter_chain() { + void hosted_connector_for_port_4443_uses_access_control_filter_chain_as_default_request_filter_chain() { Http http = createModelAndGetHttp( " <http>", " <filtering>", @@ -158,7 +155,7 @@ public class AccessControlTest extends ContainerModelBuilderTestBase { Set<String> actualBindings = getFilterBindings(http, AccessControl.ACCESS_CONTROL_CHAIN_ID); assertTrue(actualBindings.isEmpty()); - HostedSslConnectorFactory hostedConnectorFactory = (HostedSslConnectorFactory)http.getHttpServer().get().getConnectorFactories().stream() + HostedSslConnectorFactory hostedConnectorFactory = (HostedSslConnectorFactory) http.getHttpServer().get().getConnectorFactories().stream() .filter(connectorFactory -> connectorFactory instanceof HostedSslConnectorFactory) .findAny() .get(); @@ -168,7 +165,7 @@ public class AccessControlTest extends ContainerModelBuilderTestBase { } @Test - public void access_control_is_implicitly_added_for_hosted_apps() { + void access_control_is_implicitly_added_for_hosted_apps() { Http http = createModelAndGetHttp("<container version='1.0'/>"); Optional<AccessControl> maybeAccessControl = http.getAccessControl(); assertTrue(maybeAccessControl.isPresent()); @@ -178,7 +175,7 @@ public class AccessControlTest extends ContainerModelBuilderTestBase { } @Test - public void access_control_is_implicitly_added_for_hosted_apps_with_existing_http_element() { + void access_control_is_implicitly_added_for_hosted_apps_with_existing_http_element() { Http http = createModelAndGetHttp( " <http>", " <server port='" + getDefaults().vespaWebServicePort() + "' id='main' />", @@ -195,7 +192,7 @@ public class AccessControlTest extends ContainerModelBuilderTestBase { } @Test - public void access_control_chain_exclude_chain_does_not_contain_duplicate_bindings_to_user_request_filter_chain() { + void access_control_chain_exclude_chain_does_not_contain_duplicate_bindings_to_user_request_filter_chain() { Http http = createModelAndGetHttp( " <http>", " <handler id='custom.Handler'>", @@ -228,7 +225,7 @@ public class AccessControlTest extends ContainerModelBuilderTestBase { } @Test - public void access_control_excludes_are_not_affected_by_user_response_filter_chain() { + void access_control_excludes_are_not_affected_by_user_response_filter_chain() { Http http = createModelAndGetHttp( " <http>", " <handler id='custom.Handler'>", @@ -265,7 +262,7 @@ public class AccessControlTest extends ContainerModelBuilderTestBase { } @Test - public void access_control_client_auth_defaults_to_need() { + void access_control_client_auth_defaults_to_need() { Http http = createModelAndGetHttp( " <http>", " <filtering>", @@ -277,7 +274,7 @@ public class AccessControlTest extends ContainerModelBuilderTestBase { } @Test - public void access_control_client_auth_can_be_overridden() { + void access_control_client_auth_can_be_overridden() { AthenzDomain tenantDomain = AthenzDomain.from("my-tenant-domain"); DeployState state = new DeployState.Builder().properties( new TestProperties() @@ -286,17 +283,17 @@ public class AccessControlTest extends ContainerModelBuilderTestBase { .allowDisableMtls(true)) .build(); Http http = createModelAndGetHttp(state, - " <http>", - " <filtering>", - " <access-control tls-handshake-client-auth=\"want\"/>", - " </filtering>", - " </http>"); + " <http>", + " <filtering>", + " <access-control tls-handshake-client-auth=\"want\"/>", + " </filtering>", + " </http>"); assertTrue(http.getAccessControl().isPresent()); assertEquals(AccessControl.ClientAuthentication.want, http.getAccessControl().get().clientAuthentication); } @Test - public void access_control_client_auth_cannot_be_overridden_when_disabled() { + void access_control_client_auth_cannot_be_overridden_when_disabled() { AthenzDomain tenantDomain = AthenzDomain.from("my-tenant-domain"); DeployState state = new DeployState.Builder().properties( new TestProperties() @@ -307,11 +304,11 @@ public class AccessControlTest extends ContainerModelBuilderTestBase { try { Http http = createModelAndGetHttp(state, - " <http>", - " <filtering>", - " <access-control tls-handshake-client-auth=\"want\"/>", - " </filtering>", - " </http>"); + " <http>", + " <filtering>", + " <access-control tls-handshake-client-auth=\"want\"/>", + " </filtering>", + " </http>"); fail("Overriding tls-handshake-client-auth allowed, but should have failed"); } catch (IllegalArgumentException e) { assertEquals("Overriding 'tls-handshake-client-auth' for application is not allowed.", e.getMessage()); @@ -319,7 +316,7 @@ public class AccessControlTest extends ContainerModelBuilderTestBase { } @Test - public void local_connector_has_default_chain() { + void local_connector_has_default_chain() { Http http = createModelAndGetHttp( " <http>", " <filtering>", @@ -341,22 +338,22 @@ public class AccessControlTest extends ContainerModelBuilderTestBase { } @Test - public void client_authentication_is_enforced() { + void client_authentication_is_enforced() { Element clusterElem = DomBuilderTest.parse( "<container version='1.0'>", nodesXml, " <http><filtering>" + " <access-control domain=\"vespa\" tls-handshake-client-auth=\"need\"/>" + " </filtering></http>" + - "</container>" ); + "</container>"); DeployState state = new DeployState.Builder().properties( - new TestProperties() - .setHostedVespa(true) - .setEndpointCertificateSecrets(Optional.of(new EndpointCertificateSecrets("CERT", "KEY")))) + new TestProperties() + .setHostedVespa(true) + .setEndpointCertificateSecrets(Optional.of(new EndpointCertificateSecrets("CERT", "KEY")))) .build(); createModel(root, state, null, clusterElem); - ApplicationContainer container = (ApplicationContainer)root.getProducer("container/container.0"); + ApplicationContainer container = (ApplicationContainer) root.getProducer("container/container.0"); List<ConnectorFactory> connectorFactories = container.getHttp().getHttpServer().get().getConnectorFactories(); ConnectorFactory tlsPort = connectorFactories.stream().filter(connectorFactory -> connectorFactory.getListenPort() == 4443).findFirst().orElseThrow(); @@ -371,14 +368,14 @@ public class AccessControlTest extends ContainerModelBuilderTestBase { assertEquals("KEY", connectorConfig.ssl().privateKey()); assertEquals(4443, connectorConfig.listenPort()); - assertEquals("Connector must use Athenz truststore in a non-public system.", - "/opt/yahoo/share/ssl/certs/athenz_certificate_bundle.pem", - connectorConfig.ssl().caCertificateFile()); + assertEquals("/opt/yahoo/share/ssl/certs/athenz_certificate_bundle.pem", + connectorConfig.ssl().caCertificateFile(), + "Connector must use Athenz truststore in a non-public system."); assertTrue(connectorConfig.ssl().caCertificate().isEmpty()); } @Test - public void missing_security_clients_pem_fails_in_public() { + void missing_security_clients_pem_fails_in_public() { Element clusterElem = DomBuilderTest.parse("<container version='1.0' />"); try { @@ -392,16 +389,16 @@ public class AccessControlTest extends ContainerModelBuilderTestBase { createModel(root, state, null, clusterElem); } catch (RuntimeException e) { assertEquals("Client certificate authority security/clients.pem is missing - see: https://cloud.vespa.ai/en/security-model#data-plane", - e.getMessage()); + e.getMessage()); return; } fail(); } @Test - public void security_clients_pem_is_picked_up() { + void security_clients_pem_is_picked_up() { var applicationPackage = new MockApplicationPackage.Builder() - .withRoot(applicationFolder.getRoot()) + .withRoot(applicationFolder) .build(); applicationPackage.getFile(Path.fromString("security")).createDirectory(); @@ -416,9 +413,9 @@ public class AccessControlTest extends ContainerModelBuilderTestBase { } @Test - public void operator_certificates_are_joined_with_clients_pem() { + void operator_certificates_are_joined_with_clients_pem() { var applicationPackage = new MockApplicationPackage.Builder() - .withRoot(applicationFolder.getRoot()) + .withRoot(applicationFolder) .build(); var applicationTrustCert = X509CertificateUtils.toPem( @@ -429,10 +426,10 @@ public class AccessControlTest extends ContainerModelBuilderTestBase { applicationPackage.getFile(Path.fromString("security/clients.pem")).writeFile(new StringReader(applicationTrustCert)); var deployState = new DeployState.Builder().properties( - new TestProperties() - .setOperatorCertificates(List.of(operatorCert)) - .setHostedVespa(true) - .setEndpointCertificateSecrets(Optional.of(new EndpointCertificateSecrets("CERT", "KEY")))) + new TestProperties() + .setOperatorCertificates(List.of(operatorCert)) + .setHostedVespa(true) + .setEndpointCertificateSecrets(Optional.of(new EndpointCertificateSecrets("CERT", "KEY")))) .zone(new Zone(SystemName.PublicCd, Environment.dev, RegionName.defaultName())) .applicationPackage(applicationPackage) .build(); @@ -441,7 +438,7 @@ public class AccessControlTest extends ContainerModelBuilderTestBase { createModel(root, deployState, null, clusterElem); - ApplicationContainer container = (ApplicationContainer)root.getProducer("container/container.0"); + ApplicationContainer container = (ApplicationContainer) root.getProducer("container/container.0"); List<ConnectorFactory> connectorFactories = container.getHttp().getHttpServer().get().getConnectorFactories(); ConnectorFactory tlsPort = connectorFactories.stream().filter(connectorFactory -> connectorFactory.getListenPort() == 4443).findFirst().orElseThrow(); @@ -458,15 +455,15 @@ public class AccessControlTest extends ContainerModelBuilderTestBase { } @Test - public void require_allowed_ciphers() { + void require_allowed_ciphers() { Element clusterElem = DomBuilderTest.parse( "<container version='1.0'>", nodesXml, - "</container>" ); + "</container>"); DeployState state = new DeployState.Builder().properties(new TestProperties().setHostedVespa(true).setEndpointCertificateSecrets(Optional.of(new EndpointCertificateSecrets("CERT", "KEY")))).build(); createModel(root, state, null, clusterElem); - ApplicationContainer container = (ApplicationContainer)root.getProducer("container/container.0"); + ApplicationContainer container = (ApplicationContainer) root.getProducer("container/container.0"); List<ConnectorFactory> connectorFactories = container.getHttp().getHttpServer().get().getConnectorFactories(); ConnectorFactory tlsPort = connectorFactories.stream().filter(connectorFactory -> connectorFactory.getListenPort() == 4443).findFirst().orElseThrow(); @@ -479,15 +476,15 @@ public class AccessControlTest extends ContainerModelBuilderTestBase { } @Test - public void providing_endpoint_certificate_secrets_opens_port_4443() { + void providing_endpoint_certificate_secrets_opens_port_4443() { Element clusterElem = DomBuilderTest.parse( "<container version='1.0'>", nodesXml, - "</container>" ); + "</container>"); DeployState state = new DeployState.Builder().properties(new TestProperties().setHostedVespa(true).setEndpointCertificateSecrets(Optional.of(new EndpointCertificateSecrets("CERT", "KEY")))).build(); createModel(root, state, null, clusterElem); - ApplicationContainer container = (ApplicationContainer)root.getProducer("container/container.0"); + ApplicationContainer container = (ApplicationContainer) root.getProducer("container/container.0"); // Verify that there are two connectors List<ConnectorFactory> connectorFactories = container.getHttp().getHttpServer().get().getConnectorFactories(); @@ -510,9 +507,9 @@ public class AccessControlTest extends ContainerModelBuilderTestBase { assertEquals("KEY", connectorConfig.ssl().privateKey()); assertEquals(4443, connectorConfig.listenPort()); - assertEquals("Connector must use Athenz truststore in a non-public system.", - "/opt/yahoo/share/ssl/certs/athenz_certificate_bundle.pem", - connectorConfig.ssl().caCertificateFile()); + assertEquals("/opt/yahoo/share/ssl/certs/athenz_certificate_bundle.pem", + connectorConfig.ssl().caCertificateFile(), + "Connector must use Athenz truststore in a non-public system."); assertTrue(connectorConfig.ssl().caCertificate().isEmpty()); } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/AccessLogTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/AccessLogTest.java index d9659cf92d4..05e83de9157 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/AccessLogTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/AccessLogTest.java @@ -17,17 +17,14 @@ import com.yahoo.container.logging.JSONAccessLog; import com.yahoo.container.logging.VespaAccessLog; import com.yahoo.vespa.model.container.ApplicationContainerCluster; import com.yahoo.vespa.model.container.component.Component; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.w3c.dom.Element; import java.util.logging.Level; import static com.yahoo.config.model.test.TestUtil.joinLines; import static com.yahoo.text.StringUtilities.quote; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.*; /** * @author gjoranv @@ -35,13 +32,13 @@ import static org.junit.Assert.assertNull; public class AccessLogTest extends ContainerModelBuilderTestBase { @Test - public void default_access_log_is_added_by_default() { + void default_access_log_is_added_by_default() { Element cluster1Elem = DomBuilderTest.parse( "<container id='cluster1' version='1.0'>", " <nodes>", " <node hostalias='mockhost' baseport='1234' />", " </nodes>", - "</container>" ); + "</container>"); createModel(root, cluster1Elem); @@ -50,14 +47,14 @@ public class AccessLogTest extends ContainerModelBuilderTestBase { } @Test - public void default_search_access_log_can_be_disabled() { + void default_search_access_log_can_be_disabled() { final String jdiscClusterId = "jdisc-cluster"; Element clusterElem = DomBuilderTest.parse( "<container id=" + quote(jdiscClusterId) + " version='1.0'>" + " <search />" + " <accesslog type='disabled' />" + - "</container>" ); + "</container>"); createModel(root, clusterElem); assertNull(getVespaAccessLog(jdiscClusterId)); @@ -74,7 +71,7 @@ public class AccessLogTest extends ContainerModelBuilderTestBase { } @Test - public void access_log_can_be_configured() { + void access_log_can_be_configured() { Element clusterElem = DomBuilderTest.parse( "<container id='default' version='1.0'>", " <accesslog type='vespa' ", @@ -82,7 +79,7 @@ public class AccessLogTest extends ContainerModelBuilderTestBase { " <accesslog type='json' ", " fileNamePattern='pattern' rotationInterval='interval' queueSize='17' bufferSize='65536'/>", nodesXml, - "</container>" ); + "</container>"); createModel(root, clusterElem); assertNotNull(getJsonAccessLog("default")); @@ -91,19 +88,19 @@ public class AccessLogTest extends ContainerModelBuilderTestBase { { // vespa Component<?, ?> accessLogComponent = getComponent("default", VespaAccessLog.class.getName()); assertNotNull(accessLogComponent); - assertEquals(VespaAccessLog.class.getName(), accessLogComponent.getClassId().getName(), VespaAccessLog.class.getName()); + assertEquals(accessLogComponent.getClassId().getName(), VespaAccessLog.class.getName(), VespaAccessLog.class.getName()); AccessLogConfig config = root.getConfig(AccessLogConfig.class, "default/component/com.yahoo.container.logging.VespaAccessLog"); AccessLogConfig.FileHandler fileHandlerConfig = config.fileHandler(); assertEquals("pattern", fileHandlerConfig.pattern()); assertEquals("interval", fileHandlerConfig.rotation()); assertEquals(256, fileHandlerConfig.queueSize()); - assertEquals(256*1024, fileHandlerConfig.bufferSize()); + assertEquals(256 * 1024, fileHandlerConfig.bufferSize()); } { // json Component<?, ?> accessLogComponent = getComponent("default", JSONAccessLog.class.getName()); assertNotNull(accessLogComponent); - assertEquals(JSONAccessLog.class.getName(), accessLogComponent.getClassId().getName(), JSONAccessLog.class.getName()); + assertEquals(accessLogComponent.getClassId().getName(), JSONAccessLog.class.getName(), JSONAccessLog.class.getName()); AccessLogConfig config = root.getConfig(AccessLogConfig.class, "default/component/com.yahoo.container.logging.JSONAccessLog"); AccessLogConfig.FileHandler fileHandlerConfig = config.fileHandler(); assertEquals("pattern", fileHandlerConfig.pattern()); @@ -114,7 +111,7 @@ public class AccessLogTest extends ContainerModelBuilderTestBase { } @Test - public void connection_log_configured_when_access_log_not_disabled() { + void connection_log_configured_when_access_log_not_disabled() { Element clusterElem = DomBuilderTest.parse( "<container id='default' version='1.0'>", " <accesslog type='vespa' ", @@ -122,41 +119,41 @@ public class AccessLogTest extends ContainerModelBuilderTestBase { " <accesslog type='json' ", " fileNamePattern='pattern' rotationInterval='interval' />", nodesXml, - "</container>" ); + "</container>"); createModel(root, clusterElem); Component<?, ?> connectionLogComponent = getComponent("default", FileConnectionLog.class.getName()); assertNotNull(connectionLogComponent); ConnectionLogConfig config = root.getConfig(ConnectionLogConfig.class, "default/component/com.yahoo.container.logging.FileConnectionLog"); assertEquals("default", config.cluster()); assertEquals(-1, config.queueSize()); - assertEquals(256*1024, config.bufferSize()); + assertEquals(256 * 1024, config.bufferSize()); } @Test - public void connection_log_disabled_when_access_log_disabled() { + void connection_log_disabled_when_access_log_disabled() { Element clusterElem = DomBuilderTest.parse( "<container id='default' version='1.0'>", " <accesslog type='disabled' />", nodesXml, - "</container>" ); + "</container>"); createModel(root, clusterElem); Component<?, ?> fileConnectionLogComponent = getComponent("default", FileConnectionLog.class.getName()); assertNull(fileConnectionLogComponent); } @Test - public void hosted_applications_get_a_log_warning_when_overriding_accesslog() { + void hosted_applications_get_a_log_warning_when_overriding_accesslog() { String containerService = joinLines("<container id='foo' version='1.0'>", - " <accesslog type='json' fileNamePattern='logs/vespa/qrs/access.%Y%m%d%H%M%S' symlinkName='json_access' />", - " <nodes count=\"2\">", - " </nodes>", - "</container>"); + " <accesslog type='json' fileNamePattern='logs/vespa/qrs/access.%Y%m%d%H%M%S' symlinkName='json_access' />", + " <nodes count=\"2\">", + " </nodes>", + "</container>"); String deploymentXml = joinLines("<deployment version='1.0'>", - " <prod>", - " <region>us-east-1</region>", - " </prod>", - "</deployment>"); + " <prod>", + " <region>us-east-1</region>", + " </prod>", + "</deployment>"); ApplicationPackage applicationPackage = new MockApplicationPackage.Builder() .withServices(containerService) @@ -174,7 +171,7 @@ public class AccessLogTest extends ContainerModelBuilderTestBase { assertFalse(logger.msgs.isEmpty()); assertEquals(Level.WARNING, logger.msgs.get(0).getFirst()); assertEquals("Applications are not allowed to override the 'accesslog' element", - logger.msgs.get(0).getSecond()); + logger.msgs.get(0).getSecond()); } } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/BundleInstantiationSpecificationBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/BundleInstantiationSpecificationBuilderTest.java index 125f1823fec..afcb9caa805 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/BundleInstantiationSpecificationBuilderTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/BundleInstantiationSpecificationBuilderTest.java @@ -6,12 +6,12 @@ import com.yahoo.config.model.builder.xml.XmlHelper; import com.yahoo.container.bundle.BundleInstantiationSpecification; import com.yahoo.search.grouping.GroupingValidator; import com.yahoo.vespa.model.container.PlatformBundles; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.w3c.dom.Element; import java.io.StringReader; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author gjoranv @@ -21,19 +21,19 @@ import static org.junit.Assert.assertEquals; public class BundleInstantiationSpecificationBuilderTest { @Test - public void bundle_is_not_replaced_for_user_defined_class() { + void bundle_is_not_replaced_for_user_defined_class() { final String userDefinedClass = "my own class that will also be set as bundle"; verifyExpectedBundle(userDefinedClass, null, userDefinedClass); } @Test - public void bundle_is_replaced_for_internal_class() { + void bundle_is_replaced_for_internal_class() { String internalClass = GroupingValidator.class.getName(); verifyExpectedBundle(internalClass, null, PlatformBundles.SEARCH_AND_DOCPROC_BUNDLE); } @Test - public void bundle_is_not_replaced_for_internal_class_with_explicitly_set_bundle() { + void bundle_is_not_replaced_for_internal_class_with_explicitly_set_bundle() { String internalClass = GroupingValidator.class.getName(); String explicitBundle = "my-own-implementation"; verifyExpectedBundle(internalClass, explicitBundle, explicitBundle); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/ContainerDocumentApiBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/ContainerDocumentApiBuilderTest.java index 4a9d44ea2f8..3c68a77f2ad 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/ContainerDocumentApiBuilderTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/ContainerDocumentApiBuilderTest.java @@ -11,7 +11,7 @@ import com.yahoo.vespa.model.container.ContainerModel; import com.yahoo.vespa.model.container.component.Handler; import com.yahoo.vespa.model.container.component.SystemBindingPattern; import com.yahoo.vespa.model.container.component.UserBindingPattern; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.w3c.dom.Element; import java.util.Collection; @@ -19,10 +19,7 @@ import java.util.HashMap; import java.util.Map; import java.util.Set; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * @author Einar M R Rosenvinge @@ -42,7 +39,7 @@ public class ContainerDocumentApiBuilderTest extends ContainerModelBuilderTestBa } @Test - public void custom_bindings_are_allowed() { + void custom_bindings_are_allowed() { Element elem = DomBuilderTest.parse( "<container id='cluster1' version='1.0'>", " <document-api>", @@ -65,7 +62,7 @@ public class ContainerDocumentApiBuilderTest extends ContainerModelBuilderTestBa } @Test - public void test_handler_setup() { + void test_handler_setup() { Element elem = DomBuilderTest.parse( "<container id='cluster1' version='1.0'>", " <document-api />", @@ -88,14 +85,14 @@ public class ContainerDocumentApiBuilderTest extends ContainerModelBuilderTestBa } @Test - public void nonexisting_fields_can_be_ignored() { + void nonexisting_fields_can_be_ignored() { Element elem = DomBuilderTest.parse( "<container id='cluster1' version='1.0'>", " <document-api>" + - " <ignore-undefined-fields>true</ignore-undefined-fields>" + - nodesXml, + " <ignore-undefined-fields>true</ignore-undefined-fields>" + + nodesXml, " </document-api>" + - "</container>"); + "</container>"); ContainerModel model = createModel(root, elem).get(0); var documentManager = new DocumentmanagerConfig.Builder(); @@ -104,7 +101,7 @@ public class ContainerDocumentApiBuilderTest extends ContainerModelBuilderTestBa } @Test - public void feeding_api_have_separate_threadpools() { + void feeding_api_have_separate_threadpools() { Element elem = DomBuilderTest.parse( "<container id='cluster1' version='1.0'>", " <document-api />", @@ -124,7 +121,7 @@ public class ContainerDocumentApiBuilderTest extends ContainerModelBuilderTestBa } @Test - public void threadpools_configuration_can_be_overridden() { + void threadpools_configuration_can_be_overridden() { Element elem = DomBuilderTest.parse( "<container id='cluster1' version='1.0'>", " <document-api>", diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/ContainerModelBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/ContainerModelBuilderTest.java index 1d43c031a1b..4d9bd978883 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/ContainerModelBuilderTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/ContainerModelBuilderTest.java @@ -46,7 +46,7 @@ import com.yahoo.vespa.model.container.component.Handler; import com.yahoo.vespa.model.content.utils.ContentClusterUtils; import com.yahoo.vespa.model.test.VespaModelTester; import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithFilePkg; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.w3c.dom.Element; import org.xml.sax.SAXException; @@ -66,12 +66,7 @@ import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; /** * Tests for "core functionality" of the container model, e.g. ports, or the 'components' and 'bundles' configs. @@ -84,7 +79,7 @@ import static org.junit.Assert.fail; public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase { @Test - public void model_evaluation_bundles_are_deployed() { + void model_evaluation_bundles_are_deployed() { createBasicContainerModel(); PlatformBundlesConfig config = root.getConfig(PlatformBundlesConfig.class, "default"); assertTrue(config.bundlePaths().contains(ContainerModelEvaluation.MODEL_EVALUATION_BUNDLE_FILE.toString())); @@ -92,79 +87,79 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase { } @Test - public void default_port_is_4080() { + void default_port_is_4080() { Element clusterElem = DomBuilderTest.parse( "<container version='1.0'>", - nodesXml, - "</container>" ); + nodesXml, + "</container>"); createModel(root, clusterElem); - AbstractService container = (AbstractService)root.getProducer("container/container.0"); + AbstractService container = (AbstractService) root.getProducer("container/container.0"); assertEquals(getDefaults().vespaWebServicePort(), container.getRelativePort(0)); } @Test - public void http_server_port_is_configurable_and_does_not_affect_other_ports() { + void http_server_port_is_configurable_and_does_not_affect_other_ports() { Element clusterElem = DomBuilderTest.parse( "<container version='1.0'>", " <http>", " <server port='9000' id='foo' />", " </http>", - nodesXml, - "</container>" ); + nodesXml, + "</container>"); createModel(root, clusterElem); - AbstractService container = (AbstractService)root.getProducer("container/container.0"); + AbstractService container = (AbstractService) root.getProducer("container/container.0"); assertEquals(9000, container.getRelativePort(0)); assertNotEquals(9001, container.getRelativePort(1)); } @Test - public void omitting_http_server_port_gives_default() { + void omitting_http_server_port_gives_default() { Element clusterElem = DomBuilderTest.parse( "<container version='1.0'>", " <http>", " <server id='foo'/>", " </http>", nodesXml, - "</container>" ); + "</container>"); createModel(root, clusterElem); - AbstractService container = (AbstractService)root.getProducer("container/container.0"); + AbstractService container = (AbstractService) root.getProducer("container/container.0"); assertEquals(Defaults.getDefaults().vespaWebServicePort(), container.getRelativePort(0)); } @Test - public void fail_if_http_port_is_not_default_in_hosted_vespa() throws Exception { + void fail_if_http_port_is_not_default_in_hosted_vespa() throws Exception { try { String servicesXml = "<services>" + - "<admin version='3.0'>" + - " <nodes count='1'/>" + - "</admin>" + - "<container version='1.0'>" + - " <http>" + - " <server port='9000' id='foo' />" + - " </http>" + - nodesXml + - "</container>" + - "</services>"; + "<admin version='3.0'>" + + " <nodes count='1'/>" + + "</admin>" + + "<container version='1.0'>" + + " <http>" + + " <server port='9000' id='foo' />" + + " </http>" + + nodesXml + + "</container>" + + "</services>"; ApplicationPackage applicationPackage = new MockApplicationPackage.Builder().withServices(servicesXml).build(); // Need to create VespaModel to make deploy properties have effect TestLogger logger = new TestLogger(); new VespaModel(new NullConfigModelRegistry(), new DeployState.Builder() - .applicationPackage(applicationPackage) - .deployLogger(logger) - .properties(new TestProperties().setHostedVespa(true)) - .build()); + .applicationPackage(applicationPackage) + .deployLogger(logger) + .properties(new TestProperties().setHostedVespa(true)) + .build()); fail("Expected exception"); } catch (IllegalArgumentException e) { // Success assertEquals("Illegal port 9000 in http server 'foo': Port must be set to " + Defaults.getDefaults().vespaWebServicePort(), - e.getMessage()); + e.getMessage()); } } @Test - public void one_cluster_with_explicit_port_and_one_without_is_ok() { + void one_cluster_with_explicit_port_and_one_without_is_ok() { Element cluster1Elem = DomBuilderTest.parse( "<container id='cluster1' version='1.0' />"); Element cluster2Elem = DomBuilderTest.parse( @@ -177,15 +172,15 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase { } @Test - public void two_clusters_without_explicit_port_throws_exception() { + void two_clusters_without_explicit_port_throws_exception() { Element cluster1Elem = DomBuilderTest.parse( "<container id='cluster1' version='1.0'>", - nodesXml, - "</container>" ); + nodesXml, + "</container>"); Element cluster2Elem = DomBuilderTest.parse( "<container id='cluster2' version='1.0'>", - nodesXml, - "</container>" ); + nodesXml, + "</container>"); try { createModel(root, cluster1Elem, cluster2Elem); fail("Expected exception"); @@ -195,7 +190,7 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase { } @Test - public void builtin_handlers_get_default_threadpool() { + void builtin_handlers_get_default_threadpool() { createBasicContainerModel(); Handler h1 = getHandler("default", ApplicationStatusHandler.class.getName()); @@ -206,7 +201,7 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase { } @Test - public void verify_bindings_for_builtin_handlers() { + void verify_bindings_for_builtin_handlers() { createBasicContainerModel(); JdiscBindingsConfig config = root.getConfig(JdiscBindingsConfig.class, "default/container.0"); @@ -224,7 +219,7 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase { } @Test - public void processing_handler_bindings_can_be_overridden() { + void processing_handler_bindings_can_be_overridden() { Element clusterElem = DomBuilderTest.parse( "<container id='default' version='1.0'>", " <processing>", @@ -242,11 +237,11 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase { } @Test - public void serverProviders_are_included_in_components_config() { + void serverProviders_are_included_in_components_config() { Element clusterElem = DomBuilderTest.parse( "<container id='default' version='1.0'>" + - " <server id='discServer' />" + - "</container>" ); + " <server id='discServer' />" + + "</container>"); createModel(root, clusterElem); @@ -259,7 +254,7 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase { } @Test - public void searchHandler_gets_only_search_chains_in_chains_config() { + void searchHandler_gets_only_search_chains_in_chains_config() { createClusterWithProcessingAndSearchChains(); String searchHandlerConfigId = "default/component/com.yahoo.search.handler.SearchHandler"; String chainsConfig = getChainsConfig(searchHandlerConfigId); @@ -268,7 +263,7 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase { } @Test - public void processingHandler_gets_only_processing_chains_in_chains_config() { + void processingHandler_gets_only_processing_chains_in_chains_config() { createClusterWithProcessingAndSearchChains(); String processingHandlerConfigId = "default/component/" + PROCESSING_HANDLER_CLASS; String chainsConfig = getChainsConfig(processingHandlerConfigId); @@ -277,7 +272,7 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase { } @Test - public void processingHandler_is_instantiated_from_the_default_bundle() { + void processingHandler_is_instantiated_from_the_default_bundle() { createClusterWithProcessingAndSearchChains(); ComponentsConfig.Components config = getComponentInConfig(componentsConfig(), PROCESSING_HANDLER_CLASS); assertEquals(PROCESSING_HANDLER_CLASS, config.bundle()); @@ -303,13 +298,13 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase { } @Test - public void user_config_can_be_overridden_on_node() { + void user_config_can_be_overridden_on_node() { Element containerElem = DomBuilderTest.parse( "<container id='default' version='1.0'>", " <config name=\"prelude.cluster.qr-monitor\">" + - " <requesttimeout>111</requesttimeout>", + " <requesttimeout>111</requesttimeout>", " </config> " + - " <nodes>", + " <nodes>", " <node hostalias='host1' />", " <node hostalias='host2'>", " <config name=\"prelude.cluster.qr-monitor\">", @@ -321,25 +316,25 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase { root = ContentClusterUtils.createMockRoot(new String[]{"host1", "host2"}); createModel(root, containerElem); - ContainerCluster cluster = (ContainerCluster)root.getChildren().get("default"); + ContainerCluster cluster = (ContainerCluster) root.getChildren().get("default"); assertEquals(2, cluster.getContainers().size()); assertEquals(root.getConfig(QrMonitorConfig.class, "default/container.0").requesttimeout(), 111); assertEquals(root.getConfig(QrMonitorConfig.class, "default/container.1").requesttimeout(), 222); } @Test - public void component_includes_are_added() { + void component_includes_are_added() { VespaModelCreatorWithFilePkg creator = new VespaModelCreatorWithFilePkg("src/test/cfg/application/include_dirs"); VespaModel model = creator.create(true); ContainerCluster cluster = model.getContainerClusters().get("default"); Map<ComponentId, Component<?, ?>> componentsMap = cluster.getComponentsMap(); - Component<?,?> example = componentsMap.get( + Component<?, ?> example = componentsMap.get( ComponentId.fromString("test.Exampledocproc")); assertEquals("test.Exampledocproc", example.getComponentId().getName()); } @Test - public void affinity_is_set() { + void affinity_is_set() { Element clusterElem = DomBuilderTest.parse( "<container id='default' version='1.0'>", " <http>", @@ -348,14 +343,14 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase { " <nodes cpu-socket-affinity='true'>", " <node hostalias='node1' />", " </nodes>" + - "</container>"); + "</container>"); createModel(root, clusterElem); assertTrue(getContainerCluster("default").getContainers().get(0).getAffinity().isPresent()); assertEquals(0, getContainerCluster("default").getContainers().get(0).getAffinity().get().cpuSocket()); } @Test - public void singlenode_servicespec_is_used_with_hosts_xml() throws IOException, SAXException { + void singlenode_servicespec_is_used_with_hosts_xml() throws IOException, SAXException { String servicesXml = "<container id='default' version='1.0' />"; String hostsXml = "<hosts>\n" + " <host name=\"test1.yahoo.com\">\n" + @@ -371,7 +366,7 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase { } @Test - public void endpoints_are_added_to_containers() throws IOException, SAXException { + void endpoints_are_added_to_containers() throws IOException, SAXException { final var servicesXml = joinLines("", "<container id='comics-search' version='1.0'>", " <nodes>", @@ -403,7 +398,7 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase { .flatMap(cluster -> cluster.getContainers().stream()) .collect(Collectors.toList()); - assertFalse("Missing container objects based on configuration", containers.isEmpty()); + assertFalse(containers.isEmpty(), "Missing container objects based on configuration"); containers.forEach(container -> { final var rotations = container.getServicePropertyString("rotations").split(","); @@ -413,7 +408,7 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase { } @Test - public void singlenode_servicespec_is_used_with_hosted_vespa() throws IOException, SAXException { + void singlenode_servicespec_is_used_with_hosted_vespa() throws IOException, SAXException { String servicesXml = "<container id='default' version='1.0' />"; ApplicationPackage applicationPackage = new MockApplicationPackage.Builder().withServices(servicesXml).build(); VespaModel model = new VespaModel(new NullConfigModelRegistry(), new DeployState.Builder() @@ -426,23 +421,27 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase { assertEquals(2, model.hostSystem().getHosts().size()); } - @Test(expected = IllegalArgumentException.class) - public void renderers_named_JsonRenderer_are_not_allowed() { - createModel(root, generateContainerElementWithRenderer("JsonRenderer")); + @Test + void renderers_named_JsonRenderer_are_not_allowed() { + assertThrows(IllegalArgumentException.class, () -> { + createModel(root, generateContainerElementWithRenderer("JsonRenderer")); + }); } - @Test(expected = IllegalArgumentException.class) - public void renderers_named_DefaultRenderer_are_not_allowed() { - createModel(root, generateContainerElementWithRenderer("XmlRenderer")); + @Test + void renderers_named_DefaultRenderer_are_not_allowed() { + assertThrows(IllegalArgumentException.class, () -> { + createModel(root, generateContainerElementWithRenderer("XmlRenderer")); + }); } @Test - public void renderers_named_something_else_are_allowed() { + void renderers_named_something_else_are_allowed() { createModel(root, generateContainerElementWithRenderer("my-little-renderer")); } @Test - public void vip_status_handler_uses_file_for_hosted_vespa() throws Exception { + void vip_status_handler_uses_file_for_hosted_vespa() throws Exception { String servicesXml = "<services>" + "<container version='1.0'>" + nodesXml + @@ -462,7 +461,7 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase { } @Test - public void qrconfig_is_produced() throws IOException, SAXException { + void qrconfig_is_produced() throws IOException, SAXException { QrConfig qr = getQrConfig(new TestProperties()); String hostname = HostName.getLocalhost(); // Using the same way of getting hostname as filedistribution model assertEquals("default.container.0", qr.discriminator()); @@ -501,14 +500,14 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase { } @Test - public void control_container_shutdown() throws IOException, SAXException { + void control_container_shutdown() throws IOException, SAXException { QrConfig qr = getQrConfig(new TestProperties().containerShutdownTimeout(133).containerDumpHeapOnShutdownTimeout(true)); assertEquals(133.0, qr.shutdown().timeout(), 0.00000000000001); assertTrue(qr.shutdown().dumpHeapOnTimeout()); } @Test - public void environment_vars_are_honoured() { + void environment_vars_are_honoured() { Element clusterElem = DomBuilderTest.parse( "<container version='1.0'>", " <nodes>", @@ -518,7 +517,7 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase { " </environment-variables>", " <node hostalias='mockhost'/>", " </nodes>", - "</container>" ); + "</container>"); createModel(root, clusterElem); QrStartConfig.Builder qrStartBuilder = new QrStartConfig.Builder(); root.getConfig(qrStartBuilder, "container/container.0"); @@ -550,26 +549,26 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase { } @Test - public void requireThatAvailableProcessorsFollowFlavor() { - verifyAvailableprocessors(false, null,0); - verifyAvailableprocessors(true, null,0); + void requireThatAvailableProcessorsFollowFlavor() { + verifyAvailableprocessors(false, null, 0); + verifyAvailableprocessors(true, null, 0); verifyAvailableprocessors(true, new Flavor(new FlavorsConfig.Flavor.Builder().name("test-flavor").minCpuCores(9).build()), 9); verifyAvailableprocessors(true, new Flavor(new FlavorsConfig.Flavor.Builder().name("test-flavor").minCpuCores(1).build()), 2); } @Test - public void cluster_with_zookeeper() { + void cluster_with_zookeeper() { Function<Integer, String> servicesXml = (nodeCount) -> "<container version='1.0' id='default'>" + - "<nodes count='" + nodeCount + "'/>" + - "<zookeeper/>" + - "</container>"; + "<nodes count='" + nodeCount + "'/>" + + "<zookeeper/>" + + "</container>"; VespaModelTester tester = new VespaModelTester(); tester.addHosts(3); { VespaModel model = tester.createModel(servicesXml.apply(3), true); ApplicationContainerCluster cluster = model.getContainerClusters().get("default"); assertNotNull(cluster); - assertComponentConfigured(cluster,"com.yahoo.vespa.curator.Curator"); + assertComponentConfigured(cluster, "com.yahoo.vespa.curator.Curator"); cluster.getContainers().forEach(container -> { assertComponentConfigured(container, "com.yahoo.vespa.zookeeper.ReconfigurableVespaZooKeeperServer"); assertComponentConfigured(container, "com.yahoo.vespa.zookeeper.Reconfigurer"); @@ -584,39 +583,41 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase { try { tester.createModel(servicesXml.apply(2), true); fail("Expected exception"); - } catch (IllegalArgumentException ignored) {} + } catch (IllegalArgumentException ignored) { + } } { String xmlWithNodes = "<?xml version='1.0' encoding='utf-8' ?>" + - "<services>" + - " <container version='1.0' id='container1'>" + - " <zookeeper/>" + - " <nodes of='content1'/>" + - " </container>" + - " <content version='1.0' id='content1'>" + - " <nodes count='3'/>" + - " </content>" + - "</services>"; + "<services>" + + " <container version='1.0' id='container1'>" + + " <zookeeper/>" + + " <nodes of='content1'/>" + + " </container>" + + " <content version='1.0' id='content1'>" + + " <nodes count='3'/>" + + " </content>" + + "</services>"; try { tester.createModel(xmlWithNodes, true); fail("Expected exception"); - } catch (IllegalArgumentException ignored) {} + } catch (IllegalArgumentException ignored) { + } } } @Test - public void logs_deployment_spec_deprecations() throws Exception { + void logs_deployment_spec_deprecations() throws Exception { String containerService = joinLines("<container id='foo' version='1.0'>", - " <nodes>", - " <node hostalias='host1' />", - " </nodes>", - "</container>"); + " <nodes>", + " <node hostalias='host1' />", + " </nodes>", + "</container>"); String deploymentXml = joinLines("<deployment version='1.0'>", - " <prod global-service-id='foo'>", - " <region active='true'>us-east-1</region>", - " </prod>", - "</deployment>"); + " <prod global-service-id='foo'>", + " <region active='true'>us-east-1</region>", + " </prod>", + "</deployment>"); ApplicationPackage applicationPackage = new MockApplicationPackage.Builder() .withServices(containerService) @@ -636,9 +637,9 @@ public class ContainerModelBuilderTest extends ContainerModelBuilderTestBase { assertEquals(Level.WARNING, logger.msgs.get(0).getFirst()); assertEquals(Level.WARNING, logger.msgs.get(1).getFirst()); assertEquals("Element 'prod' contains attribute 'global-service-id' deprecated since major version 7. See https://cloud.vespa.ai/en/reference/routing#deprecated-syntax", - logger.msgs.get(0).getSecond()); + logger.msgs.get(0).getSecond()); assertEquals("Element 'region' contains attribute 'active' deprecated since major version 7. See https://cloud.vespa.ai/en/reference/routing#deprecated-syntax", - logger.msgs.get(1).getSecond()); + logger.msgs.get(1).getSecond()); } private void assertComponentConfigured(ApplicationContainer container, String id) { diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/ContainerModelBuilderTestBase.java b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/ContainerModelBuilderTestBase.java index dc831ef863d..9dee99f8f17 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/ContainerModelBuilderTestBase.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/ContainerModelBuilderTestBase.java @@ -15,7 +15,7 @@ import com.yahoo.vespa.model.container.ContainerModel; import com.yahoo.vespa.model.container.component.Component; import com.yahoo.vespa.model.container.component.Handler; import com.yahoo.vespa.model.container.search.ContainerSearch; -import org.junit.Before; +import org.junit.jupiter.api.BeforeEach; import org.w3c.dom.Element; import java.util.ArrayList; @@ -23,7 +23,7 @@ import java.util.Collections; import java.util.List; import java.util.logging.Level; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * Utility functions for testing the ContainerModelBuilder. Note that XML validation will @@ -54,7 +54,7 @@ public abstract class ContainerModelBuilderTestBase { protected MockRoot root; - @Before + @BeforeEach public void prepareTest() { root = new MockRoot("root"); } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/DocprocBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/DocprocBuilderTest.java index eee421e8037..e8703f57fe3 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/DocprocBuilderTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/DocprocBuilderTest.java @@ -15,17 +15,15 @@ import com.yahoo.vespa.model.container.ContainerModel; import com.yahoo.vespa.model.container.docproc.DocprocChain; import com.yahoo.vespa.model.container.docproc.DocumentProcessor; import com.yahoo.vespa.model.container.xml.ContainerModelBuilder.Networking; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.w3c.dom.Element; import java.util.HashMap; import java.util.List; import java.util.Map; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * @author Einar M R Rosenvinge @@ -40,7 +38,7 @@ public class DocprocBuilderTest extends DomBuilderTest { private SchemamappingConfig schemamappingConfig; private QrStartConfig qrStartConfig; - @Before + @BeforeEach public void setupCluster() { ContainerModel model = new ContainerModelBuilder(false, Networking.disable).build(DeployState.createTestState(), null, null, root, servicesXml()); cluster = (ApplicationContainerCluster) model.getCluster(); @@ -72,7 +70,7 @@ public class DocprocBuilderTest extends DomBuilderTest { } @Test - public void testDocprocCluster() { + void testDocprocCluster() { assertEquals("banan", cluster.getName()); List<ApplicationContainer> services = cluster.getContainers(); assertEquals(1, services.size()); @@ -93,13 +91,13 @@ public class DocprocBuilderTest extends DomBuilderTest { } @Test - public void testContainerMbusConfig() { + void testContainerMbusConfig() { assertTrue(containerMbusConfig.port() >= HostPorts.BASE_PORT); assertEquals(300, containerMbusConfig.maxpendingcount()); } @Test - public void testComponentsConfig() { + void testComponentsConfig() { Map<String, ComponentsConfig.Components> components = new HashMap<>(); for (ComponentsConfig.Components component : componentsConfig.components()) { System.err.println(component.id()); @@ -123,12 +121,12 @@ public class DocprocBuilderTest extends DomBuilderTest { assertEquals("banan/docprocchains/chain/chein/component/docproc2", docproc2.configId()); assertEquals("docproc2", docproc2.classId()); assertEquals("docproc2", docproc2.bundle()); -/* - ComponentsConfig.Components health = components.get("com.yahoo.container.jdisc.state.StateHandler"); - assertEquals("com.yahoo.container.jdisc.state.StateHandler", health.id())); - assertEquals("com.yahoo.container.jdisc.state.StateHandler", health.classId()); - assertEquals("com.yahoo.container.jdisc.state.StateHandler", health.bundle())); -*/ + /* + ComponentsConfig.Components health = components.get("com.yahoo.container.jdisc.state.StateHandler"); + assertEquals("com.yahoo.container.jdisc.state.StateHandler", health.id())); + assertEquals("com.yahoo.container.jdisc.state.StateHandler", health.classId()); + assertEquals("com.yahoo.container.jdisc.state.StateHandler", health.bundle())); + */ ComponentsConfig.Components sourceClient = components.get("source@MbusClient"); assertNotNull(sourceClient); assertEquals("com.yahoo.container.jdisc.messagebus.MbusClientProvider", sourceClient.classId()); @@ -141,7 +139,7 @@ public class DocprocBuilderTest extends DomBuilderTest { } @Test - public void testChainsConfig() { + void testChainsConfig() { Map<String, ChainsConfig.Components> components = new HashMap<>(); for (ChainsConfig.Components component : chainsConfig.components()) { components.put(component.id(), component); @@ -176,12 +174,12 @@ public class DocprocBuilderTest extends DomBuilderTest { } @Test - public void testSchemaMappingConfig() { + void testSchemaMappingConfig() { assertTrue(schemamappingConfig.fieldmapping().isEmpty()); } @Test - public void testQrStartConfig() { + void testQrStartConfig() { QrStartConfig.Jvm jvm = qrStartConfig.jvm(); assertTrue(jvm.server()); assertTrue(jvm.verbosegc()); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/EmbedderTestCase.java b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/EmbedderTestCase.java index 0dae86473c8..fcccdcf8f23 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/EmbedderTestCase.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/EmbedderTestCase.java @@ -13,7 +13,7 @@ import com.yahoo.vespa.model.VespaModel; import com.yahoo.vespa.model.container.ApplicationContainerCluster; import com.yahoo.vespa.model.container.component.Component; import com.yahoo.vespa.model.container.xml.embedder.EmbedderConfig; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; @@ -24,8 +24,8 @@ import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; public class EmbedderTestCase { @@ -33,7 +33,7 @@ public class EmbedderTestCase { private static final String PREDEFINED_EMBEDDER_CONFIG = "embedding.bert-base-embedder"; @Test - public void testGenericEmbedConfig() throws IOException, SAXException { + void testGenericEmbedConfig() throws IOException, SAXException { String embedder = "<embedder id=\"test\" class=\"ai.vespa.test\" bundle=\"bundle\" def=\"def.name\">" + " <val>123</val>" + "</embedder>"; @@ -46,7 +46,7 @@ public class EmbedderTestCase { } @Test - public void testGenericEmbedConfigRequiresBundleAndDef() throws IOException, SAXException { + void testGenericEmbedConfigRequiresBundleAndDef() throws IOException, SAXException { assertTransformThrows("<embedder id=\"test\" class=\"ai.vespa.test\"></embedder>", "Embedder configuration requires a bundle name"); assertTransformThrows("<embedder id=\"test\" class=\"ai.vespa.test\" bundle=\"bundle\"></embedder>", @@ -54,7 +54,7 @@ public class EmbedderTestCase { } @Test - public void testPredefinedEmbedConfigSelfHosted() throws IOException, SAXException { + void testPredefinedEmbedConfigSelfHosted() throws IOException, SAXException { assertTransformThrows("<embedder id=\"test\" class=\"" + PREDEFINED_EMBEDDER_CLASS + "\"></embedder>", "Embedder '" + PREDEFINED_EMBEDDER_CLASS + "' requires options for [vocab, model]"); assertTransformThrows("<embedder id=\"test\" class=\"" + PREDEFINED_EMBEDDER_CLASS + "\">" + @@ -99,7 +99,7 @@ public class EmbedderTestCase { } @Test - public void testPredefinedEmbedConfigCloud() throws IOException, SAXException { + void testPredefinedEmbedConfigCloud() throws IOException, SAXException { String embedder = "<embedder id=\"test\" class=\"" + PREDEFINED_EMBEDDER_CLASS + "\" />"; String component = "<component id=\"test\" class=\"" + PREDEFINED_EMBEDDER_CLASS + "\" bundle=\"model-integration\">" + " <config name=\"" + PREDEFINED_EMBEDDER_CONFIG + "\">" + @@ -133,7 +133,7 @@ public class EmbedderTestCase { } @Test - public void testEmbedConfig() throws Exception { + void testEmbedConfig() throws Exception { final String emptyPathFileName = "services.xml"; Path applicationDir = Path.fromString("src/test/cfg/application/embed/"); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/HandlerBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/HandlerBuilderTest.java index 42cda0d8034..291a5f21305 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/HandlerBuilderTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/HandlerBuilderTest.java @@ -7,7 +7,7 @@ import com.yahoo.container.usability.BindingsOverviewHandler; import com.yahoo.vespa.model.container.ApplicationContainerCluster; import com.yahoo.vespa.model.container.component.Component; import com.yahoo.vespa.model.container.component.Handler; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.w3c.dom.Element; import static com.yahoo.vespa.model.container.ContainerCluster.ROOT_HANDLER_BINDING; @@ -16,10 +16,7 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.hasItem; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; /** * Tests for container model building with custom handlers. @@ -29,13 +26,13 @@ import static org.junit.Assert.fail; public class HandlerBuilderTest extends ContainerModelBuilderTestBase { @Test - public void handlers_are_included_in_components_config() { + void handlers_are_included_in_components_config() { createClusterWithJDiscHandler(); assertThat(componentsConfig().toString(), containsString(".id \"discHandler\"")); } @Test - public void handler_bindings_are_included_in_discBindings_config() { + void handler_bindings_are_included_in_discBindings_config() { createClusterWithJDiscHandler(); String discBindingsConfig = root.getConfig(JdiscBindingsConfig.class, "default").toString(); assertThat(discBindingsConfig, containsString(".serverBindings[0] \"http://*/binding0\"")); @@ -43,7 +40,7 @@ public class HandlerBuilderTest extends ContainerModelBuilderTestBase { } @Test - public void nested_components_are_injected_to_handlers() { + void nested_components_are_injected_to_handlers() { Element clusterElem = DomBuilderTest.parse( "<container id='default' version='1.0'>", " <handler id='myHandler'>", @@ -52,12 +49,12 @@ public class HandlerBuilderTest extends ContainerModelBuilderTestBase { "</container>"); createModel(root, clusterElem); - Component<?,?> handler = getComponent("default", "myHandler"); + Component<?, ?> handler = getComponent("default", "myHandler"); assertThat(handler.getInjectedComponentIds(), hasItem("injected@myHandler")); } @Test - public void default_root_handler_binding_can_be_stolen_by_user_configured_handler() { + void default_root_handler_binding_can_be_stolen_by_user_configured_handler() { Element clusterElem = DomBuilderTest.parse( "<container id='default' version='1.0'>" + " <handler id='userRootHandler'>" + @@ -76,7 +73,7 @@ public class HandlerBuilderTest extends ContainerModelBuilderTestBase { } @Test - public void reserved_binding_cannot_be_stolen_by_user_configured_handler() { + void reserved_binding_cannot_be_stolen_by_user_configured_handler() { Element clusterElem = DomBuilderTest.parse( "<container id='default' version='1.0'>" + " <handler id='userHandler'>" + @@ -88,14 +85,14 @@ public class HandlerBuilderTest extends ContainerModelBuilderTestBase { fail("Expected exception when stealing a reserved binding."); } catch (IllegalArgumentException e) { assertThat(e.getMessage(), is("Binding 'http://*/state/v1' is a reserved Vespa binding " + - "and cannot be used by handler: userHandler")); + "and cannot be used by handler: userHandler")); } } @Test - public void custom_handler_gets_default_threadpool() { + void custom_handler_gets_default_threadpool() { createClusterWithJDiscHandler(); - ApplicationContainerCluster cluster = (ApplicationContainerCluster)root.getChildren().get("default"); + ApplicationContainerCluster cluster = (ApplicationContainerCluster) root.getChildren().get("default"); Handler handler = cluster.getHandlers().stream() .filter(h -> h.getComponentId().toString().equals("discHandler")) .findAny().orElseThrow(); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/IdentityBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/IdentityBuilderTest.java index 73bef70910d..78269d00cf3 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/IdentityBuilderTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/IdentityBuilderTest.java @@ -8,36 +8,36 @@ import com.yahoo.config.model.deploy.TestProperties; import com.yahoo.config.model.test.MockApplicationPackage; import com.yahoo.container.core.identity.IdentityConfig; import com.yahoo.vespa.model.container.IdentityProvider; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.w3c.dom.Element; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author mortent */ public class IdentityBuilderTest extends ContainerModelBuilderTestBase { @Test - public void identity_config_produced_from_deployment_spec() { + void identity_config_produced_from_deployment_spec() { Element clusterElem = DomBuilderTest.parse( "<container id='default' version='1.0'><search /></container>"); String deploymentXml = "<deployment version='1.0' athenz-domain='domain' athenz-service='service'>\n" + - " <test/>\n" + - " <prod>\n" + - " <region active='true'>default</region>\n" + - " </prod>\n" + - "</deployment>\n"; + " <test/>\n" + + " <prod>\n" + + " <region active='true'>default</region>\n" + + " </prod>\n" + + "</deployment>\n"; ApplicationPackage applicationPackage = new MockApplicationPackage.Builder() .withDeploymentSpec(deploymentXml) .build(); createModel(root, new DeployState.Builder() - .properties(new TestProperties().setHostedVespa(true)) - .applicationPackage(applicationPackage) - .build(), - null, - clusterElem); + .properties(new TestProperties().setHostedVespa(true)) + .applicationPackage(applicationPackage) + .build(), + null, + clusterElem); IdentityConfig identityConfig = root.getConfig(IdentityConfig.class, "default/component/" + IdentityProvider.CLASS); assertEquals("domain", identityConfig.domain()); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/JettyContainerModelBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/JettyContainerModelBuilderTest.java index 6cd0fa18c3d..8b1217758ab 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/JettyContainerModelBuilderTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/JettyContainerModelBuilderTest.java @@ -16,16 +16,14 @@ import com.yahoo.vespa.model.container.component.SimpleComponent; import com.yahoo.vespa.model.container.http.ConnectorFactory; import com.yahoo.vespa.model.container.http.JettyHttpServer; import com.yahoo.vespa.model.container.http.ssl.ConfiguredFilebasedSslProvider; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.w3c.dom.Element; import java.io.StringReader; import java.util.List; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * @author einarmr @@ -34,19 +32,19 @@ import static org.junit.Assert.assertTrue; public class JettyContainerModelBuilderTest extends ContainerModelBuilderTestBase { @Test - public void verify_that_overriding_connector_options_works() { + void verify_that_overriding_connector_options_works() { Element clusterElem = DomBuilderTest.parse( "<container id='default' version='1.0'>\n" + - " <http>\n" + - " <server id='bananarama' port='4321'>\n" + - " <config name='jdisc.http.connector'>\n" + - " <requestHeaderSize>300000</requestHeaderSize>\n" + - " <headerCacheSize>300000</headerCacheSize>\n" + - " </config>\n" + - " </server>\n" + - " </http>\n" + - nodesXml + - "</container>\n" + " <http>\n" + + " <server id='bananarama' port='4321'>\n" + + " <config name='jdisc.http.connector'>\n" + + " <requestHeaderSize>300000</requestHeaderSize>\n" + + " <headerCacheSize>300000</headerCacheSize>\n" + + " </config>\n" + + " </server>\n" + + " </http>\n" + + nodesXml + + "</container>\n" ); createModel(root, clusterElem); ConnectorConfig cfg = root.getConfig(ConnectorConfig.class, "default/http/jdisc-jetty/bananarama"); @@ -55,7 +53,7 @@ public class JettyContainerModelBuilderTest extends ContainerModelBuilderTestBas } @Test - public void verify_that_enabling_jetty_works() { + void verify_that_enabling_jetty_works() { Element clusterElem = DomBuilderTest.parse( "<container id='default' version='1.0'>" + nodesXml + @@ -66,24 +64,24 @@ public class JettyContainerModelBuilderTest extends ContainerModelBuilderTestBas } @Test - public void verify_that_enabling_jetty_works_for_custom_http_servers() { + void verify_that_enabling_jetty_works_for_custom_http_servers() { Element clusterElem = DomBuilderTest.parse( "<container id='default' version='1.0'>", " <http>", " <server port='9000' id='foo' />", " </http>", nodesXml, - "</container>" ); + "</container>"); createModel(root, clusterElem); assertJettyServerInConfig(); } @Test - public void verifyThatJettyHttpServerHasFilterBindingsProvider() { + void verifyThatJettyHttpServerHasFilterBindingsProvider() { final Element clusterElem = DomBuilderTest.parse( "<container id='default' version='1.0'>", nodesXml, - "</container>" ); + "</container>"); createModel(root, clusterElem); final ComponentsConfig.Components jettyHttpServerComponent = extractComponentByClassName( @@ -100,14 +98,14 @@ public class JettyContainerModelBuilderTest extends ContainerModelBuilderTestBas } @Test - public void verifyThatJettyHttpServerHasFilterBindingsProviderForCustomHttpServers() { + void verifyThatJettyHttpServerHasFilterBindingsProviderForCustomHttpServers() { final Element clusterElem = DomBuilderTest.parse( "<container id='default' version='1.0'>", " <http>", " <server port='9000' id='foo' />", " </http>", nodesXml, - "</container>" ); + "</container>"); createModel(root, clusterElem); final ComponentsConfig.Components jettyHttpServerComponent = extractComponentByClassName( @@ -124,7 +122,7 @@ public class JettyContainerModelBuilderTest extends ContainerModelBuilderTestBas } @Test - public void ssl_element_generates_connector_config_and_injects_provider_component() { + void ssl_element_generates_connector_config_and_injects_provider_component() { Element clusterElem = DomBuilderTest.parse( "<container id='default' version='1.0'>", " <http>", @@ -196,7 +194,7 @@ public class JettyContainerModelBuilderTest extends ContainerModelBuilderTestBas } @Test - public void verify_tht_ssl_provider_configuration_configures_correct_config() { + void verify_tht_ssl_provider_configuration_configures_correct_config() { Element clusterElem = DomBuilderTest.parse( "<container id='default' version='1.0'>", " <http>", @@ -220,7 +218,7 @@ public class JettyContainerModelBuilderTest extends ContainerModelBuilderTestBas } @Test - public void verify_that_container_factory_sees_same_config(){ + void verify_that_container_factory_sees_same_config() { Element clusterElem = DomBuilderTest.parse( "<container id='default' version='1.0'>", " <http>", @@ -241,7 +239,7 @@ public class JettyContainerModelBuilderTest extends ContainerModelBuilderTestBas } @Test - public void verify_that_container_setup_additional_tls4443(){ + void verify_that_container_setup_additional_tls4443() { Element clusterElem = DomBuilderTest.parse( "<container id='default' version='1.0'>", " <http>", @@ -257,14 +255,14 @@ public class JettyContainerModelBuilderTest extends ContainerModelBuilderTestBas "</container>"); String hostsxml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" + - "<hosts>\n" + - " <host name=\"mockhost-1\">\n" + - " <alias>mockhost1</alias>\n" + - " </host>\n" + - " <host name=\"mockhost-2\">\n" + - " <alias>mockhost2</alias>\n" + - " </host>\n" + - "</hosts>\n"; + "<hosts>\n" + + " <host name=\"mockhost-1\">\n" + + " <alias>mockhost1</alias>\n" + + " </host>\n" + + " <host name=\"mockhost-2\">\n" + + " <alias>mockhost2</alias>\n" + + " </host>\n" + + "</hosts>\n"; DeployState deployState = new DeployState.Builder() .properties( new TestProperties() diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/JvmOptionsTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/JvmOptionsTest.java index 146e383078e..3515bb7409e 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/JvmOptionsTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/JvmOptionsTest.java @@ -12,7 +12,7 @@ import com.yahoo.config.model.test.MockApplicationPackage; import com.yahoo.search.config.QrStartConfig; import com.yahoo.vespa.model.VespaModel; import com.yahoo.vespa.model.container.ContainerCluster; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.w3c.dom.Element; import org.xml.sax.SAXException; import java.io.IOException; @@ -21,9 +21,7 @@ import java.util.Collections; import java.util.List; import java.util.logging.Level; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; /** * @author baldersheim @@ -32,7 +30,7 @@ import static org.junit.Assert.fail; public class JvmOptionsTest extends ContainerModelBuilderTestBase { @Test - public void verify_jvm_tag_with_attributes() throws IOException, SAXException { + void verify_jvm_tag_with_attributes() throws IOException, SAXException { String servicesXml = "<container version='1.0'>" + " <search/>" + @@ -57,14 +55,14 @@ public class JvmOptionsTest extends ContainerModelBuilderTestBase { } @Test - public void honours_jvm_gc_options() { + void honours_jvm_gc_options() { Element clusterElem = DomBuilderTest.parse( "<container version='1.0'>", " <search/>", " <nodes jvm-gc-options='-XX:+UseG1GC'>", " <node hostalias='mockhost'/>", " </nodes>", - "</container>" ); + "</container>"); createModel(root, clusterElem); QrStartConfig.Builder qrStartBuilder = new QrStartConfig.Builder(); root.getConfig(qrStartBuilder, "container/container.0"); @@ -94,7 +92,7 @@ public class JvmOptionsTest extends ContainerModelBuilderTestBase { } @Test - public void ignores_jvmgcoptions_on_conflicting_jvmoptions() throws IOException, SAXException { + void ignores_jvmgcoptions_on_conflicting_jvmoptions() throws IOException, SAXException { verifyIgnoreJvmGCOptions(false); verifyIgnoreJvmGCOptions(true); } @@ -121,7 +119,7 @@ public class JvmOptionsTest extends ContainerModelBuilderTestBase { } @Test - public void requireThatJvmGCOptionsIsHonoured() throws IOException, SAXException { + void requireThatJvmGCOptionsIsHonoured() throws IOException, SAXException { verifyJvmGCOptions(false, null, null, ContainerCluster.G1GC); verifyJvmGCOptions(true, null, null, ContainerCluster.PARALLEL_GC); verifyJvmGCOptions(true, "", null, ContainerCluster.PARALLEL_GC); @@ -133,7 +131,7 @@ public class JvmOptionsTest extends ContainerModelBuilderTestBase { } @Test - public void requireThatValidJvmGcOptionsAreNotLogged() throws IOException, SAXException { + void requireThatValidJvmGcOptionsAreNotLogged() throws IOException, SAXException { // Valid options, should not log anything verifyLoggingOfJvmGcOptions(true, "-XX:+ParallelGCThreads=8"); verifyLoggingOfJvmGcOptions(true, "-XX:MaxTenuringThreshold=15"); // No + or - after colon @@ -141,7 +139,7 @@ public class JvmOptionsTest extends ContainerModelBuilderTestBase { } @Test - public void requireThatInvalidJvmGcOptionsFailDeployment() throws IOException, SAXException { + void requireThatInvalidJvmGcOptionsFailDeployment() throws IOException, SAXException { try { buildModelWithJvmOptions(new TestProperties().setHostedVespa(true), new TestLogger(), @@ -164,11 +162,11 @@ public class JvmOptionsTest extends ContainerModelBuilderTestBase { List<String> strings = Arrays.asList(invalidOptions.clone()); // Verify that nothing is logged if there are no invalid options if (strings.isEmpty()) { - assertEquals(logger.msgs.size() > 0 ? logger.msgs.get(0).getSecond() : "", 0, logger.msgs.size()); + assertEquals(0, logger.msgs.size(), logger.msgs.size() > 0 ? logger.msgs.get(0).getSecond() : ""); return; } - assertTrue("Expected 1 or more log messages for invalid JM options, got none", logger.msgs.size() > 0); + assertTrue(logger.msgs.size() > 0, "Expected 1 or more log messages for invalid JM options, got none"); Pair<Level, String> firstOption = logger.msgs.get(0); assertEquals(Level.WARNING, firstOption.getFirst()); @@ -200,7 +198,7 @@ public class JvmOptionsTest extends ContainerModelBuilderTestBase { } @Test - public void requireThatValidJvmOptionsAreNotLogged() throws IOException, SAXException { + void requireThatValidJvmOptionsAreNotLogged() throws IOException, SAXException { // Valid options, should not log anything verifyLoggingOfJvmOptions(true, "options", "-Xms2G"); verifyLoggingOfJvmOptions(true, "options", "-Xlog:gc"); @@ -210,12 +208,12 @@ public class JvmOptionsTest extends ContainerModelBuilderTestBase { } @Test - public void requireThatInvalidJvmOptionsFailDeployment() throws IOException, SAXException { + void requireThatInvalidJvmOptionsFailDeployment() throws IOException, SAXException { try { buildModelWithJvmOptions(new TestProperties().setHostedVespa(true), - new TestLogger(), - "options", - "-Xms2G foo bar"); + new TestLogger(), + "options", + "-Xms2G foo bar"); fail(); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().contains("Invalid or misplaced JVM options in services.xml: bar,foo")); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/RoutingBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/RoutingBuilderTest.java index c78c4d617ea..58b9462978f 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/RoutingBuilderTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/RoutingBuilderTest.java @@ -12,14 +12,14 @@ import com.yahoo.config.provision.RegionName; import com.yahoo.config.provision.Zone; import com.yahoo.vespa.model.container.ApplicationContainerCluster; import com.yahoo.vespa.model.container.ApplicationContainer; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.w3c.dom.Element; import org.xml.sax.SAXException; import java.io.IOException; import java.util.Arrays; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author mortent @@ -27,20 +27,20 @@ import static org.junit.Assert.assertEquals; public class RoutingBuilderTest extends ContainerModelBuilderTestBase { @Test - public void setsRotationActiveAccordingToDeploymentSpec() throws IOException, SAXException { + void setsRotationActiveAccordingToDeploymentSpec() throws IOException, SAXException { Element clusterElem = DomBuilderTest.parse( "<container id='default' version='1.0'><search /></container>"); String deploymentSpec = "<deployment>\n" + - " <prod> \n" + - " <region active='true'>us-north-1</region>\n" + - " <parallel>\n" + - " <region active='false'>us-north-2</region>\n" + - " <region active='true'>us-north-3</region>\n" + - " </parallel>\n" + - " <region active='false'>us-north-4</region>\n" + - " </prod>\n" + - "</deployment>"; + " <prod> \n" + + " <region active='true'>us-north-1</region>\n" + + " <parallel>\n" + + " <region active='false'>us-north-2</region>\n" + + " <region active='true'>us-north-3</region>\n" + + " </parallel>\n" + + " <region active='false'>us-north-4</region>\n" + + " </prod>\n" + + "</deployment>"; ApplicationPackage applicationPackage = new MockApplicationPackage.Builder() .withDeploymentSpec(deploymentSpec) @@ -49,18 +49,21 @@ public class RoutingBuilderTest extends ContainerModelBuilderTestBase { for (String region : Arrays.asList("us-north-1", "us-north-3")) { ApplicationContainer container = getContainer(applicationPackage, region, clusterElem); - assertEquals("Region " + region + " is active", "true", - container.getServicePropertyString("activeRotation")); + assertEquals("true", + container.getServicePropertyString("activeRotation"), + "Region " + region + " is active"); } for (String region : Arrays.asList("us-north-2", "us-north-4")) { ApplicationContainer container = getContainer(applicationPackage, region, clusterElem); - assertEquals("Region " + region + " is inactive", "false", - container.getServicePropertyString("activeRotation")); + assertEquals("false", + container.getServicePropertyString("activeRotation"), + "Region " + region + " is inactive"); } ApplicationContainer container = getContainer(applicationPackage, "unknown", clusterElem); - assertEquals("Unknown region is inactive", "false", - container.getServicePropertyString("activeRotation")); + assertEquals("false", + container.getServicePropertyString("activeRotation"), + "Unknown region is inactive"); } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/SearchBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/SearchBuilderTest.java index e6e580b9baa..8e871bb432b 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/SearchBuilderTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/SearchBuilderTest.java @@ -14,7 +14,7 @@ import com.yahoo.vespa.model.container.component.Handler; import com.yahoo.vespa.model.container.search.GUIHandler; import com.yahoo.vespa.model.test.utils.ApplicationPackageUtils; import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithMockPkg; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.w3c.dom.Element; import static com.yahoo.config.model.api.container.ContainerServiceType.CONTAINER; @@ -22,12 +22,7 @@ import static com.yahoo.test.Matchers.hasItemWithMethod; import static com.yahoo.vespa.model.container.search.ContainerSearch.QUERY_PROFILE_REGISTRY_CLASS; import static org.hamcrest.MatcherAssert.assertThat; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; /** * @author gjoranv @@ -39,13 +34,13 @@ public class SearchBuilderTest extends ContainerModelBuilderTestBase { } @Test - public void gui_search_handler_is_always_included_when_search_is_specified() { + void gui_search_handler_is_always_included_when_search_is_specified() { createBasicSearchModel(); String discBindingsConfig = root.getConfig(JdiscBindingsConfig.class, "default").toString(); assertTrue(discBindingsConfig.contains(GUIHandler.BINDING_PATH)); - ApplicationContainerCluster cluster = (ApplicationContainerCluster)root.getChildren().get("default"); + ApplicationContainerCluster cluster = (ApplicationContainerCluster) root.getChildren().get("default"); GUIHandler guiHandler = null; for (Handler handler : cluster.getHandlers()) { @@ -57,7 +52,7 @@ public class SearchBuilderTest extends ContainerModelBuilderTestBase { } @Test - public void search_handler_bindings_can_be_overridden() { + void search_handler_bindings_can_be_overridden() { Element clusterElem = DomBuilderTest.parse( "<container id='default' version='1.0'>", " <search>", @@ -76,7 +71,7 @@ public class SearchBuilderTest extends ContainerModelBuilderTestBase { } @Test - public void search_handler_bindings_can_be_disabled() { + void search_handler_bindings_can_be_disabled() { Element clusterElem = DomBuilderTest.parse( "<container id='default' version='1.0'>", " <search>", @@ -92,7 +87,7 @@ public class SearchBuilderTest extends ContainerModelBuilderTestBase { } @Test - public void search_handler_binding_can_be_stolen_by_user_configured_handler() { + void search_handler_binding_can_be_stolen_by_user_configured_handler() { var myHandler = "replaces_search_handler"; Element clusterElem = DomBuilderTest.parse( "<container id='default' version='1.0'>", @@ -112,14 +107,14 @@ public class SearchBuilderTest extends ContainerModelBuilderTestBase { // TODO: remove test when all containers are named 'container' @Test - public void cluster_with_only_search_gets_qrserver_as_service_name() { + void cluster_with_only_search_gets_qrserver_as_service_name() { createClusterWithOnlyDefaultChains(); - ApplicationContainerCluster cluster = (ApplicationContainerCluster)root.getChildren().get("default"); + ApplicationContainerCluster cluster = (ApplicationContainerCluster) root.getChildren().get("default"); assertEquals(CONTAINER.serviceName, cluster.getContainers().get(0).getServiceName()); } @Test - public void empty_search_element_gives_default_chains() { + void empty_search_element_gives_default_chains() { createClusterWithOnlyDefaultChains(); assertThat(chainsConfig().chains(), hasItemWithMethod("vespaPhases", "id")); assertThat(chainsConfig().chains(), hasItemWithMethod("native", "id")); @@ -127,9 +122,9 @@ public class SearchBuilderTest extends ContainerModelBuilderTestBase { } @Test - public void query_profiles_registry_component_is_added() { + void query_profiles_registry_component_is_added() { createClusterWithOnlyDefaultChains(); - ApplicationContainerCluster cluster = (ApplicationContainerCluster)root.getChildren().get("default"); + ApplicationContainerCluster cluster = (ApplicationContainerCluster) root.getChildren().get("default"); var queryProfileRegistryId = ComponentId.fromString(QUERY_PROFILE_REGISTRY_CLASS); assertTrue(cluster.getComponentsMap().containsKey(queryProfileRegistryId)); } @@ -147,7 +142,7 @@ public class SearchBuilderTest extends ContainerModelBuilderTestBase { } @Test - public void manually_setting_up_search_handler_is_forbidden() { + void manually_setting_up_search_handler_is_forbidden() { try { Element clusterElem = DomBuilderTest.parse( "<container id='default' version='1.0'>", @@ -164,22 +159,22 @@ public class SearchBuilderTest extends ContainerModelBuilderTestBase { } @Test - public void cluster_is_connected_to_content_clusters() { + void cluster_is_connected_to_content_clusters() { String hosts = hostsXml(); String services = "" + - "<services>"+ + "<services>" + " <admin version='2.0'>" + " <adminserver hostalias='mockhost'/>" + " </admin>" + - " <container version='1.0' id='container'>"+ + " <container version='1.0' id='container'>" + " <search>" + " <chain id='mychain' inherits='vespa'/>" + " </search>" + - " <nodes>"+ - " <node hostalias=\"mockhost\" />"+ - " </nodes>"+ - " </container>"+ + " <nodes>" + + " <node hostalias=\"mockhost\" />" + + " </nodes>" + + " </container>" + contentXml() + "</services>"; @@ -190,22 +185,22 @@ public class SearchBuilderTest extends ContainerModelBuilderTestBase { } @Test - public void cluster_is_connected_to_search_clusters() { + void cluster_is_connected_to_search_clusters() { String hosts = hostsXml(); String services = "" + - "<services>"+ + "<services>" + " <admin version='2.0'>" + " <adminserver hostalias='mockhost'/>" + " </admin>" + - " <container version='1.0' id='container'>"+ + " <container version='1.0' id='container'>" + " <search>" + " <chain id='mychain' inherits='vespa'/>" + " </search>" + - " <nodes>"+ - " <node hostalias=\"mockhost\" />"+ - " </nodes>"+ - " </container>"+ + " <nodes>" + + " <node hostalias=\"mockhost\" />" + + " </nodes>" + + " </container>" + contentXml() + "</services>"; @@ -216,7 +211,7 @@ public class SearchBuilderTest extends ContainerModelBuilderTestBase { } @Test - public void search_handler_has_dedicated_threadpool() { + void search_handler_has_dedicated_threadpool() { createBasicSearchModel(); Handler searchHandler = getHandler("default", SearchHandler.HANDLER_CLASS); @@ -230,7 +225,7 @@ public class SearchBuilderTest extends ContainerModelBuilderTestBase { } @Test - public void threadpool_configuration_can_be_overridden() { + void threadpool_configuration_can_be_overridden() { Element clusterElem = DomBuilderTest.parse( "<container id='default' version='1.0'>", " <search>", @@ -251,9 +246,9 @@ public class SearchBuilderTest extends ContainerModelBuilderTestBase { } @Test - public void ExecutionFactory_gets_same_chains_config_as_SearchHandler() { + void ExecutionFactory_gets_same_chains_config_as_SearchHandler() { createBasicSearchModel(); - Component<?,?> executionFactory = ((SearchHandler) getComponent("default",SearchHandler.HANDLER_CLASS)) + Component<?, ?> executionFactory = ((SearchHandler) getComponent("default", SearchHandler.HANDLER_CLASS)) .getChildren().get(SearchHandler.EXECUTION_FACTORY_CLASS); ChainsConfig executionFactoryChainsConfig = root.getConfig(ChainsConfig.class, executionFactory.getConfigId()); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/SecretStoreTest.java b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/SecretStoreTest.java index 8c6eee72cde..80d95752c5e 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/container/xml/SecretStoreTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/container/xml/SecretStoreTest.java @@ -12,14 +12,14 @@ import com.yahoo.config.provision.Zone; import com.yahoo.container.jdisc.secretstore.SecretStoreConfig; import com.yahoo.vespa.model.container.ApplicationContainerCluster; import com.yahoo.vespa.model.container.SecretStore; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.w3c.dom.Element; import java.util.List; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author tokle @@ -27,7 +27,7 @@ import static org.junit.Assert.fail; public class SecretStoreTest extends ContainerModelBuilderTestBase { @Test - public void secret_store_can_be_set_up() { + void secret_store_can_be_set_up() { Element clusterElem = DomBuilderTest.parse( "<container version='1.0'>", " <secret-store type='oath-ckms'>", @@ -41,7 +41,7 @@ public class SecretStoreTest extends ContainerModelBuilderTestBase { } @Test - public void cloud_secret_store_requires_configured_secret_store() { + void cloud_secret_store_requires_configured_secret_store() { Element clusterElem = DomBuilderTest.parse( "<container version='1.0'>", " <secret-store type='cloud'>", @@ -64,7 +64,7 @@ public class SecretStoreTest extends ContainerModelBuilderTestBase { @Test - public void cloud_secret_store_can_be_set_up() { + void cloud_secret_store_can_be_set_up() { Element clusterElem = DomBuilderTest.parse( "<container version='1.0'>", " <secret-store type='cloud'>", @@ -97,7 +97,7 @@ public class SecretStoreTest extends ContainerModelBuilderTestBase { } @Test - public void cloud_secret_store_fails_to_set_up_in_non_public_zone() { + void cloud_secret_store_fails_to_set_up_in_non_public_zone() { try { Element clusterElem = DomBuilderTest.parse( "<container version='1.0'>", @@ -118,7 +118,7 @@ public class SecretStoreTest extends ContainerModelBuilderTestBase { createModel(root, state, null, clusterElem); } catch (RuntimeException e) { assertEquals("Cloud secret store is not supported in non-public system, see the documentation", - e.getMessage()); + e.getMessage()); return; } fail(); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/ClusterResourceLimitsTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/ClusterResourceLimitsTest.java index cf7cd07e440..14e6efe7dff 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/content/ClusterResourceLimitsTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/content/ClusterResourceLimitsTest.java @@ -5,15 +5,12 @@ import com.yahoo.config.model.api.ModelContext; import com.yahoo.config.model.deploy.TestProperties; import com.yahoo.text.XML; import com.yahoo.vespa.model.builder.xml.dom.ModelElement; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.w3c.dom.Document; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; /** * @author geirst @@ -61,7 +58,7 @@ public class ClusterResourceLimitsTest { } @Test - public void content_node_limits_are_derived_from_cluster_controller_limits_if_not_set() { + void content_node_limits_are_derived_from_cluster_controller_limits_if_not_set() { assertLimits(0.4, 0.7, 0.76, 0.85, new Fixture().ctrlDisk(0.4).ctrlMemory(0.7)); assertLimits(0.4, 0.8, 0.76, 0.9, @@ -71,7 +68,7 @@ public class ClusterResourceLimitsTest { } @Test - public void content_node_limits_can_be_set_explicit() { + void content_node_limits_can_be_set_explicit() { assertLimits(0.4, 0.7, 0.9, 0.95, new Fixture().ctrlDisk(0.4).ctrlMemory(0.7).nodeDisk(0.9).nodeMemory(0.95)); assertLimits(0.4, 0.8, 0.95, 0.9, @@ -81,7 +78,7 @@ public class ClusterResourceLimitsTest { } @Test - public void cluster_controller_limits_are_equal_to_content_node_limits_minus_one_percent_if_not_set() { + void cluster_controller_limits_are_equal_to_content_node_limits_minus_one_percent_if_not_set() { assertLimits(0.89, 0.94, 0.9, 0.95, new Fixture().nodeDisk(0.9).nodeMemory(0.95)); assertLimits(0.89, 0.8, 0.9, 0.9, @@ -93,7 +90,7 @@ public class ClusterResourceLimitsTest { } @Test - public void limits_are_derived_from_the_other_if_not_set() { + void limits_are_derived_from_the_other_if_not_set() { assertLimits(0.6, 0.94, 0.84, 0.95, new Fixture().ctrlDisk(0.6).nodeMemory(0.95)); assertLimits(0.89, 0.7, 0.9, 0.85, @@ -101,13 +98,13 @@ public class ClusterResourceLimitsTest { } @Test - public void default_resource_limits_when_feed_block_is_enabled_in_distributor() { + void default_resource_limits_when_feed_block_is_enabled_in_distributor() { assertLimits(0.75, 0.8, 0.9, 0.9, new Fixture(true)); } @Test - public void hosted_exception_is_thrown_when_resource_limits_are_specified() { + void hosted_exception_is_thrown_when_resource_limits_are_specified() { try { hostedBuild(); fail(); @@ -117,7 +114,7 @@ public class ClusterResourceLimitsTest { } @Test - public void hosted_limits_from_feature_flag_are_used() { + void hosted_limits_from_feature_flag_are_used() { TestProperties featureFlags = new TestProperties(); featureFlags.setResourceLimitDisk(0.85); featureFlags.setResourceLimitMemory(0.90); @@ -129,7 +126,7 @@ public class ClusterResourceLimitsTest { } @Test - public void exception_is_thrown_when_resource_limits_are_out_of_range() { + void exception_is_thrown_when_resource_limits_are_out_of_range() { TestProperties featureFlags = new TestProperties(); featureFlags.setResourceLimitDisk(1.1); @@ -188,7 +185,7 @@ public class ClusterResourceLimitsTest { if (expLimit == null) { assertFalse(actLimit.isPresent()); } else { - assertEquals(limitType + " limit not as expected", expLimit, actLimit.get(), 0.00001); + assertEquals(expLimit, actLimit.get(), 0.00001, limitType + " limit not as expected"); } } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/ContentBaseTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/ContentBaseTest.java index 03fcf8df213..ccff07109a7 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/content/ContentBaseTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/content/ContentBaseTest.java @@ -3,7 +3,7 @@ package com.yahoo.vespa.model.content; import com.yahoo.messagebus.routing.RouteSpec; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class ContentBaseTest { public static String getHosts() { diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/ContentClusterTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/ContentClusterTest.java index 8c263e21a21..cfb2fceb60b 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/content/ContentClusterTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/content/ContentClusterTest.java @@ -38,7 +38,7 @@ import com.yahoo.vespa.model.routing.DocumentProtocol; import com.yahoo.vespa.model.routing.Routing; import com.yahoo.vespa.model.test.utils.ApplicationPackageUtils; import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithMockPkg; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Collections; @@ -47,13 +47,7 @@ import java.util.Map; import java.util.Optional; import java.util.OptionalInt; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; public class ContentClusterTest extends ContentBaseTest { @@ -66,41 +60,41 @@ public class ContentClusterTest extends ContentBaseTest { } @Test - public void testHierarchicRedundancy() { + void testHierarchicRedundancy() { ContentCluster cc = parse("" + - "<content version=\"1.0\" id=\"storage\">\n" + - " <documents/>" + - " <engine>" + - " <proton>" + - " <searchable-copies>3</searchable-copies>" + - " </proton>" + - " </engine>" + - " <redundancy>15</redundancy>\n" + - " <group name='root' distribution-key='0'>" + - " <distribution partitions='1|1|*'/>" + - " <group name='g-1' distribution-key='0'>" + - " <node hostalias='mockhost' distribution-key='0'/>" + - " <node hostalias='mockhost' distribution-key='1'/>" + - " <node hostalias='mockhost' distribution-key='2'/>" + - " <node hostalias='mockhost' distribution-key='3'/>" + - " <node hostalias='mockhost' distribution-key='4'/>" + - " </group>" + - " <group name='g-2' distribution-key='1'>" + - " <node hostalias='mockhost' distribution-key='5'/>" + - " <node hostalias='mockhost' distribution-key='6'/>" + - " <node hostalias='mockhost' distribution-key='7'/>" + - " <node hostalias='mockhost' distribution-key='8'/>" + - " <node hostalias='mockhost' distribution-key='9'/>" + - " </group>" + - " <group name='g-3' distribution-key='1'>" + - " <node hostalias='mockhost' distribution-key='10'/>" + - " <node hostalias='mockhost' distribution-key='11'/>" + - " <node hostalias='mockhost' distribution-key='12'/>" + - " <node hostalias='mockhost' distribution-key='13'/>" + - " <node hostalias='mockhost' distribution-key='14'/>" + - " </group>" + - " </group>" + - "</content>" + "<content version=\"1.0\" id=\"storage\">\n" + + " <documents/>" + + " <engine>" + + " <proton>" + + " <searchable-copies>3</searchable-copies>" + + " </proton>" + + " </engine>" + + " <redundancy>15</redundancy>\n" + + " <group name='root' distribution-key='0'>" + + " <distribution partitions='1|1|*'/>" + + " <group name='g-1' distribution-key='0'>" + + " <node hostalias='mockhost' distribution-key='0'/>" + + " <node hostalias='mockhost' distribution-key='1'/>" + + " <node hostalias='mockhost' distribution-key='2'/>" + + " <node hostalias='mockhost' distribution-key='3'/>" + + " <node hostalias='mockhost' distribution-key='4'/>" + + " </group>" + + " <group name='g-2' distribution-key='1'>" + + " <node hostalias='mockhost' distribution-key='5'/>" + + " <node hostalias='mockhost' distribution-key='6'/>" + + " <node hostalias='mockhost' distribution-key='7'/>" + + " <node hostalias='mockhost' distribution-key='8'/>" + + " <node hostalias='mockhost' distribution-key='9'/>" + + " </group>" + + " <group name='g-3' distribution-key='1'>" + + " <node hostalias='mockhost' distribution-key='10'/>" + + " <node hostalias='mockhost' distribution-key='11'/>" + + " <node hostalias='mockhost' distribution-key='12'/>" + + " <node hostalias='mockhost' distribution-key='13'/>" + + " <node hostalias='mockhost' distribution-key='14'/>" + + " </group>" + + " </group>" + + "</content>" ); DistributionConfig.Builder distributionBuilder = new DistributionConfig.Builder(); cc.getConfig(distributionBuilder); @@ -126,24 +120,24 @@ public class ContentClusterTest extends ContentBaseTest { } @Test - public void testRedundancy() { + void testRedundancy() { ContentCluster cc = parse("" + - "<content version=\"1.0\" id=\"storage\">\n" + - " <documents/>" + - " <engine>" + - " <proton>" + - " <searchable-copies>3</searchable-copies>" + - " </proton>" + - " </engine>" + - " <redundancy reply-after='4'>5</redundancy>\n" + - " <group>" + - " <node hostalias='mockhost' distribution-key='0'/>" + - " <node hostalias='mockhost' distribution-key='1'/>" + - " <node hostalias='mockhost' distribution-key='2'/>" + - " <node hostalias='mockhost' distribution-key='3'/>" + - " <node hostalias='mockhost' distribution-key='4'/>" + - " </group>" + - "</content>" + "<content version=\"1.0\" id=\"storage\">\n" + + " <documents/>" + + " <engine>" + + " <proton>" + + " <searchable-copies>3</searchable-copies>" + + " </proton>" + + " </engine>" + + " <redundancy reply-after='4'>5</redundancy>\n" + + " <group>" + + " <node hostalias='mockhost' distribution-key='0'/>" + + " <node hostalias='mockhost' distribution-key='1'/>" + + " <node hostalias='mockhost' distribution-key='2'/>" + + " <node hostalias='mockhost' distribution-key='3'/>" + + " <node hostalias='mockhost' distribution-key='4'/>" + + " </group>" + + "</content>" ); DistributionConfig.Builder distributionBuilder = new DistributionConfig.Builder(); cc.getConfig(distributionBuilder); @@ -167,32 +161,32 @@ public class ContentClusterTest extends ContentBaseTest { } @Test - public void testNoId() { + void testNoId() { ContentCluster c = parse( - "<content version=\"1.0\">\n" + - " <redundancy>1</redundancy>\n" + - " <documents/>" + - " <redundancy reply-after=\"4\">5</redundancy>\n" + - " <group>" + - " <node hostalias=\"mockhost\" distribution-key=\"0\"/>\"" + - " </group>" + - "</content>" + "<content version=\"1.0\">\n" + + " <redundancy>1</redundancy>\n" + + " <documents/>" + + " <redundancy reply-after=\"4\">5</redundancy>\n" + + " <group>" + + " <node hostalias=\"mockhost\" distribution-key=\"0\"/>\"" + + " </group>" + + "</content>" ); assertEquals("content", c.getName()); } @Test - public void testRedundancyDefaults() { + void testRedundancyDefaults() { ContentCluster cc = parse( - "<content version=\"1.0\" id=\"storage\">\n" + - " <documents/>" + - " <group>" + - " <node hostalias=\"mockhost\" distribution-key=\"0\"/>\"" + - " <node hostalias=\"mockhost\" distribution-key=\"1\"/>\"" + - " <node hostalias=\"mockhost\" distribution-key=\"2\"/>\"" + - " </group>" + - "</content>" + "<content version=\"1.0\" id=\"storage\">\n" + + " <documents/>" + + " <group>" + + " <node hostalias=\"mockhost\" distribution-key=\"0\"/>\"" + + " <node hostalias=\"mockhost\" distribution-key=\"1\"/>\"" + + " <node hostalias=\"mockhost\" distribution-key=\"2\"/>\"" + + " </group>" + + "</content>" ); DistributionConfig.Builder distributionBuilder = new DistributionConfig.Builder(); @@ -209,41 +203,41 @@ public class ContentClusterTest extends ContentBaseTest { } @Test - public void testEndToEnd() { + void testEndToEnd() { String xml = - "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" + - "<services>\n" + - "\n" + - " <admin version=\"2.0\">\n" + - " <adminserver hostalias=\"configserver\" />\n" + - " <logserver hostalias=\"logserver\" />\n" + - " <slobroks>\n" + - " <slobrok hostalias=\"configserver\" />\n" + - " <slobrok hostalias=\"logserver\" />\n" + - " </slobroks>\n" + - " <cluster-controllers>\n" + - " <cluster-controller hostalias=\"configserver\"/>" + - " <cluster-controller hostalias=\"configserver2\"/>" + - " <cluster-controller hostalias=\"configserver3\"/>" + - " </cluster-controllers>\n" + - " </admin>\n" + - " <content version='1.0' id='bar'>" + - " <redundancy>1</redundancy>\n" + - " <documents>" + - " <document type=\"type1\" mode=\"index\"/>\n" + - " <document type=\"type2\" mode=\"index\"/>\n" + - " </documents>\n" + - " <group>" + - " <node hostalias='node0' distribution-key='0' />" + - " </group>" + - " <tuning>" + - " <cluster-controller>\n" + - " <init-progress-time>34567</init-progress-time>" + - " </cluster-controller>" + - " </tuning>" + - " </content>" + - "\n" + - "</services>"; + "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" + + "<services>\n" + + "\n" + + " <admin version=\"2.0\">\n" + + " <adminserver hostalias=\"configserver\" />\n" + + " <logserver hostalias=\"logserver\" />\n" + + " <slobroks>\n" + + " <slobrok hostalias=\"configserver\" />\n" + + " <slobrok hostalias=\"logserver\" />\n" + + " </slobroks>\n" + + " <cluster-controllers>\n" + + " <cluster-controller hostalias=\"configserver\"/>" + + " <cluster-controller hostalias=\"configserver2\"/>" + + " <cluster-controller hostalias=\"configserver3\"/>" + + " </cluster-controllers>\n" + + " </admin>\n" + + " <content version='1.0' id='bar'>" + + " <redundancy>1</redundancy>\n" + + " <documents>" + + " <document type=\"type1\" mode=\"index\"/>\n" + + " <document type=\"type2\" mode=\"index\"/>\n" + + " </documents>\n" + + " <group>" + + " <node hostalias='node0' distribution-key='0' />" + + " </group>" + + " <tuning>" + + " <cluster-controller>\n" + + " <init-progress-time>34567</init-progress-time>" + + " </cluster-controller>" + + " </tuning>" + + " </content>" + + "\n" + + "</services>"; List<String> sds = ApplicationPackageUtils.generateSchemas("type1", "type2"); VespaModel model = new VespaModelCreatorWithMockPkg(null, xml, sds).create(); @@ -294,7 +288,7 @@ public class ContentClusterTest extends ContentBaseTest { } @Test - public void testEndToEndOneNode() { + void testEndToEndOneNode() { VespaModel model = createEnd2EndOneNode(new TestProperties()); assertEquals(1, model.getContentClusters().get("storage").getDocumentDefinitions().size()); @@ -303,34 +297,34 @@ public class ContentClusterTest extends ContentBaseTest { } @Test - public void testSearchTuning() { + void testSearchTuning() { String xml = - "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" + - "<services>\n" + - "\n" + - " <admin version=\"2.0\">\n" + - " <adminserver hostalias=\"node0\" />\n" + - " <cluster-controllers>\n" + - " <cluster-controller hostalias=\"node0\"/>" + - " </cluster-controllers>\n" + - " </admin>\n" + - " <content version='1.0' id='bar'>" + - " <redundancy>1</redundancy>\n" + - " <documents>" + - " <document type=\"type1\" mode='index'/>\n" + - " <document type=\"type2\" mode='index'/>\n" + - " </documents>\n" + - " <group>" + - " <node hostalias='node0' distribution-key='0'/>" + - " </group>" + - " <tuning>\n" + - " <cluster-controller>" + - " <init-progress-time>34567</init-progress-time>" + - " </cluster-controller>" + - " </tuning>" + - " </content>" + - "\n" + - "</services>"; + "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" + + "<services>\n" + + "\n" + + " <admin version=\"2.0\">\n" + + " <adminserver hostalias=\"node0\" />\n" + + " <cluster-controllers>\n" + + " <cluster-controller hostalias=\"node0\"/>" + + " </cluster-controllers>\n" + + " </admin>\n" + + " <content version='1.0' id='bar'>" + + " <redundancy>1</redundancy>\n" + + " <documents>" + + " <document type=\"type1\" mode='index'/>\n" + + " <document type=\"type2\" mode='index'/>\n" + + " </documents>\n" + + " <group>" + + " <node hostalias='node0' distribution-key='0'/>" + + " </group>" + + " <tuning>\n" + + " <cluster-controller>" + + " <init-progress-time>34567</init-progress-time>" + + " </cluster-controller>" + + " </tuning>" + + " </content>" + + "\n" + + "</services>"; List<String> sds = ApplicationPackageUtils.generateSchemas("type1", "type2"); VespaModel model = new VespaModelCreatorWithMockPkg(getHosts(), xml, sds).create(); @@ -353,66 +347,68 @@ public class ContentClusterTest extends ContentBaseTest { } @Test - public void testRedundancyRequired() { + void testRedundancyRequired() { String xml = - "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" + - "<services>\n" + - "\n" + - " <admin version=\"2.0\">\n" + - " <adminserver hostalias=\"node0\" />\n" + - " </admin>\n" + - " <content version='1.0' id='bar'>" + - " <documents>" + - " <document type=\"type1\" mode='index'/>\n" + - " </documents>\n" + - " <group>\n" + - " <node hostalias='node0' distribution-key='0'/>\n" + - " </group>\n" + - " </content>\n" + - "</services>\n"; + "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" + + "<services>\n" + + "\n" + + " <admin version=\"2.0\">\n" + + " <adminserver hostalias=\"node0\" />\n" + + " </admin>\n" + + " <content version='1.0' id='bar'>" + + " <documents>" + + " <document type=\"type1\" mode='index'/>\n" + + " </documents>\n" + + " <group>\n" + + " <node hostalias='node0' distribution-key='0'/>\n" + + " </group>\n" + + " </content>\n" + + "</services>\n"; List<String> sds = ApplicationPackageUtils.generateSchemas("type1", "type2"); - try{ + try { new VespaModelCreatorWithMockPkg(getHosts(), xml, sds).create(); fail("Deploying without redundancy should fail"); } catch (IllegalArgumentException e) { - assertTrue(e.getMessage(), e.getMessage().contains("missing required element \"redundancy\"")); + assertTrue(e.getMessage().contains("missing required element \"redundancy\""), e.getMessage()); } } @Test - public void testRedundancyFinalLessThanInitial() { + void testRedundancyFinalLessThanInitial() { try { parse( - "<content version=\"1.0\" id=\"storage\">\n" + - " <redundancy reply-after=\"4\">2</redundancy>\n" + - " <group>" + - " <node hostalias='node0' distribution-key='0' />" + - " </group>" + - "</content>" + "<content version=\"1.0\" id=\"storage\">\n" + + " <redundancy reply-after=\"4\">2</redundancy>\n" + + " <group>" + + " <node hostalias='node0' distribution-key='0' />" + + " </group>" + + "</content>" ); fail("no exception thrown"); - } catch (Exception e) { /* ignore */ } + } catch (Exception e) { /* ignore */ + } } @Test - public void testReadyTooHigh() { + void testReadyTooHigh() { try { parse( - "<content version=\"1.0\" id=\"storage\">\n" + - " <engine>" + - " <proton>" + - " <searchable-copies>3</searchable-copies>" + - " </proton>" + - " </engine>" + - " <redundancy>2</redundancy>\n" + - " <group>" + - " <node hostalias='node0' distribution-key='0' />" + - " </group>" + - "</content>" + "<content version=\"1.0\" id=\"storage\">\n" + + " <engine>" + + " <proton>" + + " <searchable-copies>3</searchable-copies>" + + " </proton>" + + " </engine>" + + " <redundancy>2</redundancy>\n" + + " <group>" + + " <node hostalias='node0' distribution-key='0' />" + + " </group>" + + "</content>" ); fail("no exception thrown"); - } catch (Exception e) { /* ignore */ } + } catch (Exception e) { /* ignore */ + } } FleetcontrollerConfig getFleetControllerConfig(String xml) { @@ -425,16 +421,16 @@ public class ContentClusterTest extends ContentBaseTest { } @Test - public void testFleetControllerOverride() + void testFleetControllerOverride() { { FleetcontrollerConfig config = getFleetControllerConfig( - "<content version=\"1.0\" id=\"storage\">\n" + - " <documents/>" + - " <group>\n" + - " <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" + - " </group>\n" + - "</content>" + "<content version=\"1.0\" id=\"storage\">\n" + + " <documents/>" + + " <group>\n" + + " <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" + + " </group>\n" + + "</content>" ); assertEquals(0, config.min_storage_up_ratio(), 0.01); @@ -445,17 +441,17 @@ public class ContentClusterTest extends ContentBaseTest { { FleetcontrollerConfig config = getFleetControllerConfig( - "<content version=\"1.0\" id=\"storage\">\n" + - " <documents/>" + - " <group>\n" + - " <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" + - " <node distribution-key=\"1\" hostalias=\"mockhost\"/>\n" + - " <node distribution-key=\"2\" hostalias=\"mockhost\"/>\n" + - " <node distribution-key=\"3\" hostalias=\"mockhost\"/>\n" + - " <node distribution-key=\"4\" hostalias=\"mockhost\"/>\n" + - " <node distribution-key=\"5\" hostalias=\"mockhost\"/>\n" + - " </group>\n" + - "</content>" + "<content version=\"1.0\" id=\"storage\">\n" + + " <documents/>" + + " <group>\n" + + " <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" + + " <node distribution-key=\"1\" hostalias=\"mockhost\"/>\n" + + " <node distribution-key=\"2\" hostalias=\"mockhost\"/>\n" + + " <node distribution-key=\"3\" hostalias=\"mockhost\"/>\n" + + " <node distribution-key=\"4\" hostalias=\"mockhost\"/>\n" + + " <node distribution-key=\"5\" hostalias=\"mockhost\"/>\n" + + " </group>\n" + + "</content>" ); assertNotSame(0, config.min_storage_up_ratio()); @@ -463,65 +459,65 @@ public class ContentClusterTest extends ContentBaseTest { } @Test - public void testImplicitDistributionBits() + void testImplicitDistributionBits() { ContentCluster cluster = parse( - "<content version=\"1.0\" id=\"storage\">\n" + - " <documents/>" + - " <group>\n" + - " <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" + - " </group>\n" + - "</content>" + "<content version=\"1.0\" id=\"storage\">\n" + + " <documents/>" + + " <group>\n" + + " <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" + + " </group>\n" + + "</content>" ); assertDistributionBitsInConfig(cluster, 8); cluster = parse( - "<content version=\"1.0\" id=\"storage\">\n" + - " <documents/>" + - " <group>\n" + - " <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" + - " </group>\n" + - "</content>" + "<content version=\"1.0\" id=\"storage\">\n" + + " <documents/>" + + " <group>\n" + + " <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" + + " </group>\n" + + "</content>" ); assertDistributionBitsInConfig(cluster, 8); } @Test - public void testExplicitDistributionBits() + void testExplicitDistributionBits() { ContentCluster cluster = parse( - "<content version=\"1.0\" id=\"storage\">\n" + - " <documents/>" + - " <group>\n" + - " <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" + - " </group>\n" + - " <tuning>\n" + - " <distribution type=\"strict\"/>\n" + - " </tuning>\n" + - "</content>" + "<content version=\"1.0\" id=\"storage\">\n" + + " <documents/>" + + " <group>\n" + + " <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" + + " </group>\n" + + " <tuning>\n" + + " <distribution type=\"strict\"/>\n" + + " </tuning>\n" + + "</content>" ); assertDistributionBitsInConfig(cluster, 8); cluster = parse( - "<content version=\"1.0\" id=\"storage\">\n" + - " <documents/>" + - " <group>\n" + - " <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" + - " </group>\n" + - " <tuning>\n" + - " <distribution type=\"loose\"/>\n" + - " </tuning>\n" + - "</content>" + "<content version=\"1.0\" id=\"storage\">\n" + + " <documents/>" + + " <group>\n" + + " <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" + + " </group>\n" + + " <tuning>\n" + + " <distribution type=\"loose\"/>\n" + + " </tuning>\n" + + "</content>" ); assertDistributionBitsInConfig(cluster, 8); } @Test - public void testZoneDependentDistributionBits() throws Exception { + void testZoneDependentDistributionBits() throws Exception { String xml = new ContentClusterBuilder().docTypes("test").getXml(); ContentCluster prodWith16Bits = createWithZone(xml, new Zone(Environment.prod, RegionName.from("us-east-3"))); @@ -532,19 +528,19 @@ public class ContentClusterTest extends ContentBaseTest { } @Test - public void testGenerateSearchNodes() + void testGenerateSearchNodes() { ContentCluster cluster = parse( - "<content version=\"1.0\" id=\"storage\">\n" + - " <documents/>" + - " <engine>" + - " <proton/>" + - " </engine>" + - " <group>\n" + - " <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" + - " <node distribution-key=\"1\" hostalias=\"mockhost\"/>\n" + - " </group>\n" + - "</content>" + "<content version=\"1.0\" id=\"storage\">\n" + + " <documents/>" + + " <engine>" + + " <proton/>" + + " </engine>" + + " <group>\n" + + " <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" + + " <node distribution-key=\"1\" hostalias=\"mockhost\"/>\n" + + " </group>\n" + + "</content>" ); { @@ -563,19 +559,19 @@ public class ContentClusterTest extends ContentBaseTest { } @Test - public void testAlternativeNodeSyntax() + void testAlternativeNodeSyntax() { ContentCluster cluster = parse( - "<content version=\"1.0\" id=\"test\">\n" + - " <documents/>" + - " <engine>" + - " <proton/>" + - " </engine>" + - " <nodes>\n" + - " <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" + - " <node distribution-key=\"1\" hostalias=\"mockhost\"/>\n" + - " </nodes>\n" + - "</content>" + "<content version=\"1.0\" id=\"test\">\n" + + " <documents/>" + + " <engine>" + + " <proton/>" + + " </engine>" + + " <nodes>\n" + + " <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" + + " <node distribution-key=\"1\" hostalias=\"mockhost\"/>\n" + + " </nodes>\n" + + "</content>" ); DistributionConfig.Builder bob = new DistributionConfig.Builder(); @@ -597,16 +593,16 @@ public class ContentClusterTest extends ContentBaseTest { } @Test - public void testReadyWhenInitialOne() { + void testReadyWhenInitialOne() { StorDistributionConfig.Builder builder = new StorDistributionConfig.Builder(); parse( - "<content version=\"1.0\" id=\"storage\">\n" + - " <documents/>" + - " <redundancy>1</redundancy>\n" + - " <group>\n" + - " <node distribution-key=\"0\" hostalias=\"mockhost\"/>" + - " </group>" + - "</content>" + "<content version=\"1.0\" id=\"storage\">\n" + + " <documents/>" + + " <redundancy>1</redundancy>\n" + + " <group>\n" + + " <node distribution-key=\"0\" hostalias=\"mockhost\"/>" + + " </group>" + + "</content>" ).getConfig(builder); StorDistributionConfig config = new StorDistributionConfig(builder); @@ -651,21 +647,21 @@ public class ContentClusterTest extends ContentBaseTest { } @Test - public void testProviders() { + void testProviders() { testProvider("proton", StorServerConfig.Persistence_provider.Type.RPC); testProvider("dummy", StorServerConfig.Persistence_provider.Type.DUMMY); } @Test - public void testMetrics() { + void testMetrics() { MetricsmanagerConfig.Builder builder = new MetricsmanagerConfig.Builder(); ContentCluster cluster = parse("<content version=\"1.0\" id=\"storage\">\n" + - " <documents/>" + - " <group>\n" + - " <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" + - " </group>\n" + - "</content>" + " <documents/>" + + " <group>\n" + + " <node distribution-key=\"0\" hostalias=\"mockhost\"/>\n" + + " </group>\n" + + "</content>" ); cluster.getConfig(builder); @@ -715,24 +711,24 @@ public class ContentClusterTest extends ContentBaseTest { } @Test - public void testConfiguredMetrics() { + void testConfiguredMetrics() { String xml = "" + - "<services>" + - "<content version=\"1.0\" id=\"storage\">\n" + - " <redundancy>1</redundancy>\n" + - " <documents>" + - " <document type=\"type1\" mode='index'/>\n" + - " <document type=\"type2\" mode='index'/>\n" + - " </documents>" + - " <group>\n" + - " <node distribution-key=\"0\" hostalias=\"node0\"/>\n" + - " </group>\n" + - "</content>" + - "<admin version=\"2.0\">" + - " <logserver hostalias=\"node0\"/>" + - " <adminserver hostalias=\"node0\"/>" + - "</admin>" + - "</services>"; + "<services>" + + "<content version=\"1.0\" id=\"storage\">\n" + + " <redundancy>1</redundancy>\n" + + " <documents>" + + " <document type=\"type1\" mode='index'/>\n" + + " <document type=\"type2\" mode='index'/>\n" + + " </documents>" + + " <group>\n" + + " <node distribution-key=\"0\" hostalias=\"node0\"/>\n" + + " </group>\n" + + "</content>" + + "<admin version=\"2.0\">" + + " <logserver hostalias=\"node0\"/>" + + " <adminserver hostalias=\"node0\"/>" + + "</admin>" + + "</services>"; List<String> sds = ApplicationPackageUtils.generateSchemas("type1", "type2"); @@ -745,25 +741,25 @@ public class ContentClusterTest extends ContentBaseTest { String expected = "[vds.filestor.allthreads.put\n" + - "vds.filestor.allthreads.get\n" + - "vds.filestor.allthreads.remove\n" + - "vds.filestor.allthreads.update\n" + - "vds.datastored.alldisks.docs\n" + - "vds.datastored.alldisks.bytes\n" + - "vds.filestor.queuesize\n" + - "vds.filestor.averagequeuewait\n" + - "vds.visitor.cv_queuewaittime\n" + - "vds.visitor.allthreads.averagequeuewait\n" + - "vds.visitor.allthreads.averagevisitorlifetime\n" + - "vds.visitor.allthreads.created]"; + "vds.filestor.allthreads.get\n" + + "vds.filestor.allthreads.remove\n" + + "vds.filestor.allthreads.update\n" + + "vds.datastored.alldisks.docs\n" + + "vds.datastored.alldisks.bytes\n" + + "vds.filestor.queuesize\n" + + "vds.filestor.averagequeuewait\n" + + "vds.visitor.cv_queuewaittime\n" + + "vds.visitor.allthreads.averagequeuewait\n" + + "vds.visitor.allthreads.averagevisitorlifetime\n" + + "vds.visitor.allthreads.created]"; String actual = getConsumer("log", config).addedmetrics().toString().replaceAll(", ", "\n"); assertEquals(expected, actual); assertEquals("[logdefault]", getConsumer("log", config).tags().toString()); expected = "[vds.datastored.alldisks.docs\n" + - "vds.datastored.alldisks.bytes\n" + - "vds.datastored.alldisks.buckets\n" + - "vds.datastored.bucket_space.buckets_total]"; + "vds.datastored.alldisks.bytes\n" + + "vds.datastored.alldisks.buckets\n" + + "vds.datastored.bucket_space.buckets_total]"; actual = getConsumer("fleetcontroller", config).addedmetrics().toString().replaceAll(", ", "\n"); assertEquals(expected, actual); } @@ -778,22 +774,22 @@ public class ContentClusterTest extends ContentBaseTest { } @Test - public void flush_on_shutdown_is_default_on_for_non_hosted() throws Exception { + void flush_on_shutdown_is_default_on_for_non_hosted() throws Exception { assertPrepareRestartCommand(createOneNodeCluster(false)); } @Test - public void flush_on_shutdown_can_be_turned_off_for_non_hosted() throws Exception { + void flush_on_shutdown_can_be_turned_off_for_non_hosted() throws Exception { assertNoPreShutdownCommand(createClusterWithFlushOnShutdownOverride(false, false)); } @Test - public void flush_on_shutdown_is_default_on_for_hosted() throws Exception { + void flush_on_shutdown_is_default_on_for_hosted() throws Exception { assertPrepareRestartCommand(createOneNodeCluster(true)); } @Test - public void flush_on_shutdown_can_be_turned_on_for_hosted() throws Exception { + void flush_on_shutdown_can_be_turned_on_for_hosted() throws Exception { assertPrepareRestartCommand(createClusterWithFlushOnShutdownOverride(true, true)); } @@ -861,16 +857,16 @@ public class ContentClusterTest extends ContentBaseTest { } @Test - public void reserved_document_name_throws_exception() { + void reserved_document_name_throws_exception() { String xml = "<content version=\"1.0\" id=\"storage\">" + - " <redundancy>1</redundancy>" + - " <documents>" + - " <document type=\"true\" mode=\"index\"/>" + - " </documents>" + - " <group>" + - " <node distribution-key=\"0\" hostalias=\"mockhost\"/>" + - " </group>" + - "</content>"; + " <redundancy>1</redundancy>" + + " <documents>" + + " <document type=\"true\" mode=\"index\"/>" + + " </documents>" + + " <group>" + + " <node distribution-key=\"0\" hostalias=\"mockhost\"/>" + + " </group>" + + "</content>"; List<String> sds = ApplicationPackageUtils.generateSchemas("true"); try { @@ -929,7 +925,7 @@ public class ContentClusterTest extends ContentBaseTest { } @Test - public void all_clusters_bucket_spaces_config_contains_mappings_across_all_clusters() { + void all_clusters_bucket_spaces_config_contains_mappings_across_all_clusters() { VespaModel model = createDualContentCluster(); AllClustersBucketSpacesConfig.Builder builder = new AllClustersBucketSpacesConfig.Builder(); model.getConfig(builder, "client"); @@ -940,8 +936,9 @@ public class ContentClusterTest extends ContentBaseTest { assertClusterHasBucketSpaceMappings(config, "foo_c", Arrays.asList("bunnies", "hares"), Collections.emptyList()); assertClusterHasBucketSpaceMappings(config, "bar_c", Collections.emptyList(), Collections.singletonList("rabbits")); } + @Test - public void test_routing_with_multiple_clusters() { + void test_routing_with_multiple_clusters() { VespaModel model = createDualContentCluster(); Routing routing = model.getRouting(); assertNotNull(routing); @@ -1004,7 +1001,7 @@ public class ContentClusterTest extends ContentBaseTest { } @Test - public void default_topKprobability_controlled_by_properties() { + void default_topKprobability_controlled_by_properties() { verifyTopKProbabilityPropertiesControl(); } @@ -1019,7 +1016,7 @@ public class ContentClusterTest extends ContentBaseTest { } @Test - public void default_distributor_three_phase_update_config_controlled_by_properties() { + void default_distributor_three_phase_update_config_controlled_by_properties() { assertFalse(resolveThreePhaseUpdateConfigWithFeatureFlag(false)); assertTrue(resolveThreePhaseUpdateConfigWithFeatureFlag(true)); } @@ -1039,7 +1036,7 @@ public class ContentClusterTest extends ContentBaseTest { } @Test - public void default_max_compact_buffers_config_controlled_by_properties() { + void default_max_compact_buffers_config_controlled_by_properties() { assertEquals(1, resolveMaxCompactBuffers(OptionalInt.empty())); assertEquals(2, resolveMaxCompactBuffers(OptionalInt.of(2))); assertEquals(7, resolveMaxCompactBuffers(OptionalInt.of(7))); @@ -1054,8 +1051,9 @@ public class ContentClusterTest extends ContentBaseTest { ProtonConfig protonConfig = new ProtonConfig(protonBuilder); return protonConfig.flush().memory().maxtlssize(); } + @Test - public void verifyt_max_tls_size() throws Exception { + void verifyt_max_tls_size() throws Exception { var flavor = new Flavor(new FlavorsConfig.Flavor(new FlavorsConfig.Flavor.Builder().name("test").minDiskAvailableGb(100))); assertEquals(21474836480L, resolveMaxTLSSize(Optional.empty())); assertEquals(2147483648L, resolveMaxTLSSize(Optional.of(flavor))); @@ -1087,7 +1085,7 @@ public class ContentClusterTest extends ContentBaseTest { } @Test - public void default_distributor_max_inhibited_group_activation_config_controlled_by_properties() throws Exception { + void default_distributor_max_inhibited_group_activation_config_controlled_by_properties() throws Exception { assertEquals(0, resolveMaxInhibitedGroupsConfigWithFeatureFlag(0)); assertEquals(2, resolveMaxInhibitedGroupsConfigWithFeatureFlag(2)); } @@ -1105,13 +1103,13 @@ public class ContentClusterTest extends ContentBaseTest { } @Test - public void num_distributor_stripes_config_defaults_to_zero() throws Exception { + void num_distributor_stripes_config_defaults_to_zero() throws Exception { // This triggers tuning when starting the distributor process, based on CPU core sampling on the node. assertEquals(0, resolveNumDistributorStripesConfig(Optional.empty())); } @Test - public void num_distributor_stripes_config_tuned_by_flavor() throws Exception { + void num_distributor_stripes_config_tuned_by_flavor() throws Exception { assertEquals(1, resolveTunedNumDistributorStripesConfig(1)); assertEquals(1, resolveTunedNumDistributorStripesConfig(16)); assertEquals(2, resolveTunedNumDistributorStripesConfig(17)); @@ -1120,7 +1118,7 @@ public class ContentClusterTest extends ContentBaseTest { } @Test - public void unordered_merge_chaining_config_controlled_by_properties() throws Exception { + void unordered_merge_chaining_config_controlled_by_properties() throws Exception { assertFalse(resolveUnorderedMergeChainingConfig(Optional.of(false))); assertTrue(resolveUnorderedMergeChainingConfig(Optional.empty())); } @@ -1137,60 +1135,60 @@ public class ContentClusterTest extends ContentBaseTest { } @Test - public void testDedicatedClusterControllers() { + void testDedicatedClusterControllers() { VespaModel noContentModel = createEnd2EndOneNode(new TestProperties().setHostedVespa(true) - .setMultitenant(true), - "<?xml version='1.0' encoding='UTF-8' ?>" + - "<services version='1.0'>" + - " <container id='default' version='1.0' />" + - " </services>"); + .setMultitenant(true), + "<?xml version='1.0' encoding='UTF-8' ?>" + + "<services version='1.0'>" + + " <container id='default' version='1.0' />" + + " </services>"); assertEquals(Map.of(), noContentModel.getContentClusters()); - assertNull("No cluster controller without content", noContentModel.getAdmin().getClusterControllers()); + assertNull(noContentModel.getAdmin().getClusterControllers(), "No cluster controller without content"); VespaModel oneContentModel = createEnd2EndOneNode(new TestProperties().setHostedVespa(true) - .setMultitenant(true), - "<?xml version='1.0' encoding='UTF-8' ?>" + - "<services version='1.0'>" + - " <container id='default' version='1.0' />" + - " <content id='storage' version='1.0'>" + - " <redundancy>1</redundancy>" + - " <documents>" + - " <document mode='index' type='type1' />" + - " </documents>" + - " </content>" + - " </services>"); - assertNotNull("Shared cluster controller with content", oneContentModel.getAdmin().getClusterControllers()); + .setMultitenant(true), + "<?xml version='1.0' encoding='UTF-8' ?>" + + "<services version='1.0'>" + + " <container id='default' version='1.0' />" + + " <content id='storage' version='1.0'>" + + " <redundancy>1</redundancy>" + + " <documents>" + + " <document mode='index' type='type1' />" + + " </documents>" + + " </content>" + + " </services>"); + assertNotNull(oneContentModel.getAdmin().getClusterControllers(), "Shared cluster controller with content"); String twoContentServices = "<?xml version='1.0' encoding='UTF-8' ?>" + - "<services version='1.0'>" + - " <container id='default' version='1.0' />" + - " <content id='storage' version='1.0'>" + - " <redundancy>1</redundancy>" + - " <documents>" + - " <document mode='index' type='type1' />" + - " </documents>" + - " <tuning>" + - " <cluster-controller>" + - " <min-distributor-up-ratio>0.618</min-distributor-up-ratio>" + - " </cluster-controller>" + - " </tuning>" + - " </content>" + - " <content id='dev-null' version='1.0'>" + - " <redundancy>1</redundancy>" + - " <documents>" + - " <document mode='index' type='type1' />" + - " </documents>" + - " <tuning>" + - " <cluster-controller>" + - " <min-distributor-up-ratio>0.418</min-distributor-up-ratio>" + - " </cluster-controller>" + - " </tuning>" + - " </content>" + - " </services>"; + "<services version='1.0'>" + + " <container id='default' version='1.0' />" + + " <content id='storage' version='1.0'>" + + " <redundancy>1</redundancy>" + + " <documents>" + + " <document mode='index' type='type1' />" + + " </documents>" + + " <tuning>" + + " <cluster-controller>" + + " <min-distributor-up-ratio>0.618</min-distributor-up-ratio>" + + " </cluster-controller>" + + " </tuning>" + + " </content>" + + " <content id='dev-null' version='1.0'>" + + " <redundancy>1</redundancy>" + + " <documents>" + + " <document mode='index' type='type1' />" + + " </documents>" + + " <tuning>" + + " <cluster-controller>" + + " <min-distributor-up-ratio>0.418</min-distributor-up-ratio>" + + " </cluster-controller>" + + " </tuning>" + + " </content>" + + " </services>"; VespaModel twoContentModel = createEnd2EndOneNode(new TestProperties().setHostedVespa(true) - .setMultitenant(true), - twoContentServices); - assertNotNull("Shared cluster controller with content", twoContentModel.getAdmin().getClusterControllers()); + .setMultitenant(true), + twoContentServices); + assertNotNull(twoContentModel.getAdmin().getClusterControllers(), "Shared cluster controller with content"); ClusterControllerContainerCluster clusterControllers = twoContentModel.getAdmin().getClusterControllers(); @@ -1204,11 +1202,11 @@ public class ContentClusterTest extends ContentBaseTest { assertEquals(0.418, devNullBuilder.build().min_distributor_up_ratio(), 1e-9); assertZookeeperServerImplementation("com.yahoo.vespa.zookeeper.ReconfigurableVespaZooKeeperServer", - clusterControllers); + clusterControllers); assertZookeeperServerImplementation("com.yahoo.vespa.zookeeper.Reconfigurer", - clusterControllers); + clusterControllers); assertZookeeperServerImplementation("com.yahoo.vespa.zookeeper.VespaZooKeeperAdminImpl", - clusterControllers); + clusterControllers); } } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/ContentSchemaClusterTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/ContentSchemaClusterTest.java index 67260ce1f9d..da892934070 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/content/ContentSchemaClusterTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/content/ContentSchemaClusterTest.java @@ -12,7 +12,7 @@ import com.yahoo.vespa.model.content.cluster.ContentCluster; import com.yahoo.vespa.model.content.utils.ContentClusterBuilder; import com.yahoo.vespa.model.content.utils.DocType; import com.yahoo.vespa.model.content.utils.SchemaBuilder; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Arrays; @@ -21,10 +21,7 @@ import java.util.List; import static com.yahoo.config.model.test.TestUtil.joinLines; import static com.yahoo.vespa.model.content.utils.ContentClusterUtils.createCluster; import static com.yahoo.vespa.model.content.utils.SchemaBuilder.createSchemas; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * Unit tests for content search cluster. @@ -99,51 +96,51 @@ public class ContentSchemaClusterTest { } @Test - public void requireThatProtonInitializeThreadsIsSet() throws Exception { + void requireThatProtonInitializeThreadsIsSet() throws Exception { assertEquals(2, getProtonConfig(createClusterWithOneDocumentType()).initialize().threads()); assertEquals(3, getProtonConfig(createClusterWithTwoDocumentType()).initialize().threads()); } @Test - public void requireThatProtonResourceLimitsCanBeSet() throws Exception { + void requireThatProtonResourceLimitsCanBeSet() throws Exception { assertProtonResourceLimits(0.88, 0.77, new ContentClusterBuilder().protonDiskLimit(0.88).protonMemoryLimit(0.77).getXml()); } @Test - public void requireThatOnlyDiskLimitCanBeSet() throws Exception { + void requireThatOnlyDiskLimitCanBeSet() throws Exception { assertProtonResourceLimits(0.88, 0.9, new ContentClusterBuilder().protonDiskLimit(0.88).getXml()); } @Test - public void requireThatOnlyMemoryLimitCanBeSet() throws Exception { + void requireThatOnlyMemoryLimitCanBeSet() throws Exception { assertProtonResourceLimits(0.9, 0.77, new ContentClusterBuilder().protonMemoryLimit(0.77).getXml()); } @Test - public void cluster_controller_resource_limits_can_be_set() throws Exception { + void cluster_controller_resource_limits_can_be_set() throws Exception { assertClusterControllerResourceLimits(0.92, 0.93, new ContentClusterBuilder().clusterControllerDiskLimit(0.92).clusterControllerMemoryLimit(0.93).getXml()); } @Test - public void resource_limits_are_derived_from_the_other_if_not_specified() throws Exception { + void resource_limits_are_derived_from_the_other_if_not_specified() throws Exception { var cluster = createCluster(new ContentClusterBuilder().clusterControllerDiskLimit(0.5).protonMemoryLimit(0.95).getXml()); assertProtonResourceLimits(0.8, 0.95, cluster); assertClusterControllerResourceLimits(0.5, 0.94, cluster); } @Test - public void default_resource_limits_with_feed_block_in_distributor() throws Exception { + void default_resource_limits_with_feed_block_in_distributor() throws Exception { var cluster = createCluster(new ContentClusterBuilder().getXml()); assertProtonResourceLimits(0.9, 0.9, cluster); assertClusterControllerResourceLimits(0.75, 0.8, cluster); } @Test - public void requireThatGloballyDistributedDocumentTypeIsTaggedAsSuch() throws Exception { + void requireThatGloballyDistributedDocumentTypeIsTaggedAsSuch() throws Exception { ProtonConfig cfg = getProtonConfig(createClusterWithGlobalType()); assertEquals(2, cfg.documentdb().size()); assertDocumentDb("global", true, cfg.documentdb(0)); @@ -156,7 +153,7 @@ public class ContentSchemaClusterTest { } @Test - public void require_that_document_types_with_references_are_topologically_sorted() throws Exception { + void require_that_document_types_with_references_are_topologically_sorted() throws Exception { ProtonConfig cfg = getProtonConfig(createClusterWithThreeDocumentTypes()); assertEquals(3, cfg.documentdb().size()); assertDocumentDb("c", true, cfg.documentdb(0)); @@ -202,7 +199,7 @@ public class ContentSchemaClusterTest { } @Test - public void require_that_document_types_belong_to_correct_bucket_spaces() throws Exception { + void require_that_document_types_belong_to_correct_bucket_spaces() throws Exception { BucketspacesConfig config = getBucketspacesConfig(createClusterWithGlobalType()); assertEquals(2, config.documenttype().size()); assertDocumentType("global", "global", config.documenttype(0)); @@ -210,7 +207,7 @@ public class ContentSchemaClusterTest { } @Test - public void bucket_space_config_builder_returns_correct_mappings() throws Exception { + void bucket_space_config_builder_returns_correct_mappings() throws Exception { ContentCluster cluster = createClusterWithGlobalType(); BucketspacesConfig expected = getBucketspacesConfig(cluster); AllClustersBucketSpacesConfig.Cluster actual = cluster.clusterBucketSpaceConfigBuilder().build(); @@ -223,13 +220,13 @@ public class ContentSchemaClusterTest { } @Test - public void cluster_with_global_document_types_sets_cluster_controller_global_docs_config_option() throws Exception { + void cluster_with_global_document_types_sets_cluster_controller_global_docs_config_option() throws Exception { ContentCluster cluster = createClusterWithGlobalType(); assertTrue(getFleetcontrollerConfig(cluster).cluster_has_global_document_types()); } @Test - public void cluster_without_global_document_types_unsets_cluster_controller_global_docs_config_option() throws Exception { + void cluster_without_global_document_types_unsets_cluster_controller_global_docs_config_option() throws Exception { ContentCluster cluster = createClusterWithoutGlobalType(); assertFalse(getFleetcontrollerConfig(cluster).cluster_has_global_document_types()); } @@ -241,21 +238,21 @@ public class ContentSchemaClusterTest { } @Test - public void fsync_is_controllable() throws Exception { + void fsync_is_controllable() throws Exception { assertTrue(getTlsConfig(createCluster(new ContentClusterBuilder().getXml())).usefsync()); assertTrue(getTlsConfig(createCluster(new ContentClusterBuilder().syncTransactionLog(true).getXml())).usefsync()); assertFalse(getTlsConfig(createCluster(new ContentClusterBuilder().syncTransactionLog(false).getXml())).usefsync()); } @Test - public void verifyDefaultDocStoreCompression() throws Exception { + void verifyDefaultDocStoreCompression() throws Exception { ProtonConfig cfg = getProtonConfig(createCluster(new ContentClusterBuilder().getXml())); assertEquals(3, cfg.summary().log().chunk().compression().level()); assertEquals(3, cfg.summary().log().compact().compression().level()); } @Test - public void verifyDefaultDiskBloatFactor() throws Exception { + void verifyDefaultDiskBloatFactor() throws Exception { var defaultCfg = getProtonConfig(createCluster(new ContentClusterBuilder().getXml())); assertEquals(0.25, defaultCfg.flush().memory().diskbloatfactor(), EPSILON); assertEquals(0.25, defaultCfg.flush().memory().each().diskbloatfactor(), EPSILON); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/ContentSchemaTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/ContentSchemaTest.java index 952a0b945dd..ad17d6f385b 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/content/ContentSchemaTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/content/ContentSchemaTest.java @@ -1,10 +1,10 @@ // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.model.content; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; /** * @author Simon Thoresen Hult @@ -12,7 +12,7 @@ import static org.junit.Assert.assertNull; public class ContentSchemaTest { @Test - public void requireThatAccessorsWork() { + void requireThatAccessorsWork() { ContentSearch search = new ContentSearch.Builder() .setQueryTimeout(1.0) .setVisibilityDelay(2.0) @@ -22,7 +22,7 @@ public class ContentSchemaTest { } @Test - public void requireThatDefaultsAreNull() { + void requireThatDefaultsAreNull() { ContentSearch search = new ContentSearch.Builder().build(); assertNull(search.getQueryTimeout()); assertNull(search.getVisibilityDelay()); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/DispatchTuningTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/DispatchTuningTest.java index c3a40946c06..cddbe267628 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/content/DispatchTuningTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/content/DispatchTuningTest.java @@ -1,11 +1,10 @@ // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.model.content; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Simon Thoresen Hult @@ -13,7 +12,7 @@ import static org.junit.Assert.assertTrue; public class DispatchTuningTest { @Test - public void requireThatAccessorWork() { + void requireThatAccessorWork() { DispatchTuning dispatch = new DispatchTuning.Builder() .setMaxHitsPerPartition(69) .setDispatchPolicy("round-robin") @@ -22,29 +21,30 @@ public class DispatchTuningTest { .build(); assertEquals(69, dispatch.getMaxHitsPerPartition().intValue()); assertEquals(12.5, dispatch.getMinActiveDocsCoverage().doubleValue(), 0.0); - assertTrue(DispatchTuning.DispatchPolicy.ROUNDROBIN == dispatch.getDispatchPolicy()); + assertEquals(DispatchTuning.DispatchPolicy.ROUNDROBIN, dispatch.getDispatchPolicy()); assertEquals(18.3, dispatch.getTopkProbability(), 0.0); } + @Test - public void requireThatRandomDispatchWork() { + void requireThatRandomDispatchWork() { DispatchTuning dispatch = new DispatchTuning.Builder() .setDispatchPolicy("random") .build(); - assertTrue(DispatchTuning.DispatchPolicy.ADAPTIVE == dispatch.getDispatchPolicy()); + assertEquals(DispatchTuning.DispatchPolicy.ADAPTIVE, dispatch.getDispatchPolicy()); assertNull(dispatch.getMinActiveDocsCoverage()); } @Test - public void requireThatWeightedDispatchWork() { + void requireThatWeightedDispatchWork() { DispatchTuning dispatch = new DispatchTuning.Builder() .setDispatchPolicy("adaptive") .build(); - assertTrue(DispatchTuning.DispatchPolicy.ADAPTIVE == dispatch.getDispatchPolicy()); + assertEquals(DispatchTuning.DispatchPolicy.ADAPTIVE, dispatch.getDispatchPolicy()); assertNull(dispatch.getMinActiveDocsCoverage()); } @Test - public void requireThatDefaultsAreNull() { + void requireThatDefaultsAreNull() { DispatchTuning dispatch = new DispatchTuning.Builder().build(); assertNull(dispatch.getMaxHitsPerPartition()); assertNull(dispatch.getDispatchPolicy()); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/DistributorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/DistributorTest.java index 015356d6088..06f78a1c68d 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/content/DistributorTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/content/DistributorTest.java @@ -9,13 +9,11 @@ import com.yahoo.vespa.model.content.cluster.ContentCluster; import com.yahoo.vespa.model.content.utils.ContentClusterUtils; import com.yahoo.vespa.model.content.utils.DocType; import com.yahoo.vespa.model.test.utils.ApplicationPackageUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * Test for content DistributorCluster. @@ -37,14 +35,14 @@ public class DistributorTest { } @Test - public void testBasics() { + void testBasics() { StorServerConfig.Builder builder = new StorServerConfig.Builder(); parse("<content id=\"foofighters\"><documents/>\n" + - " <group>" + - " <node distribution-key=\"0\" hostalias=\"mockhost\"/>" + - " </group>" + - "</content>\n"). + " <group>" + + " <node distribution-key=\"0\" hostalias=\"mockhost\"/>" + + " </group>" + + "</content>\n"). getConfig(builder); StorServerConfig config = new StorServerConfig(builder); @@ -53,7 +51,7 @@ public class DistributorTest { } @Test - public void testRevertDefaultOffForSearch() { + void testRevertDefaultOffForSearch() { StorDistributormanagerConfig.Builder builder = new StorDistributormanagerConfig.Builder(); parse("<cluster id=\"storage\">\n" + " <documents/>" + @@ -66,7 +64,7 @@ public class DistributorTest { } @Test - public void testSplitAndJoin() { + void testSplitAndJoin() { StorDistributormanagerConfig.Builder builder = new StorDistributormanagerConfig.Builder(); parse("<cluster id=\"storage\">\n" + " <documents/>" + @@ -89,7 +87,7 @@ public class DistributorTest { } @Test - public void testThatGroupsAreCountedInWhenComputingSplitBits() { + void testThatGroupsAreCountedInWhenComputingSplitBits() { StorDistributormanagerConfig.Builder builder = new StorDistributormanagerConfig.Builder(); ContentCluster cluster = parseCluster("<cluster id=\"storage\">\n" + " <documents/>" + @@ -145,7 +143,7 @@ public class DistributorTest { } @Test - public void testMaxMergesPerNode() { + void testMaxMergesPerNode() { StorDistributormanagerConfig.Builder builder = new StorDistributormanagerConfig.Builder(); DistributorCluster dcluster = parse("<content id=\"storage\">\n" + " <documents/>" + @@ -159,30 +157,30 @@ public class DistributorTest { builder = new StorDistributormanagerConfig.Builder(); dcluster = parse("<content id=\"storage\">\n" + - " <documents/>" + - " <tuning>\n" + - " <merges max-nodes-per-merge=\"4\"/>\n" + - " </tuning>\n" + - " <group>" + - " <node distribution-key=\"0\" hostalias=\"mockhost\"/>" + - " </group>" + - "</content>"); + " <documents/>" + + " <tuning>\n" + + " <merges max-nodes-per-merge=\"4\"/>\n" + + " </tuning>\n" + + " <group>" + + " <node distribution-key=\"0\" hostalias=\"mockhost\"/>" + + " </group>" + + "</content>"); ((ContentCluster) dcluster.getParent()).getConfig(builder); conf = new StorDistributormanagerConfig(builder); assertEquals(4, conf.maximum_nodes_per_merge()); } @Test - public void testGarbageCollectionSetExplicitly() { + void testGarbageCollectionSetExplicitly() { StorDistributormanagerConfig.Builder builder = new StorDistributormanagerConfig.Builder(); parse("<cluster id=\"storage\">\n" + - " <documents garbage-collection=\"true\">\n" + - " <document type=\"music\"/>\n" + - " </documents>\n" + + " <documents garbage-collection=\"true\">\n" + + " <document type=\"music\"/>\n" + + " </documents>\n" + " <group>" + " <node distribution-key=\"0\" hostalias=\"mockhost\"/>" + " </group>" + - "</cluster>").getConfig(builder); + "</cluster>").getConfig(builder); StorDistributormanagerConfig conf = new StorDistributormanagerConfig(builder); assertEquals(3600, conf.garbagecollection().interval()); @@ -190,7 +188,7 @@ public class DistributorTest { } @Test - public void testGarbageCollectionInterval() { + void testGarbageCollectionInterval() { StorDistributormanagerConfig.Builder builder = new StorDistributormanagerConfig.Builder(); parse("<cluster id=\"storage\">\n" + " <documents garbage-collection=\"true\" garbage-collection-interval=\"30\">\n" + @@ -206,7 +204,7 @@ public class DistributorTest { } @Test - public void testGarbageCollectionOffByDefault() { + void testGarbageCollectionOffByDefault() { StorDistributormanagerConfig.Builder builder = new StorDistributormanagerConfig.Builder(); parse("<cluster id=\"storage\">\n" + " <documents>\n" + @@ -223,7 +221,7 @@ public class DistributorTest { } @Test - public void testComplexGarbageCollectionSelectionForIndexedSearch() { + void testComplexGarbageCollectionSelectionForIndexedSearch() { StorDistributormanagerConfig.Builder builder = new StorDistributormanagerConfig.Builder(); parse("<cluster id=\"foo\">\n" + " <documents garbage-collection=\"true\" selection=\"true\">" + @@ -243,7 +241,7 @@ public class DistributorTest { } @Test - public void testGarbageCollectionDisabledIfForced() { + void testGarbageCollectionDisabledIfForced() { StorDistributormanagerConfig.Builder builder = new StorDistributormanagerConfig.Builder(); parse("<cluster id=\"foo\">\n" + " <documents selection=\"true\" garbage-collection=\"false\" garbage-collection-interval=\"30\">\n" + @@ -261,7 +259,7 @@ public class DistributorTest { } @Test - public void testPortOverride() { + void testPortOverride() { StorCommunicationmanagerConfig.Builder builder = new StorCommunicationmanagerConfig.Builder(); DistributorCluster cluster = parse("<cluster id=\"storage\" distributor-base-port=\"14065\">" + @@ -277,7 +275,7 @@ public class DistributorTest { } @Test - public void testCommunicationManagerDefaults() { + void testCommunicationManagerDefaults() { StorCommunicationmanagerConfig.Builder builder = new StorCommunicationmanagerConfig.Builder(); DistributorCluster cluster = parse("<cluster id=\"storage\">" + @@ -305,38 +303,38 @@ public class DistributorTest { } @Test - public void bucket_activation_disabled_if_no_documents_in_indexed_mode() { + void bucket_activation_disabled_if_no_documents_in_indexed_mode() { StorDistributormanagerConfig config = clusterXmlToConfig( generateXmlForDocTypes(DocType.storeOnly("music"))); assertTrue(config.disable_bucket_activation()); } @Test - public void bucket_activation_enabled_with_single_indexed_document() { + void bucket_activation_enabled_with_single_indexed_document() { StorDistributormanagerConfig config = clusterXmlToConfig( generateXmlForDocTypes(DocType.index("music"))); assertFalse(config.disable_bucket_activation()); } @Test - public void bucket_activation_enabled_with_multiple_indexed_documents() { + void bucket_activation_enabled_with_multiple_indexed_documents() { StorDistributormanagerConfig config = clusterXmlToConfig( generateXmlForDocTypes(DocType.index("music"), - DocType.index("movies"))); + DocType.index("movies"))); assertFalse(config.disable_bucket_activation()); } @Test - public void bucket_activation_enabled_if_at_least_one_document_indexed() { + void bucket_activation_enabled_if_at_least_one_document_indexed() { StorDistributormanagerConfig config = clusterXmlToConfig( generateXmlForDocTypes(DocType.storeOnly("music"), - DocType.streaming("bunnies"), - DocType.index("movies"))); + DocType.streaming("bunnies"), + DocType.index("movies"))); assertFalse(config.disable_bucket_activation()); } @Test - public void bucket_activation_disabled_for_single_streaming_type() { + void bucket_activation_disabled_for_single_streaming_type() { StorDistributormanagerConfig config = clusterXmlToConfig( generateXmlForDocTypes(DocType.streaming("music"))); assertTrue(config.disable_bucket_activation()); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/FleetControllerClusterTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/FleetControllerClusterTest.java index f9fcb777408..1e6847a47be 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/content/FleetControllerClusterTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/content/FleetControllerClusterTest.java @@ -8,11 +8,11 @@ import com.yahoo.config.model.test.MockRoot; import com.yahoo.text.XML; import com.yahoo.vespa.config.content.FleetcontrollerConfig; import com.yahoo.vespa.model.builder.xml.dom.ModelElement; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.w3c.dom.Document; import static com.yahoo.config.model.test.TestUtil.joinLines; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class FleetControllerClusterTest { @@ -36,7 +36,7 @@ public class FleetControllerClusterTest { } @Test - public void testParameters() { + void testParameters() { FleetcontrollerConfig.Builder builder = new FleetcontrollerConfig.Builder(); parse("<cluster id=\"storage\">\n" + " <documents/>" + @@ -65,7 +65,7 @@ public class FleetControllerClusterTest { } @Test - public void testDurationParameters() { + void testDurationParameters() { FleetcontrollerConfig.Builder builder = new FleetcontrollerConfig.Builder(); parse("<cluster id=\"storage\">\n" + " <documents/>" + @@ -82,7 +82,7 @@ public class FleetControllerClusterTest { } @Test - public void min_node_ratio_per_group_tuning_config_is_propagated() { + void min_node_ratio_per_group_tuning_config_is_propagated() { FleetcontrollerConfig.Builder builder = new FleetcontrollerConfig.Builder(); parse("<cluster id=\"storage\">\n" + " <documents/>\n" + @@ -97,18 +97,18 @@ public class FleetControllerClusterTest { } @Test - public void min_node_ratio_per_group_is_implicitly_zero_when_omitted() { + void min_node_ratio_per_group_is_implicitly_zero_when_omitted() { var config = getConfigForBasicCluster(); assertEquals(0.0, config.min_node_ratio_per_group(), 0.01); } @Test - public void default_cluster_feed_block_limits_are_set() { + void default_cluster_feed_block_limits_are_set() { assertLimits(0.75, 0.8, getConfigForBasicCluster()); } @Test - public void resource_limits_can_be_set_in_tuning() { + void resource_limits_can_be_set_in_tuning() { assertLimits(0.6, 0.7, getConfigForResourceLimitsTuning(0.6, 0.7)); assertLimits(0.6, 0.8, getConfigForResourceLimitsTuning(0.6, null)); assertLimits(0.75, 0.7, getConfigForResourceLimitsTuning(null, 0.7)); @@ -140,7 +140,7 @@ public class FleetControllerClusterTest { } @Test - public void feature_flag_controls_min_node_ratio_per_group() { + void feature_flag_controls_min_node_ratio_per_group() { verifyFeatureFlagControlsMinNodeRatioPerGroup(0.0, new TestProperties()); verifyFeatureFlagControlsMinNodeRatioPerGroup(0.3, new TestProperties().setMinNodeRatioPerGroup(0.3)); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/GenericConfigTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/GenericConfigTest.java index e6e8a02e951..9fcf426e2e8 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/content/GenericConfigTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/content/GenericConfigTest.java @@ -7,10 +7,10 @@ import com.yahoo.vespa.model.content.cluster.ContentCluster; import com.yahoo.vespa.model.content.storagecluster.StorageCluster; import com.yahoo.vespa.model.test.utils.ApplicationPackageUtils; import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithMockPkg; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author gjoranv @@ -47,13 +47,13 @@ public class GenericConfigTest { "</services>"; } - @Before + @BeforeEach public void getVespaModel() { model = (new VespaModelCreatorWithMockPkg(ContentBaseTest.getHosts(), servicesXml(), ApplicationPackageUtils.generateSchemas("type1"))).create(); } @Test - public void config_override_on_root_is_visible_on_storage_cluster() { + void config_override_on_root_is_visible_on_storage_cluster() { StorageCluster cluster = model.getContentClusters().get("storage").getStorageCluster(); StorFilestorConfig config = model.getConfig(StorFilestorConfig.class, cluster.getConfigId()); @@ -61,7 +61,7 @@ public class GenericConfigTest { } @Test - public void config_override_on_root_is_visible_on_content_cluster() { + void config_override_on_root_is_visible_on_content_cluster() { ContentCluster cluster = model.getContentClusters().get("storage"); StorFilestorConfig config = model.getConfig(StorFilestorConfig.class, cluster.getConfigId()); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/GlobalDistributionValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/GlobalDistributionValidatorTest.java index a47d25ab391..4def4e0c10f 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/content/GlobalDistributionValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/content/GlobalDistributionValidatorTest.java @@ -3,7 +3,7 @@ package com.yahoo.vespa.model.content; import com.yahoo.documentmodel.NewDocumentType; import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithFilePkg; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.HashMap; import java.util.HashSet; @@ -14,8 +14,8 @@ import java.util.stream.Stream; import static java.util.Collections.emptyMap; import static java.util.Collections.emptySet; import static java.util.stream.Collectors.toSet; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author bjorncs @@ -23,20 +23,20 @@ import static org.junit.Assert.fail; public class GlobalDistributionValidatorTest { @Test - public void validation_succeeds_on_no_documents() { + void validation_succeeds_on_no_documents() { new GlobalDistributionValidator() .validate(emptyMap(), emptySet()); } @Test - public void validation_succeeds_on_no_global_documents() { + void validation_succeeds_on_no_global_documents() { Fixture fixture = new Fixture() .addNonGlobalDocument(createDocumentType("foo")); validate(fixture); } @Test - public void throws_exception_if_referenced_document_not_global() { + void throws_exception_if_referenced_document_not_global() { NewDocumentType parent = createDocumentType("parent"); Fixture fixture = new Fixture() .addNonGlobalDocument(parent) @@ -51,7 +51,7 @@ public class GlobalDistributionValidatorTest { } @Test - public void validation_succeeds_if_referenced_document_is_global() { + void validation_succeeds_if_referenced_document_is_global() { NewDocumentType parent = createDocumentType("parent"); Fixture fixture = new Fixture() .addGlobalDocument(parent) @@ -60,7 +60,7 @@ public class GlobalDistributionValidatorTest { } @Test - public void throws_exception_on_unknown_document() { + void throws_exception_on_unknown_document() { NewDocumentType unknown = new NewDocumentType(new NewDocumentType.Name("unknown")); NewDocumentType child = createDocumentType("child", unknown); Fixture fixture = new Fixture() @@ -76,7 +76,7 @@ public class GlobalDistributionValidatorTest { } @Test - public void throws_exception_if_referenced_document_not_global_end_to_end() { + void throws_exception_if_referenced_document_not_global_end_to_end() { try { new VespaModelCreatorWithFilePkg("src/test/cfg/application/validation/global_distribution_validation/").create(); fail(); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/IndexedHierarchicDistributionTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/IndexedHierarchicDistributionTest.java index 7d7ba7994aa..07c032a52a5 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/content/IndexedHierarchicDistributionTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/content/IndexedHierarchicDistributionTest.java @@ -6,7 +6,7 @@ import com.yahoo.vespa.model.content.cluster.ContentCluster; import com.yahoo.vespa.model.search.DispatchGroup; import com.yahoo.vespa.model.search.SearchInterface; import com.yahoo.vespa.model.search.SearchNode; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; @@ -15,10 +15,7 @@ import java.util.Optional; import static com.yahoo.config.model.test.TestUtil.joinLines; import static com.yahoo.vespa.model.content.utils.ContentClusterUtils.createCluster; import static com.yahoo.vespa.model.content.utils.ContentClusterUtils.createClusterXml; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; /** * Unit tests for hierarchic distribution in an indexed content cluster. @@ -73,7 +70,7 @@ public class IndexedHierarchicDistributionTest { } @Test - public void requireThatSearchNodesAreCorrectWithOneGroup() throws Exception { + void requireThatSearchNodesAreCorrectWithOneGroup() throws Exception { ContentCluster c = getOneGroupCluster(); List<SearchNode> searchNodes = c.getSearch().getSearchNodes(); @@ -84,13 +81,13 @@ public class IndexedHierarchicDistributionTest { } @Test - public void requireThatActivePerLeafGroupIsDefaultWithOneGroup() throws Exception { + void requireThatActivePerLeafGroupIsDefaultWithOneGroup() throws Exception { ContentCluster c = getOneGroupCluster(); assertFalse(getStorDistributionConfig(c).active_per_leaf_group()); } @Test - public void requireThatSearchNodesAreCorrectWithTwoGroups() throws Exception { + void requireThatSearchNodesAreCorrectWithTwoGroups() throws Exception { ContentCluster c = getTwoGroupsCluster(); List<SearchNode> searchNodes = c.getSearch().getSearchNodes(); @@ -104,7 +101,7 @@ public class IndexedHierarchicDistributionTest { } @Test - public void requireThatActivePerLeafGroupIsSetWithTwoGroups() throws Exception { + void requireThatActivePerLeafGroupIsSetWithTwoGroups() throws Exception { ContentCluster c = getTwoGroupsCluster(); assertTrue(getStorDistributionConfig(c).active_per_leaf_group()); } @@ -174,7 +171,7 @@ public class IndexedHierarchicDistributionTest { } @Test - public void requireThatWeMustHaveOnlyOneGroupLevel() { + void requireThatWeMustHaveOnlyOneGroupLevel() { try { getIllegalMultipleGroupsLevelCluster(); fail("Did not get expected Exception"); @@ -184,7 +181,7 @@ public class IndexedHierarchicDistributionTest { } @Test - public void requireThatLeafGroupsMustHaveEqualNumberOfNodes() { + void requireThatLeafGroupsMustHaveEqualNumberOfNodes() { try { getIllegalGroupsCluster(); fail("Did not get expected Exception"); @@ -194,14 +191,14 @@ public class IndexedHierarchicDistributionTest { } @Test - public void requireThatLeafGroupsCanHaveUnequalNumberOfNodesIfRandomPolicy() throws Exception { + void requireThatLeafGroupsCanHaveUnequalNumberOfNodesIfRandomPolicy() throws Exception { ContentCluster c = getOddGroupsCluster(); DispatchGroup dg = c.getSearch().getIndexed().getRootDispatch(); assertEquals(8, dg.getRowBits()); assertEquals(3, dg.getNumPartitions()); assertTrue(dg.useFixedRowInDispatch()); ArrayList<SearchInterface> list = new ArrayList<>(); - for(SearchInterface si : dg.getSearchersIterable()) { + for (SearchInterface si : dg.getSearchersIterable()) { list.add(si); } assertEquals(5, list.size()); @@ -218,7 +215,7 @@ public class IndexedHierarchicDistributionTest { } @Test - public void requireThatLeafGroupsCountMustBeAFactorOfRedundancy() { + void requireThatLeafGroupsCountMustBeAFactorOfRedundancy() { try { getTwoGroupsCluster(3, 3, "2|*"); fail("Did not get expected Exception"); @@ -228,7 +225,7 @@ public class IndexedHierarchicDistributionTest { } @Test - public void requireThatRedundancyPerGroupMustBeIsEqual() { + void requireThatRedundancyPerGroupMustBeIsEqual() { try { getTwoGroupsCluster(4, 4, "1|*"); fail("Did not get expected Exception"); @@ -238,7 +235,7 @@ public class IndexedHierarchicDistributionTest { } @Test - public void requireThatReadyCopiesMustBeEqualToRedundancy() { + void requireThatReadyCopiesMustBeEqualToRedundancy() { try { getTwoGroupsCluster(4, 3, "2|*"); fail("Did not get expected Exception"); @@ -248,7 +245,7 @@ public class IndexedHierarchicDistributionTest { } @Test - public void allowLessReadyCopiesThanRedundancy() throws Exception { + void allowLessReadyCopiesThanRedundancy() throws Exception { getTwoGroupsCluster(4, 2, "2|*"); } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/IndexedSchemaNodeNamingTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/IndexedSchemaNodeNamingTest.java index 17e295c1c2a..d2de9d6c23a 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/content/IndexedSchemaNodeNamingTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/content/IndexedSchemaNodeNamingTest.java @@ -5,14 +5,14 @@ import com.yahoo.vespa.config.search.core.ProtonConfig; import com.yahoo.vespa.defaults.Defaults; import com.yahoo.vespa.model.content.cluster.ContentCluster; import com.yahoo.vespa.model.search.SearchNode; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.List; import static com.yahoo.config.model.test.TestUtil.joinLines; import static com.yahoo.vespa.model.content.utils.ContentClusterUtils.createCluster; import static com.yahoo.vespa.model.content.utils.ContentClusterUtils.createClusterXml; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Unit tests for the naming of search nodes base dir and config ids in an indexed content cluster. @@ -69,14 +69,14 @@ public class IndexedSchemaNodeNamingTest { } @Test - public void requireThatSingleNodeIsNamedAfterDistributionKey() throws Exception { + void requireThatSingleNodeIsNamedAfterDistributionKey() throws Exception { ContentCluster cluster = getSingleNodeCluster(); List<SearchNode> nodes = cluster.getSearch().getSearchNodes(); assertSearchNode("n3", "3", nodes.get(0)); } @Test - public void requireThatMultipleNodesAreNamedAfterDistributionKey() throws Exception { + void requireThatMultipleNodesAreNamedAfterDistributionKey() throws Exception { ContentCluster cluster = getMultiNodeCluster(); List<SearchNode> nodes = cluster.getSearch().getSearchNodes(); assertEquals(3, nodes.size()); @@ -86,7 +86,7 @@ public class IndexedSchemaNodeNamingTest { } @Test - public void requireThatNodesInHierarchicGroupsAreNamedAfterDistributionKey() throws Exception { + void requireThatNodesInHierarchicGroupsAreNamedAfterDistributionKey() throws Exception { ContentCluster cluster = getMultiGroupCluster(); List<SearchNode> nodes = cluster.getSearch().getSearchNodes(); assertEquals(4, nodes.size()); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/IndexedTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/IndexedTest.java index a39cbc60a89..f65a72427de 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/content/IndexedTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/content/IndexedTest.java @@ -15,13 +15,11 @@ import com.yahoo.vespa.model.routing.Routing; import com.yahoo.vespa.model.search.IndexedSearchCluster; import com.yahoo.vespa.model.test.utils.ApplicationPackageUtils; import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithMockPkg; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.*; /** * Test for using the content model to create indexed search clusters. @@ -111,7 +109,7 @@ public class IndexedTest extends ContentBaseTest { } @Test - public void requireMultipleDocumentTypes() { + void requireMultipleDocumentTypes() { VespaModelCreatorWithMockPkg creator = getIndexedVespaModelCreator(); VespaModel model = creator.create(); DeployState deployState = creator.deployState; @@ -126,7 +124,7 @@ public class IndexedTest extends ContentBaseTest { } @Test - public void requireIndexedOnlyServices() { + void requireIndexedOnlyServices() { VespaModel model = getIndexedVespaModel(); // TODO // HostResource h = model.getHostSystem().getHosts().get(0); @@ -155,7 +153,7 @@ public class IndexedTest extends ContentBaseTest { } @Test - public void requireProtonStreamingOnly() { + void requireProtonStreamingOnly() { VespaModel model = getStreamingVespaModel(); // TODO // HostResource h = model.getHostSystem().getHosts().get(0); @@ -173,7 +171,7 @@ public class IndexedTest extends ContentBaseTest { } @Test - public void requireCorrectClusterList() { + void requireCorrectClusterList() { VespaModel model = getStreamingVespaModel(); ContentCluster s = model.getContentClusters().get("test"); assertNotNull(s); @@ -185,38 +183,38 @@ public class IndexedTest extends ContentBaseTest { } @Test - public void testContentSummaryStore() { - String services= + void testContentSummaryStore() { + String services = "<services version='1.0'>" + - "<admin version='2.0'><adminserver hostalias='node0' /></admin>" + - "<content id='docstore' version='1.0'>\n" + - " <redundancy>1</redundancy>\n" + - " <documents>\n" + - " <document mode='index' type='docstorebench'/>\n" + - " </documents>\n" + - " <group>\n" + - " <node distribution-key='0' hostalias='node0'/>\n" + - " </group>\n" + - " <engine>\n" + - " <proton>\n" + - " <searchable-copies>1</searchable-copies>\n" + - " <tuning>\n" + - " <searchnode>\n" + - " <summary>\n" + - " <store>\n" + - " <logstore>\n" + - " <chunk>\n" + - " <maxsize>2048</maxsize>\n" + - " </chunk>\n" + - " </logstore>\n" + - " </store>\n" + - " </summary>\n" + - " </searchnode>\n" + - " </tuning>\n" + - " </proton>\n" + - " </engine>\n" + - " </content>\n" + - " </services>"; + "<admin version='2.0'><adminserver hostalias='node0' /></admin>" + + "<content id='docstore' version='1.0'>\n" + + " <redundancy>1</redundancy>\n" + + " <documents>\n" + + " <document mode='index' type='docstorebench'/>\n" + + " </documents>\n" + + " <group>\n" + + " <node distribution-key='0' hostalias='node0'/>\n" + + " </group>\n" + + " <engine>\n" + + " <proton>\n" + + " <searchable-copies>1</searchable-copies>\n" + + " <tuning>\n" + + " <searchnode>\n" + + " <summary>\n" + + " <store>\n" + + " <logstore>\n" + + " <chunk>\n" + + " <maxsize>2048</maxsize>\n" + + " </chunk>\n" + + " </logstore>\n" + + " </store>\n" + + " </summary>\n" + + " </searchnode>\n" + + " </tuning>\n" + + " </proton>\n" + + " </engine>\n" + + " </content>\n" + + " </services>"; List<String> sds = ApplicationPackageUtils.generateSchemas("docstorebench"); VespaModel model = new VespaModelCreatorWithMockPkg(getHosts(), services, sds).create(); @@ -225,21 +223,21 @@ public class IndexedTest extends ContentBaseTest { } @Test - public void testMixedIndexAndStoreOnly() { - String services= + void testMixedIndexAndStoreOnly() { + String services = "<services version='1.0'>" + - " <admin version='2.0'><adminserver hostalias='node0' /></admin>" + - " <content id='docstore' version=\"1.0\">" + - " <redundancy>1</redundancy>" + - " <documents>" + - " <document type=\"index_me\" mode=\"index\"/>" + - " <document type=\"store_me\" mode=\"store-only\"/>" + - " </documents>" + - " <group>" + - " <node distribution-key=\"0\" hostalias=\"node0\"/>" + - " </group>" + - " </content>" + - "</services>"; + " <admin version='2.0'><adminserver hostalias='node0' /></admin>" + + " <content id='docstore' version=\"1.0\">" + + " <redundancy>1</redundancy>" + + " <documents>" + + " <document type=\"index_me\" mode=\"index\"/>" + + " <document type=\"store_me\" mode=\"store-only\"/>" + + " </documents>" + + " <group>" + + " <node distribution-key=\"0\" hostalias=\"node0\"/>" + + " </group>" + + " </content>" + + "</services>"; List<String> sds = ApplicationPackageUtils.generateSchemas("index_me", "store_me"); VespaModel model = new VespaModelCreatorWithMockPkg(getHosts(), services, sds).create(); @@ -254,7 +252,7 @@ public class IndexedTest extends ContentBaseTest { } @Test - public void requireThatIndexingDocprocGetsConfigIdBasedOnDistributionKey() { + void requireThatIndexingDocprocGetsConfigIdBasedOnDistributionKey() { VespaModel model = getIndexedVespaModel(); ApplicationContainerCluster cluster = model.getContainerClusters().get("container"); assertEquals("container/container.0", cluster.getContainers().get(0).getConfigId()); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/IndexingAndDocprocRoutingTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/IndexingAndDocprocRoutingTest.java index 0b7dbf2eb21..430628238d9 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/content/IndexingAndDocprocRoutingTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/content/IndexingAndDocprocRoutingTest.java @@ -15,7 +15,7 @@ import com.yahoo.vespa.model.routing.Protocol; import com.yahoo.vespa.model.routing.Routing; import com.yahoo.vespa.model.test.utils.ApplicationPackageUtils; import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithMockPkg; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Arrays; @@ -23,10 +23,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; /** * @author Einar M R Rosenvinge @@ -34,7 +31,7 @@ import static org.junit.Assert.fail; public class IndexingAndDocprocRoutingTest extends ContentBaseTest { @Test - public void oneContentOneDoctypeImplicitIndexingClusterImplicitIndexingChain() { + void oneContentOneDoctypeImplicitIndexingClusterImplicitIndexingChain() { final String CLUSTERNAME = "musiccluster"; SearchClusterSpec searchCluster = new SearchClusterSpec(CLUSTERNAME, null, null); searchCluster.searchDefs.add(new SearchDefSpec("music", "artist", "album")); @@ -44,7 +41,7 @@ public class IndexingAndDocprocRoutingTest extends ContentBaseTest { } @Test - public void oneContentTwoDoctypesImplicitIndexingClusterImplicitIndexingChain() { + void oneContentTwoDoctypesImplicitIndexingClusterImplicitIndexingChain() { final String CLUSTERNAME = "musicandbookscluster"; SearchClusterSpec searchCluster = new SearchClusterSpec(CLUSTERNAME, null, null); searchCluster.searchDefs.add(new SearchDefSpec("music", "artist", "album")); @@ -55,7 +52,7 @@ public class IndexingAndDocprocRoutingTest extends ContentBaseTest { } @Test - public void twoContentTwoDoctypesImplicitIndexingClusterImplicitIndexingChain() { + void twoContentTwoDoctypesImplicitIndexingClusterImplicitIndexingChain() { final String MUSIC = "musiccluster"; SearchClusterSpec musicCluster = new SearchClusterSpec(MUSIC, null, null); musicCluster.searchDefs.add(new SearchDefSpec("music", "artist", "album")); @@ -67,7 +64,7 @@ public class IndexingAndDocprocRoutingTest extends ContentBaseTest { VespaModel model = getIndexedContentVespaModel(List.of(), List.of(musicCluster, booksCluster)); assertIndexing(model, - new DocprocClusterSpec("container", new DocprocChainSpec("container/chain.indexing"))); + new DocprocClusterSpec("container", new DocprocChainSpec("container/chain.indexing"))); assertFeedingRoute(model, MUSIC, "container/chain.indexing"); assertFeedingRoute(model, BOOKS, "container/chain.indexing"); @@ -75,7 +72,7 @@ public class IndexingAndDocprocRoutingTest extends ContentBaseTest { @Test - public void oneContentOneDoctypeExplicitIndexingClusterImplicitIndexingChain() { + void oneContentOneDoctypeExplicitIndexingClusterImplicitIndexingChain() { final String CLUSTERNAME = "musiccluster"; SearchClusterSpec searchCluster = new SearchClusterSpec(CLUSTERNAME, "dpcluster", null); searchCluster.searchDefs.add(new SearchDefSpec("music", "artist", "album")); @@ -85,45 +82,45 @@ public class IndexingAndDocprocRoutingTest extends ContentBaseTest { } @Test - public void oneSearchOneDoctypeExplicitIndexingClusterExplicitIndexingChain() { + void oneSearchOneDoctypeExplicitIndexingClusterExplicitIndexingChain() { String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + - "<services version=\"1.0\">\n" + - " <admin version=\"2.0\">\n" + - " <adminserver hostalias=\"node0\"/> \n" + - " </admin>\n" + - "\n" + - " <content id=\"searchcluster\" version=\"1.0\">\n" + - " <redundancy>2</redundancy>\n" + - " <documents>\n" + - " <document-processing cluster='dpcluster' chain='fooindexing'/>\n" + - " <document type=\"music\" mode=\"index\"/>\n" + - " </documents>\n" + - " <nodes>\n" + - " <node hostalias=\"node0\" distribution-key=\"0\"/>\n" + - " </nodes>\n" + - " </content>\n" + - " \n" + - " <container version='1.0' id='dpcluster'>\n" + - " <document-processing>\n" + - " <chain id='fooindexing' inherits='indexing '/>\n" + - " </document-processing>\n" + - " <nodes>\n" + - " <node hostalias='node0'/>\n" + - " </nodes>\n" + - " <http>\n" + - " <server id='dpcluster' port='8000'/>\n" + - " </http>\n" + - " </container>\n" + - "</services>\n"; + "<services version=\"1.0\">\n" + + " <admin version=\"2.0\">\n" + + " <adminserver hostalias=\"node0\"/> \n" + + " </admin>\n" + + "\n" + + " <content id=\"searchcluster\" version=\"1.0\">\n" + + " <redundancy>2</redundancy>\n" + + " <documents>\n" + + " <document-processing cluster='dpcluster' chain='fooindexing'/>\n" + + " <document type=\"music\" mode=\"index\"/>\n" + + " </documents>\n" + + " <nodes>\n" + + " <node hostalias=\"node0\" distribution-key=\"0\"/>\n" + + " </nodes>\n" + + " </content>\n" + + " \n" + + " <container version='1.0' id='dpcluster'>\n" + + " <document-processing>\n" + + " <chain id='fooindexing' inherits='indexing '/>\n" + + " </document-processing>\n" + + " <nodes>\n" + + " <node hostalias='node0'/>\n" + + " </nodes>\n" + + " <http>\n" + + " <server id='dpcluster' port='8000'/>\n" + + " </http>\n" + + " </container>\n" + + "</services>\n"; VespaModel model = getIndexedSearchVespaModel(xml); assertIndexing(model, new DocprocClusterSpec("dpcluster", new DocprocChainSpec("dpcluster/chain.fooindexing", "indexing"), - new DocprocChainSpec("dpcluster/chain.indexing"))); + new DocprocChainSpec("dpcluster/chain.indexing"))); assertFeedingRouteIndexed(model, "searchcluster", "dpcluster/chain.fooindexing"); } @Test - public void twoContentTwoDoctypesExplicitIndexingInSameIndexingCluster() { + void twoContentTwoDoctypesExplicitIndexingInSameIndexingCluster() { final String MUSIC = "musiccluster"; SearchClusterSpec musicCluster = new SearchClusterSpec(MUSIC, "dpcluster", null); musicCluster.searchDefs.add(new SearchDefSpec("music", "artist", "album")); @@ -133,7 +130,7 @@ public class IndexingAndDocprocRoutingTest extends ContentBaseTest { booksCluster.searchDefs.add(new SearchDefSpec("book", "author", "title")); VespaModel model = getIndexedContentVespaModel(List.of(new DocprocClusterSpec("dpcluster")), - List.of(musicCluster, booksCluster)); + List.of(musicCluster, booksCluster)); assertIndexing(model, new DocprocClusterSpec("dpcluster", new DocprocChainSpec("dpcluster/chain.indexing"))); assertFeedingRoute(model, MUSIC, "dpcluster/chain.indexing"); @@ -141,7 +138,7 @@ public class IndexingAndDocprocRoutingTest extends ContentBaseTest { } @Test - public void noContentClustersOneDocprocCluster() { + void noContentClustersOneDocprocCluster() { String services = "<?xml version='1.0' encoding='utf-8' ?>\n" + "<services version='1.0'>\n" + @@ -162,7 +159,7 @@ public class IndexingAndDocprocRoutingTest extends ContentBaseTest { } @Test - public void twoContentTwoDoctypesExplicitIndexingInDifferentIndexingClustersExplicitChain() { + void twoContentTwoDoctypesExplicitIndexingInDifferentIndexingClustersExplicitChain() { final String MUSIC = "musiccluster"; SearchClusterSpec musicCluster = new SearchClusterSpec(MUSIC, "dpmusiccluster", "dpmusicchain"); musicCluster.searchDefs.add(new SearchDefSpec("music", "artist", "album")); @@ -174,7 +171,7 @@ public class IndexingAndDocprocRoutingTest extends ContentBaseTest { DocprocClusterSpec dpMusicCluster = new DocprocClusterSpec("dpmusiccluster", new DocprocChainSpec("dpmusicchain", "indexing")); DocprocClusterSpec dpBooksCluster = new DocprocClusterSpec("dpbookscluster", new DocprocChainSpec("dpbookschain", "indexing")); VespaModel model = getIndexedContentVespaModel(List.of(dpMusicCluster, dpBooksCluster), - List.of(musicCluster, booksCluster)); + List.of(musicCluster, booksCluster)); //after we generated model, add indexing chains for validation: dpMusicCluster.chains.clear(); @@ -191,11 +188,11 @@ public class IndexingAndDocprocRoutingTest extends ContentBaseTest { } @Test - public void requiresIndexingInheritance() { + void requiresIndexingInheritance() { try { SearchClusterSpec musicCluster = new SearchClusterSpec("musiccluster", - "dpmusiccluster", - "dpmusicchain"); + "dpmusiccluster", + "dpmusicchain"); musicCluster.searchDefs.add(new SearchDefSpec("music", "artist", "album")); DocprocClusterSpec dpMusicCluster = new DocprocClusterSpec("dpmusiccluster", new DocprocChainSpec("dpmusicchain")); @@ -208,11 +205,11 @@ public class IndexingAndDocprocRoutingTest extends ContentBaseTest { } @Test - public void indexingChainShouldNotBeTheDefaultChain() { + void indexingChainShouldNotBeTheDefaultChain() { try { SearchClusterSpec musicCluster = new SearchClusterSpec("musiccluster", - "dpmusiccluster", - "default"); + "dpmusiccluster", + "default"); musicCluster.searchDefs.add(new SearchDefSpec("music", "artist", "album")); DocprocClusterSpec dpMusicCluster = new DocprocClusterSpec("dpmusiccluster", new DocprocChainSpec("default", "indexing")); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/MonitoringConfigSnoopTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/MonitoringConfigSnoopTest.java index d1ce16bfe73..95ab1b46401 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/content/MonitoringConfigSnoopTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/content/MonitoringConfigSnoopTest.java @@ -4,9 +4,10 @@ package com.yahoo.vespa.model.content; import com.yahoo.config.model.test.TestDriver; import com.yahoo.config.model.test.TestRoot; import com.yahoo.metrics.MetricsmanagerConfig; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; /** @@ -44,7 +45,7 @@ public class MonitoringConfigSnoopTest { } @Test - public void correct_config_is_snooped() { + void correct_config_is_snooped() { initRoot(60); assertEquals(2, getConfig().snapshot().periods().size()); assertEquals(60, getConfig().snapshot().periods(0)); @@ -52,7 +53,7 @@ public class MonitoringConfigSnoopTest { } @Test - public void correct_config_is_snooped_default_interval() { + void correct_config_is_snooped_default_interval() { String getAdminXmlIntervalNotSpecified = "<admin version='2.0'>" + " <adminserver hostalias='mockhost' />" + "</admin>"; @@ -64,8 +65,10 @@ public class MonitoringConfigSnoopTest { assertEquals(300, getConfig().snapshot().periods(1)); } - @Test(expected = Exception.class) - public void invalid_model_1() { - initRoot(120); + @Test + void invalid_model_1() { + assertThrows(Exception.class, () -> { + initRoot(120); + }); } } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/RedundancyTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/RedundancyTest.java index 437af50e3ef..c7e9b09d77d 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/content/RedundancyTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/content/RedundancyTest.java @@ -1,10 +1,10 @@ // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.model.content; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author bjorncs @@ -12,7 +12,7 @@ import static org.junit.Assert.assertTrue; public class RedundancyTest { @Test - public void effectively_globally_distributed_is_correct() { + void effectively_globally_distributed_is_correct() { assertFalse(createRedundancy(4, 2, 10).isEffectivelyGloballyDistributed()); assertFalse(createRedundancy(5, 1, 10).isEffectivelyGloballyDistributed()); assertFalse(createRedundancy(5, 2, 12).isEffectivelyGloballyDistributed()); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/ReservedDocumentTypeNameValidatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/ReservedDocumentTypeNameValidatorTest.java index 684f07d99f0..96ddf6ea215 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/content/ReservedDocumentTypeNameValidatorTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/content/ReservedDocumentTypeNameValidatorTest.java @@ -2,7 +2,7 @@ package com.yahoo.vespa.model.content; import com.yahoo.documentmodel.NewDocumentType; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Collections; @@ -12,9 +12,7 @@ import java.util.TreeMap; import java.util.function.Function; import java.util.stream.Collectors; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; public class ReservedDocumentTypeNameValidatorTest { @@ -23,7 +21,7 @@ public class ReservedDocumentTypeNameValidatorTest { } @Test - public void exception_thrown_on_reserved_names() { + void exception_thrown_on_reserved_names() { // Ensure ordering is consistent for testing Map<String, NewDocumentType> orderedDocTypes = new TreeMap<>(asDocTypeMapping(ReservedDocumentTypeNameValidator.ORDERED_RESERVED_NAMES)); @@ -40,13 +38,13 @@ public class ReservedDocumentTypeNameValidatorTest { } @Test - public void exception_is_not_thrown_on_unreserved_name() { + void exception_is_not_thrown_on_unreserved_name() { ReservedDocumentTypeNameValidator validator = new ReservedDocumentTypeNameValidator(); validator.validate(asDocTypeMapping(Collections.singletonList("foo"))); } @Test - public void validation_is_case_insensitive() { + void validation_is_case_insensitive() { ReservedDocumentTypeNameValidator validator = new ReservedDocumentTypeNameValidator(); Map<String, NewDocumentType> orderedDocTypes = new TreeMap<>(asDocTypeMapping(Arrays.asList("NULL", "True", "anD"))); try { @@ -54,7 +52,7 @@ public class ReservedDocumentTypeNameValidatorTest { fail(); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().startsWith("The following document types conflict with reserved keyword names: " + - "'NULL', 'True', 'anD'.")); + "'NULL', 'True', 'anD'.")); } } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/SchemaCoverageTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/SchemaCoverageTest.java index 66184d74251..7a331538291 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/content/SchemaCoverageTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/content/SchemaCoverageTest.java @@ -1,11 +1,9 @@ // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.model.content; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; /** * @author Simon Thoresen Hult @@ -13,7 +11,7 @@ import static org.junit.Assert.fail; public class SchemaCoverageTest { @Test - public void requireThatAccessorWork() { + void requireThatAccessorWork() { SearchCoverage coverage = new SearchCoverage.Builder() .setMinimum(0.1) .setMinWaitAfterCoverageFactor(0.2) @@ -25,7 +23,7 @@ public class SchemaCoverageTest { } @Test - public void requireThatDefaultsAreNull() { + void requireThatDefaultsAreNull() { SearchCoverage search = new SearchCoverage.Builder().build(); assertNull(search.getMinimum()); assertNull(search.getMinWaitAfterCoverageFactor()); @@ -33,7 +31,7 @@ public class SchemaCoverageTest { } @Test - public void requireThatInvalidMinimumCanNotBeSet() { + void requireThatInvalidMinimumCanNotBeSet() { SearchCoverage.Builder coverage = new SearchCoverage.Builder(); coverage.setMinimum(0.5); assertEquals(0.5, coverage.build().getMinimum(), 1E-6); @@ -54,7 +52,7 @@ public class SchemaCoverageTest { } @Test - public void requireThatInvalidMinWaitAfterCoverageFactorCanNotBeSet() { + void requireThatInvalidMinWaitAfterCoverageFactorCanNotBeSet() { SearchCoverage.Builder coverage = new SearchCoverage.Builder(); coverage.setMinWaitAfterCoverageFactor(0.5); assertEquals(0.5, coverage.build().getMinWaitAfterCoverageFactor(), 1E-6); @@ -75,7 +73,7 @@ public class SchemaCoverageTest { } @Test - public void requireThatInvalidMaxWaitAfterCoverageFactorCanNotBeSet() { + void requireThatInvalidMaxWaitAfterCoverageFactorCanNotBeSet() { SearchCoverage.Builder coverage = new SearchCoverage.Builder(); coverage.setMaxWaitAfterCoverageFactor(0.5); assertEquals(0.5, coverage.build().getMaxWaitAfterCoverageFactor(), 1E-6); @@ -96,7 +94,7 @@ public class SchemaCoverageTest { } @Test - public void requireThatMinWaitCanNotBeSetLargerThanMaxWait() { + void requireThatMinWaitCanNotBeSetLargerThanMaxWait() { SearchCoverage.Builder coverage = new SearchCoverage.Builder(); coverage.setMaxWaitAfterCoverageFactor(0.5); coverage.setMinWaitAfterCoverageFactor(0.4); @@ -113,7 +111,7 @@ public class SchemaCoverageTest { } @Test - public void requireThatMaxWaitCanNotBeSetSmallerThanMaxWait() { + void requireThatMaxWaitCanNotBeSetSmallerThanMaxWait() { SearchCoverage.Builder coverage = new SearchCoverage.Builder(); coverage.setMinWaitAfterCoverageFactor(0.5); coverage.setMaxWaitAfterCoverageFactor(0.6); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/StorageClusterTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/StorageClusterTest.java index c494ba0394a..f7afcc281f9 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/content/StorageClusterTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/content/StorageClusterTest.java @@ -21,13 +21,10 @@ import static com.yahoo.config.model.test.TestUtil.joinLines; import com.yahoo.vespa.model.content.cluster.ContentCluster; import com.yahoo.vespa.model.content.storagecluster.StorageCluster; import com.yahoo.vespa.model.content.utils.ContentClusterUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; public class StorageClusterTest { @@ -83,8 +80,9 @@ public class StorageClusterTest { group(), "</content>"); } + @Test - public void testBasics() { + void testBasics() { StorageCluster storage = parse(cluster("foofighters", "")); assertEquals(1, storage.getChildren().size()); @@ -95,8 +93,9 @@ public class StorageClusterTest { assertEquals("foofighters", config.cluster_name()); assertEquals(4, config.content_node_bucket_db_stripe_bits()); } + @Test - public void testCommunicationManagerDefaults() { + void testCommunicationManagerDefaults() { StorageCluster storage = parse(cluster("foofighters", "")); StorCommunicationmanagerConfig.Builder builder = new StorCommunicationmanagerConfig.Builder(); storage.getChildren().get("0").getConfig(builder); @@ -105,7 +104,7 @@ public class StorageClusterTest { } @Test - public void testMergeDefaults() { + void testMergeDefaults() { StorServerConfig.Builder builder = new StorServerConfig.Builder(); parse(cluster("foofighters", "")).getConfig(builder); @@ -116,7 +115,7 @@ public class StorageClusterTest { } @Test - public void testMerges() { + void testMerges() { StorServerConfig.Builder builder = new StorServerConfig.Builder(); parse(cluster("foofighters", joinLines( "<tuning>", @@ -127,7 +126,7 @@ public class StorageClusterTest { StorServerConfig config = new StorServerConfig(builder); assertEquals(1024, config.max_merges_per_node()); - assertEquals(1024*10, config.max_merge_queue_size()); + assertEquals(1024 * 10, config.max_merge_queue_size()); } private StorServerConfig configFromProperties(TestProperties properties) { @@ -149,7 +148,7 @@ public class StorageClusterTest { } @Test - public void verifyDefaultMbusConfig() { + void verifyDefaultMbusConfig() { var confg = communicationmanagerConfigFromProperties(new TestProperties()); assertEquals(1, confg.mbus().num_network_threads()); assertEquals(1, confg.mbus().num_rpc_targets()); @@ -159,7 +158,7 @@ public class StorageClusterTest { } @Test - public void verifyDefaultMbusConfigControl() { + void verifyDefaultMbusConfigControl() { var confg = communicationmanagerConfigFromProperties(new TestProperties() .setMbusNetworkThreads(7) .setRpcNumTargets(11) @@ -174,20 +173,20 @@ public class StorageClusterTest { } @Test - public void testMergeFeatureFlags() { + void testMergeFeatureFlags() { var config = configFromProperties(new TestProperties().setMaxMergeQueueSize(1919).setMaxConcurrentMergesPerNode(37)); assertEquals(37, config.max_merges_per_node()); assertEquals(1919, config.max_merge_queue_size()); } @Test - public void merge_throttling_policy_config_defaults_to_static() { + void merge_throttling_policy_config_defaults_to_static() { var config = configFromProperties(new TestProperties()); assertEquals(StorServerConfig.Merge_throttling_policy.Type.STATIC, config.merge_throttling_policy().type()); } @Test - public void merge_throttling_policy_config_is_derived_from_flag() { + void merge_throttling_policy_config_is_derived_from_flag() { var config = configFromProperties(new TestProperties().setMergeThrottlingPolicy("STATIC")); assertEquals(StorServerConfig.Merge_throttling_policy.Type.STATIC, config.merge_throttling_policy().type()); @@ -200,15 +199,15 @@ public class StorageClusterTest { } @Test - public void testVisitors() { + void testVisitors() { StorVisitorConfig.Builder builder = new StorVisitorConfig.Builder(); parse(cluster("bees", joinLines( - "<tuning>", - " <visitors thread-count=\"7\" max-queue-size=\"1000\">", - " <max-concurrent fixed=\"42\" variable=\"100\"/>", - " </visitors>", - "</tuning>")) + "<tuning>", + " <visitors thread-count=\"7\" max-queue-size=\"1000\">", + " <max-concurrent fixed=\"42\" variable=\"100\"/>", + " </visitors>", + "</tuning>")) ).getConfig(builder); StorVisitorConfig config = new StorVisitorConfig(builder); @@ -219,9 +218,9 @@ public class StorageClusterTest { } @Test - public void testPersistenceThreads() { + void testPersistenceThreads() { - StorageCluster stc = parse(cluster("bees",joinLines( + StorageCluster stc = parse(cluster("bees", joinLines( "<tuning>", " <persistence-threads count=\"7\"/>", "</tuning>")), @@ -244,9 +243,9 @@ public class StorageClusterTest { } @Test - public void testResponseThreads() { + void testResponseThreads() { - StorageCluster stc = parse(cluster("bees",joinLines( + StorageCluster stc = parse(cluster("bees", joinLines( "<tuning>", " <persistence-threads count=\"7\"/>", "</tuning>")), @@ -259,7 +258,7 @@ public class StorageClusterTest { } @Test - public void testPersistenceThreadsOld() { + void testPersistenceThreadsOld() { StorageCluster stc = parse(cluster("bees", joinLines( "<tuning>", @@ -287,7 +286,7 @@ public class StorageClusterTest { } @Test - public void testNoPersistenceThreads() { + void testNoPersistenceThreads() { StorageCluster stc = parse(cluster("bees", ""), new Flavor(new FlavorsConfig.Flavor.Builder().name("test-flavor").minCpuCores(9).build()) ); @@ -311,7 +310,7 @@ public class StorageClusterTest { } @Test - public void testFeatureFlagControlOfResponseSequencer() { + void testFeatureFlagControlOfResponseSequencer() { var config = filestorConfigFromProducer(simpleCluster(new TestProperties().setResponseNumThreads(13).setResponseSequencerType("THROUGHPUT"))); assertEquals(13, config.num_response_threads()); assertEquals(StorFilestorConfig.Response_sequencer_type.THROUGHPUT, config.response_sequencer_type()); @@ -321,14 +320,15 @@ public class StorageClusterTest { var config = filestorConfigFromProducer(simpleCluster(new TestProperties().setAsyncMessageHandlingOnSchedule(value))); assertEquals(expected, config.use_async_message_handling_on_schedule()); } + @Test - public void testFeatureFlagControlOfAsyncMessageHandlingOnSchedule() { + void testFeatureFlagControlOfAsyncMessageHandlingOnSchedule() { verifyAsyncMessageHandlingOnSchedule(false, false); verifyAsyncMessageHandlingOnSchedule(true, true); } @Test - public void persistence_dynamic_throttling_parameters_have_sane_defaults() { + void persistence_dynamic_throttling_parameters_have_sane_defaults() { var config = filestorConfigFromProducer(simpleCluster(new TestProperties())); assertEquals(StorFilestorConfig.Async_operation_throttler.Type.DYNAMIC, config.async_operation_throttler().type()); assertEquals(1.2, config.async_operation_throttler().window_size_decrement_factor(), 0.0001); @@ -340,7 +340,7 @@ public class StorageClusterTest { } @Test - public void persistence_dynamic_throttling_parameters_can_be_set_through_feature_flags() { + void persistence_dynamic_throttling_parameters_can_be_set_through_feature_flags() { var config = filestorConfigFromProducer(simpleCluster(new TestProperties() .setPersistenceThrottlingWsDecrementFactor(1.5) .setPersistenceThrottlingWsBackoff(0.8) @@ -357,7 +357,7 @@ public class StorageClusterTest { } @Test - public void integrity_checker_explicitly_disabled_when_not_running_with_vds_provider() { + void integrity_checker_explicitly_disabled_when_not_running_with_vds_provider() { StorIntegritycheckerConfig.Builder builder = new StorIntegritycheckerConfig.Builder(); parse(cluster("bees", "")).getConfig(builder); StorIntegritycheckerConfig config = new StorIntegritycheckerConfig(builder); @@ -366,7 +366,7 @@ public class StorageClusterTest { } @Test - public void testCapacity() { + void testCapacity() { String xml = joinLines( "<cluster id=\"storage\">", " <documents/>", @@ -385,12 +385,12 @@ public class StorageClusterTest { cluster.getStorageCluster().getConfig(builder); node.getConfig(builder); StorServerConfig config = new StorServerConfig(builder); - assertEquals(1.0 + (double)i * 0.5, config.node_capacity(), 0.001); + assertEquals(1.0 + (double) i * 0.5, config.node_capacity(), 0.001); } } @Test - public void testRootFolder() { + void testRootFolder() { ContentCluster cluster = ContentClusterUtils.createCluster(cluster("storage", ""), new MockRoot()); StorageNode node = cluster.getStorageCluster().getChildren().get("0"); @@ -413,7 +413,7 @@ public class StorageClusterTest { } @Test - public void testGenericPersistenceTuning() { + void testGenericPersistenceTuning() { String xml = joinLines( "<cluster id=\"storage\">", " <documents/>", @@ -439,7 +439,7 @@ public class StorageClusterTest { } @Test - public void requireThatUserDoesNotSpecifyBothGroupAndNodes() { + void requireThatUserDoesNotSpecifyBothGroupAndNodes() { String xml = joinLines( "<cluster id=\"storage\">", " <documents/>", @@ -465,12 +465,12 @@ public class StorageClusterTest { fail("Did not fail when having both group and nodes"); } catch (RuntimeException e) { assertEquals("Both <group> and <nodes> is specified: Only one of these tags can be used in the same configuration", - e.getMessage()); + e.getMessage()); } } @Test - public void requireThatGroupNamesMustBeUniqueAmongstSiblings() { + void requireThatGroupNamesMustBeUniqueAmongstSiblings() { String xml = joinLines( "<cluster id=\"storage\">", " <redundancy>2</redundancy>", @@ -491,12 +491,12 @@ public class StorageClusterTest { fail("Did not get exception with duplicate group names"); } catch (RuntimeException e) { assertEquals("Cluster 'storage' has multiple groups with name 'bar' in the same subgroup. " + - "Group sibling names must be unique.", e.getMessage()); + "Group sibling names must be unique.", e.getMessage()); } } @Test - public void requireThatGroupNamesCanBeDuplicatedAcrossLevels() { + void requireThatGroupNamesCanBeDuplicatedAcrossLevels() { String xml = joinLines( "<cluster id=\"storage\">", " <redundancy>2</redundancy>", @@ -521,7 +521,7 @@ public class StorageClusterTest { } @Test - public void requireThatNestedGroupsRequireDistribution() { + void requireThatNestedGroupsRequireDistribution() { String xml = joinLines( "<cluster id=\"storage\">", " <documents/>", diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/StorageContentTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/StorageContentTest.java index bbfcc0ac4c4..a7ad376b483 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/content/StorageContentTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/content/StorageContentTest.java @@ -9,7 +9,7 @@ import com.yahoo.vespa.model.routing.DocumentProtocol; import com.yahoo.vespa.model.routing.Routing; import com.yahoo.vespa.model.test.utils.ApplicationPackageUtils; import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithMockPkg; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.List; import java.util.Map; @@ -17,10 +17,7 @@ import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; public class StorageContentTest extends ContentBaseTest { // TODO: Test with document-definitions @@ -105,7 +102,7 @@ public class StorageContentTest extends ContentBaseTest { } @Test - public void testDocumentTypesRouting() throws Exception { + void testDocumentTypesRouting() throws Exception { String cluster1docs = "<documents>\n" + " <document type=\"type1\" mode=\"store-only\"/>\n" + " <document type=\"type2\" mode=\"store-only\"/>\n" + @@ -120,7 +117,7 @@ public class StorageContentTest extends ContentBaseTest { } @Test - public void testDocumentTypesAndLocalSelectionRouting() throws Exception { + void testDocumentTypesAndLocalSelectionRouting() throws Exception { String cluster1docs = "<documents>\n" + " <document type=\"type1\" mode=\"store-only\" selection=\"1 != 2\"/>\n" + " <document type=\"type2\" mode=\"store-only\" selection=\"now() > 1000\"/>\n" + @@ -135,7 +132,7 @@ public class StorageContentTest extends ContentBaseTest { } @Test - public void testDocumentTypesAndGlobalSelection() throws Exception { + void testDocumentTypesAndGlobalSelection() throws Exception { String cluster1docs = "<documents selection=\"5 != 6\">\n" + " <document type=\"type1\" mode=\"store-only\" selection=\"type1.f1 == 'baz'\"/>\n" + // Can refer to own type " <document type=\"type2\" mode=\"store-only\"/>\n" + @@ -150,7 +147,7 @@ public class StorageContentTest extends ContentBaseTest { } @Test - public void testIllegalDocumentTypesInSelection() throws Exception { + void testIllegalDocumentTypesInSelection() throws Exception { String localDefs = "<documents>\n" + " <document type=\"type1\" mode=\"store-only\"/>\n" + " <document type=\"type2\" mode=\"store-only\" selection=\"type1.bar == 'baz'\"/>\n" + // Not own type diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/StorageGroupTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/StorageGroupTest.java index 7ea8420c162..5407298d0a5 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/content/StorageGroupTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/content/StorageGroupTest.java @@ -6,10 +6,10 @@ import com.yahoo.vespa.config.content.DistributionConfig; import com.yahoo.vespa.config.content.StorDistributionConfig; import com.yahoo.vespa.model.content.cluster.ContentCluster; import com.yahoo.vespa.model.content.utils.ContentClusterUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * Test for storage groups. @@ -21,7 +21,7 @@ public class StorageGroupTest { } @Test - public void testSingleGroup() throws Exception { + void testSingleGroup() throws Exception { ContentCluster cluster = parse( "<content id=\"storage\">\n" + " <documents/>" + @@ -65,7 +65,7 @@ public class StorageGroupTest { } @Test - public void testNestedGroupsNoDistribution() { + void testNestedGroupsNoDistribution() { try { parse( "<content version=\"1.0\" id=\"storage\">\n" + @@ -87,7 +87,7 @@ public class StorageGroupTest { } @Test - public void testNestedGroups() throws Exception { + void testNestedGroups() throws Exception { ContentCluster cluster = parse( "<content version=\"1.0\" id=\"storage\">\n" + " <redundancy>4</redundancy>" + @@ -171,7 +171,7 @@ public class StorageGroupTest { } @Test - public void testGroupCapacity() throws Exception { + void testGroupCapacity() throws Exception { ContentCluster cluster = parse( "<content version=\"1.0\" id=\"storage\">\n" + " <redundancy>2</redundancy>" + diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/TopologicalDocumentTypeSorterTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/TopologicalDocumentTypeSorterTest.java index b6e2e9e4eae..cad888168fe 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/content/TopologicalDocumentTypeSorterTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/content/TopologicalDocumentTypeSorterTest.java @@ -2,7 +2,7 @@ package com.yahoo.vespa.model.content; import com.yahoo.documentmodel.NewDocumentType; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.Arrays; @@ -11,7 +11,7 @@ import java.util.List; import java.util.Set; import java.util.stream.Collectors; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author geirst @@ -19,14 +19,14 @@ import static org.junit.Assert.assertEquals; public class TopologicalDocumentTypeSorterTest { @Test - public void require_that_types_without_references_are_returned_in_input_order() { + void require_that_types_without_references_are_returned_in_input_order() { assertOrder(Arrays.asList("a"), new DocumentTypesBuilder().add("a")); assertOrder(Arrays.asList("a", "c", "b"), new DocumentTypesBuilder().add("a").add("c").add("b")); } @Test - public void require_that_types_with_references_are_sorted_in_topological_order() { + void require_that_types_with_references_are_sorted_in_topological_order() { assertOrder(Arrays.asList("b", "a"), new DocumentTypesBuilder() .add("a", Arrays.asList("b")) .add("b")); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/ClusterTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/ClusterTest.java index aa68dad83cd..1104ac7477a 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/ClusterTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/ClusterTest.java @@ -9,13 +9,13 @@ import com.yahoo.vespa.config.search.core.ProtonConfig; import com.yahoo.vespa.model.content.Content; import com.yahoo.vespa.model.search.IndexedSearchCluster; import com.yahoo.vespa.model.test.utils.ApplicationPackageUtils; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.List; import static com.yahoo.config.model.test.TestUtil.joinLines; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Simon Thoresen Hult @@ -25,7 +25,7 @@ public class ClusterTest { private static final double DELTA = 1E-12; @Test - public void requireThatContentSearchIsApplied() { + void requireThatContentSearchIsApplied() { ContentCluster cluster = newContentCluster(joinLines("<search>", " <query-timeout>1.1</query-timeout>", " <visibility-delay>2.3</visibility-delay>", @@ -39,7 +39,7 @@ public class ClusterTest { } @Test - public void requireThatVisibilityDelayIsZeroForGlobalDocumentType() { + void requireThatVisibilityDelayIsZeroForGlobalDocumentType() { ContentCluster cluster = newContentCluster(joinLines("<search>", " <visibility-delay>2.3</visibility-delay>", "</search>"), true); @@ -48,7 +48,7 @@ public class ClusterTest { } @Test - public void requireThatSearchCoverageIsApplied() { + void requireThatSearchCoverageIsApplied() { ContentCluster cluster = newContentCluster(joinLines("<search>", " <coverage>", " <minimum>0.11</minimum>", @@ -67,15 +67,15 @@ public class ClusterTest { } @Test - public void requireThatDispatchTuningIsApplied() { + void requireThatDispatchTuningIsApplied() { ContentCluster cluster = newContentCluster(joinLines("<search>", "</search>"), - "", - joinLines( - "<max-hits-per-partition>77</max-hits-per-partition>", - "<dispatch-policy>round-robin</dispatch-policy>", - "<min-active-docs-coverage>93</min-active-docs-coverage>", - "<top-k-probability>0.777</top-k-probability>"), - false); + "", + joinLines( + "<max-hits-per-partition>77</max-hits-per-partition>", + "<dispatch-policy>round-robin</dispatch-policy>", + "<min-active-docs-coverage>93</min-active-docs-coverage>", + "<top-k-probability>0.777</top-k-probability>"), + false); DispatchConfig.Builder builder = new DispatchConfig.Builder(); cluster.getSearch().getConfig(builder); DispatchConfig config = new DispatchConfig(builder); @@ -87,9 +87,9 @@ public class ClusterTest { } @Test - public void requireThatDefaultDispatchConfigIsCorrect() { + void requireThatDefaultDispatchConfigIsCorrect() { ContentCluster cluster = newContentCluster(joinLines("<search>", "</search>"), - joinLines("<tuning>", "</tuning>")); + joinLines("<tuning>", "</tuning>")); DispatchConfig.Builder builder = new DispatchConfig.Builder(); cluster.getSearch().getConfig(builder); DispatchConfig config = new DispatchConfig(builder); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/DomContentApplicationBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/DomContentApplicationBuilderTest.java index 11aeea5f90d..d73b7f78391 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/DomContentApplicationBuilderTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/DomContentApplicationBuilderTest.java @@ -3,14 +3,14 @@ package com.yahoo.vespa.model.content.cluster; import com.yahoo.vespa.model.content.ContentSearch; import com.yahoo.vespa.model.builder.xml.dom.ModelElement; -import org.junit.Test; +import org.junit.jupiter.api.Test; import javax.xml.parsers.DocumentBuilderFactory; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; /** * @author Simon Thoresen Hult @@ -18,7 +18,7 @@ import static org.junit.Assert.assertNull; public class DomContentApplicationBuilderTest { @Test - public void requireThatDefaultsAreNull() throws Exception { + void requireThatDefaultsAreNull() throws Exception { ContentSearch search = newContentSearch( "<content/>"); assertNull(search.getVisibilityDelay()); @@ -26,24 +26,24 @@ public class DomContentApplicationBuilderTest { } @Test - public void requireThatEmptySearchIsSafe() throws Exception { + void requireThatEmptySearchIsSafe() throws Exception { ContentSearch search = newContentSearch( "<content>" + - " <search/>" + - "</content>"); + " <search/>" + + "</content>"); assertNull(search.getVisibilityDelay()); assertNull(search.getQueryTimeout()); } @Test - public void requireThatContentSearchCanBeBuilt() throws Exception { + void requireThatContentSearchCanBeBuilt() throws Exception { ContentSearch search = newContentSearch( "<content>" + - " <search>" + - " <query-timeout>1.1</query-timeout>" + - " <visibility-delay>2.3</visibility-delay>" + - " </search>" + - "</content>"); + " <search>" + + " <query-timeout>1.1</query-timeout>" + + " <visibility-delay>2.3</visibility-delay>" + + " </search>" + + "</content>"); assertEquals(1.1, search.getQueryTimeout(), 1E-6); assertEquals(2.3, search.getVisibilityDelay(), 1E-6); } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/DomDispatchTuningBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/DomDispatchTuningBuilderTest.java index a9a784668b3..564d6024acf 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/DomDispatchTuningBuilderTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/DomDispatchTuningBuilderTest.java @@ -4,15 +4,14 @@ package com.yahoo.vespa.model.content.cluster; import com.yahoo.vespa.model.builder.xml.dom.ModelElement; import com.yahoo.vespa.model.content.DispatchTuning; import com.yahoo.vespa.model.test.utils.DeployLoggerStub; -import org.junit.Test; +import org.junit.jupiter.api.Test; import javax.xml.parsers.DocumentBuilderFactory; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Simon Thoresen Hult @@ -20,29 +19,29 @@ import static org.junit.Assert.assertTrue; public class DomDispatchTuningBuilderTest { @Test - public void requireThatDefaultsAreNull() throws Exception { + void requireThatDefaultsAreNull() throws Exception { DispatchTuning dispatch = newTuningDispatch( "<content/>"); assertNull(dispatch.getMaxHitsPerPartition()); } @Test - public void requireThatEmptyTuningIsSafe() throws Exception { + void requireThatEmptyTuningIsSafe() throws Exception { DispatchTuning dispatch = newTuningDispatch( "<content>" + - " <tuning/>" + - "</content>"); + " <tuning/>" + + "</content>"); assertNull(dispatch.getMaxHitsPerPartition()); } @Test - public void requireThatEmptydispatchIsSafe() throws Exception { + void requireThatEmptydispatchIsSafe() throws Exception { DispatchTuning dispatch = newTuningDispatch( "<content>" + - " <tuning>" + - " <dispatch/>" + - " </tuning>" + - "</content>"); + " <tuning>" + + " <dispatch/>" + + " </tuning>" + + "</content>"); assertNull(dispatch.getMaxHitsPerPartition()); assertNull(dispatch.getMinActiveDocsCoverage()); assertNull(dispatch.getDispatchPolicy()); @@ -50,23 +49,24 @@ public class DomDispatchTuningBuilderTest { } @Test - public void requireThatTuningDispatchCanBeBuilt() throws Exception { + void requireThatTuningDispatchCanBeBuilt() throws Exception { DispatchTuning dispatch = newTuningDispatch( "<content>" + - " <tuning>" + - " <dispatch>" + - " <max-hits-per-partition>69</max-hits-per-partition>" + - " <min-active-docs-coverage>12.5</min-active-docs-coverage>" + - " <top-k-probability>0.999</top-k-probability>" + - " </dispatch>" + - " </tuning>" + - "</content>"); + " <tuning>" + + " <dispatch>" + + " <max-hits-per-partition>69</max-hits-per-partition>" + + " <min-active-docs-coverage>12.5</min-active-docs-coverage>" + + " <top-k-probability>0.999</top-k-probability>" + + " </dispatch>" + + " </tuning>" + + "</content>"); assertEquals(69, dispatch.getMaxHitsPerPartition().intValue()); assertEquals(12.5, dispatch.getMinActiveDocsCoverage().doubleValue(), 0.0); assertEquals(0.999, dispatch.getTopkProbability().doubleValue(), 0.0); } + @Test - public void requireThatTuningDispatchPolicyRoundRobin() throws Exception { + void requireThatTuningDispatchPolicyRoundRobin() throws Exception { DispatchTuning dispatch = newTuningDispatch( "<content>" + " <tuning>" + @@ -75,10 +75,11 @@ public class DomDispatchTuningBuilderTest { " </dispatch>" + " </tuning>" + "</content>"); - assertTrue(DispatchTuning.DispatchPolicy.ROUNDROBIN == dispatch.getDispatchPolicy()); + assertEquals(DispatchTuning.DispatchPolicy.ROUNDROBIN, dispatch.getDispatchPolicy()); } + @Test - public void requireThatTuningDispatchPolicyRandom() throws Exception { + void requireThatTuningDispatchPolicyRandom() throws Exception { DispatchTuning dispatch = newTuningDispatch( "<content>" + " <tuning>" + @@ -87,7 +88,7 @@ public class DomDispatchTuningBuilderTest { " </dispatch>" + " </tuning>" + "</content>"); - assertTrue(DispatchTuning.DispatchPolicy.ADAPTIVE == dispatch.getDispatchPolicy()); + assertEquals(DispatchTuning.DispatchPolicy.ADAPTIVE, dispatch.getDispatchPolicy()); } private static DispatchTuning newTuningDispatch(String xml) throws Exception { diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/DomSchemaCoverageBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/DomSchemaCoverageBuilderTest.java index 6c5456e73fc..8fae348f648 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/DomSchemaCoverageBuilderTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/DomSchemaCoverageBuilderTest.java @@ -3,14 +3,14 @@ package com.yahoo.vespa.model.content.cluster; import com.yahoo.vespa.model.builder.xml.dom.ModelElement; import com.yahoo.vespa.model.content.SearchCoverage; -import org.junit.Test; +import org.junit.jupiter.api.Test; import javax.xml.parsers.DocumentBuilderFactory; import java.io.ByteArrayInputStream; import java.nio.charset.StandardCharsets; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; /** * @author Simon Thoresen Hult @@ -18,7 +18,7 @@ import static org.junit.Assert.assertNull; public class DomSchemaCoverageBuilderTest { @Test - public void requireThatDefaultsAreNull() throws Exception { + void requireThatDefaultsAreNull() throws Exception { SearchCoverage coverage = newSearchCoverage( "<content/>"); assertNull(coverage.getMinimum()); @@ -27,41 +27,41 @@ public class DomSchemaCoverageBuilderTest { } @Test - public void requireThatEmptySearchIsSafe() throws Exception { + void requireThatEmptySearchIsSafe() throws Exception { SearchCoverage coverage = newSearchCoverage( "<content>" + - " <search/>" + - "</content>"); + " <search/>" + + "</content>"); assertNull(coverage.getMinimum()); assertNull(coverage.getMinWaitAfterCoverageFactor()); assertNull(coverage.getMaxWaitAfterCoverageFactor()); } @Test - public void requireThatEmptyCoverageIsSafe() throws Exception { + void requireThatEmptyCoverageIsSafe() throws Exception { SearchCoverage coverage = newSearchCoverage( "<content>" + - " <search>" + - " <coverage/>" + - " </search>" + - "</content>"); + " <search>" + + " <coverage/>" + + " </search>" + + "</content>"); assertNull(coverage.getMinimum()); assertNull(coverage.getMinWaitAfterCoverageFactor()); assertNull(coverage.getMaxWaitAfterCoverageFactor()); } @Test - public void requireThatSearchCoverageCanBeBuilt() throws Exception { + void requireThatSearchCoverageCanBeBuilt() throws Exception { SearchCoverage coverage = newSearchCoverage( "<content>" + - " <search>" + - " <coverage>" + - " <minimum>0.11</minimum>" + - " <min-wait-after-coverage-factor>0.23</min-wait-after-coverage-factor>" + - " <max-wait-after-coverage-factor>0.58</max-wait-after-coverage-factor>" + - " </coverage>" + - " </search>" + - "</content>"); + " <search>" + + " <coverage>" + + " <minimum>0.11</minimum>" + + " <min-wait-after-coverage-factor>0.23</min-wait-after-coverage-factor>" + + " <max-wait-after-coverage-factor>0.58</max-wait-after-coverage-factor>" + + " </coverage>" + + " </search>" + + "</content>"); assertEquals(0.11, coverage.getMinimum(), 1E-6); assertEquals(0.23, coverage.getMinWaitAfterCoverageFactor(), 1E-6); assertEquals(0.58, coverage.getMaxWaitAfterCoverageFactor(), 1E-6); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/GlobalDistributionBuilderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/GlobalDistributionBuilderTest.java index 8f654a86fef..e1b33ddedd2 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/GlobalDistributionBuilderTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/content/cluster/GlobalDistributionBuilderTest.java @@ -4,7 +4,7 @@ package com.yahoo.vespa.model.content.cluster; import com.yahoo.documentmodel.NewDocumentType; import com.yahoo.text.XML; import com.yahoo.vespa.model.builder.xml.dom.ModelElement; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.HashMap; @@ -12,7 +12,7 @@ import java.util.HashSet; import java.util.Map; import java.util.Set; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author bjorncs @@ -25,15 +25,15 @@ public class GlobalDistributionBuilderTest { private static final NewDocumentType GLOBAL_2 = new NewDocumentType(new NewDocumentType.Name("global-2")); @Test - public void global_documents_are_identified() { + void global_documents_are_identified() { GlobalDistributionBuilder builder = new GlobalDistributionBuilder(createDocumentDefinitions()); String documentsElement = "<documents>" + - " <document type=\"" + NON_GLOBAL_EXPLICIT.getName() + "\" global=\"false\"/>" + - " <document type=\"" + GLOBAL_1.getName() + "\" global=\"true\"/>" + - " <document type=\"" + NON_GLOBAL_IMPLICIT.getName() + "\"/>" + - " <document type=\"" + GLOBAL_2.getName() + "\" global=\"true\"/>" + - "</documents>"; + " <document type=\"" + NON_GLOBAL_EXPLICIT.getName() + "\" global=\"false\"/>" + + " <document type=\"" + GLOBAL_1.getName() + "\" global=\"true\"/>" + + " <document type=\"" + NON_GLOBAL_IMPLICIT.getName() + "\"/>" + + " <document type=\"" + GLOBAL_2.getName() + "\" global=\"true\"/>" + + "</documents>"; Set<NewDocumentType> expectedResult = new HashSet<>(Arrays.asList(GLOBAL_1, GLOBAL_2)); Set<NewDocumentType> actualResult = builder.build(new ModelElement(XML.getDocument(documentsElement).getDocumentElement())); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/filedistribution/FileReferencesRepositoryTestCase.java b/config-model/src/test/java/com/yahoo/vespa/model/filedistribution/FileReferencesRepositoryTestCase.java index dd98beea091..628e87e24c5 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/filedistribution/FileReferencesRepositoryTestCase.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/filedistribution/FileReferencesRepositoryTestCase.java @@ -4,12 +4,12 @@ package com.yahoo.vespa.model.filedistribution; import com.yahoo.config.FileReference; import com.yahoo.config.application.api.FileRegistry; import com.yahoo.config.model.application.provider.MockFileRegistry; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Set; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author bratseth @@ -17,7 +17,7 @@ import static org.junit.Assert.assertNotNull; public class FileReferencesRepositoryTestCase { @Test - public void fileDistributor() { + void fileDistributor() { FileRegistry fileRegistry = new MockFileRegistry(); FileReferencesRepository fileReferencesRepository = new FileReferencesRepository(fileRegistry); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/ml/ImportedModelTester.java b/config-model/src/test/java/com/yahoo/vespa/model/ml/ImportedModelTester.java index bd07513b704..598b6b103bf 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/ml/ImportedModelTester.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/ml/ImportedModelTester.java @@ -23,9 +23,7 @@ import java.io.UncheckedIOException; import java.util.List; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * Helper for testing of imported models. @@ -79,8 +77,8 @@ public class ImportedModelTester { if (expectedSize.isPresent()) { Path constantPath = applicationDir.append(constantApplicationPackagePath); - assertTrue("Constant file '" + constantPath + "' has been written", - constantPath.toFile().exists()); + assertTrue(constantPath.toFile().exists(), + "Constant file '" + constantPath + "' has been written"); Tensor deserializedConstant = TypedBinaryFormat.decode(Optional.empty(), GrowableByteBuffer.wrap(IOUtils.readFileBytes(constantPath.toFile()))); assertEquals(expectedSize.get().longValue(), deserializedConstant.size()); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/ml/MlModelsTest.java b/config-model/src/test/java/com/yahoo/vespa/model/ml/MlModelsTest.java index b1dc78b4bb7..485d45e6c66 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/ml/MlModelsTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/ml/MlModelsTest.java @@ -6,11 +6,11 @@ import com.yahoo.io.IOUtils; import com.yahoo.path.Path; import com.yahoo.vespa.config.search.RankProfilesConfig; import com.yahoo.vespa.model.VespaModel; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests rank profile imported model evaluation @@ -20,7 +20,7 @@ import static org.junit.Assert.assertEquals; public class MlModelsTest { @Test - public void testMl_serving() throws IOException { + void testMl_serving() throws IOException { Path appDir = Path.fromString("src/test/cfg/application/ml_models"); Path storedAppDir = appDir.append("copy"); try { @@ -31,9 +31,9 @@ public class MlModelsTest { storedAppDir.toFile().mkdirs(); IOUtils.copy(appDir.append("services.xml").toString(), storedAppDir.append("services.xml").toString()); IOUtils.copyDirectory(appDir.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile(), - storedAppDir.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile()); + storedAppDir.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile()); IOUtils.copyDirectory(appDir.append(ApplicationPackage.SCHEMAS_DIR).toFile(), - storedAppDir.append(ApplicationPackage.SCHEMAS_DIR).toFile()); + storedAppDir.append(ApplicationPackage.SCHEMAS_DIR).toFile()); ImportedModelTester storedTester = new ImportedModelTester("ml_models", storedAppDir); verify(storedTester.createVespaModel()); } @@ -44,8 +44,7 @@ public class MlModelsTest { } private void verify(VespaModel model) { - assertEquals("Global models are created (although not used directly here)", - 3, model.rankProfileList().getRankProfiles().size()); + assertEquals(3, model.rankProfileList().getRankProfiles().size(), "Global models are created (although not used directly here)"); RankProfilesConfig.Builder builder = new RankProfilesConfig.Builder(); model.getSearchClusters().get(0).getConfig(builder); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/ml/ModelEvaluationTest.java b/config-model/src/test/java/com/yahoo/vespa/model/ml/ModelEvaluationTest.java index 694b908478d..f4d37cc4b35 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/ml/ModelEvaluationTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/ml/ModelEvaluationTest.java @@ -18,7 +18,7 @@ import com.yahoo.vespa.config.search.core.RankingConstantsConfig; import com.yahoo.vespa.config.search.core.RankingExpressionsConfig; import com.yahoo.vespa.model.VespaModel; import com.yahoo.vespa.model.container.ApplicationContainerCluster; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; @@ -27,11 +27,8 @@ import java.util.Map; import java.util.Set; import java.util.stream.Collectors; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assume.assumeTrue; +import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assumptions.assumeTrue; /** * Tests stateless model evaluation (turned on by the "model-evaluation" tag in "container") @@ -42,7 +39,7 @@ public class ModelEvaluationTest { /** Tests that we do not load models (which would waste memory) when not requested */ @Test - public void testMl_serving_not_activated() { + void testMl_serving_not_activated() { Path appDir = Path.fromString("src/test/cfg/application/ml_serving_not_activated"); try { ImportedModelTester tester = new ImportedModelTester("ml_serving", appDir); @@ -62,7 +59,7 @@ public class ModelEvaluationTest { } @Test - public void testMl_serving() throws IOException { + void testMl_serving() throws IOException { assumeTrue(OnnxEvaluator.isRuntimeAvailable()); Path appDir = Path.fromString("src/test/cfg/application/ml_serving"); Path storedAppDir = appDir.append("copy"); @@ -74,7 +71,7 @@ public class ModelEvaluationTest { storedAppDir.toFile().mkdirs(); IOUtils.copy(appDir.append("services.xml").toString(), storedAppDir.append("services.xml").toString()); IOUtils.copyDirectory(appDir.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile(), - storedAppDir.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile()); + storedAppDir.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile()); ImportedModelTester storedTester = new ImportedModelTester("ml_serving", storedAppDir); assertHasMlModels(storedTester.createVespaModel(), appDir); } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/ml/OnnxModelProbeTest.java b/config-model/src/test/java/com/yahoo/vespa/model/ml/OnnxModelProbeTest.java index b2d4953f8e2..804133fbc0a 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/ml/OnnxModelProbeTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/ml/OnnxModelProbeTest.java @@ -6,17 +6,17 @@ import com.yahoo.config.model.application.provider.FilesApplicationPackage; import com.yahoo.io.IOUtils; import com.yahoo.path.Path; import com.yahoo.tensor.TensorType; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Map; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; public class OnnxModelProbeTest { @Test - public void testProbedOutputTypes() throws IOException { + void testProbedOutputTypes() throws IOException { Path appDir = Path.fromString("src/test/cfg/application/onnx_probe"); Path storedAppDir = appDir.append("copy"); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/ml/StatelessOnnxEvaluationTest.java b/config-model/src/test/java/com/yahoo/vespa/model/ml/StatelessOnnxEvaluationTest.java index bad6fcc68c2..00e510ce0ff 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/ml/StatelessOnnxEvaluationTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/ml/StatelessOnnxEvaluationTest.java @@ -18,7 +18,7 @@ import com.yahoo.vespa.config.search.core.RankingConstantsConfig; import com.yahoo.vespa.config.search.core.RankingExpressionsConfig; import com.yahoo.vespa.model.VespaModel; import com.yahoo.vespa.model.container.ApplicationContainerCluster; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; @@ -27,10 +27,8 @@ import java.util.Map; import java.util.Set; import java.util.stream.Collectors; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assume.assumeTrue; +import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assumptions.assumeTrue; /** * Tests stateless model evaluation (turned on by the "model-evaluation" tag in "container") @@ -41,7 +39,7 @@ import static org.junit.Assume.assumeTrue; public class StatelessOnnxEvaluationTest { @Test - public void testStatelessOnnxModelNameCollision() { + void testStatelessOnnxModelNameCollision() { assumeTrue(OnnxEvaluator.isRuntimeAvailable()); Path appDir = Path.fromString("src/test/cfg/application/onnx_name_collision"); try { @@ -62,7 +60,7 @@ public class StatelessOnnxEvaluationTest { } @Test - public void testStatelessOnnxModelEvaluation() throws IOException { + void testStatelessOnnxModelEvaluation() throws IOException { assumeTrue(OnnxEvaluator.isRuntimeAvailable()); Path appDir = Path.fromString("src/test/cfg/application/onnx"); Path storedAppDir = appDir.append("copy"); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/routing/test/RoutingTestCase.java b/config-model/src/test/java/com/yahoo/vespa/model/routing/test/RoutingTestCase.java index 30678205e3a..f661d17bcf5 100755 --- a/config-model/src/test/java/com/yahoo/vespa/model/routing/test/RoutingTestCase.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/routing/test/RoutingTestCase.java @@ -8,7 +8,7 @@ import com.yahoo.messagebus.MessagebusConfig; import com.yahoo.documentapi.messagebus.protocol.DocumentProtocolPoliciesConfig; import com.yahoo.vespa.model.VespaModel; import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithFilePkg; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.io.BufferedReader; import java.io.File; @@ -23,9 +23,7 @@ import java.util.List; import java.util.Map; import static helpers.CompareConfigTestHelper.assertSerializedConfigEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.*; /** * @author Simon Thoresen Hult @@ -35,13 +33,13 @@ public class RoutingTestCase { private static final boolean WRITE_FILES = false; @Test - public void testRoutingContent() throws IOException { + void testRoutingContent() throws IOException { assertApplication(new File("src/test/cfg/routing/contentsimpleconfig")); assertApplication(new File("src/test/cfg/routing/content_two_clusters")); } @Test - public void testRouting() throws IOException { + void testRouting() throws IOException { assertApplication(new File("src/test/cfg/routing/unexpectedrecipient")); assertApplication(new File("src/test/cfg/routing/servicenotfound")); assertApplication(new File("src/test/cfg/routing/routenotfoundinroute")); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/search/NodeResourcesTuningTest.java b/config-model/src/test/java/com/yahoo/vespa/model/search/NodeResourcesTuningTest.java index 5571ead11ce..fece6ca47e3 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/search/NodeResourcesTuningTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/search/NodeResourcesTuningTest.java @@ -6,13 +6,13 @@ import com.yahoo.config.provision.Flavor; import com.yahoo.config.provisioning.FlavorsConfig; import com.yahoo.vespa.config.search.core.ProtonConfig; import com.yahoo.vespa.model.container.ApplicationContainerCluster; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.List; import static com.yahoo.vespa.model.search.NodeResourcesTuning.reservedMemoryGb; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import static com.yahoo.vespa.model.search.NodeResourcesTuning.MB; import static com.yahoo.vespa.model.search.NodeResourcesTuning.GB; @@ -26,19 +26,19 @@ public class NodeResourcesTuningTest { private static final double DEFAULT_MEMORY_GAIN = 0.08; @Test - public void require_that_hwinfo_disk_size_is_set() { + void require_that_hwinfo_disk_size_is_set() { ProtonConfig cfg = configFromDiskSetting(100); assertEquals(100 * GB, cfg.hwinfo().disk().size()); } @Test - public void require_that_hwinfo_memory_size_is_set() { + void require_that_hwinfo_memory_size_is_set() { assertEquals(24 * GB, configFromMemorySetting(24 + reservedMemoryGb, 0).hwinfo().memory().size()); - assertEquals(combinedFactor * 24 * GB, configFromMemorySetting(24 + reservedMemoryGb, ApplicationContainerCluster.heapSizePercentageOfTotalNodeMemoryWhenCombinedCluster*0.01).hwinfo().memory().size(), 1000); + assertEquals(combinedFactor * 24 * GB, configFromMemorySetting(24 + reservedMemoryGb, ApplicationContainerCluster.heapSizePercentageOfTotalNodeMemoryWhenCombinedCluster * 0.01).hwinfo().memory().size(), 1000); } @Test - public void reserved_memory_on_content_node_is_0_5_gb() { + void reserved_memory_on_content_node_is_0_5_gb() { assertEquals(0.5, reservedMemoryGb, delta); } @@ -65,19 +65,19 @@ public class NodeResourcesTuningTest { } @Test - public void require_that_initial_numdocs_is_dependent_of_mode_and_searchablecopies() { + void require_that_initial_numdocs_is_dependent_of_mode_and_searchablecopies() { verify_that_initial_numdocs_is_dependent_of_mode(); } @Test - public void require_that_hwinfo_cpu_cores_is_set() { + void require_that_hwinfo_cpu_cores_is_set() { ProtonConfig cfg = configFromNumCoresSetting(24); assertEquals(24, cfg.hwinfo().cpu().cores()); } @Test - public void require_that_num_search_threads_and_summary_threads_follow_cores() { + void require_that_num_search_threads_and_summary_threads_follow_cores() { ProtonConfig cfg = configFromNumCoresSetting(4.5); assertEquals(5, cfg.numsearcherthreads()); assertEquals(5, cfg.numsummarythreads()); @@ -85,7 +85,7 @@ public class NodeResourcesTuningTest { } @Test - public void require_that_num_search_threads_and_considers_explict_num_threads_per_search() { + void require_that_num_search_threads_and_considers_explict_num_threads_per_search() { ProtonConfig cfg = configFromNumCoresSetting(4.5, 3); assertEquals(15, cfg.numsearcherthreads()); assertEquals(5, cfg.numsummarythreads()); @@ -93,45 +93,45 @@ public class NodeResourcesTuningTest { } @Test - public void require_that_fast_disk_is_reflected_in_proton_config() { + void require_that_fast_disk_is_reflected_in_proton_config() { ProtonConfig cfg = configFromDiskSetting(true); assertEquals(200, cfg.hwinfo().disk().writespeed(), delta); assertEquals(100, cfg.hwinfo().disk().slowwritespeedlimit(), delta); } @Test - public void require_that_slow_disk_is_reflected_in_proton_config() { + void require_that_slow_disk_is_reflected_in_proton_config() { ProtonConfig cfg = configFromDiskSetting(false); assertEquals(40, cfg.hwinfo().disk().writespeed(), delta); assertEquals(100, cfg.hwinfo().disk().slowwritespeedlimit(), delta); } @Test - public void require_that_document_store_maxfilesize_is_set_based_on_available_memory() { + void require_that_document_store_maxfilesize_is_set_based_on_available_memory() { assertDocumentStoreMaxFileSize(256 * MB, 4); assertDocumentStoreMaxFileSize(256 * MB, 6); assertDocumentStoreMaxFileSize(256 * MB, 8); assertDocumentStoreMaxFileSize(256 * MB, 12); - assertDocumentStoreMaxFileSize((long)(16*GB*0.02), 16); - assertDocumentStoreMaxFileSize((long)(24*GB*0.02), 24); - assertDocumentStoreMaxFileSize((long)(32*GB*0.02), 32); - assertDocumentStoreMaxFileSize((long)(48*GB*0.02), 48); - assertDocumentStoreMaxFileSize((long)(64*GB*0.02), 64); - assertDocumentStoreMaxFileSize((long)(128*GB*0.02), 128); - assertDocumentStoreMaxFileSize((long)(256*GB*0.02), 256); - assertDocumentStoreMaxFileSize((long)(512*GB*0.02), 512); + assertDocumentStoreMaxFileSize((long) (16 * GB * 0.02), 16); + assertDocumentStoreMaxFileSize((long) (24 * GB * 0.02), 24); + assertDocumentStoreMaxFileSize((long) (32 * GB * 0.02), 32); + assertDocumentStoreMaxFileSize((long) (48 * GB * 0.02), 48); + assertDocumentStoreMaxFileSize((long) (64 * GB * 0.02), 64); + assertDocumentStoreMaxFileSize((long) (128 * GB * 0.02), 128); + assertDocumentStoreMaxFileSize((long) (256 * GB * 0.02), 256); + assertDocumentStoreMaxFileSize((long) (512 * GB * 0.02), 512); } @Test - public void require_that_flush_strategy_memory_limits_are_set_based_on_available_memory() { - assertFlushStrategyMemory((long)(4 * GB * DEFAULT_MEMORY_GAIN), 4); - assertFlushStrategyMemory((long)(8 * GB * DEFAULT_MEMORY_GAIN), 8); - assertFlushStrategyMemory((long)(24 * GB * DEFAULT_MEMORY_GAIN), 24); - assertFlushStrategyMemory((long)(64 * GB * DEFAULT_MEMORY_GAIN), 64); + void require_that_flush_strategy_memory_limits_are_set_based_on_available_memory() { + assertFlushStrategyMemory((long) (4 * GB * DEFAULT_MEMORY_GAIN), 4); + assertFlushStrategyMemory((long) (8 * GB * DEFAULT_MEMORY_GAIN), 8); + assertFlushStrategyMemory((long) (24 * GB * DEFAULT_MEMORY_GAIN), 24); + assertFlushStrategyMemory((long) (64 * GB * DEFAULT_MEMORY_GAIN), 64); } @Test - public void require_that_flush_strategy_tls_size_is_set_based_on_available_disk() { + void require_that_flush_strategy_tls_size_is_set_based_on_available_disk() { assertFlushStrategyTlsSize(2 * GB, 10); assertFlushStrategyTlsSize(2 * GB, 100); assertFlushStrategyTlsSize(10 * GB, 500); @@ -140,31 +140,31 @@ public class NodeResourcesTuningTest { } @Test - public void require_that_summary_read_io_is_set_based_on_disk() { + void require_that_summary_read_io_is_set_based_on_disk() { assertSummaryReadIo(ProtonConfig.Summary.Read.Io.DIRECTIO, true); assertSummaryReadIo(ProtonConfig.Summary.Read.Io.MMAP, false); } @Test - public void require_that_search_read_mmap_advise_is_set_based_on_disk() { + void require_that_search_read_mmap_advise_is_set_based_on_disk() { assertSearchReadAdvise(ProtonConfig.Search.Mmap.Advise.RANDOM, true); assertSearchReadAdvise(ProtonConfig.Search.Mmap.Advise.NORMAL, false); } @Test - public void require_that_summary_cache_max_bytes_is_set_based_on_memory() { - assertEquals(1*GB / 25, configFromMemorySetting(1 + reservedMemoryGb, 0).summary().cache().maxbytes()); - assertEquals(256*GB / 25, configFromMemorySetting(256 + reservedMemoryGb, 0).summary().cache().maxbytes()); + void require_that_summary_cache_max_bytes_is_set_based_on_memory() { + assertEquals(1 * GB / 25, configFromMemorySetting(1 + reservedMemoryGb, 0).summary().cache().maxbytes()); + assertEquals(256 * GB / 25, configFromMemorySetting(256 + reservedMemoryGb, 0).summary().cache().maxbytes()); } @Test - public void require_that_summary_cache_memory_is_reduced_with_combined_cluster() { - assertEquals(combinedFactor * 1*GB / 25, configFromMemorySetting(1 + reservedMemoryGb, ApplicationContainerCluster.heapSizePercentageOfTotalNodeMemoryWhenCombinedCluster*0.01).summary().cache().maxbytes(), 1000); - assertEquals(combinedFactor * 256*GB / 25, configFromMemorySetting(256 + reservedMemoryGb, ApplicationContainerCluster.heapSizePercentageOfTotalNodeMemoryWhenCombinedCluster*0.01).summary().cache().maxbytes(), 1000); + void require_that_summary_cache_memory_is_reduced_with_combined_cluster() { + assertEquals(combinedFactor * 1 * GB / 25, configFromMemorySetting(1 + reservedMemoryGb, ApplicationContainerCluster.heapSizePercentageOfTotalNodeMemoryWhenCombinedCluster * 0.01).summary().cache().maxbytes(), 1000); + assertEquals(combinedFactor * 256 * GB / 25, configFromMemorySetting(256 + reservedMemoryGb, ApplicationContainerCluster.heapSizePercentageOfTotalNodeMemoryWhenCombinedCluster * 0.01).summary().cache().maxbytes(), 1000); } @Test - public void require_that_docker_node_is_tagged_with_shared_disk() { + void require_that_docker_node_is_tagged_with_shared_disk() { assertSharedDisk(true, true); } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/search/test/DocumentDatabaseTestCase.java b/config-model/src/test/java/com/yahoo/vespa/model/search/test/DocumentDatabaseTestCase.java index a3c57dae2de..8830e5484b3 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/search/test/DocumentDatabaseTestCase.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/search/test/DocumentDatabaseTestCase.java @@ -17,7 +17,7 @@ import com.yahoo.vespa.model.VespaModel; import com.yahoo.vespa.model.content.ContentSearchCluster; import com.yahoo.vespa.model.content.utils.DocType; import com.yahoo.vespa.model.search.IndexedSearchCluster; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Collections; @@ -25,7 +25,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author geirst @@ -35,31 +35,31 @@ public class DocumentDatabaseTestCase { private static final double SMALL = 0.00000000000001; @Test - public void requireThatWeCanHaveOneSDForIndexedMode() { + void requireThatWeCanHaveOneSDForIndexedMode() { new SchemaTester().assertSingleSD("index"); } @Test - public void requireThatConcurrencyIsReflectedCorrectlyForDefault() { + void requireThatConcurrencyIsReflectedCorrectlyForDefault() { verifyConcurrency("index", "", 0.50); verifyConcurrency("streaming", "", 1.0); verifyConcurrency("store-only", "", 1.0); } @Test - public void requireThatFeatureFlagConcurrencyIsReflectedCorrectlyForDefault() { + void requireThatFeatureFlagConcurrencyIsReflectedCorrectlyForDefault() { verifyConcurrency("index", "", 0.30, 0.3); verifyConcurrency("streaming", "", 0.6, 0.3); verifyConcurrency("store-only", "", 0.8, 0.4); } @Test - public void requireThatMixedModeConcurrencyIsReflectedCorrectlyForDefault() { + void requireThatMixedModeConcurrencyIsReflectedCorrectlyForDefault() { verifyConcurrency(Arrays.asList(DocType.create("a", "index"), DocType.create("b", "streaming")), "", 1.0); } @Test - public void requireThatMixedModeConcurrencyIsReflected() { + void requireThatMixedModeConcurrencyIsReflected() { String feedTuning = "<feeding>" + " <concurrency>0.7</concurrency>" + "</feeding>\n"; @@ -67,10 +67,10 @@ public class DocumentDatabaseTestCase { } @Test - public void requireThatConcurrencyIsReflected() { + void requireThatConcurrencyIsReflected() { String feedTuning = "<feeding>" + - " <concurrency>0.7</concurrency>" + - "</feeding>\n"; + " <concurrency>0.7</concurrency>" + + "</feeding>\n"; verifyConcurrency("index", feedTuning, 0.7); verifyConcurrency("streaming", feedTuning, 0.7); verifyConcurrency("store-only", feedTuning, 0.7); @@ -113,17 +113,17 @@ public class DocumentDatabaseTestCase { } @Test - public void requireFeedNicenessIsReflected() { + void requireFeedNicenessIsReflected() { verifyFeedNiceness(Arrays.asList(DocType.create("a", "index")), 0.0, null); verifyFeedNiceness(Arrays.asList(DocType.create("a", "index")), 0.32, 0.32); } @Test - public void requireThatModeIsSet() { + void requireThatModeIsSet() { var tester = new SchemaTester(); VespaModel model = tester.createModel(Arrays.asList(DocType.create("a", "index"), - DocType.create("b", "streaming"), - DocType.create("c", "store-only")), ""); + DocType.create("b", "streaming"), + DocType.create("c", "store-only")), ""); ContentSearchCluster contentSearchCluster = model.getContentClusters().get("test").getSearch(); ProtonConfig proton = tester.getProtonConfig(contentSearchCluster); assertEquals(3, proton.documentdb().size()); @@ -148,13 +148,14 @@ public class DocumentDatabaseTestCase { } @Test - public void requireThatMixedModeInitialDocumentCountIsReflectedCorrectlyForDefault() { + void requireThatMixedModeInitialDocumentCountIsReflectedCorrectlyForDefault() { final long DEFAULT = 1024L; verifyInitialDocumentCount(Arrays.asList(DocType.create("a", "index"), DocType.create("b", "streaming")), "", Arrays.asList(DEFAULT, DEFAULT)); } + @Test - public void requireThatMixedModeInitialDocumentCountIsReflected() { + void requireThatMixedModeInitialDocumentCountIsReflected() { final long INITIAL = 1000000000L; String feedTuning = "<resizing>" + " <initialdocumentcount>1000000000</initialdocumentcount>" + @@ -176,11 +177,11 @@ public class DocumentDatabaseTestCase { } @Test - public void testMultipleSchemas() { + void testMultipleSchemas() { List<String> sds = List.of("type1", "type2", "type3"); var tester = new SchemaTester(); var model = tester.createModel(sds); - IndexedSearchCluster indexedSearchCluster = (IndexedSearchCluster)model.getSearchClusters().get(0); + IndexedSearchCluster indexedSearchCluster = (IndexedSearchCluster) model.getSearchClusters().get(0); ContentSearchCluster contentSearchCluster = model.getContentClusters().get("test").getSearch(); String type1Id = "test/search/cluster.test/type1"; String type2Id = "test/search/cluster.test/type2"; @@ -226,26 +227,26 @@ public class DocumentDatabaseTestCase { } @Test - public void testRankingConstants() { + void testRankingConstants() { List<String> schemas = List.of("type1"); var tester = new SchemaTester(); // Use lz4 endings to avoid having to provide file content to be validated String schemaConstants = " constant constant_1 {" + - " file: constants/my_constant_1.json.lz4" + - " type: tensor<float>(x{},y{})" + - " }" + - " constant constant_2 {" + - " file: constants/my_constant_2.json.lz4" + - " type: tensor(x[1000])" + - " }"; + " file: constants/my_constant_1.json.lz4" + + " type: tensor<float>(x{},y{})" + + " }" + + " constant constant_2 {" + + " file: constants/my_constant_2.json.lz4" + + " type: tensor(x[1000])" + + " }"; Map<Path, String> constants = new HashMap<>(); constants.put(Path.fromString("constants/my_constant_1.json.lz4"), ""); constants.put(Path.fromString("constants/my_constant_2.json.lz4"), ""); var model = tester.createModel(schemaConstants, "", schemas, constants); - IndexedSearchCluster indexedSearchCluster = (IndexedSearchCluster)model.getSearchClusters().get(0); + IndexedSearchCluster indexedSearchCluster = (IndexedSearchCluster) model.getSearchClusters().get(0); RankingConstantsConfig.Builder b = new RankingConstantsConfig.Builder(); indexedSearchCluster.getDocumentDbs().get(0).getConfig(b); RankingConstantsConfig config = b.build(); @@ -263,14 +264,14 @@ public class DocumentDatabaseTestCase { } @Test - public void requireThatRelevantConfigIsAvailableForClusterSearcher() { + void requireThatRelevantConfigIsAvailableForClusterSearcher() { String inputsProfile = " rank-profile inputs {" + - " inputs {" + - " query(foo) tensor<float>(x[10])" + - " query(bar) tensor(key{},x[1000])" + - " }" + - " }"; + " inputs {" + + " query(foo) tensor<float>(x[10])" + + " query(bar) tensor(key{},x[1000])" + + " }" + + " }"; List<String> schemas = List.of("type1", "type2"); var tester = new SchemaTester(); VespaModel model = tester.createModelWithRankProfile(inputsProfile, schemas); @@ -305,7 +306,7 @@ public class DocumentDatabaseTestCase { } @Test - public void requireThatDocumentDBConfigIsAvailableForStreaming() { + void requireThatDocumentDBConfigIsAvailableForStreaming() { assertDocumentDBConfigAvailableForStreaming("streaming"); } @@ -343,7 +344,7 @@ public class DocumentDatabaseTestCase { } @Test - public void testThatAttributesMaxUnCommittedMemoryIsControlledByFeatureFlag() { + void testThatAttributesMaxUnCommittedMemoryIsControlledByFeatureFlag() { assertAttributesConfigIndependentOfMode("index", Arrays.asList("type1"), Arrays.asList("test/search/cluster.test/type1"), ImmutableMap.of("type1", Arrays.asList("f2", "f2_nfa")), @@ -351,20 +352,21 @@ public class DocumentDatabaseTestCase { } @Test - public void testThatAttributesConfigIsProducedForIndexed() { + void testThatAttributesConfigIsProducedForIndexed() { assertAttributesConfigIndependentOfMode("index", Arrays.asList("type1"), Arrays.asList("test/search/cluster.test/type1"), ImmutableMap.of("type1", Arrays.asList("f2", "f2_nfa"))); } @Test - public void testThatAttributesConfigIsProducedForStreamingForFastAccessFields() { + void testThatAttributesConfigIsProducedForStreamingForFastAccessFields() { assertAttributesConfigIndependentOfMode("streaming", Arrays.asList("type1"), Arrays.asList("test/search/type1"), ImmutableMap.of("type1", Arrays.asList("f2"))); } + @Test - public void testThatAttributesConfigIsNotProducedForStoreOnlyEvenForFastAccessFields() { + void testThatAttributesConfigIsNotProducedForStoreOnlyEvenForFastAccessFields() { assertAttributesConfigIndependentOfMode("store-only", Arrays.asList("type1"), Arrays.asList("test/search"), Collections.emptyMap()); } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/search/test/DocumentSelectionConverterTest.java b/config-model/src/test/java/com/yahoo/vespa/model/search/test/DocumentSelectionConverterTest.java index 9f14a78d8c5..5efe75bdca5 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/search/test/DocumentSelectionConverterTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/search/test/DocumentSelectionConverterTest.java @@ -3,10 +3,10 @@ package com.yahoo.vespa.model.search.test; import com.yahoo.document.select.parser.ParseException; import com.yahoo.vespa.model.search.DocumentSelectionConverter; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; /** * Unit tests for RemoveSelection. @@ -14,19 +14,20 @@ import static org.junit.Assert.assertTrue; */ public class DocumentSelectionConverterTest { @Test - public void testQueryConversion() throws ParseException, IllegalArgumentException, UnsupportedOperationException { + void testQueryConversion() throws ParseException, IllegalArgumentException, UnsupportedOperationException { DocumentSelectionConverter converter = new DocumentSelectionConverter("music.expire>now() - 3600 and video.expire > now() - 300"); assertEquals("expire:>now(3600)", converter.getQuery("music")); assertEquals("expire:<now(3600)", converter.getInvertedQuery("music")); assertEquals("expire:>now(300)", converter.getQuery("video")); assertEquals("expire:<now(300)", converter.getInvertedQuery("video")); - assertTrue(null == converter.getQuery("book")); - assertTrue(null == converter.getInvertedQuery("book")); + assertNull(converter.getQuery("book")); + assertNull(converter.getInvertedQuery("book")); } + @Test - public void testSelection() throws ParseException, IllegalArgumentException, UnsupportedOperationException { + void testSelection() throws ParseException, IllegalArgumentException, UnsupportedOperationException { DocumentSelectionConverter converter = new DocumentSelectionConverter("music.expire>music.expire.nowdate"); - assertTrue(converter.getQuery("music") == null); - assertTrue(converter.getInvertedQuery("music") == null); + assertNull(converter.getQuery("music")); + assertNull(converter.getInvertedQuery("music")); } } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/search/test/SchemaClusterTest.java b/config-model/src/test/java/com/yahoo/vespa/model/search/test/SchemaClusterTest.java index 1d15f973d21..3e5a473c1ca 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/search/test/SchemaClusterTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/search/test/SchemaClusterTest.java @@ -21,12 +21,9 @@ import com.yahoo.vespa.model.container.component.Component; import com.yahoo.vespa.model.search.SearchCluster; import com.yahoo.vespa.model.test.utils.ApplicationPackageUtils; import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithMockPkg; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** @@ -38,7 +35,7 @@ import static org.junit.Assert.assertTrue; public class SchemaClusterTest { @Test - public void testSdConfigLogical() { + void testSdConfigLogical() { // sd1 SDDocumentType sdt1 = new SDDocumentType("s1"); Schema schema1 = new Schema("s1", MockApplicationPackage.createEmpty()); @@ -51,7 +48,7 @@ public class SchemaClusterTest { // sd2 SDDocumentType sdt2 = new SDDocumentType("s2"); Schema schema2 = new Schema("s2", MockApplicationPackage.createEmpty()); - SDField f2=new SDField(sdt2, "f2", DataType.STRING); + SDField f2 = new SDField(sdt2, "f2", DataType.STRING); f2.addAttribute(new Attribute("f2", DataType.STRING)); f2.setIndexingScript(new ScriptExpression(new StatementExpression(new AttributeExpression("f2")))); sdt2.addField(f2); @@ -64,76 +61,76 @@ public class SchemaClusterTest { } @Test - public void search_model_is_connected_to_container_clusters_two_content_clusters() { + void search_model_is_connected_to_container_clusters_two_content_clusters() { String vespaHosts = "<?xml version='1.0' encoding='utf-8' ?>" + - "<hosts>" + - " <host name='node0host'>" + - " <alias>node0</alias>" + - " </host>" + - " <host name='node1host'>" + - " <alias>node1</alias>" + - " </host>" + - " <host name='node2host'>" + - " <alias>node2</alias>" + - " </host>" + - "</hosts>"; + "<hosts>" + + " <host name='node0host'>" + + " <alias>node0</alias>" + + " </host>" + + " <host name='node1host'>" + + " <alias>node1</alias>" + + " </host>" + + " <host name='node2host'>" + + " <alias>node2</alias>" + + " </host>" + + "</hosts>"; String services = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + - "<services version=\"1.0\">" + - " <admin version='2.0'>" + - " <adminserver hostalias='node0' />" + - " </admin>\n" + - " <container version='1.0' id='j1'>\n" + - " <search>" + - " <chain id='s1Chain'>" + - " <searcher id='S1ClusterSearcher'/>" + - " </chain>" + - " <provider cluster='normal' id='normal' type='local'/>\n" + - " </search>" + - " <nodes>" + - " <node hostalias=\"node0\" />" + - " </nodes>" + - " </container>" + - - " <container version='1.0' id='j2'>" + - " <search>" + - " <chain id='s2Chain'>" + - " <searcher id='S2ClusterSearcher'/>" + - " </chain>" + - " <provider cluster='xbulk' id='xbulk' type='local'/>" + - " </search>" + - " <nodes>" + - " <node hostalias=\"node2\" />" + - " </nodes>" + - " </container>" + - - " <content id='xbulk' version=\"1.0\">" + - " <redundancy>2</redundancy>" + - " <documents>" + - " <document mode='index' type=\"music\" />" + - " </documents>" + - " <nodes>" + - " <node hostalias=\"node0\" distribution-key=\"0\" />" + - " </nodes>" + - " </content>" + - " <content id=\"normal\" version='1.0'>" + - " <redundancy>2</redundancy>" + - " <documents>" + - " <document mode='index' type=\"music\" />" + - " </documents>" + - " <nodes>" + - " <node hostalias=\"node2\" distribution-key=\"0\" />" + - " </nodes>" + - " </content>" + - "</services>"; + "<services version=\"1.0\">" + + " <admin version='2.0'>" + + " <adminserver hostalias='node0' />" + + " </admin>\n" + + " <container version='1.0' id='j1'>\n" + + " <search>" + + " <chain id='s1Chain'>" + + " <searcher id='S1ClusterSearcher'/>" + + " </chain>" + + " <provider cluster='normal' id='normal' type='local'/>\n" + + " </search>" + + " <nodes>" + + " <node hostalias=\"node0\" />" + + " </nodes>" + + " </container>" + + + " <container version='1.0' id='j2'>" + + " <search>" + + " <chain id='s2Chain'>" + + " <searcher id='S2ClusterSearcher'/>" + + " </chain>" + + " <provider cluster='xbulk' id='xbulk' type='local'/>" + + " </search>" + + " <nodes>" + + " <node hostalias=\"node2\" />" + + " </nodes>" + + " </container>" + + + " <content id='xbulk' version=\"1.0\">" + + " <redundancy>2</redundancy>" + + " <documents>" + + " <document mode='index' type=\"music\" />" + + " </documents>" + + " <nodes>" + + " <node hostalias=\"node0\" distribution-key=\"0\" />" + + " </nodes>" + + " </content>" + + " <content id=\"normal\" version='1.0'>" + + " <redundancy>2</redundancy>" + + " <documents>" + + " <document mode='index' type=\"music\" />" + + " </documents>" + + " <nodes>" + + " <node hostalias=\"node2\" distribution-key=\"0\" />" + + " </nodes>" + + " </content>" + + "</services>"; VespaModel model = new VespaModelCreatorWithMockPkg(vespaHosts, services, ApplicationPackageUtils.generateSchemas("music")).create(); - ContainerCluster containerCluster1 = (ContainerCluster)model.getConfigProducer("j1").get(); + ContainerCluster containerCluster1 = (ContainerCluster) model.getConfigProducer("j1").get(); assertFalse(containerCluster1.getSearch().getChains().localProviders().isEmpty()); - ContainerCluster containerCluster2 = (ContainerCluster)model.getConfigProducer("j2").get(); + ContainerCluster containerCluster2 = (ContainerCluster) model.getConfigProducer("j2").get(); assertFalse(containerCluster2.getSearch().getChains().localProviders().isEmpty()); QrSearchersConfig.Builder builder = new QrSearchersConfig.Builder(); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/search/test/SchemaInfoTestCase.java b/config-model/src/test/java/com/yahoo/vespa/model/search/test/SchemaInfoTestCase.java index b8a14bc763b..622fcfdf4fd 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/search/test/SchemaInfoTestCase.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/search/test/SchemaInfoTestCase.java @@ -4,34 +4,34 @@ package com.yahoo.vespa.model.search.test; import com.yahoo.search.config.SchemaInfoConfig; import com.yahoo.vespa.config.search.RankProfilesConfig; import com.yahoo.vespa.model.VespaModel; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; public class SchemaInfoTestCase { /** Schema-info should contain all schemas, independent of clusters. */ @Test - public void requireThatSchemaInfoIsAvailable() { - List.of(1.0,2.0,3.0).toArray(new Double[3]); + void requireThatSchemaInfoIsAvailable() { + List.of(1.0, 2.0, 3.0).toArray(new Double[3]); String inputs = " rank-profile inputs {" + - " inputs {" + - " query(foo) tensor<float>(x[10])" + - " query(bar) tensor(key{},x[1000])" + - " query(myDouble1) double: 0.5" + - " query(myDouble2) tensor()" + - " query(myMap) tensor(key{}): { label1:1.0,\n \"label2\": 2.0, 'label3': 3.0 }" + - " query(myVector1) tensor(x[3]):\n\n[1 ,2.0,3]" + - " query(myVector2) tensor(x[3]):{{x:0}:1,{x: 1}: 2 , { x:2}:3.0 }" + - " query(myMatrix) tensor(x[2],y[3]):[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]" + - " query(myMixed1) tensor(key{},x[2]): { key1:[-1.0, 1.1], key2: [1,2]}" + - " query(myMixed2) tensor(k1{},k2{},x[2]): { {k1:l1,k2:l1}:[-1.0, 1.1], {k1:l1,k2:l2}: [1,2]}" + - " }" + - " }"; + " inputs {" + + " query(foo) tensor<float>(x[10])" + + " query(bar) tensor(key{},x[1000])" + + " query(myDouble1) double: 0.5" + + " query(myDouble2) tensor()" + + " query(myMap) tensor(key{}): { label1:1.0,\n \"label2\": 2.0, 'label3': 3.0 }" + + " query(myVector1) tensor(x[3]):\n\n[1 ,2.0,3]" + + " query(myVector2) tensor(x[3]):{{x:0}:1,{x: 1}: 2 , { x:2}:3.0 }" + + " query(myMatrix) tensor(x[2],y[3]):[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]" + + " query(myMixed1) tensor(key{},x[2]): { key1:[-1.0, 1.1], key2: [1,2]}" + + " query(myMixed2) tensor(k1{},k2{},x[2]): { {k1:l1,k2:l1}:[-1.0, 1.1], {k1:l1,k2:l2}: [1,2]}" + + " }" + + " }"; List<String> schemas = List.of("type1", "type2"); var tester = new SchemaTester(); var model = tester.createModelWithRankProfile(inputs, schemas); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/search/test/SchemaTester.java b/config-model/src/test/java/com/yahoo/vespa/model/search/test/SchemaTester.java index 9d1aece61d4..3deccbbb679 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/search/test/SchemaTester.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/search/test/SchemaTester.java @@ -16,7 +16,7 @@ import java.util.Arrays; import java.util.List; import java.util.Map; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author bratseth diff --git a/config-model/src/test/java/com/yahoo/vespa/model/search/test/SearchNodeTest.java b/config-model/src/test/java/com/yahoo/vespa/model/search/test/SearchNodeTest.java index f8a68e4b4a5..7ed27018d5f 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/search/test/SearchNodeTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/search/test/SearchNodeTest.java @@ -13,13 +13,11 @@ import com.yahoo.vespa.model.HostResource; import com.yahoo.vespa.model.search.NodeSpec; import com.yahoo.vespa.model.search.SearchNode; import com.yahoo.vespa.model.search.TransactionLogServer; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Optional; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * Unit tests for search node. @@ -59,14 +57,14 @@ public class SearchNodeTest { } @Test - public void requireThatSyncIsHonoured() { + void requireThatSyncIsHonoured() { assertTrue(getTlsConfig(new TestProperties(), null).usefsync()); assertTrue(getTlsConfig(new TestProperties(), true).usefsync()); assertFalse(getTlsConfig(new TestProperties(), false).usefsync()); } @Test - public void requireThatBasedirIsCorrectForElasticMode() { + void requireThatBasedirIsCorrectForElasticMode() { MockRoot root = new MockRoot(""); SearchNode node = createSearchNode(root, "mynode", 3, new NodeSpec(7, 5), false, root.getDeployState().isHosted(), new TestProperties()); prepare(root, node, true); @@ -74,7 +72,7 @@ public class SearchNodeTest { } @Test - public void requireThatPreShutdownCommandIsEmptyWhenNotActivated() { + void requireThatPreShutdownCommandIsEmptyWhenNotActivated() { MockRoot root = new MockRoot(""); SearchNode node = createSearchNode(root, "mynode", 3, new NodeSpec(7, 5), false, root.getDeployState().isHosted(), new TestProperties()); node.setHostResource(new HostResource(new Host(node, "mynbode"))); @@ -83,7 +81,7 @@ public class SearchNodeTest { } @Test - public void requireThatPreShutdownCommandUsesPrepareRestartWhenActivated() { + void requireThatPreShutdownCommandUsesPrepareRestartWhenActivated() { MockRoot root = new MockRoot(""); SearchNode node = createSearchNode(root, "mynode2", 4, new NodeSpec(7, 5), true, root.getDeployState().isHosted(), new TestProperties()); node.setHostResource(new HostResource(new Host(node, "mynbode2"))); @@ -101,7 +99,7 @@ public class SearchNodeTest { } @Test - public void requireThatCodePageTypeCanBeControlled() { + void requireThatCodePageTypeCanBeControlled() { verifyCodePlacement(true); verifyCodePlacement(false); } @@ -115,7 +113,7 @@ public class SearchNodeTest { } @Test - public void requireThatSharedRepoReclaimCanBeControlled() { + void requireThatSharedRepoReclaimCanBeControlled() { verifySharedStringRepoReclaim(true); verifySharedStringRepoReclaim(false); } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/storage/DistributionBitCalculatorTest.java b/config-model/src/test/java/com/yahoo/vespa/model/storage/DistributionBitCalculatorTest.java index 356021cdd1d..e7bc3fa9867 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/storage/DistributionBitCalculatorTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/storage/DistributionBitCalculatorTest.java @@ -3,14 +3,14 @@ package com.yahoo.vespa.model.storage; import com.yahoo.vespa.model.content.DistributionBitCalculator; import com.yahoo.vespa.model.content.cluster.ContentCluster; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.*; +import static org.junit.jupiter.api.Assertions.assertEquals; public class DistributionBitCalculatorTest { @Test - public void testBitCalculator() { + void testBitCalculator() { ContentCluster.DistributionMode mode = ContentCluster.DistributionMode.STRICT; assertEquals(8, DistributionBitCalculator.getDistributionBits(1, mode)); assertEquals(16, DistributionBitCalculator.getDistributionBits(10, mode)); @@ -19,15 +19,15 @@ public class DistributionBitCalculatorTest { assertEquals(28, DistributionBitCalculator.getDistributionBits(1000, mode)); mode = ContentCluster.DistributionMode.LOOSE; - assertEquals( 8, DistributionBitCalculator.getDistributionBits(1, mode)); - assertEquals( 8, DistributionBitCalculator.getDistributionBits(4, mode)); + assertEquals(8, DistributionBitCalculator.getDistributionBits(1, mode)); + assertEquals(8, DistributionBitCalculator.getDistributionBits(4, mode)); assertEquals(16, DistributionBitCalculator.getDistributionBits(5, mode)); assertEquals(16, DistributionBitCalculator.getDistributionBits(199, mode)); assertEquals(24, DistributionBitCalculator.getDistributionBits(200, mode)); assertEquals(24, DistributionBitCalculator.getDistributionBits(2500, mode)); mode = ContentCluster.DistributionMode.LEGACY; - assertEquals( 8, DistributionBitCalculator.getDistributionBits(1, mode)); + assertEquals(8, DistributionBitCalculator.getDistributionBits(1, mode)); assertEquals(14, DistributionBitCalculator.getDistributionBits(4, mode)); assertEquals(19, DistributionBitCalculator.getDistributionBits(16, mode)); assertEquals(23, DistributionBitCalculator.getDistributionBits(200, mode)); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/storage/test/StorageModelTestCase.java b/config-model/src/test/java/com/yahoo/vespa/model/storage/test/StorageModelTestCase.java index 72d6a80e711..f0b6157ba52 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/storage/test/StorageModelTestCase.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/storage/test/StorageModelTestCase.java @@ -6,10 +6,9 @@ import com.yahoo.vespa.config.content.FleetcontrollerConfig; import com.yahoo.vespa.model.VespaModel; import com.yahoo.vespa.model.content.cluster.ContentCluster; import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithFilePkg; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.*; /** * Tests storage model @@ -19,9 +18,11 @@ import static org.junit.Assert.assertNotNull; */ public class StorageModelTestCase { - @Test(expected=RuntimeException.class) - public void testTwoClustersSameName() { - createModel("src/test/cfg/storage/twoclusterssamename"); + @Test + void testTwoClustersSameName() { + assertThrows(RuntimeException.class, () -> { + createModel("src/test/cfg/storage/twoclusterssamename"); + }); } private VespaModel createModel(String filename) { @@ -29,7 +30,7 @@ public class StorageModelTestCase { } @Test - public void testIndexGreaterThanNumNodes() { + void testIndexGreaterThanNumNodes() { VespaModel vespaModel = createModel("src/test/cfg/storage/app_index_higher_than_num_nodes"); // Test fleet controller config @@ -41,7 +42,7 @@ public class StorageModelTestCase { } @Test - public void testMetricsSnapshotIntervalYAMAS() { + void testMetricsSnapshotIntervalYAMAS() { VespaModel vespaModel = createModel("src/test/cfg/storage/clustercontroller_advanced"); ContentCluster contentCluster = vespaModel.getContentClusters().values().iterator().next(); assertNotNull(contentCluster); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/test/ModelAmendingTestCase.java b/config-model/src/test/java/com/yahoo/vespa/model/test/ModelAmendingTestCase.java index 2ae1399e9d1..9be3b15be07 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/test/ModelAmendingTestCase.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/test/ModelAmendingTestCase.java @@ -20,16 +20,14 @@ import com.yahoo.vespa.model.container.ContainerCluster; import com.yahoo.vespa.model.container.ContainerModel; import com.yahoo.vespa.model.container.xml.ContainerModelBuilder; import com.yahoo.vespa.model.content.Content; -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.w3c.dom.Element; import java.util.ArrayList; import java.util.Collection; import java.util.List; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.*; /** * Demonstrates how a model can be added at build time to amend another model. @@ -42,44 +40,44 @@ import static org.junit.Assert.assertNotNull; public class ModelAmendingTestCase { @Test - public void testModelAmending() { + void testModelAmending() { ConfigModelRegistry amendingModelRepo = MapConfigModelRegistry.createFromList(new AdminModelAmenderBuilder(), - new ContainerModelAmenderBuilder(), - new ContentModelAmenderBuilder()); + new ContainerModelAmenderBuilder(), + new ContentModelAmenderBuilder()); String services = "<services version='1.0'>" + - " <admin version='4.0'/>" + - " <container id='test1' version='1.0'>" + - " <search/>" + - " <nodes count='2'/>" + - " </container>" + - " <container id='test2' version='1.0'>" + - " <http><server id='server1' port='" + Defaults.getDefaults().vespaWebServicePort() + "'/></http>" + - " <document-api/>" + - " <nodes count='2'/>" + - " </container>" + - " <content id='test3' version='1.0'>" + - " <redundancy>1</redundancy>" + - " <documents>" + - " <document mode='index' type='type1'/>" + - " </documents>" + - " <nodes count='2'/>" + - " </content>" + - " <content id='test4' version='1.0'>" + - " <redundancy>1</redundancy>" + - " <documents>" + - " <document mode='index' type='type1'/>" + - " </documents>" + - " <nodes count='3'/>" + - " </content>" + - "</services>"; + " <admin version='4.0'/>" + + " <container id='test1' version='1.0'>" + + " <search/>" + + " <nodes count='2'/>" + + " </container>" + + " <container id='test2' version='1.0'>" + + " <http><server id='server1' port='" + Defaults.getDefaults().vespaWebServicePort() + "'/></http>" + + " <document-api/>" + + " <nodes count='2'/>" + + " </container>" + + " <content id='test3' version='1.0'>" + + " <redundancy>1</redundancy>" + + " <documents>" + + " <document mode='index' type='type1'/>" + + " </documents>" + + " <nodes count='2'/>" + + " </content>" + + " <content id='test4' version='1.0'>" + + " <redundancy>1</redundancy>" + + " <documents>" + + " <document mode='index' type='type1'/>" + + " </documents>" + + " <nodes count='3'/>" + + " </content>" + + "</services>"; VespaModelTester tester = new VespaModelTester(amendingModelRepo); tester.addHosts(12); VespaModel model = tester.createModel(services); // Check that all hosts are amended for (HostResource host : model.getAdmin().hostSystem().getHosts()) { - assertFalse(host + " is amended", host.getHost().getChildrenByTypeRecursive(AmendedService.class).isEmpty()); + assertFalse(host.getHost().getChildrenByTypeRecursive(AmendedService.class).isEmpty(), host + " is amended"); } // Check that container clusters are amended @@ -89,44 +87,44 @@ public class ModelAmendingTestCase { } @Test - public void testModelAmendingWithDedicatedCC() { + void testModelAmendingWithDedicatedCC() { ConfigModelRegistry amendingModelRepo = MapConfigModelRegistry.createFromList(new AdminModelAmenderBuilder(), - new ContainerModelAmenderBuilder(), - new ContentModelAmenderBuilder()); + new ContainerModelAmenderBuilder(), + new ContentModelAmenderBuilder()); String services = "<services version='1.0'>" + - " <admin version='4.0'/>" + - " <container id='test1' version='1.0'>" + - " <search/>" + - " <nodes count='2'/>" + - " </container>" + - " <container id='test2' version='1.0'>" + - " <http><server id='server1' port='" + Defaults.getDefaults().vespaWebServicePort() + "'/></http>" + - " <document-api/>" + - " <nodes count='2'/>" + - " </container>" + - " <content id='test3' version='1.0'>" + - " <redundancy>1</redundancy>" + - " <documents>" + - " <document mode='index' type='type1'/>" + - " </documents>" + - " <nodes count='2'/>" + - " </content>" + - " <content id='test4' version='1.0'>" + - " <redundancy>1</redundancy>" + - " <documents>" + - " <document mode='index' type='type1'/>" + - " </documents>" + - " <nodes count='3'/>" + - " </content>" + - "</services>"; + " <admin version='4.0'/>" + + " <container id='test1' version='1.0'>" + + " <search/>" + + " <nodes count='2'/>" + + " </container>" + + " <container id='test2' version='1.0'>" + + " <http><server id='server1' port='" + Defaults.getDefaults().vespaWebServicePort() + "'/></http>" + + " <document-api/>" + + " <nodes count='2'/>" + + " </container>" + + " <content id='test3' version='1.0'>" + + " <redundancy>1</redundancy>" + + " <documents>" + + " <document mode='index' type='type1'/>" + + " </documents>" + + " <nodes count='2'/>" + + " </content>" + + " <content id='test4' version='1.0'>" + + " <redundancy>1</redundancy>" + + " <documents>" + + " <document mode='index' type='type1'/>" + + " </documents>" + + " <nodes count='3'/>" + + " </content>" + + "</services>"; VespaModelTester tester = new VespaModelTester(amendingModelRepo); tester.addHosts(12); VespaModel model = tester.createModel(services); // Check that all hosts are amended for (HostResource host : model.getAdmin().hostSystem().getHosts()) { - assertFalse(host + " is amended", host.getHost().getChildrenByTypeRecursive(AmendedService.class).isEmpty()); + assertFalse(host.getHost().getChildrenByTypeRecursive(AmendedService.class).isEmpty(), host + " is amended"); } // Check that container clusters are amended diff --git a/config-model/src/test/java/com/yahoo/vespa/model/test/ModelConfigProviderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/test/ModelConfigProviderTest.java index 4632c536e43..fba51c4c027 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/test/ModelConfigProviderTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/test/ModelConfigProviderTest.java @@ -4,9 +4,9 @@ package com.yahoo.vespa.model.test; import com.yahoo.cloud.config.ModelConfig; import com.yahoo.vespa.model.VespaModel; import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithFilePkg; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test HostSystem @@ -19,13 +19,13 @@ public class ModelConfigProviderTest { * Get the config via ConfigInstance based API, by getting whole config */ @Test - public void testGetModelConfig() { + void testGetModelConfig() { VespaModel vespaModel = new VespaModelCreatorWithFilePkg("src/test/cfg/admin/adminconfig20").create(); ModelConfig config = vespaModel.getConfig(ModelConfig.class, ""); assertEquals(config.hosts().size(), 1); ModelConfig.Hosts localhost = config.hosts(0); //Actually set to hostname. - int numLogservers=0; - int numSlobroks=0; + int numLogservers = 0; + int numSlobroks = 0; for (ModelConfig.Hosts.Services service : localhost.services()) { if ("logserver".equals(service.type())) { numLogservers++; diff --git a/config-model/src/test/java/com/yahoo/vespa/model/test/PortsMetaTestCase.java b/config-model/src/test/java/com/yahoo/vespa/model/test/PortsMetaTestCase.java index a54897e7ae4..0a1506fab5d 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/test/PortsMetaTestCase.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/test/PortsMetaTestCase.java @@ -2,12 +2,9 @@ package com.yahoo.vespa.model.test; import com.yahoo.vespa.model.PortsMeta; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * Tests proper functioning of the PortsMeta. @@ -17,7 +14,7 @@ import static org.junit.Assert.assertTrue; public class PortsMetaTestCase { @Test - public void testRegister() { + void testRegister() { PortsMeta pm = new PortsMeta(); pm.on(0).tag("foo"); pm.on(1).tag("bar"); @@ -31,7 +28,7 @@ public class PortsMetaTestCase { } @Test - public void testAdminStatusApi() { + void testAdminStatusApi() { PortsMeta pm = new PortsMeta() .on(0).tag("rpc").tag("nc").tag("admin").tag("status") .on(1).tag("rpc").tag("rtx").tag("admin").tag("status") diff --git a/config-model/src/test/java/com/yahoo/vespa/model/test/VespaModelTestCase.java b/config-model/src/test/java/com/yahoo/vespa/model/test/VespaModelTestCase.java index 7f8bca825d2..ac621f1ebfc 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/test/VespaModelTestCase.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/test/VespaModelTestCase.java @@ -31,8 +31,8 @@ import com.yahoo.vespa.model.application.validation.Validation; import com.yahoo.vespa.model.test.utils.ApplicationPackageUtils; import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithFilePkg; import com.yahoo.vespa.model.test.utils.VespaModelCreatorWithMockPkg; -import org.junit.Ignore; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.xml.sax.SAXException; import java.io.File; @@ -45,10 +45,7 @@ import java.util.Optional; import java.util.Set; import java.util.logging.Level; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * @author gjoranv @@ -82,7 +79,7 @@ public class VespaModelTestCase { // Verify that common config from plugins is delivered from the root node for any configId, using the Builder based API @Test - public void testCommonConfig() { + void testCommonConfig() { VespaModel model = getVespaModel(TESTDIR + "app_nohosts/"); LogdConfig.Builder b = new LogdConfig.Builder(); b = (LogdConfig.Builder) model.getConfig(b, ""); @@ -109,7 +106,7 @@ public class VespaModelTestCase { } @Test - public void testHostsConfig() { + void testHostsConfig() { VespaModel model = getVespaModel(TESTDIR + "app_qrserverandgw"); LogdConfig config = getLogdConfig(model, ""); assertEquals(config.logserver().host(), HostName.getLocalhost()); @@ -128,7 +125,7 @@ public class VespaModelTestCase { } @Test - public void testHostsOverrides() { + void testHostsOverrides() { VespaModel model = new VespaModelCreatorWithMockPkg( simpleHosts, "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + @@ -148,23 +145,25 @@ public class VespaModelTestCase { assertEquals(config.logserver().host(), "foo"); } - @Ignore - @Test(expected = UnknownConfigIdException.class) - public void testIllegalConfigIdWithBuilders() { - VespaModel model = getVespaModel(TESTDIR + "app_nohosts/"); - DocumentmanagerConfig.Builder db = new DocumentmanagerConfig.Builder(); - model.getConfig(db, "bogus"); + @Disabled + @Test + void testIllegalConfigIdWithBuilders() { + assertThrows(UnknownConfigIdException.class, () -> { + VespaModel model = getVespaModel(TESTDIR + "app_nohosts/"); + DocumentmanagerConfig.Builder db = new DocumentmanagerConfig.Builder(); + model.getConfig(db, "bogus"); + }); } @Test - public void testConfigLists() { + void testConfigLists() { VespaModel model = getVespaModel(TESTDIR + "app_nohosts/"); assertTrue(model.allConfigsProduced().size() > 0); assertTrue(model.allConfigIds().size() > 0); } @Test - public void testCreateFromReaders() { + void testCreateFromReaders() { VespaModel model = new VespaModelCreatorWithMockPkg( simpleHosts, "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + @@ -197,20 +196,22 @@ public class VespaModelTestCase { assertEquals(mBus.routingtable().size(), 1); } - @Test(expected = IllegalArgumentException.class) - public void testHostsWithoutAliases() { - new TestDriver().buildModel( - "<services version='1.0'>" + - " <admin version='2.0'>" + - " <adminserver hostalias='node0' />" + - " </admin>" + - "</services>", - "<hosts>" + - " <host name='localhost'>" + - " <alias>node0</alias>" + - " </host>" + - " <host name='foo.yahoo.com' />" + - "</hosts>"); + @Test + void testHostsWithoutAliases() { + assertThrows(IllegalArgumentException.class, () -> { + new TestDriver().buildModel( + "<services version='1.0'>" + + " <admin version='2.0'>" + + " <adminserver hostalias='node0' />" + + " </admin>" + + "</services>", + "<hosts>" + + " <host name='localhost'>" + + " <alias>node0</alias>" + + " </host>" + + " <host name='foo.yahoo.com' />" + + "</hosts>"); + }); } static class MyLogger implements DeployLogger { @@ -220,9 +221,9 @@ public class VespaModelTestCase { msgs.add(new Pair<>(level, message)); } } - + @Test - public void testDeployLogger() throws IOException, SAXException { + void testDeployLogger() throws IOException, SAXException { final String services = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + "<services version=\"1.0\">" + "<config name=\"bar.unknsownfoo\">" + @@ -247,7 +248,7 @@ public class VespaModelTestCase { } @Test - public void testNoAdmin() { + void testNoAdmin() { VespaModel model = new VespaModelCreatorWithMockPkg( simpleHosts, "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + @@ -267,7 +268,7 @@ public class VespaModelTestCase { } @Test - public void testNoMultitenantHostExported() throws IOException, SAXException { + void testNoMultitenantHostExported() throws IOException, SAXException { ApplicationPackage applicationPackage = new MockApplicationPackage.Builder() .withServices("<services version='1.0'><admin version='3.0'><nodes count='1' /></admin></services>") .build(); @@ -280,20 +281,20 @@ public class VespaModelTestCase { .build(); VespaModel model = new VespaModel(new NullConfigModelRegistry(), deployState); AllocatedHosts info = model.allocatedHosts(); - assertEquals("Admin version 3 is ignored, and there are no other hosts to borrow for admin services", 0, info.getHosts().size()); + assertEquals(0, info.getHosts().size(), "Admin version 3 is ignored, and there are no other hosts to borrow for admin services"); } @Test - public void testMinimalApp() throws IOException, SAXException { + void testMinimalApp() throws IOException, SAXException { VespaModel model = new VespaModel(new MockApplicationPackage.Builder() - .withServices("<services version='1.0'><container version='1.0'><search /></container></services>") - .build()); + .withServices("<services version='1.0'><container version='1.0'><search /></container></services>") + .build()); assertEquals(1, model.hostSystem().getHosts().size()); assertEquals(1, model.getContainerClusters().size()); } @Test - public void testPermanentServices() throws IOException, SAXException { + void testPermanentServices() throws IOException, SAXException { ApplicationPackage app = MockApplicationPackage.createEmpty(); DeployState.Builder builder = new DeployState.Builder().applicationPackage(app); VespaModel model = new VespaModel(new NullConfigModelRegistry(), builder.build()); @@ -303,7 +304,7 @@ public class VespaModelTestCase { } @Test - public void testThatDeployLogContainsWarningWhenUsingSearchdefinitionsDir() throws IOException, SAXException { + void testThatDeployLogContainsWarningWhenUsingSearchdefinitionsDir() throws IOException, SAXException { ApplicationPackage app = FilesApplicationPackage.fromFile( new File("src/test/cfg/application/deprecated_features_app/")); MyLogger logger = new MyLogger(); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/utils/DurationTest.java b/config-model/src/test/java/com/yahoo/vespa/model/utils/DurationTest.java index 533550b1d53..9e8174e858a 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/utils/DurationTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/utils/DurationTest.java @@ -1,14 +1,14 @@ // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.vespa.model.utils; -import org.junit.Test; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; public class DurationTest { @Test - public void testDurationUnits() { + void testDurationUnits() { assertEquals(1000, new Duration("1").getMilliSeconds()); assertEquals(2.0, new Duration("2").getSeconds(), 0.0001); assertEquals(1, new Duration("1ms").getMilliSeconds()); @@ -30,7 +30,7 @@ public class DurationTest { } @Test - public void testParseError() { + void testParseError() { assertException("bjarne"); assertException(""); assertException("1 foo"); diff --git a/config-model/src/test/java/com/yahoo/vespa/model/utils/FileSenderTest.java b/config-model/src/test/java/com/yahoo/vespa/model/utils/FileSenderTest.java index 96815646a88..c7358ff1d7e 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/utils/FileSenderTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/utils/FileSenderTest.java @@ -14,8 +14,8 @@ import com.yahoo.vespa.config.ConfigPayloadBuilder; import com.yahoo.vespa.model.AbstractService; import com.yahoo.vespa.model.PortAllocBridge; import com.yahoo.vespa.model.SimpleConfigProducer; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import java.nio.ByteBuffer; import java.util.ArrayList; @@ -23,7 +23,8 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; /** * @author Ulf Lilleengen @@ -64,7 +65,7 @@ public class FileSenderTest { return new FileSender(serviceList, fileRegistry, new BaseDeployLogger()); } - @Before + @BeforeEach public void setup() { MockRoot root = new MockRoot(); producer = new SimpleConfigProducer<>(root, "test"); @@ -81,7 +82,7 @@ public class FileSenderTest { } @Test - public void require_that_simple_file_fields_are_modified() { + void require_that_simple_file_fields_are_modified() { def.addFileDef("fileVal"); def.addStringDef("stringVal"); builder.setField("fileVal", "foo.txt"); @@ -93,7 +94,7 @@ public class FileSenderTest { } @Test - public void require_that_simple_path_fields_are_modified() { + void require_that_simple_path_fields_are_modified() { def.addPathDef("fileVal"); def.addStringDef("stringVal"); builder.setField("fileVal", "foo.txt"); @@ -105,7 +106,7 @@ public class FileSenderTest { } @Test - public void require_that_fields_in_inner_arrays_are_modified() { + void require_that_fields_in_inner_arrays_are_modified() { def.innerArrayDef("inner").addFileDef("fileVal"); def.innerArrayDef("inner").addStringDef("stringVal"); ConfigPayloadBuilder inner = builder.getArray("inner").append(); @@ -118,7 +119,7 @@ public class FileSenderTest { } @Test - public void require_that_arrays_are_modified() { + void require_that_arrays_are_modified() { def.arrayDef("fileArray").setTypeSpec(new ConfigDefinition.TypeSpec("fileArray", "file", null, null, null, null)); def.arrayDef("pathArray").setTypeSpec(new ConfigDefinition.TypeSpec("pathArray", "path", null, null, null, null)); def.arrayDef("stringArray").setTypeSpec(new ConfigDefinition.TypeSpec("stringArray", "string", null, null, null, null)); @@ -137,7 +138,7 @@ public class FileSenderTest { } @Test - public void require_that_structs_are_modified() { + void require_that_structs_are_modified() { def.structDef("struct").addFileDef("fileVal"); def.structDef("struct").addStringDef("stringVal"); builder.getObject("struct").setField("fileVal", "foo.txt"); @@ -149,7 +150,7 @@ public class FileSenderTest { } @Test - public void require_that_leaf_maps_are_modified() { + void require_that_leaf_maps_are_modified() { def.leafMapDef("fileMap").setTypeSpec(new ConfigDefinition.TypeSpec("fileMap", "file", null, null, null, null)); def.leafMapDef("pathMap").setTypeSpec(new ConfigDefinition.TypeSpec("pathMap", "path", null, null, null, null)); def.leafMapDef("stringMap").setTypeSpec(new ConfigDefinition.TypeSpec("stringMap", "string", null, null, null, null)); @@ -168,7 +169,7 @@ public class FileSenderTest { } @Test - public void require_that_fields_in_inner_maps_are_modified() { + void require_that_fields_in_inner_maps_are_modified() { def.structMapDef("inner").addFileDef("fileVal"); def.structMapDef("inner").addStringDef("stringVal"); ConfigPayloadBuilder inner = builder.getMap("inner").put("foo"); @@ -180,11 +181,13 @@ public class FileSenderTest { assertEquals("bar.txt", builder.getMap("inner").get("foo").getObject("stringVal").getValue()); } - @Test(expected = IllegalArgumentException.class) - public void require_that_null_files_are_not_sent() { - def.addFileDef("fileVal"); - fileRegistry.pathToRef.put("foo.txt", new FileNode("fooshash").value()); - fileSender().sendUserConfiguredFiles(producer); + @Test + void require_that_null_files_are_not_sent() { + assertThrows(IllegalArgumentException.class, () -> { + def.addFileDef("fileVal"); + fileRegistry.pathToRef.put("foo.txt", new FileNode("fooshash").value()); + fileSender().sendUserConfiguredFiles(producer); + }); } diff --git a/config-model/src/test/java/com/yahoo/vespa/model/utils/internal/ReflectionUtilTest.java b/config-model/src/test/java/com/yahoo/vespa/model/utils/internal/ReflectionUtilTest.java index fb1afb75e10..d8ea631ac96 100644 --- a/config-model/src/test/java/com/yahoo/vespa/model/utils/internal/ReflectionUtilTest.java +++ b/config-model/src/test/java/com/yahoo/vespa/model/utils/internal/ReflectionUtilTest.java @@ -7,14 +7,12 @@ import com.yahoo.config.ChangesRequiringRestart; import com.yahoo.config.ConfigInstance; import com.yahoo.test.SimpletypesConfig; import com.yahoo.vespa.config.ConfigKey; -import org.junit.Test; +import org.junit.jupiter.api.Test; import java.util.Set; import static com.yahoo.vespa.model.utils.internal.ReflectionUtil.getAllConfigsProduced; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.*; /** * @author Ulf Lilleengen @@ -67,14 +65,14 @@ public class ReflectionUtilTest { private static class NonRestartConfig extends ConfigInstance {} @Test - public void getAllConfigsProduced_includes_configs_produced_by_super_class() { + void getAllConfigsProduced_includes_configs_produced_by_super_class() { Set<ConfigKey<?>> configs = getAllConfigsProduced(ConcreteProducer.class, "foo"); assertEquals(1, configs.size()); assertTrue(configs.contains(new ConfigKey<>(SimpletypesConfig.CONFIG_DEF_NAME, "foo", SimpletypesConfig.CONFIG_DEF_NAMESPACE))); } @Test - public void getAllConfigsProduced_includes_configs_produced_by_implemented_interface() { + void getAllConfigsProduced_includes_configs_produced_by_implemented_interface() { Set<ConfigKey<?>> configs = getAllConfigsProduced(InterfaceImplementingProducer.class, "foo"); assertEquals(2, configs.size()); assertTrue(configs.contains(new ConfigKey<>(SimpletypesConfig.CONFIG_DEF_NAME, "foo", SimpletypesConfig.CONFIG_DEF_NAMESPACE))); @@ -82,27 +80,29 @@ public class ReflectionUtilTest { } @Test - public void getAllConfigsProduced_includes_configs_directly_implemented_by_producer() { + void getAllConfigsProduced_includes_configs_directly_implemented_by_producer() { Set<ConfigKey<?>> configs = getAllConfigsProduced(SimpleProducer.class, "foo"); assertEquals(1, configs.size()); assertTrue(configs.contains(new ConfigKey<>(SimpletypesConfig.CONFIG_DEF_NAME, "foo", SimpletypesConfig.CONFIG_DEF_NAMESPACE))); } @Test - public void requireThatRestartMethodsAreDetectedProperly() { + void requireThatRestartMethodsAreDetectedProperly() { assertFalse(ReflectionUtil.hasRestartMethods(NonRestartConfig.class)); assertTrue(ReflectionUtil.hasRestartMethods(RestartConfig.class)); } @Test - public void requireThatRestartMethodsAreProperlyInvoked() { + void requireThatRestartMethodsAreProperlyInvoked() { assertTrue(ReflectionUtil.containsFieldsFlaggedWithRestart(RestartConfig.class)); assertEquals("testing", ReflectionUtil.getChangesRequiringRestart(new RestartConfig(), new RestartConfig()).getName()); } - @Test(expected = IllegalArgumentException.class) - public void requireThatGetChangesRequiringRestartValidatesParameterTypes() { - ReflectionUtil.getChangesRequiringRestart(new RestartConfig(), new NonRestartConfig()); + @Test + void requireThatGetChangesRequiringRestartValidatesParameterTypes() { + assertThrows(IllegalArgumentException.class, () -> { + ReflectionUtil.getChangesRequiringRestart(new RestartConfig(), new NonRestartConfig()); + }); } |