aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--README.md4
-rw-r--r--application-preprocessor/pom.xml27
-rw-r--r--application-preprocessor/src/test/java/com/yahoo/application/preprocessor/ApplicationPreprocessorTest.java26
-rw-r--r--application/abi-spec.json1
-rw-r--r--application/pom.xml29
-rw-r--r--application/src/main/java/com/yahoo/application/Application.java19
-rw-r--r--application/src/test/app-packages/withqueryprofile/schemas/mydoc.sd17
-rw-r--r--application/src/test/app-packages/withqueryprofile/search/query-profiles/default.xml3
-rw-r--r--application/src/test/app-packages/withqueryprofile/services.xml29
-rw-r--r--application/src/test/java/com/yahoo/application/ApplicationBuilderTest.java53
-rw-r--r--application/src/test/java/com/yahoo/application/ApplicationTest.java114
-rw-r--r--application/src/test/java/com/yahoo/application/container/ContainerDocprocTest.java80
-rw-r--r--application/src/test/java/com/yahoo/application/container/ContainerModelEvaluationTest.java23
-rw-r--r--application/src/test/java/com/yahoo/application/container/ContainerProcessingTest.java62
-rw-r--r--application/src/test/java/com/yahoo/application/container/ContainerRequestTest.java48
-rw-r--r--application/src/test/java/com/yahoo/application/container/ContainerSchemaTest.java24
-rw-r--r--application/src/test/java/com/yahoo/application/container/ContainerTest.java35
-rw-r--r--application/src/test/java/com/yahoo/application/container/handler/HeadersTestCase.java77
-rw-r--r--application/src/test/java/com/yahoo/application/container/handler/ResponseTestCase.java10
-rw-r--r--athenz-identity-provider-service/pom.xml35
-rw-r--r--athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/athenz/instanceproviderservice/IdentityDocumentGeneratorTest.java32
-rw-r--r--athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/athenz/instanceproviderservice/InstanceValidatorTest.java28
-rw-r--r--athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/CertificatesTest.java16
-rw-r--r--athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/restapi/CertificateAuthorityApiTest.java68
-rw-r--r--athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/restapi/ContainerTester.java10
-rw-r--r--athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/restapi/InstanceSerializerTest.java38
-rw-r--r--bundle-plugin-test/integration-test/pom.xml13
-rw-r--r--bundle-plugin-test/integration-test/src/test/java/com/yahoo/container/plugin/BundleTest.java36
-rw-r--r--bundle-plugin-test/integration-test/src/test/java/com/yahoo/container/plugin/ExportPackageVersionTest.java18
-rw-r--r--bundle-plugin/pom.xml15
-rw-r--r--bundle-plugin/src/test/java/com/yahoo/container/plugin/bundle/AnalyzeBundleTest.java20
-rw-r--r--bundle-plugin/src/test/java/com/yahoo/container/plugin/classanalysis/AnalyzeClassTest.java58
-rw-r--r--bundle-plugin/src/test/java/com/yahoo/container/plugin/classanalysis/AnalyzeMethodBodyTest.java26
-rw-r--r--bundle-plugin/src/test/java/com/yahoo/container/plugin/classanalysis/PackageTallyTest.java6
-rw-r--r--bundle-plugin/src/test/java/com/yahoo/container/plugin/mojo/GenerateSourcesMojoTest.java10
-rw-r--r--bundle-plugin/src/test/java/com/yahoo/container/plugin/osgi/ExportPackageParserTest.java24
-rw-r--r--bundle-plugin/src/test/java/com/yahoo/container/plugin/osgi/ImportPackageTest.java40
-rw-r--r--bundle-plugin/src/test/java/com/yahoo/container/plugin/util/TestBundleDependencyScopeTranslatorTest.java18
-rw-r--r--client/js/app/README.md11
-rw-r--r--client/js/app/src/app/main.jsx5
-rw-r--r--client/js/app/src/app/pages/querybuilder/Components/Buttons/CopyResponseButton.jsx40
-rw-r--r--client/js/app/src/app/pages/querybuilder/Components/Buttons/DownloadJSONButton.jsx44
-rw-r--r--client/js/app/src/app/pages/querybuilder/Components/Buttons/OverlayImageButton.jsx2
-rw-r--r--client/js/app/src/app/pages/querybuilder/Components/Buttons/PasteJSONButton.jsx48
-rw-r--r--client/js/app/src/app/pages/querybuilder/Components/Contexts/QueryInputContext.jsx1
-rw-r--r--client/js/app/src/app/pages/querybuilder/Components/Text/QueryDropDownForm.jsx12
-rw-r--r--client/js/app/src/app/pages/querybuilder/Components/Text/QueryInput.jsx11
-rw-r--r--client/js/app/src/app/pages/querybuilder/Components/Text/QueryInputChild.jsx7
-rw-r--r--client/js/app/src/app/pages/querybuilder/Components/Text/ResponseBox.jsx2
-rw-r--r--client/js/app/src/app/pages/querybuilder/Components/Text/SendQuery.jsx7
-rw-r--r--client/js/app/src/app/pages/querybuilder/Components/Text/SimpleDropDownForm.jsx10
-rw-r--r--client/js/app/src/app/pages/querybuilder/TransformVespaTrace.jsx345
-rw-r--r--client/js/app/src/app/pages/querybuilder/query-builder.jsx34
-rw-r--r--client/js/app/src/app/pages/querytracer/query-tracer.jsx24
-rw-r--r--cloud-tenant-base-dependencies-enforcer/pom.xml4
-rw-r--r--clustercontroller-apps/pom.xml27
-rw-r--r--clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apps/clustercontroller/ClusterControllerClusterConfigurerTest.java26
-rw-r--r--clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apps/clustercontroller/ClusterControllerTest.java20
-rw-r--r--clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apps/clustercontroller/StateRestApiV2HandlerTest.java8
-rw-r--r--clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apps/clustercontroller/StatusHandlerTest.java4
-rw-r--r--clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apputil/communication/http/JDiscHttpRequestHandlerTest.java16
-rw-r--r--clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apputil/communication/http/JDiscMetricWrapperTest.java10
-rw-r--r--clustercontroller-core/pom.xml21
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/AggregatedStatsMergePendingCheckerTest.java20
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterFeedBlockTest.java36
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStateBundleTest.java51
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStateGeneratorTest.java134
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStateViewTest.java28
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStatsAggregatorTest.java20
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStatsChangeTrackerTest.java18
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ContentClusterHtmlRendererTest.java8
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ContentNodeStatsTest.java20
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/DatabaseHandlerTest.java22
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/DatabaseTest.java21
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/DistributionBitCountTest.java17
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/EventDiffCalculatorTest.java58
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/EventLogTest.java19
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/FleetControllerContextImplTest.java6
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/FleetControllerTest.java39
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/GroupAutoTakedownLiveConfigTest.java10
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/GroupAutoTakedownTest.java57
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/GroupAvailabilityCalculatorTest.java30
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/LeafGroupsTest.java10
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/MaintenanceWhenPendingGlobalMergesTest.java16
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/MasterElectionTest.java89
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/MetricReporterTest.java14
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/NoZooKeeperTest.java7
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/NodeInfoTest.java24
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/NodeSlobrokConfigurationMembershipTest.java10
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/NodeStateChangeCheckerTest.java71
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ResourceExhaustionCalculatorTest.java73
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ResourceUsageStatsTest.java15
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/RpcServerTest.java144
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/RpcVersionAutoDowngradeTest.java6
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/SlobrokTest.java44
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/StateChangeHandlerTest.java18
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/StateChangeTest.java311
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/StateGatherTest.java6
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/StateVersionTrackerTest.java60
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/SystemStateBroadcasterTest.java42
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/UpEdgeMaintenanceTransitionConstraintTest.java16
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/WantedStateTest.java9
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ZooKeeperDatabaseTest.java44
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/hostinfo/HostInfoTest.java21
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/hostinfo/StorageNodeStatsBridgeTest.java6
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/ClusterListTest.java91
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/ClusterTest.java102
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/NodeTest.java160
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/NotMasterTest.java72
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/PartitionTest.java48
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/RequestTest.java11
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/ServiceTest.java192
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/SetNodeStateTest.java143
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/requests/SetNodeStateRequestTest.java20
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/rpc/RPCCommunicatorTest.java20
-rw-r--r--clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/rpc/SlimeClusterStateBundleCodecTest.java18
-rw-r--r--clustercontroller-reindexer/pom.xml14
-rw-r--r--clustercontroller-reindexer/src/test/java/ai/vespa/reindexing/http/ReindexingV1ApiTest.java2
-rw-r--r--clustercontroller-utils/pom.xml15
-rw-r--r--clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/async/AsyncTest.java32
-rw-r--r--clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/http/HttpRequestTest.java34
-rw-r--r--clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/http/HttpResultTest.java10
-rw-r--r--clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/http/JsonHttpResultTest.java22
-rw-r--r--clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/http/writer/HttpWriterTest.java30
-rw-r--r--clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/staterestapi/StateRestAPITest.java335
-rw-r--r--clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/staterestapi/server/RestApiHandlerTest.java6
-rw-r--r--clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/util/CertainlyCloneableTest.java10
-rw-r--r--clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/util/ClockTest.java6
-rw-r--r--clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/util/JSONObjectWrapperTest.java8
-rw-r--r--clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/util/MetricReporterTest.java42
-rwxr-xr-xcomponent/pom.xml15
-rw-r--r--component/src/test/java/com/yahoo/component/VersionCompatibilityTest.java32
-rw-r--r--component/src/test/java/com/yahoo/component/VersionSpecificationTestCase.java118
-rw-r--r--component/src/test/java/com/yahoo/component/VersionTestCase.java150
-rw-r--r--config-lib/pom.xml15
-rw-r--r--config-lib/src/test/java/com/yahoo/config/BooleanNodeTest.java8
-rw-r--r--config-lib/src/test/java/com/yahoo/config/ConfigInstanceBuilderTest.java78
-rw-r--r--config-lib/src/test/java/com/yahoo/config/ConfigInstanceEqualsTest.java36
-rw-r--r--config-lib/src/test/java/com/yahoo/config/DoubleNodeTest.java10
-rw-r--r--config-lib/src/test/java/com/yahoo/config/EnumNodeTest.java12
-rw-r--r--config-lib/src/test/java/com/yahoo/config/FileNodeTest.java12
-rw-r--r--config-lib/src/test/java/com/yahoo/config/IntegerNodeTest.java10
-rw-r--r--config-lib/src/test/java/com/yahoo/config/LongNodeTest.java10
-rw-r--r--config-lib/src/test/java/com/yahoo/config/NodeVectorTest.java97
-rw-r--r--config-lib/src/test/java/com/yahoo/config/PathNodeTest.java10
-rw-r--r--config-lib/src/test/java/com/yahoo/config/StringNodeTest.java19
-rw-r--r--config-lib/src/test/java/com/yahoo/config/UrlNodeTest.java6
-rw-r--r--config-lib/src/test/java/com/yahoo/config/codegen/NamespaceAndPackageTest.java10
-rw-r--r--config-model/pom.xml15
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/admin/clustercontroller/ClusterControllerContainerCluster.java9
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsProxyContainerCluster.java14
-rwxr-xr-xconfig-model/src/main/java/com/yahoo/vespa/model/container/ContainerCluster.java35
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/container/PlatformBundles.java33
-rw-r--r--config-model/src/main/java/com/yahoo/vespa/model/container/http/BlockFeedGlobalEndpointsFilter.java12
-rw-r--r--config-model/src/test/java/com/yahoo/config/model/ApplicationDeployTest.java140
-rw-r--r--config-model/src/test/java/com/yahoo/config/model/ConfigModelBuilderTest.java44
-rw-r--r--config-model/src/test/java/com/yahoo/config/model/ConfigModelContextTest.java8
-rw-r--r--config-model/src/test/java/com/yahoo/config/model/ConfigModelUtilsTest.java20
-rw-r--r--config-model/src/test/java/com/yahoo/config/model/MapConfigModelRegistryTest.java8
-rw-r--r--config-model/src/test/java/com/yahoo/config/model/QrserverAndGatewayPortAllocationTest.java6
-rw-r--r--config-model/src/test/java/com/yahoo/config/model/application/provider/SchemaValidatorTest.java48
-rw-r--r--config-model/src/test/java/com/yahoo/config/model/builder/xml/ConfigModelIdTest.java25
-rw-r--r--config-model/src/test/java/com/yahoo/config/model/builder/xml/XmlErrorHandlingTest.java12
-rw-r--r--config-model/src/test/java/com/yahoo/config/model/builder/xml/test/DomBuilderTest.java4
-rw-r--r--config-model/src/test/java/com/yahoo/config/model/deploy/DeployStateTest.java26
-rw-r--r--config-model/src/test/java/com/yahoo/config/model/deploy/SystemModelTestCase.java29
-rw-r--r--config-model/src/test/java/com/yahoo/config/model/graph/ModelGraphTest.java63
-rw-r--r--config-model/src/test/java/com/yahoo/config/model/producer/AbstractConfigProducerTest.java10
-rw-r--r--config-model/src/test/java/com/yahoo/config/model/provision/HostSpecTest.java46
-rw-r--r--config-model/src/test/java/com/yahoo/config/model/provision/HostsXmlProvisionerTest.java21
-rw-r--r--config-model/src/test/java/com/yahoo/config/model/provision/ModelProvisioningTest.java231
-rw-r--r--config-model/src/test/java/com/yahoo/config/model/provision/SingleNodeProvisionerTest.java24
-rw-r--r--config-model/src/test/java/com/yahoo/document/test/SDDocumentTypeTestCase.java38
-rw-r--r--config-model/src/test/java/com/yahoo/document/test/SDFieldTestCase.java8
-rw-r--r--config-model/src/test/java/com/yahoo/schema/AnnotationReferenceTestCase.java12
-rw-r--r--config-model/src/test/java/com/yahoo/schema/ArraysTestCase.java12
-rw-r--r--config-model/src/test/java/com/yahoo/schema/ArraysWeightedSetsTestCase.java16
-rw-r--r--config-model/src/test/java/com/yahoo/schema/AttributeSettingsTestCase.java65
-rw-r--r--config-model/src/test/java/com/yahoo/schema/CommentTestCase.java8
-rw-r--r--config-model/src/test/java/com/yahoo/schema/DiversityTestCase.java13
-rw-r--r--config-model/src/test/java/com/yahoo/schema/DocumentGraphValidatorTest.java101
-rw-r--r--config-model/src/test/java/com/yahoo/schema/DocumentReferenceResolverTest.java86
-rw-r--r--config-model/src/test/java/com/yahoo/schema/FeatureNamesTestCase.java30
-rw-r--r--config-model/src/test/java/com/yahoo/schema/FieldOfTypeDocumentTestCase.java11
-rw-r--r--config-model/src/test/java/com/yahoo/schema/ImportedFieldsEnumeratorTest.java8
-rw-r--r--config-model/src/test/java/com/yahoo/schema/IncorrectRankingExpressionFileRefTestCase.java12
-rw-r--r--config-model/src/test/java/com/yahoo/schema/IncorrectSummaryTypesTestCase.java29
-rw-r--r--config-model/src/test/java/com/yahoo/schema/IndexSettingsTestCase.java24
-rw-r--r--config-model/src/test/java/com/yahoo/schema/IndexingParsingTestCase.java8
-rw-r--r--config-model/src/test/java/com/yahoo/schema/MultipleSummariesTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/NameFieldCheckTestCase.java68
-rw-r--r--config-model/src/test/java/com/yahoo/schema/OutsideTestCase.java15
-rw-r--r--config-model/src/test/java/com/yahoo/schema/PredicateDataTypeTestCase.java143
-rw-r--r--config-model/src/test/java/com/yahoo/schema/RankProfileRegistryTest.java26
-rw-r--r--config-model/src/test/java/com/yahoo/schema/RankProfileTestCase.java42
-rw-r--r--config-model/src/test/java/com/yahoo/schema/RankPropertiesTestCase.java19
-rw-r--r--config-model/src/test/java/com/yahoo/schema/RankingConstantTest.java82
-rw-r--r--config-model/src/test/java/com/yahoo/schema/RankingExpressionConstantsTestCase.java25
-rw-r--r--config-model/src/test/java/com/yahoo/schema/RankingExpressionInliningTestCase.java56
-rw-r--r--config-model/src/test/java/com/yahoo/schema/RankingExpressionLoopDetectionTestCase.java302
-rw-r--r--config-model/src/test/java/com/yahoo/schema/RankingExpressionShadowingTestCase.java32
-rw-r--r--config-model/src/test/java/com/yahoo/schema/RankingExpressionValidationTestCase.java9
-rw-r--r--config-model/src/test/java/com/yahoo/schema/ReservedWordsAsFieldNamesTestCase.java6
-rw-r--r--config-model/src/test/java/com/yahoo/schema/SchemaImporterTestCase.java43
-rw-r--r--config-model/src/test/java/com/yahoo/schema/SchemaParsingTestCase.java21
-rw-r--r--config-model/src/test/java/com/yahoo/schema/SchemaTestCase.java441
-rw-r--r--config-model/src/test/java/com/yahoo/schema/StemmingSettingTestCase.java10
-rwxr-xr-xconfig-model/src/test/java/com/yahoo/schema/StructTestCase.java24
-rw-r--r--config-model/src/test/java/com/yahoo/schema/SummaryTestCase.java93
-rw-r--r--config-model/src/test/java/com/yahoo/schema/UrlFieldValidationTestCase.java18
-rwxr-xr-xconfig-model/src/test/java/com/yahoo/schema/derived/AnnotationsTestCase.java22
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/ArraysTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/AttributeListTestCase.java42
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/AttributesTestCase.java10
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/CasingTestCase.java6
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/CombinedAttributeAndIndexSchemaTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/DeriverTestCase.java6
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/DuplicateStructTestCase.java8
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/EmptyRankProfileTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/ExactMatchTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/ExportingTestCase.java82
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/ExpressionsAsArgsTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/FieldsetTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/GeminiTestCase.java7
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/IdTestCase.java12
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/ImportedFieldsTestCase.java16
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/IndexSchemaTestCase.java138
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/InheritanceTestCase.java47
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/IntegerAttributeToStringIndexTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/LiteralBoostTestCase.java30
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/LowercaseTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/MailTestCase.java5
-rwxr-xr-xconfig-model/src/test/java/com/yahoo/schema/derived/MatchSettingsResolvingTestCase.java22
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/MultiStructTestCase.java6
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/MultipleSummariesTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/NameCollisionTestCase.java9
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/NativeRankTypeDefinitionsTestCase.java9
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/NearestNeighborTestCase.java13
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/NeuralNetTestCase.java11
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/NuwaTestCase.java10
-rwxr-xr-xconfig-model/src/test/java/com/yahoo/schema/derived/OrderIlscriptsTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/PrefixExactAttributeTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/RankProfilesTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/RankPropertiesTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/ReferenceFieldsTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/ReferenceFromSeveralTestCase.java6
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/SchemaInheritanceTestCase.java10
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/SchemaOrdererTestCase.java32
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/SimpleInheritTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/SliceTestCase.java6
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/SortingTestCase.java4
-rwxr-xr-xconfig-model/src/test/java/com/yahoo/schema/derived/StreamingStructTestCase.java6
-rwxr-xr-xconfig-model/src/test/java/com/yahoo/schema/derived/StructAnyOrderTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/StructInheritanceTestCase.java37
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/SummaryMapTestCase.java32
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/SummaryTestCase.java17
-rwxr-xr-xconfig-model/src/test/java/com/yahoo/schema/derived/TokenizationTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/TwoStreamingStructsTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/TypeConversionTestCase.java9
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/TypesTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/derived/VsmFieldsTestCase.java6
-rw-r--r--config-model/src/test/java/com/yahoo/schema/document/ComplexAttributeFieldUtilsTestCase.java22
-rw-r--r--config-model/src/test/java/com/yahoo/schema/document/HnswIndexParamsTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/parser/ConvertIntermediateTestCase.java38
-rw-r--r--config-model/src/test/java/com/yahoo/schema/parser/IntermediateCollectionTestCase.java75
-rw-r--r--config-model/src/test/java/com/yahoo/schema/parser/ParsedDocumentTestCase.java15
-rw-r--r--config-model/src/test/java/com/yahoo/schema/parser/SchemaParserTestCase.java55
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/AddAttributeTransformToSummaryOfImportedFieldsTest.java6
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/AdjustPositionSummaryFieldsTestCase.java134
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/AssertIndexingScript.java8
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/AssertSearchBuilder.java2
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/AttributesExactMatchTestCase.java21
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/BoldingTestCase.java14
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/BoolAttributeValidatorTestCase.java12
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/DictionaryTestCase.java83
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/DisallowComplexMapAndWsetKeyTypesTestCase.java46
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/FastAccessValidatorTest.java85
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/ImplicitSchemaFieldsTestCase.java18
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/ImplicitStructTypesTestCase.java10
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/ImplicitSummariesTestCase.java14
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/ImplicitSummaryFieldsTestCase.java8
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/ImportedFieldsResolverTestCase.java76
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/ImportedFieldsTestCase.java119
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/IndexingInputsTestCase.java28
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/IndexingOutputsTestCase.java14
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/IndexingScriptRewriterTestCase.java90
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/IndexingValidationTestCase.java48
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/IndexingValuesTestCase.java12
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/IntegerIndex2AttributeTestCase.java8
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/MatchPhaseSettingsValidatorTestCase.java10
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/MatchedElementsOnlyResolverTestCase.java39
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/NGramTestCase.java19
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/PagedAttributeValidatorTestCase.java19
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/PositionTestCase.java18
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/RankModifierTestCase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/RankProfileSearchFixture.java2
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/RankPropertyVariablesTestCase.java12
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionTypeResolverTestCase.java174
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithLightGBMTestCase.java14
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithOnnxModelTestCase.java12
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithOnnxTestCase.java75
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithTensorTestCase.java184
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithTransformerTokensTestCase.java10
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionWithXGBoostTestCase.java14
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/RankingExpressionsTestCase.java27
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/ReferenceFieldTestCase.java79
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/ReservedDocumentNamesTestCase.java8
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/ReservedRankingExpressionFunctionNamesTestCase.java8
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/SchemaMustHaveDocumentTest.java8
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/SummaryConsistencyTestCase.java6
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/SummaryFieldsMustHaveValidSourceTestCase.java14
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/TensorFieldTestCase.java37
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/TensorTransformTestCase.java86
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/ValidateFieldTypesTest.java31
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/VespaMlModelTestCase.java12
-rw-r--r--config-model/src/test/java/com/yahoo/schema/processing/WeightedSetSummaryToTestCase.java6
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/documentmodel/DocumentModelBuilderImportedFieldsTestCase.java22
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/documentmodel/DocumentModelBuilderReferenceTypeTestCase.java34
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/documentmodel/DocumentModelBuilderTestCase.java18
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/HostPortsTest.java53
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/HostResourceTest.java10
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/InstanceResolverTest.java10
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/RecentLogFilterTest.java8
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/VespaModelFactoryTest.java56
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/admin/AdminTestCase.java22
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/admin/ClusterControllerTestCase.java146
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/admin/DedicatedAdminV4Test.java70
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsConsumersTest.java166
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsProxyContainerClusterTest.java52
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsProxyContainerTest.java46
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/MonitoringElementTest.java22
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/admin/metricsproxy/TelegrafTest.java92
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/admin/monitoring/MetricSetTest.java12
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/admin/monitoring/MetricTest.java6
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/AccessControlFilterValidatorTest.java10
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/AccessControlValidatorTestBase.java62
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/BundleValidatorTest.java24
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/CloudWatchValidatorTest.java16
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/ComplexFieldsValidatorTestCase.java94
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/ConstantTensorJsonValidatorTest.java324
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/ConstantValidatorTest.java10
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/DeploymentSpecValidatorTest.java32
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/EndpointCertificateSecretsValidatorTest.java30
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/NoPrefixForIndexesTest.java14
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/QuotaValidatorTest.java18
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/SchemaDataTypeValidatorTestCase.java14
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/SecretStoreValidatorTest.java37
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/StreamingValidatorTest.java24
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/UriBindingsValidatorTest.java53
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/ValidationOverridesValidatorTest.java24
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ClusterSizeReductionValidatorTest.java20
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ConfigChangeTestUtils.java2
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ConfigValueChangeValidatorTest.java43
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ContainerRestartValidatorTest.java14
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ContentClusterRemovalValidatorTest.java14
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ContentTypeRemovalValidatorTest.java16
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/GlobalDocumentChangeValidatorTest.java8
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/IndexedSchemaClusterChangeValidatorTest.java38
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/IndexingModeChangeValidatorTest.java26
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/NodeResourceChangeValidatorTest.java8
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/RedundancyIncreaseValidatorTest.java18
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/ResourcesReductionValidatorTest.java28
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/RestartChangesDefersConfigChangesTest.java12
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/StartupCommandChangeValidatorTest.java11
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/StreamingSchemaClusterChangeValidatorTest.java24
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/AttributeChangeValidatorTest.java94
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/ContentClusterFixture.java4
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/DocumentDatabaseChangeValidatorTest.java24
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/DocumentTypeChangeValidatorTest.java82
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/IndexingScriptChangeValidatorTest.java147
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/change/search/StructFieldAttributeChangeValidatorTestCase.java50
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/application/validation/first/RedundancyOnFirstDeploymentValidatorTest.java18
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/builder/UserConfigBuilderTest.java22
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/Bug6068056Test.java14
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/ContentBuilderTest.java557
-rwxr-xr-xconfig-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomAdminV2BuilderTest.java42
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomComponentBuilderTest.java10
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomConfigPayloadBuilderTest.java121
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/DomSchemaTuningBuilderTest.java41
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/LegacyConfigModelBuilderTest.java9
-rwxr-xr-xconfig-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/VespaDomBuilderTest.java22
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/DependenciesBuilderTest.java6
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomFederationSearcherBuilderTest.java14
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomSchemaChainsBuilderTest.java27
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/builder/xml/dom/chains/search/DomSearcherBuilderTest.java6
-rwxr-xr-xconfig-model/src/test/java/com/yahoo/vespa/model/container/ContainerClusterTest.java136
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/ContainerIncludeTest.java55
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/component/BindingPatternTest.java13
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/configserver/ConfigserverClusterTest.java44
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/http/BlockFeedGlobalEndpointsFilterTest.java13
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/http/DefaultFilterTest.java6
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/http/FilterBindingsTest.java16
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/http/FilterChainsTest.java18
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/http/FilterConfigTest.java22
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/http/StrictFilteringTest.java10
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/ml/ModelsEvaluatorTest.java8
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/processing/test/ProcessingChainsTest.java12
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/search/ImplicitIndexingClusterTest.java10
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/search/SemanticRulesTest.java9
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/Federation2Test.java10
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/FederationSearcherTest.java27
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/FederationTest.java12
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/SchemaChainsTest.java12
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/SchemaChainsTest2.java22
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/SchemaChainsTestBase.java4
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/search/searchchain/SourceGroupTest.java16
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/search/test/PageTemplatesTestCase.java8
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/search/test/QueryProfileVariantsTestCase.java32
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/search/test/QueryProfilesTestCase.java58
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/xml/AccessControlTest.java125
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/xml/AccessLogTest.java55
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/xml/BundleInstantiationSpecificationBuilderTest.java10
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/xml/ContainerDocumentApiBuilderTest.java23
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/xml/ContainerModelBuilderTest.java209
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/xml/ContainerModelBuilderTestBase.java6
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/xml/DocprocBuilderTest.java34
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/xml/EmbedderTestCase.java16
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/xml/HandlerBuilderTest.java25
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/xml/IdentityBuilderTest.java26
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/xml/JettyContainerModelBuilderTest.java66
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/xml/JvmOptionsTest.java34
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/xml/RoutingBuilderTest.java39
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/xml/SearchBuilderTest.java67
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/container/xml/SecretStoreTest.java16
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/ClusterResourceLimitsTest.java25
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/ContentBaseTest.java2
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/ContentClusterTest.java738
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/ContentSchemaClusterTest.java39
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/ContentSchemaTest.java10
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/DispatchTuningTest.java22
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/DistributorTest.java78
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/FleetControllerClusterTest.java18
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/GenericConfigTest.java12
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/GlobalDistributionValidatorTest.java18
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/IndexedHierarchicDistributionTest.java31
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/IndexedSchemaNodeNamingTest.java10
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/IndexedTest.java106
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/IndexingAndDocprocRoutingTest.java99
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/MonitoringConfigSnoopTest.java17
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/RedundancyTest.java8
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/ReservedDocumentTypeNameValidatorTest.java14
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/SchemaCoverageTest.java20
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/StorageClusterTest.java84
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/StorageContentTest.java15
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/StorageGroupTest.java14
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/TopologicalDocumentTypeSorterTest.java8
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/cluster/ClusterTest.java32
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/cluster/DomContentApplicationBuilderTest.java26
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/cluster/DomDispatchTuningBuilderTest.java53
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/cluster/DomSchemaCoverageBuilderTest.java42
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/content/cluster/GlobalDistributionBuilderTest.java16
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/filedistribution/FileReferencesRepositoryTestCase.java8
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/ml/ImportedModelTester.java8
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/ml/MlModelsTest.java13
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/ml/ModelEvaluationTest.java15
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/ml/OnnxModelProbeTest.java6
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/ml/StatelessOnnxEvaluationTest.java12
-rwxr-xr-xconfig-model/src/test/java/com/yahoo/vespa/model/routing/test/RoutingTestCase.java10
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/search/NodeResourcesTuningTest.java72
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/search/test/DocumentDatabaseTestCase.java78
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/search/test/DocumentSelectionConverterTest.java19
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/search/test/SchemaClusterTest.java133
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/search/test/SchemaInfoTestCase.java36
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/search/test/SchemaTester.java2
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/search/test/SearchNodeTest.java18
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/storage/DistributionBitCalculatorTest.java12
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/storage/test/StorageModelTestCase.java17
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/test/ModelAmendingTestCase.java122
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/test/ModelConfigProviderTest.java10
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/test/PortsMetaTestCase.java11
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/test/VespaModelTestCase.java83
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/utils/DurationTest.java10
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/utils/FileSenderTest.java35
-rw-r--r--config-model/src/test/java/com/yahoo/vespa/model/utils/internal/ReflectionUtilTest.java24
-rw-r--r--config-model/src/test/java/helpers/CompareConfigTestHelper.java2
-rw-r--r--config-provisioning/pom.xml23
-rw-r--r--config-provisioning/src/test/java/com/yahoo/config/provision/ApplicationIdTest.java67
-rw-r--r--config-provisioning/src/test/java/com/yahoo/config/provision/CapacityTest.java42
-rw-r--r--config-provisioning/src/test/java/com/yahoo/config/provision/ClusterMembershipTest.java36
-rw-r--r--config-provisioning/src/test/java/com/yahoo/config/provision/ClusterResourcesTest.java6
-rw-r--r--config-provisioning/src/test/java/com/yahoo/config/provision/ClusterSpecTest.java30
-rw-r--r--config-provisioning/src/test/java/com/yahoo/config/provision/DockerImageTest.java42
-rw-r--r--config-provisioning/src/test/java/com/yahoo/config/provision/HostFilterTest.java22
-rw-r--r--config-provisioning/src/test/java/com/yahoo/config/provision/HostNameTest.java6
-rw-r--r--config-provisioning/src/test/java/com/yahoo/config/provision/IdentifierTestBase.java16
-rw-r--r--config-provisioning/src/test/java/com/yahoo/config/provision/NodeFlavorsTest.java8
-rw-r--r--config-provisioning/src/test/java/com/yahoo/config/provision/NodeResourcesTest.java22
-rw-r--r--config-provisioning/src/test/java/com/yahoo/config/provision/SystemNameTest.java8
-rw-r--r--config-provisioning/src/test/java/com/yahoo/config/provision/TenantTest.java12
-rw-r--r--config-provisioning/src/test/java/com/yahoo/config/provision/ZoneIdTest.java10
-rw-r--r--config-provisioning/src/test/java/com/yahoo/config/provision/serialization/AllocatedHostsSerializerTest.java10
-rw-r--r--config-proxy/pom.xml21
-rw-r--r--config-proxy/src/test/java/com/yahoo/vespa/config/proxy/ConfigProxyRpcServerTest.java105
-rw-r--r--config-proxy/src/test/java/com/yahoo/vespa/config/proxy/DelayedResponseHandlerTest.java19
-rw-r--r--config-proxy/src/test/java/com/yahoo/vespa/config/proxy/DelayedResponseTest.java16
-rw-r--r--config-proxy/src/test/java/com/yahoo/vespa/config/proxy/DelayedResponsesTest.java6
-rw-r--r--config-proxy/src/test/java/com/yahoo/vespa/config/proxy/MemoryCacheConfigClientTest.java8
-rw-r--r--config-proxy/src/test/java/com/yahoo/vespa/config/proxy/MemoryCacheTest.java14
-rw-r--r--config-proxy/src/test/java/com/yahoo/vespa/config/proxy/ProxyServerTest.java44
-rw-r--r--config-proxy/src/test/java/com/yahoo/vespa/config/proxy/RpcConfigSourceClientTest.java25
-rw-r--r--config-proxy/src/test/java/com/yahoo/vespa/config/proxy/filedistribution/CachedFilesMaintainerTest.java32
-rw-r--r--configdefinitions/src/main/java/com/yahoo/vespa/config/jdisc/http/filter/package-info.java5
-rw-r--r--configdefinitions/src/vespa/jdisc.http.filter.security.rule.config.rule-based-filter.def18
-rw-r--r--configgen/pom.xml9
-rw-r--r--configgen/src/test/java/com/yahoo/config/codegen/DefLineParsingTest.java59
-rw-r--r--configgen/src/test/java/com/yahoo/config/codegen/DefParserNamespaceTest.java41
-rw-r--r--configgen/src/test/java/com/yahoo/config/codegen/DefParserPackageTest.java40
-rw-r--r--configgen/src/test/java/com/yahoo/config/codegen/DefParserTest.java115
-rw-r--r--configgen/src/test/java/com/yahoo/config/codegen/JavaClassBuilderTest.java102
-rw-r--r--configgen/src/test/java/com/yahoo/config/codegen/MakeConfigTest.java20
-rw-r--r--configgen/src/test/java/com/yahoo/config/codegen/NormalizedDefinitionTest.java18
-rw-r--r--configserver-flags/pom.xml33
-rw-r--r--configserver-flags/src/test/java/com/yahoo/vespa/configserver/flags/ConfigServerFlagSourceTest.java18
-rw-r--r--configserver-flags/src/test/java/com/yahoo/vespa/configserver/flags/db/FlagsDbImplTest.java20
-rw-r--r--configserver-flags/src/test/java/com/yahoo/vespa/configserver/flags/http/FlagsHandlerTest.java41
-rw-r--r--container-core/pom.xml18
-rw-r--r--container-core/src/test/java/com/yahoo/component/ComponentSpecTestCase.java14
-rw-r--r--container-core/src/test/java/com/yahoo/component/chain/dependencies/ordering/ChainBuilderTest.java38
-rw-r--r--container-core/src/test/java/com/yahoo/component/chain/dependencies/ordering/OrderedReadyNodesTest.java16
-rw-r--r--container-core/src/test/java/com/yahoo/component/chain/model/ChainsModelBuilderTest.java14
-rw-r--r--container-core/src/test/java/com/yahoo/component/provider/test/ComponentRegistryTestCase.java19
-rw-r--r--container-core/src/test/java/com/yahoo/component/test/ComponentIdTestCase.java31
-rw-r--r--container-core/src/test/java/com/yahoo/container/core/config/ApplicationBundleLoaderTest.java18
-rw-r--r--container-core/src/test/java/com/yahoo/container/core/config/PlatformBundleLoaderTest.java16
-rw-r--r--container-core/src/test/java/com/yahoo/container/di/ConfigRetrieverTest.java33
-rw-r--r--container-core/src/test/java/com/yahoo/container/di/ContainerTest.java38
-rw-r--r--container-core/src/test/java/com/yahoo/container/di/ContainerTestBase.java17
-rw-r--r--container-core/src/test/java/com/yahoo/container/di/DirConfigSource.java20
-rw-r--r--container-core/src/test/java/com/yahoo/container/di/componentgraph/core/ComponentGraphTest.java130
-rw-r--r--container-core/src/test/java/com/yahoo/container/di/componentgraph/core/FallbackToGuiceInjectorTest.java17
-rw-r--r--container-core/src/test/java/com/yahoo/container/di/componentgraph/core/ReuseComponentsTest.java46
-rw-r--r--container-core/src/test/java/com/yahoo/container/di/componentgraph/cycle/CycleFinderTest.java16
-rw-r--r--container-core/src/test/java/com/yahoo/container/di/componentgraph/cycle/GraphTest.java14
-rw-r--r--container-core/src/test/java/com/yahoo/container/handler/AccessLogRequestHandlerTest.java10
-rw-r--r--container-core/src/test/java/com/yahoo/container/handler/LogHandlerTest.java6
-rw-r--r--container-core/src/test/java/com/yahoo/container/handler/LogReaderTest.java36
-rw-r--r--container-core/src/test/java/com/yahoo/container/handler/VipStatusHandlerTestCase.java14
-rw-r--r--container-core/src/test/java/com/yahoo/container/handler/VipStatusTestCase.java22
-rw-r--r--container-core/src/test/java/com/yahoo/container/handler/metrics/ErrorResponseTest.java8
-rw-r--r--container-core/src/test/java/com/yahoo/container/handler/metrics/MetricsV2HandlerTest.java36
-rw-r--r--container-core/src/test/java/com/yahoo/container/handler/metrics/PrometheusV1HandlerTest.java36
-rw-r--r--container-core/src/test/java/com/yahoo/container/handler/test/MockServiceTest.java25
-rw-r--r--container-core/src/test/java/com/yahoo/container/handler/threadpool/ContainerThreadPoolImplTest.java51
-rw-r--r--container-core/src/test/java/com/yahoo/container/jdisc/ExtendedResponseTestCase.java24
-rw-r--r--container-core/src/test/java/com/yahoo/container/jdisc/HttpRequestTestCase.java35
-rw-r--r--container-core/src/test/java/com/yahoo/container/jdisc/HttpResponseTestCase.java26
-rw-r--r--container-core/src/test/java/com/yahoo/container/jdisc/LoggingRequestHandlerTestCase.java10
-rw-r--r--container-core/src/test/java/com/yahoo/container/jdisc/LoggingTestCase.java17
-rw-r--r--container-core/src/test/java/com/yahoo/container/jdisc/RequestBuilderTestCase.java18
-rw-r--r--container-core/src/test/java/com/yahoo/container/jdisc/ThreadedHttpRequestHandlerTest.java6
-rw-r--r--container-core/src/test/java/com/yahoo/container/jdisc/ThreadedRequestHandlerTestCase.java35
-rw-r--r--container-core/src/test/java/com/yahoo/container/jdisc/state/CoredumpGathererTest.java14
-rw-r--r--container-core/src/test/java/com/yahoo/container/jdisc/state/HostLifeGathererTest.java6
-rw-r--r--container-core/src/test/java/com/yahoo/container/jdisc/state/MetricSnapshotTest.java12
-rw-r--r--container-core/src/test/java/com/yahoo/container/jdisc/state/MetricsPacketsHandlerTest.java36
-rw-r--r--container-core/src/test/java/com/yahoo/container/jdisc/state/StateHandlerTest.java144
-rw-r--r--container-core/src/test/java/com/yahoo/container/jdisc/state/StateHandlerTestBase.java8
-rw-r--r--container-core/src/test/java/com/yahoo/container/logging/CircularArrayAccessLogKeeperTest.java10
-rw-r--r--container-core/src/test/java/com/yahoo/container/logging/JSONLogTestCase.java280
-rw-r--r--container-core/src/test/java/com/yahoo/container/logging/LogFileHandlerTestCase.java114
-rw-r--r--container-core/src/test/java/com/yahoo/container/logging/test/LogFormatterTestCase.java16
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/CookieTestCase.java80
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/HttpHeadersTestCase.java6
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/HttpRequestTestCase.java37
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/HttpResponseTestCase.java24
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/filter/DiscFilterRequestTest.java489
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/filter/DiscFilterResponseTest.java39
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/filter/EmptyRequestFilterTestCase.java6
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/filter/EmptyResponseFilterTestCase.java6
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/filter/JDiscCookieWrapperTest.java19
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/filter/RequestViewImplTest.java8
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/filter/SecurityRequestFilterChainTest.java35
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/filter/SecurityResponseFilterChainTest.java20
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/filter/util/FilterUtilsTest.java8
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/AccessLogRequestLogTest.java18
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/ConnectionThrottlerTest.java10
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/ConnectorFactoryTest.java16
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/ErrorResponseContentCreatorTest.java28
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/ExceptionWrapperTest.java8
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/FilterTestCase.java56
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpRequestFactoryTest.java20
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpResponseStatisticsCollectorTest.java18
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpServerConformanceTest.java12
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpServerTest.java225
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/JDiscHttpServletTest.java20
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/SimpleHttpClient.java9
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/SslHandshakeFailedListenerTest.java6
-rw-r--r--container-core/src/test/java/com/yahoo/jdisc/http/ssl/impl/TlsContextBasedProviderTest.java6
-rw-r--r--container-core/src/test/java/com/yahoo/metrics/simple/BucketTest.java72
-rw-r--r--container-core/src/test/java/com/yahoo/metrics/simple/CounterTest.java23
-rw-r--r--container-core/src/test/java/com/yahoo/metrics/simple/DimensionsCacheTest.java26
-rw-r--r--container-core/src/test/java/com/yahoo/metrics/simple/GaugeTest.java18
-rw-r--r--container-core/src/test/java/com/yahoo/metrics/simple/MetricsTest.java19
-rw-r--r--container-core/src/test/java/com/yahoo/metrics/simple/PointTest.java8
-rw-r--r--container-core/src/test/java/com/yahoo/metrics/simple/jdisc/SnapshotConverterTest.java22
-rw-r--r--container-core/src/test/java/com/yahoo/osgi/provider/model/ComponentModelTest.java19
-rw-r--r--container-core/src/test/java/com/yahoo/processing/ResponseTestCase.java30
-rw-r--r--container-core/src/test/java/com/yahoo/processing/execution/test/AsyncExecutionTestCase.java38
-rw-r--r--container-core/src/test/java/com/yahoo/processing/execution/test/ExecutionContextTestCase.java77
-rw-r--r--container-core/src/test/java/com/yahoo/processing/execution/test/FutureDataTestCase.java143
-rw-r--r--container-core/src/test/java/com/yahoo/processing/execution/test/StreamingTestCase.java48
-rw-r--r--container-core/src/test/java/com/yahoo/processing/handler/ProcessingHandlerTestCase.java295
-rw-r--r--container-core/src/test/java/com/yahoo/processing/processors/MockUserDatabaseClientTest.java17
-rw-r--r--container-core/src/test/java/com/yahoo/processing/rendering/AsynchronousSectionedRendererTest.java140
-rw-r--r--container-core/src/test/java/com/yahoo/processing/request/CompoundNameTestCase.java68
-rw-r--r--container-core/src/test/java/com/yahoo/processing/request/test/ErrorMessageTestCase.java74
-rw-r--r--container-core/src/test/java/com/yahoo/processing/request/test/PropertyMapTestCase.java32
-rw-r--r--container-core/src/test/java/com/yahoo/processing/request/test/RequestTestCase.java86
-rw-r--r--container-core/src/test/java/com/yahoo/processing/test/DocumentationTestCase.java9
-rw-r--r--container-core/src/test/java/com/yahoo/processing/test/ProcessingTestCase.java50
-rw-r--r--container-core/src/test/java/com/yahoo/restapi/PathTest.java26
-rw-r--r--container-dependency-versions/pom.xml1
-rw-r--r--container-disc/pom.xml42
-rw-r--r--container-disc/src/main/java/com/yahoo/container/jdisc/metric/MetricUpdater.java4
-rw-r--r--container-disc/src/test/java/com/yahoo/container/handler/observability/ApplicationStatusHandlerTest.java14
-rw-r--r--container-disc/src/test/java/com/yahoo/container/jdisc/ContainerThreadFactoryTest.java18
-rw-r--r--container-disc/src/test/java/com/yahoo/container/jdisc/DisableOsgiFrameworkTest.java60
-rw-r--r--container-disc/src/test/java/com/yahoo/container/jdisc/FilterBindingsProviderTest.java18
-rw-r--r--container-disc/src/test/java/com/yahoo/container/jdisc/component/DeconstructorTest.java18
-rw-r--r--container-disc/src/test/java/com/yahoo/container/jdisc/metric/ForwardingMetricConsumerTest.java8
-rw-r--r--container-disc/src/test/java/com/yahoo/container/jdisc/metric/GarbageCollectionMetricsTest.java6
-rw-r--r--container-disc/src/test/java/com/yahoo/container/jdisc/metric/MetricConsumerProviderTest.java11
-rw-r--r--container-disc/src/test/java/com/yahoo/container/jdisc/metric/MetricProviderTest.java12
-rw-r--r--container-disc/src/test/java/com/yahoo/container/jdisc/metric/MetricUpdaterTest.java8
-rw-r--r--container-search/pom.xml29
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/cluster/ClusterSearcherTestCase.java37
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/fastsearch/SlimeSummaryTestCase.java38
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/fastsearch/test/DocsumDefinitionTestCase.java9
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/fastsearch/test/FastSearcherTestCase.java83
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/fastsearch/test/PartialFillTestCase.java29
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/hitfield/XmlRendererTestCase.java96
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/hitfield/test/HitFieldTestCase.java14
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/hitfield/test/JSONStringTestCase.java500
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/hitfield/test/TokenFieldIteratorTestCase.java30
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/ItemHelperTestCase.java12
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/ItemLabelTestCase.java12
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/ItemsCommonStuffTestCase.java73
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/TaggableItemsTestCase.java23
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/WordAlternativesItemTestCase.java32
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/parser/UnicodePropertyDumpTestCase.java8
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/parser/test/ExactMatchAndDefaultIndexTestCase.java8
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/parser/test/ParseTestCase.java1191
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/parser/test/ParsingTester.java10
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/parser/test/SubstringTestCase.java12
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/parser/test/TokenizerTestCase.java50
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/parser/test/WashPhrasesTestCase.java22
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/test/DotProductItemTestCase.java13
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/test/IntItemTestCase.java6
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/test/ItemEncodingTestCase.java149
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/test/PhraseItemTestCase.java10
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/test/PredicateQueryItemTestCase.java50
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/test/QueryCanonicalizerTestCase.java85
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/test/QueryLanguageTestCase.java32
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/test/QueryTestCase.java12
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/test/RangeItemTestCase.java6
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/test/SameElementItemTestCase.java30
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/test/SegmentItemTestCase.java9
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/test/WandItemTestCase.java39
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/test/WeightedSetItemTestCase.java23
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/query/textualrepresentation/test/TextualQueryRepresentationTestCase.java10
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/querytransform/test/CJKSearcherTestCase.java16
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/querytransform/test/CollapsePhraseSearcherTestCase.java24
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/querytransform/test/LiteralBoostSearcherTestCase.java42
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/querytransform/test/NoRankingSearcherTestCase.java20
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/querytransform/test/NonPhrasingSearcherTestCase.java64
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/querytransform/test/NormalizingSearcherTestCase.java24
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/querytransform/test/PhraseMatcherTestCase.java289
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/querytransform/test/PhrasingSearcherTestCase.java156
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/querytransform/test/QueryRewriteTestCase.java30
-rwxr-xr-xcontainer-search/src/test/java/com/yahoo/prelude/querytransform/test/RecallSearcherTestCase.java13
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/querytransform/test/StemmingSearcherTestCase.java60
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/searcher/test/BlendingSearcherTestCase.java141
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/searcher/test/FieldCollapsingSearcherTestCase.java108
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/searcher/test/JSONDebugSearcherTestCase.java8
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/searcher/test/JuniperSearcherTestCase.java32
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/searcher/test/MultipleResultsTestCase.java50
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/searcher/test/PosSearcherTestCase.java34
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/searcher/test/QuotingSearcherTestCase.java23
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/searcher/test/ValidatePredicateSearcherTestCase.java12
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/searcher/test/ValidateSortingSearcherTestCase.java15
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/parser/test/SemanticsParserTestCase.java28
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/AlibabaTestCase.java18
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/AnchorTestCase.java38
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/AutomataNotTestCase.java9
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/AutomataTestCase.java69
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/BacktrackingTestCase.java38
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/BlendingTestCase.java10
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/CJKTestCase.java18
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/ComparisonTestCase.java26
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/ComparisonsTestCase.java12
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/ConditionTestCase.java32
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/ConfigurationTestCase.java29
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/DuplicateRuleTestCase.java8
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/Ellipsis2TestCase.java6
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/EllipsisTestCase.java38
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/ExactMatchTestCase.java6
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/ExactMatchTrickTestCase.java12
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/ExpansionTestCase.java12
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/InheritanceTestCase.java61
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/LabelMatchingTestCase.java36
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/MatchAllTestCase.java18
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/MatchOnlyIfNotOnlyTermTestCase.java6
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/MusicTestCase.java4
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/NoStemmingTestCase.java14
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/NotTestCase.java12
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/NumbersTestCase.java16
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/NumericTermsTestCase.java10
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/OrPhraseTestCase.java12
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/Parameter2TestCase.java8
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/ParameterTestCase.java16
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/PhraseMatchTestCase.java13
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/ProductionRuleTestCase.java10
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/RuleBaseAbstractTestCase.java2
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/RuleBaseTester.java2
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/SegmentSubstitutionTestCase.java11
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/SemanticSearcherTestCase.java92
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/StemmingTestCase.java16
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/StopwordTestCase.java12
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/SynonymTestCase.java6
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/UrlTestCase.java6
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/semantics/test/WeightingTestCase.java4
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/test/GetRawWordTestCase.java17
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/test/IndexFactsTestCase.java46
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/test/IntegrationTestCase.java6
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/test/LocationTestCase.java6
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/test/NullSetMemberTestCase.java8
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/test/QueryTestCase.java114
-rw-r--r--container-search/src/test/java/com/yahoo/prelude/test/ResultTestCase.java74
-rw-r--r--container-search/src/test/java/com/yahoo/search/cluster/test/ClusterSearcherTestCase.java20
-rw-r--r--container-search/src/test/java/com/yahoo/search/cluster/test/ClusteredConnectionTestCase.java114
-rw-r--r--container-search/src/test/java/com/yahoo/search/dispatch/DispatcherTest.java43
-rw-r--r--container-search/src/test/java/com/yahoo/search/dispatch/InterleavedSearchInvokerTest.java60
-rw-r--r--container-search/src/test/java/com/yahoo/search/dispatch/LeanHitTest.java21
-rw-r--r--container-search/src/test/java/com/yahoo/search/dispatch/LoadBalancerTest.java26
-rw-r--r--container-search/src/test/java/com/yahoo/search/dispatch/SearchPathTest.java21
-rw-r--r--container-search/src/test/java/com/yahoo/search/dispatch/TopKEstimatorTest.java55
-rw-r--r--container-search/src/test/java/com/yahoo/search/dispatch/rpc/MatchFeatureDataTest.java16
-rw-r--r--container-search/src/test/java/com/yahoo/search/dispatch/rpc/ProtobufSerializationTest.java32
-rw-r--r--container-search/src/test/java/com/yahoo/search/dispatch/rpc/RpcSearchInvokerTest.java13
-rw-r--r--container-search/src/test/java/com/yahoo/search/dispatch/searchcluster/SearchClusterCoverageTest.java32
-rw-r--r--container-search/src/test/java/com/yahoo/search/dispatch/searchcluster/SearchClusterTest.java32
-rw-r--r--container-search/src/test/java/com/yahoo/search/federation/DuplicateSourceTestCase.java14
-rw-r--r--container-search/src/test/java/com/yahoo/search/federation/FederationResultTest.java12
-rw-r--r--container-search/src/test/java/com/yahoo/search/federation/FederationSearcherTest.java41
-rw-r--r--container-search/src/test/java/com/yahoo/search/federation/FederationSearcherTestCase.java30
-rw-r--r--container-search/src/test/java/com/yahoo/search/federation/HitCountTestCase.java12
-rw-r--r--container-search/src/test/java/com/yahoo/search/federation/sourceref/test/SearchChainResolverTestCase.java20
-rw-r--r--container-search/src/test/java/com/yahoo/search/federation/sourceref/test/SourceRefResolverTestCase.java20
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/ContinuationTestCase.java8
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/GroupingQueryParserTestCase.java22
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/GroupingRequestTestCase.java18
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/GroupingValidatorTestCase.java47
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/UniqueGroupingSearcherTestCase.java74
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/request/BucketResolverTestCase.java52
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/request/ExpressionVisitorTestCase.java12
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/request/GroupingOperationTestCase.java14
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/request/MathFunctionsTestCase.java10
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/request/MathResolverTestCase.java38
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/request/RawBufferTestCase.java22
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/request/RequestTestCase.java74
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/request/parser/GroupingParserBenchmarkTest.java8
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/request/parser/GroupingParserTestCase.java380
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/result/FlatteningSearcherTestCase.java60
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/result/GroupIdTestCase.java22
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/result/GroupListTestCase.java8
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/result/GroupTestCase.java8
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/result/HitListTestCase.java8
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/result/HitRendererTestCase.java132
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/vespa/CompositeContinuationTestCase.java44
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/vespa/GroupingExecutorTestCase.java263
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/vespa/GroupingTransformTestCase.java72
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/vespa/HitConverterTestCase.java22
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/vespa/IntegerDecoderTestCase.java9
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/vespa/IntegerEmbedderTestCase.java6
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/vespa/OffsetContinuationTestCase.java26
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/vespa/RequestBuilderTestCase.java486
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/vespa/ResultBuilderTestCase.java898
-rw-r--r--container-search/src/test/java/com/yahoo/search/grouping/vespa/ResultIdTestCase.java22
-rw-r--r--container-search/src/test/java/com/yahoo/search/handler/JSONSearchHandlerTestCase.java160
-rw-r--r--container-search/src/test/java/com/yahoo/search/handler/Json2SinglelevelMapTestCase.java11
-rw-r--r--container-search/src/test/java/com/yahoo/search/handler/SearchHandlerTest.java224
-rw-r--r--container-search/src/test/java/com/yahoo/search/match/test/DocumentDbTest.java11
-rw-r--r--container-search/src/test/java/com/yahoo/search/pagetemplates/config/test/MapPageTemplateXMLReadingTestCase.java12
-rw-r--r--container-search/src/test/java/com/yahoo/search/pagetemplates/config/test/PageTemplateXMLReadingTestCase.java38
-rw-r--r--container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/AnySourceTestCase.java50
-rw-r--r--container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ChoiceOfRenderersTestCase.java36
-rw-r--r--container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ChoiceOfSubsectionsTestCase.java10
-rw-r--r--container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ChoiceOfTwoSourcesTestCase.java32
-rw-r--r--container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ChoicesTestCase.java30
-rw-r--r--container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ExecutionAbstractTestCase.java4
-rw-r--r--container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/MapSectionsToSectionsTestCase.java72
-rw-r--r--container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/MapSourcesToSectionsTestCase.java68
-rw-r--r--container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/PageTestCase.java4
-rw-r--r--container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/PageWithBlendingTestCase.java4
-rw-r--r--container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/PageWithSourceRendererTestCase.java4
-rw-r--r--container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/SourceChoiceTestCase.java8
-rw-r--r--container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/TwoSectionsFourSourcesTestCase.java96
-rw-r--r--container-search/src/test/java/com/yahoo/search/pagetemplates/test/PageTemplateSearcherTestCase.java80
-rw-r--r--container-search/src/test/java/com/yahoo/search/pagetemplates/test/SourceParametersTestCase.java48
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/MatchingTestCase.java13
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/QueryTreeTest.java72
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/RankProfileInputTest.java49
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/SoftTimeoutTestCase.java19
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/SortingTestCase.java17
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/context/test/LoggingTestCase.java40
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/context/test/PropertiesTestCase.java42
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/context/test/TraceTestCase.java48
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/ChainedMapTestCase.java16
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/compiled/BindingTestCase.java8
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/compiled/CompiledQueryProfileRegistryTest.java16
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/config/test/MultiProfileTestCase.java46
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/config/test/QueryProfileConfigurationTestCase.java69
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/config/test/QueryProfileIntegrationTestCase.java54
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/config/test/TypedProfilesConfigurationTestCase.java16
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/config/test/XmlReadingTestCase.java230
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/test/CloningTestCase.java240
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/test/DimensionBindingTestCase.java34
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/test/DumpToolTestCase.java14
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/test/QueryFromProfileTestCase.java14
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileSubstitutionTestCase.java95
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileTestCase.java376
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileVariantsCloneTestCase.java10
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileVariantsTestCase.java1476
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/types/test/FieldTypeTestCase.java16
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/types/test/MandatoryTestCase.java46
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/types/test/NameTestCase.java20
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/types/test/NativePropertiesTestCase.java10
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/types/test/OverrideTestCase.java86
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/types/test/PatchMatchingTestCase.java144
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/types/test/QueryProfileTypeInheritanceTestCase.java41
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/profile/types/test/QueryProfileTypeTestCase.java174
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/properties/test/PropertyMapTestCase.java17
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/properties/test/RequestContextPropertiesTestCase.java26
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/properties/test/SubPropertiesTestCase.java31
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/rewrite/RewriterFeaturesTestCase.java9
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/rewrite/test/GenericExpansionRewriterTestCase.java134
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/rewrite/test/MisspellRewriterTestCase.java100
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/rewrite/test/NameRewriterTestCase.java138
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/rewrite/test/QueryRewriteSearcherTestCase.java72
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/rewrite/test/QueryRewriteSearcherTestUtils.java7
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/rewrite/test/SearchChainDispatcherSearcherTestCase.java98
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/test/ModelTestCase.java58
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/test/ParametersTestCase.java20
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/test/PresentationTestCase.java18
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/test/RankFeaturesTestCase.java12
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/test/RankingTestCase.java26
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/textserialize/item/test/ParseItemTestCase.java66
-rw-r--r--container-search/src/test/java/com/yahoo/search/query/textserialize/serializer/test/SerializeItemTestCase.java30
-rw-r--r--container-search/src/test/java/com/yahoo/search/querytransform/BooleanAttributeParserTest.java12
-rw-r--r--container-search/src/test/java/com/yahoo/search/querytransform/BooleanSearcherTestCase.java22
-rw-r--r--container-search/src/test/java/com/yahoo/search/querytransform/LowercasingTestCase.java27
-rw-r--r--container-search/src/test/java/com/yahoo/search/querytransform/WandSearcherTestCase.java55
-rw-r--r--container-search/src/test/java/com/yahoo/search/querytransform/WeakAndReplacementSearcherTestCase.java18
-rw-r--r--container-search/src/test/java/com/yahoo/search/querytransform/test/NGramSearcherTestCase.java61
-rw-r--r--container-search/src/test/java/com/yahoo/search/querytransform/test/RangeQueryOptimizerTestCase.java62
-rw-r--r--container-search/src/test/java/com/yahoo/search/querytransform/test/SortingDegraderTestCase.java28
-rw-r--r--container-search/src/test/java/com/yahoo/search/rendering/AsyncGroupPopulationTestCase.java8
-rw-r--r--container-search/src/test/java/com/yahoo/search/rendering/JsonRendererTestCase.java337
-rw-r--r--container-search/src/test/java/com/yahoo/search/rendering/SyncDefaultRendererTestCase.java22
-rw-r--r--container-search/src/test/java/com/yahoo/search/rendering/XMLRendererTestCase.java76
-rw-r--r--container-search/src/test/java/com/yahoo/search/result/DefaultErrorHitTestCase.java23
-rw-r--r--container-search/src/test/java/com/yahoo/search/result/FeatureDataTestCase.java24
-rw-r--r--container-search/src/test/java/com/yahoo/search/result/NanNumberTestCase.java15
-rw-r--r--container-search/src/test/java/com/yahoo/search/result/PositionsDataTestCase.java12
-rw-r--r--container-search/src/test/java/com/yahoo/search/result/test/CoverageTestCase.java20
-rw-r--r--container-search/src/test/java/com/yahoo/search/result/test/DeepHitIteratorTestCase.java21
-rw-r--r--container-search/src/test/java/com/yahoo/search/result/test/FillingTestCase.java22
-rw-r--r--container-search/src/test/java/com/yahoo/search/result/test/HitGroupTestCase.java122
-rw-r--r--container-search/src/test/java/com/yahoo/search/schema/SchemaInfoTest.java32
-rw-r--r--container-search/src/test/java/com/yahoo/search/schema/SchemaInfoTester.java2
-rw-r--r--container-search/src/test/java/com/yahoo/search/searchchain/AsyncExecutionOfOneChainTestCase.java12
-rw-r--r--container-search/src/test/java/com/yahoo/search/searchchain/AsyncExecutionTestCase.java51
-rw-r--r--container-search/src/test/java/com/yahoo/search/searchchain/VespaAsyncSearcherTest.java14
-rw-r--r--container-search/src/test/java/com/yahoo/search/searchchain/config/test/DependencyConfigTestCase.java16
-rw-r--r--container-search/src/test/java/com/yahoo/search/searchchain/config/test/SearchChainConfigurerTestCase.java42
-rw-r--r--container-search/src/test/java/com/yahoo/search/searchchain/test/ExecutionTestCase.java53
-rw-r--r--container-search/src/test/java/com/yahoo/search/searchchain/test/FutureDataTestCase.java39
-rw-r--r--container-search/src/test/java/com/yahoo/search/searchchain/test/SearchChainTestCase.java32
-rw-r--r--container-search/src/test/java/com/yahoo/search/searchchain/test/TraceTestCase.java38
-rw-r--r--container-search/src/test/java/com/yahoo/search/searchers/ValidateFuzzySearcherTestCase.java19
-rw-r--r--container-search/src/test/java/com/yahoo/search/searchers/ValidateNearestNeighborTestCase.java30
-rw-r--r--container-search/src/test/java/com/yahoo/search/searchers/test/CacheControlSearcherTestCase.java27
-rw-r--r--container-search/src/test/java/com/yahoo/search/searchers/test/ConnectionControlSearcherTestCase.java17
-rw-r--r--container-search/src/test/java/com/yahoo/search/searchers/test/InputCheckingSearcherTestCase.java35
-rw-r--r--container-search/src/test/java/com/yahoo/search/searchers/test/QueryValidatorTestCase.java8
-rwxr-xr-xcontainer-search/src/test/java/com/yahoo/search/searchers/test/RateLimitingSearcherTestCase.java42
-rw-r--r--container-search/src/test/java/com/yahoo/search/searchers/test/ValidateMatchPhaseSearcherTestCase.java8
-rw-r--r--container-search/src/test/java/com/yahoo/search/statistics/ElapsedTimeTestCase.java50
-rw-r--r--container-search/src/test/java/com/yahoo/search/test/QueryTestCase.java341
-rw-r--r--container-search/src/test/java/com/yahoo/search/test/RequestParameterPreservationTestCase.java16
-rw-r--r--container-search/src/test/java/com/yahoo/search/yql/FieldFilterTestCase.java18
-rw-r--r--container-search/src/test/java/com/yahoo/search/yql/MinimalQueryInserterTestCase.java108
-rw-r--r--container-search/src/test/java/com/yahoo/search/yql/ParameterListParserTestCase.java12
-rw-r--r--container-search/src/test/java/com/yahoo/search/yql/TermListTestCase.java24
-rw-r--r--container-search/src/test/java/com/yahoo/search/yql/UserInputTestCase.java91
-rw-r--r--container-search/src/test/java/com/yahoo/search/yql/VespaSerializerTestCase.java170
-rw-r--r--container-search/src/test/java/com/yahoo/search/yql/YqlFieldAndSourceTestCase.java23
-rw-r--r--container-search/src/test/java/com/yahoo/search/yql/YqlParserTestCase.java566
-rw-r--r--container-search/src/test/java/com/yahoo/select/SelectTestCase.java205
-rw-r--r--container-search/src/test/java/com/yahoo/text/interpretation/test/AnnotationTestCase.java77
-rw-r--r--container-search/src/test/java/com/yahoo/vespa/streamingvisitors/ListMergerTestCase.java28
-rw-r--r--container-search/src/test/java/com/yahoo/vespa/streamingvisitors/MetricsSearcherTestCase.java30
-rw-r--r--container-search/src/test/java/com/yahoo/vespa/streamingvisitors/VdsStreamingSearcherTestCase.java40
-rw-r--r--container-search/src/test/java/com/yahoo/vespa/streamingvisitors/VdsVisitorTestCase.java24
-rw-r--r--container-search/src/test/java/com/yahoo/vespa/streamingvisitors/tracing/MaxSamplesPerPeriodTest.java12
-rw-r--r--container-search/src/test/java/com/yahoo/vespa/streamingvisitors/tracing/ProbabilisticSampleRateTest.java10
-rw-r--r--container-search/src/test/java/com/yahoo/vespa/streamingvisitors/tracing/SamplingTraceExporterTest.java4
-rw-r--r--controller-api/pom.xml16
-rw-r--r--controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/vcmr/VespaChangeRequest.java4
-rw-r--r--controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/identifiers/IdentifierTest.java167
-rw-r--r--controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/integration/deployment/JobTypeTest.java10
-rw-r--r--controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/integration/dns/AliasTargetTest.java8
-rw-r--r--controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/integration/maven/MetadataTest.java6
-rw-r--r--controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/integration/user/RolesTest.java51
-rw-r--r--controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/role/PathGroupTest.java22
-rw-r--r--controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/role/RoleTest.java48
-rw-r--r--controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/systemflags/v1/SystemFlagsDataArchiveTest.java96
-rw-r--r--controller-server/pom.xml32
-rw-r--r--controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentStatus.java4
-rw-r--r--controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/Versions.java2
-rw-r--r--controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/ChangeRequestMaintainer.java1
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/ControllerTest.java457
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/ControllerTester.java5
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/DeploymentQuotaCalculatorTest.java24
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/EndpointTest.java38
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/ApplicationPackageDiffTest.java16
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/ApplicationPackageTest.java38
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/LinesComparatorTest.java6
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/TestPackageTest.java86
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/ZipEntriesTest.java32
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/archive/CuratorArchiveBucketDbTest.java6
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/auditlog/AuditLoggerTest.java20
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/certificate/EndpointCertificatesTest.java40
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/concurrent/OnceTest.java10
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentContext.java46
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentTester.java2
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentTriggerTest.java430
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/InternalStepRunnerTest.java14
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/QuotaUsageTest.java6
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/TestConfigSerializerTest.java32
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/ZipBuilderTest.java6
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/dns/NameServiceQueueTest.java34
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ApplicationOwnershipConfirmerTest.java46
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ArchiveAccessMaintainerTest.java15
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ArchiveUriUpdaterTest.java6
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ArtifactExpirerTest.java6
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ChangeManagementAssessorTest.java48
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ChangeRequestMaintainerTest.java10
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/CloudTrialExpirerTest.java22
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ContactInformationMaintainerTest.java24
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ControllerMaintainerTest.java12
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/CostReportMaintainerTest.java12
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/DeploymentExpirerTest.java15
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/DeploymentIssueReporterTest.java48
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/DeploymentMetricsMaintainerTest.java24
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/DeploymentUpgraderTest.java18
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/EndpointCertificateMaintainerTest.java22
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/HostInfoUpdaterTest.java24
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/JobRunnerTest.java47
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/MeteringMonitorMaintainerTest.java11
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/MetricsReporterTest.java166
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/OsUpgradeSchedulerTest.java51
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/OsUpgraderTest.java96
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/OsVersionStatusUpdaterTest.java16
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/OutstandingChangeDeployerTest.java10
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ReindexingTriggererTest.java50
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ResourceMeterMaintainerTest.java16
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ResourceTagMaintainerTest.java10
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/RetriggerMaintainerTest.java6
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/SystemUpgraderTest.java88
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/TenantRoleMaintainerTest.java12
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/TrafficShareUpdaterTest.java8
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/UpgraderTest.java195
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/UserManagementMaintainerTest.java8
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/VcmrMaintainerTest.java40
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/VersionStatusUpdaterTest.java12
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/notification/NotificationFormatterTest.java16
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/notification/NotificationsDbTest.java30
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/notification/NotifierTest.java14
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ApplicationSerializerTest.java130
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ArchiveBucketsSerializerTest.java6
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/AuditLogSerializerTest.java28
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/BufferedLogStoreTest.java54
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ChangeRequestSerializerTest.java6
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ControllerVersionSerializerTest.java6
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/EndpointCertificateMetadataSerializerTest.java12
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/LogSerializerTest.java6
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/NameServiceQueueSerializerTest.java20
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/NotificationsSerializerTest.java32
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/OsVersionSerializerTest.java6
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/OsVersionStatusSerializerTest.java6
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/OsVersionTargetSerializerTest.java6
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/RoutingPolicySerializerTest.java44
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/RunSerializerTest.java38
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/SupportAccessSerializerTest.java102
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/TenantSerializerTest.java74
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/VersionStatusSerializerTest.java14
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ZoneRoutingPolicySerializerTest.java10
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/proxy/ConfigServerRestExecutorImplTest.java22
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/proxy/ProxyRequestTest.java14
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/proxy/ProxyResponseTest.java10
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/ContainerTester.java8
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/ControllerContainerTest.java8
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/ApplicationApiCloudTest.java52
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/ApplicationApiTest.java1130
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/CliApiHandlerTest.java8
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/JobControllerApiHandlerHelperTest.java18
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/MultipartParserTest.java66
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/athenz/AthenzApiTest.java12
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/billing/BillingApiHandlerTest.java37
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/billing/BillingApiHandlerV2Test.java24
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/changemanagement/ChangeManagementApiHandlerTest.java16
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/configserver/ConfigServerApiHandlerTest.java38
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/controller/ControllerApiTest.java60
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/deployment/BadgeApiTest.java48
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/deployment/DeploymentApiTest.java8
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/filter/AthenzRoleFilterTest.java48
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/filter/ControllerAuthorizationFilterTest.java28
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/filter/LastLoginUpdateFilterTest.java6
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/filter/SignatureFilterTest.java56
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/flags/AuditedFlagsApiTest.java26
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/horizon/HorizonApiTest.java4
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/horizon/TsdbQueryRewriterTest.java6
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/os/OsApiTest.java40
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/routing/RoutingApiTest.java190
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/systemflags/SystemFlagsDeployResultTest.java6
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/systemflags/SystemFlagsDeployerTest.java14
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/UserApiOnPremTest.java4
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/UserApiTest.java150
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/UserFlagsSerializerTest.java36
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/zone/v1/ZoneApiTest.java28
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/zone/v2/ZoneApiTest.java40
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/routing/RoutingPoliciesTest.java235
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/routing/rotation/RotationRepositoryTest.java60
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/tls/SecureContainerTest.java30
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/versions/MavenRepositoryClientTest.java10
-rw-r--r--controller-server/src/test/java/com/yahoo/vespa/hosted/controller/versions/VersionStatusTest.java147
-rw-r--r--flags/pom.xml27
-rw-r--r--flags/src/main/java/com/yahoo/vespa/flags/Flags.java2
-rw-r--r--flags/src/test/java/com/yahoo/vespa/flags/FlagsTest.java32
-rw-r--r--flags/src/test/java/com/yahoo/vespa/flags/OrderedFlagSourceTest.java8
-rw-r--r--flags/src/test/java/com/yahoo/vespa/flags/custom/ClusterCapacityTest.java8
-rw-r--r--flags/src/test/java/com/yahoo/vespa/flags/custom/SharedHostTest.java10
-rw-r--r--flags/src/test/java/com/yahoo/vespa/flags/file/FlagDbFileTest.java13
-rw-r--r--flags/src/test/java/com/yahoo/vespa/flags/json/ConditionTest.java14
-rw-r--r--flags/src/test/java/com/yahoo/vespa/flags/json/FlagDataTest.java10
-rw-r--r--flags/src/test/java/com/yahoo/vespa/flags/json/SerializationTest.java12
-rw-r--r--hosted-zone-api/pom.xml19
-rw-r--r--hosted-zone-api/src/test/java/ai/vespa/cloud/SystemInfoTest.java14
-rw-r--r--http-utils/pom.xml9
-rw-r--r--http-utils/src/test/java/ai/vespa/util/http/hc4/VespaHttpClientBuilderTest.java10
-rw-r--r--http-utils/src/test/java/ai/vespa/util/http/hc4/retry/DelayedConnectionLevelRetryHandlerTest.java16
-rw-r--r--http-utils/src/test/java/ai/vespa/util/http/hc4/retry/DelayedResponseLevelRetryHandlerTest.java20
-rw-r--r--http-utils/src/test/java/ai/vespa/util/http/hc5/HttpToHttpsRoutePlannerTest.java14
-rw-r--r--jdisc-security-filters/pom.xml28
-rw-r--r--jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filter/security/misc/SecurityHeadersResponseFilter.java1
-rw-r--r--jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filter/security/rule/RuleBasedRequestFilter.java3
-rw-r--r--jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filter/security/rule/package-info.java8
-rw-r--r--jdisc-security-filters/src/main/resources/configdefinitions/jdisc.http.filter.security.rule.rule-based-filter.def2
-rw-r--r--jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/athenz/AthenzAuthorizationFilterTest.java34
-rw-r--r--jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/athenz/AthenzPrincipalFilterTest.java16
-rw-r--r--jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/base/JsonSecurityRequestFilterBaseTest.java8
-rw-r--r--jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/cors/CorsPreflightRequestFilterTest.java18
-rw-r--r--jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/cors/CorsResponseFilterTest.java18
-rw-r--r--jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/misc/LocalhostFilterTest.java8
-rw-r--r--jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/misc/VespaTlsFilterTest.java8
-rw-r--r--jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/rule/RuleBasedRequestFilterTest.java8
-rw-r--r--jdisc_core/pom.xml24
-rw-r--r--jdisc_core/src/main/java/com/yahoo/jdisc/core/ApplicationLoader.java1
-rw-r--r--jdisc_core/src/main/java/com/yahoo/jdisc/core/ContainerWatchdog.java90
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/AbstractResourceTestCase.java24
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/ContainerTestCase.java10
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/HeaderFieldsTestCase.java77
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/ProxyRequestHandlerTestCase.java40
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/ReferencedResourceTestCase.java8
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/ReferencesTestCase.java6
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/RequestTestCase.java46
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/ResponseTestCase.java12
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/application/AbstractApplicationTestCase.java24
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/application/ApplicationNotReadyTestCase.java10
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/application/BindingMatchTestCase.java12
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/application/BindingRepositoryTestCase.java28
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/application/BindingSetTestCase.java78
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/application/BundleInstallationExceptionTestCase.java16
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/application/ContainerBuilderTestCase.java26
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/application/ContainerThreadTestCase.java8
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/application/GlobPatternTestCase.java30
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/application/GuiceRepositoryTestCase.java32
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/application/MetricImplTestCase.java14
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/application/OsgiHeaderTestCase.java6
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/application/OsgiRepositoryTestCase.java6
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/application/ResourcePoolTestCase.java32
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/application/ServerRepositoryTestCase.java18
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/application/UriPatternTestCase.java112
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/BindingMatchingTestCase.java4
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/LatencyTestCase.java6
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/ThroughputTestCase.java8
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/UriMatchingTestCase.java4
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/client/AbstractClientApplicationTestCase.java12
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/client/ClientDriverTestCase.java8
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/ActiveContainerTestCase.java23
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationConfigModuleTestCase.java19
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationEnvironmentModuleTestCase.java12
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationLoaderTestCase.java40
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationRestartTestCase.java10
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationShutdownTestCase.java10
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/BundleLocationResolverTestCase.java22
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/ConsoleLogFormatterTestCase.java114
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/ConsoleLogListenerTestCase.java28
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/ConsoleLogManagerTestCase.java16
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerResourceTestCase.java14
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerShutdownTestCase.java78
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerSnapshotTestCase.java24
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerTerminationTestCase.java18
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerWatchdogTest.java6
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/DefaultBindingSelectorTestCase.java10
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/ExportPackagesIT.java24
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/FelixFrameworkTestCase.java10
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/FelixParamsTestCase.java14
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/OsgiLogHandlerTestCase.java47
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/OsgiLogManagerTestCase.java16
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/OsgiLogServiceTestCase.java20
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/ScheduledQueueTestCase.java28
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/SystemTimerTestCase.java8
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/core/TimeoutManagerImplTestCase.java54
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/handler/AbstractContentOutputStreamTestCase.java26
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/handler/AbstractRequestHandlerTestCase.java20
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/handler/BindingNotFoundTestCase.java10
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/handler/BlockingContentWriterTestCase.java22
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/handler/BufferedContentChannelTestCase.java36
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/handler/CallableRequestDispatchTestCase.java8
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/handler/CallableResponseDispatchTestCase.java6
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/handler/ContentInputStreamTestCase.java8
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/handler/FastContentOutputStreamTestCase.java16
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/handler/FastContentWriterTestCase.java48
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/handler/FutureCompletionTestCase.java22
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/handler/FutureConjunctionTestCase.java30
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/handler/FutureResponseTestCase.java20
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/handler/NullContentTestCase.java12
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/handler/ReadableContentChannelTestCase.java54
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/handler/RequestDeniedTestCase.java10
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/handler/RequestDispatchTestCase.java30
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/handler/ResponseDispatchTestCase.java32
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/handler/ThreadedRequestHandlerTestCase.java32
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/handler/UnsafeContentInputStreamTestCase.java44
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/service/AbstractClientProviderTestCase.java8
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/service/AbstractServerProviderTestCase.java10
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/service/BindingSetNotFoundTestCase.java10
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/service/ConnectToHandlerTestCase.java12
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/service/ContainerNotReadyTestCase.java6
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/service/CurrentContainerTestCase.java6
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/service/NoBindingSetSelectedTestCase.java10
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingClientTestCase.java14
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingCompletionHandlerTestCase.java8
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingContentChannelTestCase.java8
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingOsgiFrameworkTestCase.java20
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingRequestHandlerTestCase.java10
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingRequestTestCase.java10
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingResponseHandlerTestCase.java6
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingServerTestCase.java10
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/test/ServerProviderConformanceTestTest.java2
-rw-r--r--jdisc_core/src/test/java/com/yahoo/jdisc/test/TestDriverTestCase.java20
-rw-r--r--messagebus/pom.xml15
-rwxr-xr-xmessagebus/src/test/java/com/yahoo/messagebus/ChokeTestCase.java39
-rwxr-xr-xmessagebus/src/test/java/com/yahoo/messagebus/ConfigAgentTestCase.java16
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/DynamicThrottlePolicyTest.java44
-rwxr-xr-xmessagebus/src/test/java/com/yahoo/messagebus/ErrorTestCase.java11
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/MessageBusTestCase.java34
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/MessengerTestCase.java14
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/ProtocolRepositoryTestCase.java14
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/RateThrottlingTestCase.java10
-rwxr-xr-xmessagebus/src/test/java/com/yahoo/messagebus/RoutableTestCase.java22
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/SendProxyTestCase.java81
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/SequencerTestCase.java10
-rwxr-xr-xmessagebus/src/test/java/com/yahoo/messagebus/SimpleTripTestCase.java22
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/ThrottlerTestCase.java47
-rwxr-xr-xmessagebus/src/test/java/com/yahoo/messagebus/TimeoutTestCase.java24
-rwxr-xr-xmessagebus/src/test/java/com/yahoo/messagebus/TraceTestCase.java89
-rwxr-xr-xmessagebus/src/test/java/com/yahoo/messagebus/TraceTripTestCase.java31
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/network/IdentityTestCase.java10
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/network/NetworkMultiplexerTest.java11
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/network/local/LocalNetworkTest.java34
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/network/rpc/BasicNetworkTestCase.java28
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/network/rpc/LoadBalanceTestCase.java24
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/network/rpc/RPCNetworkTestCase.java10
-rwxr-xr-xmessagebus/src/test/java/com/yahoo/messagebus/network/rpc/SendAdapterTestCase.java29
-rwxr-xr-xmessagebus/src/test/java/com/yahoo/messagebus/network/rpc/ServiceAddressTestCase.java19
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/network/rpc/ServicePoolTestCase.java23
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/network/rpc/SlobrokTestCase.java68
-rwxr-xr-xmessagebus/src/test/java/com/yahoo/messagebus/network/rpc/TargetPoolTestCase.java47
-rwxr-xr-xmessagebus/src/test/java/com/yahoo/messagebus/routing/AdvancedRoutingTestCase.java43
-rwxr-xr-xmessagebus/src/test/java/com/yahoo/messagebus/routing/ResenderTestCase.java82
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/routing/RetryPolicyTestCase.java10
-rwxr-xr-xmessagebus/src/test/java/com/yahoo/messagebus/routing/RouteParserTestCase.java66
-rwxr-xr-xmessagebus/src/test/java/com/yahoo/messagebus/routing/RoutingContextTestCase.java50
-rwxr-xr-xmessagebus/src/test/java/com/yahoo/messagebus/routing/RoutingSpecTestCase.java284
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/routing/RoutingTestCase.java482
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/test/QueueAdapterTestCase.java10
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/test/ReceptorTestCase.java16
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/test/SimpleMessageTestCase.java8
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/test/SimpleProtocolTestCase.java24
-rw-r--r--messagebus/src/test/java/com/yahoo/messagebus/test/SimpleReplyTestCase.java6
-rw-r--r--node-admin/pom.xml24
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/ConfigServerApiImplTest.java49
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/flags/RealFlagRepositoryTest.java8
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/AclTest.java54
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/NodeStateTest.java6
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/RealNodeRepositoryTest.java37
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/bindings/NodeRepositoryNodeTest.java6
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/reports/BaseReportTest.java16
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/orchestrator/OrchestratorImplTest.java167
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/state/HealthResponseTest.java6
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/state/StateImplTest.java8
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/ContainerNameTest.java35
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/ContainerOperationsTest.java16
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/ContainerResourcesTest.java12
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/ContainerStatsCollectorTest.java20
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/image/ContainerImageDownloaderTest.java20
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/image/ContainerImagePrunerTest.java82
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/metrics/MetricsTest.java20
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/ContainerFailTest.java4
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/MultiContainerTest.java4
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/RebootTest.java6
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/RestartTest.java4
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/StorageMaintainerTest.java18
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/acl/AclMaintainerTest.java182
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/acl/FilterTableLineEditorTest.java44
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/acl/NatTableLineEditorTest.java92
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/coredump/CoreCollectorTest.java30
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/coredump/CoredumpHandlerTest.java43
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/disk/CoredumpCleanupRuleTest.java8
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/disk/DiskCleanupTest.java12
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/disk/LinearCleanupRuleTest.java31
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/ArtifactProducersTest.java3
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/sync/SyncFileInfoTest.java12
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/sync/ZstdCompressingInputStreamTest.java12
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/NodeAdminImplTest.java12
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/NodeAdminStateUpdaterTest.java18
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentContextImplTest.java54
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentContextManagerTest.java38
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentImplTest.java72
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/provider/DebugHandlerHelperTest.java6
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/DefaultEnvWriterTest.java20
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/editor/StringEditorTest.java9
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/editor/TextBufferImplTest.java8
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/DiskSizeTest.java6
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/EditorTest.java14
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileAttributesCacheTest.java8
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileContentCacheTest.java8
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileDeleterTest.java8
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileFinderTest.java54
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileSnapshotTest.java15
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileSyncTest.java9
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileWriterTest.java10
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/MakeDirectoryTest.java13
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/StoredBooleanTest.java10
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/TemplateTest.java8
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/UnixPathTest.java52
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/network/IPAddressesTest.java37
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/process/ChildProcess2ImplTest.java26
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/process/CommandLineTest.java57
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/process/ProcessFactoryImplTest.java17
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/systemd/SystemCtlTest.java60
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/systemd/SystemCtlTesterTest.java8
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/yum/YumPackageNameTest.java43
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/yum/YumTest.java114
-rw-r--r--node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/yum/YumTesterTest.java10
-rw-r--r--parent/pom.xml37
-rw-r--r--predicate-search-core/pom.xml21
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/document/predicate/BinaryFormatTest.java28
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/document/predicate/BooleanPredicateTest.java23
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/document/predicate/ConjunctionTest.java53
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/document/predicate/DisjunctionTest.java53
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/document/predicate/FeatureConjunctionTest.java53
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/document/predicate/FeatureRangeTest.java78
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/document/predicate/FeatureSetTest.java73
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/document/predicate/NegationTest.java33
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateHashTest.java8
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateOperatorTest.java6
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateParserTest.java54
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateTest.java62
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateValueTest.java6
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicatesTest.java24
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/document/predicate/RangeEdgePartitionTest.java33
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/document/predicate/RangePartitionTest.java25
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/search/predicate/PredicateQueryParserTest.java22
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/AndOrSimplifierTest.java102
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/BooleanSimplifierTest.java18
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/ComplexNodeTransformerTest.java36
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/NotNodeReordererTest.java22
-rw-r--r--predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/OrSimplifierTest.java16
-rw-r--r--predicate-search/pom.xml15
-rw-r--r--predicate-search/src/test/java/com/yahoo/search/predicate/PredicateIndexBuilderTest.java21
-rw-r--r--predicate-search/src/test/java/com/yahoo/search/predicate/PredicateIndexTest.java18
-rw-r--r--predicate-search/src/test/java/com/yahoo/search/predicate/annotator/PredicateTreeAnalyzerTest.java30
-rw-r--r--predicate-search/src/test/java/com/yahoo/search/predicate/annotator/PredicateTreeAnnotatorTest.java22
-rw-r--r--predicate-search/src/test/java/com/yahoo/search/predicate/index/BoundsPostingListTest.java14
-rw-r--r--predicate-search/src/test/java/com/yahoo/search/predicate/index/CachedPostingListCounterTest.java19
-rw-r--r--predicate-search/src/test/java/com/yahoo/search/predicate/index/IntervalPostingListTest.java10
-rw-r--r--predicate-search/src/test/java/com/yahoo/search/predicate/index/PredicateIntervalStoreTest.java32
-rw-r--r--predicate-search/src/test/java/com/yahoo/search/predicate/index/PredicateRangeTermExpanderTest.java93
-rw-r--r--predicate-search/src/test/java/com/yahoo/search/predicate/index/PredicateSearchTest.java38
-rw-r--r--predicate-search/src/test/java/com/yahoo/search/predicate/index/SimpleIndexTest.java12
-rw-r--r--predicate-search/src/test/java/com/yahoo/search/predicate/index/ZeroConstraintPostingListTest.java10
-rw-r--r--predicate-search/src/test/java/com/yahoo/search/predicate/index/ZstarCompressedPostingListTest.java8
-rw-r--r--predicate-search/src/test/java/com/yahoo/search/predicate/index/conjunction/ConjunctionIdIteratorTest.java10
-rw-r--r--predicate-search/src/test/java/com/yahoo/search/predicate/index/conjunction/ConjunctionIndexTest.java28
-rw-r--r--predicate-search/src/test/java/com/yahoo/search/predicate/optimization/FeatureConjunctionTransformerTest.java22
-rw-r--r--predicate-search/src/test/java/com/yahoo/search/predicate/serialization/PredicateQuerySerializerTest.java18
-rw-r--r--predicate-search/src/test/java/com/yahoo/search/predicate/serialization/SerializationHelperTest.java10
-rw-r--r--predicate-search/src/test/java/com/yahoo/search/predicate/serialization/SerializationTestHelper.java2
-rw-r--r--predicate-search/src/test/java/com/yahoo/search/predicate/utils/PostingListSearchTest.java12
-rw-r--r--predicate-search/src/test/java/com/yahoo/search/predicate/utils/PrimitiveArraySorterTest.java25
-rw-r--r--security-tools/pom.xml13
-rw-r--r--security-tools/src/test/java/com/yahoo/vespa/security/tool/securityenv/MainTest.java24
-rw-r--r--security-utils/pom.xml16
-rw-r--r--security-utils/src/test/java/com/yahoo/security/AutoReloadingX509KeyManagerTest.java17
-rw-r--r--security-utils/src/test/java/com/yahoo/security/KeyStoreBuilderTest.java20
-rw-r--r--security-utils/src/test/java/com/yahoo/security/KeyUtilsTest.java24
-rw-r--r--security-utils/src/test/java/com/yahoo/security/MutableX509KeyManagerTest.java4
-rw-r--r--security-utils/src/test/java/com/yahoo/security/MutableX509TrustManagerTest.java4
-rw-r--r--security-utils/src/test/java/com/yahoo/security/Pkcs10CsrBuilderTest.java6
-rw-r--r--security-utils/src/test/java/com/yahoo/security/Pkcs10CsrTest.java12
-rw-r--r--security-utils/src/test/java/com/yahoo/security/Pkcs10CsrUtilsTest.java8
-rw-r--r--security-utils/src/test/java/com/yahoo/security/SslContextBuilderTest.java26
-rw-r--r--security-utils/src/test/java/com/yahoo/security/X509CertificateBuilderTest.java39
-rw-r--r--security-utils/src/test/java/com/yahoo/security/X509CertificateUtilsTest.java16
-rw-r--r--security-utils/src/test/java/com/yahoo/security/tls/AuthorizedPeersTest.java17
-rw-r--r--security-utils/src/test/java/com/yahoo/security/tls/ConfigFileBasedTlsContextTest.java21
-rw-r--r--security-utils/src/test/java/com/yahoo/security/tls/DefaultTlsContextTest.java4
-rw-r--r--security-utils/src/test/java/com/yahoo/security/tls/HostGlobPatternTest.java20
-rw-r--r--security-utils/src/test/java/com/yahoo/security/tls/PeerAuthorizerTest.java20
-rw-r--r--security-utils/src/test/java/com/yahoo/security/tls/TransportSecurityOptionsJsonSerializerTest.java30
-rw-r--r--security-utils/src/test/java/com/yahoo/security/tls/TransportSecurityOptionsTest.java8
-rw-r--r--standalone-container/pom.xml7
-rw-r--r--testutil/src/main/java/com/yahoo/test/JunitCompat.java65
-rw-r--r--testutil/src/main/java/com/yahoo/test/PartialOrderTester.java9
-rw-r--r--testutil/src/main/java/com/yahoo/test/TotalOrderTester.java9
-rw-r--r--testutil/src/main/java/com/yahoo/test/json/JsonTestHelper.java6
-rw-r--r--vespa-athenz/pom.xml39
-rw-r--r--vespa-athenz/src/test/java/com/yahoo/vespa/athenz/api/AthenzDomainTest.java17
-rw-r--r--vespa-athenz/src/test/java/com/yahoo/vespa/athenz/api/AthenzResourceNameTest.java6
-rw-r--r--vespa-athenz/src/test/java/com/yahoo/vespa/athenz/api/NTokenGeneratorTest.java12
-rw-r--r--vespa-athenz/src/test/java/com/yahoo/vespa/athenz/aws/AwsCredentialsTest.java14
-rw-r--r--vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identity/SiaIdentityProviderTest.java27
-rw-r--r--vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/api/VespaUniqueInstanceIdTest.java6
-rw-r--r--vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/client/AthenzIdentityProviderImplTest.java36
-rw-r--r--vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/client/IdentityDocumentSignerTest.java6
-rw-r--r--vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/client/InstanceCsrGeneratorTest.java6
-rw-r--r--vespa-athenz/src/test/java/com/yahoo/vespa/athenz/utils/AthenzIdentitiesTest.java6
-rw-r--r--vespa-athenz/src/test/java/com/yahoo/vespa/athenz/utils/AthenzIdentityVerifierTest.java8
-rw-r--r--vespa-athenz/src/test/java/com/yahoo/vespa/athenz/utils/SiaUtilsTest.java18
-rw-r--r--vespaclient-java/pom.xml16
-rw-r--r--vespaclient-java/src/test/java/com/yahoo/vespafeeder/BenchmarkProgressPrinterTest.java8
-rw-r--r--vespaclient-java/src/test/java/com/yahoo/vespafeeder/ProgressPrinterTest.java18
-rw-r--r--vespaclient-java/src/test/java/com/yahoo/vespafeeder/VespaFeederTestCase.java62
-rw-r--r--vespaclient-java/src/test/java/com/yahoo/vespaget/CommandLineOptionsTest.java75
-rw-r--r--vespaclient-java/src/test/java/com/yahoo/vespaget/DocumentRetrieverTest.java82
-rw-r--r--vespaclient-java/src/test/java/com/yahoo/vespastat/BucketStatsPrinterTest.java20
-rw-r--r--vespaclient-java/src/test/java/com/yahoo/vespastat/BucketStatsRetrieverTest.java39
-rw-r--r--vespaclient-java/src/test/java/com/yahoo/vespastat/CommandLineOptionsTest.java36
-rw-r--r--vespaclient-java/src/test/java/com/yahoo/vespavisit/StdOutVisitorHandlerTest.java27
-rw-r--r--vespaclient-java/src/test/java/com/yahoo/vespavisit/VdsVisitTargetTestCase.java13
-rw-r--r--vespaclient-java/src/test/java/com/yahoo/vespavisit/VdsVisitTestCase.java71
-rw-r--r--vespajlib/src/main/java/com/yahoo/concurrent/Threads.java30
-rw-r--r--zookeeper-client-common/pom.xml9
-rw-r--r--zookeeper-client-common/src/test/java/com/yahoo/vespa/zookeeper/client/ZkClientConfigBuilderTest.java10
1367 files changed, 28740 insertions, 27537 deletions
diff --git a/README.md b/README.md
index fa4aa5086de..df9e1109a2b 100644
--- a/README.md
+++ b/README.md
@@ -83,10 +83,6 @@ for building Vespa, running unit tests and running system tests:
Use this if you only need to build the Java modules, otherwise follow the complete development guide above.
-### Build RPM packages
-
-See [Building Vespa RPM](docker/README.md#building-vespa-rpm) for details.
-
## License
diff --git a/application-preprocessor/pom.xml b/application-preprocessor/pom.xml
index 2cc75b885a9..aae9f6bb13a 100644
--- a/application-preprocessor/pom.xml
+++ b/application-preprocessor/pom.xml
@@ -19,9 +19,9 @@
<version>${project.version}</version>
</dependency>
<dependency>
- <groupId>com.yahoo.vespa</groupId>
- <artifactId>config-model-api</artifactId>
- <version>${project.version}</version>
+ <groupId>com.yahoo.vespa</groupId>
+ <artifactId>config-model-api</artifactId>
+ <version>${project.version}</version>
</dependency>
<dependency>
<groupId>com.yahoo.vespa</groupId>
@@ -33,10 +33,10 @@
<artifactId>config-model</artifactId>
<version>${project.version}</version>
<exclusions>
- <exclusion>
- <groupId>org.antlr</groupId>
- <artifactId>antlr4-runtime</artifactId>
- </exclusion>
+ <exclusion>
+ <groupId>org.antlr</groupId>
+ <artifactId>antlr4-runtime</artifactId>
+ </exclusion>
</exclusions>
</dependency>
<dependency>
@@ -50,14 +50,19 @@
<version>${project.version}</version>
</dependency>
<dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
</dependency>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
+ </dependency>
</dependencies>
<build>
<plugins>
diff --git a/application-preprocessor/src/test/java/com/yahoo/application/preprocessor/ApplicationPreprocessorTest.java b/application-preprocessor/src/test/java/com/yahoo/application/preprocessor/ApplicationPreprocessorTest.java
index 5039b05b393..0e5d8fb2784 100644
--- a/application-preprocessor/src/test/java/com/yahoo/application/preprocessor/ApplicationPreprocessorTest.java
+++ b/application-preprocessor/src/test/java/com/yahoo/application/preprocessor/ApplicationPreprocessorTest.java
@@ -1,9 +1,8 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.application.preprocessor;
-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.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;
@@ -14,17 +13,26 @@ import java.util.Optional;
public class ApplicationPreprocessorTest {
- @Rule
- public TemporaryFolder outputDir = new TemporaryFolder();
+ @TempDir
+ public File outputDir;
// Basic test just to check that instantiation and run() works. Unit testing is in config-application-package
@Test
- public void basic() throws ParserConfigurationException, TransformerException, SAXException, IOException {
+ void basic() throws ParserConfigurationException, TransformerException, SAXException, IOException {
ApplicationPreprocessor preprocessor = new ApplicationPreprocessor(new File("src/test/resources/simple"),
- Optional.of(outputDir.newFolder()),
- Optional.empty(),
- Optional.empty());
+ Optional.of(newFolder(outputDir, "basic")),
+ Optional.empty(),
+ Optional.empty());
preprocessor.run();
}
+ 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/application/abi-spec.json b/application/abi-spec.json
index 2053eabd9ad..75ae9842982 100644
--- a/application/abi-spec.json
+++ b/application/abi-spec.json
@@ -57,6 +57,7 @@
"public static com.yahoo.application.Application fromApplicationPackage(java.nio.file.Path, com.yahoo.application.Networking)",
"public static com.yahoo.application.Application fromApplicationPackage(java.io.File, com.yahoo.application.Networking)",
"public com.yahoo.application.container.JDisc getJDisc(java.lang.String)",
+ "public com.yahoo.search.query.profile.compiled.CompiledQueryProfileRegistry getCompiledQueryProfileRegistry()",
"public void close()"
],
"fields": [
diff --git a/application/pom.xml b/application/pom.xml
index 51448502d1d..34bf1b56c0d 100644
--- a/application/pom.xml
+++ b/application/pom.xml
@@ -60,11 +60,6 @@
<version>${project.version}</version>
<scope>compile</scope>
</dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
<!-- All dependencies that should be visible in test classpath, but not compile classpath,
for user projects must be added in compile scope here.
@@ -127,6 +122,20 @@
<artifactId>testutil</artifactId>
<version>${project.version}</version>
<scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-core</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-library</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<!-- START JETTY embedded jars -->
@@ -172,6 +181,16 @@
<artifactId>jetty-servlets</artifactId>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
+ </dependency>
<!-- END JETTY embedded jars -->
</dependencies>
diff --git a/application/src/main/java/com/yahoo/application/Application.java b/application/src/main/java/com/yahoo/application/Application.java
index 1b81897b230..5d8123de48f 100644
--- a/application/src/main/java/com/yahoo/application/Application.java
+++ b/application/src/main/java/com/yahoo/application/Application.java
@@ -26,6 +26,8 @@ import com.yahoo.jdisc.handler.RequestHandler;
import com.yahoo.jdisc.service.ClientProvider;
import com.yahoo.jdisc.service.ServerProvider;
import com.yahoo.search.Searcher;
+import com.yahoo.search.query.profile.compiled.CompiledQueryProfileRegistry;
+import com.yahoo.search.query.profile.config.QueryProfileXMLReader;
import com.yahoo.search.rendering.Renderer;
import com.yahoo.text.StringUtilities;
import com.yahoo.text.Utf8;
@@ -71,6 +73,7 @@ public final class Application implements AutoCloseable {
private final List<ContentCluster> contentClusters;
private final Path path;
private final boolean deletePathWhenClosing;
+ private final CompiledQueryProfileRegistry compiledQueryProfileRegistry;
// For internal use only
Application(Path path, Networking networking, boolean deletePathWhenClosing) {
@@ -79,6 +82,7 @@ public final class Application implements AutoCloseable {
this.deletePathWhenClosing = deletePathWhenClosing;
contentClusters = ContentCluster.fromPath(path);
container = JDisc.fromPath(path, networking, createVespaModel().configModelRepo());
+ compiledQueryProfileRegistry = readQueryProfilesFromApplicationPackage(path);
}
@Beta
@@ -123,6 +127,17 @@ public final class Application implements AutoCloseable {
return fromApplicationPackage(file.toPath(), networking);
}
+ private CompiledQueryProfileRegistry readQueryProfilesFromApplicationPackage(Path path) {
+ String queryProfilePath = path + "/search/query-profiles";
+ QueryProfileXMLReader queryProfileXMLReader = new QueryProfileXMLReader();
+
+ File f = new File(queryProfilePath);
+ if(f.exists() && f.isDirectory()) {
+ return queryProfileXMLReader.read(queryProfilePath).compile();
+ }
+ return CompiledQueryProfileRegistry.empty;
+ }
+
private VespaModel createVespaModel() {
try {
List<MlModelImporter> modelImporters = List.of(new VespaImporter(),
@@ -149,6 +164,10 @@ public final class Application implements AutoCloseable {
return container;
}
+ public CompiledQueryProfileRegistry getCompiledQueryProfileRegistry() {
+ return compiledQueryProfileRegistry;
+ }
+
/**
* Shuts down all services.
*/
diff --git a/application/src/test/app-packages/withqueryprofile/schemas/mydoc.sd b/application/src/test/app-packages/withqueryprofile/schemas/mydoc.sd
new file mode 100644
index 00000000000..ca6fa37a8e6
--- /dev/null
+++ b/application/src/test/app-packages/withqueryprofile/schemas/mydoc.sd
@@ -0,0 +1,17 @@
+# Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+search mydoc {
+
+ document mydoc {
+
+ field title type string {
+ indexing: index
+ }
+
+ field substring type string {
+ indexing: index
+ match: gram
+ }
+
+ }
+
+}
diff --git a/application/src/test/app-packages/withqueryprofile/search/query-profiles/default.xml b/application/src/test/app-packages/withqueryprofile/search/query-profiles/default.xml
new file mode 100644
index 00000000000..c9ed6ab3d12
--- /dev/null
+++ b/application/src/test/app-packages/withqueryprofile/search/query-profiles/default.xml
@@ -0,0 +1,3 @@
+<query-profile id="default">
+ <field name="hits">2</field>
+</query-profile>
diff --git a/application/src/test/app-packages/withqueryprofile/services.xml b/application/src/test/app-packages/withqueryprofile/services.xml
new file mode 100644
index 00000000000..028ca561160
--- /dev/null
+++ b/application/src/test/app-packages/withqueryprofile/services.xml
@@ -0,0 +1,29 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<!-- Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. -->
+<services>
+
+ <container version="1.0">
+ <!-- Avoid using DefaultLinguisticsProvider -->
+ <component id="com.yahoo.language.simple.SimpleLinguistics" />
+
+ <search>
+ <chain id="default" inherits="vespa"/>
+ <provider id="bar" type="local" cluster="foo">
+ <searcher id="MockResultSearcher" class="com.yahoo.application.MockResultSearcher"/>
+ </provider>
+ </search>
+
+ <accesslog type="disabled" />
+ </container>
+
+ <content version="1.0" id="foo">
+ <redundancy>2</redundancy>
+ <documents>
+ <document type="mydoc" mode="index"/>
+ </documents>
+ <nodes>
+ <node hostalias="node1" distribution-key="1"/>
+ </nodes>
+ </content>
+
+</services>
diff --git a/application/src/test/java/com/yahoo/application/ApplicationBuilderTest.java b/application/src/test/java/com/yahoo/application/ApplicationBuilderTest.java
index 800c30ac8b8..503f11ca0d7 100644
--- a/application/src/test/java/com/yahoo/application/ApplicationBuilderTest.java
+++ b/application/src/test/java/com/yahoo/application/ApplicationBuilderTest.java
@@ -2,13 +2,12 @@
package com.yahoo.application;
import com.yahoo.io.IOUtils;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.Test;
import java.nio.file.Files;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Tony Vaagenes
@@ -16,55 +15,53 @@ import static org.junit.Assert.assertTrue;
*/
public class ApplicationBuilderTest {
@Test
- public void query_profile_types_can_be_added() throws Exception {
+ void query_profile_types_can_be_added() throws Exception {
withApplicationBuilder(builder -> {
builder.queryProfileType("MyProfileType", "<query-profile-type id=\"MyProfileType\">" + //
- "<field name=\"age\" type=\"integer\" />" + //
- "<field name=\"profession\" type=\"string\" />" + //
- "<field name=\"user\" type=\"query-profile:MyUserProfile\" />" + //
- "</query-profile-type>");
+ "<field name=\"age\" type=\"integer\" />" + //
+ "<field name=\"profession\" type=\"string\" />" + //
+ "<field name=\"user\" type=\"query-profile:MyUserProfile\" />" + //
+ "</query-profile-type>");
assertTrue(Files.exists(builder.getPath().resolve("search/query-profiles/types/MyProfileType.xml")));
});
}
@Test
- public void query_profile_can_be_added() throws Exception {
+ void query_profile_can_be_added() throws Exception {
withApplicationBuilder(builder -> {
builder.queryProfile("MyProfile",
- "<query-profile id=\"MyProfile\">" +
- "<field name=\"message\">Hello world!</field>" +
- "</query-profile>");
+ "<query-profile id=\"MyProfile\">" +
+ "<field name=\"message\">Hello world!</field>" +
+ "</query-profile>");
assertTrue(Files.exists(builder.getPath().resolve("search/query-profiles/MyProfile.xml")));
});
}
@Test
- public void rank_expression_can_be_added() throws Exception {
+ void rank_expression_can_be_added() throws Exception {
withApplicationBuilder(builder -> {
builder.rankExpression("myExpression", "content");
assertTrue(Files.exists(builder.getPath().resolve("schemas/myExpression.expression")));
});
}
- @SuppressWarnings("deprecation")
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
+ // application unreferenced inside try
@Test
- @SuppressWarnings("try") // application unreferenced inside try
- public void builder_cannot_be_reused() throws Exception {
- expectedException.expect(RuntimeException.class);
- expectedException.expectMessage("build method");
+ @SuppressWarnings("try")
+ void builder_cannot_be_reused() throws Exception {
+ Throwable exception = assertThrows(RuntimeException.class, () -> {
- ApplicationBuilder builder = new ApplicationBuilder();
- builder.servicesXml("<container version=\"1.0\" />");
- try (Application application = builder.build()) {
- // do nothing
- }
+ ApplicationBuilder builder = new ApplicationBuilder();
+ builder.servicesXml("<container version=\"1.0\" />");
+ try (Application application = builder.build()) {
+ // do nothing
+ }
- builder.servicesXml(""); // should fail
+ builder.servicesXml(""); // should fail
+ });
+ assertTrue(exception.getMessage().contains("build method")); // should fail
}
private interface TestCase {
diff --git a/application/src/test/java/com/yahoo/application/ApplicationTest.java b/application/src/test/java/com/yahoo/application/ApplicationTest.java
index 6ae49cc4802..5b4a68756f0 100644
--- a/application/src/test/java/com/yahoo/application/ApplicationTest.java
+++ b/application/src/test/java/com/yahoo/application/ApplicationTest.java
@@ -1,9 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.application;
-import com.yahoo.application.container.MockClient;
import com.yahoo.application.container.MockServer;
-import com.yahoo.application.container.docprocs.MockDispatchDocproc;
import com.yahoo.application.container.docprocs.MockDocproc;
import com.yahoo.application.container.handler.Request;
import com.yahoo.application.container.handler.Response;
@@ -12,10 +10,8 @@ import com.yahoo.application.container.renderers.MockRenderer;
import com.yahoo.application.container.searchers.MockSearcher;
import com.yahoo.component.Component;
import com.yahoo.component.ComponentSpecification;
-import com.yahoo.docproc.DocumentProcessor;
+import com.yahoo.container.jdisc.HttpRequest;
import com.yahoo.docproc.Processing;
-import com.yahoo.document.Document;
-import com.yahoo.document.DocumentPut;
import com.yahoo.document.DocumentRemove;
import com.yahoo.document.DocumentType;
import com.yahoo.jdisc.handler.RequestHandler;
@@ -25,7 +21,7 @@ import com.yahoo.search.handler.SearchHandler;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.BufferedReader;
import java.io.File;
@@ -37,10 +33,11 @@ import java.nio.charset.StandardCharsets;
import java.util.Map;
import static com.yahoo.vespa.defaults.Defaults.getDefaults;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author bratseth
@@ -49,31 +46,44 @@ import static org.junit.Assert.fail;
public class ApplicationTest {
@Test
- public void minimal_application_can_be_constructed() {
+ void minimal_application_can_be_constructed() {
try (Application application = Application.fromServicesXml("<container version=\"1.0\"/>", Networking.disable)) {
- Application unused = application;
+ Application unused = application;
}
}
/** Tests that an application with search chains referencing a content cluster can be constructed. */
@Test
- public void container_and_referenced_content() {
+ void container_and_referenced_content() {
try (Application application =
- Application.fromApplicationPackage(new File("src/test/app-packages/withcontent"), Networking.disable)) {
+ Application.fromApplicationPackage(new File("src/test/app-packages/withcontent"), Networking.disable)) {
Result result = application.getJDisc("default").search().process(new ComponentSpecification("default"),
- new Query("?query=substring:foobar&timeout=20000"));
+ new Query("?query=substring:foobar&timeout=20000"));
assertEquals("WEAKAND(100) (AND substring:fo substring:oo substring:ob substring:ba substring:ar)",
- result.hits().get("hasQuery").getQuery().getModel().getQueryTree().toString());
+ result.hits().get("hasQuery").getQuery().getModel().getQueryTree().toString());
}
}
+ @Test
+ void application_with_query_profile_sets_up_query_profile_registry() {
+ try (Application application =
+ Application.fromApplicationPackage(new File("src/test/app-packages/withqueryprofile"), Networking.disable)) {
+ Query query = new Query(HttpRequest.createTestRequest("?query=substring:foobar&timeout=20000", com.yahoo.jdisc.http.HttpRequest.Method.GET), application.getCompiledQueryProfileRegistry().findQueryProfile("default"));
+ Result result = application.getJDisc("default").search().process(new ComponentSpecification("default"), query);
+
+ assertEquals("WEAKAND(100) (AND substring:fo substring:oo substring:ob substring:ba substring:ar)",
+ result.hits().get("hasQuery").getQuery().getModel().getQueryTree().toString());
+ assertEquals("2", application.getCompiledQueryProfileRegistry().findQueryProfile("default").get("hits"));
+ assertEquals("select * from sources * where weakAnd(substring contains \"foobar\") limit 2 timeout 20000000", result.getQuery().yqlRepresentation(true));
+ }
+ }
private void printTrace(Result result) {
for (String message : result.getQuery().getContext(true).getTrace().traceNode().descendants(String.class))
System.out.println(message);
}
@Test
- public void empty_container() throws Exception {
+ void empty_container() throws Exception {
try (ApplicationFacade app = new ApplicationFacade(Application.fromBuilder(new Application.Builder().container("default", new Application.Builder.Container())))) {
try {
app.process(new DocumentRemove(null));
@@ -99,7 +109,7 @@ public class ApplicationTest {
}
@Test
- public void config() throws Exception {
+ void config() throws Exception {
try (
ApplicationFacade app = new ApplicationFacade(Application.fromBuilder(new Application.Builder().container("default", new Application.Builder.Container()
.documentProcessor("docproc", "default", MockDocproc.class)
@@ -113,7 +123,7 @@ public class ApplicationTest {
.mymap("key2", "value2")
.mymapstruct("key1", new MockApplicationConfig.Mymapstruct.Builder().id("mapid1").value("mapvalue1"))
.mymapstruct("key2", new MockApplicationConfig.Mymapstruct.Builder().id("mapid2").value("mapvalue2")))))))
- ) {
+ ) {
MockDocproc docproc = (MockDocproc) app.getComponentById("docproc@default");
assertNotNull(docproc);
@@ -153,11 +163,11 @@ public class ApplicationTest {
}
@Test
- public void handler() throws Exception {
+ void handler() throws Exception {
try (
ApplicationFacade app = new ApplicationFacade(Application.fromBuilder(new Application.Builder().container("default", new Application.Builder.Container()
.handler("http://*/", MockHttpHandler.class))))
- ) {
+ ) {
RequestHandler handler = app.getRequestHandlerById(MockHttpHandler.class.getName());
assertNotNull(handler);
@@ -182,13 +192,13 @@ public class ApplicationTest {
}
}
- @Test
// TODO: Creates access log
- public void renderer() throws Exception {
+ @Test
+ void renderer() throws Exception {
try (
ApplicationFacade app = new ApplicationFacade(Application.fromBuilder(new Application.Builder().container("default", new Application.Builder.Container()
.renderer("mock", MockRenderer.class))))
- ) {
+ ) {
Request request = new Request("http://localhost:" + getDefaults().vespaWebServicePort() + "/search/?format=mock");
Response response = app.handleRequest(request);
@@ -199,36 +209,36 @@ public class ApplicationTest {
}
@Test
- public void search_default() throws Exception {
+ void search_default() throws Exception {
try (
ApplicationFacade app = new ApplicationFacade(Application.fromBuilder(new Application.Builder().container("default", new Application.Builder.Container()
.searcher(MockSearcher.class))))
- ) {
+ ) {
Result result = app.search(new Query("?query=foo&timeout=20000"));
assertEquals(1, result.hits().size());
}
}
@Test
- public void search() throws Exception {
+ void search() throws Exception {
try (
ApplicationFacade app = new ApplicationFacade(Application.fromBuilder(new Application.Builder().container("default", new Application.Builder.Container()
.searcher("foo", MockSearcher.class))))
- ) {
+ ) {
Result result = app.search("foo", new Query("?query=foo&timeout=20000"));
assertEquals(1, result.hits().size());
}
}
@Test
- public void document_type() throws Exception {
+ void document_type() throws Exception {
try (
Application app = Application.fromBuilder(new Application.Builder()
.documentType("test", new String(this.getClass().getResourceAsStream("/test.sd").readAllBytes(), StandardCharsets.UTF_8))
.container("default", new Application.Builder.Container()
- .documentProcessor(MockDocproc.class)
- .config(new MockApplicationConfig(new MockApplicationConfig.Builder().mystruct(new MockApplicationConfig.Mystruct.Builder().id("foo").value("bar"))))))
- ) {
+ .documentProcessor(MockDocproc.class)
+ .config(new MockApplicationConfig(new MockApplicationConfig.Builder().mystruct(new MockApplicationConfig.Mystruct.Builder().id("foo").value("bar"))))))
+ ) {
Map<String, DocumentType> typeMap = app.getJDisc("jdisc").documentProcessing().getDocumentTypes();
assertNotNull(typeMap);
assertTrue(typeMap.containsKey("test"));
@@ -236,7 +246,7 @@ public class ApplicationTest {
}
@Test
- public void get_search_handler() throws Exception {
+ void get_search_handler() throws Exception {
try (ApplicationFacade app = new ApplicationFacade(Application.fromBuilder(new Application.Builder().container("default", new Application.Builder.Container().search(true))))) {
SearchHandler searchHandler = (SearchHandler) app.getRequestHandlerById("com.yahoo.search.handler.SearchHandler");
assertNotNull(searchHandler);
@@ -244,7 +254,7 @@ public class ApplicationTest {
}
@Test
- public void component() throws Exception {
+ void component() throws Exception {
try (ApplicationFacade app = new ApplicationFacade(Application.fromBuilder(new Application.Builder().container("default", new Application.Builder.Container()
.component(MockSearcher.class))))) {
Component c = app.getComponentById(MockSearcher.class.getName());
@@ -253,7 +263,7 @@ public class ApplicationTest {
}
@Test
- public void component_with_config() throws Exception {
+ void component_with_config() throws Exception {
MockApplicationConfig config = new MockApplicationConfig(new MockApplicationConfig.Builder().mystruct(new MockApplicationConfig.Mystruct.Builder().id("foo").value("bar")));
try (ApplicationFacade app = new ApplicationFacade(Application.fromBuilder(new Application.Builder().container("default", new Application.Builder.Container()
.component("foo", MockDocproc.class, config))))) {
@@ -263,7 +273,7 @@ public class ApplicationTest {
}
@Test
- public void file_distribution() {
+ void file_distribution() {
try (Application application = Application.fromApplicationPackage(new File("src/test/app-packages/filedistribution/"), Networking.disable)) {
// Deployment succeeded
Application unused = application;
@@ -271,7 +281,7 @@ public class ApplicationTest {
}
@Test
- public void server() throws Exception {
+ void server() throws Exception {
try (ApplicationFacade app = new ApplicationFacade(Application.fromBuilder(new Application.Builder().container("default", new Application.Builder.Container()
.server("foo", MockServer.class)))
)) {
@@ -282,7 +292,7 @@ public class ApplicationTest {
}
@Test
- public void query_profile() throws Exception {
+ void query_profile() throws Exception {
try (Application app = Application.fromBuilder(new Application.Builder()
.queryProfile("default", "<query-profile id=\"default\">\n" +
"<field name=\"defaultage\">7d</field>\n" +
@@ -293,25 +303,27 @@ public class ApplicationTest {
.rankExpression("re", "commonfirstphase(globalstaticrank)")
.documentType("test", new String(this.getClass().getResourceAsStream("/test.sd").readAllBytes(), StandardCharsets.UTF_8))
.container("default", new Application.Builder.Container()
- .search(true)
+ .search(true)
))) {
Application unused = app;
}
}
- @Test(expected = ConnectException.class)
- public void http_interface_is_off_when_networking_is_disabled() throws Exception {
- int httpPort = getFreePort();
- try (Application application = Application.fromServicesXml(servicesXmlWithServer(httpPort), Networking.disable)) {
- HttpClient client = new org.apache.http.impl.client.DefaultHttpClient();
- int statusCode = client.execute(new HttpGet("http://localhost:" + httpPort)).getStatusLine().getStatusCode();
- fail("Networking.disable is specified, but the network interface is enabled! Got status code: " + statusCode);
- Application unused = application;
- }
+ @Test
+ void http_interface_is_off_when_networking_is_disabled() throws Exception {
+ assertThrows(ConnectException.class, () -> {
+ int httpPort = getFreePort();
+ try (Application application = Application.fromServicesXml(servicesXmlWithServer(httpPort), Networking.disable)) {
+ HttpClient client = new org.apache.http.impl.client.DefaultHttpClient();
+ int statusCode = client.execute(new HttpGet("http://localhost:" + httpPort)).getStatusLine().getStatusCode();
+ fail("Networking.disable is specified, but the network interface is enabled! Got status code: " + statusCode);
+ Application unused = application;
+ }
+ });
}
@Test
- public void http_interface_is_on_when_networking_is_enabled() throws Exception {
+ void http_interface_is_on_when_networking_is_enabled() throws Exception {
int httpPort = getFreePort();
try (Application application = Application.fromServicesXml(servicesXmlWithServer(httpPort), Networking.enable)) {
HttpClient client = new org.apache.http.impl.client.DefaultHttpClient();
@@ -329,7 +341,7 @@ public class ApplicationTest {
}
@Test
- public void athenz_in_deployment_xml() {
+ void athenz_in_deployment_xml() {
try (Application application = Application.fromApplicationPackage(new File("src/test/app-packages/athenz-in-deployment-xml/"), Networking.disable)) {
// Deployment succeeded
Application unused = application;
@@ -351,7 +363,7 @@ public class ApplicationTest {
}
@Test
- public void application_with_access_control_can_be_constructed() {
+ void application_with_access_control_can_be_constructed() {
try (Application application = Application.fromServicesXml(servicesXmlWithAccessControl(), Networking.disable)) {
Application unused = application;
}
diff --git a/application/src/test/java/com/yahoo/application/container/ContainerDocprocTest.java b/application/src/test/java/com/yahoo/application/container/ContainerDocprocTest.java
index 7c786d35fab..7dad204a8ce 100644
--- a/application/src/test/java/com/yahoo/application/container/ContainerDocprocTest.java
+++ b/application/src/test/java/com/yahoo/application/container/ContainerDocprocTest.java
@@ -13,12 +13,13 @@ import com.yahoo.document.Document;
import com.yahoo.document.DocumentPut;
import com.yahoo.document.DocumentType;
import com.yahoo.processing.execution.chain.ChainRegistry;
-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.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Einar M R Rosenvinge
@@ -47,16 +48,16 @@ public class ContainerDocprocTest {
return xml;
}
- @Before
+ @BeforeEach
public void resetContainer() {
Container.resetInstance();
}
@Test
- public void requireThatBasicDocumentProcessingWorks() throws Exception {
+ void requireThatBasicDocumentProcessingWorks() throws Exception {
try (Application app = new ApplicationBuilder()
- .servicesXml(getXML(CHAIN_NAME, Rot13DocumentProcessor.class.getCanonicalName()))
- .documentType("music", DOCUMENT).build()) {
+ .servicesXml(getXML(CHAIN_NAME, Rot13DocumentProcessor.class.getCanonicalName()))
+ .documentType("music", DOCUMENT).build()) {
JDisc container = app.getJDisc("container");
DocumentProcessing docProc = container.documentProcessing();
@@ -84,11 +85,11 @@ public class ContainerDocprocTest {
}
@Test
- public void requireThatLaterDocumentProcessingWorks() throws Exception {
+ void requireThatLaterDocumentProcessingWorks() throws Exception {
try (Application app = new ApplicationBuilder()
- .servicesXml(getXML(CHAIN_NAME, Rot13DocumentProcessor.class.getCanonicalName()))
- .networking(Networking.disable)
- .documentType("music", DOCUMENT).build()) {
+ .servicesXml(getXML(CHAIN_NAME, Rot13DocumentProcessor.class.getCanonicalName()))
+ .networking(Networking.disable)
+ .documentType("music", DOCUMENT).build()) {
JDisc container = app.getJDisc("container");
DocumentProcessing docProc = container.documentProcessing();
DocumentType type = docProc.getDocumentTypes().get("music");
@@ -118,35 +119,44 @@ public class ContainerDocprocTest {
}
}
- @Test(expected = IllegalArgumentException.class)
- public void requireThatUnknownChainThrows() {
- try (JDisc container = JDisc.fromServicesXml(
- getXML("foo", Rot13DocumentProcessor.class.getCanonicalName()),
- Networking.disable)) {
- container.documentProcessing().process(ComponentSpecification.fromString("unknown"),
- new com.yahoo.docproc.Processing());
- }
+ @Test
+ void requireThatUnknownChainThrows() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ try (JDisc container = JDisc.fromServicesXml(
+ getXML("foo", Rot13DocumentProcessor.class.getCanonicalName()),
+ Networking.disable)) {
+ container.documentProcessing().process(ComponentSpecification.fromString("unknown"),
+ new com.yahoo.docproc.Processing());
+ }
+
+ });
}
- @Test(expected = UnsupportedOperationException.class)
- public void requireThatProcessingFails() {
- try (JDisc container = JDisc.fromServicesXml(
- getXML("foo", Rot13DocumentProcessor.class.getCanonicalName()),
- Networking.disable)) {
- container.processing();
- }
+ @Test
+ void requireThatProcessingFails() {
+ assertThrows(UnsupportedOperationException.class, () -> {
+ try (JDisc container = JDisc.fromServicesXml(
+ getXML("foo", Rot13DocumentProcessor.class.getCanonicalName()),
+ Networking.disable)) {
+ container.processing();
+ }
+
+ });
}
- @Test(expected = UnsupportedOperationException.class)
- public void requireThatSearchFails() {
- try (JDisc container = JDisc.fromServicesXml(
- getXML("foo", Rot13DocumentProcessor.class.getCanonicalName()),
- Networking.disable)) {
- container.search();
- }
+ @Test
+ void requireThatSearchFails() {
+ assertThrows(UnsupportedOperationException.class, () -> {
+ try (JDisc container = JDisc.fromServicesXml(
+ getXML("foo", Rot13DocumentProcessor.class.getCanonicalName()),
+ Networking.disable)) {
+ container.search();
+ }
+
+ });
}
diff --git a/application/src/test/java/com/yahoo/application/container/ContainerModelEvaluationTest.java b/application/src/test/java/com/yahoo/application/container/ContainerModelEvaluationTest.java
index f76008b4e02..656660f7580 100644
--- a/application/src/test/java/com/yahoo/application/container/ContainerModelEvaluationTest.java
+++ b/application/src/test/java/com/yahoo/application/container/ContainerModelEvaluationTest.java
@@ -9,16 +9,16 @@ import com.yahoo.application.container.handler.Response;
import com.yahoo.tensor.Tensor;
import com.yahoo.tensor.TensorType;
import com.yahoo.test.json.JsonTestHelper;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.net.URLEncoder;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.StandardCharsets;
-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;
/**
* Verify that we can create a JDisc (and hence Application) instance capable of doing model evaluation
@@ -27,22 +27,23 @@ import static org.junit.Assume.assumeTrue;
*/
public class ContainerModelEvaluationTest {
+ // This should ideally work but may not be worth the effort
@Test
- @Ignore // This should ideally work but may not be worth the effort
- public void testCreateJDiscInstanceWithModelEvaluation() {
+ @Disabled
+ void testCreateJDiscInstanceWithModelEvaluation() {
try (JDisc jdisc =
- JDisc.fromPath(new File("src/test/app-packages/model-evaluation").toPath(),
- Networking.disable)) {
+ JDisc.fromPath(new File("src/test/app-packages/model-evaluation").toPath(),
+ Networking.disable)) {
assertLoadedModels(jdisc);
}
}
@Test
- public void testCreateApplicationInstanceWithModelEvaluation() {
+ void testCreateApplicationInstanceWithModelEvaluation() {
assumeTrue(OnnxEvaluator.isRuntimeAvailable());
try (Application application =
- Application.fromApplicationPackage(new File("src/test/app-packages/model-evaluation"),
- Networking.disable)) {
+ Application.fromApplicationPackage(new File("src/test/app-packages/model-evaluation"),
+ Networking.disable)) {
assertLoadedModels(application.getJDisc("default"));
}
}
diff --git a/application/src/test/java/com/yahoo/application/container/ContainerProcessingTest.java b/application/src/test/java/com/yahoo/application/container/ContainerProcessingTest.java
index e5019d6b54f..b10d62e72e0 100644
--- a/application/src/test/java/com/yahoo/application/container/ContainerProcessingTest.java
+++ b/application/src/test/java/com/yahoo/application/container/ContainerProcessingTest.java
@@ -7,13 +7,14 @@ import com.yahoo.component.ComponentSpecification;
import com.yahoo.container.Container;
import com.yahoo.processing.Request;
import com.yahoo.processing.Response;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
-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.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Einar M R Rosenvinge
@@ -36,13 +37,13 @@ public class ContainerProcessingTest {
return xml;
}
- @Before
+ @BeforeEach
public void resetContainer() {
Container.resetInstance();
}
@Test
- public void requireThatBasicProcessingWorks() {
+ void requireThatBasicProcessingWorks() {
try (JDisc container = getContainerWithRot13()) {
Processing processing = container.processing();
@@ -55,10 +56,10 @@ public class ContainerProcessingTest {
}
@Test
- public void requireThatBasicProcessingDoesNotTruncateBigResponse() {
- int SIZE = 50*1000;
+ void requireThatBasicProcessingDoesNotTruncateBigResponse() {
+ int SIZE = 50 * 1000;
StringBuilder foo = new StringBuilder();
- for (int j = 0 ; j < SIZE ; j++) {
+ for (int j = 0; j < SIZE; j++) {
foo.append('b');
}
@@ -69,13 +70,13 @@ public class ContainerProcessingTest {
container.handleRequest(
new com.yahoo.application.container.handler.Request("http://foo/processing/?chain=foo&title=" + foo.toString()));
- assertEquals(SIZE+26, response.getBody().length);
+ assertEquals(SIZE + 26, response.getBody().length);
}
}
}
@Test
- public void processing_and_rendering_works() throws Exception {
+ void processing_and_rendering_works() throws Exception {
try (JDisc container = getContainerWithRot13()) {
Processing processing = container.processing();
@@ -90,27 +91,36 @@ public class ContainerProcessingTest {
}
}
- @Test(expected = IllegalArgumentException.class)
- public void requireThatUnknownChainThrows() {
- try (JDisc container = getContainerWithRot13()) {
- container.processing().process(ComponentSpecification.fromString("unknown"), new Request());
- }
+ @Test
+ void requireThatUnknownChainThrows() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ try (JDisc container = getContainerWithRot13()) {
+ container.processing().process(ComponentSpecification.fromString("unknown"), new Request());
+ }
+
+ });
}
- @Test(expected = UnsupportedOperationException.class)
- public void requireThatDocprocFails() {
- try (JDisc container = getContainerWithRot13()) {
- container.documentProcessing();
- }
+ @Test
+ void requireThatDocprocFails() {
+ assertThrows(UnsupportedOperationException.class, () -> {
+ try (JDisc container = getContainerWithRot13()) {
+ container.documentProcessing();
+ }
+
+ });
}
- @Test(expected = UnsupportedOperationException.class)
- public void requireThatSearchFails() {
- try (JDisc container = getContainerWithRot13()) {
- container.search();
- }
+ @Test
+ void requireThatSearchFails() {
+ assertThrows(UnsupportedOperationException.class, () -> {
+ try (JDisc container = getContainerWithRot13()) {
+ container.search();
+ }
+
+ });
}
diff --git a/application/src/test/java/com/yahoo/application/container/ContainerRequestTest.java b/application/src/test/java/com/yahoo/application/container/ContainerRequestTest.java
index 911d57a7d6e..24cae99b5ab 100644
--- a/application/src/test/java/com/yahoo/application/container/ContainerRequestTest.java
+++ b/application/src/test/java/com/yahoo/application/container/ContainerRequestTest.java
@@ -11,12 +11,13 @@ import com.yahoo.application.container.handlers.HeaderEchoRequestHandler;
import com.yahoo.application.container.handlers.ThrowingInWriteRequestHandler;
import com.yahoo.application.container.handlers.WriteException;
import com.yahoo.text.Utf8;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.charset.CharacterCodingException;
-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.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Einar M R Rosenvinge
@@ -37,7 +38,7 @@ public class ContainerRequestTest {
}
@Test
- public void requireThatRequestBodyWorks() throws CharacterCodingException {
+ void requireThatRequestBodyWorks() throws CharacterCodingException {
String DATA = "we have no bananas today";
Request req = new Request("http://banana/echo", DATA.getBytes(Utf8.getCharset()));
@@ -50,7 +51,7 @@ public class ContainerRequestTest {
}
@Test
- public void requireThatCustomRequestHeadersWork() {
+ void requireThatCustomRequestHeadersWork() {
Request req = new Request("http://banana/echo");
req.getHeaders().add("X-Foo", "Bar");
@@ -62,26 +63,31 @@ public class ContainerRequestTest {
}
}
- @Test(expected = WriteException.class)
- public void requireThatRequestHandlerThatThrowsInWriteWorks() {
- String DATA = "we have no bananas today";
- Request req = new Request("http://banana/throwwrite", DATA.getBytes(Utf8.getCharset()));
+ @Test
+ void requireThatRequestHandlerThatThrowsInWriteWorks() {
+ assertThrows(WriteException.class, () -> {
+ String DATA = "we have no bananas today";
+ Request req = new Request("http://banana/throwwrite", DATA.getBytes(Utf8.getCharset()));
- try (JDisc container = JDisc.fromServicesXml(getXML(ThrowingInWriteRequestHandler.class.getCanonicalName(), "http://*/throwwrite"), Networking.disable)) {
- Response response = container.handleRequest(req);
- req.toString();
- }
+ try (JDisc container = JDisc.fromServicesXml(getXML(ThrowingInWriteRequestHandler.class.getCanonicalName(), "http://*/throwwrite"), Networking.disable)) {
+ Response response = container.handleRequest(req);
+ req.toString();
+ }
+ });
}
- @Test(expected = DelayedWriteException.class)
- public void requireThatRequestHandlerThatThrowsDelayedInWriteWorks() {
- String DATA = "we have no bananas today";
- Request req = new Request("http://banana/delayedthrowwrite", DATA.getBytes(Utf8.getCharset()));
+ @Test
+ void requireThatRequestHandlerThatThrowsDelayedInWriteWorks() {
+ assertThrows(DelayedWriteException.class, () -> {
+ String DATA = "we have no bananas today";
+ Request req = new Request("http://banana/delayedthrowwrite", DATA.getBytes(Utf8.getCharset()));
- try (JDisc container = JDisc.fromServicesXml(getXML(DelayedThrowingInWriteRequestHandler.class.getCanonicalName(), "http://*/delayedthrowwrite"), Networking.disable)) {
- Response response = container.handleRequest(req);
- req.toString();
- }
+ try (JDisc container = JDisc.fromServicesXml(getXML(DelayedThrowingInWriteRequestHandler.class.getCanonicalName(), "http://*/delayedthrowwrite"), Networking.disable)) {
+ Response response = container.handleRequest(req);
+ req.toString();
+ }
+
+ });
}
diff --git a/application/src/test/java/com/yahoo/application/container/ContainerSchemaTest.java b/application/src/test/java/com/yahoo/application/container/ContainerSchemaTest.java
index e1e520bccc9..465bdef87a3 100644
--- a/application/src/test/java/com/yahoo/application/container/ContainerSchemaTest.java
+++ b/application/src/test/java/com/yahoo/application/container/ContainerSchemaTest.java
@@ -6,12 +6,13 @@ import com.yahoo.application.container.searchers.AddHitSearcher;
import com.yahoo.component.ComponentSpecification;
import com.yahoo.search.Query;
import com.yahoo.search.Result;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
-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.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author gjoranv
@@ -20,7 +21,7 @@ import static org.junit.Assert.assertTrue;
public class ContainerSchemaTest {
@Test
- public void processing_and_rendering_works() throws Exception {
+ void processing_and_rendering_works() throws Exception {
final String searcherId = AddHitSearcher.class.getName();
try (JDisc container = containerWithSearch(searcherId)) {
@@ -32,7 +33,7 @@ public class ContainerSchemaTest {
}
@Test
- public void searching_works() {
+ void searching_works() {
final String searcherId = AddHitSearcher.class.getName();
try (JDisc container = containerWithSearch(searcherId)) {
@@ -54,11 +55,14 @@ public class ContainerSchemaTest {
"</container>", Networking.disable);
}
- @Test(expected = UnsupportedOperationException.class)
- public void retrieving_search_from_container_without_search_is_illegal() {
- try (JDisc container = JDisc.fromServicesXml("<container version=\"1.0\" />", Networking.disable)) {
- container.search(); // throws
- }
+ @Test
+ void retrieving_search_from_container_without_search_is_illegal() {
+ assertThrows(UnsupportedOperationException.class, () -> {
+ try (JDisc container = JDisc.fromServicesXml("<container version=\"1.0\" />", Networking.disable)) {
+ container.search(); // throws
+ }
+
+ });
}
}
diff --git a/application/src/test/java/com/yahoo/application/container/ContainerTest.java b/application/src/test/java/com/yahoo/application/container/ContainerTest.java
index fda8e0c597a..31e0b71d186 100644
--- a/application/src/test/java/com/yahoo/application/container/ContainerTest.java
+++ b/application/src/test/java/com/yahoo/application/container/ContainerTest.java
@@ -10,17 +10,17 @@ import com.yahoo.application.container.handlers.TestHandler;
import com.yahoo.component.ComponentSpecification;
import com.yahoo.search.Query;
import com.yahoo.search.Result;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
import java.nio.charset.CharacterCodingException;
import java.nio.file.FileSystems;
import static com.yahoo.application.container.JDisc.fromServicesXml;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Tony Vaagenes
@@ -30,7 +30,7 @@ import static org.junit.Assert.fail;
public class ContainerTest {
@Test
- public void container_can_be_used_as_top_level_element() {
+ void container_can_be_used_as_top_level_element() {
try (JDisc container = fromServicesXml("<container version=\"1.0\">" + //
"<search />" + //
"</container>", Networking.disable)) {
@@ -39,7 +39,7 @@ public class ContainerTest {
}
@Test
- public void container_id_can_be_set() {
+ void container_id_can_be_set() {
try (JDisc container = fromServicesXml("<container version=\"1.0\" id=\"my-service-id\">" + //
"<search />" + //
"</container>", Networking.disable)) {
@@ -48,7 +48,7 @@ public class ContainerTest {
}
@Test
- public void container_can_be_embedded_in_services_tag() {
+ void container_can_be_embedded_in_services_tag() {
try (JDisc container = fromServicesXml("<services>" + //
"<container version=\"1.0\" id=\"my-service-id\">" + //
"<search />" + //
@@ -58,9 +58,10 @@ public class ContainerTest {
}
}
+ // container is unused inside the try block
@Test
- @SuppressWarnings("try") // container is unused inside the try block
- public void multiple_container_elements_gives_exception() {
+ @SuppressWarnings("try")
+ void multiple_container_elements_gives_exception() {
try (JDisc container = fromServicesXml("<services>" + //
"<container version=\"1.0\" id=\"id1\" />" + //
"<container version=\"1.0\" />" + //
@@ -72,7 +73,7 @@ public class ContainerTest {
}
@Test
- public void handleRequest_yields_response_from_correct_request_handler() {
+ void handleRequest_yields_response_from_correct_request_handler() {
final String handlerClass = TestHandler.class.getName();
try (JDisc container = fromServicesXml("<container version=\"1.0\">" + //
"<handler id=\"test-handler\" class=\"" + handlerClass + "\">" + //
@@ -89,7 +90,7 @@ public class ContainerTest {
}
@Test
- public void load_searcher_from_bundle() {
+ void load_searcher_from_bundle() {
try (JDisc container = JDisc.fromPath(FileSystems.getDefault().getPath("src/test/app-packages/searcher-app"),
Networking.disable)) {
Result result = container.search().process(ComponentSpecification.fromString("default"),
@@ -99,7 +100,7 @@ public class ContainerTest {
}
@Test
- public void document_types_can_be_accessed() throws Exception {
+ void document_types_can_be_accessed() throws Exception {
try (Application application = new ApplicationBuilder().documentType("example", EXAMPLE_DOCUMENT)
.servicesXml(CONTAINER_WITH_DOCUMENT_PROCESSING).build()) {
JDisc container = application.getJDisc("container");
@@ -109,7 +110,7 @@ public class ContainerTest {
}
@Test
- public void annotation_types_can_be_accessed() throws Exception {
+ void annotation_types_can_be_accessed() throws Exception {
try (Application application = new ApplicationBuilder().documentType("example", "search example {\n" + //
" " + EXAMPLE_DOCUMENT + "\n" + //
" annotation exampleAnnotation {}\n" + //
@@ -121,9 +122,9 @@ public class ContainerTest {
}
}
- @Ignore // Enable this when static state has been removed.
+ @Disabled // Enable this when static state has been removed.
@Test
- public void multiple_containers_can_be_run_in_parallel() throws Exception {
+ void multiple_containers_can_be_run_in_parallel() throws Exception {
try (JDisc jdisc1 = jdiscWithHttp(); JDisc jdisc2 = jdiscWithHttp()) {
sendRequest(jdisc1);
sendRequest(jdisc2);
diff --git a/application/src/test/java/com/yahoo/application/container/handler/HeadersTestCase.java b/application/src/test/java/com/yahoo/application/container/handler/HeadersTestCase.java
index d88d69f247e..19d5176c108 100644
--- a/application/src/test/java/com/yahoo/application/container/handler/HeadersTestCase.java
+++ b/application/src/test/java/com/yahoo/application/container/handler/HeadersTestCase.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.application.container.handler;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collection;
@@ -12,12 +12,13 @@ import java.util.List;
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.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.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -27,7 +28,7 @@ import static org.junit.Assert.fail;
public class HeadersTestCase {
@Test
- public void requireThatSizeWorksAsExpected() {
+ void requireThatSizeWorksAsExpected() {
Headers headers = new Headers();
assertEquals(0, headers.size());
headers.add("foo", "bar");
@@ -43,7 +44,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatIsEmptyWorksAsExpected() {
+ void requireThatIsEmptyWorksAsExpected() {
Headers headers = new Headers();
assertTrue(headers.isEmpty());
headers.add("foo", "bar");
@@ -53,7 +54,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatContainsKeyWorksAsExpected() {
+ void requireThatContainsKeyWorksAsExpected() {
Headers headers = new Headers();
assertFalse(headers.containsKey("foo"));
assertFalse(headers.containsKey("FOO"));
@@ -63,7 +64,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatContainsValueWorksAsExpected() {
+ void requireThatContainsValueWorksAsExpected() {
Headers headers = new Headers();
assertFalse(headers.containsValue(Arrays.asList("bar")));
headers.add("foo", "bar");
@@ -71,7 +72,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatContainsWorksAsExpected() {
+ void requireThatContainsWorksAsExpected() {
Headers headers = new Headers();
assertFalse(headers.contains("foo", "bar"));
assertFalse(headers.contains("FOO", "bar"));
@@ -85,7 +86,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatContainsIgnoreCaseWorksAsExpected() {
+ void requireThatContainsIgnoreCaseWorksAsExpected() {
Headers headers = new Headers();
assertFalse(headers.containsIgnoreCase("foo", "bar"));
assertFalse(headers.containsIgnoreCase("FOO", "bar"));
@@ -99,7 +100,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatAddStringWorksAsExpected() {
+ void requireThatAddStringWorksAsExpected() {
Headers headers = new Headers();
assertNull(headers.get("foo"));
headers.add("foo", "bar");
@@ -109,7 +110,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatAddListWorksAsExpected() {
+ void requireThatAddListWorksAsExpected() {
Headers headers = new Headers();
assertNull(headers.get("foo"));
headers.add("foo", Arrays.asList("bar"));
@@ -119,7 +120,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatAddAllWorksAsExpected() {
+ void requireThatAddAllWorksAsExpected() {
Headers headers = new Headers();
headers.add("foo", "bar");
headers.add("bar", "baz");
@@ -136,7 +137,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatPutStringWorksAsExpected() {
+ void requireThatPutStringWorksAsExpected() {
Headers headers = new Headers();
assertNull(headers.get("foo"));
headers.put("foo", "bar");
@@ -146,7 +147,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatPutListWorksAsExpected() {
+ void requireThatPutListWorksAsExpected() {
Headers headers = new Headers();
assertNull(headers.get("foo"));
headers.put("foo", Arrays.asList("bar"));
@@ -156,7 +157,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatPutAllWorksAsExpected() {
+ void requireThatPutAllWorksAsExpected() {
Headers headers = new Headers();
headers.add("foo", "bar");
headers.add("bar", "baz");
@@ -173,7 +174,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatRemoveWorksAsExpected() {
+ void requireThatRemoveWorksAsExpected() {
Headers headers = new Headers();
headers.put("foo", Arrays.asList("bar", "baz"));
assertEquals(Arrays.asList("bar", "baz"), headers.get("foo"));
@@ -183,7 +184,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatRemoveStringWorksAsExpected() {
+ void requireThatRemoveStringWorksAsExpected() {
Headers headers = new Headers();
headers.put("foo", Arrays.asList("bar", "baz"));
assertEquals(Arrays.asList("bar", "baz"), headers.get("foo"));
@@ -196,7 +197,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatClearWorksAsExpected() {
+ void requireThatClearWorksAsExpected() {
Headers headers = new Headers();
headers.add("foo", "bar");
headers.add("bar", "baz");
@@ -208,7 +209,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatGetWorksAsExpected() {
+ void requireThatGetWorksAsExpected() {
Headers headers = new Headers();
assertNull(headers.get("foo"));
headers.add("foo", "bar");
@@ -216,7 +217,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatGetFirstWorksAsExpected() {
+ void requireThatGetFirstWorksAsExpected() {
Headers headers = new Headers();
assertNull(headers.getFirst("foo"));
headers.add("foo", Arrays.asList("bar", "baz"));
@@ -224,7 +225,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatIsTrueWorksAsExpected() {
+ void requireThatIsTrueWorksAsExpected() {
Headers headers = new Headers();
assertFalse(headers.isTrue("foo"));
headers.put("foo", Arrays.asList("true"));
@@ -242,7 +243,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatKeySetWorksAsExpected() {
+ void requireThatKeySetWorksAsExpected() {
Headers headers = new Headers();
assertEquals(Collections.<Set<String>>emptySet(), headers.keySet());
headers.add("foo", "bar");
@@ -252,7 +253,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatValuesWorksAsExpected() {
+ void requireThatValuesWorksAsExpected() {
Headers headers = new Headers();
assertTrue(headers.values().isEmpty());
headers.add("foo", "bar");
@@ -268,7 +269,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatEntrySetWorksAsExpected() {
+ void requireThatEntrySetWorksAsExpected() {
Headers headers = new Headers();
assertEquals(Collections.emptySet(), headers.entrySet());
headers.put("foo", Arrays.asList("bar", "baz"));
@@ -282,7 +283,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatEntriesWorksAsExpected() {
+ void requireThatEntriesWorksAsExpected() {
Headers headers = new Headers();
assertEquals(Collections.emptyList(), headers.entries());
headers.put("foo", Arrays.asList("bar", "baz"));
@@ -301,7 +302,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatEntryIsUnmodifiable() {
+ void requireThatEntryIsUnmodifiable() {
Headers headers = new Headers();
headers.put("foo", "bar");
Map.Entry<String, String> entry = headers.entries().get(0);
@@ -314,7 +315,7 @@ public class HeadersTestCase {
}
@Test
- public void requireThatEntriesAreUnmodifiable() {
+ void requireThatEntriesAreUnmodifiable() {
Headers headers = new Headers();
headers.put("foo", "bar");
List<Map.Entry<String, String>> entries = headers.entries();
@@ -333,25 +334,25 @@ public class HeadersTestCase {
}
@Test
- public void requireThatEqualsWorksAsExpected() {
+ void requireThatEqualsWorksAsExpected() {
Headers lhs = new Headers();
Headers rhs = new Headers();
- assertTrue(lhs.equals(rhs));
+ assertEquals(lhs, rhs);
lhs.add("foo", "bar");
- assertFalse(lhs.equals(rhs));
+ assertNotEquals(lhs, rhs);
rhs.add("foo", "bar");
- assertTrue(lhs.equals(rhs));
+ assertEquals(lhs, rhs);
}
@Test
- public void requireThatHashCodeWorksAsExpected() {
+ void requireThatHashCodeWorksAsExpected() {
Headers lhs = new Headers();
Headers rhs = new Headers();
- assertTrue(lhs.hashCode() == rhs.hashCode());
+ assertEquals(lhs.hashCode(), rhs.hashCode());
lhs.add("foo", "bar");
assertTrue(lhs.hashCode() != rhs.hashCode());
rhs.add("foo", "bar");
- assertTrue(lhs.hashCode() == rhs.hashCode());
+ assertEquals(lhs.hashCode(), rhs.hashCode());
}
private static class MyEntry implements Map.Entry<String, String> {
diff --git a/application/src/test/java/com/yahoo/application/container/handler/ResponseTestCase.java b/application/src/test/java/com/yahoo/application/container/handler/ResponseTestCase.java
index edd2acb630d..b0971c141d6 100644
--- a/application/src/test/java/com/yahoo/application/container/handler/ResponseTestCase.java
+++ b/application/src/test/java/com/yahoo/application/container/handler/ResponseTestCase.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.application.container.handler;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* @author Einar M R Rosenvinge
@@ -12,7 +12,7 @@ import static org.junit.Assert.assertNotNull;
public class ResponseTestCase {
@Test
- public void requireThatCharsetParsingWorks() {
+ void requireThatCharsetParsingWorks() {
assertEquals("utf-8", Response.charset("text/foobar").toString().toLowerCase());
assertEquals("utf-8", Response.charset("adsf").toString().toLowerCase());
assertEquals("utf-8", Response.charset("").toString().toLowerCase());
@@ -26,7 +26,7 @@ public class ResponseTestCase {
}
@Test
- public void testDefaultResponseBody() {
+ void testDefaultResponseBody() {
Response res1 = new Response();
Response res2 = new Response(new byte[0]);
diff --git a/athenz-identity-provider-service/pom.xml b/athenz-identity-provider-service/pom.xml
index d5e6b85f571..f4daa43b8e3 100644
--- a/athenz-identity-provider-service/pom.xml
+++ b/athenz-identity-provider-service/pom.xml
@@ -93,14 +93,19 @@
<scope>test</scope>
</dependency>
<dependency>
- <groupId>com.yahoo.vespa</groupId>
- <artifactId>orchestrator</artifactId>
- <version>${project.version}</version>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.yahoo.vespa</groupId>
+ <artifactId>orchestrator</artifactId>
+ <version>${project.version}</version>
<scope>test</scope>
</dependency>
<dependency>
@@ -113,12 +118,32 @@
<artifactId>application</artifactId>
<version>${project.version}</version>
<scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>com.yahoo.vespa</groupId>
<artifactId>testutil</artifactId>
<version>${project.version}</version>
<scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-core</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-library</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>com.yahoo.vespa</groupId>
diff --git a/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/athenz/instanceproviderservice/IdentityDocumentGeneratorTest.java b/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/athenz/instanceproviderservice/IdentityDocumentGeneratorTest.java
index 508124935c1..9205baff0fc 100644
--- a/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/athenz/instanceproviderservice/IdentityDocumentGeneratorTest.java
+++ b/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/athenz/instanceproviderservice/IdentityDocumentGeneratorTest.java
@@ -25,14 +25,14 @@ import com.yahoo.vespa.hosted.provision.node.Generation;
import com.yahoo.vespa.hosted.provision.node.IP;
import com.yahoo.vespa.hosted.provision.node.Nodes;
import com.yahoo.vespa.hosted.provision.testutils.MockNodeFlavors;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Optional;
import java.util.Set;
import static com.yahoo.vespa.hosted.athenz.instanceproviderservice.TestUtils.getAthenzProviderConfig;
-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;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -45,27 +45,27 @@ public class IdentityDocumentGeneratorTest {
private static final Zone ZONE = new Zone(SystemName.cd, Environment.dev, RegionName.from("us-north-1"));
@Test
- public void generates_valid_identity_document() {
+ void generates_valid_identity_document() {
String parentHostname = "docker-host";
String containerHostname = "docker-container";
ApplicationId appid = ApplicationId.from(
TenantName.from("tenant"), ApplicationName.from("application"), InstanceName.from("default"));
Allocation allocation = new Allocation(appid,
- ClusterMembership.from("container/default/0/0", Version.fromString("1.2.3"), Optional.empty()),
- new NodeResources(1, 1, 1, 1),
- Generation.initial(),
- false);
+ ClusterMembership.from("container/default/0/0", Version.fromString("1.2.3"), Optional.empty()),
+ new NodeResources(1, 1, 1, 1),
+ Generation.initial(),
+ false);
Node parentNode = Node.create("ostkid",
- IP.Config.ofEmptyPool(Set.of("127.0.0.1")),
- parentHostname,
- new MockNodeFlavors().getFlavorOrThrow("default"),
- NodeType.host).build();
+ IP.Config.ofEmptyPool(Set.of("127.0.0.1")),
+ parentHostname,
+ new MockNodeFlavors().getFlavorOrThrow("default"),
+ NodeType.host).build();
Node containerNode = Node.reserve(Set.of("::1"),
- containerHostname,
- parentHostname,
- new MockNodeFlavors().getFlavorOrThrow("default").resources(),
- NodeType.tenant)
+ containerHostname,
+ parentHostname,
+ new MockNodeFlavors().getFlavorOrThrow("default").resources(),
+ NodeType.tenant)
.allocation(allocation).build();
NodeRepository nodeRepository = mock(NodeRepository.class);
Nodes nodes = mock(Nodes.class);
diff --git a/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/athenz/instanceproviderservice/InstanceValidatorTest.java b/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/athenz/instanceproviderservice/InstanceValidatorTest.java
index 6dc2e58059f..9a91d7372da 100644
--- a/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/athenz/instanceproviderservice/InstanceValidatorTest.java
+++ b/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/athenz/instanceproviderservice/InstanceValidatorTest.java
@@ -25,7 +25,7 @@ import com.yahoo.vespa.hosted.provision.NodeRepository;
import com.yahoo.vespa.hosted.provision.node.IP;
import com.yahoo.vespa.hosted.provision.node.Nodes;
import com.yahoo.vespa.hosted.provision.testutils.MockNodeFlavors;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.ArrayList;
@@ -42,8 +42,8 @@ import java.util.stream.Stream;
import static com.yahoo.vespa.hosted.athenz.instanceproviderservice.InstanceValidator.SERVICE_PROPERTIES_DOMAIN_KEY;
import static com.yahoo.vespa.hosted.athenz.instanceproviderservice.InstanceValidator.SERVICE_PROPERTIES_SERVICE_KEY;
-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;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -62,14 +62,14 @@ public class InstanceValidatorTest {
private final AthenzService vespaTenantDomain = new AthenzService("vespa.vespa.tenant");
@Test
- public void application_does_not_exist() {
+ void application_does_not_exist() {
SuperModelProvider superModelProvider = mockSuperModelProvider();
InstanceValidator instanceValidator = new InstanceValidator(null, superModelProvider, null, null, vespaTenantDomain);
assertFalse(instanceValidator.isValidInstance(createRegisterInstanceConfirmation(applicationId, domain, service)));
}
@Test
- public void application_does_not_have_domain_set() {
+ void application_does_not_have_domain_set() {
SuperModelProvider superModelProvider = mockSuperModelProvider(
mockApplicationInfo(applicationId, 5, Collections.emptyList()));
InstanceValidator instanceValidator = new InstanceValidator(null, superModelProvider, null, new IdentityDocumentSigner(), vespaTenantDomain);
@@ -78,9 +78,9 @@ public class InstanceValidatorTest {
}
@Test
- public void application_has_wrong_domain() {
+ void application_has_wrong_domain() {
ServiceInfo serviceInfo = new ServiceInfo("serviceName", "type", Collections.emptyList(),
- Collections.singletonMap(SERVICE_PROPERTIES_DOMAIN_KEY, "not-domain"), "confId", "hostName");
+ Collections.singletonMap(SERVICE_PROPERTIES_DOMAIN_KEY, "not-domain"), "confId", "hostName");
SuperModelProvider superModelProvider = mockSuperModelProvider(
mockApplicationInfo(applicationId, 5, Collections.singletonList(serviceInfo)));
@@ -90,13 +90,13 @@ public class InstanceValidatorTest {
}
@Test
- public void application_has_same_domain_and_service() {
+ void application_has_same_domain_and_service() {
Map<String, String> properties = new HashMap<>();
properties.put(SERVICE_PROPERTIES_DOMAIN_KEY, domain);
properties.put(SERVICE_PROPERTIES_SERVICE_KEY, service);
ServiceInfo serviceInfo = new ServiceInfo("serviceName", "type", Collections.emptyList(),
- properties, "confId", "hostName");
+ properties, "confId", "hostName");
SuperModelProvider superModelProvider = mockSuperModelProvider(
mockApplicationInfo(applicationId, 5, Collections.singletonList(serviceInfo)));
@@ -108,7 +108,7 @@ public class InstanceValidatorTest {
}
@Test
- public void rejects_invalid_provider_unique_id_in_csr() {
+ void rejects_invalid_provider_unique_id_in_csr() {
SuperModelProvider superModelProvider = mockSuperModelProvider();
InstanceValidator instanceValidator = new InstanceValidator(null, superModelProvider, null, null, vespaTenantDomain);
InstanceConfirmation instanceConfirmation = createRegisterInstanceConfirmation(applicationId, domain, service);
@@ -118,7 +118,7 @@ public class InstanceValidatorTest {
}
@Test
- public void rejects_unknown_ips_in_csr() {
+ void rejects_unknown_ips_in_csr() {
NodeRepository nodeRepository = mockNodeRepo();
InstanceValidator instanceValidator = new InstanceValidator(null, mockSuperModelProvider(), nodeRepository, null, vespaTenantDomain);
InstanceConfirmation instanceConfirmation = createRegisterInstanceConfirmation(applicationId, domain, service);
@@ -134,7 +134,7 @@ public class InstanceValidatorTest {
}
@Test
- public void accepts_valid_refresh_requests() {
+ void accepts_valid_refresh_requests() {
NodeRepository nodeRepository = mock(NodeRepository.class);
Nodes nodes = mock(Nodes.class);
when(nodeRepository.nodes()).thenReturn(nodes);
@@ -151,7 +151,7 @@ public class InstanceValidatorTest {
}
@Test
- public void rejects_refresh_on_ip_mismatch() {
+ void rejects_refresh_on_ip_mismatch() {
NodeRepository nodeRepository = mockNodeRepo();
InstanceValidator instanceValidator = new InstanceValidator(null, null, nodeRepository, new IdentityDocumentSigner(), vespaTenantDomain);
@@ -169,7 +169,7 @@ public class InstanceValidatorTest {
}
@Test
- public void rejects_refresh_when_node_is_not_allocated() {
+ void rejects_refresh_when_node_is_not_allocated() {
NodeRepository nodeRepository = mock(NodeRepository.class);
Nodes nodes = mock(Nodes.class);
when(nodeRepository.nodes()).thenReturn(nodes);
diff --git a/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/CertificatesTest.java b/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/CertificatesTest.java
index 19ee3d22330..dd3ddeeb804 100644
--- a/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/CertificatesTest.java
+++ b/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/CertificatesTest.java
@@ -5,7 +5,7 @@ import com.yahoo.security.KeyAlgorithm;
import com.yahoo.security.KeyUtils;
import com.yahoo.security.SubjectAlternativeName;
import com.yahoo.test.ManualClock;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.security.KeyPair;
import java.security.cert.X509Certificate;
@@ -13,8 +13,8 @@ import java.time.Duration;
import java.util.List;
import static java.time.temporal.ChronoUnit.SECONDS;
-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 mpolden
@@ -25,7 +25,7 @@ public class CertificatesTest {
private final X509Certificate caCertificate = CertificateTester.createCertificate("CA", keyPair);
@Test
- public void expiry() {
+ void expiry() {
var clock = new ManualClock();
var certificates = new Certificates(clock);
var csr = CertificateTester.createCsr();
@@ -37,7 +37,7 @@ public class CertificatesTest {
}
@Test
- public void add_san_from_csr() throws Exception {
+ void add_san_from_csr() throws Exception {
var certificates = new Certificates(new ManualClock());
var dnsName = "host.example.com";
var ip = "192.0.2.42";
@@ -49,13 +49,13 @@ public class CertificatesTest {
var subjectAlternativeNames = List.copyOf(certificate.getSubjectAlternativeNames());
assertEquals(List.of(SubjectAlternativeName.Type.DNS.getTag(), dnsName),
- subjectAlternativeNames.get(0));
+ subjectAlternativeNames.get(0));
assertEquals(List.of(SubjectAlternativeName.Type.IP.getTag(), ip),
- subjectAlternativeNames.get(1));
+ subjectAlternativeNames.get(1));
}
@Test
- public void parse_instance_id() {
+ void parse_instance_id() {
var instanceId = "1.cluster1.default.app1.tenant1.us-north-1.prod.node";
var instanceIdWithSuffix = instanceId + ".instanceid.athenz.dev-us-north-1.vespa.aws.oath.cloud";
var csr = CertificateTester.createCsr(List.of("foo", "bar", instanceIdWithSuffix));
diff --git a/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/restapi/CertificateAuthorityApiTest.java b/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/restapi/CertificateAuthorityApiTest.java
index 7bfc4ad41a4..bf2115e8759 100644
--- a/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/restapi/CertificateAuthorityApiTest.java
+++ b/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/restapi/CertificateAuthorityApiTest.java
@@ -17,8 +17,8 @@ import com.yahoo.vespa.athenz.client.zts.DefaultZtsClient;
import com.yahoo.vespa.hosted.ca.CertificateTester;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpUriRequest;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import javax.net.ssl.SSLContext;
import java.net.URI;
@@ -28,9 +28,9 @@ import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Optional;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author mpolden
@@ -45,25 +45,25 @@ public class CertificateAuthorityApiTest extends ContainerTester {
private static final String CONTAINER_IDENTITY = "vespa.external.tenant";
private static final String HOST_IDENTITY = "vespa.external.tenant-host";
- @Before
+ @BeforeEach
public void before() {
setCaCertificateAndKey();
}
@Test
- public void register_instance() throws Exception {
+ void register_instance() throws Exception {
// POST instance registration
var csr = CertificateTester.createCsr(List.of("node1.example.com", INSTANCE_ID_WITH_SUFFIX));
assertIdentityResponse(new Request("http://localhost:12345/ca/v1/instance/",
- instanceRegistrationJson(csr),
- Request.Method.POST));
+ instanceRegistrationJson(csr),
+ Request.Method.POST));
// POST instance registration with ZTS client
var ztsClient = new TestZtsClient(new AthenzPrincipal(new AthenzService(HOST_IDENTITY)), null, URI.create("http://localhost:12345/ca/v1/"), SSLContext.getDefault());
var instanceIdentity = ztsClient.registerInstance(new AthenzService("vespa.external", "provider_prod_us-north-1"),
- new AthenzService(CONTAINER_IDENTITY),
- getAttestationData(),
- csr);
+ new AthenzService(CONTAINER_IDENTITY),
+ getAttestationData(),
+ csr);
assertEquals("CN=Vespa CA", instanceIdentity.certificate().getIssuerX500Principal().getName());
}
@@ -84,7 +84,7 @@ public class CertificateAuthorityApiTest extends ContainerTester {
}
@Test
- public void refresh_instance() throws Exception {
+ void refresh_instance() throws Exception {
// Register instance to get cert
var certificate = registerInstance();
@@ -92,41 +92,41 @@ public class CertificateAuthorityApiTest extends ContainerTester {
var principal = new AthenzPrincipal(new AthenzService(CONTAINER_IDENTITY));
var csr = CertificateTester.createCsr(principal.getIdentity().getFullName(), List.of("node1.example.com", INSTANCE_ID_WITH_SUFFIX));
var request = new Request("http://localhost:12345/ca/v1/instance/vespa.external.provider_prod_us-north-1/vespa.external/tenant/" + INSTANCE_ID,
- instanceRefreshJson(csr),
- Request.Method.POST,
- principal);
+ instanceRefreshJson(csr),
+ Request.Method.POST,
+ principal);
request.getAttributes().put(RequestUtils.JDISC_REQUEST_X509CERT, new X509Certificate[]{certificate});
assertIdentityResponse(request);
// POST instance refresh with ZTS client
var ztsClient = new TestZtsClient(principal, certificate, URI.create("http://localhost:12345/ca/v1/"), SSLContext.getDefault());
var instanceIdentity = ztsClient.refreshInstance(new AthenzService("vespa.external", "provider_prod_us-north-1"),
- new AthenzService(CONTAINER_IDENTITY),
- INSTANCE_ID,
- csr);
+ new AthenzService(CONTAINER_IDENTITY),
+ INSTANCE_ID,
+ csr);
assertEquals("CN=Vespa CA", instanceIdentity.certificate().getIssuerX500Principal().getName());
}
@Test
- public void invalid_requests() throws Exception {
+ void invalid_requests() throws Exception {
// POST instance registration with missing fields
assertResponse(400, "{\"error-code\":\"BAD_REQUEST\",\"message\":\"POST http://localhost:12345/ca/v1/instance/ failed: Missing required field 'provider'\"}",
- new Request("http://localhost:12345/ca/v1/instance/",
- new byte[0],
- Request.Method.POST));
+ new Request("http://localhost:12345/ca/v1/instance/",
+ new byte[0],
+ Request.Method.POST));
// POST instance registration without DNS name in CSR
var csr = CertificateTester.createCsr();
var request = new Request("http://localhost:12345/ca/v1/instance/",
- instanceRegistrationJson(csr),
- Request.Method.POST);
+ instanceRegistrationJson(csr),
+ Request.Method.POST);
assertResponse(400, "{\"error-code\":\"BAD_REQUEST\",\"message\":\"POST http://localhost:12345/ca/v1/instance/ failed: No instance ID found in CSR\"}", request);
// POST instance refresh with missing field
assertResponse(400, "{\"error-code\":\"BAD_REQUEST\",\"message\":\"POST http://localhost:12345/ca/v1/instance/vespa.external.provider_prod_us-north-1/vespa.external/tenant/1.cluster1.default.app1.tenant1.us-north-1.prod.node failed: Missing required field 'csr'\"}",
- new Request("http://localhost:12345/ca/v1/instance/vespa.external.provider_prod_us-north-1/vespa.external/tenant/" + INSTANCE_ID,
- new byte[0],
- Request.Method.POST));
+ new Request("http://localhost:12345/ca/v1/instance/vespa.external.provider_prod_us-north-1/vespa.external/tenant/" + INSTANCE_ID,
+ new byte[0],
+ Request.Method.POST));
// POST instance refresh where instanceId does not match CSR dnsName
var principal = new AthenzPrincipal(new AthenzService(CONTAINER_IDENTITY));
@@ -148,9 +148,9 @@ public class CertificateAuthorityApiTest extends ContainerTester {
try {
var invalidCsr = CertificateTester.createCsr(principal.getIdentity().getFullName(), List.of("node1.example.com", INVALID_INSTANCE_ID_WITH_SUFFIX));
var instanceIdentity = ztsClient.refreshInstance(new AthenzService("vespa.external", "provider_prod_us-north-1"),
- new AthenzService(CONTAINER_IDENTITY),
- INSTANCE_ID,
- invalidCsr);
+ new AthenzService(CONTAINER_IDENTITY),
+ INSTANCE_ID,
+ invalidCsr);
fail("Refresh instance should have failed");
} catch (Exception e) {
String expectedMessage = "Received error from ZTS: code=0, message=\"POST http://localhost:12345/ca/v1/instance/vespa.external.provider_prod_us-north-1/vespa.external/tenant/1.cluster1.default.app1.tenant1.us-north-1.prod.node failed: Mismatch between instance ID in URL path and instance ID in CSR [instanceId=1.cluster1.default.app1.tenant1.us-north-1.prod.node,instanceIdFromCsr=1.cluster1.default.otherapp.othertenant.us-north-1.prod.node]\"";
@@ -174,9 +174,9 @@ public class CertificateAuthorityApiTest extends ContainerTester {
assertEquals("tenant", root.field("service").asString());
assertEquals(INSTANCE_ID, root.field("instanceId").asString());
var pemEncodedCertificate = root.field("x509Certificate").asString();
- assertTrue("Response contains PEM certificate",
- pemEncodedCertificate.startsWith("-----BEGIN CERTIFICATE-----") &&
- pemEncodedCertificate.endsWith("-----END CERTIFICATE-----\n"));
+ assertTrue(pemEncodedCertificate.startsWith("-----BEGIN CERTIFICATE-----") &&
+ pemEncodedCertificate.endsWith("-----END CERTIFICATE-----\n"),
+ "Response contains PEM certificate");
}, request);
}
diff --git a/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/restapi/ContainerTester.java b/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/restapi/ContainerTester.java
index ad0715cbbea..8112f5779e5 100644
--- a/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/restapi/ContainerTester.java
+++ b/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/restapi/ContainerTester.java
@@ -5,14 +5,14 @@ import com.yahoo.application.Networking;
import com.yahoo.application.container.JDisc;
import com.yahoo.application.container.handler.Request;
import com.yahoo.vespa.hosted.ca.restapi.mock.SecretStoreMock;
-import org.junit.After;
-import org.junit.Before;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
import java.io.UncheckedIOException;
import java.nio.charset.CharacterCodingException;
import java.util.function.Consumer;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* The superclass of REST API tests which require a functional container instance.
@@ -23,12 +23,12 @@ public class ContainerTester {
private JDisc container;
- @Before
+ @BeforeEach
public void startContainer() {
container = JDisc.fromServicesXml(servicesXml(), Networking.enable);
}
- @After
+ @AfterEach
public void stopContainer() {
container.close();
}
diff --git a/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/restapi/InstanceSerializerTest.java b/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/restapi/InstanceSerializerTest.java
index 904ebc65f35..df75e09b957 100644
--- a/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/restapi/InstanceSerializerTest.java
+++ b/athenz-identity-provider-service/src/test/java/com/yahoo/vespa/hosted/ca/restapi/InstanceSerializerTest.java
@@ -15,7 +15,7 @@ import com.yahoo.vespa.hosted.ca.CertificateTester;
import com.yahoo.vespa.hosted.ca.instance.InstanceIdentity;
import com.yahoo.vespa.hosted.ca.instance.InstanceRefresh;
import com.yahoo.vespa.hosted.ca.instance.InstanceRegistration;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.UncheckedIOException;
@@ -25,7 +25,7 @@ import java.time.temporal.ChronoUnit;
import java.util.Collections;
import java.util.Optional;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author mpolden
@@ -33,7 +33,7 @@ import static org.junit.Assert.assertEquals;
public class InstanceSerializerTest {
@Test
- public void deserialize_instance_registration() {
+ void deserialize_instance_registration() {
var csr = CertificateTester.createCsr();
var csrPem = Pkcs10CsrUtils.toPem(csr);
SignedIdentityDocument signedIdentityDocument = new SignedIdentityDocument(
@@ -49,36 +49,36 @@ public class InstanceSerializerTest {
IdentityType.NODE);
var json = String.format("{\n" +
- " \"provider\": \"provider_prod_us-north-1\",\n" +
- " \"domain\": \"vespa.external\",\n" +
- " \"service\": \"tenant\",\n" +
- " \"attestationData\":\"%s\",\n" +
- " \"csr\": \"" + csrPem + "\"\n" +
- "}", StringUtilities.escape(EntityBindingsMapper.toAttestationData(signedIdentityDocument)));
+ " \"provider\": \"provider_prod_us-north-1\",\n" +
+ " \"domain\": \"vespa.external\",\n" +
+ " \"service\": \"tenant\",\n" +
+ " \"attestationData\":\"%s\",\n" +
+ " \"csr\": \"" + csrPem + "\"\n" +
+ "}", StringUtilities.escape(EntityBindingsMapper.toAttestationData(signedIdentityDocument)));
var instanceRegistration = new InstanceRegistration("provider_prod_us-north-1", "vespa.external",
- "tenant", signedIdentityDocument,
- csr);
+ "tenant", signedIdentityDocument,
+ csr);
var deserialized = InstanceSerializer.registrationFromSlime(SlimeUtils.jsonToSlime(json));
assertEquals(instanceRegistration, deserialized);
}
@Test
- public void serialize_instance_identity() {
+ void serialize_instance_identity() {
var certificate = CertificateTester.createCertificate();
var pem = X509CertificateUtils.toPem(certificate);
var identity = new InstanceIdentity("provider_prod_us-north-1", "tenant", "node1.example.com",
- Optional.of(certificate));
+ Optional.of(certificate));
var json = "{" +
- "\"provider\":\"provider_prod_us-north-1\"," +
- "\"service\":\"tenant\"," +
- "\"instanceId\":\"node1.example.com\"," +
- "\"x509Certificate\":\"" + pem.replace("\n", "\\n") + "\"" +
- "}";
+ "\"provider\":\"provider_prod_us-north-1\"," +
+ "\"service\":\"tenant\"," +
+ "\"instanceId\":\"node1.example.com\"," +
+ "\"x509Certificate\":\"" + pem.replace("\n", "\\n") + "\"" +
+ "}";
assertEquals(json, asJsonString(InstanceSerializer.identityToSlime(identity)));
}
@Test
- public void serialize_instance_refresh() {
+ void serialize_instance_refresh() {
var csr = CertificateTester.createCsr();
var csrPem = Pkcs10CsrUtils.toPem(csr);
var json = "{\"csr\": \"" + csrPem + "\"}";
diff --git a/bundle-plugin-test/integration-test/pom.xml b/bundle-plugin-test/integration-test/pom.xml
index a97d30fbaec..7384bf3aea6 100644
--- a/bundle-plugin-test/integration-test/pom.xml
+++ b/bundle-plugin-test/integration-test/pom.xml
@@ -29,13 +29,18 @@
<scope>test</scope>
</dependency>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
+ <groupId>org.apache.maven</groupId>
+ <artifactId>maven-artifact</artifactId>
<scope>test</scope>
</dependency>
<dependency>
- <groupId>org.apache.maven</groupId>
- <artifactId>maven-artifact</artifactId>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
diff --git a/bundle-plugin-test/integration-test/src/test/java/com/yahoo/container/plugin/BundleTest.java b/bundle-plugin-test/integration-test/src/test/java/com/yahoo/container/plugin/BundleTest.java
index faa33542f5c..2e3a3204ef5 100644
--- a/bundle-plugin-test/integration-test/src/test/java/com/yahoo/container/plugin/BundleTest.java
+++ b/bundle-plugin-test/integration-test/src/test/java/com/yahoo/container/plugin/BundleTest.java
@@ -2,8 +2,8 @@
package com.yahoo.container.plugin;
import com.yahoo.vespa.config.VespaVersion;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
@@ -18,9 +18,9 @@ import java.util.jar.Manifest;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Verifies the bundle jar file built and its manifest.
@@ -38,7 +38,7 @@ public class BundleTest {
private JarFile jarFile;
private Attributes mainAttributes;
- @Before
+ @BeforeEach
public void setup() {
try {
File componentJar = findBundleJar("main");
@@ -60,7 +60,7 @@ public class BundleTest {
}
@Test
- public void require_that_bundle_version_is_added_to_manifest() {
+ void require_that_bundle_version_is_added_to_manifest() {
String bundleVersion = mainAttributes.getValue("Bundle-Version");
// Because of snapshot builds, we can only verify the major version.
@@ -69,12 +69,12 @@ public class BundleTest {
}
@Test
- public void require_that_bundle_symbolic_name_matches_pom_artifactId() {
+ void require_that_bundle_symbolic_name_matches_pom_artifactId() {
assertEquals("main", mainAttributes.getValue("Bundle-SymbolicName"));
}
@Test
- public void require_that_manifest_contains_inferred_imports() {
+ void require_that_manifest_contains_inferred_imports() {
String importPackage = mainAttributes.getValue("Import-Package");
// From SimpleSearcher
@@ -87,35 +87,35 @@ public class BundleTest {
}
@Test
- public void require_that_manifest_contains_manual_imports() {
+ void require_that_manifest_contains_manual_imports() {
String importPackage = mainAttributes.getValue("Import-Package");
assertTrue(importPackage.contains("manualImport.withoutVersion"));
assertTrue(importPackage.contains("manualImport.withVersion;version=\"12.3.4\""));
- for (int i=1; i<=2; ++i)
+ for (int i = 1; i <= 2; ++i)
assertTrue(importPackage.contains("multiple.packages.with.the.same.version" + i + ";version=\"[1,2)\""));
}
@Test
- public void require_that_manifest_contains_exports() {
+ void require_that_manifest_contains_exports() {
String exportPackage = mainAttributes.getValue("Export-Package");
assertTrue(exportPackage.contains("com.yahoo.test;version=1.2.3.RELEASE"));
}
- @Test
// TODO: use another jar than jrt, which now pulls in a lot of dependencies that pollute the manifest of the
// generated bundle. (It's compile scoped in pom.xml to be added to the bundle-cp.)
- public void require_that_manifest_contains_bundle_class_path() {
+ @Test
+ void require_that_manifest_contains_bundle_class_path() {
String bundleClassPath = mainAttributes.getValue("Bundle-ClassPath");
assertTrue(bundleClassPath.contains(".,"));
Pattern jrtPattern = Pattern.compile("dependencies/jrt" + snapshotOrVersionOrNone);
- assertTrue("Bundle class path did not contain jrt.", jrtPattern.matcher(bundleClassPath).find());
+ assertTrue(jrtPattern.matcher(bundleClassPath).find(), "Bundle class path did not contain jrt.");
}
@Test
- public void require_that_component_jar_file_contains_compile_artifacts() {
+ void require_that_component_jar_file_contains_compile_artifacts() {
String depJrt = "dependencies/jrt";
Pattern jrtPattern = Pattern.compile(depJrt + snapshotOrVersionOrNone);
ZipEntry jrtEntry = null;
@@ -130,12 +130,12 @@ public class BundleTest {
}
}
}
- assertNotNull("Component jar file did not contain jrt dependency.", jrtEntry);
+ assertNotNull(jrtEntry, "Component jar file did not contain jrt dependency.");
}
@Test
- public void require_that_web_inf_url_is_propagated_to_the_manifest() {
+ void require_that_web_inf_url_is_propagated_to_the_manifest() {
String webInfUrl = mainAttributes.getValue("WebInfUrl");
assertTrue(webInfUrl.contains("/WEB-INF/web.xml"));
}
diff --git a/bundle-plugin-test/integration-test/src/test/java/com/yahoo/container/plugin/ExportPackageVersionTest.java b/bundle-plugin-test/integration-test/src/test/java/com/yahoo/container/plugin/ExportPackageVersionTest.java
index f99f1583324..67a191f1f94 100644
--- a/bundle-plugin-test/integration-test/src/test/java/com/yahoo/container/plugin/ExportPackageVersionTest.java
+++ b/bundle-plugin-test/integration-test/src/test/java/com/yahoo/container/plugin/ExportPackageVersionTest.java
@@ -1,8 +1,8 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.plugin;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
@@ -10,8 +10,8 @@ import java.util.jar.Attributes;
import java.util.jar.JarFile;
import static com.yahoo.container.plugin.BundleTest.findBundleJar;
-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;
/**
* Verifies that the 'useArtifactVersionForExportPackages' setting for the bundle-plugin works as intended.
@@ -23,7 +23,7 @@ public class ExportPackageVersionTest {
private static Attributes mainAttributes;
private static String bundleVersion;
- @BeforeClass
+ @BeforeAll
public static void setup() {
try {
File componentJar = findBundleJar("artifact-version-for-exports");
@@ -36,7 +36,7 @@ public class ExportPackageVersionTest {
}
@Test
- public void artifact_version_without_qualifier_is_used_as_export_version() {
+ void artifact_version_without_qualifier_is_used_as_export_version() {
// Bundle-Version is artifact version without qualifier
String expectedExport = "ai.vespa.noversion;version=" + bundleVersion;
@@ -48,13 +48,13 @@ public class ExportPackageVersionTest {
}
@Test
- public void explicit_version_in_ExportPackage_annotation_overrides_artifact_version() {
+ void explicit_version_in_ExportPackage_annotation_overrides_artifact_version() {
String exportPackage = mainAttributes.getValue("Export-Package");
assertTrue(exportPackage.contains("ai.vespa.explicitversion;version=2.4.6.RELEASE"));
}
@Test
- public void artifact_version_of_dependency_is_used_as_export_version_for_package_in_compile_scoped_dependency() {
+ void artifact_version_of_dependency_is_used_as_export_version_for_package_in_compile_scoped_dependency() {
String exportPackage = mainAttributes.getValue("Export-Package");
// TODO: This test should have checked for a fixed version of the dependency bundle, different than the main bundle version.
@@ -63,7 +63,7 @@ public class ExportPackageVersionTest {
}
@Test
- public void explicit_version_in_ExportPackage_annotation_overrides_artifact_version_of_compile_scoped_dependency() {
+ void explicit_version_in_ExportPackage_annotation_overrides_artifact_version_of_compile_scoped_dependency() {
String exportPackage = mainAttributes.getValue("Export-Package");
assertTrue(exportPackage.contains("ai.vespa.explicitversion_dep;version=3.6.9.RELEASE"));
}
diff --git a/bundle-plugin/pom.xml b/bundle-plugin/pom.xml
index be5d2d59de2..4911f88b61a 100644
--- a/bundle-plugin/pom.xml
+++ b/bundle-plugin/pom.xml
@@ -33,6 +33,16 @@
<scope>provided</scope>
</dependency>
<dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-archiver</artifactId>
</dependency>
@@ -51,11 +61,6 @@
<scope>provided</scope>
</dependency>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
</dependency>
diff --git a/bundle-plugin/src/test/java/com/yahoo/container/plugin/bundle/AnalyzeBundleTest.java b/bundle-plugin/src/test/java/com/yahoo/container/plugin/bundle/AnalyzeBundleTest.java
index 62ecd780d7e..97c2bf02d9b 100644
--- a/bundle-plugin/src/test/java/com/yahoo/container/plugin/bundle/AnalyzeBundleTest.java
+++ b/bundle-plugin/src/test/java/com/yahoo/container/plugin/bundle/AnalyzeBundleTest.java
@@ -3,17 +3,17 @@ package com.yahoo.container.plugin.bundle;
import com.yahoo.container.plugin.osgi.ExportPackages;
import com.yahoo.container.plugin.osgi.ExportPackages.Export;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertFalse;
-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.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Tony Vaagenes
@@ -37,29 +37,29 @@ public class AnalyzeBundleTest {
}
@Test
- public void require_that_non_osgi_bundles_are_ignored() {
+ void require_that_non_osgi_bundles_are_ignored() {
assertFalse(exportsByPackageName.containsKey("com.yahoo.sample.exported.package.ignored"));
}
@Test
- public void require_that_exports_are_retrieved_from_manifest_in_jars() {
+ void require_that_exports_are_retrieved_from_manifest_in_jars() {
assertEquals(1, exportsByPackageName.keySet().size());
assertTrue(exportsByPackageName.containsKey("com.yahoo.sample.exported.package"));
}
@Test
- public void exported_class_names_can_be_retrieved() {
+ void exported_class_names_can_be_retrieved() {
assertEquals(ExportPackages.packageNames(exports), exports.get(0).getPackageNames().stream().collect(Collectors.toSet()));
}
@Test
- public void require_that_invalid_exports_throws_exception() {
+ void require_that_invalid_exports_throws_exception() {
try {
AnalyzeBundle.exportedPackages(jarFile("errorExport.jar"));
fail();
} catch (RuntimeException e) {
assertTrue(e.getMessage().contains("Invalid manifest in bundle 'src/test/resources/jar/errorExport.jar'"));
- assertTrue(e.getCause().getMessage(), e.getCause().getMessage().startsWith("Failed parsing Export-Package"));
+ assertTrue(e.getCause().getMessage().startsWith("Failed parsing Export-Package"), e.getCause().getMessage());
}
}
}
diff --git a/bundle-plugin/src/test/java/com/yahoo/container/plugin/classanalysis/AnalyzeClassTest.java b/bundle-plugin/src/test/java/com/yahoo/container/plugin/classanalysis/AnalyzeClassTest.java
index f9f56a31b20..8f78363dab5 100644
--- a/bundle-plugin/src/test/java/com/yahoo/container/plugin/classanalysis/AnalyzeClassTest.java
+++ b/bundle-plugin/src/test/java/com/yahoo/container/plugin/classanalysis/AnalyzeClassTest.java
@@ -17,7 +17,7 @@ import com.yahoo.container.plugin.classanalysis.sampleclasses.MethodAnnotation;
import com.yahoo.container.plugin.classanalysis.sampleclasses.MethodInvocation;
import com.yahoo.osgi.annotation.ExportPackage;
import com.yahoo.osgi.annotation.Version;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.security.auth.login.LoginException;
import java.awt.Image;
@@ -29,10 +29,10 @@ import java.util.Optional;
import static com.yahoo.container.plugin.classanalysis.TestUtilities.analyzeClass;
import static com.yahoo.container.plugin.classanalysis.TestUtilities.classFile;
import static com.yahoo.container.plugin.classanalysis.TestUtilities.name;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* Tests that analysis of class files works.
@@ -43,23 +43,23 @@ import static org.junit.Assert.fail;
public class AnalyzeClassTest {
@Test
- public void full_class_name_is_returned() {
+ void full_class_name_is_returned() {
assertEquals(name(Base.class), analyzeClass(Base.class).getName());
}
@Test
- public void base_class_is_included() {
+ void base_class_is_included() {
assertTrue(analyzeClass(Derived.class).getReferencedClasses().contains(name(Base.class)));
}
@Test
- public void implemented_interfaces_are_included() {
+ void implemented_interfaces_are_included() {
assertTrue(analyzeClass(Base.class).getReferencedClasses().containsAll(
List.of(name(Interface1.class), name(Interface2.class))));
}
@Test
- public void interface_can_be_analyzed() {
+ void interface_can_be_analyzed() {
ClassFileMetaData classMetaData = analyzeClass(Interface1.class);
assertEquals(name(Interface1.class), classMetaData.getName());
@@ -67,77 +67,77 @@ public class AnalyzeClassTest {
}
@Test
- public void return_type_is_included() {
+ void return_type_is_included() {
assertTrue(analyzeClass(Interface1.class).getReferencedClasses().contains(name(Image.class)));
}
@Test
- public void parameters_are_included() {
+ void parameters_are_included() {
assertTrue(analyzeClass(Interface1.class).getReferencedClasses().contains(name(Kernel.class)));
}
@Test
- public void exceptions_are_included() {
+ void exceptions_are_included() {
assertTrue(analyzeClass(Interface1.class).getReferencedClasses().contains(name(ImagingOpException.class)));
}
@Test
- public void basic_types_ignored() {
+ void basic_types_ignored() {
List.of("int", "float").forEach(type ->
assertFalse(analyzeClass(Interface1.class).getReferencedClasses().contains(type)));
}
@Test
- public void arrays_of_basic_types_ignored() {
+ void arrays_of_basic_types_ignored() {
List.of("int[]", "int[][]").forEach(type ->
assertFalse(analyzeClass(Interface1.class).getReferencedClasses().contains(type)));
}
@Test
- public void instance_field_types_are_included() {
+ void instance_field_types_are_included() {
assertTrue(analyzeClass(Fields.class).getReferencedClasses().contains(name(String.class)));
}
@Test
- public void static_field_types_are_included() {
+ void static_field_types_are_included() {
assertTrue(analyzeClass(Fields.class).getReferencedClasses().contains(name(java.util.List.class)));
}
@Test
- public void field_annotation_is_included() {
+ void field_annotation_is_included() {
assertTrue(analyzeClass(Fields.class).getReferencedClasses().contains(name(DummyAnnotation.class)));
}
@Test
- public void class_annotation_is_included() {
+ void class_annotation_is_included() {
assertTrue(analyzeClass(ClassAnnotation.class).getReferencedClasses().contains(name(DummyAnnotation.class)));
}
@Test
- public void invisible_annotation_not_included() {
+ void invisible_annotation_not_included() {
assertFalse(analyzeClass(InvisibleAnnotation.class).getReferencedClasses().contains(name(InvisibleDummyAnnotation.class)));
}
@Test
- public void method_annotation_is_included() {
+ void method_annotation_is_included() {
assertTrue(analyzeClass(MethodAnnotation.class).getReferencedClasses().contains(name(DummyAnnotation.class)));
}
@Test
- public void export_package_annotations_are_ignored() {
+ void export_package_annotations_are_ignored() {
List.of(ExportPackage.class, Version.class).forEach(type ->
assertFalse(Analyze.analyzeClass(classFile("com.yahoo.container.plugin.classanalysis.sampleclasses.package-info"))
.getReferencedClasses().contains(type)));
}
@Test
- public void export_annotations_are_processed() {
+ void export_annotations_are_processed() {
assertEquals(Optional.of(new ExportPackageAnnotation(3, 1, 4, "TEST_QUALIFIER-2")),
Analyze.analyzeClass(classFile("com.yahoo.container.plugin.classanalysis.sampleclasses.package-info")).getExportPackage());
}
@Test
- public void export_annotations_are_validated() {
+ void export_annotations_are_validated() {
try {
Analyze.analyzeClass(classFile("com.yahoo.container.plugin.classanalysis.sampleclasses.invalid.package-info"));
@@ -150,38 +150,38 @@ public class AnalyzeClassTest {
}
@Test
- public void catch_clauses_are_included() {
+ void catch_clauses_are_included() {
assertTrue(Analyze.analyzeClass(classFile("com.yahoo.container.plugin.classanalysis.sampleclasses.CatchException"))
.getReferencedClasses().contains(name(LoginException.class)));
}
@Test
- public void class_references_are_included() {
+ void class_references_are_included() {
assertTrue(Analyze.analyzeClass(classFile("com.yahoo.container.plugin.classanalysis.sampleclasses.ClassReference"))
.getReferencedClasses().contains(name(Interface1.class)));
}
@Test
- public void return_type_of_method_invocations_are_included() {
+ void return_type_of_method_invocations_are_included() {
assertTrue(analyzeClass(MethodInvocation.class).getReferencedClasses().contains(name(Image.class)));
}
@Test
- public void attributes_are_included() {
+ void attributes_are_included() {
//Uses com/coremedia/iso/Utf8.class from com.googlecode.mp4parser:isoparser:1.0-RC-1
assertTrue(Analyze.analyzeClass(classFile("class/Utf8")).getReferencedClasses()
.contains("org.aspectj.weaver.MethodDeclarationLineNumber"));
}
@Test
- public void switch_statements_are_analyzed() {
+ void switch_statements_are_analyzed() {
var referencedClasses = analyzeClass(SwitchStatement.class).getReferencedClasses();
assertTrue(referencedClasses.contains(name(ImmutableList.class)));
assertTrue(referencedClasses.contains(name(IllegalArgumentException.class)));
}
@Test
- public void records_are_analyzed() {
+ void records_are_analyzed() {
var referencedClasses = analyzeClass(RecordWithOverride.class).getReferencedClasses();
assertTrue(referencedClasses.containsAll(List.of(
name(java.util.List.class),
diff --git a/bundle-plugin/src/test/java/com/yahoo/container/plugin/classanalysis/AnalyzeMethodBodyTest.java b/bundle-plugin/src/test/java/com/yahoo/container/plugin/classanalysis/AnalyzeMethodBodyTest.java
index 0076869eaa5..2b2e83fb024 100644
--- a/bundle-plugin/src/test/java/com/yahoo/container/plugin/classanalysis/AnalyzeMethodBodyTest.java
+++ b/bundle-plugin/src/test/java/com/yahoo/container/plugin/classanalysis/AnalyzeMethodBodyTest.java
@@ -9,15 +9,15 @@ import com.yahoo.container.plugin.classanalysis.sampleclasses.Fields;
import com.yahoo.container.plugin.classanalysis.sampleclasses.Interface1;
import com.yahoo.container.plugin.classanalysis.sampleclasses.Interface3;
import com.yahoo.container.plugin.classanalysis.sampleclasses.Methods;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.PrintStream;
import java.util.List;
import static com.yahoo.container.plugin.classanalysis.TestUtilities.analyzeClass;
import static com.yahoo.container.plugin.classanalysis.TestUtilities.name;
-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;
/**
* Tests that classes used in method bodies are included in the imports list.
@@ -27,52 +27,52 @@ import static org.junit.Assert.assertTrue;
public class AnalyzeMethodBodyTest {
@Test
- public void class_of_locals_are_included() {
+ void class_of_locals_are_included() {
assertTrue(analyzeClass(Methods.class).getReferencedClasses().contains(name(Base.class)));
}
@Test
- public void class_of_locals_in_static_method_are_included() {
+ void class_of_locals_in_static_method_are_included() {
assertTrue(analyzeClass(Methods.class).getReferencedClasses().contains(name(Derived.class)));
}
@Test
- public void field_references_are_included() {
+ void field_references_are_included() {
assertTrue(analyzeClass(Methods.class).getReferencedClasses().containsAll(List.of(name(java.util.List.class), name(Fields.class))));
}
@Test
- public void class_owning_field_is_included() {
+ void class_owning_field_is_included() {
assertTrue(analyzeClass(Methods.class).getReferencedClasses().contains(name(System.class)));
}
@Test
- public void class_containing_method_is_included() {
+ void class_containing_method_is_included() {
assertTrue(analyzeClass(Methods.class).getReferencedClasses().contains(name(PrintStream.class)));
}
@Test
- public void element_of_new_multidimensional_array_is_included() {
+ void element_of_new_multidimensional_array_is_included() {
assertTrue(analyzeClass(Methods.class).getReferencedClasses().contains(name(Interface1.class)));
}
@Test
- public void basic_arrays_are_not_included() {
+ void basic_arrays_are_not_included() {
assertFalse(analyzeClass(Methods.class).getReferencedClasses().contains("int[]"));
}
@Test
- public void container_generic_parameters_are_included() {
+ void container_generic_parameters_are_included() {
assertTrue(analyzeClass(Methods.class).getReferencedClasses().contains(name(Dummy.class)));
}
@Test
- public void functional_interface_usage_is_included() {
+ void functional_interface_usage_is_included() {
assertTrue(analyzeClass(Methods.class).getReferencedClasses().contains(name(Interface3.class)));
}
@Test
- public void class_owning_method_handler_is_included() {
+ void class_owning_method_handler_is_included() {
assertTrue(analyzeClass(Methods.class).getReferencedClasses().contains(name(ClassWithMethod.class)));
}
}
diff --git a/bundle-plugin/src/test/java/com/yahoo/container/plugin/classanalysis/PackageTallyTest.java b/bundle-plugin/src/test/java/com/yahoo/container/plugin/classanalysis/PackageTallyTest.java
index 31abe785cbe..002959959ec 100644
--- a/bundle-plugin/src/test/java/com/yahoo/container/plugin/classanalysis/PackageTallyTest.java
+++ b/bundle-plugin/src/test/java/com/yahoo/container/plugin/classanalysis/PackageTallyTest.java
@@ -1,12 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.plugin.classanalysis;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Map;
import java.util.Set;
-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 PackageTallyTest {
@Test
- public void referenced_packages_missing_from_available_packages_are_detected() {
+ void referenced_packages_missing_from_available_packages_are_detected() {
PackageTally tally = new PackageTally(Map.of(), Set.of("p1", "java.util", "com.yahoo.api.annotations", "missing"));
Set<String> missingPackages = tally.referencedPackagesMissingFrom(Set.of("p1"));
assertEquals(Set.of("missing"), missingPackages);
diff --git a/bundle-plugin/src/test/java/com/yahoo/container/plugin/mojo/GenerateSourcesMojoTest.java b/bundle-plugin/src/test/java/com/yahoo/container/plugin/mojo/GenerateSourcesMojoTest.java
index 3b75d9dcb7d..4edc9c3712d 100644
--- a/bundle-plugin/src/test/java/com/yahoo/container/plugin/mojo/GenerateSourcesMojoTest.java
+++ b/bundle-plugin/src/test/java/com/yahoo/container/plugin/mojo/GenerateSourcesMojoTest.java
@@ -2,10 +2,10 @@
package com.yahoo.container.plugin.mojo;
import org.apache.maven.plugin.MojoExecutionException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assume.assumeNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assumptions.assumeTrue;
/**
* @author Simon Thoresen Hult
@@ -13,10 +13,10 @@ import static org.junit.Assume.assumeNotNull;
public class GenerateSourcesMojoTest {
@Test
- public void requireThatDefaultConfigGenVersionIsLoadedFromBuildProperties() throws MojoExecutionException {
+ void requireThatDefaultConfigGenVersionIsLoadedFromBuildProperties() throws MojoExecutionException {
String expected = System.getProperty("expectedDefaultConfigGenVersion");
System.out.println("expectedDefaultConfigGenVersion = " + expected);
- assumeNotNull(expected);
+ assumeTrue(expected != null);
String actual = GenerateSourcesMojo.loadDefaultConfigGenVersion();
System.out.println("defaultConfigGenVersion = " + actual);
diff --git a/bundle-plugin/src/test/java/com/yahoo/container/plugin/osgi/ExportPackageParserTest.java b/bundle-plugin/src/test/java/com/yahoo/container/plugin/osgi/ExportPackageParserTest.java
index 2c9b32a325f..de5c0f2be9d 100644
--- a/bundle-plugin/src/test/java/com/yahoo/container/plugin/osgi/ExportPackageParserTest.java
+++ b/bundle-plugin/src/test/java/com/yahoo/container/plugin/osgi/ExportPackageParserTest.java
@@ -3,13 +3,13 @@ package com.yahoo.container.plugin.osgi;
import com.yahoo.container.plugin.osgi.ExportPackages.Export;
import com.yahoo.container.plugin.osgi.ExportPackages.Parameter;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
import java.util.List;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Tony Vaagenes
@@ -19,7 +19,7 @@ public class ExportPackageParserTest {
private final Parameter versionParameter = new Parameter("version", "1.2.3.sample");
@Test
- public void require_that_package_is_parsed_correctly() {
+ void require_that_package_is_parsed_correctly() {
List<Export> exports = ExportPackageParser.parseExports("sample.exported.package");
assertEquals(1, exports.size());
@@ -28,7 +28,7 @@ public class ExportPackageParserTest {
}
@Test
- public void require_that_version_is_parsed_correctly() {
+ void require_that_version_is_parsed_correctly() {
List<Export> exports = ExportPackageParser.parseExports("com.yahoo.sample.exported.package;version=\"1.2.3.sample\"");
assertEquals(1, exports.size());
@@ -38,7 +38,7 @@ public class ExportPackageParserTest {
}
@Test
- public void require_that_multiple_packages_with_same_parameters_is_parsed_correctly() {
+ void require_that_multiple_packages_with_same_parameters_is_parsed_correctly() {
List<Export> exports = ExportPackageParser.parseExports("exported.package1;exported.package2;version=\"1.2.3.sample\"");
assertEquals(1, exports.size());
@@ -48,7 +48,7 @@ public class ExportPackageParserTest {
}
@Test
- public void require_that_spaces_between_separators_are_allowed() {
+ void require_that_spaces_between_separators_are_allowed() {
List<Export> exports = ExportPackageParser.parseExports("exported.package1 , exported.package2 ; version = \"1.2.3.sample\" ");
assertEquals(2, exports.size());
@@ -61,7 +61,7 @@ public class ExportPackageParserTest {
@SuppressWarnings("unchecked")
@Test
- public void require_that_multiple_parameters_for_a_package_is_parsed_correctly() {
+ void require_that_multiple_parameters_for_a_package_is_parsed_correctly() {
List<Export> exports = ExportPackageParser.parseExports("exported.package;version=\"1.2.3.sample\";param2=true");
assertEquals(1, exports.size());
@@ -70,7 +70,7 @@ public class ExportPackageParserTest {
}
@Test
- public void require_that_multiple_exports_are_parsed_correctly() {
+ void require_that_multiple_exports_are_parsed_correctly() {
List<Export> exports = ExportPackageParser.parseExports("exported.package1,exported.package2");
assertEquals(2, exports.size());
Export export = exports.get(0);
@@ -100,9 +100,9 @@ public class ExportPackageParserTest {
}
// TODO: MAVEN_OPTS are not propagated by the maven-surefire-plugin. Either try to fix the underlying problem or set -Xss in plugin config.
- @Ignore // Frequently causes StackOverflowError
+ @Disabled // Frequently causes StackOverflowError
@Test
- public void require_that_long_string_literals_do_not_cause_stack_overflow_error() {
+ void require_that_long_string_literals_do_not_cause_stack_overflow_error() {
//From jersey-server-1.13.jar
String exportHeader = "com.sun.jersey.server.impl.wadl;uses:=\"com.sun.jersey.api.model,com.sun.resea"
+ "rch.ws.wadl,com.sun.jersey.api.wadl.config,com.sun.jersey.server.wadl,com.sun."
diff --git a/bundle-plugin/src/test/java/com/yahoo/container/plugin/osgi/ImportPackageTest.java b/bundle-plugin/src/test/java/com/yahoo/container/plugin/osgi/ImportPackageTest.java
index 29f2be838a1..aa74746bfff 100644
--- a/bundle-plugin/src/test/java/com/yahoo/container/plugin/osgi/ImportPackageTest.java
+++ b/bundle-plugin/src/test/java/com/yahoo/container/plugin/osgi/ImportPackageTest.java
@@ -4,9 +4,7 @@ package com.yahoo.container.plugin.osgi;
import com.yahoo.container.plugin.osgi.ExportPackages.Export;
import com.yahoo.container.plugin.osgi.ExportPackages.Parameter;
import com.yahoo.container.plugin.osgi.ImportPackages.Import;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.HashSet;
@@ -15,8 +13,9 @@ import java.util.Map;
import java.util.Optional;
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.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Tony Vaagenes
@@ -34,37 +33,37 @@ public class ImportPackageTest {
}
@Test
- public void require_that_non_implemented_import_with_matching_export_is_included() {
+ void require_that_non_implemented_import_with_matching_export_is_included() {
Set<Import> imports = calculateImports(referencedPackages, Set.of(), exports);
assertEquals(1, imports.stream().filter(imp -> imp.packageName().equals(PACKAGE_NAME) && imp.version().isEmpty()).count());
}
@Test
- public void require_that_non_implemented_import_without_matching_export_is_excluded() {
+ void require_that_non_implemented_import_without_matching_export_is_excluded() {
Set<Import> imports = calculateImports(referencedPackages, Set.of(), Map.of());
assertTrue(imports.isEmpty());
}
@Test
- public void require_that_implemented_import_with_matching_export_is_excluded() {
+ void require_that_implemented_import_with_matching_export_is_excluded() {
Set<Import> imports = calculateImports(referencedPackages, referencedPackages, exports);
assertTrue(imports.isEmpty());
}
@Test
- public void require_that_version_is_included() {
+ void require_that_version_is_included() {
Set<Import> imports = calculateImports(referencedPackages, Set.of(), exportsWithVersion);
assertEquals(1, imports.stream().filter(imp -> imp.packageName().equals(PACKAGE_NAME) && imp.version().equals("1.3")).count());
}
@Test
- public void require_that_all_versions_up_to_the_next_major_version_is_in_range() {
+ void require_that_all_versions_up_to_the_next_major_version_is_in_range() {
assertEquals("[1.2,2)", new Import("foo", Optional.of("1.2")).importVersionRange().get());
}
// TODO: Detecting guava packages should be based on bundle-symbolicName, not package name.
@Test
- public void require_that_for_guava_all_future_major_versions_are_in_range() {
+ void require_that_for_guava_all_future_major_versions_are_in_range() {
Optional<String> rangeWithInfiniteUpperLimit = Optional.of("[18.1," + ImportPackages.INFINITE_VERSION + ")");
assertEquals(rangeWithInfiniteUpperLimit, new Import("com.google.common", Optional.of("18.1")).importVersionRange());
assertEquals(rangeWithInfiniteUpperLimit, new Import("com.google.common.foo", Optional.of("18.1")).importVersionRange());
@@ -72,32 +71,29 @@ public class ImportPackageTest {
}
@Test
- public void require_that_none_version_gives_non_version_range() {
+ void require_that_none_version_gives_non_version_range() {
assertTrue(new Import("foo", Optional.empty()).importVersionRange().isEmpty());
}
- @SuppressWarnings("deprecation")
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
@Test
- public void require_that_exception_is_thrown_when_major_component_is_non_numeric() {
- expectedException.expect(IllegalArgumentException.class);
- new Import("foo", Optional.of("1notValid.2"));
+ void require_that_exception_is_thrown_when_major_component_is_non_numeric() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new Import("foo", Optional.of("1notValid.2"));
+ });
}
@Test
- public void require_that_osgi_import_supports_missing_version() {
+ void require_that_osgi_import_supports_missing_version() {
assertEquals("com.yahoo.exported", new Import("com.yahoo.exported", Optional.empty()).asOsgiImport());
}
@Test
- public void require_that_osgi_import_version_range_includes_all_versions_from_the_current_up_to_the_next_major_version() {
+ void require_that_osgi_import_version_range_includes_all_versions_from_the_current_up_to_the_next_major_version() {
assertEquals("com.yahoo.exported;version=\"[1.2,2)\"", new Import("com.yahoo.exported", Optional.of("1.2")).asOsgiImport());
}
@Test
- public void require_that_osgi_import_version_range_ignores_qualifier() {
+ void require_that_osgi_import_version_range_ignores_qualifier() {
assertEquals("com.yahoo.exported;version=\"[1.2.3,2)\"", new Import("com.yahoo.exported", Optional.of("1.2.3.qualifier")).asOsgiImport());
}
diff --git a/bundle-plugin/src/test/java/com/yahoo/container/plugin/util/TestBundleDependencyScopeTranslatorTest.java b/bundle-plugin/src/test/java/com/yahoo/container/plugin/util/TestBundleDependencyScopeTranslatorTest.java
index ada2f8d208a..d20bbe0e073 100644
--- a/bundle-plugin/src/test/java/com/yahoo/container/plugin/util/TestBundleDependencyScopeTranslatorTest.java
+++ b/bundle-plugin/src/test/java/com/yahoo/container/plugin/util/TestBundleDependencyScopeTranslatorTest.java
@@ -5,7 +5,7 @@ package com.yahoo.container.plugin.util;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.DefaultArtifact;
import org.apache.maven.artifact.handler.DefaultArtifactHandler;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
@@ -14,7 +14,7 @@ import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bjorncs
@@ -24,7 +24,7 @@ public class TestBundleDependencyScopeTranslatorTest {
private static final String GROUP_ID = "com.test";
@Test
- public void test_dependencies_are_translated_to_compile_scope_by_default() {
+ void test_dependencies_are_translated_to_compile_scope_by_default() {
Set<Artifact> artifacts = new TreeSet<>();
Artifact a = createArtifact(artifacts, "a", "test", List.of());
Artifact aa = createArtifact(artifacts, "a-a", "test", List.of("a"));
@@ -40,7 +40,7 @@ public class TestBundleDependencyScopeTranslatorTest {
}
@Test
- public void non_test_scope_dependencies_keep_original_scope() {
+ void non_test_scope_dependencies_keep_original_scope() {
Set<Artifact> artifacts = new TreeSet<>();
Artifact a = createArtifact(artifacts, "a", "provided", List.of());
Artifact aa = createArtifact(artifacts, "a-a", "provided", List.of("a"));
@@ -61,14 +61,14 @@ public class TestBundleDependencyScopeTranslatorTest {
}
@Test
- public void ordering_in_config_string_determines_translation() {
+ void ordering_in_config_string_determines_translation() {
Set<Artifact> artifacts = new TreeSet<>();
Artifact a = createArtifact(artifacts, "a", "test", List.of());
Artifact aa = createArtifact(artifacts, "a-a", "test", List.of("a"));
{
String configString =
"com.test:a-a:runtime," +
- "com.test:a:test,";
+ "com.test:a:test,";
TestBundleDependencyScopeTranslator translator = TestBundleDependencyScopeTranslator.from(artifacts, configString);
assertScope(translator, a, "test");
assertScope(translator, aa, "runtime");
@@ -76,7 +76,7 @@ public class TestBundleDependencyScopeTranslatorTest {
{
String configString =
"com.test:a:test," +
- "com.test:a-a:runtime";
+ "com.test:a-a:runtime";
TestBundleDependencyScopeTranslator translator = TestBundleDependencyScopeTranslator.from(artifacts, configString);
assertScope(translator, a, "test");
assertScope(translator, aa, "test");
@@ -84,7 +84,7 @@ public class TestBundleDependencyScopeTranslatorTest {
}
@Test
- public void transitive_non_test_dependencies_of_test_dependencies_keep_original_scope() {
+ void transitive_non_test_dependencies_of_test_dependencies_keep_original_scope() {
Set<Artifact> artifacts = new TreeSet<>();
Artifact a = createArtifact(artifacts, "a", "test", List.of());
Artifact aa = createArtifact(artifacts, "a-a", "test", List.of("a"));
@@ -108,7 +108,7 @@ public class TestBundleDependencyScopeTranslatorTest {
}
@Test
- public void different_classifiers_are_handled_separately() {
+ void different_classifiers_are_handled_separately() {
Set<Artifact> artifacts = new TreeSet<>();
Artifact a = createArtifact(artifacts, "a", "test", List.of());
Artifact ab = createArtifact(artifacts, "a-b", "provided", List.of("a"));
diff --git a/client/js/app/README.md b/client/js/app/README.md
new file mode 100644
index 00000000000..c3a9e2cac50
--- /dev/null
+++ b/client/js/app/README.md
@@ -0,0 +1,11 @@
+<!-- Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. -->
+
+# Vespa client
+
+This app is work in progress
+
+# Client install and start
+
+ nvm install --lts node # in case your current node.js is too old
+ yarn install
+ yarn dev # then open link, like http://127.0.0.1:3000/
diff --git a/client/js/app/src/app/main.jsx b/client/js/app/src/app/main.jsx
index 96514d419e1..08f86115d40 100644
--- a/client/js/app/src/app/main.jsx
+++ b/client/js/app/src/app/main.jsx
@@ -1,9 +1,12 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import { App } from 'app/app';
+import { ResponseProvider } from './pages/querybuilder/Components/Contexts/ResponseContext';
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
- <App />
+ <ResponseProvider>
+ <App />
+ </ResponseProvider>
</React.StrictMode>
);
diff --git a/client/js/app/src/app/pages/querybuilder/Components/Buttons/CopyResponseButton.jsx b/client/js/app/src/app/pages/querybuilder/Components/Buttons/CopyResponseButton.jsx
new file mode 100644
index 00000000000..d01daa7b0d6
--- /dev/null
+++ b/client/js/app/src/app/pages/querybuilder/Components/Buttons/CopyResponseButton.jsx
@@ -0,0 +1,40 @@
+import React, { useContext, useState } from 'react';
+import OverlayImageButton from './OverlayImageButton';
+
+import copyImage from '../../assets/img/copy.svg';
+import { ResponseContext } from '../Contexts/ResponseContext';
+import { OverlayTrigger, Tooltip } from 'react-bootstrap';
+
+export default function CopyResponseButton() {
+ const { response } = useContext(ResponseContext);
+ const [show, setShow] = useState(false);
+
+ const handleCopy = () => {
+ setShow(true);
+ navigator.clipboard.writeText(response);
+ setTimeout(() => {
+ setShow(false);
+ }, 2000);
+ };
+
+ return (
+ <OverlayTrigger
+ placement="left-end"
+ show={show}
+ overlay={
+ <Tooltip id="copy-tooltip">Response copied to clipboard</Tooltip>
+ }
+ >
+ <span>
+ <OverlayImageButton
+ className="intro-copy"
+ image={copyImage}
+ height="30"
+ width="30"
+ tooltip="Copy"
+ onClick={handleCopy}
+ />
+ </span>
+ </OverlayTrigger>
+ );
+}
diff --git a/client/js/app/src/app/pages/querybuilder/Components/Buttons/DownloadJSONButton.jsx b/client/js/app/src/app/pages/querybuilder/Components/Buttons/DownloadJSONButton.jsx
new file mode 100644
index 00000000000..7ec6683afa3
--- /dev/null
+++ b/client/js/app/src/app/pages/querybuilder/Components/Buttons/DownloadJSONButton.jsx
@@ -0,0 +1,44 @@
+import React, { useContext } from 'react';
+import { ResponseContext } from '../Contexts/ResponseContext';
+import transform from '../../TransformVespaTrace';
+import SimpleButton from './SimpleButton';
+
+export default function DownloadJSONButton({ children }) {
+ const { response } = useContext(ResponseContext);
+
+ const transformResponse = (response) => {
+ return transform(response);
+ };
+
+ const handleClick = () => {
+ if (response != '') {
+ let transformedResponse = JSON.stringify(
+ transformResponse(JSON.parse(response), undefined, '\t')
+ );
+ // copied from safakeskin´s answer on SO, link: https://stackoverflow.com/questions/55613438/reactwrite-to-json-file-or-export-download-no-server
+ const fileName = 'vespa-response';
+ const blob = new Blob([transformedResponse], {
+ type: 'application/json',
+ });
+ const href = URL.createObjectURL(blob);
+
+ // create "a" HTLM element with href to file
+ const link = document.createElement('a');
+ link.href = href;
+ link.download = fileName + '.json';
+ document.body.appendChild(link);
+ link.click();
+
+ // clean up "a" element & remove ObjectURL
+ document.body.removeChild(link);
+ URL.revokeObjectURL(href);
+
+ // open Jaeger in a new tab
+ window.open('http://localhost:16686/search', '__blank');
+ } else {
+ alert('Response was empty');
+ }
+ };
+
+ return <SimpleButton onClick={handleClick}>{children}</SimpleButton>;
+}
diff --git a/client/js/app/src/app/pages/querybuilder/Components/Buttons/OverlayImageButton.jsx b/client/js/app/src/app/pages/querybuilder/Components/Buttons/OverlayImageButton.jsx
index 2cb9c7d6e9a..788d88fd0e6 100644
--- a/client/js/app/src/app/pages/querybuilder/Components/Buttons/OverlayImageButton.jsx
+++ b/client/js/app/src/app/pages/querybuilder/Components/Buttons/OverlayImageButton.jsx
@@ -36,5 +36,3 @@ export default function OverlayImageButton({
</OverlayTrigger>
);
}
-
-//
diff --git a/client/js/app/src/app/pages/querybuilder/Components/Buttons/PasteJSONButton.jsx b/client/js/app/src/app/pages/querybuilder/Components/Buttons/PasteJSONButton.jsx
index 73dce637500..df380c62fa1 100644
--- a/client/js/app/src/app/pages/querybuilder/Components/Buttons/PasteJSONButton.jsx
+++ b/client/js/app/src/app/pages/querybuilder/Components/Buttons/PasteJSONButton.jsx
@@ -4,18 +4,22 @@ import pasteImage from '../../assets/img/paste.svg';
import { QueryInputContext } from '../Contexts/QueryInputContext';
export default function PasteJSONButton() {
- const { inputs, setInputs, id, setId, levelZeroParameters, childMap } =
+ const { setInputs, setId, levelZeroParameters, childMap } =
useContext(QueryInputContext);
const [paste, setPaste] = useState(false);
- const handleClick = (e) => {
- alert('Button is non-functional');
- // setPaste(true);
- // window.addEventListener('paste', handlePaste)
+ //TODO: fix that the second-level dropdowns do not get set properly when pasting a JSON query
+
+ const handleClick = () => {
+ setPaste(true);
+ window.addEventListener('paste', handlePaste);
};
const handlePaste = (e) => {
setPaste(false);
+ // Stop data actually being pasted into div
+ e.stopPropagation();
+ e.preventDefault();
const pastedData = e.clipboardData.getData('text');
alert('Converting JSON: \n\n ' + pastedData);
window.removeEventListener('paste', handlePaste);
@@ -25,37 +29,51 @@ export default function PasteJSONButton() {
const convertPastedJSON = (pastedData) => {
try {
var json = JSON.parse(pastedData);
- setId(1);
- const newInputs = buildFromJSON(json, id);
+ const newInputs = buildFromJSON(json, 2);
setInputs(newInputs);
} catch (error) {
+ console.log(error);
alert('Could not parse JSON, with error-message: \n\n' + error.message);
}
};
- const buildFromJSON = (json, id) => {
+ const buildFromJSON = (json, id, parentTypeof) => {
let newInputs = [];
let keys = Object.keys(json);
for (let i = 0; i < keys.length; i++) {
let childId = 1;
- let newInput = { id: id, type: keys[i] };
- if (json[keys[i]] === Object) {
+ let newInput = { id: `${id}`, type: keys[i] };
+ //If the value for the key is a child object
+ if (typeof json[keys[i]] === 'object') {
newInput['typeof'] = 'Parent';
newInput['input'] = '';
newInput['hasChildren'] = true;
+ // Construct the id of the correct pattern
let tempId = id + '.' + childId;
childId += 1;
- newInput['children'] = buildFromJSON(json[keys[i]], tempId);
+ let type;
+ if (id.length > 1) {
+ //Used to get the correct value from childMap
+ type = parentTypeof + '_' + keys[i];
+ } else {
+ type = keys[i];
+ }
+ newInput['children'] = buildFromJSON(json[keys[i]], tempId, type);
} else {
- newInput['typeof'] = levelZeroParameters[keys[i]].type;
+ if (id.length > 1) {
+ const choices = childMap[parentTypeof];
+ newInput['typeof'] = choices[keys[i]].type;
+ } else {
+ newInput['typeof'] = levelZeroParameters[keys[i]].type;
+ }
newInput['input'] = json[keys[i]];
newInput['hasChildren'] = false;
newInput['children'] = [];
}
- setId(id + 1);
- console.log(newInput);
+ id += 1;
newInputs.push(newInput);
}
+ setId(id);
return newInputs;
};
@@ -65,7 +83,7 @@ export default function PasteJSONButton() {
id="pasteJSON"
className="pasteJSON"
image={pasteImage}
- style={{ marginTop: '-2px', marginRight: '3px' }}
+ //style={{ marginTop: '-2px', marginRight: '3px' }}
onClick={handleClick}
>
{paste ? 'Press CMD + V' : 'Paste JSON'}
diff --git a/client/js/app/src/app/pages/querybuilder/Components/Contexts/QueryInputContext.jsx b/client/js/app/src/app/pages/querybuilder/Components/Contexts/QueryInputContext.jsx
index 064bf51795b..bc21ea81d9a 100644
--- a/client/js/app/src/app/pages/querybuilder/Components/Contexts/QueryInputContext.jsx
+++ b/client/js/app/src/app/pages/querybuilder/Components/Contexts/QueryInputContext.jsx
@@ -20,6 +20,7 @@ export const QueryInputProvider = (prop) => {
},
searchChain: { name: 'searchChain', type: 'String', hasChildren: false },
timeout: { name: 'timeout', type: 'Float', hasChildren: false },
+ trace: { name: 'trace', type: 'Parent', hasChildren: true },
tracelevel: { name: 'tracelevel', type: 'Parent', hasChildren: true },
traceLevel: { name: 'traceLevel', type: 'Integer', hasChildren: false },
explainLevel: { name: 'explainLevel', type: 'Integer', hasChildren: false },
diff --git a/client/js/app/src/app/pages/querybuilder/Components/Text/QueryDropDownForm.jsx b/client/js/app/src/app/pages/querybuilder/Components/Text/QueryDropDownForm.jsx
index d9a3417752c..88bd545282a 100644
--- a/client/js/app/src/app/pages/querybuilder/Components/Text/QueryDropDownForm.jsx
+++ b/client/js/app/src/app/pages/querybuilder/Components/Text/QueryDropDownForm.jsx
@@ -1,8 +1,13 @@
+import React, { useContext, useState } from 'react';
import { QueryInputContext } from '../Contexts/QueryInputContext';
-import React, { useCallback, useContext, useState } from 'react';
import SimpleDropDownForm from './SimpleDropDownForm';
-export default function QueryDropdownForm({ choices, id, child = false }) {
+export default function QueryDropdownForm({
+ choices,
+ id,
+ child = false,
+ initial,
+}) {
const {
inputs,
setInputs,
@@ -28,6 +33,8 @@ export default function QueryDropdownForm({ choices, id, child = false }) {
let parentTypes = newInputs[index].type;
let children = newInputs[index].children;
let childChoices = childMap[parentTypes];
+ //TODO: try to rafactor this loop into a separate function that can be
+ //used everywhere in the code similar loops are used
for (let i = 3; i < id.length; i += 2) {
currentId = id.substring(0, i);
index = children.findIndex((element) => element.id === currentId);
@@ -62,6 +69,7 @@ export default function QueryDropdownForm({ choices, id, child = false }) {
onChange={updateType}
choices={choices}
value={choice}
+ initial={initial}
></SimpleDropDownForm>
);
}
diff --git a/client/js/app/src/app/pages/querybuilder/Components/Text/QueryInput.jsx b/client/js/app/src/app/pages/querybuilder/Components/Text/QueryInput.jsx
index c5410ae7c4a..bd41edd6008 100644
--- a/client/js/app/src/app/pages/querybuilder/Components/Text/QueryInput.jsx
+++ b/client/js/app/src/app/pages/querybuilder/Components/Text/QueryInput.jsx
@@ -8,7 +8,7 @@ import AddPropertyButton from '../Buttons/AddPropertyButton';
import QueryInputChild from './QueryInputChild';
export default function QueryInput() {
- const { inputs, setInputs, levelZeroParameters, childMap } =
+ const { inputs, setInputs, levelZeroParameters } =
useContext(QueryInputContext);
function removeRow(id) {
@@ -36,8 +36,12 @@ export default function QueryInput() {
const inputList = inputs.map((value) => {
return (
- <div key={value.id} id={value.id} className="queryinput">
- <QueryDropdownForm choices={levelZeroParameters} id={value.id} />
+ <div key={value.id + value.typeof} id={value.id} className="queryinput">
+ <QueryDropdownForm
+ choices={levelZeroParameters}
+ id={value.id}
+ initial={value.type}
+ />
{value.hasChildren ? (
<>
<AddPropertyButton id={value.id} />
@@ -49,6 +53,7 @@ export default function QueryInput() {
size="30"
onChange={updateInput}
placeholder={setPlaceholder(value.id)}
+ initial={value.input}
/>
)}
<OverlayTrigger
diff --git a/client/js/app/src/app/pages/querybuilder/Components/Text/QueryInputChild.jsx b/client/js/app/src/app/pages/querybuilder/Components/Text/QueryInputChild.jsx
index 0440d6ef1ba..4ab2a074214 100644
--- a/client/js/app/src/app/pages/querybuilder/Components/Text/QueryInputChild.jsx
+++ b/client/js/app/src/app/pages/querybuilder/Components/Text/QueryInputChild.jsx
@@ -94,10 +94,14 @@ export default function QueryInputChild({ id }) {
const inputList = childArray.map((child) => {
return (
<div key={child.id} id={child.id}>
+ {
+ //child.id == '4.1' && console.log(child.type)
+ }
<QueryDropdownForm
choices={childMap[currentTypes]}
id={child.id}
child={true}
+ inital={child.type}
/>
{child.hasChildren ? (
<>
@@ -109,6 +113,7 @@ export default function QueryInputChild({ id }) {
size="30"
onChange={updateInput}
placeholder={setPlaceHolder(child.id)}
+ inital={child.input}
/>
)}
<OverlayTrigger
@@ -150,6 +155,7 @@ function Child({ child, type, onChange, placeholder, removeRow }) {
choices={childMap[type]}
id={child.id}
child={true}
+ initial={child.type}
/>
{child.hasChildren ? (
<>
@@ -161,6 +167,7 @@ function Child({ child, type, onChange, placeholder, removeRow }) {
size="30"
onChange={onChange}
placeholder={placeholder(child.id)}
+ initial={child.input}
/>
)}
<OverlayTrigger
diff --git a/client/js/app/src/app/pages/querybuilder/Components/Text/ResponseBox.jsx b/client/js/app/src/app/pages/querybuilder/Components/Text/ResponseBox.jsx
index 08c65238434..dac98271965 100644
--- a/client/js/app/src/app/pages/querybuilder/Components/Text/ResponseBox.jsx
+++ b/client/js/app/src/app/pages/querybuilder/Components/Text/ResponseBox.jsx
@@ -1,4 +1,4 @@
-import React, { useContext, useEffect, useState } from 'react';
+import React, { useContext } from 'react';
import { ResponseContext } from '../Contexts/ResponseContext';
export default function ResponseBox() {
diff --git a/client/js/app/src/app/pages/querybuilder/Components/Text/SendQuery.jsx b/client/js/app/src/app/pages/querybuilder/Components/Text/SendQuery.jsx
index 9ee370de7c9..a3714f27fb5 100644
--- a/client/js/app/src/app/pages/querybuilder/Components/Text/SendQuery.jsx
+++ b/client/js/app/src/app/pages/querybuilder/Components/Text/SendQuery.jsx
@@ -1,10 +1,10 @@
import React, { useContext, useEffect, useState } from 'react';
-import SimpleDropDownForm from './SimpleDropDownForm';
import SimpleButton from '../Buttons/SimpleButton';
-import SimpleForm from './SimpleForm';
import { QueryInputContext } from '../Contexts/QueryInputContext';
import { ResponseContext } from '../Contexts/ResponseContext';
import { QueryContext } from '../Contexts/QueryContext';
+import SimpleForm from './SimpleForm';
+import SimpleDropDownForm from './SimpleDropDownForm';
export default function SendQuery() {
const { inputs } = useContext(QueryInputContext);
@@ -65,15 +65,12 @@ export default function SendQuery() {
case 'Integer':
case 'Long':
return parseInt(input);
- break;
case 'Float':
return parseFloat(input);
- break;
case 'Boolean':
return input.toLowerCase() === 'true' ? true : false;
- break;
default:
return input;
diff --git a/client/js/app/src/app/pages/querybuilder/Components/Text/SimpleDropDownForm.jsx b/client/js/app/src/app/pages/querybuilder/Components/Text/SimpleDropDownForm.jsx
index 01288cea44f..94c6c01b619 100644
--- a/client/js/app/src/app/pages/querybuilder/Components/Text/SimpleDropDownForm.jsx
+++ b/client/js/app/src/app/pages/querybuilder/Components/Text/SimpleDropDownForm.jsx
@@ -7,10 +7,11 @@ export default function SimpleDropDownForm({
className = 'input',
onChange,
value,
+ initial,
}) {
const { selectedItems } = useContext(QueryInputContext);
- //FIXME: using the filtered list to render options results in dropdown not changing the displayed selection to what was actually selected.
+ //TODO: using the filtered list to render options results in dropdown not changing the displayed selection to what was actually selected.
let filtered = Object.keys(choices).filter(
(choice) => !selectedItems.includes(choice)
);
@@ -30,7 +31,12 @@ export default function SimpleDropDownForm({
return (
<form id={id}>
- <select className={className} id={id} value={value} onChange={onChange}>
+ <select
+ className={className}
+ id={id}
+ defaultValue={initial}
+ onChange={onChange}
+ >
{options}
</select>
</form>
diff --git a/client/js/app/src/app/pages/querybuilder/TransformVespaTrace.jsx b/client/js/app/src/app/pages/querybuilder/TransformVespaTrace.jsx
new file mode 100644
index 00000000000..a6981b8a521
--- /dev/null
+++ b/client/js/app/src/app/pages/querybuilder/TransformVespaTrace.jsx
@@ -0,0 +1,345 @@
+let traceID = '';
+let processes = {};
+let output = {};
+let traceStartTimestamp = 0;
+let topSpanId = '';
+let parentID = '';
+
+// Generates a random hex string of size "size"
+const genRanHex = (size) =>
+ [...Array(size)]
+ .map(() => Math.floor(Math.random() * 16).toString(16))
+ .join('');
+
+export default function transform(trace) {
+ traceID = genRanHex(32);
+ output = { data: [{ traceID: traceID, spans: [], processes: {} }] };
+ let data = output['data'][0]['spans'];
+ processes = output['data'][0]['processes'];
+ processes.p0 = { serviceName: 'Query', tags: [] };
+ let temp = trace['trace']['children'];
+ let spans = findChildren(temp);
+ traceStartTimestamp = findTraceStartTime(spans);
+ topSpanId = genRanHex(16);
+ let topSpanFirstHalf = createNewSpan(traceStartTimestamp)[0];
+ data.push(topSpanFirstHalf);
+
+ const retrieved = findLogsAndChildren(spans, topSpanFirstHalf);
+ const logs = retrieved['logs'];
+ const children = retrieved['children'];
+ traverseLogs(logs);
+ createChildren(children);
+
+ return output;
+}
+
+function findLogsAndChildren(spans, topSpanFirstHalf) {
+ let logs = [];
+ let children = [];
+ let data = output['data'][0]['spans'];
+ //let hitQuery = false;
+ //let topSpanSecondHalf = createNewSpan();
+ //let secondHalfDuration = 0;
+ //output['data'][0]['spans'].push(topSpanSecondHalf);
+ //let firstHitSecondHalf = true;
+ for (let i = 0; i < spans.length - 1; i++) {
+ if (spans[i].hasOwnProperty('children')) {
+ let a = spans[i]['timestamp'];
+ topSpanFirstHalf = createNewSpan(traceStartTimestamp + a);
+ //firstHitSecondHalf = true;
+ //topSpanSecondHalf = createNewSpan();
+ //output['data'][0]['spans'].push(topSpanSecondHalf);
+ let log = [];
+ for (let x of spans[i]['children']) {
+ if (Array.isArray(x['message'])) {
+ if (log.length > 0) {
+ // finished moving down the search chain
+ // create a new array for holding the logs that represent moving up the search chain
+ logs.push(log);
+ log = [];
+ }
+ //hitQuery = true;
+ children.push(x['message']);
+ } else {
+ // only add logs with a timestamp
+ if (x.hasOwnProperty('timestamp')) {
+ log.push(x);
+ }
+ }
+ }
+ logs.push(log);
+ } else if (
+ spans[i].hasOwnProperty('message') &&
+ spans[i].hasOwnProperty('timestamp')
+ ) {
+ let span = createNewSpan(0, 0, 'p0', spans[i]['message'], [
+ {
+ refType: 'CHILD_OF',
+ traceID: traceID,
+ spanID: topSpanFirstHalf['spanID'],
+ },
+ ])[0];
+ data.push(span);
+ span['startTime'] = traceStartTimestamp + spans[i]['timestamp'] * 1000;
+ let duration;
+ if (i === spans.length - 1) {
+ duration = 1;
+ } else {
+ duration = (spans[i + 1]['timestamp'] - spans[i]['timestamp']) * 1000;
+ duration = duration === 0 ? 1 : duration;
+ }
+ topSpanFirstHalf['duration'] = topSpanFirstHalf['duration'] + duration;
+ span['duration'] = duration;
+ // if (hitQuery) {
+ // if (firstHitSecondHalf) {
+ // secondHalfDuration = span['timestamp'] * 1000;
+ // topSpanSecondHalf['startTime'] =
+ // traceStartTimestamp + secondHalfDuration;
+ // firstHitSecondHalf = false;
+ // }
+ // topSpanSecondHalf['duration'] =
+ // span['timestamp'] * 1000 - secondHalfDuration;
+ // topSpanSecondHalf['logs'].push({
+ // timestamp: traceStartTimestamp + span['timestamp'] * 1000,
+ // fields: [{ key: 'message', type: 'string', value: span['message'] }],
+ // });
+ // } else {
+ // topSpanFirstHalf['duration'] = span['timestamp'] * 1000;
+ // topSpanFirstHalf['logs'].push({
+ // timestamp: traceStartTimestamp + span['timestamp'] * 1000,
+ // fields: [{ key: 'message', type: 'string', value: span['message'] }],
+ // });
+ // }
+ }
+ }
+ return { logs: logs, children: children };
+}
+
+function traverseLogs(logs) {
+ let first = true;
+ let data = output['data'][0]['spans'];
+ for (let log of logs) {
+ let logStartTimestamp = traceStartTimestamp + log[0]['timestamp'] * 1000;
+ let logDuration =
+ (log[log.length - 1]['timestamp'] - log[0]['timestamp']) * 1000;
+ if (logDuration === 0) {
+ logDuration = 1;
+ }
+ let spanID = genRanHex(16);
+ if (first) {
+ parentID = spanID;
+ first = false;
+ }
+ let temp = createNewSpan(
+ logStartTimestamp,
+ logDuration,
+ 'p0',
+ 'test'
+ //[{ refType: 'CHILD_OF', traceID: traceID, spanID: topSpanId }]
+ );
+ let childSpan = temp[0];
+ let childSpanID = temp[1];
+ data.push(childSpan);
+ for (let i = 0; i < log.length - 1; i++) {
+ if (log[i].hasOwnProperty('message')) {
+ let logPointStart = traceStartTimestamp + log[i]['timestamp'] * 1000;
+ let logPointDuration;
+ if (i > log.length - 1) {
+ logPointDuration = 1;
+ } else {
+ logPointDuration =
+ (log[i + 1]['timestamp'] - log[i]['timestamp']) * 1000;
+ logPointDuration = logPointDuration === 0 ? 1 : logPointDuration;
+ }
+ let logSpan = createNewSpan(
+ logPointStart,
+ logPointDuration,
+ 'p0',
+ log[i]['message'],
+ [{ refType: 'CHILD_OF', traceID: traceID, spanID: childSpanID }]
+ )[0];
+ data.push(logSpan);
+ // childSpan['logs'].push({
+ // timestamp: traceStartTimestamp + log[i]['timestamp'] * 1000,
+ // fields: [
+ // { key: 'message', type: 'string', value: log[i]['message'] },
+ // ],
+ // });
+ }
+ }
+ }
+}
+
+function createChildren(children) {
+ for (let i = 0; i < children.length; i++) {
+ let child = children[i][0];
+ let processKey = `p${i + 1}`;
+ processes[processKey] = { serviceName: `Span${i}`, tags: [] };
+ let spanID = genRanHex(16);
+ let data = output['data'][0]['spans'];
+ let startTimestamp = Date.parse(child['start_time']) * 1000;
+ let newSpan = {
+ traceID: traceID,
+ spanID: spanID,
+ operationName: `query${i}`,
+ startTime: startTimestamp,
+ duration: child['duration_ms'] * 1000,
+ references: [{ refType: 'CHILD_OF', traceID: traceID, spanID: parentID }],
+ tags: [],
+ logs: [],
+ processID: processKey,
+ };
+ data.push(newSpan);
+ let traces = child['traces'];
+ for (let k = 0; k < traces.length; k++) {
+ let trace = traces[k];
+ let traceTimestamp = trace['timestamp_ms'];
+ let events;
+ let firstEvent;
+ let duration;
+ if (trace['tag'] === 'query_execution') {
+ events = trace['threads'][0]['traces'];
+ firstEvent = events[0];
+ duration = (traceTimestamp - firstEvent['timestamp_ms']) * 1000;
+ } else if (trace['tag'] === 'query_execution_plan') {
+ events = [];
+ let nextTrace = traces[k + 1];
+ firstEvent = trace;
+ // query execution plan has no events, duration must therefore be found using the next trace
+ if (nextTrace['tag'] === 'query_execution') {
+ duration =
+ (nextTrace['threads'][0]['traces'][0]['timestamp_ms'] -
+ traceTimestamp) *
+ 1000;
+ } else {
+ duration = (nextTrace['timestamp_ms'] - traceTimestamp) * 1000;
+ }
+ } else {
+ events = trace['traces'];
+ firstEvent = events[0];
+ duration = (traceTimestamp - firstEvent['timestamp_ms']) * 1000;
+ }
+ let childSpanID = genRanHex(16);
+ let childSpan = {
+ traceID: traceID,
+ spanID: childSpanID,
+ operationName: trace['tag'],
+ startTime: startTimestamp + firstEvent['timestamp_ms'] * 1000,
+ duration: duration,
+ references: [{ refType: 'CHILD_OF', traceID: traceID, spanID: spanID }],
+ tags: [],
+ logs: [],
+ processID: processKey,
+ };
+ data.push(childSpan);
+ if (events.length > 0) {
+ for (let j = 0; j < events.length; j++) {
+ let event = events[j];
+ let eventID = genRanHex(16);
+ let eventStart = event['timestamp_ms'];
+ let operationName;
+ if (event.hasOwnProperty('event')) {
+ operationName = event['event'];
+ if (
+ operationName === 'Complete query setup' ||
+ operationName === 'MatchThread::run Done'
+ ) {
+ duration = (traceTimestamp - eventStart) * 1000;
+ } else {
+ duration = (events[j + 1]['timestamp_ms'] - eventStart) * 1000;
+ }
+ } else {
+ operationName = event['tag'];
+ duration = (events[j + 1]['timestamp_ms'] - eventStart) * 1000;
+ }
+ let eventSpan = {
+ traceID: traceID,
+ spanID: eventID,
+ operationName: operationName,
+ startTime: startTimestamp + eventStart * 1000,
+ duration: duration,
+ references: [
+ { refType: 'CHILD_OF', traceID: traceID, spanID: childSpanID },
+ ],
+ tags: [],
+ logs: [],
+ processID: processKey,
+ };
+ data.push(eventSpan);
+ }
+ }
+ }
+ }
+}
+
+function findChildren(traces) {
+ for (let trace of traces) {
+ if (trace.hasOwnProperty('children')) {
+ return trace['children'];
+ }
+ }
+}
+
+// Get an estimated start time by using the start time of the query and subtracting the current run time
+function getTraceStartTime(trace) {
+ if (Array.isArray(trace['message'])) {
+ let timestamp = Date.parse(trace['message'][0]['start_time']) * 1000;
+ let currentTimestamp = trace['timestamp'] * 1000;
+ return timestamp - currentTimestamp;
+ }
+}
+
+function findTraceStartTime(spans) {
+ let startTime = 0;
+ for (let span of spans) {
+ if (span.hasOwnProperty('children')) {
+ startTime = findTraceStartTime(span['children']);
+ } else if (span.hasOwnProperty('message')) {
+ if (Array.isArray(span['message'])) {
+ return getTraceStartTime(span);
+ }
+ }
+ if (startTime !== 0) {
+ return startTime;
+ }
+ }
+ return startTime;
+}
+
+//TODO: remove if not needed later
+function findDuration(spans) {
+ let notFound = true;
+ let duration = 0;
+ let i = spans.length - 1;
+ while (notFound && i >= 0) {
+ if (spans[i].hasOwnProperty('timestamp')) {
+ duration = spans[i]['timestamp'];
+ notFound = false;
+ } else {
+ i--;
+ }
+ }
+ return duration;
+}
+
+function createNewSpan(
+ startTime = 0,
+ duration = 0,
+ processID = 'p0',
+ operationName = 'Complete',
+ references = []
+) {
+ let spanID = genRanHex(16);
+ let newSpan = {
+ traceID: traceID,
+ spanID: spanID,
+ operationName: operationName,
+ startTime: startTime,
+ duration: duration,
+ references: references,
+ tags: [],
+ logs: [],
+ processID: processID,
+ };
+ return [newSpan, spanID];
+}
diff --git a/client/js/app/src/app/pages/querybuilder/query-builder.jsx b/client/js/app/src/app/pages/querybuilder/query-builder.jsx
index 472ec1efe49..42a4ed829c3 100644
--- a/client/js/app/src/app/pages/querybuilder/query-builder.jsx
+++ b/client/js/app/src/app/pages/querybuilder/query-builder.jsx
@@ -1,27 +1,19 @@
-import React, { useContext } from 'react';
-import SimpleButton from './Components/Buttons/SimpleButton';
+import React from 'react';
import QueryInput from './Components/Text/QueryInput';
import TextBox from './Components/Text/TextBox';
-import ImageButton from './Components/Buttons/ImageButton';
-import OverlayImageButton from './Components/Buttons/OverlayImageButton';
import AddQueryInput from './Components/Buttons/AddQueryInputButton';
import { QueryInputProvider } from './Components/Contexts/QueryInputContext';
import SendQuery from './Components/Text/SendQuery';
-import {
- ResponseContext,
- ResponseProvider,
-} from './Components/Contexts/ResponseContext';
+import { ResponseProvider } from './Components/Contexts/ResponseContext';
import ResponseBox from './Components/Text/ResponseBox';
-
-import copyImage from './assets/img/copy.svg';
-
-import '../../styles/agency.css';
-import '../../styles/vespa.css';
import ShowQueryButton from './Components/Buttons/ShowQueryButton';
import { QueryProvider } from './Components/Contexts/QueryContext';
import PasteJSONButton from './Components/Buttons/PasteJSONButton';
+import CopyResponseButton from './Components/Buttons/CopyResponseButton';
+import DownloadJSONButton from './Components/Buttons/DownloadJSONButton';
-//import 'bootstrap/dist/css/bootstrap.min.css'; //TODO: Find out how to get this css
+import '../../styles/agency.css';
+import '../../styles/vespa.css';
export function QueryBuilder() {
return (
@@ -49,19 +41,9 @@ export function QueryBuilder() {
</QueryProvider>
<TextBox className="response">Response</TextBox>
<ResponseBox />
+ <CopyResponseButton />
+ <DownloadJSONButton>Download response as JSON</DownloadJSONButton>
</ResponseProvider>
- <OverlayImageButton
- className="intro-copy"
- image={copyImage}
- height="30"
- width="30"
- tooltip="Copy"
- onClick={() => {
- alert('Button is non-functional');
- }}
- >
- Copy
- </OverlayImageButton>
<br />
<br />
</div>
diff --git a/client/js/app/src/app/pages/querytracer/query-tracer.jsx b/client/js/app/src/app/pages/querytracer/query-tracer.jsx
index 94c293d37ed..c700b73ebba 100644
--- a/client/js/app/src/app/pages/querytracer/query-tracer.jsx
+++ b/client/js/app/src/app/pages/querytracer/query-tracer.jsx
@@ -1,6 +1,26 @@
-import React from 'react';
+import React, { useContext } from 'react';
+import DownloadJSONButton from '../querybuilder/Components/Buttons/DownloadJSONButton';
+import { ResponseContext } from '../querybuilder/Components/Contexts/ResponseContext';
import { Container } from 'app/components';
export function QueryTracer() {
- return <Container>query tracer</Container>;
+ const { response, setResponse } = useContext(ResponseContext);
+
+ const updateResponse = (e) => {
+ setResponse(e.target.value);
+ };
+
+ return (
+ <Container>
+ <textarea
+ cols="70"
+ rows="25"
+ value={response}
+ onChange={updateResponse}
+ ></textarea>
+ <DownloadJSONButton>
+ Convert to Jeager format and download trace
+ </DownloadJSONButton>
+ </Container>
+ );
}
diff --git a/cloud-tenant-base-dependencies-enforcer/pom.xml b/cloud-tenant-base-dependencies-enforcer/pom.xml
index 8f9dbd59019..1a83afd1be5 100644
--- a/cloud-tenant-base-dependencies-enforcer/pom.xml
+++ b/cloud-tenant-base-dependencies-enforcer/pom.xml
@@ -45,7 +45,7 @@
<jetty.version>9.4.48.v20220622</jetty.version>
<jetty-alpn.version>1.1.3.v20160715</jetty-alpn.version>
<org.lz4.version>1.8.0</org.lz4.version>
- <org.json.version>20090211</org.json.version>
+ <org.json.version>20220320</org.json.version>
<slf4j.version>1.7.32</slf4j.version> <!-- WARNING: when updated, also update c.y.v.tenant:base pom -->
<xml-apis.version>1.4.01</xml-apis.version>
</properties>
@@ -219,7 +219,7 @@
<include>org.eclipse.jetty:jetty-util:[${jetty.version}]:jar:test</include>
<include>org.hamcrest:hamcrest-core:1.3:jar:test</include>
<include>org.hdrhistogram:HdrHistogram:2.1.8:jar:test</include>
- <include>org.json:json:20090211:jar:test</include>
+ <include>org.json:json:${org.json.version}:jar:test</include>
<include>org.junit.jupiter:junit-jupiter-api:[${junit5.version}]:jar:test</include>
<include>org.junit.jupiter:junit-jupiter-engine:[${junit5.version}]:jar:test</include>
<include>org.junit.platform:junit-platform-commons:[${junit5.platform.version}]:jar:test</include>
diff --git a/clustercontroller-apps/pom.xml b/clustercontroller-apps/pom.xml
index fa0f5c064ad..8a3fa2da811 100644
--- a/clustercontroller-apps/pom.xml
+++ b/clustercontroller-apps/pom.xml
@@ -13,21 +13,16 @@
<packaging>container-plugin</packaging>
<dependencies>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>com.yahoo.vespa</groupId>
<artifactId>container-dev</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
- <exclusions>
- <exclusion>
- <groupId>org.antlr</groupId>
- <artifactId>antlr4-runtime</artifactId>
- </exclusion>
- </exclusions>
+ <exclusions>
+ <exclusion>
+ <groupId>org.antlr</groupId>
+ <artifactId>antlr4-runtime</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>com.yahoo.vespa</groupId>
@@ -58,6 +53,16 @@
<artifactId>jettison</artifactId>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
+ </dependency>
</dependencies>
<build>
<plugins>
diff --git a/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apps/clustercontroller/ClusterControllerClusterConfigurerTest.java b/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apps/clustercontroller/ClusterControllerClusterConfigurerTest.java
index dda18fc3396..7c5913774c3 100644
--- a/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apps/clustercontroller/ClusterControllerClusterConfigurerTest.java
+++ b/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apps/clustercontroller/ClusterControllerClusterConfigurerTest.java
@@ -6,19 +6,19 @@ import com.yahoo.cloud.config.ZookeepersConfig;
import com.yahoo.jdisc.Metric;
import com.yahoo.vespa.config.content.FleetcontrollerConfig;
import com.yahoo.vespa.config.content.StorDistributionConfig;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
public class ClusterControllerClusterConfigurerTest {
@Test
- public void testSimple() throws Exception {
+ void testSimple() throws Exception {
ClusterController controller = new ClusterController();
StorDistributionConfig.Builder distributionConfig = new StorDistributionConfig.Builder();
StorDistributionConfig.Group.Builder group = new StorDistributionConfig.Group.Builder();
@@ -45,13 +45,17 @@ public class ClusterControllerClusterConfigurerTest {
zookeepersConfig.zookeeperserverlist("foo");
Metric metric = new Metric() {
@Override
- public void set(String s, Number number, Context context) {}
+ public void set(String s, Number number, Context context) {
+ }
@Override
- public void add(String s, Number number, Context context) {}
+ public void add(String s, Number number, Context context) {
+ }
@Override
- public Context createContext(Map<String, ?> stringMap) { return null; }
+ public Context createContext(Map<String, ?> stringMap) {
+ return null;
+ }
};
- // Used in standalone mode to get config without a cluster controller instance
+ // Used in standalone mode to get config without a cluster controller instance
ClusterControllerClusterConfigurer configurer = new ClusterControllerClusterConfigurer(
null,
new StorDistributionConfig(distributionConfig),
@@ -68,7 +72,7 @@ public class ClusterControllerClusterConfigurerTest {
assertEquals(0.7, configurer.getOptions().clusterFeedBlockLimit.get("bar"), 0.01);
assertEquals(0.05, configurer.getOptions().clusterFeedBlockNoiseLevel, 0.001);
- try{
+ try {
zookeepersConfig.zookeeperserverlist("");
new ClusterControllerClusterConfigurer(
controller,
diff --git a/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apps/clustercontroller/ClusterControllerTest.java b/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apps/clustercontroller/ClusterControllerTest.java
index 2c33f781737..cfda92b472d 100644
--- a/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apps/clustercontroller/ClusterControllerTest.java
+++ b/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apps/clustercontroller/ClusterControllerTest.java
@@ -5,17 +5,17 @@ import com.yahoo.jdisc.Metric;
import com.yahoo.vdslib.distribution.ConfiguredNode;
import com.yahoo.vespa.clustercontroller.core.FleetController;
import com.yahoo.vespa.clustercontroller.core.FleetControllerOptions;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
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.assertNull;
-import static org.junit.Assert.assertTrue;
+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.assertTrue;
/**
* Doesn't really test cluster controller, but runs some lines of code.
@@ -34,7 +34,7 @@ public class ClusterControllerTest {
public Context createContext(Map<String, ?> stringMap) { return null; }
};
- @Before
+ @BeforeEach
public void setUp() {
options = new FleetControllerOptions("storage", Set.of(new ConfiguredNode(0, false)));
options.zooKeeperServerAddress = null;
@@ -43,7 +43,7 @@ public class ClusterControllerTest {
}
@Test
- public void testSimple() throws Exception {
+ void testSimple() throws Exception {
ClusterController cc = new ClusterController();
cc.setOptions(options, metric);
cc.setOptions(options, metric);
@@ -57,7 +57,7 @@ public class ClusterControllerTest {
}
@Test
- public void testShutdownException() throws Exception {
+ void testShutdownException() throws Exception {
ClusterController cc = new ClusterController() {
void shutdownController(FleetController controller) throws Exception {
throw new Exception("Foo");
diff --git a/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apps/clustercontroller/StateRestApiV2HandlerTest.java b/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apps/clustercontroller/StateRestApiV2HandlerTest.java
index bf759e3dc76..7146d95e7ba 100644
--- a/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apps/clustercontroller/StateRestApiV2HandlerTest.java
+++ b/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apps/clustercontroller/StateRestApiV2HandlerTest.java
@@ -3,17 +3,17 @@ package com.yahoo.vespa.clustercontroller.apps.clustercontroller;
import com.yahoo.cloud.config.ClusterInfoConfig;
import com.yahoo.vespa.clustercontroller.core.restapiv2.ClusterControllerStateRestAPI;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Map;
import java.util.TreeMap;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class StateRestApiV2HandlerTest {
@Test
- public void testNoMatchingSockets() {
+ void testNoMatchingSockets() {
ClusterController controller = new ClusterController();
ClusterInfoConfig config = new ClusterInfoConfig(
new ClusterInfoConfig.Builder().clusterId("cluster-id").nodeCount(1));
@@ -22,7 +22,7 @@ public class StateRestApiV2HandlerTest {
}
@Test
- public void testMappingOfIndexToClusterControllers() {
+ void testMappingOfIndexToClusterControllers() {
ClusterInfoConfig.Builder builder = new ClusterInfoConfig.Builder()
.clusterId("cluster-id")
.nodeCount(1)
diff --git a/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apps/clustercontroller/StatusHandlerTest.java b/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apps/clustercontroller/StatusHandlerTest.java
index 7a204aa791d..d4eb84677dc 100644
--- a/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apps/clustercontroller/StatusHandlerTest.java
+++ b/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apps/clustercontroller/StatusHandlerTest.java
@@ -1,12 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.clustercontroller.apps.clustercontroller;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
public class StatusHandlerTest {
@Test
- public void testSimple() {
+ void testSimple() {
ClusterController controller = new ClusterController();
StatusHandler handler = new StatusHandler(controller, StatusHandler.testContext());
}
diff --git a/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apputil/communication/http/JDiscHttpRequestHandlerTest.java b/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apputil/communication/http/JDiscHttpRequestHandlerTest.java
index 6a27228feab..19a5a2a60f9 100644
--- a/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apputil/communication/http/JDiscHttpRequestHandlerTest.java
+++ b/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apputil/communication/http/JDiscHttpRequestHandlerTest.java
@@ -2,15 +2,15 @@
package com.yahoo.vespa.clustercontroller.apputil.communication.http;
import com.yahoo.vespa.clustercontroller.utils.communication.http.HttpRequest;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
-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;
/**
* The handler is mostly tested through the apache tests, using it as endpoint here..
@@ -20,7 +20,7 @@ public class JDiscHttpRequestHandlerTest {
private ThreadPoolExecutor executor;
- @Before
+ @BeforeEach
public void setUp() {
executor = new ThreadPoolExecutor(10, 100, 100, TimeUnit.SECONDS, new ArrayBlockingQueue<>(1000));
}
@@ -30,8 +30,8 @@ public class JDiscHttpRequestHandlerTest {
}
@Test
- public void testInvalidMethod() throws Exception {
- try{
+ void testInvalidMethod() throws Exception {
+ try {
HttpRequest request = new HttpRequest();
JDiscHttpRequestHandler.setOperation(request, com.yahoo.jdisc.http.HttpRequest.Method.CONNECT);
fail("Control should not reach here");
@@ -41,7 +41,7 @@ public class JDiscHttpRequestHandlerTest {
}
@Test
- public void testNothingButAddCoverage() throws Exception {
+ void testNothingButAddCoverage() throws Exception {
new JDiscHttpRequestHandler.EmptyCompletionHandler().failed(null);
}
}
diff --git a/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apputil/communication/http/JDiscMetricWrapperTest.java b/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apputil/communication/http/JDiscMetricWrapperTest.java
index e7c8301cfca..a62437d1a8f 100644
--- a/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apputil/communication/http/JDiscMetricWrapperTest.java
+++ b/clustercontroller-apps/src/test/java/com/yahoo/vespa/clustercontroller/apputil/communication/http/JDiscMetricWrapperTest.java
@@ -2,12 +2,12 @@
package com.yahoo.vespa.clustercontroller.apputil.communication.http;
import com.yahoo.jdisc.Metric;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Map;
-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 JDiscMetricWrapperTest {
@@ -22,10 +22,10 @@ public class JDiscMetricWrapperTest {
++calls;
return new Context() {};
}
- };
+ }
@Test
- public void testSimple() {
+ void testSimple() {
MetricImpl impl1 = new MetricImpl();
MetricImpl impl2 = new MetricImpl();
JDiscMetricWrapper wrapper = new JDiscMetricWrapper(impl1);
diff --git a/clustercontroller-core/pom.xml b/clustercontroller-core/pom.xml
index 243b69bf1e2..dbd7e14a8f6 100644
--- a/clustercontroller-core/pom.xml
+++ b/clustercontroller-core/pom.xml
@@ -27,8 +27,8 @@
<scope>provided</scope>
</dependency>
<dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
@@ -38,13 +38,14 @@
<scope>test</scope>
</dependency>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
- <artifactId>mockito-core</artifactId>
+ <artifactId>mockito-junit-jupiter</artifactId>
+ <version>${mockito.version}</version>
<scope>test</scope>
</dependency>
<dependency>
@@ -53,6 +54,16 @@
<scope>test</scope>
</dependency>
<dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
<groupId>org.codehaus.jettison</groupId>
<artifactId>jettison</artifactId>
</dependency>
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/AggregatedStatsMergePendingCheckerTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/AggregatedStatsMergePendingCheckerTest.java
index dece8019e2c..b12f37e092d 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/AggregatedStatsMergePendingCheckerTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/AggregatedStatsMergePendingCheckerTest.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.clustercontroller.core;
-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;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -52,43 +52,43 @@ public class AggregatedStatsMergePendingCheckerTest {
}
@Test
- public void unknown_content_node_may_have_merges_pending() {
+ void unknown_content_node_may_have_merges_pending() {
Fixture f = Fixture.fromBucketsPending(1);
assertTrue(f.mayHaveMergesPending("default", 2));
}
@Test
- public void unknown_bucket_space_has_no_merges_pending() {
+ void unknown_bucket_space_has_no_merges_pending() {
Fixture f = Fixture.fromBucketsPending(1);
assertFalse(f.mayHaveMergesPending("global", 1));
}
@Test
- public void valid_bucket_space_stats_can_have_no_merges_pending() {
+ void valid_bucket_space_stats_can_have_no_merges_pending() {
Fixture f = Fixture.fromBucketsPending(0);
assertFalse(f.mayHaveMergesPending("default", 1));
}
@Test
- public void valid_bucket_space_stats_may_have_merges_pending() {
+ void valid_bucket_space_stats_may_have_merges_pending() {
Fixture f = Fixture.fromBucketsPending(1);
assertTrue(f.mayHaveMergesPending("default", 1));
}
@Test
- public void invalid_bucket_space_stats_may_have_merges_pending() {
+ void invalid_bucket_space_stats_may_have_merges_pending() {
Fixture f = Fixture.fromInvalidBucketStats();
assertTrue(f.mayHaveMergesPending("default", 1));
}
@Test
- public void cluster_without_updates_from_all_distributors_may_have_merges_pending() {
+ void cluster_without_updates_from_all_distributors_may_have_merges_pending() {
Fixture f = Fixture.fromIncompleteStats();
assertTrue(f.mayHaveMergesPending("default", 1));
}
@Test
- public void min_merge_completion_ratio_is_used_when_calculating_may_have_merges_pending() {
+ void min_merge_completion_ratio_is_used_when_calculating_may_have_merges_pending() {
// Completion ratio is (5-3)/5 = 0.4
assertTrue(Fixture.fromBucketsPending(3, 0.6).mayHaveMergesPending("default", 1));
// Completion ratio is (5-2)/5 = 0.6
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterFeedBlockTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterFeedBlockTest.java
index f0b91102e8f..ec6255fd13b 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterFeedBlockTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterFeedBlockTest.java
@@ -10,8 +10,8 @@ import com.yahoo.vdslib.state.State;
import com.yahoo.vespa.clustercontroller.core.database.DatabaseHandler;
import com.yahoo.vespa.clustercontroller.core.database.ZooKeeperDatabaseFactory;
import com.yahoo.vespa.clustercontroller.utils.util.NoMetricReporter;
-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.HashSet;
@@ -22,10 +22,10 @@ import java.util.Set;
import static com.yahoo.vespa.clustercontroller.core.FeedBlockUtil.mapOf;
import static com.yahoo.vespa.clustercontroller.core.FeedBlockUtil.setOf;
import static com.yahoo.vespa.clustercontroller.core.FeedBlockUtil.usage;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static com.yahoo.vespa.clustercontroller.core.FeedBlockUtil.createResourceUsageJson;
-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.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
public class ClusterFeedBlockTest extends FleetControllerTest {
@@ -36,7 +36,7 @@ public class ClusterFeedBlockTest extends FleetControllerTest {
private FleetController ctrl;
private DummyCommunicator communicator;
- @Before
+ @BeforeEach
public void setUp() {
supervisor = new Supervisor(new Transport());
}
@@ -107,7 +107,7 @@ public class ClusterFeedBlockTest extends FleetControllerTest {
}
@Test
- public void cluster_feed_can_be_blocked_and_unblocked_by_single_node() throws Exception {
+ void cluster_feed_can_be_blocked_and_unblocked_by_single_node() throws Exception {
initialize(createOptions(mapOf(usage("cheese", 0.7), usage("wine", 0.4))));
assertFalse(ctrl.getClusterStateBundle().clusterFeedIsBlocked());
@@ -127,7 +127,7 @@ public class ClusterFeedBlockTest extends FleetControllerTest {
}
@Test
- public void cluster_feed_block_state_is_recomputed_when_options_are_updated() throws Exception {
+ void cluster_feed_block_state_is_recomputed_when_options_are_updated() throws Exception {
initialize(createOptions(mapOf(usage("cheese", 0.7), usage("wine", 0.4))));
assertFalse(ctrl.getClusterStateBundle().clusterFeedIsBlocked());
@@ -142,7 +142,7 @@ public class ClusterFeedBlockTest extends FleetControllerTest {
}
@Test
- public void cluster_feed_block_state_is_recomputed_when_resource_block_set_differs() throws Exception {
+ void cluster_feed_block_state_is_recomputed_when_resource_block_set_differs() throws Exception {
initialize(createOptions(mapOf(usage("cheese", 0.7), usage("wine", 0.4))));
assertFalse(ctrl.getClusterStateBundle().clusterFeedIsBlocked());
@@ -155,12 +155,12 @@ public class ClusterFeedBlockTest extends FleetControllerTest {
bundle = ctrl.getClusterStateBundle();
assertTrue(bundle.clusterFeedIsBlocked());
assertEquals("cheese on node 1 [unknown hostname] (0.800 > 0.700), " +
- "wine on node 1 [unknown hostname] (0.500 > 0.400)",
- bundle.getFeedBlock().get().getDescription());
+ "wine on node 1 [unknown hostname] (0.500 > 0.400)",
+ bundle.getFeedBlock().get().getDescription());
}
@Test
- public void cluster_feed_block_state_is_not_recomputed_when_only_resource_usage_levels_differ() throws Exception {
+ void cluster_feed_block_state_is_not_recomputed_when_only_resource_usage_levels_differ() throws Exception {
initialize(createOptions(mapOf(usage("cheese", 0.7), usage("wine", 0.4))));
assertFalse(ctrl.getClusterStateBundle().clusterFeedIsBlocked());
@@ -177,7 +177,7 @@ public class ClusterFeedBlockTest extends FleetControllerTest {
}
@Test
- public void cluster_feed_block_state_is_recomputed_when_usage_enters_hysteresis_range() throws Exception {
+ void cluster_feed_block_state_is_recomputed_when_usage_enters_hysteresis_range() throws Exception {
initialize(createOptions(mapOf(usage("cheese", 0.7), usage("wine", 0.4)), 0.1));
assertFalse(ctrl.getClusterStateBundle().clusterFeedIsBlocked());
@@ -193,22 +193,22 @@ public class ClusterFeedBlockTest extends FleetControllerTest {
// is not discovered here. Still correct in terms of what resources are blocked or not, but
// the description is not up to date here.
assertEquals("cheese on node 1 [unknown hostname] (0.750 > 0.700)",
- bundle.getFeedBlock().get().getDescription());
+ bundle.getFeedBlock().get().getDescription());
// Trigger an explicit recompute by adding a separate resource exhaustion
reportResourceUsageFromNode(1, setOf(usage("cheese", 0.67), usage("wine", 0.5)));
bundle = ctrl.getClusterStateBundle();
assertTrue(bundle.clusterFeedIsBlocked());
assertEquals("cheese on node 1 [unknown hostname] (0.670 > 0.600), " +
- "wine on node 1 [unknown hostname] (0.500 > 0.400)", // Not under hysteresis
- bundle.getFeedBlock().get().getDescription());
+ "wine on node 1 [unknown hostname] (0.500 > 0.400)", // Not under hysteresis
+ bundle.getFeedBlock().get().getDescription());
// Wine usage drops beyond hysteresis range, should be unblocked immediately.
reportResourceUsageFromNode(1, setOf(usage("cheese", 0.61), usage("wine", 0.2)));
bundle = ctrl.getClusterStateBundle();
assertTrue(bundle.clusterFeedIsBlocked());
assertEquals("cheese on node 1 [unknown hostname] (0.610 > 0.600)",
- bundle.getFeedBlock().get().getDescription());
+ bundle.getFeedBlock().get().getDescription());
// Cheese now drops below hysteresis range, should be unblocked as well.
reportResourceUsageFromNode(1, setOf(usage("cheese", 0.59), usage("wine", 0.2)));
@@ -217,7 +217,7 @@ public class ClusterFeedBlockTest extends FleetControllerTest {
}
@Test
- public void unavailable_nodes_are_not_considered_when_computing_feed_blocked_state() throws Exception {
+ void unavailable_nodes_are_not_considered_when_computing_feed_blocked_state() throws Exception {
initialize(createOptions(mapOf(usage("cheese", 0.7), usage("wine", 0.4)), 0.1));
assertFalse(ctrl.getClusterStateBundle().clusterFeedIsBlocked());
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStateBundleTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStateBundleTest.java
index d12541687f0..17c461a487b 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStateBundleTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStateBundleTest.java
@@ -6,7 +6,7 @@ import com.yahoo.vdslib.state.Node;
import com.yahoo.vdslib.state.NodeState;
import com.yahoo.vdslib.state.NodeType;
import com.yahoo.vdslib.state.State;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Set;
import java.util.function.Function;
@@ -15,9 +15,7 @@ import static com.yahoo.vespa.clustercontroller.core.FeedBlockUtil.exhaustion;
import static com.yahoo.vespa.clustercontroller.core.FeedBlockUtil.setOf;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
-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.*;
public class ClusterStateBundleTest {
@@ -67,7 +65,7 @@ public class ClusterStateBundleTest {
}
@Test
- public void builder_creates_baseline_state_and_derived_state_per_space() {
+ void builder_creates_baseline_state_and_derived_state_per_space() {
ClusterStateBundle bundle = createTestBundle();
assertThat(bundle.getBaselineClusterState(), equalTo(stateOf("distributor:2 storage:2")));
assertThat(bundle.getDerivedBucketSpaceStates().size(), equalTo(3));
@@ -77,7 +75,7 @@ public class ClusterStateBundleTest {
}
@Test
- public void version_clone_sets_version_for_all_spaces() {
+ void version_clone_sets_version_for_all_spaces() {
ClusterStateBundle bundle = createTestBundle().clonedWithVersionSet(123);
assertThat(bundle.getBaselineClusterState(), equalTo(stateOf("version:123 distributor:2 storage:2")));
assertThat(bundle.getDerivedBucketSpaceStates().size(), equalTo(3));
@@ -87,13 +85,13 @@ public class ClusterStateBundleTest {
}
@Test
- public void same_bundle_instance_considered_similar() {
+ void same_bundle_instance_considered_similar() {
ClusterStateBundle bundle = createTestBundle();
assertTrue(bundle.similarTo(bundle));
}
@Test
- public void similarity_test_considers_all_bucket_spaces() {
+ void similarity_test_considers_all_bucket_spaces() {
ClusterStateBundle bundle = createTestBundle(false);
ClusterStateBundle unchangedBundle = createTestBundle(false);
@@ -106,7 +104,7 @@ public class ClusterStateBundleTest {
}
@Test
- public void similarity_test_considers_cluster_feed_block_state() {
+ void similarity_test_considers_cluster_feed_block_state() {
var nonBlockingBundle = createTestBundle(false);
var blockingBundle = createTestBundleWithFeedBlock("foo");
var blockingBundleWithOtherDesc = createTestBundleWithFeedBlock("bar");
@@ -119,7 +117,7 @@ public class ClusterStateBundleTest {
}
@Test
- public void similarity_test_considers_cluster_feed_block_concrete_exhaustion_set() {
+ void similarity_test_considers_cluster_feed_block_concrete_exhaustion_set() {
var blockingBundleNoSet = createTestBundleWithFeedBlock("foo");
var blockingBundleWithSet = createTestBundleWithFeedBlock("bar", setOf(exhaustion(1, "beer"), exhaustion(1, "wine")));
var blockingBundleWithOtherSet = createTestBundleWithFeedBlock("bar", setOf(exhaustion(1, "beer"), exhaustion(1, "soda")));
@@ -132,7 +130,7 @@ public class ClusterStateBundleTest {
}
@Test
- public void feed_block_state_is_available() {
+ void feed_block_state_is_available() {
var nonBlockingBundle = createTestBundle(false);
var blockingBundle = createTestBundleWithFeedBlock("foo");
@@ -147,14 +145,14 @@ public class ClusterStateBundleTest {
}
@Test
- public void toString_without_bucket_space_states_prints_only_baseline_state() {
+ void toString_without_bucket_space_states_prints_only_baseline_state() {
ClusterStateBundle bundle = ClusterStateBundle.ofBaselineOnly(
annotatedStateOf("distributor:2 storage:2"));
assertThat(bundle.toString(), equalTo("ClusterStateBundle('distributor:2 storage:2')"));
}
@Test
- public void toString_includes_all_bucket_space_states() {
+ void toString_includes_all_bucket_space_states() {
ClusterStateBundle bundle = createTestBundle();
assertThat(bundle.toString(), equalTo("ClusterStateBundle('distributor:2 storage:2', " +
"default 'distributor:2 storage:2 .0.s:d', " +
@@ -163,7 +161,7 @@ public class ClusterStateBundleTest {
}
@Test
- public void toString_with_feed_blocked_includes_description() {
+ void toString_with_feed_blocked_includes_description() {
var blockingBundle = createTestBundleWithFeedBlock("bear sleeping on server rack");
assertThat(blockingBundle.toString(), equalTo("ClusterStateBundle('distributor:2 storage:2', " +
"default 'distributor:2 storage:2', " +
@@ -173,19 +171,19 @@ public class ClusterStateBundleTest {
}
@Test
- public void toString_without_derived_states_specifies_deferred_activation_iff_set() {
+ void toString_without_derived_states_specifies_deferred_activation_iff_set() {
var bundle = ClusterStateBundle.ofBaselineOnly(annotatedStateOf("distributor:2 storage:2"), null, true);
assertThat(bundle.toString(), equalTo("ClusterStateBundle('distributor:2 storage:2' (deferred activation))"));
}
@Test
- public void toString_without_derived_states_does_not_specify_deferred_activation_iff_not_set() {
+ void toString_without_derived_states_does_not_specify_deferred_activation_iff_not_set() {
var bundle = ClusterStateBundle.ofBaselineOnly(annotatedStateOf("distributor:2 storage:2"), null, false);
assertThat(bundle.toString(), equalTo("ClusterStateBundle('distributor:2 storage:2')"));
}
@Test
- public void toString_with_derived_states_specifies_deferred_activation_iff_set() {
+ void toString_with_derived_states_specifies_deferred_activation_iff_set() {
var bundle = createTestBundleBuilder(true).deferredActivation(true).deriveAndBuild();
assertThat(bundle.toString(), equalTo("ClusterStateBundle('distributor:2 storage:2', " +
"default 'distributor:2 storage:2 .0.s:d', " +
@@ -194,7 +192,7 @@ public class ClusterStateBundleTest {
}
@Test
- public void toString_with_derived_states_does_not_specify_deferred_activation_iff_not_set() {
+ void toString_with_derived_states_does_not_specify_deferred_activation_iff_not_set() {
var bundle = createTestBundleBuilder(true).deferredActivation(false).deriveAndBuild();
assertThat(bundle.toString(), equalTo("ClusterStateBundle('distributor:2 storage:2', " +
"default 'distributor:2 storage:2 .0.s:d', " +
@@ -203,25 +201,25 @@ public class ClusterStateBundleTest {
}
@Test
- public void deferred_activation_is_disabled_by_default() {
+ void deferred_activation_is_disabled_by_default() {
ClusterStateBundle bundle = createTestBundle();
assertFalse(bundle.deferredActivation());
}
@Test
- public void can_build_bundle_with_deferred_activation_enabled() {
+ void can_build_bundle_with_deferred_activation_enabled() {
var bundle = createTestBundleBuilder(false).deferredActivation(true).deriveAndBuild();
assertTrue(bundle.deferredActivation());
}
@Test
- public void can_build_bundle_with_deferred_activation_disabled() {
+ void can_build_bundle_with_deferred_activation_disabled() {
var bundle = createTestBundleBuilder(false).deferredActivation(false).deriveAndBuild();
assertFalse(bundle.deferredActivation());
}
@Test
- public void simple_bundle_without_derived_states_propagates_deferred_activation_flag() {
+ void simple_bundle_without_derived_states_propagates_deferred_activation_flag() {
var bundle = ClusterStateBundle
.builder(annotatedStateOf("distributor:2 storage:2"))
.deferredActivation(true) // defaults to false
@@ -230,22 +228,23 @@ public class ClusterStateBundleTest {
}
@Test
- public void cloning_preserves_false_deferred_activation_flag() {
+ void cloning_preserves_false_deferred_activation_flag() {
var bundle = createTestBundleBuilder(true).deferredActivation(false).deriveAndBuild();
var derived = bundle.cloneWithMapper(Function.identity());
assertEquals(bundle, derived);
}
@Test
- public void cloning_preserves_true_deferred_activation_flag() {
+ void cloning_preserves_true_deferred_activation_flag() {
var bundle = createTestBundleBuilder(true).deferredActivation(true).deriveAndBuild();
var derived = bundle.cloneWithMapper(Function.identity());
assertEquals(bundle, derived);
}
@Test
- public void cloning_preserves_feed_block_state() {
- var bundle = createTestBundleWithFeedBlock("foo");;
+ void cloning_preserves_feed_block_state() {
+ var bundle = createTestBundleWithFeedBlock("foo");
+ ;
var derived = bundle.cloneWithMapper(Function.identity());
assertEquals(bundle, derived);
}
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStateGeneratorTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStateGeneratorTest.java
index f857bfcee89..78911c414a2 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStateGeneratorTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStateGeneratorTest.java
@@ -6,7 +6,7 @@ import com.yahoo.vdslib.state.Node;
import com.yahoo.vdslib.state.NodeState;
import com.yahoo.vdslib.state.NodeType;
import com.yahoo.vdslib.state.State;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Optional;
import java.util.Set;
@@ -30,7 +30,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void cluster_with_all_nodes_reported_down_has_state_down() {
+ void cluster_with_all_nodes_reported_down_has_state_down() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(6).markEntireClusterDown();
final AnnotatedClusterState state = generateFromFixtureWithDefaultParams(fixture);
@@ -41,7 +41,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void cluster_with_all_nodes_up_state_correct_distributor_and_storage_count() {
+ void cluster_with_all_nodes_up_state_correct_distributor_and_storage_count() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(6).bringEntireClusterUp();
final AnnotatedClusterState state = generateFromFixtureWithDefaultParams(fixture);
@@ -49,7 +49,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void distributor_reported_states_reflected_in_generated_state() {
+ void distributor_reported_states_reflected_in_generated_state() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(9)
.bringEntireClusterUp()
.reportDistributorNodeState(2, State.DOWN)
@@ -61,7 +61,7 @@ public class ClusterStateGeneratorTest {
// NOTE: initializing state tested separately since it involves init progress state info
@Test
- public void storage_reported_states_reflected_in_generated_state() {
+ void storage_reported_states_reflected_in_generated_state() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(9)
.bringEntireClusterUp()
.reportStorageNodeState(0, State.DOWN)
@@ -72,7 +72,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void worse_distributor_wanted_state_overrides_reported_state() {
+ void worse_distributor_wanted_state_overrides_reported_state() {
// Maintenance mode is illegal for distributors and therefore not tested
final ClusterFixture fixture = ClusterFixture.forFlatCluster(7)
.bringEntireClusterUp()
@@ -85,7 +85,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void worse_storage_wanted_state_overrides_reported_state() {
+ void worse_storage_wanted_state_overrides_reported_state() {
// Does not test all maintenance mode overrides; see maintenance_mode_overrides_reported_state
// for that.
final ClusterFixture fixture = ClusterFixture.forFlatCluster(7)
@@ -100,7 +100,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void better_distributor_wanted_state_does_not_override_reported_state() {
+ void better_distributor_wanted_state_does_not_override_reported_state() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(7)
.bringEntireClusterUp()
.reportDistributorNodeState(0, State.DOWN)
@@ -111,7 +111,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void better_storage_wanted_state_does_not_override_reported_state() {
+ void better_storage_wanted_state_does_not_override_reported_state() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(7)
.bringEntireClusterUp()
.reportStorageNodeState(1, State.DOWN)
@@ -130,7 +130,7 @@ public class ClusterStateGeneratorTest {
* directly from Maintenance -> Up.
*/
@Test
- public void retired_node_in_init_state_is_set_to_maintenance() {
+ void retired_node_in_init_state_is_set_to_maintenance() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(3)
.bringEntireClusterUp()
.reportStorageNodeState(1, State.INITIALIZING)
@@ -152,7 +152,7 @@ public class ClusterStateGeneratorTest {
* value and triggering on a sufficiently low value.
*/
@Test
- public void storage_node_in_init_mode_while_listing_buckets_is_marked_down() {
+ void storage_node_in_init_mode_while_listing_buckets_is_marked_down() {
final NodeState initWhileListingBuckets = new NodeState(NodeType.STORAGE, State.INITIALIZING);
initWhileListingBuckets.setInitProgress(0.0f);
@@ -169,7 +169,7 @@ public class ClusterStateGeneratorTest {
* is set to Maintenance.
*/
@Test
- public void implicit_down_while_listing_buckets_does_not_override_wanted_state() {
+ void implicit_down_while_listing_buckets_does_not_override_wanted_state() {
final NodeState initWhileListingBuckets = new NodeState(NodeType.STORAGE, State.INITIALIZING);
initWhileListingBuckets.setInitProgress(0.0f);
@@ -183,7 +183,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void distributor_nodes_in_init_mode_are_not_mapped_to_down() {
+ void distributor_nodes_in_init_mode_are_not_mapped_to_down() {
final NodeState initWhileListingBuckets = new NodeState(NodeType.DISTRIBUTOR, State.INITIALIZING);
initWhileListingBuckets.setInitProgress(0.0f);
@@ -199,7 +199,7 @@ public class ClusterStateGeneratorTest {
* Maintenance mode overrides all reported states, even Down.
*/
@Test
- public void maintenance_mode_wanted_state_overrides_reported_state() {
+ void maintenance_mode_wanted_state_overrides_reported_state() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(7)
.bringEntireClusterUp()
.proposeStorageNodeWantedState(0, State.MAINTENANCE)
@@ -215,7 +215,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void wanted_state_description_carries_over_to_generated_state() {
+ void wanted_state_description_carries_over_to_generated_state() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(7)
.bringEntireClusterUp()
.proposeStorageNodeWantedState(1, State.MAINTENANCE, "foo")
@@ -230,7 +230,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void config_retired_mode_is_reflected_in_generated_state() {
+ void config_retired_mode_is_reflected_in_generated_state() {
ClusterFixture fixture = ClusterFixture.forFlatCluster(5)
.markNodeAsConfigRetired(2)
.bringEntireClusterUp();
@@ -241,7 +241,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void config_retired_mode_is_overridden_by_worse_wanted_state() {
+ void config_retired_mode_is_overridden_by_worse_wanted_state() {
ClusterFixture fixture = ClusterFixture.forFlatCluster(5)
.markNodeAsConfigRetired(2)
.markNodeAsConfigRetired(3)
@@ -279,17 +279,17 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void reported_down_node_within_transition_time_has_maintenance_generated_state() {
+ void reported_down_node_within_transition_time_has_maintenance_generated_state() {
do_test_change_within_node_transition_time_window_generates_maintenance(State.DOWN);
}
@Test
- public void reported_stopping_node_within_transition_time_has_maintenance_generated_state() {
+ void reported_stopping_node_within_transition_time_has_maintenance_generated_state() {
do_test_change_within_node_transition_time_window_generates_maintenance(State.STOPPING);
}
@Test
- public void reported_node_down_after_transition_time_has_down_generated_state() {
+ void reported_node_down_after_transition_time_has_down_generated_state() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(5).bringEntireClusterUp();
final ClusterStateGenerator.Params params = fixture.generatorParams()
.currentTimeInMilllis(11_000)
@@ -306,7 +306,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void distributor_nodes_are_not_implicitly_transitioned_to_maintenance_mode() {
+ void distributor_nodes_are_not_implicitly_transitioned_to_maintenance_mode() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(5).bringEntireClusterUp();
final ClusterStateGenerator.Params params = fixture.generatorParams()
.currentTimeInMilllis(10_000)
@@ -323,7 +323,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void transient_maintenance_mode_does_not_override_wanted_down_state() {
+ void transient_maintenance_mode_does_not_override_wanted_down_state() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(5).bringEntireClusterUp();
final ClusterStateGenerator.Params params = fixture.generatorParams()
.currentTimeInMilllis(10_000)
@@ -340,7 +340,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void reported_down_retired_node_within_transition_time_transitions_to_maintenance() {
+ void reported_down_retired_node_within_transition_time_transitions_to_maintenance() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(5).bringEntireClusterUp();
final ClusterStateGenerator.Params params = fixture.generatorParams()
.currentTimeInMilllis(10_000)
@@ -356,7 +356,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void crash_count_exceeding_limit_marks_node_as_down() {
+ void crash_count_exceeding_limit_marks_node_as_down() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(5).bringEntireClusterUp();
final ClusterStateGenerator.Params params = fixture.generatorParams().maxPrematureCrashes(10);
@@ -368,7 +368,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void crash_count_not_exceeding_limit_does_not_mark_node_as_down() {
+ void crash_count_not_exceeding_limit_does_not_mark_node_as_down() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(5).bringEntireClusterUp();
final ClusterStateGenerator.Params params = fixture.generatorParams().maxPrematureCrashes(10);
@@ -380,7 +380,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void exceeded_crash_count_does_not_override_wanted_maintenance_state() {
+ void exceeded_crash_count_does_not_override_wanted_maintenance_state() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(5)
.bringEntireClusterUp()
.proposeStorageNodeWantedState(1, State.MAINTENANCE);
@@ -395,7 +395,7 @@ public class ClusterStateGeneratorTest {
// Stopping -> Down is expected and does not indicate an unstable node.
@Test
- public void transition_from_controlled_stop_to_down_does_not_add_to_crash_counter() {
+ void transition_from_controlled_stop_to_down_does_not_add_to_crash_counter() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(2)
.bringEntireClusterUp()
.reportStorageNodeState(1, State.STOPPING, "controlled shutdown") // urgh, string matching logic
@@ -405,7 +405,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void non_observed_storage_node_start_timestamp_is_included_in_state() {
+ void non_observed_storage_node_start_timestamp_is_included_in_state() {
final NodeState nodeState = new NodeState(NodeType.STORAGE, State.UP);
// A reported state timestamp that is not yet marked as observed in the NodeInfo
// for the same node is considered not observed by other nodes and must therefore
@@ -421,7 +421,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void non_observed_distributor_start_timestamp_is_included_in_state() {
+ void non_observed_distributor_start_timestamp_is_included_in_state() {
final NodeState nodeState = new NodeState(NodeType.DISTRIBUTOR, State.UP);
nodeState.setStartTimestamp(6000);
@@ -434,7 +434,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void fully_observed_storage_node_timestamp_not_included_in_state() {
+ void fully_observed_storage_node_timestamp_not_included_in_state() {
final NodeState nodeState = new NodeState(NodeType.STORAGE, State.UP);
nodeState.setStartTimestamp(5000);
@@ -450,7 +450,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void fully_observed_distributor_timestamp_not_included_in_state() {
+ void fully_observed_distributor_timestamp_not_included_in_state() {
final NodeState nodeState = new NodeState(NodeType.DISTRIBUTOR, State.UP);
nodeState.setStartTimestamp(6000);
@@ -466,7 +466,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void cluster_down_if_less_than_min_count_of_storage_nodes_available() {
+ void cluster_down_if_less_than_min_count_of_storage_nodes_available() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(3)
.bringEntireClusterUp()
.reportStorageNodeState(0, State.DOWN)
@@ -479,7 +479,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void cluster_not_down_if_more_than_min_count_of_storage_nodes_are_available() {
+ void cluster_not_down_if_more_than_min_count_of_storage_nodes_are_available() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(3)
.bringEntireClusterUp()
.reportStorageNodeState(0, State.DOWN);
@@ -491,7 +491,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void cluster_down_if_less_than_min_count_of_distributors_available() {
+ void cluster_down_if_less_than_min_count_of_distributors_available() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(3)
.bringEntireClusterUp()
.reportDistributorNodeState(0, State.DOWN)
@@ -504,7 +504,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void cluster_not_down_if_more_than_min_count_of_distributors_are_available() {
+ void cluster_not_down_if_more_than_min_count_of_distributors_are_available() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(3)
.bringEntireClusterUp()
.reportDistributorNodeState(0, State.DOWN);
@@ -516,7 +516,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void maintenance_mode_counted_as_down_for_cluster_availability() {
+ void maintenance_mode_counted_as_down_for_cluster_availability() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(3)
.bringEntireClusterUp()
.reportStorageNodeState(0, State.DOWN)
@@ -528,7 +528,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void init_and_retired_counted_as_up_for_cluster_availability() {
+ void init_and_retired_counted_as_up_for_cluster_availability() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(3)
.bringEntireClusterUp()
.reportStorageNodeState(0, State.INITIALIZING)
@@ -541,7 +541,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void cluster_down_if_less_than_min_ratio_of_storage_nodes_available() {
+ void cluster_down_if_less_than_min_ratio_of_storage_nodes_available() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(3)
.bringEntireClusterUp()
.reportStorageNodeState(0, State.DOWN)
@@ -555,7 +555,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void cluster_not_down_if_more_than_min_ratio_of_storage_nodes_available() {
+ void cluster_not_down_if_more_than_min_ratio_of_storage_nodes_available() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(3)
.bringEntireClusterUp()
.reportStorageNodeState(0, State.DOWN);
@@ -568,7 +568,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void cluster_down_if_less_than_min_ratio_of_distributors_available() {
+ void cluster_down_if_less_than_min_ratio_of_distributors_available() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(3)
.bringEntireClusterUp()
.reportDistributorNodeState(0, State.DOWN)
@@ -582,7 +582,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void cluster_not_down_if_more_than_min_ratio_of_distributors_available() {
+ void cluster_not_down_if_more_than_min_ratio_of_distributors_available() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(3)
.bringEntireClusterUp()
.reportDistributorNodeState(0, State.DOWN);
@@ -594,7 +594,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void group_nodes_are_marked_down_if_group_availability_too_low() {
+ void group_nodes_are_marked_down_if_group_availability_too_low() {
final ClusterFixture fixture = ClusterFixture
.forHierarchicCluster(DistributionBuilder.withGroups(3).eachWithNodeCount(3))
.bringEntireClusterUp()
@@ -608,7 +608,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void group_nodes_are_not_marked_down_if_group_availability_sufficiently_high() {
+ void group_nodes_are_not_marked_down_if_group_availability_sufficiently_high() {
final ClusterFixture fixture = ClusterFixture
.forHierarchicCluster(DistributionBuilder.withGroups(3).eachWithNodeCount(3))
.bringEntireClusterUp()
@@ -620,7 +620,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void implicitly_downed_group_nodes_receive_a_state_description() {
+ void implicitly_downed_group_nodes_receive_a_state_description() {
final ClusterFixture fixture = ClusterFixture
.forHierarchicCluster(DistributionBuilder.withGroups(2).eachWithNodeCount(2))
.bringEntireClusterUp()
@@ -634,7 +634,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void implicitly_downed_group_nodes_are_annotated_with_group_reason() {
+ void implicitly_downed_group_nodes_are_annotated_with_group_reason() {
final ClusterFixture fixture = ClusterFixture
.forHierarchicCluster(DistributionBuilder.withGroups(2).eachWithNodeCount(2))
.bringEntireClusterUp()
@@ -647,7 +647,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void maintenance_nodes_in_downed_group_are_not_affected() {
+ void maintenance_nodes_in_downed_group_are_not_affected() {
final ClusterFixture fixture = ClusterFixture
.forHierarchicCluster(DistributionBuilder.withGroups(3).eachWithNodeCount(3))
.bringEntireClusterUp()
@@ -664,7 +664,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void group_nodes_are_marked_maintenance_if_group_availability_too_low_by_orchestrator() {
+ void group_nodes_are_marked_maintenance_if_group_availability_too_low_by_orchestrator() {
final ClusterFixture fixture = ClusterFixture
.forHierarchicCluster(DistributionBuilder.withGroups(3).eachWithNodeCount(3))
.bringEntireClusterUp()
@@ -679,7 +679,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void group_nodes_are_not_marked_maintenance_if_group_availability_high_by_orchestrator() {
+ void group_nodes_are_not_marked_maintenance_if_group_availability_high_by_orchestrator() {
final ClusterFixture fixture = ClusterFixture
.forHierarchicCluster(DistributionBuilder.withGroups(3).eachWithNodeCount(3))
.bringEntireClusterUp()
@@ -698,7 +698,7 @@ public class ClusterStateGeneratorTest {
* and any buckets caught over this level would not be accessible in the data space.
*/
@Test
- public void distribution_bits_bounded_by_reported_min_bits_from_storage_node() {
+ void distribution_bits_bounded_by_reported_min_bits_from_storage_node() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(3)
.bringEntireClusterUp()
.reportStorageNodeState(1, new NodeState(NodeType.STORAGE, State.UP).setMinUsedBits(7));
@@ -708,7 +708,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void distribution_bits_bounded_by_lowest_reporting_storage_node() {
+ void distribution_bits_bounded_by_lowest_reporting_storage_node() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(3)
.bringEntireClusterUp()
.reportStorageNodeState(0, new NodeState(NodeType.STORAGE, State.UP).setMinUsedBits(6))
@@ -719,7 +719,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void distribution_bits_bounded_by_config_parameter() {
+ void distribution_bits_bounded_by_config_parameter() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(3).bringEntireClusterUp();
final ClusterStateGenerator.Params params = fixture.generatorParams().idealDistributionBits(12);
@@ -731,7 +731,7 @@ public class ClusterStateGeneratorTest {
// TODO We generally want to avoid distribution bit decreases if at all possible, since "collapsing"
// the top-level bucket space can cause data loss on timestamp collisions across super buckets.
@Test
- public void distribution_bit_not_influenced_by_nodes_down_or_in_maintenance() {
+ void distribution_bit_not_influenced_by_nodes_down_or_in_maintenance() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(3)
.bringEntireClusterUp()
.reportStorageNodeState(0, new NodeState(NodeType.STORAGE, State.UP).setMinUsedBits(7))
@@ -760,20 +760,20 @@ public class ClusterStateGeneratorTest {
* let e.g. a transition from 10 bits to 20 bits cause 10 interim full re-distributions.
*/
@Test
- public void published_distribution_bit_bound_by_low_watermark_when_nodes_report_less_than_config_bits() {
+ void published_distribution_bit_bound_by_low_watermark_when_nodes_report_less_than_config_bits() {
assertThat(do_test_distribution_bit_watermark(5, 5),
- equalTo("bits:5 distributor:3 storage:3"));
+ equalTo("bits:5 distributor:3 storage:3"));
assertThat(do_test_distribution_bit_watermark(5, 6),
- equalTo("bits:5 distributor:3 storage:3"));
+ equalTo("bits:5 distributor:3 storage:3"));
assertThat(do_test_distribution_bit_watermark(5, 15),
- equalTo("bits:5 distributor:3 storage:3"));
+ equalTo("bits:5 distributor:3 storage:3"));
}
@Test
- public void published_state_jumps_to_configured_ideal_bits_when_all_nodes_report_it() {
+ void published_state_jumps_to_configured_ideal_bits_when_all_nodes_report_it() {
// Note: the rest of the mocked nodes always report 16 bits by default
assertThat(do_test_distribution_bit_watermark(5, 16),
- equalTo("distributor:3 storage:3")); // "bits:16" implied
+ equalTo("distributor:3 storage:3")); // "bits:16" implied
}
private String do_test_storage_node_with_no_init_progress(State wantedState) {
@@ -793,9 +793,9 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void storage_node_with_no_init_progress_within_timeout_is_marked_down() {
+ void storage_node_with_no_init_progress_within_timeout_is_marked_down() {
assertThat(do_test_storage_node_with_no_init_progress(State.UP),
- equalTo("distributor:3 storage:3 .0.s:d"));
+ equalTo("distributor:3 storage:3 .0.s:d"));
}
/**
@@ -803,9 +803,9 @@ public class ClusterStateGeneratorTest {
* as the wanted state.
*/
@Test
- public void maintenance_wanted_state_overrides_storage_node_with_no_init_progress() {
+ void maintenance_wanted_state_overrides_storage_node_with_no_init_progress() {
assertThat(do_test_storage_node_with_no_init_progress(State.MAINTENANCE),
- equalTo("distributor:3 storage:3 .0.s:m"));
+ equalTo("distributor:3 storage:3 .0.s:m"));
}
/**
@@ -816,7 +816,7 @@ public class ClusterStateGeneratorTest {
* their init stage and would otherwise pop in and out of the cluster state.
*/
@Test
- public void unstable_init_storage_node_has_init_state_substituted_by_down() {
+ void unstable_init_storage_node_has_init_state_substituted_by_down() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(5)
.bringEntireClusterUp()
.reportStorageNodeState(0, State.INITIALIZING)
@@ -828,7 +828,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void storage_node_with_crashes_but_not_unstable_init_does_not_have_init_state_substituted_by_down() {
+ void storage_node_with_crashes_but_not_unstable_init_does_not_have_init_state_substituted_by_down() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(5)
.bringEntireClusterUp()
.reportStorageNodeState(0, new NodeState(NodeType.STORAGE, State.INITIALIZING).setInitProgress(0.5f));
@@ -846,7 +846,7 @@ public class ClusterStateGeneratorTest {
* potentially contributing additional instability to the cluster.
*/
@Test
- public void unstable_retired_node_should_be_marked_down() {
+ void unstable_retired_node_should_be_marked_down() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(5)
.bringEntireClusterUp()
.proposeStorageNodeWantedState(3, State.RETIRED);
@@ -860,7 +860,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void generator_params_can_inherit_values_from_controller_options() {
+ void generator_params_can_inherit_values_from_controller_options() {
FleetControllerOptions options = new FleetControllerOptions("foocluster", Set.of(new ConfiguredNode(0, false)));
options.maxPrematureCrashes = 1;
options.minStorageNodesUp = 2;
@@ -881,7 +881,7 @@ public class ClusterStateGeneratorTest {
}
@Test
- public void configured_zero_init_progress_time_disables_auto_init_to_down_feature() {
+ void configured_zero_init_progress_time_disables_auto_init_to_down_feature() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(3)
.bringEntireClusterUp()
.reportStorageNodeState(0, new NodeState(NodeType.STORAGE, State.INITIALIZING).setInitProgress(0.5f));
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStateViewTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStateViewTest.java
index 1125c431cae..473007f6a7c 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStateViewTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStateViewTest.java
@@ -4,11 +4,11 @@ package com.yahoo.vespa.clustercontroller.core;
import com.yahoo.vdslib.state.*;
import com.yahoo.vespa.clustercontroller.core.hostinfo.HostInfo;
import com.yahoo.vespa.clustercontroller.core.hostinfo.StorageNodeStatsBridge;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.*;
/**
@@ -25,7 +25,7 @@ public class ClusterStateViewTest {
}
@Test
- public void testWrongNodeType() {
+ void testWrongNodeType() {
when(nodeInfo.isDistributor()).thenReturn(false);
clusterStateView.handleUpdatedHostInfo(nodeInfo, createHostInfo("101"));
@@ -34,7 +34,7 @@ public class ClusterStateViewTest {
}
@Test
- public void testStateVersionMismatch() {
+ void testStateVersionMismatch() {
when(nodeInfo.isDistributor()).thenReturn(true);
when(clusterState.getVersion()).thenReturn(101);
@@ -44,7 +44,7 @@ public class ClusterStateViewTest {
}
@Test
- public void testFailToGetStats() {
+ void testFailToGetStats() {
when(nodeInfo.isDistributor()).thenReturn(true);
when(clusterState.getVersion()).thenReturn(101);
@@ -54,17 +54,17 @@ public class ClusterStateViewTest {
}
@Test
- public void testSuccessCase() {
+ void testSuccessCase() {
when(nodeInfo.isDistributor()).thenReturn(true);
HostInfo hostInfo = HostInfo.createHostInfo(
"{" +
- " \"cluster-state-version\": 101," +
- " \"distributor\": {\n" +
- " \"storage-nodes\": [\n" +
- " {\n" +
- " \"node-index\": 3\n" +
- " }\n" +
- " ]}}");
+ " \"cluster-state-version\": 101," +
+ " \"distributor\": {\n" +
+ " \"storage-nodes\": [\n" +
+ " {\n" +
+ " \"node-index\": 3\n" +
+ " }\n" +
+ " ]}}");
when(nodeInfo.getNodeIndex()).thenReturn(3);
@@ -76,7 +76,7 @@ public class ClusterStateViewTest {
}
@Test
- public void testIndicesOfUpNodes() {
+ void testIndicesOfUpNodes() {
when(clusterState.getNodeCount(NodeType.DISTRIBUTOR)).thenReturn(7);
NodeState nodeState = mock(NodeState.class);
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStatsAggregatorTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStatsAggregatorTest.java
index 11c00414cb8..2b62915439f 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStatsAggregatorTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStatsAggregatorTest.java
@@ -2,13 +2,11 @@
package com.yahoo.vespa.clustercontroller.core;
import com.google.common.collect.Sets;
-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.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author hakonhall
@@ -67,7 +65,7 @@ public class ClusterStatsAggregatorTest {
}
@Test
- public void aggregator_handles_updates_to_single_distributor_and_content_node() {
+ void aggregator_handles_updates_to_single_distributor_and_content_node() {
Fixture f = new Fixture(distributorNodes(1), contentNodes(3));
ContentClusterStatsBuilder stats = new ContentClusterStatsBuilder()
.add(3, "default", 10, 1)
@@ -77,7 +75,7 @@ public class ClusterStatsAggregatorTest {
}
@Test
- public void aggregator_handles_updates_to_multiple_distributors_and_content_nodes() {
+ void aggregator_handles_updates_to_multiple_distributors_and_content_nodes() {
Fixture f = new FourNodesFixture();
f.verify(new ContentClusterStatsBuilder()
@@ -88,7 +86,7 @@ public class ClusterStatsAggregatorTest {
}
@Test
- public void aggregator_handles_multiple_updates_from_same_distributor() {
+ void aggregator_handles_multiple_updates_from_same_distributor() {
Fixture f = new Fixture(distributorNodes(1, 2), contentNodes(3));
f.update(1, new ContentClusterStatsBuilder().add(3, "default"));
@@ -111,7 +109,7 @@ public class ClusterStatsAggregatorTest {
}
@Test
- public void aggregator_handles_more_content_nodes_that_distributors() {
+ void aggregator_handles_more_content_nodes_that_distributors() {
Fixture f = new Fixture(distributorNodes(1), contentNodes(3, 4));
ContentClusterStatsBuilder stats = new ContentClusterStatsBuilder()
.add(3, "default", 10, 1)
@@ -121,7 +119,7 @@ public class ClusterStatsAggregatorTest {
}
@Test
- public void aggregator_ignores_updates_to_unknown_distributor() {
+ void aggregator_ignores_updates_to_unknown_distributor() {
Fixture f = new Fixture(distributorNodes(1), contentNodes(3));
final int downDistributorIndex = 2;
f.update(downDistributorIndex, new ContentClusterStatsBuilder()
@@ -130,7 +128,7 @@ public class ClusterStatsAggregatorTest {
}
@Test
- public void aggregator_tracks_when_it_has_updates_from_all_distributors() {
+ void aggregator_tracks_when_it_has_updates_from_all_distributors() {
Fixture f = new Fixture(distributorNodes(1, 2), contentNodes(3));
assertFalse(f.hasUpdatesFromAllDistributors());
f.update(1, new ContentClusterStatsBuilder().add(3, "default"));
@@ -142,7 +140,7 @@ public class ClusterStatsAggregatorTest {
}
@Test
- public void aggregator_can_provide_aggregated_stats_per_distributor() {
+ void aggregator_can_provide_aggregated_stats_per_distributor() {
Fixture f = new FourNodesFixture();
f.verify(1, ContentNodeStatsBuilder.forNode(1)
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStatsChangeTrackerTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStatsChangeTrackerTest.java
index ae237b3330e..b9e7714671c 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStatsChangeTrackerTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ClusterStatsChangeTrackerTest.java
@@ -2,12 +2,12 @@
package com.yahoo.vespa.clustercontroller.core;
import com.google.common.collect.Sets;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Set;
-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 ClusterStatsChangeTrackerTest {
@@ -74,39 +74,39 @@ public class ClusterStatsChangeTrackerTest {
}
@Test
- public void stats_have_not_changed_if_not_all_distributors_are_updated() {
+ void stats_have_not_changed_if_not_all_distributors_are_updated() {
Fixture f = Fixture.empty();
assertFalse(f.statsHaveChanged());
}
@Test
- public void stats_have_changed_if_in_sync_node_not_found_in_previous_stats() {
+ void stats_have_changed_if_in_sync_node_not_found_in_previous_stats() {
Fixture f = Fixture.fromStats(stats().inSync(0));
assertTrue(f.statsHaveChanged());
}
@Test
- public void stats_have_changed_if_buckets_pending_node_not_found_in_previous_stats() {
+ void stats_have_changed_if_buckets_pending_node_not_found_in_previous_stats() {
Fixture f = Fixture.fromStats(stats().bucketsPending(0));
assertTrue(f.statsHaveChanged());
}
@Test
- public void stats_have_changed_if_one_node_has_in_sync_to_buckets_pending_transition() {
+ void stats_have_changed_if_one_node_has_in_sync_to_buckets_pending_transition() {
Fixture f = Fixture.fromStats(stats().bucketsPending(0).inSync(1));
f.newAggregatedStats(stats().bucketsPending(0).bucketsPending(1));
assertTrue(f.statsHaveChanged());
}
@Test
- public void stats_have_changed_if_one_node_has_buckets_pending_to_in_sync_transition() {
+ void stats_have_changed_if_one_node_has_buckets_pending_to_in_sync_transition() {
Fixture f = Fixture.fromStats(stats().bucketsPending(0).bucketsPending(1));
f.newAggregatedStats(stats().bucketsPending(0).inSync(1));
assertTrue(f.statsHaveChanged());
}
@Test
- public void stats_have_not_changed_if_no_nodes_have_changed_state() {
+ void stats_have_not_changed_if_no_nodes_have_changed_state() {
Fixture f = Fixture.fromStats(stats().bucketsPending(0).bucketsPending(1));
f.newAggregatedStats(stats().bucketsPending(0).bucketsPending(1));
assertFalse(f.statsHaveChanged());
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ContentClusterHtmlRendererTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ContentClusterHtmlRendererTest.java
index ff1c5b0bb17..d43a3e13c6a 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ContentClusterHtmlRendererTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ContentClusterHtmlRendererTest.java
@@ -7,8 +7,8 @@ import com.yahoo.vespa.clustercontroller.core.hostinfo.HostInfo;
import com.yahoo.vespa.clustercontroller.core.status.statuspage.VdsClusterHtmlRenderer;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONWriter;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.StringWriter;
import java.io.Writer;
@@ -27,7 +27,7 @@ public class ContentClusterHtmlRendererTest {
private final TreeMap<Integer, NodeInfo> distributorNodeInfoByIndex = new TreeMap<>();
private String result;
- @Before
+ @BeforeEach
public void before() throws JSONException {
final ClusterStateBundle stateBundle = ClusterStateBundle.ofBaselineOnly(
AnnotatedClusterState.withoutAnnotations(
@@ -71,7 +71,7 @@ public class ContentClusterHtmlRendererTest {
}
@Test
- public void testVtagRendering() {
+ void testVtagRendering() {
// 9 distribution nodes should have green tag on release1.
assertThat(result.split("<td bgcolor=\"#c0ffc0\" align=\"right\"><nobr>release1</nobr></td>").length, is(10));
// 1 distribution node should have warning on release1bad.
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ContentNodeStatsTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ContentNodeStatsTest.java
index 47d1970e4d6..d30de6f7954 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ContentNodeStatsTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ContentNodeStatsTest.java
@@ -1,18 +1,16 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.clustercontroller.core;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static com.yahoo.vespa.clustercontroller.core.ContentNodeStats.BucketSpaceStats;
-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.*;
public class ContentNodeStatsTest {
@Test
- public void bucket_space_stats_can_transition_from_valid_to_invalid() {
- BucketSpaceStats stats = BucketSpaceStats.of(5,1);
+ void bucket_space_stats_can_transition_from_valid_to_invalid() {
+ BucketSpaceStats stats = BucketSpaceStats.of(5, 1);
assertTrue(stats.valid());
stats.merge(BucketSpaceStats.invalid(), 1);
@@ -21,7 +19,7 @@ public class ContentNodeStatsTest {
}
@Test
- public void bucket_space_stats_can_transition_from_invalid_to_valid() {
+ void bucket_space_stats_can_transition_from_invalid_to_valid() {
BucketSpaceStats stats = BucketSpaceStats.invalid();
assertFalse(stats.valid());
@@ -33,7 +31,7 @@ public class ContentNodeStatsTest {
}
@Test
- public void bucket_space_stats_tracks_multiple_layers_of_invalid() {
+ void bucket_space_stats_tracks_multiple_layers_of_invalid() {
BucketSpaceStats stats = BucketSpaceStats.invalid();
stats.merge(BucketSpaceStats.invalid(), 1);
assertFalse(stats.valid());
@@ -52,19 +50,19 @@ public class ContentNodeStatsTest {
}
@Test
- public void invalid_bucket_space_stats_may_have_pending_buckets() {
+ void invalid_bucket_space_stats_may_have_pending_buckets() {
assertTrue(BucketSpaceStats.invalid().mayHaveBucketsPending(1.0));
}
@Test
- public void bucket_space_stats_without_buckets_total_use_buckets_pending_to_calculate_may_have_buckets_pending() {
+ void bucket_space_stats_without_buckets_total_use_buckets_pending_to_calculate_may_have_buckets_pending() {
assertTrue(BucketSpaceStats.of(0, 2).mayHaveBucketsPending(0.6));
assertTrue(BucketSpaceStats.of(0, 1).mayHaveBucketsPending(0.6));
assertFalse(BucketSpaceStats.of(0, 0).mayHaveBucketsPending(0.6));
}
@Test
- public void min_merge_completion_ratio_is_used_to_calculate_bucket_space_stats_may_have_buckets_pending() {
+ void min_merge_completion_ratio_is_used_to_calculate_bucket_space_stats_may_have_buckets_pending() {
assertTrue(BucketSpaceStats.of(5, 6).mayHaveBucketsPending(0.6));
assertTrue(BucketSpaceStats.of(5, 5).mayHaveBucketsPending(0.6));
assertTrue(BucketSpaceStats.of(5, 4).mayHaveBucketsPending(0.6));
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/DatabaseHandlerTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/DatabaseHandlerTest.java
index 1f7b9293960..4d8c7799c58 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/DatabaseHandlerTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/DatabaseHandlerTest.java
@@ -10,9 +10,9 @@ import com.yahoo.vespa.clustercontroller.core.database.DatabaseFactory;
import com.yahoo.vespa.clustercontroller.core.database.DatabaseHandler;
import com.yahoo.vespa.clustercontroller.core.listeners.NodeListener;
import com.yahoo.vespa.clustercontroller.core.listeners.SlobrokListener;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.MockitoAnnotations;
@@ -20,8 +20,8 @@ import org.mockito.MockitoAnnotations;
import java.util.Map;
import java.util.TreeMap;
-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;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
@@ -89,18 +89,18 @@ public class DatabaseHandlerTest {
}
}
- @Before
+ @BeforeEach
public void setUp() {
openMock = MockitoAnnotations.openMocks(this);
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
openMock.close();
}
@Test
- public void can_store_latest_cluster_state_bundle() throws Exception {
+ void can_store_latest_cluster_state_bundle() throws Exception {
Fixture f = new Fixture();
DatabaseHandler handler = f.createHandler();
handler.doNextZooKeeperTask(f.createMockContext()); // Database setup step
@@ -110,7 +110,7 @@ public class DatabaseHandlerTest {
}
@Test
- public void can_load_latest_cluster_state_bundle() throws Exception {
+ void can_load_latest_cluster_state_bundle() throws Exception {
Fixture f = new Fixture();
DatabaseHandler handler = f.createHandler();
handler.doNextZooKeeperTask(f.createMockContext()); // Database setup step
@@ -124,7 +124,7 @@ public class DatabaseHandlerTest {
// FIXME I don't like the semantics of this, but it mirrors the legacy behavior for the
// rest of the DB load operations exposed by the DatabaseHandler.
@Test
- public void empty_bundle_is_returned_if_no_db_connection() throws Exception {
+ void empty_bundle_is_returned_if_no_db_connection() throws Exception {
Fixture f = new Fixture();
DatabaseHandler handler = f.createHandler();
// Note: no DB setup step
@@ -134,7 +134,7 @@ public class DatabaseHandlerTest {
}
@Test
- public void save_wanted_state_of_configured_nodes() throws Exception {
+ void save_wanted_state_of_configured_nodes() throws Exception {
var fixture = new Fixture();
DatabaseHandler handler = fixture.createHandler();
DatabaseHandler.DatabaseContext databaseContext = fixture.createMockContext();
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/DatabaseTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/DatabaseTest.java
index 2ff48e00d0f..dc297e7a549 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/DatabaseTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/DatabaseTest.java
@@ -12,22 +12,21 @@ import com.yahoo.vdslib.state.Node;
import com.yahoo.vdslib.state.NodeState;
import com.yahoo.vdslib.state.NodeType;
import com.yahoo.vdslib.state.State;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Map;
import java.util.TreeMap;
import java.util.logging.Logger;
-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 DatabaseTest extends FleetControllerTest {
private static final Logger log = Logger.getLogger(DatabaseTest.class.getName());
@Test
- public void testWantedStatesInZooKeeper() throws Exception {
+ void testWantedStatesInZooKeeper() throws Exception {
startingTest("DatabaseTest::testWantedStatesInZooKeeper");
FleetControllerOptions options = defaultOptions("mycluster");
options.zooKeeperServerAddress = "127.0.0.1";
@@ -81,7 +80,7 @@ public class DatabaseTest extends FleetControllerTest {
}
@Test
- public void testWantedStateOfUnknownNode() throws Exception {
+ void testWantedStateOfUnknownNode() throws Exception {
startingTest("DatabaseTest::testWantedStatesOfUnknownNode");
FleetControllerOptions options = defaultOptions("mycluster");
options.minRatioOfDistributorNodesUp = 0;
@@ -124,7 +123,7 @@ public class DatabaseTest extends FleetControllerTest {
assertWantedStates(wantedStates);
stopFleetController();
- for (int i=6; i<nodes.size(); ++i) nodes.get(i).disconnect();
+ for (int i = 6; i < nodes.size(); ++i) nodes.get(i).disconnect();
startFleetController();
waitForState("version:\\d+ distributor:3 storage:7 .1.s:m .3.s:d .4.s:d .5.s:d .6.s:m");
@@ -132,14 +131,14 @@ public class DatabaseTest extends FleetControllerTest {
setWantedState(new Node(NodeType.STORAGE, 6), new NodeState(NodeType.STORAGE, State.UP), wantedStates);
waitForState("version:\\d+ distributor:3 storage:3 .1.s:m");
- for (int i=6; i<nodes.size(); ++i) nodes.get(i).connect();
+ for (int i = 6; i < nodes.size(); ++i) nodes.get(i).connect();
waitForState("version:\\d+ distributor:10 .8.s:d storage:10 .1.s:m .7.s:r .8.s:d");
assertWantedStates(wantedStates);
}
private void assertWantedStates(Map<Node, NodeState> wantedStates) {
for (DummyVdsNode node : nodes) {
- assertEquals(node.getNode().toString(), wantedStates.get(node.getNode()), fleetController.getWantedNodeState(node.getNode()));
+ assertEquals(wantedStates.get(node.getNode()), fleetController.getWantedNodeState(node.getNode()), node.getNode().toString());
}
}
@@ -156,8 +155,8 @@ public class DatabaseTest extends FleetControllerTest {
req.parameters().add(new StringValue("storage/cluster.mycluster/" + n.getType().toString() + "/" + n.getIndex()));
req.parameters().add(new StringValue(ns.serialize(true)));
connection.invokeSync(req, timeoutS);
- assertEquals(req.toString(), ErrorCode.NONE, req.errorCode());
- assertTrue(req.toString(), req.checkReturnTypes("s"));
+ assertEquals(ErrorCode.NONE, req.errorCode(), req.toString());
+ assertTrue(req.checkReturnTypes("s"), req.toString());
wantedStates.put(n, ns);
}
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/DistributionBitCountTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/DistributionBitCountTest.java
index e9d3a9cf83e..d3b0addbb13 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/DistributionBitCountTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/DistributionBitCountTest.java
@@ -6,12 +6,12 @@ import com.yahoo.vdslib.state.ClusterState;
import com.yahoo.vdslib.state.NodeState;
import com.yahoo.vdslib.state.NodeType;
import com.yahoo.vdslib.state.State;
-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.jupiter.api.Assertions.assertEquals;
public class DistributionBitCountTest extends FleetControllerTest {
@@ -37,7 +37,7 @@ public class DistributionBitCountTest extends FleetControllerTest {
* Test that then altering config to increased bit count, that a new system state is not sent out (and not altered) if a storagenode needs it to be no further split.
*/
@Test
- public void testDistributionBitCountConfigIncrease() throws Exception {
+ void testDistributionBitCountConfigIncrease() throws Exception {
setUpSystem("DistributionBitCountTest::testDistributionBitCountConfigIncrease");
options.distributionBits = 20;
fleetController.updateOptions(options);
@@ -53,7 +53,7 @@ public class DistributionBitCountTest extends FleetControllerTest {
* Test that then altering config to decrease bit count, that a new system state is sent out with that bit count.
*/
@Test
- public void testDistributionBitCountConfigDecrease() throws Exception {
+ void testDistributionBitCountConfigDecrease() throws Exception {
setUpSystem("DistributionBitCountTest::testDistributionBitCountConfigDecrease");
options.distributionBits = 12;
fleetController.updateOptions(options);
@@ -69,7 +69,7 @@ public class DistributionBitCountTest extends FleetControllerTest {
* node now being lowest, the fleetcontroller adjusts to use that bit in system state.
*/
@Test
- public void testStorageNodeReportingHigherBitCount() throws Exception {
+ void testStorageNodeReportingHigherBitCount() throws Exception {
setUpSystem("DistributionBitCountTest::testStorageNodeReportingHigherBitCount");
nodes.get(1).setNodeState(new NodeState(NodeType.STORAGE, State.UP).setMinUsedBits(11));
@@ -78,12 +78,11 @@ public class DistributionBitCountTest extends FleetControllerTest {
ClusterState startState = waitForState("version:\\d+ bits:11 distributor:10 storage:10");
nodes.get(1).setNodeState(new NodeState(NodeType.STORAGE, State.UP).setMinUsedBits(12));
- assertEquals(startState + "->" + fleetController.getSystemState(),
- startState.getVersion(), fleetController.getSystemState().getVersion());
+ assertEquals(startState.getVersion(), fleetController.getSystemState().getVersion(), startState + "->" + fleetController.getSystemState());
for (int i = 0; i < 10; ++i) {
// nodes is array of [distr.0, stor.0, distr.1, stor.1, ...] and we just want the storage nodes
- nodes.get(i*2 + 1).setNodeState(new NodeState(NodeType.STORAGE, State.UP).setMinUsedBits(17));
+ nodes.get(i * 2 + 1).setNodeState(new NodeState(NodeType.STORAGE, State.UP).setMinUsedBits(17));
}
assertEquals(startState.getVersion() + 1, waitForState("version:\\d+ bits:17 distributor:10 storage:10").getVersion());
}
@@ -93,7 +92,7 @@ public class DistributionBitCountTest extends FleetControllerTest {
* Test that then storage node report lower bit count, and then becomes the smallest, the fleetcontroller adjusts to use that bit in system state.
*/
@Test
- public void testStorageNodeReportingLowerBitCount() throws Exception {
+ void testStorageNodeReportingLowerBitCount() throws Exception {
setUpSystem("DistributionBitCountTest::testStorageNodeReportingLowerBitCount");
nodes.get(1).setNodeState(new NodeState(NodeType.STORAGE, State.UP).setMinUsedBits(13));
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/EventDiffCalculatorTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/EventDiffCalculatorTest.java
index 48d6ccbf655..8b07c216774 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/EventDiffCalculatorTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/EventDiffCalculatorTest.java
@@ -18,7 +18,7 @@ import static org.hamcrest.CoreMatchers.hasItem;
import static com.yahoo.vespa.clustercontroller.core.ClusterFixture.storageNode;
import static com.yahoo.vespa.clustercontroller.core.ClusterFixture.distributorNode;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.List;
@@ -124,7 +124,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void single_storage_node_state_transition_emits_altered_node_state_event() {
+ void single_storage_node_state_transition_emits_altered_node_state_event() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.clusterStateAfter("distributor:3 storage:3 .0.s:d");
@@ -138,7 +138,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void single_distributor_node_state_transition_emits_altered_node_state_event() {
+ void single_distributor_node_state_transition_emits_altered_node_state_event() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.clusterStateAfter("distributor:3 .1.s:d storage:3");
@@ -152,7 +152,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void node_state_change_event_is_tagged_with_given_time() {
+ void node_state_change_event_is_tagged_with_given_time() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.clusterStateAfter("distributor:3 storage:3 .0.s:d")
@@ -164,7 +164,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void multiple_node_state_transitions_emit_multiple_node_state_events() {
+ void multiple_node_state_transitions_emit_multiple_node_state_events() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3 .1.s:d")
.clusterStateAfter("distributor:3 .2.s:d storage:3 .0.s:r");
@@ -183,7 +183,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void no_emitted_node_state_event_when_node_state_not_changed() {
+ void no_emitted_node_state_event_when_node_state_not_changed() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.clusterStateAfter("distributor:3 storage:3");
@@ -193,7 +193,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void node_down_edge_with_group_down_reason_has_separate_event_emitted() {
+ void node_down_edge_with_group_down_reason_has_separate_event_emitted() {
// We sneakily use a flat cluster here but still use a 'group down' reason. Differ doesn't currently care.
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
@@ -213,7 +213,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void group_down_to_group_down_does_not_emit_new_event() {
+ void group_down_to_group_down_does_not_emit_new_event() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3 .1.s:d")
.clusterStateAfter("distributor:3 storage:3 .1.s:m")
@@ -229,7 +229,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void group_down_to_clear_reason_emits_group_up_event() {
+ void group_down_to_clear_reason_emits_group_up_event() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3 .2.s:d")
.clusterStateAfter("distributor:3 storage:3")
@@ -247,7 +247,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void cluster_up_edge_emits_sufficient_node_availability_event() {
+ void cluster_up_edge_emits_sufficient_node_availability_event() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("cluster:d distributor:3 storage:3")
.clusterStateAfter("distributor:3 storage:3");
@@ -259,7 +259,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void cluster_down_event_without_reason_annotation_emits_generic_down_event() {
+ void cluster_down_event_without_reason_annotation_emits_generic_down_event() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.clusterStateAfter("cluster:d distributor:3 storage:3");
@@ -271,7 +271,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void cluster_event_is_tagged_with_given_time() {
+ void cluster_event_is_tagged_with_given_time() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.clusterStateAfter("cluster:d distributor:3 storage:3")
@@ -283,7 +283,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void no_event_emitted_for_cluster_down_to_down_edge() {
+ void no_event_emitted_for_cluster_down_to_down_edge() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("cluster:d distributor:3 storage:3")
.clusterStateAfter("cluster:d distributor:3 storage:3");
@@ -293,7 +293,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void too_few_storage_nodes_cluster_down_reason_emits_corresponding_event() {
+ void too_few_storage_nodes_cluster_down_reason_emits_corresponding_event() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.clusterStateAfter("cluster:d distributor:3 storage:3")
@@ -307,7 +307,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void too_few_distributor_nodes_cluster_down_reason_emits_corresponding_event() {
+ void too_few_distributor_nodes_cluster_down_reason_emits_corresponding_event() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.clusterStateAfter("cluster:d distributor:3 storage:3")
@@ -320,7 +320,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void too_low_storage_node_ratio_cluster_down_reason_emits_corresponding_event() {
+ void too_low_storage_node_ratio_cluster_down_reason_emits_corresponding_event() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.clusterStateAfter("cluster:d distributor:3 storage:3")
@@ -333,7 +333,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void too_low_distributor_node_ratio_cluster_down_reason_emits_corresponding_event() {
+ void too_low_distributor_node_ratio_cluster_down_reason_emits_corresponding_event() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.clusterStateAfter("cluster:d distributor:3 storage:3")
@@ -346,7 +346,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void may_have_merges_pending_up_edge_event_emitted_if_derived_bucket_space_state_differs_from_baseline() {
+ void may_have_merges_pending_up_edge_event_emitted_if_derived_bucket_space_state_differs_from_baseline() {
EventFixture f = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.derivedClusterStateBefore("default", "distributor:3 storage:3")
@@ -367,7 +367,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void may_have_merges_pending_down_edge_event_emitted_if_derived_bucket_space_state_differs_from_baseline() {
+ void may_have_merges_pending_down_edge_event_emitted_if_derived_bucket_space_state_differs_from_baseline() {
EventFixture f = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.derivedClusterStateBefore("default", "distributor:3 storage:3 .1.s:m")
@@ -388,7 +388,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void both_baseline_and_derived_bucket_space_state_events_are_emitted() {
+ void both_baseline_and_derived_bucket_space_state_events_are_emitted() {
EventFixture f = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.derivedClusterStateBefore("default", "distributor:3 storage:3")
@@ -408,7 +408,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void derived_bucket_space_state_events_are_not_emitted_if_similar_to_baseline() {
+ void derived_bucket_space_state_events_are_not_emitted_if_similar_to_baseline() {
EventFixture f = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.derivedClusterStateBefore("default", "distributor:3 storage:3")
@@ -426,7 +426,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void storage_node_passed_maintenance_grace_period_emits_event() {
+ void storage_node_passed_maintenance_grace_period_emits_event() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3 .0.s:m")
.clusterStateAfter("distributor:3 storage:3 .0.s:d")
@@ -443,7 +443,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void storage_node_maintenance_grace_period_event_only_emitted_on_maintenance_to_down_edge() {
+ void storage_node_maintenance_grace_period_event_only_emitted_on_maintenance_to_down_edge() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3 .0.s:u")
.clusterStateAfter("distributor:3 storage:3 .0.s:d")
@@ -457,7 +457,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void feed_block_engage_edge_emits_cluster_event() {
+ void feed_block_engage_edge_emits_cluster_event() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.feedBlockBefore(null)
@@ -471,7 +471,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void feed_block_disengage_edge_emits_cluster_event() {
+ void feed_block_disengage_edge_emits_cluster_event() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.feedBlockBefore(ClusterStateBundle.FeedBlock.blockedWithDescription("we're closed"))
@@ -484,7 +484,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void feed_block_engaged_to_engaged_edge_does_not_emit_new_cluster_event() {
+ void feed_block_engaged_to_engaged_edge_does_not_emit_new_cluster_event() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.feedBlockBefore(ClusterStateBundle.FeedBlock.blockedWithDescription("we're closed"))
@@ -496,7 +496,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void feed_block_engage_edge_with_node_exhaustion_info_emits_cluster_and_node_events() {
+ void feed_block_engage_edge_with_node_exhaustion_info_emits_cluster_and_node_events() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.feedBlockBefore(null)
@@ -515,7 +515,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void added_exhaustion_in_feed_block_resource_set_emits_node_event() {
+ void added_exhaustion_in_feed_block_resource_set_emits_node_event() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.feedBlockBefore(ClusterStateBundle.FeedBlock.blockedWith(
@@ -533,7 +533,7 @@ public class EventDiffCalculatorTest {
}
@Test
- public void removed_exhaustion_in_feed_block_resource_set_emits_node_event() {
+ void removed_exhaustion_in_feed_block_resource_set_emits_node_event() {
final EventFixture fixture = EventFixture.createForNodes(3)
.clusterStateBefore("distributor:3 storage:3")
.feedBlockBefore(ClusterStateBundle.FeedBlock.blockedWith(
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/EventLogTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/EventLogTest.java
index afbc50124e2..eee0cb41eeb 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/EventLogTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/EventLogTest.java
@@ -3,19 +3,22 @@ package com.yahoo.vespa.clustercontroller.core;
import com.yahoo.vdslib.state.Node;
import com.yahoo.vdslib.state.NodeType;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.junit.MockitoJUnitRunner;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.junit.jupiter.MockitoExtension;
+import org.mockito.junit.jupiter.MockitoSettings;
+import org.mockito.quality.Strictness;
import java.util.logging.Level;
-import static org.junit.Assert.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
-@RunWith(MockitoJUnitRunner.class)
+@ExtendWith(MockitoExtension.class)
+@MockitoSettings(strictness = Strictness.LENIENT)
public class EventLogTest {
private final MetricUpdater metricUpdater = mock(MetricUpdater.class);
private final NodeEvent nodeEvent = mock(NodeEvent.class);
@@ -33,7 +36,7 @@ public class EventLogTest {
}
@Test
- public void testMetric() {
+ void testMetric() {
initialize(metricUpdater);
eventLog.addNodeOnlyEvent(nodeEvent, Level.INFO);
@@ -43,7 +46,7 @@ public class EventLogTest {
}
@Test
- public void testNullMetricReporter() {
+ void testNullMetricReporter() {
initialize(null);
eventLog.addNodeOnlyEvent(nodeEvent, Level.INFO);
@@ -52,7 +55,7 @@ public class EventLogTest {
}
@Test
- public void testNoEventsDoNotThrowException() {
+ void testNoEventsDoNotThrowException() {
initialize(metricUpdater);
StringBuilder builder = new StringBuilder();
Node nonExistantNode = new Node(NodeType.DISTRIBUTOR, 0);
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/FleetControllerContextImplTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/FleetControllerContextImplTest.java
index 450975076bb..96ce050f33b 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/FleetControllerContextImplTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/FleetControllerContextImplTest.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.vespa.clustercontroller.core;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
@@ -9,7 +9,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.jupiter.api.Assertions.assertEquals;
/**
* @author hakonhall
@@ -20,7 +20,7 @@ public class FleetControllerContextImplTest {
private final FleetControllerContextImpl context = new FleetControllerContextImpl(id);
@Test
- public void verify() {
+ void verify() {
context.log(logger, Level.INFO, "A %s message", "log");
assertEquals(1, logger.records.size());
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/FleetControllerTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/FleetControllerTest.java
index a5eeb69e126..5e4b62e0462 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/FleetControllerTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/FleetControllerTest.java
@@ -27,11 +27,10 @@ import com.yahoo.vespa.clustercontroller.core.testutils.WaitCondition;
import com.yahoo.vespa.clustercontroller.core.testutils.WaitTask;
import com.yahoo.vespa.clustercontroller.core.testutils.Waiter;
import com.yahoo.vespa.clustercontroller.utils.util.NoMetricReporter;
-import org.junit.After;
-import org.junit.Rule;
-import org.junit.rules.TestRule;
-import org.junit.rules.TestWatcher;
-import org.junit.runner.Description;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.junit.jupiter.api.extension.ExtensionContext;
+import org.junit.jupiter.api.extension.TestWatcher;
import java.util.ArrayList;
import java.util.Arrays;
@@ -49,11 +48,12 @@ import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Håkon Humberset
*/
+@ExtendWith(FleetControllerTest.CleanupZookeeperLogsOnSuccess.class)
public abstract class FleetControllerTest implements Waiter {
private static final Logger log = Logger.getLogger(FleetControllerTest.class.getName());
@@ -96,30 +96,31 @@ public abstract class FleetControllerTest implements Waiter {
public boolean shouldInform(double v) { return false; }
}
- protected class CleanupZookeeperLogsOnSuccess extends TestWatcher {
+ public static class CleanupZookeeperLogsOnSuccess implements TestWatcher {
+
+ public CleanupZookeeperLogsOnSuccess() {}
+
@Override
- protected void failed(Throwable e, Description description) {
+ public void testFailed(ExtensionContext context, Throwable cause) {
System.err.println("TEST FAILED - NOT cleaning up zookeeper directory");
- shutdownZooKeeper(false);
+ shutdownZooKeeper(context, false);
}
@Override
- protected void succeeded(Description description) {
+ public void testSuccessful(ExtensionContext context) {
System.err.println("TEST SUCCEEDED - cleaning up zookeeper directory");
- shutdownZooKeeper(true);
+ shutdownZooKeeper(context, true);
}
- private void shutdownZooKeeper(boolean cleanupZooKeeperDir) {
- if (zooKeeperServer != null) {
- zooKeeperServer.shutdown(cleanupZooKeeperDir);
- zooKeeperServer = null;
+ private void shutdownZooKeeper(ExtensionContext ctx, boolean cleanupZooKeeperDir) {
+ FleetControllerTest test = (FleetControllerTest) ctx.getTestInstance().orElseThrow();
+ if (test.zooKeeperServer != null) {
+ test.zooKeeperServer.shutdown(cleanupZooKeeperDir);
+ test.zooKeeperServer = null;
}
}
}
- @Rule
- public TestRule cleanupZookeeperLogsOnSuccess = new CleanupZookeeperLogsOnSuccess();
-
protected void startingTest(String name) {
System.err.println("STARTING TEST: " + name);
testName = name;
@@ -330,7 +331,7 @@ public abstract class FleetControllerTest implements Waiter {
}
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
tearDownSystem();
}
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/GroupAutoTakedownLiveConfigTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/GroupAutoTakedownLiveConfigTest.java
index e6c5c31010f..7f6684e595d 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/GroupAutoTakedownLiveConfigTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/GroupAutoTakedownLiveConfigTest.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.vespa.clustercontroller.core;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.HashSet;
-import static org.junit.Assert.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertFalse;
public class GroupAutoTakedownLiveConfigTest extends FleetControllerTest {
@@ -53,14 +53,14 @@ public class GroupAutoTakedownLiveConfigTest extends FleetControllerTest {
}
@Test
- public void bootstrap_min_ratio_option_is_propagated_to_group_availability_logic() throws Exception {
+ void bootstrap_min_ratio_option_is_propagated_to_group_availability_logic() throws Exception {
setUp3x3ClusterWithMinNodeRatio(0.67);
takeDownContentNode(0);
waitForStateExcludingNodeSubset("version:\\d+ distributor:9 storage:9 .0.s:d .1.s:d .2.s:d", asIntSet(0));
}
@Test
- public void min_ratio_live_reconfig_immediately_takes_effect() throws Exception {
+ void min_ratio_live_reconfig_immediately_takes_effect() throws Exception {
// Initially, arbitrarily many nodes may be down in a group.
setUp3x3ClusterWithMinNodeRatio(0.0);
takeDownContentNode(3);
@@ -75,7 +75,7 @@ public class GroupAutoTakedownLiveConfigTest extends FleetControllerTest {
}
@Test
- public void live_distribution_config_changes_trigger_cluster_state_change() throws Exception {
+ void live_distribution_config_changes_trigger_cluster_state_change() throws Exception {
setUp3x3ClusterWithMinNodeRatio(0.65);
takeDownContentNode(6);
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/GroupAutoTakedownTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/GroupAutoTakedownTest.java
index 1d4b2a73560..f0c8503fed9 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/GroupAutoTakedownTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/GroupAutoTakedownTest.java
@@ -8,7 +8,7 @@ import com.yahoo.vdslib.state.NodeType;
import com.yahoo.vdslib.state.State;
import com.yahoo.vespa.clustercontroller.core.database.DatabaseHandler;
import com.yahoo.vespa.clustercontroller.core.listeners.NodeListener;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.HashSet;
import java.util.List;
@@ -19,7 +19,7 @@ import static com.yahoo.vespa.clustercontroller.core.matchers.NodeEventWithDescr
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.AllOf.allOf;
import static org.hamcrest.core.IsCollectionContaining.hasItem;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -71,17 +71,17 @@ public class GroupAutoTakedownTest {
* not apply to a flat structure.
*/
@Test
- public void config_does_not_apply_to_flat_hierarchy_clusters() {
+ void config_does_not_apply_to_flat_hierarchy_clusters() {
ClusterFixture fixture = createFixtureForAllUpFlatCluster(5, 0.99);
assertEquals("distributor:5 storage:5", fixture.generatedClusterState());
assertEquals("distributor:5 storage:5 .1.s:d",
- stateAfterStorageTransition(fixture, 1, State.DOWN));
+ stateAfterStorageTransition(fixture, 1, State.DOWN));
}
@Test
- public void group_node_down_edge_implicitly_marks_down_rest_of_nodes_in_group() {
+ void group_node_down_edge_implicitly_marks_down_rest_of_nodes_in_group() {
ClusterFixture fixture = createFixtureForAllUpHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(2), 0.51);
@@ -89,28 +89,28 @@ public class GroupAutoTakedownTest {
// Same group as node 4
assertEquals("distributor:6 storage:4",
- stateAfterStorageTransition(fixture, 5, State.DOWN));
+ stateAfterStorageTransition(fixture, 5, State.DOWN));
// Same group as node 1
assertEquals("distributor:6 storage:4 .0.s:d .1.s:d",
- stateAfterStorageTransition(fixture, 0, State.DOWN));
+ stateAfterStorageTransition(fixture, 0, State.DOWN));
}
@Test
- public void restored_group_node_availability_takes_group_back_up_automatically() {
+ void restored_group_node_availability_takes_group_back_up_automatically() {
ClusterFixture fixture = createFixtureForAllUpHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(2), 0.51);
// Group #2 -> down
assertEquals("distributor:6 storage:4",
- stateAfterStorageTransition(fixture, 5, State.DOWN));
+ stateAfterStorageTransition(fixture, 5, State.DOWN));
// Group #2 -> back up again
assertEquals("distributor:6 storage:6",
- stateAfterStorageTransition(fixture, 5, State.UP));
+ stateAfterStorageTransition(fixture, 5, State.UP));
}
@Test
- public void no_op_for_downed_nodes_in_already_downed_group() {
+ void no_op_for_downed_nodes_in_already_downed_group() {
ClusterFixture fixture = createFixtureForAllUpHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(2), 0.51);
@@ -123,7 +123,7 @@ public class GroupAutoTakedownTest {
}
@Test
- public void verbose_node_state_description_updated_for_implicitly_downed_nodes() {
+ void verbose_node_state_description_updated_for_implicitly_downed_nodes() {
ClusterFixture fixture = createFixtureForAllUpHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(3), 0.75);
@@ -131,15 +131,15 @@ public class GroupAutoTakedownTest {
// Node 8 is taken down by the fixture and gets a fixture-assigned message that
// we should _not_ lose/overwrite.
assertEquals("distributor:9 storage:9 .6.s:d " +
- ".6.m:group\\x20node\\x20availability\\x20below\\x20configured\\x20threshold " +
- ".7.s:d " +
- ".7.m:group\\x20node\\x20availability\\x20below\\x20configured\\x20threshold " +
- ".8.s:d .8.m:mockdesc",
- verboseStateAfterStorageTransition(fixture, 8, State.DOWN));
+ ".6.m:group\\x20node\\x20availability\\x20below\\x20configured\\x20threshold " +
+ ".7.s:d " +
+ ".7.m:group\\x20node\\x20availability\\x20below\\x20configured\\x20threshold " +
+ ".8.s:d .8.m:mockdesc",
+ verboseStateAfterStorageTransition(fixture, 8, State.DOWN));
}
@Test
- public void legacy_cluster_wide_availabilty_ratio_is_computed_after_group_takedowns() {
+ void legacy_cluster_wide_availabilty_ratio_is_computed_after_group_takedowns() {
ClusterFixture fixture = createFixtureForAllUpHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(2), 0.51);
fixture.setMinNodesUp(5, 5, 0.51, 0.51);
@@ -152,7 +152,7 @@ public class GroupAutoTakedownTest {
}
@Test
- public void maintenance_wanted_state_not_overwritten() {
+ void maintenance_wanted_state_not_overwritten() {
ClusterFixture fixture = createFixtureForAllUpHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(3), 0.99);
@@ -166,7 +166,7 @@ public class GroupAutoTakedownTest {
}
@Test
- public void transient_maintenance_mode_on_down_edge_does_not_take_down_group() {
+ void transient_maintenance_mode_on_down_edge_does_not_take_down_group() {
ClusterFixture fixture = createFixtureForAllUpHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(3), 0.99);
fixture.enableTransientMaintenanceModeOnDown(1000);
@@ -190,7 +190,7 @@ public class GroupAutoTakedownTest {
}
@Test
- public void taking_down_node_adds_node_specific_event() {
+ void taking_down_node_adds_node_specific_event() {
ClusterFixture fixture = createFixtureForAllUpHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(2), 0.51);
@@ -205,7 +205,7 @@ public class GroupAutoTakedownTest {
}
@Test
- public void bringing_node_back_up_adds_node_specific_event() {
+ void bringing_node_back_up_adds_node_specific_event() {
ClusterFixture fixture = createFixtureForAllUpHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(2), 0.51);
@@ -223,7 +223,7 @@ public class GroupAutoTakedownTest {
}
@Test
- public void wanted_state_retired_implicitly_down_node_is_transitioned_to_retired_mode_immediately() {
+ void wanted_state_retired_implicitly_down_node_is_transitioned_to_retired_mode_immediately() {
ClusterFixture fixture = createFixtureForAllUpHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(3), 0.99);
@@ -237,7 +237,7 @@ public class GroupAutoTakedownTest {
}
@Test
- public void downed_config_retired_node_transitions_back_to_retired_on_up_edge() {
+ void downed_config_retired_node_transitions_back_to_retired_on_up_edge() {
ClusterFixture fixture = createFixtureForAllUpHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(2), 0.49);
@@ -252,14 +252,15 @@ public class GroupAutoTakedownTest {
nodes.add(new ConfiguredNode(5, true));
// TODO this should ideally also set the retired flag in the distribution
// config, but only the ConfiguredNodes are actually looked at currently.
- fixture.cluster.setNodes(nodes, new NodeListener() {});
+ fixture.cluster.setNodes(nodes, new NodeListener() {
+ });
assertEquals("distributor:6 storage:6 .4.s:d .5.s:r",
stateAfterStorageTransition(fixture, 5, State.UP));
}
@Test
- public void init_progress_is_preserved_across_group_down_up_edge() {
+ void init_progress_is_preserved_across_group_down_up_edge() {
ClusterFixture fixture = createFixtureForAllUpHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(2), 0.51);
@@ -277,7 +278,7 @@ public class GroupAutoTakedownTest {
}
@Test
- public void down_wanted_state_is_preserved_across_group_down_up_edge() {
+ void down_wanted_state_is_preserved_across_group_down_up_edge() {
ClusterFixture fixture = createFixtureForAllUpHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(3), 0.60);
@@ -294,7 +295,7 @@ public class GroupAutoTakedownTest {
}
@Test
- public void previously_cleared_start_timestamps_are_not_reintroduced_on_up_edge() throws Exception {
+ void previously_cleared_start_timestamps_are_not_reintroduced_on_up_edge() throws Exception {
ClusterFixture fixture = createFixtureForAllUpHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(2), 0.51);
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/GroupAvailabilityCalculatorTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/GroupAvailabilityCalculatorTest.java
index a5357e0a639..d176455f4c0 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/GroupAvailabilityCalculatorTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/GroupAvailabilityCalculatorTest.java
@@ -2,7 +2,7 @@
package com.yahoo.vespa.clustercontroller.core;
import com.yahoo.vdslib.state.ClusterState;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.text.ParseException;
import java.util.Collections;
@@ -49,7 +49,7 @@ public class GroupAvailabilityCalculatorTest {
private static Set<Integer> emptySet() { return indices(); }
@Test
- public void flat_cluster_does_not_implicitly_take_down_nodes() {
+ void flat_cluster_does_not_implicitly_take_down_nodes() {
GroupAvailabilityCalculator calc = calcForFlatCluster(5, 0.99);
assertThat(calc.nodesThatShouldBeDown(clusterState(
@@ -58,7 +58,7 @@ public class GroupAvailabilityCalculatorTest {
}
@Test
- public void group_node_down_edge_implicitly_marks_down_rest_of_nodes_in_group() {
+ void group_node_down_edge_implicitly_marks_down_rest_of_nodes_in_group() {
// 3 groups of 2 nodes, take down node #4 (1st node in last group). Since we require
// at least 51% of group capacity to be available, implicitly take down the last group
// entirely.
@@ -72,7 +72,7 @@ public class GroupAvailabilityCalculatorTest {
// Setting 50% as min ratio in a group with 2 nodes should let group be up if
// one node goes down.
@Test
- public void min_ratio_per_group_is_closed_interval() {
+ void min_ratio_per_group_is_closed_interval() {
GroupAvailabilityCalculator calc = calcForHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(2), 0.50);
assertThat(calc.nodesThatShouldBeDown(clusterState(
@@ -80,7 +80,7 @@ public class GroupAvailabilityCalculatorTest {
}
@Test
- public void retired_node_is_counted_as_down() {
+ void retired_node_is_counted_as_down() {
GroupAvailabilityCalculator calc = calcForHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(2), 0.99);
assertThat(calc.nodesThatShouldBeDown(clusterState(
@@ -88,7 +88,7 @@ public class GroupAvailabilityCalculatorTest {
}
@Test
- public void initializing_node_not_counted_as_down() {
+ void initializing_node_not_counted_as_down() {
GroupAvailabilityCalculator calc = calcForHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(2), 0.99);
assertThat(calc.nodesThatShouldBeDown(clusterState(
@@ -96,7 +96,7 @@ public class GroupAvailabilityCalculatorTest {
}
@Test
- public void maintenance_node_not_counted_as_down() {
+ void maintenance_node_not_counted_as_down() {
GroupAvailabilityCalculator calc = calcForHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(2), 0.99);
assertThat(calc.nodesThatShouldBeDown(clusterState(
@@ -104,7 +104,7 @@ public class GroupAvailabilityCalculatorTest {
}
@Test
- public void existing_maintenance_node_not_implicitly_downed_when_group_taken_down() {
+ void existing_maintenance_node_not_implicitly_downed_when_group_taken_down() {
GroupAvailabilityCalculator calc = calcForHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(3), 0.99);
assertThat(calc.nodesThatShouldBeDown(clusterState(
@@ -112,7 +112,7 @@ public class GroupAvailabilityCalculatorTest {
}
@Test
- public void existing_retired_node_not_implicitly_downed_when_group_taken_down() {
+ void existing_retired_node_not_implicitly_downed_when_group_taken_down() {
GroupAvailabilityCalculator calc = calcForHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(3), 0.99);
assertThat(calc.nodesThatShouldBeDown(clusterState(
@@ -120,7 +120,7 @@ public class GroupAvailabilityCalculatorTest {
}
@Test
- public void down_to_down_edge_keeps_group_down() {
+ void down_to_down_edge_keeps_group_down() {
GroupAvailabilityCalculator calc = calcForHierarchicCluster(
DistributionBuilder.withGroups(2).eachWithNodeCount(4), 0.76);
@@ -135,7 +135,7 @@ public class GroupAvailabilityCalculatorTest {
// causing "storage:6 .5.s:d" to be reduced to "storage:5". This still implies a
// node is down according to the distribution config and must be handled as such.
@Test
- public void implicitly_downed_node_at_state_end_is_counted_as_explicitly_down() {
+ void implicitly_downed_node_at_state_end_is_counted_as_explicitly_down() {
GroupAvailabilityCalculator calc = calcForHierarchicCluster(
DistributionBuilder.withGroups(3).eachWithNodeCount(2), 0.99);
assertThat(calc.nodesThatShouldBeDown(clusterState(
@@ -143,7 +143,7 @@ public class GroupAvailabilityCalculatorTest {
}
@Test
- public void non_uniform_group_sizes_are_supported() {
+ void non_uniform_group_sizes_are_supported() {
GroupAvailabilityCalculator calc = calcForHierarchicCluster(
DistributionBuilder.withGroupNodes(1, 2, 3, 4), 0.67);
@@ -167,7 +167,7 @@ public class GroupAvailabilityCalculatorTest {
}
@Test
- public void min_ratio_of_zero_never_takes_down_groups_implicitly() {
+ void min_ratio_of_zero_never_takes_down_groups_implicitly() {
GroupAvailabilityCalculator calc = calcForHierarchicCluster(
DistributionBuilder.withGroups(2).eachWithNodeCount(4), 0.0);
assertThat(calc.nodesThatShouldBeDown(clusterState(
@@ -184,7 +184,7 @@ public class GroupAvailabilityCalculatorTest {
}
@Test
- public void one_safe_maintenance_node_does_not_take_down_group() {
+ void one_safe_maintenance_node_does_not_take_down_group() {
// 2 groups of 5 nodes each. Set node #5 safely in maintenance (1st node in last group).
// Since the minimum number of nodes that can safely be set to maintenance before taking
// the whole group down is 2, the whole group should NOT be taken down.
@@ -204,7 +204,7 @@ public class GroupAvailabilityCalculatorTest {
}
@Test
- public void two_safe_maintenance_nodes_takes_down_group() {
+ void two_safe_maintenance_nodes_takes_down_group() {
// 2 groups of 5 nodes each. Set nodes #5 and #6 safely in maintenance (1st and 2nd nodes
// in last group, respectively). Since the minimum number of nodes that can safely be set to
// maintenance before taking the whole group down is 2, the whole group should be taken down.
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/LeafGroupsTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/LeafGroupsTest.java
index 418400b3fff..b6bd6a3bf75 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/LeafGroupsTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/LeafGroupsTest.java
@@ -2,7 +2,7 @@
package com.yahoo.vespa.clustercontroller.core;
import com.yahoo.vdslib.distribution.Group;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
@@ -12,7 +12,7 @@ import static org.hamcrest.MatcherAssert.assertThat;
public class LeafGroupsTest {
@Test
- public void rootGroupCountedAsLeafWhenNoChildren() {
+ void rootGroupCountedAsLeafWhenNoChildren() {
Group g = new Group(0, "donkeykong");
List<Group> leaves = LeafGroups.enumerateFrom(g);
@@ -25,7 +25,7 @@ public class LeafGroupsTest {
}
@Test
- public void singleLeafIsEnumerated() throws Exception {
+ void singleLeafIsEnumerated() throws Exception {
Group g = new Group(0, "donkeykong", dummyDistribution());
Group child = new Group(1, "mario");
g.addSubGroup(child);
@@ -36,7 +36,7 @@ public class LeafGroupsTest {
}
@Test
- public void singleLeafIsEnumeratedInNestedCase() throws Exception {
+ void singleLeafIsEnumeratedInNestedCase() throws Exception {
Group g = new Group(0, "donkeykong", dummyDistribution());
Group child = new Group(1, "mario", dummyDistribution());
child.addSubGroup(new Group(2, "toad"));
@@ -48,7 +48,7 @@ public class LeafGroupsTest {
}
@Test
- public void multipleLeafGroupsAreEnumerated() throws Exception {
+ void multipleLeafGroupsAreEnumerated() throws Exception {
Group g = new Group(0, "donkeykong", dummyDistribution());
Group child = new Group(1, "mario", dummyDistribution());
child.addSubGroup(new Group(2, "toad"));
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/MaintenanceWhenPendingGlobalMergesTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/MaintenanceWhenPendingGlobalMergesTest.java
index 2f79ad3fa95..6a05cc78508 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/MaintenanceWhenPendingGlobalMergesTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/MaintenanceWhenPendingGlobalMergesTest.java
@@ -3,7 +3,7 @@ package com.yahoo.vespa.clustercontroller.core;
import com.yahoo.document.FixedBucketSpaces;
import com.yahoo.vdslib.state.ClusterState;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
@@ -53,7 +53,7 @@ public class MaintenanceWhenPendingGlobalMergesTest {
}
@Test
- public void no_nodes_set_to_maintenance_in_global_bucket_space_state() {
+ void no_nodes_set_to_maintenance_in_global_bucket_space_state() {
Fixture f = new Fixture();
when(f.mockPendingChecker.mayHaveMergesPending(eq(globalSpace()), anyInt())).thenReturn(true); // False returned by default otherwise
AnnotatedClusterState derived = f.deriver.derivedFrom(stateFromString("distributor:2 storage:2"), globalSpace());
@@ -61,7 +61,7 @@ public class MaintenanceWhenPendingGlobalMergesTest {
}
@Test
- public void content_nodes_with_global_merge_pending_set_to_maintenance_in_default_space_state() {
+ void content_nodes_with_global_merge_pending_set_to_maintenance_in_default_space_state() {
Fixture f = new Fixture();
when(f.mockPendingChecker.mayHaveMergesPending(globalSpace(), 1)).thenReturn(true);
when(f.mockPendingChecker.mayHaveMergesPending(globalSpace(), 3)).thenReturn(true);
@@ -71,14 +71,14 @@ public class MaintenanceWhenPendingGlobalMergesTest {
}
@Test
- public void no_nodes_set_to_maintenance_when_no_merges_pending() {
+ void no_nodes_set_to_maintenance_when_no_merges_pending() {
Fixture f = new Fixture();
AnnotatedClusterState derived = f.deriver.derivedFrom(stateFromString("distributor:5 storage:5"), defaultSpace());
assertThat(derived, equalTo(stateFromString("distributor:5 storage:5")));
}
@Test
- public void default_space_merges_do_not_count_towards_maintenance() {
+ void default_space_merges_do_not_count_towards_maintenance() {
Fixture f = new Fixture();
when(f.mockPendingChecker.mayHaveMergesPending(eq(defaultSpace()), anyInt())).thenReturn(true);
AnnotatedClusterState derived = f.deriver.derivedFrom(stateFromString("distributor:2 storage:2"), defaultSpace());
@@ -86,7 +86,7 @@ public class MaintenanceWhenPendingGlobalMergesTest {
}
@Test
- public void nodes_only_set_to_maintenance_when_marked_up_init_or_retiring() {
+ void nodes_only_set_to_maintenance_when_marked_up_init_or_retiring() {
Fixture f = new Fixture();
when(f.mockPendingChecker.mayHaveMergesPending(eq(globalSpace()), anyInt())).thenReturn(true);
AnnotatedClusterState derived = f.deriver.derivedFrom(stateFromString("distributor:5 storage:5 .1.s:m .2.s:r .3.s:i .4.s:d"), defaultSpace());
@@ -96,7 +96,7 @@ public class MaintenanceWhenPendingGlobalMergesTest {
}
@Test
- public void node_state_reasons_are_used_as_baseline_in_default_bucket_space_state() {
+ void node_state_reasons_are_used_as_baseline_in_default_bucket_space_state() {
Fixture f = new Fixture();
when(f.mockPendingChecker.mayHaveMergesPending(globalSpace(), 1)).thenReturn(true);
when(f.mockPendingChecker.mayHaveMergesPending(globalSpace(), 3)).thenReturn(true);
@@ -108,7 +108,7 @@ public class MaintenanceWhenPendingGlobalMergesTest {
}
@Test
- public void node_with_pending_merges_only_set_to_maintenance_if_eligible() {
+ void node_with_pending_merges_only_set_to_maintenance_if_eligible() {
Fixture f = new Fixture();
Arrays.asList(1, 2, 3).forEach(idx -> when(f.mockPendingChecker.mayHaveMergesPending(globalSpace(), idx)).thenReturn(true));
Arrays.asList(1, 2, 4).forEach(idx -> when(f.mockTransitionConstraint.maintenanceTransitionAllowed(idx)).thenReturn(false));
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/MasterElectionTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/MasterElectionTest.java
index 257bb54047c..ae7ffd248d6 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/MasterElectionTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/MasterElectionTest.java
@@ -12,10 +12,9 @@ import com.yahoo.vdslib.state.NodeState;
import com.yahoo.vdslib.state.NodeType;
import com.yahoo.vdslib.state.State;
import com.yahoo.vespa.clustercontroller.core.status.StatusHandler;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TestRule;
-import org.junit.rules.Timeout;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+import org.junit.jupiter.api.extension.ExtendWith;
import java.util.ArrayList;
import java.util.List;
@@ -24,10 +23,12 @@ import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Stream;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+@ExtendWith(FleetControllerTest.CleanupZookeeperLogsOnSuccess.class)
+@Timeout(120)
public class MasterElectionTest extends FleetControllerTest {
private static final Logger log = Logger.getLogger(MasterElectionTest.class.getName());
@@ -35,12 +36,6 @@ public class MasterElectionTest extends FleetControllerTest {
private Supervisor supervisor;
private final List<FleetController> fleetControllers = new ArrayList<>();
- @Rule
- public TestRule cleanupZookeeperLogsOnSuccess = new CleanupZookeeperLogsOnSuccess();
-
- @Rule
- public Timeout globalTimeout = Timeout.seconds(120);
-
private static int defaultZkSessionTimeoutInMillis() { return 30_000; }
protected void setUpFleetController(int count, boolean useFakeTimer, FleetControllerOptions options) throws Exception {
@@ -116,7 +111,7 @@ public class MasterElectionTest extends FleetControllerTest {
}
@Test
- public void testMasterElection() throws Exception {
+ void testMasterElection() throws Exception {
startingTest("MasterElectionTest::testMasterElection");
log.log(Level.INFO, "STARTING TEST: MasterElectionTest::testMasterElection()");
FleetControllerOptions options = defaultOptions("mycluster");
@@ -135,7 +130,7 @@ public class MasterElectionTest extends FleetControllerTest {
// Too few for there to be a master at this point
for (int i = 0; i < fleetControllers.size(); ++i) {
if (fleetControllers.get(i).isRunning()) waitForCompleteCycle(i);
- assertFalse("Fleet controller " + i, fleetControllers.get(i).isMaster());
+ assertFalse(fleetControllers.get(i).isMaster(), "Fleet controller " + i);
}
StatusHandler.ContainerStatusPageServer statusPageServer = new StatusHandler.ContainerStatusPageServer();
@@ -222,7 +217,7 @@ public class MasterElectionTest extends FleetControllerTest {
}
@Test
- public void testClusterStateVersionIncreasesAcrossMasterElections() throws Exception {
+ void testClusterStateVersionIncreasesAcrossMasterElections() throws Exception {
startingTest("MasterElectionTest::testClusterStateVersionIncreasesAcrossMasterElections");
FleetControllerOptions options = defaultOptions("mycluster");
options.masterZooKeeperCooldownPeriod = 1;
@@ -243,7 +238,7 @@ public class MasterElectionTest extends FleetControllerTest {
}
@Test
- public void testVotingCorrectnessInFaceOfZKDisconnect() throws Exception {
+ void testVotingCorrectnessInFaceOfZKDisconnect() throws Exception {
startingTest("MasterElectionTest::testVotingCorrectnessInFaceOfZKDisconnect");
FleetControllerOptions options = defaultOptions("mycluster");
// "Magic" port value is in range allocated to module for testing.
@@ -264,7 +259,7 @@ public class MasterElectionTest extends FleetControllerTest {
}
@Test
- public void testZooKeeperUnavailable() throws Exception {
+ void testZooKeeperUnavailable() throws Exception {
startingTest("MasterElectionTest::testZooKeeperUnavailable");
FleetControllerOptions options = defaultOptions("mycluster");
options.masterZooKeeperCooldownPeriod = 100;
@@ -279,7 +274,7 @@ public class MasterElectionTest extends FleetControllerTest {
// No one can be master if server is unavailable
log.log(Level.INFO, "Checking master status");
for (int i = 0; i < fleetControllers.size(); ++i) {
- assertFalse("Index " + i, fleetControllers.get(i).isMaster());
+ assertFalse(fleetControllers.get(i).isMaster(), "Index " + i);
}
zooKeeperServer = new ZooKeeperTestServer();
@@ -295,7 +290,7 @@ public class MasterElectionTest extends FleetControllerTest {
}
@Test
- public void testMasterZooKeeperCooldown() throws Exception {
+ void testMasterZooKeeperCooldown() throws Exception {
startingTest("MasterElectionTest::testMasterZooKeeperCooldown");
FleetControllerOptions options = defaultOptions("mycluster");
options.masterZooKeeperCooldownPeriod = 3600 * 1000; // An hour
@@ -343,7 +338,7 @@ public class MasterElectionTest extends FleetControllerTest {
}
@Test
- public void testGetMaster() throws Exception {
+ void testGetMaster() throws Exception {
startingTest("MasterElectionTest::testGetMaster");
FleetControllerOptions options = defaultOptions("mycluster");
options.masterZooKeeperCooldownPeriod = 3600 * 1000; // An hour
@@ -364,33 +359,33 @@ public class MasterElectionTest extends FleetControllerTest {
Request req = new Request("getMaster");
- for (int nodeIndex = 0; nodeIndex<3; ++nodeIndex) {
+ for (int nodeIndex = 0; nodeIndex < 3; ++nodeIndex) {
for (int retry = 0; retry < FleetControllerTest.timeoutS * 10; ++retry) {
req = new Request("getMaster");
connections.get(nodeIndex).invokeSync(req, FleetControllerTest.timeoutS);
- assertFalse(req.errorMessage(), req.isError());
+ assertFalse(req.isError(), req.errorMessage());
if (req.returnValues().get(0).asInt32() == 0 &&
- req.returnValues().get(1).asString().equals("All 3 nodes agree that 0 is current master.")) {
+ req.returnValues().get(1).asString().equals("All 3 nodes agree that 0 is current master.")) {
break;
}
}
- assertEquals(req.toString(), 0, req.returnValues().get(0).asInt32());
- assertEquals(req.toString(), "All 3 nodes agree that 0 is current master.", req.returnValues().get(1).asString());
+ assertEquals(0, req.returnValues().get(0).asInt32(), req.toString());
+ assertEquals("All 3 nodes agree that 0 is current master.", req.returnValues().get(1).asString(), req.toString());
}
log.log(Level.INFO, "SHUTTING DOWN FLEET CONTROLLER 0");
fleetControllers.get(0).shutdown();
- // Wait until fc 1 & 2 votes for node 1
+ // Wait until fc 1 & 2 votes for node 1
waitForCompleteCycle(1);
waitForCompleteCycle(2);
- // 5 minutes is not long enough period to wait before letting this node be master.
+ // 5 minutes is not long enough period to wait before letting this node be master.
timer.advanceTime(300 * 1000); // 5 minutes
- int[] remainingNodes = { 1, 2 };
+ int[] remainingNodes = {1, 2};
waitForMasterReason(
"2 of 3 nodes agree 1 should be master, but old master cooldown period of 3600000 ms has not passed yet. To ensure it has got time to realize it is no longer master before we elect a new one, currently there is no master.",
-1, connections, remainingNodes);
- // Verify that fc 1 is not master, and the correct reasons for why not
+ // Verify that fc 1 is not master, and the correct reasons for why not
assertFalse(fleetControllers.get(1).isMaster());
// But after an hour it should become one.
@@ -399,31 +394,31 @@ public class MasterElectionTest extends FleetControllerTest {
req = new Request("getMaster");
connections.get(0).invokeSync(req, FleetControllerTest.timeoutS);
- assertEquals(req.toString(), 104, req.errorCode());
- assertEquals(req.toString(), "Connection error", req.errorMessage());
+ assertEquals(104, req.errorCode(), req.toString());
+ assertEquals("Connection error", req.errorMessage(), req.toString());
- for (int i=0; i<FleetControllerTest.timeoutS * 10; ++i) {
+ for (int i = 0; i < FleetControllerTest.timeoutS * 10; ++i) {
req = new Request("getMaster");
connections.get(1).invokeSync(req, FleetControllerTest.timeoutS);
- assertFalse(req.errorMessage(), req.isError());
+ assertFalse(req.isError(), req.errorMessage());
if (req.returnValues().get(0).asInt32() != -1) break;
- // We may have bad timing causing node not to have realized it is master yet
+ // We may have bad timing causing node not to have realized it is master yet
}
- assertEquals(req.toString(), 1, req.returnValues().get(0).asInt32());
- assertEquals(req.toString(), "2 of 3 nodes agree 1 is master.", req.returnValues().get(1).asString());
+ assertEquals(1, req.returnValues().get(0).asInt32(), req.toString());
+ assertEquals("2 of 3 nodes agree 1 is master.", req.returnValues().get(1).asString(), req.toString());
- for (int i=0; i<FleetControllerTest.timeoutS * 10; ++i) {
+ for (int i = 0; i < FleetControllerTest.timeoutS * 10; ++i) {
req = new Request("getMaster");
connections.get(2).invokeSync(req, FleetControllerTest.timeoutS);
- assertFalse(req.errorMessage(), req.isError());
+ assertFalse(req.isError(), req.errorMessage());
if (req.returnValues().get(0).asInt32() != -1) break;
}
- assertEquals(req.toString(), 1, req.returnValues().get(0).asInt32());
- assertEquals(req.toString(), "2 of 3 nodes agree 1 is master.", req.returnValues().get(1).asString());
+ assertEquals(1, req.returnValues().get(0).asInt32(), req.toString());
+ assertEquals("2 of 3 nodes agree 1 is master.", req.returnValues().get(1).asString(), req.toString());
}
@Test
- public void testReconfigure() throws Exception {
+ void testReconfigure() throws Exception {
startingTest("MasterElectionTest::testReconfigure");
FleetControllerOptions options = defaultOptions("mycluster");
options.masterZooKeeperCooldownPeriod = 1;
@@ -431,7 +426,7 @@ public class MasterElectionTest extends FleetControllerTest {
waitForMaster(0);
FleetControllerOptions newOptions = options.clone();
- for (int i=0; i<fleetControllers.size(); ++i) {
+ for (int i = 0; i < fleetControllers.size(); ++i) {
FleetControllerOptions nodeOptions = adjustConfig(newOptions, i, fleetControllers.size());
fleetControllers.get(i).updateOptions(nodeOptions);
}
@@ -448,7 +443,7 @@ public class MasterElectionTest extends FleetControllerTest {
* risk rolling back the version number in the face of a reelection.
*/
@Test
- public void cluster_state_version_written_to_zookeeper_even_with_empty_send_set() throws Exception {
+ void cluster_state_version_written_to_zookeeper_even_with_empty_send_set() throws Exception {
startingTest("MasterElectionTest::cluster_state_version_written_to_zookeeper_even_with_empty_send_set");
FleetControllerOptions options = defaultOptions("mycluster");
options.masterZooKeeperCooldownPeriod = 1;
@@ -474,7 +469,7 @@ public class MasterElectionTest extends FleetControllerTest {
n.disconnectImmediately();
waitForCompleteCycle(0);
});
- setWantedState(this.nodes.get(2*10 - 1), State.MAINTENANCE, "bar");
+ setWantedState(this.nodes.get(2 * 10 - 1), State.MAINTENANCE, "bar");
waitForCompleteCycle(0);
// This receives the version number of the highest _working_ cluster state, with
@@ -494,7 +489,7 @@ public class MasterElectionTest extends FleetControllerTest {
}
@Test
- public void previously_published_state_is_taken_into_account_for_default_space_when_controller_bootstraps() throws Exception {
+ void previously_published_state_is_taken_into_account_for_default_space_when_controller_bootstraps() throws Exception {
startingTest("MasterElectionTest::previously_published_state_is_taken_into_account_for_default_space_when_controller_bootstraps");
FleetControllerOptions options = defaultOptions("mycluster");
options.clusterHasGlobalDocumentTypes = true;
@@ -537,7 +532,7 @@ public class MasterElectionTest extends FleetControllerTest {
}
@Test
- public void default_space_nodes_not_marked_as_maintenance_when_cluster_has_no_global_document_types() throws Exception {
+ void default_space_nodes_not_marked_as_maintenance_when_cluster_has_no_global_document_types() throws Exception {
startingTest("MasterElectionTest::default_space_nodes_not_marked_as_maintenance_when_cluster_has_no_global_document_types");
FleetControllerOptions options = defaultOptions("mycluster");
options.clusterHasGlobalDocumentTypes = false;
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/MetricReporterTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/MetricReporterTest.java
index 4cd2fcdfbd5..a6defaee7fe 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/MetricReporterTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/MetricReporterTest.java
@@ -4,7 +4,7 @@ package com.yahoo.vespa.clustercontroller.core;
import com.yahoo.vdslib.state.ClusterState;
import com.yahoo.vespa.clustercontroller.core.matchers.HasMetricContext;
import com.yahoo.vespa.clustercontroller.utils.util.MetricReporter;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Map;
@@ -57,7 +57,7 @@ public class MetricReporterTest {
}
@Test
- public void metrics_are_emitted_for_different_node_state_counts() {
+ void metrics_are_emitted_for_different_node_state_counts() {
Fixture f = new Fixture();
f.metricUpdater.updateClusterStateMetrics(f.clusterFixture.cluster(),
ClusterState.stateFromString("distributor:10 .1.s:d storage:9 .1.s:d .2.s:m .4.s:d"),
@@ -90,28 +90,28 @@ public class MetricReporterTest {
}
@Test
- public void metrics_are_emitted_for_partial_node_availability_ratio() {
+ void metrics_are_emitted_for_partial_node_availability_ratio() {
// Only Up, Init, Retired and Maintenance are counted as available states
doTestRatiosInState("distributor:10 .1.s:d storage:9 .1.s:d .2.s:m .4.s:r .5.s:i .6.s:s", 0.9, 0.7);
}
@Test
- public void metrics_are_emitted_for_full_node_availability_ratio() {
+ void metrics_are_emitted_for_full_node_availability_ratio() {
doTestRatiosInState("distributor:10 storage:10", 1.0, 1.0);
}
@Test
- public void metrics_are_emitted_for_zero_node_availability_ratio() {
+ void metrics_are_emitted_for_zero_node_availability_ratio() {
doTestRatiosInState("cluster:d", 0.0, 0.0);
}
@Test
- public void maintenance_mode_is_counted_as_available() {
+ void maintenance_mode_is_counted_as_available() {
doTestRatiosInState("distributor:10 storage:10 .0.s:m", 1.0, 1.0);
}
@Test
- public void metrics_are_emitted_for_resource_usage() {
+ void metrics_are_emitted_for_resource_usage() {
Fixture f = new Fixture();
f.metricUpdater.updateClusterStateMetrics(f.clusterFixture.cluster(),
ClusterState.stateFromString("distributor:10 storage:10"),
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/NoZooKeeperTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/NoZooKeeperTest.java
index bd1ffac089c..62a49ecf969 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/NoZooKeeperTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/NoZooKeeperTest.java
@@ -1,13 +1,14 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.clustercontroller.core;
-import org.junit.Test;
-import static org.junit.Assert.assertTrue;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
public class NoZooKeeperTest extends FleetControllerTest {
@Test
- public void testWantedStatesInZooKeeper() throws Exception {
+ void testWantedStatesInZooKeeper() throws Exception {
startingTest("NoZooKeeperTest::testWantedStatesInZooKeeper");
FleetControllerOptions options = defaultOptions("mycluster");
options.zooKeeperServerAddress = null;
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/NodeInfoTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/NodeInfoTest.java
index 129c70d1d29..4b068d107bf 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/NodeInfoTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/NodeInfoTest.java
@@ -4,16 +4,14 @@ package com.yahoo.vespa.clustercontroller.core;
import com.yahoo.vdslib.state.Node;
import com.yahoo.vdslib.state.NodeType;
import com.yahoo.vdslib.state.State;
-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.jupiter.api.Assertions.*;
public class NodeInfoTest {
@Test
- public void unstable_init_flag_is_initially_clear() {
+ void unstable_init_flag_is_initially_clear() {
ClusterFixture fixture = ClusterFixture.forFlatCluster(3);
final NodeInfo nodeInfo = fixture.cluster.getNodeInfo(new Node(NodeType.STORAGE, 1));
assertFalse(nodeInfo.recentlyObservedUnstableDuringInit());
@@ -26,7 +24,7 @@ public class NodeInfoTest {
}
@Test
- public void down_edge_during_init_state_marks_as_unstable_init() {
+ void down_edge_during_init_state_marks_as_unstable_init() {
ClusterFixture fixture = fixtureWithNodeMarkedAsUnstableInit(1);
final NodeInfo nodeInfo = fixture.cluster.getNodeInfo(new Node(NodeType.STORAGE, 1));
@@ -34,7 +32,7 @@ public class NodeInfoTest {
}
@Test
- public void stopping_edge_during_init_does_not_mark_as_unstable_init() {
+ void stopping_edge_during_init_does_not_mark_as_unstable_init() {
ClusterFixture fixture = ClusterFixture.forFlatCluster(3).reportStorageNodeState(0, State.INITIALIZING);
fixture.reportStorageNodeState(0, State.STOPPING);
final NodeInfo nodeInfo = fixture.cluster.getNodeInfo(new Node(NodeType.STORAGE, 0));
@@ -48,7 +46,7 @@ public class NodeInfoTest {
* from haunting a now stable node.
*/
@Test
- public void zeroing_crash_count_resets_unstable_init_flag() {
+ void zeroing_crash_count_resets_unstable_init_flag() {
ClusterFixture fixture = fixtureWithNodeMarkedAsUnstableInit(1);
final NodeInfo nodeInfo = fixture.cluster.getNodeInfo(new Node(NodeType.STORAGE, 1));
@@ -61,7 +59,7 @@ public class NodeInfoTest {
* further instabilities and should not clear the unstable init flag.
*/
@Test
- public void non_zero_crash_count_update_does_not_reset_unstable_init_flag() {
+ void non_zero_crash_count_update_does_not_reset_unstable_init_flag() {
ClusterFixture fixture = fixtureWithNodeMarkedAsUnstableInit(1);
final NodeInfo nodeInfo = fixture.cluster.getNodeInfo(new Node(NodeType.STORAGE, 1));
@@ -70,7 +68,7 @@ public class NodeInfoTest {
}
@Test
- public void non_zero_crash_count_does_not_implicitly_set_unstable_init_flag() {
+ void non_zero_crash_count_does_not_implicitly_set_unstable_init_flag() {
ClusterFixture fixture = ClusterFixture.forFlatCluster(3);
final NodeInfo nodeInfo = fixture.cluster.getNodeInfo(new Node(NodeType.STORAGE, 1));
@@ -79,7 +77,7 @@ public class NodeInfoTest {
}
@Test
- public void down_wanted_state_overrides_config_retired_state() {
+ void down_wanted_state_overrides_config_retired_state() {
ClusterFixture fixture = ClusterFixture.forFlatCluster(3)
.markNodeAsConfigRetired(1)
.proposeStorageNodeWantedState(1, State.DOWN);
@@ -89,7 +87,7 @@ public class NodeInfoTest {
}
@Test
- public void maintenance_wanted_state_overrides_config_retired_state() {
+ void maintenance_wanted_state_overrides_config_retired_state() {
ClusterFixture fixture = ClusterFixture.forFlatCluster(3)
.markNodeAsConfigRetired(1)
.proposeStorageNodeWantedState(1, State.MAINTENANCE);
@@ -99,7 +97,7 @@ public class NodeInfoTest {
}
@Test
- public void retired_state_overrides_default_up_wanted_state() {
+ void retired_state_overrides_default_up_wanted_state() {
final ClusterFixture fixture = ClusterFixture.forFlatCluster(3).markNodeAsConfigRetired(1);
NodeInfo nodeInfo = fixture.cluster.getNodeInfo(new Node(NodeType.STORAGE, 1));
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/NodeSlobrokConfigurationMembershipTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/NodeSlobrokConfigurationMembershipTest.java
index ea539cc13e0..69ddf8e2c02 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/NodeSlobrokConfigurationMembershipTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/NodeSlobrokConfigurationMembershipTest.java
@@ -2,12 +2,12 @@
package com.yahoo.vespa.clustercontroller.core;
import com.yahoo.vdslib.distribution.ConfiguredNode;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Set;
import java.util.TreeSet;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
public class NodeSlobrokConfigurationMembershipTest extends FleetControllerTest {
@@ -32,13 +32,13 @@ public class NodeSlobrokConfigurationMembershipTest extends FleetControllerTest
}
@Test
- public void testSlobrokNodeOutsideConfiguredIndexSetIsNotIncludedInCluster() throws Exception {
+ void testSlobrokNodeOutsideConfiguredIndexSetIsNotIncludedInCluster() throws Exception {
setUpClusterWithForeignNode(nodeIndices, foreignNode);
waitForStateExcludingNodeSubset("version:\\d+ distributor:4 storage:4", asIntSet(foreignNode));
}
@Test
- public void testNodeSetReconfigurationForcesFreshSlobrokFetch() throws Exception {
+ void testNodeSetReconfigurationForcesFreshSlobrokFetch() throws Exception {
setUpClusterWithForeignNode(nodeIndices, foreignNode);
waitForStateExcludingNodeSubset("version:\\d+ distributor:4 storage:4", asIntSet(foreignNode));
@@ -53,7 +53,7 @@ public class NodeSlobrokConfigurationMembershipTest extends FleetControllerTest
}
@Test
- public void test_removed_retired_node_is_not_included_in_state() throws Exception {
+ void test_removed_retired_node_is_not_included_in_state() throws Exception {
final Set<ConfiguredNode> configuredNodes = asConfiguredNodes(nodeIndices);
FleetControllerOptions options = optionsForConfiguredNodes(configuredNodes);
setUpFleetController(true, options);
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/NodeStateChangeCheckerTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/NodeStateChangeCheckerTest.java
index 87e102c67c1..6af852aa3ed 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/NodeStateChangeCheckerTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/NodeStateChangeCheckerTest.java
@@ -13,17 +13,14 @@ import com.yahoo.vdslib.state.State;
import com.yahoo.vespa.clustercontroller.core.hostinfo.HostInfo;
import com.yahoo.vespa.clustercontroller.utils.staterestapi.requests.SetUnitStateRequest;
import com.yahoo.vespa.config.content.StorDistributionConfig;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.text.ParseException;
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.assertNotEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -107,7 +104,7 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testCanUpgradeForce() {
+ void testCanUpgradeForce() {
NodeStateChangeChecker nodeStateChangeChecker = createChangeChecker(createCluster(createNodes(1)));
NodeState newState = new NodeState(NodeType.STORAGE, State.INITIALIZING);
NodeStateChangeChecker.Result result = nodeStateChangeChecker.evaluateTransition(
@@ -118,7 +115,7 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testDeniedInMoratorium() {
+ void testDeniedInMoratorium() {
ContentCluster cluster = createCluster(createNodes(4));
NodeStateChangeChecker nodeStateChangeChecker = new NodeStateChangeChecker(
requiredRedundancy, noopVisiting, cluster.clusterInfo(), true);
@@ -131,7 +128,7 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testUnknownStorageNode() {
+ void testUnknownStorageNode() {
ContentCluster cluster = createCluster(createNodes(4));
NodeStateChangeChecker nodeStateChangeChecker = new NodeStateChangeChecker(
requiredRedundancy, noopVisiting, cluster.clusterInfo(), false);
@@ -144,7 +141,7 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testSafeMaintenanceDisallowedWhenOtherStorageNodeInFlatClusterIsSuspended() {
+ void testSafeMaintenanceDisallowedWhenOtherStorageNodeInFlatClusterIsSuspended() {
// Nodes 0-3, storage node 0 being in maintenance with "Orchestrator" description.
ContentCluster cluster = createCluster(createNodes(4));
cluster.clusterInfo().getStorageNodeInfo(0).setWantedState(new NodeState(NodeType.STORAGE, State.MAINTENANCE).setDescription("Orchestrator"));
@@ -164,7 +161,7 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testSafeMaintenanceDisallowedWhenOtherDistributorInFlatClusterIsSuspended() {
+ void testSafeMaintenanceDisallowedWhenOtherDistributorInFlatClusterIsSuspended() {
// Nodes 0-3, storage node 0 being in maintenance with "Orchestrator" description.
ContentCluster cluster = createCluster(createNodes(4));
cluster.clusterInfo().getDistributorNodeInfo(0)
@@ -185,7 +182,7 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testSafeMaintenanceDisallowedWhenDistributorInGroupIsDown() {
+ void testSafeMaintenanceDisallowedWhenDistributorInGroupIsDown() {
// Nodes 0-3, distributor 0 being in maintenance with "Orchestrator" description.
// 2 groups: nodes 0-1 is group 0, 2-3 is group 1.
ContentCluster cluster = createCluster(createNodes(4));
@@ -214,13 +211,13 @@ public class NodeStateChangeCheckerTest {
NodeStateChangeChecker.Result result = nodeStateChangeChecker.evaluateTransition(
new Node(NodeType.STORAGE, 1), clusterStateWith0InMaintenance,
SetUnitStateRequest.Condition.SAFE, UP_NODE_STATE, MAINTENANCE_NODE_STATE);
- assertFalse(result.getReason(), result.settingWantedStateIsAllowed());
+ assertFalse(result.settingWantedStateIsAllowed(), result.getReason());
assertEquals("Another distributor wants state DOWN: 0", result.getReason());
}
}
@Test
- public void testSafeMaintenanceWhenOtherStorageNodeInGroupIsSuspended() {
+ void testSafeMaintenanceWhenOtherStorageNodeInGroupIsSuspended() {
// Nodes 0-3, storage node 0 being in maintenance with "Orchestrator" description.
// 2 groups: nodes 0-1 is group 0, 2-3 is group 1.
ContentCluster cluster = createCluster(createNodes(4));
@@ -249,7 +246,7 @@ public class NodeStateChangeCheckerTest {
NodeStateChangeChecker.Result result = nodeStateChangeChecker.evaluateTransition(
new Node(NodeType.STORAGE, 1), clusterStateWith0InMaintenance,
SetUnitStateRequest.Condition.SAFE, UP_NODE_STATE, MAINTENANCE_NODE_STATE);
- assertTrue(result.getReason(), result.settingWantedStateIsAllowed());
+ assertTrue(result.settingWantedStateIsAllowed(), result.getReason());
assertFalse(result.wantedStateAlreadySet());
}
}
@@ -295,7 +292,7 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testSafeSetStateDistributors() {
+ void testSafeSetStateDistributors() {
NodeStateChangeChecker nodeStateChangeChecker = createChangeChecker(createCluster(createNodes(1)));
NodeStateChangeChecker.Result result = nodeStateChangeChecker.evaluateTransition(
nodeDistributor, defaultAllUpClusterState(), SetUnitStateRequest.Condition.SAFE,
@@ -306,7 +303,7 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testCanUpgradeSafeMissingStorage() {
+ void testCanUpgradeSafeMissingStorage() {
// Create a content cluster with 4 nodes, and storage node with index 3 down.
ContentCluster cluster = createCluster(createNodes(4));
setAllNodesUp(cluster, HostInfo.createHostInfo(createDistributorHostInfo(4, 5, 6)));
@@ -327,14 +324,14 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testCanUpgradeStorageSafeYes() {
+ void testCanUpgradeStorageSafeYes() {
NodeStateChangeChecker.Result result = transitionToMaintenanceWithNoStorageNodesDown();
assertTrue(result.settingWantedStateIsAllowed());
assertFalse(result.wantedStateAlreadySet());
}
@Test
- public void testSetUpFailsIfReportedIsDown() {
+ void testSetUpFailsIfReportedIsDown() {
ContentCluster cluster = createCluster(createNodes(4));
NodeStateChangeChecker nodeStateChangeChecker = createChangeChecker(cluster);
// Not setting nodes up -> all are down
@@ -349,7 +346,7 @@ public class NodeStateChangeCheckerTest {
// A node may be reported as Up but have a generated state of Down if it's part of
// nodes taken down implicitly due to a group having too low node availability.
@Test
- public void testSetUpSucceedsIfReportedIsUpButGeneratedIsDown() {
+ void testSetUpSucceedsIfReportedIsUpButGeneratedIsDown() {
ContentCluster cluster = createCluster(createNodes(4));
NodeStateChangeChecker nodeStateChangeChecker = createChangeChecker(cluster);
@@ -367,7 +364,7 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testCanSetUpEvenIfOldWantedStateIsDown() {
+ void testCanSetUpEvenIfOldWantedStateIsDown() {
ContentCluster cluster = createCluster(createNodes(4));
NodeStateChangeChecker nodeStateChangeChecker = createChangeChecker(cluster);
setAllNodesUp(cluster, HostInfo.createHostInfo(createDistributorHostInfo(4, 3, 6)));
@@ -380,7 +377,7 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testCanUpgradeStorageSafeNo() {
+ void testCanUpgradeStorageSafeNo() {
ContentCluster cluster = createCluster(createNodes(4));
NodeStateChangeChecker nodeStateChangeChecker = createChangeChecker(cluster);
setAllNodesUp(cluster, HostInfo.createHostInfo(createDistributorHostInfo(4, 3, 6)));
@@ -395,7 +392,7 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testCanUpgradeIfMissingMinReplicationFactor() {
+ void testCanUpgradeIfMissingMinReplicationFactor() {
ContentCluster cluster = createCluster(createNodes(4));
NodeStateChangeChecker nodeStateChangeChecker = createChangeChecker(cluster);
setAllNodesUp(cluster, HostInfo.createHostInfo(createDistributorHostInfo(4, 3, 6)));
@@ -408,7 +405,7 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testCanUpgradeIfStorageNodeMissingFromNodeInfo() {
+ void testCanUpgradeIfStorageNodeMissingFromNodeInfo() {
ContentCluster cluster = createCluster(createNodes(4));
NodeStateChangeChecker nodeStateChangeChecker = createChangeChecker(cluster);
String hostInfo = "{\n" +
@@ -432,7 +429,7 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testMissingDistributorState() {
+ void testMissingDistributorState() {
ContentCluster cluster = createCluster(createNodes(4));
NodeStateChangeChecker nodeStateChangeChecker = createChangeChecker(cluster);
cluster.clusterInfo().getStorageNodeInfo(1).setReportedState(new NodeState(NodeType.STORAGE, State.UP), 0);
@@ -460,20 +457,20 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testSettingUpWhenUpCausesAlreadySet() {
+ void testSettingUpWhenUpCausesAlreadySet() {
NodeStateChangeChecker.Result result = transitionToSameState(State.UP, "foo", "bar");
assertTrue(result.wantedStateAlreadySet());
}
@Test
- public void testSettingAlreadySetState() {
+ void testSettingAlreadySetState() {
NodeStateChangeChecker.Result result = transitionToSameState("foo", "foo");
assertFalse(result.settingWantedStateIsAllowed());
assertTrue(result.wantedStateAlreadySet());
}
@Test
- public void testDifferentDescriptionImpliesDenied() {
+ void testDifferentDescriptionImpliesDenied() {
NodeStateChangeChecker.Result result = transitionToSameState("foo", "bar");
assertFalse(result.settingWantedStateIsAllowed());
assertFalse(result.wantedStateAlreadySet());
@@ -526,28 +523,28 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testCanUpgradeWhenAllUp() {
+ void testCanUpgradeWhenAllUp() {
NodeStateChangeChecker.Result result = transitionToMaintenanceWithNoStorageNodesDown();
assertTrue(result.settingWantedStateIsAllowed());
assertFalse(result.wantedStateAlreadySet());
}
@Test
- public void testCanUpgradeWhenAllUpOrRetired() {
+ void testCanUpgradeWhenAllUpOrRetired() {
NodeStateChangeChecker.Result result = transitionToMaintenanceWithNoStorageNodesDown();
assertTrue(result.settingWantedStateIsAllowed());
assertFalse(result.wantedStateAlreadySet());
}
@Test
- public void testCanUpgradeWhenStorageIsDown() {
+ void testCanUpgradeWhenStorageIsDown() {
NodeStateChangeChecker.Result result = transitionToMaintenanceWithOneStorageNodeDown(nodeStorage.getIndex());
assertTrue(result.settingWantedStateIsAllowed());
assertFalse(result.wantedStateAlreadySet());
}
@Test
- public void testCannotUpgradeWhenOtherStorageIsDown() {
+ void testCannotUpgradeWhenOtherStorageIsDown() {
int otherIndex = 2;
// If this fails, just set otherIndex to some other valid index.
assertNotEquals(nodeStorage.getIndex(), otherIndex);
@@ -559,7 +556,7 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testNodeRatioRequirementConsidersGeneratedNodeStates() {
+ void testNodeRatioRequirementConsidersGeneratedNodeStates() {
ContentCluster cluster = createCluster(createNodes(4));
NodeStateChangeChecker nodeStateChangeChecker = createChangeChecker(cluster);
@@ -581,7 +578,7 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testDownDisallowedByNonRetiredState() {
+ void testDownDisallowedByNonRetiredState() {
NodeStateChangeChecker.Result result = evaluateDownTransition(
defaultAllUpClusterState(),
State.UP,
@@ -593,7 +590,7 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testDownDisallowedByBuckets() {
+ void testDownDisallowedByBuckets() {
NodeStateChangeChecker.Result result = evaluateDownTransition(
retiredClusterStateSuffix(),
State.UP,
@@ -605,7 +602,7 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testDownDisallowedByReportedState() {
+ void testDownDisallowedByReportedState() {
NodeStateChangeChecker.Result result = evaluateDownTransition(
retiredClusterStateSuffix(),
State.INITIALIZING,
@@ -617,7 +614,7 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testDownDisallowedByVersionMismatch() {
+ void testDownDisallowedByVersionMismatch() {
NodeStateChangeChecker.Result result = evaluateDownTransition(
retiredClusterStateSuffix(),
State.UP,
@@ -630,7 +627,7 @@ public class NodeStateChangeCheckerTest {
}
@Test
- public void testAllowedToSetDown() {
+ void testAllowedToSetDown() {
NodeStateChangeChecker.Result result = evaluateDownTransition(
retiredClusterStateSuffix(),
State.UP,
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ResourceExhaustionCalculatorTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ResourceExhaustionCalculatorTest.java
index e136ddfa72d..24945d0d261 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ResourceExhaustionCalculatorTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ResourceExhaustionCalculatorTest.java
@@ -2,7 +2,7 @@
package com.yahoo.vespa.clustercontroller.core;
import com.yahoo.vdslib.state.State;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static com.yahoo.vespa.clustercontroller.core.ClusterFixture.storageNode;
import static com.yahoo.vespa.clustercontroller.core.FeedBlockUtil.createFixtureWithReportedUsages;
@@ -11,27 +11,24 @@ import static com.yahoo.vespa.clustercontroller.core.FeedBlockUtil.forNode;
import static com.yahoo.vespa.clustercontroller.core.FeedBlockUtil.mapOf;
import static com.yahoo.vespa.clustercontroller.core.FeedBlockUtil.setOf;
import static com.yahoo.vespa.clustercontroller.core.FeedBlockUtil.usage;
-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.*;
public class ResourceExhaustionCalculatorTest {
@Test
- public void no_feed_block_returned_when_no_resources_lower_than_limit() {
+ void no_feed_block_returned_when_no_resources_lower_than_limit() {
var calc = new ResourceExhaustionCalculator(true, mapOf(usage("disk", 0.5), usage("memory", 0.8)));
var cf = createFixtureWithReportedUsages(forNode(1, usage("disk", 0.49), usage("memory", 0.79)),
- forNode(2, usage("disk", 0.4), usage("memory", 0.6)));
+ forNode(2, usage("disk", 0.4), usage("memory", 0.6)));
var feedBlock = calc.inferContentClusterFeedBlockOrNull(cf.cluster().getNodeInfos());
assertNull(feedBlock);
}
@Test
- public void feed_block_returned_when_single_resource_beyond_limit() {
+ void feed_block_returned_when_single_resource_beyond_limit() {
var calc = new ResourceExhaustionCalculator(true, mapOf(usage("disk", 0.5), usage("memory", 0.8)));
var cf = createFixtureWithReportedUsages(forNode(1, usage("disk", 0.51), usage("memory", 0.79)),
- forNode(2, usage("disk", 0.4), usage("memory", 0.6)));
+ forNode(2, usage("disk", 0.4), usage("memory", 0.6)));
var feedBlock = calc.inferContentClusterFeedBlockOrNull(cf.cluster().getNodeInfos());
assertNotNull(feedBlock);
assertTrue(feedBlock.blockFeedInCluster());
@@ -39,10 +36,10 @@ public class ResourceExhaustionCalculatorTest {
}
@Test
- public void feed_block_description_can_contain_optional_name_component() {
+ void feed_block_description_can_contain_optional_name_component() {
var calc = new ResourceExhaustionCalculator(true, mapOf(usage("disk", 0.5), usage("memory", 0.8)));
var cf = createFixtureWithReportedUsages(forNode(1, usage("disk", "a-fancy-disk", 0.51), usage("memory", 0.79)),
- forNode(2, usage("disk", 0.4), usage("memory", 0.6)));
+ forNode(2, usage("disk", 0.4), usage("memory", 0.6)));
var feedBlock = calc.inferContentClusterFeedBlockOrNull(cf.cluster().getNodeInfos());
assertNotNull(feedBlock);
assertTrue(feedBlock.blockFeedInCluster());
@@ -50,80 +47,80 @@ public class ResourceExhaustionCalculatorTest {
}
@Test
- public void missing_or_malformed_rpc_addresses_are_emitted_as_unknown_hostnames() {
+ void missing_or_malformed_rpc_addresses_are_emitted_as_unknown_hostnames() {
var calc = new ResourceExhaustionCalculator(true, mapOf(usage("disk", 0.5), usage("memory", 0.8)));
var cf = createFixtureWithReportedUsages(forNode(1, usage("disk", 0.51), usage("memory", 0.79)),
- forNode(2, usage("disk", 0.4), usage("memory", 0.85)));
+ forNode(2, usage("disk", 0.4), usage("memory", 0.85)));
cf.cluster().getNodeInfo(storageNode(1)).setRpcAddress(null);
cf.cluster().getNodeInfo(storageNode(2)).setRpcAddress("max mekker");
var feedBlock = calc.inferContentClusterFeedBlockOrNull(cf.cluster().getNodeInfos());
assertNotNull(feedBlock);
assertTrue(feedBlock.blockFeedInCluster());
assertEquals("disk on node 1 [unknown hostname] (0.510 > 0.500), " +
- "memory on node 2 [unknown hostname] (0.850 > 0.800)", feedBlock.getDescription());
+ "memory on node 2 [unknown hostname] (0.850 > 0.800)", feedBlock.getDescription());
}
@Test
- public void feed_block_returned_when_multiple_resources_beyond_limit() {
+ void feed_block_returned_when_multiple_resources_beyond_limit() {
var calc = new ResourceExhaustionCalculator(true, mapOf(usage("disk", 0.4), usage("memory", 0.8)));
var cf = createFixtureWithReportedUsages(forNode(1, usage("disk", 0.51), usage("memory", 0.85)),
- forNode(2, usage("disk", 0.45), usage("memory", 0.6)));
+ forNode(2, usage("disk", 0.45), usage("memory", 0.6)));
var feedBlock = calc.inferContentClusterFeedBlockOrNull(cf.cluster().getNodeInfos());
assertNotNull(feedBlock);
assertTrue(feedBlock.blockFeedInCluster());
assertEquals("disk on node 1 [storage.1.local] (0.510 > 0.400), " +
- "memory on node 1 [storage.1.local] (0.850 > 0.800), " +
- "disk on node 2 [storage.2.local] (0.450 > 0.400)",
- feedBlock.getDescription());
+ "memory on node 1 [storage.1.local] (0.850 > 0.800), " +
+ "disk on node 2 [storage.2.local] (0.450 > 0.400)",
+ feedBlock.getDescription());
}
@Test
- public void feed_block_description_is_bounded_in_number_of_described_resources() {
+ void feed_block_description_is_bounded_in_number_of_described_resources() {
var calc = new ResourceExhaustionCalculator(true, mapOf(usage("disk", 0.4), usage("memory", 0.8)));
var cf = createFixtureWithReportedUsages(forNode(1, usage("disk", 0.51), usage("memory", 0.85)),
- forNode(2, usage("disk", 0.45), usage("memory", 0.6)),
- forNode(3, usage("disk", 0.6), usage("memory", 0.9)));
+ forNode(2, usage("disk", 0.45), usage("memory", 0.6)),
+ forNode(3, usage("disk", 0.6), usage("memory", 0.9)));
var feedBlock = calc.inferContentClusterFeedBlockOrNull(cf.cluster().getNodeInfos());
assertNotNull(feedBlock);
assertTrue(feedBlock.blockFeedInCluster());
assertEquals("disk on node 1 [storage.1.local] (0.510 > 0.400), " +
- "memory on node 1 [storage.1.local] (0.850 > 0.800), " +
- "disk on node 2 [storage.2.local] (0.450 > 0.400) (... and 2 more)",
- feedBlock.getDescription());
+ "memory on node 1 [storage.1.local] (0.850 > 0.800), " +
+ "disk on node 2 [storage.2.local] (0.450 > 0.400) (... and 2 more)",
+ feedBlock.getDescription());
}
@Test
- public void no_feed_block_returned_when_feed_block_disabled() {
+ void no_feed_block_returned_when_feed_block_disabled() {
var calc = new ResourceExhaustionCalculator(false, mapOf(usage("disk", 0.5), usage("memory", 0.8)));
var cf = createFixtureWithReportedUsages(forNode(1, usage("disk", 0.51), usage("memory", 0.79)),
- forNode(2, usage("disk", 0.4), usage("memory", 0.6)));
+ forNode(2, usage("disk", 0.4), usage("memory", 0.6)));
var feedBlock = calc.inferContentClusterFeedBlockOrNull(cf.cluster().getNodeInfos());
assertNull(feedBlock);
}
@Test
- public void retain_node_feed_block_status_when_within_hysteresis_window_limit_crossed_edge_case() {
+ void retain_node_feed_block_status_when_within_hysteresis_window_limit_crossed_edge_case() {
var curFeedBlock = ClusterStateBundle.FeedBlock.blockedWith("foo", setOf(exhaustion(1, "memory", 0.51)));
var calc = new ResourceExhaustionCalculator(true, mapOf(usage("disk", 0.5), usage("memory", 0.5)), curFeedBlock, 0.1);
// Node 1 goes from 0.51 to 0.49, crossing the 0.5 threshold. Should still be blocked.
// Node 2 is at 0.49 but was not previously blocked and should not be blocked now either.
var cf = createFixtureWithReportedUsages(forNode(1, usage("disk", 0.3), usage("memory", 0.49)),
- forNode(2, usage("disk", 0.3), usage("memory", 0.49)));
+ forNode(2, usage("disk", 0.3), usage("memory", 0.49)));
var feedBlock = calc.inferContentClusterFeedBlockOrNull(cf.cluster().getNodeInfos());
assertNotNull(feedBlock);
// TODO should we not change the limits themselves? Explicit mention of hysteresis state?
assertEquals("memory on node 1 [storage.1.local] (0.490 > 0.400)",
- feedBlock.getDescription());
+ feedBlock.getDescription());
}
@Test
- public void retain_node_feed_block_status_when_within_hysteresis_window_under_limit_edge_case() {
+ void retain_node_feed_block_status_when_within_hysteresis_window_under_limit_edge_case() {
var curFeedBlock = ClusterStateBundle.FeedBlock.blockedWith("foo", setOf(exhaustion(1, "memory", 0.49)));
var calc = new ResourceExhaustionCalculator(true, mapOf(usage("disk", 0.5), usage("memory", 0.5)), curFeedBlock, 0.1);
// Node 1 goes from 0.49 to 0.48, NOT crossing the 0.5 threshold. Should still be blocked.
// Node 2 is at 0.49 but was not previously blocked and should not be blocked now either.
var cf = createFixtureWithReportedUsages(forNode(1, usage("disk", 0.3), usage("memory", 0.48)),
- forNode(2, usage("disk", 0.3), usage("memory", 0.49)));
+ forNode(2, usage("disk", 0.3), usage("memory", 0.49)));
var feedBlock = calc.inferContentClusterFeedBlockOrNull(cf.cluster().getNodeInfos());
assertNotNull(feedBlock);
assertEquals("memory on node 1 [storage.1.local] (0.480 > 0.400)",
@@ -131,22 +128,22 @@ public class ResourceExhaustionCalculatorTest {
}
@Test
- public void retained_node_feed_block_cleared_once_hysteresis_threshold_is_passed() {
+ void retained_node_feed_block_cleared_once_hysteresis_threshold_is_passed() {
var curFeedBlock = ClusterStateBundle.FeedBlock.blockedWith("foo", setOf(exhaustion(1, "memory", 0.48)));
var calc = new ResourceExhaustionCalculator(true, mapOf(usage("disk", 0.5), usage("memory", 0.5)), curFeedBlock, 0.1);
// Node 1 goes from 0.48 to 0.39. Should be unblocked
// Node 2 is at 0.49 but was not previously blocked and should not be blocked now either.
var cf = createFixtureWithReportedUsages(forNode(1, usage("disk", 0.3), usage("memory", 0.39)),
- forNode(2, usage("disk", 0.3), usage("memory", 0.49)));
+ forNode(2, usage("disk", 0.3), usage("memory", 0.49)));
var feedBlock = calc.inferContentClusterFeedBlockOrNull(cf.cluster().getNodeInfos());
assertNull(feedBlock);
}
@Test
- public void node_must_be_available_in_reported_state_to_trigger_feed_block() {
+ void node_must_be_available_in_reported_state_to_trigger_feed_block() {
var calc = new ResourceExhaustionCalculator(true, mapOf(usage("disk", 0.5), usage("memory", 0.8)));
var cf = createFixtureWithReportedUsages(forNode(1, usage("disk", 0.51), usage("memory", 0.79)),
- forNode(2, usage("disk", 0.6), usage("memory", 0.6)));
+ forNode(2, usage("disk", 0.6), usage("memory", 0.6)));
cf.reportStorageNodeState(1, State.DOWN);
cf.reportStorageNodeState(2, State.DOWN);
var feedBlock = calc.inferContentClusterFeedBlockOrNull(cf.cluster().getNodeInfos());
@@ -154,10 +151,10 @@ public class ResourceExhaustionCalculatorTest {
}
@Test
- public void node_must_be_available_in_wanted_state_to_trigger_feed_block() {
+ void node_must_be_available_in_wanted_state_to_trigger_feed_block() {
var calc = new ResourceExhaustionCalculator(true, mapOf(usage("disk", 0.5), usage("memory", 0.8)));
var cf = createFixtureWithReportedUsages(forNode(1, usage("disk", 0.51), usage("memory", 0.79)),
- forNode(2, usage("disk", 0.6), usage("memory", 0.6)));
+ forNode(2, usage("disk", 0.6), usage("memory", 0.6)));
cf.proposeStorageNodeWantedState(1, State.DOWN);
cf.proposeStorageNodeWantedState(2, State.MAINTENANCE);
var feedBlock = calc.inferContentClusterFeedBlockOrNull(cf.cluster().getNodeInfos());
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ResourceUsageStatsTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ResourceUsageStatsTest.java
index 2eeaf7658ff..fddd5b52aa2 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ResourceUsageStatsTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ResourceUsageStatsTest.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.vespa.clustercontroller.core;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collection;
import java.util.Collections;
@@ -13,15 +13,14 @@ import static com.yahoo.vespa.clustercontroller.core.FeedBlockUtil.exhaustion;
import static com.yahoo.vespa.clustercontroller.core.FeedBlockUtil.forNode;
import static com.yahoo.vespa.clustercontroller.core.FeedBlockUtil.setOf;
import static com.yahoo.vespa.clustercontroller.core.FeedBlockUtil.usage;
-
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class ResourceUsageStatsTest {
private final double DELTA = 0.00001;
@Test
- public void disk_and_memory_utilization_is_max_among_all_content_nodes() {
+ void disk_and_memory_utilization_is_max_among_all_content_nodes() {
var stats = ResourceUsageStats.calculateFrom(createNodeInfo(
forNode(1, usage("disk", 0.3), usage("memory", 0.6)),
forNode(2, usage("disk", 0.4), usage("memory", 0.5))),
@@ -34,7 +33,7 @@ public class ResourceUsageStatsTest {
}
@Test
- public void disk_and_memory_utilization_is_zero_if_no_samples_are_available() {
+ void disk_and_memory_utilization_is_zero_if_no_samples_are_available() {
var stats = ResourceUsageStats.calculateFrom(createNodeInfo(
forNode(1), forNode(2)),
createFeedBlockLimits(0.8, 0.9),
@@ -46,20 +45,20 @@ public class ResourceUsageStatsTest {
}
@Test
- public void nodes_above_limit_is_zero_without_feed_block_status() {
+ void nodes_above_limit_is_zero_without_feed_block_status() {
var stats = ResourceUsageStats.calculateFrom(Collections.emptyList(), Collections.emptyMap(), Optional.empty());
assertEquals(0, stats.getNodesAboveLimit());
}
@Test
- public void nodes_above_limit_is_equal_to_node_resource_exhaustions() {
+ void nodes_above_limit_is_equal_to_node_resource_exhaustions() {
var stats = ResourceUsageStats.calculateFrom(Collections.emptyList(), Collections.emptyMap(),
createFeedBlock(exhaustion(1, "disk"), exhaustion(2, "memory")));
assertEquals(2, stats.getNodesAboveLimit());
}
@Test
- public void nodes_above_limit_counts_each_node_only_once() {
+ void nodes_above_limit_counts_each_node_only_once() {
var stats = ResourceUsageStats.calculateFrom(Collections.emptyList(), Collections.emptyMap(),
createFeedBlock(exhaustion(1, "disk"), exhaustion(1, "memory")));
assertEquals(1, stats.getNodesAboveLimit());
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/RpcServerTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/RpcServerTest.java
index fee1d33725c..41d7465b602 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/RpcServerTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/RpcServerTest.java
@@ -20,7 +20,7 @@ import com.yahoo.vdslib.state.State;
import com.yahoo.vespa.clustercontroller.core.rpc.RpcServer;
import com.yahoo.vespa.clustercontroller.core.testutils.LogFormatter;
import com.yahoo.vespa.clustercontroller.core.testutils.WaitCondition;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
@@ -30,10 +30,7 @@ import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
-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 humbe
@@ -52,7 +49,7 @@ public class RpcServerTest extends FleetControllerTest {
}
@Test
- public void testRebinding() throws Exception {
+ void testRebinding() throws Exception {
startingTest("RpcServerTest::testRebinding");
Slobrok slobrok = new Slobrok();
String[] slobrokConnectionSpecs = new String[1];
@@ -81,17 +78,18 @@ public class RpcServerTest extends FleetControllerTest {
* similar things, so strange if it should be from them too though. Maybe last test there.
*/
@Test
- public void testFailOccasionallyAndIgnoreToSeeIfOtherTestsThenWork() {
- try{
+ void testFailOccasionallyAndIgnoreToSeeIfOtherTestsThenWork() {
+ try {
startingTest("RpcServerTest::testFailOccasionallyAndIgnoreToSeeIfOtherTestsThenWork");
setUpFleetController(true, defaultOptions("mycluster"));
setUpVdsNodes(true, new DummyVdsNodeOptions());
waitForStableSystem();
- } catch (Throwable t) {}
+ } catch (Throwable t) {
+ }
}
@Test
- public void testGetSystemState() throws Exception {
+ void testGetSystemState() throws Exception {
LogFormatter.initializeLogging();
startingTest("RpcServerTest::testGetSystemState");
FleetControllerOptions options = defaultOptions("mycluster");
@@ -131,12 +129,12 @@ public class RpcServerTest extends FleetControllerTest {
Request req = new Request("getSystemState");
connection.invokeSync(req, timeoutS);
- assertEquals(req.toString(), ErrorCode.NONE, req.errorCode());
- assertTrue(req.toString(), req.checkReturnTypes("ss"));
+ assertEquals(ErrorCode.NONE, req.errorCode(), req.toString());
+ assertTrue(req.checkReturnTypes("ss"), req.toString());
String systemState = req.returnValues().get(1).asString();
ClusterState retrievedClusterState = new ClusterState(systemState);
- assertEquals(systemState, State.DOWN, retrievedClusterState.getNodeState(new Node(NodeType.DISTRIBUTOR, 0)).getState());
- assertTrue(systemState, retrievedClusterState.getNodeState(new Node(NodeType.STORAGE, 9)).getState().oneOf("md"));
+ assertEquals(State.DOWN, retrievedClusterState.getNodeState(new Node(NodeType.DISTRIBUTOR, 0)).getState(), systemState);
+ assertTrue(retrievedClusterState.getNodeState(new Node(NodeType.STORAGE, 9)).getState().oneOf("md"), systemState);
}
private void setWantedNodeState(State newState, NodeType nodeType, int nodeIndex) {
@@ -154,12 +152,12 @@ public class RpcServerTest extends FleetControllerTest {
req.parameters().add(new StringValue("storage/cluster.mycluster/" + node.getType().toString() + "/" + node.getIndex()));
req.parameters().add(new StringValue(newNodeState.serialize(true)));
connection.invokeSync(req, timeoutS);
- assertEquals(req.toString(), ErrorCode.NONE, req.errorCode());
- assertTrue(req.toString(), req.checkReturnTypes("s"));
+ assertEquals(ErrorCode.NONE, req.errorCode(), req.toString());
+ assertTrue(req.checkReturnTypes("s"), req.toString());
}
@Test
- public void testGetNodeState() throws Exception {
+ void testGetNodeState() throws Exception {
startingTest("RpcServerTest::testGetNodeState");
Set<ConfiguredNode> configuredNodes = new TreeSet<>();
for (int i = 0; i < 10; i++)
@@ -199,19 +197,19 @@ public class RpcServerTest extends FleetControllerTest {
req.parameters().add(new StringValue("distributor"));
req.parameters().add(new Int32Value(0));
connection.invokeSync(req, timeoutS);
- assertEquals(req.toString(), ErrorCode.NONE, req.errorCode());
- assertTrue(req.toString(), req.checkReturnTypes("ssss"));
+ assertEquals(ErrorCode.NONE, req.errorCode(), req.toString());
+ assertTrue(req.checkReturnTypes("ssss"), req.toString());
assertEquals(State.DOWN, NodeState.deserialize(NodeType.DISTRIBUTOR, req.returnValues().get(0).asString()).getState());
NodeState reported = NodeState.deserialize(NodeType.DISTRIBUTOR, req.returnValues().get(1).asString());
- assertTrue(req.returnValues().get(1).asString(), reported.getState().oneOf("d-"));
+ assertTrue(reported.getState().oneOf("d-"), req.returnValues().get(1).asString());
assertEquals("", req.returnValues().get(2).asString());
req = new Request("getNodeState");
req.parameters().add(new StringValue("distributor"));
req.parameters().add(new Int32Value(2));
connection.invokeSync(req, timeoutS);
- assertEquals(req.toString(), ErrorCode.NONE, req.errorCode());
- assertTrue(req.toString(), req.checkReturnTypes("ssss"));
+ assertEquals(ErrorCode.NONE, req.errorCode(), req.toString());
+ assertTrue(req.checkReturnTypes("ssss"), req.toString());
assertEquals(State.DOWN, NodeState.deserialize(NodeType.DISTRIBUTOR, req.returnValues().get(0).asString()).getState());
assertEquals("t:946080000", req.returnValues().get(1).asString());
assertEquals(State.DOWN, NodeState.deserialize(NodeType.DISTRIBUTOR, req.returnValues().get(2).asString()).getState());
@@ -220,8 +218,8 @@ public class RpcServerTest extends FleetControllerTest {
req.parameters().add(new StringValue("distributor"));
req.parameters().add(new Int32Value(4));
connection.invokeSync(req, timeoutS);
- assertEquals(req.toString(), ErrorCode.NONE, req.errorCode());
- assertTrue(req.toString(), req.checkReturnTypes("ssss"));
+ assertEquals(ErrorCode.NONE, req.errorCode(), req.toString());
+ assertTrue(req.checkReturnTypes("ssss"), req.toString());
assertEquals("", req.returnValues().get(0).asString());
assertEquals("t:946080000", req.returnValues().get(1).asString());
assertEquals("", req.returnValues().get(2).asString());
@@ -230,16 +228,16 @@ public class RpcServerTest extends FleetControllerTest {
req.parameters().add(new StringValue("distributor"));
req.parameters().add(new Int32Value(15));
connection.invokeSync(req, timeoutS);
- assertEquals(req.toString(), ErrorCode.METHOD_FAILED, req.errorCode());
+ assertEquals(ErrorCode.METHOD_FAILED, req.errorCode(), req.toString());
assertEquals("No node distributor.15 exists in cluster mycluster", req.errorMessage());
- assertFalse(req.toString(), req.checkReturnTypes("ssss"));
+ assertFalse(req.checkReturnTypes("ssss"), req.toString());
req = new Request("getNodeState");
req.parameters().add(new StringValue("storage"));
req.parameters().add(new Int32Value(1));
connection.invokeSync(req, timeoutS);
- assertEquals(req.toString(), ErrorCode.NONE, req.errorCode());
- assertTrue(req.toString(), req.checkReturnTypes("ssss"));
+ assertEquals(ErrorCode.NONE, req.errorCode(), req.toString());
+ assertTrue(req.checkReturnTypes("ssss"), req.toString());
assertEquals("s:i i:0.2", req.returnValues().get(0).asString());
assertEquals("s:i i:0.2", req.returnValues().get(1).asString());
assertEquals("", req.returnValues().get(2).asString());
@@ -248,19 +246,19 @@ public class RpcServerTest extends FleetControllerTest {
req.parameters().add(new StringValue("storage"));
req.parameters().add(new Int32Value(2));
connection.invokeSync(req, timeoutS);
- assertEquals(req.toString(), ErrorCode.NONE, req.errorCode());
- assertTrue(req.toString(), req.checkReturnTypes("ssss"));
+ assertEquals(ErrorCode.NONE, req.errorCode(), req.toString());
+ assertTrue(req.checkReturnTypes("ssss"), req.toString());
assertEquals(State.DOWN, NodeState.deserialize(NodeType.STORAGE, req.returnValues().get(0).asString()).getState());
reported = NodeState.deserialize(NodeType.STORAGE, req.returnValues().get(1).asString());
- assertTrue(req.returnValues().get(1).asString(), reported.getState().oneOf("d-"));
+ assertTrue(reported.getState().oneOf("d-"), req.returnValues().get(1).asString());
assertEquals(State.RETIRED, NodeState.deserialize(NodeType.STORAGE, req.returnValues().get(2).asString()).getState());
req = new Request("getNodeState");
req.parameters().add(new StringValue("storage"));
req.parameters().add(new Int32Value(5));
connection.invokeSync(req, timeoutS);
- assertEquals(req.toString(), ErrorCode.NONE, req.errorCode());
- assertTrue(req.toString(), req.checkReturnTypes("ssss"));
+ assertEquals(ErrorCode.NONE, req.errorCode(), req.toString());
+ assertTrue(req.checkReturnTypes("ssss"), req.toString());
assertEquals("", req.returnValues().get(0).asString());
assertEquals("t:946080000", req.returnValues().get(1).asString());
assertEquals("", req.returnValues().get(2).asString());
@@ -269,15 +267,15 @@ public class RpcServerTest extends FleetControllerTest {
req.parameters().add(new StringValue("storage"));
req.parameters().add(new Int32Value(7));
connection.invokeSync(req, timeoutS);
- assertEquals(req.toString(), ErrorCode.NONE, req.errorCode());
- assertTrue(req.toString(), req.checkReturnTypes("ssss"));
+ assertEquals(ErrorCode.NONE, req.errorCode(), req.toString());
+ assertTrue(req.checkReturnTypes("ssss"), req.toString());
assertEquals(State.MAINTENANCE, NodeState.deserialize(NodeType.STORAGE, req.returnValues().get(0).asString()).getState());
assertEquals("t:946080000", req.returnValues().get(1).asString());
assertEquals(State.MAINTENANCE, NodeState.deserialize(NodeType.STORAGE, req.returnValues().get(2).asString()).getState());
}
@Test
- public void testGetNodeStateWithConfiguredRetired() throws Exception {
+ void testGetNodeStateWithConfiguredRetired() throws Exception {
startingTest("RpcServerTest::testGetNodeStateWithConfiguredRetired");
List<ConfiguredNode> configuredNodes = new ArrayList<>();
for (int i = 0; i < 4; i++)
@@ -311,7 +309,7 @@ public class RpcServerTest extends FleetControllerTest {
}
@Test
- public void testGetNodeStateWithConfigurationChangeToRetiredWhileNodeDown() throws Exception {
+ void testGetNodeStateWithConfigurationChangeToRetiredWhileNodeDown() throws Exception {
startingTest("RpcServerTest::testGetNodeStateWithConfigurationChangeToRetiredWhileNodeDown");
{ // Configuration: 5 nodes, all normal
@@ -392,7 +390,7 @@ public class RpcServerTest extends FleetControllerTest {
}
@Test
- public void testGetNodeStateWithConfigurationChangeToRetired() throws Exception {
+ void testGetNodeStateWithConfigurationChangeToRetired() throws Exception {
startingTest("RpcServerTest::testGetNodeStateWithConfigurationChangeToRetired");
{ // Configuration: 5 nodes, all normal
@@ -450,27 +448,27 @@ public class RpcServerTest extends FleetControllerTest {
{ // Configuration change: Remove the previously retired nodes
/*
- TODO: Verify current result: version:23 distributor:7 .0.s:d .1.s:d .2.s:d .3.s:d .4.s:d storage:7 .0.s:m .1.s:m .2.s:m .3.s:m .4.s:m
- TODO: Make this work without stopping/disconnecting (see StateChangeHandler.setNodes
- Set<ConfiguredNode> configuredNodes = new TreeSet<>();
- configuredNodes.add(new ConfiguredNode(5, false));
- configuredNodes.add(new ConfiguredNode(6, false));
- FleetControllerOptions options = new FleetControllerOptions("mycluster", configuredNodes);
- options.slobrokConnectionSpecs = this.options.slobrokConnectionSpecs;
- this.options.maxInitProgressTimeMs = 30000;
- this.options.stableStateTimePeriod = 60000;
- fleetController.updateOptions(options, 0);
- for (int i = 0; i < 5*2; i++) {
- nodes.get(i).disconnectSlobrok();
- nodes.get(i).disconnect();
- }
- waitForState("version:\\d+ distributor:7 storage:7 .0.s:d .1.s:d .2.s:d .3.s:d .4.s:d");
- */
+ TODO: Verify current result: version:23 distributor:7 .0.s:d .1.s:d .2.s:d .3.s:d .4.s:d storage:7 .0.s:m .1.s:m .2.s:m .3.s:m .4.s:m
+ TODO: Make this work without stopping/disconnecting (see StateChangeHandler.setNodes
+ Set<ConfiguredNode> configuredNodes = new TreeSet<>();
+ configuredNodes.add(new ConfiguredNode(5, false));
+ configuredNodes.add(new ConfiguredNode(6, false));
+ FleetControllerOptions options = new FleetControllerOptions("mycluster", configuredNodes);
+ options.slobrokConnectionSpecs = this.options.slobrokConnectionSpecs;
+ this.options.maxInitProgressTimeMs = 30000;
+ this.options.stableStateTimePeriod = 60000;
+ fleetController.updateOptions(options, 0);
+ for (int i = 0; i < 5*2; i++) {
+ nodes.get(i).disconnectSlobrok();
+ nodes.get(i).disconnect();
+ }
+ waitForState("version:\\d+ distributor:7 storage:7 .0.s:d .1.s:d .2.s:d .3.s:d .4.s:d");
+ */
}
}
@Test
- public void testSetNodeState() throws Exception {
+ void testSetNodeState() throws Exception {
startingTest("RpcServerTest::testSetNodeState");
Set<Integer> nodeIndexes = new TreeSet<>(List.of(4, 6, 9, 10, 14, 16, 21, 22, 23, 25));
Set<ConfiguredNode> configuredNodes = nodeIndexes.stream().map(i -> new ConfiguredNode(i, false)).collect(Collectors.toSet());
@@ -489,8 +487,8 @@ public class RpcServerTest extends FleetControllerTest {
req.parameters().add(new StringValue("storage/cluster.mycluster/storage/14"));
req.parameters().add(new StringValue("s:r"));
connection.invokeSync(req, timeoutS);
- assertEquals(req.toString(), ErrorCode.NONE, req.errorCode());
- assertTrue(req.toString(), req.checkReturnTypes("s"));
+ assertEquals(ErrorCode.NONE, req.errorCode(), req.toString());
+ assertTrue(req.checkReturnTypes("s"), req.toString());
waitForState("version:\\d+ distributor:26 .* storage:26 .* .14.s:r .*");
@@ -498,8 +496,8 @@ public class RpcServerTest extends FleetControllerTest {
req.parameters().add(new StringValue("storage/cluster.mycluster/storage/16"));
req.parameters().add(new StringValue("s:m"));
connection.invokeSync(req, timeoutS);
- assertEquals(req.toString(), ErrorCode.NONE, req.errorCode());
- assertTrue(req.toString(), req.checkReturnTypes("s"));
+ assertEquals(ErrorCode.NONE, req.errorCode(), req.toString());
+ assertTrue(req.checkReturnTypes("s"), req.toString());
waitForState("version:\\d+ distributor:26 .* storage:26 .* .14.s:r.* .16.s:m .*");
nodes.get(5 * 2 + 1).disconnect();
@@ -517,7 +515,7 @@ public class RpcServerTest extends FleetControllerTest {
}
@Test
- public void testSetNodeStateOutOfRange() throws Exception {
+ void testSetNodeStateOutOfRange() throws Exception {
startingTest("RpcServerTest::testSetNodeStateOutOfRange");
FleetControllerOptions options = defaultOptions("mycluster");
options.setStorageDistribution(new Distribution(Distribution.getDefaultDistributionConfig(2, 10)));
@@ -534,27 +532,27 @@ public class RpcServerTest extends FleetControllerTest {
req.parameters().add(new StringValue("storage/cluster.mycluster/storage/10"));
req.parameters().add(new StringValue("s:m"));
connection.invokeSync(req, timeoutS);
- assertEquals(req.toString(), ErrorCode.METHOD_FAILED, req.errorCode());
- assertEquals(req.toString(), "Cannot set wanted state of node storage.10. Index does not correspond to a configured node.", req.errorMessage());
+ assertEquals(ErrorCode.METHOD_FAILED, req.errorCode(), req.toString());
+ assertEquals("Cannot set wanted state of node storage.10. Index does not correspond to a configured node.", req.errorMessage(), req.toString());
req = new Request("setNodeState");
req.parameters().add(new StringValue("storage/cluster.mycluster/distributor/10"));
req.parameters().add(new StringValue("s:m"));
connection.invokeSync(req, timeoutS);
- assertEquals(req.toString(), ErrorCode.METHOD_FAILED, req.errorCode());
- assertEquals(req.toString(), "Cannot set wanted state of node distributor.10. Index does not correspond to a configured node.", req.errorMessage());
+ assertEquals(ErrorCode.METHOD_FAILED, req.errorCode(), req.toString());
+ assertEquals("Cannot set wanted state of node distributor.10. Index does not correspond to a configured node.", req.errorMessage(), req.toString());
req = new Request("setNodeState");
req.parameters().add(new StringValue("storage/cluster.mycluster/storage/9"));
req.parameters().add(new StringValue("s:m"));
connection.invokeSync(req, timeoutS);
- assertEquals(req.toString(), ErrorCode.NONE, req.errorCode());
+ assertEquals(ErrorCode.NONE, req.errorCode(), req.toString());
waitForState("version:\\d+ distributor:10 storage:10 .9.s:m");
}
@Test
- public void testGetMaster() throws Exception {
+ void testGetMaster() throws Exception {
startingTest("RpcServerTest::testGetMaster");
FleetControllerOptions options = defaultOptions("mycluster");
options.setStorageDistribution(new Distribution(Distribution.getDefaultDistributionConfig(2, 10)));
@@ -569,14 +567,14 @@ public class RpcServerTest extends FleetControllerTest {
Request req = new Request("getMaster");
connection.invokeSync(req, timeoutS);
- assertEquals(req.toString(), 0, req.returnValues().get(0).asInt32());
- assertEquals(req.toString(), "All 1 nodes agree that 0 is current master.", req.returnValues().get(1).asString());
+ assertEquals(0, req.returnValues().get(0).asInt32(), req.toString());
+ assertEquals("All 1 nodes agree that 0 is current master.", req.returnValues().get(1).asString(), req.toString());
// Note that this feature is tested better in MasterElectionTest.testGetMaster as it has multiple fleetcontrollers
}
@Test
- public void testGetNodeList() throws Exception {
+ void testGetNodeList() throws Exception {
startingTest("RpcServerTest::testGetNodeList");
setUpFleetController(true, defaultOptions("mycluster", 5));
final int nodeCount = 5;
@@ -596,8 +594,8 @@ public class RpcServerTest extends FleetControllerTest {
for (int j = 0; j <= nodeCount; ++j) {
Request req = new Request("getNodeList");
connection.invokeSync(req, timeoutS);
- assertEquals(req.errorMessage(), ErrorCode.NONE, req.errorCode());
- assertTrue(req.toString(), req.checkReturnTypes("SS"));
+ assertEquals(ErrorCode.NONE, req.errorCode(), req.errorMessage());
+ assertTrue(req.checkReturnTypes("SS"), req.toString());
String[] slobrok = req.returnValues().get(0).asStringArray().clone();
String[] rpc = req.returnValues().get(1).asStringArray().clone();
@@ -610,7 +608,7 @@ public class RpcServerTest extends FleetControllerTest {
if (i < nodeCount && !"".equals(rpc[i])) {
continue;
}
- assertEquals(slobrok[i], "", rpc[i]);
+ assertEquals("", rpc[i], slobrok[i]);
continue;
}
assertNotEquals("", rpc[i]);
@@ -618,7 +616,7 @@ public class RpcServerTest extends FleetControllerTest {
req2.parameters().add(new StringValue("unknown"));
Target connection2 = supervisor.connect(new Spec(rpc[i]));
connection2.invokeSync(req2, timeoutS);
- assertEquals(req2.toString(), ErrorCode.NONE, req.errorCode());
+ assertEquals(ErrorCode.NONE, req.errorCode(), req2.toString());
}
break;
}
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/RpcVersionAutoDowngradeTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/RpcVersionAutoDowngradeTest.java
index d61cd1271b6..df0b873e25b 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/RpcVersionAutoDowngradeTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/RpcVersionAutoDowngradeTest.java
@@ -4,7 +4,7 @@ package com.yahoo.vespa.clustercontroller.core;
import com.yahoo.vdslib.distribution.ConfiguredNode;
import com.yahoo.vdslib.state.NodeState;
import com.yahoo.vdslib.state.State;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
@@ -28,13 +28,13 @@ public class RpcVersionAutoDowngradeTest extends FleetControllerTest {
}
@Test
- public void cluster_state_rpc_version_is_auto_downgraded_and_retried_for_older_nodes() throws Exception {
+ void cluster_state_rpc_version_is_auto_downgraded_and_retried_for_older_nodes() throws Exception {
setUpFakeCluster(2); // HEAD is at v4
waitForState("version:\\d+ distributor:10 storage:10");
}
@Test
- public void implicit_activation_for_nodes_that_return_not_found_for_version_activation_rpc() throws Exception {
+ void implicit_activation_for_nodes_that_return_not_found_for_version_activation_rpc() throws Exception {
setUpFakeCluster(3); // HEAD is at v4
waitForState("version:\\d+ distributor:10 storage:10");
}
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/SlobrokTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/SlobrokTest.java
index 47ba7e1cb77..b59c90f4955 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/SlobrokTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/SlobrokTest.java
@@ -3,9 +3,10 @@ package com.yahoo.vespa.clustercontroller.core;
import com.yahoo.jrt.slobrok.server.Slobrok;
import java.util.logging.Level;
-import org.junit.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.logging.Logger;
@@ -14,7 +15,7 @@ public class SlobrokTest extends FleetControllerTest {
private static final Logger log = Logger.getLogger(SlobrokTest.class.getName());
@Test
- public void testSingleSlobrokRestart() throws Exception {
+ void testSingleSlobrokRestart() throws Exception {
startingTest("SlobrokTest::testSingleSlobrokRestart");
FleetControllerOptions options = defaultOptions("mycluster");
options.nodeStateRequestTimeoutMS = 60 * 60 * 1000;
@@ -26,13 +27,13 @@ public class SlobrokTest extends FleetControllerTest {
int version = fleetController.getSystemState().getVersion();
int slobrokPort = slobrok.port();
- // Test that we survive some slobrok instability without changing system state.
- for (int j=0; j<4; ++j) {
+ // Test that we survive some slobrok instability without changing system state.
+ for (int j = 0; j < 4; ++j) {
log.log(Level.INFO, "Mirror updateForDistributor count is " + fleetController.getSlobrokMirrorUpdates());
- log.log(Level.INFO, "STOPPING SLOBROK SERVER (" + (j+1) + "/4)");
+ log.log(Level.INFO, "STOPPING SLOBROK SERVER (" + (j + 1) + "/4)");
slobrok.stop();
- for (int i=0; i<10; ++i) {
- // Force one node to at least notice that the slobrok server is gone
+ for (int i = 0; i < 10; ++i) {
+ // Force one node to at least notice that the slobrok server is gone
if (i == 5) {
log.log(Level.INFO, "Forcing one node to initate a resend: " + nodes.get(3));
nodes.get(3).replyToPendingNodeStateRequests();
@@ -40,9 +41,9 @@ public class SlobrokTest extends FleetControllerTest {
waitForCompleteCycle();
timer.advanceTime(100);
}
- log.log(Level.INFO, "STARTING SLOBROK SERVER AGAIN (" + (j+1) + "/4)");
+ log.log(Level.INFO, "STARTING SLOBROK SERVER AGAIN (" + (j + 1) + "/4)");
slobrok = new Slobrok(slobrokPort);
- // May take up to 30 seconds for slobrok clients to re-register. Trigger retry.
+ // May take up to 30 seconds for slobrok clients to re-register. Trigger retry.
for (DummyVdsNode node : nodes) {
node.disconnectSlobrok();
node.registerSlobrok();
@@ -56,19 +57,19 @@ public class SlobrokTest extends FleetControllerTest {
if (clusterAvailable()) break;
timer.advanceTime(1000);
waitForCompleteCycle();
- try{
+ try {
Thread.sleep(10);
- } catch (InterruptedException e) { /* ignore */ }
+ } catch (InterruptedException e) { /* ignore */
+ }
}
assertClusterAvailable();
}
- assertEquals("Cluster state was affected, although it should not have been.",
- version, fleetController.getSystemState().getVersion());
+ assertEquals(version, fleetController.getSystemState().getVersion(), "Cluster state was affected, although it should not have been.");
}
@Test
- public void testNodeTooLongOutOfSlobrok() throws Exception {
+ void testNodeTooLongOutOfSlobrok() throws Exception {
startingTest("SlobrokTest::testNodeTooLongOutOfSlobrok");
FleetControllerOptions options = defaultOptions("mycluster");
options.maxSlobrokDisconnectGracePeriod = 60 * 1000;
@@ -81,13 +82,16 @@ public class SlobrokTest extends FleetControllerTest {
nodes.get(0).disconnectSlobrok();
log.log(Level.INFO, "DISCONNECTED NODE FROM SLOBROK. SHOULD BE IN COOLDOWN PERIOD");
fleetController.waitForNodesInSlobrok(9, 10, timeoutMS);
- synchronized (timer) {
+ synchronized(timer) {
nodes.get(0).sendGetNodeStateReply(0);
}
// Give system a little time to possible faultily removing node not in slobrok
timer.advanceTime(1000);
- try{ Thread.sleep(10); } catch (InterruptedException e) { /* ignore */ }
+ try {
+ Thread.sleep(10);
+ } catch (InterruptedException e) { /* ignore */
+ }
assertEquals(version, fleetController.getSystemState().getVersion());
log.log(Level.INFO, "JUMPING TIME. NODE SHOULD BE MARKED DOWN");
// At this point the fleetcontroller might not have noticed that the node is out of slobrok yet.
@@ -108,8 +112,8 @@ public class SlobrokTest extends FleetControllerTest {
private void assertClusterAvailable() {
ContentCluster cluster = fleetController.getCluster();
for (NodeInfo info : cluster.getNodeInfos()) {
- assertEquals("Node " + info + " connection attempts.", 0, info.getConnectionAttemptCount());
- assertTrue("Node " + info + " has no last request time.", info.getLatestNodeStateRequestTime() != 0);
+ assertEquals(0, info.getConnectionAttemptCount(), "Node " + info + " connection attempts.");
+ assertTrue(info.getLatestNodeStateRequestTime() != 0, "Node " + info + " has no last request time.");
}
}
}
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/StateChangeHandlerTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/StateChangeHandlerTest.java
index 699a35a190c..2bea95ab8c5 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/StateChangeHandlerTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/StateChangeHandlerTest.java
@@ -12,8 +12,8 @@ import com.yahoo.vespa.clustercontroller.core.hostinfo.HostInfo;
import com.yahoo.vespa.clustercontroller.core.listeners.NodeListener;
import com.yahoo.vespa.clustercontroller.core.mocks.TestEventLog;
import com.yahoo.vespa.clustercontroller.core.testutils.LogFormatter;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.util.LinkedList;
@@ -21,8 +21,8 @@ import java.util.Set;
import java.util.TreeSet;
import java.util.logging.Logger;
-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 StateChangeHandlerTest {
@@ -76,7 +76,7 @@ public class StateChangeHandlerTest {
private TestNodeListener nodeStateUpdateListener;
private final ClusterStateGenerator.Params params = new ClusterStateGenerator.Params();
- @Before
+ @BeforeEach
public void setUp() {
LogFormatter.initializeLogging();
}
@@ -125,7 +125,7 @@ public class StateChangeHandlerTest {
log.info("Marking " + node + " out of slobrok");
cluster.getNodeInfo(node).markRpcAddressOutdated(clock);
nodeStateChangeHandler.handleMissingNode(stateBefore, cluster.getNodeInfo(node), nodeStateUpdateListener);
- assertTrue(eventLog.toString(), eventLog.toString().contains("Node is no longer in slobrok"));
+ assertTrue(eventLog.toString().contains("Node is no longer in slobrok"), eventLog.toString());
eventLog.clear();
}
@@ -159,16 +159,16 @@ public class StateChangeHandlerTest {
}
@Test
- public void testUnstableNodeInSlobrok() {
+ void testUnstableNodeInSlobrok() {
initialize(new Config());
startWithStableStateClusterWithNodesUp();
Node node = new Node(NodeType.STORAGE, 0);
- for (int j=0; j<3; ++j) {
+ for (int j = 0; j < 3; ++j) {
log.info("Iteration " + j);
assertEquals(0, cluster.getNodeInfo(node).getPrematureCrashCount());
assertEquals(State.UP, cluster.getNodeInfo(node).getWantedState().getState());
assertEquals(State.UP, currentClusterState().getNodeState(node).getState());
- for (int k=0; k<config.maxPrematureCrashes; ++k) {
+ for (int k = 0; k < config.maxPrematureCrashes; ++k) {
log.info("Premature iteration " + k);
markNodeOutOfSlobrok(node);
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/StateChangeTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/StateChangeTest.java
index 5a33414c955..7c61423ac2b 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/StateChangeTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/StateChangeTest.java
@@ -13,8 +13,8 @@ import com.yahoo.vespa.clustercontroller.core.database.DatabaseHandler;
import com.yahoo.vespa.clustercontroller.core.database.ZooKeeperDatabaseFactory;
import com.yahoo.vespa.clustercontroller.core.testutils.StateWaiter;
import com.yahoo.vespa.clustercontroller.utils.util.NoMetricReporter;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.ArrayList;
@@ -25,9 +25,7 @@ import java.util.logging.Logger;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
-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.*;
public class StateChangeTest extends FleetControllerTest {
@@ -37,7 +35,7 @@ public class StateChangeTest extends FleetControllerTest {
private DummyCommunicator communicator;
private EventLog eventLog;
- @Before
+ @BeforeEach
public void setUp() {
supervisor = new Supervisor(new Transport());
}
@@ -101,7 +99,7 @@ public class StateChangeTest extends FleetControllerTest {
}
@Test
- public void testNormalStartup() throws Exception {
+ void testNormalStartup() throws Exception {
FleetControllerOptions options = defaultOptions("mycluster", createNodes(10));
options.maxInitProgressTime = 50000;
@@ -115,7 +113,7 @@ public class StateChangeTest extends FleetControllerTest {
communicator.setNodeState(new Node(NodeType.DISTRIBUTOR, j), new NodeState(NodeType.DISTRIBUTOR, State.INITIALIZING).setInitProgress(0.0f), "");
}
- for (int i=0; i<100; i += 10) {
+ for (int i = 0; i < 100; i += 10) {
timer.advanceTime(options.maxInitProgressTime / 20);
ctrl.tick();
for (int j = 0; j < 10; ++j) {
@@ -129,9 +127,9 @@ public class StateChangeTest extends FleetControllerTest {
// Regular init progress does not update the cluster state until the node is done initializing (or goes down,
// whichever comes first).
assertEquals("version:6 distributor:10 .0.s:i .0.i:0.0 .1.s:i .1.i:0.0 .2.s:i .2.i:0.0 .3.s:i .3.i:0.0 " +
- ".4.s:i .4.i:0.0 .5.s:i .5.i:0.0 .6.s:i .6.i:0.0 .7.s:i .7.i:0.0 .8.s:i .8.i:0.0 " +
- ".9.s:i .9.i:0.0 storage:10 .0.s:i .0.i:0.1 .1.s:i .1.i:0.1 .2.s:i .2.i:0.1 .3.s:i .3.i:0.1 " +
- ".4.s:i .4.i:0.1 .5.s:i .5.i:0.1 .6.s:i .6.i:0.1 .7.s:i .7.i:0.1 .8.s:i .8.i:0.1 .9.s:i .9.i:0.1",
+ ".4.s:i .4.i:0.0 .5.s:i .5.i:0.0 .6.s:i .6.i:0.0 .7.s:i .7.i:0.0 .8.s:i .8.i:0.0 " +
+ ".9.s:i .9.i:0.0 storage:10 .0.s:i .0.i:0.1 .1.s:i .1.i:0.1 .2.s:i .2.i:0.1 .3.s:i .3.i:0.1 " +
+ ".4.s:i .4.i:0.1 .5.s:i .5.i:0.1 .6.s:i .6.i:0.1 .7.s:i .7.i:0.1 .8.s:i .8.i:0.1 .9.s:i .9.i:0.1",
ctrl.consolidatedClusterState().toString());
timer.advanceTime(options.maxInitProgressTime / 20);
@@ -155,25 +153,25 @@ public class StateChangeTest extends FleetControllerTest {
verifyNodeEvents(new Node(NodeType.DISTRIBUTOR, 0),
"Event: distributor.0: Now reporting state U\n" +
- "Event: distributor.0: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
- "Event: distributor.0: Now reporting state I, i 0.00\n" +
- "Event: distributor.0: Altered node state in cluster state from 'U' to 'I, i 0.00'\n" +
- "Event: distributor.0: Now reporting state U\n" +
- "Event: distributor.0: Altered node state in cluster state from 'I, i 0.00' to 'U'\n");
+ "Event: distributor.0: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
+ "Event: distributor.0: Now reporting state I, i 0.00\n" +
+ "Event: distributor.0: Altered node state in cluster state from 'U' to 'I, i 0.00'\n" +
+ "Event: distributor.0: Now reporting state U\n" +
+ "Event: distributor.0: Altered node state in cluster state from 'I, i 0.00' to 'U'\n");
verifyNodeEvents(new Node(NodeType.STORAGE, 0),
"Event: storage.0: Now reporting state U\n" +
- "Event: storage.0: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
- "Event: storage.0: Now reporting state I, i 0.00 (ls)\n" +
- "Event: storage.0: Altered node state in cluster state from 'U' to 'D'\n" +
- "Event: storage.0: Now reporting state I, i 0.100 (read)\n" +
- "Event: storage.0: Altered node state in cluster state from 'D' to 'I, i 0.100 (read)'\n" +
- "Event: storage.0: Now reporting state U\n" +
- "Event: storage.0: Altered node state in cluster state from 'I, i 0.100 (read)' to 'U'\n");
+ "Event: storage.0: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
+ "Event: storage.0: Now reporting state I, i 0.00 (ls)\n" +
+ "Event: storage.0: Altered node state in cluster state from 'U' to 'D'\n" +
+ "Event: storage.0: Now reporting state I, i 0.100 (read)\n" +
+ "Event: storage.0: Altered node state in cluster state from 'D' to 'I, i 0.100 (read)'\n" +
+ "Event: storage.0: Now reporting state U\n" +
+ "Event: storage.0: Altered node state in cluster state from 'I, i 0.100 (read)' to 'U'\n");
}
@Test
- public void testNodeGoingDownAndUp() throws Exception {
+ void testNodeGoingDownAndUp() throws Exception {
FleetControllerOptions options = defaultOptions("mycluster", createNodes(10));
options.nodeStateRequestTimeoutMS = 60 * 60 * 1000;
options.minTimeBetweenNewSystemStates = 0;
@@ -191,7 +189,7 @@ public class StateChangeTest extends FleetControllerTest {
ctrl.tick();
String desc = ctrl.getReportedNodeState(new Node(NodeType.DISTRIBUTOR, 0)).getDescription();
- assertTrue(desc, desc.contains("Closed at other end"));
+ assertTrue(desc.contains("Closed at other end"), desc);
assertEquals("version:4 distributor:10 .0.s:d storage:10", ctrl.getSystemState().toString());
@@ -208,7 +206,7 @@ public class StateChangeTest extends FleetControllerTest {
assert(!ctrl.getReportedNodeState(new Node(NodeType.DISTRIBUTOR, 0)).hasDescription());
desc = ctrl.getReportedNodeState(new Node(NodeType.STORAGE, 0)).getDescription();
- assertTrue(desc, desc.contains("Closed at other end"));
+ assertTrue(desc.contains("Closed at other end"), desc);
timer.advanceTime(options.maxTransitionTime.get(NodeType.STORAGE) + 1);
@@ -217,7 +215,7 @@ public class StateChangeTest extends FleetControllerTest {
assertEquals("version:6 distributor:10 .0.t:12345678 storage:10 .0.s:d", ctrl.getSystemState().toString());
desc = ctrl.getReportedNodeState(new Node(NodeType.STORAGE, 0)).getDescription();
- assertTrue(desc, desc.contains("Closed at other end"));
+ assertTrue(desc.contains("Closed at other end"), desc);
timer.advanceTime(1000);
@@ -233,24 +231,24 @@ public class StateChangeTest extends FleetControllerTest {
verifyNodeEvents(new Node(NodeType.DISTRIBUTOR, 0),
"Event: distributor.0: Now reporting state U\n" +
- "Event: distributor.0: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
- "Event: distributor.0: Failed to get node state: D: Closed at other end\n" +
- "Event: distributor.0: Stopped or possibly crashed after 0 ms, which is before stable state time period. Premature crash count is now 1.\n" +
- "Event: distributor.0: Altered node state in cluster state from 'U' to 'D: Closed at other end'\n" +
- "Event: distributor.0: Now reporting state U, t 12345678\n" +
- "Event: distributor.0: Altered node state in cluster state from 'D: Closed at other end' to 'U, t 12345678'\n" +
- "Event: distributor.0: Altered node state in cluster state from 'U, t 12345678' to 'U'\n");
+ "Event: distributor.0: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
+ "Event: distributor.0: Failed to get node state: D: Closed at other end\n" +
+ "Event: distributor.0: Stopped or possibly crashed after 0 ms, which is before stable state time period. Premature crash count is now 1.\n" +
+ "Event: distributor.0: Altered node state in cluster state from 'U' to 'D: Closed at other end'\n" +
+ "Event: distributor.0: Now reporting state U, t 12345678\n" +
+ "Event: distributor.0: Altered node state in cluster state from 'D: Closed at other end' to 'U, t 12345678'\n" +
+ "Event: distributor.0: Altered node state in cluster state from 'U, t 12345678' to 'U'\n");
verifyNodeEvents(new Node(NodeType.STORAGE, 0),
"Event: storage.0: Now reporting state U\n" +
- "Event: storage.0: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
- "Event: storage.0: Failed to get node state: D: Closed at other end\n" +
- "Event: storage.0: Stopped or possibly crashed after 1000 ms, which is before stable state time period. Premature crash count is now 1.\n" +
- "Event: storage.0: Altered node state in cluster state from 'U' to 'M: Closed at other end'\n" +
- "Event: storage.0: Exceeded implicit maintenance mode grace period of 5000 milliseconds. Marking node down.\n" +
- "Event: storage.0: Altered node state in cluster state from 'M: Closed at other end' to 'D: Closed at other end'\n" +
- "Event: storage.0: Now reporting state U, t 12345679\n" +
- "Event: storage.0: Altered node state in cluster state from 'D: Closed at other end' to 'U, t 12345679'\n");
+ "Event: storage.0: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
+ "Event: storage.0: Failed to get node state: D: Closed at other end\n" +
+ "Event: storage.0: Stopped or possibly crashed after 1000 ms, which is before stable state time period. Premature crash count is now 1.\n" +
+ "Event: storage.0: Altered node state in cluster state from 'U' to 'M: Closed at other end'\n" +
+ "Event: storage.0: Exceeded implicit maintenance mode grace period of 5000 milliseconds. Marking node down.\n" +
+ "Event: storage.0: Altered node state in cluster state from 'M: Closed at other end' to 'D: Closed at other end'\n" +
+ "Event: storage.0: Now reporting state U, t 12345679\n" +
+ "Event: storage.0: Altered node state in cluster state from 'D: Closed at other end' to 'U, t 12345679'\n");
assertEquals(1, ctrl.getCluster().getNodeInfo(new Node(NodeType.DISTRIBUTOR, 0)).getPrematureCrashCount());
assertEquals(1, ctrl.getCluster().getNodeInfo(new Node(NodeType.STORAGE, 0)).getPrematureCrashCount());
@@ -262,7 +260,7 @@ public class StateChangeTest extends FleetControllerTest {
}
@Test
- public void testNodeGoingDownAndUpNotifying() throws Exception {
+ void testNodeGoingDownAndUpNotifying() throws Exception {
// Same test as above, but node manages to notify why it is going down first.
FleetControllerOptions options = defaultOptions("mycluster", createNodes(10));
options.nodeStateRequestTimeoutMS = 60 * 60 * 1000;
@@ -272,15 +270,15 @@ public class StateChangeTest extends FleetControllerTest {
ctrl.tick();
- tick((int)options.stableStateTimePeriod + 1);
+ tick((int) options.stableStateTimePeriod + 1);
communicator.setNodeState(new Node(NodeType.DISTRIBUTOR, 0), State.DOWN, "controlled shutdown");
ctrl.tick();
String desc = ctrl.getReportedNodeState(new Node(NodeType.DISTRIBUTOR, 0)).getDescription();
- assertTrue(desc, desc.contains("Received signal 15 (SIGTERM - Termination signal)")
- || desc.contains("controlled shutdown"));
+ assertTrue(desc.contains("Received signal 15 (SIGTERM - Termination signal)")
+ || desc.contains("controlled shutdown"), desc);
tick(1000);
@@ -293,15 +291,15 @@ public class StateChangeTest extends FleetControllerTest {
assert(!ctrl.getReportedNodeState(new Node(NodeType.DISTRIBUTOR, 0)).hasDescription());
desc = ctrl.getReportedNodeState(new Node(NodeType.STORAGE, 0)).getDescription();
- assertTrue(desc, desc.contains("Received signal 15 (SIGTERM - Termination signal)")
- || desc.contains("controlled shutdown"));
+ assertTrue(desc.contains("Received signal 15 (SIGTERM - Termination signal)")
+ || desc.contains("controlled shutdown"), desc);
tick(options.maxTransitionTime.get(NodeType.STORAGE) + 1);
assertEquals("version:6 distributor:10 storage:10 .0.s:d", ctrl.getSystemState().toString());
desc = ctrl.getReportedNodeState(new Node(NodeType.STORAGE, 0)).getDescription();
- assertTrue(desc, desc.contains("Received signal 15 (SIGTERM - Termination signal)")
- || desc.contains("controlled shutdown"));
+ assertTrue(desc.contains("Received signal 15 (SIGTERM - Termination signal)")
+ || desc.contains("controlled shutdown"), desc);
communicator.setNodeState(new Node(NodeType.STORAGE, 0), State.UP, "");
@@ -315,26 +313,26 @@ public class StateChangeTest extends FleetControllerTest {
verifyNodeEvents(new Node(NodeType.DISTRIBUTOR, 0),
"Event: distributor.0: Now reporting state U\n" +
- "Event: distributor.0: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
- "Event: distributor.0: Failed to get node state: D: controlled shutdown\n" +
- "Event: distributor.0: Altered node state in cluster state from 'U' to 'D: controlled shutdown'\n" +
- "Event: distributor.0: Now reporting state U\n" +
- "Event: distributor.0: Altered node state in cluster state from 'D: controlled shutdown' to 'U'\n");
+ "Event: distributor.0: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
+ "Event: distributor.0: Failed to get node state: D: controlled shutdown\n" +
+ "Event: distributor.0: Altered node state in cluster state from 'U' to 'D: controlled shutdown'\n" +
+ "Event: distributor.0: Now reporting state U\n" +
+ "Event: distributor.0: Altered node state in cluster state from 'D: controlled shutdown' to 'U'\n");
verifyNodeEvents(new Node(NodeType.STORAGE, 0),
"Event: storage.0: Now reporting state U\n" +
- "Event: storage.0: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
- "Event: storage.0: Failed to get node state: D: controlled shutdown\n" +
- "Event: storage.0: Altered node state in cluster state from 'U' to 'M: controlled shutdown'\n" +
- "Event: storage.0: Exceeded implicit maintenance mode grace period of 5000 milliseconds. Marking node down.\n" +
- "Event: storage.0: Altered node state in cluster state from 'M: controlled shutdown' to 'D: controlled shutdown'\n" +
- "Event: storage.0: Now reporting state U\n" +
- "Event: storage.0: Altered node state in cluster state from 'D: controlled shutdown' to 'U'\n");
+ "Event: storage.0: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
+ "Event: storage.0: Failed to get node state: D: controlled shutdown\n" +
+ "Event: storage.0: Altered node state in cluster state from 'U' to 'M: controlled shutdown'\n" +
+ "Event: storage.0: Exceeded implicit maintenance mode grace period of 5000 milliseconds. Marking node down.\n" +
+ "Event: storage.0: Altered node state in cluster state from 'M: controlled shutdown' to 'D: controlled shutdown'\n" +
+ "Event: storage.0: Now reporting state U\n" +
+ "Event: storage.0: Altered node state in cluster state from 'D: controlled shutdown' to 'U'\n");
}
@Test
- public void testNodeGoingDownAndUpFast() throws Exception {
+ void testNodeGoingDownAndUpFast() throws Exception {
FleetControllerOptions options = defaultOptions("mycluster", createNodes(10));
options.maxSlobrokDisconnectGracePeriod = 60 * 1000;
@@ -370,12 +368,12 @@ public class StateChangeTest extends FleetControllerTest {
verifyNodeEvents(new Node(NodeType.STORAGE, 0),
"Event: storage.0: Now reporting state U\n" +
- "Event: storage.0: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
- "Event: storage.0: Node is no longer in slobrok, but we still have a pending state request.\n");
+ "Event: storage.0: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
+ "Event: storage.0: Node is no longer in slobrok, but we still have a pending state request.\n");
}
@Test
- public void testMaintenanceWhileNormalStorageNodeRestart() throws Exception {
+ void testMaintenanceWhileNormalStorageNodeRestart() throws Exception {
FleetControllerOptions options = defaultOptions("mycluster", createNodes(10));
options.maxSlobrokDisconnectGracePeriod = 60 * 1000;
@@ -388,7 +386,7 @@ public class StateChangeTest extends FleetControllerTest {
assertEquals("version:4 distributor:10 storage:10 .6.s:m", ctrl.getSystemState().toString());
NodeState ns = ctrl.getReportedNodeState(new Node(NodeType.STORAGE, 6));
- assertTrue(ns.toString(), ns.getDescription().contains("Connection error: Closed at other end"));
+ assertTrue(ns.getDescription().contains("Connection error: Closed at other end"), ns.toString());
tick(1000);
@@ -417,19 +415,19 @@ public class StateChangeTest extends FleetControllerTest {
verifyNodeEvents(new Node(NodeType.STORAGE, 6),
"Event: storage.6: Now reporting state U\n" +
- "Event: storage.6: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
- "Event: storage.6: Failed to get node state: D: Connection error: Closed at other end\n" +
- "Event: storage.6: Stopped or possibly crashed after 0 ms, which is before stable state time period. Premature crash count is now 1.\n" +
- "Event: storage.6: Altered node state in cluster state from 'U' to 'M: Connection error: Closed at other end'\n" +
- "Event: storage.6: Now reporting state I, i 0.00 (ls)\n" +
- "Event: storage.6: Now reporting state I, i 0.600 (read)\n" +
- "Event: storage.6: Altered node state in cluster state from 'M: Connection error: Closed at other end' to 'I, i 0.600 (read)'\n" +
- "Event: storage.6: Now reporting state U\n" +
- "Event: storage.6: Altered node state in cluster state from 'I, i 0.600 (read)' to 'U'\n");
+ "Event: storage.6: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
+ "Event: storage.6: Failed to get node state: D: Connection error: Closed at other end\n" +
+ "Event: storage.6: Stopped or possibly crashed after 0 ms, which is before stable state time period. Premature crash count is now 1.\n" +
+ "Event: storage.6: Altered node state in cluster state from 'U' to 'M: Connection error: Closed at other end'\n" +
+ "Event: storage.6: Now reporting state I, i 0.00 (ls)\n" +
+ "Event: storage.6: Now reporting state I, i 0.600 (read)\n" +
+ "Event: storage.6: Altered node state in cluster state from 'M: Connection error: Closed at other end' to 'I, i 0.600 (read)'\n" +
+ "Event: storage.6: Now reporting state U\n" +
+ "Event: storage.6: Altered node state in cluster state from 'I, i 0.600 (read)' to 'U'\n");
}
@Test
- public void testMaintenanceWithoutInitIfRetired() throws Exception {
+ void testMaintenanceWithoutInitIfRetired() throws Exception {
List<ConfiguredNode> nodes = new ArrayList<>();
for (int i = 0; i < 10; i++) {
boolean retired = (i == 6);
@@ -448,7 +446,7 @@ public class StateChangeTest extends FleetControllerTest {
assertEquals("version:4 distributor:10 storage:10 .6.s:m", ctrl.getSystemState().toString());
NodeState ns = ctrl.getReportedNodeState(new Node(NodeType.STORAGE, 6));
- assertTrue(ns.toString(), ns.getDescription().contains("Connection error: Closed at other end"));
+ assertTrue(ns.getDescription().contains("Connection error: Closed at other end"), ns.toString());
tick(1000);
@@ -477,18 +475,18 @@ public class StateChangeTest extends FleetControllerTest {
verifyNodeEvents(new Node(NodeType.STORAGE, 6),
"Event: storage.6: Now reporting state U\n" +
- "Event: storage.6: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'R'\n" +
- "Event: storage.6: Failed to get node state: D: Connection error: Closed at other end\n" +
- "Event: storage.6: Stopped or possibly crashed after 0 ms, which is before stable state time period. Premature crash count is now 1.\n" +
- "Event: storage.6: Altered node state in cluster state from 'R' to 'M: Connection error: Closed at other end'\n" +
- "Event: storage.6: Now reporting state I, i 0.00 (ls)\n" +
- "Event: storage.6: Now reporting state I, i 0.600 (read)\n" +
- "Event: storage.6: Now reporting state U\n" +
- "Event: storage.6: Altered node state in cluster state from 'M: Connection error: Closed at other end' to 'R'\n");
+ "Event: storage.6: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'R'\n" +
+ "Event: storage.6: Failed to get node state: D: Connection error: Closed at other end\n" +
+ "Event: storage.6: Stopped or possibly crashed after 0 ms, which is before stable state time period. Premature crash count is now 1.\n" +
+ "Event: storage.6: Altered node state in cluster state from 'R' to 'M: Connection error: Closed at other end'\n" +
+ "Event: storage.6: Now reporting state I, i 0.00 (ls)\n" +
+ "Event: storage.6: Now reporting state I, i 0.600 (read)\n" +
+ "Event: storage.6: Now reporting state U\n" +
+ "Event: storage.6: Altered node state in cluster state from 'M: Connection error: Closed at other end' to 'R'\n");
}
@Test
- public void testMaintenanceToDownIfPastTransitionTimeAndRetired() throws Exception {
+ void testMaintenanceToDownIfPastTransitionTimeAndRetired() throws Exception {
List<ConfiguredNode> nodes = new ArrayList<>();
for (int i = 0; i < 10; i++) {
boolean retired = (i == 6);
@@ -516,7 +514,7 @@ public class StateChangeTest extends FleetControllerTest {
// Test that a node that has been down for a long time (above steady state period), actually alters cluster state to
// tell that it is initializing, rather than being ignored as a just restarted/unstable node should be.
@Test
- public void testDownNodeInitializing() throws Exception {
+ void testDownNodeInitializing() throws Exception {
// Actually report initializing state if node has been down steadily for a while
FleetControllerOptions options = defaultOptions("mycluster", createNodes(10));
options.maxTransitionTime.put(NodeType.STORAGE, 5000);
@@ -566,20 +564,20 @@ public class StateChangeTest extends FleetControllerTest {
verifyNodeEvents(new Node(NodeType.STORAGE, 6),
"Event: storage.6: Now reporting state U\n" +
- "Event: storage.6: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
- "Event: storage.6: Failed to get node state: D: Connection error: Closed at other end\n" +
- "Event: storage.6: Altered node state in cluster state from 'U' to 'M: Connection error: Closed at other end'\n" +
- "Event: storage.6: Exceeded implicit maintenance mode grace period of 5000 milliseconds. Marking node down.\n" +
- "Event: storage.6: Altered node state in cluster state from 'M: Connection error: Closed at other end' to 'D: Connection error: Closed at other end'\n" +
- "Event: storage.6: Now reporting state I, i 0.00100 (ls)\n" +
- "Event: storage.6: Now reporting state I, i 0.100 (read)\n" +
- "Event: storage.6: Altered node state in cluster state from 'D: Connection error: Closed at other end' to 'I, i 0.100 (read)'\n" +
- "Event: storage.6: Now reporting state U\n" +
- "Event: storage.6: Altered node state in cluster state from 'I, i 0.100 (read)' to 'U'\n");
+ "Event: storage.6: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
+ "Event: storage.6: Failed to get node state: D: Connection error: Closed at other end\n" +
+ "Event: storage.6: Altered node state in cluster state from 'U' to 'M: Connection error: Closed at other end'\n" +
+ "Event: storage.6: Exceeded implicit maintenance mode grace period of 5000 milliseconds. Marking node down.\n" +
+ "Event: storage.6: Altered node state in cluster state from 'M: Connection error: Closed at other end' to 'D: Connection error: Closed at other end'\n" +
+ "Event: storage.6: Now reporting state I, i 0.00100 (ls)\n" +
+ "Event: storage.6: Now reporting state I, i 0.100 (read)\n" +
+ "Event: storage.6: Altered node state in cluster state from 'D: Connection error: Closed at other end' to 'I, i 0.100 (read)'\n" +
+ "Event: storage.6: Now reporting state U\n" +
+ "Event: storage.6: Altered node state in cluster state from 'I, i 0.100 (read)' to 'U'\n");
}
@Test
- public void testNodeInitializationStalled() throws Exception {
+ void testNodeInitializationStalled() throws Exception {
// Node should eventually be marked down, and not become initializing next time, but stay down until up
FleetControllerOptions options = defaultOptions("mycluster", createNodes(10));
options.maxTransitionTime.put(NodeType.STORAGE, 5000);
@@ -647,31 +645,31 @@ public class StateChangeTest extends FleetControllerTest {
verifyNodeEvents(new Node(NodeType.STORAGE, 6),
"Event: storage.6: Now reporting state U\n" +
- "Event: storage.6: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
- "Event: storage.6: Failed to get node state: D: Connection error: Closed at other end\n" +
- "Event: storage.6: Altered node state in cluster state from 'U' to 'M: Connection error: Closed at other end'\n" +
- "Event: storage.6: Exceeded implicit maintenance mode grace period of 5000 milliseconds. Marking node down.\n" +
- "Event: storage.6: Altered node state in cluster state from 'M: Connection error: Closed at other end' to 'D: Connection error: Closed at other end'\n" +
- "Event: storage.6: Now reporting state I, i 0.100 (read)\n" +
- "Event: storage.6: Altered node state in cluster state from 'D: Connection error: Closed at other end' to 'I, i 0.100 (read)'\n" +
- "Event: storage.6: 5001 milliseconds without initialize progress. Marking node down. Premature crash count is now 1.\n" +
- "Event: storage.6: Altered node state in cluster state from 'I, i 0.100 (read)' to 'D'\n" +
- "Event: storage.6: Failed to get node state: D: Connection error: Closed at other end\n" +
- "Event: storage.6: Now reporting state I, i 0.00 (ls)\n" +
- "Event: storage.6: Now reporting state I, i 0.100 (read)\n" +
- "Event: storage.6: Now reporting state U\n" +
- "Event: storage.6: Altered node state in cluster state from 'D' to 'U'\n");
+ "Event: storage.6: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
+ "Event: storage.6: Failed to get node state: D: Connection error: Closed at other end\n" +
+ "Event: storage.6: Altered node state in cluster state from 'U' to 'M: Connection error: Closed at other end'\n" +
+ "Event: storage.6: Exceeded implicit maintenance mode grace period of 5000 milliseconds. Marking node down.\n" +
+ "Event: storage.6: Altered node state in cluster state from 'M: Connection error: Closed at other end' to 'D: Connection error: Closed at other end'\n" +
+ "Event: storage.6: Now reporting state I, i 0.100 (read)\n" +
+ "Event: storage.6: Altered node state in cluster state from 'D: Connection error: Closed at other end' to 'I, i 0.100 (read)'\n" +
+ "Event: storage.6: 5001 milliseconds without initialize progress. Marking node down. Premature crash count is now 1.\n" +
+ "Event: storage.6: Altered node state in cluster state from 'I, i 0.100 (read)' to 'D'\n" +
+ "Event: storage.6: Failed to get node state: D: Connection error: Closed at other end\n" +
+ "Event: storage.6: Now reporting state I, i 0.00 (ls)\n" +
+ "Event: storage.6: Now reporting state I, i 0.100 (read)\n" +
+ "Event: storage.6: Now reporting state U\n" +
+ "Event: storage.6: Altered node state in cluster state from 'D' to 'U'\n");
}
@Test
- public void testBackwardsInitializationProgress() throws Exception {
+ void testBackwardsInitializationProgress() throws Exception {
// Same as stalled. Mark down, keep down until up
FleetControllerOptions options = defaultOptions("mycluster", createNodes(10));
options.maxTransitionTime.put(NodeType.STORAGE, 5000);
options.maxInitProgressTime = 5000;
options.stableStateTimePeriod = 1000000;
- // Set long so we dont time out RPC requests and mark nodes down due to advancing time to get in steady state
+ // Set long so we dont time out RPC requests and mark nodes down due to advancing time to get in steady state
options.nodeStateRequestTimeoutMS = (int) options.stableStateTimePeriod * 2;
initialize(options);
@@ -708,7 +706,7 @@ public class StateChangeTest extends FleetControllerTest {
}
@Test
- public void testNodeGoingDownWhileInitializing() throws Exception {
+ void testNodeGoingDownWhileInitializing() throws Exception {
// Same as stalled. Mark down, keep down until up
FleetControllerOptions options = defaultOptions("mycluster", createNodes(10));
options.maxTransitionTime.put(NodeType.STORAGE, 5000);
@@ -766,7 +764,7 @@ public class StateChangeTest extends FleetControllerTest {
}
@Test
- public void testContinuousCrashRightAfterInit() throws Exception {
+ void testContinuousCrashRightAfterInit() throws Exception {
startingTest("StateChangeTest::testContinuousCrashRightAfterInit");
// If node does this too many times, take it out of service
FleetControllerOptions options = defaultOptions("mycluster", createNodes(10));
@@ -820,7 +818,7 @@ public class StateChangeTest extends FleetControllerTest {
}
@Test
- public void testClusterStateMinNodes() throws Exception {
+ void testClusterStateMinNodes() throws Exception {
startingTest("StateChangeTest::testClusterStateMinNodes");
// If node does this too many times, take it out of service
FleetControllerOptions options = defaultOptions("mycluster", createNodes(10));
@@ -875,7 +873,7 @@ public class StateChangeTest extends FleetControllerTest {
}
@Test
- public void testClusterStateMinFactor() throws Exception {
+ void testClusterStateMinFactor() throws Exception {
startingTest("StateChangeTest::testClusterStateMinFactor");
// If node does this too many times, take it out of service
FleetControllerOptions options = defaultOptions("mycluster", createNodes(10));
@@ -942,21 +940,21 @@ public class StateChangeTest extends FleetControllerTest {
for (ClusterState state : states) {
debugString.append(state.toString()).append("\n");
}
- assertEquals(debugString.toString(), expectedMessageCount(node), states.size());
+ assertEquals(expectedMessageCount(node), states.size(), debugString.toString());
}
}
abstract int expectedMessageCount(final DummyVdsNode node);
}
@Test
- public void testNoSystemStateBeforeInitialTimePeriod() throws Exception {
+ void testNoSystemStateBeforeInitialTimePeriod() throws Exception {
startingTest("StateChangeTest::testNoSystemStateBeforeInitialTimePeriod()");
FleetControllerOptions options = defaultOptions("mycluster", createNodes(10));
options.minTimeBeforeFirstSystemStateBroadcast = 3 * 60 * 1000;
setUpSystem(true, options);
setUpVdsNodes(true, new DummyVdsNodeOptions(), true);
// Leave one node down to avoid sending cluster state due to having seen all node states.
- for (int i=0; i<nodes.size(); ++i) {
+ for (int i = 0; i < nodes.size(); ++i) {
if (i != 3) {
nodes.get(i).connect();
}
@@ -971,7 +969,10 @@ public class StateChangeTest extends FleetControllerTest {
waiter.waitForState("^distributor:10 (\\.\\d+\\.t:\\d+ )*storage:10 (\\.\\d+\\.t:\\d+ )*.1.s:d( \\.\\d+\\.t:\\d+)*", timeoutMS);
waitForCompleteCycle();
new StateMessageChecker(nodes) {
- @Override int expectedMessageCount(final DummyVdsNode node) { return 0; }
+ @Override
+ int expectedMessageCount(final DummyVdsNode node) {
+ return 0;
+ }
};
// Pass time and see that the nodes get state
@@ -982,7 +983,8 @@ public class StateChangeTest extends FleetControllerTest {
fleetController.waitForNodesHavingSystemStateVersionEqualToOrAbove(version, 19, timeoutMS);
new StateMessageChecker(nodes) {
- @Override int expectedMessageCount(final DummyVdsNode node) {
+ @Override
+ int expectedMessageCount(final DummyVdsNode node) {
return node.getNode().equals(new Node(NodeType.STORAGE, 1)) ? 0 : 2;
}
};
@@ -990,7 +992,7 @@ public class StateChangeTest extends FleetControllerTest {
}
@Test
- public void testSystemStateSentWhenNodesReplied() throws Exception {
+ void testSystemStateSentWhenNodesReplied() throws Exception {
startingTest("StateChangeTest::testSystemStateSentWhenNodesReplied()");
final FleetControllerOptions options = defaultOptions("mycluster", createNodes(10));
options.minTimeBeforeFirstSystemStateBroadcast = 300 * 60 * 1000;
@@ -1019,12 +1021,15 @@ public class StateChangeTest extends FleetControllerTest {
// The last two versions of the cluster state should be seen (all nodes up,
// zero out timestate)
new StateMessageChecker(nodes) {
- @Override int expectedMessageCount(final DummyVdsNode node) { return 2; }
+ @Override
+ int expectedMessageCount(final DummyVdsNode node) {
+ return 2;
+ }
};
}
@Test
- public void testDontTagFailingSetSystemStateOk() throws Exception {
+ void testDontTagFailingSetSystemStateOk() throws Exception {
startingTest("StateChangeTest::testDontTagFailingSetSystemStateOk()");
FleetControllerOptions options = defaultOptions("mycluster", createNodes(10));
setUpFleetController(true, options);
@@ -1055,7 +1060,7 @@ public class StateChangeTest extends FleetControllerTest {
}
@Test
- public void testAlteringDistributionSplitCount() throws Exception {
+ void testAlteringDistributionSplitCount() throws Exception {
startingTest("StateChangeTest::testAlteringDistributionSplitCount");
FleetControllerOptions options = defaultOptions("mycluster", createNodes(10));
options.distributionBits = 17;
@@ -1102,7 +1107,7 @@ public class StateChangeTest extends FleetControllerTest {
}
@Test
- public void testSetAllTimestampsAfterDowntime() throws Exception {
+ void testSetAllTimestampsAfterDowntime() throws Exception {
startingTest("StateChangeTest::testSetAllTimestampsAfterDowntime");
FleetControllerOptions options = defaultOptions("mycluster", createNodes(10));
setUpFleetController(true, options);
@@ -1135,24 +1140,24 @@ public class StateChangeTest extends FleetControllerTest {
for (ConfiguredNode i : options.nodes) {
Node nodeId = new Node(NodeType.STORAGE, i.index());
long ts = lastState.getNodeState(nodeId).getStartTimestamp();
- assertTrue(nodeId + "\n" + stateHistory + "\nWas " + ts + " should be " + fleetController.getCluster().getNodeInfo(nodeId).getStartTimestamp(), ts > 0);
+ assertTrue(ts > 0, nodeId + "\n" + stateHistory + "\nWas " + ts + " should be " + fleetController.getCluster().getNodeInfo(nodeId).getStartTimestamp());
}
} else {
for (ConfiguredNode i : options.nodes) {
Node nodeId = new Node(NodeType.STORAGE, i.index());
- assertEquals(nodeId.toString(), 0, lastState.getNodeState(nodeId).getStartTimestamp());
+ assertEquals(0, lastState.getNodeState(nodeId).getStartTimestamp(), nodeId.toString());
}
}
for (ConfiguredNode i : options.nodes) {
Node nodeId = new Node(NodeType.DISTRIBUTOR, i.index());
- assertEquals(nodeId.toString(), 0, lastState.getNodeState(nodeId).getStartTimestamp());
+ assertEquals(0, lastState.getNodeState(nodeId).getStartTimestamp(), nodeId.toString());
}
}
}
@Test
- public void consolidated_cluster_state_reflects_node_changes_when_cluster_is_down() throws Exception {
+ void consolidated_cluster_state_reflects_node_changes_when_cluster_is_down() throws Exception {
FleetControllerOptions options = defaultOptions("mycluster", createNodes(10));
options.maxTransitionTime.put(NodeType.STORAGE, 0);
options.minStorageNodesUp = 10;
@@ -1166,7 +1171,7 @@ public class StateChangeTest extends FleetControllerTest {
ctrl.tick();
assertThat(ctrl.consolidatedClusterState().toString(),
- equalTo("version:4 cluster:d distributor:10 storage:10 .2.s:d"));
+ equalTo("version:4 cluster:d distributor:10 storage:10 .2.s:d"));
// After this point, any further node changes while the cluster is still down won't be published.
// This is because cluster state similarity checks are short-circuited if both are Down, as no other parts
@@ -1179,14 +1184,14 @@ public class StateChangeTest extends FleetControllerTest {
// NOTE: _same_ version, different node state content. Overall cluster down-state is still the same.
assertThat(ctrl.consolidatedClusterState().toString(),
- equalTo("version:4 cluster:d distributor:10 storage:10 .2.s:d .5.s:d"));
+ equalTo("version:4 cluster:d distributor:10 storage:10 .2.s:d .5.s:d"));
}
// Related to the above test, watchTimer invocations must receive the _current_ state and not the
// published state. Failure to ensure this would cause events to be fired non-stop, as the effect
// of previous timer invocations (with subsequent state generation) would not be visible.
@Test
- public void timer_events_during_cluster_down_observe_most_recent_node_changes() throws Exception {
+ void timer_events_during_cluster_down_observe_most_recent_node_changes() throws Exception {
FleetControllerOptions options = defaultOptions("mycluster", createNodes(10));
options.maxTransitionTime.put(NodeType.STORAGE, 1000);
options.minStorageNodesUp = 10;
@@ -1210,10 +1215,10 @@ public class StateChangeTest extends FleetControllerTest {
verifyNodeEvents(new Node(NodeType.STORAGE, 2),
"Event: storage.2: Now reporting state U\n" +
- "Event: storage.2: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
- "Event: storage.2: Failed to get node state: D: foo\n" +
- "Event: storage.2: Stopped or possibly crashed after 500 ms, which is before stable state time period. Premature crash count is now 1.\n" +
- "Event: storage.2: Altered node state in cluster state from 'U' to 'M: foo'\n");
+ "Event: storage.2: Altered node state in cluster state from 'D: Node not seen in slobrok.' to 'U'\n" +
+ "Event: storage.2: Failed to get node state: D: foo\n" +
+ "Event: storage.2: Stopped or possibly crashed after 500 ms, which is before stable state time period. Premature crash count is now 1.\n" +
+ "Event: storage.2: Altered node state in cluster state from 'U' to 'M: foo'\n");
// Note: even though max transition time has passed, events are now emitted only on cluster state
// publish edges. These are currently suppressed when the cluster state is down, as all cluster down
// states are considered similar to other cluster down states. This is not necessarily optimal, but
@@ -1221,7 +1226,7 @@ public class StateChangeTest extends FleetControllerTest {
}
@Test
- public void do_not_emit_multiple_events_when_node_state_does_not_match_versioned_state() throws Exception {
+ void do_not_emit_multiple_events_when_node_state_does_not_match_versioned_state() throws Exception {
FleetControllerOptions options = defaultOptions("mycluster", createNodes(10));
initialize(options);
@@ -1418,7 +1423,7 @@ public class StateChangeTest extends FleetControllerTest {
}
@Test
- public void synchronous_remote_task_is_completed_when_state_is_acked_by_cluster() throws Exception {
+ void synchronous_remote_task_is_completed_when_state_is_acked_by_cluster() throws Exception {
RemoteTaskFixture fixture = createDefaultFixture();
MockTask task = fixture.scheduleVersionDependentTaskWithSideEffects();
@@ -1437,7 +1442,7 @@ public class StateChangeTest extends FleetControllerTest {
}
@Test
- public void failing_task_is_immediately_completed() throws Exception {
+ void failing_task_is_immediately_completed() throws Exception {
RemoteTaskFixture fixture = createDefaultFixture();
MockTask task = fixture.scheduleFailingVersionDependentTaskWithSideEffects();
@@ -1446,7 +1451,7 @@ public class StateChangeTest extends FleetControllerTest {
}
@Test
- public void no_op_synchronous_remote_task_can_complete_immediately_if_current_state_already_acked() throws Exception {
+ void no_op_synchronous_remote_task_can_complete_immediately_if_current_state_already_acked() throws Exception {
RemoteTaskFixture fixture = createFixtureWith(optionsWithZeroTransitionTime());
fixture.markStorageNodeDown(0);
MockTask task = fixture.scheduleNoOpVersionDependentTask(); // Tries to set node 0 into Down; already in that state
@@ -1459,7 +1464,7 @@ public class StateChangeTest extends FleetControllerTest {
}
@Test
- public void no_op_synchronous_remote_task_waits_until_current_state_is_acked() throws Exception {
+ void no_op_synchronous_remote_task_waits_until_current_state_is_acked() throws Exception {
RemoteTaskFixture fixture = createFixtureWith(optionsWithZeroTransitionTime());
communicator.setShouldDeferDistributorClusterStateAcks(true);
@@ -1483,7 +1488,7 @@ public class StateChangeTest extends FleetControllerTest {
// tasks running in such a context as if they were no-ops. I.e. we only require
// the cluster down-state to have been published.
@Test
- public void immediately_complete_sync_remote_task_when_cluster_is_down() throws Exception {
+ void immediately_complete_sync_remote_task_when_cluster_is_down() throws Exception {
RemoteTaskFixture fixture = createFixtureWith(optionsAllowingZeroNodesDown());
// Controller options require 10/10 nodes up, so take one down to trigger a cluster Down edge.
fixture.markStorageNodeDown(1);
@@ -1497,7 +1502,7 @@ public class StateChangeTest extends FleetControllerTest {
}
@Test
- public void multiple_tasks_may_be_scheduled_and_answered_at_the_same_time() throws Exception {
+ void multiple_tasks_may_be_scheduled_and_answered_at_the_same_time() throws Exception {
RemoteTaskFixture fixture = createDefaultFixture();
communicator.setShouldDeferDistributorClusterStateAcks(true);
@@ -1515,7 +1520,7 @@ public class StateChangeTest extends FleetControllerTest {
}
@Test
- public void synchronous_task_immediately_failed_when_leadership_lost() throws Exception {
+ void synchronous_task_immediately_failed_when_leadership_lost() throws Exception {
FleetControllerOptions options = optionsWithZeroTransitionTime();
options.fleetControllerCount = 3;
RemoteTaskFixture fixture = createFixtureWith(options);
@@ -1540,7 +1545,7 @@ public class StateChangeTest extends FleetControllerTest {
}
@Test
- public void cluster_state_ack_is_not_dependent_on_state_send_grace_period() throws Exception {
+ void cluster_state_ack_is_not_dependent_on_state_send_grace_period() throws Exception {
FleetControllerOptions options = defaultOptions();
options.minTimeBetweenNewSystemStates = 10_000;
RemoteTaskFixture fixture = createFixtureWith(options);
@@ -1560,7 +1565,7 @@ public class StateChangeTest extends FleetControllerTest {
}
@Test
- public void synchronous_task_immediately_answered_when_not_leader() throws Exception {
+ void synchronous_task_immediately_answered_when_not_leader() throws Exception {
FleetControllerOptions options = optionsWithZeroTransitionTime();
options.fleetControllerCount = 3;
RemoteTaskFixture fixture = createFixtureWith(options);
@@ -1575,7 +1580,7 @@ public class StateChangeTest extends FleetControllerTest {
}
@Test
- public void task_not_completed_within_deadline_is_failed_with_deadline_exceeded_error() throws Exception {
+ void task_not_completed_within_deadline_is_failed_with_deadline_exceeded_error() throws Exception {
FleetControllerOptions options = defaultOptions();
options.setMaxDeferredTaskVersionWaitTime(Duration.ofSeconds(60));
RemoteTaskFixture fixture = createFixtureWith(options);
@@ -1624,14 +1629,14 @@ public class StateChangeTest extends FleetControllerTest {
}
@Test
- public void task_not_completed_within_deadline_lists_nodes_not_converged_in_error_message() throws Exception {
+ void task_not_completed_within_deadline_lists_nodes_not_converged_in_error_message() throws Exception {
doTestTaskDeadlineExceeded(false, "the following nodes have not converged to " +
"at least version 4: distributor.0, distributor.1, distributor.2, distributor.3, " +
"distributor.4, distributor.5, distributor.6, distributor.7, distributor.8, distributor.9");
}
@Test
- public void task_not_completed_within_deadline_with_deferred_activation_checks_activation_version() throws Exception {
+ void task_not_completed_within_deadline_with_deferred_activation_checks_activation_version() throws Exception {
doTestTaskDeadlineExceeded(true, "the following nodes have not converged to " +
"at least version 4: distributor.0, distributor.1, distributor.2, distributor.3, " +
"distributor.4, distributor.5, distributor.6, distributor.7, distributor.8, distributor.9 " +
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/StateGatherTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/StateGatherTest.java
index 041f4e4052d..892aefbb865 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/StateGatherTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/StateGatherTest.java
@@ -2,12 +2,12 @@
package com.yahoo.vespa.clustercontroller.core;
import java.util.logging.Level;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.TimeoutException;
import java.util.logging.Logger;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class StateGatherTest extends FleetControllerTest {
@@ -24,7 +24,7 @@ public class StateGatherTest extends FleetControllerTest {
}
@Test
- public void testAlwaysHavePendingGetNodeStateRequestTowardsNodes() throws Exception {
+ void testAlwaysHavePendingGetNodeStateRequestTowardsNodes() throws Exception {
Logger.getLogger(NodeStateGatherer.class.getName()).setLevel(Level.FINEST);
startingTest("StateGatherTest::testOverlappingGetNodeStateRequests");
FleetControllerOptions options = defaultOptions("mycluster");
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/StateVersionTrackerTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/StateVersionTrackerTest.java
index 2361a5cefd8..0e3c3c6d4b3 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/StateVersionTrackerTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/StateVersionTrackerTest.java
@@ -7,13 +7,11 @@ import com.yahoo.vdslib.state.NodeState;
import com.yahoo.vdslib.state.NodeType;
import com.yahoo.vdslib.state.State;
import com.yahoo.vespa.clustercontroller.core.hostinfo.HostInfo;
-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.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -40,7 +38,7 @@ public class StateVersionTrackerTest {
}
@Test
- public void version_is_incremented_when_new_state_is_applied() {
+ void version_is_incremented_when_new_state_is_applied() {
final StateVersionTracker versionTracker = createWithMockedMetrics();
versionTracker.setVersionRetrievedFromZooKeeper(100);
updateAndPromote(versionTracker, stateWithoutAnnotations("distributor:2 storage:2"), 123);
@@ -49,33 +47,33 @@ public class StateVersionTrackerTest {
}
@Test
- public void version_is_1_upon_construction() {
+ void version_is_1_upon_construction() {
final StateVersionTracker versionTracker = createWithMockedMetrics();
assertEquals(1, versionTracker.getCurrentVersion());
}
@Test
- public void set_current_version_caps_lowest_version_to_1() {
+ void set_current_version_caps_lowest_version_to_1() {
final StateVersionTracker versionTracker = createWithMockedMetrics();
versionTracker.setVersionRetrievedFromZooKeeper(0);
assertEquals(1, versionTracker.getCurrentVersion());
}
@Test
- public void new_version_from_zk_predicate_initially_false() {
+ void new_version_from_zk_predicate_initially_false() {
final StateVersionTracker versionTracker = createWithMockedMetrics();
assertFalse(versionTracker.hasReceivedNewVersionFromZooKeeper());
}
@Test
- public void new_version_from_zk_predicate_true_after_setting_zk_version() {
+ void new_version_from_zk_predicate_true_after_setting_zk_version() {
final StateVersionTracker versionTracker = createWithMockedMetrics();
versionTracker.setVersionRetrievedFromZooKeeper(5);
assertTrue(versionTracker.hasReceivedNewVersionFromZooKeeper());
}
@Test
- public void new_version_from_zk_predicate_false_after_applying_higher_version() {
+ void new_version_from_zk_predicate_false_after_applying_higher_version() {
final StateVersionTracker versionTracker = createWithMockedMetrics();
versionTracker.setVersionRetrievedFromZooKeeper(5);
updateAndPromote(versionTracker, stateWithoutAnnotations("distributor:2 storage:2"), 123);
@@ -83,14 +81,14 @@ public class StateVersionTrackerTest {
}
@Test
- public void exposed_states_are_empty_upon_construction() {
+ void exposed_states_are_empty_upon_construction() {
final StateVersionTracker versionTracker = createWithMockedMetrics();
assertTrue(versionTracker.getVersionedClusterState().toString().isEmpty());
assertTrue(versionTracker.getAnnotatedVersionedClusterState().getClusterState().toString().isEmpty());
}
@Test
- public void diff_from_initial_state_implies_changed_state() {
+ void diff_from_initial_state_implies_changed_state() {
final StateVersionTracker versionTracker = createWithMockedMetrics();
versionTracker.updateLatestCandidateStateBundle(stateBundleWithoutAnnotations("cluster:d"));
assertTrue(versionTracker.candidateChangedEnoughFromCurrentToWarrantPublish());
@@ -104,48 +102,48 @@ public class StateVersionTrackerTest {
}
@Test
- public void version_mismatch_not_counted_as_changed_state() {
+ void version_mismatch_not_counted_as_changed_state() {
assertFalse(stateChangedBetween("distributor:2 storage:2", "distributor:2 storage:2"));
}
@Test
- public void different_distributor_node_count_implies_changed_state() {
+ void different_distributor_node_count_implies_changed_state() {
assertTrue(stateChangedBetween("distributor:2 storage:2", "distributor:3 storage:2"));
assertTrue(stateChangedBetween("distributor:3 storage:2", "distributor:2 storage:2"));
}
@Test
- public void different_storage_node_count_implies_changed_state() {
+ void different_storage_node_count_implies_changed_state() {
assertTrue(stateChangedBetween("distributor:2 storage:2", "distributor:2 storage:3"));
assertTrue(stateChangedBetween("distributor:2 storage:3", "distributor:2 storage:2"));
}
@Test
- public void different_distributor_node_state_implies_changed_state() {
+ void different_distributor_node_state_implies_changed_state() {
assertTrue(stateChangedBetween("distributor:2 storage:2", "distributor:2 .0.s:d storage:2"));
assertTrue(stateChangedBetween("distributor:2 .0.s:d storage:2", "distributor:2 storage:2"));
}
@Test
- public void different_storage_node_state_implies_changed_state() {
+ void different_storage_node_state_implies_changed_state() {
assertTrue(stateChangedBetween("distributor:2 storage:2", "distributor:2 storage:2 .0.s:d"));
assertTrue(stateChangedBetween("distributor:2 storage:2 .0.s:d", "distributor:2 storage:2"));
}
@Test
- public void init_progress_change_not_counted_as_changed_state() {
+ void init_progress_change_not_counted_as_changed_state() {
assertFalse(stateChangedBetween("distributor:2 storage:2 .0.s:i .0.i:0.5",
- "distributor:2 storage:2 .0.s:i .0.i:0.6"));
+ "distributor:2 storage:2 .0.s:i .0.i:0.6"));
}
@Test
- public void lowest_observed_distribution_bit_is_initially_16() {
+ void lowest_observed_distribution_bit_is_initially_16() {
final StateVersionTracker versionTracker = createWithMockedMetrics();
assertEquals(16, versionTracker.getLowestObservedDistributionBits());
}
@Test
- public void lowest_observed_distribution_bit_is_tracked_across_states() {
+ void lowest_observed_distribution_bit_is_tracked_across_states() {
final StateVersionTracker versionTracker = createWithMockedMetrics();
updateAndPromote(versionTracker, stateWithoutAnnotations("bits:15 distributor:2 storage:2"), 100);
assertEquals(15, versionTracker.getLowestObservedDistributionBits());
@@ -161,7 +159,7 @@ public class StateVersionTrackerTest {
// min used bits. The former is derived from the latter, but the latter is not visible in the
// published state (but _is_ visible in the internal ClusterState structures).
@Test
- public void per_node_min_bits_changes_are_not_considered_different() {
+ void per_node_min_bits_changes_are_not_considered_different() {
final StateVersionTracker versionTracker = createWithMockedMetrics();
final AnnotatedClusterState stateWithMinBits = stateWithoutAnnotations("distributor:2 storage:2");
stateWithMinBits.getClusterState().setNodeState(
@@ -173,7 +171,7 @@ public class StateVersionTrackerTest {
}
@Test
- public void state_history_is_initially_empty() {
+ void state_history_is_initially_empty() {
final StateVersionTracker versionTracker = createWithMockedMetrics();
assertTrue(versionTracker.getClusterStateHistory().isEmpty());
}
@@ -188,9 +186,9 @@ public class StateVersionTrackerTest {
}
@Test
- public void applying_state_adds_to_cluster_state_history() {
+ void applying_state_adds_to_cluster_state_history() {
final StateVersionTracker versionTracker = createWithMockedMetrics();
- updateAndPromote(versionTracker, stateWithoutAnnotations("distributor:2 storage:2") ,100);
+ updateAndPromote(versionTracker, stateWithoutAnnotations("distributor:2 storage:2"), 100);
updateAndPromote(versionTracker, stateWithoutAnnotations("distributor:3 storage:3"), 200);
updateAndPromote(versionTracker, stateWithoutAnnotations("distributor:4 storage:4"), 300);
@@ -204,11 +202,11 @@ public class StateVersionTrackerTest {
}
@Test
- public void old_states_pruned_when_state_history_limit_reached() {
+ void old_states_pruned_when_state_history_limit_reached() {
final StateVersionTracker versionTracker = createWithMockedMetrics();
versionTracker.setMaxHistoryEntryCount(2);
- updateAndPromote(versionTracker, stateWithoutAnnotations("distributor:2 storage:2") ,100);
+ updateAndPromote(versionTracker, stateWithoutAnnotations("distributor:2 storage:2"), 100);
updateAndPromote(versionTracker, stateWithoutAnnotations("distributor:3 storage:3"), 200);
updateAndPromote(versionTracker, stateWithoutAnnotations("distributor:4 storage:4"), 300);
@@ -227,7 +225,7 @@ public class StateVersionTrackerTest {
}
@Test
- public void can_get_latest_non_published_candidate_state() {
+ void can_get_latest_non_published_candidate_state() {
final StateVersionTracker versionTracker = createWithMockedMetrics();
AnnotatedClusterState candidate = stateWithoutAnnotations("distributor:2 storage:2");
@@ -258,7 +256,7 @@ public class StateVersionTrackerTest {
}
@Test
- public void version_change_check_takes_derived_states_into_account() {
+ void version_change_check_takes_derived_states_into_account() {
final StateVersionTracker versionTracker = createWithMockedMetrics();
versionTracker.updateLatestCandidateStateBundle(baselineBundle(false));
versionTracker.promoteCandidateToVersionedState(1234);
@@ -273,7 +271,7 @@ public class StateVersionTrackerTest {
}
@Test
- public void buckets_pending_state_is_tracked_between_cluster_states() {
+ void buckets_pending_state_is_tracked_between_cluster_states() {
final StateVersionTracker tracker = createWithMockedMetrics();
final NodeInfo distributorNode = mock(DistributorNodeInfo.class);
when(distributorNode.isDistributor()).thenReturn(true);
@@ -307,7 +305,7 @@ public class StateVersionTrackerTest {
}
@Test
- public void setting_zookeeper_retrieved_bundle_sets_current_versioned_state_and_resets_candidate_state() {
+ void setting_zookeeper_retrieved_bundle_sets_current_versioned_state_and_resets_candidate_state() {
final StateVersionTracker versionTracker = createWithMockedMetrics();
versionTracker.setVersionRetrievedFromZooKeeper(100);
versionTracker.updateLatestCandidateStateBundle(
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/SystemStateBroadcasterTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/SystemStateBroadcasterTest.java
index 1832f1132ac..0a193766df3 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/SystemStateBroadcasterTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/SystemStateBroadcasterTest.java
@@ -8,13 +8,13 @@ import com.yahoo.vdslib.state.State;
import com.yahoo.vespa.clustercontroller.core.database.DatabaseHandler;
import com.yahoo.vespa.clustercontroller.core.listeners.SlobrokListener;
import com.yahoo.vespa.clustercontroller.core.listeners.NodeListener;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.stream.Stream;
-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;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
@@ -85,7 +85,7 @@ public class SystemStateBroadcasterTest {
}
@Test
- public void always_publish_baseline_cluster_state() {
+ void always_publish_baseline_cluster_state() {
Fixture f = new Fixture();
ClusterStateBundle stateBundle = ClusterStateBundleUtil.makeBundle("version:3 distributor:2 storage:2");
ClusterFixture cf = ClusterFixture.forFlatCluster(2).bringEntireClusterUp().assignDummyRpcAddresses();
@@ -95,7 +95,7 @@ public class SystemStateBroadcasterTest {
}
@Test
- public void non_observed_startup_timestamps_are_published_per_node_for_baseline_state() {
+ void non_observed_startup_timestamps_are_published_per_node_for_baseline_state() {
Fixture f = new Fixture();
ClusterStateBundle stateBundle = ClusterStateBundleUtil.makeBundle("version:3 distributor:2 storage:2");
ClusterFixture cf = ClusterFixture.forFlatCluster(2).bringEntireClusterUp().assignDummyRpcAddresses();
@@ -112,7 +112,7 @@ public class SystemStateBroadcasterTest {
}
@Test
- public void bucket_space_states_are_published_verbatim_when_no_additional_timestamps_needed() {
+ void bucket_space_states_are_published_verbatim_when_no_additional_timestamps_needed() {
Fixture f = new Fixture();
ClusterStateBundle stateBundle = ClusterStateBundleUtil.makeBundle("version:3 distributor:2 storage:2",
StateMapping.of("default", "version:3 distributor:2 storage:2 .0.s:d"),
@@ -125,7 +125,7 @@ public class SystemStateBroadcasterTest {
}
@Test
- public void non_observed_startup_timestamps_are_published_per_bucket_space_state() {
+ void non_observed_startup_timestamps_are_published_per_bucket_space_state() {
Fixture f = new Fixture();
ClusterStateBundle stateBundle = ClusterStateBundleUtil.makeBundle("version:3 distributor:2 storage:2",
StateMapping.of("default", "version:3 distributor:2 storage:2 .0.s:d"),
@@ -146,7 +146,7 @@ public class SystemStateBroadcasterTest {
}
@Test
- public void state_not_broadcast_if_version_not_tagged_as_written_to_zookeeper() {
+ void state_not_broadcast_if_version_not_tagged_as_written_to_zookeeper() {
Fixture f = new Fixture();
ClusterStateBundle stateBundle = ClusterStateBundleUtil.makeBundle("version:100 distributor:2 storage:2");
ClusterFixture cf = ClusterFixture.forFlatCluster(2).bringEntireClusterUp().assignDummyRpcAddresses();
@@ -159,7 +159,7 @@ public class SystemStateBroadcasterTest {
}
@Test
- public void state_is_broadcast_if_version_is_tagged_as_written_to_zookeeper() {
+ void state_is_broadcast_if_version_is_tagged_as_written_to_zookeeper() {
Fixture f = new Fixture();
ClusterStateBundle stateBundle = ClusterStateBundleUtil.makeBundle("version:100 distributor:2 storage:2");
ClusterFixture cf = ClusterFixture.forFlatCluster(2).bringEntireClusterUp().assignDummyRpcAddresses();
@@ -262,9 +262,10 @@ public class SystemStateBroadcasterTest {
}
}
+ // Type erasure of Waiter in mocked argument capture
@Test
- @SuppressWarnings("unchecked") // Type erasure of Waiter in mocked argument capture
- public void activation_not_sent_before_all_distributors_have_acked_state_bundle() {
+ @SuppressWarnings("unchecked")
+ void activation_not_sent_before_all_distributors_have_acked_state_bundle() {
var f = StateActivationFixture.withTwoPhaseEnabled();
var cf = f.cf;
@@ -292,9 +293,10 @@ public class SystemStateBroadcasterTest {
assertNull(f.broadcaster.getLastClusterStateBundleConverged());
}
+ // Type erasure of Waiter in mocked argument capture
@Test
- @SuppressWarnings("unchecked") // Type erasure of Waiter in mocked argument capture
- public void state_bundle_not_considered_converged_until_activation_acked_by_all_distributors() {
+ @SuppressWarnings("unchecked")
+ void state_bundle_not_considered_converged_until_activation_acked_by_all_distributors() {
var f = StateActivationFixture.withTwoPhaseEnabled();
var cf = f.cf;
@@ -309,22 +311,23 @@ public class SystemStateBroadcasterTest {
});
respondToActivateClusterStateVersion(cf.cluster.getNodeInfo(Node.ofDistributor(0)),
- f.stateBundle, d0ActivateWaiter.getValue());
+ f.stateBundle, d0ActivateWaiter.getValue());
f.simulateBroadcastTick(cf, 123);
assertNull(f.broadcaster.getLastClusterStateBundleConverged()); // Not yet converged
respondToActivateClusterStateVersion(cf.cluster.getNodeInfo(Node.ofDistributor(1)),
- f.stateBundle, d1ActivateWaiter.getValue());
+ f.stateBundle, d1ActivateWaiter.getValue());
f.simulateBroadcastTick(cf, 123);
// Finally, all distributors have ACKed the version! State is marked as converged.
assertEquals(f.stateBundle, f.broadcaster.getLastClusterStateBundleConverged());
}
+ // Type erasure of Waiter in mocked argument capture
@Test
- @SuppressWarnings("unchecked") // Type erasure of Waiter in mocked argument capture
- public void activation_not_sent_if_deferred_activation_is_disabled_in_state_bundle() {
+ @SuppressWarnings("unchecked")
+ void activation_not_sent_if_deferred_activation_is_disabled_in_state_bundle() {
var f = StateActivationFixture.withTwoPhaseDisabled();
var cf = f.cf;
@@ -339,9 +342,10 @@ public class SystemStateBroadcasterTest {
});
}
+ // Type erasure of Waiter in mocked argument capture
@Test
- @SuppressWarnings("unchecked") // Type erasure of Waiter in mocked argument capture
- public void activation_convergence_considers_actual_version_returned_from_node() {
+ @SuppressWarnings("unchecked")
+ void activation_convergence_considers_actual_version_returned_from_node() {
var f = StateActivationFixture.withTwoPhaseEnabled();
var cf = f.cf;
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/UpEdgeMaintenanceTransitionConstraintTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/UpEdgeMaintenanceTransitionConstraintTest.java
index 6257a10064a..5471a6ff4be 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/UpEdgeMaintenanceTransitionConstraintTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/UpEdgeMaintenanceTransitionConstraintTest.java
@@ -2,10 +2,10 @@
package com.yahoo.vespa.clustercontroller.core;
import com.yahoo.vdslib.state.ClusterState;
-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;
public class UpEdgeMaintenanceTransitionConstraintTest {
@@ -19,27 +19,27 @@ public class UpEdgeMaintenanceTransitionConstraintTest {
}
@Test
- public void transition_allowed_when_previous_state_is_down() {
+ void transition_allowed_when_previous_state_is_down() {
assertTrue(nodeMayTransitionToMaintenanceInState(1, "distributor:5 storage:5 .1.s:d"));
}
@Test
- public void transition_allowed_when_previous_state_is_maintenance() {
+ void transition_allowed_when_previous_state_is_maintenance() {
assertTrue(nodeMayTransitionToMaintenanceInState(1, "distributor:5 storage:5 .1.s:m"));
}
@Test
- public void transition_not_allowed_when_previous_state_is_up() {
+ void transition_not_allowed_when_previous_state_is_up() {
assertFalse(nodeMayTransitionToMaintenanceInState(0, "distributor:5 storage:5"));
}
@Test
- public void transition_not_allowed_when_previous_state_is_initializing() {
+ void transition_not_allowed_when_previous_state_is_initializing() {
assertFalse(nodeMayTransitionToMaintenanceInState(0, "distributor:5 storage:5 .0.s:i"));
}
@Test
- public void transition_not_allowed_when_previous_state_is_retired() {
+ void transition_not_allowed_when_previous_state_is_retired() {
assertFalse(nodeMayTransitionToMaintenanceInState(0, "distributor:5 storage:5 .0.s:r"));
}
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/WantedStateTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/WantedStateTest.java
index a58f75dba02..7bbae78dbab 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/WantedStateTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/WantedStateTest.java
@@ -2,13 +2,14 @@
package com.yahoo.vespa.clustercontroller.core;
import com.yahoo.vdslib.state.State;
-import org.junit.Test;
-import static org.junit.Assert.assertEquals;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class WantedStateTest extends FleetControllerTest {
@Test
- public void testSettingStorageNodeMaintenanceAndBack() throws Exception {
+ void testSettingStorageNodeMaintenanceAndBack() throws Exception {
startingTest("WantedStateTest::testSettingStorageNodeMaintenanceAndBack()");
setUpFleetController(true, defaultOptions("mycluster"));
setUpVdsNodes(true, new DummyVdsNodeOptions());
@@ -22,7 +23,7 @@ public class WantedStateTest extends FleetControllerTest {
}
@Test
- public void testOverridingWantedStateOtherReason() throws Exception {
+ void testOverridingWantedStateOtherReason() throws Exception {
startingTest("WantedStateTest::testOverridingWantedStateOtherReason()");
setUpFleetController(true, defaultOptions("mycluster"));
setUpVdsNodes(true, new DummyVdsNodeOptions());
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ZooKeeperDatabaseTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ZooKeeperDatabaseTest.java
index 1ce7586adea..79c03a67698 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ZooKeeperDatabaseTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/ZooKeeperDatabaseTest.java
@@ -4,22 +4,16 @@ package com.yahoo.vespa.clustercontroller.core;
import com.yahoo.vespa.clustercontroller.core.database.CasWriteFailed;
import com.yahoo.vespa.clustercontroller.core.database.Database;
import com.yahoo.vespa.clustercontroller.core.database.ZooKeeperDatabase;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.time.Duration;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.mock;
public class ZooKeeperDatabaseTest {
- @SuppressWarnings("deprecation")
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
private static class Fixture implements AutoCloseable {
final ZooKeeperTestServer zkServer;
ClusterFixture clusterFixture;
@@ -58,7 +52,7 @@ public class ZooKeeperDatabaseTest {
}
@Test
- public void can_store_and_load_cluster_state_bundle_from_database() throws Exception {
+ void can_store_and_load_cluster_state_bundle_from_database() throws Exception {
try (Fixture f = new Fixture()) {
f.createDatabase();
f.db().retrieveLastPublishedStateBundle(); // Must be called once prior to prime last known znode version
@@ -77,27 +71,29 @@ public class ZooKeeperDatabaseTest {
}
@Test
- public void storing_cluster_state_bundle_with_mismatching_expected_znode_version_throws_exception() throws Exception {
- expectedException.expect(CasWriteFailed.class);
- expectedException.expectMessage("version mismatch in cluster state bundle znode (expected -2)");
- try (Fixture f = new Fixture()) {
- f.createDatabase();
- f.db().storeLastPublishedStateBundle(dummyBundle());
- }
+ void storing_cluster_state_bundle_with_mismatching_expected_znode_version_throws_exception() throws Exception {
+ Throwable exception = assertThrows(CasWriteFailed.class, () -> {
+ try (Fixture f = new Fixture()) {
+ f.createDatabase();
+ f.db().storeLastPublishedStateBundle(dummyBundle());
+ }
+ });
+ assertTrue(exception.getMessage().contains("version mismatch in cluster state bundle znode (expected -2)"));
}
@Test
- public void storing_cluster_state_version_with_mismatching_expected_znode_version_throws_exception() throws Exception {
- expectedException.expect(CasWriteFailed.class);
- expectedException.expectMessage("version mismatch in cluster state version znode (expected -2)");
- try (Fixture f = new Fixture()) {
- f.createDatabase();
- f.db().storeLatestSystemStateVersion(12345);
- }
+ void storing_cluster_state_version_with_mismatching_expected_znode_version_throws_exception() throws Exception {
+ Throwable exception = assertThrows(CasWriteFailed.class, () -> {
+ try (Fixture f = new Fixture()) {
+ f.createDatabase();
+ f.db().storeLatestSystemStateVersion(12345);
+ }
+ });
+ assertTrue(exception.getMessage().contains("version mismatch in cluster state version znode (expected -2)"));
}
@Test
- public void empty_state_bundle_is_returned_if_no_bundle_already_stored_in_database() throws Exception {
+ void empty_state_bundle_is_returned_if_no_bundle_already_stored_in_database() throws Exception {
try (Fixture f = new Fixture()) {
f.createDatabase();
ClusterStateBundle bundleReceived = f.db().retrieveLastPublishedStateBundle();
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/hostinfo/HostInfoTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/hostinfo/HostInfoTest.java
index b5ad82b6b0c..3c9fd069e14 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/hostinfo/HostInfoTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/hostinfo/HostInfoTest.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.vespa.clustercontroller.core.hostinfo;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@@ -13,10 +13,7 @@ import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
-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.*;
public class HostInfoTest {
@@ -29,7 +26,7 @@ public class HostInfoTest {
}
@Test
- public void testEmptyJson() {
+ void testEmptyJson() {
HostInfo hostInfo = HostInfo.createHostInfo("{}");
assertNull(hostInfo.getVtag().getVersionOrNull());
assertTrue(hostInfo.getDistributor().getStorageNodes().isEmpty());
@@ -39,13 +36,13 @@ public class HostInfoTest {
}
@Test
- public void testExtendedJson() throws IOException {
+ void testExtendedJson() throws IOException {
HostInfo hostInfo = HostInfo.createHostInfo(readDataFile("host_info.json"));
assertEquals("5.32.76", hostInfo.getVtag().getVersionOrNull());
}
@Test
- public void testFullSet() throws IOException {
+ void testFullSet() throws IOException {
HostInfo hostInfo = HostInfo.createHostInfo(readDataFile("host_info.json"));
List<StorageNode> storageNodeList = hostInfo.getDistributor().getStorageNodes();
assertEquals(2, storageNodeList.size());
@@ -59,8 +56,8 @@ public class HostInfoTest {
assertEquals(123, hostInfo.getClusterStateVersionOrNull().intValue());
assertEquals(Optional.of(129L), hostInfo.getMetrics()
- .getValueAt("vds.datastored.bucket_space.buckets_total", Map.of("bucketSpace", "default"))
- .map(Metrics.Value::getLast));
+ .getValueAt("vds.datastored.bucket_space.buckets_total", Map.of("bucketSpace", "default"))
+ .map(Metrics.Value::getLast));
assertEquals(Optional.of(0L),
hostInfo.getMetrics()
.getValueAt("vds.datastored.bucket_space.buckets_total", Map.of("bucketSpace", "global"))
@@ -75,7 +72,7 @@ public class HostInfoTest {
}
@Test
- public void testSpeed() throws Exception {
+ void testSpeed() throws Exception {
String json = readDataFile("slow_host_info.json");
long start = 0;
@@ -92,7 +89,7 @@ public class HostInfoTest {
}
@Test
- public void testSharedFile() throws Exception {
+ void testSharedFile() throws Exception {
String json = readDataFile("distributor.json");
HostInfo hostInfo = HostInfo.createHostInfo(json);
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/hostinfo/StorageNodeStatsBridgeTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/hostinfo/StorageNodeStatsBridgeTest.java
index cb99dfe38e3..0eb25ab5cd4 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/hostinfo/StorageNodeStatsBridgeTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/hostinfo/StorageNodeStatsBridgeTest.java
@@ -3,7 +3,7 @@ package com.yahoo.vespa.clustercontroller.core.hostinfo;
import com.yahoo.vespa.clustercontroller.core.ContentNodeStats;
import com.yahoo.vespa.clustercontroller.core.ContentClusterStats;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@@ -14,7 +14,7 @@ import java.util.Iterator;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertFalse;
/**
* @author hakonhall
@@ -29,7 +29,7 @@ public class StorageNodeStatsBridgeTest {
}
@Test
- public void testContentNodeStats() throws IOException {
+ void testContentNodeStats() throws IOException {
String data = getJsonString();
HostInfo hostInfo = HostInfo.createHostInfo(data);
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/ClusterListTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/ClusterListTest.java
index 84116674afa..8e49703c94b 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/ClusterListTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/ClusterListTest.java
@@ -2,67 +2,68 @@
package com.yahoo.vespa.clustercontroller.core.restapiv2;
import com.yahoo.vespa.clustercontroller.utils.staterestapi.response.UnitResponse;
-import org.junit.Test;
-import static org.junit.Assert.assertEquals;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class ClusterListTest extends StateRestApiTest {
@Test
- public void testClusterList() throws Exception {
+ void testClusterList() throws Exception {
setUp(true);
UnitResponse response = restAPI.getState(new StateRequest("", 0));
String expected =
"{\"cluster\": {\n" +
- " \"books\": {\"link\": \"\\/cluster\\/v2\\/books\"},\n" +
- " \"music\": {\"link\": \"\\/cluster\\/v2\\/music\"}\n" +
- "}}";
+ " \"books\": {\"link\": \"\\/cluster\\/v2\\/books\"},\n" +
+ " \"music\": {\"link\": \"\\/cluster\\/v2\\/music\"}\n" +
+ "}}";
assertEquals(expected, jsonWriter.createJson(response).toString(2));
}
@Test
- public void testRecursiveClusterList() throws Exception {
+ void testRecursiveClusterList() throws Exception {
setUp(true);
UnitResponse response = restAPI.getState(new StateRequest("", 1));
String expected =
"{\"cluster\": {\n" +
- " \"books\": {\n" +
- " \"state\": {\"generated\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " }},\n" +
- " \"service\": {\n" +
- " \"storage\": {\"link\": \"\\/cluster\\/v2\\/books\\/storage\"},\n" +
- " \"distributor\": {\"link\": \"\\/cluster\\/v2\\/books\\/distributor\"}\n" +
- " },\n" +
- " \"distribution-states\": {\"published\": {\n" +
- " \"baseline\": \"distributor:4 storage:4\",\n" +
- " \"bucket-spaces\": [\n" +
- " {\n" +
- " \"name\": \"default\",\n" +
- " \"state\": \"distributor:4 storage:4 .3.s:m\"\n" +
- " },\n" +
- " {\n" +
- " \"name\": \"global\",\n" +
- " \"state\": \"distributor:4 storage:4\"\n" +
- " }\n" +
- " ]\n" +
- " }}\n" +
- " },\n" +
- " \"music\": {\n" +
- " \"state\": {\"generated\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " }},\n" +
- " \"service\": {\n" +
- " \"storage\": {\"link\": \"\\/cluster\\/v2\\/music\\/storage\"},\n" +
- " \"distributor\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\"}\n" +
- " },\n" +
- " \"distribution-states\": {\"published\": {\n" +
- " \"baseline\": \"distributor:8 .0.s:d .2.s:d .4.s:d .6.s:d storage:8 .0.s:d .2.s:d .4.s:d .6.s:d\",\n" +
- " \"bucket-spaces\": []\n" +
- " }}\n" +
- " }\n" +
- "}}";
+ " \"books\": {\n" +
+ " \"state\": {\"generated\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " }},\n" +
+ " \"service\": {\n" +
+ " \"storage\": {\"link\": \"\\/cluster\\/v2\\/books\\/storage\"},\n" +
+ " \"distributor\": {\"link\": \"\\/cluster\\/v2\\/books\\/distributor\"}\n" +
+ " },\n" +
+ " \"distribution-states\": {\"published\": {\n" +
+ " \"baseline\": \"distributor:4 storage:4\",\n" +
+ " \"bucket-spaces\": [\n" +
+ " {\n" +
+ " \"name\": \"default\",\n" +
+ " \"state\": \"distributor:4 storage:4 .3.s:m\"\n" +
+ " },\n" +
+ " {\n" +
+ " \"name\": \"global\",\n" +
+ " \"state\": \"distributor:4 storage:4\"\n" +
+ " }\n" +
+ " ]\n" +
+ " }}\n" +
+ " },\n" +
+ " \"music\": {\n" +
+ " \"state\": {\"generated\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " }},\n" +
+ " \"service\": {\n" +
+ " \"storage\": {\"link\": \"\\/cluster\\/v2\\/music\\/storage\"},\n" +
+ " \"distributor\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\"}\n" +
+ " },\n" +
+ " \"distribution-states\": {\"published\": {\n" +
+ " \"baseline\": \"distributor:8 .0.s:d .2.s:d .4.s:d .6.s:d storage:8 .0.s:d .2.s:d .4.s:d .6.s:d\",\n" +
+ " \"bucket-spaces\": []\n" +
+ " }}\n" +
+ " }\n" +
+ "}}";
assertEquals(expected, jsonWriter.createJson(response).toString(2));
}
}
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/ClusterTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/ClusterTest.java
index 2efb731c88c..ab9c92a6d9e 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/ClusterTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/ClusterTest.java
@@ -2,74 +2,74 @@
package com.yahoo.vespa.clustercontroller.core.restapiv2;
import com.yahoo.vespa.clustercontroller.utils.staterestapi.response.UnitResponse;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class ClusterTest extends StateRestApiTest {
@Test
- public void testCluster() throws Exception {
+ void testCluster() throws Exception {
setUp(true);
UnitResponse response = restAPI.getState(new StateRequest("books", 0));
String expected =
"{\n" +
- " \"state\": {\"generated\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " }},\n" +
- " \"service\": {\n" +
- " \"storage\": {\"link\": \"\\/cluster\\/v2\\/books\\/storage\"},\n" +
- " \"distributor\": {\"link\": \"\\/cluster\\/v2\\/books\\/distributor\"}\n" +
- " },\n" +
- " \"distribution-states\": {\"published\": {\n" +
- " \"baseline\": \"distributor:4 storage:4\",\n" +
- " \"bucket-spaces\": [\n" +
- " {\n" +
- " \"name\": \"default\",\n" +
- " \"state\": \"distributor:4 storage:4 .3.s:m\"\n" +
- " },\n" +
- " {\n" +
- " \"name\": \"global\",\n" +
- " \"state\": \"distributor:4 storage:4\"\n" +
- " }\n" +
- " ]\n" +
- " }}\n" +
- "}";
+ " \"state\": {\"generated\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " }},\n" +
+ " \"service\": {\n" +
+ " \"storage\": {\"link\": \"\\/cluster\\/v2\\/books\\/storage\"},\n" +
+ " \"distributor\": {\"link\": \"\\/cluster\\/v2\\/books\\/distributor\"}\n" +
+ " },\n" +
+ " \"distribution-states\": {\"published\": {\n" +
+ " \"baseline\": \"distributor:4 storage:4\",\n" +
+ " \"bucket-spaces\": [\n" +
+ " {\n" +
+ " \"name\": \"default\",\n" +
+ " \"state\": \"distributor:4 storage:4 .3.s:m\"\n" +
+ " },\n" +
+ " {\n" +
+ " \"name\": \"global\",\n" +
+ " \"state\": \"distributor:4 storage:4\"\n" +
+ " }\n" +
+ " ]\n" +
+ " }}\n" +
+ "}";
assertEquals(expected, jsonWriter.createJson(response).toString(2));
}
@Test
- public void testRecursiveCluster() throws Exception {
+ void testRecursiveCluster() throws Exception {
setUp(true);
UnitResponse response = restAPI.getState(new StateRequest("music", 1));
String expected =
"{\n" +
- " \"state\": {\"generated\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " }},\n" +
- " \"service\": {\n" +
- " \"storage\": {\"node\": {\n" +
- " \"1\": {\"link\": \"\\/cluster\\/v2\\/music\\/storage\\/1\"},\n" +
- " \"2\": {\"link\": \"\\/cluster\\/v2\\/music\\/storage\\/2\"},\n" +
- " \"3\": {\"link\": \"\\/cluster\\/v2\\/music\\/storage\\/3\"},\n" +
- " \"5\": {\"link\": \"\\/cluster\\/v2\\/music\\/storage\\/5\"},\n" +
- " \"7\": {\"link\": \"\\/cluster\\/v2\\/music\\/storage\\/7\"}\n" +
- " }},\n" +
- " \"distributor\": {\"node\": {\n" +
- " \"1\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\\/1\"},\n" +
- " \"2\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\\/2\"},\n" +
- " \"3\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\\/3\"},\n" +
- " \"5\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\\/5\"},\n" +
- " \"7\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\\/7\"}\n" +
- " }}\n" +
- " },\n" +
- " \"distribution-states\": {\"published\": {\n" +
- " \"baseline\": \"distributor:8 .0.s:d .2.s:d .4.s:d .6.s:d storage:8 .0.s:d .2.s:d .4.s:d .6.s:d\",\n" +
- " \"bucket-spaces\": []\n" +
- " }}\n" +
- "}";
+ " \"state\": {\"generated\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " }},\n" +
+ " \"service\": {\n" +
+ " \"storage\": {\"node\": {\n" +
+ " \"1\": {\"link\": \"\\/cluster\\/v2\\/music\\/storage\\/1\"},\n" +
+ " \"2\": {\"link\": \"\\/cluster\\/v2\\/music\\/storage\\/2\"},\n" +
+ " \"3\": {\"link\": \"\\/cluster\\/v2\\/music\\/storage\\/3\"},\n" +
+ " \"5\": {\"link\": \"\\/cluster\\/v2\\/music\\/storage\\/5\"},\n" +
+ " \"7\": {\"link\": \"\\/cluster\\/v2\\/music\\/storage\\/7\"}\n" +
+ " }},\n" +
+ " \"distributor\": {\"node\": {\n" +
+ " \"1\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\\/1\"},\n" +
+ " \"2\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\\/2\"},\n" +
+ " \"3\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\\/3\"},\n" +
+ " \"5\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\\/5\"},\n" +
+ " \"7\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\\/7\"}\n" +
+ " }}\n" +
+ " },\n" +
+ " \"distribution-states\": {\"published\": {\n" +
+ " \"baseline\": \"distributor:8 .0.s:d .2.s:d .4.s:d .6.s:d storage:8 .0.s:d .2.s:d .4.s:d .6.s:d\",\n" +
+ " \"bucket-spaces\": []\n" +
+ " }}\n" +
+ "}";
assertEquals(expected, jsonWriter.createJson(response).toString(2));
}
}
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/NodeTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/NodeTest.java
index 38fab2f5c54..52c46215e50 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/NodeTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/NodeTest.java
@@ -8,99 +8,99 @@ import com.yahoo.vdslib.state.State;
import com.yahoo.vespa.clustercontroller.core.ContentCluster;
import com.yahoo.vespa.clustercontroller.utils.staterestapi.response.UnitResponse;
import org.codehaus.jettison.json.JSONObject;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class NodeTest extends StateRestApiTest {
@Test
- public void testDistributor() throws Exception {
+ void testDistributor() throws Exception {
setUp(true);
UnitResponse response = restAPI.getState(new StateRequest("music/distributor/1", 0));
String expected =
"{\n" +
- " \"attributes\": {\"hierarchical-group\": \"east.g2\"},\n" +
- " \"state\": {\n" +
- " \"generated\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " },\n" +
- " \"unit\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " },\n" +
- " \"user\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " }\n" +
- " }\n" +
- "}";
+ " \"attributes\": {\"hierarchical-group\": \"east.g2\"},\n" +
+ " \"state\": {\n" +
+ " \"generated\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " },\n" +
+ " \"unit\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " },\n" +
+ " \"user\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " }\n" +
+ " }\n" +
+ "}";
assertEquals(expected, jsonWriter.createJson(response).toString(2));
}
@Test
- public void testStorage() throws Exception {
+ void testStorage() throws Exception {
setUp(true);
UnitResponse response = restAPI.getState(new StateRequest("music/storage/1", 0));
String expected =
"{\n" +
- " \"attributes\": {\"hierarchical-group\": \"east.g2\"},\n" +
- " \"state\": {\n" +
- " \"generated\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " },\n" +
- " \"unit\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " },\n" +
- " \"user\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " }\n" +
- " },\n" +
- " \"metrics\": {\n" +
- " \"bucket-count\": 1,\n" +
- " \"unique-document-count\": 2,\n" +
- " \"unique-document-total-size\": 3\n" +
- " }\n" +
- "}";
+ " \"attributes\": {\"hierarchical-group\": \"east.g2\"},\n" +
+ " \"state\": {\n" +
+ " \"generated\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " },\n" +
+ " \"unit\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " },\n" +
+ " \"user\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " }\n" +
+ " },\n" +
+ " \"metrics\": {\n" +
+ " \"bucket-count\": 1,\n" +
+ " \"unique-document-count\": 2,\n" +
+ " \"unique-document-total-size\": 3\n" +
+ " }\n" +
+ "}";
assertEquals(expected, jsonWriter.createJson(response).toString(2));
}
@Test
- public void testRecursiveNode() throws Exception {
+ void testRecursiveNode() throws Exception {
setUp(true);
UnitResponse response = restAPI.getState(new StateRequest("music/storage/1", 1));
String expected =
"{\n" +
- " \"attributes\": {\"hierarchical-group\": \"east.g2\"},\n" +
- " \"state\": {\n" +
- " \"generated\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " },\n" +
- " \"unit\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " },\n" +
- " \"user\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " }\n" +
- " },\n" +
- " \"metrics\": {\n" +
- " \"bucket-count\": 1,\n" +
- " \"unique-document-count\": 2,\n" +
- " \"unique-document-total-size\": 3\n" +
- " }\n" +
- "}";
+ " \"attributes\": {\"hierarchical-group\": \"east.g2\"},\n" +
+ " \"state\": {\n" +
+ " \"generated\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " },\n" +
+ " \"unit\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " },\n" +
+ " \"user\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " }\n" +
+ " },\n" +
+ " \"metrics\": {\n" +
+ " \"bucket-count\": 1,\n" +
+ " \"unique-document-count\": 2,\n" +
+ " \"unique-document-total-size\": 3\n" +
+ " }\n" +
+ "}";
assertEquals(expected, jsonWriter.createJson(response).toString(2));
}
@Test
- public void testNodeNotSeenInSlobrok() throws Exception {
+ void testNodeNotSeenInSlobrok() throws Exception {
setUp(true);
ContentCluster old = music.context.cluster;
music.context.cluster = new ContentCluster(old.getName(), old.getConfiguredNodes().values(), old.getDistribution());
@@ -110,22 +110,22 @@ public class NodeTest extends StateRestApiTest {
UnitResponse response = restAPI.getState(new StateRequest("music/storage/1", 0));
String expected =
"{\n" +
- " \"attributes\": {\"hierarchical-group\": \"east.g2\"},\n" +
- " \"state\": {\n" +
- " \"generated\": {\n" +
- " \"state\": \"down\",\n" +
- " \"reason\": \"Not seen\"\n" +
- " },\n" +
- " \"unit\": {\n" +
- " \"state\": \"down\",\n" +
- " \"reason\": \"Node not seen in slobrok.\"\n" +
- " },\n" +
- " \"user\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " }\n" +
- " }\n" +
- "}";
+ " \"attributes\": {\"hierarchical-group\": \"east.g2\"},\n" +
+ " \"state\": {\n" +
+ " \"generated\": {\n" +
+ " \"state\": \"down\",\n" +
+ " \"reason\": \"Not seen\"\n" +
+ " },\n" +
+ " \"unit\": {\n" +
+ " \"state\": \"down\",\n" +
+ " \"reason\": \"Node not seen in slobrok.\"\n" +
+ " },\n" +
+ " \"user\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " }\n" +
+ " }\n" +
+ "}";
assertEquals(expected, jsonWriter.createJson(response).toString(2));
}
}
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/NotMasterTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/NotMasterTest.java
index d85cf95defc..15aeded2d37 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/NotMasterTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/NotMasterTest.java
@@ -5,19 +5,17 @@ import com.yahoo.vespa.clustercontroller.utils.staterestapi.errors.OtherMasterEx
import com.yahoo.vespa.clustercontroller.utils.staterestapi.errors.UnknownMasterException;
import com.yahoo.vespa.clustercontroller.utils.staterestapi.response.UnitResponse;
import static com.yahoo.vespa.defaults.Defaults.getDefaults;
-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.*;
public class NotMasterTest extends StateRestApiTest {
@Test
- public void testUnknownMaster() throws Exception {
+ void testUnknownMaster() throws Exception {
setUp(true);
music.fleetControllerMaster = null;
- // Non-recursive cluster list works, as it doesn't touches into fleetcontrollers
+ // Non-recursive cluster list works, as it doesn't touches into fleetcontrollers
{
UnitResponse response = restAPI.getState(new StateRequest("", 0));
String expected =
@@ -27,49 +25,49 @@ public class NotMasterTest extends StateRestApiTest {
"}}";
assertEquals(expected, jsonWriter.createJson(response).toString(2));
}
- // Recursive cluster list does not work
- try{
+ // Recursive cluster list does not work
+ try {
restAPI.getState(new StateRequest("", 1));
fail();
} catch (UnknownMasterException e) {
- assertTrue(e.getMessage(), e.getMessage().contains("No known master cluster controller"));
+ assertTrue(e.getMessage().contains("No known master cluster controller"), e.getMessage());
}
- // Other requests does not work either
- try{
+ // Other requests does not work either
+ try {
restAPI.getState(new StateRequest("music", 0));
fail();
} catch (UnknownMasterException e) {
- assertTrue(e.getMessage(), e.getMessage().contains("No known master cluster controller"));
+ assertTrue(e.getMessage().contains("No known master cluster controller"), e.getMessage());
}
- try{
+ try {
restAPI.getState(new StateRequest("music/storage", 0));
fail();
} catch (UnknownMasterException e) {
- assertTrue(e.getMessage(), e.getMessage().contains("No known master cluster controller"));
+ assertTrue(e.getMessage().contains("No known master cluster controller"), e.getMessage());
}
- try{
+ try {
restAPI.getState(new StateRequest("music/storage/1", 0));
fail();
} catch (UnknownMasterException e) {
- assertTrue(e.getMessage(), e.getMessage().contains("No known master cluster controller"));
+ assertTrue(e.getMessage().contains("No known master cluster controller"), e.getMessage());
}
- try{
+ try {
restAPI.getState(new StateRequest("music/storage/1/0", 0));
fail();
} catch (UnknownMasterException e) {
- assertTrue(e.getMessage(), e.getMessage().contains("No known master cluster controller"));
+ assertTrue(e.getMessage().contains("No known master cluster controller"), e.getMessage());
}
- try{
+ try {
restAPI.setUnitState(new SetNodeStateTest.SetUnitStateRequestImpl("music/storage/1")
- .setNewState("user", "down", "test"));
+ .setNewState("user", "down", "test"));
fail();
} catch (UnknownMasterException e) {
- assertTrue(e.getMessage(), e.getMessage().contains("No known master cluster controller"));
+ assertTrue(e.getMessage().contains("No known master cluster controller"), e.getMessage());
}
}
@Test
- public void testKnownOtherMaster() throws Exception {
+ void testKnownOtherMaster() throws Exception {
setUp(true);
ccSockets.put(1, new ClusterControllerStateRestAPI.Socket("otherhost", getDefaults().vespaWebServicePort()));
music.fleetControllerMaster = 1;
@@ -78,59 +76,59 @@ public class NotMasterTest extends StateRestApiTest {
UnitResponse response = restAPI.getState(new StateRequest("", 0));
String expected =
"{\"cluster\": {\n" +
- " \"books\": {\"link\": \"\\/cluster\\/v2\\/books\"},\n" +
- " \"music\": {\"link\": \"\\/cluster\\/v2\\/music\"}\n" +
- "}}";
+ " \"books\": {\"link\": \"\\/cluster\\/v2\\/books\"},\n" +
+ " \"music\": {\"link\": \"\\/cluster\\/v2\\/music\"}\n" +
+ "}}";
assertEquals(expected, jsonWriter.createJson(response).toString(2));
}
// Recursive cluster list does not work
- try{
+ try {
restAPI.getState(new StateRequest("", 1));
fail();
} catch (OtherMasterException e) {
- assertTrue(e.getMessage(), e.getMessage().contains("Cluster controller not master. Use master at otherhost:" + getDefaults().vespaWebServicePort() + "."));
+ assertTrue(e.getMessage().contains("Cluster controller not master. Use master at otherhost:" + getDefaults().vespaWebServicePort() + "."), e.getMessage());
assertEquals("otherhost", e.getHost());
assertEquals(e.getPort(), getDefaults().vespaWebServicePort());
}
// Other requests does not work either
- try{
+ try {
restAPI.getState(new StateRequest("music", 0));
fail();
} catch (OtherMasterException e) {
- assertTrue(e.getMessage(), e.getMessage().contains("Cluster controller not master. Use master at otherhost:" + getDefaults().vespaWebServicePort() + "."));
+ assertTrue(e.getMessage().contains("Cluster controller not master. Use master at otherhost:" + getDefaults().vespaWebServicePort() + "."), e.getMessage());
assertEquals("otherhost", e.getHost());
assertEquals(e.getPort(), getDefaults().vespaWebServicePort());
}
- try{
+ try {
restAPI.getState(new StateRequest("music/storage", 0));
fail();
} catch (OtherMasterException e) {
- assertTrue(e.getMessage(), e.getMessage().contains("Cluster controller not master. Use master at otherhost:" + getDefaults().vespaWebServicePort() + "."));
+ assertTrue(e.getMessage().contains("Cluster controller not master. Use master at otherhost:" + getDefaults().vespaWebServicePort() + "."), e.getMessage());
assertEquals("otherhost", e.getHost());
assertEquals(e.getPort(), getDefaults().vespaWebServicePort());
}
- try{
+ try {
restAPI.getState(new StateRequest("music/storage/1", 0));
fail();
} catch (OtherMasterException e) {
- assertTrue(e.getMessage(), e.getMessage().contains("Cluster controller not master. Use master at otherhost:" + getDefaults().vespaWebServicePort() + "."));
+ assertTrue(e.getMessage().contains("Cluster controller not master. Use master at otherhost:" + getDefaults().vespaWebServicePort() + "."), e.getMessage());
assertEquals("otherhost", e.getHost());
assertEquals(e.getPort(), getDefaults().vespaWebServicePort());
}
- try{
+ try {
restAPI.getState(new StateRequest("music/storage/1/0", 0));
fail();
} catch (OtherMasterException e) {
- assertTrue(e.getMessage(), e.getMessage().contains("Cluster controller not master. Use master at otherhost:" + getDefaults().vespaWebServicePort() + "."));
+ assertTrue(e.getMessage().contains("Cluster controller not master. Use master at otherhost:" + getDefaults().vespaWebServicePort() + "."), e.getMessage());
assertEquals("otherhost", e.getHost());
assertEquals(e.getPort(), getDefaults().vespaWebServicePort());
}
- try{
+ try {
restAPI.setUnitState(new SetNodeStateTest.SetUnitStateRequestImpl("music/storage/1")
.setNewState("user", "down", "test"));
fail();
} catch (OtherMasterException e) {
- assertTrue(e.getMessage(), e.getMessage().contains("Cluster controller not master. Use master at otherhost:" + getDefaults().vespaWebServicePort() + "."));
+ assertTrue(e.getMessage().contains("Cluster controller not master. Use master at otherhost:" + getDefaults().vespaWebServicePort() + "."), e.getMessage());
assertEquals("otherhost", e.getHost());
assertEquals(e.getPort(), getDefaults().vespaWebServicePort());
}
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/PartitionTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/PartitionTest.java
index ec60adf16d3..65acea02d34 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/PartitionTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/PartitionTest.java
@@ -3,47 +3,47 @@ package com.yahoo.vespa.clustercontroller.core.restapiv2;
import com.yahoo.vespa.clustercontroller.utils.staterestapi.response.UnitResponse;
import org.codehaus.jettison.json.JSONObject;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class PartitionTest extends StateRestApiTest {
@Test
- public void testPartition() throws Exception {
+ void testPartition() throws Exception {
setUp(true);
UnitResponse response = restAPI.getState(new StateRequest("music/storage/1/0", 0));
String expected =
"{\n" +
- " \"state\": {\"generated\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " }},\n" +
- " \"metrics\": {\n" +
- " \"bucket-count\": 1,\n" +
- " \"unique-document-count\": 2,\n" +
- " \"unique-document-total-size\": 3\n" +
- " }\n" +
- "}";
+ " \"state\": {\"generated\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " }},\n" +
+ " \"metrics\": {\n" +
+ " \"bucket-count\": 1,\n" +
+ " \"unique-document-count\": 2,\n" +
+ " \"unique-document-total-size\": 3\n" +
+ " }\n" +
+ "}";
assertEquals(expected, jsonWriter.createJson(response).toString(2));
}
@Test
- public void testRecursiveCluster() throws Exception {
+ void testRecursiveCluster() throws Exception {
setUp(true);
UnitResponse response = restAPI.getState(new StateRequest("music/storage/1/0", 1));
String expected =
"{\n" +
- " \"state\": {\"generated\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " }},\n" +
- " \"metrics\": {\n" +
- " \"bucket-count\": 1,\n" +
- " \"unique-document-count\": 2,\n" +
- " \"unique-document-total-size\": 3\n" +
- " }\n" +
- "}";
+ " \"state\": {\"generated\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " }},\n" +
+ " \"metrics\": {\n" +
+ " \"bucket-count\": 1,\n" +
+ " \"unique-document-count\": 2,\n" +
+ " \"unique-document-total-size\": 3\n" +
+ " }\n" +
+ "}";
assertEquals(expected, jsonWriter.createJson(response).toString(2));
}
}
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/RequestTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/RequestTest.java
index ec8e7855db6..adbf24bc4d1 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/RequestTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/RequestTest.java
@@ -2,22 +2,21 @@
package com.yahoo.vespa.clustercontroller.core.restapiv2;
import com.yahoo.vespa.clustercontroller.utils.staterestapi.errors.InternalFailure;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.fail;
public class RequestTest {
@Test
- public void testGetResultBeforeCompletion() {
+ void testGetResultBeforeCompletion() {
Request<String> r = new Request<>(Request.MasterState.MUST_BE_MASTER) {
@Override
public String calculateResult(Context context) {
return "foo";
}
};
- try{
+ try {
r.getResult();
fail();
} catch (InternalFailure e) {
@@ -25,7 +24,7 @@ public class RequestTest {
fail();
}
r.notifyCompleted();
- try{
+ try {
r.getResult();
fail();
} catch (InternalFailure e) {
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/ServiceTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/ServiceTest.java
index f2aa00ea13e..2e5b610a039 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/ServiceTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/ServiceTest.java
@@ -2,119 +2,119 @@
package com.yahoo.vespa.clustercontroller.core.restapiv2;
import com.yahoo.vespa.clustercontroller.utils.staterestapi.response.UnitResponse;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class ServiceTest extends StateRestApiTest {
@Test
- public void testService() throws Exception {
+ void testService() throws Exception {
setUp(true);
UnitResponse response = restAPI.getState(new StateRequest("music/distributor", 0));
String expected =
"{\"node\": {\n" +
- " \"1\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\\/1\"},\n" +
- " \"2\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\\/2\"},\n" +
- " \"3\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\\/3\"},\n" +
- " \"5\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\\/5\"},\n" +
- " \"7\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\\/7\"}\n" +
- "}}";
+ " \"1\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\\/1\"},\n" +
+ " \"2\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\\/2\"},\n" +
+ " \"3\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\\/3\"},\n" +
+ " \"5\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\\/5\"},\n" +
+ " \"7\": {\"link\": \"\\/cluster\\/v2\\/music\\/distributor\\/7\"}\n" +
+ "}}";
assertEquals(expected, jsonWriter.createJson(response).toString(2));
}
@Test
- public void testRecursiveCluster() throws Exception {
+ void testRecursiveCluster() throws Exception {
setUp(true);
UnitResponse response = restAPI.getState(new StateRequest("music/distributor", 1));
String expected =
"{\"node\": {\n" +
- " \"1\": {\n" +
- " \"attributes\": {\"hierarchical-group\": \"east.g2\"},\n" +
- " \"state\": {\n" +
- " \"generated\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " },\n" +
- " \"unit\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " },\n" +
- " \"user\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " }\n" +
- " }\n" +
- " },\n" +
- " \"2\": {\n" +
- " \"attributes\": {\"hierarchical-group\": \"east.g1\"},\n" +
- " \"state\": {\n" +
- " \"generated\": {\n" +
- " \"state\": \"down\",\n" +
- " \"reason\": \"\"\n" +
- " },\n" +
- " \"unit\": {\n" +
- " \"state\": \"down\",\n" +
- " \"reason\": \"Node not seen in slobrok.\"\n" +
- " },\n" +
- " \"user\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " }\n" +
- " }\n" +
- " },\n" +
- " \"3\": {\n" +
- " \"attributes\": {\"hierarchical-group\": \"east.g2\"},\n" +
- " \"state\": {\n" +
- " \"generated\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " },\n" +
- " \"unit\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " },\n" +
- " \"user\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " }\n" +
- " }\n" +
- " },\n" +
- " \"5\": {\n" +
- " \"attributes\": {\"hierarchical-group\": \"east.g2\"},\n" +
- " \"state\": {\n" +
- " \"generated\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " },\n" +
- " \"unit\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " },\n" +
- " \"user\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " }\n" +
- " }\n" +
- " },\n" +
- " \"7\": {\n" +
- " \"attributes\": {\"hierarchical-group\": \"east.g2\"},\n" +
- " \"state\": {\n" +
- " \"generated\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " },\n" +
- " \"unit\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " },\n" +
- " \"user\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " }\n" +
- " }\n" +
- " }\n" +
- "}}";
+ " \"1\": {\n" +
+ " \"attributes\": {\"hierarchical-group\": \"east.g2\"},\n" +
+ " \"state\": {\n" +
+ " \"generated\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " },\n" +
+ " \"unit\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " },\n" +
+ " \"user\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " }\n" +
+ " }\n" +
+ " },\n" +
+ " \"2\": {\n" +
+ " \"attributes\": {\"hierarchical-group\": \"east.g1\"},\n" +
+ " \"state\": {\n" +
+ " \"generated\": {\n" +
+ " \"state\": \"down\",\n" +
+ " \"reason\": \"\"\n" +
+ " },\n" +
+ " \"unit\": {\n" +
+ " \"state\": \"down\",\n" +
+ " \"reason\": \"Node not seen in slobrok.\"\n" +
+ " },\n" +
+ " \"user\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " }\n" +
+ " }\n" +
+ " },\n" +
+ " \"3\": {\n" +
+ " \"attributes\": {\"hierarchical-group\": \"east.g2\"},\n" +
+ " \"state\": {\n" +
+ " \"generated\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " },\n" +
+ " \"unit\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " },\n" +
+ " \"user\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " }\n" +
+ " }\n" +
+ " },\n" +
+ " \"5\": {\n" +
+ " \"attributes\": {\"hierarchical-group\": \"east.g2\"},\n" +
+ " \"state\": {\n" +
+ " \"generated\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " },\n" +
+ " \"unit\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " },\n" +
+ " \"user\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " }\n" +
+ " }\n" +
+ " },\n" +
+ " \"7\": {\n" +
+ " \"attributes\": {\"hierarchical-group\": \"east.g2\"},\n" +
+ " \"state\": {\n" +
+ " \"generated\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " },\n" +
+ " \"unit\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " },\n" +
+ " \"user\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " }\n" +
+ " }\n" +
+ " }\n" +
+ "}}";
assertEquals(expected, jsonWriter.createJson(response).toString(2));
}
}
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/SetNodeStateTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/SetNodeStateTest.java
index 685ad3f0b43..1b52194b270 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/SetNodeStateTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/SetNodeStateTest.java
@@ -18,9 +18,7 @@ import com.yahoo.vespa.clustercontroller.utils.staterestapi.requests.SetUnitStat
import com.yahoo.vespa.clustercontroller.utils.staterestapi.response.SetResponse;
import com.yahoo.vespa.clustercontroller.utils.staterestapi.response.UnitResponse;
import com.yahoo.vespa.clustercontroller.utils.staterestapi.response.UnitState;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.Test;
import java.time.Clock;
import java.time.Duration;
@@ -32,11 +30,7 @@ import java.util.regex.Pattern;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.StringContains.containsString;
-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.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.Mockito.mock;
@@ -44,10 +38,6 @@ import static org.mockito.Mockito.when;
public class SetNodeStateTest extends StateRestApiTest {
- @SuppressWarnings("deprecation")
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
-
public static class SetUnitStateRequestImpl extends StateRequest implements SetUnitStateRequest {
private final Map<String, UnitState> newStates = new LinkedHashMap<>();
private Condition condition = Condition.FORCE;
@@ -176,7 +166,7 @@ public class SetNodeStateTest extends StateRestApiTest {
}
@Test
- public void testSimple() throws Exception {
+ void testSimple() throws Exception {
setUp(true);
verifyStateSet("down", "testing");
verifyStateSet("up", "foo");
@@ -186,14 +176,14 @@ public class SetNodeStateTest extends StateRestApiTest {
}
@Test
- public void testSetNodesForCluster() throws Exception {
+ void testSetNodesForCluster() throws Exception {
setUp(true);
verifyClusterSet("maintenance", "prepare for maintenance");
verifyClusterSet("up", "and we're back online");
}
@Test
- public void testShouldNotModifyDistributorSafe() throws Exception {
+ void testShouldNotModifyDistributorSafe() throws Exception {
setUp(false);
SetResponse setResponse = restAPI.setUnitState(new SetUnitStateRequestImpl("music/distributor/1")
.setNewState("user", "up", "whatever reason.")
@@ -204,7 +194,7 @@ public class SetNodeStateTest extends StateRestApiTest {
}
@Test
- public void testShouldModifyStorageSafeOk() throws Exception {
+ void testShouldModifyStorageSafeOk() throws Exception {
setUp(false);
SetResponse setResponse = restAPI.setUnitState(new SetUnitStateRequestImpl("music/storage/2")
.setNewState("user", "maintenance", "whatever reason.")
@@ -214,7 +204,7 @@ public class SetNodeStateTest extends StateRestApiTest {
}
@Test
- public void testShouldModifyStorageSafeBlocked() throws Exception {
+ void testShouldModifyStorageSafeBlocked() throws Exception {
// Sets up 2 groups: [0, 2, 4] and [1, 3, 5]
setUpMusicGroup(6, "");
@@ -254,7 +244,7 @@ public class SetNodeStateTest extends StateRestApiTest {
}
@Test
- public void settingSafeMaintenanceWhenNodeDown() throws Exception {
+ void settingSafeMaintenanceWhenNodeDown() throws Exception {
// Sets up 2 groups: [0, 2, 4] and [1, 3, 5], with 1 being down
setUpMusicGroup(6, " .1.s:d");
assertUnitState(1, "generated", State.DOWN, "");
@@ -289,7 +279,7 @@ public class SetNodeStateTest extends StateRestApiTest {
UnitResponse response = restAPI.getState(new StateRequest(path, 0));
Response.NodeResponse nodeResponse = (Response.NodeResponse) response;
UnitState unitState = nodeResponse.getStatePerType().get(type);
- assertNotNull("No such type " + type + " at path " + path, unitState);
+ assertNotNull(unitState, "No such type " + type + " at path " + path);
assertEquals(state.toString().toLowerCase(), unitState.getId());
assertEquals(reason, unitState.getReason());
}
@@ -326,19 +316,18 @@ public class SetNodeStateTest extends StateRestApiTest {
Matcher matcher = Pattern.compile(reasonRegex).matcher(setResponse.getReason());
String errorMessage = "Expected reason to match '" + reasonRegex + "', but got: " + setResponse.getReason() + "'";
- assertTrue(errorMessage, matcher.find());
+ assertTrue(matcher.find(), errorMessage);
int alreadyMaintainedIndex = Integer.parseInt(matcher.group(1));
// Example: Say index 1 is in maintenance, and we try to set 2 in maintenance. This should
// NOT be allowed, since 2 is in a different group than 1.
- assertEquals("Tried to set " + index + " in maintenance, but got: " + setResponse.getReason(),
- index % 2, (alreadyMaintainedIndex + 1) % 2);
+ assertEquals(index % 2, (alreadyMaintainedIndex + 1) % 2, "Tried to set " + index + " in maintenance, but got: " + setResponse.getReason());
assertThat(setResponse.getWasModified(), is(false));
}
@Test
- public void testSetWantedStateOnNodeNotInSlobrok() throws Exception {
+ void testSetWantedStateOnNodeNotInSlobrok() throws Exception {
// Node 2 in cluster music does not have a valid NodeInfo due to passing true to setUp
setUp(true);
restAPI.setUnitState(new SetUnitStateRequestImpl("music/distributor/2").setNewState("user", "down", "borked node"));
@@ -348,73 +337,73 @@ public class SetNodeStateTest extends StateRestApiTest {
}
@Test
- public void testWrongUnit() throws Exception {
+ void testWrongUnit() throws Exception {
setUp(true);
String wrongUnitMessage = "State can only be set at cluster or node level";
- try{
+ try {
restAPI.setUnitState(new SetUnitStateRequestImpl(
"").setNewState("user", "down", "testing"));
fail();
} catch (OperationNotSupportedForUnitException e) {
- assertTrue(e.getMessage(), e.getMessage().contains(wrongUnitMessage));
+ assertTrue(e.getMessage().contains(wrongUnitMessage), e.getMessage());
}
// ... setting at cluster-level is allowed
- try{
+ try {
restAPI.setUnitState(new SetUnitStateRequestImpl(
"music/distributor").setNewState("user", "down", "testing"));
fail();
} catch (OperationNotSupportedForUnitException e) {
- assertTrue(e.getMessage(), e.getMessage().contains(wrongUnitMessage));
+ assertTrue(e.getMessage().contains(wrongUnitMessage), e.getMessage());
}
// ... setting at node-level is allowed
- try{
+ try {
restAPI.setUnitState(new SetUnitStateRequestImpl(
"music/storage/1/0").setNewState("user", "down", "testing"));
fail();
} catch (OperationNotSupportedForUnitException e) {
- assertTrue(e.getMessage(), e.getMessage().contains(wrongUnitMessage));
+ assertTrue(e.getMessage().contains(wrongUnitMessage), e.getMessage());
}
}
@Test
- public void testInvalidUnit() throws Exception {
+ void testInvalidUnit() throws Exception {
setUp(true);
- try{
+ try {
restAPI.setUnitState(new SetUnitStateRequestImpl(
"foo").setNewState("user", "down", "testing"));
fail();
} catch (MissingUnitException e) {
}
- try{
+ try {
restAPI.setUnitState(new SetUnitStateRequestImpl(
"music/content").setNewState("user", "down", "testing"));
fail();
} catch (MissingUnitException e) {
}
- try{
+ try {
restAPI.setUnitState(new SetUnitStateRequestImpl(
"music/storage/bah").setNewState("user", "down", "testing"));
fail();
} catch (MissingUnitException e) {
}
- try{
+ try {
restAPI.setUnitState(new SetUnitStateRequestImpl(
"music/storage/10").setNewState("user", "down", "testing"));
fail();
} catch (MissingUnitException e) {
}
- try{
+ try {
restAPI.setUnitState(new SetUnitStateRequestImpl(
"music/storage/1/0/1").setNewState("user", "down", "testing"));
fail();
} catch (MissingUnitException e) {
}
- try{
+ try {
restAPI.setUnitState(new SetUnitStateRequestImpl(
"music/storage/1/bar").setNewState("user", "down", "testing"));
fail();
@@ -423,71 +412,71 @@ public class SetNodeStateTest extends StateRestApiTest {
}
@Test
- public void testSettingInvalidStateType() throws Exception {
+ void testSettingInvalidStateType() throws Exception {
setUp(true);
- try{
+ try {
restAPI.setUnitState(new SetUnitStateRequestImpl(
"music/distributor/1").setNewState("foo", "down", "testing"));
} catch (InvalidContentException e) {
- assertTrue(e.getMessage(), e.getMessage().contains("No new user state given"));
+ assertTrue(e.getMessage().contains("No new user state given"), e.getMessage());
}
}
@Test
- public void testSafeIsInvalidForSetNodesStatesForCluster() throws Exception {
+ void testSafeIsInvalidForSetNodesStatesForCluster() throws Exception {
setUp(true);
- try{
+ try {
restAPI.setUnitState(new SetUnitStateRequestImpl("music")
.setNewState("user", "maintenance", "example reason")
.setCondition(SetUnitStateRequest.Condition.SAFE));
} catch (InvalidContentException e) {
- assertTrue(e.getMessage(), e.getMessage().contains(
- "Setting all nodes in a cluster to a state is only supported with FORCE"));
+ assertTrue(e.getMessage().contains(
+ "Setting all nodes in a cluster to a state is only supported with FORCE"), e.getMessage());
}
}
@Test
- public void testSettingWrongStateType() throws Exception {
+ void testSettingWrongStateType() throws Exception {
setUp(true);
- try{
+ try {
restAPI.setUnitState(new SetUnitStateRequestImpl(
"music/distributor/1").setNewState("generated", "down", "testing"));
} catch (InvalidContentException e) {
- assertTrue(e.getMessage(), e.getMessage().contains("No new user state given"));
+ assertTrue(e.getMessage().contains("No new user state given"), e.getMessage());
}
- try{
+ try {
restAPI.setUnitState(new SetUnitStateRequestImpl(
"music/distributor/1").setNewState("unit", "down", "testing"));
} catch (InvalidContentException e) {
- assertTrue(e.getMessage(), e.getMessage().contains("No new user state given"));
+ assertTrue(e.getMessage().contains("No new user state given"), e.getMessage());
}
}
@Test
- public void testInvalidState() throws Exception {
+ void testInvalidState() throws Exception {
setUp(true);
- try{
+ try {
restAPI.setUnitState(new SetUnitStateRequestImpl(
"music/distributor/1").setNewState("user", "initializing", "testing"));
} catch (InvalidContentException e) {
- assertTrue(e.getMessage(), e.getMessage().contains("Invalid user state"));
+ assertTrue(e.getMessage().contains("Invalid user state"), e.getMessage());
}
- try{
+ try {
restAPI.setUnitState(new SetUnitStateRequestImpl(
"music/distributor/1").setNewState("user", "stopping", "testing"));
} catch (InvalidContentException e) {
- assertTrue(e.getMessage(), e.getMessage().contains("Invalid user state"));
+ assertTrue(e.getMessage().contains("Invalid user state"), e.getMessage());
}
- try{
+ try {
restAPI.setUnitState(new SetUnitStateRequestImpl(
"music/distributor/1").setNewState("user", "foo", "testing"));
} catch (InvalidContentException e) {
- assertTrue(e.getMessage(), e.getMessage().contains("Invalid user state"));
+ assertTrue(e.getMessage().contains("Invalid user state"), e.getMessage());
}
}
@Test
- public void testOverwriteReason() throws Exception {
+ void testOverwriteReason() throws Exception {
setUp(true);
restAPI.setUnitState(new SetUnitStateRequestImpl(
"music/distributor/1").setNewState("user", "down", "testing"));
@@ -508,19 +497,19 @@ public class SetNodeStateTest extends StateRestApiTest {
}
@Test
- public void set_node_state_requests_are_by_default_tagged_as_having_version_ack_dependency() {
+ void set_node_state_requests_are_by_default_tagged_as_having_version_ack_dependency() {
SetNodeStateRequest request = createDummySetNodeStateRequest();
assertTrue(request.hasVersionAckDependency());
}
@Test
- public void set_node_state_requests_not_initially_marked_as_failed() {
+ void set_node_state_requests_not_initially_marked_as_failed() {
SetNodeStateRequest request = createDummySetNodeStateRequest();
assertFalse(request.isFailed());
}
@Test
- public void set_node_state_requests_may_override_version_ack_dependency() {
+ void set_node_state_requests_may_override_version_ack_dependency() {
SetNodeStateRequest request = new SetNodeStateRequest(createDummyId(), new SetUnitStateRequestImpl("music/storage/1")
.setNewState("user", "maintenance", "whatever reason.")
.setResponseWait(SetUnitStateRequest.ResponseWait.NO_WAIT));
@@ -531,40 +520,42 @@ public class SetNodeStateTest extends StateRestApiTest {
// important to test (and expected to happen) for requests that have dependencies on cluster
// state version publishing.
@Test
- public void leadership_loss_fails_set_node_state_request() throws Exception {
- expectedException.expectMessage("Leadership lost before request could complete");
- expectedException.expect(UnknownMasterException.class);
+ void leadership_loss_fails_set_node_state_request() throws Exception {
+ Throwable exception = assertThrows(UnknownMasterException.class, () -> {
- SetNodeStateRequest request = createDummySetNodeStateRequest();
- request.handleFailure(RemoteClusterControllerTask.Failure.of(RemoteClusterControllerTask.FailureCondition.LEADERSHIP_LOST));
- request.getResult();
+ SetNodeStateRequest request = createDummySetNodeStateRequest();
+ request.handleFailure(RemoteClusterControllerTask.Failure.of(RemoteClusterControllerTask.FailureCondition.LEADERSHIP_LOST));
+ request.getResult();
+ });
+ assertTrue(exception.getMessage().contains("Leadership lost before request could complete"));
}
@Test
- public void leadership_loss_marks_request_as_failed_for_early_out_response() {
+ void leadership_loss_marks_request_as_failed_for_early_out_response() {
SetNodeStateRequest request = createDummySetNodeStateRequest();
request.handleFailure(RemoteClusterControllerTask.Failure.of(RemoteClusterControllerTask.FailureCondition.LEADERSHIP_LOST));
assertTrue(request.isFailed());
}
@Test
- public void deadline_exceeded_fails_set_node_state_request() throws Exception {
- expectedException.expectMessage("Task exceeded its version wait deadline: gremlins in the computer");
- expectedException.expect(DeadlineExceededException.class);
+ void deadline_exceeded_fails_set_node_state_request() throws Exception {
+ Throwable exception = assertThrows(DeadlineExceededException.class, () -> {
- SetNodeStateRequest request = createDummySetNodeStateRequest();
- request.handleFailure(RemoteClusterControllerTask.Failure.of(
- RemoteClusterControllerTask.FailureCondition.DEADLINE_EXCEEDED, "gremlins in the computer"));
- request.getResult();
+ SetNodeStateRequest request = createDummySetNodeStateRequest();
+ request.handleFailure(RemoteClusterControllerTask.Failure.of(
+ RemoteClusterControllerTask.FailureCondition.DEADLINE_EXCEEDED, "gremlins in the computer"));
+ request.getResult();
+ });
+ assertTrue(exception.getMessage().contains("Task exceeded its version wait deadline: gremlins in the computer"));
}
@Test
- public void no_fail_if_modified() throws StateRestApiException {
+ void no_fail_if_modified() throws StateRestApiException {
assertFalse(isFailed(true));
}
@Test
- public void fail_if_not_modified() throws StateRestApiException {
+ void fail_if_not_modified() throws StateRestApiException {
assertTrue(isFailed(false));
}
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/requests/SetNodeStateRequestTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/requests/SetNodeStateRequestTest.java
index 9f14b2e71d2..1bd17b11755 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/requests/SetNodeStateRequestTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/restapiv2/requests/SetNodeStateRequestTest.java
@@ -15,8 +15,8 @@ import com.yahoo.vespa.clustercontroller.utils.staterestapi.errors.StateRestApiE
import com.yahoo.vespa.clustercontroller.utils.staterestapi.requests.SetUnitStateRequest;
import com.yahoo.vespa.clustercontroller.utils.staterestapi.response.SetResponse;
import com.yahoo.vespa.clustercontroller.utils.staterestapi.response.UnitState;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
@@ -43,13 +43,13 @@ public class SetNodeStateRequestTest {
private boolean inMasterMoratorium = false;
private boolean probe = false;
- @Before
+ @BeforeEach
public void setUp() {
newStates.put("user", unitState);
}
@Test
- public void testUpToMaintenance() throws StateRestApiException {
+ void testUpToMaintenance() throws StateRestApiException {
testSetStateRequest(
"maintenance",
State.UP, State.UP,
@@ -58,7 +58,7 @@ public class SetNodeStateRequestTest {
}
@Test
- public void testProbingDoesntChangeState() throws StateRestApiException {
+ void testProbingDoesntChangeState() throws StateRestApiException {
probe = true;
testSetStateRequest(
"maintenance",
@@ -68,7 +68,7 @@ public class SetNodeStateRequestTest {
}
@Test
- public void testUpToDown() throws StateRestApiException {
+ void testUpToDown() throws StateRestApiException {
testSetStateRequest(
"down",
State.UP, State.UP,
@@ -77,7 +77,7 @@ public class SetNodeStateRequestTest {
}
@Test
- public void testMaintenanceToUp() throws StateRestApiException {
+ void testMaintenanceToUp() throws StateRestApiException {
testSetStateRequest(
"up",
State.MAINTENANCE, State.DOWN,
@@ -86,7 +86,7 @@ public class SetNodeStateRequestTest {
}
@Test
- public void testDownToUp() throws StateRestApiException {
+ void testDownToUp() throws StateRestApiException {
testSetStateRequest(
"up",
State.DOWN, State.DOWN,
@@ -95,7 +95,7 @@ public class SetNodeStateRequestTest {
}
@Test
- public void testOnlyStorageInMaintenaceToMaintenance() throws StateRestApiException {
+ void testOnlyStorageInMaintenaceToMaintenance() throws StateRestApiException {
testSetStateRequest(
"maintenance",
State.MAINTENANCE, State.UP,
@@ -104,7 +104,7 @@ public class SetNodeStateRequestTest {
}
@Test
- public void testNoOpMaintenaceToMaintenance() throws StateRestApiException {
+ void testNoOpMaintenaceToMaintenance() throws StateRestApiException {
testSetStateRequest(
"maintenance",
State.MAINTENANCE, State.DOWN,
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/rpc/RPCCommunicatorTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/rpc/RPCCommunicatorTest.java
index ca9e81b6bc4..809979620c2 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/rpc/RPCCommunicatorTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/rpc/RPCCommunicatorTest.java
@@ -21,7 +21,7 @@ import com.yahoo.vespa.clustercontroller.core.FleetControllerOptions;
import com.yahoo.vespa.clustercontroller.core.NodeInfo;
import com.yahoo.vespa.clustercontroller.core.SetClusterStateRequest;
import com.yahoo.vespa.clustercontroller.core.Timer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.util.HashSet;
@@ -33,7 +33,7 @@ import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.not;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyDouble;
import static org.mockito.ArgumentMatchers.eq;
@@ -51,7 +51,7 @@ public class RPCCommunicatorTest {
private static final int ROUNDTRIP_LATENCY_SECONDS = 2000;
@Test
- public void testGenerateNodeStateRequestTimeoutMs() {
+ void testGenerateNodeStateRequestTimeoutMs() {
final RPCCommunicator communicator = new RPCCommunicator(
RPCCommunicator.createRealSupervisor(),
null /* Timer */,
@@ -74,11 +74,11 @@ public class RPCCommunicatorTest {
assertThat(min, is(not(max)));
assertTrue(min >= NODE_STATE_REQUEST_TIMEOUT_INTERVAL_START_PERCENTAGE *
NODE_STATE_REQUEST_TIMEOUT_INTERVAL_MAX_MS / 100);
- assertTrue(uniqueTimeoutValues.size()> TEST_ITERATIONS/2);
+ assertTrue(uniqueTimeoutValues.size() > TEST_ITERATIONS / 2);
}
@Test
- public void testGenerateNodeStateRequestTimeoutMsWithUpdates() {
+ void testGenerateNodeStateRequestTimeoutMsWithUpdates() {
final RPCCommunicator communicator = new RPCCommunicator(RPCCommunicator.createRealSupervisor(), null /* Timer */, INDEX, 1, 1, 100, 0);
FleetControllerOptions fleetControllerOptions = new FleetControllerOptions(null /*clustername*/, Set.of(new ConfiguredNode(0, false)));
fleetControllerOptions.nodeStateRequestTimeoutEarliestPercentage = 100;
@@ -90,7 +90,7 @@ public class RPCCommunicatorTest {
}
@Test
- public void testRoundtripLatency() {
+ void testRoundtripLatency() {
final Timer timer = new FakeTimer();
final RPCCommunicator communicator = new RPCCommunicator(
RPCCommunicator.createRealSupervisor(),
@@ -111,7 +111,7 @@ public class RPCCommunicatorTest {
communicator.getNodeState(nodeInfo, null);
Mockito.verify(target).invokeAsync(
any(),
- eq(ROUNDTRIP_LATENCY_SECONDS + NODE_STATE_REQUEST_TIMEOUT_INTERVAL_MAX_MS/1000.0),
+ eq(ROUNDTRIP_LATENCY_SECONDS + NODE_STATE_REQUEST_TIMEOUT_INTERVAL_MAX_MS / 1000.0),
any());
}
@@ -146,7 +146,7 @@ public class RPCCommunicatorTest {
}
@Test
- public void setSystemState_v3_sends_distribution_states_rpc() {
+ void setSystemState_v3_sends_distribution_states_rpc() {
var f = new Fixture<SetClusterStateRequest>();
var cf = ClusterFixture.forFlatCluster(3).bringEntireClusterUp().assignDummyRpcAddresses();
var sentBundle = ClusterStateBundleUtil.makeBundle("distributor:3 storage:3");
@@ -162,7 +162,7 @@ public class RPCCommunicatorTest {
}
@Test
- public void set_distribution_states_v3_rpc_auto_downgrades_to_v2_on_unknown_method_error() {
+ void set_distribution_states_v3_rpc_auto_downgrades_to_v2_on_unknown_method_error() {
var f = new Fixture<SetClusterStateRequest>();
var cf = ClusterFixture.forFlatCluster(3).bringEntireClusterUp().assignDummyRpcAddresses();
var sentBundle = ClusterStateBundleUtil.makeBundle("version:123 distributor:3 storage:3");
@@ -188,7 +188,7 @@ public class RPCCommunicatorTest {
}
@Test
- public void activateClusterStateVersion_sends_version_activation_rpc() {
+ void activateClusterStateVersion_sends_version_activation_rpc() {
var f = new Fixture<ActivateClusterStateVersionRequest>();
var cf = ClusterFixture.forFlatCluster(3).bringEntireClusterUp().assignDummyRpcAddresses();
f.communicator.activateClusterStateVersion(12345, cf.cluster().getNodeInfo(Node.ofDistributor(1)), f.mockWaiter);
diff --git a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/rpc/SlimeClusterStateBundleCodecTest.java b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/rpc/SlimeClusterStateBundleCodecTest.java
index 3d3347acb2d..7564fb40d46 100644
--- a/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/rpc/SlimeClusterStateBundleCodecTest.java
+++ b/clustercontroller-core/src/test/java/com/yahoo/vespa/clustercontroller/core/rpc/SlimeClusterStateBundleCodecTest.java
@@ -4,7 +4,7 @@ package com.yahoo.vespa.clustercontroller.core.rpc;
import com.yahoo.vespa.clustercontroller.core.ClusterStateBundle;
import com.yahoo.vespa.clustercontroller.core.ClusterStateBundleUtil;
import com.yahoo.vespa.clustercontroller.core.StateMapping;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.Matchers.lessThan;
@@ -25,13 +25,13 @@ public class SlimeClusterStateBundleCodecTest {
}
@Test
- public void baseline_only_bundle_can_be_round_trip_encoded() {
+ void baseline_only_bundle_can_be_round_trip_encoded() {
ClusterStateBundle stateBundle = ClusterStateBundleUtil.makeBundle("distributor:2 storage:2");
assertThat(roundtripEncode(stateBundle), equalTo(stateBundle));
}
@Test
- public void multi_space_state_bundle_can_be_round_trip_encoded() {
+ void multi_space_state_bundle_can_be_round_trip_encoded() {
ClusterStateBundle stateBundle = ClusterStateBundleUtil.makeBundle("distributor:2 storage:2",
StateMapping.of("default", "distributor:2 storage:2 .0.s:d"),
StateMapping.of("upsidedown", "distributor:2 .0.s:d storage:2"));
@@ -49,7 +49,7 @@ public class SlimeClusterStateBundleCodecTest {
}
@Test
- public void encoded_cluster_states_can_be_compressed() {
+ void encoded_cluster_states_can_be_compressed() {
ClusterStateBundle stateBundle = makeCompressableBundle();
SlimeClusterStateBundleCodec codec = new SlimeClusterStateBundleCodec();
@@ -60,20 +60,20 @@ public class SlimeClusterStateBundleCodecTest {
}
@Test
- public void uncompressed_enveloped_bundle_can_be_roundtrip_encoded() {
+ void uncompressed_enveloped_bundle_can_be_roundtrip_encoded() {
// Insufficient length and too much entropy to be compressed
ClusterStateBundle stateBundle = ClusterStateBundleUtil.makeBundle("distributor:2 storage:3");
assertThat(roundtripEncodeWithEnvelope(stateBundle), equalTo(stateBundle));
}
@Test
- public void compressable_enveloped_bundle_can_be_roundtrip_encoded() {
+ void compressable_enveloped_bundle_can_be_roundtrip_encoded() {
ClusterStateBundle stateBundle = makeCompressableBundle();
assertThat(roundtripEncodeWithEnvelope(stateBundle), equalTo(stateBundle));
}
@Test
- public void can_roundtrip_encode_bundle_with_deferred_activation_enabled() {
+ void can_roundtrip_encode_bundle_with_deferred_activation_enabled() {
var stateBundle = ClusterStateBundleUtil.makeBundleBuilder("distributor:2 storage:2")
.deferredActivation(true)
.deriveAndBuild();
@@ -81,7 +81,7 @@ public class SlimeClusterStateBundleCodecTest {
}
@Test
- public void can_roundtrip_encode_bundle_with_deferred_activation_disabled() {
+ void can_roundtrip_encode_bundle_with_deferred_activation_disabled() {
var stateBundle = ClusterStateBundleUtil.makeBundleBuilder("distributor:2 storage:2")
.deferredActivation(false)
.deriveAndBuild();
@@ -89,7 +89,7 @@ public class SlimeClusterStateBundleCodecTest {
}
@Test
- public void can_roundtrip_encode_bundle_with_feed_block_state() {
+ void can_roundtrip_encode_bundle_with_feed_block_state() {
var stateBundle = ClusterStateBundleUtil.makeBundleBuilder("distributor:2 storage:2")
.feedBlock(ClusterStateBundle.FeedBlock.blockedWithDescription("more cake needed"))
.deriveAndBuild();
diff --git a/clustercontroller-reindexer/pom.xml b/clustercontroller-reindexer/pom.xml
index 42e746c1bae..c94b5b134fe 100644
--- a/clustercontroller-reindexer/pom.xml
+++ b/clustercontroller-reindexer/pom.xml
@@ -51,6 +51,20 @@
<artifactId>testutil</artifactId>
<version>${project.version}</version>
<scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-core</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-library</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>com.yahoo.vespa</groupId>
diff --git a/clustercontroller-reindexer/src/test/java/ai/vespa/reindexing/http/ReindexingV1ApiTest.java b/clustercontroller-reindexer/src/test/java/ai/vespa/reindexing/http/ReindexingV1ApiTest.java
index 2e3f4942b7d..b4aad7bc3ca 100644
--- a/clustercontroller-reindexer/src/test/java/ai/vespa/reindexing/http/ReindexingV1ApiTest.java
+++ b/clustercontroller-reindexer/src/test/java/ai/vespa/reindexing/http/ReindexingV1ApiTest.java
@@ -19,7 +19,7 @@ import java.util.List;
import java.util.concurrent.Executors;
import static com.yahoo.jdisc.http.HttpRequest.Method.POST;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author jonmv
diff --git a/clustercontroller-utils/pom.xml b/clustercontroller-utils/pom.xml
index a1f0b1c21c2..0d8e30d3693 100644
--- a/clustercontroller-utils/pom.xml
+++ b/clustercontroller-utils/pom.xml
@@ -14,11 +14,6 @@
<packaging>container-plugin</packaging>
<dependencies>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>org.codehaus.jettison</groupId>
<artifactId>jettison</artifactId>
</dependency>
@@ -35,6 +30,16 @@
<scope>provided</scope>
</dependency>
<dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<scope>provided</scope>
diff --git a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/async/AsyncTest.java b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/async/AsyncTest.java
index 7cea1adced6..739b8d4bf15 100644
--- a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/async/AsyncTest.java
+++ b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/async/AsyncTest.java
@@ -1,19 +1,20 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.clustercontroller.utils.communication.async;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.LinkedList;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
public class AsyncTest {
@Test
- public void testListeners() {
+ void testListeners() {
AsyncOperationImpl<String> op = new AsyncOperationImpl<>("test");
class Listener implements AsyncCallback<String> {
boolean called = false;
+
@Override
public void done(AsyncOperation<String> op) {
called = true;
@@ -40,7 +41,7 @@ public class AsyncTest {
}
@Test
- public void testMultipleResultSetters() {
+ void testMultipleResultSetters() {
{
AsyncOperationImpl<String> op = new AsyncOperationImpl<>("test");
op.setResult("foo");
@@ -65,7 +66,7 @@ public class AsyncTest {
}
@Test
- public void testPartialResultOnFailure() {
+ void testPartialResultOnFailure() {
AsyncOperationImpl<String> op = new AsyncOperationImpl<>("test");
op.setFailure(new Exception("bar"), "foo");
assertEquals("foo", op.getResult());
@@ -74,14 +75,16 @@ public class AsyncTest {
}
@Test
- public void testListenImpl() {
+ void testListenImpl() {
class ListenImpl extends AsyncOperationListenImpl<String> {
public ListenImpl(AsyncOperation<String> op) {
super(op);
}
- };
+ }
+ ;
class Listener implements AsyncCallback<String> {
int calls = 0;
+
@Override
public void done(AsyncOperation<String> op) {
++calls;
@@ -98,7 +101,7 @@ public class AsyncTest {
}
@Test
- public void testRedirectedOperation() {
+ void testRedirectedOperation() {
{
final AsyncOperationImpl<String> op = new AsyncOperationImpl<>("test", "desc");
AsyncOperation<Integer> deleteRequest = new RedirectedAsyncOperation<String, Integer>(op) {
@@ -147,7 +150,7 @@ public class AsyncTest {
}
@Test
- public void testRedirectOnSuccessOperation() {
+ void testRedirectOnSuccessOperation() {
{
final AsyncOperationImpl<Integer> target = new AsyncOperationImpl<>("foo");
SuccessfulAsyncCallback<String, Integer> callback = new SuccessfulAsyncCallback<String, Integer>(target) {
@@ -243,17 +246,17 @@ public class AsyncTest {
}
@Test
- public void testStressCompletionAndRegisterToDetectRace() throws Exception {
+ void testStressCompletionAndRegisterToDetectRace() throws Exception {
int iterations = 1000;
Object monitor = new Object();
Completer completer = new Completer(monitor);
Listener listener = new Listener(monitor);
Thread t1 = new Thread(completer);
Thread t2 = new Thread(listener);
- try{
+ try {
t1.start();
t2.start();
- for (int i=0; i<iterations; ++i) {
+ for (int i = 0; i < iterations; ++i) {
AsyncOperationImpl<String> op = new AsyncOperationImpl<>("test");
synchronized (monitor) {
completer.op = op;
@@ -261,7 +264,10 @@ public class AsyncTest {
monitor.notifyAll();
}
while (completer.op != null || listener.op != null) {
- try{ Thread.sleep(0); } catch (InterruptedException e) {}
+ try {
+ Thread.sleep(0);
+ } catch (InterruptedException e) {
+ }
}
}
} finally {
diff --git a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/http/HttpRequestTest.java b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/http/HttpRequestTest.java
index 2583c3392c4..41328494f52 100644
--- a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/http/HttpRequestTest.java
+++ b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/http/HttpRequestTest.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.clustercontroller.utils.communication.http;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
public class HttpRequestTest {
@@ -21,7 +19,7 @@ public class HttpRequestTest {
}
@Test
- public void testEquality() {
+ void testEquality() {
assertEquals(createRequest(), createRequest());
assertNotSame(createRequest(), createRequest().setHost("localhost"));
assertNotSame(createRequest(), createRequest().setPort(40));
@@ -31,16 +29,16 @@ public class HttpRequestTest {
}
@Test
- public void testVerifyComplete() {
+ void testVerifyComplete() {
// To be a complete request, an HTTP request must include:
// - A path
// - The HTTP operation type
- try{
+ try {
new HttpRequest().setPath("/foo").verifyComplete();
assertTrue(false);
} catch (IllegalStateException e) {
}
- try{
+ try {
new HttpRequest().setHttpOperation(HttpRequest.HttpOp.GET).verifyComplete();
assertTrue(false);
} catch (IllegalStateException e) {
@@ -49,7 +47,7 @@ public class HttpRequestTest {
}
@Test
- public void testMerge() {
+ void testMerge() {
{
HttpRequest base = new HttpRequest()
.setHttpOperation(HttpRequest.HttpOp.POST)
@@ -92,25 +90,25 @@ public class HttpRequestTest {
}
@Test
- public void testNonExistingHeader() {
+ void testNonExistingHeader() {
assertEquals("foo", new HttpRequest().getHeader("asd", "foo"));
assertEquals("foo", new HttpRequest().addHttpHeader("bar", "foo").getHeader("asd", "foo"));
}
@Test
- public void testOption() {
+ void testOption() {
assertEquals("bar", new HttpRequest().addUrlOption("foo", "bar").getOption("foo", "foo"));
assertEquals("foo", new HttpRequest().getOption("asd", "foo"));
}
@Test
- public void testToString() {
+ void testToString() {
assertEquals("GET? http://localhost:8080/",
- new HttpRequest()
- .setScheme("http")
- .setHost("localhost")
- .setPort(8080)
- .toString(true));
+ new HttpRequest()
+ .setScheme("http")
+ .setHost("localhost")
+ .setPort(8080)
+ .toString(true));
assertEquals("POST http://localhost/",
new HttpRequest()
.setScheme("http")
@@ -127,7 +125,7 @@ public class HttpRequestTest {
}
@Test
- public void testNothingButGetCoverage() {
+ void testNothingButGetCoverage() {
assertEquals(false, new HttpRequest().equals(new Object()));
new HttpRequest().getHeaders();
new HttpRequest().setUrlOptions(new HttpRequest().getUrlOptions());
diff --git a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/http/HttpResultTest.java b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/http/HttpResultTest.java
index 59fd4521efb..3a08d735a4e 100644
--- a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/http/HttpResultTest.java
+++ b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/http/HttpResultTest.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.clustercontroller.utils.communication.http;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class HttpResultTest {
@Test
- public void testSuccess() {
+ void testSuccess() {
assertEquals(false, new HttpResult().setHttpCode(199, "foo").isSuccess());
assertEquals(true, new HttpResult().setHttpCode(200, "foo").isSuccess());
assertEquals(true, new HttpResult().setHttpCode(299, "foo").isSuccess());
@@ -16,7 +16,7 @@ public class HttpResultTest {
}
@Test
- public void testToString() {
+ void testToString() {
assertEquals("HTTP 200/OK", new HttpResult().setContent("Foo").toString());
assertEquals("HTTP 200/OK\n\nFoo", new HttpResult().setContent("Foo").toString(true));
assertEquals("HTTP 200/OK", new HttpResult().toString(true));
@@ -24,7 +24,7 @@ public class HttpResultTest {
}
@Test
- public void testNothingButGetCoverage() {
+ void testNothingButGetCoverage() {
new HttpResult().getHeaders();
}
diff --git a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/http/JsonHttpResultTest.java b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/http/JsonHttpResultTest.java
index 2e8f9ea9b58..19fc27669af 100644
--- a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/http/JsonHttpResultTest.java
+++ b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/http/JsonHttpResultTest.java
@@ -3,31 +3,31 @@ package com.yahoo.vespa.clustercontroller.utils.communication.http;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class JsonHttpResultTest {
@Test
- public void testCopyConstructor() {
+ void testCopyConstructor() {
assertEquals("{}", new JsonHttpResult(new HttpResult()).getJson().toString());
}
@Test
- public void testOutput() {
+ void testOutput() {
assertEquals("HTTP 200/OK\n"
- + "\n"
- + "JSON: {\"foo\": 3}",
- new JsonHttpResult(new HttpResult().setContent("{ \"foo\" : 3 }")).toString(true));
+ + "\n"
+ + "JSON: {\"foo\": 3}",
+ new JsonHttpResult(new HttpResult().setContent("{ \"foo\" : 3 }")).toString(true));
assertEquals("HTTP 200/OK\n"
- + "\n"
- + "{ \"foo\" : }",
+ + "\n"
+ + "{ \"foo\" : }",
new JsonHttpResult(new HttpResult().setContent("{ \"foo\" : }")).toString(true));
}
@Test
- public void testNonJsonOutput() {
+ void testNonJsonOutput() {
JsonHttpResult result = new JsonHttpResult();
result.setContent("Foo");
StringBuilder sb = new StringBuilder();
@@ -36,7 +36,7 @@ public class JsonHttpResultTest {
}
@Test
- public void testInvalidJsonOutput() {
+ void testInvalidJsonOutput() {
JsonHttpResult result = new JsonHttpResult();
result.setJson(new JSONObject() {
@Override
diff --git a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/http/writer/HttpWriterTest.java b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/http/writer/HttpWriterTest.java
index 2c9d9296aae..52b632c6eb8 100644
--- a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/http/writer/HttpWriterTest.java
+++ b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/communication/http/writer/HttpWriterTest.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.clustercontroller.utils.communication.http.writer;
-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;
public class HttpWriterTest {
@@ -19,34 +19,34 @@ public class HttpWriterTest {
+ "</html>\n";
@Test
- public void testStructure() {
+ void testStructure() {
HttpWriter writer = new HttpWriter();
String header = defaultHeader.replace(defaultTitle, "Untitled page");
assertEquals(header + defaultFooter, writer.toString());
}
@Test
- public void testTitle() {
+ void testTitle() {
HttpWriter writer = new HttpWriter().addTitle(defaultTitle);
assertEquals(defaultHeader + defaultFooter, writer.toString());
}
@Test
- public void testParagraph() {
+ void testParagraph() {
String paragraph = "This is a paragraph";
String paragraph2 = "More text";
HttpWriter writer = new HttpWriter().addTitle(defaultTitle).write(paragraph).write(paragraph2);
String content = " <p>\n"
- + " " + paragraph + "\n"
- + " </p>\n"
- + " <p>\n"
- + " " + paragraph2 + "\n"
- + " </p>\n";
+ + " " + paragraph + "\n"
+ + " </p>\n"
+ + " <p>\n"
+ + " " + paragraph2 + "\n"
+ + " </p>\n";
assertEquals(defaultHeader + content + defaultFooter, writer.toString());
}
@Test
- public void testLink() {
+ void testLink() {
String name = "My link";
String link = "/foo/bar?hmm";
HttpWriter writer = new HttpWriter().addTitle(defaultTitle).writeLink(name, link);
@@ -55,15 +55,15 @@ public class HttpWriterTest {
}
@Test
- public void testErrors() {
- try{
+ void testErrors() {
+ try {
HttpWriter writer = new HttpWriter().addTitle(defaultTitle);
writer.toString();
writer.write("foo");
assertTrue(false);
} catch (IllegalStateException e) {
}
- try{
+ try {
new HttpWriter().write("foo").addTitle("bar");
assertTrue(false);
} catch (IllegalStateException e) {
diff --git a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/staterestapi/StateRestAPITest.java b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/staterestapi/StateRestAPITest.java
index 0f6e9e235dc..d0378dd9065 100644
--- a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/staterestapi/StateRestAPITest.java
+++ b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/staterestapi/StateRestAPITest.java
@@ -9,12 +9,11 @@ import com.yahoo.vespa.clustercontroller.utils.staterestapi.errors.*;
import com.yahoo.vespa.clustercontroller.utils.staterestapi.server.RestApiHandler;
import com.yahoo.vespa.clustercontroller.utils.test.TestTransport;
import org.codehaus.jettison.json.JSONObject;
-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.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
public class StateRestAPITest {
@@ -60,96 +59,96 @@ public class StateRestAPITest {
AsyncOperation<HttpResult> op = testTransport.getClient().execute(request);
AsyncUtils.waitFor(op);
if (!op.isSuccess()) { // Don't call getCause() unless it fails
- assertTrue(op.getCause().toString(), op.isSuccess());
+ assertTrue(op.isSuccess(), op.getCause().toString());
}
assertTrue(op.getResult() != null);
return op.getResult();
}
private JSONObject executeOkJsonRequest(HttpRequest request) {
HttpResult result = execute(request);
- assertEquals(result.toString(true), 200, result.getHttpReturnCode());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
+ assertEquals(200, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
return (JSONObject) result.getContent();
}
@Test
- public void testTopLevelList() throws Exception {
+ void testTopLevelList() throws Exception {
setupDummyStateApi();
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2"));
- assertEquals(result.toString(true), 200, result.getHttpReturnCode());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
+ assertEquals(200, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
String expected = "{\"cluster\": {\n"
- + " \"foo\": {\"link\": \"\\/cluster\\/v2\\/foo\"},\n"
- + " \"bar\": {\"link\": \"\\/cluster\\/v2\\/bar\"}\n"
- + "}}";
+ + " \"foo\": {\"link\": \"\\/cluster\\/v2\\/foo\"},\n"
+ + " \"bar\": {\"link\": \"\\/cluster\\/v2\\/bar\"}\n"
+ + "}}";
assertEquals(expected, ((JSONObject) result.getContent()).toString(2));
}
@Test
- public void testClusterState() throws Exception {
+ void testClusterState() throws Exception {
setupDummyStateApi();
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2/foo"));
- assertEquals(result.toString(true), 200, result.getHttpReturnCode());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
+ assertEquals(200, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
String expected = "{\"node\": {\n"
- + " \"1\": {\"link\": \"\\/cluster\\/v2\\/foo\\/1\"},\n"
- + " \"3\": {\"link\": \"\\/cluster\\/v2\\/foo\\/3\"}\n"
- + "}}";
+ + " \"1\": {\"link\": \"\\/cluster\\/v2\\/foo\\/1\"},\n"
+ + " \"3\": {\"link\": \"\\/cluster\\/v2\\/foo\\/3\"}\n"
+ + "}}";
assertEquals(expected, ((JSONObject) result.getContent()).toString(2));
}
@Test
- public void testNodeState() throws Exception {
+ void testNodeState() throws Exception {
setupDummyStateApi();
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2/foo/3"));
- assertEquals(result.toString(true), 200, result.getHttpReturnCode());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
+ assertEquals(200, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
String expected = "{\n"
- + " \"attributes\": {\"group\": \"mygroup\"},\n"
- + " \"state\": {\"current\": {\n"
- + " \"state\": \"up\",\n"
- + " \"reason\": \"\"\n"
- + " }},\n"
- + " \"metrics\": {\"doc-count\": 8}\n"
- + "}";
+ + " \"attributes\": {\"group\": \"mygroup\"},\n"
+ + " \"state\": {\"current\": {\n"
+ + " \"state\": \"up\",\n"
+ + " \"reason\": \"\"\n"
+ + " }},\n"
+ + " \"metrics\": {\"doc-count\": 8}\n"
+ + "}";
assertEquals(expected, ((JSONObject) result.getContent()).toString(2));
}
@Test
- public void testRecursiveMode() throws Exception {
+ void testRecursiveMode() throws Exception {
setupDummyStateApi();
{
JSONObject json = executeOkJsonRequest(
new HttpRequest().setPath("/cluster/v2").addUrlOption("recursive", "true"));
String expected =
"{\"cluster\": {\n" +
- " \"foo\": {\"node\": {\n" +
- " \"1\": {\n" +
- " \"attributes\": {\"group\": \"mygroup\"},\n" +
- " \"state\": {\"current\": {\n" +
- " \"state\": \"initializing\",\n" +
- " \"reason\": \"\"\n" +
- " }},\n" +
- " \"metrics\": {\"doc-count\": 5}\n" +
- " },\n" +
- " \"3\": {\n" +
- " \"attributes\": {\"group\": \"mygroup\"},\n" +
- " \"state\": {\"current\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " }},\n" +
- " \"metrics\": {\"doc-count\": 8}\n" +
- " }\n" +
- " }},\n" +
- " \"bar\": {\"node\": {\"2\": {\n" +
- " \"attributes\": {\"group\": \"mygroup\"},\n" +
- " \"state\": {\"current\": {\n" +
- " \"state\": \"down\",\n" +
- " \"reason\": \"\"\n" +
- " }},\n" +
- " \"metrics\": {\"doc-count\": 0}\n" +
- " }}}\n" +
- "}}";
+ " \"foo\": {\"node\": {\n" +
+ " \"1\": {\n" +
+ " \"attributes\": {\"group\": \"mygroup\"},\n" +
+ " \"state\": {\"current\": {\n" +
+ " \"state\": \"initializing\",\n" +
+ " \"reason\": \"\"\n" +
+ " }},\n" +
+ " \"metrics\": {\"doc-count\": 5}\n" +
+ " },\n" +
+ " \"3\": {\n" +
+ " \"attributes\": {\"group\": \"mygroup\"},\n" +
+ " \"state\": {\"current\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " }},\n" +
+ " \"metrics\": {\"doc-count\": 8}\n" +
+ " }\n" +
+ " }},\n" +
+ " \"bar\": {\"node\": {\"2\": {\n" +
+ " \"attributes\": {\"group\": \"mygroup\"},\n" +
+ " \"state\": {\"current\": {\n" +
+ " \"state\": \"down\",\n" +
+ " \"reason\": \"\"\n" +
+ " }},\n" +
+ " \"metrics\": {\"doc-count\": 0}\n" +
+ " }}}\n" +
+ "}}";
assertEquals(expected, json.toString(2));
}
{
@@ -157,17 +156,17 @@ public class StateRestAPITest {
new HttpRequest().setPath("/cluster/v2").addUrlOption("recursive", "1"));
String expected =
"{\"cluster\": {\n" +
- " \"foo\": {\"node\": {\n" +
- " \"1\": {\"link\": \"\\/cluster\\/v2\\/foo\\/1\"},\n" +
- " \"3\": {\"link\": \"\\/cluster\\/v2\\/foo\\/3\"}\n" +
- " }},\n" +
- " \"bar\": {\"node\": {\"2\": {\"link\": \"\\/cluster\\/v2\\/bar\\/2\"}}}\n" +
- "}}";
+ " \"foo\": {\"node\": {\n" +
+ " \"1\": {\"link\": \"\\/cluster\\/v2\\/foo\\/1\"},\n" +
+ " \"3\": {\"link\": \"\\/cluster\\/v2\\/foo\\/3\"}\n" +
+ " }},\n" +
+ " \"bar\": {\"node\": {\"2\": {\"link\": \"\\/cluster\\/v2\\/bar\\/2\"}}}\n" +
+ "}}";
// Verify that the actual link does not contain backslash. It's just an artifact of
// jettison json output.
assertEquals("/cluster/v2/foo/1",
- json.getJSONObject("cluster").getJSONObject("foo").getJSONObject("node")
- .getJSONObject("1").getString("link"));
+ json.getJSONObject("cluster").getJSONObject("foo").getJSONObject("node")
+ .getJSONObject("1").getString("link"));
assertEquals(expected, json.toString(2));
}
{
@@ -175,23 +174,23 @@ public class StateRestAPITest {
new HttpRequest().setPath("/cluster/v2/foo").addUrlOption("recursive", "1"));
String expected =
"{\"node\": {\n" +
- " \"1\": {\n" +
- " \"attributes\": {\"group\": \"mygroup\"},\n" +
- " \"state\": {\"current\": {\n" +
- " \"state\": \"initializing\",\n" +
- " \"reason\": \"\"\n" +
- " }},\n" +
- " \"metrics\": {\"doc-count\": 5}\n" +
- " },\n" +
- " \"3\": {\n" +
- " \"attributes\": {\"group\": \"mygroup\"},\n" +
- " \"state\": {\"current\": {\n" +
- " \"state\": \"up\",\n" +
- " \"reason\": \"\"\n" +
- " }},\n" +
- " \"metrics\": {\"doc-count\": 8}\n" +
- " }\n" +
- "}}";
+ " \"1\": {\n" +
+ " \"attributes\": {\"group\": \"mygroup\"},\n" +
+ " \"state\": {\"current\": {\n" +
+ " \"state\": \"initializing\",\n" +
+ " \"reason\": \"\"\n" +
+ " }},\n" +
+ " \"metrics\": {\"doc-count\": 5}\n" +
+ " },\n" +
+ " \"3\": {\n" +
+ " \"attributes\": {\"group\": \"mygroup\"},\n" +
+ " \"state\": {\"current\": {\n" +
+ " \"state\": \"up\",\n" +
+ " \"reason\": \"\"\n" +
+ " }},\n" +
+ " \"metrics\": {\"doc-count\": 8}\n" +
+ " }\n" +
+ "}}";
assertEquals(expected, json.toString(2));
}
{
@@ -199,9 +198,9 @@ public class StateRestAPITest {
new HttpRequest().setPath("/cluster/v2/foo").addUrlOption("recursive", "false"));
String expected =
"{\"node\": {\n" +
- " \"1\": {\"link\": \"\\/cluster\\/v2\\/foo\\/1\"},\n" +
- " \"3\": {\"link\": \"\\/cluster\\/v2\\/foo\\/3\"}\n" +
- "}}";
+ " \"1\": {\"link\": \"\\/cluster\\/v2\\/foo\\/1\"},\n" +
+ " \"3\": {\"link\": \"\\/cluster\\/v2\\/foo\\/3\"}\n" +
+ "}}";
assertEquals(expected, json.toString(2));
}
}
@@ -217,15 +216,15 @@ public class StateRestAPITest {
json.put("response-wait", responseWait.get());
}
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2/foo/3").setPostContent(json));
- assertEquals(result.toString(true), 200, result.getHttpReturnCode());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
+ assertEquals(200, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
StringBuilder print = new StringBuilder();
result.printContent(print);
return print.toString();
}
@Test
- public void testSetNodeState() throws Exception {
+ void testSetNodeState() throws Exception {
setupDummyStateApi();
{
JSONObject json = new JSONObject().put("state", new JSONObject()
@@ -233,8 +232,8 @@ public class StateRestAPITest {
.put("state", "retired")
.put("reason", "No reason")));
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2/foo/3").setPostContent(json));
- assertEquals(result.toString(true), 200, result.getHttpReturnCode());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
+ assertEquals(200, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
}
{
JSONObject json = executeOkJsonRequest(new HttpRequest().setPath("/cluster/v2/foo/3"));
@@ -246,14 +245,14 @@ public class StateRestAPITest {
+ " }},\n"
+ " \"metrics\": {\"doc-count\": 8}\n"
+ "}";
- assertEquals(json.toString(2), expected, json.toString(2));
+ assertEquals(expected, json.toString(2), json.toString(2));
}
{
JSONObject json = new JSONObject().put("state", new JSONObject()
.put("current", new JSONObject()));
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2/foo/3").setPostContent(json));
- assertEquals(result.toString(true), 200, result.getHttpReturnCode());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
+ assertEquals(200, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
}
{
JSONObject json = executeOkJsonRequest(new HttpRequest().setPath("/cluster/v2/foo/3"));
@@ -265,12 +264,12 @@ public class StateRestAPITest {
+ " }},\n"
+ " \"metrics\": {\"doc-count\": 8}\n"
+ "}";
- assertEquals(json.toString(2), expected, json.toString(2));
+ assertEquals(expected, json.toString(2), json.toString(2));
}
}
@Test
- public void set_node_state_response_wait_type_is_propagated_to_handler() throws Exception {
+ void set_node_state_response_wait_type_is_propagated_to_handler() throws Exception {
setupDummyStateApi();
{
String result = retireAndExpectHttp200Response(Optional.of("wait-until-cluster-acked"));
@@ -291,7 +290,7 @@ public class StateRestAPITest {
}
@Test
- public void set_node_state_response_wait_type_is_cluster_acked_by_default() throws Exception {
+ void set_node_state_response_wait_type_is_cluster_acked_by_default() throws Exception {
setupDummyStateApi();
String result = retireAndExpectHttp200Response(Optional.empty());
assertEquals(result,
@@ -302,92 +301,92 @@ public class StateRestAPITest {
}
@Test
- public void testMissingUnits() throws Exception {
+ void testMissingUnits() throws Exception {
setupDummyStateApi();
{
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2/unknown"));
- assertEquals(result.toString(true), 404, result.getHttpReturnCode());
- assertEquals(result.toString(true), "No such resource 'unknown'.", result.getHttpReturnCodeDescription());
+ assertEquals(404, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("No such resource 'unknown'.", result.getHttpReturnCodeDescription(), result.toString(true));
String expected = "{\"message\":\"No such resource 'unknown'.\"}";
assertEquals(expected, result.getContent().toString());
}
{
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2/foo/1234"));
- assertEquals(result.toString(true), 404, result.getHttpReturnCode());
- assertEquals(result.toString(true), "No such resource 'foo/1234'.", result.getHttpReturnCodeDescription());
+ assertEquals(404, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("No such resource 'foo/1234'.", result.getHttpReturnCodeDescription(), result.toString(true));
String expected = "{\"message\":\"No such resource 'foo\\/1234'.\"}";
assertEquals(expected, result.getContent().toString());
}
}
@Test
- public void testUnknownMaster() throws Exception {
+ void testUnknownMaster() throws Exception {
setupDummyStateApi();
stateApi.induceException(new UnknownMasterException());
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2"));
- assertEquals(result.toString(true), 503, result.getHttpReturnCode());
- assertEquals(result.toString(true), "Service Unavailable", result.getHttpReturnCodeDescription());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
+ assertEquals(503, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("Service Unavailable", result.getHttpReturnCodeDescription(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
String expected = "{\"message\":\"No known master cluster controller currently exists.\"}";
assertEquals(expected, result.getContent().toString());
- assertTrue(result.getHeader("Location") == null);
+ assertNull(result.getHeader("Location"));
}
@Test
- public void testOtherMaster() throws Exception {
+ void testOtherMaster() throws Exception {
setupDummyStateApi();
{
stateApi.induceException(new OtherMasterException("example.com", 80));
HttpResult result = execute(new HttpRequest().setScheme("https").setPath("/cluster/v2").addUrlOption(" %=?&", "&?%=").addUrlOption("foo", "bar"));
- assertEquals(result.toString(true), 307, result.getHttpReturnCode());
- assertEquals(result.toString(true), "Temporary Redirect", result.getHttpReturnCodeDescription());
- assertEquals(result.toString(true), "https://example.com:80/cluster/v2?%20%25%3D%3F%26=%26%3F%25%3D&foo=bar", result.getHeader("Location"));
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
+ assertEquals(307, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("Temporary Redirect", result.getHttpReturnCodeDescription(), result.toString(true));
+ assertEquals("https://example.com:80/cluster/v2?%20%25%3D%3F%26=%26%3F%25%3D&foo=bar", result.getHeader("Location"), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
String expected = "{\"message\":\"Cluster controller not master. Use master at example.com:80.\"}";
assertEquals(expected, result.getContent().toString());
}
{
stateApi.induceException(new OtherMasterException("example.com", 80));
HttpResult result = execute(new HttpRequest().setScheme("http").setPath("/cluster/v2/foo"));
- assertEquals(result.toString(true), 307, result.getHttpReturnCode());
- assertEquals(result.toString(true), "Temporary Redirect", result.getHttpReturnCodeDescription());
- assertEquals(result.toString(true), "http://example.com:80/cluster/v2/foo", result.getHeader("Location"));
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
+ assertEquals(307, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("Temporary Redirect", result.getHttpReturnCodeDescription(), result.toString(true));
+ assertEquals("http://example.com:80/cluster/v2/foo", result.getHeader("Location"), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
String expected = "{\"message\":\"Cluster controller not master. Use master at example.com:80.\"}";
assertEquals(expected, result.getContent().toString());
}
}
@Test
- public void testRuntimeException() throws Exception {
+ void testRuntimeException() throws Exception {
setupDummyStateApi();
stateApi.induceException(new RuntimeException("Moahaha"));
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2"));
- assertEquals(result.toString(true), 500, result.getHttpReturnCode());
- assertEquals(result.toString(true), "Failed to process request", result.getHttpReturnCodeDescription());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
+ assertEquals(500, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("Failed to process request", result.getHttpReturnCodeDescription(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
String expected = "{\"message\":\"java.lang.RuntimeException: Moahaha\"}";
assertEquals(expected, result.getContent().toString());
}
@Test
- public void testClientFailures() throws Exception {
+ void testClientFailures() throws Exception {
setupDummyStateApi();
{
stateApi.induceException(new InvalidContentException("Foo bar"));
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2"));
- assertEquals(result.toString(true), 400, result.getHttpReturnCode());
- assertEquals(result.toString(true), "Content of HTTP request had invalid data", result.getHttpReturnCodeDescription());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
+ assertEquals(400, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("Content of HTTP request had invalid data", result.getHttpReturnCodeDescription(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
String expected = "{\"message\":\"Foo bar\"}";
assertEquals(expected, result.getContent().toString());
}
{
stateApi.induceException(new InvalidOptionValueException("foo", "bar", "Foo can not be bar"));
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2"));
- assertEquals(result.toString(true), 400, result.getHttpReturnCode());
- assertEquals(result.toString(true), "Option 'foo' have invalid value 'bar'", result.getHttpReturnCodeDescription());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
+ assertEquals(400, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("Option 'foo' have invalid value 'bar'", result.getHttpReturnCodeDescription(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
String expected = "{\"message\":\"Option 'foo' have invalid value 'bar': Foo can not be bar\"}";
assertEquals(expected, result.getContent().toString());
}
@@ -396,94 +395,94 @@ public class StateRestAPITest {
path[0] = "foo";
stateApi.induceException(new OperationNotSupportedForUnitException(path, "Foo"));
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2"));
- assertEquals(result.toString(true), 405, result.getHttpReturnCode());
- assertEquals(result.toString(true), "Operation not supported for resource", result.getHttpReturnCodeDescription());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
+ assertEquals(405, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("Operation not supported for resource", result.getHttpReturnCodeDescription(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
String expected = "{\"message\":\"[foo]: Foo\"}";
assertEquals(expected, result.getContent().toString());
}
}
@Test
- public void testInternalFailure() throws Exception {
+ void testInternalFailure() throws Exception {
setupDummyStateApi();
{
stateApi.induceException(new InternalFailure("Foo"));
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2"));
- assertEquals(result.toString(true), 500, result.getHttpReturnCode());
- assertEquals(result.toString(true), "Failed to process request", result.getHttpReturnCodeDescription());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
+ assertEquals(500, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("Failed to process request", result.getHttpReturnCodeDescription(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
String expected = "{\"message\":\"Internal failure. Should not happen: Foo\"}";
assertEquals(expected, result.getContent().toString());
}
}
@Test
- public void testInvalidRecursiveValues() throws Exception {
+ void testInvalidRecursiveValues() throws Exception {
setupDummyStateApi();
{
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2").addUrlOption("recursive", "-5"));
- assertEquals(result.toString(true), 400, result.getHttpReturnCode());
- assertEquals(result.toString(true), "Option 'recursive' have invalid value '-5'", result.getHttpReturnCodeDescription());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
+ assertEquals(400, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("Option 'recursive' have invalid value '-5'", result.getHttpReturnCodeDescription(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
String expected = "{\"message\":\"Option 'recursive' have invalid value '-5': Recursive option must be true, false, 0 or a positive integer\"}";
assertEquals(expected, result.getContent().toString());
}
{
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2").addUrlOption("recursive", "foo"));
- assertEquals(result.toString(true), 400, result.getHttpReturnCode());
- assertEquals(result.toString(true), "Option 'recursive' have invalid value 'foo'", result.getHttpReturnCodeDescription());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
+ assertEquals(400, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("Option 'recursive' have invalid value 'foo'", result.getHttpReturnCodeDescription(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
String expected = "{\"message\":\"Option 'recursive' have invalid value 'foo': Recursive option must be true, false, 0 or a positive integer\"}";
assertEquals(expected, result.getContent().toString());
}
}
@Test
- public void testInvalidJsonInSetStateRequest() throws Exception {
+ void testInvalidJsonInSetStateRequest() throws Exception {
setupDummyStateApi();
{
JSONObject json = new JSONObject();
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2/foo/3").setPostContent(json));
- assertEquals(result.toString(true), 400, result.getHttpReturnCode());
- assertEquals(result.toString(true), "Content of HTTP request had invalid data", result.getHttpReturnCodeDescription());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
- assertTrue(result.toString(true), result.getContent().toString().contains("Set state requests must contain a state object"));
+ assertEquals(400, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("Content of HTTP request had invalid data", result.getHttpReturnCodeDescription(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
+ assertTrue(result.getContent().toString().contains("Set state requests must contain a state object"), result.toString(true));
}
{
JSONObject json = new JSONObject().put("state", 5);
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2/foo/3").setPostContent(json));
- assertEquals(result.toString(true), 400, result.getHttpReturnCode());
- assertEquals(result.toString(true), "Content of HTTP request had invalid data", result.getHttpReturnCodeDescription());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
- assertTrue(result.toString(true), result.getContent().toString().contains("value of state is not a json object"));
+ assertEquals(400, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("Content of HTTP request had invalid data", result.getHttpReturnCodeDescription(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
+ assertTrue(result.getContent().toString().contains("value of state is not a json object"), result.toString(true));
}
{
JSONObject json = new JSONObject().put("state", new JSONObject()
.put("current", 5));
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2/foo/3").setPostContent(json));
- assertEquals(result.toString(true), 400, result.getHttpReturnCode());
- assertEquals(result.toString(true), "Content of HTTP request had invalid data", result.getHttpReturnCodeDescription());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
- assertTrue(result.toString(true), result.getContent().toString().contains("value of state->current is not a json object"));
+ assertEquals(400, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("Content of HTTP request had invalid data", result.getHttpReturnCodeDescription(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
+ assertTrue(result.getContent().toString().contains("value of state->current is not a json object"), result.toString(true));
}
{
JSONObject json = new JSONObject().put("state", new JSONObject()
.put("current", new JSONObject().put("state", 5)));
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2/foo/3").setPostContent(json));
- assertEquals(result.toString(true), 400, result.getHttpReturnCode());
- assertEquals(result.toString(true), "Content of HTTP request had invalid data", result.getHttpReturnCodeDescription());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
- assertTrue(result.toString(true), result.getContent().toString().contains("value of state->current->state is not a string"));
+ assertEquals(400, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("Content of HTTP request had invalid data", result.getHttpReturnCodeDescription(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
+ assertTrue(result.getContent().toString().contains("value of state->current->state is not a string"), result.toString(true));
}
{
JSONObject json = new JSONObject().put("state", new JSONObject()
.put("current", new JSONObject().put("state", "down").put("reason", 5)));
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2/foo/3").setPostContent(json));
- assertEquals(result.toString(true), 400, result.getHttpReturnCode());
- assertEquals(result.toString(true), "Content of HTTP request had invalid data", result.getHttpReturnCodeDescription());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
- assertTrue(result.toString(true), result.getContent().toString().contains("value of state->current->reason is not a string"));
+ assertEquals(400, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("Content of HTTP request had invalid data", result.getHttpReturnCodeDescription(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
+ assertTrue(result.getContent().toString().contains("value of state->current->reason is not a string"), result.toString(true));
}
{
String result = retireAndExpectHttp400Response("Non existing condition", "no-wait");
@@ -506,21 +505,21 @@ public class StateRestAPITest {
.put("condition", condition)
.put("response-wait", responseWait);
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2/foo/3").setPostContent(json));
- assertEquals(result.toString(true), 400, result.getHttpReturnCode());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
+ assertEquals(400, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
StringBuilder print = new StringBuilder();
result.printContent(print);
return print.toString();
}
@Test
- public void testInvalidPathPrefix() throws Exception {
+ void testInvalidPathPrefix() throws Exception {
DummyBackend backend = new DummyBackend();
stateApi = new DummyStateApi(backend);
populateDummyBackend(backend);
testTransport = new TestTransport();
RestApiHandler handler = new RestApiHandler(stateApi);
- try{
+ try {
handler.setDefaultPathPrefix("cluster/v2");
assertTrue(false);
} catch (IllegalArgumentException e) {
@@ -528,14 +527,14 @@ public class StateRestAPITest {
}
@Test
- public void deadline_exceeded_exception_returns_http_504_error() throws Exception {
+ void deadline_exceeded_exception_returns_http_504_error() throws Exception {
setupDummyStateApi();
stateApi.induceException(new DeadlineExceededException("argh!"));
HttpResult result = execute(new HttpRequest().setPath("/cluster/v2"));
- assertEquals(result.toString(true), 504, result.getHttpReturnCode());
- assertEquals(result.toString(true), "Gateway Timeout", result.getHttpReturnCodeDescription());
- assertEquals(result.toString(true), "application/json", result.getHeader("Content-Type"));
+ assertEquals(504, result.getHttpReturnCode(), result.toString(true));
+ assertEquals("Gateway Timeout", result.getHttpReturnCodeDescription(), result.toString(true));
+ assertEquals("application/json", result.getHeader("Content-Type"), result.toString(true));
String expected = "{\"message\":\"argh!\"}";
assertEquals(expected, result.getContent().toString());
}
diff --git a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/staterestapi/server/RestApiHandlerTest.java b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/staterestapi/server/RestApiHandlerTest.java
index 2826c70f40a..6363264ce3e 100644
--- a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/staterestapi/server/RestApiHandlerTest.java
+++ b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/staterestapi/server/RestApiHandlerTest.java
@@ -2,16 +2,16 @@
package com.yahoo.vespa.clustercontroller.utils.staterestapi.server;
import com.yahoo.vespa.clustercontroller.utils.staterestapi.errors.InvalidContentException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.Optional;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class RestApiHandlerTest {
@Test
- public void testParsingOfTimeout() throws InvalidContentException {
+ void testParsingOfTimeout() throws InvalidContentException {
assertEquals(Optional.empty(), RestApiHandler.parseTimeout(null));
assertEquals(Optional.of(Duration.ofMillis(12500)), RestApiHandler.parseTimeout("12.5"));
assertEquals(Optional.of(Duration.ofMillis(0)), RestApiHandler.parseTimeout("-1"));
diff --git a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/util/CertainlyCloneableTest.java b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/util/CertainlyCloneableTest.java
index f81c4ba7a96..e14562d42c0 100644
--- a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/util/CertainlyCloneableTest.java
+++ b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/util/CertainlyCloneableTest.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.clustercontroller.utils.util;
-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 CertainlyCloneableTest {
@@ -15,8 +15,8 @@ public class CertainlyCloneableTest {
}
@Test
- public void testSimple() {
- try{
+ void testSimple() {
+ try {
Foo f = new Foo();
f.clone();
fail("Control should not get here");
diff --git a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/util/ClockTest.java b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/util/ClockTest.java
index ef338d35eb3..c791723615c 100644
--- a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/util/ClockTest.java
+++ b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/util/ClockTest.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.clustercontroller.utils.util;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
public class ClockTest {
@Test
- public void testNothingButGetCoverage() {
+ void testNothingButGetCoverage() {
long s = new Clock().getTimeInSecs();
long ms = new Clock().getTimeInMillis();
assertTrue(ms >= 1000 * s);
diff --git a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/util/JSONObjectWrapperTest.java b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/util/JSONObjectWrapperTest.java
index a5f57510194..f09907e7fcd 100644
--- a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/util/JSONObjectWrapperTest.java
+++ b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/util/JSONObjectWrapperTest.java
@@ -1,16 +1,16 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.clustercontroller.utils.util;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class JSONObjectWrapperTest {
@Test
- public void testExceptionWrapping() {
+ void testExceptionWrapping() {
JSONObjectWrapper wrapper = new JSONObjectWrapper();
- try{
+ try {
wrapper.put(null, "foo");
} catch (NullPointerException e) {
assertEquals("Null key.", e.getMessage());
diff --git a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/util/MetricReporterTest.java b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/util/MetricReporterTest.java
index b29de4c972c..33164aaf53e 100644
--- a/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/util/MetricReporterTest.java
+++ b/clustercontroller-utils/src/test/java/com/yahoo/vespa/clustercontroller/utils/util/MetricReporterTest.java
@@ -1,12 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.clustercontroller.utils.util;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Map;
import java.util.TreeMap;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class MetricReporterTest {
@@ -31,10 +31,10 @@ public class MetricReporterTest {
sb.append(" )\n");
return new Context() {};
}
- };
+ }
@Test
- public void testNoMetricReporter() {
+ void testNoMetricReporter() {
NoMetricReporter reporter = new NoMetricReporter();
reporter.add("foo", 3, null);
reporter.set("foo", 3, null);
@@ -42,7 +42,7 @@ public class MetricReporterTest {
}
@Test
- public void testPrefix() {
+ void testPrefix() {
MetricReporterMock mock = new MetricReporterMock();
ComponentMetricReporter c = new ComponentMetricReporter(mock, "prefix");
c.addDimension("urk", "fy");
@@ -50,14 +50,14 @@ public class MetricReporterTest {
c.set("bar", 1);
assertEquals(
"createContext( )\n" +
- "createContext( urk=fy )\n" +
- "add(prefixfoo, 2)\n" +
- "set(prefixbar, 1)\n", mock.sb.toString());
+ "createContext( urk=fy )\n" +
+ "add(prefixfoo, 2)\n" +
+ "set(prefixbar, 1)\n", mock.sb.toString());
}
@Test
- public void testWithContext() {
+ void testWithContext() {
MetricReporterMock mock = new MetricReporterMock();
ComponentMetricReporter c = new ComponentMetricReporter(mock, "prefix");
c.addDimension("urk", "fy");
@@ -67,27 +67,27 @@ public class MetricReporterTest {
c.set("bar", 1, c.createContext(myContext));
assertEquals(
"createContext( )\n" +
- "createContext( urk=fy )\n" +
- "createContext( myvar=3 urk=fy )\n" +
- "add(prefixfoo, 2)\n" +
- "createContext( myvar=3 urk=fy )\n" +
- "set(prefixbar, 1)\n", mock.sb.toString());
+ "createContext( urk=fy )\n" +
+ "createContext( myvar=3 urk=fy )\n" +
+ "add(prefixfoo, 2)\n" +
+ "createContext( myvar=3 urk=fy )\n" +
+ "set(prefixbar, 1)\n", mock.sb.toString());
}
@Test
- public void testDefaultContext() {
+ void testDefaultContext() {
MetricReporterMock mock = new MetricReporterMock();
ComponentMetricReporter c = new ComponentMetricReporter(mock, "prefix");
c.addDimension("urk", "fy");
c.add("foo", 2, c.createContext(null));
assertEquals(
"createContext( )\n" +
- "createContext( urk=fy )\n" +
- "add(prefixfoo, 2)\n", mock.sb.toString());
+ "createContext( urk=fy )\n" +
+ "add(prefixfoo, 2)\n", mock.sb.toString());
}
@Test
- public void testContextOverlap() {
+ void testContextOverlap() {
MetricReporterMock mock = new MetricReporterMock();
ComponentMetricReporter c = new ComponentMetricReporter(mock, "prefix");
c.addDimension("urk", "fy");
@@ -96,9 +96,9 @@ public class MetricReporterTest {
c.add("foo", 2, c.createContext(myContext));
assertEquals(
"createContext( )\n" +
- "createContext( urk=fy )\n" +
- "createContext( urk=yes )\n" +
- "add(prefixfoo, 2)\n", mock.sb.toString());
+ "createContext( urk=fy )\n" +
+ "createContext( urk=yes )\n" +
+ "add(prefixfoo, 2)\n", mock.sb.toString());
}
}
diff --git a/component/pom.xml b/component/pom.xml
index a4330957069..e8cee594066 100755
--- a/component/pom.xml
+++ b/component/pom.xml
@@ -16,11 +16,6 @@
<version>8-SNAPSHOT</version>
<dependencies>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>com.yahoo.vespa</groupId>
<artifactId>config-bundle</artifactId>
<version>${project.version}</version>
@@ -39,6 +34,16 @@
<scope>provided</scope>
</dependency>
<dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<scope>provided</scope>
diff --git a/component/src/test/java/com/yahoo/component/VersionCompatibilityTest.java b/component/src/test/java/com/yahoo/component/VersionCompatibilityTest.java
index c4f0e0f7439..45c94591b11 100644
--- a/component/src/test/java/com/yahoo/component/VersionCompatibilityTest.java
+++ b/component/src/test/java/com/yahoo/component/VersionCompatibilityTest.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.component;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Locale;
-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.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author jonmv
@@ -16,7 +16,7 @@ import static org.junit.Assert.fail;
public class VersionCompatibilityTest {
@Test
- public void testNoIncompatibilities() {
+ void testNoIncompatibilities() {
List<String> versions = List.of();
VersionCompatibility compatibility = VersionCompatibility.fromVersionList(versions);
assertTrue(compatibility.accept(new Version(0, 0, 0), new Version(0, 0, 0)));
@@ -26,36 +26,36 @@ public class VersionCompatibilityTest {
}
@Test
- public void testValidIncompatibilities() {
+ void testValidIncompatibilities() {
List<String> versions = List.of("1.2.*", "2", "3.*", "4.0.0", "4.0.1", "4.0.3", "4.1.0", "5");
VersionCompatibility compatibility = VersionCompatibility.fromVersionList(versions);
- assertTrue (compatibility.accept(new Version(0, 0, 0), new Version(0, 0, 0)));
- assertTrue (compatibility.accept(new Version(0, 0, 0), new Version(1, 1, 1)));
+ assertTrue(compatibility.accept(new Version(0, 0, 0), new Version(0, 0, 0)));
+ assertTrue(compatibility.accept(new Version(0, 0, 0), new Version(1, 1, 1)));
assertFalse(compatibility.accept(new Version(0, 0, 0), new Version(1, 2, 3)));
assertFalse(compatibility.accept(new Version(1, 1, 0), new Version(1, 2, 0)));
assertFalse(compatibility.accept(new Version(1, 2, 1), new Version(1, 2, 0)));
assertFalse(compatibility.accept(new Version(1, 1, 0), new Version(1, 3, 0)));
- assertTrue (compatibility.accept(new Version(1, 2, 3), new Version(1, 2, 3)));
- assertTrue (compatibility.accept(new Version(1, 3, 0), new Version(1, 9, 9)));
+ assertTrue(compatibility.accept(new Version(1, 2, 3), new Version(1, 2, 3)));
+ assertTrue(compatibility.accept(new Version(1, 3, 0), new Version(1, 9, 9)));
assertFalse(compatibility.accept(new Version(1, 3, 0), new Version(2, 0, 0)));
- assertTrue (compatibility.accept(new Version(2, 0, 0), new Version(2, 2, 2)));
+ assertTrue(compatibility.accept(new Version(2, 0, 0), new Version(2, 2, 2)));
assertFalse(compatibility.accept(new Version(2, 0, 0), new Version(3, 0, 0)));
- assertTrue (compatibility.accept(new Version(3, 0, 0), new Version(3, 0, 0)));
+ assertTrue(compatibility.accept(new Version(3, 0, 0), new Version(3, 0, 0)));
assertFalse(compatibility.accept(new Version(3, 0, 0), new Version(3, 1, 0)));
- assertTrue (compatibility.accept(new Version(3, 0, 0), new Version(3, 0, 1)));
+ assertTrue(compatibility.accept(new Version(3, 0, 0), new Version(3, 0, 1)));
assertFalse(compatibility.accept(new Version(3, 0, 0), new Version(4, 0, 0)));
assertFalse(compatibility.accept(new Version(4, 0, 0), new Version(4, 0, 1)));
- assertTrue (compatibility.accept(new Version(4, 0, 1), new Version(4, 0, 2)));
+ assertTrue(compatibility.accept(new Version(4, 0, 1), new Version(4, 0, 2)));
assertFalse(compatibility.accept(new Version(4, 0, 2), new Version(4, 0, 3)));
assertFalse(compatibility.accept(new Version(4, 0, 3), new Version(4, 1, 0)));
assertFalse(compatibility.accept(new Version(4, 1, 0), new Version(5, 0, 0)));
- assertTrue (compatibility.accept(new Version(5, 0, 0), new Version(6, 0, 0)));
+ assertTrue(compatibility.accept(new Version(5, 0, 0), new Version(6, 0, 0)));
assertFalse(compatibility.accept(new Version(0, 0, 0), new Version(2, 0, 0)));
assertFalse(compatibility.accept(new Version(0, 0, 0), new Version(6, 0, 0)));
}
@Test
- public void testIllegalIncompatibilities() {
+ void testIllegalIncompatibilities() {
assertThrows(List.of("1", "*"), IllegalArgumentException.class, "may not have siblings");
assertThrows(List.of("*", "*.*"), IllegalArgumentException.class, "may not have siblings");
assertThrows(List.of("*", "*"), IllegalArgumentException.class, "may not have siblings");
diff --git a/component/src/test/java/com/yahoo/component/VersionSpecificationTestCase.java b/component/src/test/java/com/yahoo/component/VersionSpecificationTestCase.java
index 7b419f0fc5d..cb4b07f1b33 100644
--- a/component/src/test/java/com/yahoo/component/VersionSpecificationTestCase.java
+++ b/component/src/test/java/com/yahoo/component/VersionSpecificationTestCase.java
@@ -1,11 +1,13 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.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.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author bratseth
@@ -13,74 +15,74 @@ import static org.junit.Assert.assertTrue;
public class VersionSpecificationTestCase {
@Test
- public void testPrimitiveCreation() {
- VersionSpecification version=new VersionSpecification(1,2,3,"qualifier");
- assertEquals(1, (int)version.getSpecifiedMajor());
- assertEquals(2, (int)version.getSpecifiedMinor());
- assertEquals(3, (int)version.getSpecifiedMicro());
- assertEquals("qualifier",version.getSpecifiedQualifier());
+ void testPrimitiveCreation() {
+ VersionSpecification version = new VersionSpecification(1, 2, 3, "qualifier");
+ assertEquals(1, (int) version.getSpecifiedMajor());
+ assertEquals(2, (int) version.getSpecifiedMinor());
+ assertEquals(3, (int) version.getSpecifiedMicro());
+ assertEquals("qualifier", version.getSpecifiedQualifier());
assertEquals(1, version.getMajor());
assertEquals(2, version.getMinor());
assertEquals(3, version.getMicro());
- assertEquals("qualifier",version.getQualifier());
+ assertEquals("qualifier", version.getQualifier());
}
@Test
- public void testUnderspecifiedPrimitiveCreation() {
- VersionSpecification version=new VersionSpecification(1);
- assertEquals(1,(int)version.getSpecifiedMajor());
- assertEquals(null,version.getSpecifiedMinor());
- assertEquals(null,version.getSpecifiedMicro());
- assertEquals(null,version.getSpecifiedQualifier());
+ void testUnderspecifiedPrimitiveCreation() {
+ VersionSpecification version = new VersionSpecification(1);
+ assertEquals(1, (int) version.getSpecifiedMajor());
+ assertNull(version.getSpecifiedMinor());
+ assertNull(version.getSpecifiedMicro());
+ assertNull(version.getSpecifiedQualifier());
assertEquals(1, version.getMajor());
assertEquals(0, version.getMinor());
assertEquals(0, version.getMicro());
- assertEquals("",version.getQualifier());
+ assertEquals("", version.getQualifier());
}
@Test
- public void testStringCreation() {
- VersionSpecification version=new VersionSpecification("1.2.3.qualifier");
- assertEquals(1,(int)version.getSpecifiedMajor());
- assertEquals(2,(int)version.getSpecifiedMinor());
- assertEquals(3,(int)version.getSpecifiedMicro());
- assertEquals("qualifier",version.getSpecifiedQualifier());
+ void testStringCreation() {
+ VersionSpecification version = new VersionSpecification("1.2.3.qualifier");
+ assertEquals(1, (int) version.getSpecifiedMajor());
+ assertEquals(2, (int) version.getSpecifiedMinor());
+ assertEquals(3, (int) version.getSpecifiedMicro());
+ assertEquals("qualifier", version.getSpecifiedQualifier());
}
@Test
- public void testUnderspecifiedStringCreation() {
- VersionSpecification version=new VersionSpecification("1");
- assertEquals(1,(int)version.getSpecifiedMajor());
- assertEquals(null,version.getSpecifiedMinor());
- assertEquals(null,version.getSpecifiedMicro());
- assertEquals(null,version.getSpecifiedQualifier());
+ void testUnderspecifiedStringCreation() {
+ VersionSpecification version = new VersionSpecification("1");
+ assertEquals(1, (int) version.getSpecifiedMajor());
+ assertNull(version.getSpecifiedMinor());
+ assertNull(version.getSpecifiedMicro());
+ assertNull(version.getSpecifiedQualifier());
assertEquals(1, version.getMajor());
assertEquals(0, version.getMinor());
assertEquals(0, version.getMicro());
- assertEquals("",version.getQualifier());
+ assertEquals("", version.getQualifier());
}
@Test
- public void testEquality() {
- assertEquals(new VersionSpecification(),VersionSpecification.emptyVersionSpecification);
- assertEquals(new VersionSpecification(),new VersionSpecification(""));
- assertEquals(new VersionSpecification(1),new VersionSpecification("1"));
- assertEquals(new VersionSpecification(1,2),new VersionSpecification("1.2"));
- assertEquals(new VersionSpecification(1,2,3),new VersionSpecification("1.2.3"));
- assertEquals(new VersionSpecification(1,2,3,"qualifier"),new VersionSpecification("1.2.3.qualifier"));
+ void testEquality() {
+ assertEquals(new VersionSpecification(), VersionSpecification.emptyVersionSpecification);
+ assertEquals(new VersionSpecification(), new VersionSpecification(""));
+ assertEquals(new VersionSpecification(1), new VersionSpecification("1"));
+ assertEquals(new VersionSpecification(1, 2), new VersionSpecification("1.2"));
+ assertEquals(new VersionSpecification(1, 2, 3), new VersionSpecification("1.2.3"));
+ assertEquals(new VersionSpecification(1, 2, 3, "qualifier"), new VersionSpecification("1.2.3.qualifier"));
}
@Test
- public void testToString() {
- assertEquals("",new VersionSpecification().toString());
- assertEquals("1",new VersionSpecification(1).toString());
- assertEquals("1.2",new VersionSpecification(1,2).toString());
- assertEquals("1.2.3",new VersionSpecification(1,2,3).toString());
- assertEquals("1.2.3.qualifier",new VersionSpecification(1,2,3,"qualifier").toString());
+ void testToString() {
+ assertEquals("", new VersionSpecification().toString());
+ assertEquals("1", new VersionSpecification(1).toString());
+ assertEquals("1.2", new VersionSpecification(1, 2).toString());
+ assertEquals("1.2.3", new VersionSpecification(1, 2, 3).toString());
+ assertEquals("1.2.3.qualifier", new VersionSpecification(1, 2, 3, "qualifier").toString());
}
@Test
- public void testMatches() {
+ void testMatches() {
assertTrue(new VersionSpecification("").matches(new Version("1")));
assertTrue(new VersionSpecification("1").matches(new Version("1")));
assertFalse(new VersionSpecification("1").matches(new Version("2")));
@@ -112,19 +114,19 @@ public class VersionSpecificationTestCase {
}
@Test
- public void testOrder() {
- assertTrue(new VersionSpecification("1.2.3").compareTo(new VersionSpecification("1.2.3"))==0);
- assertTrue(new VersionSpecification("1.2.3").compareTo(new VersionSpecification("1.2.4"))<0);
- assertTrue(new VersionSpecification("1.2.3").compareTo(new VersionSpecification("1.2.2"))>0);
+ void testOrder() {
+ assertEquals(new VersionSpecification("1.2.3").compareTo(new VersionSpecification("1.2.3")), 0);
+ assertTrue(new VersionSpecification("1.2.3").compareTo(new VersionSpecification("1.2.4")) < 0);
+ assertTrue(new VersionSpecification("1.2.3").compareTo(new VersionSpecification("1.2.2")) > 0);
- assertTrue(new VersionSpecification("1.2.3").compareTo(new VersionSpecification("2"))<0);
- assertTrue(new VersionSpecification("1.2.3").compareTo(new VersionSpecification("1.3"))<0);
+ assertTrue(new VersionSpecification("1.2.3").compareTo(new VersionSpecification("2")) < 0);
+ assertTrue(new VersionSpecification("1.2.3").compareTo(new VersionSpecification("1.3")) < 0);
- assertTrue(new VersionSpecification("1.0.0").compareTo(new VersionSpecification("1"))==0);
+ assertEquals(new VersionSpecification("1.0.0").compareTo(new VersionSpecification("1")), 0);
}
@Test
- public void testValidIntersect() {
+ void testValidIntersect() {
VersionSpecification mostSpecific = new VersionSpecification(4, 2, 1);
VersionSpecification leastSpecific = new VersionSpecification(4, 2);
@@ -134,9 +136,11 @@ public class VersionSpecificationTestCase {
leastSpecific.intersect(mostSpecific));
}
- @Test(expected=RuntimeException.class)
- public void testInvalidIntersect() {
- new VersionSpecification(4, 1).intersect(
- new VersionSpecification(4, 2));
+ @Test
+ void testInvalidIntersect() {
+ assertThrows(RuntimeException.class, () -> {
+ new VersionSpecification(4, 1).intersect(
+ new VersionSpecification(4, 2));
+ });
}
}
diff --git a/component/src/test/java/com/yahoo/component/VersionTestCase.java b/component/src/test/java/com/yahoo/component/VersionTestCase.java
index f66bc245f85..96adb6ce38f 100644
--- a/component/src/test/java/com/yahoo/component/VersionTestCase.java
+++ b/component/src/test/java/com/yahoo/component/VersionTestCase.java
@@ -3,11 +3,11 @@ package com.yahoo.component;
import com.yahoo.text.Utf8Array;
import com.yahoo.text.Utf8String;
-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.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author bratseth
@@ -15,111 +15,111 @@ import static org.junit.Assert.assertTrue;
public class VersionTestCase {
@Test
- public void testPrimitiveCreation() {
- Version version=new Version(1,2,3,"qualifier");
- assertEquals(1,version.getMajor());
- assertEquals(2,version.getMinor());
- assertEquals(3,version.getMicro());
- assertEquals("qualifier",version.getQualifier());
+ void testPrimitiveCreation() {
+ Version version = new Version(1, 2, 3, "qualifier");
+ assertEquals(1, version.getMajor());
+ assertEquals(2, version.getMinor());
+ assertEquals(3, version.getMicro());
+ assertEquals("qualifier", version.getQualifier());
}
@Test
- public void testUnderspecifiedPrimitiveCreation() {
- Version version=new Version(1);
- assertEquals(1,version.getMajor());
- assertEquals(1,version.getMajor());
- assertEquals(0,version.getMinor());
- assertEquals(0,version.getMicro());
- assertEquals("",version.getQualifier());
+ void testUnderspecifiedPrimitiveCreation() {
+ Version version = new Version(1);
+ assertEquals(1, version.getMajor());
+ assertEquals(1, version.getMajor());
+ assertEquals(0, version.getMinor());
+ assertEquals(0, version.getMicro());
+ assertEquals("", version.getQualifier());
}
@Test
- public void testStringCreation() {
- Version version=new Version("1.2.3.qualifier");
- assertEquals(1,version.getMajor());
- assertEquals(2,version.getMinor());
- assertEquals(3,version.getMicro());
- assertEquals("qualifier",version.getQualifier());
+ void testStringCreation() {
+ Version version = new Version("1.2.3.qualifier");
+ assertEquals(1, version.getMajor());
+ assertEquals(2, version.getMinor());
+ assertEquals(3, version.getMicro());
+ assertEquals("qualifier", version.getQualifier());
}
@Test
- public void testUtf8StringCreation() {
- Version version=new Version((Utf8Array)new Utf8String("1.2.3.qualifier"));
- assertEquals(1,version.getMajor());
- assertEquals(2,version.getMinor());
- assertEquals(3,version.getMicro());
- assertEquals("qualifier",version.getQualifier());
+ void testUtf8StringCreation() {
+ Version version = new Version((Utf8Array) new Utf8String("1.2.3.qualifier"));
+ assertEquals(1, version.getMajor());
+ assertEquals(2, version.getMinor());
+ assertEquals(3, version.getMicro());
+ assertEquals("qualifier", version.getQualifier());
}
@Test
- public void testUnderspecifiedStringCreation() {
- Version version=new Version("1");
- assertEquals(1,version.getMajor());
- assertEquals(0,version.getMinor());
- assertEquals(0,version.getMicro());
- assertEquals("",version.getQualifier());
+ void testUnderspecifiedStringCreation() {
+ Version version = new Version("1");
+ assertEquals(1, version.getMajor());
+ assertEquals(0, version.getMinor());
+ assertEquals(0, version.getMicro());
+ assertEquals("", version.getQualifier());
}
@Test
- public void testEquality() {
- assertEquals(new Version(),Version.emptyVersion);
- assertEquals(new Version(),new Version(""));
- assertEquals(new Version(0,0,0),Version.emptyVersion);
- assertEquals(new Version(1),new Version("1"));
- assertEquals(new Version(1,2),new Version("1.2"));
- assertEquals(new Version(1,2,3),new Version("1.2.3"));
- assertEquals(new Version(1,2,3,"qualifier"),new Version("1.2.3.qualifier"));
+ void testEquality() {
+ assertEquals(new Version(), Version.emptyVersion);
+ assertEquals(new Version(), new Version(""));
+ assertEquals(new Version(0, 0, 0), Version.emptyVersion);
+ assertEquals(new Version(1), new Version("1"));
+ assertEquals(new Version(1, 2), new Version("1.2"));
+ assertEquals(new Version(1, 2, 3), new Version("1.2.3"));
+ assertEquals(new Version(1, 2, 3, "qualifier"), new Version("1.2.3.qualifier"));
}
@Test
- public void testToString() {
- assertEquals("",new Version().toString());
- assertEquals("1",new Version(1).toString());
- assertEquals("1.2",new Version(1,2).toString());
- assertEquals("1.2.3",new Version(1,2,3).toString());
- assertEquals("1.2.3.qualifier",new Version(1,2,3,"qualifier").toString());
+ void testToString() {
+ assertEquals("", new Version().toString());
+ assertEquals("1", new Version(1).toString());
+ assertEquals("1.2", new Version(1, 2).toString());
+ assertEquals("1.2.3", new Version(1, 2, 3).toString());
+ assertEquals("1.2.3.qualifier", new Version(1, 2, 3, "qualifier").toString());
}
@Test
- public void testToFullString() {
- assertEquals("0.0.0",new Version().toFullString());
- assertEquals("1.0.0",new Version(1).toFullString());
- assertEquals("1.2.0",new Version(1,2).toFullString());
- assertEquals("1.2.3",new Version(1,2,3).toFullString());
- assertEquals("1.2.3.qualifier",new Version(1,2,3,"qualifier").toFullString());
+ void testToFullString() {
+ assertEquals("0.0.0", new Version().toFullString());
+ assertEquals("1.0.0", new Version(1).toFullString());
+ assertEquals("1.2.0", new Version(1, 2).toFullString());
+ assertEquals("1.2.3", new Version(1, 2, 3).toFullString());
+ assertEquals("1.2.3.qualifier", new Version(1, 2, 3, "qualifier").toFullString());
}
@Test
- public void testOrder() {
- assertTrue(new Version("1.2.3").compareTo(new Version("1.2.3"))==0);
- assertTrue(new Version("1.2.3").compareTo(new Version("1.2.4"))<0);
- assertTrue(new Version("1.2.3").compareTo(new Version("1.2.3.foo"))<0);
- assertTrue(new Version("1.2.3").compareTo(new Version("1.2.2"))>0);
- assertTrue(new Version("1.2.3.foo").compareTo(new Version("1.2.3"))>0);
- assertTrue(new Version("1.2.3").compareTo(new Version("2"))<0);
- assertTrue(new Version("1.2.3").compareTo(new Version("1.3"))<0);
- assertTrue(new Version("1.0.0").compareTo(new Version("1"))==0);
+ void testOrder() {
+ assertEquals(new Version("1.2.3").compareTo(new Version("1.2.3")), 0);
+ assertTrue(new Version("1.2.3").compareTo(new Version("1.2.4")) < 0);
+ assertTrue(new Version("1.2.3").compareTo(new Version("1.2.3.foo")) < 0);
+ assertTrue(new Version("1.2.3").compareTo(new Version("1.2.2")) > 0);
+ assertTrue(new Version("1.2.3.foo").compareTo(new Version("1.2.3")) > 0);
+ assertTrue(new Version("1.2.3").compareTo(new Version("2")) < 0);
+ assertTrue(new Version("1.2.3").compareTo(new Version("1.3")) < 0);
+ assertEquals(new Version("1.0.0").compareTo(new Version("1")), 0);
}
-
+
@Test
- public void testIsBefore() {
+ void testIsBefore() {
assertFalse(new Version("1.2.3").isBefore(new Version("0.2.3")));
assertFalse(new Version("1.2.3").isBefore(new Version("1.1.3")));
assertFalse(new Version("1.2.3").isBefore(new Version("1.2.2")));
assertFalse(new Version("1.2.3").isBefore(new Version("1.2.3")));
assertFalse(new Version("1.2.3.foo").isBefore(new Version("1.2.3")));
- assertTrue( new Version("1.2.3").isBefore(new Version("1.2.4")));
- assertTrue( new Version("1.2.3").isBefore(new Version("1.3.3")));
- assertTrue( new Version("1.2.3").isBefore(new Version("2.2.3")));
- assertTrue( new Version("1.2.3").isBefore(new Version("1.2.3.foo")));
+ assertTrue(new Version("1.2.3").isBefore(new Version("1.2.4")));
+ assertTrue(new Version("1.2.3").isBefore(new Version("1.3.3")));
+ assertTrue(new Version("1.2.3").isBefore(new Version("2.2.3")));
+ assertTrue(new Version("1.2.3").isBefore(new Version("1.2.3.foo")));
}
@Test
- public void testIsAfter() {
- assertTrue( new Version("1.2.3").isAfter(new Version("0.2.3")));
- assertTrue( new Version("1.2.3").isAfter(new Version("1.1.3")));
- assertTrue( new Version("1.2.3").isAfter(new Version("1.2.2")));
- assertTrue( new Version("1.2.3.foo").isAfter(new Version("1.2.3")));
+ void testIsAfter() {
+ assertTrue(new Version("1.2.3").isAfter(new Version("0.2.3")));
+ assertTrue(new Version("1.2.3").isAfter(new Version("1.1.3")));
+ assertTrue(new Version("1.2.3").isAfter(new Version("1.2.2")));
+ assertTrue(new Version("1.2.3.foo").isAfter(new Version("1.2.3")));
assertFalse(new Version("1.2.3").isAfter(new Version("1.2.3")));
assertFalse(new Version("1.2.3").isAfter(new Version("1.2.4")));
assertFalse(new Version("1.2.3").isAfter(new Version("1.3.3")));
diff --git a/config-lib/pom.xml b/config-lib/pom.xml
index ea72afb568d..66603deeb38 100644
--- a/config-lib/pom.xml
+++ b/config-lib/pom.xml
@@ -17,11 +17,6 @@
<name>${project.artifactId}</name>
<dependencies>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>com.yahoo.vespa</groupId>
<artifactId>annotations</artifactId>
<version>${project.version}</version>
@@ -33,6 +28,16 @@
<version>${project.version}</version>
<scope>provided</scope>
</dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
+ </dependency>
</dependencies>
<build>
<plugins>
diff --git a/config-lib/src/test/java/com/yahoo/config/BooleanNodeTest.java b/config-lib/src/test/java/com/yahoo/config/BooleanNodeTest.java
index bfa2f747c1c..50d71ba50e9 100644
--- a/config-lib/src/test/java/com/yahoo/config/BooleanNodeTest.java
+++ b/config-lib/src/test/java/com/yahoo/config/BooleanNodeTest.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.config;
-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 Ulf Lilleengen
@@ -12,7 +12,7 @@ import static org.junit.Assert.assertTrue;
*/
public class BooleanNodeTest {
@Test
- public void testSetValue() {
+ void testSetValue() {
BooleanNode n = new BooleanNode();
assertTrue(n.doSetValue("true"));
assertTrue(n.doSetValue("TRUE"));
diff --git a/config-lib/src/test/java/com/yahoo/config/ConfigInstanceBuilderTest.java b/config-lib/src/test/java/com/yahoo/config/ConfigInstanceBuilderTest.java
index 613cfe1cced..f05baeff08c 100644
--- a/config-lib/src/test/java/com/yahoo/config/ConfigInstanceBuilderTest.java
+++ b/config-lib/src/test/java/com/yahoo/config/ConfigInstanceBuilderTest.java
@@ -6,7 +6,7 @@ import com.yahoo.foo.StructtypesConfig;
import com.yahoo.test.FunctionTestConfig;
import com.yahoo.test.IntConfig;
import com.yahoo.test.RestartConfig;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.lang.reflect.Field;
@@ -26,11 +26,11 @@ import static com.yahoo.test.FunctionTestConfig.RootStruct;
import static com.yahoo.test.FunctionTestConfig.MyStructMap;
import static com.yahoo.foo.MaptypesConfig.Innermap;
-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.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.assertTrue;
/**
* @author gjoranv
@@ -40,7 +40,7 @@ public class ConfigInstanceBuilderTest
{
@Test
- public void struct_values_can_be_set_without_declaring_a_new_struct_builder() {
+ void struct_values_can_be_set_without_declaring_a_new_struct_builder() {
var builder = new StructtypesConfig.Builder();
builder.simple
.name("myname")
@@ -52,7 +52,7 @@ public class ConfigInstanceBuilderTest
}
@Test
- public void leaf_map_setter_merges_maps() {
+ void leaf_map_setter_merges_maps() {
MaptypesConfig.Builder builder = new MaptypesConfig.Builder()
.intmap("one", 1);
@@ -66,10 +66,10 @@ public class ConfigInstanceBuilderTest
}
@Test
- public void inner_map_setter_merges_maps() {
+ void inner_map_setter_merges_maps() {
MaptypesConfig.Builder builder = new MaptypesConfig.Builder()
.innermap("one", new Innermap.Builder()
- .foo(1));
+ .foo(1));
Map<String, Innermap.Builder> newMap = new HashMap<>();
newMap.put("two", new Innermap.Builder().foo(2));
@@ -81,13 +81,13 @@ public class ConfigInstanceBuilderTest
}
@Test
- public void testVariableAccessWithBuilder() {
+ void testVariableAccessWithBuilder() {
FunctionTestConfig config = createVariableAccessConfigWithBuilder();
assertVariableAccessValues(config, ":parent:");
}
@Test
- public void require_that_unset_builder_fields_are_null() throws Exception {
+ void require_that_unset_builder_fields_are_null() throws Exception {
FunctionTestConfig.Builder builder = new FunctionTestConfig.Builder();
assertNull(getMember(builder, "bool_val"));
assertNull(getMember(builder, "bool_with_def"));
@@ -111,7 +111,7 @@ public class ConfigInstanceBuilderTest
}
@Test
- public void require_that_set_builder_fields_are_nonNull() throws Exception {
+ void require_that_set_builder_fields_are_nonNull() throws Exception {
FunctionTestConfig.Builder builder = createVariableAccessBuilder();
assertNotNull(getMember(builder, "bool_val"));
assertNotNull(getMember(builder, "bool_with_def"));
@@ -129,13 +129,13 @@ public class ConfigInstanceBuilderTest
assertNotNull(getMember(builder, "refwithdef"));
assertNotNull(getMember(builder, "fileVal"));
- BasicStruct.Builder basicStructBuilder = (BasicStruct.Builder)getMember(builder, "basicStruct");
+ BasicStruct.Builder basicStructBuilder = (BasicStruct.Builder) getMember(builder, "basicStruct");
assertNotNull(getMember(basicStructBuilder, "foo"));
assertNotNull(getMember(basicStructBuilder, "bar"));
}
@Test
- public void require_that_config_can_be_recreated_from_another_configs_builder() {
+ void require_that_config_can_be_recreated_from_another_configs_builder() {
FunctionTestConfig original = createVariableAccessConfigWithBuilder();
FunctionTestConfig copy = new FunctionTestConfig(new FunctionTestConfig.Builder(original));
assertVariableAccessValues(copy, ":parent:");
@@ -330,13 +330,13 @@ public class ConfigInstanceBuilderTest
}
@Test
- public void require_that_config_class_reports_any_restart_values() throws Exception {
+ void require_that_config_class_reports_any_restart_values() throws Exception {
assertTrue(callContainsFieldsFlaggedWithRestart(RestartConfig.class));
assertFalse(callContainsFieldsFlaggedWithRestart(IntConfig.class));
}
@Test
- public void require_that_config_class_can_make_change_report() throws Exception {
+ void require_that_config_class_can_make_change_report() throws Exception {
IntConfig noRestart1 = new IntConfig(new IntConfig.Builder().intVal(42));
IntConfig noRestart2 = new IntConfig(new IntConfig.Builder().intVal(21));
ChangesRequiringRestart report = callGetChangesRequiringRestart(noRestart1, noRestart2);
@@ -370,33 +370,33 @@ public class ConfigInstanceBuilderTest
assertEquals("function-test", report.getName());
assertTrue(
report.toString().startsWith(
- "# An int value\n" +
- "# Also test that multiline comments\n" +
- "# work.\n" +
- "function-test.int_val has changed from 5 to 100\n" +
- "function-test.stringarr[0] has changed from \"bar\" to \"foo\"\n" +
- "# This is a map of ints.\n" +
- "function-test.intMap{one} has changed from 1 to 42\n" +
- "# This is a map of ints.\n" +
- "function-test.intMap{two} with value 2 was removed\n" +
- "# This is a map of ints.\n" +
- "function-test.intMap{three} was added with value 3\n" +
- "# A basic struct\n" +
- "function-test.basicStruct.foo has changed from \"basicFoo\" to \"basic\"\n" +
- "function-test.basicStruct.bar has changed from 3 to 1234\n" +
- "function-test.basicStruct.intArr[0] with value 310 was removed\n" +
- "function-test.basicStruct.intArr[1] with value 311 was removed\n" +
- "function-test.myarray[0].anotherarray[0].foo has changed from 7 to 32\n" +
- "# This is my array\n" +
- "function-test.myarray[1].intval has changed from 5 to 17\n" +
- "function-test.myarray[2] was added with value \n"
+ "# An int value\n" +
+ "# Also test that multiline comments\n" +
+ "# work.\n" +
+ "function-test.int_val has changed from 5 to 100\n" +
+ "function-test.stringarr[0] has changed from \"bar\" to \"foo\"\n" +
+ "# This is a map of ints.\n" +
+ "function-test.intMap{one} has changed from 1 to 42\n" +
+ "# This is a map of ints.\n" +
+ "function-test.intMap{two} with value 2 was removed\n" +
+ "# This is a map of ints.\n" +
+ "function-test.intMap{three} was added with value 3\n" +
+ "# A basic struct\n" +
+ "function-test.basicStruct.foo has changed from \"basicFoo\" to \"basic\"\n" +
+ "function-test.basicStruct.bar has changed from 3 to 1234\n" +
+ "function-test.basicStruct.intArr[0] with value 310 was removed\n" +
+ "function-test.basicStruct.intArr[1] with value 311 was removed\n" +
+ "function-test.myarray[0].anotherarray[0].foo has changed from 7 to 32\n" +
+ "# This is my array\n" +
+ "function-test.myarray[1].intval has changed from 5 to 17\n" +
+ "function-test.myarray[2] was added with value \n"
)
);
assertTrue(
report.toString().contains(
- "function-test.myStructMap{one}.myInt has changed from 1 to 42\n" +
- "function-test.myStructMap{new} was added with value \n"
+ "function-test.myStructMap{one}.myInt has changed from 1 to 42\n" +
+ "function-test.myStructMap{new} was added with value \n"
)
);
diff --git a/config-lib/src/test/java/com/yahoo/config/ConfigInstanceEqualsTest.java b/config-lib/src/test/java/com/yahoo/config/ConfigInstanceEqualsTest.java
index 536c18786da..1584293a137 100644
--- a/config-lib/src/test/java/com/yahoo/config/ConfigInstanceEqualsTest.java
+++ b/config-lib/src/test/java/com/yahoo/config/ConfigInstanceEqualsTest.java
@@ -3,8 +3,8 @@ package com.yahoo.config;
import com.yahoo.test.AppConfig;
import com.yahoo.test.FunctionTestConfig;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.util.Arrays;
@@ -14,15 +14,15 @@ import static com.yahoo.test.FunctionTestConfig.Enum_val;
import static com.yahoo.test.FunctionTestConfig.Enumarr;
import static com.yahoo.test.FunctionTestConfig.Myarray;
import static com.yahoo.test.FunctionTestConfig.RootStruct;
-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;
public class ConfigInstanceEqualsTest {
FunctionTestConfig config1;
FunctionTestConfig.Builder builder2;
FunctionTestConfig config2;
- @Before
+ @BeforeEach
public void reset() {
config1 = new FunctionTestConfig(newBuilder());
builder2 = newBuilder();
@@ -30,28 +30,28 @@ public class ConfigInstanceEqualsTest {
}
@Test
- public void require_same_hashCode_for_equal_instances() {
+ void require_same_hashCode_for_equal_instances() {
assertEquals(config1.hashCode(), config2.hashCode());
}
@Test
- public void require_true_for_equal_instances() {
+ void require_true_for_equal_instances() {
assertEquals(config1, config2);
}
@Test
- public void require_false_for_null() {
+ void require_false_for_null() {
assertNotEquals(null, config1);
}
@Test
- public void require_false_for_different_subclass() {
+ void require_false_for_different_subclass() {
assertNotEquals(config1, new AppConfig(new AppConfig.Builder()));
}
@Test
- public void require_false_for_different_scalars_at_root_node() {
+ void require_false_for_different_scalars_at_root_node() {
assertNotEquals(config1, new FunctionTestConfig(newBuilder().bool_val(true)));
assertNotEquals(config1, new FunctionTestConfig(newBuilder().int_val(0)));
assertNotEquals(config1, new FunctionTestConfig(newBuilder().long_val(0L)));
@@ -63,50 +63,50 @@ public class ConfigInstanceEqualsTest {
}
@Test
- public void require_false_for_different_leaf_array_at_root_node() {
+ void require_false_for_different_leaf_array_at_root_node() {
builder2.longarr.set(0, 0L);
assertNotEquals(config1, new FunctionTestConfig(builder2));
}
@Test
- public void require_false_for_different_scalar_in_struct() {
+ void require_false_for_different_scalar_in_struct() {
builder2.basicStruct(new BasicStruct.Builder(config1.basicStruct()).bar(0));
assertNotEquals(config1, new FunctionTestConfig(builder2));
}
@Test
- public void require_false_for_different_scalar_in_inner_array() {
+ void require_false_for_different_scalar_in_inner_array() {
builder2.myarray.get(0).intval(0);
assertNotEquals(config1, new FunctionTestConfig(builder2));
}
@Test
- public void require_false_for_different_leaf_array_in_inner_array() {
+ void require_false_for_different_leaf_array_in_inner_array() {
builder2.myarray.get(0).stringval.set(0, "");
assertNotEquals(config1, new FunctionTestConfig(builder2));
}
@Test
- public void require_equal_structs_for_equal_configs() {
+ void require_equal_structs_for_equal_configs() {
assertEquals(config1.basicStruct(), config2.basicStruct());
assertEquals(config1.rootStruct(), config2.rootStruct());
assertEquals(config1.rootStruct().inner0(), config2.rootStruct().inner0());
}
@Test
- public void require_equal_inner_arrays_for_equal_configs() {
+ void require_equal_inner_arrays_for_equal_configs() {
assertEquals(config1.myarray(), config2.myarray());
assertEquals(config1.myarray(0).anotherarray(), config2.myarray(0).anotherarray());
}
@Test
- public void require_equal_inner_array_elements_for_equal_configs() {
+ void require_equal_inner_array_elements_for_equal_configs() {
assertEquals(config1.myarray(0), config2.myarray(0));
assertEquals(config1.myarray(0).anotherarray(0), config2.myarray(0).anotherarray(0));
}
@Test
- public void require_equal_leaf_arrays_for_equal_configs() {
+ void require_equal_leaf_arrays_for_equal_configs() {
assertEquals(config1.intarr(), config2.intarr());
assertEquals(config1.boolarr(), config2.boolarr());
assertEquals(config1.longarr(), config2.longarr());
diff --git a/config-lib/src/test/java/com/yahoo/config/DoubleNodeTest.java b/config-lib/src/test/java/com/yahoo/config/DoubleNodeTest.java
index 1192cc6673e..475a33104b0 100644
--- a/config-lib/src/test/java/com/yahoo/config/DoubleNodeTest.java
+++ b/config-lib/src/test/java/com/yahoo/config/DoubleNodeTest.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;
-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.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -14,7 +14,7 @@ import static org.junit.Assert.assertTrue;
*/
public class DoubleNodeTest {
@Test
- public void testSetValue() {
+ void testSetValue() {
DoubleNode n = new DoubleNode();
assertFalse(n.doSetValue("invalid"));
assertTrue(n.doSetValue("3.14"));
diff --git a/config-lib/src/test/java/com/yahoo/config/EnumNodeTest.java b/config-lib/src/test/java/com/yahoo/config/EnumNodeTest.java
index fac765f40aa..e7723409736 100644
--- a/config-lib/src/test/java/com/yahoo/config/EnumNodeTest.java
+++ b/config-lib/src/test/java/com/yahoo/config/EnumNodeTest.java
@@ -1,12 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Ulf Lilleengen
@@ -30,7 +30,7 @@ public class EnumNodeTest {
}
@Test
- public void testEnumNode() {
+ void testEnumNode() {
MyNode n = new MyNode();
assertNull(n.getValue());
assertEquals("(null)", n.toString());
diff --git a/config-lib/src/test/java/com/yahoo/config/FileNodeTest.java b/config-lib/src/test/java/com/yahoo/config/FileNodeTest.java
index 42e4978091d..8bec9378f8f 100644
--- a/config-lib/src/test/java/com/yahoo/config/FileNodeTest.java
+++ b/config-lib/src/test/java/com/yahoo/config/FileNodeTest.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;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThrows;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Ulf Lilleengen
@@ -14,7 +14,7 @@ import static org.junit.Assert.assertTrue;
public class FileNodeTest {
@Test
- public void testSetValue() {
+ void testSetValue() {
FileNode n = new FileNode();
assertEquals("(null)", n.toString());
assertTrue(n.doSetValue("foo.txt"));
@@ -24,7 +24,7 @@ public class FileNodeTest {
assertEquals("\"foo.txt\"", n.toString());
assertEquals("path may not start with '..', but got: foo/../../boo",
- assertThrows(IllegalArgumentException.class, () -> new FileNode("foo/../../boo")).getMessage());
+ assertThrows(IllegalArgumentException.class, () -> new FileNode("foo/../../boo")).getMessage());
}
}
diff --git a/config-lib/src/test/java/com/yahoo/config/IntegerNodeTest.java b/config-lib/src/test/java/com/yahoo/config/IntegerNodeTest.java
index 899e34edce4..a195a5f65fb 100644
--- a/config-lib/src/test/java/com/yahoo/config/IntegerNodeTest.java
+++ b/config-lib/src/test/java/com/yahoo/config/IntegerNodeTest.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;
-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.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Ulf Lilleengen
@@ -13,7 +13,7 @@ import static org.junit.Assert.assertTrue;
*/
public class IntegerNodeTest {
@Test
- public void testSetValue() {
+ void testSetValue() {
IntegerNode n = new IntegerNode();
assertFalse(n.setValue("invalid"));
assertTrue(n.setValue("10"));
diff --git a/config-lib/src/test/java/com/yahoo/config/LongNodeTest.java b/config-lib/src/test/java/com/yahoo/config/LongNodeTest.java
index fc603ba65ac..dc6d59bbc46 100644
--- a/config-lib/src/test/java/com/yahoo/config/LongNodeTest.java
+++ b/config-lib/src/test/java/com/yahoo/config/LongNodeTest.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;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertFalse;
-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.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Ulf Lilleengen
@@ -13,7 +13,7 @@ import static org.junit.Assert.assertTrue;
*/
public class LongNodeTest {
@Test
- public void testSetValue() {
+ void testSetValue() {
LongNode n = new LongNode();
assertFalse(n.setValue("invalid"));
assertTrue(n.setValue("10"));
diff --git a/config-lib/src/test/java/com/yahoo/config/NodeVectorTest.java b/config-lib/src/test/java/com/yahoo/config/NodeVectorTest.java
index 9637ab25278..e6b3b4b6a71 100644
--- a/config-lib/src/test/java/com/yahoo/config/NodeVectorTest.java
+++ b/config-lib/src/test/java/com/yahoo/config/NodeVectorTest.java
@@ -1,13 +1,14 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
-import static org.junit.Assert.assertFalse;
-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;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* @author Ulf Lilleengen
@@ -15,38 +16,78 @@ import static org.junit.Assert.assertTrue;
*/
public class NodeVectorTest {
- @Test(expected = NodeVector.ReadOnlyException.class)
- public void require_that_add_throws_exception() { new TestNodeVector("foo").add(barNode()); }
+ @Test
+ void require_that_add_throws_exception() {
+ assertThrows(NodeVector.ReadOnlyException.class, () -> {
+ new TestNodeVector("foo").add(barNode());
+ });
+ }
- @Test(expected = NodeVector.ReadOnlyException.class)
- public void require_that_addindex_throws_exception() { new TestNodeVector("foo").add(0, barNode()); }
+ @Test
+ void require_that_addindex_throws_exception() {
+ assertThrows(NodeVector.ReadOnlyException.class, () -> {
+ new TestNodeVector("foo").add(0, barNode());
+ });
+ }
- @Test(expected = NodeVector.ReadOnlyException.class)
- public void require_that_addAll_throws_exception() { new TestNodeVector("foo").addAll(Arrays.asList(barNode())); }
+ @Test
+ void require_that_addAll_throws_exception() {
+ assertThrows(NodeVector.ReadOnlyException.class, () -> {
+ new TestNodeVector("foo").addAll(Arrays.asList(barNode()));
+ });
+ }
- @Test(expected = NodeVector.ReadOnlyException.class)
- public void require_that_addAllindex_throws_exception() { new TestNodeVector("foo").addAll(0, Arrays.asList(barNode())); }
+ @Test
+ void require_that_addAllindex_throws_exception() {
+ assertThrows(NodeVector.ReadOnlyException.class, () -> {
+ new TestNodeVector("foo").addAll(0, Arrays.asList(barNode()));
+ });
+ }
- @Test(expected = NodeVector.ReadOnlyException.class)
- public void require_that_clear_throws_exception() { new TestNodeVector("foo").clear(); }
+ @Test
+ void require_that_clear_throws_exception() {
+ assertThrows(NodeVector.ReadOnlyException.class, () -> {
+ new TestNodeVector("foo").clear();
+ });
+ }
- @Test(expected = NodeVector.ReadOnlyException.class)
- public void require_that_remove_index_throws_exception() { new TestNodeVector("foo").remove(0); }
+ @Test
+ void require_that_remove_index_throws_exception() {
+ assertThrows(NodeVector.ReadOnlyException.class, () -> {
+ new TestNodeVector("foo").remove(0);
+ });
+ }
- @Test(expected = NodeVector.ReadOnlyException.class)
- public void require_that_remove_object_throws_exception() { new TestNodeVector("foo").remove(null); }
+ @Test
+ void require_that_remove_object_throws_exception() {
+ assertThrows(NodeVector.ReadOnlyException.class, () -> {
+ new TestNodeVector("foo").remove(null);
+ });
+ }
- @Test(expected = NodeVector.ReadOnlyException.class)
- public void require_that_removeAll_throws_exception() { new TestNodeVector("foo").removeAll(null); }
+ @Test
+ void require_that_removeAll_throws_exception() {
+ assertThrows(NodeVector.ReadOnlyException.class, () -> {
+ new TestNodeVector("foo").removeAll(null);
+ });
+ }
- @Test(expected = NodeVector.ReadOnlyException.class)
- public void require_that_retainAll_throws_exception() { new TestNodeVector("foo").retainAll(null); }
+ @Test
+ void require_that_retainAll_throws_exception() {
+ assertThrows(NodeVector.ReadOnlyException.class, () -> {
+ new TestNodeVector("foo").retainAll(null);
+ });
+ }
- @Test(expected = NodeVector.ReadOnlyException.class)
- public void require_that_set_throws_exception() { new TestNodeVector("foo").set(0, null); }
+ @Test
+ void require_that_set_throws_exception() {
+ assertThrows(NodeVector.ReadOnlyException.class, () -> {
+ new TestNodeVector("foo").set(0, null);
+ });
+ }
@Test
- public void require_that_contains_works() {
+ void require_that_contains_works() {
StringNode val = new StringNode("foo");
TestNodeVector v = new TestNodeVector(val.getValue());
assertTrue(v.contains(val));
@@ -56,7 +97,7 @@ public class NodeVectorTest {
}
@Test
- public void require_that_indexOf_works() {
+ void require_that_indexOf_works() {
StringNode val = new StringNode("foo");
TestNodeVector v = new TestNodeVector(val.getValue());
assertFalse(v.isEmpty());
@@ -67,7 +108,7 @@ public class NodeVectorTest {
}
@Test
- public void require_that_iterators_work() {
+ void require_that_iterators_work() {
String val = "foo";
TestNodeVector v = new TestNodeVector(val, val, val);
assertTrue(v.listIterator().hasNext());
@@ -78,7 +119,7 @@ public class NodeVectorTest {
}
@Test
- public void require_that_sublisting_works() {
+ void require_that_sublisting_works() {
String val = "foo";
TestNodeVector v = new TestNodeVector(val, val, val);
assertEquals(1, v.subList(0, 1).size());
diff --git a/config-lib/src/test/java/com/yahoo/config/PathNodeTest.java b/config-lib/src/test/java/com/yahoo/config/PathNodeTest.java
index 016c53b42e3..ad8f5e2e65f 100644
--- a/config-lib/src/test/java/com/yahoo/config/PathNodeTest.java
+++ b/config-lib/src/test/java/com/yahoo/config/PathNodeTest.java
@@ -1,12 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config;
-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.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* @author gjoranv
@@ -15,7 +15,7 @@ import static org.junit.Assert.assertThrows;
public class PathNodeTest {
@Test
- public void testSetValue() {
+ void testSetValue() {
PathNode n = new PathNode();
assertEquals("(null)", n.toString());
@@ -23,7 +23,7 @@ public class PathNodeTest {
assertEquals(new File("foo.txt").toPath(), n.value());
assertEquals("path may not start with '..', but got: foo/../../boo",
- assertThrows(IllegalArgumentException.class, () -> new PathNode(new FileReference("foo/../../boo"))).getMessage());
+ assertThrows(IllegalArgumentException.class, () -> new PathNode(new FileReference("foo/../../boo"))).getMessage());
}
}
diff --git a/config-lib/src/test/java/com/yahoo/config/StringNodeTest.java b/config-lib/src/test/java/com/yahoo/config/StringNodeTest.java
index 5d606e12454..d0baf8d1837 100644
--- a/config-lib/src/test/java/com/yahoo/config/StringNodeTest.java
+++ b/config-lib/src/test/java/com/yahoo/config/StringNodeTest.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.config;
-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;
/**
* @author hmusum
@@ -12,7 +13,7 @@ import static org.junit.Assert.assertEquals;
public class StringNodeTest {
@Test
- public void testUnescapeQuotedString() {
+ void testUnescapeQuotedString() {
String a = "\"Hei\"";
assertEquals("Hei", StringNode.unescapeQuotedString(a));
assertEquals("foo\"bar\"", StringNode.unescapeQuotedString("foo\"bar\""));
@@ -21,13 +22,15 @@ public class StringNodeTest {
assertEquals("U", StringNode.unescapeQuotedString("\\x55"));
}
- @Test(expected = IllegalArgumentException.class)
- public void testUnescapedQuotedStringExceptions() {
- StringNode.unescapeQuotedString("foo\\");
+ @Test
+ void testUnescapedQuotedStringExceptions() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ StringNode.unescapeQuotedString("foo\\");
+ });
}
@Test
- public void testToString() {
+ void testToString() {
StringNode n = new StringNode();
assertEquals("(null)", n.toString());
n.setValue("foo");
@@ -35,7 +38,7 @@ public class StringNodeTest {
}
@Test
- public void testSetValue() {
+ void testSetValue() {
StringNode n = new StringNode();
n.setValue("\"foo\"");
assertEquals("foo", n.getValue());
diff --git a/config-lib/src/test/java/com/yahoo/config/UrlNodeTest.java b/config-lib/src/test/java/com/yahoo/config/UrlNodeTest.java
index abf04c34bb8..1f40cb58a71 100644
--- a/config-lib/src/test/java/com/yahoo/config/UrlNodeTest.java
+++ b/config-lib/src/test/java/com/yahoo/config/UrlNodeTest.java
@@ -1,9 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config;
-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 lesters
@@ -11,7 +11,7 @@ import static org.junit.Assert.assertEquals;
public class UrlNodeTest {
@Test
- public void testSetValue() {
+ void testSetValue() {
UrlNode url = new UrlNode();
assertEquals("(null)", url.toString());
diff --git a/config-lib/src/test/java/com/yahoo/config/codegen/NamespaceAndPackageTest.java b/config-lib/src/test/java/com/yahoo/config/codegen/NamespaceAndPackageTest.java
index 54e2271f7dc..39e5f64e5e2 100644
--- a/config-lib/src/test/java/com/yahoo/config/codegen/NamespaceAndPackageTest.java
+++ b/config-lib/src/test/java/com/yahoo/config/codegen/NamespaceAndPackageTest.java
@@ -4,9 +4,9 @@ package com.yahoo.config.codegen;
import com.github.myproject.NamespaceAndPackageConfig;
import com.github.myproject.PackageConfig;
import com.yahoo.my.namespace.NamespaceConfig;
-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 gjoranv
@@ -16,17 +16,17 @@ public class NamespaceAndPackageTest {
private static String PACKAGE = "com.github.myproject";
@Test
- public void namespace_is_set_from_def_file() {
+ void namespace_is_set_from_def_file() {
assertEquals(NAMESPACE, NamespaceConfig.CONFIG_DEF_NAMESPACE);
}
@Test
- public void package_is_used_as_namespace_when_namespace_is_not_set_explicitly() {
+ void package_is_used_as_namespace_when_namespace_is_not_set_explicitly() {
assertEquals(PACKAGE, PackageConfig.CONFIG_DEF_NAMESPACE);
}
@Test
- public void package_does_not_override_namespace() {
+ void package_does_not_override_namespace() {
assertEquals(NAMESPACE, NamespaceAndPackageConfig.CONFIG_DEF_NAMESPACE);
}
diff --git a/config-model/pom.xml b/config-model/pom.xml
index c39f84b864d..d1af9eab915 100644
--- a/config-model/pom.xml
+++ b/config-model/pom.xml
@@ -36,8 +36,13 @@
<scope>test</scope>
</dependency>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
@@ -133,6 +138,12 @@
<artifactId>testutil</artifactId>
<version>${project.version}</version>
<scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>com.yahoo.vespa</groupId>
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/admin/clustercontroller/ClusterControllerContainerCluster.java b/config-model/src/main/java/com/yahoo/vespa/model/admin/clustercontroller/ClusterControllerContainerCluster.java
index a7f3a6224f2..f7007fec181 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/admin/clustercontroller/ClusterControllerContainerCluster.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/admin/clustercontroller/ClusterControllerContainerCluster.java
@@ -7,8 +7,12 @@ import com.yahoo.config.model.producer.AbstractConfigProducer;
import com.yahoo.config.provision.ClusterSpec;
import com.yahoo.search.config.QrStartConfig;
import com.yahoo.vespa.model.container.ContainerCluster;
+import com.yahoo.vespa.model.container.PlatformBundles;
+import java.nio.file.Path;
+import java.util.Collections;
import java.util.Optional;
+import java.util.Set;
/**
* Container cluster for cluster-controller containers.
@@ -18,6 +22,8 @@ import java.util.Optional;
*/
public class ClusterControllerContainerCluster extends ContainerCluster<ClusterControllerContainer> {
+ private static final Set<Path> UNNECESSARY_BUNDLES = Collections.unmodifiableSet(PlatformBundles.VESPA_SECURITY_BUNDLES);
+
private final ReindexingContext reindexingContext;
public ClusterControllerContainerCluster(
@@ -29,6 +35,9 @@ public class ClusterControllerContainerCluster extends ContainerCluster<ClusterC
}
@Override
+ protected Set<Path> unnecessaryPlatformBundles() { return UNNECESSARY_BUNDLES; }
+
+ @Override
protected void doPrepare(DeployState deployState) { }
@Override protected boolean messageBusEnabled() { return false; }
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsProxyContainerCluster.java b/config-model/src/main/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsProxyContainerCluster.java
index 680a4b97f86..17f169033d3 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsProxyContainerCluster.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/admin/metricsproxy/MetricsProxyContainerCluster.java
@@ -36,16 +36,19 @@ import com.yahoo.vespa.model.admin.monitoring.MetricSet;
import com.yahoo.vespa.model.admin.monitoring.MetricsConsumer;
import com.yahoo.vespa.model.admin.monitoring.Monitoring;
import com.yahoo.vespa.model.container.ContainerCluster;
+import com.yahoo.vespa.model.container.PlatformBundles;
import com.yahoo.vespa.model.container.component.Handler;
import com.yahoo.vespa.model.container.component.SystemBindingPattern;
-import com.yahoo.vespa.model.container.PlatformBundles;
import java.nio.file.Path;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
+import java.util.Set;
import java.util.logging.Logger;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
import static com.yahoo.vespa.model.admin.metricsproxy.ConsumersConfigGenerator.addMetrics;
import static com.yahoo.vespa.model.admin.metricsproxy.ConsumersConfigGenerator.generateConsumers;
@@ -75,6 +78,12 @@ public class MetricsProxyContainerCluster extends ContainerCluster<MetricsProxyC
static final Path METRICS_PROXY_BUNDLE_FILE = PlatformBundles.absoluteBundlePath(METRICS_PROXY_NAME);
static final String METRICS_PROXY_BUNDLE_NAME = "com.yahoo.vespa." + METRICS_PROXY_NAME;
+ private static final Set<Path> UNNECESSARY_BUNDLES = Stream.concat
+ (
+ PlatformBundles.VESPA_SECURITY_BUNDLES.stream(),
+ PlatformBundles.VESPA_ZK_BUNDLES.stream()
+ ).collect(Collectors.toSet());
+
static final class AppDimensionNames {
static final String SYSTEM = "system";
static final String TENANT = "tenantName";
@@ -98,6 +107,9 @@ public class MetricsProxyContainerCluster extends ContainerCluster<MetricsProxyC
addClusterComponents();
}
+ @Override
+ protected Set<Path> unnecessaryPlatformBundles() { return UNNECESSARY_BUNDLES; }
+
private void addClusterComponents() {
addMetricsProxyComponent(ApplicationDimensions.class);
addMetricsProxyComponent(ConfigSentinelClient.class);
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/ContainerCluster.java b/config-model/src/main/java/com/yahoo/vespa/model/container/ContainerCluster.java
index c1267568581..7e375951c7f 100755
--- a/config-model/src/main/java/com/yahoo/vespa/model/container/ContainerCluster.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/container/ContainerCluster.java
@@ -194,6 +194,8 @@ public abstract class ContainerCluster<CONTAINER extends Container>
addSimpleComponent(com.yahoo.jdisc.http.server.jetty.Janitor.class);
}
+ protected abstract boolean messageBusEnabled();
+
public ClusterSpec.Id id() { return ClusterSpec.Id.from(getName()); }
public void setZone(Zone zone) {
@@ -455,18 +457,21 @@ public abstract class ContainerCluster<CONTAINER extends Container>
}
/**
- * Adds the Vespa bundles that are necessary for all container types.
+ * Adds the Vespa bundles that are necessary for most container types.
+ * Note that some of these can be removed later by the individual cluster types.
*/
public void addCommonVespaBundles() {
- PlatformBundles.commonVespaBundles.forEach(this::addPlatformBundle);
+ PlatformBundles.COMMON_VESPA_BUNDLES.forEach(this::addPlatformBundle);
+ PlatformBundles.VESPA_SECURITY_BUNDLES.forEach(this::addPlatformBundle);
+ PlatformBundles.VESPA_ZK_BUNDLES.forEach(this::addPlatformBundle);
}
- /*
- Add all search/docproc/feed related platform bundles.
- This is only required for application configured containers as the platform bundle set is not allowed to change
- between config generations. For standalone container platform bundles can be added on features enabled as an
- update of application package requires restart.
- */
+ /**
+ * Add all search/docproc/feed related platform bundles.
+ * These are only required for application configured containers as the platform bundle set is not allowed to change
+ * between config generations. For standalone container platform bundles can be added on features enabled as an
+ * update of application package requires restart.
+ */
public void addAllPlatformBundles() {
ContainerDocumentApi.addVespaClientContainerBundle(this);
addSearchAndDocprocBundles();
@@ -481,9 +486,19 @@ public abstract class ContainerCluster<CONTAINER extends Container>
* @param bundlePath usually an absolute path, e.g. '$VESPA_HOME/lib/jars/foo.jar'
*/
public final void addPlatformBundle(Path bundlePath) {
- platformBundles.add(bundlePath);
+ if (! unnecessaryPlatformBundles().contains(bundlePath)) {
+ platformBundles.add(bundlePath);
+ } else {
+ log.fine(() -> "Not installing bundle " + bundlePath + " for cluster " + getName());
+ }
}
+ /**
+ * Implement in subclasses to avoid installing unnecessary bundles, see {@link PlatformBundles}
+ * Should only return constant values, as there is no guarantee for when this is called.
+ */
+ protected Set<Path> unnecessaryPlatformBundles() { return Set.of(); }
+
@Override
public void getConfig(PlatformBundlesConfig.Builder builder) {
platformBundles.stream()
@@ -645,8 +660,6 @@ public abstract class ContainerCluster<CONTAINER extends Container>
return "container cluster '" + getName() + "'";
}
- protected abstract boolean messageBusEnabled();
-
/**
* Mark whether the config emitted by this cluster currently should be applied by clients already running with
* a previous generation of it only by restarting the consuming processes.
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/PlatformBundles.java b/config-model/src/main/java/com/yahoo/vespa/model/container/PlatformBundles.java
index f8691dcde53..7ce82848d09 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/container/PlatformBundles.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/container/PlatformBundles.java
@@ -33,17 +33,35 @@ public class PlatformBundles {
public static final String SEARCH_AND_DOCPROC_BUNDLE = BundleInstantiationSpecification.CONTAINER_SEARCH_AND_DOCPROC;
// Bundles that must be loaded for all container types.
- public static final Set<Path> commonVespaBundles = Stream.of(
+ public static final Set<Path> COMMON_VESPA_BUNDLES = toBundlePaths(
+ "container-spifly.jar", // Aries SPIFly repackaged
+ // Used by vespa-athenz, zkfacade, other vespa bundles and nearly all hosted apps.
+ // TODO Vespa 9: stop installing and providing servlet-api. Seems difficult, though.
+ "javax.servlet-api-3.1.0.jar"
+ );
+
+ public static final Set<Path> VESPA_SECURITY_BUNDLES = toBundlePaths(
+ "jdisc-security-filters",
+ "vespa-athenz"
+ );
+
+ public static final Set<Path> VESPA_ZK_BUNDLES = toBundlePaths(
"zkfacade",
- "zookeeper-server" // TODO: not necessary in metrics-proxy.
- ).map(PlatformBundles::absoluteBundlePath).collect(Collectors.toSet());
+ "zookeeper-server"
+ );
- public static final Set<Path> SEARCH_AND_DOCPROC_BUNDLES = Stream.of(
- PlatformBundles.SEARCH_AND_DOCPROC_BUNDLE,
+ public static final Set<Path> SEARCH_AND_DOCPROC_BUNDLES = toBundlePaths(
+ SEARCH_AND_DOCPROC_BUNDLE,
"container-search-gui",
"docprocs",
"linguistics-components"
- ).map(PlatformBundles::absoluteBundlePath).collect(Collectors.toSet());
+ );
+
+ private static Set<Path> toBundlePaths(String... bundleNames) {
+ return Stream.of(bundleNames)
+ .map(PlatformBundles::absoluteBundlePath)
+ .collect(Collectors.toSet());
+ }
public static Path absoluteBundlePath(String fileName) {
return absoluteBundlePath(fileName, JarSuffix.JAR_WITH_DEPS);
@@ -51,7 +69,8 @@ public class PlatformBundles {
public static Path absoluteBundlePath(String fileName, JarSuffix jarSuffix) {
if (fileName == null) return null;
- return LIBRARY_PATH.resolve(Paths.get(fileName + jarSuffix.suffix));
+ String fullFilename = fileName.endsWith(".jar") ? fileName : fileName + jarSuffix.suffix;
+ return LIBRARY_PATH.resolve(Paths.get(fullFilename));
}
public static boolean isSearchAndDocprocClass(String className) {
diff --git a/config-model/src/main/java/com/yahoo/vespa/model/container/http/BlockFeedGlobalEndpointsFilter.java b/config-model/src/main/java/com/yahoo/vespa/model/container/http/BlockFeedGlobalEndpointsFilter.java
index 167dac4c57e..039daba8ad0 100644
--- a/config-model/src/main/java/com/yahoo/vespa/model/container/http/BlockFeedGlobalEndpointsFilter.java
+++ b/config-model/src/main/java/com/yahoo/vespa/model/container/http/BlockFeedGlobalEndpointsFilter.java
@@ -7,7 +7,7 @@ import com.yahoo.component.chain.dependencies.Dependencies;
import com.yahoo.component.chain.model.ChainedComponentModel;
import com.yahoo.config.model.api.ContainerEndpoint;
import com.yahoo.container.bundle.BundleInstantiationSpecification;
-import com.yahoo.jdisc.http.filter.security.rule.RuleBasedFilterConfig;
+import com.yahoo.vespa.config.jdisc.http.filter.RuleBasedFilterConfig;
import com.yahoo.vespa.model.clients.ContainerDocumentApi;
import com.yahoo.vespa.model.container.ContainerCluster;
@@ -17,11 +17,11 @@ import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
-import static com.yahoo.jdisc.http.filter.security.rule.RuleBasedFilterConfig.DefaultRule.Action.Enum.ALLOW;
-import static com.yahoo.jdisc.http.filter.security.rule.RuleBasedFilterConfig.Rule.Action.Enum.BLOCK;
-import static com.yahoo.jdisc.http.filter.security.rule.RuleBasedFilterConfig.Rule.Methods.Enum.DELETE;
-import static com.yahoo.jdisc.http.filter.security.rule.RuleBasedFilterConfig.Rule.Methods.Enum.POST;
-import static com.yahoo.jdisc.http.filter.security.rule.RuleBasedFilterConfig.Rule.Methods.Enum.PUT;
+import static com.yahoo.vespa.config.jdisc.http.filter.RuleBasedFilterConfig.DefaultRule.Action.Enum.ALLOW;
+import static com.yahoo.vespa.config.jdisc.http.filter.RuleBasedFilterConfig.Rule.Action.Enum.BLOCK;
+import static com.yahoo.vespa.config.jdisc.http.filter.RuleBasedFilterConfig.Rule.Methods.Enum.DELETE;
+import static com.yahoo.vespa.config.jdisc.http.filter.RuleBasedFilterConfig.Rule.Methods.Enum.POST;
+import static com.yahoo.vespa.config.jdisc.http.filter.RuleBasedFilterConfig.Rule.Methods.Enum.PUT;
/**
* @author mortent
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&lt;float&gt;(d0[1],d1[784])'/>" +
- "</query-profile-type>";
+ " <field name='query(mytensor)' type='tensor&lt;float&gt;(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&lt;float&gt;(d0[1],d1[784],d2[10])'/>" +
- "</query-profile-type>";
+ " <field name='query(mytensor)' type='tensor&lt;float&gt;(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 8012a00076b..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
@@ -20,6 +20,7 @@ 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 com.yahoo.container.di.config.PlatformBundlesConfig;
import com.yahoo.search.config.QrStartConfig;
import com.yahoo.vespa.config.content.FleetcontrollerConfig;
import com.yahoo.vespa.config.content.StorDistributionConfig;
@@ -29,24 +30,25 @@ import com.yahoo.vespa.model.Service;
import com.yahoo.vespa.model.VespaModel;
import com.yahoo.vespa.model.admin.clustercontroller.ClusterControllerContainer;
import com.yahoo.vespa.model.admin.clustercontroller.ClusterControllerContainerCluster;
+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;
import java.io.StringReader;
+import java.nio.file.Path;
import java.time.Instant;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
+import java.util.Set;
-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 java.util.stream.Collectors.toSet;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Test for creating cluster controllers under the admin tag.
@@ -55,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" +
@@ -85,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>" +
@@ -110,66 +112,78 @@ public class ClusterControllerTestCase extends DomBuilderTest {
assertEquals(4000, cfg.storage_transition_time());
assertEquals(3600000, cfg.stable_state_time_period());
}
+
+ assertOnlyNecessaryBundles(model);
}
+ private void assertOnlyNecessaryBundles(VespaModel model) {
+ PlatformBundlesConfig config = model.getConfig(PlatformBundlesConfig.class, "admin/cluster-controllers");
+ Set<String> unnecessaryBundles = PlatformBundles.VESPA_SECURITY_BUNDLES.stream().map(Path::toString).collect(toSet());
+ assertTrue(config.bundlePaths().stream()
+ .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" +
@@ -245,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" +
@@ -307,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" +
@@ -349,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" +
@@ -404,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" +
@@ -425,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 b3860459323..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
@@ -15,12 +15,15 @@ import com.yahoo.container.core.ApplicationMetadataConfig;
import com.yahoo.container.di.config.PlatformBundlesConfig;
import com.yahoo.vespa.model.VespaModel;
import com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyContainerCluster.AppDimensionNames;
+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;
-import java.util.stream.Collectors;
+import java.util.Set;
+import java.util.stream.Stream;
import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyContainerCluster.METRICS_PROXY_BUNDLE_FILE;
import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyContainerCluster.zoneString;
@@ -35,9 +38,9 @@ import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyModelTester.g
import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyModelTester.getModel;
import static com.yahoo.vespa.model.admin.metricsproxy.MetricsProxyModelTester.servicesWithAdminOnly;
import static java.util.stream.Collectors.toList;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static java.util.stream.Collectors.toSet;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author gjoranv
@@ -45,29 +48,38 @@ 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);
- var builder = new PlatformBundlesConfig.Builder();
- model.getConfig(builder, CLUSTER_CONFIG_ID);
- PlatformBundlesConfig config = builder.build();
- assertFalse(config.bundlePaths().stream()
- .filter(p -> p.endsWith(METRICS_PROXY_BUNDLE_FILE.toString()))
- .collect(Collectors.toList())
- .isEmpty());
+ PlatformBundlesConfig config = model.getConfig(PlatformBundlesConfig.class, CLUSTER_CONFIG_ID);
+ assertTrue(config.bundlePaths().stream()
+ .anyMatch(p -> p.equals(METRICS_PROXY_BUNDLE_FILE.toString())));
}
@Test
- public void cluster_is_prepared_so_that_application_metadata_config_is_produced() {
+ void unnecessary_bundles_are_not_installed() {
VespaModel model = getModel(servicesWithAdminOnly(), self_hosted);
- var builder = new ApplicationMetadataConfig.Builder();
- model.getConfig(builder, CLUSTER_CONFIG_ID);
- ApplicationMetadataConfig config = builder.build();
+ PlatformBundlesConfig config = model.getConfig(PlatformBundlesConfig.class, CLUSTER_CONFIG_ID);
+
+ Set<String> unnecessaryBundles = Stream.concat
+ (
+ PlatformBundles.VESPA_SECURITY_BUNDLES.stream(),
+ PlatformBundles.VESPA_ZK_BUNDLES.stream()
+ ).map(Path::toString).collect(toSet());
+
+ assertTrue(config.bundlePaths().stream()
+ .noneMatch(unnecessaryBundles::contains));
+ }
+
+ @Test
+ 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());
assertEquals(MockApplicationPackage.APPLICATION_NAME, config.name());
}
@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());
@@ -79,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);
@@ -93,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 1691868ee65..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
@@ -4,21 +4,20 @@ package com.yahoo.vespa.model.container.http;
import com.yahoo.config.model.api.ApplicationClusterEndpoint;
import com.yahoo.config.model.api.ContainerEndpoint;
-import com.yahoo.jdisc.http.filter.security.rule.RuleBasedFilterConfig;
-import org.junit.Test;
+import com.yahoo.vespa.config.jdisc.http.filter.RuleBasedFilterConfig;
+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.assertThat;
-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);
@@ -29,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() &gt; 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());
+ });
}
diff --git a/config-model/src/test/java/helpers/CompareConfigTestHelper.java b/config-model/src/test/java/helpers/CompareConfigTestHelper.java
index ba06ecc9397..4d8c46d0edb 100644
--- a/config-model/src/test/java/helpers/CompareConfigTestHelper.java
+++ b/config-model/src/test/java/helpers/CompareConfigTestHelper.java
@@ -11,7 +11,7 @@ import java.io.IOException;
import java.util.Collections;
import java.util.List;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Vegard Sjonfjell
diff --git a/config-provisioning/pom.xml b/config-provisioning/pom.xml
index 119931465bf..b190bca06a5 100644
--- a/config-provisioning/pom.xml
+++ b/config-provisioning/pom.xml
@@ -61,10 +61,29 @@
<artifactId>testutil</artifactId>
<version>${project.version}</version>
<scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-core</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-library</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
diff --git a/config-provisioning/src/test/java/com/yahoo/config/provision/ApplicationIdTest.java b/config-provisioning/src/test/java/com/yahoo/config/provision/ApplicationIdTest.java
index 622fc2527bf..0a60b868bde 100644
--- a/config-provisioning/src/test/java/com/yahoo/config/provision/ApplicationIdTest.java
+++ b/config-provisioning/src/test/java/com/yahoo/config/provision/ApplicationIdTest.java
@@ -3,7 +3,7 @@ package com.yahoo.config.provision;
import com.yahoo.cloud.config.ApplicationIdConfig;
import com.yahoo.test.TotalOrderTester;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.HashSet;
import java.util.List;
@@ -11,8 +11,9 @@ import java.util.Set;
import static com.yahoo.config.provision.ApplicationId.from;
import static com.yahoo.config.provision.ApplicationId.global;
-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;
+import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* @author Ulf Lilleengen
@@ -22,7 +23,7 @@ import static org.junit.Assert.assertNotEquals;
public class ApplicationIdTest {
@Test
- public void require_that_application_id_is_set() {
+ void require_that_application_id_is_set() {
ApplicationId app = applicationId("application");
assertEquals("application", app.application().value());
app = from("tenant", "application", "instance");
@@ -32,23 +33,23 @@ public class ApplicationIdTest {
}
@Test
- public void require_that_equals_and_hashcode_behaves_correctly() {
+ void require_that_equals_and_hashcode_behaves_correctly() {
assertEquals(Set.of(from("tenant1", "name1", "instance1"),
- from("tenant2", "name1", "instance1"),
- from("tenant1", "name2", "instance1"),
- from("tenant1", "name1", "instance2"),
- applicationId("name1"),
- applicationId("name2")),
- new HashSet<>(List.of(from("tenant1", "name1", "instance1"),
- from("tenant2", "name1", "instance1"),
- from("tenant1", "name2", "instance1"),
- from("tenant1", "name1", "instance2"),
- applicationId("name1"),
- applicationId("name2"))));
+ from("tenant2", "name1", "instance1"),
+ from("tenant1", "name2", "instance1"),
+ from("tenant1", "name1", "instance2"),
+ applicationId("name1"),
+ applicationId("name2")),
+ new HashSet<>(List.of(from("tenant1", "name1", "instance1"),
+ from("tenant2", "name1", "instance1"),
+ from("tenant1", "name2", "instance1"),
+ from("tenant1", "name1", "instance2"),
+ applicationId("name1"),
+ applicationId("name2"))));
}
@Test
- public void require_that_value_format_is_correct() {
+ void require_that_value_format_is_correct() {
ApplicationId id1 = applicationId("foo");
ApplicationId id2 = applicationId("bar");
ApplicationId id3 = from("tenant", "baz", "bim");
@@ -58,7 +59,7 @@ public class ApplicationIdTest {
}
@Test
- public void require_string_formats_are_correct() {
+ void require_string_formats_are_correct() {
ApplicationId id1 = applicationId("foo");
ApplicationId id2 = from("bar", "baz", "default");
ApplicationId id3 = from("tenant", "baz", "bim");
@@ -71,38 +72,40 @@ public class ApplicationIdTest {
}
@Test
- public void require_that_idstring_can_be_parsed() {
+ void require_that_idstring_can_be_parsed() {
ApplicationId id = ApplicationId.fromSerializedForm("ten:foo:bim");
assertEquals("ten", id.tenant().value());
assertEquals("foo", id.application().value());
assertEquals("bim", id.instance().value());
}
- @Test(expected = IllegalArgumentException.class)
- public void require_that_invalid_idstring_throws_exception() {
- ApplicationId.fromSerializedForm("foo:baz");
+ @Test
+ void require_that_invalid_idstring_throws_exception() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ ApplicationId.fromSerializedForm("foo:baz");
+ });
}
@Test
- public void require_that_defaults_are_given() {
+ void require_that_defaults_are_given() {
ApplicationId id1 = applicationId("foo");
assertEquals("default", id1.tenant().value());
assertEquals("default", id1.instance().value());
}
@Test
- public void require_that_compare_to_is_correct() {
+ void require_that_compare_to_is_correct() {
new TotalOrderTester<ApplicationId>()
- .theseObjects(from("tenant1", "name1", "instance1"),
- from("tenant1", "name1", "instance1"))
- .areLessThan(from("tenant2", "name1", "instance1"))
- .areLessThan(from("tenant2", "name2", "instance1"))
- .areLessThan(from("tenant2", "name2", "instance2"))
- .testOrdering();
+ .theseObjects(from("tenant1", "name1", "instance1"),
+ from("tenant1", "name1", "instance1"))
+ .areLessThan(from("tenant2", "name1", "instance1"))
+ .areLessThan(from("tenant2", "name2", "instance1"))
+ .areLessThan(from("tenant2", "name2", "instance2"))
+ .testOrdering();
}
@Test
- public void require_that_instance_from_config_is_correct() {
+ void require_that_instance_from_config_is_correct() {
ApplicationIdConfig.Builder builder = new ApplicationIdConfig.Builder();
builder.tenant("a");
builder.application("b");
@@ -114,7 +117,7 @@ public class ApplicationIdTest {
}
@Test
- public void require_that_global_is_special() {
+ void require_that_global_is_special() {
assertEquals(global(), global());
assertNotEquals(global(), from("hosted-vespa", "routing", "default"));
assertEquals(global().serializedForm(), from("hosted-vespa", "routing", "default").serializedForm());
diff --git a/config-provisioning/src/test/java/com/yahoo/config/provision/CapacityTest.java b/config-provisioning/src/test/java/com/yahoo/config/provision/CapacityTest.java
index 706addc4298..a6ddb401b2f 100644
--- a/config-provisioning/src/test/java/com/yahoo/config/provision/CapacityTest.java
+++ b/config-provisioning/src/test/java/com/yahoo/config/provision/CapacityTest.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.config.provision;
-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
@@ -12,26 +12,26 @@ import static org.junit.Assert.fail;
public class CapacityTest {
@Test
- public void testCapacityValidation() {
+ void testCapacityValidation() {
// Equal min and max is allowed
- Capacity.from(new ClusterResources(4, 2, new NodeResources(1,2,3,4)),
- new ClusterResources(4, 2, new NodeResources(1,2,3,4)),
- false, true);
- assertValidationFailure(new ClusterResources(4, 2, new NodeResources(1,2,3,4)),
- new ClusterResources(2, 2, new NodeResources(1,2,3,4)));
- assertValidationFailure(new ClusterResources(4, 4, new NodeResources(1,2,3,4)),
- new ClusterResources(4, 2, new NodeResources(1,2,3,4)));
- assertValidationFailure(new ClusterResources(4, 2, new NodeResources(2,2,3,4)),
- new ClusterResources(4, 2, new NodeResources(1,2,3,4)));
- assertValidationFailure(new ClusterResources(4, 2, new NodeResources(1,3,3,4)),
- new ClusterResources(4, 2, new NodeResources(1,2,3,4)));
- assertValidationFailure(new ClusterResources(4, 2, new NodeResources(1,2,4,4)),
- new ClusterResources(4, 2, new NodeResources(1,2,3,4)));
- assertValidationFailure(new ClusterResources(4, 2, new NodeResources(1,2,3,5)),
- new ClusterResources(4, 2, new NodeResources(1,2,3,4)));
+ Capacity.from(new ClusterResources(4, 2, new NodeResources(1, 2, 3, 4)),
+ new ClusterResources(4, 2, new NodeResources(1, 2, 3, 4)),
+ false, true);
+ assertValidationFailure(new ClusterResources(4, 2, new NodeResources(1, 2, 3, 4)),
+ new ClusterResources(2, 2, new NodeResources(1, 2, 3, 4)));
+ assertValidationFailure(new ClusterResources(4, 4, new NodeResources(1, 2, 3, 4)),
+ new ClusterResources(4, 2, new NodeResources(1, 2, 3, 4)));
+ assertValidationFailure(new ClusterResources(4, 2, new NodeResources(2, 2, 3, 4)),
+ new ClusterResources(4, 2, new NodeResources(1, 2, 3, 4)));
+ assertValidationFailure(new ClusterResources(4, 2, new NodeResources(1, 3, 3, 4)),
+ new ClusterResources(4, 2, new NodeResources(1, 2, 3, 4)));
+ assertValidationFailure(new ClusterResources(4, 2, new NodeResources(1, 2, 4, 4)),
+ new ClusterResources(4, 2, new NodeResources(1, 2, 3, 4)));
+ assertValidationFailure(new ClusterResources(4, 2, new NodeResources(1, 2, 3, 5)),
+ new ClusterResources(4, 2, new NodeResources(1, 2, 3, 4)));
// It's enough than one dimension is smaller also when the others are larger
- assertValidationFailure(new ClusterResources(4, 2, new NodeResources(1,2,3,4)),
- new ClusterResources(8, 4, new NodeResources(2,1,6,8)));
+ assertValidationFailure(new ClusterResources(4, 2, new NodeResources(1, 2, 3, 4)),
+ new ClusterResources(8, 4, new NodeResources(2, 1, 6, 8)));
}
private void assertValidationFailure(ClusterResources min, ClusterResources max) {
diff --git a/config-provisioning/src/test/java/com/yahoo/config/provision/ClusterMembershipTest.java b/config-provisioning/src/test/java/com/yahoo/config/provision/ClusterMembershipTest.java
index 986609357aa..b1195b6a54b 100644
--- a/config-provisioning/src/test/java/com/yahoo/config/provision/ClusterMembershipTest.java
+++ b/config-provisioning/src/test/java/com/yahoo/config/provision/ClusterMembershipTest.java
@@ -2,13 +2,13 @@
package com.yahoo.config.provision;
import com.yahoo.component.Vtag;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author bratseth
@@ -16,13 +16,13 @@ import static org.junit.Assert.assertTrue;
public class ClusterMembershipTest {
@Test
- public void testContainerServiceInstance() {
+ void testContainerServiceInstance() {
ClusterSpec cluster = ClusterSpec.request(ClusterSpec.Type.container, ClusterSpec.Id.from("id1")).vespaVersion("6.42").build();
assertContainerService(ClusterMembership.from(cluster, 3));
}
@Test
- public void testSerializationWithOptionalParts() {
+ void testSerializationWithOptionalParts() {
{
ClusterMembership instance = ClusterMembership.from("container/id1/4/37/exclusive/retired", Vtag.currentVersion, Optional.empty());
ClusterMembership serialized = ClusterMembership.from(instance.stringValue(), Vtag.currentVersion, Optional.empty());
@@ -56,42 +56,42 @@ public class ClusterMembershipTest {
}
@Test
- public void testServiceInstance() {
+ void testServiceInstance() {
ClusterSpec cluster = ClusterSpec.request(ClusterSpec.Type.content, ClusterSpec.Id.from("id1")).vespaVersion("6.42").build();
assertContentService(ClusterMembership.from(cluster, 37));
}
@Test
- public void testServiceInstanceWithGroup() {
+ void testServiceInstanceWithGroup() {
ClusterSpec cluster = ClusterSpec.specification(ClusterSpec.Type.content, ClusterSpec.Id.from("id1"))
- .group(ClusterSpec.Group.from(4))
- .vespaVersion("6.42")
- .build();
+ .group(ClusterSpec.Group.from(4))
+ .vespaVersion("6.42")
+ .build();
assertContentServiceWithGroup(ClusterMembership.from(cluster, 37));
}
@Test
- public void testServiceInstanceWithGroupFromString() {
+ void testServiceInstanceWithGroupFromString() {
assertContentServiceWithGroup(ClusterMembership.from("content/id1/4/37/stateful", Vtag.currentVersion, Optional.empty()));
}
@Test
- public void testServiceInstanceWithRetire() {
+ void testServiceInstanceWithRetire() {
ClusterSpec cluster = ClusterSpec.request(ClusterSpec.Type.content, ClusterSpec.Id.from("id1")).vespaVersion("6.42").build();
assertContentServiceWithRetire(ClusterMembership.retiredFrom(cluster, 37));
}
@Test
- public void testServiceInstanceWithGroupAndRetire() {
+ void testServiceInstanceWithGroupAndRetire() {
ClusterSpec cluster = ClusterSpec.specification(ClusterSpec.Type.content, ClusterSpec.Id.from("id1"))
- .group(ClusterSpec.Group.from(4))
- .vespaVersion("6.42")
- .build();
+ .group(ClusterSpec.Group.from(4))
+ .vespaVersion("6.42")
+ .build();
assertContentServiceWithGroupAndRetire(ClusterMembership.retiredFrom(cluster, 37));
}
@Test
- public void testServiceInstanceWithGroupAndRetireFromString() {
+ void testServiceInstanceWithGroupAndRetireFromString() {
assertContentServiceWithGroupAndRetire(ClusterMembership.from("content/id1/4/37/retired/stateful", Vtag.currentVersion, Optional.empty()));
}
diff --git a/config-provisioning/src/test/java/com/yahoo/config/provision/ClusterResourcesTest.java b/config-provisioning/src/test/java/com/yahoo/config/provision/ClusterResourcesTest.java
index cbca931e4d0..06b5dd472d6 100644
--- a/config-provisioning/src/test/java/com/yahoo/config/provision/ClusterResourcesTest.java
+++ b/config-provisioning/src/test/java/com/yahoo/config/provision/ClusterResourcesTest.java
@@ -1,9 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.provision;
-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 bratseth
@@ -11,7 +11,7 @@ import static org.junit.Assert.assertEquals;
public class ClusterResourcesTest {
@Test
- public void testCost() {
+ void testCost() {
ClusterResources r1 = new ClusterResources(3, 1, new NodeResources(2, 8, 50, 1));
ClusterResources r2 = new ClusterResources(3, 1, new NodeResources(2, 16, 50, 1));
assertEquals(2.232, r1.cost() + r2.cost(), 0.01);
diff --git a/config-provisioning/src/test/java/com/yahoo/config/provision/ClusterSpecTest.java b/config-provisioning/src/test/java/com/yahoo/config/provision/ClusterSpecTest.java
index dc228ee7fd2..21118266ce0 100644
--- a/config-provisioning/src/test/java/com/yahoo/config/provision/ClusterSpecTest.java
+++ b/config-provisioning/src/test/java/com/yahoo/config/provision/ClusterSpecTest.java
@@ -4,7 +4,7 @@ package com.yahoo.config.provision;
import com.yahoo.component.Version;
import com.yahoo.config.provision.ClusterSpec.Group;
import com.yahoo.config.provision.ClusterSpec.Id;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.HashSet;
import java.util.List;
@@ -12,7 +12,7 @@ import java.util.Map;
import java.util.Optional;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Ulf Lilleengen
@@ -20,32 +20,32 @@ import static org.junit.Assert.assertEquals;
public class ClusterSpecTest {
@Test
- public void testIdEquals() {
+ void testIdEquals() {
assertEquals(Set.of(Id.from("id1"), Id.from("id2"), Id.from("id3")),
- new HashSet<>(List.of(Id.from("id1"), Id.from("id1"), Id.from("id2"), Id.from("id3"))));
+ new HashSet<>(List.of(Id.from("id1"), Id.from("id1"), Id.from("id2"), Id.from("id3"))));
}
@Test
- public void testGroupEquals() {
+ void testGroupEquals() {
assertEquals(Set.of(Group.from(1), Group.from(2), Group.from(3)),
- new HashSet<>(List.of(Group.from(1), Group.from(1), Group.from(2), Group.from(3))));
+ new HashSet<>(List.of(Group.from(1), Group.from(1), Group.from(2), Group.from(3))));
}
@Test
- public void testSatisfies() {
+ void testSatisfies() {
var tests = Map.of(
- List.of(spec(ClusterSpec.Type.content, "id1"), spec(ClusterSpec.Type.content, "id2")), false,
- List.of(spec(ClusterSpec.Type.admin, "id1"), spec(ClusterSpec.Type.container, "id1")), false,
- List.of(spec(ClusterSpec.Type.admin, "id1"), spec(ClusterSpec.Type.content, "id1")), false,
- List.of(spec(ClusterSpec.Type.combined, "id1"), spec(ClusterSpec.Type.container, "id1")), false,
- List.of(spec(ClusterSpec.Type.combined, "id1"), spec(ClusterSpec.Type.content, "id1")), true,
- List.of(spec(ClusterSpec.Type.content, "id1"), spec(ClusterSpec.Type.content, "id1")), true
+ List.of(spec(ClusterSpec.Type.content, "id1"), spec(ClusterSpec.Type.content, "id2")), false,
+ List.of(spec(ClusterSpec.Type.admin, "id1"), spec(ClusterSpec.Type.container, "id1")), false,
+ List.of(spec(ClusterSpec.Type.admin, "id1"), spec(ClusterSpec.Type.content, "id1")), false,
+ List.of(spec(ClusterSpec.Type.combined, "id1"), spec(ClusterSpec.Type.container, "id1")), false,
+ List.of(spec(ClusterSpec.Type.combined, "id1"), spec(ClusterSpec.Type.content, "id1")), true,
+ List.of(spec(ClusterSpec.Type.content, "id1"), spec(ClusterSpec.Type.content, "id1")), true
);
tests.forEach((specs, satisfies) -> {
var s1 = specs.get(0);
var s2 = specs.get(1);
- assertEquals(s1 + (satisfies ? " satisfies " : " does not satisfy ") + s2, satisfies, s1.satisfies(s2));
- assertEquals(s2 + (satisfies ? " satisfies " : " does not satisfy ") + s1, satisfies, s2.satisfies(s1));
+ assertEquals(satisfies, s1.satisfies(s2), s1 + (satisfies ? " satisfies " : " does not satisfy ") + s2);
+ assertEquals(satisfies, s2.satisfies(s1), s2 + (satisfies ? " satisfies " : " does not satisfy ") + s1);
});
}
diff --git a/config-provisioning/src/test/java/com/yahoo/config/provision/DockerImageTest.java b/config-provisioning/src/test/java/com/yahoo/config/provision/DockerImageTest.java
index 2e0de192f03..36cc83f91b6 100644
--- a/config-provisioning/src/test/java/com/yahoo/config/provision/DockerImageTest.java
+++ b/config-provisioning/src/test/java/com/yahoo/config/provision/DockerImageTest.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.config.provision;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import java.util.Optional;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThrows;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author mpolden
@@ -17,42 +17,42 @@ import static org.junit.Assert.fail;
public class DockerImageTest {
@Test
- public void parse() {
+ void parse() {
Map<String, DockerImage> tests = Map.of(
- "", DockerImage.EMPTY,
- "registry.example.com:9999/vespa/vespa:7.42", new DockerImage("registry.example.com:9999", "vespa/vespa", Optional.of("7.42")),
- "registry.example.com/vespa/vespa:7.42", new DockerImage("registry.example.com", "vespa/vespa", Optional.of("7.42")),
- "registry.example.com:9999/vespa/vespa", new DockerImage("registry.example.com:9999", "vespa/vespa", Optional.empty()),
- "registry.example.com/vespa/vespa", new DockerImage("registry.example.com", "vespa/vespa", Optional.empty()),
- "registry.example.com/project/repo/vespa/vespa", new DockerImage("registry.example.com/project/repo", "vespa/vespa", Optional.empty())
+ "", DockerImage.EMPTY,
+ "registry.example.com:9999/vespa/vespa:7.42", new DockerImage("registry.example.com:9999", "vespa/vespa", Optional.of("7.42")),
+ "registry.example.com/vespa/vespa:7.42", new DockerImage("registry.example.com", "vespa/vespa", Optional.of("7.42")),
+ "registry.example.com:9999/vespa/vespa", new DockerImage("registry.example.com:9999", "vespa/vespa", Optional.empty()),
+ "registry.example.com/vespa/vespa", new DockerImage("registry.example.com", "vespa/vespa", Optional.empty()),
+ "registry.example.com/project/repo/vespa/vespa", new DockerImage("registry.example.com/project/repo", "vespa/vespa", Optional.empty())
);
tests.forEach((value, expected) -> {
DockerImage parsed = DockerImage.fromString(value);
assertEquals(value, parsed.asString());
String untagged = expected.equals(DockerImage.EMPTY)
- ? ""
- : expected.registry() + "/" + expected.repository();
+ ? ""
+ : expected.registry() + "/" + expected.repository();
assertEquals(untagged, parsed.untagged());
});
}
@Test
- public void registry_cannot_contain_slash() {
+ void registry_cannot_contain_slash() {
DockerImage image = DockerImage.fromString("registry.example.com/vespa/vespa");
assertThrows(IllegalArgumentException.class, () -> image.withRegistry(""));
assertThrows(IllegalArgumentException.class, () -> image.withRegistry("my-registry/path/"));
}
@Test
- public void parse_invalid() {
+ void parse_invalid() {
List<String> tests = List.of(
- "registry.example.com",
- "registry.example.com/",
- "registry.example.com/repository",
- "registry.example.com/repository:",
- "foo",
- "foo:1.2.3"
+ "registry.example.com",
+ "registry.example.com/",
+ "registry.example.com/repository",
+ "registry.example.com/repository:",
+ "foo",
+ "foo:1.2.3"
);
for (var value : tests) {
try {
diff --git a/config-provisioning/src/test/java/com/yahoo/config/provision/HostFilterTest.java b/config-provisioning/src/test/java/com/yahoo/config/provision/HostFilterTest.java
index b0ce1b3b8cb..e8ad99ff0d3 100644
--- a/config-provisioning/src/test/java/com/yahoo/config/provision/HostFilterTest.java
+++ b/config-provisioning/src/test/java/com/yahoo/config/provision/HostFilterTest.java
@@ -2,13 +2,13 @@
package com.yahoo.config.provision;
import com.yahoo.component.Vtag;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.Optional;
-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
@@ -16,7 +16,7 @@ import static org.junit.Assert.assertTrue;
public class HostFilterTest {
@Test
- public void testSingleConditionFilter() {
+ void testSingleConditionFilter() {
HostFilter all = HostFilter.all();
HostFilter hostname = HostFilter.hostname("host1");
HostFilter type = HostFilter.clusterType(ClusterSpec.Type.content);
@@ -33,22 +33,22 @@ public class HostFilterTest {
assertFalse( id.matches("anyhost", "flavor", membership("content/anytype/0/0/stateful")));
assertTrue( all.matches("host1", "flavor", membership("content/anytype/0/0/stateful")));
- assertTrue( hostname.matches("host1", "flavor", membership("content/anytype/0/0/stateful")));
+ assertTrue(hostname.matches("host1", "flavor", membership("content/anytype/0/0/stateful")));
assertTrue( type.matches("host1", "flavor", membership("content/anytype/0/0/stateful")));
assertFalse( id.matches("host1", "flavor", membership("content/anytype/0/0/stateful")));
assertTrue( all.matches("host1", "flavor", membership("content/type1/0/0/stateful")));
- assertTrue( hostname.matches("host1", "flavor", membership("content/type1/0/0/stateful")));
+ assertTrue(hostname.matches("host1", "flavor", membership("content/type1/0/0/stateful")));
assertTrue( type.matches("host1", "flavor", membership("content/type1/0/0/stateful")));
assertTrue( id.matches("host1", "flavor", membership("content/type1/0/0/stateful")));
}
@Test
- public void testMultiConditionFilter() {
+ void testMultiConditionFilter() {
HostFilter typeAndId = HostFilter.from(Collections.emptyList(),
- Collections.emptyList(),
- Collections.singletonList(ClusterSpec.Type.content),
- Collections.singletonList(ClusterSpec.Id.from("type1")));
+ Collections.emptyList(),
+ Collections.singletonList(ClusterSpec.Type.content),
+ Collections.singletonList(ClusterSpec.Id.from("type1")));
assertFalse(typeAndId.matches("anyhost", "flavor", membership("content/anyType/0/0/stateful")));
assertFalse(typeAndId.matches("anyhost", "flavor", membership("container/type1/0/0")));
@@ -56,7 +56,7 @@ public class HostFilterTest {
}
@Test
- public void testMultiConditionFilterFromStrings() {
+ void testMultiConditionFilterFromStrings() {
HostFilter typeAndId = HostFilter.from("host1 host2, host3,host4", " , ,flavor", null, "type1 ");
assertFalse(typeAndId.matches("anotherhost", "flavor", membership("content/type1/0/0/stateful")));
diff --git a/config-provisioning/src/test/java/com/yahoo/config/provision/HostNameTest.java b/config-provisioning/src/test/java/com/yahoo/config/provision/HostNameTest.java
index da01920cc57..fe42e71682b 100644
--- a/config-provisioning/src/test/java/com/yahoo/config/provision/HostNameTest.java
+++ b/config-provisioning/src/test/java/com/yahoo/config/provision/HostNameTest.java
@@ -1,9 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.provision;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* @author jonmv
@@ -11,7 +11,7 @@ import static org.junit.Assert.assertThrows;
public class HostNameTest {
@Test
- public void testNames() {
+ void testNames() {
HostName.of("name-123.0.321-eman");
HostName.of(("." + "a".repeat(32)).repeat(2).substring(1, 65));
HostName.of("123");
diff --git a/config-provisioning/src/test/java/com/yahoo/config/provision/IdentifierTestBase.java b/config-provisioning/src/test/java/com/yahoo/config/provision/IdentifierTestBase.java
index fd1a9401b81..1fd4c2e06ce 100644
--- a/config-provisioning/src/test/java/com/yahoo/config/provision/IdentifierTestBase.java
+++ b/config-provisioning/src/test/java/com/yahoo/config/provision/IdentifierTestBase.java
@@ -1,16 +1,16 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.provision;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Generic test for identifiers such as {@link Environment} and {@link RegionName}.
@@ -23,7 +23,7 @@ public abstract class IdentifierTestBase<ID_TYPE> {
protected abstract boolean isDefault(ID_TYPE instance);
@Test
- public void testDefault() {
+ void testDefault() {
ID_TYPE def = createDefaultInstance();
ID_TYPE def2 = createInstance("default");
ID_TYPE notdef = createInstance("default2");
@@ -35,9 +35,9 @@ public abstract class IdentifierTestBase<ID_TYPE> {
}
@Test
- public void testEquals() {
+ void testEquals() {
assertEquals(Set.of(createInstance("foo"), createInstance("bar"), createInstance("baz")),
- new HashSet<>(List.of(createInstance("foo"), createInstance("foo"), createInstance("bar"), createInstance("baz"))));
+ new HashSet<>(List.of(createInstance("foo"), createInstance("foo"), createInstance("bar"), createInstance("baz"))));
}
}
diff --git a/config-provisioning/src/test/java/com/yahoo/config/provision/NodeFlavorsTest.java b/config-provisioning/src/test/java/com/yahoo/config/provision/NodeFlavorsTest.java
index 8c2a6b70cf5..5ab6aa64516 100644
--- a/config-provisioning/src/test/java/com/yahoo/config/provision/NodeFlavorsTest.java
+++ b/config-provisioning/src/test/java/com/yahoo/config/provision/NodeFlavorsTest.java
@@ -2,19 +2,19 @@
package com.yahoo.config.provision;
import com.yahoo.config.provisioning.FlavorsConfig;
-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.jupiter.api.Assertions.assertEquals;
public class NodeFlavorsTest {
private static final double delta = 0.00001;
@Test
- public void testConfigParsing() {
+ void testConfigParsing() {
FlavorsConfig.Builder builder = new FlavorsConfig.Builder();
List<FlavorsConfig.Flavor.Builder> flavorBuilderList = new ArrayList<>();
{
@@ -35,7 +35,7 @@ public class NodeFlavorsTest {
Flavor banana = nodeFlavors.getFlavor("banana").get();
assertEquals(3, banana.cost());
assertEquals(13, banana.resources().vcpu(), delta);
- assertEquals("10 * 1.3", 13, banana.resources().vcpu(), delta);
+ assertEquals(13, banana.resources().vcpu(), delta, "10 * 1.3");
}
}
diff --git a/config-provisioning/src/test/java/com/yahoo/config/provision/NodeResourcesTest.java b/config-provisioning/src/test/java/com/yahoo/config/provision/NodeResourcesTest.java
index 564c53eeff0..35c7bfd35ec 100644
--- a/config-provisioning/src/test/java/com/yahoo/config/provision/NodeResourcesTest.java
+++ b/config-provisioning/src/test/java/com/yahoo/config/provision/NodeResourcesTest.java
@@ -1,12 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.provision;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.function.Supplier;
-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,17 +14,17 @@ import static org.junit.Assert.fail;
public class NodeResourcesTest {
@Test
- public void testToString() {
+ void testToString() {
assertEquals("[vcpu: 1.0, memory: 10.0 Gb, disk 100.0 Gb, architecture: x86_64]",
- new NodeResources(1., 10., 100., 0).toString());
+ new NodeResources(1., 10., 100., 0).toString());
assertEquals("[vcpu: 0.3, memory: 3.3 Gb, disk 33.3 Gb, bandwidth: 0.3 Gbps, architecture: x86_64]",
- new NodeResources(1/3., 10/3., 100/3., 0.3).toString());
+ new NodeResources(1 / 3., 10 / 3., 100 / 3., 0.3).toString());
assertEquals("[vcpu: 0.7, memory: 9.0 Gb, disk 66.7 Gb, bandwidth: 0.7 Gbps, architecture: x86_64]",
- new NodeResources(2/3., 8.97, 200/3., 0.67).toString());
+ new NodeResources(2 / 3., 8.97, 200 / 3., 0.67).toString());
}
@Test
- public void testInvalid() {
+ void testInvalid() {
assertInvalid("vcpu", () -> new NodeResources(Double.NaN, 1.0, 1.0, 1.0));
assertInvalid("memory", () -> new NodeResources(1.0, Double.NaN, 1.0, 1.0));
assertInvalid("disk", () -> new NodeResources(1.0, 1.0, Double.NaN, 1.0));
@@ -32,17 +32,17 @@ public class NodeResourcesTest {
}
@Test
- public void benchmark() {
+ void benchmark() {
NodeResources [] resouces = new NodeResources[100];
for (int i = 0; i < resouces.length; i++) {
- resouces[i] = new NodeResources(1/3., 10/3., 100/3., 0.3);
+ resouces[i] = new NodeResources(1 / 3., 10 / 3., 100 / 3., 0.3);
}
int NUM_ITER = 100; // Use at least 100000 for proper benchmarking
long warmup = runTest(resouces, NUM_ITER);
long start = System.nanoTime();
long benchmark = runTest(resouces, NUM_ITER);
long duration = System.nanoTime() - start;
- System.out.println("NodeResources.toString() took " + duration/1000000 + " ms");
+ System.out.println("NodeResources.toString() took " + duration / 1000000 + " ms");
assertEquals(warmup, benchmark);
}
diff --git a/config-provisioning/src/test/java/com/yahoo/config/provision/SystemNameTest.java b/config-provisioning/src/test/java/com/yahoo/config/provision/SystemNameTest.java
index beb28241963..f0656f84a07 100644
--- a/config-provisioning/src/test/java/com/yahoo/config/provision/SystemNameTest.java
+++ b/config-provisioning/src/test/java/com/yahoo/config/provision/SystemNameTest.java
@@ -1,25 +1,25 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.provision;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author hakonhall
*/
public class SystemNameTest {
@Test
- public void test() {
+ void test() {
for (SystemName name : SystemName.values()) {
assertEquals(name, SystemName.from(name.value()));
}
}
@Test
- public void allOf() {
+ void allOf() {
assertEquals(Set.of(SystemName.cd, SystemName.PublicCd), SystemName.allOf(SystemName::isCd));
assertEquals(Set.of(SystemName.PublicCd, SystemName.Public), SystemName.allOf(SystemName::isPublic));
}
diff --git a/config-provisioning/src/test/java/com/yahoo/config/provision/TenantTest.java b/config-provisioning/src/test/java/com/yahoo/config/provision/TenantTest.java
index 2bfcd183c85..a68ea952475 100644
--- a/config-provisioning/src/test/java/com/yahoo/config/provision/TenantTest.java
+++ b/config-provisioning/src/test/java/com/yahoo/config/provision/TenantTest.java
@@ -2,9 +2,9 @@
package com.yahoo.config.provision;
import com.yahoo.test.TotalOrderTester;
-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 Ulf Lilleengen
@@ -27,12 +27,12 @@ public class TenantTest extends IdentifierTestBase<TenantName> {
}
@Test
- public void testComparator() {
+ void testComparator() {
assertEquals(0, TenantName.defaultName().compareTo(TenantName.defaultName()));
new TotalOrderTester<TenantName>()
- .theseObjects(TenantName.from("a"), TenantName.from("a"))
- .areLessThan(TenantName.from("b"))
- .testOrdering();
+ .theseObjects(TenantName.from("a"), TenantName.from("a"))
+ .areLessThan(TenantName.from("b"))
+ .testOrdering();
}
}
diff --git a/config-provisioning/src/test/java/com/yahoo/config/provision/ZoneIdTest.java b/config-provisioning/src/test/java/com/yahoo/config/provision/ZoneIdTest.java
index ae61be8f2e9..4fd1b1bbc26 100644
--- a/config-provisioning/src/test/java/com/yahoo/config/provision/ZoneIdTest.java
+++ b/config-provisioning/src/test/java/com/yahoo/config/provision/ZoneIdTest.java
@@ -2,10 +2,10 @@
package com.yahoo.config.provision;
import com.yahoo.config.provision.zone.ZoneId;
-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 hmusum
@@ -16,14 +16,14 @@ public class ZoneIdTest {
private static final RegionName region = RegionName.from("moon-dark-side-1");
@Test
- public void testCreatingZoneId() {
+ void testCreatingZoneId() {
ZoneId zoneId = ZoneId.from(environment, region);
assertEquals(region, zoneId.region());
assertEquals(environment, zoneId.environment());
}
@Test
- public void testSerializingAndDeserializing() {
+ void testSerializingAndDeserializing() {
ZoneId zoneId = ZoneId.from(environment, region);
assertEquals(environment.value() + "." + region.value(), zoneId.value());
assertEquals(ZoneId.from(zoneId.value()), zoneId);
diff --git a/config-provisioning/src/test/java/com/yahoo/config/provision/serialization/AllocatedHostsSerializerTest.java b/config-provisioning/src/test/java/com/yahoo/config/provision/serialization/AllocatedHostsSerializerTest.java
index ed87ff9f555..fec8be59c50 100644
--- a/config-provisioning/src/test/java/com/yahoo/config/provision/serialization/AllocatedHostsSerializerTest.java
+++ b/config-provisioning/src/test/java/com/yahoo/config/provision/serialization/AllocatedHostsSerializerTest.java
@@ -8,7 +8,7 @@ import com.yahoo.config.provision.DockerImage;
import com.yahoo.config.provision.HostSpec;
import com.yahoo.config.provision.NetworkPorts;
import com.yahoo.config.provision.NodeResources;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.LinkedHashSet;
@@ -18,7 +18,7 @@ import java.util.Set;
import static com.yahoo.config.provision.serialization.AllocatedHostsSerializer.fromJson;
import static com.yahoo.config.provision.serialization.AllocatedHostsSerializer.toJson;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bratseth
@@ -31,7 +31,7 @@ public class AllocatedHostsSerializerTest {
private static final NodeResources arm64Node = new NodeResources(0.5, 3.1, 4, 1, NodeResources.DiskSpeed.any, NodeResources.StorageType.any, NodeResources.Architecture.arm64);
@Test
- public void testAllocatedHostsSerialization() throws IOException {
+ void testAllocatedHostsSerialization() throws IOException {
Set<HostSpec> hosts = new LinkedHashSet<>();
hosts.add(new HostSpec("empty", List.of(), Optional.empty()));
hosts.add(new HostSpec("with-aliases", List.of("alias1", "alias2"), Optional.empty()));
@@ -69,7 +69,7 @@ public class AllocatedHostsSerializerTest {
Optional.empty()),
Optional.empty(),
Optional.of(new NetworkPorts(List.of(new NetworkPorts.Allocation(1234, "service1", "configId1", "suffix1"),
- new NetworkPorts.Allocation(4567, "service2", "configId2", "suffix2")))),
+ new NetworkPorts.Allocation(4567, "service2", "configId2", "suffix2")))),
Optional.empty()));
hosts.add(new HostSpec("arm64",
arm64Node,
@@ -79,7 +79,7 @@ public class AllocatedHostsSerializerTest {
Optional.empty()),
Optional.empty(),
Optional.of(new NetworkPorts(List.of(new NetworkPorts.Allocation(1234, "service1", "configId1", "suffix1"),
- new NetworkPorts.Allocation(4567, "service2", "configId2", "suffix2")))),
+ new NetworkPorts.Allocation(4567, "service2", "configId2", "suffix2")))),
Optional.empty()));
assertAllocatedHosts(AllocatedHosts.withHosts(hosts));
diff --git a/config-proxy/pom.xml b/config-proxy/pom.xml
index b28714925ee..476f5f99b86 100644
--- a/config-proxy/pom.xml
+++ b/config-proxy/pom.xml
@@ -14,11 +14,6 @@
<version>8-SNAPSHOT</version>
<dependencies>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>com.yahoo.vespa</groupId>
<artifactId>config-lib</artifactId>
<version>${project.version}</version>
@@ -59,9 +54,19 @@
<scope>compile</scope>
</dependency>
<dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-api</artifactId>
- <scope>compile</scope>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ <scope>compile</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
</dependency>
<dependency>
<groupId>com.yahoo.vespa</groupId>
diff --git a/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/ConfigProxyRpcServerTest.java b/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/ConfigProxyRpcServerTest.java
index f743c0ed231..a946704234d 100644
--- a/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/ConfigProxyRpcServerTest.java
+++ b/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/ConfigProxyRpcServerTest.java
@@ -11,17 +11,17 @@ import com.yahoo.jrt.Supervisor;
import com.yahoo.jrt.Target;
import com.yahoo.jrt.Transport;
import com.yahoo.vespa.config.RawConfig;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import java.io.File;
import java.io.IOException;
import java.time.Duration;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
/**
* @author hmusum
@@ -34,16 +34,16 @@ public class ConfigProxyRpcServerTest {
private static TestServer server;
private static TestClient client;
- @Rule
- public TemporaryFolder temporaryFolder = new TemporaryFolder();
+ @TempDir
+ public File temporaryFolder;
- @BeforeClass
+ @BeforeAll
public static void setup() throws ListenFailedException {
server = new TestServer();
client = new TestClient(server.listenPort());
}
- @AfterClass
+ @AfterAll
public static void teardown() {
client.close();
server.close();
@@ -55,7 +55,7 @@ public class ConfigProxyRpcServerTest {
}
@Test
- public void basic() {
+ void basic() {
ProxyServer proxy = createTestServer(new MockConfigSource());
Spec spec = new Spec("localhost", 12345);
ConfigProxyRpcServer server = new ConfigProxyRpcServer(proxy, new Supervisor(new Transport()), spec);
@@ -66,11 +66,11 @@ public class ConfigProxyRpcServerTest {
* Tests ping RPC command
*/
@Test
- public void testRpcMethodPing() {
+ void testRpcMethodPing() {
Request req = new Request("ping");
client.invoke(req);
- assertFalse(req.errorMessage(), req.isError());
+ assertFalse(req.isError(), req.errorMessage());
assertEquals(1, req.returnValues().size());
assertEquals(0, req.returnValues().get(0).asInt32());
}
@@ -79,13 +79,13 @@ public class ConfigProxyRpcServerTest {
* Tests listCachedConfig RPC command
*/
@Test
- public void testRpcMethodListCachedConfig() throws ListenFailedException {
+ void testRpcMethodListCachedConfig() throws ListenFailedException {
reset();
Request req = new Request("listCachedConfig");
client.invoke(req);
- assertFalse(req.errorMessage(), req.isError());
+ assertFalse(req.isError(), req.errorMessage());
String[] ret = req.returnValues().get(0).asStringArray();
assertEquals(1, req.returnValues().size());
assertEquals(0, ret.length);
@@ -94,24 +94,24 @@ public class ConfigProxyRpcServerTest {
server.proxyServer().memoryCache().update(config);
req = new Request("listCachedConfig");
client.invoke(req);
- assertFalse(req.errorMessage(), req.isError());
+ assertFalse(req.isError(), req.errorMessage());
assertEquals(1, req.returnValues().size());
ret = req.returnValues().get(0).asStringArray();
assertEquals(1, ret.length);
assertEquals(config.getNamespace() + "." + config.getName() + "," + config.getConfigId() + "," +
- config.getGeneration() + "," + config.getPayloadChecksums(),
- ret[0]);
+ config.getGeneration() + "," + config.getPayloadChecksums(),
+ ret[0]);
}
/**
* Tests listCachedConfig RPC command
*/
@Test
- public void testRpcMethodListCachedConfigFull() {
+ void testRpcMethodListCachedConfigFull() {
Request req = new Request("listCachedConfigFull");
client.invoke(req);
- assertFalse(req.errorMessage(), req.isError());
+ assertFalse(req.isError(), req.errorMessage());
assertEquals(1, req.returnValues().size());
String[] ret = req.returnValues().get(0).asStringArray();
assertEquals(0, ret.length);
@@ -120,25 +120,25 @@ public class ConfigProxyRpcServerTest {
server.proxyServer().memoryCache().update(config);
req = new Request("listCachedConfigFull");
client.invoke(req);
- assertFalse(req.errorMessage(), req.isError());
+ assertFalse(req.isError(), req.errorMessage());
ret = req.returnValues().get(0).asStringArray();
assertEquals(1, ret.length);
assertEquals(config.getNamespace() + "." + config.getName() + "," + config.getConfigId() + "," +
- config.getGeneration() + "," + config.getPayloadChecksums() + "," + config.getPayload().getData(),
- ret[0]);
+ config.getGeneration() + "," + config.getPayloadChecksums() + "," + config.getPayload().getData(),
+ ret[0]);
}
/**
* Tests listSourceConnections RPC command
*/
@Test
- public void testRpcMethodListSourceConnections() throws ListenFailedException {
+ void testRpcMethodListSourceConnections() throws ListenFailedException {
reset();
Request req = new Request("listSourceConnections");
client.invoke(req);
- assertFalse(req.errorMessage(), req.isError());
+ assertFalse(req.isError(), req.errorMessage());
assertEquals(1, req.returnValues().size());
final String[] ret = req.returnValues().get(0).asStringArray();
assertEquals(2, ret.length);
@@ -150,11 +150,11 @@ public class ConfigProxyRpcServerTest {
* Tests invalidateCache RPC command
*/
@Test
- public void testRpcMethodInvalidateCache() {
+ void testRpcMethodInvalidateCache() {
Request req = new Request("invalidateCache");
client.invoke(req);
- assertFalse(req.errorMessage(), req.isError());
+ assertFalse(req.isError(), req.errorMessage());
assertEquals(1, req.returnValues().size());
final String[] ret = req.returnValues().get(0).asStringArray();
assertEquals(2, ret.length);
@@ -166,10 +166,10 @@ public class ConfigProxyRpcServerTest {
* Tests getMode and setMode RPC commands
*/
@Test
- public void testRpcMethodGetModeAndSetMode() {
+ void testRpcMethodGetModeAndSetMode() {
Request req = new Request("getMode");
client.invoke(req);
- assertFalse(req.errorMessage(), req.isError());
+ assertFalse(req.isError(), req.errorMessage());
assertEquals(1, req.returnValues().size());
assertEquals("default", req.returnValues().get(0).asString());
@@ -177,7 +177,7 @@ public class ConfigProxyRpcServerTest {
String mode = "memorycache";
req.parameters().add(new StringValue(mode));
client.invoke(req);
- assertFalse(req.errorMessage(), req.isError());
+ assertFalse(req.isError(), req.errorMessage());
assertEquals(1, req.returnValues().size());
String[] ret = req.returnValues().get(0).asStringArray();
assertEquals(2, ret.length);
@@ -187,7 +187,7 @@ public class ConfigProxyRpcServerTest {
req = new Request("getMode");
client.invoke(req);
- assertFalse(req.errorMessage(), req.isError());
+ assertFalse(req.isError(), req.errorMessage());
assertEquals(1, req.returnValues().size());
assertEquals(mode, req.returnValues().get(0).asString());
@@ -197,7 +197,7 @@ public class ConfigProxyRpcServerTest {
req.parameters().add(new StringValue(mode));
client.invoke(req);
- assertFalse(req.errorMessage(), req.isError());
+ assertFalse(req.isError(), req.errorMessage());
ret = req.returnValues().get(0).asStringArray();
assertEquals(2, ret.length);
assertEquals("1", ret[0]);
@@ -209,7 +209,7 @@ public class ConfigProxyRpcServerTest {
* Tests updateSources RPC command
*/
@Test
- public void testRpcMethodUpdateSources() throws ListenFailedException {
+ void testRpcMethodUpdateSources() throws ListenFailedException {
reset();
Request req = new Request("updateSources");
@@ -217,7 +217,7 @@ public class ConfigProxyRpcServerTest {
String spec2 = "tcp/b:19070";
req.parameters().add(new StringValue(spec1 + "," + spec2));
client.invoke(req);
- assertFalse(req.errorMessage(), req.isError());
+ assertFalse(req.isError(), req.errorMessage());
assertEquals(1, req.returnValues().size());
assertEquals("Updated config sources to: " + spec1 + "," + spec2, req.returnValues().get(0).asString());
@@ -227,7 +227,7 @@ public class ConfigProxyRpcServerTest {
req = new Request("updateSources");
req.parameters().add(new StringValue(spec1 + "," + spec2));
client.invoke(req);
- assertFalse(req.errorMessage(), req.isError());
+ assertFalse(req.isError(), req.errorMessage());
assertEquals(1, req.returnValues().size());
assertEquals("Cannot update sources when in '" + Mode.ModeName.MEMORYCACHE.name().toLowerCase() + "' mode", req.returnValues().get(0).asString());
@@ -246,12 +246,12 @@ public class ConfigProxyRpcServerTest {
* Tests dumpCache RPC command
*/
@Test
- public void testRpcMethodDumpCache() throws IOException {
+ void testRpcMethodDumpCache() throws IOException {
Request req = new Request("dumpCache");
- String path = temporaryFolder.newFolder().getAbsolutePath();
+ String path = temporaryFolder.getAbsolutePath();
req.parameters().add(new StringValue(path));
client.invoke(req);
- assertFalse(req.errorMessage(), req.isError());
+ assertFalse(req.isError(), req.errorMessage());
assertEquals(1, req.returnValues().size());
assertEquals("success", req.returnValues().get(0).asString());
}
@@ -287,6 +287,15 @@ public class ConfigProxyRpcServerTest {
supervisor.transport().shutdown().join();
rpcServer.shutdown();
}
+
+ 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;
+ }
}
private static class TestClient implements AutoCloseable {
@@ -308,5 +317,23 @@ public class ConfigProxyRpcServerTest {
target.close();
supervisor.transport().shutdown().join();
}
+
+ 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;
+ }
+ }
+
+ 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-proxy/src/test/java/com/yahoo/vespa/config/proxy/DelayedResponseHandlerTest.java b/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/DelayedResponseHandlerTest.java
index 8a668b34fd0..7fbd6b2e68f 100644
--- a/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/DelayedResponseHandlerTest.java
+++ b/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/DelayedResponseHandlerTest.java
@@ -1,12 +1,13 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.config.proxy;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
-import static org.junit.Assert.assertEquals;
+import java.io.File;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author hmusum
@@ -15,17 +16,17 @@ public class DelayedResponseHandlerTest {
private final MockConfigSource source = new MockConfigSource();
- @Rule
- public TemporaryFolder temporaryFolder = new TemporaryFolder();
+ @TempDir
+ public File temporaryFolder;
- @Before
+ @BeforeEach
public void setup() {
source.clear();
source.put(ProxyServerTest.fooConfig.getKey(), ProxyServerTest.createConfigWithNextConfigGeneration(ProxyServerTest.fooConfig, 0));
}
@Test
- public void basic() {
+ void basic() {
ConfigTester tester = new ConfigTester();
DelayedResponses delayedResponses = new DelayedResponses();
MemoryCache memoryCache = new MemoryCache();
diff --git a/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/DelayedResponseTest.java b/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/DelayedResponseTest.java
index d8c03961ddb..6bb9f74105c 100644
--- a/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/DelayedResponseTest.java
+++ b/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/DelayedResponseTest.java
@@ -2,13 +2,13 @@
package com.yahoo.vespa.config.proxy;
import com.yahoo.vespa.config.protocol.JRTServerConfigRequest;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
-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 hmusum
@@ -20,7 +20,7 @@ public class DelayedResponseTest {
private static final String namespace = "bar";
@Test
- public void basic() {
+ void basic() {
ConfigTester tester = new ConfigTester();
final long returnTime = System.currentTimeMillis();
final long timeout = 1;
@@ -51,7 +51,7 @@ public class DelayedResponseTest {
}
@Test
- public void testDelayedResponse() {
+ void testDelayedResponse() {
ConfigTester tester = new ConfigTester();
final long timeout = 20000;
JRTServerConfigRequest request1 = tester.createRequest("baz", configId, namespace, timeout);
@@ -69,9 +69,9 @@ public class DelayedResponseTest {
// New request, should have larger delay than the first
JRTServerConfigRequest request2 = tester.createRequest("baz", configId, namespace, timeout);
DelayedResponse delayed2 = new DelayedResponse(request2);
- assertTrue("delayed1=" + delayed1.getReturnTime() + ", delayed2=" +
- delayed2.getReturnTime() + ": delayed2 should be greater than delayed1",
- delayed2.getReturnTime() > delayed1.getReturnTime());
+ assertTrue(delayed2.getReturnTime() > delayed1.getReturnTime(),
+ "delayed1=" + delayed1.getReturnTime() + ", delayed2=" +
+ delayed2.getReturnTime() + ": delayed2 should be greater than delayed1");
// Test compareTo() method
assertEquals(0, delayed1.compareTo(delayed1));
diff --git a/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/DelayedResponsesTest.java b/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/DelayedResponsesTest.java
index c9e714a11a3..6d9fa668bf5 100644
--- a/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/DelayedResponsesTest.java
+++ b/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/DelayedResponsesTest.java
@@ -1,9 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.config.proxy;
-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 hmusum
@@ -11,7 +11,7 @@ import static org.junit.Assert.assertEquals;
public class DelayedResponsesTest {
@Test
- public void basic() throws InterruptedException {
+ void basic() throws InterruptedException {
ConfigTester tester = new ConfigTester();
DelayedResponses responses = new DelayedResponses();
DelayedResponse delayedResponse = new DelayedResponse(tester.createRequest("foo", "id", "bar", 10));
diff --git a/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/MemoryCacheConfigClientTest.java b/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/MemoryCacheConfigClientTest.java
index d243d9c6dff..ff30a5b2381 100644
--- a/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/MemoryCacheConfigClientTest.java
+++ b/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/MemoryCacheConfigClientTest.java
@@ -1,12 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.config.proxy;
-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.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author hmusum
@@ -14,7 +14,7 @@ import static org.junit.Assert.assertTrue;
public class MemoryCacheConfigClientTest {
@Test
- public void basic() {
+ void basic() {
MemoryCacheConfigClient client = new MemoryCacheConfigClient(new MemoryCache());
client.memoryCache().update(ConfigTester.fooConfig);
assertEquals(ConfigTester.fooConfig, client.getConfig(ConfigTester.fooConfig, null).orElseThrow());
diff --git a/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/MemoryCacheTest.java b/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/MemoryCacheTest.java
index b0cba728a0c..2732a84527e 100644
--- a/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/MemoryCacheTest.java
+++ b/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/MemoryCacheTest.java
@@ -8,14 +8,14 @@ import com.yahoo.vespa.config.ConfigPayload;
import com.yahoo.vespa.config.PayloadChecksums;
import com.yahoo.vespa.config.RawConfig;
import com.yahoo.vespa.config.protocol.Payload;
-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.Optional;
-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 hmusum
@@ -47,7 +47,7 @@ public class MemoryCacheTest {
private Payload payload2;
private Payload payloadDifferentMd5;
- @Before
+ @BeforeEach
public void setup() {
ArrayList<String> defContent = new ArrayList<>();
defContent.add("bar string");
@@ -74,7 +74,7 @@ public class MemoryCacheTest {
}
@Test
- public void basic() {
+ void basic() {
MemoryCache cache = new MemoryCache();
cache.update(config);
@@ -97,7 +97,7 @@ public class MemoryCacheTest {
}
@Test
- public void testSameConfigNameDifferentMd5() {
+ void testSameConfigNameDifferentMd5() {
MemoryCache cache = new MemoryCache();
cache.update(config);
diff --git a/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/ProxyServerTest.java b/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/ProxyServerTest.java
index 0e25e62b925..0277ea60b49 100644
--- a/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/ProxyServerTest.java
+++ b/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/ProxyServerTest.java
@@ -8,18 +8,18 @@ import com.yahoo.vespa.config.ErrorCode;
import com.yahoo.vespa.config.RawConfig;
import com.yahoo.vespa.config.protocol.JRTServerConfigRequest;
import com.yahoo.vespa.config.protocol.Payload;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import java.io.File;
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.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.assertTrue;
/**
* @author hmusum
@@ -38,10 +38,10 @@ public class ProxyServerTest {
fooConfig.getPayloadChecksums(), fooConfig.getGeneration(), false,
ErrorCode.UNKNOWN_DEFINITION, fooConfig.getDefContent(), Optional.empty());
- @Rule
- public TemporaryFolder temporaryFolder = new TemporaryFolder();
+ @TempDir
+ public File temporaryFolder;
- @Before
+ @BeforeEach
public void setup() {
source.clear();
source.put(fooConfig.getKey(), createConfigWithNextConfigGeneration(fooConfig, 0));
@@ -49,13 +49,13 @@ public class ProxyServerTest {
proxy = createTestServer(source, client);
}
- @After
+ @AfterEach
public void shutdown() {
proxy.stop();
}
@Test
- public void basic() {
+ void basic() {
assertTrue(proxy.getMode().isDefault());
assertEquals(0, proxy.memoryCache().size());
@@ -72,7 +72,7 @@ public class ProxyServerTest {
* Tests that the proxy server RPC commands for setting and getting mode works..
*/
@Test
- public void testModeSwitch() {
+ void testModeSwitch() {
ProxyServer proxy = createTestServer(source, client);
assertTrue(proxy.getMode().isDefault());
@@ -106,7 +106,7 @@ public class ProxyServerTest {
* when it is found there.
*/
@Test
- public void testGetConfigAndCaching() {
+ void testGetConfigAndCaching() {
ConfigTester tester = new ConfigTester();
MemoryCache memoryCache = proxy.memoryCache();
assertEquals(0, memoryCache.size());
@@ -127,7 +127,7 @@ public class ProxyServerTest {
* it must be updated in cache.
*/
@Test
- public void testNoCachingOfErrorRequests() {
+ void testNoCachingOfErrorRequests() {
ConfigTester tester = new ConfigTester();
// Simulate an error response
source.put(fooConfig.getKey(), createConfigWithNextConfigGeneration(fooConfig, ErrorCode.INTERNAL_ERROR));
@@ -163,7 +163,7 @@ public class ProxyServerTest {
* When the config has been successfully retrieved it must be updated in cache.
*/
@Test
- public void testNoCachingOfEmptyConfig() {
+ void testNoCachingOfEmptyConfig() {
ConfigTester tester = new ConfigTester();
MemoryCache cache = proxy.memoryCache();
@@ -175,8 +175,8 @@ public class ProxyServerTest {
// Simulate an empty response
RawConfig emptyConfig = new RawConfig(fooConfig.getKey(), fooConfig.getDefMd5(), Payload.from("{}"),
- fooConfig.getPayloadChecksums(), 0, false,
- 0, fooConfig.getDefContent(), Optional.empty());
+ fooConfig.getPayloadChecksums(), 0, false,
+ 0, fooConfig.getDefContent(), Optional.empty());
source.put(fooConfig.getKey(), emptyConfig);
res = proxy.resolveConfig(tester.createRequest(fooConfig)).orElseThrow();
@@ -195,7 +195,7 @@ public class ProxyServerTest {
}
@Test
- public void testReconfiguration() {
+ void testReconfiguration() {
ConfigTester tester = new ConfigTester();
RawConfig res = proxy.resolveConfig(tester.createRequest(fooConfig)).orElseThrow();
assertEquals(ConfigTester.fooPayload.toString(), res.getPayload().toString());
@@ -210,7 +210,7 @@ public class ProxyServerTest {
}
@Test
- public void testReadingSystemProperties() {
+ void testReadingSystemProperties() {
ProxyServer.Properties properties = ProxyServer.getSystemProperties();
assertEquals(1, properties.configSources.length);
assertEquals(ProxyServer.DEFAULT_PROXY_CONFIG_SOURCES, properties.configSources[0]);
diff --git a/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/RpcConfigSourceClientTest.java b/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/RpcConfigSourceClientTest.java
index ada98f4b30e..b55d6fb9e26 100644
--- a/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/RpcConfigSourceClientTest.java
+++ b/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/RpcConfigSourceClientTest.java
@@ -5,12 +5,13 @@ import com.yahoo.vespa.config.ConfigKey;
import com.yahoo.vespa.config.RawConfig;
import com.yahoo.vespa.config.protocol.JRTConfigRequestFactory;
import com.yahoo.vespa.config.protocol.JRTServerConfigRequestV3;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
-import static org.junit.Assert.assertEquals;
+import java.io.File;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author hmusum
@@ -20,18 +21,18 @@ public class RpcConfigSourceClientTest {
private ResponseHandler responseHandler;
private RpcConfigSourceClient rpcConfigSourceClient;
- @Rule
- public TemporaryFolder tempFolder = new TemporaryFolder();
+ @TempDir
+ public File tempFolder;
- @Before
+ @BeforeEach
public void setup() {
responseHandler = new ResponseHandler(true);
rpcConfigSourceClient = new RpcConfigSourceClient(responseHandler, new MockConfigSource());
}
@Test
- public void basic() {
+ void basic() {
final RawConfig fooConfig = ProxyServerTest.fooConfig;
configUpdatedSendResponse(fooConfig);
// Nobody asked for the config, so no response sent
@@ -48,13 +49,13 @@ public class RpcConfigSourceClientTest {
}
@Test
- public void errorResponse() {
+ void errorResponse() {
configUpdatedSendResponse(ProxyServerTest.errorConfig);
assertSentResponses(0);
}
@Test
- public void it_does_not_send_old_config_in_response() {
+ void it_does_not_send_old_config_in_response() {
RawConfig fooConfigOldGeneration = ProxyServerTest.fooConfig;
RawConfig fooConfig = createConfigWithNextConfigGeneration(fooConfigOldGeneration);
@@ -74,7 +75,7 @@ public class RpcConfigSourceClientTest {
}
@Test
- public void it_does_send_config_with_generation_0_in_response() {
+ void it_does_send_config_with_generation_0_in_response() {
RawConfig fooConfigOldGeneration = ProxyServerTest.fooConfig;
RawConfig fooConfig = createConfigWithNextConfigGeneration(fooConfigOldGeneration, 1);
diff --git a/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/filedistribution/CachedFilesMaintainerTest.java b/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/filedistribution/CachedFilesMaintainerTest.java
index 3987ba176d7..a491a7b4fc4 100644
--- a/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/filedistribution/CachedFilesMaintainerTest.java
+++ b/config-proxy/src/test/java/com/yahoo/vespa/config/proxy/filedistribution/CachedFilesMaintainerTest.java
@@ -2,18 +2,17 @@
package com.yahoo.vespa.config.proxy.filedistribution;
import com.yahoo.io.IOUtils;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import java.io.File;
import java.io.IOException;
import java.time.Duration;
import java.time.Instant;
-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 hmusum
@@ -24,18 +23,18 @@ public class CachedFilesMaintainerTest {
private File cachedDownloads;
private CachedFilesMaintainer cachedFilesMaintainer;
- @Rule
- public TemporaryFolder tempFolder = new TemporaryFolder();
+ @TempDir
+ public File tempFolder;
- @Before
+ @BeforeEach
public void setup() throws IOException {
- cachedFileReferences = tempFolder.newFolder();
- cachedDownloads = tempFolder.newFolder();
+ cachedFileReferences = newFolder(tempFolder, "cachedFileReferences");
+ cachedDownloads = newFolder(tempFolder, "cachedDownloads");
cachedFilesMaintainer = new CachedFilesMaintainer(cachedFileReferences, cachedDownloads, Duration.ofMinutes(1));
}
@Test
- public void require_old_files_to_be_deleted() throws IOException {
+ void require_old_files_to_be_deleted() throws IOException {
runMaintainerAndAssertFiles(0, 0);
File fileReference = writeFile(cachedFileReferences, "fileReference");
@@ -72,4 +71,13 @@ public class CachedFilesMaintainerTest {
return file;
}
+ 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/configdefinitions/src/main/java/com/yahoo/vespa/config/jdisc/http/filter/package-info.java b/configdefinitions/src/main/java/com/yahoo/vespa/config/jdisc/http/filter/package-info.java
new file mode 100644
index 00000000000..9dcdc2504d1
--- /dev/null
+++ b/configdefinitions/src/main/java/com/yahoo/vespa/config/jdisc/http/filter/package-info.java
@@ -0,0 +1,5 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+@ExportPackage
+package com.yahoo.vespa.config.jdisc.http.filter;
+
+import com.yahoo.osgi.annotation.ExportPackage;
diff --git a/configdefinitions/src/vespa/jdisc.http.filter.security.rule.config.rule-based-filter.def b/configdefinitions/src/vespa/jdisc.http.filter.security.rule.config.rule-based-filter.def
new file mode 100644
index 00000000000..3fe850908dc
--- /dev/null
+++ b/configdefinitions/src/vespa/jdisc.http.filter.security.rule.config.rule-based-filter.def
@@ -0,0 +1,18 @@
+# Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package=com.yahoo.vespa.config.jdisc.http.filter
+
+dryrun bool default=false
+defaultRule.action enum { ALLOW, BLOCK }
+defaultRule.blockResponseCode int default=403
+defaultRule.blockResponseMessage string default=""
+defaultRule.blockResponseHeaders[].name string
+defaultRule.blockResponseHeaders[].value string
+rule[].name string
+rule[].action enum { ALLOW, BLOCK }
+rule[].hostNames[] string
+rule[].methods[] enum { GET, POST, PUT, PATCH, DELETE }
+rule[].pathExpressions[] string
+rule[].blockResponseCode int default=403
+rule[].blockResponseMessage string default=""
+rule[].blockResponseHeaders[].name string
+rule[].blockResponseHeaders[].value string
diff --git a/configgen/pom.xml b/configgen/pom.xml
index 11d6a195bc6..3c7032d684b 100644
--- a/configgen/pom.xml
+++ b/configgen/pom.xml
@@ -15,8 +15,13 @@
<description>Config java code generation from config definition files for Java Vespa components.</description>
<dependencies>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
diff --git a/configgen/src/test/java/com/yahoo/config/codegen/DefLineParsingTest.java b/configgen/src/test/java/com/yahoo/config/codegen/DefLineParsingTest.java
index 9cf363376cc..53d02689fed 100644
--- a/configgen/src/test/java/com/yahoo/config/codegen/DefLineParsingTest.java
+++ b/configgen/src/test/java/com/yahoo/config/codegen/DefLineParsingTest.java
@@ -1,12 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.codegen;
-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 parsing of a single line of a .def file
@@ -16,13 +13,15 @@ import static org.junit.Assert.assertTrue;
*/
public class DefLineParsingTest {
- @Test(expected = IllegalArgumentException.class)
- public void require_that_null_default_is_not_allowed() {
- new DefLine("s string default=null");
+ @Test
+ void require_that_null_default_is_not_allowed() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new DefLine("s string default=null");
+ });
}
@Test
- public void testParseIntArray() {
+ void testParseIntArray() {
DefLine l = new DefLine("foo[] int");
assertEquals("foo[]", l.getName());
@@ -31,7 +30,7 @@ public class DefLineParsingTest {
}
@Test
- public void testParseIntMap() {
+ void testParseIntMap() {
DefLine l = new DefLine("foo{} int");
assertEquals("foo{}", l.getName());
@@ -40,7 +39,7 @@ public class DefLineParsingTest {
}
@Test
- public void testParseInnerMap() {
+ void testParseInnerMap() {
DefLine l = new DefLine("foo{}.i int");
assertEquals("foo{}.i", l.getName());
@@ -49,7 +48,7 @@ public class DefLineParsingTest {
}
@Test
- public void testParseEnum() {
+ void testParseEnum() {
DefLine l = new DefLine("idtype enum { us_east, US_WEST, EMEA } default=EMEA");
assertEquals("idtype", l.getName());
@@ -62,7 +61,7 @@ public class DefLineParsingTest {
}
@Test
- public void testParseDefaultReference() {
+ void testParseDefaultReference() {
DefLine l = new DefLine("foo.bar reference default=\"value\"");
assertEquals("foo.bar", l.getName());
@@ -72,7 +71,7 @@ public class DefLineParsingTest {
}
@Test
- public void testParseNoDefaultReference() {
+ void testParseNoDefaultReference() {
DefLine l = new DefLine("foo.bar reference");
assertEquals("foo.bar", l.getName());
@@ -85,7 +84,7 @@ public class DefLineParsingTest {
* the future, so the test is included to verify that value and name can be retrieved.
*/
@Test
- public void testParseDefaultFile() {
+ void testParseDefaultFile() {
DefLine l = new DefLine("fileWithDef file default=\"value\"");
assertEquals("fileWithDef", l.getName());
@@ -95,7 +94,7 @@ public class DefLineParsingTest {
}
@Test
- public void testParseNoDefaultFile() {
+ void testParseNoDefaultFile() {
DefLine l = new DefLine("fileVal file");
assertEquals("fileVal", l.getName());
@@ -104,7 +103,7 @@ public class DefLineParsingTest {
}
@Test
- public void testParseUrls() {
+ void testParseUrls() {
DefLine l = new DefLine("urlVal url");
assertEquals("urlVal", l.getName());
@@ -113,7 +112,7 @@ public class DefLineParsingTest {
}
@Test
- public void testParseDefaultUrls() {
+ void testParseDefaultUrls() {
DefLine l = new DefLine("urlVal url default=\"http://docs.vespa.ai\"");
assertEquals("urlVal", l.getName());
@@ -124,7 +123,7 @@ public class DefLineParsingTest {
@Test
- public void testParseDefaultInt() {
+ void testParseDefaultInt() {
DefLine l = new DefLine("foo int default=1000");
assertEquals("foo", l.getName());
@@ -134,7 +133,7 @@ public class DefLineParsingTest {
}
@Test
- public void testParseDefaultLong() {
+ void testParseDefaultLong() {
DefLine l = new DefLine("foo long default=9223372036854775807");
assertEquals("foo", l.getName());
@@ -144,7 +143,7 @@ public class DefLineParsingTest {
}
@Test
- public void testParseDefaultDouble() {
+ void testParseDefaultDouble() {
DefLine l = new DefLine("foo double default=5.37");
assertEquals("foo", l.getName());
@@ -154,7 +153,7 @@ public class DefLineParsingTest {
}
@Test
- public void testParseDefaultFalseBoolean() {
+ void testParseDefaultFalseBoolean() {
DefLine l = new DefLine("foo bool default=false");
assertEquals("foo", l.getName());
@@ -164,7 +163,7 @@ public class DefLineParsingTest {
}
@Test
- public void testParseDefaultTrueBoolean() {
+ void testParseDefaultTrueBoolean() {
DefLine l = new DefLine("foo bool default=true");
assertEquals("foo", l.getName());
@@ -174,7 +173,7 @@ public class DefLineParsingTest {
}
@Test
- public void testParseNoDefaultString() {
+ void testParseNoDefaultString() {
DefLine l = new DefLine("foo.bar string");
assertEquals("foo.bar", l.getName());
@@ -183,7 +182,7 @@ public class DefLineParsingTest {
}
@Test
- public void testParseDefaultString() {
+ void testParseDefaultString() {
DefLine l = new DefLine("foo.bar string default=\"value\"");
assertEquals("foo.bar", l.getName());
@@ -193,7 +192,7 @@ public class DefLineParsingTest {
}
@Test
- public void testParseDefaultEmptyString() {
+ void testParseDefaultEmptyString() {
DefLine l = new DefLine("foo.bar string default=\"\"");
assertEquals("foo.bar", l.getName());
@@ -203,7 +202,7 @@ public class DefLineParsingTest {
}
@Test
- public void testParseDefaultStringUnquoted() {
+ void testParseDefaultStringUnquoted() {
DefLine l = new DefLine("foo.bar string default=value");
assertEquals("foo.bar", l.getName());
@@ -213,7 +212,7 @@ public class DefLineParsingTest {
}
@Test
- public void testParseStringnullDefaultString() {
+ void testParseStringnullDefaultString() {
DefLine l = new DefLine("foo.bar string default=\"null\"");
assertEquals("foo.bar", l.getName());
@@ -223,7 +222,7 @@ public class DefLineParsingTest {
}
@Test
- public void testRanges() {
+ void testRanges() {
DefLine i = new DefLine("i int range=[0, 100]");
DefLine l = new DefLine("l long range=[-1e10, 0]");
DefLine d = new DefLine("d double range=[0, 1.0]");
@@ -233,7 +232,7 @@ public class DefLineParsingTest {
}
@Test
- public void testRestartSpecification() {
+ void testRestartSpecification() {
DefLine r0 = new DefLine("i int");
DefLine r1 = new DefLine("i int restart");
assertFalse(r0.getRestart());
diff --git a/configgen/src/test/java/com/yahoo/config/codegen/DefParserNamespaceTest.java b/configgen/src/test/java/com/yahoo/config/codegen/DefParserNamespaceTest.java
index 2eb86546e51..c57114a9ba8 100644
--- a/configgen/src/test/java/com/yahoo/config/codegen/DefParserNamespaceTest.java
+++ b/configgen/src/test/java/com/yahoo/config/codegen/DefParserNamespaceTest.java
@@ -1,15 +1,14 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.codegen;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import static com.yahoo.config.codegen.DefParserTest.assertLineFails;
import static com.yahoo.config.codegen.DefParserTest.createDefTemplate;
import static com.yahoo.config.codegen.DefParserTest.createParser;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author gjoranv
@@ -18,49 +17,53 @@ import static org.junit.Assert.assertNotEquals;
public class DefParserNamespaceTest {
@Test
- public void namespace_is_set_on_root_node() {
+ void namespace_is_set_on_root_node() {
DefParser parser = createParser("namespace=myproject.config\n");
CNode root = parser.getTree();
assertEquals("myproject.config", root.getNamespace());
}
@Test
- public void package_is_used_as_namespace_when_no_namespace_is_given() {
+ void package_is_used_as_namespace_when_no_namespace_is_given() {
String PACKAGE = "com.github.myproject";
DefParser parser = createParser("package=" + PACKAGE + "\n");
CNode root = parser.getTree();
assertEquals(PACKAGE, root.getNamespace());
}
- @Test(expected = CodegenRuntimeException.class)
- public void uppercase_chars_are_not_allowed() {
- createParser("namespace=Foo\n").getTree();
+ @Test
+ void uppercase_chars_are_not_allowed() {
+ assertThrows(CodegenRuntimeException.class, () -> {
+ createParser("namespace=Foo\n").getTree();
+ });
}
- @Test(expected = CodegenRuntimeException.class)
- public void explicit_com_yahoo_prefix_is_not_allowed() {
- createParser("namespace=com.yahoo.myproject.config\n").getTree();
+ @Test
+ void explicit_com_yahoo_prefix_is_not_allowed() {
+ assertThrows(CodegenRuntimeException.class, () -> {
+ createParser("namespace=com.yahoo.myproject.config\n").getTree();
+ });
}
@Test
- public void spaces_are_allowed_around_equals_sign() {
+ void spaces_are_allowed_around_equals_sign() {
DefParser parser = createParser("namespace = myproject.config\n");
CNode root = parser.getTree();
assertEquals("myproject.config", root.getNamespace());
}
@Test
- public void empty_namespace_is_not_allowed() {
+ void empty_namespace_is_not_allowed() {
assertLineFails("namespace");
}
@Test
- public void consecutive_dots_are_not_allowed() {
+ void consecutive_dots_are_not_allowed() {
assertLineFails("namespace=a..b");
}
@Test
- public void namespace_alters_def_md5() {
+ void namespace_alters_def_md5() {
DefParser parser = createParser("");
CNode root = parser.getTree();
@@ -72,7 +75,7 @@ public class DefParserNamespaceTest {
@Test
- public void number_is_allowed_as_non_leading_char_in_namespace() throws IOException, DefParser.DefParserException {
+ void number_is_allowed_as_non_leading_char_in_namespace() throws IOException, DefParser.DefParserException {
StringBuilder sb = createDefTemplate();
String line = "namespace=a.b.c2\n";
sb.append(line);
@@ -80,17 +83,17 @@ public class DefParserNamespaceTest {
}
@Test
- public void number_is_not_allowed_as_namespace_start_char() {
+ void number_is_not_allowed_as_namespace_start_char() {
assertLineFails("namespace=2.a.b");
}
@Test
- public void number_is_not_allowed_as_leading_char_in_namespace_token() {
+ void number_is_not_allowed_as_leading_char_in_namespace_token() {
assertLineFails("namespace=a.b.2c");
}
@Test
- public void underscore_in_namespace_is_allowed() throws IOException, DefParser.DefParserException {
+ void underscore_in_namespace_is_allowed() throws IOException, DefParser.DefParserException {
StringBuilder sb = createDefTemplate();
String line = "namespace=a_b.c\n";
sb.append(line);
diff --git a/configgen/src/test/java/com/yahoo/config/codegen/DefParserPackageTest.java b/configgen/src/test/java/com/yahoo/config/codegen/DefParserPackageTest.java
index cd7ca1a89b9..4aa40ae902c 100644
--- a/configgen/src/test/java/com/yahoo/config/codegen/DefParserPackageTest.java
+++ b/configgen/src/test/java/com/yahoo/config/codegen/DefParserPackageTest.java
@@ -1,16 +1,14 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.codegen;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import static com.yahoo.config.codegen.DefParserTest.assertLineFails;
import static com.yahoo.config.codegen.DefParserTest.createDefTemplate;
import static com.yahoo.config.codegen.DefParserTest.createParser;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Tests setting explicit java package in the def file.
@@ -21,17 +19,17 @@ public class DefParserPackageTest {
String PACKAGE = "com.github.myproject";
@Test
- public void package_is_set_on_root_node() {
+ void package_is_set_on_root_node() {
DefParser parser = createParser("package=" + PACKAGE + "\n");
CNode root = parser.getTree();
assertEquals(PACKAGE, root.getPackage());
}
@Test
- public void package_and_namespace_can_coexist() {
+ void package_and_namespace_can_coexist() {
String namespace = "test.namespace";
DefParser parser = createParser("package=" + PACKAGE +
- "\nnamespace=" + namespace +"\n");
+ "\nnamespace=" + namespace + "\n");
CNode root = parser.getTree();
assertEquals(PACKAGE, root.getPackage());
assertEquals(namespace, root.getNamespace());
@@ -39,37 +37,39 @@ public class DefParserPackageTest {
// Required by JavaClassBuilder ctor.
@Test
- public void package_is_null_when_not_explicitly_given() {
+ void package_is_null_when_not_explicitly_given() {
String namespace = "test.namespace";
DefParser parser = createParser("namespace=" + namespace + "\n");
CNode root = parser.getTree();
assertNull(root.getPackage());
}
- @Test(expected = CodegenRuntimeException.class)
- public void uppercase_chars_are_not_allowed() {
- createParser("package=Foo.bar\n").getTree();
+ @Test
+ void uppercase_chars_are_not_allowed() {
+ assertThrows(CodegenRuntimeException.class, () -> {
+ createParser("package=Foo.bar\n").getTree();
+ });
}
@Test
- public void spaces_are_allowed_around_equals_sign() {
+ void spaces_are_allowed_around_equals_sign() {
DefParser parser = createParser("package = " + PACKAGE + "\n");
CNode root = parser.getTree();
assertEquals(PACKAGE, root.getPackage());
}
@Test
- public void empty_package_is_not_allowed() {
- assertLineFails("package");
+ void empty_package_is_not_allowed() {
+ assertLineFails("package");
}
@Test
- public void consecutive_dots_are_not_allowed() {
+ void consecutive_dots_are_not_allowed() {
assertLineFails("package=a..b");
}
@Test
- public void package_alters_def_md5() {
+ void package_alters_def_md5() {
DefParser parser = createParser("a string\n");
CNode root = parser.getTree();
@@ -81,7 +81,7 @@ public class DefParserPackageTest {
@Test
- public void number_is_allowed_as_non_leading_char() throws IOException, DefParser.DefParserException {
+ void number_is_allowed_as_non_leading_char() throws IOException, DefParser.DefParserException {
StringBuilder sb = createDefTemplate();
String line = "package=a.b.c2\n";
sb.append(line);
@@ -89,17 +89,17 @@ public class DefParserPackageTest {
}
@Test
- public void number_is_not_allowed_as_package_start_char() {
+ void number_is_not_allowed_as_package_start_char() {
assertLineFails("package=2.a.b");
}
@Test
- public void number_is_not_allowed_as_leading_char_in_package_token() {
+ void number_is_not_allowed_as_leading_char_in_package_token() {
assertLineFails("package=a.b.2c");
}
@Test
- public void underscore_in_package_is_allowed() throws IOException, DefParser.DefParserException {
+ void underscore_in_package_is_allowed() throws IOException, DefParser.DefParserException {
StringBuilder sb = createDefTemplate();
String line = "package=a_b.c\n";
sb.append(line);
diff --git a/configgen/src/test/java/com/yahoo/config/codegen/DefParserTest.java b/configgen/src/test/java/com/yahoo/config/codegen/DefParserTest.java
index 915edce1440..4fbf01892cc 100644
--- a/configgen/src/test/java/com/yahoo/config/codegen/DefParserTest.java
+++ b/configgen/src/test/java/com/yahoo/config/codegen/DefParserTest.java
@@ -1,17 +1,15 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.codegen;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
+
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringReader;
-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.*;
/**
* Unit tests for DefParser.
@@ -25,7 +23,7 @@ public class DefParserTest {
private static final String DEF_NAME = TEST_DIR + "configgen.allfeatures.def";
@Test
- public void testTraverseTree() throws IOException {
+ void testTraverseTree() throws IOException {
File defFile = new File(DEF_NAME);
CNode root = new DefParser("test", new FileReader(defFile)).getTree();
assertNotNull(root);
@@ -62,21 +60,21 @@ public class DefParserTest {
}
@Test
- public void testFileWithNamespaceInFilename() throws IOException {
+ void testFileWithNamespaceInFilename() throws IOException {
File defFile = new File(TEST_DIR + "baz.bar.foo.def");
CNode root = new DefParser("test", new FileReader(defFile)).getTree();
assertEquals("31a0f9bda0e5ff929762a29569575a7e", root.defMd5);
}
@Test
- public void testMd5Sum() throws IOException {
+ void testMd5Sum() throws IOException {
File defFile = new File(DEF_NAME);
CNode root = new DefParser("test", new FileReader(defFile)).getTree();
assertEquals("f901bdc5c96e7005130399c63f247823", root.defMd5);
}
@Test
- public void testMd5Sum2() {
+ void testMd5Sum2() {
String def = "a string\n";
CNode root = new DefParser("testMd5Sum2", new StringReader(def)).getTree();
assertEquals("a5e5fdbb2b27e56ba7d5e60e335c598b", root.defMd5);
@@ -84,7 +82,7 @@ public class DefParserTest {
// TODO: Version is not used anymore, remove test in Vespa 9
@Test
- public void testValidVersions() {
+ void testValidVersions() {
try {
parse("version=8");
parse("version=8-1");
@@ -103,7 +101,7 @@ public class DefParserTest {
}
@Test
- public void testInvalidType() {
+ void testInvalidType() {
String line = "a sting";
assertLineFails(line, "Could not create sting a");
}
@@ -113,20 +111,23 @@ public class DefParserTest {
}
@Test
- public void verify_fail_on_default_for_file() {
+ void verify_fail_on_default_for_file() {
assertLineFails("f file default=\"file1.txt\"",
- "Invalid default value");
+ "Invalid default value");
}
- @Test(expected = CodegenRuntimeException.class)
- @Ignore("Not implemented yet")
- public void testInvalidEnum() {
- DefParser parser = createParser("anEnum enum {A, B, A}\n");
+ @Test
+ @Disabled("Not implemented yet")
+ void testInvalidEnum() {
+ assertThrows(CodegenRuntimeException.class, () -> {
+ DefParser parser = createParser("anEnum enum {A, B, A}\n");
+ //parser.validateDef(def);
+ });
//parser.validateDef(def);
}
@Test
- public void testEnum() {
+ void testEnum() {
StringBuilder sb = createDefTemplate();
sb.append("enum1 enum {A,B} default=A\n");
sb.append("enum2 enum {A, B} default=A\n");
@@ -148,20 +149,22 @@ public class DefParserTest {
assertEquals("A", node.getDefaultValue().getStringRepresentation());
}
- @Test(expected = DefParser.DefParserException.class)
- public void testInvalidCommaInEnum() throws DefParser.DefParserException, IOException {
- String invalidEnum = "anEnum enum {A, B, } default=A\n";
- String validEnum = "anotherEnum enum {A, B} default=A\n";
- StringBuilder sb = createDefTemplate();
- sb.append(invalidEnum);
- sb.append(validEnum);
- DefParser parser = createParser(sb.toString());
- parser.parse();
+ @Test
+ void testInvalidCommaInEnum() throws DefParser.DefParserException, IOException {
+ assertThrows(DefParser.DefParserException.class, () -> {
+ String invalidEnum = "anEnum enum {A, B, } default=A\n";
+ String validEnum = "anotherEnum enum {A, B} default=A\n";
+ StringBuilder sb = createDefTemplate();
+ sb.append(invalidEnum);
+ sb.append(validEnum);
+ DefParser parser = createParser(sb.toString());
+ parser.parse();
+ });
}
- @Ignore //TODO: finish this! The numeric leaf nodes must contain their range.
+ @Disabled //TODO: finish this! The numeric leaf nodes must contain their range.
@Test
- public void testRanges() {
+ void testRanges() {
StringBuilder sb = new StringBuilder();
sb.append("i int range=[0,10]");
sb.append("l long range=[-1e20,0]");
@@ -173,7 +176,7 @@ public class DefParserTest {
}
@Test
- public void duplicate_parameter_is_illegal() {
+ void duplicate_parameter_is_illegal() {
Class<?> exceptionClass = DefParser.DefParserException.class;
StringBuilder sb = createDefTemplate();
String duplicateLine = "b int\n";
@@ -189,76 +192,76 @@ public class DefParserTest {
}
@Test
- public void testIllegalCharacterInName() {
- assertLineFails("a-b int",
- "a-b contains unexpected character");
+ void testIllegalCharacterInName() {
+ assertLineFails("a-b int",
+ "a-b contains unexpected character");
}
@Test
- public void parameter_name_starting_with_digit_is_illegal() {
+ void parameter_name_starting_with_digit_is_illegal() {
assertLineFails("1a int",
- "1a must start with a non-digit character");
+ "1a must start with a non-digit character");
}
@Test
- public void parameter_name_starting_with_uppercase_is_illegal() {
+ void parameter_name_starting_with_uppercase_is_illegal() {
assertLineFails("SomeInt int",
- "'SomeInt' cannot start with an uppercase letter");
+ "'SomeInt' cannot start with an uppercase letter");
}
@Test
- public void parameter_name_starting_with_the_internal_prefix_is_illegal() {
+ void parameter_name_starting_with_the_internal_prefix_is_illegal() {
String internalPrefix = ReservedWords.INTERNAL_PREFIX;
assertLineFails(internalPrefix + "i int",
- "'" + internalPrefix + "i' cannot start with '" + internalPrefix + "'");
+ "'" + internalPrefix + "i' cannot start with '" + internalPrefix + "'");
}
@Test
- public void testIllegalArray() {
+ void testIllegalArray() {
assertLineFails("intArr[ int",
- "intArr[ Expected ] to terminate array definition");
+ "intArr[ Expected ] to terminate array definition");
}
@Test
- public void testIllegalDefault() {
+ void testIllegalDefault() {
assertLineFails("a int deflt 10",
- " deflt 10");
+ " deflt 10");
}
@Test
- public void testReservedWordInC() {
+ void testReservedWordInC() {
assertLineFails("auto int",
- "auto is a reserved word in C");
+ "auto is a reserved word in C");
}
@Test
- public void testReservedWordInCForArray() {
+ void testReservedWordInCForArray() {
assertLineFails("auto[] int",
- "auto is a reserved word in C");
+ "auto is a reserved word in C");
}
@Test
- public void testReservedWordInJava() {
+ void testReservedWordInJava() {
assertLineFails("abstract int",
- "abstract is a reserved word in Java");
+ "abstract is a reserved word in Java");
}
@Test
- public void testReservedWordInJavaForMap() {
+ void testReservedWordInJavaForMap() {
assertLineFails("abstract{} int",
- "abstract is a reserved word in Java");
+ "abstract is a reserved word in Java");
}
@Test
- public void testReservedWordInCAndJava() {
+ void testReservedWordInCAndJava() {
assertLineFails("continue int",
- "continue is a reserved word in C and Java");
+ "continue is a reserved word in C and Java");
}
@Test
- public void testReservedWordInCAndJavaForArray() {
+ void testReservedWordInCAndJavaForArray() {
assertLineFails("continue[] int",
- "continue is a reserved word in C and Java");
+ "continue is a reserved word in C and Java");
}
static StringBuilder createDefTemplate() {
diff --git a/configgen/src/test/java/com/yahoo/config/codegen/JavaClassBuilderTest.java b/configgen/src/test/java/com/yahoo/config/codegen/JavaClassBuilderTest.java
index e6e86b2c2a3..69a690b0e82 100644
--- a/configgen/src/test/java/com/yahoo/config/codegen/JavaClassBuilderTest.java
+++ b/configgen/src/test/java/com/yahoo/config/codegen/JavaClassBuilderTest.java
@@ -1,8 +1,8 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.codegen;
-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 java.io.StringReader;
@@ -12,9 +12,7 @@ import java.util.List;
import static com.yahoo.config.codegen.ConfiggenUtil.createClassName;
import static com.yahoo.config.codegen.JavaClassBuilder.createUniqueSymbol;
-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
@@ -26,44 +24,44 @@ public class JavaClassBuilderTest {
private static final String DEF_NAME = TEST_DIR + "configgen.allfeatures.def";
private static final String REFERENCE_NAME = TEST_DIR + "allfeatures.reference";
- @Ignore
+ @Disabled
@Test
- public void visual_inspection_of_generated_class() {
+ void visual_inspection_of_generated_class() {
final String testDefinition =
"namespace=test\n" + //
- "p path\n" + //
- "pathArr[] path\n" + //
- "u url\n" + //
- "urlArr[] url\n" + //
- "f file\n" + //
- "fileArr[] file\n" + //
- "i int default=0\n" + //
- "# A long value\n" + //
- "l long default=0\n" + //
- "s string default=\"\"\n" + //
- "b bool\n" + //
- "# An enum value\n" + //
- "e enum {A, B, C}\n" + //
- "intArr[] int\n" + //
- "boolArr[] bool\n" + //
- "enumArr[] enum {FOO, BAR}\n" + //
- "intMap{} int\n" + //
- "# A struct\n" + //
- "# with multi-line\n" + //
- "# comment and \"quotes\".\n" + //
- "myStruct.i int\n" + //
- "myStruct.s string\n" + //
- "# An inner array\n" + //
- "myArr[].i int\n" + //
- "myArr[].newStruct.s string\n" + //
- "myArr[].newStruct.b bool\n" + //
- "myArr[].intArr[] int\n" + //
- "# An inner map\n" + //
- "myMap{}.i int\n" + //
- "myMap{}.newStruct.s string\n" + //
- "myMap{}.newStruct.b bool\n" + //
- "myMap{}.intArr[] int\n" + //
- "intMap{} int\n";
+ "p path\n" + //
+ "pathArr[] path\n" + //
+ "u url\n" + //
+ "urlArr[] url\n" + //
+ "f file\n" + //
+ "fileArr[] file\n" + //
+ "i int default=0\n" + //
+ "# A long value\n" + //
+ "l long default=0\n" + //
+ "s string default=\"\"\n" + //
+ "b bool\n" + //
+ "# An enum value\n" + //
+ "e enum {A, B, C}\n" + //
+ "intArr[] int\n" + //
+ "boolArr[] bool\n" + //
+ "enumArr[] enum {FOO, BAR}\n" + //
+ "intMap{} int\n" + //
+ "# A struct\n" + //
+ "# with multi-line\n" + //
+ "# comment and \"quotes\".\n" + //
+ "myStruct.i int\n" + //
+ "myStruct.s string\n" + //
+ "# An inner array\n" + //
+ "myArr[].i int\n" + //
+ "myArr[].newStruct.s string\n" + //
+ "myArr[].newStruct.b bool\n" + //
+ "myArr[].intArr[] int\n" + //
+ "# An inner map\n" + //
+ "myMap{}.i int\n" + //
+ "myMap{}.newStruct.s string\n" + //
+ "myMap{}.newStruct.b bool\n" + //
+ "myMap{}.intArr[] int\n" + //
+ "intMap{} int\n";
DefParser parser = new DefParser("test", new StringReader(testDefinition));
InnerCNode root = parser.getTree();
@@ -73,11 +71,11 @@ public class JavaClassBuilderTest {
}
@Test
- public void testCreateUniqueSymbol() {
+ void testCreateUniqueSymbol() {
final String testDefinition =
"namespace=test\n" + //
- "m int\n" + //
- "n int\n";
+ "m int\n" + //
+ "n int\n";
InnerCNode root = new DefParser("test", new StringReader(testDefinition)).getTree();
assertEquals("f", createUniqueSymbol(root, "foo"));
@@ -90,7 +88,7 @@ public class JavaClassBuilderTest {
}
@Test
- public void testCreateClassName() {
+ void testCreateClassName() {
assertEquals("SimpleConfig", createClassName("simple"));
assertEquals("AConfig", createClassName("a"));
assertEquals("ABCConfig", createClassName("a-b-c"));
@@ -99,13 +97,15 @@ public class JavaClassBuilderTest {
assertEquals("MyAppConfig", createClassName("MyApp"));
}
- @Test(expected = CodegenRuntimeException.class)
- public void testIllegalClassName() {
- createClassName("+illegal");
+ @Test
+ void testIllegalClassName() {
+ assertThrows(CodegenRuntimeException.class, () -> {
+ createClassName("+illegal");
+ });
}
@Test
- public void verify_generated_class_against_reference() throws IOException {
+ void verify_generated_class_against_reference() throws IOException {
String testDefinition = String.join("\n", Files.readAllLines(FileSystems.getDefault().getPath(DEF_NAME)));
List<String> referenceClassLines = Files.readAllLines(FileSystems.getDefault().getPath(REFERENCE_NAME));
@@ -114,11 +114,13 @@ public class JavaClassBuilderTest {
JavaClassBuilder builder = new JavaClassBuilder(root, parser.getNormalizedDefinition(), null, null);
String[] configClassLines = builder.getConfigClass("AllfeaturesConfig").split("\n");
- for (var line : configClassLines) { System.out.println(line); }
+ for (var line : configClassLines) {
+ System.out.println(line);
+ }
for (int i = 0; i < referenceClassLines.size(); i++) {
if (configClassLines.length <= i)
fail("Missing lines i generated config class. First missing line:\n" + referenceClassLines.get(i));
- assertEquals("Line " + i, referenceClassLines.get(i), configClassLines[i]);
+ assertEquals(referenceClassLines.get(i), configClassLines[i], "Line " + i);
}
}
diff --git a/configgen/src/test/java/com/yahoo/config/codegen/MakeConfigTest.java b/configgen/src/test/java/com/yahoo/config/codegen/MakeConfigTest.java
index 9b3e9c31363..d967e16ba0b 100644
--- a/configgen/src/test/java/com/yahoo/config/codegen/MakeConfigTest.java
+++ b/configgen/src/test/java/com/yahoo/config/codegen/MakeConfigTest.java
@@ -1,26 +1,26 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.codegen;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
import java.io.File;
import java.io.IOException;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
public class MakeConfigTest {
private File dest;
- @Before
+ @BeforeEach
public void setUp() {
dest = new File("/tmp/"+System.currentTimeMillis()+File.separator);
dest.mkdir();
}
- @After
+ @AfterEach
public void tearDown() {
recursiveDeleteDir(dest);
}
@@ -40,9 +40,9 @@ public class MakeConfigTest {
// The directory is now empty so delete it
return dir.delete();
}
-
+
@Test
- public void testProps() throws PropertyException {
+ void testProps() throws PropertyException {
System.setProperty("config.dumpTree", "true");
System.setProperty("config.useFramework", "true");
System.setProperty("config.dest", dest.getAbsolutePath());
@@ -53,7 +53,7 @@ public class MakeConfigTest {
assertTrue(p.generateFrameworkCode);
assertEquals(p.specFiles.size(), 1);
assertEquals(p.specFiles.get(0).getAbsolutePath(), new File("src/test/resources/configgen.allfeatures.def").getAbsolutePath());
-
+
System.setProperty("config.dumpTree", "false");
System.setProperty("config.useFramework", "false");
System.setProperty("config.dest", dest.getAbsolutePath());
@@ -66,7 +66,7 @@ public class MakeConfigTest {
}
@Test
- public void testMake() throws IOException {
+ void testMake() throws IOException {
System.setProperty("config.dumpTree", "true");
System.setProperty("config.useFramework", "true");
System.setProperty("config.dest", dest.getAbsolutePath());
diff --git a/configgen/src/test/java/com/yahoo/config/codegen/NormalizedDefinitionTest.java b/configgen/src/test/java/com/yahoo/config/codegen/NormalizedDefinitionTest.java
index d57210dd9ed..61b5eb5a759 100644
--- a/configgen/src/test/java/com/yahoo/config/codegen/NormalizedDefinitionTest.java
+++ b/configgen/src/test/java/com/yahoo/config/codegen/NormalizedDefinitionTest.java
@@ -9,10 +9,10 @@ import java.io.IOException;
import java.io.StringReader;
import java.util.List;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
@@ -21,13 +21,13 @@ import static org.junit.Assert.assertNotNull;
public class NormalizedDefinitionTest {
@Test
- public void testNormalizingFromReader() {
+ void testNormalizingFromReader() {
String def =
"aString string \n" +
- "anInt int #comment \n" +
- "aStringCommentCharacterAfter string default=\"ab\" #foo\n" +
- "aStringWithCommentCharacter string default=\"a#b\"\n" +
- "aStringWithEscapedQuote string default=\"a\"b\"\n";
+ "anInt int #comment \n" +
+ "aStringCommentCharacterAfter string default=\"ab\" #foo\n" +
+ "aStringWithCommentCharacter string default=\"a#b\"\n" +
+ "aStringWithEscapedQuote string default=\"a\"b\"\n";
StringReader reader = new StringReader(def);
@@ -52,7 +52,7 @@ public class NormalizedDefinitionTest {
}
@Test
- public void testNormalizingFromFile() throws IOException {
+ void testNormalizingFromFile() throws IOException {
FileReader fileReader = null;
try {
fileReader = new FileReader("src/test/resources/configgen.allfeatures.def");
diff --git a/configserver-flags/pom.xml b/configserver-flags/pom.xml
index 61d03e41cd5..e9c0c68685c 100644
--- a/configserver-flags/pom.xml
+++ b/configserver-flags/pom.xml
@@ -59,6 +59,12 @@
<artifactId>guice</artifactId>
<scope>provided</scope>
<classifier>no_aop</classifier>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
@@ -78,15 +84,29 @@
<artifactId>testutil</artifactId>
<version>${project.version}</version>
<scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-core</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-library</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
+ <groupId>org.apache.curator</groupId>
+ <artifactId>curator-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
- <groupId>org.apache.curator</groupId>
- <artifactId>curator-test</artifactId>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
@@ -94,6 +114,11 @@
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.assertj</groupId>
+ <artifactId>assertj-core</artifactId>
+ <scope>test</scope>
+ </dependency>
</dependencies>
<build>
<plugins>
diff --git a/configserver-flags/src/test/java/com/yahoo/vespa/configserver/flags/ConfigServerFlagSourceTest.java b/configserver-flags/src/test/java/com/yahoo/vespa/configserver/flags/ConfigServerFlagSourceTest.java
index 05802db6223..f0df08bfb6b 100644
--- a/configserver-flags/src/test/java/com/yahoo/vespa/configserver/flags/ConfigServerFlagSourceTest.java
+++ b/configserver-flags/src/test/java/com/yahoo/vespa/configserver/flags/ConfigServerFlagSourceTest.java
@@ -8,9 +8,9 @@ import com.yahoo.vespa.flags.FlagId;
import com.yahoo.vespa.flags.Flags;
import com.yahoo.vespa.flags.RawFlag;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@@ -20,8 +20,8 @@ import java.nio.file.Path;
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.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
@@ -41,12 +41,12 @@ public class ConfigServerFlagSourceTest {
private ConfigServerFlagSource flagSource;
private BooleanFlag flag;
- @Before
+ @BeforeEach
public void setUp() {
flagsReplacer = Flags.clearFlagsForTesting();
}
- @After
+ @AfterEach
public void tearDown() {
flagsReplacer.close();
}
@@ -57,7 +57,7 @@ public class ConfigServerFlagSourceTest {
}
@Test
- public void testAbsentInFileSystemForwardsToFlagsDb() {
+ void testAbsentInFileSystemForwardsToFlagsDb() {
initialize();
when(flagsDb.getValue(flagId)).thenReturn(Optional.empty());
@@ -67,7 +67,7 @@ public class ConfigServerFlagSourceTest {
}
@Test
- public void testAvoidingZooKeeperWhenOverridingInFile() throws IOException {
+ void testAvoidingZooKeeperWhenOverridingInFile() throws IOException {
// Here is how to set the value of a flag, such that ZooKeeper will NOT be queried when getting that value:
// - Make a flag.db file with the override
Path flagPath = fileSystem.getPath(vespaHome + "/var/vespa/flag.db");
diff --git a/configserver-flags/src/test/java/com/yahoo/vespa/configserver/flags/db/FlagsDbImplTest.java b/configserver-flags/src/test/java/com/yahoo/vespa/configserver/flags/db/FlagsDbImplTest.java
index f3087aa0e3b..36451e759fa 100644
--- a/configserver-flags/src/test/java/com/yahoo/vespa/configserver/flags/db/FlagsDbImplTest.java
+++ b/configserver-flags/src/test/java/com/yahoo/vespa/configserver/flags/db/FlagsDbImplTest.java
@@ -9,24 +9,22 @@ import com.yahoo.vespa.flags.json.Condition;
import com.yahoo.vespa.flags.json.FlagData;
import com.yahoo.vespa.flags.json.Rule;
import com.yahoo.vespa.flags.json.WhitelistCondition;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Map;
import java.util.Optional;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.equalTo;
-import static org.hamcrest.Matchers.notNullValue;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author hakonhall
*/
public class FlagsDbImplTest {
@Test
- public void test() {
+ void test() {
MockCurator curator = new MockCurator();
FlagsDbImpl db = new FlagsDbImpl(curator);
@@ -48,9 +46,9 @@ public class FlagsDbImplTest {
FlagData data2 = new FlagData(flagId2, new FetchVector().with(FetchVector.Dimension.ZONE_ID, "zone-a"), rule1);
db.setValue(flagId2, data2);
Map<FlagId, FlagData> flags = db.getAllFlagData();
- assertThat(flags.size(), equalTo(2));
- assertThat(flags.get(flagId), notNullValue());
- assertThat(flags.get(flagId2), notNullValue());
+ assertEquals(flags.size(), 2);
+ assertNotNull(flags.get(flagId));
+ assertNotNull(flags.get(flagId2));
db.removeValue(flagId2);
assertFalse(db.getValue(flagId2).isPresent());
diff --git a/configserver-flags/src/test/java/com/yahoo/vespa/configserver/flags/http/FlagsHandlerTest.java b/configserver-flags/src/test/java/com/yahoo/vespa/configserver/flags/http/FlagsHandlerTest.java
index 3ca0567a1c5..2700ab114e9 100644
--- a/configserver-flags/src/test/java/com/yahoo/vespa/configserver/flags/http/FlagsHandlerTest.java
+++ b/configserver-flags/src/test/java/com/yahoo/vespa/configserver/flags/http/FlagsHandlerTest.java
@@ -13,7 +13,7 @@ import com.yahoo.vespa.flags.FlagId;
import com.yahoo.vespa.flags.Flags;
import com.yahoo.vespa.flags.UnboundBooleanFlag;
import com.yahoo.yolean.Exceptions;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@@ -23,10 +23,8 @@ import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.containsString;
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertEquals;
+import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author hakonhall
@@ -44,7 +42,7 @@ public class FlagsHandlerTest {
private final FlagsHandler handler = new FlagsHandler(FlagsHandler.testContext(), flagsDb);
@Test
- public void testV1() {
+ void testV1() {
String expectedResponse = "{" +
Stream.of("data", "defined")
.map(name -> "\"" + name + "\":{\"url\":\"https://foo.com:4443/flags/v1/" + name + "\"}")
@@ -55,7 +53,7 @@ public class FlagsHandlerTest {
}
@Test
- public void testDefined() {
+ void testDefined() {
try (Flags.Replacer replacer = Flags.clearFlagsForTesting()) {
fixUnusedWarning(replacer);
Flags.defineFeatureFlag("id", false, List.of("joe"), "2010-01-01", "2030-01-01", "desc", "mod", FetchVector.Dimension.HOSTNAME);
@@ -70,7 +68,7 @@ public class FlagsHandlerTest {
private void fixUnusedWarning(Flags.Replacer replacer) { }
@Test
- public void testData() {
+ void testData() {
// PUT flag with ID id1
verifySuccessfulRequest(Method.PUT, "/data/" + FLAG1.id(),
"{\n" +
@@ -96,8 +94,8 @@ public class FlagsHandlerTest {
"", "{\"flags\":[{\"id\":\"id1\",\"url\":\"https://foo.com:4443/flags/v1/data/id1\"}]}");
// Verify absent port => absent in response
- assertThat(handleWithPort(Method.GET, -1, "/data", "", 200),
- is("{\"flags\":[{\"id\":\"id1\",\"url\":\"https://foo.com/flags/v1/data/id1\"}]}"));
+ assertEquals(handleWithPort(Method.GET, -1, "/data", "", 200),
+ "{\"flags\":[{\"id\":\"id1\",\"url\":\"https://foo.com/flags/v1/data/id1\"}]}");
// PUT id2
verifySuccessfulRequest(Method.PUT, "/data/" + FLAG2.id(),
@@ -163,25 +161,24 @@ public class FlagsHandlerTest {
}
@Test
- public void testForcing() {
- assertThat(handle(Method.PUT, "/data/" + new FlagId("undef"), "", 400),
- containsString("There is no flag 'undef'"));
+ void testForcing() {
+ assertThat(handle(Method.PUT, "/data/" + new FlagId("undef"), "", 400)).contains("There is no flag 'undef'");
- assertThat(handle(Method.PUT, "/data/" + new FlagId("undef") + "?force=true", "", 400),
- containsString("No content to map due to end-of-input"));
+ assertThat(handle(Method.PUT, "/data/" + new FlagId("undef") + "?force=true", "", 400)).
+ contains("No content to map due to end-of-input");
- assertThat(handle(Method.PUT, "/data/" + FLAG1.id(), "{}", 400),
- containsString("Flag ID missing"));
+ assertThat(handle(Method.PUT, "/data/" + FLAG1.id(), "{}", 400)).
+ contains("Flag ID missing");
- assertThat(handle(Method.PUT, "/data/" + FLAG1.id(), "{\"id\": \"id1\",\"rules\": [{\"value\":\"string\"}]}", 400),
- containsString("Wrong type of JsonNode: STRING"));
+ assertThat(handle(Method.PUT, "/data/" + FLAG1.id(), "{\"id\": \"id1\",\"rules\": [{\"value\":\"string\"}]}", 400)).
+ contains("Wrong type of JsonNode: STRING");
- assertThat(handle(Method.PUT, "/data/" + FLAG1.id() + "?force=true", "{\"id\": \"id1\",\"rules\": [{\"value\":\"string\"}]}", 200),
- is(""));
+ assertEquals(handle(Method.PUT, "/data/" + FLAG1.id() + "?force=true", "{\"id\": \"id1\",\"rules\": [{\"value\":\"string\"}]}", 200),
+ "");
}
private void verifySuccessfulRequest(Method method, String pathSuffix, String requestBody, String expectedResponseBody) {
- assertThat(handle(method, pathSuffix, requestBody, 200), is(expectedResponseBody));
+ assertEquals(handle(method, pathSuffix, requestBody, 200), expectedResponseBody);
}
private String handle(Method method, String pathSuffix, String requestBody, int expectedStatus) {
diff --git a/container-core/pom.xml b/container-core/pom.xml
index e1443702e95..ed4b05495e3 100644
--- a/container-core/pom.xml
+++ b/container-core/pom.xml
@@ -269,7 +269,7 @@
<!-- TEST scope -->
<dependency>
<groupId>com.github.tomakehurst</groupId>
- <artifactId>wiremock-standalone</artifactId>
+ <artifactId>wiremock-jre8-standalone</artifactId>
<scope>test</scope>
</dependency>
<dependency>
@@ -277,11 +277,12 @@
<artifactId>testutil</artifactId>
<version>${project.version}</version>
<scope>test</scope>
- </dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
@@ -304,11 +305,6 @@
<scope>test</scope>
</dependency>
<dependency>
- <groupId>org.junit.vintage</groupId>
- <artifactId>junit-vintage-engine</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
diff --git a/container-core/src/test/java/com/yahoo/component/ComponentSpecTestCase.java b/container-core/src/test/java/com/yahoo/component/ComponentSpecTestCase.java
index 07e1d806bfb..7d8491e4826 100644
--- a/container-core/src/test/java/com/yahoo/component/ComponentSpecTestCase.java
+++ b/container-core/src/test/java/com/yahoo/component/ComponentSpecTestCase.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.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.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Arne Bergene Fossaa
@@ -13,7 +11,7 @@ import static org.junit.Assert.assertTrue;
public class ComponentSpecTestCase {
@Test
- public void testMatches() {
+ void testMatches() {
ComponentId a = new ComponentId("test:1");
ComponentId b = new ComponentId("test:1.1.1");
ComponentId c = new ComponentId("test:2");
@@ -52,14 +50,14 @@ public class ComponentSpecTestCase {
}
@Test
- public void testMatchesWithNamespace() {
+ void testMatchesWithNamespace() {
ComponentId namespace = new ComponentId("namespace:2");
ComponentId a = new ComponentId("test", new Version(1), namespace);
ComponentId b = new ComponentId("test:1@namespace:2");
ComponentId c = new ComponentId("test:1@namespace");
assertEquals(a, b);
- assertFalse(a.equals(c));
+ assertNotEquals(a, c);
ComponentSpecification spec = new ComponentSpecification("test", null, namespace);
assertTrue(spec.matches(a));
@@ -68,7 +66,7 @@ public class ComponentSpecTestCase {
}
@Test
- public void testStringValue() {
+ void testStringValue() {
assertStringValueEqualsInputSpec("a:1.0.0.alpha@namespace");
assertStringValueEqualsInputSpec("a:1.0.0.alpha");
assertStringValueEqualsInputSpec("a:1.0");
diff --git a/container-core/src/test/java/com/yahoo/component/chain/dependencies/ordering/ChainBuilderTest.java b/container-core/src/test/java/com/yahoo/component/chain/dependencies/ordering/ChainBuilderTest.java
index a83de433968..6e107bf9934 100644
--- a/container-core/src/test/java/com/yahoo/component/chain/dependencies/ordering/ChainBuilderTest.java
+++ b/container-core/src/test/java/com/yahoo/component/chain/dependencies/ordering/ChainBuilderTest.java
@@ -8,7 +8,7 @@ import com.yahoo.component.chain.Phase;
import com.yahoo.component.chain.dependencies.After;
import com.yahoo.component.chain.dependencies.Before;
import com.yahoo.component.chain.dependencies.Provides;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
@@ -18,8 +18,8 @@ import java.util.Iterator;
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;
/**
* @author Tony Vaagenes
@@ -56,7 +56,7 @@ public class ChainBuilderTest {
}
@Test
- public void testRegular() throws Exception {
+ void testRegular() throws Exception {
ChainBuilder chainBuilder = createDependencyHandler();
addAtoG(chainBuilder);
@@ -64,13 +64,13 @@ public class ChainBuilderTest {
Chain<ChainedComponent> res = chainBuilder.orderNodes();
Iterator<ChainedComponent> i = res.components().iterator();
- for (char j=0; j< 'G' - 'A'; ++j) {
- assertEquals(String.valueOf((char)('A' + j)), name(i.next()));
+ for (char j = 0; j < 'G' - 'A'; ++j) {
+ assertEquals(String.valueOf((char) ('A' + j)), name(i.next()));
}
}
@Test
- public void testCycle() throws Exception {
+ void testCycle() throws Exception {
ChainBuilder chainBuilder = createDependencyHandler();
@@ -88,7 +88,7 @@ public class ChainBuilderTest {
@Test
- public void testPhaseAndSearcher() {
+ void testPhaseAndSearcher() {
ChainBuilder depHandler = newChainBuilder();
depHandler.addPhase(new Phase("phase1", set("phase2"), Collections.<String>emptySet()));
depHandler.addPhase(new Phase("phase2", set("phase3"), set("phase1")));
@@ -103,7 +103,7 @@ public class ChainBuilderTest {
}
@Test
- public void testInputOrderPreservedWhenProvidesOverlap() {
+ void testInputOrderPreservedWhenProvidesOverlap() {
ChainBuilder chainBuilder = newChainBuilder();
A a1 = new A();
@@ -136,38 +136,38 @@ public class ChainBuilderTest {
}
@Test
- public void testAfterAll1() throws Exception {
+ void testAfterAll1() throws Exception {
ChainBuilder chainBuilder = createDependencyHandler();
ChainedComponent afterAll1 = new AfterAll();
chainBuilder.addComponent(afterAll1);
addAtoG(chainBuilder);
- List<ChainedComponent> resolution= chainBuilder.orderNodes().components();
- assertEquals(afterAll1,resolution.get(resolution.size()-1));
+ List<ChainedComponent> resolution = chainBuilder.orderNodes().components();
+ assertEquals(afterAll1, resolution.get(resolution.size() - 1));
}
@Test
- public void testAfterAll2() throws Exception {
+ void testAfterAll2() throws Exception {
ChainBuilder chainBuilder = createDependencyHandler();
addAtoG(chainBuilder);
ChainedComponent afterAll1 = new AfterAll();
chainBuilder.addComponent(afterAll1);
List<ChainedComponent> resolution = chainBuilder.orderNodes().components();
- assertEquals(afterAll1,resolution.get(resolution.size()-1));
+ assertEquals(afterAll1, resolution.get(resolution.size() - 1));
}
@Test
- public void testAfterImplicitProvides()
+ void testAfterImplicitProvides()
throws InstantiationException, IllegalAccessException {
ChainBuilder chainBuilder = createDependencyHandler();
- ChainedComponent afterProvidesNothing=new AfterProvidesNothing();
- ChainedComponent providesNothing=new ProvidesNothing();
+ ChainedComponent afterProvidesNothing = new AfterProvidesNothing();
+ ChainedComponent providesNothing = new ProvidesNothing();
chainBuilder.addComponent(afterProvidesNothing);
chainBuilder.addComponent(providesNothing);
List<ChainedComponent> resolution = chainBuilder.orderNodes().components();
- assertEquals(providesNothing,resolution.get(0));
- assertEquals(afterProvidesNothing,resolution.get(1));
+ assertEquals(providesNothing, resolution.get(0));
+ assertEquals(afterProvidesNothing, resolution.get(1));
}
private ChainBuilder createDependencyHandler() {
diff --git a/container-core/src/test/java/com/yahoo/component/chain/dependencies/ordering/OrderedReadyNodesTest.java b/container-core/src/test/java/com/yahoo/component/chain/dependencies/ordering/OrderedReadyNodesTest.java
index c33fb71a07c..a5704b51bbe 100644
--- a/container-core/src/test/java/com/yahoo/component/chain/dependencies/ordering/OrderedReadyNodesTest.java
+++ b/container-core/src/test/java/com/yahoo/component/chain/dependencies/ordering/OrderedReadyNodesTest.java
@@ -1,19 +1,17 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.component.chain.dependencies.ordering;
-import static org.junit.Assert.assertEquals;
-
import java.util.Arrays;
import com.yahoo.component.chain.ChainedComponent;
-import com.yahoo.component.chain.dependencies.Dependencies;
-import org.junit.Before;
-import org.junit.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import com.yahoo.component.chain.dependencies.Dependencies;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import com.yahoo.component.ComponentId;
-
/**
* Test for OrderedReadyNodes.
*
@@ -41,13 +39,13 @@ public class OrderedReadyNodesTest {
private OrderedReadyNodes readyNodes;
- @Before
+ @BeforeEach
public void setup() {
readyNodes = new OrderedReadyNodes();
}
@Test
- public void require_NameProviders_before_SearcherNodes() {
+ void require_NameProviders_before_SearcherNodes() {
NameProvider nameProvider = createDummyNameProvider(100);
ComponentNode componentNode = new ComponentNode<>(createFakeComponentA("a"), 1);
@@ -72,7 +70,7 @@ public class OrderedReadyNodesTest {
}
@Test
- public void require_SearcherNodes_ordered_by_insertion_order() {
+ void require_SearcherNodes_ordered_by_insertion_order() {
int priority = 0;
ComponentNode a = new ComponentNode<>(createFakeComponentB("1"), priority++);
ComponentNode b = new ComponentNode<>(createFakeComponentA("2"), priority++);
diff --git a/container-core/src/test/java/com/yahoo/component/chain/model/ChainsModelBuilderTest.java b/container-core/src/test/java/com/yahoo/component/chain/model/ChainsModelBuilderTest.java
index 54b57789ba8..0871b36b0b3 100644
--- a/container-core/src/test/java/com/yahoo/component/chain/model/ChainsModelBuilderTest.java
+++ b/container-core/src/test/java/com/yahoo/component/chain/model/ChainsModelBuilderTest.java
@@ -4,15 +4,15 @@ package com.yahoo.component.chain.model;
import com.yahoo.component.ComponentId;
import com.yahoo.component.ComponentSpecification;
import com.yahoo.container.core.ChainsConfig;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Map;
import java.util.Set;
import static com.yahoo.container.core.ChainsConfig.Components;
import static com.yahoo.container.core.ChainsConfig.Chains;
-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
@@ -20,27 +20,27 @@ import static org.junit.Assert.assertTrue;
public class ChainsModelBuilderTest {
@Test
- public void components_are_added_to_componentModels() throws Exception {
+ void components_are_added_to_componentModels() throws Exception {
ChainsModel model = chainsModel();
assertEquals(2, model.allComponents().size());
assertTrue(model.componentModels().containsKey(new ComponentId("componentA")));
}
@Test
- public void components_are_added_to_chainSpecification() throws Exception {
+ void components_are_added_to_chainSpecification() throws Exception {
ChainsModel model = chainsModel();
ChainSpecification chainSpec = model.chainSpecifications().get(new ComponentId("chain1")).model();
assertTrue(getComponentsByName(chainSpec.componentReferences).containsKey("componentA"));
}
@Test
- public void inherited_chains_are_added_to_chainSpecification() throws Exception {
+ void inherited_chains_are_added_to_chainSpecification() throws Exception {
ChainsModel model = chainsModel();
ChainSpecification inheritsChain1 = model.chainSpecifications().get(new ComponentId("inheritsChain1")).model();
assertEquals(2, model.allChainsFlattened().size());
assertTrue(getComponentsByName(inheritsChain1.inheritance.chainSpecifications).containsKey("chain1"));
assertTrue(getComponentsByName(inheritsChain1.inheritance.excludedComponents).containsKey("componentA"));
- }
+ }
private ChainsModel chainsModel() {
ChainsConfig.Builder builder = new ChainsConfig.Builder()
diff --git a/container-core/src/test/java/com/yahoo/component/provider/test/ComponentRegistryTestCase.java b/container-core/src/test/java/com/yahoo/component/provider/test/ComponentRegistryTestCase.java
index 5f8fec564bc..eb7439df0ff 100644
--- a/container-core/src/test/java/com/yahoo/component/provider/test/ComponentRegistryTestCase.java
+++ b/container-core/src/test/java/com/yahoo/component/provider/test/ComponentRegistryTestCase.java
@@ -1,12 +1,11 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.component.provider.test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-
-import org.junit.Before;
-import org.junit.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import com.yahoo.component.AbstractComponent;
import com.yahoo.component.ComponentId;
import com.yahoo.component.ComponentSpecification;
@@ -48,7 +47,7 @@ public class ComponentRegistryTestCase {
return new TestComponent(idInNamespace(namespace));
}
- @Before
+ @BeforeEach
public void before() {
registry = new ComponentRegistry<>();
@@ -58,19 +57,19 @@ public class ComponentRegistryTestCase {
}
@Test
- public void testAllPresent() {
+ void testAllPresent() {
assertEquals(3, registry.getComponentCount());
}
@Test
- public void testIdNamespaceLookup() {
+ void testIdNamespaceLookup() {
assertEquals(component1, registry.getComponent(idInNamespace(namespace1)));
assertEquals(component2, registry.getComponent(idInNamespace(namespace2)));
assertEquals(component21, registry.getComponent(idInNamespace(namespace21)));
}
@Test
- public void testSpecNamespaceLookup() {
+ void testSpecNamespaceLookup() {
assertEquals(component1, registry.getComponent(specInNamespace(namespace1)));
// Version for namespace must match the specification exactly, so do not return version '1' when an
@@ -80,7 +79,7 @@ public class ComponentRegistryTestCase {
}
@Test
- public void testInnerComponentNotMixedWithTopLevelComponent() {
+ void testInnerComponentNotMixedWithTopLevelComponent() {
assertNull(registry.getComponent(componentName));
TestComponent topLevel = new TestComponent(new ComponentId(componentName));
diff --git a/container-core/src/test/java/com/yahoo/component/test/ComponentIdTestCase.java b/container-core/src/test/java/com/yahoo/component/test/ComponentIdTestCase.java
index 8d86010ea5a..4561c18bc3d 100644
--- a/container-core/src/test/java/com/yahoo/component/test/ComponentIdTestCase.java
+++ b/container-core/src/test/java/com/yahoo/component/test/ComponentIdTestCase.java
@@ -2,9 +2,9 @@
package com.yahoo.component.test;
import com.yahoo.component.ComponentId;
-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 bratseth
@@ -12,27 +12,26 @@ import static org.junit.Assert.assertEquals;
public class ComponentIdTestCase {
@Test
- public void testFileNameConversion() {
- assertFileNameEquals("a","a");
- assertFileNameEquals("a-1","a-1");
- assertFileNameEquals("a-1","a-1.0.0");
- assertFileNameEquals("a-1.0.0.qualifier","a-1.0.0.qualifier");
- assertFileNameEquals("a.b-1.0.0.qualifier","a.b-1.0.0.qualifier");
- assertFileNameEquals("a@space","a@space");
- assertFileNameEquals("a-1@space","a-1@space");
- assertFileNameEquals("a-1@space","a-1.0.0@space");
- assertFileNameEquals("a-1.0.0.qualifier@space","a-1.0.0.qualifier@space");
- assertFileNameEquals("a.b-1.0.0.qualifier@space","a.b-1.0.0.qualifier@space");
+ void testFileNameConversion() {
+ assertFileNameEquals("a", "a");
+ assertFileNameEquals("a-1", "a-1");
+ assertFileNameEquals("a-1", "a-1.0.0");
+ assertFileNameEquals("a-1.0.0.qualifier", "a-1.0.0.qualifier");
+ assertFileNameEquals("a.b-1.0.0.qualifier", "a.b-1.0.0.qualifier");
+ assertFileNameEquals("a@space", "a@space");
+ assertFileNameEquals("a-1@space", "a-1@space");
+ assertFileNameEquals("a-1@space", "a-1.0.0@space");
+ assertFileNameEquals("a-1.0.0.qualifier@space", "a-1.0.0.qualifier@space");
+ assertFileNameEquals("a.b-1.0.0.qualifier@space", "a.b-1.0.0.qualifier@space");
}
/** Takes two id file names as input */
private void assertFileNameEquals(String expected,String initial) {
- assertEquals("'" + initial + "' became id '" + ComponentId.fromFileName(initial) + "' which should become '" + expected + "'",
- expected,ComponentId.fromFileName(initial).toFileName());
+ assertEquals(expected,ComponentId.fromFileName(initial).toFileName(),"'" + initial + "' became id '" + ComponentId.fromFileName(initial) + "' which should become '" + expected + "'");
}
@Test
- public void testCompareWithNameSpace() {
+ void testCompareWithNameSpace() {
ComponentId withNS = ComponentId.fromString("foo@ns");
ComponentId withoutNS = ComponentId.fromString("foo"); // Should be less than withNs
diff --git a/container-core/src/test/java/com/yahoo/container/core/config/ApplicationBundleLoaderTest.java b/container-core/src/test/java/com/yahoo/container/core/config/ApplicationBundleLoaderTest.java
index 4f6fea76828..cf8cc6053cd 100644
--- a/container-core/src/test/java/com/yahoo/container/core/config/ApplicationBundleLoaderTest.java
+++ b/container-core/src/test/java/com/yahoo/container/core/config/ApplicationBundleLoaderTest.java
@@ -5,16 +5,16 @@ import com.yahoo.config.FileReference;
import com.yahoo.filedistribution.fileacquirer.FileAcquirer;
import com.yahoo.filedistribution.fileacquirer.MockFileAcquirer;
import com.yahoo.osgi.Osgi;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.osgi.framework.Bundle;
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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author gjoranv
@@ -29,7 +29,7 @@ public class ApplicationBundleLoaderTest {
private ApplicationBundleLoader bundleLoader;
private TestOsgi osgi;
- @Before
+ @BeforeEach
public void setup() {
osgi = new TestOsgi(testBundles());
var bundleInstaller = new TestBundleInstaller(MockFileAcquirer.returnFile(null));
@@ -38,12 +38,12 @@ public class ApplicationBundleLoaderTest {
}
@Test
- public void bundles_are_installed_and_started() {
+ void bundles_are_installed_and_started() {
bundleLoader.useBundles(List.of(BUNDLE_1_REF));
assertEquals(1, osgi.getInstalledBundles().size());
// The bundle is installed and started
- TestBundle installedBundle = (TestBundle)osgi.getInstalledBundles().get(0);
+ TestBundle installedBundle = (TestBundle) osgi.getInstalledBundles().get(0);
assertEquals(BUNDLE_1.getSymbolicName(), installedBundle.getSymbolicName());
assertTrue(installedBundle.started);
@@ -53,7 +53,7 @@ public class ApplicationBundleLoaderTest {
}
@Test
- public void new_bundle_can_be_installed_in_reconfig() {
+ void new_bundle_can_be_installed_in_reconfig() {
bundleLoader.useBundles(List.of(BUNDLE_1_REF));
Set<Bundle> obsoleteBundles = bundleLoader.useBundles(List.of(BUNDLE_1_REF, BUNDLE_2_REF));
@@ -78,7 +78,7 @@ public class ApplicationBundleLoaderTest {
}
@Test
- public void unused_bundle_is_marked_obsolete_after_reconfig() {
+ void unused_bundle_is_marked_obsolete_after_reconfig() {
bundleLoader.useBundles(List.of(BUNDLE_1_REF));
Set<Bundle> obsoleteBundles = bundleLoader.useBundles(List.of(BUNDLE_2_REF));
diff --git a/container-core/src/test/java/com/yahoo/container/core/config/PlatformBundleLoaderTest.java b/container-core/src/test/java/com/yahoo/container/core/config/PlatformBundleLoaderTest.java
index 3cd9779f878..21d99915c5c 100644
--- a/container-core/src/test/java/com/yahoo/container/core/config/PlatformBundleLoaderTest.java
+++ b/container-core/src/test/java/com/yahoo/container/core/config/PlatformBundleLoaderTest.java
@@ -2,15 +2,15 @@
package com.yahoo.container.core.config;
import com.yahoo.osgi.Osgi;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.osgi.framework.Bundle;
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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author gjoranv
@@ -25,25 +25,25 @@ public class PlatformBundleLoaderTest {
private PlatformBundleLoader bundleLoader;
private TestOsgi osgi;
- @Before
+ @BeforeEach
public void setup() {
osgi = new TestOsgi(testBundles());
bundleLoader = new PlatformBundleLoader(osgi, new TestBundleInstaller());
}
@Test
- public void bundles_are_installed_and_started() {
+ void bundles_are_installed_and_started() {
bundleLoader.useBundles(List.of(BUNDLE_1_REF));
assertEquals(1, osgi.getInstalledBundles().size());
// The bundle is installed and started
- TestBundle installedBundle = (TestBundle)osgi.getInstalledBundles().get(0);
+ TestBundle installedBundle = (TestBundle) osgi.getInstalledBundles().get(0);
assertEquals(BUNDLE_1.getSymbolicName(), installedBundle.getSymbolicName());
assertTrue(installedBundle.started);
}
@Test
- public void bundles_cannot_be_added_by_later_calls() {
+ void bundles_cannot_be_added_by_later_calls() {
bundleLoader.useBundles(List.of(BUNDLE_1_REF));
bundleLoader.useBundles(List.of(BUNDLE_2_REF)); // Should be a NOP
diff --git a/container-core/src/test/java/com/yahoo/container/di/ConfigRetrieverTest.java b/container-core/src/test/java/com/yahoo/container/di/ConfigRetrieverTest.java
index 695efbf7c17..942555e391d 100644
--- a/container-core/src/test/java/com/yahoo/container/di/ConfigRetrieverTest.java
+++ b/container-core/src/test/java/com/yahoo/container/di/ConfigRetrieverTest.java
@@ -9,18 +9,20 @@ import com.yahoo.container.di.ConfigRetriever.BootstrapConfigs;
import com.yahoo.container.di.ConfigRetriever.ComponentsConfigs;
import com.yahoo.container.di.ConfigRetriever.ConfigSnapshot;
import com.yahoo.vespa.config.ConfigKey;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import java.io.File;
import java.util.Collections;
import java.util.HashSet;
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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
*
@@ -32,18 +34,21 @@ public class ConfigRetrieverTest {
private DirConfigSource dirConfigSource = null;
- @Before
+ @TempDir
+ File tmpDir;
+
+ @BeforeEach
public void setup() {
- dirConfigSource = new DirConfigSource("ConfigRetrieverTest-");
+ dirConfigSource = new DirConfigSource(tmpDir, "ConfigRetrieverTest-");
}
- @After
+ @AfterEach
public void cleanup() {
dirConfigSource.cleanup();
}
@Test
- public void require_that_bootstrap_configs_come_first() {
+ void require_that_bootstrap_configs_come_first() {
writeConfigs();
ConfigRetriever retriever = createConfigRetriever();
ConfigSnapshot bootstrapConfigs = retriever.getConfigs(Collections.emptySet(), 0, true);
@@ -53,7 +58,7 @@ public class ConfigRetrieverTest {
@Test
@SuppressWarnings("unused")
- public void require_that_components_comes_after_bootstrap() {
+ void require_that_components_comes_after_bootstrap() {
writeConfigs();
ConfigRetriever retriever = createConfigRetriever();
ConfigSnapshot bootstrapConfigs = retriever.getConfigs(Collections.emptySet(), 0, true);
@@ -68,7 +73,7 @@ public class ConfigRetrieverTest {
}
}
- @Ignore
+ @Disabled
@SuppressWarnings("unused")
public void require_exception_upon_modified_components_keys_without_bootstrap() {
@@ -89,7 +94,7 @@ public class ConfigRetrieverTest {
}
@Test
- public void require_that_empty_components_keys_after_bootstrap_returns_components_configs() {
+ void require_that_empty_components_keys_after_bootstrap_returns_components_configs() {
writeConfigs();
ConfigRetriever retriever = createConfigRetriever();
assertTrue(retriever.getConfigs(Collections.emptySet(), 0, true) instanceof BootstrapConfigs);
diff --git a/container-core/src/test/java/com/yahoo/container/di/ContainerTest.java b/container-core/src/test/java/com/yahoo/container/di/ContainerTest.java
index 30dc4f313e4..04091c25ad6 100644
--- a/container-core/src/test/java/com/yahoo/container/di/ContainerTest.java
+++ b/container-core/src/test/java/com/yahoo/container/di/ContainerTest.java
@@ -9,8 +9,8 @@ import com.yahoo.container.di.componentgraph.Provider;
import com.yahoo.container.di.componentgraph.core.ComponentGraph;
import com.yahoo.container.di.componentgraph.core.ComponentGraphTest.SimpleComponent;
import com.yahoo.container.di.componentgraph.core.ComponentNode.ComponentConstructorException;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
import org.osgi.framework.Bundle;
import java.util.Collection;
@@ -20,13 +20,7 @@ import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
-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.Assert.assertThrows;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Tony Vaagenes
@@ -36,7 +30,7 @@ import static org.junit.Assert.fail;
public class ContainerTest extends ContainerTestBase {
@Test
- public void components_can_be_created_from_config() {
+ void components_can_be_created_from_config() {
writeBootstrapConfigs();
dirConfigSource.writeConfig("test", "stringVal \"myString\"");
@@ -49,7 +43,7 @@ public class ContainerTest extends ContainerTestBase {
}
@Test
- public void components_are_reconfigured_after_config_update_without_bootstrap_configs() {
+ void components_are_reconfigured_after_config_update_without_bootstrap_configs() {
writeBootstrapConfigs();
dirConfigSource.writeConfig("test", "stringVal \"original\"");
@@ -71,7 +65,7 @@ public class ContainerTest extends ContainerTestBase {
}
@Test
- public void graph_is_updated_after_bootstrap_update() {
+ void graph_is_updated_after_bootstrap_update() {
dirConfigSource.writeConfig("test", "stringVal \"original\"");
writeBootstrapConfigs("id1");
@@ -99,7 +93,7 @@ public class ContainerTest extends ContainerTestBase {
}
@Test
- public void component_is_deconstructed_when_not_reused() {
+ void component_is_deconstructed_when_not_reused() {
writeBootstrapConfigs("id1", DestructableComponent.class);
Container container = newContainer(dirConfigSource);
@@ -113,9 +107,9 @@ public class ContainerTest extends ContainerTestBase {
assertTrue(componentToDestruct.deconstructed);
}
- @Ignore // because logAndDie is impossible(?) to verify programmatically
+ @Disabled // because logAndDie is impossible(?) to verify programmatically
@Test
- public void manually_verify_what_happens_when_first_graph_contains_component_that_throws_exception_in_ctor() {
+ void manually_verify_what_happens_when_first_graph_contains_component_that_throws_exception_in_ctor() {
writeBootstrapConfigs("thrower", ComponentThrowingExceptionInConstructor.class);
Container container = newContainer(dirConfigSource);
try {
@@ -127,7 +121,7 @@ public class ContainerTest extends ContainerTestBase {
}
@Test
- public void previous_graph_is_retained_when_new_graph_contains_component_that_throws_exception_in_ctor() {
+ void previous_graph_is_retained_when_new_graph_contains_component_that_throws_exception_in_ctor() {
ComponentEntry simpleComponentEntry = new ComponentEntry("simpleComponent", SimpleComponent.class);
writeBootstrapConfigs(simpleComponentEntry);
@@ -161,7 +155,7 @@ public class ContainerTest extends ContainerTestBase {
}
@Test
- public void previous_graph_is_retained_when_new_graph_throws_exception_for_missing_config() {
+ void previous_graph_is_retained_when_new_graph_throws_exception_for_missing_config() {
ComponentEntry simpleComponentEntry = new ComponentEntry("simpleComponent", SimpleComponent.class);
writeBootstrapConfigs(simpleComponentEntry);
@@ -185,7 +179,7 @@ public class ContainerTest extends ContainerTestBase {
}
@Test
- public void getNewComponentGraph_hangs_waiting_for_valid_config_after_invalid_config() throws Exception {
+ void getNewComponentGraph_hangs_waiting_for_valid_config_after_invalid_config() throws Exception {
dirConfigSource.writeConfig("test", "stringVal \"original\"");
writeBootstrapConfigs("myId", ComponentTakingConfig.class);
@@ -196,7 +190,7 @@ public class ContainerTest extends ContainerTestBase {
container.reloadConfig(2);
assertThrows(IllegalArgumentException.class,
- () -> getNewComponentGraph(container, currentGraph));
+ () -> getNewComponentGraph(container, currentGraph));
ExecutorService exec = Executors.newFixedThreadPool(1);
Future<ComponentGraph> newGraph = exec.submit(() -> getNewComponentGraph(container, currentGraph));
@@ -215,7 +209,7 @@ public class ContainerTest extends ContainerTestBase {
}
@Test
- public void providers_are_destructed() {
+ void providers_are_destructed() {
writeBootstrapConfigs("id1", DestructableProvider.class);
ComponentDeconstructor deconstructor = (generation, components, bundles) -> {
@@ -226,7 +220,7 @@ public class ContainerTest extends ContainerTestBase {
((Provider<?>) component).deconstruct();
}
});
- if (! bundles.isEmpty()) throw new IllegalArgumentException("This test should not use bundles");
+ if (!bundles.isEmpty()) throw new IllegalArgumentException("This test should not use bundles");
};
Container container = newContainer(dirConfigSource, deconstructor);
@@ -242,7 +236,7 @@ public class ContainerTest extends ContainerTestBase {
}
@Test
- public void providers_are_invoked_only_when_needed() {
+ void providers_are_invoked_only_when_needed() {
writeBootstrapConfigs("id1", FailOnGetProvider.class);
Container container = newContainer(dirConfigSource);
diff --git a/container-core/src/test/java/com/yahoo/container/di/ContainerTestBase.java b/container-core/src/test/java/com/yahoo/container/di/ContainerTestBase.java
index e7f12d3f228..4383bd08f71 100644
--- a/container-core/src/test/java/com/yahoo/container/di/ContainerTestBase.java
+++ b/container-core/src/test/java/com/yahoo/container/di/ContainerTestBase.java
@@ -7,10 +7,12 @@ import com.yahoo.config.FileReference;
import com.yahoo.container.bundle.BundleInstantiationSpecification;
import com.yahoo.container.di.ContainerTest.ComponentTakingConfig;
import com.yahoo.container.di.componentgraph.core.ComponentGraph;
-import org.junit.After;
-import org.junit.Before;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.io.TempDir;
import org.osgi.framework.Bundle;
+import java.io.File;
import java.util.Collection;
import java.util.Set;
@@ -26,17 +28,20 @@ public class ContainerTestBase {
private ComponentGraph componentGraph;
protected DirConfigSource dirConfigSource = null;
- @Before
+ @TempDir
+ File tmpDir;
+
+ @BeforeEach
public void setup() {
- dirConfigSource = new DirConfigSource("ContainerTest-");
+ dirConfigSource = new DirConfigSource(tmpDir, "ContainerTest-");
}
- @After
+ @AfterEach
public void cleanup() {
dirConfigSource.cleanup();
}
- @Before
+ @BeforeEach
public void createGraph() {
componentGraph = new ComponentGraph(0);
}
diff --git a/container-core/src/test/java/com/yahoo/container/di/DirConfigSource.java b/container-core/src/test/java/com/yahoo/container/di/DirConfigSource.java
index 43b2c8ad8e6..db7e93f7c6e 100644
--- a/container-core/src/test/java/com/yahoo/container/di/DirConfigSource.java
+++ b/container-core/src/test/java/com/yahoo/container/di/DirConfigSource.java
@@ -3,7 +3,6 @@ package com.yahoo.container.di;
import com.yahoo.config.subscription.ConfigSource;
import com.yahoo.config.subscription.ConfigSourceSet;
-import org.junit.rules.TemporaryFolder;
import java.io.File;
import java.io.FileOutputStream;
@@ -18,15 +17,16 @@ import java.util.Random;
*/
public class DirConfigSource {
- private final TemporaryFolder tempFolder = createTemporaryFolder();
+ private final File tempFolder;
public final ConfigSource configSource;
- public DirConfigSource(String testSourcePrefix) {
+ public DirConfigSource(File tmpDir, String testSourcePrefix) {
+ this.tempFolder = tmpDir;
this.configSource = new ConfigSourceSet(testSourcePrefix + new Random().nextLong());
}
public void writeConfig(String name, String contents) {
- File file = new File(tempFolder.getRoot(), name + ".cfg");
+ File file = new File(tempFolder, name + ".cfg");
if (!file.exists()) {
try {
file.createNewFile();
@@ -39,7 +39,7 @@ public class DirConfigSource {
}
public String configId() {
- return "dir:" + tempFolder.getRoot().getPath();
+ return "dir:" + tempFolder.getPath();
}
public ConfigSource configSource() {
@@ -58,14 +58,4 @@ public class DirConfigSource {
}
}
- private static TemporaryFolder createTemporaryFolder() {
- TemporaryFolder folder = new TemporaryFolder();
- try {
- folder.create();
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- return folder;
- }
-
}
diff --git a/container-core/src/test/java/com/yahoo/container/di/componentgraph/core/ComponentGraphTest.java b/container-core/src/test/java/com/yahoo/container/di/componentgraph/core/ComponentGraphTest.java
index 5abb96527bd..c21c1b35782 100644
--- a/container-core/src/test/java/com/yahoo/container/di/componentgraph/core/ComponentGraphTest.java
+++ b/container-core/src/test/java/com/yahoo/container/di/componentgraph/core/ComponentGraphTest.java
@@ -18,7 +18,7 @@ import com.yahoo.config.test.Test2Config;
import com.yahoo.config.test.TestConfig;
import com.yahoo.container.di.componentgraph.Provider;
import com.yahoo.vespa.config.ConfigKey;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.lang.annotation.Annotation;
import java.util.Collections;
@@ -30,13 +30,7 @@ import java.util.concurrent.Executors;
import java.util.function.Supplier;
import static com.yahoo.container.di.componentgraph.core.ComponentGraph.isBindingAnnotation;
-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.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author gjoranv
@@ -65,7 +59,7 @@ public class ComponentGraphTest {
}
@Test
- public void component_taking_config_can_be_instantiated() {
+ void component_taking_config_can_be_instantiated() {
ComponentGraph componentGraph = new ComponentGraph();
String configId = "raw:stringVal \"test-value\"";
Node componentNode = mockComponentNode(ComponentTakingConfig.class, configId);
@@ -80,7 +74,7 @@ public class ComponentGraphTest {
}
@Test
- public void all_created_components_are_returned_in_reverse_topological_order() {
+ void all_created_components_are_returned_in_reverse_topological_order() {
for (int i = 0; i < 10; i++) {
Node innerComponent = mockComponentNode(SimpleComponent.class);
Node middleComponent = mockComponentNode(ComponentTakingComponent.class);
@@ -97,12 +91,12 @@ public class ComponentGraphTest {
outerComponent.constructInstance();
assertEquals(List.of(outerComponent.constructedInstance().get(), middleComponent.constructedInstance().get(), innerComponent.constructedInstance().get()),
- componentGraph.allConstructedComponentsAndProviders());
+ componentGraph.allConstructedComponentsAndProviders());
}
}
@Test
- public void component_can_be_explicitly_injected_into_another_component() {
+ void component_can_be_explicitly_injected_into_another_component() {
Node injectedComponent = mockComponentNode(SimpleComponent.class);
Node targetComponent = mockComponentNode(ComponentTakingComponent.class);
targetComponent.inject(injectedComponent);
@@ -121,7 +115,7 @@ public class ComponentGraphTest {
}
@Test
- public void explicitly_injected_components_may_be_unused() {
+ void explicitly_injected_components_may_be_unused() {
Node notUsingInjected = mockComponentNode(SimpleComponent.class);
Node injectedComponent = mockComponentNode(SimpleComponent2.class);
notUsingInjected.inject(injectedComponent);
@@ -136,7 +130,7 @@ public class ComponentGraphTest {
}
@Test
- public void interface_implementation_can_be_injected() {
+ void interface_implementation_can_be_injected() {
ComponentGraph componentGraph = new ComponentGraph();
componentGraph.add(mockComponentNode(ComponentImpl.class));
componentGraph.add(mockComponentNode(ComponentTakingInterface.class));
@@ -147,7 +141,7 @@ public class ComponentGraphTest {
}
@Test
- public void private_class_with_public_ctor_can_be_instantiated() {
+ void private_class_with_public_ctor_can_be_instantiated() {
ComponentGraph componentGraph = new ComponentGraph();
componentGraph.add(mockComponentNode(PrivateClassComponent.class));
componentGraph.complete();
@@ -157,7 +151,7 @@ public class ComponentGraphTest {
}
@Test
- public void all_components_of_a_type_can_be_injected() {
+ void all_components_of_a_type_can_be_injected() {
ComponentGraph componentGraph = new ComponentGraph();
componentGraph.add(mockComponentNode(SimpleComponent.class));
componentGraph.add(mockComponentNode(SimpleComponent.class));
@@ -170,7 +164,7 @@ public class ComponentGraphTest {
}
@Test
- public void empty_component_registry_can_be_injected() {
+ void empty_component_registry_can_be_injected() {
ComponentGraph componentGraph = new ComponentGraph();
componentGraph.add(mockComponentNode(ComponentTakingAllSimpleComponents.class));
componentGraph.complete();
@@ -180,7 +174,7 @@ public class ComponentGraphTest {
}
@Test
- public void component_registry_with_wildcard_upper_bound_can_be_injected() {
+ void component_registry_with_wildcard_upper_bound_can_be_injected() {
ComponentGraph componentGraph = new ComponentGraph();
componentGraph.add(mockComponentNode(SimpleComponent.class));
componentGraph.add(mockComponentNode(SimpleDerivedComponent.class));
@@ -192,22 +186,24 @@ public class ComponentGraphTest {
assertEquals(2, instance.simpleComponents.allComponents().size());
}
- @Test(expected = RuntimeException.class)
- public void require_exception_when_injecting_registry_with_unknown_type_variable() {
- @SuppressWarnings("rawtypes")
- Class<ComponentTakingAllComponentsWithTypeVariable> clazz = ComponentTakingAllComponentsWithTypeVariable.class;
+ @Test
+ void require_exception_when_injecting_registry_with_unknown_type_variable() {
+ assertThrows(RuntimeException.class, () -> {
+ @SuppressWarnings("rawtypes")
+ Class<ComponentTakingAllComponentsWithTypeVariable> clazz = ComponentTakingAllComponentsWithTypeVariable.class;
- ComponentGraph componentGraph = new ComponentGraph();
- componentGraph.add(mockComponentNode(SimpleComponent.class));
- componentGraph.add(mockComponentNode(SimpleDerivedComponent.class));
- componentGraph.add(mockComponentNode(clazz));
- componentGraph.complete();
+ ComponentGraph componentGraph = new ComponentGraph();
+ componentGraph.add(mockComponentNode(SimpleComponent.class));
+ componentGraph.add(mockComponentNode(SimpleDerivedComponent.class));
+ componentGraph.add(mockComponentNode(clazz));
+ componentGraph.complete();
- componentGraph.getInstance(clazz);
+ componentGraph.getInstance(clazz);
+ });
}
@Test
- public void components_are_shared() {
+ void components_are_shared() {
ComponentGraph componentGraph = new ComponentGraph();
componentGraph.add(mockComponentNode(SimpleComponent.class));
componentGraph.complete();
@@ -218,7 +214,7 @@ public class ComponentGraphTest {
}
@Test
- public void singleton_components_can_be_injected() {
+ void singleton_components_can_be_injected() {
ComponentGraph componentGraph = new ComponentGraph();
String configId = "raw:stringVal \"test-value\"";
@@ -233,17 +229,19 @@ public class ComponentGraphTest {
assertEquals("test-value", injected.config.stringVal());
}
- @Test(expected = RuntimeException.class)
- public void require_error_when_multiple_components_match_a_singleton_dependency() {
- ComponentGraph componentGraph = new ComponentGraph();
- componentGraph.add(mockComponentNode(SimpleDerivedComponent.class));
- componentGraph.add(mockComponentNode(SimpleComponent.class));
- componentGraph.add(mockComponentNode(ComponentTakingComponent.class));
- componentGraph.complete();
+ @Test
+ void require_error_when_multiple_components_match_a_singleton_dependency() {
+ assertThrows(RuntimeException.class, () -> {
+ ComponentGraph componentGraph = new ComponentGraph();
+ componentGraph.add(mockComponentNode(SimpleDerivedComponent.class));
+ componentGraph.add(mockComponentNode(SimpleComponent.class));
+ componentGraph.add(mockComponentNode(ComponentTakingComponent.class));
+ componentGraph.complete();
+ });
}
@Test
- public void named_component_can_be_injected() {
+ void named_component_can_be_injected() {
ComponentGraph componentGraph = new ComponentGraph();
componentGraph.add(mockComponentNode(SimpleComponent.class));
componentGraph.add(mockComponentNode(SimpleComponent.class, Names.named("named-test")));
@@ -252,7 +250,7 @@ public class ComponentGraphTest {
}
@Test
- public void config_keys_can_be_retrieved() {
+ void config_keys_can_be_retrieved() {
ComponentGraph componentGraph = new ComponentGraph();
componentGraph.add(mockComponentNode(ComponentTakingConfig.class, "raw:stringVal \"component1\""));
componentGraph.add(mockComponentNode(ComponentTakingConfig.class, "raw:stringVal \"component2\""));
@@ -269,7 +267,7 @@ public class ComponentGraphTest {
}
@Test
- public void providers_can_be_instantiated() {
+ void providers_can_be_instantiated() {
ComponentGraph componentGraph = new ComponentGraph();
componentGraph.add(mockComponentNode(ExecutorProvider.class));
componentGraph.complete();
@@ -278,7 +276,7 @@ public class ComponentGraphTest {
}
@Test
- public void providers_can_be_inherited() {
+ void providers_can_be_inherited() {
ComponentGraph componentGraph = new ComponentGraph();
componentGraph.add(mockComponentNode(DerivedExecutorProvider.class));
componentGraph.complete();
@@ -287,7 +285,7 @@ public class ComponentGraphTest {
}
@Test
- public void providers_can_deliver_a_new_instance_for_each_component() {
+ void providers_can_deliver_a_new_instance_for_each_component() {
ComponentGraph componentGraph = new ComponentGraph();
componentGraph.add(mockComponentNode(NewIntProvider.class));
componentGraph.complete();
@@ -299,7 +297,7 @@ public class ComponentGraphTest {
}
@Test
- public void providers_can_be_injected_explicitly() {
+ void providers_can_be_injected_explicitly() {
ComponentGraph componentGraph = new ComponentGraph();
Node componentTakingExecutor = mockComponentNode(ComponentTakingExecutor.class);
@@ -316,7 +314,7 @@ public class ComponentGraphTest {
}
@Test
- public void global_providers_can_be_injected() {
+ void global_providers_can_be_injected() {
ComponentGraph componentGraph = new ComponentGraph();
componentGraph.add(mockComponentNode(ComponentTakingExecutor.class));
@@ -327,18 +325,20 @@ public class ComponentGraphTest {
assertNotNull(componentGraph.getInstance(ComponentTakingExecutor.class));
}
- @Test(expected = RuntimeException.class)
- public void throw_if_multiple_global_providers_exist() {
- ComponentGraph componentGraph = new ComponentGraph();
+ @Test
+ void throw_if_multiple_global_providers_exist() {
+ assertThrows(RuntimeException.class, () -> {
+ ComponentGraph componentGraph = new ComponentGraph();
- componentGraph.add(mockComponentNode(ExecutorProvider.class));
- componentGraph.add(mockComponentNode(ExecutorProvider.class));
- componentGraph.add(mockComponentNode(ComponentTakingExecutor.class));
- componentGraph.complete();
+ componentGraph.add(mockComponentNode(ExecutorProvider.class));
+ componentGraph.add(mockComponentNode(ExecutorProvider.class));
+ componentGraph.add(mockComponentNode(ComponentTakingExecutor.class));
+ componentGraph.complete();
+ });
}
@Test
- public void provider_is_not_used_when_component_of_provided_class_exists() {
+ void provider_is_not_used_when_component_of_provided_class_exists() {
ComponentGraph componentGraph = new ComponentGraph();
componentGraph.add(mockComponentNode(SimpleComponent.class));
@@ -352,13 +352,13 @@ public class ComponentGraphTest {
//TODO: move
@Test
- public void check_if_annotation_is_a_binding_annotation() {
+ void check_if_annotation_is_a_binding_annotation() {
assertTrue(isBindingAnnotation(Names.named("name")));
assertFalse(isBindingAnnotation(Named.class.getAnnotations()[0]));
}
@Test
- public void cycles_gives_exception() {
+ void cycles_gives_exception() {
ComponentGraph componentGraph = new ComponentGraph();
Node node1 = mockComponentNode(ComponentCausingCycle.class);
@@ -379,18 +379,20 @@ public class ComponentGraphTest {
}
}
- @Test(expected = IllegalArgumentException.class)
- public void abstract_classes_are_rejected() {
- new ComponentNode(ComponentId.fromString("Test"), "", AbstractClass.class);
+ @Test
+ void abstract_classes_are_rejected() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new ComponentNode(ComponentId.fromString("Test"), "", AbstractClass.class);
+ });
}
@Test
- public void inject_constructor_is_preferred() {
+ void inject_constructor_is_preferred() {
assertThatComponentCanBeCreated(ComponentWithInjectConstructor.class);
}
@Test
- public void constructor_with_most_parameters_is_preferred() {
+ void constructor_with_most_parameters_is_preferred() {
assertThatComponentCanBeCreated(ComponentWithMultipleConstructors.class);
}
@@ -407,7 +409,7 @@ public class ComponentGraphTest {
}
@Test
- public void require_fallback_to_child_injector() {
+ void require_fallback_to_child_injector() {
ComponentGraph componentGraph = new ComponentGraph();
componentGraph.add(mockComponentNode(ComponentTakingExecutor.class));
@@ -417,7 +419,7 @@ public class ComponentGraphTest {
}
@Test
- public void child_injector_can_inject_multiple_instances_for_same_key() {
+ void child_injector_can_inject_multiple_instances_for_same_key() {
Pair<Integer, Pair<Executor, Executor>> graph = buildGraphWithChildInjector(Executors::newSingleThreadExecutor);
int graphSize = graph.getFirst();
Executor executorA = graph.getSecond().getFirst();
@@ -428,7 +430,7 @@ public class ComponentGraphTest {
}
@Test
- public void components_injected_via_child_injector_can_be_shared() {
+ void components_injected_via_child_injector_can_be_shared() {
Executor commonExecutor = Executors.newSingleThreadExecutor();
Pair<Integer, Pair<Executor, Executor>> graph = buildGraphWithChildInjector(() -> commonExecutor);
int graphSize = graph.getFirst();
@@ -462,7 +464,7 @@ public class ComponentGraphTest {
}
@Test
- public void providers_can_be_reused() {
+ void providers_can_be_reused() {
ComponentGraph oldGraph = createReusingGraph();
Executor executor = oldGraph.getInstance(Executor.class);
@@ -483,7 +485,7 @@ public class ComponentGraphTest {
}
@Test
- public void component_id_can_be_injected() {
+ void component_id_can_be_injected() {
String componentId = "myId:1.2@namespace";
ComponentGraph componentGraph = new ComponentGraph();
diff --git a/container-core/src/test/java/com/yahoo/container/di/componentgraph/core/FallbackToGuiceInjectorTest.java b/container-core/src/test/java/com/yahoo/container/di/componentgraph/core/FallbackToGuiceInjectorTest.java
index 1e3d67ed463..878c245a708 100644
--- a/container-core/src/test/java/com/yahoo/container/di/componentgraph/core/FallbackToGuiceInjectorTest.java
+++ b/container-core/src/test/java/com/yahoo/container/di/componentgraph/core/FallbackToGuiceInjectorTest.java
@@ -11,18 +11,15 @@ import com.yahoo.component.AbstractComponent;
import com.yahoo.component.ComponentId;
import com.yahoo.config.ConfigInstance;
import com.yahoo.vespa.config.ConfigKey;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
-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 Tony Vaagenes
@@ -36,7 +33,7 @@ public class FallbackToGuiceInjectorTest {
private final Map<ConfigKey<? extends ConfigInstance>, ConfigInstance> configs = new HashMap<>();
- @Before
+ @BeforeEach
public void createGraph() {
injector = Guice.createInjector();
componentGraph = new ComponentGraph(0);
@@ -70,7 +67,7 @@ public class FallbackToGuiceInjectorTest {
}
@Test
- public void guice_injector_is_used_when_no_global_component_exists() {
+ void guice_injector_is_used_when_no_global_component_exists() {
setInjector(
Guice.createInjector(new AbstractModule() {
@Override
@@ -89,7 +86,7 @@ public class FallbackToGuiceInjectorTest {
}
@Test
- public void guice_injector_creates_a_new_instance_with_default_ctor_when_no_explicit_binding_exists() {
+ void guice_injector_creates_a_new_instance_with_default_ctor_when_no_explicit_binding_exists() {
setInjector(emptyGuiceInjector());
register(ComponentTakingDefaultString.class);
complete();
@@ -99,7 +96,7 @@ public class FallbackToGuiceInjectorTest {
}
@Test
- public void guice_injector_fails_when_no_explicit_binding_exists_and_class_has_no_default_ctor() {
+ void guice_injector_fails_when_no_explicit_binding_exists_and_class_has_no_default_ctor() {
setInjector(emptyGuiceInjector());
register(ComponentThatCannotBeConstructed.class);
try {
diff --git a/container-core/src/test/java/com/yahoo/container/di/componentgraph/core/ReuseComponentsTest.java b/container-core/src/test/java/com/yahoo/container/di/componentgraph/core/ReuseComponentsTest.java
index 2215fcdf4dd..edd06e37e64 100644
--- a/container-core/src/test/java/com/yahoo/container/di/componentgraph/core/ReuseComponentsTest.java
+++ b/container-core/src/test/java/com/yahoo/container/di/componentgraph/core/ReuseComponentsTest.java
@@ -14,16 +14,14 @@ import com.yahoo.container.di.componentgraph.core.ComponentGraphTest.ExecutorPro
import com.yahoo.container.di.componentgraph.core.ComponentGraphTest.SimpleComponent;
import com.yahoo.container.di.componentgraph.core.ComponentGraphTest.SimpleComponent2;
import com.yahoo.vespa.config.ConfigKey;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.concurrent.Executor;
import java.util.function.Function;
import java.util.function.Supplier;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertSame;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author gjoranv
@@ -32,7 +30,7 @@ import static org.junit.Assert.assertSame;
*/
public class ReuseComponentsTest {
@Test
- public void require_that_component_is_reused_when_componentNode_is_unmodified() {
+ void require_that_component_is_reused_when_componentNode_is_unmodified() {
reuseAndTest(SimpleComponent.class, SimpleComponent.class);
reuseAndTest(ExecutorProvider.class, Executor.class);
}
@@ -48,23 +46,25 @@ public class ReuseComponentsTest {
assertSame(instance2, instance);
}
- @Test(expected = IllegalStateException.class)
- public void require_that_component_is_not_reused_when_class_is_changed() {
- ComponentGraph graph = buildGraphAndSetNoConfigs(SimpleComponent.class);
- SimpleComponent instance = getComponent(graph, SimpleComponent.class);
-
- ComponentGraph newGraph = buildGraphAndSetNoConfigs(SimpleComponent2.class);
- newGraph.reuseNodes(graph);
- SimpleComponent2 instance2 = getComponent(newGraph, SimpleComponent2.class);
-
- assertEquals(instance2.getId(),instance.getId());
- @SuppressWarnings("unused")
- SimpleComponent throwsException = getComponent(newGraph, SimpleComponent.class);
+ @Test
+ void require_that_component_is_not_reused_when_class_is_changed() {
+ assertThrows(IllegalStateException.class, () -> {
+ ComponentGraph graph = buildGraphAndSetNoConfigs(SimpleComponent.class);
+ SimpleComponent instance = getComponent(graph, SimpleComponent.class);
+
+ ComponentGraph newGraph = buildGraphAndSetNoConfigs(SimpleComponent2.class);
+ newGraph.reuseNodes(graph);
+ SimpleComponent2 instance2 = getComponent(newGraph, SimpleComponent2.class);
+
+ assertEquals(instance2.getId(), instance.getId());
+ @SuppressWarnings("unused")
+ SimpleComponent throwsException = getComponent(newGraph, SimpleComponent.class);
+ });
}
@SuppressWarnings("deprecation")
@Test
- public void require_that_component_is_not_reused_when_config_is_changed() {
+ void require_that_component_is_not_reused_when_config_is_changed() {
Class<ComponentTakingConfig> componentClass = ComponentTakingConfig.class;
ComponentGraph graph = buildGraph(componentClass);
@@ -83,7 +83,7 @@ public class ReuseComponentsTest {
@SuppressWarnings("deprecation")
@Test
- public void require_that_component_is_not_reused_when_injected_component_is_changed() {
+ void require_that_component_is_not_reused_when_injected_component_is_changed() {
Function<String, ComponentGraph> buildGraph = config -> {
ComponentGraph graph = new ComponentGraph();
@@ -115,7 +115,7 @@ public class ReuseComponentsTest {
}
@Test
- public void require_that_component_is_not_reused_when_injected_component_registry_has_one_component_removed() {
+ void require_that_component_is_not_reused_when_injected_component_registry_has_one_component_removed() {
Function<Boolean, ComponentGraph> buildGraph = useBothInjectedComponents -> {
ComponentGraph graph = new ComponentGraph();
graph.add(mockComponentNode(ComponentTakingAllSimpleComponents.class, "root_component"));
@@ -148,7 +148,7 @@ public class ReuseComponentsTest {
@SuppressWarnings("deprecation")
@Test
- public void require_that_injected_component_is_reused_even_when_dependent_component_is_changed() {
+ void require_that_injected_component_is_reused_even_when_dependent_component_is_changed() {
Function<String, ComponentGraph> buildGraph = config -> {
ComponentGraph graph = new ComponentGraph();
@@ -183,7 +183,7 @@ public class ReuseComponentsTest {
}
@Test
- public void require_that_node_depending_on_guice_node_is_reused() {
+ void require_that_node_depending_on_guice_node_is_reused() {
Supplier<ComponentGraph> makeGraph = () -> {
ComponentGraph graph = new ComponentGraph();
graph.add(mockComponentNode(ComponentTakingExecutor.class, "dummyId"));
@@ -202,7 +202,7 @@ public class ReuseComponentsTest {
}
@Test
- public void require_that_node_equals_only_checks_first_level_components_to_inject() {
+ void require_that_node_equals_only_checks_first_level_components_to_inject() {
Function<String, Node> createNodeWithInjectedNodeWithInjectedNode = indirectlyInjectedComponentId -> {
ComponentNode targetComponent = mockComponentNode(SimpleComponent.class, "target");
ComponentNode directlyInjectedComponent = mockComponentNode(SimpleComponent.class, "directlyInjected");
diff --git a/container-core/src/test/java/com/yahoo/container/di/componentgraph/cycle/CycleFinderTest.java b/container-core/src/test/java/com/yahoo/container/di/componentgraph/cycle/CycleFinderTest.java
index 65fbdc578aa..b7ce61c2f1a 100644
--- a/container-core/src/test/java/com/yahoo/container/di/componentgraph/cycle/CycleFinderTest.java
+++ b/container-core/src/test/java/com/yahoo/container/di/componentgraph/cycle/CycleFinderTest.java
@@ -2,7 +2,7 @@
package com.yahoo.container.di.componentgraph.cycle;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
@@ -10,7 +10,7 @@ import static com.yahoo.container.di.componentgraph.cycle.CycleFinderTest.Vertic
import static com.yahoo.container.di.componentgraph.cycle.CycleFinderTest.Vertices.B;
import static com.yahoo.container.di.componentgraph.cycle.CycleFinderTest.Vertices.C;
import static com.yahoo.container.di.componentgraph.cycle.CycleFinderTest.Vertices.D;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author gjoranv
@@ -20,7 +20,7 @@ public class CycleFinderTest {
enum Vertices {A, B, C, D}
@Test
- public void graph_without_cycles_returns_no_cycle() {
+ void graph_without_cycles_returns_no_cycle() {
var graph = new Graph<Vertices>();
graph.edge(A, B);
graph.edge(B, C);
@@ -32,7 +32,7 @@ public class CycleFinderTest {
}
@Test
- public void graph_with_cycle_returns_cycle() {
+ void graph_with_cycle_returns_cycle() {
var graph = new Graph<Vertices>();
graph.edge(A, B);
graph.edge(B, C);
@@ -43,7 +43,7 @@ public class CycleFinderTest {
}
@Test
- public void graph_with_self_referencing_vertex_returns_cycle() {
+ void graph_with_self_referencing_vertex_returns_cycle() {
var graph = new Graph<Vertices>();
graph.edge(A, A);
@@ -52,7 +52,7 @@ public class CycleFinderTest {
}
@Test
- public void leading_nodes_are_stripped_from_cycle() {
+ void leading_nodes_are_stripped_from_cycle() {
var graph = new Graph<Vertices>();
graph.edge(A, B);
graph.edge(B, C);
@@ -63,7 +63,7 @@ public class CycleFinderTest {
}
@Test
- public void findCycle_is_idempotent_with_cycle() {
+ void findCycle_is_idempotent_with_cycle() {
var graph = new Graph<Vertices>();
graph.edge(A, A);
@@ -73,7 +73,7 @@ public class CycleFinderTest {
}
@Test
- public void findCycle_is_idempotent_without_cycle() {
+ void findCycle_is_idempotent_without_cycle() {
var graph = new Graph<Vertices>();
graph.edge(A, B);
diff --git a/container-core/src/test/java/com/yahoo/container/di/componentgraph/cycle/GraphTest.java b/container-core/src/test/java/com/yahoo/container/di/componentgraph/cycle/GraphTest.java
index 526e683ad46..d945b4f0544 100644
--- a/container-core/src/test/java/com/yahoo/container/di/componentgraph/cycle/GraphTest.java
+++ b/container-core/src/test/java/com/yahoo/container/di/componentgraph/cycle/GraphTest.java
@@ -2,16 +2,14 @@
package com.yahoo.container.di.componentgraph.cycle;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import static com.yahoo.container.di.componentgraph.cycle.GraphTest.Vertices.A;
import static com.yahoo.container.di.componentgraph.cycle.GraphTest.Vertices.B;
import static com.yahoo.container.di.componentgraph.cycle.GraphTest.Vertices.C;
-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
@@ -21,7 +19,7 @@ public class GraphTest {
enum Vertices {A, B, C}
@Test
- public void vertices_and_edges_are_added_and_can_be_retrieved() {
+ void vertices_and_edges_are_added_and_can_be_retrieved() {
var graph = new Graph<Vertices>();
graph.edge(A, B);
graph.edge(B, C);
@@ -34,7 +32,7 @@ public class GraphTest {
}
@Test
- public void null_vertices_are_not_allowed() {
+ void null_vertices_are_not_allowed() {
var graph = new Graph<Vertices>();
try {
@@ -46,7 +44,7 @@ public class GraphTest {
}
@Test
- public void duplicate_edges_are_ignored() {
+ void duplicate_edges_are_ignored() {
var graph = new Graph<Vertices>();
graph.edge(A, B);
graph.edge(A, B);
@@ -55,7 +53,7 @@ public class GraphTest {
}
@Test
- public void self_edges_are_allowed() {
+ void self_edges_are_allowed() {
var graph = new Graph<Vertices>();
graph.edge(A, A);
diff --git a/container-core/src/test/java/com/yahoo/container/handler/AccessLogRequestHandlerTest.java b/container-core/src/test/java/com/yahoo/container/handler/AccessLogRequestHandlerTest.java
index 2eba4144b45..728118c38cc 100644
--- a/container-core/src/test/java/com/yahoo/container/handler/AccessLogRequestHandlerTest.java
+++ b/container-core/src/test/java/com/yahoo/container/handler/AccessLogRequestHandlerTest.java
@@ -3,13 +3,13 @@ package com.yahoo.container.handler;
import com.yahoo.container.jdisc.HttpResponse;
import com.yahoo.container.logging.CircularArrayAccessLogKeeper;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.Executor;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
public class AccessLogRequestHandlerTest {
@@ -20,7 +20,7 @@ public class AccessLogRequestHandlerTest {
private final ByteArrayOutputStream out = new ByteArrayOutputStream();
@Test
- public void testOneLogLine() throws IOException {
+ void testOneLogLine() throws IOException {
keeper.addUri("foo");
HttpResponse response = handler.handle(null);
response.render(out);
@@ -28,14 +28,14 @@ public class AccessLogRequestHandlerTest {
}
@Test
- public void testEmpty() throws IOException {
+ void testEmpty() throws IOException {
HttpResponse response = handler.handle(null);
response.render(out);
assertEquals("{\"entries\":[]}", out.toString());
}
@Test
- public void testManyLogLines() throws IOException {
+ void testManyLogLines() throws IOException {
keeper.addUri("foo");
keeper.addUri("foo");
HttpResponse response = handler.handle(null);
diff --git a/container-core/src/test/java/com/yahoo/container/handler/LogHandlerTest.java b/container-core/src/test/java/com/yahoo/container/handler/LogHandlerTest.java
index 4c7cb5475dd..3d9a2360e77 100644
--- a/container-core/src/test/java/com/yahoo/container/handler/LogHandlerTest.java
+++ b/container-core/src/test/java/com/yahoo/container/handler/LogHandlerTest.java
@@ -6,7 +6,7 @@ import com.yahoo.container.jdisc.ContentChannelOutputStream;
import com.yahoo.container.jdisc.HttpRequest;
import com.yahoo.jdisc.handler.ReadableContentChannel;
import com.yahoo.yolean.Exceptions;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.OutputStream;
@@ -15,13 +15,13 @@ import java.util.Optional;
import java.util.concurrent.Executor;
import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
public class LogHandlerTest {
@Test
- public void handleCorrectlyParsesQueryParameters() throws IOException {
+ void handleCorrectlyParsesQueryParameters() throws IOException {
MockLogReader mockLogReader = new MockLogReader();
LogHandler logHandler = new LogHandler(mock(Executor.class), mockLogReader);
diff --git a/container-core/src/test/java/com/yahoo/container/handler/LogReaderTest.java b/container-core/src/test/java/com/yahoo/container/handler/LogReaderTest.java
index e1bd0da457e..f49c127cb01 100644
--- a/container-core/src/test/java/com/yahoo/container/handler/LogReaderTest.java
+++ b/container-core/src/test/java/com/yahoo/container/handler/LogReaderTest.java
@@ -2,15 +2,14 @@
package com.yahoo.container.handler;
import com.yahoo.compress.ZstdCompressor;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.Rule;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import java.io.ByteArrayOutputStream;
+import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
-import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
@@ -20,12 +19,12 @@ import java.util.regex.Pattern;
import java.util.zip.GZIPOutputStream;
import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class LogReaderTest {
- @Rule
- public TemporaryFolder folder = new TemporaryFolder();
+ @TempDir
+ public File folder;
private Path logDirectory;
private static final String logv11 = "3600.2\tnode1.com\t5480\tcontainer\tstdout\tinfo\tfourth\n";
@@ -35,9 +34,9 @@ public class LogReaderTest {
private static final String log110 = "3600.1\tnode1.com\t5480\tcontainer\tstderr\twarning\tthird\n";
private static final String log200 = "86400.1\tnode2.com\t5480\tcontainer\tstderr\twarning\tjava.lang.NullPointerException\\n\\tat org.apache.felix.framework.BundleRevisionImpl.calculateContentPath(BundleRevisionImpl.java:438)\\n\\tat org.apache.felix.framework.BundleRevisionImpl.initializeContentPath(BundleRevisionImpl.java:371)\n";
- @Before
+ @BeforeEach
public void setup() throws IOException {
- logDirectory = folder.newFolder("opt/vespa/logs").toPath();
+ logDirectory = newFolder(folder, "opt/vespa/logs").toPath();
// Log archive paths and file names indicate what hour they contain logs for, with the start of that hour.
// Multiple entries may exist for each hour.
Files.createDirectories(logDirectory.resolve("1970/01/01"));
@@ -55,7 +54,7 @@ public class LogReaderTest {
}
@Test
- public void testThatLogsOutsideRangeAreExcluded() {
+ void testThatLogsOutsideRangeAreExcluded() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
LogReader logReader = new LogReader(logDirectory, Pattern.compile(".*"));
logReader.writeLogs(baos, Instant.ofEpochMilli(150), Instant.ofEpochMilli(3601050), Optional.empty());
@@ -64,7 +63,7 @@ public class LogReaderTest {
}
@Test
- public void testThatLogsNotMatchingRegexAreExcluded() {
+ void testThatLogsNotMatchingRegexAreExcluded() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
LogReader logReader = new LogReader(logDirectory, Pattern.compile(".*-1.*"));
logReader.writeLogs(baos, Instant.EPOCH, Instant.EPOCH.plus(Duration.ofDays(2)), Optional.empty());
@@ -73,7 +72,7 @@ public class LogReaderTest {
}
@Test
- public void testZippedStreaming() {
+ void testZippedStreaming() {
ByteArrayOutputStream zippedBaos = new ByteArrayOutputStream();
LogReader logReader = new LogReader(logDirectory, Pattern.compile(".*"));
logReader.writeLogs(zippedBaos, Instant.EPOCH, Instant.EPOCH.plus(Duration.ofDays(2)), Optional.empty());
@@ -82,7 +81,7 @@ public class LogReaderTest {
}
@Test
- public void logsForSingeNodeIsRetrieved() {
+ void logsForSingeNodeIsRetrieved() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
LogReader logReader = new LogReader(logDirectory, Pattern.compile(".*"));
logReader.writeLogs(baos, Instant.EPOCH, Instant.EPOCH.plus(Duration.ofDays(2)), Optional.of("node2.com"));
@@ -103,4 +102,13 @@ public class LogReaderTest {
return new ZstdCompressor().compress(data, 0, data.length);
}
+ 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/container-core/src/test/java/com/yahoo/container/handler/VipStatusHandlerTestCase.java b/container-core/src/test/java/com/yahoo/container/handler/VipStatusHandlerTestCase.java
index e78810db897..18eca0bc8bd 100644
--- a/container-core/src/test/java/com/yahoo/container/handler/VipStatusHandlerTestCase.java
+++ b/container-core/src/test/java/com/yahoo/container/handler/VipStatusHandlerTestCase.java
@@ -15,7 +15,7 @@ import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.http.HttpRequest;
import com.yahoo.jdisc.service.CurrentContainer;
import com.yahoo.text.Utf8;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.io.File;
@@ -27,8 +27,8 @@ import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.util.concurrent.Executors;
-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;
/**
* Check semantics of VIP status handler. Do note this handler does not need to
@@ -52,7 +52,7 @@ public class VipStatusHandlerTestCase {
Metric metric = Mockito.mock(Metric.class);
@Test
- public void testHandleRequest() {
+ void testHandleRequest() {
VipStatusConfig config = new VipStatusConfig(new VipStatusConfig.Builder().accessdisk(false));
VipStatusHandler handler = new VipStatusHandler(Executors.newCachedThreadPool(), config, metric);
MockResponseHandler responseHandler = new MockResponseHandler();
@@ -78,7 +78,7 @@ public class VipStatusHandlerTestCase {
}
@Test
- public void testFileNotFound() {
+ void testFileNotFound() {
VipStatusConfig config = new VipStatusConfig(new VipStatusConfig.Builder().accessdisk(true)
.statusfile("/VipStatusHandlerTestCaseFileThatReallyReallyShouldNotExist"));
VipStatusHandler handler = new VipStatusHandler(Executors.newCachedThreadPool(), config, metric);
@@ -95,7 +95,7 @@ public class VipStatusHandlerTestCase {
}
@Test
- public void testFileFound() throws IOException {
+ void testFileFound() throws IOException {
File statusFile = File.createTempFile("VipStatusHandlerTestCase", null);
try {
FileWriter writer = new FileWriter(statusFile);
@@ -121,7 +121,7 @@ public class VipStatusHandlerTestCase {
}
@Test
- public void testExplicitlyRotationControl() {
+ void testExplicitlyRotationControl() {
VipStatus vipStatus = new VipStatus();
VipStatusConfig config = new VipStatusConfig(new VipStatusConfig.Builder().accessdisk(false));
VipStatusHandler handler = new VipStatusHandler(Executors.newCachedThreadPool(), config, metric, vipStatus);
diff --git a/container-core/src/test/java/com/yahoo/container/handler/VipStatusTestCase.java b/container-core/src/test/java/com/yahoo/container/handler/VipStatusTestCase.java
index 168dd2cac7b..eed3c047b0a 100644
--- a/container-core/src/test/java/com/yahoo/container/handler/VipStatusTestCase.java
+++ b/container-core/src/test/java/com/yahoo/container/handler/VipStatusTestCase.java
@@ -5,13 +5,11 @@ import com.yahoo.container.QrSearchersConfig;
import com.yahoo.container.core.VipStatusConfig;
import com.yahoo.container.jdisc.state.StateMonitor;
import com.yahoo.jdisc.Metric;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Map;
-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 bratseth
@@ -19,14 +17,14 @@ import static org.junit.Assert.assertTrue;
public class VipStatusTestCase {
@Test
- public void testInitializingOrDownRequireAllUp() {
+ void testInitializingOrDownRequireAllUp() {
String[] clusters = {"cluster1", "cluster2", "cluster3"};
verifyStatus(clusters, StateMonitor.Status.initializing);
verifyStatus(clusters, StateMonitor.Status.down);
}
@Test
- public void testUpRequireAllDown() {
+ void testUpRequireAllDown() {
String[] clusters = {"cluster1", "cluster2", "cluster3"};
VipStatus v = createVipStatus(clusters, StateMonitor.Status.initializing, true, new ClustersStatus(), new MetricMock());
@@ -54,21 +52,21 @@ public class VipStatusTestCase {
}
@Test
- public void testNoClustersConfiguringInitiallyInRotationFalse() {
+ void testNoClustersConfiguringInitiallyInRotationFalse() {
String[] clusters = {};
VipStatus v = createVipStatus(clusters, StateMonitor.Status.initializing, false, new ClustersStatus(), new MetricMock());
assertFalse(v.isInRotation());
}
@Test
- public void testNoClustersConfiguringInitiallyInRotationTrue() {
+ void testNoClustersConfiguringInitiallyInRotationTrue() {
String[] clusters = {};
VipStatus v = createVipStatus(clusters, StateMonitor.Status.initializing, true, new ClustersStatus(), new MetricMock());
assertTrue(v.isInRotation());
}
@Test
- public void testInRotationMetricFollowsRotationState() {
+ void testInRotationMetricFollowsRotationState() {
MetricMock metric = new MetricMock();
String[] clusters = {"cluster1", "cluster2", "cluster3"};
@@ -81,17 +79,17 @@ public class VipStatusTestCase {
}
@Test
- public void testClusterRemovalRemovedIsDown() {
+ void testClusterRemovalRemovedIsDown() {
assertClusterRemoval(true, false);
}
@Test
- public void testClusterRemovalRemovedIsUp() {
+ void testClusterRemovalRemovedIsUp() {
assertClusterRemoval(false, false);
}
@Test
- public void testClusterRemovalAnotherIsDown() {
+ void testClusterRemovalAnotherIsDown() {
assertClusterRemoval(false, true);
}
diff --git a/container-core/src/test/java/com/yahoo/container/handler/metrics/ErrorResponseTest.java b/container-core/src/test/java/com/yahoo/container/handler/metrics/ErrorResponseTest.java
index c6e3986e870..4743075a9a6 100644
--- a/container-core/src/test/java/com/yahoo/container/handler/metrics/ErrorResponseTest.java
+++ b/container-core/src/test/java/com/yahoo/container/handler/metrics/ErrorResponseTest.java
@@ -1,9 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.handler.metrics;
-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 gjoranv
@@ -11,13 +11,13 @@ import static org.junit.Assert.assertEquals;
public class ErrorResponseTest {
@Test
- public void error_message_is_wrapped_in_json_object() {
+ void error_message_is_wrapped_in_json_object() {
var json = ErrorResponse.asErrorJson("bad");
assertEquals("{\"error\":\"bad\"}", json);
}
@Test
- public void quotes_are_escaped() {
+ void quotes_are_escaped() {
var json = ErrorResponse.asErrorJson("Message \" with \" embedded quotes.");
assertEquals("{\"error\":\"Message \\\" with \\\" embedded quotes.\"}", json);
}
diff --git a/container-core/src/test/java/com/yahoo/container/handler/metrics/MetricsV2HandlerTest.java b/container-core/src/test/java/com/yahoo/container/handler/metrics/MetricsV2HandlerTest.java
index 350aad8198b..ad5b1a49670 100644
--- a/container-core/src/test/java/com/yahoo/container/handler/metrics/MetricsV2HandlerTest.java
+++ b/container-core/src/test/java/com/yahoo/container/handler/metrics/MetricsV2HandlerTest.java
@@ -4,12 +4,12 @@ package com.yahoo.container.handler.metrics;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
-import com.github.tomakehurst.wiremock.junit.WireMockRule;
+import com.github.tomakehurst.wiremock.junit5.WireMockExtension;
import com.yahoo.container.jdisc.RequestHandlerTestDriver;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Rule;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
import java.io.BufferedReader;
import java.io.IOException;
@@ -26,9 +26,7 @@ import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options
import static com.yahoo.container.handler.metrics.MetricsV2Handler.V2_PATH;
import static com.yahoo.container.handler.metrics.MetricsV2Handler.VALUES_PATH;
import static com.yahoo.container.handler.metrics.MetricsV2Handler.consumerQuery;
-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
@@ -53,15 +51,15 @@ public class MetricsV2HandlerTest {
private static RequestHandlerTestDriver testDriver;
- @Rule
- public WireMockRule wireMockRule = new WireMockRule(options().dynamicPort());
+ @RegisterExtension
+ public WireMockExtension wireMockRule = WireMockExtension.newInstance().options(options().dynamicPort()).build();
- @Before
+ @BeforeEach
public void setup() {
setupWireMock();
var handler = new MetricsV2Handler(Executors.newSingleThreadExecutor(),
new MetricsProxyApiConfig.Builder()
- .metricsPort(wireMockRule.port())
+ .metricsPort(wireMockRule.getPort())
.metricsApiPath(MOCK_METRICS_PATH)
.prometheusApiPath("Not/In/Use")
.build());
@@ -80,7 +78,7 @@ public class MetricsV2HandlerTest {
}
@Test
- public void v2_response_contains_values_uri() throws Exception {
+ void v2_response_contains_values_uri() throws Exception {
String response = testDriver.sendRequest(V2_URI).readAll();
JsonNode root = jsonMapper.readTree(response);
assertTrue(root.has("resources"));
@@ -92,29 +90,29 @@ public class MetricsV2HandlerTest {
assertEquals(VALUES_URI, valuesUri.get("url").textValue());
}
- @Ignore
+ @Disabled
@Test
- public void visually_inspect_values_response() {
+ void visually_inspect_values_response() {
JsonNode responseJson = getResponseAsJson(null);
System.out.println(responseJson);
}
@Test
- public void invalid_path_yields_error_response() throws Exception {
+ void invalid_path_yields_error_response() throws Exception {
String response = testDriver.sendRequest(V2_URI + "/invalid").readAll();
JsonNode root = jsonMapper.readTree(response);
assertTrue(root.has("error"));
- assertTrue(root.get("error" ).textValue().startsWith("No content"));
+ assertTrue(root.get("error").textValue().startsWith("No content"));
}
@Test
- public void values_response_is_equal_to_test_file() {
+ void values_response_is_equal_to_test_file() {
String response = testDriver.sendRequest(VALUES_URI).readAll();
assertEquals(RESPONSE, response);
}
@Test
- public void consumer_is_propagated_to_metrics_proxy_api() {
+ void consumer_is_propagated_to_metrics_proxy_api() {
JsonNode responseJson = getResponseAsJson(CUSTOM_CONSUMER);
JsonNode firstNodeMetricsValues =
diff --git a/container-core/src/test/java/com/yahoo/container/handler/metrics/PrometheusV1HandlerTest.java b/container-core/src/test/java/com/yahoo/container/handler/metrics/PrometheusV1HandlerTest.java
index 98920b895e0..5989ba4a202 100644
--- a/container-core/src/test/java/com/yahoo/container/handler/metrics/PrometheusV1HandlerTest.java
+++ b/container-core/src/test/java/com/yahoo/container/handler/metrics/PrometheusV1HandlerTest.java
@@ -4,12 +4,12 @@ package com.yahoo.container.handler.metrics;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
-import com.github.tomakehurst.wiremock.junit.WireMockRule;
+import com.github.tomakehurst.wiremock.junit5.WireMockExtension;
import com.yahoo.container.jdisc.RequestHandlerTestDriver;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Rule;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
import java.util.concurrent.Executors;
@@ -20,8 +20,8 @@ import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;
import static com.yahoo.container.handler.metrics.MetricsV2Handler.consumerQuery;
import static com.yahoo.container.handler.metrics.MetricsV2HandlerTest.getFileContents;
-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
@@ -46,16 +46,16 @@ public class PrometheusV1HandlerTest {
private static RequestHandlerTestDriver testDriver;
- @Rule
- public WireMockRule wireMockRule = new WireMockRule(options().dynamicPort());
+ @RegisterExtension
+ public WireMockExtension wireMockRule = WireMockExtension.newInstance().options(options().dynamicPort()).build();
- @Before
+ @BeforeEach
public void setup() {
setupWireMock();
var handler = new PrometheusV1Handler(Executors.newSingleThreadExecutor(),
new MetricsProxyApiConfig.Builder()
.prometheusApiPath(MOCK_METRICS_PATH)
- .metricsPort(wireMockRule.port())
+ .metricsPort(wireMockRule.getPort())
.metricsApiPath("/Not/In/Use")
.build());
testDriver = new RequestHandlerTestDriver(handler);
@@ -74,7 +74,7 @@ public class PrometheusV1HandlerTest {
}
@Test
- public void v1_response_contains_values_uri() throws Exception {
+ void v1_response_contains_values_uri() throws Exception {
String response = testDriver.sendRequest(V1_URI).readAll();
JsonNode root = jsonMapper.readTree(response);
assertTrue(root.has("resources"));
@@ -86,29 +86,29 @@ public class PrometheusV1HandlerTest {
assertEquals(VALUES_URI, valuesUri.get("url").asText());
}
- @Ignore
+ @Disabled
@Test
- public void visually_inspect_values_response() {
+ void visually_inspect_values_response() {
String response = testDriver.sendRequest(VALUES_URI).readAll();
System.out.println(response);
}
@Test
- public void invalid_path_yields_error_response() throws Exception {
+ void invalid_path_yields_error_response() throws Exception {
String response = testDriver.sendRequest(V1_URI + "/invalid").readAll();
JsonNode root = jsonMapper.readTree(response);
assertTrue(root.has("error"));
- assertTrue(root.get("error" ).textValue().startsWith("No content"));
+ assertTrue(root.get("error").textValue().startsWith("No content"));
}
@Test
- public void values_response_is_equal_to_test_file() {
+ void values_response_is_equal_to_test_file() {
String response = testDriver.sendRequest(VALUES_URI).readAll();
assertEquals(RESPONSE, response);
}
@Test
- public void consumer_is_propagated_to_metrics_proxy_api() {
+ void consumer_is_propagated_to_metrics_proxy_api() {
String response = testDriver.sendRequest(VALUES_URI + consumerQuery(CUSTOM_CONSUMER)).readAll();
assertTrue(response.contains(REPLACED_CPU_METRIC));
diff --git a/container-core/src/test/java/com/yahoo/container/handler/test/MockServiceTest.java b/container-core/src/test/java/com/yahoo/container/handler/test/MockServiceTest.java
index 2efa717800d..eefcc43fcb7 100644
--- a/container-core/src/test/java/com/yahoo/container/handler/test/MockServiceTest.java
+++ b/container-core/src/test/java/com/yahoo/container/handler/test/MockServiceTest.java
@@ -4,7 +4,7 @@ package com.yahoo.container.handler.test;
import com.yahoo.container.jdisc.HttpRequest;
import com.yahoo.container.jdisc.HttpResponse;
import com.yahoo.filedistribution.fileacquirer.MockFileAcquirer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.File;
@@ -12,7 +12,8 @@ import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.concurrent.Executor;
-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
@@ -22,7 +23,7 @@ public class MockServiceTest {
private final File testFile = new File("src/test/java/com/yahoo/container/handler/test/test.txt");
@Test
- public void testHandlerTextFormat() throws InterruptedException, IOException {
+ void testHandlerTextFormat() throws InterruptedException, IOException {
HttpResponse response = runHandler(com.yahoo.jdisc.http.HttpRequest.Method.GET, "/foo/bar");
assertResponse(response, 200, "Hello\nThere!");
@@ -34,20 +35,24 @@ public class MockServiceTest {
}
@Test
- public void testNoHandlerFound() throws InterruptedException, IOException {
+ void testNoHandlerFound() throws InterruptedException, IOException {
HttpResponse response = runHandler(com.yahoo.jdisc.http.HttpRequest.Method.DELETE, "/foo/bar");
assertEquals(404, response.getStatus());
assertResponseContents(response, "DELETE:/foo/bar was not found");
}
- @Test(expected = IllegalArgumentException.class)
- public void testUnknownFileType() throws InterruptedException, IOException {
- runHandlerWithFile(com.yahoo.jdisc.http.HttpRequest.Method.GET, "", new File("nonexistant"));
+ @Test
+ void testUnknownFileType() throws InterruptedException, IOException {
+ assertThrows(IllegalArgumentException.class, () -> {
+ runHandlerWithFile(com.yahoo.jdisc.http.HttpRequest.Method.GET, "", new File("nonexistant"));
+ });
}
- @Test(expected = FileNotFoundException.class)
- public void testExceptionResponse() throws InterruptedException, IOException {
- runHandlerWithFile(com.yahoo.jdisc.http.HttpRequest.Method.GET, "", new File("nonexistant.txt"));
+ @Test
+ void testExceptionResponse() throws InterruptedException, IOException {
+ assertThrows(FileNotFoundException.class, () -> {
+ runHandlerWithFile(com.yahoo.jdisc.http.HttpRequest.Method.GET, "", new File("nonexistant.txt"));
+ });
}
private void assertResponse(HttpResponse response, int expectedCode, String expectedMessage) throws IOException {
diff --git a/container-core/src/test/java/com/yahoo/container/handler/threadpool/ContainerThreadPoolImplTest.java b/container-core/src/test/java/com/yahoo/container/handler/threadpool/ContainerThreadPoolImplTest.java
index c3f91000296..4639022d767 100644
--- a/container-core/src/test/java/com/yahoo/container/handler/threadpool/ContainerThreadPoolImplTest.java
+++ b/container-core/src/test/java/com/yahoo/container/handler/threadpool/ContainerThreadPoolImplTest.java
@@ -6,15 +6,15 @@ import com.yahoo.concurrent.Receiver;
import com.yahoo.container.protect.ProcessTerminator;
import com.yahoo.container.test.MetricMock;
import com.yahoo.jdisc.Metric;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.Executor;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
-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 Steinar Knutsen
@@ -25,14 +25,14 @@ public class ContainerThreadPoolImplTest {
private static final int CPUS = 16;
@Test
- public final void testThreadPool() throws InterruptedException {
+ final void testThreadPool() throws InterruptedException {
Metric metrics = new MetricMock();
ContainerThreadpoolConfig config = new ContainerThreadpoolConfig(new ContainerThreadpoolConfig.Builder().maxThreads(1));
ContainerThreadPool threadPool = new ContainerThreadpoolImpl(config, metrics);
Executor exec = threadPool.executor();
Tuple2<Receiver.MessageState, Boolean> reply;
FlipIt command = new FlipIt();
- for (boolean done = false; !done;) {
+ for (boolean done = false; !done; ) {
try {
exec.execute(command);
done = true;
@@ -74,7 +74,7 @@ public class ContainerThreadPoolImplTest {
}
@Test
- public void testThatThreadPoolSizeFollowsConfig() {
+ void testThatThreadPoolSizeFollowsConfig() {
MetricMock metrics = new MetricMock();
ThreadPoolExecutor executor = createPool(metrics, 3, 1200);
assertEquals(3, executor.getMaximumPoolSize());
@@ -86,11 +86,12 @@ public class ContainerThreadPoolImplTest {
assertEquals(1200L, metrics.innvocations().get("jdisc.thread_pool.work_queue.capacity").val);
assertEquals(0L, metrics.innvocations().get("jdisc.thread_pool.work_queue.size").val);
}
+
@Test
- public void testThatThreadPoolSizeAutoDetected() {
+ void testThatThreadPoolSizeAutoDetected() {
MetricMock metrics = new MetricMock();
ThreadPoolExecutor executor = createPool(metrics, 0, 0);
- assertEquals(CPUS*4, executor.getMaximumPoolSize());
+ assertEquals(CPUS * 4, executor.getMaximumPoolSize());
assertEquals(0, executor.getQueue().remainingCapacity());
assertEquals(7, metrics.innvocations().size());
assertEquals(64L, metrics.innvocations().get("serverThreadPoolSize").val);
@@ -99,17 +100,19 @@ public class ContainerThreadPoolImplTest {
assertEquals(64L, metrics.innvocations().get("jdisc.thread_pool.work_queue.capacity").val);
assertEquals(0L, metrics.innvocations().get("jdisc.thread_pool.work_queue.size").val);
}
+
@Test
- public void testThatQueueSizeAutoDetected() {
+ void testThatQueueSizeAutoDetected() {
ThreadPoolExecutor executor = createPool(24, -50);
assertEquals(24, executor.getMaximumPoolSize());
- assertEquals(24*50, executor.getQueue().remainingCapacity());
+ assertEquals(24 * 50, executor.getQueue().remainingCapacity());
}
+
@Test
- public void testThatThreadPoolSizeAndQueueSizeAutoDetected() {
+ void testThatThreadPoolSizeAndQueueSizeAutoDetected() {
ThreadPoolExecutor executor = createPool(0, -100);
- assertEquals(CPUS*4, executor.getMaximumPoolSize());
- assertEquals(CPUS*4*100, executor.getQueue().remainingCapacity());
+ assertEquals(CPUS * 4, executor.getMaximumPoolSize());
+ assertEquals(CPUS * 4 * 100, executor.getQueue().remainingCapacity());
}
private class FlipIt implements Runnable {
@@ -121,9 +124,10 @@ public class ContainerThreadPoolImplTest {
}
}
+ // Ignored because it depends on the system time and so is unstable on factory
@Test
- @Ignore // Ignored because it depends on the system time and so is unstable on factory
- public void testThreadPoolTerminationOnBreakdown() throws InterruptedException {
+ @Disabled
+ void testThreadPoolTerminationOnBreakdown() throws InterruptedException {
ContainerThreadpoolConfig config = new ContainerThreadpoolConfig(
new ContainerThreadpoolConfig.Builder()
.maxThreads(2)
@@ -138,10 +142,16 @@ public class ContainerThreadPoolImplTest {
assertEquals(0, terminator.dieRequests);
assertRejected(threadPool, new Hang(500)); // no more threads
assertEquals(0, terminator.dieRequests); // ... but not for long enough yet
- try { Thread.sleep(1500); } catch (InterruptedException e) {}
+ try {
+ Thread.sleep(1500);
+ } catch (InterruptedException e) {
+ }
threadPool.executor().execute(new Hang(1));
assertEquals(0, terminator.dieRequests);
- try { Thread.sleep(50); } catch (InterruptedException e) {} // Make sure both threads are available
+ try {
+ Thread.sleep(50);
+ } catch (InterruptedException e) {
+ } // Make sure both threads are available
// Dying when hanging both thread pool threads for longer than max thread execution time
threadPool.executor().execute(new Hang(2000));
@@ -149,7 +159,10 @@ public class ContainerThreadPoolImplTest {
assertEquals(0, terminator.dieRequests);
assertRejected(threadPool, new Hang(2000)); // no more threads
assertEquals(0, terminator.dieRequests); // ... but not for long enough yet
- try { Thread.sleep(1500); } catch (InterruptedException e) {}
+ try {
+ Thread.sleep(1500);
+ } catch (InterruptedException e) {
+ }
assertRejected(threadPool, new Hang(2000)); // no more threads
assertEquals(1, terminator.dieRequests); // ... for longer than maxThreadExecutionTime
}
diff --git a/container-core/src/test/java/com/yahoo/container/jdisc/ExtendedResponseTestCase.java b/container-core/src/test/java/com/yahoo/container/jdisc/ExtendedResponseTestCase.java
index 400697af2a8..1b0521177e0 100644
--- a/container-core/src/test/java/com/yahoo/container/jdisc/ExtendedResponseTestCase.java
+++ b/container-core/src/test/java/com/yahoo/container/jdisc/ExtendedResponseTestCase.java
@@ -1,16 +1,16 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.jdisc;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import com.yahoo.jdisc.Response;
import com.yahoo.jdisc.handler.CompletionHandler;
import com.yahoo.jdisc.handler.ContentChannel;
@@ -48,18 +48,18 @@ public class ExtendedResponseTestCase {
}
- @Before
+ @BeforeEach
public void setUp() throws Exception {
r = new TestResponse(Response.Status.OK);
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
r = null;
}
@Test
- public final void testRenderOutputStreamContentChannelCompletionHandler() throws IOException {
+ final void testRenderOutputStreamContentChannelCompletionHandler() throws IOException {
ByteArrayOutputStream b = new ByteArrayOutputStream();
r.render(b, null, null);
assertEquals(COM_YAHOO_CONTAINER_JDISC_EXTENDED_RESPONSE_TEST_CASE, Utf8.toString(b.toByteArray()));
@@ -67,22 +67,22 @@ public class ExtendedResponseTestCase {
@Test
- public final void testGetParsedQuery() {
+ final void testGetParsedQuery() {
assertNull(r.getParsedQuery());
}
@Test
- public final void testGetTiming() {
+ final void testGetTiming() {
assertNull(r.getTiming());
}
@Test
- public final void testGetCoverage() {
+ final void testGetCoverage() {
assertNull(r.getCoverage());
}
@Test
- public final void testGetHitCounts() {
+ final void testGetHitCounts() {
assertNull(r.getHitCounts());
}
diff --git a/container-core/src/test/java/com/yahoo/container/jdisc/HttpRequestTestCase.java b/container-core/src/test/java/com/yahoo/container/jdisc/HttpRequestTestCase.java
index 7fcca89b0d3..ca3c24113ff 100644
--- a/container-core/src/test/java/com/yahoo/container/jdisc/HttpRequestTestCase.java
+++ b/container-core/src/test/java/com/yahoo/container/jdisc/HttpRequestTestCase.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.container.jdisc;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
import java.io.ByteArrayInputStream;
import java.io.IOException;
@@ -10,10 +10,9 @@ import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collections;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import com.yahoo.jdisc.http.HttpRequest.Method;
import com.yahoo.text.Utf8;
@@ -28,74 +27,74 @@ public class HttpRequestTestCase {
HttpRequest r;
InputStream requestData;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
requestData = new ByteArrayInputStream(Utf8.toBytes(X_RAY_YANKEE_ZULU));
r = HttpRequest.createTestRequest(HTTP_MAILHOST_25_ALPHA_BRAVO_CHARLIE_DELTA, Method.GET, requestData, Collections.singletonMap("foxtrot", "golf"));
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
r = null;
}
@Test
- public final void testGetMethod() {
+ final void testGetMethod() {
assertSame(Method.GET, r.getMethod());
}
@Test
- public final void testGetUri() throws URISyntaxException {
+ final void testGetUri() throws URISyntaxException {
assertEquals(new URI(HTTP_MAILHOST_25_ALPHA_BRAVO_CHARLIE_DELTA), r.getUri());
}
@Test
- public final void testGetJDiscRequest() throws URISyntaxException {
+ final void testGetJDiscRequest() throws URISyntaxException {
assertEquals(new URI(HTTP_MAILHOST_25_ALPHA_BRAVO_CHARLIE_DELTA), r.getJDiscRequest().getUri());
}
@Test
- public final void testGetProperty() {
+ final void testGetProperty() {
assertEquals("charlie", r.getProperty("bravo"));
assertEquals("golf", r.getProperty("foxtrot"));
assertNull(r.getProperty("zulu"));
}
@Test
- public final void testPropertyMap() {
+ final void testPropertyMap() {
assertEquals(4, r.propertyMap().size());
}
@Test
- public final void testGetBooleanProperty() {
+ final void testGetBooleanProperty() {
assertTrue(r.getBooleanProperty("trueboolean"));
assertFalse(r.getBooleanProperty("falseboolean"));
assertFalse(r.getBooleanProperty("bravo"));
}
@Test
- public final void testHasProperty() {
+ final void testHasProperty() {
assertFalse(r.hasProperty("alpha"));
assertTrue(r.hasProperty("bravo"));
}
@Test
- public final void testGetHeader() {
+ final void testGetHeader() {
assertNull(r.getHeader("SyntheticHeaderFor-com.yahoo.container.jdisc.HttpRequestTestCase"));
}
@Test
- public final void testGetHost() {
+ final void testGetHost() {
assertEquals("mailhost", r.getHost());
}
@Test
- public final void testGetPort() {
+ final void testGetPort() {
assertEquals(25, r.getPort());
}
@Test
- public final void testGetData() throws IOException {
+ final void testGetData() throws IOException {
byte[] b = new byte[X_RAY_YANKEE_ZULU.length()];
r.getData().read(b);
assertEquals(X_RAY_YANKEE_ZULU, Utf8.toString(b));
diff --git a/container-core/src/test/java/com/yahoo/container/jdisc/HttpResponseTestCase.java b/container-core/src/test/java/com/yahoo/container/jdisc/HttpResponseTestCase.java
index 8dfa9a83988..963c98c2469 100644
--- a/container-core/src/test/java/com/yahoo/container/jdisc/HttpResponseTestCase.java
+++ b/container-core/src/test/java/com/yahoo/container/jdisc/HttpResponseTestCase.java
@@ -1,16 +1,16 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.jdisc;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import com.yahoo.jdisc.Response;
import com.yahoo.text.Utf8;
@@ -37,45 +37,45 @@ public class HttpResponseTestCase {
HttpResponse r;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
r = new TestResponse(Response.Status.OK);
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
r = null;
}
@Test
- public final void testRender() throws IOException {
+ final void testRender() throws IOException {
ByteArrayOutputStream o = new ByteArrayOutputStream(1024);
r.render(o);
assertEquals(COM_YAHOO_CONTAINER_JDISC_HTTP_RESPONSE_TEST_CASE_TEST_RESPONSE, Utf8.toString(o.toByteArray()));
}
@Test
- public final void testGetStatus() {
+ final void testGetStatus() {
assertEquals(Response.Status.OK, r.getStatus());
}
@Test
- public final void testHeaders() {
+ final void testHeaders() {
assertNotNull(r.headers());
}
@Test
- public final void testGetJdiscResponse() {
+ final void testGetJdiscResponse() {
assertNotNull(r.getJdiscResponse());
}
@Test
- public final void testGetContentType() {
+ final void testGetContentType() {
assertEquals(HttpResponse.DEFAULT_MIME_TYPE, r.getContentType());
}
@Test
- public final void testGetCharacterEncoding() {
+ final void testGetCharacterEncoding() {
assertEquals(HttpResponse.DEFAULT_CHARACTER_ENCODING, r.getCharacterEncoding());
}
diff --git a/container-core/src/test/java/com/yahoo/container/jdisc/LoggingRequestHandlerTestCase.java b/container-core/src/test/java/com/yahoo/container/jdisc/LoggingRequestHandlerTestCase.java
index ae0f679771e..94158b277c4 100644
--- a/container-core/src/test/java/com/yahoo/container/jdisc/LoggingRequestHandlerTestCase.java
+++ b/container-core/src/test/java/com/yahoo/container/jdisc/LoggingRequestHandlerTestCase.java
@@ -13,8 +13,8 @@ import com.yahoo.jdisc.handler.ContentChannel;
import com.yahoo.jdisc.handler.RequestHandler;
import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.service.CurrentContainer;
-import org.junit.After;
-import org.junit.Before;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
import java.io.IOException;
import java.io.OutputStream;
@@ -26,7 +26,7 @@ import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* Test contracts in LoggingRequestHandler.
@@ -110,13 +110,13 @@ public class LoggingRequestHandlerTestCase {
}
- @Before
+ @BeforeEach
public void setUp() throws Exception {
executor = Executors.newCachedThreadPool();
handler = new AccessLogTestHandler(executor);
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
handler = null;
executor.shutdown();
diff --git a/container-core/src/test/java/com/yahoo/container/jdisc/LoggingTestCase.java b/container-core/src/test/java/com/yahoo/container/jdisc/LoggingTestCase.java
index ee76b3c5321..e423d44dfa4 100644
--- a/container-core/src/test/java/com/yahoo/container/jdisc/LoggingTestCase.java
+++ b/container-core/src/test/java/com/yahoo/container/jdisc/LoggingTestCase.java
@@ -3,10 +3,9 @@ package com.yahoo.container.jdisc;
import com.yahoo.jdisc.handler.CompletionHandler;
import com.yahoo.jdisc.handler.ContentChannel;
-import java.util.logging.Level;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.ByteBuffer;
@@ -17,8 +16,8 @@ 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.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
/**
* Check error logging from ContentChannelOutputStream is sane.
@@ -72,7 +71,7 @@ public class LoggingTestCase {
ContentChannelOutputStream stream;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
stream = new ContentChannelOutputStream(new FailingContentChannel());
logger = Logger.getLogger(ContentChannelOutputStream.class.getName());
@@ -83,7 +82,7 @@ public class LoggingTestCase {
logger.addHandler(logChecker);
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
logger.removeHandler(logChecker);
logger.setUseParentHandlers(initUseParentHandlers);
@@ -96,7 +95,7 @@ public class LoggingTestCase {
}
@Test
- public final void testFailed() throws IOException {
+ final void testFailed() throws IOException {
stream.send(createData());
stream.send(createData());
stream.send(createData());
diff --git a/container-core/src/test/java/com/yahoo/container/jdisc/RequestBuilderTestCase.java b/container-core/src/test/java/com/yahoo/container/jdisc/RequestBuilderTestCase.java
index 9967ead052d..2a3adaff16e 100644
--- a/container-core/src/test/java/com/yahoo/container/jdisc/RequestBuilderTestCase.java
+++ b/container-core/src/test/java/com/yahoo/container/jdisc/RequestBuilderTestCase.java
@@ -1,12 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.jdisc;
-import static org.junit.Assert.*;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import com.yahoo.jdisc.http.HttpRequest.Method;
/**
@@ -17,26 +17,26 @@ import com.yahoo.jdisc.http.HttpRequest.Method;
public class RequestBuilderTestCase {
HttpRequest.Builder b;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
HttpRequest r = HttpRequest.createTestRequest("http://ssh:22/alpha?bravo=charlie", Method.GET);
b = new HttpRequest.Builder(r);
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
b = null;
}
@Test
- public final void testBasic() {
+ final void testBasic() {
HttpRequest r = b.put("delta", "echo").createDirectRequest();
assertEquals("charlie", r.getProperty("bravo"));
assertEquals("echo", r.getProperty("delta"));
}
@Test
- public void testRemove() {
+ void testRemove() {
HttpRequest orig = b.put("delta", "echo").createDirectRequest();
HttpRequest child = new HttpRequest.Builder(orig).removeProperty("delta").createDirectRequest();
diff --git a/container-core/src/test/java/com/yahoo/container/jdisc/ThreadedHttpRequestHandlerTest.java b/container-core/src/test/java/com/yahoo/container/jdisc/ThreadedHttpRequestHandlerTest.java
index 2592b587539..86b7f545762 100644
--- a/container-core/src/test/java/com/yahoo/container/jdisc/ThreadedHttpRequestHandlerTest.java
+++ b/container-core/src/test/java/com/yahoo/container/jdisc/ThreadedHttpRequestHandlerTest.java
@@ -3,7 +3,7 @@ package com.yahoo.container.jdisc;
import com.yahoo.container.test.MetricMock;
import com.yahoo.jdisc.Metric;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.Executors;
@@ -15,7 +15,7 @@ import static org.assertj.core.api.Assertions.assertThat;
public class ThreadedHttpRequestHandlerTest {
@Test
- public void unhandled_exceptions_metric_is_incremented_if_subclassed_handler_throws_exception() {
+ void unhandled_exceptions_metric_is_incremented_if_subclassed_handler_throws_exception() {
MetricMock metricMock = new MetricMock();
ThreadedHttpRequestHandlerThrowingException handler = new ThreadedHttpRequestHandlerThrowingException(metricMock);
RequestHandlerTestDriver driver = new RequestHandlerTestDriver(handler);
@@ -24,7 +24,7 @@ public class ThreadedHttpRequestHandlerTest {
String expectedMetricName = "jdisc.http.handler.unhandled_exceptions";
assertThat(metricMock.innvocations())
.containsKey(expectedMetricName);
- assertThat(((MetricMock.SimpleMetricContext)metricMock.innvocations().get(expectedMetricName).ctx).dimensions)
+ assertThat(((MetricMock.SimpleMetricContext) metricMock.innvocations().get(expectedMetricName).ctx).dimensions)
.containsEntry("exception", "DummyException");
}
diff --git a/container-core/src/test/java/com/yahoo/container/jdisc/ThreadedRequestHandlerTestCase.java b/container-core/src/test/java/com/yahoo/container/jdisc/ThreadedRequestHandlerTestCase.java
index a9b16799aea..0fbe533fd99 100644
--- a/container-core/src/test/java/com/yahoo/container/jdisc/ThreadedRequestHandlerTestCase.java
+++ b/container-core/src/test/java/com/yahoo/container/jdisc/ThreadedRequestHandlerTestCase.java
@@ -7,7 +7,7 @@ import com.yahoo.jdisc.application.ContainerBuilder;
import com.yahoo.jdisc.handler.*;
import com.yahoo.jdisc.test.TestDriver;
import com.yahoo.yolean.Exceptions;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.URI;
@@ -23,7 +23,7 @@ import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -31,7 +31,7 @@ import static org.junit.Assert.*;
public class ThreadedRequestHandlerTestCase {
@Test
- public void requireThatNullExecutorThrowsException() {
+ void requireThatNullExecutorThrowsException() {
try {
new ThreadedRequestHandler(null) {
@@ -47,7 +47,7 @@ public class ThreadedRequestHandlerTestCase {
}
@Test
- public void requireThatHandlerSetsRequestTimeout() throws InterruptedException {
+ void requireThatHandlerSetsRequestTimeout() throws InterruptedException {
Executor executor = Executors.newSingleThreadExecutor();
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
@@ -69,7 +69,7 @@ public class ThreadedRequestHandlerTestCase {
}
@Test
- public void requireThatOverriddenRequestTimeoutIsUsed() throws InterruptedException {
+ void requireThatOverriddenRequestTimeoutIsUsed() throws InterruptedException {
Executor executor = Executors.newSingleThreadExecutor();
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
@@ -82,7 +82,7 @@ public class ThreadedRequestHandlerTestCase {
requestHandler.entryLatch.countDown();
assertTrue(requestHandler.exitLatch.await(60, TimeUnit.SECONDS));
- assertEquals(1, (long)requestHandler.request.getTimeout(TimeUnit.SECONDS));
+ assertEquals(1, (long) requestHandler.request.getTimeout(TimeUnit.SECONDS));
assertTrue(responseHandler.latch.await(60, TimeUnit.SECONDS));
assertNull(responseHandler.content.read());
@@ -90,7 +90,7 @@ public class ThreadedRequestHandlerTestCase {
}
@Test
- public void requireThatRequestAndResponseReachHandlers() throws InterruptedException {
+ void requireThatRequestAndResponseReachHandlers() throws InterruptedException {
Executor executor = Executors.newSingleThreadExecutor();
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
@@ -119,7 +119,7 @@ public class ThreadedRequestHandlerTestCase {
}
@Test
- public void requireThatRejectedExecutionIsHandledGracefully() throws Exception {
+ void requireThatRejectedExecutionIsHandledGracefully() throws Exception {
// Instrumentation.
final Executor executor = new Executor() {
@Override
@@ -150,14 +150,14 @@ public class ThreadedRequestHandlerTestCase {
}
// Verification.
- assertEquals("Response handler should be invoked synchronously in this case.", 0, responseHandler.latch.getCount());
+ assertEquals(0, responseHandler.latch.getCount(), "Response handler should be invoked synchronously in this case.");
assertEquals(Response.Status.SERVICE_UNAVAILABLE, responseHandler.response.getStatus());
assertNull(responseHandler.content.read());
assertTrue(driver.close());
}
@Test
- public void requireThatRequestContentIsClosedIfHandlerIgnoresIt() throws InterruptedException {
+ void requireThatRequestContentIsClosedIfHandlerIgnoresIt() throws InterruptedException {
Executor executor = Executors.newSingleThreadExecutor();
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
@@ -186,7 +186,7 @@ public class ThreadedRequestHandlerTestCase {
}
@Test
- public void requireThatResponseIsDispatchedIfHandlerIgnoresIt() throws InterruptedException {
+ void requireThatResponseIsDispatchedIfHandlerIgnoresIt() throws InterruptedException {
Executor executor = Executors.newSingleThreadExecutor();
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
@@ -207,7 +207,7 @@ public class ThreadedRequestHandlerTestCase {
}
@Test
- public void requireThatRequestContentIsClosedAndResponseIsDispatchedIfHandlerIgnoresIt()
+ void requireThatRequestContentIsClosedAndResponseIsDispatchedIfHandlerIgnoresIt()
throws InterruptedException
{
Executor executor = Executors.newSingleThreadExecutor();
@@ -360,7 +360,7 @@ public class ThreadedRequestHandlerTestCase {
}
@Test
- public void testMaxPendingOutputStream() throws IOException, ExecutionException, InterruptedException {
+ void testMaxPendingOutputStream() throws IOException, ExecutionException, InterruptedException {
ReadableContentChannel buffer = new ReadableContentChannel();
MaxPendingContentChannelOutputStream limited = new MaxPendingContentChannelOutputStream(buffer, 2);
@@ -375,7 +375,8 @@ public class ThreadedRequestHandlerTestCase {
future.get(100, TimeUnit.MILLISECONDS);
fail("Should not be able to write now");
}
- catch (TimeoutException expected) { }
+ catch (TimeoutException expected) {
+ }
// Free buffer capacity, so write completes, then drain buffer.
assertEquals(2, buffer.read().capacity());
@@ -390,12 +391,14 @@ public class ThreadedRequestHandlerTestCase {
limited.send(ByteBuffer.allocate(3));
fail("Should throw");
}
- catch (IOException expected) { }
+ catch (IOException expected) {
+ }
try {
limited.send(ByteBuffer.allocate(3));
fail("Should throw");
}
- catch (IOException expected) { }
+ catch (IOException expected) {
+ }
}
}
diff --git a/container-core/src/test/java/com/yahoo/container/jdisc/state/CoredumpGathererTest.java b/container-core/src/test/java/com/yahoo/container/jdisc/state/CoredumpGathererTest.java
index 1b075ace190..5cec6c471fe 100644
--- a/container-core/src/test/java/com/yahoo/container/jdisc/state/CoredumpGathererTest.java
+++ b/container-core/src/test/java/com/yahoo/container/jdisc/state/CoredumpGathererTest.java
@@ -2,12 +2,12 @@
package com.yahoo.container.jdisc.state;
import com.fasterxml.jackson.databind.JsonNode;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.file.Path;
import java.util.stream.Stream;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
@@ -16,12 +16,12 @@ import static org.junit.Assert.assertEquals;
public class CoredumpGathererTest {
@Test
- public void finds_one_coredump() {
- JsonNode packet = CoredumpGatherer.gatherCoredumpMetrics(new MockFileWrapper());
+ void finds_one_coredump() {
+ JsonNode packet = CoredumpGatherer.gatherCoredumpMetrics(new MockFileWrapper());
- assertEquals("system-coredumps-processing", packet.get("application").textValue());
- assertEquals(1, packet.get("status_code").intValue());
- assertEquals("Found 1 coredump(s)", packet.get("status_msg").textValue());
+ assertEquals("system-coredumps-processing", packet.get("application").textValue());
+ assertEquals(1, packet.get("status_code").intValue());
+ assertEquals("Found 1 coredump(s)", packet.get("status_msg").textValue());
}
diff --git a/container-core/src/test/java/com/yahoo/container/jdisc/state/HostLifeGathererTest.java b/container-core/src/test/java/com/yahoo/container/jdisc/state/HostLifeGathererTest.java
index 634f5321555..c394630cb40 100644
--- a/container-core/src/test/java/com/yahoo/container/jdisc/state/HostLifeGathererTest.java
+++ b/container-core/src/test/java/com/yahoo/container/jdisc/state/HostLifeGathererTest.java
@@ -2,11 +2,11 @@
package com.yahoo.container.jdisc.state;
import com.fasterxml.jackson.databind.JsonNode;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.file.Path;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
@@ -15,7 +15,7 @@ import static org.junit.Assert.assertEquals;
public class HostLifeGathererTest {
@Test
- public void host_is_alive() {
+ void host_is_alive() {
JsonNode packet = HostLifeGatherer.getHostLifePacket(new MockFileWrapper());
JsonNode metrics = packet.get("metrics");
assertEquals("host_life", packet.get("application").textValue());
diff --git a/container-core/src/test/java/com/yahoo/container/jdisc/state/MetricSnapshotTest.java b/container-core/src/test/java/com/yahoo/container/jdisc/state/MetricSnapshotTest.java
index 82349dd6af9..1fd5e081fb0 100644
--- a/container-core/src/test/java/com/yahoo/container/jdisc/state/MetricSnapshotTest.java
+++ b/container-core/src/test/java/com/yahoo/container/jdisc/state/MetricSnapshotTest.java
@@ -1,13 +1,13 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.jdisc.state;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.HashMap;
-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;
public class MetricSnapshotTest {
@@ -19,16 +19,16 @@ public class MetricSnapshotTest {
* most likely be deprecated.
*/
@Test
- public void emptyMetricSetNotAddedToClonedSnapshot() {
+ void emptyMetricSetNotAddedToClonedSnapshot() {
StateMetricContext ctx = StateMetricContext.newInstance(null);
MetricSnapshot snapshot = new MetricSnapshot();
snapshot.add(ctx, "foo", 1234);
MetricSnapshot newSnapshot = snapshot.createSnapshot();
assertFalse(newSnapshot.iterator().hasNext());
}
-
+
@Test
- public void testEquality() {
+ void testEquality() {
assertEquals(Collections.unmodifiableMap(new HashMap(0)).hashCode(), Collections.emptyMap().hashCode());
assertEquals(Collections.unmodifiableMap(new HashMap(0)), Collections.emptyMap());
}
diff --git a/container-core/src/test/java/com/yahoo/container/jdisc/state/MetricsPacketsHandlerTest.java b/container-core/src/test/java/com/yahoo/container/jdisc/state/MetricsPacketsHandlerTest.java
index 6c05af95289..019fc1e1e78 100644
--- a/container-core/src/test/java/com/yahoo/container/jdisc/state/MetricsPacketsHandlerTest.java
+++ b/container-core/src/test/java/com/yahoo/container/jdisc/state/MetricsPacketsHandlerTest.java
@@ -4,8 +4,8 @@ package com.yahoo.container.jdisc.state;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yahoo.container.jdisc.RequestHandlerTestDriver;
-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;
@@ -18,8 +18,8 @@ import static com.yahoo.container.jdisc.state.MetricsPacketsHandler.PACKET_SEPAR
import static com.yahoo.container.jdisc.state.MetricsPacketsHandler.STATUS_CODE_KEY;
import static com.yahoo.container.jdisc.state.MetricsPacketsHandler.STATUS_MSG_KEY;
import static com.yahoo.container.jdisc.state.MetricsPacketsHandler.TIMESTAMP_KEY;
-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
@@ -31,7 +31,7 @@ public class MetricsPacketsHandlerTest extends StateHandlerTestBase {
private static MetricsPacketsHandler metricsPacketsHandler;
- @Before
+ @BeforeEach
public void setupHandler() {
metricsPacketsHandlerConfig = new MetricsPacketsHandlerConfig(new MetricsPacketsHandlerConfig.Builder()
.application(APPLICATION_NAME).hostname(HOST_DIMENSION));
@@ -40,20 +40,20 @@ public class MetricsPacketsHandlerTest extends StateHandlerTestBase {
}
@Test
- public void status_packet_is_returned_prior_to_first_snapshot() throws Exception {
+ void status_packet_is_returned_prior_to_first_snapshot() throws Exception {
String response = requestAsString("http://localhost/metrics-packets");
List<JsonNode> packets = toJsonPackets(response);
assertEquals(1, packets.size());
JsonNode statusPacket = packets.get(0);
- assertEquals(statusPacket.toString(), APPLICATION_NAME, statusPacket.get(APPLICATION_KEY).asText());
- assertEquals(statusPacket.toString(), 0, statusPacket.get(STATUS_CODE_KEY).asInt());
- assertEquals(statusPacket.toString(), "up", statusPacket.get(STATUS_MSG_KEY).asText());
+ assertEquals(APPLICATION_NAME, statusPacket.get(APPLICATION_KEY).asText(), statusPacket.toString());
+ assertEquals(0, statusPacket.get(STATUS_CODE_KEY).asInt(), statusPacket.toString());
+ assertEquals("up", statusPacket.get(STATUS_MSG_KEY).asText(), statusPacket.toString());
}
@Test
- public void metrics_are_included_after_snapshot() throws Exception {
+ void metrics_are_included_after_snapshot() throws Exception {
createSnapshotWithCountMetric("counter", 1, null);
List<JsonNode> packets = incrementTimeAndGetJsonPackets();
assertEquals(2, packets.size());
@@ -63,7 +63,7 @@ public class MetricsPacketsHandlerTest extends StateHandlerTestBase {
}
@Test
- public void metadata_is_included_in_each_metrics_packet() throws Exception {
+ void metadata_is_included_in_each_metrics_packet() throws Exception {
createSnapshotWithCountMetric("counter", 1, null);
List<JsonNode> packets = incrementTimeAndGetJsonPackets();
JsonNode counterPacket = packets.get(1);
@@ -74,16 +74,16 @@ public class MetricsPacketsHandlerTest extends StateHandlerTestBase {
}
@Test
- public void timestamp_resolution_is_in_seconds() throws Exception {
+ void timestamp_resolution_is_in_seconds() throws Exception {
createSnapshotWithCountMetric("counter", 1, null);
List<JsonNode> packets = incrementTimeAndGetJsonPackets();
JsonNode counterPacket = packets.get(1);
- assertEquals(SNAPSHOT_INTERVAL/1000L, counterPacket.get(TIMESTAMP_KEY).asLong());
+ assertEquals(SNAPSHOT_INTERVAL / 1000L, counterPacket.get(TIMESTAMP_KEY).asLong());
}
@Test
- public void expected_aggregators_are_output_for_gauge_metrics() throws Exception{
+ void expected_aggregators_are_output_for_gauge_metrics() throws Exception {
var context = StateMetricContext.newInstance(Map.of("dim1", "value1"));
var snapshot = new MetricSnapshot();
snapshot.set(context, "gauge", 0.2);
@@ -98,7 +98,7 @@ public class MetricsPacketsHandlerTest extends StateHandlerTestBase {
}
@Test
- public void dimensions_from_context_are_included() throws Exception {
+ void dimensions_from_context_are_included() throws Exception {
var context = StateMetricContext.newInstance(Map.of("dim1", "value1"));
createSnapshotWithCountMetric("counter", 1, context);
@@ -111,7 +111,7 @@ public class MetricsPacketsHandlerTest extends StateHandlerTestBase {
}
@Test
- public void metrics_with_identical_dimensions_are_contained_in_the_same_packet() throws Exception {
+ void metrics_with_identical_dimensions_are_contained_in_the_same_packet() throws Exception {
var context = StateMetricContext.newInstance(Map.of("dim1", "value1"));
var snapshot = new MetricSnapshot();
snapshot.add(context, "counter1", 1);
@@ -128,7 +128,7 @@ public class MetricsPacketsHandlerTest extends StateHandlerTestBase {
}
@Test
- public void metrics_with_different_dimensions_get_separate_packets() throws Exception {
+ void metrics_with_different_dimensions_get_separate_packets() throws Exception {
var context1 = StateMetricContext.newInstance(Map.of("dim1", "value1"));
var context2 = StateMetricContext.newInstance(Map.of("dim2", "value2"));
var snapshot = new MetricSnapshot();
@@ -141,7 +141,7 @@ public class MetricsPacketsHandlerTest extends StateHandlerTestBase {
}
@Test
- public void host_dimension_only_created_if_absent() throws Exception {
+ void host_dimension_only_created_if_absent() throws Exception {
var context1 = StateMetricContext.newInstance(Map.of("dim1", "value1", "host", "foo.bar"));
var context2 = StateMetricContext.newInstance(Map.of("dim2", "value2"));
var snapshot = new MetricSnapshot();
diff --git a/container-core/src/test/java/com/yahoo/container/jdisc/state/StateHandlerTest.java b/container-core/src/test/java/com/yahoo/container/jdisc/state/StateHandlerTest.java
index 8f800707f7a..63502a6b49f 100644
--- a/container-core/src/test/java/com/yahoo/container/jdisc/state/StateHandlerTest.java
+++ b/container-core/src/test/java/com/yahoo/container/jdisc/state/StateHandlerTest.java
@@ -5,15 +5,13 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.yahoo.component.Vtag;
import com.yahoo.container.jdisc.RequestHandlerTestDriver;
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 java.util.Map;
import java.util.concurrent.TimeUnit;
-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
@@ -23,47 +21,47 @@ public class StateHandlerTest extends StateHandlerTestBase {
private static final String V1_URI = URI_BASE + "/state/v1/";
private static StateHandler stateHandler;
- @Before
+ @BeforeEach
public void setupHandler() {
stateHandler = new StateHandler(monitor, timer, applicationMetadataConfig, snapshotProviderRegistry);
testDriver = new RequestHandlerTestDriver(stateHandler);
}
@Test
- public void testStatusReportPriorToFirstSnapshot() throws Exception {
+ void testStatusReportPriorToFirstSnapshot() throws Exception {
JsonNode json = requestAsJson(V1_URI + "/all");
- assertEquals(json.toString(), "up", json.get("status").get("code").asText());
- assertFalse(json.toString(), json.get("metrics").has("values"));
+ assertEquals("up", json.get("status").get("code").asText(), json.toString());
+ assertFalse(json.get("metrics").has("values"), json.toString());
}
@Test
- public void testReportIncludesMetricsAfterSnapshot() throws Exception {
+ void testReportIncludesMetricsAfterSnapshot() throws Exception {
var snapshot = new MetricSnapshot();
snapshot.add(null, "foo", 1);
snapshot.set(null, "bar", 4);
snapshotProvider.setSnapshot(snapshot);
JsonNode json1 = requestAsJson(V1_URI + "metrics");
- assertEquals(json1.toString(), "up", json1.get("status").get("code").asText());
- assertEquals(json1.toString(), 2, json1.get("metrics").get("values").size());
+ assertEquals("up", json1.get("status").get("code").asText(), json1.toString());
+ assertEquals(2, json1.get("metrics").get("values").size(), json1.toString());
}
@Test
- public void testCountMetricCount() throws Exception {
+ void testCountMetricCount() throws Exception {
var snapshot = new MetricSnapshot();
snapshot.add(null, "foo", 4);
snapshot.add(null, "foo", 2);
snapshotProvider.setSnapshot(snapshot);
JsonNode json = requestAsJson(V1_URI + "all");
- assertEquals(json.toString(), "up", json.get("status").get("code").asText());
- assertEquals(json.toString(), 1, json.get("metrics").get("values").size());
- assertEquals(json.toString(), 6,
- json.get("metrics").get("values").get(0).get("values").get("count").asDouble(), 0.001);
+ assertEquals("up", json.get("status").get("code").asText(), json.toString());
+ assertEquals(1, json.get("metrics").get("values").size(), json.toString());
+ assertEquals(6,
+ json.get("metrics").get("values").get(0).get("values").get("count").asDouble(), 0.001, json.toString());
}
@Test
- public void gaugeSnapshotsTracksCountMinMaxAvgPerPeriod() throws Exception {
+ void gaugeSnapshotsTracksCountMinMaxAvgPerPeriod() throws Exception {
var snapshot = new MetricSnapshot();
snapshot.set(null, "bar", 20);
snapshot.set(null, "bar", 40);
@@ -71,23 +69,23 @@ public class StateHandlerTest extends StateHandlerTestBase {
JsonNode json = requestAsJson(V1_URI + "all");
JsonNode metricValues = getFirstMetricValueNode(json);
- assertEquals(json.toString(), 40, metricValues.get("last").asDouble(), 0.001);
+ assertEquals(40, metricValues.get("last").asDouble(), 0.001, json.toString());
// Last snapshot had explicit values set
- assertEquals(json.toString(), 30, metricValues.get("average").asDouble(), 0.001);
- assertEquals(json.toString(), 20, metricValues.get("min").asDouble(), 0.001);
- assertEquals(json.toString(), 40, metricValues.get("max").asDouble(), 0.001);
- assertEquals(json.toString(), 2, metricValues.get("count").asInt());
+ assertEquals(30, metricValues.get("average").asDouble(), 0.001, json.toString());
+ assertEquals(20, metricValues.get("min").asDouble(), 0.001, json.toString());
+ assertEquals(40, metricValues.get("max").asDouble(), 0.001, json.toString());
+ assertEquals(2, metricValues.get("count").asInt(), json.toString());
}
private JsonNode getFirstMetricValueNode(JsonNode root) {
- assertEquals(root.toString(), 1, root.get("metrics").get("values").size());
+ assertEquals(1, root.get("metrics").get("values").size(), root.toString());
JsonNode metricValues = root.get("metrics").get("values").get(0).get("values");
- assertTrue(root.toString(), metricValues.has("last"));
+ assertTrue(metricValues.has("last"), root.toString());
return metricValues;
}
@Test
- public void testReadabilityOfJsonReport() {
+ void testReadabilityOfJsonReport() {
var snapshot = new MetricSnapshot(0L, SNAPSHOT_INTERVAL, TimeUnit.MILLISECONDS);
snapshot.add(null, "foo", 1);
var ctx = StateMetricContext.newInstance(Map.of("component", "test"));
@@ -98,43 +96,43 @@ public class StateHandlerTest extends StateHandlerTestBase {
snapshotProvider.setSnapshot(snapshot);
advanceToNextSnapshot();
assertEquals("{\n" +
- " \"time\" : 300000,\n" +
- " \"status\" : {\n" +
- " \"code\" : \"up\"\n" +
- " },\n" +
- " \"metrics\" : {\n" +
- " \"snapshot\" : {\n" +
- " \"from\" : 0.0,\n" +
- " \"to\" : 300.0\n" +
- " },\n" +
- " \"values\" : [ {\n" +
- " \"name\" : \"foo\",\n" +
- " \"values\" : {\n" +
- " \"count\" : 1,\n" +
- " \"rate\" : 0.0033333333333333335\n" +
- " }\n" +
- " }, {\n" +
- " \"name\" : \"bar\",\n" +
- " \"values\" : {\n" +
- " \"average\" : 3.5,\n" +
- " \"sum\" : 14.0,\n" +
- " \"count\" : 4,\n" +
- " \"last\" : 5.0,\n" +
- " \"max\" : 5.0,\n" +
- " \"min\" : 2.0,\n" +
- " \"rate\" : 0.013333333333333334\n" +
- " },\n" +
- " \"dimensions\" : {\n" +
- " \"component\" : \"test\"\n" +
- " }\n" +
- " } ]\n" +
- " }\n" +
- "}",
- requestAsString(V1_URI + "all"));
+ " \"time\" : 300000,\n" +
+ " \"status\" : {\n" +
+ " \"code\" : \"up\"\n" +
+ " },\n" +
+ " \"metrics\" : {\n" +
+ " \"snapshot\" : {\n" +
+ " \"from\" : 0.0,\n" +
+ " \"to\" : 300.0\n" +
+ " },\n" +
+ " \"values\" : [ {\n" +
+ " \"name\" : \"foo\",\n" +
+ " \"values\" : {\n" +
+ " \"count\" : 1,\n" +
+ " \"rate\" : 0.0033333333333333335\n" +
+ " }\n" +
+ " }, {\n" +
+ " \"name\" : \"bar\",\n" +
+ " \"values\" : {\n" +
+ " \"average\" : 3.5,\n" +
+ " \"sum\" : 14.0,\n" +
+ " \"count\" : 4,\n" +
+ " \"last\" : 5.0,\n" +
+ " \"max\" : 5.0,\n" +
+ " \"min\" : 2.0,\n" +
+ " \"rate\" : 0.013333333333333334\n" +
+ " },\n" +
+ " \"dimensions\" : {\n" +
+ " \"component\" : \"test\"\n" +
+ " }\n" +
+ " } ]\n" +
+ " }\n" +
+ "}",
+ requestAsString(V1_URI + "all"));
}
@Test
- public void testHealthAggregation() throws Exception {
+ void testHealthAggregation() throws Exception {
var context1 = StateMetricContext.newInstance(Map.of("port", Defaults.getDefaults().vespaWebServicePort()));
var context2 = StateMetricContext.newInstance(Map.of("port", 80));
var snapshot = new MetricSnapshot();
@@ -146,20 +144,22 @@ public class StateHandlerTest extends StateHandlerTestBase {
snapshotProvider.setSnapshot(snapshot);
JsonNode json = requestAsJson(V1_URI + "health");
- assertEquals(json.toString(), "up", json.get("status").get("code").asText());
- assertEquals(json.toString(), 2, json.get("metrics").get("values").size());
- assertEquals(json.toString(), "requestsPerSecond",
- json.get("metrics").get("values").get(0).get("name").asText());
- assertEquals(json.toString(), 6,
- json.get("metrics").get("values").get(0).get("values").get("count").asDouble(), 0.001);
- assertEquals(json.toString(), "latencySeconds",
- json.get("metrics").get("values").get(1).get("name").asText());
- assertEquals(json.toString(), 0.03,
- json.get("metrics").get("values").get(1).get("values").get("average").asDouble(), 0.001);
+ assertEquals("up", json.get("status").get("code").asText(), json.toString());
+ assertEquals(2, json.get("metrics").get("values").size(), json.toString());
+ assertEquals("requestsPerSecond",
+ json.get("metrics").get("values").get(0).get("name").asText(),
+ json.toString());
+ assertEquals(6,
+ json.get("metrics").get("values").get(0).get("values").get("count").asDouble(), 0.001, json.toString());
+ assertEquals("latencySeconds",
+ json.get("metrics").get("values").get(1).get("name").asText(),
+ json.toString());
+ assertEquals(0.03,
+ json.get("metrics").get("values").get(1).get("values").get("average").asDouble(), 0.001, json.toString());
}
@Test
- public void testStateConfig() throws Exception {
+ void testStateConfig() throws Exception {
JsonNode root = requestAsJson(V1_URI + "config");
JsonNode config = root.get("config");
@@ -168,7 +168,7 @@ public class StateHandlerTest extends StateHandlerTestBase {
}
@Test
- public void testStateVersion() throws Exception {
+ void testStateVersion() throws Exception {
JsonNode root = requestAsJson(V1_URI + "version");
JsonNode version = root.get("version");
diff --git a/container-core/src/test/java/com/yahoo/container/jdisc/state/StateHandlerTestBase.java b/container-core/src/test/java/com/yahoo/container/jdisc/state/StateHandlerTestBase.java
index b87a1179832..e3d01391a9c 100644
--- a/container-core/src/test/java/com/yahoo/container/jdisc/state/StateHandlerTestBase.java
+++ b/container-core/src/test/java/com/yahoo/container/jdisc/state/StateHandlerTestBase.java
@@ -9,8 +9,8 @@ import com.yahoo.container.core.ApplicationMetadataConfig;
import com.yahoo.container.jdisc.RequestHandlerTestDriver;
import com.yahoo.container.jdisc.config.HealthMonitorConfig;
import com.yahoo.jdisc.Timer;
-import org.junit.Before;
-import org.junit.BeforeClass;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
@@ -38,7 +38,7 @@ public class StateHandlerTestBase {
MockSnapshotProvider snapshotProvider;
ComponentRegistry<SnapshotProvider> snapshotProviderRegistry;
- @BeforeClass
+ @BeforeAll
public static void setupClass() {
healthMonitorConfig = new HealthMonitorConfig(new HealthMonitorConfig.Builder()
.initialStatus("up"));
@@ -46,7 +46,7 @@ public class StateHandlerTestBase {
.generation(META_GENERATION));
}
- @Before
+ @BeforeEach
public void setupSnapshotProvider() {
timer = currentTimeMillis::get;
snapshotProvider = new MockSnapshotProvider();
diff --git a/container-core/src/test/java/com/yahoo/container/logging/CircularArrayAccessLogKeeperTest.java b/container-core/src/test/java/com/yahoo/container/logging/CircularArrayAccessLogKeeperTest.java
index 451e6dc42bb..f942ee588be 100644
--- a/container-core/src/test/java/com/yahoo/container/logging/CircularArrayAccessLogKeeperTest.java
+++ b/container-core/src/test/java/com/yahoo/container/logging/CircularArrayAccessLogKeeperTest.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.container.logging;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.Matchers.contains;
@@ -14,11 +14,11 @@ public class CircularArrayAccessLogKeeperTest {
private CircularArrayAccessLogKeeper circularArrayAccessLogKeeper = new CircularArrayAccessLogKeeper();
@Test
- public void testSizeIsCroppedCorrectly() {
+ void testSizeIsCroppedCorrectly() {
for (int i = 0; i < CircularArrayAccessLogKeeper.SIZE - 1; i++) {
circularArrayAccessLogKeeper.addUri(String.valueOf(i));
}
- assertThat(circularArrayAccessLogKeeper.getUris().size(), is(CircularArrayAccessLogKeeper.SIZE -1));
+ assertThat(circularArrayAccessLogKeeper.getUris().size(), is(CircularArrayAccessLogKeeper.SIZE - 1));
circularArrayAccessLogKeeper.addUri("foo");
assertThat(circularArrayAccessLogKeeper.getUris().size(), is(CircularArrayAccessLogKeeper.SIZE));
circularArrayAccessLogKeeper.addUri("bar");
@@ -28,12 +28,12 @@ public class CircularArrayAccessLogKeeperTest {
}
@Test
- public void testEmpty() {
+ void testEmpty() {
assertThat(circularArrayAccessLogKeeper.getUris().size(), is(0));
}
@Test
- public void testSomeItems() {
+ void testSomeItems() {
circularArrayAccessLogKeeper.addUri("a");
circularArrayAccessLogKeeper.addUri("b");
circularArrayAccessLogKeeper.addUri("b");
diff --git a/container-core/src/test/java/com/yahoo/container/logging/JSONLogTestCase.java b/container-core/src/test/java/com/yahoo/container/logging/JSONLogTestCase.java
index eb862d69b5b..1c66a1d805a 100644
--- a/container-core/src/test/java/com/yahoo/container/logging/JSONLogTestCase.java
+++ b/container-core/src/test/java/com/yahoo/container/logging/JSONLogTestCase.java
@@ -2,7 +2,7 @@
package com.yahoo.container.logging;
import com.yahoo.yolean.trace.TraceNode;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -41,35 +41,36 @@ public class JSONLogTestCase {
}
@Test
- public void test_json_log_entry() {
+ void test_json_log_entry() {
RequestLogEntry entry = newRequestLogEntry("test").build();
- String expectedOutput =
- "{\"ip\":\"152.200.54.243\"," +
- "\"peeraddr\":\"152.200.54.243\"," +
- "\"time\":920880005.023," +
- "\"duration\":0.122," +
- "\"responsesize\":9875," +
- "\"requestsize\":0," +
- "\"code\":200," +
- "\"method\":\"GET\"," +
- "\"uri\":\"?query=test\"," +
- "\"version\":\"HTTP/1.1\"," +
- "\"agent\":\"Mozilla/4.05 [en] (Win95; I)\"," +
- "\"host\":\"localhost\"," +
- "\"scheme\":null," +
- "\"localport\":0," +
- "\"search\":{" +
- "\"totalhits\":1234," +
- "\"hits\":0," +
- "\"coverage\":{\"coverage\":100,\"documents\":100}" +
- "}" +
- "}";
+ String expectedOutput =
+ "{\"ip\":\"152.200.54.243\"," +
+ "\"peeraddr\":\"152.200.54.243\"," +
+ "\"time\":920880005.023," +
+ "\"duration\":0.122," +
+ "\"responsesize\":9875," +
+ "\"requestsize\":0," +
+ "\"code\":200," +
+ "\"method\":\"GET\"," +
+ "\"uri\":\"?query=test\"," +
+ "\"version\":\"HTTP/1.1\"," +
+ "\"agent\":\"Mozilla/4.05 [en] (Win95; I)\"," +
+ "\"host\":\"localhost\"," +
+ "\"scheme\":null," +
+ "\"localport\":0," +
+ "\"search\":{" +
+ "\"totalhits\":1234," +
+ "\"hits\":0," +
+ "\"coverage\":{\"coverage\":100,\"documents\":100}" +
+ "}" +
+ "}";
assertJsonEquals(formatEntry(entry), expectedOutput);
}
+
@Test
- public void test_json_of_trace() {
+ void test_json_of_trace() {
TraceNode root = new TraceNode("root", 7);
RequestLogEntry entry = newRequestLogEntry("test")
.traceNode(root)
@@ -77,31 +78,32 @@ public class JSONLogTestCase {
String expectedOutput =
"{\"ip\":\"152.200.54.243\"," +
- "\"peeraddr\":\"152.200.54.243\"," +
- "\"time\":920880005.023," +
- "\"duration\":0.122," +
- "\"responsesize\":9875," +
- "\"requestsize\":0," +
- "\"code\":200," +
- "\"method\":\"GET\"," +
- "\"uri\":\"?query=test\"," +
- "\"version\":\"HTTP/1.1\"," +
- "\"agent\":\"Mozilla/4.05 [en] (Win95; I)\"," +
- "\"host\":\"localhost\"," +
- "\"scheme\":null," +
- "\"localport\":0," +
- "\"trace\":{\"timestamp\":0,\"message\":\"root\"}," +
- "\"search\":{" +
- "\"totalhits\":1234," +
- "\"hits\":0," +
- "\"coverage\":{\"coverage\":100,\"documents\":100}" +
- "}" +
- "}";
+ "\"peeraddr\":\"152.200.54.243\"," +
+ "\"time\":920880005.023," +
+ "\"duration\":0.122," +
+ "\"responsesize\":9875," +
+ "\"requestsize\":0," +
+ "\"code\":200," +
+ "\"method\":\"GET\"," +
+ "\"uri\":\"?query=test\"," +
+ "\"version\":\"HTTP/1.1\"," +
+ "\"agent\":\"Mozilla/4.05 [en] (Win95; I)\"," +
+ "\"host\":\"localhost\"," +
+ "\"scheme\":null," +
+ "\"localport\":0," +
+ "\"trace\":{\"timestamp\":0,\"message\":\"root\"}," +
+ "\"search\":{" +
+ "\"totalhits\":1234," +
+ "\"hits\":0," +
+ "\"coverage\":{\"coverage\":100,\"documents\":100}" +
+ "}" +
+ "}";
assertJsonEquals(formatEntry(entry), expectedOutput);
}
+
@Test
- public void test_with_keyvalues() {
+ void test_with_keyvalues() {
RequestLogEntry entry = newRequestLogEntry("test")
.addExtraAttribute("singlevalue", "value1")
.addExtraAttribute("multivalue", "value2")
@@ -109,62 +111,62 @@ public class JSONLogTestCase {
.build();
String expectedOutput =
- "{\"ip\":\"152.200.54.243\"," +
- "\"peeraddr\":\"152.200.54.243\"," +
- "\"time\":920880005.023," +
- "\"duration\":0.122," +
- "\"responsesize\":9875," +
- "\"requestsize\":0," +
- "\"code\":200," +
- "\"method\":\"GET\"," +
- "\"uri\":\"?query=test\"," +
- "\"version\":\"HTTP/1.1\"," +
- "\"agent\":\"Mozilla/4.05 [en] (Win95; I)\"," +
- "\"host\":\"localhost\"," +
- "\"scheme\":null," +
- "\"localport\":0," +
- "\"search\":{" +
- "\"totalhits\":1234," +
- "\"hits\":0," +
- "\"coverage\":{\"coverage\":100,\"documents\":100}" +
- "}," +
- "\"attributes\":{" +
- "\"singlevalue\":\"value1\"," +
- "\"multivalue\":[\"value2\",\"value3\"]}" +
- "}";
+ "{\"ip\":\"152.200.54.243\"," +
+ "\"peeraddr\":\"152.200.54.243\"," +
+ "\"time\":920880005.023," +
+ "\"duration\":0.122," +
+ "\"responsesize\":9875," +
+ "\"requestsize\":0," +
+ "\"code\":200," +
+ "\"method\":\"GET\"," +
+ "\"uri\":\"?query=test\"," +
+ "\"version\":\"HTTP/1.1\"," +
+ "\"agent\":\"Mozilla/4.05 [en] (Win95; I)\"," +
+ "\"host\":\"localhost\"," +
+ "\"scheme\":null," +
+ "\"localport\":0," +
+ "\"search\":{" +
+ "\"totalhits\":1234," +
+ "\"hits\":0," +
+ "\"coverage\":{\"coverage\":100,\"documents\":100}" +
+ "}," +
+ "\"attributes\":{" +
+ "\"singlevalue\":\"value1\"," +
+ "\"multivalue\":[\"value2\",\"value3\"]}" +
+ "}";
assertJsonEquals(formatEntry(entry), expectedOutput);
}
@Test
- public void test_with_remoteaddrport() throws Exception {
+ void test_with_remoteaddrport() throws Exception {
RequestLogEntry entry = newRequestLogEntry("test")
.remoteAddress("FE80:0000:0000:0000:0202:B3FF:FE1E:8329")
.build();
String expectedOutput =
- "{\"ip\":\"152.200.54.243\"," +
- "\"peeraddr\":\"152.200.54.243\"," +
- "\"time\":920880005.023," +
- "\"duration\":0.122," +
- "\"responsesize\":9875," +
- "\"requestsize\":0," +
- "\"code\":200," +
- "\"method\":\"GET\"," +
- "\"uri\":\"?query=test\"," +
- "\"version\":\"HTTP/1.1\"," +
- "\"agent\":\"Mozilla/4.05 [en] (Win95; I)\"," +
- "\"host\":\"localhost\"," +
- "\"scheme\":null," +
- "\"localport\":0," +
- "\"remoteaddr\":\"FE80:0000:0000:0000:0202:B3FF:FE1E:8329\"," +
- "\"search\":{" +
- "\"totalhits\":1234," +
- "\"hits\":0," +
- "\"coverage\":{\"coverage\":100,\"documents\":100}" +
- "}" +
- "}";
+ "{\"ip\":\"152.200.54.243\"," +
+ "\"peeraddr\":\"152.200.54.243\"," +
+ "\"time\":920880005.023," +
+ "\"duration\":0.122," +
+ "\"responsesize\":9875," +
+ "\"requestsize\":0," +
+ "\"code\":200," +
+ "\"method\":\"GET\"," +
+ "\"uri\":\"?query=test\"," +
+ "\"version\":\"HTTP/1.1\"," +
+ "\"agent\":\"Mozilla/4.05 [en] (Win95; I)\"," +
+ "\"host\":\"localhost\"," +
+ "\"scheme\":null," +
+ "\"localport\":0," +
+ "\"remoteaddr\":\"FE80:0000:0000:0000:0202:B3FF:FE1E:8329\"," +
+ "\"search\":{" +
+ "\"totalhits\":1234," +
+ "\"hits\":0," +
+ "\"coverage\":{\"coverage\":100,\"documents\":100}" +
+ "}" +
+ "}";
assertJsonEquals(formatEntry(entry), expectedOutput);
@@ -175,34 +177,34 @@ public class JSONLogTestCase {
.build();
expectedOutput =
- "{\"ip\":\"152.200.54.243\"," +
- "\"peeraddr\":\"152.200.54.243\"," +
- "\"time\":920880005.023," +
- "\"duration\":0.122," +
- "\"responsesize\":9875," +
- "\"requestsize\":0," +
- "\"code\":200," +
- "\"method\":\"GET\"," +
- "\"uri\":\"?query=test\"," +
- "\"version\":\"HTTP/1.1\"," +
- "\"agent\":\"Mozilla/4.05 [en] (Win95; I)\"," +
- "\"host\":\"localhost\"," +
- "\"scheme\":null," +
- "\"localport\":0," +
- "\"remoteaddr\":\"FE80:0000:0000:0000:0202:B3FF:FE1E:8329\"," +
- "\"remoteport\":1234," +
- "\"search\":{" +
- "\"totalhits\":1234," +
- "\"hits\":0," +
- "\"coverage\":{\"coverage\":100,\"documents\":100}" +
- "}" +
- "}";
+ "{\"ip\":\"152.200.54.243\"," +
+ "\"peeraddr\":\"152.200.54.243\"," +
+ "\"time\":920880005.023," +
+ "\"duration\":0.122," +
+ "\"responsesize\":9875," +
+ "\"requestsize\":0," +
+ "\"code\":200," +
+ "\"method\":\"GET\"," +
+ "\"uri\":\"?query=test\"," +
+ "\"version\":\"HTTP/1.1\"," +
+ "\"agent\":\"Mozilla/4.05 [en] (Win95; I)\"," +
+ "\"host\":\"localhost\"," +
+ "\"scheme\":null," +
+ "\"localport\":0," +
+ "\"remoteaddr\":\"FE80:0000:0000:0000:0202:B3FF:FE1E:8329\"," +
+ "\"remoteport\":1234," +
+ "\"search\":{" +
+ "\"totalhits\":1234," +
+ "\"hits\":0," +
+ "\"coverage\":{\"coverage\":100,\"documents\":100}" +
+ "}" +
+ "}";
assertJsonEquals(formatEntry(entry), expectedOutput);
}
@Test
- public void test_remote_address_same_as_ip_address() throws Exception {
+ void test_remote_address_same_as_ip_address() throws Exception {
RequestLogEntry entry = newRequestLogEntry("test").build();
RequestLogEntry entrywithremote = newRequestLogEntry("test")
.remoteAddress(entry.peerAddress().get())
@@ -212,7 +214,7 @@ public class JSONLogTestCase {
}
@Test
- public void test_useragent_with_quotes() {
+ void test_useragent_with_quotes() {
RequestLogEntry entry = new RequestLogEntry.Builder()
.rawQuery("query=test")
.rawPath("")
@@ -231,26 +233,26 @@ public class JSONLogTestCase {
.build();
String expectedOutput =
- "{\"ip\":\"152.200.54.243\"," +
- "\"peeraddr\":\"152.200.54.243\"," +
- "\"time\":920880005.023," +
- "\"duration\":0.122," +
- "\"responsesize\":9875," +
- "\"requestsize\":0," +
- "\"code\":200," +
- "\"method\":\"GET\"," +
- "\"uri\":\"?query=test\"," +
- "\"version\":\"HTTP/1.1\"," +
- "\"agent\":\"Mozilla/4.05 [en] (Win95; I; \\\"Best Browser Ever\\\")\"," +
- "\"host\":\"localhost\"," +
- "\"scheme\":null," +
- "\"localport\":0," +
- "\"search\":{" +
- "\"totalhits\":1234," +
- "\"hits\":0," +
- "\"coverage\":{\"coverage\":50,\"documents\":100,\"degraded\":{\"non-ideal-state\":true}}" +
- "}" +
- "}";
+ "{\"ip\":\"152.200.54.243\"," +
+ "\"peeraddr\":\"152.200.54.243\"," +
+ "\"time\":920880005.023," +
+ "\"duration\":0.122," +
+ "\"responsesize\":9875," +
+ "\"requestsize\":0," +
+ "\"code\":200," +
+ "\"method\":\"GET\"," +
+ "\"uri\":\"?query=test\"," +
+ "\"version\":\"HTTP/1.1\"," +
+ "\"agent\":\"Mozilla/4.05 [en] (Win95; I; \\\"Best Browser Ever\\\")\"," +
+ "\"host\":\"localhost\"," +
+ "\"scheme\":null," +
+ "\"localport\":0," +
+ "\"search\":{" +
+ "\"totalhits\":1234," +
+ "\"hits\":0," +
+ "\"coverage\":{\"coverage\":50,\"documents\":100,\"degraded\":{\"non-ideal-state\":true}}" +
+ "}" +
+ "}";
assertJsonEquals(formatEntry(entry), expectedOutput);
}
@@ -280,15 +282,15 @@ public class JSONLogTestCase {
}
@Test
- public void test_with_coverage_degradation() {
+ void test_with_coverage_degradation() {
verifyCoverage("\"coverage\":{\"coverage\":50,\"documents\":100,\"degraded\":{\"non-ideal-state\":true}}",
- newRequestLogEntry("test", new Coverage(100,200,200,0)).build());
+ newRequestLogEntry("test", new Coverage(100, 200, 200, 0)).build());
verifyCoverage("\"coverage\":{\"coverage\":50,\"documents\":100,\"degraded\":{\"match-phase\":true}}",
- newRequestLogEntry("test", new Coverage(100,200,200,1)).build());
+ newRequestLogEntry("test", new Coverage(100, 200, 200, 1)).build());
verifyCoverage("\"coverage\":{\"coverage\":50,\"documents\":100,\"degraded\":{\"timeout\":true}}",
- newRequestLogEntry("test", new Coverage(100,200,200,2)).build());
+ newRequestLogEntry("test", new Coverage(100, 200, 200, 2)).build());
verifyCoverage("\"coverage\":{\"coverage\":50,\"documents\":100,\"degraded\":{\"adaptive-timeout\":true}}",
- newRequestLogEntry("test", new Coverage(100,200,200,4)).build());
+ newRequestLogEntry("test", new Coverage(100, 200, 200, 4)).build());
}
private String formatEntry(RequestLogEntry entry) {
diff --git a/container-core/src/test/java/com/yahoo/container/logging/LogFileHandlerTestCase.java b/container-core/src/test/java/com/yahoo/container/logging/LogFileHandlerTestCase.java
index 2a3877100f5..b5c65733436 100644
--- a/container-core/src/test/java/com/yahoo/container/logging/LogFileHandlerTestCase.java
+++ b/container-core/src/test/java/com/yahoo/container/logging/LogFileHandlerTestCase.java
@@ -4,9 +4,9 @@ package com.yahoo.container.logging;
import com.yahoo.compress.ZstdCompressor;
import com.yahoo.container.logging.LogFileHandler.Compression;
import com.yahoo.io.IOUtils;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+import org.junit.jupiter.api.io.TempDir;
import java.io.File;
import java.io.IOException;
@@ -26,7 +26,7 @@ import java.util.zip.GZIPInputStream;
import static com.yahoo.yolean.Exceptions.uncheck;
import static org.assertj.core.api.Assertions.assertThat;
-import static org.junit.Assert.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
/**
* @author Bob Travis
@@ -35,26 +35,26 @@ import static org.junit.Assert.assertNotEquals;
public class LogFileHandlerTestCase {
private static final int BUFFER_SIZE = 0x10000;
- @Rule
- public TemporaryFolder temporaryFolder = new TemporaryFolder();
+ @TempDir
+ public File temporaryFolder;
@Test
- public void testIt() throws IOException {
- File root = temporaryFolder.newFolder("logfilehandlertest");
+ void testIt() throws IOException {
+ File root = newFolder(temporaryFolder, "logfilehandlertest");
String pattern = root.getAbsolutePath() + "/logfilehandlertest.%Y%m%d%H%M%S";
long[] rTimes = {1000, 2000, 10000};
LogFileHandler<String> h = new LogFileHandler<>(Compression.NONE, BUFFER_SIZE, pattern, rTimes, null, 2048, "thread-name", new StringLogWriter());
long now = System.currentTimeMillis();
- long millisPerDay = 60*60*24*1000;
- long tomorrowDays = (now / millisPerDay) +1;
+ long millisPerDay = 60 * 60 * 24 * 1000;
+ long tomorrowDays = (now / millisPerDay) + 1;
long tomorrowMillis = tomorrowDays * millisPerDay;
- assertThat(tomorrowMillis+1000).isEqualTo(h.logThread.getNextRotationTime(tomorrowMillis));
- assertThat(tomorrowMillis+10000).isEqualTo(h.logThread.getNextRotationTime(tomorrowMillis+3000));
+ assertThat(tomorrowMillis + 1000).isEqualTo(h.logThread.getNextRotationTime(tomorrowMillis));
+ assertThat(tomorrowMillis + 10000).isEqualTo(h.logThread.getNextRotationTime(tomorrowMillis + 3000));
String message = "test";
h.publish(message);
- h.publish( "another test");
+ h.publish("another test");
h.rotateNow();
h.publish(message);
h.flush();
@@ -62,41 +62,42 @@ public class LogFileHandlerTestCase {
}
@Test
- public void testSimpleLogging() throws IOException {
- File logFile = temporaryFolder.newFile("testLogFileG1.txt");
+ void testSimpleLogging() throws IOException {
+ File logFile = File.createTempFile("testLogFileG1.txt", null, temporaryFolder);
- //create logfilehandler
- LogFileHandler<String> h = new LogFileHandler<>(Compression.NONE, BUFFER_SIZE, logFile.getAbsolutePath(), "0 5 ...", null, 2048, "thread-name", new StringLogWriter());
+ //create logfilehandler
+ LogFileHandler<String> h = new LogFileHandler<>(Compression.NONE, BUFFER_SIZE, logFile.getAbsolutePath(), "0 5 ...", null, 2048, "thread-name", new StringLogWriter());
- //write log
- h.publish("testDeleteFileFirst1");
- h.flush();
- h.shutdown();
+ //write log
+ h.publish("testDeleteFileFirst1");
+ h.flush();
+ h.shutdown();
}
@Test
- public void testDeleteFileDuringLogging() throws IOException {
- File logFile = temporaryFolder.newFile("testLogFileG2.txt");
+ void testDeleteFileDuringLogging() throws IOException {
+ File logFile = File.createTempFile("testLogFileG2.txt", null, temporaryFolder);
- //create logfilehandler
- LogFileHandler<String> h = new LogFileHandler<>(Compression.NONE, BUFFER_SIZE, logFile.getAbsolutePath(), "0 5 ...", null, 2048, "thread-name", new StringLogWriter());
+ //create logfilehandler
+ LogFileHandler<String> h = new LogFileHandler<>(Compression.NONE, BUFFER_SIZE, logFile.getAbsolutePath(), "0 5 ...", null, 2048, "thread-name", new StringLogWriter());
- //write log
- h.publish("testDeleteFileDuringLogging1");
- h.flush();
+ //write log
+ h.publish("testDeleteFileDuringLogging1");
+ h.flush();
- //delete log file
+ //delete log file
logFile.delete();
- //write log again
- h.publish("testDeleteFileDuringLogging2");
- h.flush();
- h.shutdown();
+ //write log again
+ h.publish("testDeleteFileDuringLogging2");
+ h.flush();
+ h.shutdown();
}
- @Test(timeout = /*5 minutes*/300_000)
- public void testSymlink() throws IOException, InterruptedException {
- File root = temporaryFolder.newFolder("testlogforsymlinkchecking");
+ @Test
+ @Timeout(300_000)
+ void testSymlink() throws IOException, InterruptedException {
+ File root = newFolder(temporaryFolder, "testlogforsymlinkchecking");
Formatter formatter = new Formatter() {
public String format(LogRecord r) {
DateFormat df = new SimpleDateFormat("yyyy.MM.dd:HH:mm:ss.SSS");
@@ -125,9 +126,10 @@ public class LogFileHandlerTestCase {
handler.shutdown();
}
- @Test(timeout = /*5 minutes*/300_000)
- public void compresses_previous_log_file() throws InterruptedException, IOException {
- File root = temporaryFolder.newFolder("compressespreviouslogfile");
+ @Test
+ @Timeout(300_000)
+ void compresses_previous_log_file() throws InterruptedException, IOException {
+ File root = newFolder(temporaryFolder, "compressespreviouslogfile");
LogFileHandler<String> firstHandler = new LogFileHandler<>(
Compression.ZSTD, BUFFER_SIZE, root.getAbsolutePath() + "/compressespreviouslogfile.%Y%m%d%H%M%S%s", new long[]{0}, "symlink", 2048, "thread-name", new StringLogWriter());
firstHandler.publishAndWait("test");
@@ -135,7 +137,7 @@ public class LogFileHandlerTestCase {
assertThat(Files.size(Paths.get(firstHandler.getFileName()))).isEqualTo(5);
assertThat(root.toPath().resolve("symlink").toRealPath().toString()).isEqualTo(
- Paths.get(firstHandler.getFileName()).toRealPath().toString());
+ Paths.get(firstHandler.getFileName()).toRealPath().toString());
LogFileHandler<String> secondHandler = new LogFileHandler<>(
Compression.ZSTD, BUFFER_SIZE, root.getAbsolutePath() + "/compressespreviouslogfile.%Y%m%d%H%M%S%s", new long[]{0}, "symlink", 2048, "thread-name", new StringLogWriter());
@@ -143,22 +145,24 @@ public class LogFileHandlerTestCase {
secondHandler.rotateNow();
assertThat(root.toPath().resolve("symlink").toRealPath().toString()).isEqualTo(
- Paths.get(secondHandler.getFileName()).toRealPath().toString());
+ Paths.get(secondHandler.getFileName()).toRealPath().toString());
while (Files.exists(root.toPath().resolve(firstHandler.getFileName()))) Thread.sleep(1);
assertThat(Files.exists(Paths.get(firstHandler.getFileName() + ".zst"))).isTrue();
secondHandler.shutdown();
}
- @Test(timeout = /*5 minutes*/300_000)
- public void testcompression_gzip() throws InterruptedException, IOException {
+ @Test
+ @Timeout(300_000)
+ void testcompression_gzip() throws InterruptedException, IOException {
testcompression(
Compression.GZIP, "gz",
(compressedFile, __) -> uncheck(() -> new String(new GZIPInputStream(Files.newInputStream(compressedFile)).readAllBytes())));
}
- @Test(timeout = /*5 minutes*/300_000)
- public void testcompression_zstd() throws InterruptedException, IOException {
+ @Test
+ @Timeout(300_000)
+ void testcompression_zstd() throws InterruptedException, IOException {
testcompression(
Compression.ZSTD, "zst",
(compressedFile, uncompressedSize) -> uncheck(() -> {
@@ -173,7 +177,7 @@ public class LogFileHandlerTestCase {
private void testcompression(Compression compression,
String fileExtension,
BiFunction<Path, Integer, String> decompressor) throws IOException, InterruptedException {
- File root = temporaryFolder.newFolder("testcompression" + compression.name());
+ File root = newFolder(temporaryFolder, "testcompression" + compression.name());
LogFileHandler<String> h = new LogFileHandler<>(
compression, BUFFER_SIZE, root.getAbsolutePath() + "/logfilehandlertest.%Y%m%d%H%M%S%s", new long[]{0}, null, 2048, "thread-name", new StringLogWriter());
@@ -206,5 +210,23 @@ public class LogFileHandlerTestCase {
public void write(String record, OutputStream outputStream) throws IOException {
outputStream.write(record.getBytes(StandardCharsets.UTF_8));
}
+
+ 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;
+ }
+ }
+
+ 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/container-core/src/test/java/com/yahoo/container/logging/test/LogFormatterTestCase.java b/container-core/src/test/java/com/yahoo/container/logging/test/LogFormatterTestCase.java
index 382f17f072f..c3526b42f55 100644
--- a/container-core/src/test/java/com/yahoo/container/logging/test/LogFormatterTestCase.java
+++ b/container-core/src/test/java/com/yahoo/container/logging/test/LogFormatterTestCase.java
@@ -2,11 +2,11 @@
package com.yahoo.container.logging.test;
import com.yahoo.container.logging.LogFormatter;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Date;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Bob Travis
@@ -14,14 +14,14 @@ import static org.junit.Assert.assertEquals;
public class LogFormatterTestCase {
@Test
- public void testIt() {
+ void testIt() {
java.util.TimeZone.setDefault(java.util.TimeZone.getTimeZone("UTC"));
@SuppressWarnings("deprecation")
- long time = new Date(103,7,25,13,30,35).getTime();
- String result = LogFormatter.insertDate("test%Y%m%d%H%M%S%x",time);
- assertEquals("test20030825133035Aug",result);
- result = LogFormatter.insertDate("test%s%T",time);
- assertEquals("test000"+time, result);
+ long time = new Date(103, 7, 25, 13, 30, 35).getTime();
+ String result = LogFormatter.insertDate("test%Y%m%d%H%M%S%x", time);
+ assertEquals("test20030825133035Aug", result);
+ result = LogFormatter.insertDate("test%s%T", time);
+ assertEquals("test000" + time, result);
}
}
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/CookieTestCase.java b/container-core/src/test/java/com/yahoo/jdisc/http/CookieTestCase.java
index cf43a6470bc..3f18d41badd 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/CookieTestCase.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/CookieTestCase.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.jdisc.http;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.concurrent.TimeUnit;
@@ -9,9 +9,7 @@ import java.util.concurrent.TimeUnit;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.equalTo;
-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
@@ -20,19 +18,19 @@ import static org.junit.Assert.assertTrue;
public class CookieTestCase {
@Test
- public void requireThatDefaultValuesAreSane() {
+ void requireThatDefaultValuesAreSane() {
Cookie cookie = new Cookie("foo", "bar");
assertEquals("foo", cookie.getName());
assertEquals("bar", cookie.getValue());
- assertEquals(null, cookie.getDomain());
+ assertNull(cookie.getDomain());
assertEquals(Integer.MIN_VALUE, cookie.getMaxAge(TimeUnit.SECONDS));
- assertEquals(null, cookie.getPath());
+ assertNull(cookie.getPath());
assertEquals(false, cookie.isHttpOnly());
assertEquals(false, cookie.isSecure());
}
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
final Cookie cookie = new Cookie();
cookie.setName("foo");
assertEquals("foo", cookie.getName());
@@ -70,7 +68,7 @@ public class CookieTestCase {
}
@Test
- public void requireThatCopyConstructorWorks() {
+ void requireThatCopyConstructorWorks() {
final Cookie lhs = newSetCookie("foo");
final Cookie rhs = new Cookie(lhs);
assertEquals(rhs.getName(), rhs.getName());
@@ -83,23 +81,23 @@ public class CookieTestCase {
}
@Test
- public void requireThatHashCodeIsImplemented() {
+ void requireThatHashCodeIsImplemented() {
final Cookie cookie = newCookie("foo");
- assertFalse(cookie.hashCode() == new Cookie().hashCode());
+ assertNotNull(new Cookie().hashCode());
assertEquals(cookie.hashCode(), cookie.hashCode());
assertEquals(cookie.hashCode(), new Cookie(cookie).hashCode());
}
@Test
- public void requireThatEqualsIsImplemented() {
+ void requireThatEqualsIsImplemented() {
final Cookie cookie = newCookie("foo");
- assertFalse(cookie.equals(new Cookie()));
+ assertNotEquals(cookie, new Cookie());
assertEquals(cookie, cookie);
assertEquals(cookie, new Cookie(cookie));
}
@Test
- public void requireThatCookieCanBeEncoded() {
+ void requireThatCookieCanBeEncoded() {
assertEncodeCookie(
"foo.name=foo.value",
List.of(newCookie("foo")));
@@ -109,7 +107,7 @@ public class CookieTestCase {
}
@Test
- public void requireThatSetCookieCanBeEncoded() {
+ void requireThatSetCookieCanBeEncoded() {
assertEncodeSetCookie(
List.of("foo.name=foo.value; Path=path; Domain=domain; Secure; HttpOnly",
"foo.name=foo.value; Path=path; Domain=domain; Secure; HttpOnly; SameSite=None"),
@@ -118,7 +116,7 @@ public class CookieTestCase {
}
@Test
- public void requireThatCookieCanBeDecoded() {
+ void requireThatCookieCanBeDecoded() {
final Cookie foo = new Cookie();
foo.setName("foo.name");
foo.setValue("foo.value");
@@ -127,11 +125,11 @@ public class CookieTestCase {
final Cookie bar = new Cookie();
bar.setName("bar.name");
bar.setValue("bar.value");
- assertDecodeCookie(List.of(foo, bar),"foo.name=foo.value; bar.name=bar.value");
+ assertDecodeCookie(List.of(foo, bar), "foo.name=foo.value; bar.name=bar.value");
}
@Test
- public void requireThatSetCookieCanBeDecoded() {
+ void requireThatSetCookieCanBeDecoded() {
final Cookie foo = new Cookie();
foo.setName("foo.name");
foo.setValue("foo.value");
@@ -152,45 +150,45 @@ public class CookieTestCase {
}
@Test
- public void requireThatCookieDecoderWorksForGenericValidCookies() {
+ void requireThatCookieDecoderWorksForGenericValidCookies() {
Cookie.fromCookieHeader("Y=v=1&n=8es5opih9ljtk&l=og0_iedeh0qqvqqr/o&p=m2g2rs6012000000&r=pv&lg=en-US&intl=" +
- "us&np=1; T=z=h.nzPBhSP4PBVd5JqacVnIbNjU1NAY2TjYzNzVOTjYzNzM0Mj&a=YAE&sk=DAALShmNQ" +
- "vhoZV&ks=EAABsibvMK6ejwn0uUoS4rC9w--~E&d=c2wBTVRJeU13RXhPVEUwTURJNU9URTBNRFF6TlRJ" +
- "NU5nLS0BYQFZQUUBZwE1VkNHT0w3VUVDTklJVEdRR1FXT0pOSkhEQQFzY2lkAWNOUnZIbEc3ZHZoVHlWZ" +
- "0NoXzEwYkxhOVdzcy0Bb2sBWlcwLQF0aXABWUhwTmVDAXp6AWgubnpQQkE3RQ--");
+ "us&np=1; T=z=h.nzPBhSP4PBVd5JqacVnIbNjU1NAY2TjYzNzVOTjYzNzM0Mj&a=YAE&sk=DAALShmNQ" +
+ "vhoZV&ks=EAABsibvMK6ejwn0uUoS4rC9w--~E&d=c2wBTVRJeU13RXhPVEUwTURJNU9URTBNRFF6TlRJ" +
+ "NU5nLS0BYQFZQUUBZwE1VkNHT0w3VUVDTklJVEdRR1FXT0pOSkhEQQFzY2lkAWNOUnZIbEc3ZHZoVHlWZ" +
+ "0NoXzEwYkxhOVdzcy0Bb2sBWlcwLQF0aXABWUhwTmVDAXp6AWgubnpQQkE3RQ--");
}
@Test
- public void requireThatCookieDecoderWorksForYInvalidCookies() {
+ void requireThatCookieDecoderWorksForYInvalidCookies() {
Cookie.fromCookieHeader("Y=v=1&n=77nkr5t7o4nqn&l=og0_iedeh0qqvqqr/o&p=m2g2rs6012000000&r=pv&lg=en-US&intl=" +
- "us&np=1; T=z=05nzPB0NP4PBN/n0gwc1AWGNjU1NAY2TjYzNzVOTjYzNzM0Mj&a=QAE&sk=DAA4R2svo" +
- "osjIa&ks=EAAj3nBQFkN4ZmuhqFxJdNoaQ--~E&d=c2wBTVRJeU13RXhPVEUwTURJNU9URTBNRFF6TlRJ" +
- "NU5nLS0BYQFRQUUBZwE1VkNHT0w3VUVDTklJVEdRR1FXT0pOSkhEQQFzY2lkAUpPalRXOEVsUDZrR3RHT" +
- "VZkX29CWk53clJIQS0BdGlwAVlIcE5lQwF6egEwNW56UEJBN0U-");
+ "us&np=1; T=z=05nzPB0NP4PBN/n0gwc1AWGNjU1NAY2TjYzNzVOTjYzNzM0Mj&a=QAE&sk=DAA4R2svo" +
+ "osjIa&ks=EAAj3nBQFkN4ZmuhqFxJdNoaQ--~E&d=c2wBTVRJeU13RXhPVEUwTURJNU9URTBNRFF6TlRJ" +
+ "NU5nLS0BYQFRQUUBZwE1VkNHT0w3VUVDTklJVEdRR1FXT0pOSkhEQQFzY2lkAUpPalRXOEVsUDZrR3RHT" +
+ "VZkX29CWk53clJIQS0BdGlwAVlIcE5lQwF6egEwNW56UEJBN0U-");
}
@Test
- public void requireThatCookieDecoderWorksForYValidCookies() {
+ void requireThatCookieDecoderWorksForYValidCookies() {
Cookie.fromCookieHeader("Y=v=1&n=3767k6te5aj2s&l=1v4u3001uw2ys00q0rw0qrw34q0x5s3u/o&p=030vvit012000000&iz=" +
- "&r=pu&lg=en-US,it-IT,it&intl=it&np=1; T=z=m38yPBmLk3PBWvehTPBhBHYNU5OBjQ3NE5ONU5P" +
- "NDY0NzU0M0&a=IAE&sk=DAAAx5URYgbhQ6&ks=EAA4rTgdlAGeMQmdYeM_VehGg--~E&d=c2wBTWprNUF" +
- "UTXdNems1TWprNE16RXpNREl6TkRneAFhAUlBRQFnAUVJSlNMSzVRM1pWNVNLQVBNRkszQTRaWDZBAXNj" +
- "aWQBSUlyZW5paXp4NS4zTUZMMDVlSVhuMjZKYUcwLQFvawFaVzAtAWFsAW1hcmlvYXByZWFAeW1haWwuY" +
- "29tAXp6AW0zOHlQQkE3RQF0aXABaXRZOFRE");
+ "&r=pu&lg=en-US,it-IT,it&intl=it&np=1; T=z=m38yPBmLk3PBWvehTPBhBHYNU5OBjQ3NE5ONU5P" +
+ "NDY0NzU0M0&a=IAE&sk=DAAAx5URYgbhQ6&ks=EAA4rTgdlAGeMQmdYeM_VehGg--~E&d=c2wBTWprNUF" +
+ "UTXdNems1TWprNE16RXpNREl6TkRneAFhAUlBRQFnAUVJSlNMSzVRM1pWNVNLQVBNRkszQTRaWDZBAXNj" +
+ "aWQBSUlyZW5paXp4NS4zTUZMMDVlSVhuMjZKYUcwLQFvawFaVzAtAWFsAW1hcmlvYXByZWFAeW1haWwuY" +
+ "29tAXp6AW0zOHlQQkE3RQF0aXABaXRZOFRE");
}
@Test
- public void requireThatCookieDecoderWorksForGenericInvalidCookies() {
+ void requireThatCookieDecoderWorksForGenericInvalidCookies() {
Cookie.fromCookieHeader("Y=v=1&n=e92s5cq8qbs6h&l=3kdb0f.3@i126be10b.d4j/o&p=m1f2qgmb13000107&r=g5&lg=en-US" +
- "&intl=us; T=z=TXp3OBTrQ8OBFMcj3GBpFSyNk83TgY2MjMwN04zMDMw&a=YAE&sk=DAAVfaNwLeISrX" +
- "&ks=EAAOeNNgY8c5hV8YzPYmnrW7w--~E&d=c2wBTVRnd09RRXhOVFEzTURrME56UTMBYQFZQUUBZwFMQ" +
- "U5NT0Q2UjY2Q0I1STY0R0tKSUdVQVlRRQFvawFaVzAtAXRpcAFMTlRUdkMBenoBVFhwM09CQTdF&af=QU" +
- "FBQ0FDQURBd0FCMUNCOUFJQUJBQ0FEQU1IME1nTWhNbiZ0cz0xMzIzMjEwMTk1JnBzPVA1d3NYakh0aVk" +
- "2UDMuUGZ6WkdTT2ctLQ--");
+ "&intl=us; T=z=TXp3OBTrQ8OBFMcj3GBpFSyNk83TgY2MjMwN04zMDMw&a=YAE&sk=DAAVfaNwLeISrX" +
+ "&ks=EAAOeNNgY8c5hV8YzPYmnrW7w--~E&d=c2wBTVRnd09RRXhOVFEzTURrME56UTMBYQFZQUUBZwFMQ" +
+ "U5NT0Q2UjY2Q0I1STY0R0tKSUdVQVlRRQFvawFaVzAtAXRpcAFMTlRUdkMBenoBVFhwM09CQTdF&af=QU" +
+ "FBQ0FDQURBd0FCMUNCOUFJQUJBQ0FEQU1IME1nTWhNbiZ0cz0xMzIzMjEwMTk1JnBzPVA1d3NYakh0aVk" +
+ "2UDMuUGZ6WkdTT2ctLQ--");
}
@Test
- public void requireMappingBetweenSameSiteAndJettySameSite() {
+ void requireMappingBetweenSameSiteAndJettySameSite() {
for (var jdiscSameSite : Cookie.SameSite.values()) {
assertEquals(jdiscSameSite, Cookie.SameSite.fromJettySameSite(jdiscSameSite.jettySameSite()));
}
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/HttpHeadersTestCase.java b/container-core/src/test/java/com/yahoo/jdisc/http/HttpHeadersTestCase.java
index 3ab4fb1078c..08f646c069e 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/HttpHeadersTestCase.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/HttpHeadersTestCase.java
@@ -1,9 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.http;
-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 Simon Thoresen Hult
@@ -11,7 +11,7 @@ import static org.junit.Assert.assertEquals;
public class HttpHeadersTestCase {
@Test
- public void requireThatHeadersDoNotChange() {
+ void requireThatHeadersDoNotChange() {
assertEquals("X-JDisc-Disable-Chunking", HttpHeaders.Names.X_DISABLE_CHUNKING);
}
}
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/HttpRequestTestCase.java b/container-core/src/test/java/com/yahoo/jdisc/http/HttpRequestTestCase.java
index 7f9e1e8bd64..30e58f6d2f5 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/HttpRequestTestCase.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/HttpRequestTestCase.java
@@ -4,7 +4,7 @@ package com.yahoo.jdisc.http;
import com.yahoo.jdisc.Container;
import com.yahoo.jdisc.Request;
import com.yahoo.jdisc.service.CurrentContainer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.InetSocketAddress;
import java.net.URI;
@@ -13,10 +13,7 @@ import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
-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.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -27,7 +24,7 @@ import static org.mockito.Mockito.when;
public class HttpRequestTestCase {
@Test
- public void requireThatSimpleServerConstructorsUseReasonableDefaults() {
+ void requireThatSimpleServerConstructorsUseReasonableDefaults() {
URI uri = URI.create("http://localhost/");
HttpRequest request = HttpRequest.newServerRequest(mockContainer(), uri);
assertTrue(request.isServerRequest());
@@ -49,7 +46,7 @@ public class HttpRequestTestCase {
}
@Test
- public void requireThatSimpleClientConstructorsUseReasonableDefaults() {
+ void requireThatSimpleClientConstructorsUseReasonableDefaults() {
Request parent = new Request(mockContainer(), URI.create("http://localhost/"));
URI uri = URI.create("http://remotehost/");
@@ -73,11 +70,11 @@ public class HttpRequestTestCase {
}
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
URI uri = URI.create("http://localhost/path?foo=bar&foo=baz&cox=69");
InetSocketAddress address = new InetSocketAddress("remotehost", 69);
final HttpRequest request = HttpRequest.newServerRequest(mockContainer(), uri, HttpRequest.Method.GET,
- HttpRequest.Version.HTTP_1_1, address, 1L);
+ HttpRequest.Version.HTTP_1_1, address, 1L);
assertEquals(uri, request.getUri());
assertEquals(HttpRequest.Method.GET, request.getMethod());
@@ -110,7 +107,7 @@ public class HttpRequestTestCase {
}
@Test
- public void requireThatHttp10EncodingIsNeverChunked() throws Exception {
+ void requireThatHttp10EncodingIsNeverChunked() throws Exception {
final HttpRequest request = newRequest(HttpRequest.Version.HTTP_1_0);
assertFalse(request.isChunked());
request.headers().add(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED);
@@ -118,20 +115,20 @@ public class HttpRequestTestCase {
}
@Test
- public void requireThatHttp11EncodingIsNotChunkedByDefault() throws Exception {
+ void requireThatHttp11EncodingIsNotChunkedByDefault() throws Exception {
final HttpRequest request = newRequest(HttpRequest.Version.HTTP_1_1);
assertFalse(request.isChunked());
}
@Test
- public void requireThatHttp11EncodingCanBeChunked() throws Exception {
+ void requireThatHttp11EncodingCanBeChunked() throws Exception {
final HttpRequest request = newRequest(HttpRequest.Version.HTTP_1_1);
request.headers().add(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED);
assertTrue(request.isChunked());
}
@Test
- public void requireThatHttp10ConnectionIsAlwaysClose() throws Exception {
+ void requireThatHttp10ConnectionIsAlwaysClose() throws Exception {
final HttpRequest request = newRequest(HttpRequest.Version.HTTP_1_0);
assertFalse(request.isKeepAlive());
request.headers().add(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
@@ -139,39 +136,39 @@ public class HttpRequestTestCase {
}
@Test
- public void requireThatHttp11ConnectionIsKeepAliveByDefault() throws Exception {
+ void requireThatHttp11ConnectionIsKeepAliveByDefault() throws Exception {
final HttpRequest request = newRequest(HttpRequest.Version.HTTP_1_1);
assertTrue(request.isKeepAlive());
}
@Test
- public void requireThatHttp11ConnectionCanBeClose() throws Exception {
+ void requireThatHttp11ConnectionCanBeClose() throws Exception {
final HttpRequest request = newRequest(HttpRequest.Version.HTTP_1_1);
request.headers().add(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
assertFalse(request.isKeepAlive());
}
@Test
- public void requireThatHttp10NeverHasChunkedResponse() throws Exception {
+ void requireThatHttp10NeverHasChunkedResponse() throws Exception {
final HttpRequest request = newRequest(HttpRequest.Version.HTTP_1_0);
assertFalse(request.hasChunkedResponse());
}
@Test
- public void requireThatHttp11HasDefaultChunkedResponse() throws Exception {
+ void requireThatHttp11HasDefaultChunkedResponse() throws Exception {
final HttpRequest request = newRequest(HttpRequest.Version.HTTP_1_1);
assertTrue(request.hasChunkedResponse());
}
@Test
- public void requireThatHttp11CanDisableChunkedResponse() throws Exception {
+ void requireThatHttp11CanDisableChunkedResponse() throws Exception {
final HttpRequest request = newRequest(HttpRequest.Version.HTTP_1_0);
request.headers().add(com.yahoo.jdisc.http.HttpHeaders.Names.X_DISABLE_CHUNKING, "true");
assertFalse(request.hasChunkedResponse());
}
@Test
- public void requireThatCookieHeaderCanBeEncoded() throws Exception {
+ void requireThatCookieHeaderCanBeEncoded() throws Exception {
final HttpRequest request = newRequest(HttpRequest.Version.HTTP_1_0);
final List<Cookie> cookies = Collections.singletonList(new Cookie("foo", "bar"));
request.encodeCookieHeader(cookies);
@@ -181,7 +178,7 @@ public class HttpRequestTestCase {
}
@Test
- public void requireThatCookieHeaderCanBeDecoded() throws Exception {
+ void requireThatCookieHeaderCanBeDecoded() throws Exception {
final HttpRequest request = newRequest(HttpRequest.Version.HTTP_1_0);
final List<Cookie> cookies = Collections.singletonList(new Cookie("foo", "bar"));
request.encodeCookieHeader(cookies);
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/HttpResponseTestCase.java b/container-core/src/test/java/com/yahoo/jdisc/http/HttpResponseTestCase.java
index c4cf1de0e4e..09682e73630 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/HttpResponseTestCase.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/HttpResponseTestCase.java
@@ -5,18 +5,14 @@ import com.yahoo.jdisc.Container;
import com.yahoo.jdisc.Request;
import com.yahoo.jdisc.Response;
import com.yahoo.jdisc.service.CurrentContainer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.util.Arrays;
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.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -27,7 +23,7 @@ import static org.mockito.Mockito.when;
public class HttpResponseTestCase {
@Test
- public void requireThatAccessorsWork() throws Exception {
+ void requireThatAccessorsWork() throws Exception {
final HttpResponse response = newResponse(6, "foo");
assertEquals(6, response.getStatus());
assertEquals("foo", response.getMessage());
@@ -49,7 +45,7 @@ public class HttpResponseTestCase {
}
@Test
- public void requireThatStatusCodesDoNotChange() {
+ void requireThatStatusCodesDoNotChange() {
assertEquals(HttpResponse.Status.CREATED, 201);
assertEquals(HttpResponse.Status.ACCEPTED, 202);
assertEquals(HttpResponse.Status.NON_AUTHORITATIVE_INFORMATION, 203);
@@ -79,14 +75,14 @@ public class HttpResponseTestCase {
}
@Test
- public void requireThat5xxIsServerError() {
+ void requireThat5xxIsServerError() {
for (int i = 0; i < 999; ++i) {
assertEquals(i >= 500 && i < 600, HttpResponse.isServerError(new Response(i)));
}
}
@Test
- public void requireThatCookieHeaderCanBeEncoded() throws Exception {
+ void requireThatCookieHeaderCanBeEncoded() throws Exception {
final HttpResponse response = newResponse(69, "foo");
final List<Cookie> cookies = Collections.singletonList(new Cookie("foo", "bar"));
response.encodeSetCookieHeader(cookies);
@@ -96,18 +92,18 @@ public class HttpResponseTestCase {
}
@Test
- public void requireThatMultipleCookieHeadersCanBeEncoded() throws Exception {
+ void requireThatMultipleCookieHeadersCanBeEncoded() throws Exception {
final HttpResponse response = newResponse(69, "foo");
final List<Cookie> cookies = Arrays.asList(new Cookie("foo", "bar"), new Cookie("baz", "cox"));
response.encodeSetCookieHeader(cookies);
final List<String> headers = response.headers().get(HttpHeaders.Names.SET_COOKIE);
assertEquals(2, headers.size());
assertEquals(Cookie.toSetCookieHeaders(Arrays.asList(new Cookie("foo", "bar"), new Cookie("baz", "cox"))),
- headers);
+ headers);
}
@Test
- public void requireThatCookieHeaderCanBeDecoded() throws Exception {
+ void requireThatCookieHeaderCanBeDecoded() throws Exception {
final HttpResponse response = newResponse(69, "foo");
final List<Cookie> cookies = Collections.singletonList(new Cookie("foo", "bar"));
response.encodeSetCookieHeader(cookies);
@@ -115,7 +111,7 @@ public class HttpResponseTestCase {
}
@Test
- public void requireThatMultipleCookieHeadersCanBeDecoded() throws Exception {
+ void requireThatMultipleCookieHeadersCanBeDecoded() throws Exception {
final HttpResponse response = newResponse(69, "foo");
final List<Cookie> cookies = Arrays.asList(new Cookie("foo", "bar"), new Cookie("baz", "cox"));
response.encodeSetCookieHeader(cookies);
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/filter/DiscFilterRequestTest.java b/container-core/src/test/java/com/yahoo/jdisc/http/filter/DiscFilterRequestTest.java
index 294e19aa2a1..0f5474cbf57 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/filter/DiscFilterRequestTest.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/filter/DiscFilterRequestTest.java
@@ -7,8 +7,7 @@ import com.yahoo.jdisc.http.HttpHeaders;
import com.yahoo.jdisc.http.HttpRequest;
import com.yahoo.jdisc.http.HttpRequest.Version;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.InetSocketAddress;
import java.net.URI;
@@ -18,7 +17,7 @@ import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
public class DiscFilterRequestTest {
@@ -32,323 +31,323 @@ public class DiscFilterRequestTest {
return request;
}
- @Test
- public void testRequestConstruction(){
- URI uri = URI.create("http://localhost:8080/test?param1=abc");
- HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
- httpReq.headers().add(HttpHeaders.Names.CONTENT_TYPE, "text/html;charset=UTF-8");
- httpReq.headers().add("X-Custom-Header", "custom_header");
- List<Cookie> cookies = new ArrayList<>();
- cookies.add(new Cookie("XYZ", "value"));
- cookies.add(new Cookie("ABC", "value"));
- httpReq.encodeCookieHeader(cookies);
- DiscFilterRequest request = new DiscFilterRequest(httpReq);
- Assert.assertEquals(request.getHeader("X-Custom-Header"),"custom_header");
- Assert.assertEquals(request.getHeader(HttpHeaders.Names.CONTENT_TYPE),"text/html;charset=UTF-8");
-
- List<Cookie> c = request.getCookies();
- Assert.assertNotNull(c);
- Assert.assertEquals(c.size(), 2);
-
- Assert.assertEquals(request.getParameter("param1"),"abc");
- Assert.assertNull(request.getParameter("param2"));
- Assert.assertEquals(request.getVersion(),Version.HTTP_1_1);
- Assert.assertEquals(request.getProtocol(),Version.HTTP_1_1.name());
- Assert.assertNull(request.getRequestedSessionId());
- }
-
- @Test
- public void testRequestConstruction2() {
- URI uri = URI.create("http://localhost:8080/test");
- HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
- httpReq.headers().add("some-header", "some-value");
- DiscFilterRequest request = new DiscFilterRequest(httpReq);
-
- request.addHeader("some-header", "some-value");
- String value = request.getUntreatedHeaders().get("some-header").get(0);
- Assert.assertEquals(value,"some-value");
- }
-
- @Test
- public void testRequestAttributes() {
- URI uri = URI.create("http://localhost:8080/test");
- HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
- DiscFilterRequest request = new DiscFilterRequest(httpReq);
- request.setAttribute("some_attr", "some_value");
-
- Assert.assertTrue(request.containsAttribute("some_attr"));
-
- Assert.assertEquals(request.getAttribute("some_attr"),"some_value");
-
- }
-
- @Test
- public void testGetAttributeNames() {
- URI uri = URI.create("http://localhost:8080/test");
- HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
- DiscFilterRequest request = new DiscFilterRequest(httpReq);
- request.setAttribute("some_attr_1", "some_value1");
- request.setAttribute("some_attr_2", "some_value2");
-
- Enumeration<String> e = request.getAttributeNames();
- List<String> attrList = Collections.list(e);
- Assert.assertEquals(2, attrList.size());
- Assert.assertTrue(attrList.contains("some_attr_1"));
- Assert.assertTrue(attrList.contains("some_attr_2"));
-
- }
-
- @Test
- public void testRemoveAttribute() {
- URI uri = URI.create("http://localhost:8080/test");
- HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
- DiscFilterRequest request = new DiscFilterRequest(httpReq);
+ @Test
+ void testRequestConstruction() {
+ URI uri = URI.create("http://localhost:8080/test?param1=abc");
+ HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
+ httpReq.headers().add(HttpHeaders.Names.CONTENT_TYPE, "text/html;charset=UTF-8");
+ httpReq.headers().add("X-Custom-Header", "custom_header");
+ List<Cookie> cookies = new ArrayList<>();
+ cookies.add(new Cookie("XYZ", "value"));
+ cookies.add(new Cookie("ABC", "value"));
+ httpReq.encodeCookieHeader(cookies);
+ DiscFilterRequest request = new DiscFilterRequest(httpReq);
+ assertEquals(request.getHeader("X-Custom-Header"), "custom_header");
+ assertEquals(request.getHeader(HttpHeaders.Names.CONTENT_TYPE), "text/html;charset=UTF-8");
+
+ List<Cookie> c = request.getCookies();
+ assertNotNull(c);
+ assertEquals(c.size(), 2);
+
+ assertEquals(request.getParameter("param1"), "abc");
+ assertNull(request.getParameter("param2"));
+ assertEquals(request.getVersion(), Version.HTTP_1_1);
+ assertEquals(request.getProtocol(), Version.HTTP_1_1.name());
+ assertNull(request.getRequestedSessionId());
+ }
+
+ @Test
+ void testRequestConstruction2() {
+ URI uri = URI.create("http://localhost:8080/test");
+ HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
+ httpReq.headers().add("some-header", "some-value");
+ DiscFilterRequest request = new DiscFilterRequest(httpReq);
+
+ request.addHeader("some-header", "some-value");
+ String value = request.getUntreatedHeaders().get("some-header").get(0);
+ assertEquals(value, "some-value");
+ }
+
+ @Test
+ void testRequestAttributes() {
+ URI uri = URI.create("http://localhost:8080/test");
+ HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
+ DiscFilterRequest request = new DiscFilterRequest(httpReq);
request.setAttribute("some_attr", "some_value");
- Assert.assertTrue(request.containsAttribute("some_attr"));
+ assertTrue(request.containsAttribute("some_attr"));
- request.removeAttribute("some_attr");
+ assertEquals(request.getAttribute("some_attr"), "some_value");
- Assert.assertFalse(request.containsAttribute("some_attr"));
- }
+ }
- @Test
- public void testGetIntHeader() {
- URI uri = URI.create("http://localhost:8080/test");
- HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
- DiscFilterRequest request = new DiscFilterRequest(httpReq);
+ @Test
+ void testGetAttributeNames() {
+ URI uri = URI.create("http://localhost:8080/test");
+ HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
+ DiscFilterRequest request = new DiscFilterRequest(httpReq);
+ request.setAttribute("some_attr_1", "some_value1");
+ request.setAttribute("some_attr_2", "some_value2");
- Assert.assertEquals(-1, request.getIntHeader("int_header"));
+ Enumeration<String> e = request.getAttributeNames();
+ List<String> attrList = Collections.list(e);
+ assertEquals(2, attrList.size());
+ assertTrue(attrList.contains("some_attr_1"));
+ assertTrue(attrList.contains("some_attr_2"));
- request.addHeader("int_header", String.valueOf(5));
+ }
- Assert.assertEquals(5, request.getIntHeader("int_header"));
- }
+ @Test
+ void testRemoveAttribute() {
+ URI uri = URI.create("http://localhost:8080/test");
+ HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
+ DiscFilterRequest request = new DiscFilterRequest(httpReq);
+ request.setAttribute("some_attr", "some_value");
+
+ assertTrue(request.containsAttribute("some_attr"));
+
+ request.removeAttribute("some_attr");
+
+ assertFalse(request.containsAttribute("some_attr"));
+ }
+
+ @Test
+ void testGetIntHeader() {
+ URI uri = URI.create("http://localhost:8080/test");
+ HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
+ DiscFilterRequest request = new DiscFilterRequest(httpReq);
+
+ assertEquals(-1, request.getIntHeader("int_header"));
- @Test
- public void testDateHeader() {
- URI uri = URI.create("http://localhost:8080/test");
- HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
- DiscFilterRequest request = new DiscFilterRequest(httpReq);
+ request.addHeader("int_header", String.valueOf(5));
+ assertEquals(5, request.getIntHeader("int_header"));
+ }
+
+ @Test
+ void testDateHeader() {
+ URI uri = URI.create("http://localhost:8080/test");
+ HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
+ DiscFilterRequest request = new DiscFilterRequest(httpReq);
- Assert.assertEquals(-1, request.getDateHeader(HttpHeaders.Names.IF_MODIFIED_SINCE));
- request.addHeader(HttpHeaders.Names.IF_MODIFIED_SINCE, "Sat, 29 Oct 1994 19:43:31 GMT");
+ assertEquals(-1, request.getDateHeader(HttpHeaders.Names.IF_MODIFIED_SINCE));
- Assert.assertEquals(783459811000L, request.getDateHeader(HttpHeaders.Names.IF_MODIFIED_SINCE));
- }
+ request.addHeader(HttpHeaders.Names.IF_MODIFIED_SINCE, "Sat, 29 Oct 1994 19:43:31 GMT");
- @Test
- public void testParameterAPIsAsList() {
+ assertEquals(783459811000L, request.getDateHeader(HttpHeaders.Names.IF_MODIFIED_SINCE));
+ }
+
+ @Test
+ void testParameterAPIsAsList() {
URI uri = URI.create("http://example.yahoo.com:8080/test?param1=abc&param2=xyz&param2=pqr");
- HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
- DiscFilterRequest request = new DiscFilterRequest(httpReq);
- Assert.assertEquals(request.getParameter("param1"),"abc");
+ HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
+ DiscFilterRequest request = new DiscFilterRequest(httpReq);
+ assertEquals(request.getParameter("param1"), "abc");
List<String> values = request.getParameterValuesAsList("param2");
- Assert.assertEquals(values.get(0),"xyz");
- Assert.assertEquals(values.get(1),"pqr");
+ assertEquals(values.get(0), "xyz");
+ assertEquals(values.get(1), "pqr");
List<String> paramNames = request.getParameterNamesAsList();
- Assert.assertEquals(paramNames.size(), 2);
+ assertEquals(paramNames.size(), 2);
- }
+ }
- @Test
- public void testParameterAPI(){
- URI uri = URI.create("http://example.yahoo.com:8080/test?param1=abc&param2=xyz&param2=pqr");
+ @Test
+ void testParameterAPI() {
+ URI uri = URI.create("http://example.yahoo.com:8080/test?param1=abc&param2=xyz&param2=pqr");
HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
DiscFilterRequest request = new DiscFilterRequest(httpReq);
- Assert.assertEquals(request.getParameter("param1"),"abc");
+ assertEquals(request.getParameter("param1"), "abc");
Enumeration<String> values = request.getParameterValues("param2");
List<String> valuesList = Collections.list(values);
- Assert.assertEquals(valuesList.get(0),"xyz");
- Assert.assertEquals(valuesList.get(1),"pqr");
+ assertEquals(valuesList.get(0), "xyz");
+ assertEquals(valuesList.get(1), "pqr");
Enumeration<String> paramNames = request.getParameterNames();
List<String> paramNamesList = Collections.list(paramNames);
- Assert.assertEquals(paramNamesList.size(), 2);
- }
+ assertEquals(paramNamesList.size(), 2);
+ }
- @Test
- public void testGetHeaderNamesAsList() {
- URI uri = URI.create("http://localhost:8080/test");
+ @Test
+ void testGetHeaderNamesAsList() {
+ URI uri = URI.create("http://localhost:8080/test");
HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
httpReq.headers().add(HttpHeaders.Names.CONTENT_TYPE, "multipart/form-data");
httpReq.headers().add("header_1", "value1");
httpReq.headers().add("header_2", "value2");
DiscFilterRequest request = new DiscFilterRequest(httpReq);
- Assert.assertNotNull(request.getHeaderNamesAsList());
- Assert.assertEquals(request.getHeaderNamesAsList().size(), 3);
- }
+ assertNotNull(request.getHeaderNamesAsList());
+ assertEquals(request.getHeaderNamesAsList().size(), 3);
+ }
- @Test
- public void testGetHeadersAsList() {
+ @Test
+ void testGetHeadersAsList() {
URI uri = URI.create("http://localhost:8080/test");
HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
DiscFilterRequest request = new DiscFilterRequest(httpReq);
- Assert.assertNotNull(request.getHeaderNamesAsList());
- Assert.assertEquals(request.getHeaderNamesAsList().size(), 0);
+ assertNotNull(request.getHeaderNamesAsList());
+ assertEquals(request.getHeaderNamesAsList().size(), 0);
httpReq.headers().add("header_1", "value1");
httpReq.headers().add("header_1", "value2");
- Assert.assertEquals(request.getHeadersAsList("header_1").size(), 2);
+ assertEquals(request.getHeadersAsList("header_1").size(), 2);
}
- @Test
- public void testIsMultipart() {
+ @Test
+ void testIsMultipart() {
- URI uri = URI.create("http://localhost:8080/test");
- HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
- httpReq.headers().add(HttpHeaders.Names.CONTENT_TYPE, "multipart/form-data");
- DiscFilterRequest request = new DiscFilterRequest(httpReq);
+ URI uri = URI.create("http://localhost:8080/test");
+ HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
+ httpReq.headers().add(HttpHeaders.Names.CONTENT_TYPE, "multipart/form-data");
+ DiscFilterRequest request = new DiscFilterRequest(httpReq);
- Assert.assertTrue(DiscFilterRequest.isMultipart(request));
+ assertTrue(DiscFilterRequest.isMultipart(request));
- httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
- httpReq.headers().add(HttpHeaders.Names.CONTENT_TYPE, "text/html;charset=UTF-8");
- request = new DiscFilterRequest(httpReq);
+ httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
+ httpReq.headers().add(HttpHeaders.Names.CONTENT_TYPE, "text/html;charset=UTF-8");
+ request = new DiscFilterRequest(httpReq);
- Assert.assertFalse(DiscFilterRequest.isMultipart(request));
+ assertFalse(DiscFilterRequest.isMultipart(request));
- Assert.assertFalse(DiscFilterRequest.isMultipart(null));
+ assertFalse(DiscFilterRequest.isMultipart(null));
- httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
- request = new DiscFilterRequest(httpReq);
- Assert.assertFalse(DiscFilterRequest.isMultipart(request));
- }
+ httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
+ request = new DiscFilterRequest(httpReq);
+ assertFalse(DiscFilterRequest.isMultipart(request));
+ }
- @Test
- public void testGetRemotePortLocalPort() {
+ @Test
+ void testGetRemotePortLocalPort() {
URI uri = URI.create("http://example.yahoo.com:8080/test");
- HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
- DiscFilterRequest request = new DiscFilterRequest(httpReq);
+ HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
+ DiscFilterRequest request = new DiscFilterRequest(httpReq);
- Assert.assertEquals(69, request.getRemotePort());
- Assert.assertEquals(8080, request.getLocalPort());
+ assertEquals(69, request.getRemotePort());
+ assertEquals(8080, request.getLocalPort());
- if (request.getRemoteHost() != null) // if we have network
- Assert.assertEquals("example.yahoo.com", request.getRemoteHost());
+ if (request.getRemoteHost() != null) // if we have network
+ assertEquals("example.yahoo.com", request.getRemoteHost());
request.setRemoteAddr("1.1.1.1");
- Assert.assertEquals("1.1.1.1",request.getRemoteAddr());
- }
-
- @Test
- public void testCharacterEncoding() {
- URI uri = URI.create("http://example.yahoo.com:8080/test");
- HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
- DiscFilterRequest request = new DiscFilterRequest(httpReq);
- request.setHeaders(HttpHeaders.Names.CONTENT_TYPE, "text/html;charset=UTF-8");
-
- Assert.assertEquals(request.getCharacterEncoding(), "UTF-8");
-
- httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
- request = new DiscFilterRequest(httpReq);
- request.setHeaders(HttpHeaders.Names.CONTENT_TYPE, "text/html");
- request.setCharacterEncoding("UTF-8");
-
- Assert.assertEquals(request.getCharacterEncoding(),"UTF-8");
-
- Assert.assertEquals(request.getHeader(HttpHeaders.Names.CONTENT_TYPE),"text/html;charset=UTF-8");
- }
-
- @Test
- public void testGetServerPort() {
- {
- URI uri = URI.create("http://example.yahoo.com/test");
- HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
- DiscFilterRequest request = new DiscFilterRequest(httpReq);
- Assert.assertEquals(request.getServerPort(), 80);
-
- }
- {
- URI uri = URI.create("https://example.yahoo.com/test");
- HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
- DiscFilterRequest request = new DiscFilterRequest(httpReq);
- Assert.assertEquals(request.getServerPort(), 443);
- }
- }
-
- @Test
- public void testIsSecure() {
- {
- URI uri = URI.create("http://example.yahoo.com/test");
- HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
- DiscFilterRequest request = new DiscFilterRequest(httpReq);
- Assert.assertFalse(request.isSecure());
- }
- {
- URI uri = URI.create("https://example.yahoo.com/test");
- HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
- DiscFilterRequest request = new DiscFilterRequest(httpReq);
- Assert.assertTrue(request.isSecure());
- }
- }
+ assertEquals("1.1.1.1", request.getRemoteAddr());
+ }
+
+ @Test
+ void testCharacterEncoding() {
+ URI uri = URI.create("http://example.yahoo.com:8080/test");
+ HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
+ DiscFilterRequest request = new DiscFilterRequest(httpReq);
+ request.setHeaders(HttpHeaders.Names.CONTENT_TYPE, "text/html;charset=UTF-8");
+
+ assertEquals(request.getCharacterEncoding(), "UTF-8");
+
+ httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
+ request = new DiscFilterRequest(httpReq);
+ request.setHeaders(HttpHeaders.Names.CONTENT_TYPE, "text/html");
+ request.setCharacterEncoding("UTF-8");
+
+ assertEquals(request.getCharacterEncoding(), "UTF-8");
+
+ assertEquals(request.getHeader(HttpHeaders.Names.CONTENT_TYPE), "text/html;charset=UTF-8");
+ }
+
+ @Test
+ void testGetServerPort() {
+ {
+ URI uri = URI.create("http://example.yahoo.com/test");
+ HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
+ DiscFilterRequest request = new DiscFilterRequest(httpReq);
+ assertEquals(request.getServerPort(), 80);
+
+ }
+ {
+ URI uri = URI.create("https://example.yahoo.com/test");
+ HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
+ DiscFilterRequest request = new DiscFilterRequest(httpReq);
+ assertEquals(request.getServerPort(), 443);
+ }
+ }
@Test
- public void requireThatUnresolvableRemoteAddressesAreSupported() {
+ void testIsSecure() {
+ {
+ URI uri = URI.create("http://example.yahoo.com/test");
+ HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
+ DiscFilterRequest request = new DiscFilterRequest(httpReq);
+ assertFalse(request.isSecure());
+ }
+ {
+ URI uri = URI.create("https://example.yahoo.com/test");
+ HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
+ DiscFilterRequest request = new DiscFilterRequest(httpReq);
+ assertTrue(request.isSecure());
+ }
+ }
+
+ @Test
+ void requireThatUnresolvableRemoteAddressesAreSupported() {
URI uri = URI.create("http://doesnotresolve.zzz:8080/test");
HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
DiscFilterRequest request = new DiscFilterRequest(httpReq);
- Assert.assertNull(request.getLocalAddr());
+ assertNull(request.getLocalAddr());
}
@Test
- public void testGetUntreatedHeaders() {
- URI uri = URI.create("http://example.yahoo.com/test");
+ void testGetUntreatedHeaders() {
+ URI uri = URI.create("http://example.yahoo.com/test");
HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
httpReq.headers().add("key1", "value1");
- httpReq.headers().add("key2", Arrays.asList("value1","value2"));
+ httpReq.headers().add("key2", Arrays.asList("value1", "value2"));
DiscFilterRequest request = new DiscFilterRequest(httpReq);
HeaderFields headers = request.getUntreatedHeaders();
- Assert.assertEquals(headers.keySet().size(), 2);
- Assert.assertEquals(headers.get("key1").get(0), "value1" );
- Assert.assertEquals(headers.get("key2").get(0), "value1" );
- Assert.assertEquals(headers.get("key2").get(1), "value2" );
+ assertEquals(headers.keySet().size(), 2);
+ assertEquals(headers.get("key1").get(0), "value1");
+ assertEquals(headers.get("key2").get(0), "value1");
+ assertEquals(headers.get("key2").get(1), "value2");
+ }
+
+ @Test
+ void testClearCookies() {
+ URI uri = URI.create("http://example.yahoo.com/test");
+ HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
+ httpReq.headers().put(HttpHeaders.Names.COOKIE, "XYZ=value");
+ DiscFilterRequest request = new DiscFilterRequest(httpReq);
+ request.clearCookies();
+ assertNull(request.getHeader(HttpHeaders.Names.COOKIE));
+ }
+
+ @Test
+ void testGetWrapedCookies() {
+ URI uri = URI.create("http://example.yahoo.com/test");
+ HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
+ httpReq.headers().put(HttpHeaders.Names.COOKIE, "XYZ=value");
+ DiscFilterRequest request = new DiscFilterRequest(httpReq);
+ JDiscCookieWrapper[] wrappers = request.getWrappedCookies();
+ assertEquals(wrappers.length, 1);
+ assertEquals(wrappers[0].getName(), "XYZ");
+ assertEquals(wrappers[0].getValue(), "value");
}
- @Test
- public void testClearCookies() {
- URI uri = URI.create("http://example.yahoo.com/test");
- HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
- httpReq.headers().put(HttpHeaders.Names.COOKIE, "XYZ=value");
- DiscFilterRequest request = new DiscFilterRequest(httpReq);
- request.clearCookies();
- Assert.assertNull(request.getHeader(HttpHeaders.Names.COOKIE));
- }
-
- @Test
- public void testGetWrapedCookies() {
- URI uri = URI.create("http://example.yahoo.com/test");
- HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
- httpReq.headers().put(HttpHeaders.Names.COOKIE, "XYZ=value");
- DiscFilterRequest request = new DiscFilterRequest(httpReq);
- JDiscCookieWrapper[] wrappers = request.getWrappedCookies();
- Assert.assertEquals(wrappers.length ,1);
- Assert.assertEquals(wrappers[0].getName(), "XYZ");
- Assert.assertEquals(wrappers[0].getValue(), "value");
- }
-
- @Test
- public void testAddCookie() {
- URI uri = URI.create("http://example.yahoo.com/test");
- HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
- DiscFilterRequest request = new DiscFilterRequest(httpReq);
- request.addCookie(JDiscCookieWrapper.wrap(new Cookie("name", "value")));
-
- List<Cookie> cookies = request.getCookies();
- Assert.assertEquals(cookies.size(), 1);
- Assert.assertEquals(cookies.get(0).getName(), "name");
- Assert.assertEquals(cookies.get(0).getValue(), "value");
- }
+ @Test
+ void testAddCookie() {
+ URI uri = URI.create("http://example.yahoo.com/test");
+ HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
+ DiscFilterRequest request = new DiscFilterRequest(httpReq);
+ request.addCookie(JDiscCookieWrapper.wrap(new Cookie("name", "value")));
+
+ List<Cookie> cookies = request.getCookies();
+ assertEquals(cookies.size(), 1);
+ assertEquals(cookies.get(0).getName(), "name");
+ assertEquals(cookies.get(0).getValue(), "value");
+ }
}
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/filter/DiscFilterResponseTest.java b/container-core/src/test/java/com/yahoo/jdisc/http/filter/DiscFilterResponseTest.java
index ace41473eb4..73498e27892 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/filter/DiscFilterResponseTest.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/filter/DiscFilterResponseTest.java
@@ -6,15 +6,14 @@ import com.yahoo.jdisc.http.Cookie;
import com.yahoo.jdisc.http.HttpRequest;
import com.yahoo.jdisc.http.HttpResponse;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.InetSocketAddress;
import java.net.URI;
import java.util.Collections;
import java.util.List;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
public class DiscFilterResponseTest {
@@ -33,40 +32,40 @@ public class DiscFilterResponseTest {
}
@Test
- public void testGetSetStatus() {
+ void testGetSetStatus() {
HttpRequest request = newRequest(URI.create("http://localhost:8080/echo"),
HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
DiscFilterResponse response = new DiscFilterResponse(HttpResponse.newInstance(HttpResponse.Status.OK));
- Assert.assertEquals(response.getStatus(), HttpResponse.Status.OK);
+ assertEquals(response.getStatus(), HttpResponse.Status.OK);
response.setStatus(HttpResponse.Status.REQUEST_TIMEOUT);
- Assert.assertEquals(response.getStatus(), HttpResponse.Status.REQUEST_TIMEOUT);
+ assertEquals(response.getStatus(), HttpResponse.Status.REQUEST_TIMEOUT);
}
@Test
- public void testAttributes() {
+ void testAttributes() {
HttpRequest request = newRequest(URI.create("http://localhost:8080/echo"),
HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
DiscFilterResponse response = new DiscFilterResponse(HttpResponse.newInstance(HttpResponse.Status.OK));
response.setAttribute("attr_1", "value1");
- Assert.assertEquals(response.getAttribute("attr_1"), "value1");
+ assertEquals(response.getAttribute("attr_1"), "value1");
List<String> list = Collections.list(response.getAttributeNames());
- Assert.assertEquals(list.get(0), "attr_1");
+ assertEquals(list.get(0), "attr_1");
response.removeAttribute("attr_1");
- Assert.assertNull(response.getAttribute("attr_1"));
+ assertNull(response.getAttribute("attr_1"));
}
@Test
- public void testAddHeader() {
+ void testAddHeader() {
HttpRequest request = newRequest(URI.create("http://localhost:8080/echo"),
HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
DiscFilterResponse response = new DiscFilterResponse(HttpResponse.newInstance(HttpResponse.Status.OK));
response.addHeader("header1", "value1");
- Assert.assertEquals(response.getHeader("header1"), "value1");
+ assertEquals(response.getHeader("header1"), "value1");
}
@Test
- public void testAddCookie() {
+ void testAddCookie() {
URI uri = URI.create("http://example.com/test");
HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
HttpResponse httpResp = newResponse(httpReq, 200);
@@ -74,31 +73,31 @@ public class DiscFilterResponseTest {
response.addCookie(JDiscCookieWrapper.wrap(new Cookie("name", "value")));
List<Cookie> cookies = response.getCookies();
- Assert.assertEquals(cookies.size(),1);
- Assert.assertEquals(cookies.get(0).getName(),"name");
+ assertEquals(cookies.size(), 1);
+ assertEquals(cookies.get(0).getName(), "name");
}
@Test
- public void testSetCookie() {
+ void testSetCookie() {
URI uri = URI.create("http://example.com/test");
HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
HttpResponse httpResp = newResponse(httpReq, 200);
DiscFilterResponse response = new DiscFilterResponse(httpResp);
response.setCookie("name", "value");
List<Cookie> cookies = response.getCookies();
- Assert.assertEquals(cookies.size(),1);
- Assert.assertEquals(cookies.get(0).getName(),"name");
+ assertEquals(cookies.size(), 1);
+ assertEquals(cookies.get(0).getName(), "name");
}
@Test
- public void testSetHeader() {
+ void testSetHeader() {
URI uri = URI.create("http://example.com/test");
HttpRequest httpReq = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
HttpResponse httpResp = newResponse(httpReq, 200);
DiscFilterResponse response = new DiscFilterResponse(httpResp);
response.setHeader("name", "value");
- Assert.assertEquals(response.getHeader("name"), "value");
+ assertEquals(response.getHeader("name"), "value");
}
}
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/filter/EmptyRequestFilterTestCase.java b/container-core/src/test/java/com/yahoo/jdisc/http/filter/EmptyRequestFilterTestCase.java
index 214ee6b91cc..dc263bb08a6 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/filter/EmptyRequestFilterTestCase.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/filter/EmptyRequestFilterTestCase.java
@@ -6,14 +6,14 @@ import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.http.HttpRequest;
import com.yahoo.jdisc.http.filter.chain.EmptyRequestFilter;
import com.yahoo.jdisc.service.CurrentContainer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.util.concurrent.TimeUnit;
import static com.yahoo.jdisc.http.HttpRequest.Method;
import static com.yahoo.jdisc.http.HttpRequest.Version;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -24,7 +24,7 @@ import static org.mockito.Mockito.when;
public class EmptyRequestFilterTestCase {
@Test
- public void requireThatEmptyFilterDoesNothing() throws Exception {
+ void requireThatEmptyFilterDoesNothing() throws Exception {
final HttpRequest lhs = newRequest(Method.GET, "/status.html", Version.HTTP_1_1);
final HttpRequest rhs = newRequest(Method.GET, "/status.html", Version.HTTP_1_1);
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/filter/EmptyResponseFilterTestCase.java b/container-core/src/test/java/com/yahoo/jdisc/http/filter/EmptyResponseFilterTestCase.java
index 91bc0b1aa4c..53e794cef29 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/filter/EmptyResponseFilterTestCase.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/filter/EmptyResponseFilterTestCase.java
@@ -7,13 +7,13 @@ import com.yahoo.jdisc.http.HttpRequest;
import com.yahoo.jdisc.http.HttpResponse;
import com.yahoo.jdisc.http.filter.chain.EmptyResponseFilter;
import com.yahoo.jdisc.service.CurrentContainer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import static com.yahoo.jdisc.http.HttpRequest.Method;
import static com.yahoo.jdisc.http.HttpRequest.Version;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -24,7 +24,7 @@ import static org.mockito.Mockito.when;
public class EmptyResponseFilterTestCase {
@Test
- public void requireThatEmptyFilterDoesNothing() throws Exception {
+ void requireThatEmptyFilterDoesNothing() throws Exception {
final HttpRequest request = newRequest(Method.GET, "/status.html", Version.HTTP_1_1);
final HttpResponse lhs = HttpResponse.newInstance(Response.Status.OK);
final HttpResponse rhs = HttpResponse.newInstance(Response.Status.OK);
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/filter/JDiscCookieWrapperTest.java b/container-core/src/test/java/com/yahoo/jdisc/http/filter/JDiscCookieWrapperTest.java
index 36217012fb0..41d80d16c54 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/filter/JDiscCookieWrapperTest.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/filter/JDiscCookieWrapperTest.java
@@ -2,15 +2,16 @@
package com.yahoo.jdisc.http.filter;
import com.yahoo.jdisc.http.Cookie;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.TimeUnit;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
public class JDiscCookieWrapperTest {
@Test
- public void requireThatWrapWorks() {
+ void requireThatWrapWorks() {
Cookie cookie = new Cookie("name", "value");
JDiscCookieWrapper wrapper = JDiscCookieWrapper.wrap(cookie);
@@ -18,12 +19,12 @@ public class JDiscCookieWrapperTest {
wrapper.setMaxAge(10);
wrapper.setPath("/path");
- Assert.assertEquals(wrapper.getName(), cookie.getName());
- Assert.assertEquals(wrapper.getValue(), cookie.getValue());
- Assert.assertEquals(wrapper.getDomain(), cookie.getDomain());
- Assert.assertEquals(wrapper.getMaxAge(), cookie.getMaxAge(TimeUnit.SECONDS));
- Assert.assertEquals(wrapper.getPath(), cookie.getPath());
- Assert.assertEquals(wrapper.getSecure(), cookie.isSecure());
+ assertEquals(wrapper.getName(), cookie.getName());
+ assertEquals(wrapper.getValue(), cookie.getValue());
+ assertEquals(wrapper.getDomain(), cookie.getDomain());
+ assertEquals(wrapper.getMaxAge(), cookie.getMaxAge(TimeUnit.SECONDS));
+ assertEquals(wrapper.getPath(), cookie.getPath());
+ assertEquals(wrapper.getSecure(), cookie.isSecure());
}
}
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/filter/RequestViewImplTest.java b/container-core/src/test/java/com/yahoo/jdisc/http/filter/RequestViewImplTest.java
index ab682ea9059..840a5537042 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/filter/RequestViewImplTest.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/filter/RequestViewImplTest.java
@@ -5,9 +5,9 @@ import com.google.common.collect.Lists;
import com.yahoo.jdisc.HeaderFields;
import com.yahoo.jdisc.Request;
import com.yahoo.jdisc.http.filter.SecurityResponseFilterChain.RequestViewImpl;
-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.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -17,7 +17,7 @@ import static org.mockito.Mockito.when;
public class RequestViewImplTest {
@Test
- public void header_from_the_parent_request_is_available() throws Exception {
+ void header_from_the_parent_request_is_available() throws Exception {
final String HEADER = "single-header";
HeaderFields parentHeaders = new HeaderFields();
@@ -32,7 +32,7 @@ public class RequestViewImplTest {
@Test
- public void multi_value_header_from_the_parent_request_is_available() throws Exception {
+ void multi_value_header_from_the_parent_request_is_available() throws Exception {
final String HEADER = "list-header";
HeaderFields parentHeaders = new HeaderFields();
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/filter/SecurityRequestFilterChainTest.java b/container-core/src/test/java/com/yahoo/jdisc/http/filter/SecurityRequestFilterChainTest.java
index 46d6be2e73b..645e523c155 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/filter/SecurityRequestFilterChainTest.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/filter/SecurityRequestFilterChainTest.java
@@ -9,8 +9,7 @@ import com.yahoo.jdisc.handler.ResponseDispatch;
import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.http.HttpRequest;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.InetSocketAddress;
import java.net.URI;
@@ -18,7 +17,7 @@ import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bjorncs
@@ -32,40 +31,40 @@ public class SecurityRequestFilterChainTest {
driver.activateContainer(driver.newContainerBuilder());
HttpRequest request = HttpRequest.newServerRequest(driver, uri, method, version, address);
request.release();
- Assert.assertTrue(driver.close());
+ assertTrue(driver.close());
return request;
}
@Test
- public void testFilterChainConstruction() {
- SecurityRequestFilterChain chain = (SecurityRequestFilterChain)SecurityRequestFilterChain.newInstance();
- assertEquals(chain.getFilters().size(),0);
+ void testFilterChainConstruction() {
+ SecurityRequestFilterChain chain = (SecurityRequestFilterChain) SecurityRequestFilterChain.newInstance();
+ assertEquals(chain.getFilters().size(), 0);
List<SecurityRequestFilter> requestFilters = new ArrayList<SecurityRequestFilter>();
- chain = (SecurityRequestFilterChain)SecurityRequestFilterChain.newInstance();
+ chain = (SecurityRequestFilterChain) SecurityRequestFilterChain.newInstance();
- chain = (SecurityRequestFilterChain)SecurityRequestFilterChain.newInstance(new RequestHeaderFilter("abc", "xyz"),
- new RequestHeaderFilter("pqr", "def"));
+ chain = (SecurityRequestFilterChain) SecurityRequestFilterChain.newInstance(new RequestHeaderFilter("abc", "xyz"),
+ new RequestHeaderFilter("pqr", "def"));
assertEquals(chain instanceof SecurityRequestFilterChain, true);
}
@Test
- public void testFilterChainRun() {
+ void testFilterChainRun() {
RequestFilter chain = SecurityRequestFilterChain.newInstance(new RequestHeaderFilter("abc", "xyz"),
- new RequestHeaderFilter("pqr", "def"));
+ new RequestHeaderFilter("pqr", "def"));
assertEquals(chain instanceof SecurityRequestFilterChain, true);
ResponseHandler handler = newResponseHandler();
HttpRequest request = newRequest(URI.create("http://test/test"), HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
chain.filter(request, handler);
- Assert.assertTrue(request.headers().contains("abc", "xyz"));
- Assert.assertTrue(request.headers().contains("pqr", "def"));
+ assertTrue(request.headers().contains("abc", "xyz"));
+ assertTrue(request.headers().contains("pqr", "def"));
}
@Test
- public void testFilterChainResponds() {
+ void testFilterChainResponds() {
RequestFilter chain = SecurityRequestFilterChain.newInstance(
new MyFilter(),
new RequestHeaderFilter("abc", "xyz"),
@@ -76,9 +75,9 @@ public class SecurityRequestFilterChainTest {
HttpRequest request = newRequest(URI.create("http://test/test"), HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
chain.filter(request, handler);
Response response = getResponse(handler);
- Assert.assertNotNull(response);
- Assert.assertTrue(!request.headers().contains("abc", "xyz"));
- Assert.assertTrue(!request.headers().contains("pqr", "def"));
+ assertNotNull(response);
+ assertFalse(request.headers().contains("abc", "xyz"));
+ assertFalse(request.headers().contains("pqr", "def"));
}
private class RequestHeaderFilter extends AbstractResource implements SecurityRequestFilter {
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/filter/SecurityResponseFilterChainTest.java b/container-core/src/test/java/com/yahoo/jdisc/http/filter/SecurityResponseFilterChainTest.java
index d44fdbfd39b..3f04154e3f8 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/filter/SecurityResponseFilterChainTest.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/filter/SecurityResponseFilterChainTest.java
@@ -6,13 +6,13 @@ import com.yahoo.jdisc.Response;
import com.yahoo.jdisc.http.HttpRequest;
import com.yahoo.jdisc.http.HttpResponse;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.InetSocketAddress;
import java.net.URI;
-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 bjorncs
@@ -29,24 +29,24 @@ public class SecurityResponseFilterChainTest {
}
@Test
- public void testFilterChainConstruction() {
- SecurityResponseFilterChain chain = (SecurityResponseFilterChain)SecurityResponseFilterChain.newInstance();
- assertEquals(chain.getFilters().size(),0);
+ void testFilterChainConstruction() {
+ SecurityResponseFilterChain chain = (SecurityResponseFilterChain) SecurityResponseFilterChain.newInstance();
+ assertEquals(chain.getFilters().size(), 0);
- chain = (SecurityResponseFilterChain)SecurityResponseFilterChain.newInstance(new ResponseHeaderFilter("abc", "xyz"),
- new ResponseHeaderFilter("pqr", "def"));
+ chain = (SecurityResponseFilterChain) SecurityResponseFilterChain.newInstance(new ResponseHeaderFilter("abc", "xyz"),
+ new ResponseHeaderFilter("pqr", "def"));
assertEquals(chain instanceof SecurityResponseFilterChain, true);
}
@Test
- public void testFilterChainRun() {
+ void testFilterChainRun() {
URI uri = URI.create("http://localhost:8080/echo");
HttpRequest request = newRequest(uri, HttpRequest.Method.GET, HttpRequest.Version.HTTP_1_1);
Response response = HttpResponse.newInstance(Response.Status.OK);
ResponseFilter chain = SecurityResponseFilterChain.newInstance(new ResponseHeaderFilter("abc", "xyz"),
- new ResponseHeaderFilter("pqr", "def"));
+ new ResponseHeaderFilter("pqr", "def"));
chain.filter(response, null);
assertTrue(response.headers().contains("abc", "xyz"));
assertTrue(response.headers().contains("pqr", "def"));
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/filter/util/FilterUtilsTest.java b/container-core/src/test/java/com/yahoo/jdisc/http/filter/util/FilterUtilsTest.java
index 16883f1a48e..b53479abdd8 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/filter/util/FilterUtilsTest.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/filter/util/FilterUtilsTest.java
@@ -4,14 +4,14 @@ package com.yahoo.jdisc.http.filter.util;
import com.yahoo.container.jdisc.RequestHandlerTestDriver;
import com.yahoo.jdisc.Response;
import com.yahoo.jdisc.http.Cookie;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static com.yahoo.jdisc.http.filter.util.FilterUtils.sendMessageResponse;
import static com.yahoo.jdisc.http.filter.util.FilterUtils.sendRedirectResponse;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author valerijf
@@ -21,7 +21,7 @@ public class FilterUtilsTest {
private static final List<Cookie> cookies = List.of(new Cookie("my-cookie", "value1"), new Cookie("second-cookie", "value2"));
@Test
- public void redirect_test() {
+ void redirect_test() {
RequestHandlerTestDriver.MockResponseHandler responseHandler = new RequestHandlerTestDriver.MockResponseHandler();
String location = "http://domain.tld/path?query";
@@ -31,7 +31,7 @@ public class FilterUtilsTest {
}
@Test
- public void message_response() {
+ void message_response() {
RequestHandlerTestDriver.MockResponseHandler responseHandler = new RequestHandlerTestDriver.MockResponseHandler();
sendMessageResponse(responseHandler, List.of(), 404, "Not found");
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/AccessLogRequestLogTest.java b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/AccessLogRequestLogTest.java
index 65f871e47ea..766c7918882 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/AccessLogRequestLogTest.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/AccessLogRequestLogTest.java
@@ -7,7 +7,7 @@ import com.yahoo.container.logging.RequestLogEntry;
import com.yahoo.jdisc.http.ServerConfig;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Response;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Optional;
@@ -16,8 +16,8 @@ import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
-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 Oyvind Bakksjo
@@ -25,7 +25,7 @@ import static org.junit.Assert.assertTrue;
*/
public class AccessLogRequestLogTest {
@Test
- public void requireThatQueryWithUnquotedSpecialCharactersIsHandled() {
+ void requireThatQueryWithUnquotedSpecialCharactersIsHandled() {
Request jettyRequest = createRequestBuilder()
.uri("http", "localhost", 12345, "/search/", "query=year:>2010")
.build();
@@ -39,7 +39,7 @@ public class AccessLogRequestLogTest {
}
@Test
- public void requireThatDoubleQuotingIsNotPerformed() {
+ void requireThatDoubleQuotingIsNotPerformed() {
String path = "/search/";
String query = "query=year%252010+%3B&customParameter=something";
Request jettyRequest = createRequestBuilder()
@@ -56,7 +56,7 @@ public class AccessLogRequestLogTest {
}
@Test
- public void raw_path_and_query_are_set_from_request() {
+ void raw_path_and_query_are_set_from_request() {
String rawPath = "//search/";
String rawQuery = "q=%%2";
Request jettyRequest = createRequestBuilder()
@@ -73,7 +73,7 @@ public class AccessLogRequestLogTest {
}
@Test
- public void verify_x_forwarded_for_precedence () {
+ void verify_x_forwarded_for_precedence() {
Request jettyRequest = createRequestBuilder()
.uri("http", "localhost", 12345, "//search/", "q=%%2")
.header("x-forwarded-for", List.of("1.2.3.4"))
@@ -87,7 +87,7 @@ public class AccessLogRequestLogTest {
}
@Test
- public void verify_x_forwarded_port_precedence () {
+ void verify_x_forwarded_port_precedence() {
Request jettyRequest = createRequestBuilder()
.uri("http", "localhost", 12345, "//search/", "q=%%2")
.header("X-Forwarded-Port", List.of("80"))
@@ -101,7 +101,7 @@ public class AccessLogRequestLogTest {
}
@Test
- public void defaults_to_peer_port_if_remote_port_header_is_invalid() {
+ void defaults_to_peer_port_if_remote_port_header_is_invalid() {
Request jettyRequest = createRequestBuilder()
.uri("http", "localhost", 12345, "/search/", null)
.header("X-Forwarded-Port", List.of("8o8o"))
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/ConnectionThrottlerTest.java b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/ConnectionThrottlerTest.java
index add7e458fbd..a65231db2b7 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/ConnectionThrottlerTest.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/ConnectionThrottlerTest.java
@@ -6,11 +6,11 @@ import org.eclipse.jetty.server.AbstractConnector;
import org.eclipse.jetty.util.component.AbstractLifeCycle;
import org.eclipse.jetty.util.statistic.RateStatistic;
import org.eclipse.jetty.util.thread.Scheduler;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.TimeUnit;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@@ -23,14 +23,14 @@ import static org.mockito.internal.verification.VerificationModeFactory.times;
public class ConnectionThrottlerTest {
@Test
- public void throttles_when_any_resource_check_exceeds_configured_threshold() {
+ void throttles_when_any_resource_check_exceeds_configured_threshold() {
Runtime runtime = mock(Runtime.class);
when(runtime.maxMemory()).thenReturn(100l);
RateStatistic rateStatistic = new RateStatistic(1, TimeUnit.HOURS);
MockScheduler scheduler = new MockScheduler();
ConnectorConfig.Throttling config = new ConnectorConfig.Throttling(new ConnectorConfig.Throttling.Builder()
- .maxHeapUtilization(0.8)
- .maxAcceptRate(1));
+ .maxHeapUtilization(0.8)
+ .maxAcceptRate(1));
AbstractConnector connector = mock(AbstractConnector.class);
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/ConnectorFactoryTest.java b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/ConnectorFactoryTest.java
index b47df9d5931..1ff2783cc53 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/ConnectorFactoryTest.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/ConnectorFactoryTest.java
@@ -8,9 +8,9 @@ import com.yahoo.jdisc.http.ssl.impl.ConfiguredSslContextFactoryProvider;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@@ -18,7 +18,7 @@ import java.io.IOException;
import java.util.Map;
import static org.hamcrest.CoreMatchers.equalTo;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Einar M R Rosenvinge
@@ -28,12 +28,12 @@ public class ConnectorFactoryTest {
private Server server;
- @Before
+ @BeforeEach
public void createServer() {
server = new Server();
}
- @After
+ @AfterEach
public void stopServer() {
try {
server.stop();
@@ -44,7 +44,7 @@ public class ConnectorFactoryTest {
}
@Test
- public void requireThatServerCanBindChannel() throws Exception {
+ void requireThatServerCanBindChannel() throws Exception {
ConnectorConfig config = new ConnectorConfig(new ConnectorConfig.Builder());
ConnectorFactory factory = createConnectorFactory(config);
JDiscServerConnector connector = createConnectorFromFactory(factory);
@@ -59,7 +59,7 @@ public class ConnectorFactoryTest {
}
@Test
- public void constructed_connector_is_based_on_jdisc_connector_config() {
+ void constructed_connector_is_based_on_jdisc_connector_config() {
ConnectorConfig config = new ConnectorConfig.Builder()
.idleTimeout(25)
.name("my-server-name")
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/ErrorResponseContentCreatorTest.java b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/ErrorResponseContentCreatorTest.java
index 796adebb5e8..8b18c8cf09d 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/ErrorResponseContentCreatorTest.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/ErrorResponseContentCreatorTest.java
@@ -2,12 +2,12 @@
package com.yahoo.jdisc.http.server.jetty;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
@@ -16,20 +16,20 @@ import static org.junit.Assert.assertEquals;
public class ErrorResponseContentCreatorTest {
@Test
- public void response_content_matches_expected_string() {
+ void response_content_matches_expected_string() {
String expectedHtml =
"<html>\n" +
- "<head>\n" +
- "<meta http-equiv=\"Content-Type\" content=\"text/html;charset=ISO-8859-1\"/>\n" +
- "<title>Error 200</title>\n" +
- "</head>\n" +
- "<body>\n" +
- "<h2>HTTP ERROR: 200</h2>\n" +
- "<p>Problem accessing http://foo.bar. Reason:\n" +
- "<pre> My custom error message</pre></p>\n" +
- "<hr/>\n" +
- "</body>\n" +
- "</html>\n";
+ "<head>\n" +
+ "<meta http-equiv=\"Content-Type\" content=\"text/html;charset=ISO-8859-1\"/>\n" +
+ "<title>Error 200</title>\n" +
+ "</head>\n" +
+ "<body>\n" +
+ "<h2>HTTP ERROR: 200</h2>\n" +
+ "<p>Problem accessing http://foo.bar. Reason:\n" +
+ "<pre> My custom error message</pre></p>\n" +
+ "<hr/>\n" +
+ "</body>\n" +
+ "</html>\n";
ErrorResponseContentCreator c = new ErrorResponseContentCreator();
byte[] rawContent = c.createErrorContent(
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/ExceptionWrapperTest.java b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/ExceptionWrapperTest.java
index 153d3f34899..9512dc22a93 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/ExceptionWrapperTest.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/ExceptionWrapperTest.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.jdisc.http.server.jetty;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
@@ -15,7 +15,7 @@ import static org.hamcrest.MatcherAssert.assertThat;
public class ExceptionWrapperTest {
@Test
- public final void requireNoMessageIsOK() {
+ final void requireNoMessageIsOK() {
final Throwable t = new Throwable();
final ExceptionWrapper e = new ExceptionWrapper(t);
final String expected = "Throwable() at com.yahoo.jdisc.http.server.jetty.ExceptionWrapperTest(ExceptionWrapperTest.java:19)";
@@ -24,7 +24,7 @@ public class ExceptionWrapperTest {
}
@Test
- public final void requireAllWrappedLevelsShowUp() {
+ final void requireAllWrappedLevelsShowUp() {
final Throwable t0 = new Throwable("t0");
final Throwable t1 = new Throwable("t1", t0);
final Throwable t2 = new Throwable("t2", t1);
@@ -37,7 +37,7 @@ public class ExceptionWrapperTest {
}
@Test
- public final void requireMixOfMessageAndNoMessageWorks() {
+ final void requireMixOfMessageAndNoMessageWorks() {
final Throwable t0 = new Throwable("t0");
final Throwable t1 = new Throwable(t0);
final Throwable t2 = new Throwable("t2", t1);
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/FilterTestCase.java b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/FilterTestCase.java
index c975f7c17c3..ce49926c58b 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/FilterTestCase.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/FilterTestCase.java
@@ -29,7 +29,7 @@ import com.yahoo.jdisc.http.filter.chain.RequestFilterChain;
import com.yahoo.jdisc.http.filter.chain.ResponseFilterChain;
import com.yahoo.jdisc.http.server.jetty.testutils.ConnectorFactoryRegistryModule;
import org.assertj.core.api.Assertions;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.io.IOException;
@@ -58,7 +58,7 @@ import static org.mockito.Mockito.when;
*/
public class FilterTestCase {
@Test
- public void requireThatRequestFilterIsNotRunOnUnboundPath() throws Exception {
+ void requireThatRequestFilterIsNotRunOnUnboundPath() throws Exception {
RequestFilterMockBase filter = mock(RequestFilterMockBase.class);
FilterBindings filterBindings = new FilterBindings.Builder()
.addRequestFilter("my-request-filter", filter)
@@ -76,7 +76,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatRequestFilterIsRunOnBoundPath() throws Exception {
+ void requireThatRequestFilterIsRunOnBoundPath() throws Exception {
final RequestFilter filter = mock(RequestFilterMockBase.class);
FilterBindings filterBindings = new FilterBindings.Builder()
.addRequestFilter("my-request-filter", filter)
@@ -94,7 +94,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatRequestFilterChangesAreSeenByRequestHandler() throws Exception {
+ void requireThatRequestFilterChangesAreSeenByRequestHandler() throws Exception {
final RequestFilter filter = new HeaderRequestFilter("foo", "bar");
FilterBindings filterBindings = new FilterBindings.Builder()
.addRequestFilter("my-request-filter", filter)
@@ -112,7 +112,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatRequestFilterCanRespond() throws Exception {
+ void requireThatRequestFilterCanRespond() throws Exception {
FilterBindings filterBindings = new FilterBindings.Builder()
.addRequestFilter("my-request-filter", new RespondForbiddenFilter())
.addRequestFilterBinding("my-request-filter", "http://*/*")
@@ -128,7 +128,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatFilterCanHaveNullCompletionHandler() throws Exception {
+ void requireThatFilterCanHaveNullCompletionHandler() throws Exception {
final int responseStatus = Response.Status.OK;
final String responseMessage = "Excellent";
FilterBindings filterBindings = new FilterBindings.Builder()
@@ -148,7 +148,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatRequestFilterExecutionIsExceptionSafe() throws Exception {
+ void requireThatRequestFilterExecutionIsExceptionSafe() throws Exception {
FilterBindings filterBindings = new FilterBindings.Builder()
.addRequestFilter("my-request-filter", new ThrowingRequestFilter())
.addRequestFilterBinding("my-request-filter", "http://*/*")
@@ -164,7 +164,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatResponseFilterIsNotRunOnUnboundPath() throws Exception {
+ void requireThatResponseFilterIsNotRunOnUnboundPath() throws Exception {
final ResponseFilter filter = mock(ResponseFilterMockBase.class);
FilterBindings filterBindings = new FilterBindings.Builder()
.addResponseFilter("my-response-filter", filter)
@@ -182,7 +182,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatResponseFilterIsRunOnBoundPath() throws Exception {
+ void requireThatResponseFilterIsRunOnBoundPath() throws Exception {
final ResponseFilter filter = mock(ResponseFilterMockBase.class);
FilterBindings filterBindings = new FilterBindings.Builder()
.addResponseFilter("my-response-filter", filter)
@@ -200,7 +200,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatResponseFilterChangesAreWrittenToResponse() throws Exception {
+ void requireThatResponseFilterChangesAreWrittenToResponse() throws Exception {
FilterBindings filterBindings = new FilterBindings.Builder()
.addResponseFilter("my-response-filter", new HeaderResponseFilter("foo", "bar"))
.addResponseFilterBinding("my-response-filter", "http://*/*")
@@ -217,7 +217,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatResponseFilterExecutionIsExceptionSafe() throws Exception {
+ void requireThatResponseFilterExecutionIsExceptionSafe() throws Exception {
FilterBindings filterBindings = new FilterBindings.Builder()
.addResponseFilter("my-response-filter", new ThrowingResponseFilter())
.addResponseFilterBinding("my-response-filter", "http://*/*")
@@ -233,7 +233,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatRequestFilterAndResponseFilterCanBindToSamePath() throws Exception {
+ void requireThatRequestFilterAndResponseFilterCanBindToSamePath() throws Exception {
final RequestFilter requestFilter = mock(RequestFilterMockBase.class);
final ResponseFilter responseFilter = mock(ResponseFilterMockBase.class);
final String uriPattern = "http://*/*";
@@ -256,7 +256,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatResponseFromRequestFilterGoesThroughResponseFilter() throws Exception {
+ void requireThatResponseFromRequestFilterGoesThroughResponseFilter() throws Exception {
FilterBindings filterBindings = new FilterBindings.Builder()
.addRequestFilter("my-request-filter", new RespondForbiddenFilter())
.addRequestFilterBinding("my-request-filter", "http://*/*")
@@ -276,7 +276,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatRequestFilterChainRetainsFilters() {
+ void requireThatRequestFilterChainRetainsFilters() {
final RequestFilter requestFilter1 = mock(RequestFilter.class);
final RequestFilter requestFilter2 = mock(RequestFilter.class);
@@ -296,7 +296,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatRequestFilterChainIsRun() throws Exception {
+ void requireThatRequestFilterChainIsRun() throws Exception {
final RequestFilter requestFilter1 = mock(RequestFilter.class);
final RequestFilter requestFilter2 = mock(RequestFilter.class);
final RequestFilter requestFilterChain = RequestFilterChain.newInstance(requestFilter1, requestFilter2);
@@ -308,7 +308,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatRequestFilterChainCallsFilterWithOriginalRequest() throws Exception {
+ void requireThatRequestFilterChainCallsFilterWithOriginalRequest() throws Exception {
final RequestFilter requestFilter = mock(RequestFilter.class);
final RequestFilter requestFilterChain = RequestFilterChain.newInstance(requestFilter);
final HttpRequest request = mock(HttpRequest.class);
@@ -325,7 +325,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatRequestFilterChainCallsFilterWithOriginalResponseHandler() throws Exception {
+ void requireThatRequestFilterChainCallsFilterWithOriginalResponseHandler() throws Exception {
final RequestFilter requestFilter = mock(RequestFilter.class);
final RequestFilter requestFilterChain = RequestFilterChain.newInstance(requestFilter);
final HttpRequest request = null;
@@ -342,7 +342,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatRequestFilterCanTerminateChain() throws Exception {
+ void requireThatRequestFilterCanTerminateChain() throws Exception {
final RequestFilter requestFilter1 = new RespondForbiddenFilter();
final RequestFilter requestFilter2 = mock(RequestFilter.class);
final RequestFilter requestFilterChain = RequestFilterChain.newInstance(requestFilter1, requestFilter2);
@@ -360,7 +360,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatResponseFilterChainRetainsFilters() {
+ void requireThatResponseFilterChainRetainsFilters() {
final ResponseFilter responseFilter1 = mock(ResponseFilter.class);
final ResponseFilter responseFilter2 = mock(ResponseFilter.class);
@@ -380,7 +380,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatResponseFilterChainIsRun() {
+ void requireThatResponseFilterChainIsRun() {
final ResponseFilter responseFilter1 = new ResponseHeaderFilter("foo", "bar");
final ResponseFilter responseFilter2 = mock(ResponseFilter.class);
final int statusCode = Response.Status.BAD_GATEWAY;
@@ -399,7 +399,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatDefaultRequestFilterChainIsRunIfNoOtherFilterChainMatches() throws IOException, InterruptedException {
+ void requireThatDefaultRequestFilterChainIsRunIfNoOtherFilterChainMatches() throws IOException, InterruptedException {
RequestFilter filterWithBinding = mock(RequestFilter.class);
RequestFilter defaultFilter = mock(RequestFilter.class);
String defaultFilterId = "default-request-filter";
@@ -422,7 +422,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatDefaultResponseFilterChainIsRunIfNoOtherFilterChainMatches() throws IOException, InterruptedException {
+ void requireThatDefaultResponseFilterChainIsRunIfNoOtherFilterChainMatches() throws IOException, InterruptedException {
ResponseFilter filterWithBinding = mock(ResponseFilter.class);
ResponseFilter defaultFilter = mock(ResponseFilter.class);
String defaultFilterId = "default-response-filter";
@@ -445,7 +445,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatRequestFilterWithBindingMatchHasPrecedenceOverDefaultFilter() throws IOException, InterruptedException {
+ void requireThatRequestFilterWithBindingMatchHasPrecedenceOverDefaultFilter() throws IOException, InterruptedException {
RequestFilterMockBase filterWithBinding = mock(RequestFilterMockBase.class);
RequestFilterMockBase defaultFilter = mock(RequestFilterMockBase.class);
String defaultFilterId = "default-request-filter";
@@ -468,7 +468,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatResponseFilterWithBindingMatchHasPrecedenceOverDefaultFilter() throws IOException, InterruptedException {
+ void requireThatResponseFilterWithBindingMatchHasPrecedenceOverDefaultFilter() throws IOException, InterruptedException {
ResponseFilter filterWithBinding = mock(ResponseFilter.class);
ResponseFilter defaultFilter = mock(ResponseFilter.class);
String defaultFilterId = "default-response-filter";
@@ -491,7 +491,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatMetricAreReported() throws IOException, InterruptedException {
+ void requireThatMetricAreReported() throws IOException, InterruptedException {
FilterBindings filterBindings = new FilterBindings.Builder()
.addRequestFilter("my-request-filter", mock(RequestFilter.class))
.addRequestFilterBinding("my-request-filter", "http://*/*")
@@ -514,7 +514,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatStrictFilteringRejectsRequestsNotMatchingFilterChains() throws IOException {
+ void requireThatStrictFilteringRejectsRequestsNotMatchingFilterChains() throws IOException {
RequestFilter filter = mock(RequestFilter.class);
FilterBindings filterBindings = new FilterBindings.Builder()
.addRequestFilter("my-request-filter", filter)
@@ -531,7 +531,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatRequestHandlerSpecIsAvailableThroughDelegate() throws IOException, InterruptedException {
+ void requireThatRequestHandlerSpecIsAvailableThroughDelegate() throws IOException, InterruptedException {
MyRequestHandler requestHandler = new MyHttpRequestHandler();
MyDelegatedHandler delegateHandler1 = new MyDelegatedHandler(requestHandler);
MyDelegatedHandler delegateHandler2 = new MyDelegatedHandler(delegateHandler1);
@@ -539,7 +539,7 @@ public class FilterTestCase {
}
@Test
- public void requireThatRequestHandlerSpecIsAvailable() throws IOException, InterruptedException {
+ void requireThatRequestHandlerSpecIsAvailable() throws IOException, InterruptedException {
MyRequestHandler requestHandler = new MyHttpRequestHandler();
requestHandlerSpecTest(requestHandler);
}
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpRequestFactoryTest.java b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpRequestFactoryTest.java
index d1ba4a4d190..a23a3505bcb 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpRequestFactoryTest.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpRequestFactoryTest.java
@@ -8,7 +8,7 @@ import com.yahoo.jdisc.Response;
import com.yahoo.jdisc.handler.RequestHandler;
import com.yahoo.jdisc.http.HttpRequest;
import com.yahoo.jdisc.service.CurrentContainer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.servlet.http.HttpServletRequest;
import java.net.URI;
@@ -16,9 +16,7 @@ import java.net.URI;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
-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 Steinar Knutsen
@@ -29,7 +27,7 @@ public class HttpRequestFactoryTest {
private static final int LOCAL_PORT = 80;
@Test
- public void testLegalURIs() {
+ void testLegalURIs() {
{
URI uri = HttpRequestFactory.getUri(createMockRequest("https", "host", null, null));
assertEquals("https", uri.getScheme());
@@ -68,7 +66,7 @@ public class HttpRequestFactoryTest {
}
@Test
- public void testIllegalQuery() {
+ void testIllegalQuery() {
try {
HttpRequestFactory.newJDiscRequest(
new MockContainer(),
@@ -80,7 +78,7 @@ public class HttpRequestFactoryTest {
}
@Test
- public final void illegal_host_throws_requestexception1() {
+ final void illegal_host_throws_requestexception1() {
try {
HttpRequestFactory.newJDiscRequest(
new MockContainer(),
@@ -92,7 +90,7 @@ public class HttpRequestFactoryTest {
}
@Test
- public final void illegal_host_throws_requestexception2() {
+ final void illegal_host_throws_requestexception2() {
try {
HttpRequestFactory.newJDiscRequest(
new MockContainer(),
@@ -104,7 +102,7 @@ public class HttpRequestFactoryTest {
}
@Test
- public final void illegal_host_throws_requestexception3() {
+ final void illegal_host_throws_requestexception3() {
try {
HttpRequestFactory.newJDiscRequest(
new MockContainer(),
@@ -116,7 +114,7 @@ public class HttpRequestFactoryTest {
}
@Test
- public final void illegal_unicode_in_query_throws_requestexception() {
+ final void illegal_unicode_in_query_throws_requestexception() {
try {
HttpRequestFactory.newJDiscRequest(
new MockContainer(),
@@ -129,7 +127,7 @@ public class HttpRequestFactoryTest {
}
@Test
- public void request_uri_uses_local_port() {
+ void request_uri_uses_local_port() {
HttpRequest request = HttpRequestFactory.newJDiscRequest(
new MockContainer(),
createMockRequest("https", "example.com", "/search", "query=value"));
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpResponseStatisticsCollectorTest.java b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpResponseStatisticsCollectorTest.java
index 89908e6d56b..1f65bc4f582 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpResponseStatisticsCollectorTest.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpResponseStatisticsCollectorTest.java
@@ -16,8 +16,8 @@ import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.AbstractHandler;
import org.eclipse.jetty.util.Callback;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
@@ -42,7 +42,7 @@ public class HttpResponseStatisticsCollectorTest {
private int httpResponseCode = 500;
@Test
- public void statistics_are_aggregated_by_category() {
+ void statistics_are_aggregated_by_category() {
testRequest("http", 300, "GET");
testRequest("http", 301, "GET");
testRequest("http", 200, "GET");
@@ -54,7 +54,7 @@ public class HttpResponseStatisticsCollectorTest {
}
@Test
- public void statistics_are_grouped_by_http_method_and_scheme() {
+ void statistics_are_grouped_by_http_method_and_scheme() {
testRequest("http", 200, "GET");
testRequest("http", 200, "PUT");
testRequest("http", 200, "POST");
@@ -77,7 +77,7 @@ public class HttpResponseStatisticsCollectorTest {
@Test
@SuppressWarnings("removal")
- public void statistics_include_grouped_and_single_statuscodes() {
+ void statistics_include_grouped_and_single_statuscodes() {
testRequest("http", 401, "GET");
testRequest("http", 404, "GET");
testRequest("http", 403, "GET");
@@ -90,7 +90,7 @@ public class HttpResponseStatisticsCollectorTest {
}
@Test
- public void retrieving_statistics_resets_the_counters() {
+ void retrieving_statistics_resets_the_counters() {
testRequest("http", 200, "GET");
testRequest("http", 200, "GET");
@@ -104,7 +104,7 @@ public class HttpResponseStatisticsCollectorTest {
}
@Test
- public void statistics_include_request_type_dimension() {
+ void statistics_include_request_type_dimension() {
testRequest("http", 200, "GET", "/search");
testRequest("http", 200, "POST", "/search");
testRequest("http", 200, "POST", "/feed");
@@ -123,14 +123,14 @@ public class HttpResponseStatisticsCollectorTest {
}
@Test
- public void request_type_can_be_set_explicitly() {
+ void request_type_can_be_set_explicitly() {
testRequest("http", 200, "GET", "/search", com.yahoo.jdisc.Request.RequestType.WRITE);
var stats = collector.takeStatistics();
assertStatisticsEntry(stats, "http", "GET", MetricDefinitions.RESPONSES_2XX, "write", 200, 1L);
}
- @Before
+ @BeforeEach
public void initializeCollector() throws Exception {
Server server = new Server();
connector = new AbstractConnector(server, null, null, null, 0) {
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpServerConformanceTest.java b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpServerConformanceTest.java
index baf198dde5d..7cce9f2a9ff 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpServerConformanceTest.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpServerConformanceTest.java
@@ -21,9 +21,9 @@ import org.apache.http.util.EntityUtils;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.URI;
@@ -71,7 +71,7 @@ public class HttpServerConformanceTest extends ServerProviderConformanceTest {
* Reduce logging of every stack trace for {@link ServerProviderConformanceTest.ConformanceException} thrown.
* This makes the log more readable and the test faster as well.
*/
- @BeforeClass
+ @BeforeAll
public static void reduceExcessiveLogging() {
httpRequestDispatchLoggerOriginalLevel = httpRequestDispatchLogger.getLevel();
httpRequestDispatchLogger.setLevel(Level.SEVERE);
@@ -79,7 +79,7 @@ public class HttpServerConformanceTest extends ServerProviderConformanceTest {
executorService = Executors.newSingleThreadExecutor();
}
- @AfterClass
+ @AfterAll
public static void restoreExcessiveLogging() throws IOException, InterruptedException {
httpRequestDispatchLogger.setLevel(httpRequestDispatchLoggerOriginalLevel);
httpClient.close();
@@ -87,7 +87,7 @@ public class HttpServerConformanceTest extends ServerProviderConformanceTest {
executorService.awaitTermination(30, TimeUnit.SECONDS);
}
- @AfterClass
+ @AfterAll
public static void reportDiagnostics() {
System.out.println(
"After " + HttpServerConformanceTest.class.getSimpleName()
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpServerTest.java b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpServerTest.java
index 3f84bd3d632..5814ab230bd 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpServerTest.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/HttpServerTest.java
@@ -38,12 +38,13 @@ import org.apache.hc.core5.http.ConnectionClosedException;
import org.apache.hc.core5.http.ContentType;
import org.assertj.core.api.Assertions;
import org.eclipse.jetty.server.handler.AbstractHandlerContainer;
-import org.junit.Ignore;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import javax.net.ssl.SSLContext;
+
+import java.io.File;
import java.io.IOException;
import java.net.BindException;
import java.net.URI;
@@ -88,9 +89,7 @@ import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.startsWith;
import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.mock;
@@ -104,18 +103,18 @@ import static org.mockito.Mockito.when;
*/
public class HttpServerTest {
- @Rule
- public TemporaryFolder tmpFolder = new TemporaryFolder();
+ @TempDir
+ public File tmpFolder;
@Test
- public void requireThatServerCanListenToRandomPort() {
+ void requireThatServerCanListenToRandomPort() {
final JettyTestDriver driver = JettyTestDriver.newInstance(mockRequestHandler());
assertNotEquals(0, driver.server().getListenPort());
assertTrue(driver.close());
}
@Test
- public void requireThatServerCanNotListenToBoundPort() {
+ void requireThatServerCanNotListenToBoundPort() {
final JettyTestDriver driver = JettyTestDriver.newInstance(mockRequestHandler());
try {
JettyTestDriver.newConfiguredInstance(
@@ -131,7 +130,7 @@ public class HttpServerTest {
}
@Test
- public void requireThatBindingSetNotFoundReturns404() throws Exception {
+ void requireThatBindingSetNotFoundReturns404() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newConfiguredInstance(
mockRequestHandler(),
new ServerConfig.Builder()
@@ -139,28 +138,28 @@ public class HttpServerTest {
new ConnectorConfig.Builder(),
newBindingSetSelector("unknown"));
driver.client().get("/status.html")
- .expectStatusCode(is(NOT_FOUND))
- .expectContent(containsPattern(Pattern.compile(
- Pattern.quote(BindingSetNotFoundException.class.getName()) +
- ": No binding set named &apos;unknown&apos;\\.\n\tat .+",
- Pattern.DOTALL | Pattern.MULTILINE)));
+ .expectStatusCode(is(NOT_FOUND))
+ .expectContent(containsPattern(Pattern.compile(
+ Pattern.quote(BindingSetNotFoundException.class.getName()) +
+ ": No binding set named &apos;unknown&apos;\\.\n\tat .+",
+ Pattern.DOTALL | Pattern.MULTILINE)));
assertTrue(driver.close());
}
@Test
- public void requireThatTooLongInitLineReturns414() throws Exception {
+ void requireThatTooLongInitLineReturns414() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newConfiguredInstance(
mockRequestHandler(),
new ServerConfig.Builder(),
new ConnectorConfig.Builder()
.requestHeaderSize(1));
driver.client().get("/status.html")
- .expectStatusCode(is(REQUEST_URI_TOO_LONG));
+ .expectStatusCode(is(REQUEST_URI_TOO_LONG));
assertTrue(driver.close());
}
@Test
- public void requireThatAccessLogIsCalledForRequestRejectedByJetty() throws Exception {
+ void requireThatAccessLogIsCalledForRequestRejectedByJetty() throws Exception {
BlockingQueueRequestLog requestLogMock = new BlockingQueueRequestLog();
final JettyTestDriver driver = JettyTestDriver.newConfiguredInstance(
mockRequestHandler(),
@@ -175,15 +174,15 @@ public class HttpServerTest {
}
@Test
- public void requireThatServerCanEcho() throws Exception {
+ void requireThatServerCanEcho() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newInstance(new EchoRequestHandler());
driver.client().get("/status.html")
- .expectStatusCode(is(OK));
+ .expectStatusCode(is(OK));
assertTrue(driver.close());
}
@Test
- public void requireThatServerCanEchoCompressed() throws Exception {
+ void requireThatServerCanEchoCompressed() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newInstance(new EchoRequestHandler());
SimpleHttpClient client = driver.newClient(true);
client.get("/status.html")
@@ -192,31 +191,31 @@ public class HttpServerTest {
}
@Test
- public void requireThatServerCanHandleMultipleRequests() throws Exception {
+ void requireThatServerCanHandleMultipleRequests() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newInstance(new EchoRequestHandler());
driver.client().get("/status.html")
- .expectStatusCode(is(OK));
+ .expectStatusCode(is(OK));
driver.client().get("/status.html")
- .expectStatusCode(is(OK));
+ .expectStatusCode(is(OK));
assertTrue(driver.close());
}
@Test
- public void requireThatFormPostWorks() throws Exception {
+ void requireThatFormPostWorks() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newInstance(new ParameterPrinterRequestHandler());
final String requestContent = generateContent('a', 30);
final ResponseValidator response =
driver.client().newPost("/status.html")
- .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED)
- .setContent(requestContent)
- .execute();
+ .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED)
+ .setContent(requestContent)
+ .execute();
response.expectStatusCode(is(OK))
.expectContent(startsWith('{' + requestContent + "=[]}"));
assertTrue(driver.close());
}
@Test
- public void requireThatFormPostDoesNotRemoveContentByDefault() throws Exception {
+ void requireThatFormPostDoesNotRemoveContentByDefault() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newInstance(new ParameterPrinterRequestHandler());
final ResponseValidator response =
driver.client().newPost("/status.html")
@@ -229,7 +228,7 @@ public class HttpServerTest {
}
@Test
- public void requireThatFormPostKeepsContentWhenConfiguredTo() throws Exception {
+ void requireThatFormPostKeepsContentWhenConfiguredTo() throws Exception {
final JettyTestDriver driver = newDriverWithFormPostContentRemoved(new ParameterPrinterRequestHandler(), false);
final ResponseValidator response =
driver.client().newPost("/status.html")
@@ -242,7 +241,7 @@ public class HttpServerTest {
}
@Test
- public void requireThatFormPostRemovesContentWhenConfiguredTo() throws Exception {
+ void requireThatFormPostRemovesContentWhenConfiguredTo() throws Exception {
final JettyTestDriver driver = newDriverWithFormPostContentRemoved(new ParameterPrinterRequestHandler(), true);
final ResponseValidator response =
driver.client().newPost("/status.html")
@@ -255,72 +254,72 @@ public class HttpServerTest {
}
@Test
- public void requireThatFormPostWithCharsetSpecifiedWorks() throws Exception {
+ void requireThatFormPostWithCharsetSpecifiedWorks() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newInstance(new ParameterPrinterRequestHandler());
final String requestContent = generateContent('a', 30);
final ResponseValidator response =
driver.client().newPost("/status.html")
- .addHeader(X_DISABLE_CHUNKING, "true")
- .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED + ";charset=UTF-8")
- .setContent(requestContent)
- .execute();
+ .addHeader(X_DISABLE_CHUNKING, "true")
+ .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED + ";charset=UTF-8")
+ .setContent(requestContent)
+ .execute();
response.expectStatusCode(is(OK))
.expectContent(startsWith('{' + requestContent + "=[]}"));
assertTrue(driver.close());
}
@Test
- public void requireThatEmptyFormPostWorks() throws Exception {
+ void requireThatEmptyFormPostWorks() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newInstance(new ParameterPrinterRequestHandler());
final ResponseValidator response =
driver.client().newPost("/status.html")
- .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED)
- .execute();
+ .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED)
+ .execute();
response.expectStatusCode(is(OK))
.expectContent(is("{}"));
assertTrue(driver.close());
}
@Test
- public void requireThatFormParametersAreParsed() throws Exception {
+ void requireThatFormParametersAreParsed() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newInstance(new ParameterPrinterRequestHandler());
final ResponseValidator response =
driver.client().newPost("/status.html")
- .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED)
- .setContent("a=b&c=d")
- .execute();
+ .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED)
+ .setContent("a=b&c=d")
+ .execute();
response.expectStatusCode(is(OK))
.expectContent(startsWith("{a=[b], c=[d]}"));
assertTrue(driver.close());
}
@Test
- public void requireThatUriParametersAreParsed() throws Exception {
+ void requireThatUriParametersAreParsed() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newInstance(new ParameterPrinterRequestHandler());
final ResponseValidator response =
driver.client().newPost("/status.html?a=b&c=d")
- .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED)
- .execute();
+ .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED)
+ .execute();
response.expectStatusCode(is(OK))
.expectContent(is("{a=[b], c=[d]}"));
assertTrue(driver.close());
}
@Test
- public void requireThatFormAndUriParametersAreMerged() throws Exception {
+ void requireThatFormAndUriParametersAreMerged() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newInstance(new ParameterPrinterRequestHandler());
final ResponseValidator response =
driver.client().newPost("/status.html?a=b&c=d1")
- .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED)
- .setContent("c=d2&e=f")
- .execute();
+ .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED)
+ .setContent("c=d2&e=f")
+ .execute();
response.expectStatusCode(is(OK))
.expectContent(startsWith("{a=[b], c=[d1, d2], e=[f]}"));
assertTrue(driver.close());
}
@Test
- public void requireThatFormCharsetIsHonored() throws Exception {
+ void requireThatFormCharsetIsHonored() throws Exception {
final JettyTestDriver driver = newDriverWithFormPostContentRemoved(new ParameterPrinterRequestHandler(), true);
final ResponseValidator response =
driver.client().newPost("/status.html")
@@ -333,7 +332,7 @@ public class HttpServerTest {
}
@Test
- public void requireThatUnknownFormCharsetIsTreatedAsBadRequest() throws Exception {
+ void requireThatUnknownFormCharsetIsTreatedAsBadRequest() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newInstance(new ParameterPrinterRequestHandler());
final ResponseValidator response =
driver.client().newPost("/status.html")
@@ -343,9 +342,9 @@ public class HttpServerTest {
response.expectStatusCode(is(UNSUPPORTED_MEDIA_TYPE));
assertTrue(driver.close());
}
-
+
@Test
- public void requireThatFormPostWithPercentEncodedContentIsDecoded() throws Exception {
+ void requireThatFormPostWithPercentEncodedContentIsDecoded() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newInstance(new ParameterPrinterRequestHandler());
final ResponseValidator response =
driver.client().newPost("/status.html")
@@ -358,7 +357,7 @@ public class HttpServerTest {
}
@Test
- public void requireThatFormPostWithThrowingHandlerIsExceptionSafe() throws Exception {
+ void requireThatFormPostWithThrowingHandlerIsExceptionSafe() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newInstance(new ThrowingHandler());
final ResponseValidator response =
driver.client().newPost("/status.html")
@@ -370,7 +369,7 @@ public class HttpServerTest {
}
@Test
- public void requireThatMultiPostWorks() throws Exception {
+ void requireThatMultiPostWorks() throws Exception {
// This is taken from tcpdump of bug 5433352 and reassembled here to see that httpserver passes things on.
final String startTxtContent = "this is a test for POST.";
final String updaterConfContent
@@ -389,19 +388,19 @@ public class HttpServerTest {
}
@Test
- public void requireThatRequestCookiesAreReceived() throws Exception {
+ void requireThatRequestCookiesAreReceived() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newInstance(new CookiePrinterRequestHandler());
final ResponseValidator response =
driver.client().newPost("/status.html")
- .addHeader(COOKIE, "foo=bar")
- .execute();
+ .addHeader(COOKIE, "foo=bar")
+ .execute();
response.expectStatusCode(is(OK))
.expectContent(containsString("[foo=bar]"));
assertTrue(driver.close());
}
@Test
- public void requireThatSetCookieHeaderIsCorrect() throws Exception {
+ void requireThatSetCookieHeaderIsCorrect() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newInstance(new CookieSetterRequestHandler(
new Cookie("foo", "bar")
.setDomain(".localhost")
@@ -409,18 +408,18 @@ public class HttpServerTest {
.setPath("/foopath")
.setSecure(true)));
driver.client().get("/status.html")
- .expectStatusCode(is(OK))
- .expectHeader("Set-Cookie",
- is("foo=bar; Path=/foopath; Domain=.localhost; Secure; HttpOnly"));
+ .expectStatusCode(is(OK))
+ .expectHeader("Set-Cookie",
+ is("foo=bar; Path=/foopath; Domain=.localhost; Secure; HttpOnly"));
assertTrue(driver.close());
}
@Test
- public void requireThatTimeoutWorks() throws Exception {
+ void requireThatTimeoutWorks() throws Exception {
final UnresponsiveHandler requestHandler = new UnresponsiveHandler();
final JettyTestDriver driver = JettyTestDriver.newInstance(requestHandler);
driver.client().get("/status.html")
- .expectStatusCode(is(GATEWAY_TIMEOUT));
+ .expectStatusCode(is(GATEWAY_TIMEOUT));
ResponseDispatch.newInstance(OK).dispatch(requestHandler.responseHandler);
assertTrue(driver.close());
}
@@ -428,18 +427,18 @@ public class HttpServerTest {
// Header with no value is disallowed by https://tools.ietf.org/html/rfc7230#section-3.2
// Details in https://github.com/eclipse/jetty.project/issues/1116
@Test
- public void requireThatHeaderWithNullValueIsOmitted() throws Exception {
+ void requireThatHeaderWithNullValueIsOmitted() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newInstance(new EchoWithHeaderRequestHandler("X-Foo", null));
driver.client().get("/status.html")
- .expectStatusCode(is(OK))
- .expectNoHeader("X-Foo");
+ .expectStatusCode(is(OK))
+ .expectNoHeader("X-Foo");
assertTrue(driver.close());
}
// Header with empty value is allowed by https://tools.ietf.org/html/rfc7230#section-3.2
// Details in https://github.com/eclipse/jetty.project/issues/1116
@Test
- public void requireThatHeaderWithEmptyValueIsAllowed() throws Exception {
+ void requireThatHeaderWithEmptyValueIsAllowed() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newInstance(new EchoWithHeaderRequestHandler("X-Foo", ""));
driver.client().get("/status.html")
.expectStatusCode(is(OK))
@@ -448,19 +447,19 @@ public class HttpServerTest {
}
@Test
- public void requireThatNoConnectionHeaderMeansKeepAliveInHttp11KeepAliveDisabled() throws Exception {
+ void requireThatNoConnectionHeaderMeansKeepAliveInHttp11KeepAliveDisabled() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newInstance(new EchoWithHeaderRequestHandler(CONNECTION, CLOSE));
driver.client().get("/status.html")
- .expectHeader(CONNECTION, is(CLOSE));
+ .expectHeader(CONNECTION, is(CLOSE));
assertThat(driver.close(), is(true));
}
@Test
- @Ignore("Temporarily ignore until stabilized")
- public void requireThatConnectionIsClosedAfterXRequests() throws Exception {
+ @Disabled("Temporarily ignore until stabilized")
+ void requireThatConnectionIsClosedAfterXRequests() throws Exception {
final int MAX_REQUESTS = 10;
- Path privateKeyFile = tmpFolder.newFile().toPath();
- Path certificateFile = tmpFolder.newFile().toPath();
+ Path privateKeyFile = File.createTempFile("junit", null, tmpFolder).toPath();
+ Path certificateFile = File.createTempFile("junit", null, tmpFolder).toPath();
generatePrivateKeyAndCertificate(privateKeyFile, certificateFile);
ConnectorConfig.Builder connectorConfig = new ConnectorConfig.Builder()
.maxRequestsPerConnection(MAX_REQUESTS)
@@ -490,7 +489,7 @@ public class HttpServerTest {
// HTTP/2
try (CloseableHttpAsyncClient client = createHttp2Client(driver)) {
String uri = "https://localhost:" + driver.server().getListenPort() + "/status.html";
- for (int i = 0; i < 2*MAX_REQUESTS; i++) {
+ for (int i = 0; i < 2 * MAX_REQUESTS; i++) {
try {
client.execute(SimpleRequestBuilder.get(uri).build(), null).get();
} catch (ExecutionException e) {
@@ -508,22 +507,22 @@ public class HttpServerTest {
}
@Test
- public void requireThatServerCanRespondToSslRequest() throws Exception {
- Path privateKeyFile = tmpFolder.newFile().toPath();
- Path certificateFile = tmpFolder.newFile().toPath();
+ void requireThatServerCanRespondToSslRequest() throws Exception {
+ Path privateKeyFile = File.createTempFile("junit", null, tmpFolder).toPath();
+ Path certificateFile = File.createTempFile("junit", null, tmpFolder).toPath();
generatePrivateKeyAndCertificate(privateKeyFile, certificateFile);
final JettyTestDriver driver = JettyTestDriver.newInstanceWithSsl(new EchoRequestHandler(), certificateFile, privateKeyFile, TlsClientAuth.WANT);
driver.client().get("/status.html")
- .expectStatusCode(is(OK));
+ .expectStatusCode(is(OK));
assertTrue(driver.close());
}
@Test
- public void requireThatTlsClientAuthenticationEnforcerRejectsRequestsForNonWhitelistedPaths() throws IOException {
- Path privateKeyFile = tmpFolder.newFile().toPath();
- Path certificateFile = tmpFolder.newFile().toPath();
+ void requireThatTlsClientAuthenticationEnforcerRejectsRequestsForNonWhitelistedPaths() throws IOException {
+ Path privateKeyFile = File.createTempFile("junit", null, tmpFolder).toPath();
+ Path certificateFile = File.createTempFile("junit", null, tmpFolder).toPath();
generatePrivateKeyAndCertificate(privateKeyFile, certificateFile);
JettyTestDriver driver = createSslWithTlsClientAuthenticationEnforcer(certificateFile, privateKeyFile);
@@ -539,9 +538,9 @@ public class HttpServerTest {
}
@Test
- public void requireThatTlsClientAuthenticationEnforcerAllowsRequestForWhitelistedPaths() throws IOException {
- Path privateKeyFile = tmpFolder.newFile().toPath();
- Path certificateFile = tmpFolder.newFile().toPath();
+ void requireThatTlsClientAuthenticationEnforcerAllowsRequestForWhitelistedPaths() throws IOException {
+ Path privateKeyFile = File.createTempFile("junit", null, tmpFolder).toPath();
+ Path certificateFile = File.createTempFile("junit", null, tmpFolder).toPath();
generatePrivateKeyAndCertificate(privateKeyFile, certificateFile);
JettyTestDriver driver = JettyTestDriver.newInstanceWithSsl(new EchoRequestHandler(), certificateFile, privateKeyFile, TlsClientAuth.WANT);
@@ -557,33 +556,33 @@ public class HttpServerTest {
}
@Test
- public void requireThatConnectedAtReturnsNonZero() throws Exception {
+ void requireThatConnectedAtReturnsNonZero() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newInstance(new ConnectedAtRequestHandler());
driver.client().get("/status.html")
- .expectStatusCode(is(OK))
- .expectContent(matchesPattern("\\d{13,}"));
+ .expectStatusCode(is(OK))
+ .expectContent(matchesPattern("\\d{13,}"));
assertThat(driver.close(), is(true));
}
@Test
- public void requireThatGzipEncodingRequestsAreAutomaticallyDecompressed() throws Exception {
+ void requireThatGzipEncodingRequestsAreAutomaticallyDecompressed() throws Exception {
JettyTestDriver driver = JettyTestDriver.newInstance(new ParameterPrinterRequestHandler());
String requestContent = generateContent('a', 30);
ResponseValidator response = driver.client().newPost("/status.html")
- .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED)
- .setGzipContent(requestContent)
- .execute();
+ .addHeader(CONTENT_TYPE, APPLICATION_X_WWW_FORM_URLENCODED)
+ .setGzipContent(requestContent)
+ .execute();
response.expectStatusCode(is(OK))
.expectContent(startsWith('{' + requestContent + "=[]}"));
assertTrue(driver.close());
}
@Test
- public void requireThatResponseStatsAreCollected() throws Exception {
+ void requireThatResponseStatsAreCollected() throws Exception {
RequestTypeHandler handler = new RequestTypeHandler();
JettyTestDriver driver = JettyTestDriver.newInstance(handler);
HttpResponseStatisticsCollector statisticsCollector = ((AbstractHandlerContainer) driver.server().server().getHandler())
- .getChildHandlerByClass(HttpResponseStatisticsCollector.class);
+ .getChildHandlerByClass(HttpResponseStatisticsCollector.class);
{
List<HttpResponseStatisticsCollector.StatisticsEntry> stats = statisticsCollector.takeStatistics();
@@ -614,7 +613,7 @@ public class HttpServerTest {
handler.setRequestType(Request.RequestType.READ);
driver.client().newPost("/status.html").execute();
var entry = waitForStatistics(statisticsCollector);
- assertEquals("Handler overrides request type", "read", entry.dimensions.requestType);
+ assertEquals("read", entry.dimensions.requestType, "Handler overrides request type");
}
assertTrue(driver.close());
@@ -635,25 +634,25 @@ public class HttpServerTest {
}
@Test
- public void requireThatConnectionThrottleDoesNotBlockConnectionsBelowThreshold() throws Exception {
+ void requireThatConnectionThrottleDoesNotBlockConnectionsBelowThreshold() throws Exception {
JettyTestDriver driver = JettyTestDriver.newConfiguredInstance(
new EchoRequestHandler(),
new ServerConfig.Builder(),
new ConnectorConfig.Builder()
.throttling(new Throttling.Builder()
- .enabled(true)
- .maxAcceptRate(10)
- .maxHeapUtilization(1.0)
- .maxConnections(10)));
+ .enabled(true)
+ .maxAcceptRate(10)
+ .maxHeapUtilization(1.0)
+ .maxConnections(10)));
driver.client().get("/status.html")
.expectStatusCode(is(OK));
assertTrue(driver.close());
}
@Test
- public void requireThatConnectionIsTrackedInConnectionLog() throws Exception {
- Path privateKeyFile = tmpFolder.newFile().toPath();
- Path certificateFile = tmpFolder.newFile().toPath();
+ void requireThatConnectionIsTrackedInConnectionLog() throws Exception {
+ Path privateKeyFile = File.createTempFile("junit", null, tmpFolder).toPath();
+ Path certificateFile = File.createTempFile("junit", null, tmpFolder).toPath();
generatePrivateKeyAndCertificate(privateKeyFile, certificateFile);
InMemoryConnectionLog connectionLog = new InMemoryConnectionLog();
Module overrideModule = binder -> binder.bind(ConnectionLog.class).toInstance(connectionLog);
@@ -690,7 +689,7 @@ public class HttpServerTest {
}
@Test
- public void requireThatRequestIsTrackedInAccessLog() throws IOException, InterruptedException {
+ void requireThatRequestIsTrackedInAccessLog() throws IOException, InterruptedException {
BlockingQueueRequestLog requestLogMock = new BlockingQueueRequestLog();
JettyTestDriver driver = JettyTestDriver.newConfiguredInstance(
new EchoRequestHandler(),
@@ -705,9 +704,9 @@ public class HttpServerTest {
}
@Test
- public void requireThatRequestsPerConnectionMetricIsAggregated() throws IOException {
- Path privateKeyFile = tmpFolder.newFile().toPath();
- Path certificateFile = tmpFolder.newFile().toPath();
+ void requireThatRequestsPerConnectionMetricIsAggregated() throws IOException {
+ Path privateKeyFile = File.createTempFile("junit", null, tmpFolder).toPath();
+ Path certificateFile = File.createTempFile("junit", null, tmpFolder).toPath();
generatePrivateKeyAndCertificate(privateKeyFile, certificateFile);
var metricConsumer = new MetricConsumerMock();
InMemoryConnectionLog connectionLog = new InMemoryConnectionLog();
@@ -719,9 +718,9 @@ public class HttpServerTest {
}
@Test
- public void uriWithEmptyPathSegmentIsAllowed() throws Exception {
- Path privateKeyFile = tmpFolder.newFile().toPath();
- Path certificateFile = tmpFolder.newFile().toPath();
+ void uriWithEmptyPathSegmentIsAllowed() throws Exception {
+ Path privateKeyFile = File.createTempFile("junit", null, tmpFolder).toPath();
+ Path certificateFile = File.createTempFile("junit", null, tmpFolder).toPath();
generatePrivateKeyAndCertificate(privateKeyFile, certificateFile);
MetricConsumerMock metricConsumer = new MetricConsumerMock();
InMemoryConnectionLog connectionLog = new InMemoryConnectionLog();
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/JDiscHttpServletTest.java b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/JDiscHttpServletTest.java
index 494f33ca04b..348bfd6183e 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/JDiscHttpServletTest.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/JDiscHttpServletTest.java
@@ -16,7 +16,7 @@ import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.classic.methods.HttpPut;
import org.apache.hc.client5.http.classic.methods.HttpTrace;
import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.URI;
@@ -32,30 +32,30 @@ import static org.hamcrest.MatcherAssert.assertThat;
public class JDiscHttpServletTest {
@Test
- public void requireThatServerRespondsToAllMethods() throws Exception {
+ void requireThatServerRespondsToAllMethods() throws Exception {
final JettyTestDriver driver = JettyTestDriver.newInstance(newEchoHandler());
final URI uri = driver.client().newUri("/status.html");
driver.client().execute(new HttpGet(uri))
- .expectStatusCode(is(OK));
+ .expectStatusCode(is(OK));
driver.client().execute(new HttpPost(uri))
- .expectStatusCode(is(OK));
+ .expectStatusCode(is(OK));
driver.client().execute(new HttpHead(uri))
- .expectStatusCode(is(OK));
+ .expectStatusCode(is(OK));
driver.client().execute(new HttpPut(uri))
- .expectStatusCode(is(OK));
+ .expectStatusCode(is(OK));
driver.client().execute(new HttpDelete(uri))
- .expectStatusCode(is(OK));
+ .expectStatusCode(is(OK));
driver.client().execute(new HttpOptions(uri))
- .expectStatusCode(is(OK));
+ .expectStatusCode(is(OK));
driver.client().execute(new HttpTrace(uri))
- .expectStatusCode(is(OK));
+ .expectStatusCode(is(OK));
driver.client().execute(new HttpPatch(uri))
.expectStatusCode(is(OK));
assertThat(driver.close(), is(true));
}
@Test
- public void requireThatServerResponds405ToUnknownMethods() throws IOException {
+ void requireThatServerResponds405ToUnknownMethods() throws IOException {
JettyTestDriver driver = JettyTestDriver.newInstance(newEchoHandler());
final URI uri = driver.client().newUri("/status.html");
driver.client().execute(new UnknownMethodHttpRequest(uri))
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/SimpleHttpClient.java b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/SimpleHttpClient.java
index c2a6e0326e2..298f0feb9e6 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/SimpleHttpClient.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/SimpleHttpClient.java
@@ -24,7 +24,6 @@ import org.apache.hc.core5.http.io.entity.ByteArrayEntity;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.hamcrest.Matcher;
-import org.hamcrest.MatcherAssert;
import javax.net.ssl.SSLContext;
import java.io.IOException;
@@ -38,7 +37,7 @@ import java.util.List;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* A simple http client for testing
@@ -186,14 +185,14 @@ public class SimpleHttpClient implements AutoCloseable {
}
public ResponseValidator expectStatusCode(Matcher<Integer> matcher) {
- MatcherAssert.assertThat(response.getCode(), matcher);
+ assertThat(response.getCode(), matcher);
return this;
}
public ResponseValidator expectHeader(String headerName, Matcher<String> matcher) {
Header firstHeader = response.getFirstHeader(headerName);
String headerValue = firstHeader != null ? firstHeader.getValue() : null;
- MatcherAssert.assertThat(headerValue, matcher);
+ assertThat(headerValue, matcher);
assertNotNull(firstHeader);
return this;
}
@@ -205,7 +204,7 @@ public class SimpleHttpClient implements AutoCloseable {
}
public ResponseValidator expectContent(final Matcher<String> matcher) {
- MatcherAssert.assertThat(content, matcher);
+ assertThat(content, matcher);
return this;
}
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/SslHandshakeFailedListenerTest.java b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/SslHandshakeFailedListenerTest.java
index cf7e1de4381..3858d6b9e4e 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/SslHandshakeFailedListenerTest.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/server/jetty/SslHandshakeFailedListenerTest.java
@@ -3,7 +3,7 @@ package com.yahoo.jdisc.http.server.jetty;
import com.yahoo.jdisc.Metric;
import org.eclipse.jetty.io.ssl.SslHandshakeListener;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLHandshakeException;
@@ -23,13 +23,13 @@ public class SslHandshakeFailedListenerTest {
SslHandshakeFailedListener listener = new SslHandshakeFailedListener(metrics, "connector", 1234);
@Test
- public void includes_client_ip_dimension_present_when_peer_available() {
+ void includes_client_ip_dimension_present_when_peer_available() {
listener.handshakeFailed(handshakeEvent(true), new SSLHandshakeException("Empty server certificate chain"));
verify(metrics).createContext(eq(Map.of("clientIp", "127.0.0.1", "serverName", "connector", "serverPort", 1234)));
}
@Test
- public void does_not_include_client_ip_dimension_present_when_peer_unavailable() {
+ void does_not_include_client_ip_dimension_present_when_peer_unavailable() {
listener.handshakeFailed(handshakeEvent(false), new SSLHandshakeException("Empty server certificate chain"));
verify(metrics).createContext(eq(Map.of("serverName", "connector", "serverPort", 1234)));
}
diff --git a/container-core/src/test/java/com/yahoo/jdisc/http/ssl/impl/TlsContextBasedProviderTest.java b/container-core/src/test/java/com/yahoo/jdisc/http/ssl/impl/TlsContextBasedProviderTest.java
index e8e358252dc..a192c49aeb9 100644
--- a/container-core/src/test/java/com/yahoo/jdisc/http/ssl/impl/TlsContextBasedProviderTest.java
+++ b/container-core/src/test/java/com/yahoo/jdisc/http/ssl/impl/TlsContextBasedProviderTest.java
@@ -9,7 +9,7 @@ import com.yahoo.security.tls.DefaultTlsContext;
import com.yahoo.security.tls.HostnameVerification;
import com.yahoo.security.tls.PeerAuthentication;
import com.yahoo.security.tls.TlsContext;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.security.auth.x500.X500Principal;
import java.math.BigInteger;
@@ -22,7 +22,7 @@ import java.util.Set;
import static com.yahoo.security.KeyAlgorithm.EC;
import static com.yahoo.security.SignatureAlgorithm.SHA256_WITH_ECDSA;
-import static org.junit.Assert.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
/**
* @author bjorncs
@@ -30,7 +30,7 @@ import static org.junit.Assert.assertArrayEquals;
public class TlsContextBasedProviderTest {
@Test
- public void creates_sslcontextfactory_from_tlscontext() {
+ void creates_sslcontextfactory_from_tlscontext() {
TlsContext tlsContext = createTlsContext();
var provider = new SimpleTlsContextBasedProvider(tlsContext);
DefaultConnectorSsl ssl = new DefaultConnectorSsl();
diff --git a/container-core/src/test/java/com/yahoo/metrics/simple/BucketTest.java b/container-core/src/test/java/com/yahoo/metrics/simple/BucketTest.java
index cc5d110d423..11cc8b86a09 100644
--- a/container-core/src/test/java/com/yahoo/metrics/simple/BucketTest.java
+++ b/container-core/src/test/java/com/yahoo/metrics/simple/BucketTest.java
@@ -1,7 +1,8 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.metrics.simple;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Collection;
import java.util.List;
@@ -12,10 +13,9 @@ import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.Set;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import com.google.common.collect.ImmutableMap;
import com.yahoo.metrics.simple.UntypedMetric.AssumedType;
@@ -28,18 +28,18 @@ import com.yahoo.metrics.simple.UntypedMetric.AssumedType;
public class BucketTest {
private Bucket bucket;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
bucket = new Bucket();
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
bucket = null;
}
@Test
- public final void testEntrySet() {
+ final void testEntrySet() {
assertEquals(0, bucket.entrySet().size());
for (int i = 0; i < 4; ++i) {
bucket.put(new Sample(new Measurement(i), new Identifier("nalle_" + i, null), AssumedType.GAUGE));
@@ -47,7 +47,7 @@ public class BucketTest {
assertEquals(4, bucket.entrySet().size());
for (int i = 0; i < 4; ++i) {
bucket.put(new Sample(new Measurement(i), new Identifier("nalle",
- new Point(new ImmutableMap.Builder<String, Integer>().put("dim", Integer.valueOf(i)).build())),
+ new Point(new ImmutableMap.Builder<String, Integer>().put("dim", Integer.valueOf(i)).build())),
AssumedType.GAUGE));
}
assertEquals(8, bucket.entrySet().size());
@@ -55,23 +55,23 @@ public class BucketTest {
for (Entry<Identifier, UntypedMetric> x : bucket.entrySet()) {
String metricName = x.getKey().getName();
switch (metricName) {
- case "nalle":
- ++nalle;
- break;
- case "nalle_0":
- ++nalle0;
- break;
- case "nalle_1":
- ++nalle1;
- break;
- case "nalle_2":
- ++nalle2;
- break;
- case "nalle_3":
- ++nalle3;
- break;
- default:
- throw new IllegalStateException();
+ case "nalle":
+ ++nalle;
+ break;
+ case "nalle_0":
+ ++nalle0;
+ break;
+ case "nalle_1":
+ ++nalle1;
+ break;
+ case "nalle_2":
+ ++nalle2;
+ break;
+ case "nalle_3":
+ ++nalle3;
+ break;
+ default:
+ throw new IllegalStateException();
}
}
assertEquals(4, nalle);
@@ -82,7 +82,7 @@ public class BucketTest {
}
@Test
- public final void testPutSampleWithUnsupportedType() {
+ final void testPutSampleWithUnsupportedType() {
boolean caughtIt = false;
try {
bucket.put(new Sample(new Measurement(1), new Identifier("nalle", null), AssumedType.NONE));
@@ -93,7 +93,7 @@ public class BucketTest {
}
@Test
- public final void testPutIdentifierUntypedValue() {
+ final void testPutIdentifierUntypedValue() {
UntypedMetric v = new UntypedMetric(null);
v.add(2);
bucket.put(new Sample(new Measurement(3), new Identifier("nalle", null), AssumedType.GAUGE));
@@ -106,10 +106,10 @@ public class BucketTest {
}
@Test
- public final void testHasIdentifier() {
+ final void testHasIdentifier() {
for (int i = 0; i < 4; ++i) {
bucket.put(new Sample(new Measurement(i), new Identifier("nalle_" + i, new Point(
- new ImmutableMap.Builder<String, Integer>().put(String.valueOf(i), Integer.valueOf(i)).build())),
+ new ImmutableMap.Builder<String, Integer>().put(String.valueOf(i), Integer.valueOf(i)).build())),
AssumedType.GAUGE));
}
for (int i = 0; i < 4; ++i) {
@@ -119,7 +119,7 @@ public class BucketTest {
}
@Test
- public final void testOkMerge() {
+ final void testOkMerge() {
bucket.put(new Sample(new Measurement(2), new Identifier("nalle", null), AssumedType.GAUGE));
Bucket otherNew = new Bucket();
otherNew.put(new Sample(new Measurement(3), new Identifier("nalle", null), AssumedType.GAUGE));
@@ -138,7 +138,7 @@ public class BucketTest {
}
@Test
- public final void testMergeDifferentMetrics() {
+ final void testMergeDifferentMetrics() {
bucket.put(new Sample(new Measurement(2), new Identifier("nalle", null), AssumedType.GAUGE));
Bucket otherNew = new Bucket();
otherNew.put(new Sample(new Measurement(3), new Identifier("other", null), AssumedType.GAUGE));
@@ -188,7 +188,7 @@ public class BucketTest {
}
@Test
- public final void testMismatchedMerge() {
+ final void testMismatchedMerge() {
Logger log = Logger.getLogger(Bucket.class.getName());
boolean[] loggingMarker = new boolean[1];
loggingMarker[0] = false;
@@ -205,7 +205,7 @@ public class BucketTest {
}
@Test
- public final void testGetAllMetricNames() {
+ final void testGetAllMetricNames() {
twoMetricsUniqueDimensions();
Collection<String> names = bucket.getAllMetricNames();
assertEquals(2, names.size());
@@ -214,7 +214,7 @@ public class BucketTest {
}
@Test
- public final void testGetValuesForMetric() {
+ final void testGetValuesForMetric() {
twoMetricsUniqueDimensions();
Collection<Entry<Point, UntypedMetric>> values = bucket.getValuesForMetric("nalle");
assertEquals(4, values.size());
@@ -231,7 +231,7 @@ public class BucketTest {
}
@Test
- public final void testGetValuesByMetricName() {
+ final void testGetValuesByMetricName() {
twoMetricsUniqueDimensions();
Map<String, List<Entry<Point, UntypedMetric>>> values = bucket.getValuesByMetricName();
assertEquals(2, values.size());
diff --git a/container-core/src/test/java/com/yahoo/metrics/simple/CounterTest.java b/container-core/src/test/java/com/yahoo/metrics/simple/CounterTest.java
index f579b1584aa..45a76078619 100644
--- a/container-core/src/test/java/com/yahoo/metrics/simple/CounterTest.java
+++ b/container-core/src/test/java/com/yahoo/metrics/simple/CounterTest.java
@@ -1,8 +1,6 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.metrics.simple;
-import static org.junit.Assert.*;
-
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
@@ -10,9 +8,10 @@ import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
/**
* Functional tests for counters.
@@ -23,18 +22,18 @@ public class CounterTest {
MetricReceiver receiver;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
receiver = new MetricReceiver.MockReceiver();
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
receiver = null;
}
@Test
- public final void testAdd() throws InterruptedException {
+ final void testAdd() throws InterruptedException {
final String metricName = "unitTestCounter";
Counter c = receiver.declareCounter(metricName);
c.add();
@@ -48,7 +47,7 @@ public class CounterTest {
}
@Test
- public final void testAddLong() throws InterruptedException {
+ final void testAddLong() throws InterruptedException {
final String metricName = "unitTestCounter";
Counter c = receiver.declareCounter(metricName);
final long twoToThePowerOfFourtyeight = 65536L * 65536L * 65536L;
@@ -63,7 +62,7 @@ public class CounterTest {
}
@Test
- public final void testAddPoint() throws InterruptedException {
+ final void testAddPoint() throws InterruptedException {
final String metricName = "unitTestCounter";
Point p = receiver.pointBuilder().set("x", 2L).set("y", 3.0d).set("z", "5").build();
Counter c = receiver.declareCounter(metricName, p);
@@ -75,10 +74,10 @@ public class CounterTest {
assertEquals(1, x.size());
assertEquals(p, x.get(0).getKey());
assertEquals(1, x.get(0).getValue().getCount());
- }
+ }
@Test
- public final void testAddLongPoint() throws InterruptedException {
+ final void testAddLongPoint() throws InterruptedException {
final String metricName = "unitTestCounter";
Point p = receiver.pointBuilder().set("x", 2L).set("y", 3.0d).set("z", "5").build();
Counter c = receiver.declareCounter(metricName, p);
diff --git a/container-core/src/test/java/com/yahoo/metrics/simple/DimensionsCacheTest.java b/container-core/src/test/java/com/yahoo/metrics/simple/DimensionsCacheTest.java
index b1b1ff28aeb..267ca1d575d 100644
--- a/container-core/src/test/java/com/yahoo/metrics/simple/DimensionsCacheTest.java
+++ b/container-core/src/test/java/com/yahoo/metrics/simple/DimensionsCacheTest.java
@@ -1,17 +1,17 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.metrics.simple;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import com.yahoo.metrics.simple.UntypedMetric.AssumedType;
/**
@@ -24,18 +24,18 @@ public class DimensionsCacheTest {
private static final int POINTS_TO_KEEP = 3;
DimensionCache cache;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
cache = new DimensionCache(POINTS_TO_KEEP);
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
cache = null;
}
@Test
- public final void smokeTest() {
+ final void smokeTest() {
String metricName = "testMetric";
Bucket first = new Bucket();
for (int i = 0; i < 4; ++i) {
@@ -53,11 +53,11 @@ public class DimensionsCacheTest {
newestFound = true;
}
}
- assertTrue("Kept newest measurement when padding points.", newestFound);
+ assertTrue(newestFound, "Kept newest measurement when padding points.");
}
@Test
- public final void testNoBoomWithEmptyBuckets() {
+ final void testNoBoomWithEmptyBuckets() {
Bucket check = new Bucket();
cache.updateDimensionPersistence(null, new Bucket());
cache.updateDimensionPersistence(null, new Bucket());
@@ -66,7 +66,7 @@ public class DimensionsCacheTest {
}
@Test
- public final void testUpdateWithNullThenDataThenData() {
+ final void testUpdateWithNullThenDataThenData() {
Bucket first = new Bucket();
populateDimensionLessValue("one", first, 2);
cache.updateDimensionPersistence(null, first);
@@ -80,7 +80,7 @@ public class DimensionsCacheTest {
}
@Test
- public final void requireThatOldDataIsForgotten() {
+ final void requireThatOldDataIsForgotten() {
Bucket first = new Bucket(); // "now" as timestamp
populateDimensionLessValue("one", first, 2);
cache.updateDimensionPersistence(first, new Bucket());
@@ -96,7 +96,7 @@ public class DimensionsCacheTest {
}
@Test
- public final void testUpdateWithNullThenDataThenNoDataThenData() {
+ final void testUpdateWithNullThenDataThenNoDataThenData() {
Bucket first = new Bucket();
Bucket second = new Bucket();
populateDimensionLessValue("first", first, 1.0d);
diff --git a/container-core/src/test/java/com/yahoo/metrics/simple/GaugeTest.java b/container-core/src/test/java/com/yahoo/metrics/simple/GaugeTest.java
index 0d4d6360f20..8147f9a53cc 100644
--- a/container-core/src/test/java/com/yahoo/metrics/simple/GaugeTest.java
+++ b/container-core/src/test/java/com/yahoo/metrics/simple/GaugeTest.java
@@ -1,8 +1,6 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.metrics.simple;
-import static org.junit.Assert.*;
-
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
@@ -10,10 +8,10 @@ import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import com.yahoo.metrics.ManagerConfig;
/**
@@ -25,18 +23,18 @@ public class GaugeTest {
MetricReceiver receiver;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
receiver = new MetricReceiver.MockReceiver();
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
receiver = null;
}
@Test
- public final void testSampleDouble() throws InterruptedException {
+ final void testSampleDouble() throws InterruptedException {
final String metricName = "unitTestGauge";
Gauge g = receiver.declareGauge(metricName);
g.sample(1.0d);
@@ -51,7 +49,7 @@ public class GaugeTest {
}
@Test
- public final void testSampleDoublePoint() throws InterruptedException {
+ final void testSampleDoublePoint() throws InterruptedException {
final String metricName = "unitTestGauge";
Point p = receiver.pointBuilder().set("x", 2L).set("y", 3.0d).set("z", "5").build();
Gauge g = receiver.declareGauge(metricName, p);
diff --git a/container-core/src/test/java/com/yahoo/metrics/simple/MetricsTest.java b/container-core/src/test/java/com/yahoo/metrics/simple/MetricsTest.java
index c8a5f17fdfb..f64998f0be4 100644
--- a/container-core/src/test/java/com/yahoo/metrics/simple/MetricsTest.java
+++ b/container-core/src/test/java/com/yahoo/metrics/simple/MetricsTest.java
@@ -1,17 +1,16 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.metrics.simple;
-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;
import java.util.Collection;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import com.yahoo.metrics.simple.jdisc.JdiscMetricsFactory;
import com.yahoo.metrics.simple.jdisc.SimpleMetricConsumer;
@@ -23,19 +22,19 @@ import com.yahoo.metrics.simple.jdisc.SimpleMetricConsumer;
public class MetricsTest extends UnitTestSetup {
SimpleMetricConsumer metricApi;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
super.init();
metricApi = (SimpleMetricConsumer) new JdiscMetricsFactory(metricManager.get()).newInstance();
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
super.fini();
}
@Test
- public final void smokeTest() throws InterruptedException {
+ final void smokeTest() throws InterruptedException {
final String metricName = "testMetric";
metricApi.set(metricName, Double.valueOf(1.0d), null);
updater.gotData.await(10, TimeUnit.SECONDS);
@@ -49,7 +48,7 @@ public class MetricsTest extends UnitTestSetup {
}
@Test
- public final void testRedefinition() {
+ final void testRedefinition() {
MetricReceiver r = metricManager.get();
final String metricName = "gah";
r.addMetricDefinition(metricName, new MetricSettings.Builder().build());
diff --git a/container-core/src/test/java/com/yahoo/metrics/simple/PointTest.java b/container-core/src/test/java/com/yahoo/metrics/simple/PointTest.java
index ca680c805ef..e6cb70db07a 100644
--- a/container-core/src/test/java/com/yahoo/metrics/simple/PointTest.java
+++ b/container-core/src/test/java/com/yahoo/metrics/simple/PointTest.java
@@ -1,20 +1,20 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.metrics.simple;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.HashMap;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bratseth
*/
public class PointTest {
-
+
@Test
- public void testPointEquality() {
+ void testPointEquality() {
Point a = new Point(Collections.emptyMap());
Point b = new Point(new HashMap<>(0));
assertEquals(a.hashCode(), b.hashCode());
diff --git a/container-core/src/test/java/com/yahoo/metrics/simple/jdisc/SnapshotConverterTest.java b/container-core/src/test/java/com/yahoo/metrics/simple/jdisc/SnapshotConverterTest.java
index 4d4229e8369..7981e5904f3 100644
--- a/container-core/src/test/java/com/yahoo/metrics/simple/jdisc/SnapshotConverterTest.java
+++ b/container-core/src/test/java/com/yahoo/metrics/simple/jdisc/SnapshotConverterTest.java
@@ -12,14 +12,14 @@ import com.yahoo.metrics.simple.Identifier;
import com.yahoo.metrics.simple.MetricReceiver;
import com.yahoo.metrics.simple.Point;
import com.yahoo.metrics.simple.UntypedMetric;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
-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 bratseth
@@ -27,10 +27,10 @@ import static org.junit.Assert.assertTrue;
public class SnapshotConverterTest {
@Test
- public void testPointConversion() {
+ void testPointConversion() {
MetricDimensions a = SnapshotConverter.convert(new Point(Collections.emptyMap()));
MetricDimensions b = SnapshotConverter.convert(new Point(new HashMap<>(0)));
- MetricDimensions c = SnapshotConverter.convert((Point)null);
+ MetricDimensions c = SnapshotConverter.convert((Point) null);
assertEquals(a.hashCode(), b.hashCode());
assertEquals(a, b);
assertEquals(a.hashCode(), c.hashCode());
@@ -40,11 +40,11 @@ public class SnapshotConverterTest {
}
@Test
- public void testConversion() {
+ void testConversion() {
MetricReceiver mock = new MetricReceiver.MockReceiver();
mock.declareCounter("foo").add(1);
mock.declareGauge("quuux").sample(42.25);
- mock.declareCounter("bar", new Point(new HashMap<String,String>())).add(4);
+ mock.declareCounter("bar", new Point(new HashMap<String, String>())).add(4);
MetricSnapshot snapshot = new SnapshotConverter(mock.getSnapshot()).convert();
@@ -58,14 +58,14 @@ public class SnapshotConverterTest {
++cnt;
if ("foo".equals(mv.getKey())) {
assertTrue(mv.getValue() instanceof CountMetric);
- assertEquals(1, ((CountMetric)mv.getValue()).getCount());
+ assertEquals(1, ((CountMetric) mv.getValue()).getCount());
} else if ("bar".equals(mv.getKey())) {
assertTrue(mv.getValue() instanceof CountMetric);
- assertEquals(4, ((CountMetric)mv.getValue()).getCount());
+ assertEquals(4, ((CountMetric) mv.getValue()).getCount());
} else if ("quuux".equals(mv.getKey())) {
assertTrue(mv.getValue() instanceof GaugeMetric);
- assertEquals(42.25, ((GaugeMetric)mv.getValue()).getLast(), 0.001);
- assertEquals(1, ((GaugeMetric)mv.getValue()).getCount());
+ assertEquals(42.25, ((GaugeMetric) mv.getValue()).getLast(), 0.001);
+ assertEquals(1, ((GaugeMetric) mv.getValue()).getCount());
} else {
assertTrue(false);
}
diff --git a/container-core/src/test/java/com/yahoo/osgi/provider/model/ComponentModelTest.java b/container-core/src/test/java/com/yahoo/osgi/provider/model/ComponentModelTest.java
index a1e533158b5..c1f4991cfcc 100644
--- a/container-core/src/test/java/com/yahoo/osgi/provider/model/ComponentModelTest.java
+++ b/container-core/src/test/java/com/yahoo/osgi/provider/model/ComponentModelTest.java
@@ -2,9 +2,10 @@
package com.yahoo.osgi.provider.model;
import com.yahoo.container.bundle.BundleInstantiationSpecification;
-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;
/**
* @author gjoranv
@@ -12,19 +13,21 @@ import static org.junit.Assert.assertEquals;
public class ComponentModelTest {
@Test
- public void create_from_instantiation_spec() {
+ void create_from_instantiation_spec() {
ComponentModel model = new ComponentModel(
BundleInstantiationSpecification.fromStrings("id", "class", "bundle"));
verifyBundleSpec(model);
}
- @Test(expected = IllegalArgumentException.class)
- public void require_exception_upon_null_instantiation_spec() throws Exception {
- ComponentModel model = new ComponentModel(null);
+ @Test
+ void require_exception_upon_null_instantiation_spec() throws Exception {
+ assertThrows(IllegalArgumentException.class, () -> {
+ ComponentModel model = new ComponentModel(null);
+ });
}
@Test
- public void create_from_instantiation_spec_and_config_id() throws Exception {
+ void create_from_instantiation_spec_and_config_id() throws Exception {
ComponentModel model = new ComponentModel(
BundleInstantiationSpecification.fromStrings("id", "class", "bundle"), "configId");
verifyBundleSpec(model);
@@ -32,7 +35,7 @@ public class ComponentModelTest {
}
@Test
- public void create_from_strings() throws Exception {
+ void create_from_strings() throws Exception {
ComponentModel model = new ComponentModel("id", "class", "bundle", "configId");
verifyBundleSpec(model);
assertEquals("configId", model.configId);
diff --git a/container-core/src/test/java/com/yahoo/processing/ResponseTestCase.java b/container-core/src/test/java/com/yahoo/processing/ResponseTestCase.java
index f8cd646909d..274bd2050f2 100644
--- a/container-core/src/test/java/com/yahoo/processing/ResponseTestCase.java
+++ b/container-core/src/test/java/com/yahoo/processing/ResponseTestCase.java
@@ -5,11 +5,11 @@ import com.yahoo.processing.response.ArrayDataList;
import com.yahoo.processing.response.DataList;
import com.yahoo.processing.test.ProcessorLibrary;
import com.yahoo.processing.test.Responses;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.ExecutionException;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bratseth
@@ -24,7 +24,7 @@ public class ResponseTestCase {
*/
@SuppressWarnings({"unchecked"})
@Test
- public void testRecursiveCompletionAndToString() throws InterruptedException, ExecutionException {
+ void testRecursiveCompletionAndToString() throws InterruptedException, ExecutionException {
// create lists
Request request = new Request();
DataList list1 = ArrayDataList.create(request);
@@ -48,22 +48,22 @@ public class ResponseTestCase {
list123.add(list1231);
list123.add(list1232);
// add sync data elements
- list1.add(new ProcessorLibrary.StringData(request,"list1"));
- list12.add(new ProcessorLibrary.StringData(request,"list12"));
- list14.add(new ProcessorLibrary.StringData(request,"list14"));
- list122.add(new ProcessorLibrary.StringData(request,"list122"));
- list1231.add(new ProcessorLibrary.StringData(request,"list1231"));
+ list1.add(new ProcessorLibrary.StringData(request, "list1"));
+ list12.add(new ProcessorLibrary.StringData(request, "list12"));
+ list14.add(new ProcessorLibrary.StringData(request, "list14"));
+ list122.add(new ProcessorLibrary.StringData(request, "list122"));
+ list1231.add(new ProcessorLibrary.StringData(request, "list1231"));
- assertEqualsIgnoreObjectNumbers("Uncompleted tree, no incoming",uncompletedTreeUncompletedIncoming,Responses.recursiveToString(list1));
+ assertEqualsIgnoreObjectNumbers("Uncompleted tree, no incoming", uncompletedTreeUncompletedIncoming, Responses.recursiveToString(list1));
// provide all async incoming data
list12.incoming().markComplete();
- list121.incoming().addLast(new ProcessorLibrary.StringData(request,"list121async1"));
+ list121.incoming().addLast(new ProcessorLibrary.StringData(request, "list121async1"));
list123.incoming().markComplete();
- list1231.incoming().add(new ProcessorLibrary.StringData(request,"list13231async1"));
- list1231.incoming().addLast(new ProcessorLibrary.StringData(request,"list1231async2"));
- list13.incoming().add(new ProcessorLibrary.StringData(request,"list13async1"));
- list13.incoming().addLast(new ProcessorLibrary.StringData(request,"list13async2"));
+ list1231.incoming().add(new ProcessorLibrary.StringData(request, "list13231async1"));
+ list1231.incoming().addLast(new ProcessorLibrary.StringData(request, "list1231async2"));
+ list13.incoming().add(new ProcessorLibrary.StringData(request, "list13async1"));
+ list13.incoming().addLast(new ProcessorLibrary.StringData(request, "list13async2"));
assertEqualsIgnoreObjectNumbers("Uncompleted tree, incoming complete", uncompletedTreeCompletedIncoming, Responses.recursiveToString(list1));
@@ -73,7 +73,7 @@ public class ResponseTestCase {
}
private void assertEqualsIgnoreObjectNumbers(String explanation,String expected,String actual) {
- assertEquals(explanation,expected,removeObjectNumbers(actual));
+ assertEquals(expected,removeObjectNumbers(actual),explanation);
}
/** Removes all object numbers (occurrences of @hexnumber) */
diff --git a/container-core/src/test/java/com/yahoo/processing/execution/test/AsyncExecutionTestCase.java b/container-core/src/test/java/com/yahoo/processing/execution/test/AsyncExecutionTestCase.java
index 22f69a87bc3..fb469c36e14 100644
--- a/container-core/src/test/java/com/yahoo/processing/execution/test/AsyncExecutionTestCase.java
+++ b/container-core/src/test/java/com/yahoo/processing/execution/test/AsyncExecutionTestCase.java
@@ -6,10 +6,10 @@ import com.yahoo.processing.Processor;
import com.yahoo.processing.Request;
import com.yahoo.processing.Response;
import com.yahoo.processing.execution.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static com.yahoo.processing.test.ProcessorLibrary.*;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bratseth
@@ -18,29 +18,29 @@ public class AsyncExecutionTestCase {
/** Execute a processing chain which forks off into multiple threads */
@Test
- public void testAsyncExecution() {
+ void testAsyncExecution() {
// Create a chain
- Chain<Processor> chain=new Chain<>(new CombineData(),new BlockingSplitter(2),new Get6DataItems(), new DataSource());
+ Chain<Processor> chain = new Chain<>(new CombineData(), new BlockingSplitter(2), new Get6DataItems(), new DataSource());
// Execute it
- Request request=new Request();
- request.properties().set("appendage",1);
- Response response=Execution.createRoot(chain,0,Execution.Environment.createEmpty()).process(request);
+ Request request = new Request();
+ request.properties().set("appendage", 1);
+ Response response = Execution.createRoot(chain, 0, Execution.Environment.createEmpty()).process(request);
// Verify the result
- assertEquals(6*2-1,response.data().asList().size());
- assertEquals("first.2, third.2",response.data().get(0).toString());
- assertEquals("second.2",response.data().get(1).toString());
- assertEquals("first.3",response.data().get(2).toString());
- assertEquals("second.3",response.data().get(3).toString());
- assertEquals("third.3",response.data().get(4).toString());
+ assertEquals(6 * 2 - 1, response.data().asList().size());
+ assertEquals("first.2, third.2", response.data().get(0).toString());
+ assertEquals("second.2", response.data().get(1).toString());
+ assertEquals("first.3", response.data().get(2).toString());
+ assertEquals("second.3", response.data().get(3).toString());
+ assertEquals("third.3", response.data().get(4).toString());
// from the parallel execution
- assertEquals("first.2",response.data().get(5).toString());
- assertEquals("second.2",response.data().get(6).toString());
- assertEquals("third.2",response.data().get(7).toString());
- assertEquals("first.3",response.data().get(8).toString());
- assertEquals("second.3",response.data().get(9).toString());
- assertEquals("third.3",response.data().get(10).toString());
+ assertEquals("first.2", response.data().get(5).toString());
+ assertEquals("second.2", response.data().get(6).toString());
+ assertEquals("third.2", response.data().get(7).toString());
+ assertEquals("first.3", response.data().get(8).toString());
+ assertEquals("second.3", response.data().get(9).toString());
+ assertEquals("third.3", response.data().get(10).toString());
}
}
diff --git a/container-core/src/test/java/com/yahoo/processing/execution/test/ExecutionContextTestCase.java b/container-core/src/test/java/com/yahoo/processing/execution/test/ExecutionContextTestCase.java
index c8c489b2f9d..ce7a747d676 100644
--- a/container-core/src/test/java/com/yahoo/processing/execution/test/ExecutionContextTestCase.java
+++ b/container-core/src/test/java/com/yahoo/processing/execution/test/ExecutionContextTestCase.java
@@ -5,16 +5,13 @@ import com.yahoo.component.chain.Chain;
import com.yahoo.processing.Processor;
import com.yahoo.processing.execution.Execution;
import com.yahoo.processing.test.ProcessorLibrary;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
-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.*;
/**
* @author bratseth
@@ -25,53 +22,53 @@ public class ExecutionContextTestCase {
/** Tests combined use of trace messages, context values and access log entries */
@Test
- public void testtrace() {
- Execution execution1=Execution.createRoot(chain,2,Execution.Environment.createEmpty());
- execution1.trace().setProperty("a","a1");
- execution1.trace().logValue("a","a1");
+ void testtrace() {
+ Execution execution1 = Execution.createRoot(chain, 2, Execution.Environment.createEmpty());
+ execution1.trace().setProperty("a", "a1");
+ execution1.trace().logValue("a", "a1");
execution1.trace().trace("root 1", 2);
- execution1.trace().setProperty("a","a2");
- execution1.trace().setProperty("b","b1");
- execution1.trace().logValue("a","a2");
- execution1.trace().logValue("b","b1");
-
- Execution execution2=new Execution(chain,execution1);
- execution2.trace().setProperty("b","b2");
- execution2.trace().logValue("b","b2");
+ execution1.trace().setProperty("a", "a2");
+ execution1.trace().setProperty("b", "b1");
+ execution1.trace().logValue("a", "a2");
+ execution1.trace().logValue("b", "b1");
+
+ Execution execution2 = new Execution(chain, execution1);
+ execution2.trace().setProperty("b", "b2");
+ execution2.trace().logValue("b", "b2");
execution2.trace().trace(" child-1 1", 2);
execution2.trace().setProperty("b", "b3");
- execution2.trace().logValue("b","b3");
+ execution2.trace().logValue("b", "b3");
- execution1.trace().setProperty("b","b4");
- execution1.trace().logValue("b","b4");
+ execution1.trace().setProperty("b", "b4");
+ execution1.trace().logValue("b", "b4");
- Execution execution3=new Execution(chain,execution1);
- execution3.trace().setProperty("b","b5");
- execution3.trace().setProperty("c","c1");
- execution3.trace().logValue("b","b5");
- execution3.trace().logValue("c","c1");
+ Execution execution3 = new Execution(chain, execution1);
+ execution3.trace().setProperty("b", "b5");
+ execution3.trace().setProperty("c", "c1");
+ execution3.trace().logValue("b", "b5");
+ execution3.trace().logValue("c", "c1");
execution3.trace().trace(" child-2 1", 2);
- execution2.trace().setProperty("c","c2");
- execution2.trace().logValue("c","c2");
+ execution2.trace().setProperty("c", "c2");
+ execution2.trace().logValue("c", "c2");
execution1.trace().trace("root 2", 2);
execution3.trace().setProperty("d", "d1");
- execution1.trace().logValue("d","d1");
+ execution1.trace().logValue("d", "d1");
execution2.trace().trace(" child-1 2", 2);
execution2.trace().setProperty("c", "c3");
- execution2.trace().logValue("c","c3");
+ execution2.trace().logValue("c", "c3");
- execution1.trace().setProperty("c","c4");
- execution1.trace().logValue("c","c4");
+ execution1.trace().setProperty("c", "c4");
+ execution1.trace().logValue("c", "c4");
- Iterator<String> traceIterator=execution1.trace().traceNode().root().descendants(String.class).iterator();
- assertEquals("root 1",traceIterator.next());
- assertEquals(" child-1 1",traceIterator.next());
- assertEquals(" child-1 2",traceIterator.next());
- assertEquals(" child-2 1",traceIterator.next());
- assertEquals("root 2",traceIterator.next());
+ Iterator<String> traceIterator = execution1.trace().traceNode().root().descendants(String.class).iterator();
+ assertEquals("root 1", traceIterator.next());
+ assertEquals(" child-1 1", traceIterator.next());
+ assertEquals(" child-1 2", traceIterator.next());
+ assertEquals(" child-2 1", traceIterator.next());
+ assertEquals("root 2", traceIterator.next());
assertFalse(traceIterator.hasNext());
// Verify context variables
@@ -82,10 +79,10 @@ public class ExecutionContextTestCase {
assertNull(execution1.trace().getProperty("e"));
// Verify access log
- Set<String> logValues=new HashSet<>();
- for (Iterator<Execution.Trace.LogValue> logValueIterator=execution1.trace().logValueIterator(); logValueIterator.hasNext(); )
+ Set<String> logValues = new HashSet<>();
+ for (Iterator<Execution.Trace.LogValue> logValueIterator = execution1.trace().logValueIterator(); logValueIterator.hasNext(); )
logValues.add(logValueIterator.next().toString());
- assertEquals(12,logValues.size());
+ assertEquals(12, logValues.size());
assertTrue(logValues.contains("a=a1"));
assertTrue(logValues.contains("a=a2"));
assertTrue(logValues.contains("b=b1"));
diff --git a/container-core/src/test/java/com/yahoo/processing/execution/test/FutureDataTestCase.java b/container-core/src/test/java/com/yahoo/processing/execution/test/FutureDataTestCase.java
index 7dd043383a1..e346628452c 100644
--- a/container-core/src/test/java/com/yahoo/processing/execution/test/FutureDataTestCase.java
+++ b/container-core/src/test/java/com/yahoo/processing/execution/test/FutureDataTestCase.java
@@ -7,14 +7,14 @@ import com.yahoo.processing.Request;
import com.yahoo.processing.Response;
import com.yahoo.processing.execution.Execution;
import com.yahoo.processing.response.DataList;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import static com.yahoo.processing.test.ProcessorLibrary.*;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Tests scenarios where a data producer returns a promise of some future data rather than the data itself.
@@ -27,92 +27,92 @@ public class FutureDataTestCase {
/** Run a chain which ends in a processor which returns a response containing future data. */
@SuppressWarnings({"unchecked"})
@Test
- public void testFutureDataPassThrough() throws InterruptedException, ExecutionException, TimeoutException {
+ void testFutureDataPassThrough() throws InterruptedException, ExecutionException, TimeoutException {
// Set up
- FutureDataSource futureDataSource=new FutureDataSource();
- Chain<Processor> chain=new Chain<>(new DataCounter(),futureDataSource);
+ FutureDataSource futureDataSource = new FutureDataSource();
+ Chain<Processor> chain = new Chain<>(new DataCounter(), futureDataSource);
// Execute
- Request request=new Request();
- Response response=Execution.createRoot(chain,0,Execution.Environment.createEmpty()).process(request); // Urk ...
+ Request request = new Request();
+ Response response = Execution.createRoot(chain, 0, Execution.Environment.createEmpty()).process(request); // Urk ...
// Verify the result prior to completion of delayed data
- assertEquals(1,response.data().asList().size());
- assertEquals("Data count: 0",response.data().get(0).toString());
+ assertEquals(1, response.data().asList().size());
+ assertEquals("Data count: 0", response.data().get(0).toString());
// complete delayed data
- assertEquals("Delayed data was requested once", 1, futureDataSource.incomingData.size());
+ assertEquals(1, futureDataSource.incomingData.size(), "Delayed data was requested once");
futureDataSource.incomingData.get(0).add(new StringData(request, "d1"));
futureDataSource.incomingData.get(0).addLast(new StringData(request, "d2"));
- assertEquals("New data is not visible because we haven't asked for it", 1, response.data().asList().size());
+ assertEquals(1, response.data().asList().size(), "New data is not visible because we haven't asked for it");
response.data().completeFuture().get(1000, TimeUnit.MILLISECONDS);
- assertEquals("Now the data is available", 3, response.data().asList().size());
- assertEquals("d1",response.data().get(1).toString().toString());
- assertEquals("d2",response.data().get(2).toString().toString());
+ assertEquals(3, response.data().asList().size(), "Now the data is available");
+ assertEquals("d1", response.data().get(1).toString().toString());
+ assertEquals("d2", response.data().get(2).toString().toString());
}
/** Federate to one source which returns data immediately and one who return future data */
@SuppressWarnings({"unchecked"})
@Test
- public void testFederateSyncAndAsyncData() throws InterruptedException, ExecutionException, TimeoutException {
+ void testFederateSyncAndAsyncData() throws InterruptedException, ExecutionException, TimeoutException {
// Set up
- FutureDataSource futureDataSource=new FutureDataSource();
- Chain<Processor> chain=new Chain<>(new DataCounter(),new Federator(new Chain<>(new DataSource()),new Chain<>(futureDataSource)));
+ FutureDataSource futureDataSource = new FutureDataSource();
+ Chain<Processor> chain = new Chain<>(new DataCounter(), new Federator(new Chain<>(new DataSource()), new Chain<>(futureDataSource)));
// Execute
- Request request=new Request();
- request.properties().set("appendage",1);
- Response response=Execution.createRoot(chain,0,Execution.Environment.createEmpty()).process(request);
+ Request request = new Request();
+ request.properties().set("appendage", 1);
+ Response response = Execution.createRoot(chain, 0, Execution.Environment.createEmpty()).process(request);
// Verify the result prior to completion of delayed data
- assertEquals(3,response.data().asList().size()); // The sync data list + the (currently empty) future data list) + the data count
- DataList syncData=(DataList)response.data().get(0);
- DataList asyncData=(DataList)response.data().get(1);
- StringData countData=(StringData)response.data().get(2);
+ assertEquals(3, response.data().asList().size()); // The sync data list + the (currently empty) future data list) + the data count
+ DataList syncData = (DataList) response.data().get(0);
+ DataList asyncData = (DataList) response.data().get(1);
+ StringData countData = (StringData) response.data().get(2);
- assertEquals("The sync data is available",3,syncData.asList().size());
- assertEquals( "first.1",syncData.get(0).toString());
+ assertEquals(3, syncData.asList().size(), "The sync data is available");
+ assertEquals("first.1", syncData.get(0).toString());
assertEquals("second.1", syncData.get(1).toString());
- assertEquals( "third.1",syncData.get(2).toString());
- assertEquals("No async data yet",0,asyncData.asList().size());
- assertEquals("The data counter has run and accessed the sync data","Data count: 3",countData.toString());
+ assertEquals("third.1", syncData.get(2).toString());
+ assertEquals(0, asyncData.asList().size(), "No async data yet");
+ assertEquals("Data count: 3", countData.toString(), "The data counter has run and accessed the sync data");
// complete async data
futureDataSource.incomingData.get(0).add(new StringData(request, "d1"));
futureDataSource.incomingData.get(0).addLast(new StringData(request, "d2"));
- assertEquals("New data is not visible because we haven't asked for it", 0, asyncData.asList().size());
+ assertEquals(0, asyncData.asList().size(), "New data is not visible because we haven't asked for it");
asyncData.completeFuture().get(1000, TimeUnit.MILLISECONDS);
- assertEquals("Now the data is available", 2, asyncData.asList().size());
- assertEquals("d1",asyncData.get(0).toString().toString());
+ assertEquals(2, asyncData.asList().size(), "Now the data is available");
+ assertEquals("d1", asyncData.get(0).toString().toString());
assertEquals("d2", asyncData.get(1).toString().toString());
}
/** Register a chain which will be called when some async data is available */
@SuppressWarnings({"unchecked", "removal"})
@Test
- public void testAsyncDataProcessing() throws InterruptedException, ExecutionException, TimeoutException {
+ void testAsyncDataProcessing() throws InterruptedException, ExecutionException, TimeoutException {
// Set up
- FutureDataSource futureDataSource=new FutureDataSource();
- Chain<Processor> asyncChain=new Chain<Processor>(new DataCounter());
- Chain<Processor> chain=new Chain<>(new AsyncDataProcessingInitiator(asyncChain),futureDataSource);
+ FutureDataSource futureDataSource = new FutureDataSource();
+ Chain<Processor> asyncChain = new Chain<Processor>(new DataCounter());
+ Chain<Processor> chain = new Chain<>(new AsyncDataProcessingInitiator(asyncChain), futureDataSource);
// Execute
- Request request=new Request();
- Response response=Execution.createRoot(chain,0,Execution.Environment.createEmpty()).process(request);
+ Request request = new Request();
+ Response response = Execution.createRoot(chain, 0, Execution.Environment.createEmpty()).process(request);
// Verify the result prior to completion of delayed data
- assertEquals("No data yet",0,response.data().asList().size());
+ assertEquals(0, response.data().asList().size(), "No data yet");
// complete async data
futureDataSource.incomingData.get(0).add(new StringData(request, "d1"));
- assertEquals("New data is not visible because it is not complete", 0, response.data().asList().size());
+ assertEquals(0, response.data().asList().size(), "New data is not visible because it is not complete");
futureDataSource.incomingData.get(0).addLast(new StringData(request, "d2"));
- assertEquals("Not visible because it has not been synced yet", 0, response.data().asList().size());
+ assertEquals(0, response.data().asList().size(), "Not visible because it has not been synced yet");
response.data().completeFuture().get(1000, TimeUnit.MILLISECONDS);
- assertEquals("Now the data as well as the count is available", 3, response.data().asList().size());
- assertEquals("d1",response.data().get(0).toString().toString());
- assertEquals("d2",response.data().get(1).toString().toString());
- assertEquals("Data count: 2",response.data().get(2).toString());
+ assertEquals(3, response.data().asList().size(), "Now the data as well as the count is available");
+ assertEquals("d1", response.data().get(0).toString().toString());
+ assertEquals("d2", response.data().get(1).toString().toString());
+ assertEquals("Data count: 2", response.data().get(2).toString());
}
/**
@@ -122,52 +122,51 @@ public class FutureDataTestCase {
*/
@SuppressWarnings({"unchecked"})
@Test
- public void testAsyncDataProcessingOfFederatedResult() throws InterruptedException, ExecutionException, TimeoutException {
+ void testAsyncDataProcessingOfFederatedResult() throws InterruptedException, ExecutionException, TimeoutException {
// Set up
// Source 1 (async with completion chain)
- FutureDataSource futureSource1=new FutureDataSource();
- Chain<Processor> asyncChainSource1=new Chain<Processor>(new DataCounter("source1"));
- Chain<Processor> chainSource1=new Chain<>(new AsyncDataProcessingInitiator(asyncChainSource1),futureSource1);
+ FutureDataSource futureSource1 = new FutureDataSource();
+ Chain<Processor> asyncChainSource1 = new Chain<Processor>(new DataCounter("source1"));
+ Chain<Processor> chainSource1 = new Chain<>(new AsyncDataProcessingInitiator(asyncChainSource1), futureSource1);
// Source 2 (async source)
- FutureDataSource futureSource2=new FutureDataSource();
- Chain<Processor> chainSource2=new Chain<Processor>(futureSource2);
+ FutureDataSource futureSource2 = new FutureDataSource();
+ Chain<Processor> chainSource2 = new Chain<Processor>(futureSource2);
// Source 3 (sync source)
- Chain<Processor> chainSource3=new Chain<Processor>(new DataSource());
+ Chain<Processor> chainSource3 = new Chain<Processor>(new DataSource());
// Main chain federating to the above - not waiting for source 1 and 2 but invoking asyncMain when both are complete
- Chain<Processor> asyncMain=new Chain<Processor>(new DataCounter("main"));
- Chain<Processor> main=new Chain<>(new AsyncDataProcessingInitiator(asyncMain),new Federator(chainSource1,chainSource2,chainSource3));
+ Chain<Processor> asyncMain = new Chain<Processor>(new DataCounter("main"));
+ Chain<Processor> main = new Chain<>(new AsyncDataProcessingInitiator(asyncMain), new Federator(chainSource1, chainSource2, chainSource3));
// Execute
- Request request=new Request();
- Response response=Execution.createRoot(main,0,Execution.Environment.createEmpty()).process(request);
+ Request request = new Request();
+ Response response = Execution.createRoot(main, 0, Execution.Environment.createEmpty()).process(request);
// Verify the result prior to completion of delayed data
- assertEquals("We have the sync data plus placeholders for the async lists",3,response.data().asList().size());
- DataList source1Data=((DataList)response.data().get(0));
- DataList source2Data=((DataList)response.data().get(1));
- DataList source3Data=((DataList)response.data().get(2));
+ assertEquals(3, response.data().asList().size(), "We have the sync data plus placeholders for the async lists");
+ DataList source1Data = ((DataList) response.data().get(0));
+ DataList source2Data = ((DataList) response.data().get(1));
+ DataList source3Data = ((DataList) response.data().get(2));
- assertEquals("No data yet",0,source1Data.asList().size());
- assertEquals("No data yet",0,source2Data.asList().size());
- assertEquals(3,source3Data.asList().size());
+ assertEquals(0, source1Data.asList().size(), "No data yet");
+ assertEquals(0, source2Data.asList().size(), "No data yet");
+ assertEquals(3, source3Data.asList().size());
// complete async data in source1
- futureSource1.incomingData.get(0).addLast(new StringData(request,"source1Data"));
- assertEquals("Not visible yet", 0, source1Data.asList().size());
+ futureSource1.incomingData.get(0).addLast(new StringData(request, "source1Data"));
+ assertEquals(0, source1Data.asList().size(), "Not visible yet");
source1Data.completeFuture().get(1000, TimeUnit.MILLISECONDS);
assertEquals(2, source1Data.asList().size());
- assertEquals("source1Data",source1Data.get(0).toString());
- assertEquals("Completion listener chain on this has run", "[source1] Data count: 1", source1Data.get(1).toString());
+ assertEquals("source1Data", source1Data.get(0).toString());
+ assertEquals("[source1] Data count: 1", source1Data.get(1).toString(), "Completion listener chain on this has run");
// source2 & main completion
- assertEquals("Main completion listener has not run", 3, response.data().asList().size());
+ assertEquals(3, response.data().asList().size(), "Main completion listener has not run");
futureSource2.incomingData.get(0).addLast(new StringData(request, "source2Data"));
- assertEquals("Main completion listener has not run", 3, response.data().asList().size());
+ assertEquals(3, response.data().asList().size(), "Main completion listener has not run");
Response.recursiveFuture(response.data()).get();
- assertEquals("Main completion listener has run", 4, response.data().asList().size());
- assertEquals("The main data counter saw all sync data, but not source2 data as it executes after this",
- "[main] Data count: " + (2 + 0 + 3), response.data().get(3).toString());
+ assertEquals(4, response.data().asList().size(), "Main completion listener has run");
+ assertEquals("[main] Data count: " + (2 + 0 + 3), response.data().get(3).toString(), "The main data counter saw all sync data, but not source2 data as it executes after this");
}
}
diff --git a/container-core/src/test/java/com/yahoo/processing/execution/test/StreamingTestCase.java b/container-core/src/test/java/com/yahoo/processing/execution/test/StreamingTestCase.java
index d494e774f8e..557bef39276 100644
--- a/container-core/src/test/java/com/yahoo/processing/execution/test/StreamingTestCase.java
+++ b/container-core/src/test/java/com/yahoo/processing/execution/test/StreamingTestCase.java
@@ -10,13 +10,13 @@ import com.yahoo.processing.execution.Execution;
import com.yahoo.processing.response.Data;
import com.yahoo.processing.response.IncomingData;
import com.yahoo.processing.test.ProcessorLibrary;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Tests listening on every available new piece of data in a response
@@ -28,48 +28,48 @@ public class StreamingTestCase {
/** Tests adding a chain which is called every time new data is added to a data list */
@SuppressWarnings({"unchecked"})
@Test
- public void testStreamingData() throws InterruptedException, ExecutionException, TimeoutException {
+ void testStreamingData() throws InterruptedException, ExecutionException, TimeoutException {
// Set up
StreamProcessor streamProcessor = new StreamProcessor();
Chain<Processor> streamProcessing = new Chain<Processor>(streamProcessor);
- ProcessorLibrary.FutureDataSource futureDataSource=new ProcessorLibrary.FutureDataSource();
- Chain<Processor> main=new Chain<>(new ProcessorLibrary.DataCounter(),
- new ProcessorLibrary.StreamProcessingInitiator(streamProcessing),
- futureDataSource);
+ ProcessorLibrary.FutureDataSource futureDataSource = new ProcessorLibrary.FutureDataSource();
+ Chain<Processor> main = new Chain<>(new ProcessorLibrary.DataCounter(),
+ new ProcessorLibrary.StreamProcessingInitiator(streamProcessing),
+ futureDataSource);
// Execute
- Request request=new Request();
- Response response= Execution.createRoot(main, 0, Execution.Environment.createEmpty()).process(request);
+ Request request = new Request();
+ Response response = Execution.createRoot(main, 0, Execution.Environment.createEmpty()).process(request);
IncomingData incomingData = futureDataSource.incomingData.get(0);
// State prior to receiving any additional data
- assertEquals(1,response.data().asList().size());
- assertEquals("Data count: 0",response.data().get(0).toString());
- assertEquals("Add data listener invoked also for DataCounter", 1, streamProcessor.invocationCount);
- assertEquals("Initial data count", 1, response.data().asList().size());
+ assertEquals(1, response.data().asList().size());
+ assertEquals("Data count: 0", response.data().get(0).toString());
+ assertEquals(1, streamProcessor.invocationCount, "Add data listener invoked also for DataCounter");
+ assertEquals(1, response.data().asList().size(), "Initial data count");
// add first data - we have no listener so the data is held in the incoming buffer
incomingData.add(new ProcessorLibrary.StringData(request, "d1"));
- assertEquals("Data add listener not invoked as we are not listening on new data yet",1, streamProcessor.invocationCount);
- assertEquals("New data is not consumed", 1, response.data().asList().size());
+ assertEquals(1, streamProcessor.invocationCount, "Data add listener not invoked as we are not listening on new data yet");
+ assertEquals(1, response.data().asList().size(), "New data is not consumed");
// start listening on incoming data - this is what a renderer will do
incomingData.addNewDataListener(new MockNewDataListener(incomingData), MoreExecutors.directExecutor());
- assertEquals("We got a data add event for the data which was already added", 2, streamProcessor.invocationCount);
- assertEquals("New data is consumed", 2, response.data().asList().size());
+ assertEquals(2, streamProcessor.invocationCount, "We got a data add event for the data which was already added");
+ assertEquals(2, response.data().asList().size(), "New data is consumed");
incomingData.add(new ProcessorLibrary.StringData(request, "d2"));
- assertEquals("We are now getting data add events each time", 3, streamProcessor.invocationCount);
- assertEquals("New data is consumed", 3, response.data().asList().size());
+ assertEquals(3, streamProcessor.invocationCount, "We are now getting data add events each time");
+ assertEquals(3, response.data().asList().size(), "New data is consumed");
incomingData.addLast(new ProcessorLibrary.StringData(request, "d3"));
- assertEquals("We are getting data add events also the last time", 4, streamProcessor.invocationCount);
- assertEquals("New data is consumed", 4, response.data().asList().size());
+ assertEquals(4, streamProcessor.invocationCount, "We are getting data add events also the last time");
+ assertEquals(4, response.data().asList().size(), "New data is consumed");
response.data().completeFuture().get(1000, TimeUnit.MILLISECONDS); // no-op here
- assertEquals("d1",response.data().get(1).toString().toString());
- assertEquals("d2",response.data().get(2).toString().toString());
- assertEquals("d3",response.data().get(3).toString().toString());
+ assertEquals("d1", response.data().get(1).toString().toString());
+ assertEquals("d2", response.data().get(2).toString().toString());
+ assertEquals("d3", response.data().get(3).toString().toString());
}
private static class MockNewDataListener implements Runnable {
diff --git a/container-core/src/test/java/com/yahoo/processing/handler/ProcessingHandlerTestCase.java b/container-core/src/test/java/com/yahoo/processing/handler/ProcessingHandlerTestCase.java
index baed2ccdcc8..70bae6c97b1 100644
--- a/container-core/src/test/java/com/yahoo/processing/handler/ProcessingHandlerTestCase.java
+++ b/container-core/src/test/java/com/yahoo/processing/handler/ProcessingHandlerTestCase.java
@@ -21,9 +21,9 @@ import com.yahoo.processing.rendering.Renderer;
import com.yahoo.processing.request.ErrorMessage;
import com.yahoo.processing.response.Data;
import com.yahoo.processing.test.ProcessorLibrary;
-import org.junit.After;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.InputStream;
@@ -39,12 +39,7 @@ import java.util.concurrent.ExecutionException;
import static com.yahoo.jdisc.http.server.jetty.AccessLoggingRequestHandler.CONTEXT_KEY_ACCESS_LOG_ENTRY;
import static com.yahoo.processing.test.ProcessorLibrary.MapData;
-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.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Tests processing handler scenarios end to end.
@@ -74,13 +69,13 @@ public class ProcessingHandlerTestCase {
new Chain<>("log-value",
new ProcessorLibrary.LogValueAdder(LOG_KEY, LOG_VALUE));
- @After
+ @AfterEach
public void shutDown() {
driver.close();
}
@Test
- public void processing_handler_stores_trace_log_values_in_the_access_log_entry() {
+ void processing_handler_stores_trace_log_values_in_the_access_log_entry() {
driver = new ProcessingTestDriver(logValueChain);
Request request = HttpRequest.newServerRequest(driver.jDiscDriver(), URI.create("http://localhost/?chain=log-value"), HttpRequest.Method.GET);
AccessLogEntry entry = new AccessLogEntry();
@@ -95,7 +90,7 @@ public class ProcessingHandlerTestCase {
}
@Test
- public void testProcessingHandlerResolvesChains() {
+ void testProcessingHandlerResolvesChains() {
List<Chain<Processor>> chains = new ArrayList<>();
chains.add(defaultChain);
chains.add(simpleChain);
@@ -106,16 +101,16 @@ public class ProcessingHandlerTestCase {
}
@Test
- public void testProcessingHandlerPropagatesRequestParametersAndContext() {
+ void testProcessingHandlerPropagatesRequestParametersAndContext() {
List<Chain<Processor>> chains = new ArrayList<>();
chains.add(new Chain<>("default", new RequestPropertyTracer()));
driver = new ProcessingTestDriver(chains);
- assertTrue("JDisc request context is propagated to properties()",
- driver.sendRequest("http://localhost/?chain=default&tracelevel=4").readAll().contains("context.contextVariable: '37'"));
+ assertTrue(driver.sendRequest("http://localhost/?chain=default&tracelevel=4").readAll().contains("context.contextVariable: '37'"),
+ "JDisc request context is propagated to properties()");
}
@Test
- public void testProcessingHandlerOutputsTrace() {
+ void testProcessingHandlerOutputsTrace() {
List<Chain<Processor>> chains = new ArrayList<>();
chains.add(defaultChain);
driver = new ProcessingTestDriver(chains);
@@ -128,28 +123,28 @@ public class ProcessingHandlerTestCase {
}
@Test
- public void testProcessingHandlerTransfersErrorsToHttpStatusCodesNoData() {
+ void testProcessingHandlerTransfersErrorsToHttpStatusCodesNoData() {
List<Chain<Processor>> chains = new ArrayList<>();
chains.add(simpleChain);
- chains.add(new Chain<>("moved_permanently", new ProcessorLibrary.ErrorAdder(new ErrorMessage(301,"Message"))));
- chains.add(new Chain<>("unauthorized", new ProcessorLibrary.ErrorAdder(new ErrorMessage(401,"Message"))));
- chains.add(new Chain<>("unauthorized_mapped", new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.UNAUTHORIZED.code,"Message"))));
- chains.add(new Chain<>("forbidden", new ProcessorLibrary.ErrorAdder(new ErrorMessage(403,"Message"))));
- chains.add(new Chain<>("forbidden_mapped", new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.FORBIDDEN.code,"Message"))));
- chains.add(new Chain<>("not_found", new ProcessorLibrary.ErrorAdder(new ErrorMessage(404,"Message"))));
- chains.add(new Chain<>("not_found_mapped", new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.NOT_FOUND.code,"Message"))));
- chains.add(new Chain<>("too_many_requests", new ProcessorLibrary.ErrorAdder(new ErrorMessage(429,"Message"))));
- chains.add(new Chain<>("bad_request", new ProcessorLibrary.ErrorAdder(new ErrorMessage(400,"Message"))));
- chains.add(new Chain<>("bad_request_mapped", new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.BAD_REQUEST.code,"Message"))));
- chains.add(new Chain<>("internal_server_error", new ProcessorLibrary.ErrorAdder(new ErrorMessage(500,"Message"))));
- chains.add(new Chain<>("internal_server_error_mapped", new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.INTERNAL_SERVER_ERROR.code,"Message"))));
- chains.add(new Chain<>("service_unavailable", new ProcessorLibrary.ErrorAdder(new ErrorMessage(503,"Message"))));
- chains.add(new Chain<>("service_unavailable_mapped", new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.NO_BACKENDS_IN_SERVICE.code,"Message"))));
- chains.add(new Chain<>("gateway_timeout", new ProcessorLibrary.ErrorAdder(new ErrorMessage(504,"Message"))));
- chains.add(new Chain<>("gateway_timeout_mapped", new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.TIMEOUT.code,"Message"))));
- chains.add(new Chain<>("bad_gateway", new ProcessorLibrary.ErrorAdder(new ErrorMessage(502,"Message"))));
- chains.add(new Chain<>("bad_gateway_mapped", new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.BACKEND_COMMUNICATION_ERROR.code,"Message"))));
- chains.add(new Chain<>("unknown_code", new ProcessorLibrary.ErrorAdder(new ErrorMessage(1234567,"Message"))));
+ chains.add(new Chain<>("moved_permanently", new ProcessorLibrary.ErrorAdder(new ErrorMessage(301, "Message"))));
+ chains.add(new Chain<>("unauthorized", new ProcessorLibrary.ErrorAdder(new ErrorMessage(401, "Message"))));
+ chains.add(new Chain<>("unauthorized_mapped", new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.UNAUTHORIZED.code, "Message"))));
+ chains.add(new Chain<>("forbidden", new ProcessorLibrary.ErrorAdder(new ErrorMessage(403, "Message"))));
+ chains.add(new Chain<>("forbidden_mapped", new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.FORBIDDEN.code, "Message"))));
+ chains.add(new Chain<>("not_found", new ProcessorLibrary.ErrorAdder(new ErrorMessage(404, "Message"))));
+ chains.add(new Chain<>("not_found_mapped", new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.NOT_FOUND.code, "Message"))));
+ chains.add(new Chain<>("too_many_requests", new ProcessorLibrary.ErrorAdder(new ErrorMessage(429, "Message"))));
+ chains.add(new Chain<>("bad_request", new ProcessorLibrary.ErrorAdder(new ErrorMessage(400, "Message"))));
+ chains.add(new Chain<>("bad_request_mapped", new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.BAD_REQUEST.code, "Message"))));
+ chains.add(new Chain<>("internal_server_error", new ProcessorLibrary.ErrorAdder(new ErrorMessage(500, "Message"))));
+ chains.add(new Chain<>("internal_server_error_mapped", new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.INTERNAL_SERVER_ERROR.code, "Message"))));
+ chains.add(new Chain<>("service_unavailable", new ProcessorLibrary.ErrorAdder(new ErrorMessage(503, "Message"))));
+ chains.add(new Chain<>("service_unavailable_mapped", new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.NO_BACKENDS_IN_SERVICE.code, "Message"))));
+ chains.add(new Chain<>("gateway_timeout", new ProcessorLibrary.ErrorAdder(new ErrorMessage(504, "Message"))));
+ chains.add(new Chain<>("gateway_timeout_mapped", new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.TIMEOUT.code, "Message"))));
+ chains.add(new Chain<>("bad_gateway", new ProcessorLibrary.ErrorAdder(new ErrorMessage(502, "Message"))));
+ chains.add(new Chain<>("bad_gateway_mapped", new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.BACKEND_COMMUNICATION_ERROR.code, "Message"))));
+ chains.add(new Chain<>("unknown_code", new ProcessorLibrary.ErrorAdder(new ErrorMessage(1234567, "Message"))));
driver = new ProcessingTestDriver(chains);
assertEqualStatus(200, "http://localhost/?chain=simple");
assertEqualStatus(301, "http://localhost/?chain=moved_permanently");
@@ -174,28 +169,28 @@ public class ProcessingHandlerTestCase {
}
@Test
- public void testProcessingHandlerTransfersErrorsToHttpStatusCodesWithData() {
+ void testProcessingHandlerTransfersErrorsToHttpStatusCodesWithData() {
List<Chain<Processor>> chains = new ArrayList<>();
chains.add(simpleChain);
- chains.add(new Chain<>("moved_permanently", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(301,"Message"))));
- chains.add(new Chain<>("unauthorized", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(401,"Message"))));
- chains.add(new Chain<>("unauthorized_mapped", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.UNAUTHORIZED.code,"Message"))));
- chains.add(new Chain<>("forbidden", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(403,"Message"))));
- chains.add(new Chain<>("forbidden_mapped", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.FORBIDDEN.code,"Message"))));
- chains.add(new Chain<>("not_found", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(404,"Message"))));
- chains.add(new Chain<>("not_found_mapped", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.NOT_FOUND.code,"Message"))));
- chains.add(new Chain<>("too_many_requests", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(429,"Message"))));
- chains.add(new Chain<>("bad_request", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(400,"Message"))));
- chains.add(new Chain<>("bad_request_mapped", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.BAD_REQUEST.code,"Message"))));
- chains.add(new Chain<>("internal_server_error", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(500,"Message"))));
- chains.add(new Chain<>("internal_server_error_mapped", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.INTERNAL_SERVER_ERROR.code,"Message"))));
- chains.add(new Chain<>("service_unavailable", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(503,"Message"))));
- chains.add(new Chain<>("service_unavailable_mapped", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.NO_BACKENDS_IN_SERVICE.code,"Message"))));
- chains.add(new Chain<>("gateway_timeout", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(504,"Message"))));
- chains.add(new Chain<>("gateway_timeout_mapped", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.TIMEOUT.code,"Message"))));
- chains.add(new Chain<>("bad_gateway", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(502,"Message"))));
- chains.add(new Chain<>("bad_gateway_mapped", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.BACKEND_COMMUNICATION_ERROR.code,"Message"))));
- chains.add(new Chain<>("unknown_code", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(1234567,"Message"))));
+ chains.add(new Chain<>("moved_permanently", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(301, "Message"))));
+ chains.add(new Chain<>("unauthorized", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(401, "Message"))));
+ chains.add(new Chain<>("unauthorized_mapped", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.UNAUTHORIZED.code, "Message"))));
+ chains.add(new Chain<>("forbidden", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(403, "Message"))));
+ chains.add(new Chain<>("forbidden_mapped", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.FORBIDDEN.code, "Message"))));
+ chains.add(new Chain<>("not_found", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(404, "Message"))));
+ chains.add(new Chain<>("not_found_mapped", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.NOT_FOUND.code, "Message"))));
+ chains.add(new Chain<>("too_many_requests", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(429, "Message"))));
+ chains.add(new Chain<>("bad_request", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(400, "Message"))));
+ chains.add(new Chain<>("bad_request_mapped", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.BAD_REQUEST.code, "Message"))));
+ chains.add(new Chain<>("internal_server_error", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(500, "Message"))));
+ chains.add(new Chain<>("internal_server_error_mapped", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.INTERNAL_SERVER_ERROR.code, "Message"))));
+ chains.add(new Chain<>("service_unavailable", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(503, "Message"))));
+ chains.add(new Chain<>("service_unavailable_mapped", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.NO_BACKENDS_IN_SERVICE.code, "Message"))));
+ chains.add(new Chain<>("gateway_timeout", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(504, "Message"))));
+ chains.add(new Chain<>("gateway_timeout_mapped", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.TIMEOUT.code, "Message"))));
+ chains.add(new Chain<>("bad_gateway", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(502, "Message"))));
+ chains.add(new Chain<>("bad_gateway_mapped", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.BACKEND_COMMUNICATION_ERROR.code, "Message"))));
+ chains.add(new Chain<>("unknown_code", new ProcessorLibrary.StringDataAdder("Hello"), new ProcessorLibrary.ErrorAdder(new ErrorMessage(1234567, "Message"))));
driver = new ProcessingTestDriver(chains);
assertEqualStatus(200, "http://localhost/?chain=simple");
assertEqualStatus(301, "http://localhost/?chain=moved_permanently");
@@ -220,27 +215,27 @@ public class ProcessingHandlerTestCase {
}
@Test
- public void testProcessorSetsResponseHeaders() throws InterruptedException {
+ void testProcessorSetsResponseHeaders() throws InterruptedException {
ProcessingTestDriver.MockResponseHandler responseHandler = null;
try {
- Map<String,List<String>> responseHeaders = new HashMap<>();
+ Map<String, List<String>> responseHeaders = new HashMap<>();
responseHeaders.put("foo", List.of("fooValue"));
responseHeaders.put("bar", List.of("barValue", "bazValue"));
- Map<String,List<String>> otherResponseHeaders = new HashMap<>();
+ Map<String, List<String>> otherResponseHeaders = new HashMap<>();
otherResponseHeaders.put("foo", List.of("fooValue2"));
otherResponseHeaders.put("bax", List.of("baxValue"));
List<Chain<Processor>> chains = new ArrayList<>();
- chains.add(new Chain<>("default",new ResponseHeaderSetter(responseHeaders),
- new ResponseHeaderSetter(otherResponseHeaders)));
+ chains.add(new Chain<>("default", new ResponseHeaderSetter(responseHeaders),
+ new ResponseHeaderSetter(otherResponseHeaders)));
driver = new ProcessingTestDriver(chains);
responseHandler = driver.sendRequest("http://localhost/?chain=default").awaitResponse();
Response response = responseHandler.getResponse();
- assertEquals("[fooValue2, fooValue]",response.headers().get("foo").toString());
+ assertEquals("[fooValue2, fooValue]", response.headers().get("foo").toString());
assertEquals("[barValue, bazValue]", response.headers().get("bar").toString());
assertEquals("[baxValue]", response.headers().get("bax").toString());
- assertEquals("ResponseHeaders are not rendered", "{\"datalist\":[]}", responseHandler.read());
+ assertEquals("{\"datalist\":[]}", responseHandler.read(), "ResponseHeaders are not rendered");
}
finally {
if (responseHandler != null)
@@ -249,7 +244,7 @@ public class ProcessingHandlerTestCase {
}
@Test
- public void testResponseDataStatus() throws InterruptedException {
+ void testResponseDataStatus() throws InterruptedException {
ProcessingTestDriver.MockResponseHandler responseHandler = null;
try {
List<Chain<Processor>> chains = new ArrayList<>();
@@ -258,7 +253,7 @@ public class ProcessingHandlerTestCase {
responseHandler = driver.sendRequest("http://localhost/?chain=default").awaitResponse();
Response response = responseHandler.getResponse();
assertEquals(429, response.getStatus());
- assertEquals("ResponseHeaders are not rendered", "{\"datalist\":[]}", responseHandler.read());
+ assertEquals("{\"datalist\":[]}", responseHandler.read(), "ResponseHeaders are not rendered");
}
finally {
if (responseHandler != null)
@@ -268,13 +263,13 @@ public class ProcessingHandlerTestCase {
/** Tests that the ResponseStatus takes precedence over errors */
@Test
- public void testResponseDataStatusOverridesErrors() throws InterruptedException {
+ void testResponseDataStatusOverridesErrors() throws InterruptedException {
ProcessingTestDriver.MockResponseHandler responseHandler = null;
try {
List<Chain<Processor>> chains = new ArrayList<>();
chains.add(new Chain<>("default", new ResponseStatusSetter(200),
- new ProcessorLibrary.StringDataAdder("Hello"),
- new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.FORBIDDEN.code,"Message"))));
+ new ProcessorLibrary.StringDataAdder("Hello"),
+ new ProcessorLibrary.ErrorAdder(new ErrorMessage(Error.FORBIDDEN.code, "Message"))));
driver = new ProcessingTestDriver(chains);
responseHandler = driver.sendRequest("http://localhost/?chain=default").awaitResponse();
Response response = responseHandler.getResponse();
@@ -304,14 +299,14 @@ public class ProcessingHandlerTestCase {
@SuppressWarnings("unchecked")
@Test
- public void testProcessingHandlerSupportsAsyncRendering() {
+ void testProcessingHandlerSupportsAsyncRendering() {
// Set up
ProcessorLibrary.FutureDataSource futureDataSource = new ProcessorLibrary.FutureDataSource();
Chain<Processor> asyncCompletionChain = new Chain<>("asyncCompletion", new ProcessorLibrary.DataCounter("async"));
Chain<Processor> chain =
new Chain<>("federation", new ProcessorLibrary.DataCounter("sync"),
- new ProcessorLibrary.Federator(new Chain<Processor>(new ProcessorLibrary.DataSource()),
- new Chain<>(new ProcessorLibrary.AsyncDataProcessingInitiator(asyncCompletionChain),futureDataSource)));
+ new ProcessorLibrary.Federator(new Chain<Processor>(new ProcessorLibrary.DataSource()),
+ new Chain<>(new ProcessorLibrary.AsyncDataProcessingInitiator(asyncCompletionChain), futureDataSource)));
List<Chain<Processor>> chains = new ArrayList<>();
chains.add(chain);
driver = new ProcessingTestDriver(chains);
@@ -320,46 +315,46 @@ public class ProcessingHandlerTestCase {
String synchronousResponse = responseHandler.read();
assertEquals(
"{\"datalist\":[" +
- "{\"datalist\":[" +
- "{\"data\":\"first.null\"}," +
- "{\"data\":\"second.null\"}," +
- "{\"data\":\"third.null\"}" +
- "]}",
+ "{\"datalist\":[" +
+ "{\"data\":\"first.null\"}," +
+ "{\"data\":\"second.null\"}," +
+ "{\"data\":\"third.null\"}" +
+ "]}",
synchronousResponse);
- assertEquals("No more data is available at this point", 0, responseHandler.available());
+ assertEquals(0, responseHandler.available(), "No more data is available at this point");
// Now, complete async data
futureDataSource.incomingData.get(0).add(new ProcessorLibrary.StringData(null, "d1"));
assertEquals(
- "," +
- "{\"datalist\":[" +
- "{\"data\":\"d1\"}",
- responseHandler.read());
+ "," +
+ "{\"datalist\":[" +
+ "{\"data\":\"d1\"}",
+ responseHandler.read());
futureDataSource.incomingData.get(0).addLast(new ProcessorLibrary.StringData(null, "d2"));
// ... which leads to the rest of the response becoming available
assertEquals(
- "," +
- "{\"data\":\"d2\"}," +
- "{\"data\":\"[async] Data count: 2\"}" +
- "]}",
+ "," +
+ "{\"data\":\"d2\"}," +
+ "{\"data\":\"[async] Data count: 2\"}" +
+ "]}",
responseHandler.read());
assertEquals(",{\"data\":\"[sync] Data count: 3\"}" + // Async items not counted as they arrive after chain completion
- "]}",
- responseHandler.read());
- assertNull("Transmission completed", responseHandler.read());
+ "]}",
+ responseHandler.read());
+ assertNull(responseHandler.read(), "Transmission completed");
}
@SuppressWarnings("unchecked")
@Test
- public void testProcessingHandlerSupportsAsyncUnorderedRendering() {
+ void testProcessingHandlerSupportsAsyncUnorderedRendering() {
// Set up
ProcessorLibrary.FutureDataSource futureDataSource1 = new ProcessorLibrary.FutureDataSource();
ProcessorLibrary.FutureDataSource futureDataSource2 = new ProcessorLibrary.FutureDataSource();
Chain<Processor> chain =
new Chain<>("federation",
- new ProcessorLibrary.Federator(false,new Chain<Processor>(futureDataSource1),
- new Chain<Processor>(futureDataSource2)));
+ new ProcessorLibrary.Federator(false, new Chain<Processor>(futureDataSource1),
+ new Chain<Processor>(futureDataSource2)));
List<Chain<Processor>> chains = new ArrayList<>();
chains.add(chain);
driver = new ProcessingTestDriver(chains);
@@ -368,69 +363,69 @@ public class ProcessingHandlerTestCase {
assertEquals(
"{\"datalist\":[",
responseHandler.read());
- assertEquals("No more data is available at this point", 0, responseHandler.available());
+ assertEquals(0, responseHandler.available(), "No more data is available at this point");
// Complete second async data first
futureDataSource2.incomingData.get(0).addLast(new ProcessorLibrary.StringData(null, "d2"));
assertEquals(
- "{\"datalist\":[" +
- "{\"data\":\"d2\"}"+
- "]}",
- responseHandler.read());
+ "{\"datalist\":[" +
+ "{\"data\":\"d2\"}" +
+ "]}",
+ responseHandler.read());
// Now complete first async data (which is therefore rendered last)
futureDataSource1.incomingData.get(0).addLast(new ProcessorLibrary.StringData(null, "d1"));
assertEquals(
- "," +
- "{\"datalist\":[" +
- "{\"data\":\"d1\"}"+
- "]}",
- responseHandler.read());
+ "," +
+ "{\"datalist\":[" +
+ "{\"data\":\"d1\"}" +
+ "]}",
+ responseHandler.read());
assertEquals(
- "]}",
- responseHandler.read());
+ "]}",
+ responseHandler.read());
- assertNull("Transmission completed", responseHandler.read());
+ assertNull(responseHandler.read(), "Transmission completed");
}
@SuppressWarnings("unchecked")
@Test
- public void testAsyncOnlyRendering() throws Exception {
+ void testAsyncOnlyRendering() throws Exception {
// Set up
ProcessorLibrary.ListenableFutureDataSource futureDataSource = new ProcessorLibrary.ListenableFutureDataSource();
Chain<Processor> chain = new Chain<>("main", List.of(futureDataSource));
driver = new ProcessingTestDriver(chain);
ProcessingTestDriver.MockResponseHandler responseHandler = driver.sendRequest("http://localhost/?chain=main");
- assertEquals("No data is available at this point", 0, responseHandler.available());
+ assertEquals(0, responseHandler.available(), "No data is available at this point");
futureDataSource.incomingData.get().add(new ProcessorLibrary.StringData(null, "d1"));
assertEquals(
- "{\"datalist\":[" +
- "{\"data\":\"d1\"}",
- responseHandler.read());
+ "{\"datalist\":[" +
+ "{\"data\":\"d1\"}",
+ responseHandler.read());
futureDataSource.incomingData.get().addLast(new ProcessorLibrary.StringData(null, "d2"));
assertEquals(
"," +
- "{\"data\":\"d2\"}" +
- "]}",
+ "{\"data\":\"d2\"}" +
+ "]}",
responseHandler.read());
assertEquals(200, responseHandler.getStatus());
- assertNull("Transmission completed", responseHandler.read());
+ assertNull(responseHandler.read(), "Transmission completed");
}
@SuppressWarnings("unchecked")
@Test
- public void testAsyncRenderingWithClientClose() throws Exception {
+ void testAsyncRenderingWithClientClose() throws Exception {
// Set up
ProcessorLibrary.ListenableFutureDataSource futureDataSource = new ProcessorLibrary.ListenableFutureDataSource();
Chain<Processor> chain = new Chain<>("main", List.of(futureDataSource));
driver = new ProcessingTestDriver(chain);
ProcessingTestDriver.MockResponseHandler responseHandler = driver.sendRequest("http://localhost/?chain=main");
- assertEquals("No data is available at this point", 0, responseHandler.available());
+ assertEquals(0, responseHandler.available(), "No data is available at this point");
futureDataSource.incomingData.get().add(new ProcessorLibrary.StringData(null, "d1"));
assertEquals(
@@ -443,24 +438,24 @@ public class ProcessingHandlerTestCase {
assertNull(responseHandler.read());
assertEquals(200, responseHandler.getStatus());
- assertNull("Transmission completed", responseHandler.read());
+ assertNull(responseHandler.read(), "Transmission completed");
}
@SuppressWarnings("unchecked")
@Test
- public void testAsyncOnlyRenderingWithAsyncPostData() throws Exception {
+ void testAsyncOnlyRenderingWithAsyncPostData() throws Exception {
// Set up
ProcessorLibrary.ListenableFutureDataSource futureDataSource = new ProcessorLibrary.ListenableFutureDataSource();
PostReader postReader = new PostReader();
Chain<Processor> chain = new Chain<>("main",
- new ProcessorLibrary.AsyncDataProcessingInitiator(new Chain<>(postReader)),
- futureDataSource);
+ new ProcessorLibrary.AsyncDataProcessingInitiator(new Chain<>(postReader)),
+ futureDataSource);
driver = new ProcessingTestDriver(chain);
RequestHandlerTestDriver.MockResponseHandler responseHandler =
driver.sendRequest("http://localhost/?chain=main", HttpRequest.Method.POST, "Hello, world!");
- assertFalse("Post data is read later, on async completion", postReader.bodyDataFuture.isDone());
- assertEquals("No data is available at this point", 0, responseHandler.available());
+ assertFalse(postReader.bodyDataFuture.isDone(), "Post data is read later, on async completion");
+ assertEquals(0, responseHandler.available(), "No data is available at this point");
futureDataSource.incomingData.get().add(new ProcessorLibrary.StringData(null, "d1"));
assertEquals(
@@ -476,10 +471,10 @@ public class ProcessingHandlerTestCase {
"]}",
responseHandler.read()
);
- assertEquals("Data is completed, so post data is read", "Hello, world!", postReader.bodyDataFuture.get().trim());
+ assertEquals("Hello, world!", postReader.bodyDataFuture.get().trim(), "Data is completed, so post data is read");
assertEquals(200, responseHandler.getStatus());
- assertNull("Transmission completed", responseHandler.read());
+ assertNull(responseHandler.read(), "Transmission completed");
}
private static class PostReader extends Processor {
@@ -506,8 +501,8 @@ public class ProcessingHandlerTestCase {
@SuppressWarnings("unchecked")
@Test
- public void testStatusAndHeadersCanBeSetAsynchronously() throws Exception {
- Map<String,List<String>> responseHeaders = new HashMap<>();
+ void testStatusAndHeadersCanBeSetAsynchronously() throws Exception {
+ Map<String, List<String>> responseHeaders = new HashMap<>();
responseHeaders.put("foo", List.of("fooValue"));
responseHeaders.put("bar", List.of("barValue", "bazValue"));
@@ -517,7 +512,7 @@ public class ProcessingHandlerTestCase {
driver = new ProcessingTestDriver(chain);
ProcessingTestDriver.MockResponseHandler responseHandler = driver.sendRequest("http://localhost/?chain=main");
- assertEquals("No data is available at this point", 0, responseHandler.available());
+ assertEquals(0, responseHandler.available(), "No data is available at this point");
com.yahoo.processing.Request request = futureDataSource.incomingData.get().getOwner().request();
futureDataSource.incomingData.get().addLast(new ProcessorLibrary.StringData(request, "d1"));
@@ -527,12 +522,12 @@ public class ProcessingHandlerTestCase {
assertEquals(500, responseHandler.getStatus());
assertEquals("[fooValue]", responseHandler.getResponse().headers().get("foo").toString());
assertEquals("[barValue, bazValue]", responseHandler.getResponse().headers().get("bar").toString());
- assertNull("Transmission completed", responseHandler.read());
+ assertNull(responseHandler.read(), "Transmission completed");
}
@SuppressWarnings("unchecked")
@Test
- public void testAsyncRenderingDoesNotHoldThreads() {
+ void testAsyncRenderingDoesNotHoldThreads() {
// Set up
ProcessorLibrary.FutureDataSource futureDataSource = new ProcessorLibrary.FutureDataSource();
// Add some sync data as well to cause rendering to start before async data is added.
@@ -545,11 +540,11 @@ public class ProcessingHandlerTestCase {
ProcessingTestDriver.MockResponseHandler[] responseHandler = new ProcessingTestDriver.MockResponseHandler[requestCount];
for (int i = 0; i < requestCount; i++) {
responseHandler[i] = driver.sendRequest("http://localhost/?chain=main");
- assertEquals("Sync data is available",
- "{\"datalist\":[{\"datalist\":[{\"data\":\"first.null\"},{\"data\":\"second.null\"},{\"data\":\"third.null\"}]}",
- responseHandler[i].read());
+ assertEquals("{\"datalist\":[{\"datalist\":[{\"data\":\"first.null\"},{\"data\":\"second.null\"},{\"data\":\"third.null\"}]}",
+ responseHandler[i].read(),
+ "Sync data is available");
}
- assertEquals("All requests was processed", requestCount, futureDataSource.incomingData.size());
+ assertEquals(requestCount, futureDataSource.incomingData.size(), "All requests was processed");
// Complete all
for (int i = 0; i < requestCount; i++) {
@@ -558,13 +553,13 @@ public class ProcessingHandlerTestCase {
futureDataSource.incomingData.get(i).addLast(new ProcessorLibrary.StringData(null, "d2"));
assertEquals(",{\"data\":\"d2\"}]}", responseHandler[i].read());
assertEquals("]}", responseHandler[i].read());
- assertNull("Transmission completed", responseHandler[i].read());
+ assertNull(responseHandler[i].read(), "Transmission completed");
}
}
@SuppressWarnings("unchecked")
@Test
- public void testStreamedRendering() throws Exception {
+ void testStreamedRendering() throws Exception {
// Set up
Chain<Processor> streamChain = new Chain<>(new StreamProcessor());
@@ -593,26 +588,27 @@ public class ProcessingHandlerTestCase {
",{\"data\":\"map data: {streamProcessed=true}\"}]}",
responseHandler.read());
- assertNull("Transmission completed", responseHandler.read());
+ assertNull(responseHandler.read(), "Transmission completed");
}
@Test
- public void testEagerStreamedRenderingOnFreeze() {
+ void testEagerStreamedRenderingOnFreeze() {
FreezingDataSource source = new FreezingDataSource();
Chain<Processor> mainChain = new Chain<>("main", source);
driver = new ProcessingTestDriver(mainChain);
ProcessingTestDriver.MockResponseHandler responseHandler = driver.sendRequest("http://localhost/?chain=main");
- assertEquals("No data is available at this point", 0, responseHandler.available());
+ assertEquals(0, responseHandler.available(), "No data is available at this point");
source.freeze.set(true);
assertEquals("{\"datalist\":[{\"data\":\"d1\"}", responseHandler.read());
source.addLastData.set(true); // signal completion
assertEquals(",{\"data\":\"d2\"}]}", responseHandler.read());
- assertNull("Transmission completed", responseHandler.read());
+ assertNull(responseHandler.read(), "Transmission completed");
}
+ // TODO
@Test
- @Ignore // TODO
- public void testNestedEagerStreamedRenderingOnFreeze() {
+ @Disabled
+ void testNestedEagerStreamedRenderingOnFreeze() {
try {
FreezingDataSource source1 = new FreezingDataSource("s1");
FreezingDataSource source2 = new FreezingDataSource("s2");
@@ -625,16 +621,15 @@ public class ProcessingHandlerTestCase {
new Chain<Processor>(source3)));
driver = new ProcessingTestDriver(mainChain);
ProcessingTestDriver.MockResponseHandler responseHandler = driver.sendRequest("http://localhost/?chain=main");
- assertEquals("No data is available at this point", 0, responseHandler.available());
+ assertEquals(0, responseHandler.available(), "No data is available at this point");
source1.freeze.set(true);
- assertEquals("Received because the parent list and source1 list is frozen",
- "{\"datalist\":[{\"datalist\":[{\"data\":\"s1d1\"}", responseHandler.read());
+ assertEquals("{\"datalist\":[{\"datalist\":[{\"data\":\"s1d1\"}", responseHandler.read(), "Received because the parent list and source1 list is frozen");
source2.addLastData.set(true); // No effect as we are working on source1, which is not completed yet
assertEquals("{\"datalist\":[{\"data\":\"s1d1\"}", responseHandler.read());
source1.addLastData.set(true); // Make source 1 and 2 available
assertEquals(",{\"data\":\"d2\"}]}", responseHandler.read());
- assertNull("Transmission completed", responseHandler.read());
+ assertNull(responseHandler.read(), "Transmission completed");
}
catch (Throwable t) {
t.printStackTrace();
@@ -642,14 +637,16 @@ public class ProcessingHandlerTestCase {
}
}
- @Test(expected = IllegalArgumentException.class)
- public void testRetrievingNonExistingRendererThrows() {
- driver = new ProcessingTestDriver(List.of());
- driver.processingHandler().getRendererCopy(ComponentSpecification.fromString("non-existent"));
+ @Test
+ void testRetrievingNonExistingRendererThrows() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ driver = new ProcessingTestDriver(List.of());
+ driver.processingHandler().getRendererCopy(ComponentSpecification.fromString("non-existent"));
+ });
}
@Test
- public void testDefaultRendererIsAddedToRegistryWhenNoneIsGivenByUser() {
+ void testDefaultRendererIsAddedToRegistryWhenNoneIsGivenByUser() {
String defaultId = AbstractProcessingHandler.DEFAULT_RENDERER_ID;
driver = new ProcessingTestDriver(List.of());
@@ -659,7 +656,7 @@ public class ProcessingHandlerTestCase {
}
@Test
- public void testUserSpecifiedDefaultRendererIsNotReplacedInRegistry() {
+ void testUserSpecifiedDefaultRendererIsNotReplacedInRegistry() {
String defaultId = AbstractProcessingHandler.DEFAULT_RENDERER_ID;
Renderer myDefaultRenderer = new ProcessingRenderer();
ComponentRegistry<Renderer> renderers = new ComponentRegistry<>();
diff --git a/container-core/src/test/java/com/yahoo/processing/processors/MockUserDatabaseClientTest.java b/container-core/src/test/java/com/yahoo/processing/processors/MockUserDatabaseClientTest.java
index 8de08189f7a..58a490b8e80 100644
--- a/container-core/src/test/java/com/yahoo/processing/processors/MockUserDatabaseClientTest.java
+++ b/container-core/src/test/java/com/yahoo/processing/processors/MockUserDatabaseClientTest.java
@@ -11,30 +11,29 @@ import com.yahoo.processing.Request;
import com.yahoo.processing.Response;
import com.yahoo.processing.execution.Execution;
import com.yahoo.processing.execution.chain.ChainRegistry;
-import org.junit.After;
-import org.junit.Test;
-import static org.junit.Assert.*;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.net.URI;
import java.util.Collection;
import java.util.Collections;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
public class MockUserDatabaseClientTest {
private TestDriver driver;
@Test
- public void testClientExampleProcessor() {
- Request request=null;
+ void testClientExampleProcessor() {
+ Request request = null;
try {
- Chain<Processor> chain = new Chain<>("default",new MockUserDatabaseClient());
+ Chain<Processor> chain = new Chain<>("default", new MockUserDatabaseClient());
setupJDisc(Collections.singletonList(chain));
request = createRequest();
Response response = Execution.createRoot(chain, 0, Execution.Environment.createEmpty()).process(request);
- MockUserDatabaseClient.User user = (MockUserDatabaseClient.User)response.data().request().properties().get("User");
+ MockUserDatabaseClient.User user = (MockUserDatabaseClient.User) response.data().request().properties().get("User");
assertNotNull(user);
assertEquals("foo", user.getId());
}
@@ -71,7 +70,7 @@ public class MockUserDatabaseClientTest {
driver.activateContainer(builder);
}
- @After
+ @AfterEach
public void shutDownDisc() {
assertTrue(driver.close());
}
diff --git a/container-core/src/test/java/com/yahoo/processing/rendering/AsynchronousSectionedRendererTest.java b/container-core/src/test/java/com/yahoo/processing/rendering/AsynchronousSectionedRendererTest.java
index 5dfe29dd4a1..fb8aca95d9a 100644
--- a/container-core/src/test/java/com/yahoo/processing/rendering/AsynchronousSectionedRendererTest.java
+++ b/container-core/src/test/java/com/yahoo/processing/rendering/AsynchronousSectionedRendererTest.java
@@ -13,7 +13,7 @@ import com.yahoo.processing.response.Data;
import com.yahoo.processing.response.DataList;
import com.yahoo.processing.response.IncomingData;
import com.yahoo.text.Utf8;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.OutputStream;
@@ -23,9 +23,7 @@ import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertSame;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Einar M R Rosenvinge
@@ -35,27 +33,27 @@ public class AsynchronousSectionedRendererTest {
private static final Charset CHARSET = Utf8.getCharset();
@Test
- public void testRenderersOfTheSamePrototypeUseTheSameExecutor() {
+ void testRenderersOfTheSamePrototypeUseTheSameExecutor() {
TestRenderer rendererPrototype = new TestRenderer();
- TestRenderer rendererCopy1 = (TestRenderer)rendererPrototype.clone();
+ TestRenderer rendererCopy1 = (TestRenderer) rendererPrototype.clone();
rendererCopy1.init();
assertSame(rendererPrototype.getRenderingExecutor(), rendererCopy1.getRenderingExecutor());
}
@Test
- public void testRenderersOfDifferentPrototypesUseDifferentExecutors() {
+ void testRenderersOfDifferentPrototypesUseDifferentExecutors() {
TestRenderer rendererPrototype1 = new TestRenderer();
- TestRenderer rendererCopy1 = (TestRenderer)rendererPrototype1.clone();
+ TestRenderer rendererCopy1 = (TestRenderer) rendererPrototype1.clone();
rendererCopy1.init();
TestRenderer rendererPrototype2 = new TestRenderer();
- TestRenderer rendererCopy2 = (TestRenderer)rendererPrototype2.clone();
+ TestRenderer rendererCopy2 = (TestRenderer) rendererPrototype2.clone();
rendererCopy2.init();
assertNotSame(rendererPrototype1.getRenderingExecutor(), rendererCopy2.getRenderingExecutor());
}
@Test
- public void testAsyncSectionedRenderer() throws IOException, InterruptedException {
+ void testAsyncSectionedRenderer() throws IOException, InterruptedException {
StringDataList dataList = createDataListWithStrangeStrings();
TestRenderer renderer = new TestRenderer();
@@ -69,7 +67,7 @@ public class AsynchronousSectionedRendererTest {
}
@Test
- public void testEmptyProcessingRendering() throws IOException, InterruptedException {
+ void testEmptyProcessingRendering() throws IOException, InterruptedException {
Request request = new Request();
DataList dataList = ArrayDataList.create(request);
@@ -77,117 +75,117 @@ public class AsynchronousSectionedRendererTest {
}
@Test
- public void testProcessingRendering() throws IOException, InterruptedException {
+ void testProcessingRendering() throws IOException, InterruptedException {
StringDataList dataList = createDataListWithStrangeStrings();
assertEquals("{\"datalist\":[" +
- "{\"data\":\"f\\\\o\\\"o\"}," +
- "{\"datalist\":[" +
- "{\"data\":\"b/a\\br\"}," +
- "{\"data\":\"f\\f\\no\\ro\\tbar\\u0005\"}" +
- "]}" +
- "]}",
+ "{\"data\":\"f\\\\o\\\"o\"}," +
+ "{\"datalist\":[" +
+ "{\"data\":\"b/a\\br\"}," +
+ "{\"data\":\"f\\f\\no\\ro\\tbar\\u0005\"}" +
+ "]}" +
+ "]}",
render(dataList));
}
@Test
- public void testProcessingRenderingWithErrors() throws IOException, InterruptedException {
+ void testProcessingRenderingWithErrors() throws IOException, InterruptedException {
StringDataList dataList = createDataList();
// Add errors
- dataList.request().errors().add(new ErrorMessage("m1","d1"));
- dataList.request().errors().add(new ErrorMessage("m2","d2"));
+ dataList.request().errors().add(new ErrorMessage("m1", "d1"));
+ dataList.request().errors().add(new ErrorMessage("m2", "d2"));
assertEquals("{\"errors\":[" +
- "\"m1: d1\"," +
- "\"m2: d2\"" +
- "]," +
- "\"datalist\":[" +
- "{\"data\":\"l1\"}," +
- "{\"datalist\":[" +
- "{\"data\":\"l11\"}," +
- "{\"data\":\"l12\"}" +
- "]}" +
- "]}",
+ "\"m1: d1\"," +
+ "\"m2: d2\"" +
+ "]," +
+ "\"datalist\":[" +
+ "{\"data\":\"l1\"}," +
+ "{\"datalist\":[" +
+ "{\"data\":\"l11\"}," +
+ "{\"data\":\"l12\"}" +
+ "]}" +
+ "]}",
render(dataList));
}
@Test
- public void testProcessingRenderingWithStackTraces() throws IOException, InterruptedException {
+ void testProcessingRenderingWithStackTraces() throws IOException, InterruptedException {
Exception exception;
// Create thrown exception
try {
throw new RuntimeException("Thrown");
}
catch (RuntimeException e) {
- exception=e;
+ exception = e;
}
StringDataList dataList = createDataList();
// Add errors
- dataList.request().errors().add(new ErrorMessage("m1","d1",exception));
- dataList.request().errors().add(new ErrorMessage("m2","d2"));
+ dataList.request().errors().add(new ErrorMessage("m1", "d1", exception));
+ dataList.request().errors().add(new ErrorMessage("m2", "d2"));
assertEquals(
"{\"errors\":[" +
- "{" +
- "\"error\":\"m1: d1: Thrown\"," +
- "\"stacktrace\":\"java.lang.RuntimeException: Thrown\\n\\tat com.yahoo.processing.rendering.AsynchronousSectionedRendererTest.",
- render(dataList).substring(0,157));
+ "{" +
+ "\"error\":\"m1: d1: Thrown\"," +
+ "\"stacktrace\":\"java.lang.RuntimeException: Thrown\\n\\tat com.yahoo.processing.rendering.AsynchronousSectionedRendererTest.",
+ render(dataList).substring(0, 157));
}
@Test
- public void testProcessingRenderingWithClonedErrorRequest() throws IOException, InterruptedException {
+ void testProcessingRenderingWithClonedErrorRequest() throws IOException, InterruptedException {
StringDataList dataList = createDataList();
// Add errors
- dataList.request().errors().add(new ErrorMessage("m1","d1"));
- dataList.request().errors().add(new ErrorMessage("m2","d2"));
+ dataList.request().errors().add(new ErrorMessage("m1", "d1"));
+ dataList.request().errors().add(new ErrorMessage("m2", "d2"));
dataList.add(new StringDataList(dataList.request().clone())); // Cloning a request which contains errors
// ... should not cause repetition of those errors
assertEquals("{\"errors\":[" +
- "\"m1: d1\"," +
- "\"m2: d2\"" +
- "]," +
- "\"datalist\":[" +
- "{\"data\":\"l1\"}," +
- "{\"datalist\":[" +
- "{\"data\":\"l11\"}," +
- "{\"data\":\"l12\"}" +
- "]}," +
- "{\"datalist\":[]}" +
- "]}",
+ "\"m1: d1\"," +
+ "\"m2: d2\"" +
+ "]," +
+ "\"datalist\":[" +
+ "{\"data\":\"l1\"}," +
+ "{\"datalist\":[" +
+ "{\"data\":\"l11\"}," +
+ "{\"data\":\"l12\"}" +
+ "]}," +
+ "{\"datalist\":[]}" +
+ "]}",
render(dataList));
}
@Test
- public void testProcessingRenderingWithClonedErrorRequestContainingNewErrors() throws IOException, InterruptedException {
+ void testProcessingRenderingWithClonedErrorRequestContainingNewErrors() throws IOException, InterruptedException {
StringDataList dataList = createDataList();
// Add errors
- dataList.request().errors().add(new ErrorMessage("m1","d1"));
- dataList.request().errors().add(new ErrorMessage("m2","d2"));
+ dataList.request().errors().add(new ErrorMessage("m1", "d1"));
+ dataList.request().errors().add(new ErrorMessage("m2", "d2"));
dataList.add(new StringDataList(dataList.request().clone())); // Cloning a request containing errors
// and adding new errors to it
- dataList.asList().get(2).request().errors().add(new ErrorMessage("m3","d3"));
+ dataList.asList().get(2).request().errors().add(new ErrorMessage("m3", "d3"));
assertEquals("{\"errors\":[" +
- "\"m1: d1\"," +
- "\"m2: d2\"" +
- "]," +
- "\"datalist\":[" +
- "{\"data\":\"l1\"}," +
- "{\"datalist\":[" +
- "{\"data\":\"l11\"}," +
- "{\"data\":\"l12\"}" +
- "]}," +
- "{\"errors\":[" +
- "\"m3: d3\"" +
- "]," +
- "\"datalist\":[]}" +
- "]}",
+ "\"m1: d1\"," +
+ "\"m2: d2\"" +
+ "]," +
+ "\"datalist\":[" +
+ "{\"data\":\"l1\"}," +
+ "{\"datalist\":[" +
+ "{\"data\":\"l11\"}," +
+ "{\"data\":\"l12\"}" +
+ "]}," +
+ "{\"errors\":[" +
+ "\"m3: d3\"" +
+ "]," +
+ "\"datalist\":[]}" +
+ "]}",
render(dataList));
}
diff --git a/container-core/src/test/java/com/yahoo/processing/request/CompoundNameTestCase.java b/container-core/src/test/java/com/yahoo/processing/request/CompoundNameTestCase.java
index a8a2c76a609..055dbf77371 100644
--- a/container-core/src/test/java/com/yahoo/processing/request/CompoundNameTestCase.java
+++ b/container-core/src/test/java/com/yahoo/processing/request/CompoundNameTestCase.java
@@ -6,12 +6,9 @@ import com.yahoo.text.Lowercase;
import java.util.Iterator;
import java.util.List;
-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.*;
/**
* Module local test of the basic property name building block.
@@ -30,23 +27,24 @@ public class CompoundNameTestCase {
void verifyStrict(String expected, CompoundName actual) {
verifyStrict(new CompoundName(expected), actual);
}
+
@Test
- public final void testLast() {
+ final void testLast() {
assertEquals(NAME.substring(NAME.lastIndexOf('.') + 1), cn.last());
}
@Test
- public final void testFirst() {
+ final void testFirst() {
assertEquals(NAME.substring(0, NAME.indexOf('.')), cn.first());
}
@Test
- public final void testRest() {
+ final void testRest() {
verifyStrict(NAME.substring(NAME.indexOf('.') + 1), cn.rest());
}
@Test
- public final void testRestN() {
+ final void testRestN() {
verifyStrict("a.b.c.d.e", new CompoundName("a.b.c.d.e").rest(0));
verifyStrict("b.c.d.e", new CompoundName("a.b.c.d.e").rest(1));
verifyStrict("c.d.e", new CompoundName("a.b.c.d.e").rest(2));
@@ -56,7 +54,7 @@ public class CompoundNameTestCase {
}
@Test
- public final void testPrefix() {
+ final void testPrefix() {
assertTrue(new CompoundName("a.b.c").hasPrefix(new CompoundName("")));
assertTrue(new CompoundName("a.b.c").hasPrefix(new CompoundName("a")));
assertTrue(new CompoundName("a.b.c").hasPrefix(new CompoundName("a.b")));
@@ -67,13 +65,13 @@ public class CompoundNameTestCase {
}
@Test
- public void testFromComponents() {
+ void testFromComponents() {
verifyStrict("a", CompoundName.fromComponents("a"));
verifyStrict("a.b", CompoundName.fromComponents("a", "b"));
}
@Test
- public final void testSize() {
+ final void testSize() {
Splitter s = Splitter.on('.');
Iterable<String> i = s.split(NAME);
int n = 0;
@@ -84,23 +82,23 @@ public class CompoundNameTestCase {
}
@Test
- public final void testGet() {
+ final void testGet() {
String s = cn.get(0);
assertEquals(NAME.substring(0, NAME.indexOf('.')), s);
}
@Test
- public final void testIsCompound() {
+ final void testIsCompound() {
assertTrue(cn.isCompound());
}
@Test
- public final void testIsEmpty() {
+ final void testIsEmpty() {
assertFalse(cn.isEmpty());
}
@Test
- public final void testAsList() {
+ final void testAsList() {
List<String> l = cn.asList();
Splitter peoplesFront = Splitter.on('.');
Iterable<String> answer = peoplesFront.split(NAME);
@@ -112,15 +110,15 @@ public class CompoundNameTestCase {
}
@Test
- public final void testEqualsObject() {
- assertFalse(cn.equals(NAME));
- assertFalse(cn.equals(null));
+ final void testEqualsObject() {
+ assertNotEquals(cn, NAME);
+ assertNotEquals(cn, null);
verifyStrict(cn, cn);
verifyStrict(cn, new CompoundName(NAME));
}
@Test
- public final void testEmptyNonEmpty() {
+ final void testEmptyNonEmpty() {
assertTrue(new CompoundName("").isEmpty());
assertEquals(0, new CompoundName("").size());
assertFalse(new CompoundName("a").isEmpty());
@@ -131,12 +129,12 @@ public class CompoundNameTestCase {
}
@Test
- public final void testGetLowerCasedName() {
+ final void testGetLowerCasedName() {
assertEquals(Lowercase.toLowerCase(NAME), cn.getLowerCasedName());
}
@Test
- public void testAppendCompound() {
+ void testAppendCompound() {
verifyStrict("a.b.c.d", new CompoundName("").append(new CompoundName("a.b.c.d")));
verifyStrict("a.b.c.d", new CompoundName("a").append(new CompoundName("b.c.d")));
verifyStrict("a.b.c.d", new CompoundName("a.b").append(new CompoundName("c.d")));
@@ -145,7 +143,7 @@ public class CompoundNameTestCase {
}
@Test
- public void empty_CompoundName_is_prefix_of_any_CompoundName() {
+ void empty_CompoundName_is_prefix_of_any_CompoundName() {
CompoundName empty = new CompoundName("");
assertTrue(empty.hasPrefix(empty));
@@ -153,7 +151,7 @@ public class CompoundNameTestCase {
}
@Test
- public void whole_components_must_match_to_be_prefix() {
+ void whole_components_must_match_to_be_prefix() {
CompoundName stringPrefix = new CompoundName("a");
CompoundName name = new CompoundName("aa");
@@ -161,28 +159,28 @@ public class CompoundNameTestCase {
}
@Test
- public void testFirstRest() {
+ void testFirstRest() {
verifyStrict(CompoundName.empty, CompoundName.empty.rest());
- CompoundName n=new CompoundName("on.two.three");
+ CompoundName n = new CompoundName("on.two.three");
assertEquals("on", n.first());
verifyStrict("two.three", n.rest());
- n=n.rest();
+ n = n.rest();
assertEquals("two", n.first());
verifyStrict("three", n.rest());
- n=n.rest();
+ n = n.rest();
assertEquals("three", n.first());
verifyStrict("", n.rest());
- n=n.rest();
+ n = n.rest();
assertEquals("", n.first());
verifyStrict("", n.rest());
- n=n.rest();
+ n = n.rest();
assertEquals("", n.first());
verifyStrict("", n.rest());
}
@Test
- public void testHashCodeAndEquals() {
+ void testHashCodeAndEquals() {
CompoundName n1 = new CompoundName("venn.d.a");
CompoundName n2 = new CompoundName(n1.asList());
assertEquals(n1.hashCode(), n2.hashCode());
@@ -190,7 +188,7 @@ public class CompoundNameTestCase {
}
@Test
- public void testAppendString() {
+ void testAppendString() {
verifyStrict("a", new CompoundName("a").append(""));
verifyStrict("a", new CompoundName("").append("a"));
verifyStrict("a.b", new CompoundName("a").append("b"));
@@ -203,14 +201,14 @@ public class CompoundNameTestCase {
}
@Test
- public void testEmpty() {
- CompoundName empty=new CompoundName("");
+ void testEmpty() {
+ CompoundName empty = new CompoundName("");
assertEquals("", empty.toString());
assertEquals(0, empty.asList().size());
}
@Test
- public void testAsList2() {
+ void testAsList2() {
assertEquals("[one]", new CompoundName("one").asList().toString());
assertEquals("[one, two, three]", new CompoundName("one.two.three").asList().toString());
}
diff --git a/container-core/src/test/java/com/yahoo/processing/request/test/ErrorMessageTestCase.java b/container-core/src/test/java/com/yahoo/processing/request/test/ErrorMessageTestCase.java
index fd152dccb96..1d4208fd356 100644
--- a/container-core/src/test/java/com/yahoo/processing/request/test/ErrorMessageTestCase.java
+++ b/container-core/src/test/java/com/yahoo/processing/request/test/ErrorMessageTestCase.java
@@ -2,10 +2,10 @@
package com.yahoo.processing.request.test;
import com.yahoo.processing.request.ErrorMessage;
-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 bratseth
@@ -13,49 +13,49 @@ import static org.junit.Assert.assertNotEquals;
public class ErrorMessageTestCase {
@Test
- public void testToString() {
- assertEquals("message",new ErrorMessage("message").toString());
- assertEquals("message: hello",new ErrorMessage("message",new Exception("hello")).toString());
- assertEquals("message: detail",new ErrorMessage("message","detail").toString());
- assertEquals("37: message: detail",new ErrorMessage(37,"message","detail").toString());
- assertEquals("message: detail: hello",new ErrorMessage("message","detail",new Exception("hello")).toString());
- assertEquals("message: detail: hello: world",new ErrorMessage("message","detail",new Exception("hello",new Exception("world"))).toString());
- assertEquals("message: detail: hello: Exception",new ErrorMessage("message","detail",new Exception("hello",new Exception())).toString());
- assertEquals("message: detail: hello",new ErrorMessage("message","detail",new Exception(new Exception("hello"))).toString());
- assertEquals("message: detail: java.lang.Exception: Exception",new ErrorMessage("message","detail",new Exception(new Exception())).toString());
+ void testToString() {
+ assertEquals("message", new ErrorMessage("message").toString());
+ assertEquals("message: hello", new ErrorMessage("message", new Exception("hello")).toString());
+ assertEquals("message: detail", new ErrorMessage("message", "detail").toString());
+ assertEquals("37: message: detail", new ErrorMessage(37, "message", "detail").toString());
+ assertEquals("message: detail: hello", new ErrorMessage("message", "detail", new Exception("hello")).toString());
+ assertEquals("message: detail: hello: world", new ErrorMessage("message", "detail", new Exception("hello", new Exception("world"))).toString());
+ assertEquals("message: detail: hello: Exception", new ErrorMessage("message", "detail", new Exception("hello", new Exception())).toString());
+ assertEquals("message: detail: hello", new ErrorMessage("message", "detail", new Exception(new Exception("hello"))).toString());
+ assertEquals("message: detail: java.lang.Exception: Exception", new ErrorMessage("message", "detail", new Exception(new Exception())).toString());
}
@Test
- public void testAccessors() {
- ErrorMessage m = new ErrorMessage(37,"message","detail",new Exception("hello"));
- assertEquals(37,m.getCode());
- assertEquals("message",m.getMessage());
- assertEquals("detail",m.getDetailedMessage());
- assertEquals("hello",m.getCause().getMessage());
+ void testAccessors() {
+ ErrorMessage m = new ErrorMessage(37, "message", "detail", new Exception("hello"));
+ assertEquals(37, m.getCode());
+ assertEquals("message", m.getMessage());
+ assertEquals("detail", m.getDetailedMessage());
+ assertEquals("hello", m.getCause().getMessage());
}
@Test
- public void testEquality() {
- assertEquals(new ErrorMessage(37,"message","detail",new Exception("hello")),
- new ErrorMessage(37,"message","detail",new Exception("hello")));
- assertEquals(new ErrorMessage("message","detail",new Exception("hello")),
- new ErrorMessage("message","detail",new Exception("hello")));
- assertEquals(new ErrorMessage("message",new Exception("hello")),
- new ErrorMessage("message",new Exception("hello")));
+ void testEquality() {
+ assertEquals(new ErrorMessage(37, "message", "detail", new Exception("hello")),
+ new ErrorMessage(37, "message", "detail", new Exception("hello")));
+ assertEquals(new ErrorMessage("message", "detail", new Exception("hello")),
+ new ErrorMessage("message", "detail", new Exception("hello")));
+ assertEquals(new ErrorMessage("message", new Exception("hello")),
+ new ErrorMessage("message", new Exception("hello")));
assertEquals(new ErrorMessage("message"),
- new ErrorMessage("message"));
- assertEquals(new ErrorMessage("message",new Exception()),
- new ErrorMessage("message"));
+ new ErrorMessage("message"));
+ assertEquals(new ErrorMessage("message", new Exception()),
+ new ErrorMessage("message"));
assertNotEquals(new ErrorMessage("message"),
- new ErrorMessage("message","detail"));
- assertNotEquals(new ErrorMessage(37,"message"),
- new ErrorMessage("message"));
- assertNotEquals(new ErrorMessage(37,"message"),
- new ErrorMessage(38,"message"));
- assertNotEquals(new ErrorMessage("message","detail1"),
- new ErrorMessage("message","detail2"));
+ new ErrorMessage("message", "detail"));
+ assertNotEquals(new ErrorMessage(37, "message"),
+ new ErrorMessage("message"));
+ assertNotEquals(new ErrorMessage(37, "message"),
+ new ErrorMessage(38, "message"));
+ assertNotEquals(new ErrorMessage("message", "detail1"),
+ new ErrorMessage("message", "detail2"));
assertNotEquals(new ErrorMessage("message1"),
- new ErrorMessage("message2"));
+ new ErrorMessage("message2"));
}
}
diff --git a/container-core/src/test/java/com/yahoo/processing/request/test/PropertyMapTestCase.java b/container-core/src/test/java/com/yahoo/processing/request/test/PropertyMapTestCase.java
index 5d7d1e63b21..de5437ab658 100644
--- a/container-core/src/test/java/com/yahoo/processing/request/test/PropertyMapTestCase.java
+++ b/container-core/src/test/java/com/yahoo/processing/request/test/PropertyMapTestCase.java
@@ -3,15 +3,13 @@ package com.yahoo.processing.request.test;
import com.yahoo.processing.request.properties.PropertyMap;
import com.yahoo.processing.request.properties.PublicCloneable;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -19,40 +17,40 @@ import static org.junit.Assert.assertTrue;
public class PropertyMapTestCase {
@Test
- public void testObjectCloning() {
+ void testObjectCloning() {
PropertyMap map = new PropertyMap();
map.set("clonable", new ClonableObject());
map.set("publicClonable", new PublicClonableObject());
map.set("nonclonable", new NonClonableObject());
- map.set("clonableArray", new ClonableObject[] {new ClonableObject()});
- map.set("publicClonableArray", new ClonableObject[] {new ClonableObject()});
- map.set("nonclonableArray", new NonClonableObject[] {new NonClonableObject()});
+ map.set("clonableArray", new ClonableObject[]{new ClonableObject()});
+ map.set("publicClonableArray", new ClonableObject[]{new ClonableObject()});
+ map.set("nonclonableArray", new NonClonableObject[]{new NonClonableObject()});
map.set("clonableList", Collections.singletonList(new ClonableObject()));
map.set("nonclonableList", Collections.singletonList(new NonClonableObject()));
assertNotNull(map.get("clonable"));
assertNotNull(map.get("nonclonable"));
- PropertyMap mapClone=map.clone();
+ PropertyMap mapClone = map.clone();
assertTrue(map.get("clonable") != mapClone.get("clonable"));
- assertTrue(map.get("publicClonable")!= mapClone.get("publicClonable"));
- assertTrue(map.get("nonclonable") == mapClone.get("nonclonable"));
+ assertTrue(map.get("publicClonable") != mapClone.get("publicClonable"));
+ assertEquals(map.get("nonclonable"), mapClone.get("nonclonable"));
assertTrue(map.get("clonableArray") != mapClone.get("clonableArray"));
assertTrue(first(map.get("clonableArray")) != first(mapClone.get("clonableArray")));
assertTrue(map.get("publicClonableArray") != mapClone.get("publicClonableArray"));
assertTrue(first(map.get("publicClonableArray")) != first(mapClone.get("publicClonableArray")));
- assertTrue(first(map.get("nonclonableArray")) == first(mapClone.get("nonclonableArray")));
+ assertEquals(first(map.get("nonclonableArray")), first(mapClone.get("nonclonableArray")));
}
-
+
@Test
- public void testArrayCloning() {
+ void testArrayCloning() {
PropertyMap map = new PropertyMap();
- byte[] byteArray = new byte[] {2, 4, 7};
+ byte[] byteArray = new byte[]{2, 4, 7};
map.set("byteArray", byteArray);
PropertyMap mapClone = map.clone();
- assertArrayEquals(byteArray, (byte[])mapClone.get("byteArray"));
- assertTrue("Array was cloned", mapClone.get("byteArray") != byteArray);
+ assertArrayEquals(byteArray, (byte[]) mapClone.get("byteArray"));
+ assertTrue(mapClone.get("byteArray") != byteArray, "Array was cloned");
}
private Object first(Object object) {
diff --git a/container-core/src/test/java/com/yahoo/processing/request/test/RequestTestCase.java b/container-core/src/test/java/com/yahoo/processing/request/test/RequestTestCase.java
index a791c535b5d..c82b85d84d9 100644
--- a/container-core/src/test/java/com/yahoo/processing/request/test/RequestTestCase.java
+++ b/container-core/src/test/java/com/yahoo/processing/request/test/RequestTestCase.java
@@ -6,10 +6,10 @@ import com.yahoo.processing.request.CompoundName;
import com.yahoo.processing.request.ErrorMessage;
import com.yahoo.processing.request.Properties;
import com.yahoo.processing.request.properties.PropertyMap;
-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;
/**
* Tests using requests
@@ -21,7 +21,7 @@ public class RequestTestCase {
private static final double delta = 0.0000000001;
@Test
- public void testProperties() {
+ void testProperties() {
Properties p = new PropertyMap();
p.set("a", "a1");
Request r = new Request(p);
@@ -39,52 +39,52 @@ public class RequestTestCase {
assertNull(r.properties().get(new CompoundName("c")));
assertEquals("b1", r.properties().getString("b"));
- assertEquals("b1", r.properties().getString("b","default"));
- assertEquals("default", r.properties().getString("c","default"));
- assertEquals(null, r.properties().getString("c"));
+ assertEquals("b1", r.properties().getString("b", "default"));
+ assertEquals("default", r.properties().getString("c", "default"));
+ assertNull(r.properties().getString("c"));
assertEquals("b1", r.properties().getString(new CompoundName("b")));
- assertEquals("b1", r.properties().getString(new CompoundName("b"),"default"));
- assertEquals("default", r.properties().getString(new CompoundName("c"),"default"));
- assertEquals(null, r.properties().getString(new CompoundName("c")));
-
- r.properties().set("i",7);
- assertEquals(7, (int)r.properties().getInteger("i"));
- assertEquals(7, (int)r.properties().getInteger("i",3));
- assertEquals(3, (int)r.properties().getInteger("n",3));
+ assertEquals("b1", r.properties().getString(new CompoundName("b"), "default"));
+ assertEquals("default", r.properties().getString(new CompoundName("c"), "default"));
+ assertNull(r.properties().getString(new CompoundName("c")));
+
+ r.properties().set("i", 7);
+ assertEquals(7, (int) r.properties().getInteger("i"));
+ assertEquals(7, (int) r.properties().getInteger("i", 3));
+ assertEquals(3, (int) r.properties().getInteger("n", 3));
assertNull(r.properties().getInteger("n"));
- assertEquals(7, (int)r.properties().getInteger(new CompoundName("i")));
- assertEquals(7, (int)r.properties().getInteger(new CompoundName("i"),3));
- assertEquals(3, (int)r.properties().getInteger(new CompoundName("n"),3));
+ assertEquals(7, (int) r.properties().getInteger(new CompoundName("i")));
+ assertEquals(7, (int) r.properties().getInteger(new CompoundName("i"), 3));
+ assertEquals(3, (int) r.properties().getInteger(new CompoundName("n"), 3));
assertNull(r.properties().getInteger("n"));
r.properties().set(new CompoundName("l"), 7);
assertEquals(7, (long) r.properties().getLong("l"));
- assertEquals(7, (long)r.properties().getLong("l",3l));
- assertEquals(3, (long)r.properties().getLong("m",3l));
+ assertEquals(7, (long) r.properties().getLong("l", 3l));
+ assertEquals(3, (long) r.properties().getLong("m", 3l));
assertNull(r.properties().getInteger("m"));
- assertEquals(7, (long)r.properties().getLong(new CompoundName("l")));
- assertEquals(7, (long)r.properties().getLong(new CompoundName("l"),3l));
- assertEquals(3, (long)r.properties().getLong(new CompoundName("m"),3l));
+ assertEquals(7, (long) r.properties().getLong(new CompoundName("l")));
+ assertEquals(7, (long) r.properties().getLong(new CompoundName("l"), 3l));
+ assertEquals(3, (long) r.properties().getLong(new CompoundName("m"), 3l));
assertNull(r.properties().getInteger("m"));
r.properties().set("d", 7.3);
assertEquals(7.3, r.properties().getDouble("d"), delta);
- assertEquals(7.3, r.properties().getDouble("d",3.4d), delta);
- assertEquals(3.4, r.properties().getDouble("f",3.4d), delta);
+ assertEquals(7.3, r.properties().getDouble("d", 3.4d), delta);
+ assertEquals(3.4, r.properties().getDouble("f", 3.4d), delta);
assertNull(r.properties().getDouble("f"));
assertEquals(7.3, r.properties().getDouble(new CompoundName("d")), delta);
- assertEquals(7.3, r.properties().getDouble(new CompoundName("d"),3.4d), delta);
- assertEquals(3.4, r.properties().getDouble(new CompoundName("f"),3.4d), delta);
+ assertEquals(7.3, r.properties().getDouble(new CompoundName("d"), 3.4d), delta);
+ assertEquals(3.4, r.properties().getDouble(new CompoundName("f"), 3.4d), delta);
assertNull(r.properties().getDouble("f"));
- r.properties().set("o",true);
+ r.properties().set("o", true);
assertEquals(true, r.properties().getBoolean("o"));
- assertEquals(true, r.properties().getBoolean("o",true));
- assertEquals(true, r.properties().getBoolean("g",true));
+ assertEquals(true, r.properties().getBoolean("o", true));
+ assertEquals(true, r.properties().getBoolean("g", true));
assertEquals(false, r.properties().getBoolean("g"));
assertEquals(true, r.properties().getBoolean(new CompoundName("o")));
- assertEquals(true, r.properties().getBoolean(new CompoundName("o"),true));
- assertEquals(true, r.properties().getBoolean(new CompoundName("g"),true));
+ assertEquals(true, r.properties().getBoolean(new CompoundName("o"), true));
+ assertEquals(true, r.properties().getBoolean(new CompoundName("g"), true));
assertEquals(false, r.properties().getBoolean("g"));
r.properties().set(new CompoundName("x.y"), "x1.y1");
@@ -99,20 +99,20 @@ public class RequestTestCase {
}
@Test
- public void testErrorMessages() {
+ void testErrorMessages() {
Request r = new Request();
r.errors().add(new ErrorMessage("foo"));
r.errors().add(new ErrorMessage("bar"));
- assertEquals(2,r.errors().size());
+ assertEquals(2, r.errors().size());
assertEquals("foo", r.errors().get(0).getMessage());
assertEquals("bar", r.errors().get(1).getMessage());
}
@Test
- public void testCloning() {
+ void testCloning() {
Request request = new Request();
- request.properties().set("a","a1");
- request.properties().set("b","b1");
+ request.properties().set("a", "a1");
+ request.properties().set("b", "b1");
request.errors().add(new ErrorMessage("foo"));
request.errors().add(new ErrorMessage("bar"));
Request rcloned = request.clone();
@@ -125,17 +125,17 @@ public class RequestTestCase {
assertEquals("a1", rcloned.properties().get("a"));
assertEquals("b1", request.properties().get("b"));
assertEquals("b1", rcloned.properties().get("b"));
- assertEquals(null, request.properties().get("c"));
+ assertNull(request.properties().get("c"));
assertEquals("c1", rcloned.properties().get("c"));
assertEquals("d1", request.properties().get("d"));
- assertEquals(null, rcloned.properties().get("d"));
+ assertNull(rcloned.properties().get("d"));
assertEquals(3, request.errors().size());
assertEquals(1, rcloned.errors().size());
- assertEquals("foo",request.errors().get(0).getMessage());
- assertEquals("bar",request.errors().get(1).getMessage());
- assertEquals("boz",request.errors().get(2).getMessage());
- assertEquals("baz",rcloned.errors().get(0).getMessage());
+ assertEquals("foo", request.errors().get(0).getMessage());
+ assertEquals("bar", request.errors().get(1).getMessage());
+ assertEquals("boz", request.errors().get(2).getMessage());
+ assertEquals("baz", rcloned.errors().get(0).getMessage());
}
}
diff --git a/container-core/src/test/java/com/yahoo/processing/test/DocumentationTestCase.java b/container-core/src/test/java/com/yahoo/processing/test/DocumentationTestCase.java
index 2028d39f973..8716b858696 100644
--- a/container-core/src/test/java/com/yahoo/processing/test/DocumentationTestCase.java
+++ b/container-core/src/test/java/com/yahoo/processing/test/DocumentationTestCase.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.processing.test;
-import static org.junit.Assert.*;
-
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.yahoo.component.chain.Chain;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
import com.yahoo.processing.Processor;
import com.yahoo.processing.Request;
import com.yahoo.processing.Response;
@@ -24,7 +23,7 @@ public class DocumentationTestCase {
@SuppressWarnings("unchecked")
@Test
- public final void test() {
+ final void test() {
Processor p = new ExampleProcessor();
Chain<Processor> basic = new Chain<>(p);
Processor initiator = new AsyncDataProcessingInitiator(basic);
diff --git a/container-core/src/test/java/com/yahoo/processing/test/ProcessingTestCase.java b/container-core/src/test/java/com/yahoo/processing/test/ProcessingTestCase.java
index 3f11663a1d7..da1b406927f 100644
--- a/container-core/src/test/java/com/yahoo/processing/test/ProcessingTestCase.java
+++ b/container-core/src/test/java/com/yahoo/processing/test/ProcessingTestCase.java
@@ -6,10 +6,10 @@ import com.yahoo.processing.Processor;
import com.yahoo.processing.Request;
import com.yahoo.processing.Response;
import com.yahoo.processing.execution.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static com.yahoo.processing.test.ProcessorLibrary.*;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Tests the basic of the processing framework
@@ -18,43 +18,43 @@ public class ProcessingTestCase {
/** Execute three simple processors doing some phony processing */
@Test
- public void testChainedProcessing1() {
+ void testChainedProcessing1() {
// Create a chain
- Chain<Processor> chain=new Chain<>(new CombineData(),new Get6DataItems(), new DataSource());
+ Chain<Processor> chain = new Chain<>(new CombineData(), new Get6DataItems(), new DataSource());
// Execute it
- Request request=new Request();
- request.properties().set("appendage",1);
- Response response=Execution.createRoot(chain,0,Execution.Environment.createEmpty()).process(request);
+ Request request = new Request();
+ request.properties().set("appendage", 1);
+ Response response = Execution.createRoot(chain, 0, Execution.Environment.createEmpty()).process(request);
// Verify the result
- assertEquals(6-1,response.data().asList().size());
- assertEquals("first.2, third.2",response.data().get(0).toString());
- assertEquals("second.2",response.data().get(1).toString());
- assertEquals("first.3",response.data().get(2).toString());
- assertEquals("second.3",response.data().get(3).toString());
- assertEquals("third.3",response.data().get(4).toString());
+ assertEquals(6 - 1, response.data().asList().size());
+ assertEquals("first.2, third.2", response.data().get(0).toString());
+ assertEquals("second.2", response.data().get(1).toString());
+ assertEquals("first.3", response.data().get(2).toString());
+ assertEquals("second.3", response.data().get(3).toString());
+ assertEquals("third.3", response.data().get(4).toString());
}
/** Execute the same processors in a different order */
@Test
- public void testChainedProcessing2() {
+ void testChainedProcessing2() {
// Create a chain
- Chain<Processor> chain=new Chain<>(new Get6DataItems(),new CombineData(), new DataSource());
+ Chain<Processor> chain = new Chain<>(new Get6DataItems(), new CombineData(), new DataSource());
// Execute it
- Request request=new Request();
- request.properties().set("appendage",1);
- Response response=Execution.createRoot(chain,0,Execution.Environment.createEmpty()).process(request);
+ Request request = new Request();
+ request.properties().set("appendage", 1);
+ Response response = Execution.createRoot(chain, 0, Execution.Environment.createEmpty()).process(request);
// Check the result
- assertEquals(6,response.data().asList().size());
- assertEquals("first.2, third.2",response.data().get(0).toString());
- assertEquals("second.2",response.data().get(1).toString());
- assertEquals("first.4, third.4",response.data().get(2).toString());
- assertEquals("second.4",response.data().get(3).toString());
- assertEquals("first.6, third.6",response.data().get(4).toString());
- assertEquals("second.6",response.data().get(5).toString());
+ assertEquals(6, response.data().asList().size());
+ assertEquals("first.2, third.2", response.data().get(0).toString());
+ assertEquals("second.2", response.data().get(1).toString());
+ assertEquals("first.4, third.4", response.data().get(2).toString());
+ assertEquals("second.4", response.data().get(3).toString());
+ assertEquals("first.6, third.6", response.data().get(4).toString());
+ assertEquals("second.6", response.data().get(5).toString());
}
}
diff --git a/container-core/src/test/java/com/yahoo/restapi/PathTest.java b/container-core/src/test/java/com/yahoo/restapi/PathTest.java
index b0392c16e2e..60d4f3b9831 100644
--- a/container-core/src/test/java/com/yahoo/restapi/PathTest.java
+++ b/container-core/src/test/java/com/yahoo/restapi/PathTest.java
@@ -1,16 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.restapi;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.util.List;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertThrows;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -18,7 +14,7 @@ import static org.junit.Assert.fail;
public class PathTest {
@Test
- public void testPath() {
+ void testPath() {
assertFalse(new Path(URI.create("")).matches("/a/{foo}/bar/{b}"));
assertFalse(new Path(URI.create("///")).matches("/a/{foo}/bar/{b}"));
assertFalse(new Path(URI.create("///foo")).matches("/a/{foo}/bar/{b}"));
@@ -30,7 +26,7 @@ public class PathTest {
}
@Test
- public void testPathWithRest() {
+ void testPathWithRest() {
{
Path path = new Path(URI.create("/a/1/bar/fuz/"));
assertTrue(path.matches("/a/{foo}/bar/{b}/{*}"));
@@ -65,21 +61,23 @@ public class PathTest {
}
@Test
- public void testUrlEncodedPath() {
+ void testUrlEncodedPath() {
assertTrue(new Path(URI.create("/a/%62/c")).matches("/a/b/c"));
- assertFalse(new Path(URI.create("/a/b%2fc"), __ -> { }).matches("/a/b/c"));
+ assertFalse(new Path(URI.create("/a/b%2fc"), __ -> {
+ }).matches("/a/b/c"));
assertEquals("path segments cannot be \"\", \".\", or \"..\", but got: '..'",
- assertThrows(IllegalArgumentException.class,
- () -> new Path(URI.create("/foo")).matches("/foo/bar/%2e%2e")).getMessage());
+ assertThrows(IllegalArgumentException.class,
+ () -> new Path(URI.create("/foo")).matches("/foo/bar/%2e%2e")).getMessage());
- Path path = new Path(URI.create("/%61/%2f/%63"), __ -> { });
+ Path path = new Path(URI.create("/%61/%2f/%63"), __ -> {
+ });
assertTrue(path.matches("/a/{slash}/{c}"));
assertEquals("/", path.get("slash"));
assertEquals("c", path.get("c"));
}
@Test
- public void testInvalidPaths() {
+ void testInvalidPaths() {
assertInvalid(URI.create("/foo/../bar"));
assertInvalid(URI.create("/foo/%2e%2e/bar"));
assertInvalidPathSpec(URI.create("/foo/bar"), "/foo/bar/..");
diff --git a/container-dependency-versions/pom.xml b/container-dependency-versions/pom.xml
index 709f9dc333a..695ee72df5c 100644
--- a/container-dependency-versions/pom.xml
+++ b/container-dependency-versions/pom.xml
@@ -242,7 +242,6 @@
<javax.servlet-api.version>3.1.0</javax.servlet-api.version>
<javax.ws.rs-api.version>2.0.1</javax.ws.rs-api.version>
<jaxb.version>2.3.0</jaxb.version>
- <org.json.version>20090211</org.json.version>
<slf4j.version>1.7.32</slf4j.version> <!-- WARNING: when updated, also update c.y.v.tenant:base pom -->
<xml-apis.version>1.4.01</xml-apis.version>
diff --git a/container-disc/pom.xml b/container-disc/pom.xml
index 3e42b924ec6..273270b208b 100644
--- a/container-disc/pom.xml
+++ b/container-disc/pom.xml
@@ -16,25 +16,29 @@
<packaging>container-plugin</packaging>
<dependencies>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
- <groupId>org.junit.vintage</groupId>
- <artifactId>junit-vintage-engine</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>com.yahoo.vespa</groupId>
<artifactId>testutil</artifactId>
<version>${project.version}</version>
<scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-core</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-library</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
@@ -185,26 +189,16 @@
<discApplicationClass>com.yahoo.container.jdisc.ConfiguredApplication</discApplicationClass>
<buildLegacyVespaPlatformBundle>true</buildLegacyVespaPlatformBundle>
<discPreInstallBundle>
- <!-- Vespa bundles -->
+ <!-- BEGIN Bundles needed to retrieve config, or used by container-disc -->
config-bundle-jar-with-dependencies.jar,
configdefinitions-jar-with-dependencies.jar,
hosted-zone-api-jar-with-dependencies.jar,
- jdisc-security-filters-jar-with-dependencies.jar,
- vespa-athenz-jar-with-dependencies.jar,
-
- <!-- Apache http client repackaged as bundle -->
container-apache-http-client-bundle-jar-with-dependencies.jar,
-
- <!-- Vespa security utils with necessary 3rd party bundles -->
security-utils.jar,
- bcpkix-jdk15on-${bouncycastle.version}.jar,
- bcprov-jdk15on-${bouncycastle.version}.jar,
-
- <!-- TODO Vespa 9 Stop providing servlet-api 3.x -->
- javax.servlet-api-3.1.0.jar,
+ bcprov-jdk15on-${bouncycastle.version}.jar, <!-- Used by security-utils -->
+ <!-- END Bundles needed to retrieve config, or used by container-disc -->
- <!-- Aries SPIFly repackaged -->
- container-spifly.jar,
+ bcpkix-jdk15on-${bouncycastle.version}.jar, <!-- Used by security-utils -->
jackson-annotations-${jackson2.version}.jar,
jackson-core-${jackson2.version}.jar,
diff --git a/container-disc/src/main/java/com/yahoo/container/jdisc/metric/MetricUpdater.java b/container-disc/src/main/java/com/yahoo/container/jdisc/metric/MetricUpdater.java
index 4b75bc233d6..3f7990288f5 100644
--- a/container-disc/src/main/java/com/yahoo/container/jdisc/metric/MetricUpdater.java
+++ b/container-disc/src/main/java/com/yahoo/container/jdisc/metric/MetricUpdater.java
@@ -9,6 +9,7 @@ import com.yahoo.nativec.NativeHeap;
import java.lang.management.BufferPoolMXBean;
import java.lang.management.ManagementFactory;
+import java.lang.management.ThreadMXBean;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -39,6 +40,7 @@ public class MetricUpdater extends AbstractComponent {
private static final String DIRECT_COUNT = "mem.direct.count";
private static final String MEMORY_MAPPINGS_COUNT = "jdisc.memory_mappings";
private static final String OPEN_FILE_DESCRIPTORS = "jdisc.open_file_descriptors";
+ private static final String TOTAL_THREADS = "jdisc.threads.total";
private final Scheduler scheduler;
@@ -99,6 +101,7 @@ public class MetricUpdater extends AbstractComponent {
private final ContainerWatchdogMetrics containerWatchdogMetrics;
private final GarbageCollectionMetrics garbageCollectionMetrics;
private final JrtMetrics jrtMetrics;
+ private final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
public UpdaterTask(Metric metric, ContainerWatchdogMetrics containerWatchdogMetrics) {
this.metric = metric;
@@ -148,6 +151,7 @@ public class MetricUpdater extends AbstractComponent {
metric.set(HEAP_TOTAL_MEMORY_BYTES, totalMemory, null);
metric.set(MEMORY_MAPPINGS_COUNT, count_mappings(), null);
metric.set(OPEN_FILE_DESCRIPTORS, count_open_files(), null);
+ metric.set(TOTAL_THREADS, threadMXBean.getThreadCount(), null);
directMemoryUsed();
nativeHeapUsed();
diff --git a/container-disc/src/test/java/com/yahoo/container/handler/observability/ApplicationStatusHandlerTest.java b/container-disc/src/test/java/com/yahoo/container/handler/observability/ApplicationStatusHandlerTest.java
index 4c58a943199..30c31a64a29 100644
--- a/container-disc/src/test/java/com/yahoo/container/handler/observability/ApplicationStatusHandlerTest.java
+++ b/container-disc/src/test/java/com/yahoo/container/handler/observability/ApplicationStatusHandlerTest.java
@@ -12,13 +12,13 @@ import com.yahoo.processing.Request;
import com.yahoo.processing.Response;
import com.yahoo.processing.execution.Execution;
import com.yahoo.processing.execution.chain.ChainRegistry;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.util.HashMap;
import static com.yahoo.container.jdisc.JdiscBindingsConfig.Handlers;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author gjoranv
@@ -26,7 +26,7 @@ import static org.junit.Assert.assertTrue;
public class ApplicationStatusHandlerTest {
@Test
- public void application_configs_are_rendered() {
+ void application_configs_are_rendered() {
ApplicationMetadataConfig metaConfig = new ApplicationMetadataConfig(
new ApplicationMetadataConfig.Builder()
.checksum("abc")
@@ -52,7 +52,7 @@ public class ApplicationStatusHandlerTest {
}
@Test
- public void object_components_are_rendered() {
+ void object_components_are_rendered() {
HashMap<ComponentId, Object> id2object = new HashMap<>();
id2object.put(new ComponentId("myComponent"), new Object());
@@ -61,7 +61,7 @@ public class ApplicationStatusHandlerTest {
}
@Test
- public void request_handlers_are_rendered() {
+ void request_handlers_are_rendered() {
final String id = "myHandler";
final String serverBinding1 = "http://*/serverBinding";
final String serverBinding2 = "http://*/anotherServerBinding";
@@ -84,7 +84,7 @@ public class ApplicationStatusHandlerTest {
}
@Test
- public void client_providers_are_rendered() {
+ void client_providers_are_rendered() {
final String id = "myClient";
final String clientBinding = "http://*/clientBinding";
final String clientBinding2 = "http://*/anotherClientBinding";
@@ -108,7 +108,7 @@ public class ApplicationStatusHandlerTest {
}
@Test
- public void chains_are_rendered() {
+ void chains_are_rendered() {
ChainRegistry<Processor> chains = new ChainRegistry<>();
Chain<Processor> chain = new Chain<>("myChain", new VoidProcessor(new ComponentId("voidProcessor")));
chains.register(new ComponentId("myChain"), chain);
diff --git a/container-disc/src/test/java/com/yahoo/container/jdisc/ContainerThreadFactoryTest.java b/container-disc/src/test/java/com/yahoo/container/jdisc/ContainerThreadFactoryTest.java
index ec727c506b5..d55bf18c823 100644
--- a/container-disc/src/test/java/com/yahoo/container/jdisc/ContainerThreadFactoryTest.java
+++ b/container-disc/src/test/java/com/yahoo/container/jdisc/ContainerThreadFactoryTest.java
@@ -3,13 +3,13 @@ package com.yahoo.container.jdisc;
import com.yahoo.container.jdisc.metric.MetricConsumerProvider;
import com.yahoo.jdisc.application.ContainerThread;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.util.concurrent.ThreadFactory;
-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
@@ -17,7 +17,7 @@ import static org.junit.Assert.fail;
public class ContainerThreadFactoryTest {
@Test
- public void requireThatMetricConsumerProviderCanNotBeNull() {
+ void requireThatMetricConsumerProviderCanNotBeNull() {
try {
new ContainerThreadFactory(null);
fail();
@@ -27,15 +27,15 @@ public class ContainerThreadFactoryTest {
}
@Test
- public void requireThatThreadsCreatedAreJDiscContainerThreads() {
+ void requireThatThreadsCreatedAreJDiscContainerThreads() {
assertEquals(ContainerThread.class,
- new ContainerThreadFactory(Mockito.mock(MetricConsumerProvider.class))
- .newThread(Mockito.mock(Runnable.class))
- .getClass());
+ new ContainerThreadFactory(Mockito.mock(MetricConsumerProvider.class))
+ .newThread(Mockito.mock(Runnable.class))
+ .getClass());
}
@Test
- public void requireThatThreadFactoryCallsProvider() {
+ void requireThatThreadFactoryCallsProvider() {
MetricConsumerProvider provider = Mockito.mock(MetricConsumerProvider.class);
ThreadFactory factory = new ContainerThreadFactory(provider);
factory.newThread(Mockito.mock(Runnable.class));
diff --git a/container-disc/src/test/java/com/yahoo/container/jdisc/DisableOsgiFrameworkTest.java b/container-disc/src/test/java/com/yahoo/container/jdisc/DisableOsgiFrameworkTest.java
index 46acd5ce2b8..f6b2424e0e1 100644
--- a/container-disc/src/test/java/com/yahoo/container/jdisc/DisableOsgiFrameworkTest.java
+++ b/container-disc/src/test/java/com/yahoo/container/jdisc/DisableOsgiFrameworkTest.java
@@ -1,47 +1,63 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.container.jdisc;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.osgi.framework.BundleException;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
/**
* @author Ulf Lilleengen
*/
public class DisableOsgiFrameworkTest {
- @Test(expected = RuntimeException.class)
- public void require_that_installBundle_throws_exception() throws BundleException {
- new DisableOsgiFramework().installBundle("foo");
+ @Test
+ void require_that_installBundle_throws_exception() throws BundleException {
+ assertThrows(RuntimeException.class, () -> {
+ new DisableOsgiFramework().installBundle("foo");
+ });
}
- @Test(expected = RuntimeException.class)
- public void require_that_startBundles_throws_exception() throws BundleException {
- new DisableOsgiFramework().startBundles(null, true);
+ @Test
+ void require_that_startBundles_throws_exception() throws BundleException {
+ assertThrows(RuntimeException.class, () -> {
+ new DisableOsgiFramework().startBundles(null, true);
+ });
}
- @Test(expected = RuntimeException.class)
- public void require_that_bundleContext_throws_exception() throws BundleException {
- new DisableOsgiFramework().bundleContext();
+ @Test
+ void require_that_bundleContext_throws_exception() throws BundleException {
+ assertThrows(RuntimeException.class, () -> {
+ new DisableOsgiFramework().bundleContext();
+ });
}
- @Test(expected = RuntimeException.class)
- public void require_that_refreshPackages_throws_exception() {
- new DisableOsgiFramework().refreshPackages();
+ @Test
+ void require_that_refreshPackages_throws_exception() {
+ assertThrows(RuntimeException.class, () -> {
+ new DisableOsgiFramework().refreshPackages();
+ });
}
- @Test(expected = RuntimeException.class)
- public void require_that_bundles_throws_exception() {
- new DisableOsgiFramework().bundles();
+ @Test
+ void require_that_bundles_throws_exception() {
+ assertThrows(RuntimeException.class, () -> {
+ new DisableOsgiFramework().bundles();
+ });
}
- @Test(expected = RuntimeException.class)
- public void require_that_start_throws_exception() throws BundleException {
- new DisableOsgiFramework().start();
+ @Test
+ void require_that_start_throws_exception() throws BundleException {
+ assertThrows(RuntimeException.class, () -> {
+ new DisableOsgiFramework().start();
+ });
}
- @Test(expected = RuntimeException.class)
- public void require_that_stop_throws_exception() throws BundleException {
- new DisableOsgiFramework().stop();
+ @Test
+ void require_that_stop_throws_exception() throws BundleException {
+ assertThrows(RuntimeException.class, () -> {
+ new DisableOsgiFramework().stop();
+ });
}
}
diff --git a/container-disc/src/test/java/com/yahoo/container/jdisc/FilterBindingsProviderTest.java b/container-disc/src/test/java/com/yahoo/container/jdisc/FilterBindingsProviderTest.java
index 70e956480ed..fe18206b5af 100644
--- a/container-disc/src/test/java/com/yahoo/container/jdisc/FilterBindingsProviderTest.java
+++ b/container-disc/src/test/java/com/yahoo/container/jdisc/FilterBindingsProviderTest.java
@@ -9,15 +9,15 @@ import com.yahoo.jdisc.http.ServerConfig;
import com.yahoo.jdisc.http.filter.RequestFilter;
import com.yahoo.jdisc.http.filter.ResponseFilter;
import com.yahoo.jdisc.http.server.jetty.FilterBindings;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
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.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.mock;
/**
@@ -28,7 +28,7 @@ public class FilterBindingsProviderTest {
final ServerConfig.Builder configBuilder = new ServerConfig.Builder();
@Test
- public void requireThatEmptyInputGivesEmptyOutput() {
+ void requireThatEmptyInputGivesEmptyOutput() {
final FilterChainRepository filterChainRepository = new FilterChainRepository(
new ChainsConfig(new ChainsConfig.Builder()),
new ComponentRegistry<>(),
@@ -50,7 +50,7 @@ public class FilterBindingsProviderTest {
}
@Test
- public void requireThatCorrectlyConfiguredFiltersAreIncluded() {
+ void requireThatCorrectlyConfiguredFiltersAreIncluded() {
final String requestFilter1Id = "requestFilter1";
final String requestFilter2Id = "requestFilter2";
final String requestFilter3Id = "requestFilter3";
@@ -107,7 +107,7 @@ public class FilterBindingsProviderTest {
private interface DualRoleFilter extends RequestFilter, ResponseFilter {}
@Test
- public void requireThatInstanceCanNotBeBothRequestAndResponseFilter() {
+ void requireThatInstanceCanNotBeBothRequestAndResponseFilter() {
final String filterId = "filter";
// Set up config.
@@ -137,7 +137,7 @@ public class FilterBindingsProviderTest {
}
@Test
- public void requireThatConfigWithUnknownReferenceFails() {
+ void requireThatConfigWithUnknownReferenceFails() {
// Set up config.
configBuilder.filter(new ServerConfig.Filter.Builder().id("someFilter").binding("http://*/*"));
diff --git a/container-disc/src/test/java/com/yahoo/container/jdisc/component/DeconstructorTest.java b/container-disc/src/test/java/com/yahoo/container/jdisc/component/DeconstructorTest.java
index 715c2759aa6..76b4d7701ea 100644
--- a/container-disc/src/test/java/com/yahoo/container/jdisc/component/DeconstructorTest.java
+++ b/container-disc/src/test/java/com/yahoo/container/jdisc/component/DeconstructorTest.java
@@ -6,8 +6,8 @@ import com.yahoo.container.bundle.MockBundle;
import com.yahoo.container.di.componentgraph.Provider;
import com.yahoo.jdisc.ResourceReference;
import com.yahoo.jdisc.SharedResource;
-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.List;
@@ -15,7 +15,7 @@ import java.util.function.Supplier;
import static java.util.Collections.emptyList;
import static java.util.Collections.singleton;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author gjoranv
@@ -23,13 +23,13 @@ import static org.junit.Assert.assertTrue;
public class DeconstructorTest {
public static Deconstructor deconstructor;
- @Before
+ @BeforeEach
public void init() {
deconstructor = new Deconstructor();
}
@Test
- public void deconstructor_waits_for_completion_on_shutdown() {
+ void deconstructor_waits_for_completion_on_shutdown() {
deconstructor = new Deconstructor();
var slowDeconstructComponent = new SlowDeconstructComponent();
@@ -39,7 +39,7 @@ public class DeconstructorTest {
}
@Test
- public void require_abstract_component_destructed() throws InterruptedException {
+ void require_abstract_component_destructed() throws InterruptedException {
TestAbstractComponent abstractComponent = new TestAbstractComponent();
deconstructor.deconstruct(0, List.of(abstractComponent), emptyList());
@@ -48,7 +48,7 @@ public class DeconstructorTest {
}
@Test
- public void require_provider_destructed() throws InterruptedException {
+ void require_provider_destructed() throws InterruptedException {
TestProvider provider = new TestProvider();
deconstructor.deconstruct(0, List.of(provider), emptyList());
@@ -57,7 +57,7 @@ public class DeconstructorTest {
}
@Test
- public void require_shared_resource_released() throws InterruptedException {
+ void require_shared_resource_released() throws InterruptedException {
TestSharedResource sharedResource = new TestSharedResource();
deconstructor.deconstruct(0, List.of(sharedResource), emptyList());
waitForDeconstructToComplete(() -> sharedResource.released);
@@ -65,7 +65,7 @@ public class DeconstructorTest {
}
@Test
- public void bundles_are_uninstalled() throws InterruptedException {
+ void bundles_are_uninstalled() throws InterruptedException {
var bundle = new UninstallableMockBundle();
// Done by executor, so it takes some time even with a 0 delay.
deconstructor.deconstruct(0, emptyList(), singleton(bundle));
diff --git a/container-disc/src/test/java/com/yahoo/container/jdisc/metric/ForwardingMetricConsumerTest.java b/container-disc/src/test/java/com/yahoo/container/jdisc/metric/ForwardingMetricConsumerTest.java
index 95b179c207f..982ad4389c2 100644
--- a/container-disc/src/test/java/com/yahoo/container/jdisc/metric/ForwardingMetricConsumerTest.java
+++ b/container-disc/src/test/java/com/yahoo/container/jdisc/metric/ForwardingMetricConsumerTest.java
@@ -3,13 +3,13 @@ package com.yahoo.container.jdisc.metric;
import com.yahoo.jdisc.Metric;
import com.yahoo.jdisc.application.MetricConsumer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.util.HashMap;
import java.util.Map;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* @author Simon Thoresen Hult
@@ -17,7 +17,7 @@ import static org.junit.Assert.assertNotNull;
public class ForwardingMetricConsumerTest {
@Test
- public void requireThatAllMethodsAreForwarded() {
+ void requireThatAllMethodsAreForwarded() {
MetricConsumer fooConsumer = Mockito.mock(MetricConsumer.class);
Metric.Context fooCtx = Mockito.mock(Metric.Context.class);
Mockito.when(fooConsumer.createContext(Mockito.<Map<String, ?>>any())).thenReturn(fooCtx);
@@ -26,7 +26,7 @@ public class ForwardingMetricConsumerTest {
Metric.Context barCtx = Mockito.mock(Metric.Context.class);
Mockito.when(barConsumer.createContext(Mockito.<Map<String, ?>>any())).thenReturn(barCtx);
- MetricConsumer fwdConsumer = new ForwardingMetricConsumer(new MetricConsumer[] { fooConsumer, barConsumer });
+ MetricConsumer fwdConsumer = new ForwardingMetricConsumer(new MetricConsumer[]{fooConsumer, barConsumer});
Map<String, ?> properties = new HashMap<>();
Metric.Context ctx = fwdConsumer.createContext(properties);
diff --git a/container-disc/src/test/java/com/yahoo/container/jdisc/metric/GarbageCollectionMetricsTest.java b/container-disc/src/test/java/com/yahoo/container/jdisc/metric/GarbageCollectionMetricsTest.java
index e4f8c6d76ed..8e38420b872 100644
--- a/container-disc/src/test/java/com/yahoo/container/jdisc/metric/GarbageCollectionMetricsTest.java
+++ b/container-disc/src/test/java/com/yahoo/container/jdisc/metric/GarbageCollectionMetricsTest.java
@@ -3,13 +3,13 @@ package com.yahoo.container.jdisc.metric;
import com.yahoo.jdisc.Metric;
import com.yahoo.test.ManualClock;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.lang.management.ManagementFactory;
import java.time.Duration;
import java.util.LinkedList;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
@@ -21,7 +21,7 @@ import static org.mockito.Mockito.verify;
*/
public class GarbageCollectionMetricsTest {
@Test
- public void gc_metrics_are_collected_in_a_sliding_window() {
+ void gc_metrics_are_collected_in_a_sliding_window() {
ManualClock clock = new ManualClock();
Metric metric = mock(Metric.class);
int garbageCollectors = ManagementFactory.getGarbageCollectorMXBeans().size();
diff --git a/container-disc/src/test/java/com/yahoo/container/jdisc/metric/MetricConsumerProviderTest.java b/container-disc/src/test/java/com/yahoo/container/jdisc/metric/MetricConsumerProviderTest.java
index e0650ad3d0c..5a67b7189c4 100644
--- a/container-disc/src/test/java/com/yahoo/container/jdisc/metric/MetricConsumerProviderTest.java
+++ b/container-disc/src/test/java/com/yahoo/container/jdisc/metric/MetricConsumerProviderTest.java
@@ -2,12 +2,11 @@
package com.yahoo.container.jdisc.metric;
import com.yahoo.jdisc.application.MetricConsumer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertSame;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertSame;
/**
* @author Simon Thoresen Hult
@@ -15,14 +14,14 @@ import static org.junit.Assert.assertSame;
public class MetricConsumerProviderTest {
@Test
- public void requireThatSingleConsumerIsNotDelegated() {
+ void requireThatSingleConsumerIsNotDelegated() {
MetricConsumer consumer = Mockito.mock(MetricConsumer.class);
MetricConsumerProvider provider = MetricConsumerProviders.newSingletonFactories(consumer);
assertSame(consumer, provider.newInstance());
}
@Test
- public void requireThatMultipleConsumersAreDelegated() {
+ void requireThatMultipleConsumersAreDelegated() {
MetricConsumer foo = Mockito.mock(MetricConsumer.class);
MetricConsumer bar = Mockito.mock(MetricConsumer.class);
MetricConsumerProvider provider = MetricConsumerProviders.newSingletonFactories(foo, bar);
diff --git a/container-disc/src/test/java/com/yahoo/container/jdisc/metric/MetricProviderTest.java b/container-disc/src/test/java/com/yahoo/container/jdisc/metric/MetricProviderTest.java
index eac3ad2f060..5ad7d5767a6 100644
--- a/container-disc/src/test/java/com/yahoo/container/jdisc/metric/MetricProviderTest.java
+++ b/container-disc/src/test/java/com/yahoo/container/jdisc/metric/MetricProviderTest.java
@@ -4,7 +4,7 @@ package com.yahoo.container.jdisc.metric;
import com.yahoo.container.di.componentgraph.Provider;
import com.yahoo.jdisc.Metric;
import com.yahoo.jdisc.application.MetricConsumer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.util.concurrent.Callable;
@@ -13,9 +13,9 @@ import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
-import static org.junit.Assert.assertNotNull;
-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.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Simon Thoresen Hult
@@ -23,7 +23,7 @@ import static org.junit.Assert.assertTrue;
public class MetricProviderTest {
@Test
- public void requireThatMetricProviderDelegatesToConsumerFactory() {
+ void requireThatMetricProviderDelegatesToConsumerFactory() {
MetricConsumer consumer = Mockito.mock(MetricConsumer.class);
MetricProvider provider = MetricProviders.newInstance(consumer);
@@ -38,7 +38,7 @@ public class MetricProviderTest {
}
@Test
- public void requireThatThreadLocalConsumersAreProvided() throws Exception {
+ void requireThatThreadLocalConsumersAreProvided() throws Exception {
AtomicInteger cnt = new AtomicInteger(0);
final MetricProvider metricProvider = MetricProviders.newInstance(MetricConsumerFactories.newCounter(cnt));
assertEquals(0, cnt.get());
diff --git a/container-disc/src/test/java/com/yahoo/container/jdisc/metric/MetricUpdaterTest.java b/container-disc/src/test/java/com/yahoo/container/jdisc/metric/MetricUpdaterTest.java
index 0652f35a5d1..bc196b08ab9 100644
--- a/container-disc/src/test/java/com/yahoo/container/jdisc/metric/MetricUpdaterTest.java
+++ b/container-disc/src/test/java/com/yahoo/container/jdisc/metric/MetricUpdaterTest.java
@@ -3,7 +3,7 @@ package com.yahoo.container.jdisc.metric;
import com.yahoo.jdisc.Metric;
import com.yahoo.jdisc.statistics.ContainerWatchdogMetrics;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.lang.management.ManagementFactory;
import java.time.Duration;
@@ -18,16 +18,16 @@ import static org.mockito.Mockito.verify;
* @author bjorncs
*/
public class MetricUpdaterTest {
-
+
@Test
- public void metrics_are_updated_in_scheduler_cycle() {
+ void metrics_are_updated_in_scheduler_cycle() {
int gcCount = ManagementFactory.getGarbageCollectorMXBeans().size();
Metric metric = mock(Metric.class);
ContainerWatchdogMetrics containerWatchdogMetrics = mock(ContainerWatchdogMetrics.class);
new MetricUpdater(new MockScheduler(), metric, containerWatchdogMetrics);
verify(containerWatchdogMetrics, times(1)).emitMetrics(any());
- verify(metric, times(13 + 2 * gcCount)).set(anyString(), any(), any());
+ verify(metric, times(14 + 2 * gcCount)).set(anyString(), any(), any());
}
private static class MockScheduler implements MetricUpdater.Scheduler {
diff --git a/container-search/pom.xml b/container-search/pom.xml
index 031d25c7d02..1c3e7e71497 100644
--- a/container-search/pom.xml
+++ b/container-search/pom.xml
@@ -16,11 +16,6 @@
<version>8-SNAPSHOT</version>
<dependencies>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<scope>test</scope>
@@ -152,12 +147,36 @@
<artifactId>testutil</artifactId>
<version>${project.version}</version>
<scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-core</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-library</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
+ </dependency>
</dependencies>
<build>
<plugins>
diff --git a/container-search/src/test/java/com/yahoo/prelude/cluster/ClusterSearcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/cluster/ClusterSearcherTestCase.java
index ac860faffa5..2b560713c57 100644
--- a/container-search/src/test/java/com/yahoo/prelude/cluster/ClusterSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/cluster/ClusterSearcherTestCase.java
@@ -26,7 +26,7 @@ import com.yahoo.search.schema.Schema;
import com.yahoo.search.schema.SchemaInfo;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.vespa.config.search.DispatchConfig;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
@@ -38,10 +38,7 @@ import java.util.List;
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.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Tests cluster monitoring
@@ -53,7 +50,7 @@ public class ClusterSearcherTestCase {
private static final double DELTA = 0.0000000000000001;
@Test
- public void testNoBackends() {
+ void testNoBackends() {
ClusterSearcher cluster = new ClusterSearcher(new LinkedHashSet<>(Arrays.asList("dummy")));
try {
Execution execution = new Execution(cluster, Execution.Context.createContextStub());
@@ -87,7 +84,7 @@ public class ClusterSearcherTestCase {
}
@Test
- public void testThatDocumentTypesAreResolved() {
+ void testThatDocumentTypesAreResolved() {
ClusterSearcher cluster1 = new ClusterSearcher(new LinkedHashSet<>(Arrays.asList("type1", "type2", "type3")));
try {
ClusterSearcher type1 = new ClusterSearcher(new LinkedHashSet<>(Arrays.asList("type6")));
@@ -126,7 +123,7 @@ public class ClusterSearcherTestCase {
}
@Test
- public void testThatDocumentTypesAreResolvedTODO_REMOVE() {
+ void testThatDocumentTypesAreResolvedTODO_REMOVE() {
ClusterSearcher cluster1 = new ClusterSearcher(new LinkedHashSet<>(List.of("type1", "type2", "type3")));
try {
ClusterSearcher type1 = new ClusterSearcher(new LinkedHashSet<>(List.of("type6")));
@@ -284,7 +281,7 @@ public class ClusterSearcherTestCase {
}
@Test
- public void testThatSingleDocumentTypeCanBeSearched() {
+ void testThatSingleDocumentTypeCanBeSearched() {
{ // Explicit 1 type in restrict set
Execution execution = createExecution();
Query query = new Query("?query=hello&restrict=type1");
@@ -311,7 +308,7 @@ public class ClusterSearcherTestCase {
}
@Test
- public void testThatSubsetOfDocumentTypesCanBeSearched() {
+ void testThatSubsetOfDocumentTypesCanBeSearched() {
Execution execution = createExecution();
Query query = new Query("?query=hello&restrict=type1,type3");
@@ -328,7 +325,7 @@ public class ClusterSearcherTestCase {
}
@Test
- public void testThatMultipleDocumentTypesCanBeSearchedAndFilled() {
+ void testThatMultipleDocumentTypesCanBeSearchedAndFilled() {
Execution execution = createExecution();
Query query = new Query("?query=hello");
@@ -386,7 +383,7 @@ public class ClusterSearcherTestCase {
}
@Test
- public void testThatWeCanSpecifyNumHitsAndHitOffset() {
+ void testThatWeCanSpecifyNumHitsAndHitOffset() {
Execution ex = createExecution();
// all types
@@ -411,7 +408,7 @@ public class ClusterSearcherTestCase {
}
@Test
- public void testThatWeCanSpecifyNumHitsAndHitOffsetWhenSorting() {
+ void testThatWeCanSpecifyNumHitsAndHitOffsetWhenSorting() {
Execution ex = createExecution(true);
String extra = "&restrict=type1,type2&sorting=%2Basc-score";
@@ -485,7 +482,7 @@ public class ClusterSearcherTestCase {
}
@Test
- public void testThatVipStatusIsSetUpForStreamingSearch() {
+ void testThatVipStatusIsSetUpForStreamingSearch() {
String clusterName = "test-cluster";
VipStatus vipStatus = new VipStatus(new QrSearchersConfig.Builder().searchcluster(new QrSearchersConfig.Searchcluster.Builder().name(clusterName)).build(), new ClustersStatus());
assertFalse(vipStatus.isInRotation());
@@ -494,7 +491,7 @@ public class ClusterSearcherTestCase {
}
@Test
- public void testThatQueryTimeoutIsCappedWithDefaultMax() {
+ void testThatQueryTimeoutIsCappedWithDefaultMax() {
QueryTimeoutFixture f = new QueryTimeoutFixture(null, null);
f.query.setTimeout(600001);
f.search();
@@ -502,7 +499,7 @@ public class ClusterSearcherTestCase {
}
@Test
- public void testThatQueryTimeoutIsNotCapped() {
+ void testThatQueryTimeoutIsNotCapped() {
QueryTimeoutFixture f = new QueryTimeoutFixture(null, null);
f.query.setTimeout(599999);
f.search();
@@ -510,7 +507,7 @@ public class ClusterSearcherTestCase {
}
@Test
- public void testThatQueryTimeoutIsCappedWithSpecifiedMax() {
+ void testThatQueryTimeoutIsCappedWithSpecifiedMax() {
QueryTimeoutFixture f = new QueryTimeoutFixture(70.0, null);
f.query.setTimeout(70001);
f.search();
@@ -518,7 +515,7 @@ public class ClusterSearcherTestCase {
}
@Test
- public void testThatQueryCacheIsDisabledIfTimeoutIsLargerThanMax() {
+ void testThatQueryCacheIsDisabledIfTimeoutIsLargerThanMax() {
QueryTimeoutFixture f = new QueryTimeoutFixture(null, null);
f.query.setTimeout(10001);
f.query.getRanking().setQueryCache(true);
@@ -527,7 +524,7 @@ public class ClusterSearcherTestCase {
}
@Test
- public void testThatQueryCacheIsNotDisabledIfTimeoutIsOk() {
+ void testThatQueryCacheIsNotDisabledIfTimeoutIsOk() {
QueryTimeoutFixture f = new QueryTimeoutFixture(null, null);
f.query.setTimeout(10000);
f.query.getRanking().setQueryCache(true);
@@ -536,7 +533,7 @@ public class ClusterSearcherTestCase {
}
@Test
- public void testThatQueryCacheIsDisabledIfTimeoutIsLargerThanConfiguredMax() {
+ void testThatQueryCacheIsDisabledIfTimeoutIsLargerThanConfiguredMax() {
QueryTimeoutFixture f = new QueryTimeoutFixture(null, 5.0);
f.query.setTimeout(5001);
f.query.getRanking().setQueryCache(true);
diff --git a/container-search/src/test/java/com/yahoo/prelude/fastsearch/SlimeSummaryTestCase.java b/container-search/src/test/java/com/yahoo/prelude/fastsearch/SlimeSummaryTestCase.java
index c39efe21e70..74874c28452 100644
--- a/container-search/src/test/java/com/yahoo/prelude/fastsearch/SlimeSummaryTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/fastsearch/SlimeSummaryTestCase.java
@@ -16,7 +16,7 @@ import com.yahoo.slime.Cursor;
import com.yahoo.slime.Slime;
import com.yahoo.tensor.Tensor;
import com.yahoo.tensor.serialization.TypedBinaryFormat;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
@@ -27,12 +27,7 @@ import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
-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.*;
public class SlimeSummaryTestCase {
@@ -43,7 +38,7 @@ public class SlimeSummaryTestCase {
private static final String partial_summary3_cf = cf_pre + "partial-summary3.cfg";
@Test
- public void testDecodingEmpty() {
+ void testDecodingEmpty() {
DocsumDefinitionSet docsum = createDocsumDefinitionSet();
FastHit hit = new FastHit();
assertNull(docsum.lazyDecode("default", emptySummary(), hit));
@@ -69,23 +64,23 @@ public class SlimeSummaryTestCase {
}
@Test
- public void testTimeout() {
+ void testTimeout() {
DocsumDefinitionSet docsum = createDocsumDefinitionSet();
FastHit hit = new FastHit();
assertEquals("Hit hit index:null/0/000000000000000000000000 (relevance 0.0) [fasthit, globalid: 0 0 0 0 0 0 0 0 0 0 0 0, partId: 0, distributionkey: 0] failed: Timed out....",
- docsum.lazyDecode("default", timeoutSummary(), hit));
+ docsum.lazyDecode("default", timeoutSummary(), hit));
}
@Test
- public void testDecoding() {
+ void testDecoding() {
Tensor tensor1 = Tensor.from("tensor(x{},y{}):{{x:foo,y:bar}:0.1}");
Tensor tensor2 = Tensor.from("tensor(x[1],y[1]):{{x:0,y:0}:-0.3}");
DocsumDefinitionSet docsum = createDocsumDefinitionSet();
FastHit hit = new FastHit();
assertNull(docsum.lazyDecode("default", fullSummary(tensor1, tensor2), hit));
assertEquals(4, hit.getField("integer_field"));
- assertEquals((short)2, hit.getField("short_field"));
- assertEquals((byte)1, hit.getField("byte_field"));
+ assertEquals((short) 2, hit.getField("short_field"));
+ assertEquals((byte) 1, hit.getField("byte_field"));
assertEquals(4.5F, hit.getField("float_field"));
assertEquals(8.75, hit.getField("double_field"));
assertEquals(8L, hit.getField("int64_field"));
@@ -117,7 +112,7 @@ public class SlimeSummaryTestCase {
assertEquals(tensor2, hit.getField("tensor_field2"));
FeatureData featureData = hit.features();
assertEquals("double_feature,rankingExpression(tensor1_feature),tensor2_feature",
- featureData.featureNames().stream().sorted().collect(Collectors.joining(",")));
+ featureData.featureNames().stream().sorted().collect(Collectors.joining(",")));
assertEquals(0.5, featureData.getDouble("double_feature"), 0.00000001);
assertEquals(tensor1, featureData.getTensor("tensor1_feature"));
assertEquals(tensor1, featureData.getTensor("rankingExpression(tensor1_feature)"));
@@ -125,7 +120,7 @@ public class SlimeSummaryTestCase {
}
@Test
- public void testFieldAccessAPI() {
+ void testFieldAccessAPI() {
DocsumDefinitionSet partialDocsum1 = createPartialDocsumDefinitionSet1();
DocsumDefinitionSet partialDocsum2 = createPartialDocsumDefinitionSet2();
DocsumDefinitionSet partialDocsum3 = createPartialDocsumDefinitionSet3();
@@ -253,8 +248,8 @@ public class SlimeSummaryTestCase {
Tensor tensor2 = Tensor.from("tensor(x[1],y[1]):{{x:0,y:0}:-0.3}");
assertNull(fullDocsum.lazyDecode("default", fullishSummary(tensor1, tensor2), hit));
expected.put("integer_field", 4);
- expected.put("short_field", (short)2);
- expected.put("byte_field", (byte)1);
+ expected.put("short_field", (short) 2);
+ expected.put("byte_field", (byte) 1);
expected.put("float_field", 4.5f);
expected.put("double_field", 8.75d);
expected.put("int64_field", 8L);
@@ -303,7 +298,7 @@ public class SlimeSummaryTestCase {
for (Iterator<String> i = hit.fieldKeys().iterator(); i.hasNext(); ) {
fieldNameIteratorFieldCount++;
String name = i.next();
- assertTrue("Expected field " + name, expected.containsKey(name));
+ assertTrue(expected.containsKey(name), "Expected field " + name);
}
assertEquals(expected.size(), fieldNameIteratorFieldCount);
// fieldKeys
@@ -324,11 +319,10 @@ public class SlimeSummaryTestCase {
}
private void assertEqualMaps(Map<String, Object> expected, Map<String, Object> actual) {
- assertEquals("Map sizes", expected.size(), actual.size());
- assertEquals("Keys", expected.keySet(), actual.keySet());
+ assertEquals(expected.size(), actual.size(), "Map sizes");
+ assertEquals(expected.keySet(), actual.keySet(), "Keys");
for (var expectedEntry : expected.entrySet()) {
- assertEquals("Key '" + expectedEntry.getKey() + "'",
- expectedEntry.getValue(), actual.get(expectedEntry.getKey()));
+ assertEquals(expectedEntry.getValue(), actual.get(expectedEntry.getKey()), "Key '" + expectedEntry.getKey() + "'");
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/fastsearch/test/DocsumDefinitionTestCase.java b/container-search/src/test/java/com/yahoo/prelude/fastsearch/test/DocsumDefinitionTestCase.java
index da9d849db90..f07ef0f733b 100644
--- a/container-search/src/test/java/com/yahoo/prelude/fastsearch/test/DocsumDefinitionTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/fastsearch/test/DocsumDefinitionTestCase.java
@@ -15,15 +15,12 @@ import com.yahoo.search.schema.Schema;
import com.yahoo.slime.BinaryFormat;
import com.yahoo.slime.Cursor;
import com.yahoo.slime.Slime;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
-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.jupiter.api.Assertions.assertEquals;
/**
* Tests docsum class functionality
@@ -33,7 +30,7 @@ import static org.junit.Assert.assertTrue;
public class DocsumDefinitionTestCase {
@Test
- public void testDecoding() {
+ void testDecoding() {
DocsumDefinitionSet set = createDocsumDefinitionSet();
FastHit hit = new FastHit();
diff --git a/container-search/src/test/java/com/yahoo/prelude/fastsearch/test/FastSearcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/fastsearch/test/FastSearcherTestCase.java
index d5630063f4b..dbc827ea5c2 100644
--- a/container-search/src/test/java/com/yahoo/prelude/fastsearch/test/FastSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/fastsearch/test/FastSearcherTestCase.java
@@ -30,7 +30,7 @@ import com.yahoo.search.schema.RankProfile;
import com.yahoo.search.schema.Schema;
import com.yahoo.search.schema.SchemaInfo;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Collections;
@@ -39,11 +39,7 @@ import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
-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.jupiter.api.Assertions.*;
/**
@@ -54,20 +50,20 @@ import static org.junit.Assert.assertTrue;
public class FastSearcherTestCase {
@Test
- public void testNullQuery() {
+ void testNullQuery() {
Logger.getLogger(FastSearcher.class.getName()).setLevel(Level.ALL);
FastSearcher fastSearcher = new FastSearcher("container.0",
- MockDispatcher.create(Collections.emptyList()),
- new SummaryParameters(null),
- new ClusterParams("testhittype"),
- documentdbInfoConfig("test"),
- schemaInfo("test"));
+ MockDispatcher.create(Collections.emptyList()),
+ new SummaryParameters(null),
+ new ClusterParams("testhittype"),
+ documentdbInfoConfig("test"),
+ schemaInfo("test"));
String query = "?junkparam=ignored";
Result result = doSearch(fastSearcher, new Query(query), 0, 10);
ErrorMessage message = result.hits().getError();
- assertNotNull("Got error", message);
+ assertNotNull(message, "Got error");
assertEquals("Null query", message.getMessage());
assertEquals(query, message.getDetailedMessage());
assertEquals(Error.NULL_QUERY.code, message.getCode());
@@ -90,13 +86,13 @@ public class FastSearcherTestCase {
}
@Test
- public void testSinglePassGroupingIsForcedWithSingleNodeGroups() {
+ void testSinglePassGroupingIsForcedWithSingleNodeGroups() {
FastSearcher fastSearcher = new FastSearcher("container.0",
- MockDispatcher.create(List.of(new Node(0, "host0", 0))),
- new SummaryParameters(null),
- new ClusterParams("testhittype"),
- documentdbInfoConfig("test"),
- schemaInfo("test"));
+ MockDispatcher.create(List.of(new Node(0, "host0", 0))),
+ new SummaryParameters(null),
+ new ClusterParams("testhittype"),
+ documentdbInfoConfig("test"),
+ schemaInfo("test"));
Query q = new Query("?query=foo");
GroupingRequest request1 = GroupingRequest.newInstance(q);
request1.setRootOperation(new AllOperation());
@@ -113,32 +109,32 @@ public class FastSearcherTestCase {
}
@Test
- public void testRankProfileValidation() {
+ void testRankProfileValidation() {
FastSearcher fastSearcher = new FastSearcher("container.0",
- MockDispatcher.create(List.of(new Node(0, "host0", 0))),
- new SummaryParameters(null),
- new ClusterParams("testhittype"),
- documentdbInfoConfig("test"),
- schemaInfo("test"));
+ MockDispatcher.create(List.of(new Node(0, "host0", 0))),
+ new SummaryParameters(null),
+ new ClusterParams("testhittype"),
+ documentdbInfoConfig("test"),
+ schemaInfo("test"));
assertFalse(searchError("?query=q", fastSearcher).contains("does not contain requested rank profile"));
assertFalse(searchError("?query=q&ranking.profile=default", fastSearcher).contains("does not contain requested rank profile"));
assertTrue(searchError("?query=q&ranking.profile=nosuch", fastSearcher).contains("does not contain requested rank profile"));
}
@Test
- public void testSummaryNeedsQuery() {
+ void testSummaryNeedsQuery() {
var documentDb = new DocumentdbInfoConfig(new DocumentdbInfoConfig.Builder().documentdb(new DocumentdbInfoConfig.Documentdb.Builder().name("test")));
var schema = new Schema.Builder("test")
- .add(new DocumentSummary.Builder("default").build())
- .add(new RankProfile.Builder("default").setHasRankFeatures(false)
- .setHasSummaryFeatures(false)
- .build());
+ .add(new DocumentSummary.Builder("default").build())
+ .add(new RankProfile.Builder("default").setHasRankFeatures(false)
+ .setHasSummaryFeatures(false)
+ .build());
FastSearcher backend = new FastSearcher("container.0",
- MockDispatcher.create(Collections.singletonList(new Node(0, "host0", 0))),
- new SummaryParameters(null),
- new ClusterParams("testhittype"),
- documentDb,
- new SchemaInfo(List.of(schema.build()), Map.of()));
+ MockDispatcher.create(Collections.singletonList(new Node(0, "host0", 0))),
+ new SummaryParameters(null),
+ new ClusterParams("testhittype"),
+ documentDb,
+ new SchemaInfo(List.of(schema.build()), Map.of()));
Query q = new Query("?query=foo");
Result result = doSearch(backend, q, 0, 10);
assertFalse(backend.summaryNeedsQuery(q));
@@ -150,15 +146,15 @@ public class FastSearcherTestCase {
}
@Test
- public void testSinglePassGroupingIsNotForcedWithSingleNodeGroups() {
+ void testSinglePassGroupingIsNotForcedWithSingleNodeGroups() {
MockDispatcher dispatcher = MockDispatcher.create(ImmutableList.of(new Node(0, "host0", 0), new Node(2, "host1", 0)));
FastSearcher fastSearcher = new FastSearcher("container.0",
- dispatcher,
- new SummaryParameters(null),
- new ClusterParams("testhittype"),
- documentdbInfoConfig("test"),
- schemaInfo("test"));
+ dispatcher,
+ new SummaryParameters(null),
+ new ClusterParams("testhittype"),
+ documentdbInfoConfig("test"),
+ schemaInfo("test"));
Query q = new Query("?query=foo");
GroupingRequest request1 = GroupingRequest.newInstance(q);
request1.setRootOperation(new AllOperation());
@@ -180,14 +176,13 @@ public class FastSearcherTestCase {
}
private void assertForceSinglePassIs(boolean expected, GroupingOperation operation) {
- assertEquals("Force single pass is " + expected + " in " + operation,
- expected, operation.getForceSinglePass());
+ assertEquals(expected, operation.getForceSinglePass(), "Force single pass is " + expected + " in " + operation);
for (GroupingOperation child : operation.getChildren())
assertForceSinglePassIs(expected, child);
}
@Test
- public void testDispatchReconfig() {
+ void testDispatchReconfig() {
String clusterName = "a";
var b = new QrSearchersConfig.Builder();
var searchClusterB = new QrSearchersConfig.Searchcluster.Builder();
diff --git a/container-search/src/test/java/com/yahoo/prelude/fastsearch/test/PartialFillTestCase.java b/container-search/src/test/java/com/yahoo/prelude/fastsearch/test/PartialFillTestCase.java
index 45ae8241696..f73edfec4c5 100644
--- a/container-search/src/test/java/com/yahoo/prelude/fastsearch/test/PartialFillTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/fastsearch/test/PartialFillTestCase.java
@@ -12,16 +12,13 @@ import com.yahoo.search.rendering.RendererRegistry;
import com.yahoo.search.result.ErrorHit;
import com.yahoo.search.result.ErrorMessage;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
-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 havardpe
@@ -50,7 +47,7 @@ public class PartialFillTestCase {
}
@Test
- public void testPartitioning() {
+ void testPartitioning() {
FS4 fs4 = new FS4();
Query a = new Query("/?query=foo");
Query b = new Query("/?query=bar");
@@ -107,7 +104,7 @@ public class PartialFillTestCase {
}
@Test
- public void testMergeErrors() {
+ void testMergeErrors() {
BadFS4 fs4 = new BadFS4();
Query a = new Query("/?query=foo");
Query b = new Query("/?query=bar");
@@ -129,17 +126,17 @@ public class PartialFillTestCase {
assertNotNull(eh);
ErrorMessage exp_sub = ErrorMessage.createUnspecifiedError("error");
int n = 0;
- for (Iterator<? extends com.yahoo.search.result.ErrorMessage> i = eh.errorIterator(); i.hasNext();) {
+ for (Iterator<? extends com.yahoo.search.result.ErrorMessage> i = eh.errorIterator(); i.hasNext(); ) {
com.yahoo.search.result.ErrorMessage error = i.next();
switch (n) {
- case 0:
- assertEquals(exp_sub, error);
- break;
- case 1:
- assertEquals(exp_sub, error);
- break;
- default:
- assertTrue(false);
+ case 0:
+ assertEquals(exp_sub, error);
+ break;
+ case 1:
+ assertEquals(exp_sub, error);
+ break;
+ default:
+ assertTrue(false);
}
n++;
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/hitfield/XmlRendererTestCase.java b/container-search/src/test/java/com/yahoo/prelude/hitfield/XmlRendererTestCase.java
index f35c45e7ad6..bf020b5ca84 100644
--- a/container-search/src/test/java/com/yahoo/prelude/hitfield/XmlRendererTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/hitfield/XmlRendererTestCase.java
@@ -2,71 +2,71 @@
package com.yahoo.prelude.hitfield;
import com.yahoo.data.access.simple.Value;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class XmlRendererTestCase {
@Test
- public void testWeightedSet1() {
+ void testWeightedSet1() {
Value.ArrayValue top = new Value.ArrayValue();
top
- .add(new Value.ArrayValue()
- .add(new Value.StringValue("per"))
- .add(new Value.LongValue(10)))
- .add(new Value.ArrayValue()
- .add(new Value.StringValue("paal"))
- .add(new Value.LongValue(20)))
- .add(new Value.ArrayValue()
- .add(new Value.StringValue("espen"))
- .add(new Value.LongValue(30)));
+ .add(new Value.ArrayValue()
+ .add(new Value.StringValue("per"))
+ .add(new Value.LongValue(10)))
+ .add(new Value.ArrayValue()
+ .add(new Value.StringValue("paal"))
+ .add(new Value.LongValue(20)))
+ .add(new Value.ArrayValue()
+ .add(new Value.StringValue("espen"))
+ .add(new Value.LongValue(30)));
String rendered = XmlRenderer.render(new StringBuilder(), top).toString();
String correct = "\n"
- + " <item weight=\"10\">per</item>\n"
- + " <item weight=\"20\">paal</item>\n"
- + " <item weight=\"30\">espen</item>\n"
- + " ";
+ + " <item weight=\"10\">per</item>\n"
+ + " <item weight=\"20\">paal</item>\n"
+ + " <item weight=\"30\">espen</item>\n"
+ + " ";
assertEquals(correct, rendered);
}
@Test
- public void testWeightedSet2() {
+ void testWeightedSet2() {
Value.ObjectValue top = new Value.ObjectValue();
top
- .put("foo", new Value.ArrayValue()
- .add(new Value.ArrayValue()
- .add(new Value.StringValue("per"))
- .add(new Value.LongValue(10)))
- .add(new Value.ArrayValue()
- .add(new Value.StringValue("paal"))
- .add(new Value.LongValue(20)))
- .add(new Value.ArrayValue()
- .add(new Value.StringValue("espen"))
- .add(new Value.LongValue(30))))
- .put("bar", new Value.ArrayValue()
- .add(new Value.ObjectValue()
- .put("item",new Value.StringValue("per"))
- .put("weight",new Value.LongValue(10)))
- .add(new Value.ObjectValue()
- .put("item",new Value.StringValue("paal"))
- .put("weight",new Value.LongValue(20)))
- .add(new Value.ObjectValue()
- .put("weight",new Value.LongValue(30))
- .put("item",new Value.StringValue("espen"))));
+ .put("foo", new Value.ArrayValue()
+ .add(new Value.ArrayValue()
+ .add(new Value.StringValue("per"))
+ .add(new Value.LongValue(10)))
+ .add(new Value.ArrayValue()
+ .add(new Value.StringValue("paal"))
+ .add(new Value.LongValue(20)))
+ .add(new Value.ArrayValue()
+ .add(new Value.StringValue("espen"))
+ .add(new Value.LongValue(30))))
+ .put("bar", new Value.ArrayValue()
+ .add(new Value.ObjectValue()
+ .put("item", new Value.StringValue("per"))
+ .put("weight", new Value.LongValue(10)))
+ .add(new Value.ObjectValue()
+ .put("item", new Value.StringValue("paal"))
+ .put("weight", new Value.LongValue(20)))
+ .add(new Value.ObjectValue()
+ .put("weight", new Value.LongValue(30))
+ .put("item", new Value.StringValue("espen"))));
String rendered = XmlRenderer.render(new StringBuilder(), top).toString();
String correct = "\n"
- + " <struct-field name=\"foo\">\n"
- + " <item weight=\"10\">per</item>\n"
- + " <item weight=\"20\">paal</item>\n"
- + " <item weight=\"30\">espen</item>\n"
- + " </struct-field>\n"
- + " <struct-field name=\"bar\">\n"
- + " <item weight=\"10\">per</item>\n"
- + " <item weight=\"20\">paal</item>\n"
- + " <item weight=\"30\">espen</item>\n"
- + " </struct-field>\n"
- + " ";
+ + " <struct-field name=\"foo\">\n"
+ + " <item weight=\"10\">per</item>\n"
+ + " <item weight=\"20\">paal</item>\n"
+ + " <item weight=\"30\">espen</item>\n"
+ + " </struct-field>\n"
+ + " <struct-field name=\"bar\">\n"
+ + " <item weight=\"10\">per</item>\n"
+ + " <item weight=\"20\">paal</item>\n"
+ + " <item weight=\"30\">espen</item>\n"
+ + " </struct-field>\n"
+ + " ";
assertEquals(correct, rendered);
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/hitfield/test/HitFieldTestCase.java b/container-search/src/test/java/com/yahoo/prelude/hitfield/test/HitFieldTestCase.java
index 7c264f40388..f6b3ee65d12 100644
--- a/container-search/src/test/java/com/yahoo/prelude/hitfield/test/HitFieldTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/hitfield/test/HitFieldTestCase.java
@@ -5,10 +5,10 @@ import java.util.ArrayList;
import java.util.List;
import com.yahoo.prelude.hitfield.HitField;
-import com.yahoo.prelude.hitfield.StringFieldPart;
-import org.junit.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import com.yahoo.prelude.hitfield.StringFieldPart;
+import org.junit.jupiter.api.Test;
/**
* Tests the HitField class
@@ -19,7 +19,7 @@ import static org.junit.Assert.assertEquals;
public class HitFieldTestCase {
@Test
- public void testHitField() {
+ void testHitField() {
HitField hf = new HitField("boo", "hei paa deg");
assertEquals(3, hf.getTokenizedContent().size());
List l = new ArrayList();
@@ -32,7 +32,7 @@ public class HitFieldTestCase {
}
@Test
- public void testCjk() {
+ void testCjk() {
HitField hf = new HitField("boo", "hmm\u001fgr");
assertEquals(2, hf.getTokenizedContent().size());
assertEquals("hmmgr", hf.getContent());
@@ -44,7 +44,7 @@ public class HitFieldTestCase {
}
@Test
- public void testAnnotateField() {
+ void testAnnotateField() {
HitField hf = new HitField("boo", "The <hi>Eclipse</hi> SDK \uFFF9include\uFFFAincludes\uFFFB the <hi>Eclipse</hi> Platform");
assertEquals(11, hf.getTokenizedContent().size());
hf = new HitField("boo", "\uFFF9include\uFFFAincludes\uFFFB the <hi>Eclipse</hi> Platform");
@@ -72,7 +72,7 @@ public class HitFieldTestCase {
}
@Test
- public void testEmptyField() {
+ void testEmptyField() {
HitField hf = new HitField("boo", "");
assertEquals(0, hf.getTokenizedContent().size());
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/hitfield/test/JSONStringTestCase.java b/container-search/src/test/java/com/yahoo/prelude/hitfield/test/JSONStringTestCase.java
index 256014b7df4..944e1e0a02f 100644
--- a/container-search/src/test/java/com/yahoo/prelude/hitfield/test/JSONStringTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/hitfield/test/JSONStringTestCase.java
@@ -8,10 +8,10 @@ import com.yahoo.data.access.Inspector;
import com.yahoo.data.access.Type;
import com.yahoo.slime.Slime;
import com.yahoo.slime.Cursor;
-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 the JSONString XML rendering.
@@ -23,7 +23,7 @@ import static org.junit.Assert.assertTrue;
public class JSONStringTestCase {
@Test
- public void testWeightedSet() {
+ void testWeightedSet() {
String json = "[[{\"as1\":[\"per\",\"paal\"],\"l1\":1122334455667788997,\"d1\":87.790001,\"i1\":7,\"al1\":[11223344556677881,11223344556677883],\"s1\":\"string\\n"
+ "espa\u00F1a\\n"
+ "wssf1.s1[0]\"},10],"
@@ -44,7 +44,7 @@ public class JSONStringTestCase {
+ " <item>paal</item>\n"
+ " </struct-field>\n",
" <struct-field name=\"s1\">string\n" + "españa\n"
- + "wssf1.s1[0]</struct-field>\n" };
+ + "wssf1.s1[0]</struct-field>\n"};
String o2 = " <item weight=\"20\">\n";
String[] o2Fields = {
" <struct-field name=\"l1\">1122334455667788998</struct-field>\n",
@@ -59,7 +59,7 @@ public class JSONStringTestCase {
+ " <item>paal</item>\n"
+ " </struct-field>\n",
" <struct-field name=\"s1\">string\n"
- + "españa wssf1.s1[1]</struct-field>\n" };
+ + "españa wssf1.s1[1]</struct-field>\n"};
String rendered = js.toString();
int o1Offset = rendered.indexOf(o1);
assertTrue(-1 < o1Offset);
@@ -72,88 +72,88 @@ public class JSONStringTestCase {
}
@Test
- public void testWeightedSetFromInspector() {
+ void testWeightedSetFromInspector() {
Value.ArrayValue top = new Value.ArrayValue();
top.add(new Value.ArrayValue()
.add(new Value.ObjectValue()
- .put("d1", new Value.DoubleValue(87.790001))
- .put("s1", new Value.StringValue("string\n" + "espa\u00F1a\n" + "wssf1.s1[0]"))
- .put("al1", new Value.ArrayValue()
- .add(new Value.LongValue(11223344556677881L))
- .add(new Value.LongValue(11223344556677883L)))
- .put("l1", new Value.LongValue(1122334455667788997L))
- .put("as1", new Value.ArrayValue()
- .add(new Value.StringValue("per"))
- .add(new Value.StringValue("paal")))
- .put("i1", new Value.LongValue(7)))
+ .put("d1", new Value.DoubleValue(87.790001))
+ .put("s1", new Value.StringValue("string\n" + "espa\u00F1a\n" + "wssf1.s1[0]"))
+ .put("al1", new Value.ArrayValue()
+ .add(new Value.LongValue(11223344556677881L))
+ .add(new Value.LongValue(11223344556677883L)))
+ .put("l1", new Value.LongValue(1122334455667788997L))
+ .put("as1", new Value.ArrayValue()
+ .add(new Value.StringValue("per"))
+ .add(new Value.StringValue("paal")))
+ .put("i1", new Value.LongValue(7)))
.add(new Value.LongValue(10)))
- .add(new Value.ArrayValue()
- .add(new Value.ObjectValue()
- .put("d1", new Value.DoubleValue(88.790001))
- .put("s1", new Value.StringValue("string\n" + "espa\u00F1a wssf1.s1[1]"))
- .put("al1", new Value.ArrayValue()
- .add(new Value.LongValue(11223344556677881L))
- .add(new Value.LongValue(11223344556677883L)))
- .put("l1", new Value.LongValue(1122334455667788998L))
- .put("as1", new Value.ArrayValue()
- .add(new Value.StringValue("per"))
- .add(new Value.StringValue("paal")))
- .put("i1", new Value.LongValue(8)))
- .add(new Value.LongValue(20)));
+ .add(new Value.ArrayValue()
+ .add(new Value.ObjectValue()
+ .put("d1", new Value.DoubleValue(88.790001))
+ .put("s1", new Value.StringValue("string\n" + "espa\u00F1a wssf1.s1[1]"))
+ .put("al1", new Value.ArrayValue()
+ .add(new Value.LongValue(11223344556677881L))
+ .add(new Value.LongValue(11223344556677883L)))
+ .put("l1", new Value.LongValue(1122334455667788998L))
+ .put("as1", new Value.ArrayValue()
+ .add(new Value.StringValue("per"))
+ .add(new Value.StringValue("paal")))
+ .put("i1", new Value.LongValue(8)))
+ .add(new Value.LongValue(20)));
JSONString js = new JSONString(top);
String correct = "\n"
- + " <item weight=\"10\">\n"
- + " <struct-field name=\"d1\">87.790001</struct-field>\n"
- + " <struct-field name=\"s1\">string\n"
- + "espa\u00F1a\n"
- + "wssf1.s1[0]</struct-field>\n"
- + " <struct-field name=\"al1\">\n"
- + " <item>11223344556677881</item>\n"
- + " <item>11223344556677883</item>\n"
- + " </struct-field>\n"
- + " <struct-field name=\"l1\">1122334455667788997</struct-field>\n"
- + " <struct-field name=\"as1\">\n"
- + " <item>per</item>\n"
- + " <item>paal</item>\n"
- + " </struct-field>\n"
- + " <struct-field name=\"i1\">7</struct-field>\n"
- + " </item>\n"
- + " <item weight=\"20\">\n"
- + " <struct-field name=\"d1\">88.790001</struct-field>\n"
- + " <struct-field name=\"s1\">string\n"
- + "espa\u00F1a wssf1.s1[1]</struct-field>\n"
- + " <struct-field name=\"al1\">\n"
- + " <item>11223344556677881</item>\n"
- + " <item>11223344556677883</item>\n"
- + " </struct-field>\n"
- + " <struct-field name=\"l1\">1122334455667788998</struct-field>\n"
- + " <struct-field name=\"as1\">\n"
- + " <item>per</item>\n"
- + " <item>paal</item>\n"
- + " </struct-field>\n"
- + " <struct-field name=\"i1\">8</struct-field>\n"
- + " </item>\n"
- + " ";
+ + " <item weight=\"10\">\n"
+ + " <struct-field name=\"d1\">87.790001</struct-field>\n"
+ + " <struct-field name=\"s1\">string\n"
+ + "espa\u00F1a\n"
+ + "wssf1.s1[0]</struct-field>\n"
+ + " <struct-field name=\"al1\">\n"
+ + " <item>11223344556677881</item>\n"
+ + " <item>11223344556677883</item>\n"
+ + " </struct-field>\n"
+ + " <struct-field name=\"l1\">1122334455667788997</struct-field>\n"
+ + " <struct-field name=\"as1\">\n"
+ + " <item>per</item>\n"
+ + " <item>paal</item>\n"
+ + " </struct-field>\n"
+ + " <struct-field name=\"i1\">7</struct-field>\n"
+ + " </item>\n"
+ + " <item weight=\"20\">\n"
+ + " <struct-field name=\"d1\">88.790001</struct-field>\n"
+ + " <struct-field name=\"s1\">string\n"
+ + "espa\u00F1a wssf1.s1[1]</struct-field>\n"
+ + " <struct-field name=\"al1\">\n"
+ + " <item>11223344556677881</item>\n"
+ + " <item>11223344556677883</item>\n"
+ + " </struct-field>\n"
+ + " <struct-field name=\"l1\">1122334455667788998</struct-field>\n"
+ + " <struct-field name=\"as1\">\n"
+ + " <item>per</item>\n"
+ + " <item>paal</item>\n"
+ + " </struct-field>\n"
+ + " <struct-field name=\"i1\">8</struct-field>\n"
+ + " </item>\n"
+ + " ";
assertEquals(correct, js.renderFromInspector());
top = new Value.ArrayValue();
top.add(new Value.ArrayValue()
.add(new Value.StringValue("s1"))
.add(new Value.LongValue(10)))
- .add(new Value.ArrayValue()
- .add(new Value.StringValue("s2"))
- .add(new Value.LongValue(20)));
+ .add(new Value.ArrayValue()
+ .add(new Value.StringValue("s2"))
+ .add(new Value.LongValue(20)));
js = new JSONString(top);
correct = "\n" +
- " <item weight=\"10\">s1</item>\n" +
- " <item weight=\"20\">s2</item>\n" +
- " ";
+ " <item weight=\"10\">s1</item>\n" +
+ " <item weight=\"20\">s2</item>\n" +
+ " ";
assertEquals(correct, js.renderFromInspector());
}
@Test
- public void testStruct() {
+ void testStruct() {
{
Value.ObjectValue top = new Value.ObjectValue();
top.put("d1", new Value.DoubleValue(81.790001))
@@ -184,7 +184,7 @@ public class JSONStringTestCase {
+ " <item>per</item>\n"
+ " <item>paal</item>\n"
+ " </struct-field>\n",
- " <struct-field name=\"i1\">1</struct-field>\n" };
+ " <struct-field name=\"i1\">1</struct-field>\n"};
String rendered = js.renderFromInspector();
checkSubstrings(renderedFields, rendered);
@@ -213,7 +213,7 @@ public class JSONStringTestCase {
+ " <item>per</item>\n"
+ " <item>paal</item>\n"
+ " </struct-field>\n",
- " <struct-field name=\"i1\">4</struct-field>\n " };
+ " <struct-field name=\"i1\">4</struct-field>\n "};
String rendered = js.renderFromInspector();
checkSubstrings(renderedFields, rendered);
@@ -299,7 +299,7 @@ public class JSONStringTestCase {
String[] renderedFields = {
" <struct-field name=\"nss1\">\n",
" <struct-field name=\"s2\">string españa\n"
- + "ssf8.s2</struct-field>\n " };
+ + "ssf8.s2</struct-field>\n "};
String nss1Fields[] = {
" <struct-field name=\"al1\">\n"
+ " <item>11223344556677881</item>\n"
@@ -310,7 +310,7 @@ public class JSONStringTestCase {
" <struct-field name=\"as1\">\n"
+ " <item>per</item>\n"
+ " <item>paal</item>\n"
- + " </struct-field>\n" };
+ + " </struct-field>\n"};
checkSubstrings(renderedFields, rendered);
int nss1Offset = rendered.indexOf(renderedFields[0])
@@ -321,58 +321,58 @@ public class JSONStringTestCase {
}
@Test
- public void testMap() {
+ void testMap() {
String json = "[{\"key\":\"k1\",\"value\":\"v1\"},{\"key\":\"k2\",\"value\":\"v2\"}]";
JSONString js = new JSONString(json);
String correct = "\n"
- + " <item><key>k1</key><value>v1</value></item>\n"
- + " <item><key>k2</key><value>v2</value></item>\n ";
- assertEquals(correct,js.toString());
+ + " <item><key>k1</key><value>v1</value></item>\n"
+ + " <item><key>k2</key><value>v2</value></item>\n ";
+ assertEquals(correct, js.toString());
Inspector top = new Value.ArrayValue()
- .add(new Value.ObjectValue()
- .put("key", "k1")
- .put("value", "v1"))
- .add(new Value.ObjectValue()
- .put("key", "k2")
- .put("value", "v2"));
+ .add(new Value.ObjectValue()
+ .put("key", "k1")
+ .put("value", "v1"))
+ .add(new Value.ObjectValue()
+ .put("key", "k2")
+ .put("value", "v2"));
js = new JSONString(top);
assertEquals(correct, js.renderFromInspector());
}
@Test
- public void testWithData() {
- byte[] d1 = { (byte)0x41, (byte)0x42, (byte)0x43 };
- byte[] d2 = { (byte)0x00, (byte)0x01, (byte)0x00, (byte)0x02 };
- byte[] d3 = { (byte)0x12, (byte)0x34 };
- byte[] d4 = { (byte)0xff, (byte)0x80, (byte)0x7f };
+ void testWithData() {
+ byte[] d1 = {(byte) 0x41, (byte) 0x42, (byte) 0x43};
+ byte[] d2 = {(byte) 0x00, (byte) 0x01, (byte) 0x00, (byte) 0x02};
+ byte[] d3 = {(byte) 0x12, (byte) 0x34};
+ byte[] d4 = {(byte) 0xff, (byte) 0x80, (byte) 0x7f};
Inspector top = new Value.ObjectValue()
- .put("simple", new Value.DataValue(d1))
- .put("array", new Value.ArrayValue()
- .add(new Value.DataValue(d2))
- .add(new Value.DataValue(d3))
- .add(new Value.DataValue(d4)));
+ .put("simple", new Value.DataValue(d1))
+ .put("array", new Value.ArrayValue()
+ .add(new Value.DataValue(d2))
+ .add(new Value.DataValue(d3))
+ .add(new Value.DataValue(d4)));
JSONString js = new JSONString(top);
String correct = "\n"
- + " <struct-field name=\"simple\">"
- + "<data length=\"3\" encoding=\"hex\">414243</data>"
- + "</struct-field>\n"
- + " <struct-field name=\"array\">\n"
- + " <item>"
- + "<data length=\"4\" encoding=\"hex\">00010002</data>"
- + "</item>\n"
- + " <item>"
- + "<data length=\"2\" encoding=\"hex\">1234</data>"
- + "</item>\n"
- + " <item>"
- + "<data length=\"3\" encoding=\"hex\">FF807F</data>"
- + "</item>\n"
- + " </struct-field>\n ";
+ + " <struct-field name=\"simple\">"
+ + "<data length=\"3\" encoding=\"hex\">414243</data>"
+ + "</struct-field>\n"
+ + " <struct-field name=\"array\">\n"
+ + " <item>"
+ + "<data length=\"4\" encoding=\"hex\">00010002</data>"
+ + "</item>\n"
+ + " <item>"
+ + "<data length=\"2\" encoding=\"hex\">1234</data>"
+ + "</item>\n"
+ + " <item>"
+ + "<data length=\"3\" encoding=\"hex\">FF807F</data>"
+ + "</item>\n"
+ + " </struct-field>\n ";
assertEquals(correct, js.renderFromInspector());
}
@Test
- public void testArrayOfArray() {
+ void testArrayOfArray() {
String json = "[[\"c1\", 0], [\"c2\", 2, 3], [\"c3\", 3, 4, 5], [\"c4\", 4,5,6,7]]";
JSONString js = new JSONString(json);
Inspector outer = js.inspect();
@@ -402,48 +402,48 @@ public class JSONStringTestCase {
}
@Test
- public void testSimpleArrays() {
+ void testSimpleArrays() {
String json = "[1, 2, 3]";
JSONString js = new JSONString(json);
String correct = "\n"
- + " <item>1</item>\n"
- + " <item>2</item>\n"
- + " <item>3</item>\n ";
+ + " <item>1</item>\n"
+ + " <item>2</item>\n"
+ + " <item>3</item>\n ";
assertEquals(correct, js.toString());
Inspector top = new Value.ArrayValue()
- .add(1).add(2).add(3);
+ .add(1).add(2).add(3);
js = new JSONString(top);
assertEquals(correct, js.renderFromInspector());
json = "[1.0, 2.0, 3.0]";
js = new JSONString(json);
correct = "\n"
- + " <item>1.0</item>\n"
- + " <item>2.0</item>\n"
- + " <item>3.0</item>\n ";
+ + " <item>1.0</item>\n"
+ + " <item>2.0</item>\n"
+ + " <item>3.0</item>\n ";
assertEquals(correct, js.toString());
top = new Value.ArrayValue()
- .add(1.0).add(2.0).add(3.0);
+ .add(1.0).add(2.0).add(3.0);
js = new JSONString(top);
assertEquals(correct, js.renderFromInspector());
json = "[\"a\", \"b\", \"c\"]";
correct = "\n"
- + " <item>a</item>\n"
- + " <item>b</item>\n"
- + " <item>c</item>\n ";
+ + " <item>a</item>\n"
+ + " <item>b</item>\n"
+ + " <item>c</item>\n ";
js = new JSONString(json);
assertEquals(correct, js.toString());
top = new Value.ArrayValue()
- .add("a").add("b").add("c");
+ .add("a").add("b").add("c");
js = new JSONString(top);
assertEquals(correct, js.renderFromInspector());
}
@Test
- public void testArrayOfStruct() {
+ void testArrayOfStruct() {
String json = "[{\"as1\":[\"per\",\"paal\"],"
+ "\"l1\":1122334455667788994,\"d1\":74.790001,"
+ "\"i1\":14,\"al1\":[11223344556677881,11223344556677883],\"s1\":\"string\\n"
@@ -465,7 +465,7 @@ public class JSONStringTestCase {
+ " <item>paal</item>\n"
+ " </struct-field>\n",
" <struct-field name=\"s1\">string\n" + "españa\n"
- + "asf1[0].s1</struct-field>\n" };
+ + "asf1[0].s1</struct-field>\n"};
String separator = " </item>\n" + " <item>\n";
String[] o2Fields = {
" <struct-field name=\"l1\">1122334455667788995</struct-field>\n",
@@ -480,7 +480,7 @@ public class JSONStringTestCase {
+ " <item>paal</item>\n"
+ " </struct-field>\n",
" <struct-field name=\"s1\">string\n"
- + "españa asf1[1].s1</struct-field>\n" };
+ + "españa asf1[1].s1</struct-field>\n"};
String rendered = js.toString();
int o2Offset = rendered.indexOf(separator);
@@ -535,153 +535,153 @@ public class JSONStringTestCase {
}
}
-/*** here is some json for you
-
- [{"asf":"here is 1st simple string field",
- "map":[{"key":"one key string","value":["one value string","embedded array"]},
- {"key":"two key string","value":["two value string","embedded array"]}],
- "sf2":"here is 2nd simple string field"},
- {"asf":"here is 3rd simple string field",
- "map":[{"key":"three key string","value":["three value string","embedded array"]},
- {"key":"four key string","value":["four value string","embedded array"]}],
- "sf2":"here is 4th simple string field"},
- ]
-
-***/
-
-/*** and here is some corresponding XML
-
- <item>
- <struct-field name="asf">here is 1st simple string field</struct-field>
- <struct-field name="map">
- <item><key>one key string</key><value>
- <item>one value string</item>
- <item>embedded array</item>
- </value></item>
- <item><key>two key string</key><value>
- <item>two value string</item>
- <item>embedded array</item>
- </value></item>
- </struct-field>
- <struct-field name="sf2">here is 2nd simple string field</struct-field>
- </item>
- <item>
- <struct-field name="asf">here is 3rd simple string field</struct-field>
- <struct-field name="map">
- <item><key>three key string</key><value>
- <item>three value string</item>
- <item>embedded array</item>
- </value></item>
- <item><key>four key string</key><value>
- <item>four value string</item>
- <item>embedded array</item>
- </value></item>
- </struct-field>
- <struct-field name="sf2">here is 4th simple string field</struct-field>
- </item>
-
-***/
+ /*** here is some json for you
+
+ [{"asf":"here is 1st simple string field",
+ "map":[{"key":"one key string","value":["one value string","embedded array"]},
+ {"key":"two key string","value":["two value string","embedded array"]}],
+ "sf2":"here is 2nd simple string field"},
+ {"asf":"here is 3rd simple string field",
+ "map":[{"key":"three key string","value":["three value string","embedded array"]},
+ {"key":"four key string","value":["four value string","embedded array"]}],
+ "sf2":"here is 4th simple string field"},
+ ]
+
+ ***/
+
+ /*** and here is some corresponding XML
+
+ <item>
+ <struct-field name="asf">here is 1st simple string field</struct-field>
+ <struct-field name="map">
+ <item><key>one key string</key><value>
+ <item>one value string</item>
+ <item>embedded array</item>
+ </value></item>
+ <item><key>two key string</key><value>
+ <item>two value string</item>
+ <item>embedded array</item>
+ </value></item>
+ </struct-field>
+ <struct-field name="sf2">here is 2nd simple string field</struct-field>
+ </item>
+ <item>
+ <struct-field name="asf">here is 3rd simple string field</struct-field>
+ <struct-field name="map">
+ <item><key>three key string</key><value>
+ <item>three value string</item>
+ <item>embedded array</item>
+ </value></item>
+ <item><key>four key string</key><value>
+ <item>four value string</item>
+ <item>embedded array</item>
+ </value></item>
+ </struct-field>
+ <struct-field name="sf2">here is 4th simple string field</struct-field>
+ </item>
+
+ ***/
@Test
- public void testArrayOfStructWithMap() {
+ void testArrayOfStructWithMap() {
String json = "[{\"asf\":\"here is 1st simple string field\",\"map\":[{\"key\":\"one key string\",\"value\":[\"one value string\",\"embedded array\"]},{\"key\":\"two key string\",\"value\":[\"two value string\",\"embedded array\"]}],\"sf2\":\"here is 2nd simple string field\"},{\"asf\":\"here is 3rd simple string field\",\"map\":[{\"key\":\"three key string\",\"value\":[\"three value string\",\"embedded array\"]},{\"key\":\"four key string\",\"value\":[\"four value string\",\"embedded array\"]}],\"sf2\":\"here is 4th simple string field\"}]";
JSONString js = new JSONString(json);
String correct = "\n"
- + " <item>\n"
- + " <struct-field name=\"asf\">here is 1st simple string field</struct-field>\n"
- + " <struct-field name=\"map\">\n"
- + " <item><key>one key string</key><value>\n"
- + " <item>one value string</item>\n"
- + " <item>embedded array</item>\n"
- + " </value></item>\n"
- + " <item><key>two key string</key><value>\n"
- + " <item>two value string</item>\n"
- + " <item>embedded array</item>\n"
- + " </value></item>\n"
- + " </struct-field>\n"
- + " <struct-field name=\"sf2\">here is 2nd simple string field</struct-field>\n"
- + " </item>\n"
- + " <item>\n"
- + " <struct-field name=\"asf\">here is 3rd simple string field</struct-field>\n"
- + " <struct-field name=\"map\">\n"
- + " <item><key>three key string</key><value>\n"
- + " <item>three value string</item>\n"
- + " <item>embedded array</item>\n"
- + " </value></item>\n"
- + " <item><key>four key string</key><value>\n"
- + " <item>four value string</item>\n"
- + " <item>embedded array</item>\n"
- + " </value></item>\n"
- + " </struct-field>\n"
- + " <struct-field name=\"sf2\">here is 4th simple string field</struct-field>\n"
- + " </item>\n"
- + " ";
+ + " <item>\n"
+ + " <struct-field name=\"asf\">here is 1st simple string field</struct-field>\n"
+ + " <struct-field name=\"map\">\n"
+ + " <item><key>one key string</key><value>\n"
+ + " <item>one value string</item>\n"
+ + " <item>embedded array</item>\n"
+ + " </value></item>\n"
+ + " <item><key>two key string</key><value>\n"
+ + " <item>two value string</item>\n"
+ + " <item>embedded array</item>\n"
+ + " </value></item>\n"
+ + " </struct-field>\n"
+ + " <struct-field name=\"sf2\">here is 2nd simple string field</struct-field>\n"
+ + " </item>\n"
+ + " <item>\n"
+ + " <struct-field name=\"asf\">here is 3rd simple string field</struct-field>\n"
+ + " <struct-field name=\"map\">\n"
+ + " <item><key>three key string</key><value>\n"
+ + " <item>three value string</item>\n"
+ + " <item>embedded array</item>\n"
+ + " </value></item>\n"
+ + " <item><key>four key string</key><value>\n"
+ + " <item>four value string</item>\n"
+ + " <item>embedded array</item>\n"
+ + " </value></item>\n"
+ + " </struct-field>\n"
+ + " <struct-field name=\"sf2\">here is 4th simple string field</struct-field>\n"
+ + " </item>\n"
+ + " ";
assertEquals(correct, js.toString());
Inspector top = new Value.ArrayValue()
- .add(new Value.ObjectValue()
- .put("asf", "here is 1st simple string field")
- .put("map", new Value.ArrayValue()
- .add(new Value.ObjectValue()
- .put("key", "one key string")
- .put("value", new Value.ArrayValue()
- .add("one value string")
- .add("embedded array")))
- .add(new Value.ObjectValue()
- .put("key", "two key string")
- .put("value", new Value.ArrayValue()
- .add("two value string")
- .add("embedded array"))))
- .put("sf2", "here is 2nd simple string field"))
- .add(new Value.ObjectValue()
- .put("asf", "here is 3rd simple string field")
- .put("map", new Value.ArrayValue()
- .add(new Value.ObjectValue()
- .put("key", "three key string")
- .put("value", new Value.ArrayValue()
- .add("three value string")
- .add("embedded array")))
- .add(new Value.ObjectValue()
- .put("key", "four key string")
- .put("value", new Value.ArrayValue()
- .add("four value string")
- .add("embedded array"))))
- .put("sf2", "here is 4th simple string field"));
+ .add(new Value.ObjectValue()
+ .put("asf", "here is 1st simple string field")
+ .put("map", new Value.ArrayValue()
+ .add(new Value.ObjectValue()
+ .put("key", "one key string")
+ .put("value", new Value.ArrayValue()
+ .add("one value string")
+ .add("embedded array")))
+ .add(new Value.ObjectValue()
+ .put("key", "two key string")
+ .put("value", new Value.ArrayValue()
+ .add("two value string")
+ .add("embedded array"))))
+ .put("sf2", "here is 2nd simple string field"))
+ .add(new Value.ObjectValue()
+ .put("asf", "here is 3rd simple string field")
+ .put("map", new Value.ArrayValue()
+ .add(new Value.ObjectValue()
+ .put("key", "three key string")
+ .put("value", new Value.ArrayValue()
+ .add("three value string")
+ .add("embedded array")))
+ .add(new Value.ObjectValue()
+ .put("key", "four key string")
+ .put("value", new Value.ArrayValue()
+ .add("four value string")
+ .add("embedded array"))))
+ .put("sf2", "here is 4th simple string field"));
js = new JSONString(top);
assertEquals(correct, js.renderFromInspector());
}
@Test
- public void testArrayOfStructWithEmptyMap() {
+ void testArrayOfStructWithEmptyMap() {
String json = "[{\"asf\":\"here is 1st simple string field\",\"map\":[],\"sf2\":\"here is 2nd simple string field\"},{\"asf\":\"here is 3rd simple string field\",\"map\":[],\"sf2\":\"here is 4th simple string field\"}]";
JSONString js = new JSONString(json);
String correct = "\n"
- + " <item>\n"
- + " <struct-field name=\"asf\">here is 1st simple string field</struct-field>\n"
- + " <struct-field name=\"map\"></struct-field>\n"
- + " <struct-field name=\"sf2\">here is 2nd simple string field</struct-field>\n"
- + " </item>\n"
- + " <item>\n"
- + " <struct-field name=\"asf\">here is 3rd simple string field</struct-field>\n"
- + " <struct-field name=\"map\"></struct-field>\n"
- + " <struct-field name=\"sf2\">here is 4th simple string field</struct-field>\n"
- + " </item>\n"
- + " ";
+ + " <item>\n"
+ + " <struct-field name=\"asf\">here is 1st simple string field</struct-field>\n"
+ + " <struct-field name=\"map\"></struct-field>\n"
+ + " <struct-field name=\"sf2\">here is 2nd simple string field</struct-field>\n"
+ + " </item>\n"
+ + " <item>\n"
+ + " <struct-field name=\"asf\">here is 3rd simple string field</struct-field>\n"
+ + " <struct-field name=\"map\"></struct-field>\n"
+ + " <struct-field name=\"sf2\">here is 4th simple string field</struct-field>\n"
+ + " </item>\n"
+ + " ";
assertEquals(correct, js.toString());
Inspector top = new Value.ArrayValue()
- .add(new Value.ObjectValue()
- .put("asf", "here is 1st simple string field")
- .put("map", new Value.ArrayValue())
- .put("sf2", "here is 2nd simple string field"))
- .add(new Value.ObjectValue()
- .put("asf", "here is 3rd simple string field")
- .put("map", new Value.ArrayValue())
- .put("sf2", "here is 4th simple string field"));
+ .add(new Value.ObjectValue()
+ .put("asf", "here is 1st simple string field")
+ .put("map", new Value.ArrayValue())
+ .put("sf2", "here is 2nd simple string field"))
+ .add(new Value.ObjectValue()
+ .put("asf", "here is 3rd simple string field")
+ .put("map", new Value.ArrayValue())
+ .put("sf2", "here is 4th simple string field"));
js = new JSONString(top);
assertEquals(correct, js.renderFromInspector());
@@ -718,7 +718,7 @@ public class JSONStringTestCase {
}
@Test
- public void testInspectorToContentMapping() {
+ void testInspectorToContentMapping() {
String content1 = new JSONString(getSlime1()).getContent();
String content2 = new JSONString(getSlime2()).getContent();
String content3 = new JSONString(getSlime3()).getContent();
@@ -732,7 +732,7 @@ public class JSONStringTestCase {
}
@Test
- public void testContentToInspectorMapping() {
+ void testContentToInspectorMapping() {
Inspector value1 = new JSONString("").inspect();
Inspector value2 = new JSONString("foo").inspect();
Inspector value3 = new JSONString("\"foo\"").inspect();
diff --git a/container-search/src/test/java/com/yahoo/prelude/hitfield/test/TokenFieldIteratorTestCase.java b/container-search/src/test/java/com/yahoo/prelude/hitfield/test/TokenFieldIteratorTestCase.java
index 4b59a31785a..1e689d95cee 100644
--- a/container-search/src/test/java/com/yahoo/prelude/hitfield/test/TokenFieldIteratorTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/hitfield/test/TokenFieldIteratorTestCase.java
@@ -4,11 +4,11 @@ package com.yahoo.prelude.hitfield.test;
import java.util.ListIterator;
import com.yahoo.prelude.hitfield.FieldPart;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
import com.yahoo.prelude.hitfield.HitField;
import com.yahoo.prelude.hitfield.StringFieldPart;
-import org.junit.Test;
-
-import static org.junit.Assert.assertEquals;
+import org.junit.jupiter.api.Test;
/**
* Tests the FieldTokenIterator class
@@ -18,35 +18,35 @@ import static org.junit.Assert.assertEquals;
public class TokenFieldIteratorTestCase {
@Test
- public void testTokenIteratorNext() {
+ void testTokenIteratorNext() {
HitField hf = new HitField("boo", "hei paa deg");
assertEquals(3, hf.getTokenizedContent().size());
ListIterator<?> l = hf.tokenIterator();
- FieldPart p = (FieldPart)l.next();
+ FieldPart p = (FieldPart) l.next();
assertEquals("hei", p.getContent());
- p = (FieldPart)l.next();
+ p = (FieldPart) l.next();
assertEquals("paa", p.getContent());
- p = (FieldPart)l.next();
+ p = (FieldPart) l.next();
assertEquals("deg", p.getContent());
assertEquals(false, l.hasNext());
}
@Test
- public void testTokenIteratorPrevious() {
+ void testTokenIteratorPrevious() {
HitField hf = new HitField("boo", "hei paa");
ListIterator<?> l = hf.tokenIterator();
- FieldPart p = (FieldPart)l.next();
+ FieldPart p = (FieldPart) l.next();
assertEquals("hei", p.getContent());
- p = (FieldPart)l.next();
+ p = (FieldPart) l.next();
assertEquals("paa", p.getContent());
- p = (FieldPart)l.previous();
+ p = (FieldPart) l.previous();
assertEquals("paa", p.getContent());
- p = (FieldPart)l.previous();
+ p = (FieldPart) l.previous();
assertEquals("hei", p.getContent());
}
@Test
- public void testTokenIteratorSet() {
+ void testTokenIteratorSet() {
HitField hf = new HitField("boo", "hei paa deg");
assertEquals(3, hf.getTokenizedContent().size());
ListIterator<FieldPart> l = hf.tokenIterator();
@@ -61,7 +61,7 @@ public class TokenFieldIteratorTestCase {
}
@Test
- public void testTokenIteratorAdd() {
+ void testTokenIteratorAdd() {
HitField hf = new HitField("boo", "hei paa deg");
assertEquals(3, hf.getTokenizedContent().size());
ListIterator<FieldPart> l = hf.tokenIterator();
@@ -76,7 +76,7 @@ public class TokenFieldIteratorTestCase {
}
@Test
- public void testTokenIteratorRemove() {
+ void testTokenIteratorRemove() {
HitField hf = new HitField("boo", "hei paa deg");
ListIterator<FieldPart> l = hf.tokenIterator();
l.next();
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/ItemHelperTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/ItemHelperTestCase.java
index 657d7fb30bc..dccf471fb04 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/ItemHelperTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/ItemHelperTestCase.java
@@ -1,7 +1,8 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.query;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
@@ -9,8 +10,7 @@ import java.util.ArrayList;
import java.util.List;
import com.yahoo.search.test.QueryTestCase;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.yahoo.search.Query;
@@ -23,14 +23,14 @@ import com.yahoo.search.Query;
public class ItemHelperTestCase {
@Test
- public final void testGetNumTerms() {
+ final void testGetNumTerms() {
ItemHelper helper = new ItemHelper();
Query q = new Query("/?query=" + enc("a b c"));
assertEquals(3, helper.getNumTerms(q.getModel().getQueryTree().getRoot()));
}
@Test
- public final void testGetPositiveTerms() {
+ final void testGetPositiveTerms() {
ItemHelper helper = new ItemHelper();
Query q = new Query("/?query=" + enc("a b c \"d e\" -f"));
List<IndexedItem> l = new ArrayList<>();
@@ -52,7 +52,7 @@ public class ItemHelperTestCase {
c = true;
}
}
- assertFalse("An item is missing.", (a & b & c & d) == false);
+ assertNotNull(false);
}
private String enc(String s) {
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/ItemLabelTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/ItemLabelTestCase.java
index 06808d2c8d5..17a4ce400ff 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/ItemLabelTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/ItemLabelTestCase.java
@@ -3,9 +3,9 @@ package com.yahoo.prelude.query;
import java.lang.reflect.Modifier;
-import static org.junit.Assert.*;
-import org.junit.Test;
+import static org.junit.jupiter.api.Assertions.*;
+import org.junit.jupiter.api.Test;
import com.yahoo.search.Query;
import com.yahoo.prelude.query.textualrepresentation.Discloser;
@@ -27,13 +27,13 @@ public class ItemLabelTestCase {
}
@Test
- public final void testLabelVisibility() throws Exception {
+ final void testLabelVisibility() throws Exception {
assertTrue(Modifier.isPublic(Item.class.getMethod("setLabel", String.class).getModifiers()));
assertTrue(Modifier.isPublic(Item.class.getMethod("getLabel").getModifiers()));
}
@Test
- public final void testLabelAccess() {
+ final void testLabelAccess() {
Item item = new WordItem("word");
assertFalse(item.hasUniqueID());
assertNull(item.getLabel());
@@ -43,7 +43,7 @@ public class ItemLabelTestCase {
}
@Test
- public final void testLabelDisclose() {
+ final void testLabelDisclose() {
LabelCatcher catcher = new LabelCatcher();
Item item = new WordItem("word");
item.disclose(catcher);
@@ -54,7 +54,7 @@ public class ItemLabelTestCase {
}
@Test
- public final void testLabelEncode() {
+ final void testLabelEncode() {
Item w1 = new WordItem("w1");
Item w2 = new WordItem("w2");
Item w3 = new WordItem("w3");
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/ItemsCommonStuffTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/ItemsCommonStuffTestCase.java
index 418d7121769..f25c858a6a4 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/ItemsCommonStuffTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/ItemsCommonStuffTestCase.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.prelude.query;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
import java.nio.ByteBuffer;
import java.util.Arrays;
@@ -9,8 +9,7 @@ import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.util.regex.PatternSyntaxException;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.yahoo.prelude.query.Item.ItemType;
/**
@@ -21,7 +20,7 @@ import com.yahoo.prelude.query.Item.ItemType;
public class ItemsCommonStuffTestCase {
@Test
- public void testLoops() {
+ void testLoops() {
AndSegmentItem as = new AndSegmentItem("farmyards", false, false);
boolean caught = false;
try {
@@ -58,7 +57,7 @@ public class ItemsCommonStuffTestCase {
}
@Test
- public void testIndexName() {
+ void testIndexName() {
WordItem w = new WordItem("nalle");
AndItem a = new AndItem();
a.addItem(w);
@@ -68,7 +67,7 @@ public class ItemsCommonStuffTestCase {
}
@Test
- public void testBoundaries() {
+ void testBoundaries() {
WordItem w = new WordItem("nalle");
AndItem a = new AndItem();
boolean caught = false;
@@ -102,7 +101,7 @@ public class ItemsCommonStuffTestCase {
}
@Test
- public void testRemoving() {
+ void testRemoving() {
AndItem other = new AndItem();
WordItem w = new WordItem("nalle");
AndItem a = new AndItem();
@@ -117,7 +116,7 @@ public class ItemsCommonStuffTestCase {
}
@Test
- public void testGeneralMutability() {
+ void testGeneralMutability() {
AndItem a = new AndItem();
assertFalse(a.isLocked());
a.lock();
@@ -125,7 +124,7 @@ public class ItemsCommonStuffTestCase {
}
@Test
- public void testCounting() {
+ void testCounting() {
WordItem w = new WordItem("nalle");
AndItem a = new AndItem();
WordItem v = new WordItem("bamse");
@@ -139,7 +138,7 @@ public class ItemsCommonStuffTestCase {
}
@Test
- public void testIteratorJuggling() {
+ void testIteratorJuggling() {
AndItem a = new AndItem();
WordItem w0 = new WordItem("nalle");
WordItem w1 = new WordItem("bamse");
@@ -168,7 +167,7 @@ public class ItemsCommonStuffTestCase {
}
@Test
- public void testIdStuff() {
+ void testIdStuff() {
Item i;
String expected = "i";
i = new ExactStringItem(expected);
@@ -187,7 +186,7 @@ public class ItemsCommonStuffTestCase {
i = new WeightedSetItem("nalle");
assertEquals(ItemType.WEIGHTEDSET, i.getItemType());
assertEquals("WEIGHTEDSET", i.getName());
- i = new AndSegmentItem("",false, false);
+ i = new AndSegmentItem("", false, false);
assertEquals(ItemType.AND, i.getItemType());
assertEquals("SAND", i.getName());
i = new WeakAndItem();
@@ -196,7 +195,7 @@ public class ItemsCommonStuffTestCase {
}
@Test
- public void testEquivBuilding() {
+ void testEquivBuilding() {
WordItem w = new WordItem("nalle");
WordItem v = new WordItem("bamse");
w.setConnectivity(v, 1.0);
@@ -206,7 +205,7 @@ public class ItemsCommonStuffTestCase {
}
@Test
- public final void testEquivBuildingFromCollection() {
+ final void testEquivBuildingFromCollection() {
WordItem w = new WordItem("nalle");
WordItem v = new WordItem("bamse");
w.setConnectivity(v, 1.0);
@@ -220,7 +219,7 @@ public class ItemsCommonStuffTestCase {
}
@Test
- public void testSegment() {
+ void testSegment() {
AndSegmentItem as = new AndSegmentItem("farmyards", false, false);
assertFalse(as.isLocked());
WordItem firstItem = new WordItem("nalle");
@@ -253,20 +252,20 @@ public class ItemsCommonStuffTestCase {
}
@Test
- public void testMarkersVsWords() {
+ void testMarkersVsWords() {
WordItem mw0 = MarkerWordItem.createEndOfHost();
WordItem mw1 = MarkerWordItem.createStartOfHost();
WordItem w0 = new WordItem("$");
WordItem w1 = new WordItem("^");
assertEquals(w0.getWord(), mw0.getWord());
assertEquals(w1.getWord(), mw1.getWord());
- assertFalse(mw0.equals(w0));
- assertTrue(mw0.equals(MarkerWordItem.createEndOfHost()));
- assertFalse(w1.hashCode() == mw1.hashCode());
+ assertNotEquals(mw0, w0);
+ assertEquals(mw0, MarkerWordItem.createEndOfHost());
+ assertNotNull(mw1.hashCode());
}
@Test
- public void testNumberBasics() {
+ void testNumberBasics() {
String expected = "12";
IntItem i = new IntItem(expected, "num");
assertEquals(expected, i.stringValue());
@@ -279,12 +278,12 @@ public class ItemsCommonStuffTestCase {
assertTrue(i.isStemmed());
assertFalse(i.isWords());
assertEquals(1, i.getNumWords());
- assertFalse(i.equals(new IntItem(expected3)));
- assertTrue(i.equals(new IntItem(expected3, "num")));
+ assertNotEquals(i, new IntItem(expected3));
+ assertEquals(i, new IntItem(expected3, "num"));
}
@Test
- public void testNullItemFailsProperly() {
+ void testNullItemFailsProperly() {
NullItem n = new NullItem();
n.setIndexName("nalle");
boolean caught = false;
@@ -311,7 +310,7 @@ public class ItemsCommonStuffTestCase {
}
@Test
- public void testNearisNotAnd() {
+ void testNearisNotAnd() {
AndItem a = new AndItem();
NearItem n = new NearItem();
n.setDistance(2);
@@ -323,14 +322,14 @@ public class ItemsCommonStuffTestCase {
fill(n);
fill(n2);
fill(n3);
- assertFalse(a.hashCode() == n.hashCode());
- assertFalse(n.equals(a));
- assertTrue(n.equals(n2));
- assertFalse(n.equals(n3));
+ assertNotNull(n.hashCode());
+ assertNotEquals(n, a);
+ assertEquals(n, n2);
+ assertNotEquals(n, n3);
}
@Test
- public void testPhraseSegmentBasics() {
+ void testPhraseSegmentBasics() {
AndSegmentItem a = new AndSegmentItem("gnurk", "gurk", false, false);
fill(a);
a.lock();
@@ -352,7 +351,7 @@ public class ItemsCommonStuffTestCase {
}
@Test
- public void testPhraseConnectivity() {
+ void testPhraseConnectivity() {
WordItem w = new WordItem("a");
PhraseItem p = new PhraseItem();
fill(p);
@@ -362,7 +361,7 @@ public class ItemsCommonStuffTestCase {
}
@Test
- public void testBaseClassPhraseSegments() {
+ void testBaseClassPhraseSegments() {
PhraseSegmentItem p = new PhraseSegmentItem("g", false, true);
fill(p);
assertEquals(4, p.encode(ByteBuffer.allocate(5000)));
@@ -373,18 +372,18 @@ public class ItemsCommonStuffTestCase {
}
@Test
- public void testTermTypeBasic() {
- assertFalse(TermType.AND.equals(TermType.DEFAULT));
- assertFalse(TermType.AND.equals(Integer.valueOf(10)));
- assertTrue(TermType.AND.equals(TermType.AND));
+ void testTermTypeBasic() {
+ assertNotEquals(TermType.AND, TermType.DEFAULT);
+ assertNotEquals(TermType.AND, Integer.valueOf(10));
+ assertEquals(TermType.AND, TermType.AND);
assertSame(AndItem.class, TermType.DEFAULT.createItemClass().getClass());
assertSame(CompositeItem.class, TermType.DEFAULT.getItemClass());
- assertFalse(TermType.AND.hashCode() == TermType.PHRASE.hashCode());
+ assertNotNull(TermType.PHRASE.hashCode());
assertEquals("term type 'not'", TermType.NOT.toString());
}
@Test
- public void testRegexp() {
+ void testRegexp() {
RegExpItem empty = new RegExpItem("a", true, "");
assertTrue(empty.isFromQuery());
assertTrue(empty.isStemmed());
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/TaggableItemsTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/TaggableItemsTestCase.java
index 3d16859a79d..ec2a69fb9b0 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/TaggableItemsTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/TaggableItemsTestCase.java
@@ -1,18 +1,15 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.query;
-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.jupiter.api.Assertions.*;
import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
/**
* Keep CompositeTaggableItem, SimpleTaggableItem and TaggableSegmentItem in
@@ -22,11 +19,11 @@ import org.junit.Test;
*/
public class TaggableItemsTestCase {
- @Before
+ @BeforeEach
public void setUp() throws Exception {
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
}
@@ -97,7 +94,7 @@ public class TaggableItemsTestCase {
}
@Test
- public void requireSimilarAPIs() {
+ void requireSimilarAPIs() {
final Method[] composite = CompositeTaggableItem.class
.getDeclaredMethods();
final Method[] simple = SimpleTaggableItem.class.getDeclaredMethods();
@@ -123,7 +120,7 @@ public class TaggableItemsTestCase {
}
@Test
- public final void testSetUniqueID() {
+ final void testSetUniqueID() {
final PhraseSegmentItem p = new PhraseSegmentItem("farmyards", false,
false);
assertFalse(p.hasUniqueID());
@@ -133,7 +130,7 @@ public class TaggableItemsTestCase {
}
@Test
- public final void testSetConnectivity() {
+ final void testSetConnectivity() {
final PhraseSegmentItem p = new PhraseSegmentItem("farmyards", false,
false);
assertEquals(0.0d, p.getConnectivity(), 1e-9);
@@ -145,7 +142,7 @@ public class TaggableItemsTestCase {
}
@Test
- public final void testSetSignificance() {
+ final void testSetSignificance() {
final PhraseSegmentItem p = new PhraseSegmentItem("farmyards", false,
false);
// unset
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/WordAlternativesItemTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/WordAlternativesItemTestCase.java
index 4f39e07f6d3..c246abb14da 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/WordAlternativesItemTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/WordAlternativesItemTestCase.java
@@ -1,13 +1,13 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.query;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.List;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.yahoo.prelude.query.WordAlternativesItem.Alternative;
/**
@@ -18,7 +18,7 @@ import com.yahoo.prelude.query.WordAlternativesItem.Alternative;
public class WordAlternativesItemTestCase {
@Test
- public final void testWordAlternativesItem() {
+ final void testWordAlternativesItem() {
List<Alternative> terms = new ArrayList<>();
List<Alternative> expected;
terms.add(new Alternative("1", 1.0));
@@ -35,7 +35,7 @@ public class WordAlternativesItemTestCase {
}
@Test
- public final void testSetAlternatives() {
+ final void testSetAlternatives() {
List<Alternative> terms = new ArrayList<>();
terms.add(new Alternative("1", 1.0));
terms.add(new Alternative("2", 1.0));
@@ -43,19 +43,19 @@ public class WordAlternativesItemTestCase {
terms.add(new Alternative("1", 1.5));
terms.add(new Alternative("2", 0.5));
w.setAlternatives(terms);
- assertTrue("Could not overwrite alternative",
- w.getAlternatives().stream().anyMatch((a) -> a.word.equals("1") && a.exactness == 1.5));
- assertTrue("Old alternative unexpectedly removed",
- w.getAlternatives().stream().anyMatch((a) -> a.word.equals("2") && a.exactness == 1.0));
+ assertTrue(w.getAlternatives().stream().anyMatch((a) -> a.word.equals("1") && a.exactness == 1.5),
+ "Could not overwrite alternative");
+ assertTrue(w.getAlternatives().stream().anyMatch((a) -> a.word.equals("2") && a.exactness == 1.0),
+ "Old alternative unexpectedly removed");
assertEquals(2, w.getAlternatives().size());
terms.add(new Alternative("3", 0.5));
w.setAlternatives(terms);
- assertTrue("Could not add new term",
- w.getAlternatives().stream().anyMatch((a) -> a.word.equals("3") && a.exactness == 0.5));
+ assertTrue(w.getAlternatives().stream().anyMatch((a) -> a.word.equals("3") && a.exactness == 0.5),
+ "Could not add new term");
}
@Test
- public final void testAddTerm() {
+ final void testAddTerm() {
List<Alternative> terms = new ArrayList<>();
terms.add(new Alternative("1", 1.0));
terms.add(new Alternative("2", 1.0));
@@ -63,12 +63,12 @@ public class WordAlternativesItemTestCase {
w.addTerm("1", 0.1);
assertEquals(terms, w.getAlternatives());
w.addTerm("1", 2.0);
- assertTrue("Could not add new alternative",
- w.getAlternatives().stream().anyMatch((a) -> a.word.equals("1") && a.exactness == 2.0));
+ assertTrue(w.getAlternatives().stream().anyMatch((a) -> a.word.equals("1") && a.exactness == 2.0),
+ "Could not add new alternative");
assertEquals(2, w.getAlternatives().size());
w.addTerm("3", 0.5);
- assertTrue("Could not add new term",
- w.getAlternatives().stream().anyMatch((a) -> a.word.equals("3") && a.exactness == 0.5));
+ assertTrue(w.getAlternatives().stream().anyMatch((a) -> a.word.equals("3") && a.exactness == 0.5),
+ "Could not add new term");
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/parser/UnicodePropertyDumpTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/parser/UnicodePropertyDumpTestCase.java
index 5e19f2e2ae6..40911fd6e11 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/parser/UnicodePropertyDumpTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/parser/UnicodePropertyDumpTestCase.java
@@ -1,13 +1,13 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.query.parser;
-import static org.junit.Assert.assertEquals;
-
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Test UnicodePropertyDump gives expected data.
@@ -17,7 +17,7 @@ import org.junit.Test;
public class UnicodePropertyDumpTestCase {
@Test
- public final void testMain() throws IOException {
+ final void testMain() throws IOException {
ByteArrayOutputStream toCheck;
PrintStream out;
toCheck = new ByteArrayOutputStream();
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/parser/test/ExactMatchAndDefaultIndexTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/parser/test/ExactMatchAndDefaultIndexTestCase.java
index a662afcd51c..cda966f714f 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/parser/test/ExactMatchAndDefaultIndexTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/parser/test/ExactMatchAndDefaultIndexTestCase.java
@@ -7,14 +7,14 @@ import com.yahoo.prelude.IndexModel;
import com.yahoo.prelude.SearchDefinition;
import com.yahoo.search.Query;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Check default index propagates correctly to the tokenizer.
@@ -24,7 +24,7 @@ import static org.junit.Assert.assertEquals;
public class ExactMatchAndDefaultIndexTestCase {
@Test
- public void testExactMatchTokenization() {
+ void testExactMatchTokenization() {
SearchDefinition sd = new SearchDefinition("testsd");
Index index = new Index("testexact");
index.setExact(true, null);
@@ -39,7 +39,7 @@ public class ExactMatchAndDefaultIndexTestCase {
}
@Test
- public void testDefaultIndexSpecialChars() {
+ void testDefaultIndexSpecialChars() {
Query q = new Query("?query=" + enc("dog & cat") + "&default-index=textsearch");
assertEquals("WEAKAND(100) textsearch:dog textsearch:cat", q.getModel().getQueryTree().getRoot().toString());
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/parser/test/ParseTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/parser/test/ParseTestCase.java
index 77d8b2b973e..bd6b2f1f21d 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/parser/test/ParseTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/parser/test/ParseTestCase.java
@@ -24,14 +24,11 @@ import com.yahoo.prelude.query.WordItem;
import com.yahoo.language.process.SpecialTokens;
import com.yahoo.prelude.query.parser.TestLinguistics;
import com.yahoo.search.Query;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Iterator;
-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 query parsing.
@@ -41,562 +38,562 @@ import static org.junit.Assert.assertTrue;
public class ParseTestCase {
private final ParsingTester tester = new ParsingTester();
-
+
@Test
- public void testSimpleTermQuery() {
+ void testSimpleTermQuery() {
tester.assertParsed("foobar", "foobar", Query.Type.ANY);
}
@Test
- public void testTermWithIndexPrefix() {
+ void testTermWithIndexPrefix() {
tester.assertParsed("url:foobar",
- "url:foobar",
- Query.Type.ANY);
+ "url:foobar",
+ Query.Type.ANY);
}
@Test
- public void testTermWithCatalogAndIndexPrefix() {
+ void testTermWithCatalogAndIndexPrefix() {
tester.assertParsed("normal.title:foobar", "normal.title:foobar", Query.Type.ANY);
}
@Test
- public void testMultipleTermsWithUTF8EncodingOred() {
+ void testMultipleTermsWithUTF8EncodingOred() {
tester.assertParsed("OR l\u00e5gen delta M\u00dcNICH M\u00fcnchen",
- "l\u00e5gen delta M\u00dcNICH M\u00fcnchen",
- Query.Type.ANY);
+ "l\u00e5gen delta M\u00dcNICH M\u00fcnchen",
+ Query.Type.ANY);
}
@Test
- public void testMultipleTermsWithMultiplePrefixes() {
+ void testMultipleTermsWithMultiplePrefixes() {
tester.assertParsed("RANK (+bar -normal.title:foo -baz) url:foobar",
- "url:foobar +bar -normal.title:foo -baz", Query.Type.ANY);
+ "url:foobar +bar -normal.title:foo -baz", Query.Type.ANY);
}
@Test
- public void testSimpleQueryDefaultOr() {
+ void testSimpleQueryDefaultOr() {
tester.assertParsed("OR foobar foo bar baz", "foobar foo bar baz", Query.Type.ANY);
}
@Test
- public void testOrAndNot() {
+ void testOrAndNot() {
tester.assertParsed("RANK (+(AND baz bar) -xyzzy -foobaz) foobar foo",
- "foobar +baz foo -xyzzy -foobaz +bar", Query.Type.ANY);
+ "foobar +baz foo -xyzzy -foobaz +bar", Query.Type.ANY);
}
@Test
- public void testSimpleOrNestedAnd() {
+ void testSimpleOrNestedAnd() {
tester.assertParsed("RANK (OR foo bar baz) foobar xyzzy",
- "foobar +(foo bar baz) xyzzy", Query.Type.ANY);
+ "foobar +(foo bar baz) xyzzy", Query.Type.ANY);
}
@Test
- public void testSimpleOrNestedNot() {
+ void testSimpleOrNestedNot() {
tester.assertParsed("+(OR foobar xyzzy) -(AND foo bar baz)",
- "foobar -(foo bar baz) xyzzy", Query.Type.ANY);
+ "foobar -(foo bar baz) xyzzy", Query.Type.ANY);
}
@Test
- public void testOrNotNestedAnd() {
+ void testOrNotNestedAnd() {
tester.assertParsed("RANK (+(AND baz (OR foo bar baz) bar) -xyzzy -foobaz) foobar foo",
- "foobar +baz foo -xyzzy +(foo bar baz) -foobaz +bar",
- Query.Type.ANY);
+ "foobar +baz foo -xyzzy +(foo bar baz) -foobaz +bar",
+ Query.Type.ANY);
}
@Test
- public void testOrAndNotNestedNot() {
+ void testOrAndNotNestedNot() {
tester.assertParsed("RANK (+(AND baz bar) -xyzzy -(AND foo bar baz) -foobaz) foobar foo",
- "foobar +baz foo -xyzzy -(foo bar baz) -foobaz +bar",
- Query.Type.ANY);
+ "foobar +baz foo -xyzzy -(foo bar baz) -foobaz +bar",
+ Query.Type.ANY);
}
@Test
- public void testOrMultipleNestedAnd() {
+ void testOrMultipleNestedAnd() {
tester.assertParsed("RANK (AND (OR fo ba foba) (OR foz baraz)) foobar foo bar baz",
- "foobar +(fo ba foba) foo bar +(foz baraz) baz",
- Query.Type.ANY);
+ "foobar +(fo ba foba) foo bar +(foz baraz) baz",
+ Query.Type.ANY);
}
@Test
- public void testOrMultipleNestedNot() {
+ void testOrMultipleNestedNot() {
tester.assertParsed("+(OR foobar foo bar baz) -(AND fo ba foba) -(AND foz baraz)",
- "foobar -(fo ba foba) foo bar -(foz baraz) baz",
- Query.Type.ANY);
+ "foobar -(fo ba foba) foo bar -(foz baraz) baz",
+ Query.Type.ANY);
}
@Test
- public void testOrAndNotMultipleNestedAnd() {
+ void testOrAndNotMultipleNestedAnd() {
tester.assertParsed("RANK (+(AND baz (OR foo bar baz) (OR foz bazaz) bar) -xyzzy -foobaz) foobar foo",
- "foobar +baz foo -xyzzy +(foo bar baz) -foobaz +(foz bazaz) +bar",
- Query.Type.ANY);
+ "foobar +baz foo -xyzzy +(foo bar baz) -foobaz +(foz bazaz) +bar",
+ Query.Type.ANY);
}
@Test
- public void testOrAndNotMultipleNestedNot() {
+ void testOrAndNotMultipleNestedNot() {
tester.assertParsed("RANK (+(AND baz bar) -xyzzy -(AND foo bar baz) -foobaz -(AND foz bazaz)) foobar foo",
- "foobar +baz foo -xyzzy -(foo bar baz) -foobaz -(foz bazaz) +bar",
- Query.Type.ANY);
+ "foobar +baz foo -xyzzy -(foo bar baz) -foobaz -(foz bazaz) +bar",
+ Query.Type.ANY);
}
@Test
- public void testOrMultipleNestedAndNot() {
+ void testOrMultipleNestedAndNot() {
tester.assertParsed("RANK (+(AND (OR ffoooo bbaarr) (OR oof rab raboof)) -(AND fo ba foba) -(AND foz baraz)) foobar foo bar baz",
- "foobar -(fo ba foba) foo +(ffoooo bbaarr) bar +(oof rab raboof) -(foz baraz) baz",
- Query.Type.ANY);
+ "foobar -(fo ba foba) foo +(ffoooo bbaarr) bar +(oof rab raboof) -(foz baraz) baz",
+ Query.Type.ANY);
}
@Test
- public void testOrAndNotMultipleNestedAndNot() {
+ void testOrAndNotMultipleNestedAndNot() {
tester.assertParsed("RANK (+(AND (OR ffoooo bbaarr) (OR oof rab raboof) baz xyxyzzy) -(AND fo ba foba) -foo -bar -(AND foz baraz)) foobar",
- "foobar -(fo ba foba) -foo +(ffoooo bbaarr) -bar +(oof rab raboof) -(foz baraz) +baz +xyxyzzy",
- Query.Type.ANY);
+ "foobar -(fo ba foba) -foo +(ffoooo bbaarr) -bar +(oof rab raboof) -(foz baraz) +baz +xyxyzzy",
+ Query.Type.ANY);
}
@Test
- public void testExplicitPhrase() {
+ void testExplicitPhrase() {
Item root = tester.assertParsed("\"foo bar foobar\"", "\"foo bar foobar\"", Query.Type.ANY);
assertTrue(root instanceof PhraseItem);
- assertTrue(((PhraseItem)root).isExplicit());
+ assertTrue(((PhraseItem) root).isExplicit());
}
@Test
- public void testPhraseWithIndex() {
+ void testPhraseWithIndex() {
tester.assertParsed("normal.title:\"foo bar foobar\"",
- "normal.title:\"foo bar foobar\"", Query.Type.ANY);
+ "normal.title:\"foo bar foobar\"", Query.Type.ANY);
}
@Test
- public void testPhrasesAndTerms() {
+ void testPhrasesAndTerms() {
tester.assertParsed("OR \"foo bar foobar\" xyzzy \"baz gaz faz\"",
- "\"foo bar foobar\" xyzzy \"baz gaz faz\"", Query.Type.ANY);
+ "\"foo bar foobar\" xyzzy \"baz gaz faz\"", Query.Type.ANY);
}
@Test
- public void testPhrasesAndTermsWithOperators() {
+ void testPhrasesAndTermsWithOperators() {
tester.assertParsed("RANK (+(AND \"baz gaz faz\" bazar) -\"foo bar foobar\") foofoo xyzzy",
- "foofoo -\"foo bar foobar\" xyzzy +\"baz gaz faz\" +bazar",
- Query.Type.ANY);
+ "foofoo -\"foo bar foobar\" xyzzy +\"baz gaz faz\" +bazar",
+ Query.Type.ANY);
}
@Test
- public void testSimpleTermQueryDefaultAnd() {
+ void testSimpleTermQueryDefaultAnd() {
tester.assertParsed("foobar", "foobar", Query.Type.ALL);
}
@Test
- public void testTermWithCatalogAndIndexPrefixDefaultAnd() {
+ void testTermWithCatalogAndIndexPrefixDefaultAnd() {
tester.assertParsed("normal.title:foobar", "normal.title:foobar", Query.Type.ALL);
}
@Test
- public void testMultipleTermsWithMultiplePrefixesDefaultAnd() {
+ void testMultipleTermsWithMultiplePrefixesDefaultAnd() {
tester.assertParsed("+(AND url:foobar bar) -normal.title:foo -baz",
- "url:foobar +bar -normal.title:foo -baz",
- Query.Type.ALL);
+ "url:foobar +bar -normal.title:foo -baz",
+ Query.Type.ALL);
}
@Test
- public void testSimpleQueryDefaultAnd() {
+ void testSimpleQueryDefaultAnd() {
tester.assertParsed("AND foobar foo bar baz", "foobar foo bar baz", Query.Type.ALL);
}
@Test
- public void testNotDefaultAnd() {
+ void testNotDefaultAnd() {
tester.assertParsed("+(AND foobar (OR foo bar baz) xyzzy) -(AND foz baraz bazar)",
- "foobar +(foo bar baz) xyzzy -(foz baraz bazar)",
- Query.Type.ALL);
+ "foobar +(foo bar baz) xyzzy -(foz baraz bazar)",
+ Query.Type.ALL);
}
@Test
- public void testSimpleTermQueryDefaultPhrase() {
+ void testSimpleTermQueryDefaultPhrase() {
tester.assertParsed("foobar",
- "foobar",
- Query.Type.PHRASE);
+ "foobar",
+ Query.Type.PHRASE);
}
@Test
- public void testSimpleQueryDefaultPhrase() {
+ void testSimpleQueryDefaultPhrase() {
Item root = tester.assertParsed("\"foobar foo bar baz\"",
- "foobar foo bar baz",
- Query.Type.PHRASE);
+ "foobar foo bar baz",
+ Query.Type.PHRASE);
assertTrue(root instanceof PhraseItem);
- assertFalse(((PhraseItem)root).isExplicit());
+ assertFalse(((PhraseItem) root).isExplicit());
}
@Test
- public void testMultipleTermsWithMultiplePrefixesDefaultPhrase() {
+ void testMultipleTermsWithMultiplePrefixesDefaultPhrase() {
tester.assertParsed("\"url foobar bar normal title foo baz\"",
- "url:foobar +bar -normal.title:foo -baz",
- Query.Type.PHRASE);
+ "url:foobar +bar -normal.title:foo -baz",
+ Query.Type.PHRASE);
}
@Test
- public void testOdd1() {
+ void testOdd1() {
tester.assertParsed("AND window print error", "+window.print() +error",
- Query.Type.ALL);
+ Query.Type.ALL);
}
@Test
- public void testOdd2() {
+ void testOdd2() {
tester.assertParsed("normal.title:kaboom", "normal.title:\"kaboom\"",
- Query.Type.ALL);
+ Query.Type.ALL);
}
@Test
- public void testOdd2Uppercase() {
+ void testOdd2Uppercase() {
tester.assertParsed("normal.title:KABOOM", "NORMAL.TITLE:\"KABOOM\"", Query.Type.ALL);
}
@Test
- public void testOdd3() {
+ void testOdd3() {
tester.assertParsed("AND foo (OR size.all:[200;300] date.all:512)",
"foo +(size.all:[200;300] date.all:512)", Query.Type.ALL);
}
@Test
- public void testNullQuery() {
+ void testNullQuery() {
tester.assertParsed(null, null, Query.Type.ALL);
}
@Test
- public void testEmptyQuery() {
+ void testEmptyQuery() {
tester.assertParsed(null, "", Query.Type.ALL);
}
@Test
- public void testNotOnly() {
+ void testNotOnly() {
tester.assertParsed(null, "-foobar", Query.Type.ALL);
}
@Test
- public void testMultipleNotsOnlt() {
+ void testMultipleNotsOnlt() {
tester.assertParsed(null, "-foo -bar -foobar", Query.Type.ALL);
}
@Test
- public void testOnlyNotComposite() {
+ void testOnlyNotComposite() {
tester.assertParsed(null, "-(foo bar baz)", Query.Type.ALL);
}
@Test
- public void testNestedCompositesDefaultOr() {
+ void testNestedCompositesDefaultOr() {
tester.assertParsed("RANK (OR foobar bar baz) foo xyzzy",
- "foo +(foobar +(bar baz)) xyzzy", Query.Type.ANY);
+ "foo +(foobar +(bar baz)) xyzzy", Query.Type.ANY);
}
@Test
- public void testNestedCompositesDefaultAnd() {
+ void testNestedCompositesDefaultAnd() {
tester.assertParsed("AND foo (OR foobar bar baz) xyzzy",
- "foo +(foobar +(bar baz)) xyzzy", Query.Type.ALL);
+ "foo +(foobar +(bar baz)) xyzzy", Query.Type.ALL);
}
@Test
- public void testNestedCompositesPhraseDefault() {
+ void testNestedCompositesPhraseDefault() {
tester.assertParsed("\"foo foobar bar baz xyzzy\"",
- "foo +(foobar +(bar baz)) xyzzy", Query.Type.PHRASE);
+ "foo +(foobar +(bar baz)) xyzzy", Query.Type.PHRASE);
}
@Test
- public void testNumeric() {
+ void testNumeric() {
tester.assertParsed("34", "34", Query.Type.ANY);
}
@Test
- public void testGreaterNumeric() {
+ void testGreaterNumeric() {
tester.assertParsed("<454", "<454", Query.Type.ANY);
}
@Test
- public void testGreaterNumericWithIndex() {
- IntItem item = (IntItem)tester.assertParsed("score:<454", "score:<454", Query.Type.ANY);
+ void testGreaterNumericWithIndex() {
+ IntItem item = (IntItem) tester.assertParsed("score:<454", "score:<454", Query.Type.ANY);
assertEquals("score", item.getIndexName());
assertEquals(454L, item.getToLimit().number());
assertFalse(item.getToLimit().isInclusive());
}
@Test
- public void testSmallerNumeric() {
+ void testSmallerNumeric() {
tester.assertParsed(">454", ">454", Query.Type.ANY);
}
@Test
- public void testSmallerNumericWithIndex() {
- IntItem item = (IntItem)tester.assertParsed("score:>454", "score:>454", Query.Type.ANY);
+ void testSmallerNumericWithIndex() {
+ IntItem item = (IntItem) tester.assertParsed("score:>454", "score:>454", Query.Type.ANY);
assertEquals("score", item.getIndexName());
assertEquals(454L, item.getFromLimit().number());
assertFalse(item.getFromLimit().isInclusive());
}
@Test
- public void testFullRange() {
+ void testFullRange() {
tester.assertParsed("[34;454]", "[34;454]", Query.Type.ANY);
}
@Test
- public void testFullRangeLimit() {
+ void testFullRangeLimit() {
tester.assertParsed("[34;454;7]", "[34;454;7]", Query.Type.ANY);
tester.assertParsed("[34;454;-7]", "[34;454;-7]", Query.Type.ANY);
}
@Test
- public void testLowOpenRange() {
+ void testLowOpenRange() {
tester.assertParsed("[;454]", "[;454]", Query.Type.ANY);
}
@Test
- public void testHiOpenRange() {
+ void testHiOpenRange() {
tester.assertParsed("[34;]", "[34;]", Query.Type.ANY);
}
@Test
- public void testNumericWithIndex() {
+ void testNumericWithIndex() {
tester.assertParsed("document.size:[34;454]", "document.size:[34;454]", Query.Type.ANY);
}
@Test
- public void testMultipleNumeric() {
+ void testMultipleNumeric() {
tester.assertParsed("OR [34;454] <34", "[34;454] <34", Query.Type.ANY);
}
@Test
- public void testMultipleIntegerWithIndex() {
+ void testMultipleIntegerWithIndex() {
tester.assertParsed("OR document.size:[34;454] date:>1234567890",
- "document.size:[34;454] date:>1234567890", Query.Type.ANY);
+ "document.size:[34;454] date:>1234567890", Query.Type.ANY);
}
@Test
- public void testMixedNumericAndOtherTerms() {
+ void testMixedNumericAndOtherTerms() {
tester.assertParsed("RANK (AND document.size:<1024 xyzzy) foo date:>123456890",
- "foo +document.size:<1024 +xyzzy date:>123456890",
- Query.Type.ANY);
+ "foo +document.size:<1024 +xyzzy date:>123456890",
+ Query.Type.ANY);
}
@Test
- public void testEmptyPhrase() {
+ void testEmptyPhrase() {
tester.assertParsed("\"to be or not\"", "\"\"to be or not", Query.Type.ANY);
}
@Test
- public void testItemPhraseEmptyPhrase() {
+ void testItemPhraseEmptyPhrase() {
tester.assertParsed("RANK to \"or not to be\"", "+to\"or not to be\"\"\"", Query.Type.ANY);
}
@Test
- public void testSimpleQuery() {
+ void testSimpleQuery() {
tester.assertParsed("OR if am \"f g 4 2\" maybe", "if am \" f g 4 2\"\" maybe", Query.Type.ANY);
}
@Test
- public void testExcessivePluses() {
+ void testExcessivePluses() {
tester.assertParsed("+(AND other is nothing) -test",
- "++other +++++is ++++++nothing -test", Query.Type.ANY);
+ "++other +++++is ++++++nothing -test", Query.Type.ANY);
}
@Test
- public void testMinusAndPluses() {
+ void testMinusAndPluses() {
tester.assertParsed(null, "--test+-if", Query.Type.ANY);
}
@Test
- public void testPlusesAndMinuses() {
+ void testPlusesAndMinuses() {
tester.assertParsed("AND a b c d d", "a+b+c+d--d", Query.Type.ANY);
}
@Test
- public void testNumbers() {
+ void testNumbers() {
tester.assertParsed("AND 123 2132odfd 934032 32423", "123+2132odfd.934032,,32423", Query.Type.ANY);
}
@Test
- public void testOtherSignsInQuote() {
+ void testOtherSignsInQuote() {
tester.assertParsed("AND 0032 4 320 24329043", "0032+4\\320.24329043", Query.Type.ANY);
}
@Test
- public void testGribberish() {
+ void testGribberish() {
tester.assertParsed("1349832840234l3040roer\u00e6lf12",
- ",1349832840234l3040roer\u00e6lf12",
- Query.Type.ANY);
+ ",1349832840234l3040roer\u00e6lf12",
+ Query.Type.ANY);
}
@Test
- public void testUrl() {
+ void testUrl() {
tester.assertParsed("AND www:www www:hotelaiguablava www:com",
- "+www:www.hotelaiguablava:com",
- Query.Type.ANY);
+ "+www:www.hotelaiguablava:com",
+ Query.Type.ANY);
}
@Test
- public void testUrlGribberish() {
+ void testUrlGribberish() {
tester.assertParsed("OR (AND 3 16) fast.type:lycosoffensive",
- "[ 3:16 fast.type:lycosoffensive",
- Query.Type.ANY);
+ "[ 3:16 fast.type:lycosoffensive",
+ Query.Type.ANY);
}
@Test
- public void testBracedWordAny() {
+ void testBracedWordAny() {
tester.assertParsed("foo", "(foo)", Query.Type.ANY);
}
@Test
- public void testBracedWordAll() {
+ void testBracedWordAll() {
tester.assertParsed("foo", "(foo)", Query.Type.ALL);
}
@Test
- public void testBracedWords() {
+ void testBracedWords() {
tester.assertParsed("OR (OR foo bar) (OR xyzzy foobar)",
"(foo bar) (xyzzy foobar)", Query.Type.ANY);
}
@Test
- public void testNullAdvanced() {
+ void testNullAdvanced() {
tester.assertParsed(null, null, Query.Type.ADVANCED);
}
@Test
- public void testEmptyAdvanced() {
+ void testEmptyAdvanced() {
tester.assertParsed(null, "", Query.Type.ADVANCED);
}
@Test
- public void testSimpleAdvanced() {
+ void testSimpleAdvanced() {
tester.assertParsed("foobar", "foobar", Query.Type.ADVANCED);
}
@Test
- public void testPrefixAdvanced() {
+ void testPrefixAdvanced() {
tester.assertParsed("url:foobar", "url:foobar", Query.Type.ADVANCED);
}
@Test
- public void testPrefixWithDotAdvanced() {
+ void testPrefixWithDotAdvanced() {
tester.assertParsed("normal.title:foobar", "normal.title:foobar", Query.Type.ADVANCED);
}
@Test
- public void testUTF8Advanced() {
+ void testUTF8Advanced() {
tester.assertParsed("m\u00fcnchen", "m\u00fcnchen", Query.Type.ADVANCED);
}
@Test
- public void testSimplePhraseAdvanced() {
+ void testSimplePhraseAdvanced() {
tester.assertParsed("\"foo bar foobar\"", "\"foo bar foobar\"", Query.Type.ADVANCED);
}
@Test
- public void testSimplePhraseWithIndexAdvanced() {
+ void testSimplePhraseWithIndexAdvanced() {
tester.assertParsed("normal.title:\"foo bar foobar\"",
- "normal.title:\"foo bar foobar\"",
- Query.Type.ADVANCED);
+ "normal.title:\"foo bar foobar\"",
+ Query.Type.ADVANCED);
}
@Test
- public void testMultiplePhrasesAdvanced() {
+ void testMultiplePhrasesAdvanced() {
tester.assertParsed("AND \"foo bar foobar\" \"baz gaz faz\"",
- "\"foo bar foobar\" and \"baz gaz faz\"",
- Query.Type.ADVANCED);
+ "\"foo bar foobar\" and \"baz gaz faz\"",
+ Query.Type.ADVANCED);
}
@Test
- public void testNumberAdvanced() {
+ void testNumberAdvanced() {
tester.assertParsed("34", "34", Query.Type.ADVANCED);
}
@Test
- public void testLargerNumberAdvanced() {
+ void testLargerNumberAdvanced() {
tester.assertParsed("<454", "<454", Query.Type.ADVANCED);
}
@Test
- public void testLesserNumberAdvanced() {
+ void testLesserNumberAdvanced() {
tester.assertParsed(">454", ">454", Query.Type.ADVANCED);
}
@Test
- public void testRangeAdvanced() {
+ void testRangeAdvanced() {
tester.assertParsed("[34;454]", "[34;454]", Query.Type.ADVANCED);
}
@Test
- public void testLowOpenRangeAdvanced() {
+ void testLowOpenRangeAdvanced() {
tester.assertParsed("[;454]", "[;454]", Query.Type.ADVANCED);
}
@Test
- public void testHighOpenRangeAdvanced() {
+ void testHighOpenRangeAdvanced() {
tester.assertParsed("[34;]", "[34;]", Query.Type.ADVANCED);
}
@Test
- public void testIdexedRangeAdvanced() {
+ void testIdexedRangeAdvanced() {
tester.assertParsed("document.size:[34;454]", "document.size:[34;454]", Query.Type.ADVANCED);
}
@Test
- public void testSimpleAndAdvanced() {
+ void testSimpleAndAdvanced() {
tester.assertParsed("AND foo bar", "foo and bar", Query.Type.ADVANCED);
}
@Test
- public void testSimpleOrAdvanced() {
+ void testSimpleOrAdvanced() {
tester.assertParsed("OR foo bar", "foo or bar", Query.Type.ADVANCED);
}
@Test
- public void testSimpleAndNotAdvanced() {
+ void testSimpleAndNotAdvanced() {
tester.assertParsed("+foo -bar", "foo andnot bar", Query.Type.ADVANCED);
}
@Test
- public void testSimpleRankAdvanced() {
+ void testSimpleRankAdvanced() {
tester.assertParsed("RANK foo bar", "foo rank bar", Query.Type.ADVANCED);
}
@Test
- public void testMultipleAndAdvanced() {
+ void testMultipleAndAdvanced() {
tester.assertParsed("AND foo bar foobar", "foo and bar and foobar", Query.Type.ADVANCED);
}
@Test
- public void testMultipleOrAdvanced() {
+ void testMultipleOrAdvanced() {
tester.assertParsed("OR foo bar foobar", "foo or bar or foobar", Query.Type.ADVANCED);
}
@Test
- public void testMultipleAndnotAdvanced() {
+ void testMultipleAndnotAdvanced() {
tester.assertParsed("+foo -bar -foobar", "foo andnot bar andnot foobar", Query.Type.ADVANCED);
}
@Test
- public void testMultipleRankAdvanced() {
+ void testMultipleRankAdvanced() {
tester.assertParsed("RANK foo bar foobar", "foo rank bar rank foobar", Query.Type.ADVANCED);
}
@Test
- public void testMixedAdvanced() {
+ void testMixedAdvanced() {
tester.assertParsed("OR (AND foo bar) foobar", "foo and bar or foobar", Query.Type.ADVANCED);
}
@Test
- public void testNestedAdvanced() {
+ void testNestedAdvanced() {
tester.assertParsed("AND foo (OR bar foobar)", "foo and (bar or foobar)", Query.Type.ADVANCED);
}
@Test
- public void testMultipleNestedAdvanced() {
+ void testMultipleNestedAdvanced() {
tester.assertParsed("+(AND foo xyzzy) -(OR bar foobar)",
- "(foo and xyzzy) andnot (bar or foobar)", Query.Type.ADVANCED);
+ "(foo and xyzzy) andnot (bar or foobar)", Query.Type.ADVANCED);
}
@Test
- public void testDoubleNestedAdvanced() {
+ void testDoubleNestedAdvanced() {
tester.assertParsed("AND foo (OR bar (OR xyzzy foobar))",
- "foo and (bar or (xyzzy or foobar))", Query.Type.ADVANCED);
+ "foo and (bar or (xyzzy or foobar))", Query.Type.ADVANCED);
}
@Test
- public void testDeeplyAdvanced() {
+ void testDeeplyAdvanced() {
tester.assertParsed(
"AND foo (OR bar (OR (AND (AND baz (+(OR bazar zyxxy) -fozbaz)) (OR boz bozor) xyzzy) foobar))",
"foo and (bar or ((baz and ((bazar or zyxxy) andnot fozbaz)) and (boz or bozor) and xyzzy or foobar))",
@@ -604,7 +601,7 @@ public class ParseTestCase {
}
@Test
- public void testDeeplyAdvancedUppercase() {
+ void testDeeplyAdvancedUppercase() {
tester.assertParsed(
"AND FOO (OR BAR (OR (AND (AND BAZ (+(OR BAZAR ZYXXY) -FOZBAZ)) (OR BOZ BOZOR) XYZZY) FOOBAR))",
"FOO AND (BAR OR ((BAZ AND ((BAZAR OR ZYXXY) ANDNOT FOZBAZ)) AND (BOZ OR BOZOR) AND XYZZY OR FOOBAR))",
@@ -612,230 +609,230 @@ public class ParseTestCase {
}
@Test
- public void testAbortedIntegerRange() {
+ void testAbortedIntegerRange() {
tester.assertParsed("AND audio.audall:744 audio.audall:ph",
"+audio.audall:[744 +audio.audall:ph", Query.Type.ANY);
}
@Test
- public void testJunk() {
+ void testJunk() {
tester.assertParsed("+l -fast.type:offensive",
",;'/.<l:>? -fast.type:offensive", Query.Type.ALL);
}
@Test
- public void testOneTermPhraseWithIndex() {
+ void testOneTermPhraseWithIndex() {
tester.assertParsed("normal.title:foo", "normal.title:\"foo\"", Query.Type.ANY);
}
@Test
- public void testOneTermPhraseWithIndexAdvanced() {
+ void testOneTermPhraseWithIndexAdvanced() {
tester.assertParsed("normal.title:foo", "normal.title:\"foo\"", Query.Type.ADVANCED);
}
@Test
- public void testIncorrect1Advanced() {
+ void testIncorrect1Advanced() {
tester.assertParsed("\"to be or not\"", "\"\"to be or not", Query.Type.ADVANCED);
}
@Test
- public void testIncorrect2Advanced() {
+ void testIncorrect2Advanced() {
tester.assertParsed("AND to \"or not to be\"", "+to\"or not to be\"\"\"", Query.Type.ADVANCED);
}
@Test
- public void testIncorrect3Advanced() {
+ void testIncorrect3Advanced() {
tester.assertParsed("AND if am \"f g 4 2\" maybe",
"if am \" f g 4 2\"\" maybe", Query.Type.ADVANCED);
}
@Test
- public void testIncorrect4Advanced() {
+ void testIncorrect4Advanced() {
tester.assertParsed("AND other is nothing test",
"++other +++++is ++++++nothing -test", Query.Type.ADVANCED);
}
@Test
- public void testImplicitPhrase1Advanced() {
+ void testImplicitPhrase1Advanced() {
tester.assertParsed("AND test if", "--test+-if", Query.Type.ADVANCED);
}
@Test
- public void testImplicitPhrase2Advanced() {
+ void testImplicitPhrase2Advanced() {
tester.assertParsed("AND a b c d d", "a+b+c+d--d", Query.Type.ADVANCED);
}
@Test
- public void testImplicitPhrase3Advanced() {
+ void testImplicitPhrase3Advanced() {
tester.assertParsed("AND 123 2132odfd 934032 32423",
"123+2132odfd.934032,,32423", Query.Type.ADVANCED);
}
@Test
- public void testImplicitPhrase4Advanced() {
+ void testImplicitPhrase4Advanced() {
tester.assertParsed("AND 0032 4 320 24329043", "0032+4\\320.24329043", Query.Type.ADVANCED);
}
@Test
- public void testUtf8Advanced() {
+ void testUtf8Advanced() {
tester.assertParsed("1349832840234l3040roer\u00e6lf12",
",1349832840234l3040roer\u00e6lf12", Query.Type.ADVANCED);
}
@Test
- public void testOperatorSearchAdvanced() {
+ void testOperatorSearchAdvanced() {
tester.assertParsed("RANK (OR (AND and and) or andnot) rank",
"and and and or or or andnot rank rank", Query.Type.ADVANCED);
}
@Test
- public void testIncorrectParenthesisAdvanced() {
+ void testIncorrectParenthesisAdvanced() {
tester.assertParsed("AND foo bar", "foo and bar )", Query.Type.ADVANCED);
}
@Test
- public void testOpeningParenthesisOnlyAdvanced() {
+ void testOpeningParenthesisOnlyAdvanced() {
tester.assertParsed("AND foo (OR bar (AND foobar xyzzy))",
"(foo and (bar or (foobar and xyzzy", Query.Type.ADVANCED);
}
@Test
- public void testSimpleWeight() {
+ void testSimpleWeight() {
tester.assertParsed("foo!150", "foo!", Query.Type.ANY);
}
@Test
- public void testMultipleWeight() {
+ void testMultipleWeight() {
tester.assertParsed("foo!250", "foo!!!", Query.Type.ANY);
}
@Test
- public void testExplicitWeight() {
+ void testExplicitWeight() {
tester.assertParsed("foo!200", "foo!200", Query.Type.ANY);
}
@Test
- public void testExplicitZeroWeight() {
+ void testExplicitZeroWeight() {
tester.assertParsed("foo!0", "foo!0", Query.Type.ANY);
}
@Test
- public void testSimplePhraseWeight() {
+ void testSimplePhraseWeight() {
tester.assertParsed("\"foo bar\"!150", "\"foo bar\"!", Query.Type.ANY);
}
@Test
- public void testSingleHyphen() {
+ void testSingleHyphen() {
tester.assertParsed("AND a b", "a-b", Query.Type.ALL);
}
@Test
- public void testUserCase() {
+ void testUserCase() {
tester.assertParsed("\"a a\"", "\"a- a-*\"", Query.Type.ALL);
}
@Test
- public void testMultiplePhraseWeight() {
+ void testMultiplePhraseWeight() {
tester.assertParsed("\"foo bar\"!250", "\"foo bar\"!!!", Query.Type.ANY);
}
@Test
- public void testExplicitPhraseWeight() {
+ void testExplicitPhraseWeight() {
tester.assertParsed("\"foo bar\"!200", "\"foo bar\"!200", Query.Type.ANY);
}
@Test
- public void testUrlSubmodeHyphen() {
+ void testUrlSubmodeHyphen() {
assertTrue(ParsingTester.createIndexFacts().newSession(new Query()).getIndex("url.all").isUriIndex());
tester.assertParsed("url.all:\"www-microsoft com\"", "url.all:www-microsoft.com", Query.Type.ANY);
}
@Test
- public void testUrlSubmodeUnderscore() {
+ void testUrlSubmodeUnderscore() {
tester.assertParsed("url.all:\"www_microsoft com\"", "url.all:www_microsoft.com", Query.Type.ANY);
}
@Test
- public void testUrlSubmode() {
+ void testUrlSubmode() {
tester.assertParsed("host.all:\"www-microsoft com $\"", "host.all:www-microsoft.com", Query.Type.ANY);
}
@Test
- public void testExplicitHostNameAnchoringHost() {
+ void testExplicitHostNameAnchoringHost() {
tester.assertParsed("host.all:\"^ www-microsoft com $\"", "host.all:^www-microsoft.com$", Query.Type.ANY);
}
@Test
- public void testExplicitHostNameAnchoringSite() {
+ void testExplicitHostNameAnchoringSite() {
tester.assertParsed("site:\"^ www-microsoft com $\"", "site:^www-microsoft.com$", Query.Type.ANY);
}
@Test
- public void testExplicitHostNameAnchoring() {
+ void testExplicitHostNameAnchoring() {
tester.assertParsed("host.all:\"^ http www krangaz-central com index html $\"",
"host.all:^http://www.krangaz-central.com/index.html$",
Query.Type.ANY);
}
@Test
- public void testExplicitHostAnchoringRemoval() {
+ void testExplicitHostAnchoringRemoval() {
tester.assertParsed("host.all:\"www-microsoft com\"",
"host.all:www-microsoft.com*", Query.Type.ANY);
}
@Test
- public void testQuery1Any() {
+ void testQuery1Any() {
tester.assertParsed("RANK (AND fast \"search engine\") kernel",
"+fast +\"search engine\" kernel", Query.Type.ANY);
}
@Test
- public void testQuery1Advanced() {
+ void testQuery1Advanced() {
tester.assertParsed("RANK (AND fast \"search engine\") kernel",
"+fast and \"search engine\" rank kernel", Query.Type.ADVANCED);
}
@Test
- public void testQuery2Any() {
+ void testQuery2Any() {
tester.assertParsed("+(OR title:car bmw) -z3", "title:car bmw -z3",
Query.Type.ANY);
}
@Test
- public void testQuery2Advanced() {
+ void testQuery2Advanced() {
tester.assertParsed("+(OR title:car bmw) -z3", "title:car or bmw andnot z3", Query.Type.ADVANCED);
}
@Test
- public void testQuery3All() {
+ void testQuery3All() {
tester.assertParsed("+(AND FAST search domain:no pagedepth:0) -title:phrase",
- "FAST search -title:phrase domain:no Pagedepth:0",
- Query.Type.ALL);
+ "FAST search -title:phrase domain:no Pagedepth:0",
+ Query.Type.ALL);
}
@Test
- public void testQuery4Advanced() {
+ void testQuery4Advanced() {
tester.assertParsed("AND (+(AND FAST search) -title:phrase) domain:no pagedepth:0",
- "FAST and search andnot title:phrase and domain:no and Pagedepth:0",
- Query.Type.ADVANCED);
+ "FAST and search andnot title:phrase and domain:no and Pagedepth:0",
+ Query.Type.ADVANCED);
}
@Test
- public void testQuery5Any() {
+ void testQuery5Any() {
tester.assertParsed("AND alltheweb fast search", "+alltheweb +fast +search", Query.Type.ANY);
}
@Test
- public void testQuery6Any() {
+ void testQuery6Any() {
tester.assertParsed("RANK (+(AND query language) -sql) search", "+query +language -sql search", Query.Type.ANY);
}
@Test
- public void testQuery7Any() {
+ void testQuery7Any() {
tester.assertParsed(
"+(AND alltheweb (OR search engine)) -(OR excite altavista)",
"(alltheweb and (search or engine)) andnot (excite or altavista)",
@@ -843,7 +840,7 @@ public class ParseTestCase {
}
@Test
- public void testQuery8Advanced() {
+ void testQuery8Advanced() {
tester.assertParsed(
"RANK (AND \"search engines\" \"query processing\") \"fast search\"",
"(\"search engines\" and \"query processing\") rank \"fast search\"",
@@ -851,132 +848,132 @@ public class ParseTestCase {
}
@Test
- public void testPStrangeAdvanced() {
+ void testPStrangeAdvanced() {
tester.assertParsed("AND AND r.s:jnl", "( AND +r.s:jnl) ", Query.Type.ADVANCED);
}
@Test
- public void testEmptyNestAdvanced() {
+ void testEmptyNestAdvanced() {
tester.assertParsed(null, "() ", Query.Type.ADVANCED);
}
@Test
- public void testNestedBeginningAdvanced() {
+ void testNestedBeginningAdvanced() {
tester.assertParsed("AND (OR a b) c", "(a or b) and c", Query.Type.ADVANCED);
}
@Test
- public void testNestedPositiveAny() {
+ void testNestedPositiveAny() {
tester.assertParsed("AND (OR a b) c", "+(a b) +c", Query.Type.ANY);
}
@Test
- public void testParseAdvancedQuery() {
+ void testParseAdvancedQuery() {
tester.assertParsed("AND joplin remediation r.s:jnl",
"(joplin and + and remediation and +r.s:jnl)",
Query.Type.ADVANCED);
}
@Test
- public void testSimpleDotPhraseAny() {
+ void testSimpleDotPhraseAny() {
tester.assertParsed("OR a (AND b c) d", "a b.c d", Query.Type.ANY);
}
@Test
- public void testSimpleHyphenPhraseAny() {
+ void testSimpleHyphenPhraseAny() {
tester.assertParsed("OR a (AND b c) d", "a b-c d", Query.Type.ANY);
}
@Test
- public void testAnotherSimpleDotPhraseAny() {
+ void testAnotherSimpleDotPhraseAny() {
tester.assertParsed("OR (AND a b) c d", "a.b c d", Query.Type.ANY);
}
@Test
- public void testYetAnotherSimpleDotPhraseAny() {
+ void testYetAnotherSimpleDotPhraseAny() {
tester.assertParsed("OR a b (AND c d)", "a b c.d", Query.Type.ANY);
}
@Test
- public void testVariousSeparatorsPhraseAny() {
+ void testVariousSeparatorsPhraseAny() {
tester.assertParsed("AND a b c d", "a-b.c%d", Query.Type.ANY);
}
@Test
- public void testDoublyMarkedPhraseAny() {
+ void testDoublyMarkedPhraseAny() {
tester.assertParsed("OR a \"b c\" d", "a \"b.c\" d", Query.Type.ANY);
}
@Test
- public void testPartlyDoublyMarkedPhraseAny() {
+ void testPartlyDoublyMarkedPhraseAny() {
tester.assertParsed("OR a \"b c d\"", "a \"b.c d\"", Query.Type.ANY);
}
@Test
- public void testIndexedDottedPhraseAny() {
+ void testIndexedDottedPhraseAny() {
tester.assertParsed("OR a (AND url:b url:c) d", "a url:b.c d", Query.Type.ANY);
}
@Test
- public void testIndexedPlusedPhraseAny() {
+ void testIndexedPlusedPhraseAny() {
tester.assertParsed("OR a (AND normal.title:b normal.title:c) d", "a normal.title:b+c d", Query.Type.ANY);
}
@Test
- public void testNestedNotAny() {
+ void testNestedNotAny() {
tester.assertParsed(
"RANK (+(OR normal.title:foobar (AND url:www url:pvv url:org)) -foo) a",
"a +(normal.title:foobar url:www.pvv.org) -foo", Query.Type.ANY);
}
@Test
- public void testDottedPhraseAdvanced() {
+ void testDottedPhraseAdvanced() {
tester.assertParsed("OR a (AND b c)", "a or b.c", Query.Type.ADVANCED);
}
@Test
- public void testHyphenPhraseAdvanced() {
+ void testHyphenPhraseAdvanced() {
tester.assertParsed("OR (AND a (AND b c)) d", "a and b-c or d", Query.Type.ADVANCED);
}
@Test
- public void testAnotherDottedPhraseAdvanced() {
+ void testAnotherDottedPhraseAdvanced() {
tester.assertParsed("OR (AND a b) c", "a.b or c", Query.Type.ADVANCED);
}
@Test
- public void testNottedDottedPhraseAdvanced() {
+ void testNottedDottedPhraseAdvanced() {
tester.assertParsed("+a -(AND c d)", "a andnot c.d", Query.Type.ADVANCED);
}
@Test
- public void testVariousSeparatorsPhraseAdvanced() {
+ void testVariousSeparatorsPhraseAdvanced() {
tester.assertParsed("AND a b c d", "a-b.c%d", Query.Type.ADVANCED);
}
@Test
- public void testDoublyPhrasedAdvanced() {
+ void testDoublyPhrasedAdvanced() {
tester.assertParsed("OR (AND a \"b c\") d", "a and \"b.c\" or d", Query.Type.ADVANCED);
}
@Test
- public void testPartlyDoublyPhrasedAdvanced() {
+ void testPartlyDoublyPhrasedAdvanced() {
tester.assertParsed("OR a \"b c d\"", "a or \"b.c d\"", Query.Type.ADVANCED);
}
@Test
- public void testNestedDottedPhraseAdvanced() {
+ void testNestedDottedPhraseAdvanced() {
tester.assertParsed("AND a (OR url:\"b c\" d)", "a and(url:\"b.c\" or d)", Query.Type.ADVANCED);
}
@Test
- public void testNestedPlussedPhraseAdvanced() {
+ void testNestedPlussedPhraseAdvanced() {
tester.assertParsed("AND (OR a (AND normal.title:b normal.title:c)) d",
"a or normal.title:b+c and d", Query.Type.ADVANCED);
}
@Test
- public void testNottedNestedDottedPhraseAdvanced() {
+ void testNottedNestedDottedPhraseAdvanced() {
tester.assertParsed(
"+(AND a (OR normal.title:foobar (AND url:www url:pvv url:org))) -foo",
"a and (normal.title:foobar or url:www.pvv.org) andnot foo",
@@ -984,570 +981,570 @@ public class ParseTestCase {
}
@Test
- public void testPlusedThenQuotedPhraseAny() {
+ void testPlusedThenQuotedPhraseAny() {
tester.assertParsed("\"a b c\"", "a+\"b c\"", Query.Type.ANY);
}
@Test
- public void testPlusedTwiceThenQuotedPhraseAny() {
+ void testPlusedTwiceThenQuotedPhraseAny() {
tester.assertParsed("AND a b c d", "a+b+\"c d\"", Query.Type.ANY);
}
@Test
- public void testPlusedThenQuotedPhraseAdvanced() {
+ void testPlusedThenQuotedPhraseAdvanced() {
tester.assertParsed("\"a b c\"", "a+\"b c\"", Query.Type.ADVANCED);
}
@Test
- public void testPhrasesInBraces() {
+ void testPhrasesInBraces() {
tester.assertParsed("AND url.domain:microsoft url.domain:com",
"+(url.domain:microsoft.com)", Query.Type.ALL);
}
@Test
- public void testDoublyPhrasedPhrasesInBraces() {
+ void testDoublyPhrasedPhrasesInBraces() {
tester.assertParsed("url.domain:\"microsoft com\"",
"+(url.domain:\"microsoft.com\")", Query.Type.ALL);
}
@Test
- public void testSinglePrefixTerm() {
+ void testSinglePrefixTerm() {
Item root = tester.assertParsed("prefix*", "prefix*", Query.Type.ANY);
assertTrue(root instanceof PrefixItem);
}
@Test
- public void testSingleSubstringTerm() {
+ void testSingleSubstringTerm() {
Item root = tester.assertParsed("*substring*", "*substring*", Query.Type.ANY);
assertTrue(root instanceof SubstringItem);
}
@Test
- public void testSingleSuffixTerm() {
+ void testSingleSuffixTerm() {
Item root = tester.assertParsed("*suffix", "*suffix", Query.Type.ANY);
assertTrue(root instanceof SuffixItem);
}
@Test
- public void testPrefixAndWordTerms() {
+ void testPrefixAndWordTerms() {
Item root = tester.assertParsed("OR foo prefix* bar", "foo prefix* bar", Query.Type.ANY);
- assertTrue(((OrItem)root).getItem(1) instanceof PrefixItem);
+ assertTrue(((OrItem) root).getItem(1) instanceof PrefixItem);
}
@Test
- public void testSubstringAndWordTerms() {
+ void testSubstringAndWordTerms() {
Item root = tester.assertParsed("OR foo *substring* bar", "foo *substring* bar", Query.Type.ANY);
- assertTrue(((OrItem)root).getItem(1) instanceof SubstringItem);
+ assertTrue(((OrItem) root).getItem(1) instanceof SubstringItem);
}
@Test
- public void testSuffixAndWordTerms() {
+ void testSuffixAndWordTerms() {
Item root = tester.assertParsed("OR foo *suffix bar", "foo *suffix bar", Query.Type.ANY);
- assertTrue(((OrItem)root).getItem(1) instanceof SuffixItem);
+ assertTrue(((OrItem) root).getItem(1) instanceof SuffixItem);
}
@Test
- public void testPhraseNotPrefix() {
+ void testPhraseNotPrefix() {
tester.assertParsed("OR foo (AND prefix bar)", "foo prefix*bar", Query.Type.ANY);
}
@Test
- public void testPhraseNotSubstring() {
+ void testPhraseNotSubstring() {
tester.assertParsed("OR foo (AND substring bar)", "foo *substring*bar", Query.Type.ANY);
}
@Test
- public void testPhraseNotSuffix() {
+ void testPhraseNotSuffix() {
tester.assertParsed("OR (AND foo suffix) bar", "foo*suffix bar", Query.Type.ANY);
}
@Test
- public void testIndexedPrefix() {
+ void testIndexedPrefix() {
Item root = tester.assertParsed("foo.bar:prefix*", "foo.bar:prefix*", Query.Type.ANY);
assertTrue(root instanceof PrefixItem);
}
@Test
- public void testIndexedSubstring() {
+ void testIndexedSubstring() {
Item root = tester.assertParsed("foo.bar:*substring*", "foo.bar:*substring*", Query.Type.ANY);
assertTrue(root instanceof SubstringItem);
}
@Test
- public void testIndexedSuffix() {
+ void testIndexedSuffix() {
Item root = tester.assertParsed("foo.bar:*suffix", "foo.bar:*suffix", Query.Type.ANY);
assertTrue(root instanceof SuffixItem);
}
@Test
- public void testIndexedPhraseNotPrefix() {
+ void testIndexedPhraseNotPrefix() {
tester.assertParsed("AND foo.bar:prefix foo.bar:xyzzy", "foo.bar:prefix*xyzzy", Query.Type.ANY);
}
@Test
- public void testIndexedPhraseNotSubstring() {
+ void testIndexedPhraseNotSubstring() {
tester.assertParsed("AND foo.bar:substring foo.bar:xyzzy", "foo.bar:*substring*xyzzy", Query.Type.ANY);
}
@Test
- public void testIndexedPhraseNotSuffix() {
+ void testIndexedPhraseNotSuffix() {
tester.assertParsed("AND foo.bar:xyzzy foo.bar:suffix", "foo.bar:xyzzy*suffix", Query.Type.ANY);
}
@Test
- public void testPrefixWithWeight() {
+ void testPrefixWithWeight() {
Item root = tester.assertParsed("prefix*!200", "prefix*!200", Query.Type.ANY);
assertTrue(root instanceof PrefixItem);
}
@Test
- public void testSubstringWithWeight() {
+ void testSubstringWithWeight() {
Item root = tester.assertParsed("*substring*!200", "*substring*!200", Query.Type.ANY);
assertTrue(root instanceof SubstringItem);
}
@Test
- public void testSuffixWithWeight() {
+ void testSuffixWithWeight() {
Item root = tester.assertParsed("*suffix!200", "*suffix!200", Query.Type.ANY);
assertTrue(root instanceof SuffixItem);
}
/** Non existing index → and **/
@Test
- public void testNonIndexPhraseNotPrefix() {
+ void testNonIndexPhraseNotPrefix() {
tester.assertParsed("AND void prefix", "void:prefix*", Query.Type.ANY);
}
@Test
- public void testNonIndexPhraseNotSubstring() {
+ void testNonIndexPhraseNotSubstring() {
tester.assertParsed("AND void substring", "void:*substring*", Query.Type.ANY);
}
@Test
- public void testNonIndexPhraseNotSuffix() {
+ void testNonIndexPhraseNotSuffix() {
tester.assertParsed("AND void suffix", "void:*suffix", Query.Type.ANY);
}
/** Explicit phrase → remove '*' **/
@Test
- public void testExplicitPhraseNotPrefix() {
+ void testExplicitPhraseNotPrefix() {
tester.assertParsed("\"prefix bar\"", "\"prefix* bar\"", Query.Type.ANY);
}
@Test
- public void testExplicitPhraseNotSubstring() {
+ void testExplicitPhraseNotSubstring() {
tester.assertParsed("\"substring bar\"", "\"*substring* bar\"", Query.Type.ANY);
}
@Test
- public void testExplicitPhraseNotSuffix() {
+ void testExplicitPhraseNotSuffix() {
tester.assertParsed("\"suffix bar\"", "\"*suffix bar\"", Query.Type.ANY);
}
/** Extra star is ignored */
@Test
- public void testPrefixExtraStar() {
+ void testPrefixExtraStar() {
Item root = tester.assertParsed("prefix*", "prefix**", Query.Type.ANY);
assertTrue(root instanceof PrefixItem);
}
@Test
- public void testSubstringExtraStar() {
+ void testSubstringExtraStar() {
Item root = tester.assertParsed("*substring*", "**substring**", Query.Type.ANY);
assertTrue(root instanceof SubstringItem);
}
@Test
- public void testSuffixExtraStar() {
+ void testSuffixExtraStar() {
Item root = tester.assertParsed("*suffix", "**suffix", Query.Type.ANY);
assertTrue(root instanceof SuffixItem);
}
@Test
- public void testPrefixExtraSpace() {
+ void testPrefixExtraSpace() {
Item root = tester.assertParsed("prefix", "prefix *", Query.Type.ANY);
assertTrue(root instanceof WordItem);
}
@Test
- public void testSubstringExtraSpace() {
+ void testSubstringExtraSpace() {
Item root = tester.assertParsed("*substring*", "* substring*", Query.Type.ANY);
assertTrue(root instanceof SubstringItem);
}
@Test
- public void testSubstringExtraSpace2() {
+ void testSubstringExtraSpace2() {
Item root = tester.assertParsed("*substring", "* substring *", Query.Type.ANY);
assertTrue(root instanceof SuffixItem);
}
@Test
- public void testSuffixExtraSpace() {
+ void testSuffixExtraSpace() {
Item root = tester.assertParsed("*suffix", "* suffix", Query.Type.ANY);
assertTrue(root instanceof SuffixItem);
}
/** Extra spaces with index **/
@Test
- public void testIndexPrefixExtraSpace() {
+ void testIndexPrefixExtraSpace() {
tester.assertParsed("AND foo prefix", "foo:prefix *", Query.Type.ANY);
}
@Test
- public void testIndexSubstringExtraSpace() {
+ void testIndexSubstringExtraSpace() {
Item root = tester.assertParsed("OR foo substring*", "foo:* substring*", Query.Type.ANY);
- assertTrue(((OrItem)root).getItem(0) instanceof WordItem);
- assertTrue(((OrItem)root).getItem(1) instanceof PrefixItem);
+ assertTrue(((OrItem) root).getItem(0) instanceof WordItem);
+ assertTrue(((OrItem) root).getItem(1) instanceof PrefixItem);
}
@Test
- public void testIndexSubstringExtraSpace2() {
+ void testIndexSubstringExtraSpace2() {
Item root = tester.assertParsed("OR foo substring", "foo:* substring *", Query.Type.ANY);
- assertTrue(((OrItem)root).getItem(0) instanceof WordItem);
- assertTrue(((OrItem)root).getItem(1) instanceof WordItem);
+ assertTrue(((OrItem) root).getItem(0) instanceof WordItem);
+ assertTrue(((OrItem) root).getItem(1) instanceof WordItem);
}
@Test
- public void testIndexSuffixExtraSpace() {
+ void testIndexSuffixExtraSpace() {
Item root = tester.assertParsed("OR foo suffix", "foo:* suffix", Query.Type.ANY);
- assertTrue(((OrItem)root).getItem(0) instanceof WordItem);
- assertTrue(((OrItem)root).getItem(1) instanceof WordItem);
+ assertTrue(((OrItem) root).getItem(0) instanceof WordItem);
+ assertTrue(((OrItem) root).getItem(1) instanceof WordItem);
}
/** Various tests for prefix, substring, and suffix terms **/
@Test
- public void testTermsWithStarsAndSpaces() {
+ void testTermsWithStarsAndSpaces() {
tester.assertParsed("OR foo *bar", "foo * bar", Query.Type.ANY);
}
@Test
- public void testTermsWithStarsAndSpaces2() {
+ void testTermsWithStarsAndSpaces2() {
tester.assertParsed("OR foo *bar *baz", "foo * * bar * * baz", Query.Type.ANY);
}
@Test
- public void testTermsWithStarsAndPlussAndMinus() {
+ void testTermsWithStarsAndPlussAndMinus() {
tester.assertParsed("+(AND *bar baz*) -*foo*", "+*bar -*foo* +baz*", Query.Type.ANY);
}
@Test
- public void testTermsWithStarsAndPlussAndMinus2() {
+ void testTermsWithStarsAndPlussAndMinus2() {
tester.assertParsed("OR *bar *foo baz", "+ * bar - * foo * + baz *", Query.Type.ANY);
}
@Test
- public void testTermsWithStarsAndExclamation() {
+ void testTermsWithStarsAndExclamation() {
tester.assertParsed("OR foo* 200 *bar* 200 *baz 200", "foo* !200 *bar* !200 *baz !200", Query.Type.ANY);
}
@Test
- public void testTermsWithStarsAndExclamation2() {
+ void testTermsWithStarsAndExclamation2() {
tester.assertParsed("OR foo 200 *bar 200", "foo *!200 *bar *!200", Query.Type.ANY);
}
@Test
- public void testTermsWithStarsAndParenthesis() {
+ void testTermsWithStarsAndParenthesis() {
tester.assertParsed("RANK *baz *bar* foo*", "(foo*) (*bar*) (*baz)", Query.Type.ANY);
}
@Test
- public void testTermsWithStarsAndParenthesis2() {
+ void testTermsWithStarsAndParenthesis2() {
tester.assertParsed("RANK baz bar foo", "(foo)* *(bar)* *(baz)", Query.Type.ANY);
}
@Test
- public void testSimpleAndFilter() {
+ void testSimpleAndFilter() {
tester.assertParsed("AND bar |foo", "bar", "+foo", Query.Type.ANY);
}
@Test
- public void testSimpleRankFilter() {
+ void testSimpleRankFilter() {
tester.assertParsed("RANK bar |foo", "bar", "foo", Query.Type.ANY);
}
@Test
- public void testSimpleNotFilter() {
+ void testSimpleNotFilter() {
tester.assertParsed("+bar -|foo", "bar", "-foo", Query.Type.ANY);
}
@Test
- public void testSimpleCompoundFilter1() {
+ void testSimpleCompoundFilter1() {
tester.assertParsed("RANK (AND bar |foo1) |foo2", "bar", "+foo1 foo2",
Query.Type.ANY);
}
@Test
- public void testSimpleCompoundFilter2() {
+ void testSimpleCompoundFilter2() {
tester.assertParsed("+(AND bar |foo1) -|foo3", "bar", "+foo1 -foo3",
Query.Type.ANY);
}
@Test
- public void testSimpleCompoundFilter3() {
+ void testSimpleCompoundFilter3() {
tester.assertParsed("RANK (+bar -|foo3) |foo2", "bar", "foo2 -foo3",
Query.Type.ANY);
}
@Test
- public void testSimpleCompoundFilter4() {
+ void testSimpleCompoundFilter4() {
tester.assertParsed("RANK (+(AND bar |foo1) -|foo3) |foo2", "bar",
"+foo1 foo2 -foo3", Query.Type.ANY);
}
@Test
- public void testAndFilterEmptyQuery() {
+ void testAndFilterEmptyQuery() {
tester.assertParsed("|foo", "", "+foo", Query.Type.ANY);
}
@Test
- public void testRankFilterEmptyQuery() {
+ void testRankFilterEmptyQuery() {
tester.assertParsed("|foo", "", "foo", Query.Type.ANY);
}
@Test
- public void testNotFilterEmptyQuery() {
+ void testNotFilterEmptyQuery() {
tester.assertParsed(null, "", "-foo", Query.Type.ANY);
}
@Test
- public void testCompoundFilter1EmptyQuery() {
+ void testCompoundFilter1EmptyQuery() {
tester.assertParsed("RANK |foo1 |foo2", "", "+foo1 foo2", Query.Type.ANY);
}
@Test
- public void testCompoundFilter2EmptyQuery() {
+ void testCompoundFilter2EmptyQuery() {
tester.assertParsed("+|foo1 -|foo3", "", "+foo1 -foo3", Query.Type.ANY);
}
@Test
- public void testCompoundFilter3EmptyQuery() {
+ void testCompoundFilter3EmptyQuery() {
tester.assertParsed("+|foo2 -|foo3", "", "foo2 -foo3", Query.Type.ANY);
}
@Test
- public void testCompoundFilter4EmptyQuery() {
+ void testCompoundFilter4EmptyQuery() {
tester.assertParsed("RANK (+|foo1 -|foo3) |foo2", "", "+foo1 foo2 -foo3",
Query.Type.ANY);
}
@Test
- public void testMultitermAndFilter() {
+ void testMultitermAndFilter() {
tester.assertParsed("AND bar |foo |foz", "bar", "+foo +foz", Query.Type.ANY);
}
@Test
- public void testMultitermRankFilter() {
+ void testMultitermRankFilter() {
tester.assertParsed("RANK bar |foo |foz", "bar", "foo foz", Query.Type.ANY);
}
@Test
- public void testMultitermNotFilter() {
+ void testMultitermNotFilter() {
tester.assertParsed("+bar -|foo -|foz", "bar", "-foo -foz", Query.Type.ANY);
}
@Test
- public void testMultitermCompoundFilter1() {
+ void testMultitermCompoundFilter1() {
tester.assertParsed("RANK (AND bar |foo1 |foz1) |foo2 |foz2", "bar",
"+foo1 +foz1 foo2 foz2", Query.Type.ANY);
}
@Test
- public void testMultitermCompoundFilter2() {
+ void testMultitermCompoundFilter2() {
tester.assertParsed("+(AND bar |foo1 |foz1) -|foo3 -|foz3", "bar",
"+foo1 +foz1 -foo3 -foz3", Query.Type.ANY);
}
@Test
- public void testMultitermCompoundFilter3() {
+ void testMultitermCompoundFilter3() {
tester.assertParsed("RANK (+bar -|foo3 -|foz3) |foo2 |foz2", "bar",
"foo2 foz2 -foo3 -foz3", Query.Type.ANY);
}
@Test
- public void testMultitermCompoundFilter4() {
+ void testMultitermCompoundFilter4() {
tester.assertParsed("RANK (+(AND bar |foo1 |foz1) -|foo3 -|foz3) |foo2 |foz2",
"bar", "+foo1 +foz1 foo2 foz2 -foo3 -foz3", Query.Type.ANY);
}
@Test
- public void testMultitermAndFilterEmptyQuery() {
+ void testMultitermAndFilterEmptyQuery() {
tester.assertParsed("AND |foo |foz", "", "+foo +foz", Query.Type.ANY);
}
@Test
- public void testMultitermRankFilterEmptyQuery() {
+ void testMultitermRankFilterEmptyQuery() {
tester.assertParsed("OR |foo |foz", "", "foo foz", Query.Type.ANY);
}
@Test
- public void testMultitermNotFilterEmptyQuery() {
+ void testMultitermNotFilterEmptyQuery() {
tester.assertParsed(null, "", "-foo -foz", Query.Type.ANY);
}
@Test
- public void testMultitermCompoundFilter1EmptyQuery() {
+ void testMultitermCompoundFilter1EmptyQuery() {
tester.assertParsed("RANK (AND |foo1 |foz1) |foo2 |foz2", "",
"+foo1 +foz1 foo2 foz2", Query.Type.ANY);
}
@Test
- public void testMultitermCompoundFilter2EmptyQuery() {
+ void testMultitermCompoundFilter2EmptyQuery() {
tester.assertParsed("+(AND |foo1 |foz1) -|foo3 -|foz3", "",
"+foo1 +foz1 -foo3 -foz3", Query.Type.ANY);
}
@Test
- public void testMultitermCompoundFilter3EmptyQuery() {
+ void testMultitermCompoundFilter3EmptyQuery() {
tester.assertParsed("+(OR |foo2 |foz2) -|foo3 -|foz3", "",
"foo2 foz2 -foo3 -foz3", Query.Type.ANY);
}
@Test
- public void testMultitermCompoundFilter4EmptyQuery() {
+ void testMultitermCompoundFilter4EmptyQuery() {
tester.assertParsed("RANK (+(AND |foo1 |foz1) -|foo3 -|foz3) |foo2 |foz2", "",
"+foo1 +foz1 foo2 foz2 -foo3 -foz3", Query.Type.ANY);
}
@Test
- public void testMultipleDifferentPhraseSeparators() {
+ void testMultipleDifferentPhraseSeparators() {
tester.assertParsed("AND foo bar", "foo.-.bar", Query.Type.ANY);
}
@Test
- public void testNoisyFilter() {
+ void testNoisyFilter() {
tester.assertParsed("RANK (+(AND foobar kanoo) -|foo) |bar", "foobar and kanoo",
"-foo ;+;bar", Query.Type.ADVANCED);
}
@Test
- public void testReallyNoisyQuery1() {
+ void testReallyNoisyQuery1() {
tester.assertParsed("AND word another", "&word\"()/&#)(/&another!\"", Query.Type.ALL);
}
@Test
- public void testReallyNoisyQuery2() {
+ void testReallyNoisyQuery2() {
tester.assertParsed("AND \u03bc\u03bc hei", "&&&`\u00b5\u00b5=@hei", Query.Type.ALL);
}
@Test
- public void testReallyNoisyQuery3() {
+ void testReallyNoisyQuery3() {
tester.assertParsed("AND hei hallo du der", "hei-hallo;du;der", Query.Type.ALL);
}
@Test
- public void testNumberParsing() {
+ void testNumberParsing() {
Item root = tester.parseQuery("normal:400", null, Language.UNKNOWN, Query.Type.ANY, TestLinguistics.INSTANCE);
assertEquals(root.getCode(), 5);
}
@Test
- public void testRangeParsing() {
+ void testRangeParsing() {
Item root = tester.parseQuery("normal:[5;400]", null, Language.UNKNOWN, Query.Type.ANY, TestLinguistics.INSTANCE);
assertEquals(root.toString(), "normal:[5;400]");
assertEquals(root.getCode(), 5);
}
@Test
- public void testNumberAsPrefix() {
+ void testNumberAsPrefix() {
Item root = tester.assertParsed("89*", "89*", Query.Type.ANY);
assertTrue(root instanceof PrefixItem);
}
@Test
- public void testNumberAsSubstring() {
+ void testNumberAsSubstring() {
Item root = tester.assertParsed("*89*", "*89*", Query.Type.ANY);
assertTrue(root instanceof SubstringItem);
}
@Test
- public void testNumberAsSuffix() {
+ void testNumberAsSuffix() {
Item root = tester.assertParsed("*89", "*89", Query.Type.ANY);
assertTrue(root instanceof SuffixItem);
}
@Test
- public void testTheStupidSymbolsWhichAreNowWordCharactersInUnicode() {
+ void testTheStupidSymbolsWhichAreNowWordCharactersInUnicode() {
tester.assertParsed("AND yz a", "yz\u00A8\u00AA\u00AF", Query.Type.ANY);
}
@Test
- public void testTWoWords() {
+ void testTWoWords() {
tester.assertParsed("\"hei h\u00e5\"", "\"hei h\u00e5\"", Query.Type.ANY);
}
@Test
- public void testLoneStar() {
+ void testLoneStar() {
assertNull(tester.parseQuery("*", null, Language.UNKNOWN, Query.Type.ANY, TestLinguistics.INSTANCE));
}
@Test
- public void testLoneStarWithFilter() {
+ void testLoneStarWithFilter() {
tester.assertParsed("|a", "*", "+a", Query.Type.ANY);
}
@Test
- public void testImplicitPhrasingWithIndex() {
+ void testImplicitPhrasingWithIndex() {
tester.assertParsed("AND a:b a:c", "a:/b/c", Query.Type.ANY);
}
@Test
- public void testSingleNoisyTermWithIndex() {
+ void testSingleNoisyTermWithIndex() {
tester.assertParsed("a:b", "a:/b", Query.Type.ANY);
}
@Test
- public void testSingleNoisyPhraseWithIndex() {
+ void testSingleNoisyPhraseWithIndex() {
tester.assertParsed("AND mail:yahoo mail:com", "mail:@yahoo.com", Query.Type.ANY);
}
@Test
- public void testPhraseWithWeightAndIndex() {
+ void testPhraseWithWeightAndIndex() {
tester.assertParsed("to:\"a b\"!150", "to:\"a b\"!150", Query.Type.ANY);
}
@Test
- public void testTermWithWeightAndIndex() {
+ void testTermWithWeightAndIndex() {
tester.assertParsed("to:a!150", "to:a!150", Query.Type.ANY);
}
@Test
- public void testPhrasingWithIndexAndQuerySyntax() {
+ void testPhrasingWithIndexAndQuerySyntax() {
tester.assertParsed("to:\"a b c\"", "to:\"a (b c)\"", Query.Type.ANY);
}
@Test
- public void testPhrasingWithIndexAndHalfBrokenQuerySyntax() {
+ void testPhrasingWithIndexAndHalfBrokenQuerySyntax() {
tester.assertParsed("to:\"a b c\"", "to:\"a +b c)\"", Query.Type.ANY);
}
@Test
- public void testURLHostQueryOneTerm1() {
+ void testURLHostQueryOneTerm1() {
tester.assertParsed("site:\"com $\"", "site:com", Query.Type.ANY);
}
@Test
- public void testURLHostQueryOneTerm2() {
+ void testURLHostQueryOneTerm2() {
tester.assertParsed("site:com", "site:com*", Query.Type.ANY);
}
@Test
- public void testURLHostQueryOneTerm3() {
+ void testURLHostQueryOneTerm3() {
tester.assertParsed("site:\"com $\"", "site:.com", Query.Type.ANY);
}
@Test
- public void testURLHostQueryOneTerm4() {
+ void testURLHostQueryOneTerm4() {
tester.assertParsed("site:\"^ com $\"", "site:^com", Query.Type.ANY);
}
@Test
- public void testURLHostQueryOneTerm5() {
+ void testURLHostQueryOneTerm5() {
tester.assertParsed("site:\"^ com\"", "site:^com*", Query.Type.ANY);
}
@Test
- public void testFullURLQuery() {
+ void testFullURLQuery() {
tester.assertParsed(
"url.all:\"http shopping yahoo-inc com 1080 this is a path shop d hab id 1804905709 frag1\"",
"url.all:http://shopping.yahoo-inc.com:1080/this/is/a/path/shop?d=hab&id=1804905709#frag1",
@@ -1555,7 +1552,7 @@ public class ParseTestCase {
}
@Test
- public void testURLQueryHyphen() {
+ void testURLQueryHyphen() {
tester.assertParsed(
"url.all:\"http news bbc co uk go rss test - sport1 hi tennis 4112866 stm\"",
"url.all:http://news.bbc.co.uk/go/rss/test/-/sport1/hi/tennis/4112866.stm",
@@ -1563,7 +1560,7 @@ public class ParseTestCase {
}
@Test
- public void testURLQueryUnderScoreNumber() {
+ void testURLQueryUnderScoreNumber() {
tester.assertParsed(
"url.all:\"ap 20050621 45_ap_on_re_la_am_ca aruba_missing_teen_5\"",
"url.all:/ap/20050621/45_ap_on_re_la_am_ca/aruba_missing_teen_5",
@@ -1571,7 +1568,7 @@ public class ParseTestCase {
}
@Test
- public void testOtherComplexUrls() {
+ void testOtherComplexUrls() {
tester.assertParsed(
"url.all:\"http redir folha com br redir online dinheiro rss091 http www1 folha uol com br folha dinheiro ult91u96593 shtml\"",
"url.all:http://redir.folha.com.br/redir/online/dinheiro/rss091/*http://www1.folha.uol.com.br/folha/dinheiro/ult91u96593.shtml",
@@ -1595,33 +1592,33 @@ public class ParseTestCase {
}
@Test
- public void testTooGreedyUrlParsing() {
+ void testTooGreedyUrlParsing() {
tester.assertParsed("AND site:\"nypost com $\" about", "site:nypost.com about",
Query.Type.ALL);
}
@Test
- public void testTooGreedyUrlParsing2() {
+ void testTooGreedyUrlParsing2() {
tester.assertParsed("AND site:\"nypost com $\" about foo",
"site:nypost.com about foo", Query.Type.ALL);
}
@Test
- public void testSimplerDurbin() {
+ void testSimplerDurbin() {
tester.assertParsed("+(OR language:en \"Durbin said\" a) -newstype:rssexclude",
"( a (\"Durbin said\" ) -newstype:rssexclude (language:en )",
Query.Type.ALL);
}
@Test
- public void testSimplerDurbin2() {
+ void testSimplerDurbin2() {
tester.assertParsed("+(AND \"Durbin said\" language:en) -newstype:rssexclude",
"( , (\"Durbin said\" ) -newstype:rssexclude (language:en )",
Query.Type.ALL);
}
@Test
- public void testDurbin() {
+ void testDurbin() {
tester.assertParsed(
"AND \"Richard Durbin\" Welfare (+(OR language:en \"Durbin said\" \"Durbin says\" \"Durbin added\" \"Durbin agreed\" \"Durbin questioned\" date:>1109664000) -newstype:rssexclude)",
"(\"Richard Durbin\" ) \"Welfare\" ((\"Durbin said\" \"Durbin says\" \"Durbin added\" \"Durbin agreed\" \"Durbin questioned\" ) -newstype:rssexclude date:>1109664000 (language:en )",
@@ -1629,35 +1626,35 @@ public class ParseTestCase {
}
@Test
- public void testTooLongQueryTerms() {
+ void testTooLongQueryTerms() {
tester.assertParsed("AND 545558598787gggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggcfffffffffffffffffffffffffffffffffffffffffffccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccclllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyytttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrreeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeewwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqlkjhcxxdfffxdzzaqwwsxedcrfvtgbyhnujmikkiloolpppof filter ew 545558598787gggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggcfffffffffffffffffffffffffffffffffffffffffffccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccclllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyytttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrreeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeewwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqlkjhcxxdfffxdzzaqwwsxedcrfvtgbyhnujmikkiloolpppof 2b 2f 545558598787gggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggcfffffffffffffffffffffffffffffffffffffffffffccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccclllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyytttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrreeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeewwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqlkjhcxxdfffxdzzaqwwsxedcrfvtgbyhnujmikkiloolpppof",
"+/545558598787gggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggcfffffffffffffffffffffffffffffffffffffffffffccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccclllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyytttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrreeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeewwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqlkjhcxxdfffxdzzaqwwsxedcrfvtgbyhnujmikkiloolpppof&filter=ew:545558598787gggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggcfffffffffffffffffffffffffffffffffffffffffffccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccclllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyytttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrreeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeewwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqlkjhcxxdfffxdzzaqwwsxedcrfvtgbyhnujmikkiloolpppof!1000 =.2b..2f.545558598787gggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggcfffffffffffffffffffffffffffffffffffffffffffccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccclllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyytttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrreeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeewwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqlkjhcxxdfffxdzzaqwwsxedcrfvtgbyhnujmikkiloolpppof",
Query.Type.ALL);
}
@Test
- public void testNonSpecialTokenParsing() {
+ void testNonSpecialTokenParsing() {
ParsingTester customTester = new ParsingTester(SpecialTokens.empty());
customTester.assertParsed("OR c or c with (AND tcp ip)", "c# or c++ with tcp/ip", Query.Type.ANY);
}
@Test
- public void testNonIndexWithColons1() {
+ void testNonIndexWithColons1() {
tester.assertParsed("OR this is (AND notan iindex)", "this is notan:iindex", Query.Type.ANY);
}
@Test
- public void testNonIndexWithColons2() {
+ void testNonIndexWithColons2() {
tester.assertParsed("OR this is (AND notan iindex either)", "this is notan:iindex:either", Query.Type.ANY);
}
@Test
- public void testIndexThenUnderscoreTermBecomesIndex() {
+ void testIndexThenUnderscoreTermBecomesIndex() {
tester.assertParsed("AND name:batch name:article", "name:batch_article", Query.Type.ANY);
}
@Test
- public void testFakeCJKSegmenting() {
+ void testFakeCJKSegmenting() {
// "first" "second" and "third" are segments in the test language
Item item = tester.parseQuery("name:firstsecondthird", null, Language.CHINESE_SIMPLIFIED, Query.Type.ANY, TestLinguistics.INSTANCE);
@@ -1675,7 +1672,7 @@ public class ParseTestCase {
}
@Test
- public void testFakeCJKSegmentingOfPhrase() {
+ void testFakeCJKSegmentingOfPhrase() {
// "first" "second" and "third" are segments in the test language
Item item = tester.parseQuery("name:\"firstsecondthird\"", null, Language.CHINESE_SIMPLIFIED, Query.Type.ANY, TestLinguistics.INSTANCE);
@@ -1689,23 +1686,23 @@ public class ParseTestCase {
assertEquals("name", ((WordItem) segment.getItem(0)).getIndexName());
assertEquals("name", ((WordItem) segment.getItem(1)).getIndexName());
- assertEquals("name", ((WordItem)segment.getItem(2)).getIndexName());
+ assertEquals("name", ((WordItem) segment.getItem(2)).getIndexName());
}
@Test
- public void testAndItemAndImplicitPhrase() {
+ void testAndItemAndImplicitPhrase() {
tester.assertParsed("AND \u00d8 \u00d8 \u00d8 \u00d9",
- "\u00d8\u00b9\u00d8\u00b1\u00d8\u00a8\u00d9", "",
- Query.Type.ALL, Language.CHINESE_SIMPLIFIED);
+ "\u00d8\u00b9\u00d8\u00b1\u00d8\u00a8\u00d9", "",
+ Query.Type.ALL, Language.CHINESE_SIMPLIFIED);
}
@Test
- public void testAvoidMultiLevelAndForLongCJKQueries() {
+ void testAvoidMultiLevelAndForLongCJKQueries() {
Item root = tester.parseQuery(
"\u30d7\u30ed\u91ce\u7403\u962a\u795e\u306e\u672c\u62e0\u5730\u3001\u7532\u5b50\u5712\u7403\u5834\uff08\u5175\u5eab\u770c\u897f\u5bae\u5e02\uff09\u306f\uff11\u65e5\u3001\uff11\uff19\uff12\uff14\u5e74\u30d7\u30ed\u91ce\u7403\u962a\u795e\u306e\u672c\u62e0\u5730\u3001\u7532\u5b50\u5712\u7403\u5834\uff08\u5175\u5eab\u770c\u897f\u5bae\u5e02\uff09\u306f\uff11\u65e5\u3001\uff11\uff19\uff12\uff14\u5e74\u30d7\u30ed\u91ce\u7403\u962a\u795e\u306e\u672c\u62e0\u5730\u3001\u7532\u5b50\u5712\u7403\u5834\uff08\u5175\u5eab\u770c\u897f\u5bae\u5e02\uff09\u306f\uff11\u65e5\u3001\uff11\uff19\uff12\uff14\u5e74\u30d7\u30ed\u91ce\u7403\u962a\u795e\u306e\u672c\u62e0\u5730\u3001\u7532\u5b50\u5712\u7403\u5834\uff08\u5175\u5eab\u770c\u897f\u5bae\u5e02\uff09\u306f\uff11\u65e5\u3001\uff11\uff19\uff12\uff14\u5e74\u30d7\u30ed\u91ce\u7403\u962a\u795e\u306e\u672c\u62e0\u5730\u3001\u7532\u5b50\u5712\u7403\u5834\uff08\u5175\u5eab\u770c\u897f\u5bae\u5e02\uff09\u306f\uff11\u65e5\u3001\uff11\uff19\uff12\uff14\u5e74\u30d7\u30ed\u91ce\u7403\u962a\u795e\u306e\u672c\u62e0\u5730\u3001\u7532\u5b50\u5712\u7403\u5834\uff08\u5175\u5eab\u770c\u897f\u5bae\u5e02\uff09\u306f\uff11\u65e5\u3001\uff11\uff19\uff12\uff14\u5e74",
"", Language.UNKNOWN, Query.Type.ALL, TestLinguistics.INSTANCE);
- assertTrue("Query tree too deep when parsing CJK queries.", 4 > stackDepth(0, root));
+ assertTrue(4 > stackDepth(0, root), "Query tree too deep when parsing CJK queries.");
}
private int stackDepth(int i, Item root) {
@@ -1724,151 +1721,151 @@ public class ParseTestCase {
}
@Test
- public void testFakeCJKSegmentingOfMultiplePhrases() {
+ void testFakeCJKSegmentingOfMultiplePhrases() {
Item item = tester.parseQuery("name:firstsecond.s", null, Language.CHINESE_SIMPLIFIED, Query.Type.ANY, TestLinguistics.INSTANCE);
assertEquals("AND (SAND name:first name:second) name:s", item.toString());
}
@Test
- public void testOrFilter() {
+ void testOrFilter() {
tester.assertParsed("AND d (OR |a |b)", "d", "+(a b)", Query.Type.ALL);
}
@Test
- public void testOrFilterWithTypeAdv() {
+ void testOrFilterWithTypeAdv() {
tester.assertParsed("AND d (OR |a |b)", "d", "+(a b)", Query.Type.ADVANCED);
}
@Test
- public void testPhraseFilter() {
+ void testPhraseFilter() {
tester.assertParsed("AND d |\"a b\"", "d", "+\"a b\"", Query.Type.ALL);
}
@Test
- public void testMinusAndFilter() {
+ void testMinusAndFilter() {
tester.assertParsed("+d -(AND |a |b)", "d", "-(a b)", Query.Type.ALL);
}
@Test
- public void testOrAndSomeTermsFilter() {
+ void testOrAndSomeTermsFilter() {
tester.assertParsed("RANK d |c |a |b |e", "d", "c (a b) e", Query.Type.ALL);
}
// This is an ugly parse tree, but it's at least reasonable
@Test
- public void testOrAndSomeTermsFilterAndAnAnd() {
- AndItem root=(AndItem)tester.assertParsed("AND (RANK d |c |a |b |e) (OR |e |f)", "d", "c (a b) e +(e f)", Query.Type.ALL);
+ void testOrAndSomeTermsFilterAndAnAnd() {
+ AndItem root = (AndItem) tester.assertParsed("AND (RANK d |c |a |b |e) (OR |e |f)", "d", "c (a b) e +(e f)", Query.Type.ALL);
assertFalse(root.isFilter()); // AND
assertFalse(root.getItem(0).isFilter()); // RANK
- assertFalse(((RankItem)root.getItem(0)).getItem(0).isFilter()); // d
- assertTrue(((RankItem)root.getItem(0)).getItem(1).isFilter()); // c
- assertTrue(((RankItem)root.getItem(0)).getItem(2).isFilter()); // a
- assertTrue(((RankItem)root.getItem(0)).getItem(3).isFilter()); // b
- assertTrue(((RankItem)root.getItem(0)).getItem(4).isFilter()); // e
+ assertFalse(((RankItem) root.getItem(0)).getItem(0).isFilter()); // d
+ assertTrue(((RankItem) root.getItem(0)).getItem(1).isFilter()); // c
+ assertTrue(((RankItem) root.getItem(0)).getItem(2).isFilter()); // a
+ assertTrue(((RankItem) root.getItem(0)).getItem(3).isFilter()); // b
+ assertTrue(((RankItem) root.getItem(0)).getItem(4).isFilter()); // e
assertFalse(root.getItem(1).isFilter()); // OR
- assertTrue(((OrItem)root.getItem(1)).getItem(0).isFilter()); // e
- assertTrue(((OrItem)root.getItem(1)).getItem(1).isFilter()); // f
+ assertTrue(((OrItem) root.getItem(1)).getItem(0).isFilter()); // e
+ assertTrue(((OrItem) root.getItem(1)).getItem(1).isFilter()); // f
}
@Test
- public void testUrlNotConsumingBrace() {
+ void testUrlNotConsumingBrace() {
tester.assertParsed("AND A (OR url.all:B url.all:C) D E", "A (url.all:B url.all:C) D E", Query.Type.ALL);
}
// Really a syntax error on part of the user, but it's part of
// the logic where balanced braces are allowed in URLs
@Test
- public void testUrlNotConsumingBrace2() {
+ void testUrlNotConsumingBrace2() {
tester.assertParsed("AND A (OR url.all:B url.all:C) D E",
"A (url.all:B url.all:C)D E", Query.Type.ALL);
}
@Test
- public void testSiteNotConsumingBrace() {
+ void testSiteNotConsumingBrace() {
tester.assertParsed("AND A (OR site:\"B $\" site:\"C $\") D E",
"A (site:B site:C) D E", Query.Type.ALL);
}
@Test
- public void testCommaOnlyLeadsToImplicitPhrasing() {
+ void testCommaOnlyLeadsToImplicitPhrasing() {
tester.assertParsed("AND A B C", "A,B,C", Query.Type.ALL);
}
@Test
- public void testBangDoesNotBindAcrossSpace() {
+ void testBangDoesNotBindAcrossSpace() {
tester.assertParsed("word", "word !", Query.Type.ALL);
}
@Test
- public void testLotsOfPlusMinus() {
+ void testLotsOfPlusMinus() {
tester.assertParsed("OR word term", "word - + - + - term", Query.Type.ANY);
}
@Test
- public void testLotsOfMinusPlus() {
+ void testLotsOfMinusPlus() {
tester.assertParsed("OR word term", "word - + - + term", Query.Type.ANY);
}
@Test
- public void testMinusDoesNotBindAcrossSpace() {
+ void testMinusDoesNotBindAcrossSpace() {
tester.assertParsed("OR word term", "word - term", Query.Type.ANY);
}
@Test
- public void testPlusDoesNotBindAcrossSpace() {
+ void testPlusDoesNotBindAcrossSpace() {
tester.assertParsed("OR word term", "word + term", Query.Type.ANY);
}
@Test
- public void testMinusDoesNotBindAcrossSpaceAllQuery() {
+ void testMinusDoesNotBindAcrossSpaceAllQuery() {
tester.assertParsed("AND word term", "word - term", Query.Type.ALL);
}
@Test
- public void testPlusDoesNotBindAcrossSpaceAllQuery() {
+ void testPlusDoesNotBindAcrossSpaceAllQuery() {
tester.assertParsed("AND word term", "word + term", Query.Type.ALL);
}
@Test
- public void testNoSpaceInIndexPrefix() {
+ void testNoSpaceInIndexPrefix() {
tester.assertParsed("AND url domain:s url.domain:b",
"url. domain:s url.domain:b", Query.Type.ALL);
}
@Test
- public void testNestedParensAndLittleElse() {
+ void testNestedParensAndLittleElse() {
tester.assertParsed("OR a b c d", "((a b) (c d))", Query.Type.ALL);
}
// This is simply to control it doesn't crash
@Test
- public void testNestedParensAndLittleElseMoreBroken() {
+ void testNestedParensAndLittleElseMoreBroken() {
tester.assertParsed("AND (OR a b) (OR c d)", "(a b) +(c d))", Query.Type.ALL);
}
@Test
- public void testNestedUnbalancedParensAndLittleElseMoreBroken() {
+ void testNestedUnbalancedParensAndLittleElseMoreBroken() {
tester.assertParsed("OR a b c d", "((a b) +(c d)", Query.Type.ALL);
}
@Test
- public void testUnbalancedParens() {
+ void testUnbalancedParens() {
tester.assertParsed("AND a b (OR c d)", "a b) +(c d))", Query.Type.ALL);
}
@Test
- public void testUnbalancedStartingParens() {
+ void testUnbalancedStartingParens() {
tester.assertParsed("OR a b c d", "((a b) +(c d", Query.Type.ALL);
}
@Test
- public void testJPMobileExceptionQuery() {
+ void testJPMobileExceptionQuery() {
tester.assertParsed("OR concat and (AND make string) 1 47 or",
- "(concat \"and\" (make-string 1 47) \"or\")", Query.Type.ALL);
+ "(concat \"and\" (make-string 1 47) \"or\")", Query.Type.ALL);
}
@Test
- public void testColonDoesNotBindAcrossSpace() {
+ void testColonDoesNotBindAcrossSpace() {
tester.assertParsed("b", "a: b", Query.Type.ALL);
tester.assertParsed("AND a b", "a : b", Query.Type.ALL);
tester.assertParsed("AND a b", "a :b", Query.Type.ALL);
@@ -1877,14 +1874,14 @@ public class ParseTestCase {
}
@Test
- public void testGermanUriDecompounding() {
+ void testGermanUriDecompounding() {
tester.assertParsed("url.all:\"kommunikationsfehler de\"",
- "url.all:kommunikationsfehler.de", "", Query.Type.ALL, Language.GERMAN);
+ "url.all:kommunikationsfehler.de", "", Query.Type.ALL, Language.GERMAN);
}
// Check the parser doesn't fail on these horrible query strings
@Test
- public void testTicket443882() {
+ void testTicket443882() {
tester.assertParsed(
"AND australian LOTTERY (+(OR language:en IN AFFILIATION WITH THE UK NATIONAL LOTTERY date:>1125475200) -newstype:rssexclude)",
"australian LOTTERY (IN AFFILIATION WITH THE UK NATIONAL LOTTERY -newstype:rssexclude date:>1125475200 (language:en )",
@@ -1900,7 +1897,7 @@ public class ParseTestCase {
}
@Test
- public void testParensInQuotes() {
+ void testParensInQuotes() {
tester.assertParsed("AND ringtone (OR a:\"Delivery SMAF large max 150kB 063\" a:\"RealMusic Delivery\")",
"ringtone AND (a:\"Delivery SMAF large max.150kB (063)\" OR a:\"RealMusic Delivery\" )",
Query.Type.ADVANCED);
@@ -1914,7 +1911,7 @@ public class ParseTestCase {
}
@Test
- public void testMixedCaseIndexNames() {
+ void testMixedCaseIndexNames() {
tester.assertParsed("AND mixedCase:a mixedCase:b notAnIndex c mixedCase:d",
"mixedcase:a MIXEDCASE:b notAnIndex:c mixedCase:d",
Query.Type.ALL);
@@ -1922,9 +1919,9 @@ public class ParseTestCase {
/** CJK special tokens should be recognized also on non-boundaries */
@Test
- public void testChineseSpecialTokens() {
+ void testChineseSpecialTokens() {
tester.assertParsed("AND cat tcp/ip zu foo dotnet bar dotnet dotnet c# c++ bar dotnet dotnet wiz",
- "cattcp/ipzu foo.netbar.net.netC#c++bar.net.netwiz","", Query.Type.ALL, Language.CHINESE_SIMPLIFIED);
+ "cattcp/ipzu foo.netbar.net.netC#c++bar.net.netwiz", "", Query.Type.ALL, Language.CHINESE_SIMPLIFIED);
}
/**
@@ -1932,69 +1929,69 @@ public class ParseTestCase {
* but right now it is not
*/
@Test
- public void testChineseSpecialTokensWithMultiSegmentReplace() {
+ void testChineseSpecialTokensWithMultiSegmentReplace() {
// special-token-fs is a special token, to be replaced by firstsecond, first and second are segments in test
- tester.assertParsed("AND tcp/ip firstsecond dotnet firstsecond (SAND first second)","tcp/ipspecial-token-fs.net special-token-fs firstsecond",
- "", Query.Type.ALL, Language.CHINESE_SIMPLIFIED, TestLinguistics.INSTANCE);
+ tester.assertParsed("AND tcp/ip firstsecond dotnet firstsecond (SAND first second)", "tcp/ipspecial-token-fs.net special-token-fs firstsecond",
+ "", Query.Type.ALL, Language.CHINESE_SIMPLIFIED, TestLinguistics.INSTANCE);
}
@Test
- public void testSpaceAndTermWeights() {
+ void testSpaceAndTermWeights() {
tester.assertParsed("AND yahoo!360 yahoo 360 yahoo!150 360 yahoo 360 yahoo yahoo!150 yahoo!200",
- "yahoo!360 yahoo !360 yahoo! 360 yahoo ! 360 yahoo !!! yahoo! ! yahoo!!", Query.Type.ALL);
+ "yahoo!360 yahoo !360 yahoo! 360 yahoo ! 360 yahoo !!! yahoo! ! yahoo!!", Query.Type.ALL);
}
@Test
- public void testNumbersAndNot() {
+ void testNumbersAndNot() {
tester.assertParsed("AND a -12", "a -12", Query.Type.ALL);
}
@Test
- public void testNumbersAndDoubleNot() {
+ void testNumbersAndDoubleNot() {
tester.assertParsed("+a --12", "a --12", Query.Type.ALL);
}
@Test
- public void testNegativeNumberWithIndex() {
+ void testNegativeNumberWithIndex() {
tester.assertParsed("normal:-12", "normal:-12", Query.Type.ALL);
}
@Test
- public void testNegativeTermPositiveNumberWithIndex() {
+ void testNegativeTermPositiveNumberWithIndex() {
tester.assertParsed("+a -normal:12", "a -normal:12", Query.Type.ALL);
}
@Test
- public void testNegativeTermNegativeNumberWithIndex() {
+ void testNegativeTermNegativeNumberWithIndex() {
tester.assertParsed("+a -normal:-12", "a -normal:-12", Query.Type.ALL);
}
@Test
- public void testNegativeTermPositiveNumberInParentheses() {
+ void testNegativeTermPositiveNumberInParentheses() {
tester.assertParsed("+a -12", "a -(12)", Query.Type.ALL);
tester.assertParsed("+a -(AND 12 15)", "a -(12 15)", Query.Type.ALL);
tester.assertParsed("+a -12 -15", "a -(12) -(15)", Query.Type.ALL);
}
@Test
- public void testSingleNegativeNumberLikeTerm() {
+ void testSingleNegativeNumberLikeTerm() {
tester.assertParsed("-12", "-12", Query.Type.ALL);
}
@Test
- public void testNegativeLessThan() {
+ void testNegativeLessThan() {
tester.assertParsed("normal:<-3", "normal:<-3", Query.Type.ALL);
tester.assertParsed("<-3", "<-3", Query.Type.ALL);
}
@Test
- public void testNegativeBiggerThan() {
+ void testNegativeBiggerThan() {
tester.assertParsed("normal:>-3", "normal:>-3", Query.Type.ALL);
tester.assertParsed(">-3", ">-3", Query.Type.ALL);
}
@Test
- public void testNegativesInRanges() {
+ void testNegativesInRanges() {
tester.assertParsed("normal:[-4;9]", "normal:[-4;9]", Query.Type.ALL);
tester.assertParsed("[-4;9]", "[-4;9]", Query.Type.ALL);
tester.assertParsed("normal:[-4;-9]", "normal:[-4;-9]", Query.Type.ALL);
@@ -2002,51 +1999,51 @@ public class ParseTestCase {
}
@Test
- public void testDecimal() {
- Item root=tester.assertParsed("2.2", "2.2", Query.Type.ALL);
+ void testDecimal() {
+ Item root = tester.assertParsed("2.2", "2.2", Query.Type.ALL);
assertTrue(root instanceof IntItem);
tester.assertParsed("normal:2.2", "normal:2.2", Query.Type.ALL);
}
@Test
- public void testVersionNumbers() {
+ void testVersionNumbers() {
tester.assertParsed("AND 1 0 9", "1.0.9", Query.Type.ALL);
}
@Test
- public void testDecimalNumbersAndNot() {
+ void testDecimalNumbersAndNot() {
tester.assertParsed("AND a -12.2", "a -12.2", Query.Type.ALL);
}
@Test
- public void testDecimalNumbersAndDoubleNot() {
+ void testDecimalNumbersAndDoubleNot() {
tester.assertParsed("+a --12.2", "a --12.2", Query.Type.ALL);
}
@Test
- public void testNegativeDecimalNumberWithIndex() {
+ void testNegativeDecimalNumberWithIndex() {
tester.assertParsed("normal:-12.2", "normal:-12.2", Query.Type.ALL);
}
@Test
- public void testSingleNegativeDecimalNumberLikeTerm() {
+ void testSingleNegativeDecimalNumberLikeTerm() {
tester.assertParsed("-12.2", "-12.2", Query.Type.ALL);
}
@Test
- public void testNegativeDecimalLessThan() {
+ void testNegativeDecimalLessThan() {
tester.assertParsed("normal:<-3.14", "normal:<-3.14", Query.Type.ALL);
tester.assertParsed("<-3.14", "<-3.14", Query.Type.ALL);
}
@Test
- public void testNegativeDecimalBiggerThan() {
+ void testNegativeDecimalBiggerThan() {
tester.assertParsed("normal:>-3.14", "normal:>-3.14", Query.Type.ALL);
tester.assertParsed(">-3.14", ">-3.14", Query.Type.ALL);
}
@Test
- public void testNegativesDecimalInRanges() {
+ void testNegativesDecimalInRanges() {
tester.assertParsed("normal:[-4.16;9.2]", "normal:[-4.16;9.2]", Query.Type.ALL);
tester.assertParsed("[-4.16;9.2]", "[-4.16;9.2]", Query.Type.ALL);
tester.assertParsed("normal:[-4.16;-9.2]", "normal:[-4.16;-9.2]", Query.Type.ALL);
@@ -2054,12 +2051,12 @@ public class ParseTestCase {
}
@Test
- public void testRangesAndNoise() {
+ void testRangesAndNoise() {
tester.assertParsed("[2;3]", "[2;3]]", Query.Type.ALL);
}
@Test
- public void testIndexNoise() {
+ void testIndexNoise() {
tester.assertParsed("AND normal:a notanindex", "normal:a normal: notanindex:", Query.Type.ALL);
tester.assertParsed(null, "normal:", Query.Type.ALL);
tester.assertParsed(null, "normal:!", Query.Type.ALL);
@@ -2070,13 +2067,13 @@ public class ParseTestCase {
}
@Test
- public void testIndexNoiseAndExplicitPhrases() {
+ void testIndexNoiseAndExplicitPhrases() {
tester.assertParsed("normal:\"a b\"", "normal:\" a b\"", Query.Type.ALL);
tester.assertParsed("normal:\"a b\"", "normal:\"a b\"", Query.Type.ALL);
}
@Test
- public void testExactMatchParsing1() {
+ void testExactMatchParsing1() {
SearchDefinition sd = new SearchDefinition("testsd");
Index index1 = new Index("testexact1");
@@ -2092,13 +2089,13 @@ public class ParseTestCase {
customTester.assertParsed("testexact1:/,%&#", "testexact1:/,%&#", Query.Type.ALL);
customTester.assertParsed("testexact2:/,%&#!!", "testexact2:/,%&#!!()/aa*::*&", Query.Type.ALL);
- customTester.assertParsed("AND word1 (OR testexact1:word2 testexact1:word3)","word1 AND (testexact1:word2 OR testexact1:word3 )",Query.Type.ADVANCED);
- customTester.assertParsed("AND word (OR testexact1:AND testexact1:OR)","word AND (testexact1: AND OR testexact1: OR )",Query.Type.ADVANCED);
+ customTester.assertParsed("AND word1 (OR testexact1:word2 testexact1:word3)", "word1 AND (testexact1:word2 OR testexact1:word3 )", Query.Type.ADVANCED);
+ customTester.assertParsed("AND word (OR testexact1:AND testexact1:OR)", "word AND (testexact1: AND OR testexact1: OR )", Query.Type.ADVANCED);
}
/** Testing terminators containing control characters in conjunction with those control characters */
@Test
- public void testExactMatchParsing2() {
+ void testExactMatchParsing2() {
SearchDefinition sd = new SearchDefinition("testsd");
Index index1 = new Index("testexact1");
@@ -2108,12 +2105,12 @@ public class ParseTestCase {
IndexFacts indexFacts = new IndexFacts(new IndexModel(sd));
ParsingTester customTester = new ParsingTester(indexFacts);
- customTester.assertParsed("testexact1:_-_*!200","testexact1:_-_*!**!!",Query.Type.ALL);
+ customTester.assertParsed("testexact1:_-_*!200", "testexact1:_-_*!**!!", Query.Type.ALL);
}
/** Testing terminators containing control characters in conjunction with those control characters */
@Test
- public void testExactMatchParsing3() {
+ void testExactMatchParsing3() {
SearchDefinition sd = new SearchDefinition("testsd");
Index index1 = new Index("testexact1");
@@ -2123,48 +2120,48 @@ public class ParseTestCase {
IndexFacts indexFacts = new IndexFacts(new IndexModel(sd));
ParsingTester customTester = new ParsingTester(indexFacts);
- customTester.assertParsed("testexact1:_-_*!200","testexact1:_-_**!!",Query.Type.ALL);
+ customTester.assertParsed("testexact1:_-_*!200", "testexact1:_-_**!!", Query.Type.ALL);
}
// bug 1393139
@Test
- public void testMinimalBritneyFilter() {
+ void testMinimalBritneyFilter() {
tester.assertParsed("RANK (+a -|c) b", "a RANK b", "-c", Query.Type.ADVANCED);
}
@Test
- public void testBritneyFilter() {
+ void testBritneyFilter() {
tester.assertParsed("RANK (+(AND performernameall:britney performernameall:spears songnameall:toxic |SongConsumable:1 |country:us |collapsedrecord:1 |doctype:song) -|collapsecount:0) (AND metadata:britney metadata:spears metadata:toxic)",
- "((performernameall:britney AND performernameall:spears AND songnameall:toxic) RANK (metadata:britney AND metadata:spears AND metadata:toxic))",
- "+SongConsumable:1 +country:us +collapsedrecord:1 -collapsecount:0 +doctype:song",
- Query.Type.ADVANCED);
+ "((performernameall:britney AND performernameall:spears AND songnameall:toxic) RANK (metadata:britney AND metadata:spears AND metadata:toxic))",
+ "+SongConsumable:1 +country:us +collapsedrecord:1 -collapsecount:0 +doctype:song",
+ Query.Type.ADVANCED);
tester.assertParsed("AND (+(AND (RANK (OR (AND performernameall:britney performernameall:spears songnameall:toxic) (AND performernameall:britney performernameall:spears songnameall:toxic)) (AND metadata:britney metadata:spears metadata:toxic)) |SongConsumable:1 |country:us |collapsedrecord:1) -|collapsecount:0) |doctype:song",
- "(((performernameall:britney AND performernameall:spears AND songnameall:toxic) OR (performernameall:britney AND performernameall:spears AND songnameall:toxic)) RANK (metadata:britney AND metadata:spears AND metadata:toxic)))",
- "+SongConsumable:1 +country:us +collapsedrecord:1 -collapsecount:0 +doctype:song",
- Query.Type.ADVANCED);
+ "(((performernameall:britney AND performernameall:spears AND songnameall:toxic) OR (performernameall:britney AND performernameall:spears AND songnameall:toxic)) RANK (metadata:britney AND metadata:spears AND metadata:toxic)))",
+ "+SongConsumable:1 +country:us +collapsedrecord:1 -collapsecount:0 +doctype:song",
+ Query.Type.ADVANCED);
}
// bug 1412840
@Test
- public void testGreedyPhrases() {
+ void testGreedyPhrases() {
tester.assertParsed("AND title:why title:\"1 2\"", "title:\"why\" title:\"&\" title:\"1/2\"", Query.Type.ALL);
}
// bug 1509347
@Test
- public void testUnderscoreInFieldNames() {
+ void testUnderscoreInFieldNames() {
tester.assertParsed("AND title:why score_under:what score_under:>5000",
- "title:why score_under:what score_under:>5000",
- Query.Type.ALL);
+ "title:why score_under:what score_under:>5000",
+ Query.Type.ALL);
}
// bug 1509347
@Test
- public void testLeadingUnderscoreInFieldNames() {
+ void testLeadingUnderscoreInFieldNames() {
tester.assertParsed("AND title:why _under_score_:what _under_score_:>5000",
- "title:why _under_score_:what _under_score_:>5000",
- Query.Type.ALL);
+ "title:why _under_score_:what _under_score_:>5000",
+ Query.Type.ALL);
}
// Re-add if underscore should be a word character
@@ -2185,7 +2182,7 @@ public class ParseTestCase {
// bug 524918
@Test
- public void testAdvancedSyntaxParensAndQuotes() {
+ void testAdvancedSyntaxParensAndQuotes() {
tester.assertParsed("OR a (AND \"b c d\" e)",
"a OR (\"b (c) d\" AND e)",
Query.Type.ADVANCED);
@@ -2195,7 +2192,7 @@ public class ParseTestCase {
// this needs to become series of tests where the tokenizer
// and parser will step on each other's toes.
@Test
- public void testStarFirstInAttributes() {
+ void testStarFirstInAttributes() {
tester.assertParsed("exactindex:*test",
"exactindex:*test",
Query.Type.ALL);
@@ -2203,162 +2200,162 @@ public class ParseTestCase {
}
@Test
- public void testOneWordWebParsing() {
- tester.assertParsed("a","a",Query.Type.WEB);
+ void testOneWordWebParsing() {
+ tester.assertParsed("a", "a", Query.Type.WEB);
}
@Test
- public void testTwoWordWebParsing() {
- tester.assertParsed("AND a b","a b",Query.Type.WEB);
+ void testTwoWordWebParsing() {
+ tester.assertParsed("AND a b", "a b", Query.Type.WEB);
}
@Test
- public void testPlusWordWebParsing1() {
- Item root=tester.assertParsed("AND a b","+a b",Query.Type.WEB);
- assertTrue(((AndItem)root).getItem(0).isProtected());
- assertFalse(((AndItem)root).getItem(1).isProtected());
+ void testPlusWordWebParsing1() {
+ Item root = tester.assertParsed("AND a b", "+a b", Query.Type.WEB);
+ assertTrue(((AndItem) root).getItem(0).isProtected());
+ assertFalse(((AndItem) root).getItem(1).isProtected());
}
@Test
- public void testPlusWordWebParsing2() {
- Item root=tester.assertParsed("AND a b","+a +b",Query.Type.WEB);
- assertTrue(((AndItem)root).getItem(0).isProtected());
- assertTrue(((AndItem)root).getItem(1).isProtected());
+ void testPlusWordWebParsing2() {
+ Item root = tester.assertParsed("AND a b", "+a +b", Query.Type.WEB);
+ assertTrue(((AndItem) root).getItem(0).isProtected());
+ assertTrue(((AndItem) root).getItem(1).isProtected());
}
@Test
- public void testNegativeWordsParsing1() {
- Item root=tester.assertParsed("+a -b","a -b",Query.Type.WEB);
- assertFalse(((NotItem)root).getItem(0).isProtected());
- assertTrue(((NotItem)root).getItem(1).isProtected());
+ void testNegativeWordsParsing1() {
+ Item root = tester.assertParsed("+a -b", "a -b", Query.Type.WEB);
+ assertFalse(((NotItem) root).getItem(0).isProtected());
+ assertTrue(((NotItem) root).getItem(1).isProtected());
}
@Test
- public void testNegativeWordsParsing2() {
- Item root=tester.assertParsed("+a -b","+a -b",Query.Type.WEB);
- assertTrue(((NotItem)root).getItem(0).isProtected());
- assertTrue(((NotItem)root).getItem(1).isProtected());
+ void testNegativeWordsParsing2() {
+ Item root = tester.assertParsed("+a -b", "+a -b", Query.Type.WEB);
+ assertTrue(((NotItem) root).getItem(0).isProtected());
+ assertTrue(((NotItem) root).getItem(1).isProtected());
}
@Test
- public void testNegativeWordsParsing3() {
- tester.assertParsed("+a -b","-b a",Query.Type.WEB);
+ void testNegativeWordsParsing3() {
+ tester.assertParsed("+a -b", "-b a", Query.Type.WEB);
}
@Test
- public void testNegativeWordsParsing4() {
- tester.assertParsed("+(AND a b) -c -d","a b -c -d",Query.Type.WEB);
+ void testNegativeWordsParsing4() {
+ tester.assertParsed("+(AND a b) -c -d", "a b -c -d", Query.Type.WEB);
}
@Test
- public void testNegativeWordsParsing5() {
- tester.assertParsed("+(AND a \"b c\" d) -e -f","a -e \"b c\" d -f",Query.Type.WEB);
+ void testNegativeWordsParsing5() {
+ tester.assertParsed("+(AND a \"b c\" d) -e -f", "a -e \"b c\" d -f", Query.Type.WEB);
}
@Test
- public void testPhraseWebParsing() {
- tester.assertParsed("\"a b\"","\"a b\"",Query.Type.WEB);
+ void testPhraseWebParsing() {
+ tester.assertParsed("\"a b\"", "\"a b\"", Query.Type.WEB);
}
@Test
- public void testPhraseAndExtraTermWebParsing() {
- tester.assertParsed("AND \"a b\" c","\"a b\" c",Query.Type.WEB);
+ void testPhraseAndExtraTermWebParsing() {
+ tester.assertParsed("AND \"a b\" c", "\"a b\" c", Query.Type.WEB);
}
@Test
- public void testNotOrWebParsing() {
- tester.assertParsed("AND a or b","a or b",Query.Type.WEB);
+ void testNotOrWebParsing() {
+ tester.assertParsed("AND a or b", "a or b", Query.Type.WEB);
}
@Test
- public void testNotOrALLParsing() {
- tester.assertParsed("AND a OR b","a OR b",Query.Type.ALL);
+ void testNotOrALLParsing() {
+ tester.assertParsed("AND a OR b", "a OR b", Query.Type.ALL);
}
@Test
- public void testOrParsing1() {
- tester.assertParsed("OR a b","a OR b",Query.Type.WEB);
+ void testOrParsing1() {
+ tester.assertParsed("OR a b", "a OR b", Query.Type.WEB);
}
@Test
- public void testOrParsing2() {
- tester.assertParsed("OR a b c","a OR b OR c",Query.Type.WEB);
+ void testOrParsing2() {
+ tester.assertParsed("OR a b c", "a OR b OR c", Query.Type.WEB);
}
@Test
- public void testOrParsing3() {
- tester.assertParsed("OR a (AND b c) \"d e\"","a OR b c OR \"d e\"",Query.Type.WEB);
+ void testOrParsing3() {
+ tester.assertParsed("OR a (AND b c) \"d e\"", "a OR b c OR \"d e\"", Query.Type.WEB);
}
@Test
- public void testOrParsing4() {
- tester.assertParsed("OR (AND or1 a) or2","or1 a OR or2",Query.Type.WEB);
+ void testOrParsing4() {
+ tester.assertParsed("OR (AND or1 a) or2", "or1 a OR or2", Query.Type.WEB);
}
@Test
- public void testOrCornerCase1() {
- tester.assertParsed("AND OR a","OR a",Query.Type.WEB);
+ void testOrCornerCase1() {
+ tester.assertParsed("AND OR a", "OR a", Query.Type.WEB);
}
@Test
- public void testOrCornerCase2() {
- tester.assertParsed("AND OR a","OR a OR",Query.Type.WEB); // Don't care
+ void testOrCornerCase2() {
+ tester.assertParsed("AND OR a", "OR a OR", Query.Type.WEB); // Don't care
}
@Test
- public void testOrCornerCase3() {
- tester.assertParsed("AND OR a","OR a OR OR",Query.Type.WEB); // Don't care
+ void testOrCornerCase3() {
+ tester.assertParsed("AND OR a", "OR a OR OR", Query.Type.WEB); // Don't care
}
@Test
- public void testOrCornerCase4() {
- tester.assertParsed("+(OR (AND a b) (AND d c) (AND g h)) -e -f","a b OR d c -e -f OR g h",Query.Type.WEB);
+ void testOrCornerCase4() {
+ tester.assertParsed("+(OR (AND a b) (AND d c) (AND g h)) -e -f", "a b OR d c -e -f OR g h", Query.Type.WEB);
}
@Test
- public void testOdd1Web() {
- tester.assertParsed("AND window print error", "+window.print() +error",Query.Type.WEB);
+ void testOdd1Web() {
+ tester.assertParsed("AND window print error", "+window.print() +error", Query.Type.WEB);
}
@Test
- public void testNotOnlyWeb() {
+ void testNotOnlyWeb() {
tester.assertParsed(null, "-foobar", Query.Type.WEB);
}
@Test
- public void testMultipleNotsOnltWeb() {
+ void testMultipleNotsOnltWeb() {
tester.assertParsed(null, "-foo -bar -foobar", Query.Type.WEB);
}
@Test
- public void testOnlyNotCompositeWeb() {
+ void testOnlyNotCompositeWeb() {
tester.assertParsed(null, "-(foo bar baz)", Query.Type.WEB);
}
@Test
- public void testSingleNegativeNumberLikeTermWeb() {
+ void testSingleNegativeNumberLikeTermWeb() {
tester.assertParsed("-12", "-12", Query.Type.WEB);
}
@Test
- public void testSingleNegativeDecimalNumberLikeTermWeb() {
+ void testSingleNegativeDecimalNumberLikeTermWeb() {
tester.assertParsed("-12.2", "-12.2", Query.Type.WEB);
}
@Test
- public void testDefaultWebIndices() {
- tester.assertParsed("AND notanindex b","notanindex:b", Query.Type.WEB);
- tester.assertParsed("site:\"b $\"","site:b", Query.Type.WEB);
- tester.assertParsed("hostname:b","hostname:b", Query.Type.WEB);
- tester.assertParsed("link:b","link:b", Query.Type.WEB);
- tester.assertParsed("url:b","url:b", Query.Type.WEB);
- tester.assertParsed("inurl:b","inurl:b", Query.Type.WEB);
- tester.assertParsed("intitle:b","intitle:b", Query.Type.WEB);
+ void testDefaultWebIndices() {
+ tester.assertParsed("AND notanindex b", "notanindex:b", Query.Type.WEB);
+ tester.assertParsed("site:\"b $\"", "site:b", Query.Type.WEB);
+ tester.assertParsed("hostname:b", "hostname:b", Query.Type.WEB);
+ tester.assertParsed("link:b", "link:b", Query.Type.WEB);
+ tester.assertParsed("url:b", "url:b", Query.Type.WEB);
+ tester.assertParsed("inurl:b", "inurl:b", Query.Type.WEB);
+ tester.assertParsed("intitle:b", "intitle:b", Query.Type.WEB);
}
@Test
- public void testHTMLWeb() {
- tester.assertParsed("AND h2 Title h2","<h2>Title</h2>",Query.Type.WEB);
+ void testHTMLWeb() {
+ tester.assertParsed("AND h2 Title h2", "<h2>Title</h2>", Query.Type.WEB);
}
/**
@@ -2366,82 +2363,82 @@ public class ParseTestCase {
* The information about added bangs is available from the origin as shown (do not use the weight to find this)
*/
@Test
- public void testShortcutsWeb() {
- tester.assertParsed("AND map new york","map new york",Query.Type.WEB);
+ void testShortcutsWeb() {
+ tester.assertParsed("AND map new york", "map new york", Query.Type.WEB);
- AndItem root=(AndItem)tester.assertParsed("AND map!150 new york","map! new york",Query.Type.WEB);
- assertEquals('!',((WordItem)root.getItem(0)).getOrigin().charAfter(0));
+ AndItem root = (AndItem) tester.assertParsed("AND map!150 new york", "map! new york", Query.Type.WEB);
+ assertEquals('!', ((WordItem) root.getItem(0)).getOrigin().charAfter(0));
- root=(AndItem)tester.assertParsed("AND barack obama news!150","barack obama news!",Query.Type.WEB);
- assertEquals('!',((WordItem)root.getItem(2)).getOrigin().charAfter(0));
+ root = (AndItem) tester.assertParsed("AND barack obama news!150", "barack obama news!", Query.Type.WEB);
+ assertEquals('!', ((WordItem) root.getItem(2)).getOrigin().charAfter(0));
}
@Test
- public void testZipCodeShortcutWeb() {
- tester.assertParsed("12345","12345",Query.Type.WEB);
- IntItem root=(IntItem)tester.assertParsed("00012!150","00012!",Query.Type.WEB);
- assertEquals('!',root.getOrigin().charAfter(0));
+ void testZipCodeShortcutWeb() {
+ tester.assertParsed("12345", "12345", Query.Type.WEB);
+ IntItem root = (IntItem) tester.assertParsed("00012!150", "00012!", Query.Type.WEB);
+ assertEquals('!', root.getOrigin().charAfter(0));
}
@Test
- public void testDouble() {
- Item number=tester.assertParsed("123456789.987654321","123456789.987654321",Query.Type.ALL);
+ void testDouble() {
+ Item number = tester.assertParsed("123456789.987654321", "123456789.987654321", Query.Type.ALL);
assertTrue(number instanceof IntItem);
}
@Test
- public void testLong() {
- Item number=tester.assertParsed("3000000000000","3000000000000",Query.Type.ALL);
+ void testLong() {
+ Item number = tester.assertParsed("3000000000000", "3000000000000", Query.Type.ALL);
assertTrue(number instanceof IntItem);
}
@Test
- public void testNear1() {
- tester.assertParsed("NEAR(2) new york","new NEAR york",Query.Type.ADVANCED);
+ void testNear1() {
+ tester.assertParsed("NEAR(2) new york", "new NEAR york", Query.Type.ADVANCED);
}
@Test
- public void testNear2() {
- tester.assertParsed("ONEAR(2) new york","new ONEAR york",Query.Type.ADVANCED);
+ void testNear2() {
+ tester.assertParsed("ONEAR(2) new york", "new ONEAR york", Query.Type.ADVANCED);
}
@Test
- public void testNear3() {
- tester.assertParsed("NEAR(3) new york","new NEAR(3) york",Query.Type.ADVANCED);
+ void testNear3() {
+ tester.assertParsed("NEAR(3) new york", "new NEAR(3) york", Query.Type.ADVANCED);
}
@Test
- public void testNear4() {
- tester.assertParsed("ONEAR(3) new york","new ONEAR(3) york",Query.Type.ADVANCED);
+ void testNear4() {
+ tester.assertParsed("ONEAR(3) new york", "new ONEAR(3) york", Query.Type.ADVANCED);
}
@Test
- public void testNear5() {
- tester.assertParsed("NEAR(3) map new york","map NEAR(3) new NEAR(3) york",Query.Type.ADVANCED);
+ void testNear5() {
+ tester.assertParsed("NEAR(3) map new york", "map NEAR(3) new NEAR(3) york", Query.Type.ADVANCED);
}
@Test
- public void testNear6() {
- tester.assertParsed("ONEAR(3) map new york","map ONEAR(3) new ONEAR(3) york",Query.Type.ADVANCED);
+ void testNear6() {
+ tester.assertParsed("ONEAR(3) map new york", "map ONEAR(3) new ONEAR(3) york", Query.Type.ADVANCED);
}
@Test
- public void testNear7() {
- tester.assertParsed("NEAR(4) (NEAR(3) map new) york","map NEAR(3) new NEAR(4) york",Query.Type.ADVANCED);
+ void testNear7() {
+ tester.assertParsed("NEAR(4) (NEAR(3) map new) york", "map NEAR(3) new NEAR(4) york", Query.Type.ADVANCED);
}
@Test
- public void testNear8() {
- tester.assertParsed("ONEAR(4) (ONEAR(3) map new) york","map ONEAR(3) new ONEAR(4) york",Query.Type.ADVANCED);
+ void testNear8() {
+ tester.assertParsed("ONEAR(4) (ONEAR(3) map new) york", "map ONEAR(3) new ONEAR(4) york", Query.Type.ADVANCED);
}
@Test
- public void testNearPrefix() {
- tester.assertParsed("NEAR(2) a b*","a NEAR b*",Query.Type.ADVANCED);
+ void testNearPrefix() {
+ tester.assertParsed("NEAR(2) a b*", "a NEAR b*", Query.Type.ADVANCED);
}
@Test
- public void testNestedBracesAndPhrases() {
+ void testNestedBracesAndPhrases() {
String userQuery = "(\"Secondary Curriculum\" (\"Key Stage 3\" OR KS3) (\"Key Stage 4\" OR KS4)) ";
tester.assertParsed(
"OR \"Secondary Curriculum\" \"Key Stage 3\" OR KS3 \"Key Stage 4\" OR KS4",
@@ -2458,53 +2455,53 @@ public class ParseTestCase {
}
@Test
- public void testYetAnotherCycleQuery() {
+ void testYetAnotherCycleQuery() {
tester.assertParsed("+(OR (+d -f) b) -c",
"( b -c ( d -f )",
Query.Type.ALL);
}
@Test
- public void testSimpleEquivAdvanced() {
+ void testSimpleEquivAdvanced() {
tester.assertParsed("EQUIV foo bar baz", "foo equiv bar equiv baz", Query.Type.ADVANCED);
}
@Test
- public void testEquivWordIntPhraseAdvanced() {
+ void testEquivWordIntPhraseAdvanced() {
tester.assertParsed("EQUIV foo 5 \"a b\"", "foo equiv 5 equiv \"a b\"", Query.Type.ADVANCED);
}
@Test
- public void testEquivRejectCompositeAdvanced() {
+ void testEquivRejectCompositeAdvanced() {
try {
tester.assertParsed("this should not parse", "foo equiv (a or b)", Query.Type.ADVANCED);
- } catch(Exception e) {
+ } catch (Exception e) {
// Success
}
}
@Test
- public void testSimpleWandAdvanced() {
+ void testSimpleWandAdvanced() {
tester.assertParsed("WEAKAND(100) foo bar baz", "foo wand bar wand baz", Query.Type.ADVANCED);
}
@Test
- public void testSimpleWandAdvancedWithNonDefaultN() {
+ void testSimpleWandAdvancedWithNonDefaultN() {
tester.assertParsed("WEAKAND(32) foo bar baz", "foo weakand(32) bar weakand(32) baz", Query.Type.ADVANCED);
}
@Test
- public void testSimpleWandAdvancedWithNonDefaultNAndWeights() {
+ void testSimpleWandAdvancedWithNonDefaultNAndWeights() {
tester.assertParsed("WEAKAND(32) foo!32 bar!64 baz", "foo!32 weakand(32) bar!64 weakand(32) baz", Query.Type.ADVANCED);
}
@Test
- public void testTwoRanges() {
- tester.assertParsed("AND score:[1.25;2.18] age:[25;30]","score:[1.25;2.18] AND age:[25;30]", Query.Type.ADVANCED);
+ void testTwoRanges() {
+ tester.assertParsed("AND score:[1.25;2.18] age:[25;30]", "score:[1.25;2.18] AND age:[25;30]", Query.Type.ADVANCED);
}
@Test
- public void testTooLargeTermWeights() {
+ void testTooLargeTermWeights() {
// This behavior is a bit silly:
tester.assertParsed("AND a 12345678901234567890", "a!12345678901234567890", Query.Type.ALL);
// but in light of
@@ -2515,7 +2512,7 @@ public class ParseTestCase {
}
@Test
- public void testAndSegmenting() {
+ void testAndSegmenting() {
Item root = tester.parseQuery("a'b&c'd", Language.ENGLISH, Query.Type.ALL);
assertTrue(root instanceof AndItem);
AndItem top = (AndItem) root;
@@ -2527,59 +2524,59 @@ public class ParseTestCase {
Item t2 = seg1.getItem(1);
Item t3 = seg2.getItem(0);
Item t4 = seg2.getItem(1);
- assertTrue(((TaggableItem)t2).hasUniqueID());
- assertTrue(((TaggableItem)t3).hasUniqueID());
- assertTrue(((TaggableItem)t1).getConnectedItem() == t2);
- assertTrue(((TaggableItem)t2).getConnectedItem() == t3);
- assertTrue(((TaggableItem)t3).getConnectedItem() == t4);
+ assertTrue(((TaggableItem) t2).hasUniqueID());
+ assertTrue(((TaggableItem) t3).hasUniqueID());
+ assertEquals(((TaggableItem) t1).getConnectedItem(), t2);
+ assertEquals(((TaggableItem) t2).getConnectedItem(), t3);
+ assertEquals(((TaggableItem) t3).getConnectedItem(), t4);
}
@Test
- public void testSiteAndSegmentPhrases() {
+ void testSiteAndSegmentPhrases() {
tester.assertParsed("host.all:\"www abc com x y-z $\"",
- "host.all:www.abc.com/x'y-z", "",
- Query.Type.ALL, Language.ENGLISH);
+ "host.all:www.abc.com/x'y-z", "",
+ Query.Type.ALL, Language.ENGLISH);
}
@Test
- public void testSiteAndSegmentPhrasesFollowedByText() {
+ void testSiteAndSegmentPhrasesFollowedByText() {
tester.assertParsed("AND host.all:\"www abc com x y-z $\" (SAND a b)",
- "host.all:www.abc.com/x'y-z a'b", "",
- Query.Type.ALL, Language.ENGLISH);
+ "host.all:www.abc.com/x'y-z a'b", "",
+ Query.Type.ALL, Language.ENGLISH);
}
@Test
- public void testIntItemFollowedByDot() {
- tester.assertParsed("AND Campion Ste 3 When To Her Lute Corinna Sings","Campion Ste: 3. When To Her Lute Corinna Sings", Query.Type.ALL);
+ void testIntItemFollowedByDot() {
+ tester.assertParsed("AND Campion Ste 3 When To Her Lute Corinna Sings", "Campion Ste: 3. When To Her Lute Corinna Sings", Query.Type.ALL);
}
@Test
- public void testNotIntItemIfPrecededByHyphen() {
- tester.assertParsed("AND Horny Horny '98 Radio Edit","Horny [Horny '98 Radio Edit]]", Query.Type.ALL);
+ void testNotIntItemIfPrecededByHyphen() {
+ tester.assertParsed("AND Horny Horny '98 Radio Edit", "Horny [Horny '98 Radio Edit]]", Query.Type.ALL);
}
@Test
- public void testNonAsciiNumber() {
+ void testNonAsciiNumber() {
tester.assertParsed("AND title:199 title:119 title:201 title:149", "title:199.119.201.149", Query.Type.ALL);
}
@Test
- public void testNoGrammar1() {
+ void testNoGrammar1() {
tester.assertParsed("WEAKAND(100) foobar", "foobar", Query.Type.TOKENIZE);
}
@Test
- public void testNoGrammar2() {
+ void testNoGrammar2() {
tester.assertParsed("WEAKAND(100) foobar", "-foobar", Query.Type.TOKENIZE);
}
@Test
- public void testNoGrammar3() {
+ void testNoGrammar3() {
tester.assertParsed("WEAKAND(100) foo bar", "foo -bar", Query.Type.TOKENIZE);
}
@Test
- public void testNoGrammar4() {
+ void testNoGrammar4() {
tester.assertParsed("WEAKAND(100) foo bar baz one two 37", "foo -(bar baz \"one two\" 37)", Query.Type.TOKENIZE);
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/parser/test/ParsingTester.java b/container-search/src/test/java/com/yahoo/prelude/query/parser/test/ParsingTester.java
index 42bc1c22529..ab314c4c1e7 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/parser/test/ParsingTester.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/parser/test/ParsingTester.java
@@ -23,9 +23,7 @@ import com.yahoo.search.query.parser.ParserFactory;
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.*;
/**
* A utility for writing parser tests
@@ -119,10 +117,10 @@ public class ParsingTester {
Language language, Linguistics linguistics) {
Item root = parseQuery(toParse, filter, language, mode, linguistics);
if (parsed == null) {
- assertTrue("root should be null, but was " + root, root == null);
+ assertNull(root);
} else {
- assertNotNull("Got null from parsing " + toParse, root);
- assertEquals("Parse of '" + toParse + "'", parsed, root.toString());
+ assertNotNull(root, "Got null from parsing " + toParse);
+ assertEquals(parsed, root.toString(), "Parse of '" + toParse + "'");
}
return root;
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/parser/test/SubstringTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/parser/test/SubstringTestCase.java
index e7d938e6bd8..129563d1456 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/parser/test/SubstringTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/parser/test/SubstringTestCase.java
@@ -1,9 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.query.parser.test;
-import org.junit.Test;
-import static org.junit.Assert.assertEquals;
-
+import org.junit.jupiter.api.Test;
import com.yahoo.prelude.query.CompositeItem;
import com.yahoo.prelude.query.WordItem;
import com.yahoo.search.Query;
@@ -11,6 +9,8 @@ import com.yahoo.search.Query;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
/**
* Check Substring in conjunction with query tokenization and parsing behaves properly.
*
@@ -19,15 +19,15 @@ import java.net.URLEncoder;
public class SubstringTestCase {
@Test
- public final void testTokenLengthAndLowercasing() {
+ final void testTokenLengthAndLowercasing() {
Query q = new Query("/?query=\u0130");
- WordItem root = (WordItem) ((CompositeItem)q.getModel().getQueryTree().getRoot()).getItem(0);
+ WordItem root = (WordItem) ((CompositeItem) q.getModel().getQueryTree().getRoot()).getItem(0);
assertEquals("\u0130", root.getRawWord());
}
@Test
- public final void testBug5968479() {
+ final void testBug5968479() {
String first = "\u0130\u015EBANKASI";
String second = "GAZ\u0130EM\u0130R";
Query q = new Query("/?query=" + enc(first) + "%20" + enc(second));
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/parser/test/TokenizerTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/parser/test/TokenizerTestCase.java
index 5b660f78429..1ff5574ec03 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/parser/test/TokenizerTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/parser/test/TokenizerTestCase.java
@@ -10,7 +10,7 @@ import com.yahoo.language.process.SpecialTokenRegistry;
import com.yahoo.language.process.SpecialTokens;
import com.yahoo.prelude.query.parser.Token;
import com.yahoo.prelude.query.parser.Tokenizer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Collections;
@@ -29,9 +29,7 @@ import static com.yahoo.prelude.query.parser.Token.Kind.SPACE;
import static com.yahoo.prelude.query.parser.Token.Kind.STAR;
import static com.yahoo.prelude.query.parser.Token.Kind.UNDERSCORE;
import static com.yahoo.prelude.query.parser.Token.Kind.WORD;
-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 the tokenizer
@@ -41,7 +39,7 @@ import static org.junit.Assert.assertTrue;
public class TokenizerTestCase {
@Test
- public void testPlainTokenization() {
+ void testPlainTokenization() {
Tokenizer tokenizer = new Tokenizer(new SimpleLinguistics());
tokenizer.setSpecialTokens(createSpecialTokens().getSpecialTokens("default"));
@@ -76,14 +74,14 @@ public class TokenizerTestCase {
}
@Test
- public void testOutsideBMPCodepoints() {
+ void testOutsideBMPCodepoints() {
Tokenizer tokenizer = new Tokenizer(new SimpleLinguistics());
List<?> tokens = tokenizer.tokenize("\ud841\udd47");
assertEquals(new Token(WORD, "\ud841\udd47"), tokens.get(0));
}
@Test
- public void testOneSpecialToken() {
+ void testOneSpecialToken() {
Tokenizer tokenizer = new Tokenizer(new SimpleLinguistics());
tokenizer.setSpecialTokens(createSpecialTokens().getSpecialTokens("default"));
@@ -93,7 +91,7 @@ public class TokenizerTestCase {
}
@Test
- public void testSpecialTokenCombination() {
+ void testSpecialTokenCombination() {
Tokenizer tokenizer = new Tokenizer(new SimpleLinguistics());
tokenizer.setSpecialTokens(createSpecialTokens().getSpecialTokens("default"));
@@ -121,7 +119,7 @@ public class TokenizerTestCase {
* separated by space, as special token recognition happens before tokenization
*/
@Test
- public void testSpecialTokenCJK() {
+ void testSpecialTokenCJK() {
Tokenizer tokenizer = new Tokenizer(new SimpleLinguistics());
tokenizer.setSubstringSpecialTokens(true);
tokenizer.setSpecialTokens(createSpecialTokens().getSpecialTokens("replacing"));
@@ -146,7 +144,7 @@ public class TokenizerTestCase {
}
@Test
- public void testSpecialTokenCaseInsensitive() {
+ void testSpecialTokenCaseInsensitive() {
Tokenizer tokenizer = new Tokenizer(new SimpleLinguistics());
tokenizer.setSpecialTokens(createSpecialTokens().getSpecialTokens("default"));
@@ -162,7 +160,7 @@ public class TokenizerTestCase {
}
@Test
- public void testSpecialTokenNonMatch() {
+ void testSpecialTokenNonMatch() {
Tokenizer tokenizer = new Tokenizer(new SimpleLinguistics());
tokenizer.setSpecialTokens(createSpecialTokens().getSpecialTokens("default"));
@@ -187,7 +185,7 @@ public class TokenizerTestCase {
}
@Test
- public void testSpecialTokenConfigurationDefault() {
+ void testSpecialTokenConfigurationDefault() {
Tokenizer tokenizer = new Tokenizer(new SimpleLinguistics());
tokenizer.setSpecialTokens(createSpecialTokens().getSpecialTokens("default"));
@@ -212,7 +210,7 @@ public class TokenizerTestCase {
}
@Test
- public void testSpecialTokenConfigurationOther() {
+ void testSpecialTokenConfigurationOther() {
Tokenizer tokenizer = new Tokenizer(new SimpleLinguistics());
tokenizer.setSpecialTokens(createSpecialTokens().getSpecialTokens("other"));
@@ -247,7 +245,7 @@ public class TokenizerTestCase {
}
@Test
- public void testTokenReplacing() {
+ void testTokenReplacing() {
Tokenizer tokenizer = new Tokenizer(new SimpleLinguistics());
tokenizer.setSpecialTokens(createSpecialTokens().getSpecialTokens("replacing"));
@@ -273,7 +271,7 @@ public class TokenizerTestCase {
}
@Test
- public void testExactMatchTokenization() {
+ void testExactMatchTokenization() {
SearchDefinition sd = new SearchDefinition("testsd");
Index index1 = new Index("testexact1");
@@ -286,8 +284,8 @@ public class TokenizerTestCase {
IndexFacts facts = new IndexFacts(new IndexModel(sd));
IndexFacts.Session session = facts.newSession(Collections.emptySet(), Collections.emptySet());
- Tokenizer tokenizer=new Tokenizer(new SimpleLinguistics());
- List<?> tokens=tokenizer.tokenize("normal a:b (normal testexact1:/,%#%&+-+ ) testexact2:ho_/&%&/()/aa*::*& b:c", "default", session);
+ Tokenizer tokenizer = new Tokenizer(new SimpleLinguistics());
+ List<?> tokens = tokenizer.tokenize("normal a:b (normal testexact1:/,%#%&+-+ ) testexact2:ho_/&%&/()/aa*::*& b:c", "default", session);
// tokenizer.print();
assertEquals(new Token(WORD, "normal"), tokens.get(0));
assertEquals(new Token(SPACE, " "), tokens.get(1));
@@ -317,7 +315,7 @@ public class TokenizerTestCase {
}
@Test
- public void testExactMatchTokenizationTerminatorTerminatesQuery() {
+ void testExactMatchTokenizationTerminatorTerminatesQuery() {
SearchDefinition sd = new SearchDefinition("testsd");
Index index1 = new Index("testexact1");
@@ -354,7 +352,7 @@ public class TokenizerTestCase {
}
@Test
- public void testExactMatchTokenizationWithTerminatorTerminatedByEndOfString() {
+ void testExactMatchTokenizationWithTerminatorTerminatedByEndOfString() {
SearchDefinition sd = new SearchDefinition("testsd");
Index index1 = new Index("testexact1");
@@ -391,7 +389,7 @@ public class TokenizerTestCase {
}
@Test
- public void testExactMatchTokenizationEndsByColon() {
+ void testExactMatchTokenizationEndsByColon() {
SearchDefinition sd = new SearchDefinition("testsd");
Index index1 = new Index("testexact1");
@@ -429,7 +427,7 @@ public class TokenizerTestCase {
}
@Test
- public void testExactMatchHeuristics() {
+ void testExactMatchHeuristics() {
SearchDefinition sd = new SearchDefinition("testsd");
Index index1 = new Index("testexact1");
@@ -542,7 +540,7 @@ public class TokenizerTestCase {
assertEquals(new Token(WORD, "testexact1"), tokens.get(0));
assertEquals(new Token(COLON, ":"), tokens.get(1));
assertEquals(new Token(STAR, "*"), tokens.get(2));
- assertEquals(new Token(WORD, "foobar*!100"),tokens.get(3));
+ assertEquals(new Token(WORD, "foobar*!100"), tokens.get(3));
assertEquals(new Token(EXCLAMATION, "!"), tokens.get(4));
tokens = tokenizer.tokenize("testexact1:foo(bar)", facts);
@@ -582,7 +580,7 @@ public class TokenizerTestCase {
tokens = tokenizer.tokenize("testexact1:\"news search\" testexact2:resolved", facts);
assertEquals(new Token(WORD, "testexact1"), tokens.get(0));
assertEquals(new Token(COLON, ":"), tokens.get(1));
- assertEquals(new Token(WORD, "news search"),tokens.get(2));
+ assertEquals(new Token(WORD, "news search"), tokens.get(2));
assertEquals(new Token(SPACE, " "), tokens.get(3));
assertEquals(new Token(WORD, "testexact2"), tokens.get(4));
assertEquals(new Token(COLON, ":"), tokens.get(5));
@@ -592,7 +590,7 @@ public class TokenizerTestCase {
assertEquals(new Token(LBRACE, "("), tokens.get(0));
assertEquals(new Token(WORD, "testexact1"), tokens.get(1));
assertEquals(new Token(COLON, ":"), tokens.get(2));
- assertEquals(new Token(WORD, "news search"),tokens.get(3));
+ assertEquals(new Token(WORD, "news search"), tokens.get(3));
assertEquals(new Token(SPACE, " "), tokens.get(4));
assertEquals(new Token(WORD, "testexact1"), tokens.get(5));
assertEquals(new Token(COLON, ":"), tokens.get(6));
@@ -614,7 +612,7 @@ public class TokenizerTestCase {
tokens = tokenizer.tokenize("testexact1:\"news search\"!200", facts);
assertEquals(new Token(WORD, "testexact1"), tokens.get(0));
assertEquals(new Token(COLON, ":"), tokens.get(1));
- assertEquals(new Token(WORD, "news search"),tokens.get(2));
+ assertEquals(new Token(WORD, "news search"), tokens.get(2));
assertEquals(new Token(EXCLAMATION, "!"), tokens.get(3));
assertEquals(new Token(NUMBER, "200"), tokens.get(4));
@@ -705,7 +703,7 @@ public class TokenizerTestCase {
}
@Test
- public void testSingleQuoteAsWordCharacter() {
+ void testSingleQuoteAsWordCharacter() {
Tokenizer tokenizer = new Tokenizer(new SimpleLinguistics());
tokenizer.setSpecialTokens(createSpecialTokens().getSpecialTokens("default"));
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/parser/test/WashPhrasesTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/parser/test/WashPhrasesTestCase.java
index 061089cd25f..f0b768a010f 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/parser/test/WashPhrasesTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/parser/test/WashPhrasesTestCase.java
@@ -13,10 +13,10 @@ import com.yahoo.search.query.parser.Parsable;
import com.yahoo.search.query.parser.Parser;
import com.yahoo.search.query.parser.ParserEnvironment;
import com.yahoo.search.query.parser.ParserFactory;
-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;
/**
* Tests guards against in single item phrases.
@@ -26,7 +26,7 @@ import static org.junit.Assert.assertNull;
public class WashPhrasesTestCase {
@Test
- public void testSimplePositive() {
+ void testSimplePositive() {
PhraseItem root = new PhraseItem();
root.addItem(new WordItem("abc"));
@@ -34,7 +34,7 @@ public class WashPhrasesTestCase {
}
@Test
- public void testPositive1() {
+ void testPositive1() {
AndItem root = new AndItem();
root.addItem(new WordItem("a"));
@@ -47,7 +47,7 @@ public class WashPhrasesTestCase {
}
@Test
- public void testPositive2() {
+ void testPositive2() {
AndItem root = new AndItem();
root.addItem(new WordItem("a"));
@@ -64,22 +64,22 @@ public class WashPhrasesTestCase {
}
@Test
- public void testNoTerms() {
+ void testNoTerms() {
assertNull(transformQuery("\"\""));
}
@Test
- public void testNegative1() {
+ void testNegative1() {
assertEquals("\"abc def\"", transformQuery("\"abc def\""));
}
@Test
- public void testNegative2() {
+ void testNegative2() {
assertEquals("AND a \"abc def\" b", transformQuery("a \"abc def\" b"));
}
- @Test
- public void testNegative3() {
+ @Test
+ void testNegative3() {
AndItem root = new AndItem();
root.addItem(new WordItem("a"));
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/test/DotProductItemTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/test/DotProductItemTestCase.java
index 1585e58ca5d..2bb8584cba3 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/test/DotProductItemTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/test/DotProductItemTestCase.java
@@ -1,28 +1,27 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.query.test;
-import org.junit.Test;
-
-import static org.junit.Assert.assertEquals;
-
+import org.junit.jupiter.api.Test;
import com.yahoo.prelude.query.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
/**
* @author havardpe
*/
public class DotProductItemTestCase {
@Test
- public void testDotProductItem() {
+ void testDotProductItem() {
DotProductItem item = new DotProductItem("index_name");
assertEquals("index_name", item.getIndexName());
assertEquals(Item.ItemType.DOTPRODUCT, item.getItemType());
}
@Test
- public void testDotProductClone() {
+ void testDotProductClone() {
DotProductItem dpOrig = new DotProductItem("myDP");
- dpOrig.addToken("first",11);
+ dpOrig.addToken("first", 11);
dpOrig.getTokens();
DotProductItem dpClone = (DotProductItem) dpOrig.clone();
dpClone.addToken("second", 22);
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/test/IntItemTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/test/IntItemTestCase.java
index 28cf5008417..3e1abddbdf4 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/test/IntItemTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/test/IntItemTestCase.java
@@ -5,9 +5,9 @@ import com.yahoo.prelude.query.AndItem;
import com.yahoo.prelude.query.IntItem;
import com.yahoo.prelude.query.WeakAndItem;
import com.yahoo.search.Query;
-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 bratseth
@@ -15,7 +15,7 @@ import static org.junit.Assert.assertEquals;
public class IntItemTestCase {
@Test
- public void testEquals() {
+ void testEquals() {
Query q1 = new Query("/?query=123%20456%20789");
Query q2 = new Query("/?query=123%20456");
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/test/ItemEncodingTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/test/ItemEncodingTestCase.java
index eb880bab826..c43d7e3b9d5 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/test/ItemEncodingTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/test/ItemEncodingTestCase.java
@@ -10,11 +10,11 @@ import com.yahoo.prelude.query.PureWeightedInteger;
import com.yahoo.prelude.query.PureWeightedString;
import com.yahoo.prelude.query.WeakAndItem;
import com.yahoo.prelude.query.WordItem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Item encoding tests
@@ -25,17 +25,17 @@ public class ItemEncodingTestCase {
private void assertType(ByteBuffer buffer, int etype, int features) {
byte type = buffer.get();
- assertEquals("Code", etype, type & 0x1f);
- assertEquals("Features", features, (type & 0xe0) >> 5);
+ assertEquals(etype, type & 0x1f, "Code");
+ assertEquals(features, (type & 0xe0) >> 5, "Features");
}
private void assertWeight(ByteBuffer buffer, int weight) {
int w = (weight > (1 << 5)) ? buffer.getShort() & 0x3fff: buffer.get();
- assertEquals("Weight", weight, w);
+ assertEquals(weight, w, "Weight");
}
@Test
- public void testWordItemEncoding() {
+ void testWordItemEncoding() {
WordItem word = new WordItem("test");
word.setWeight(150);
@@ -44,14 +44,14 @@ public class ItemEncodingTestCase {
buffer.flip();
- assertEquals("Serialization count", 1, count);
+ assertEquals(1, count, "Serialization count");
assertType(buffer, 4, 1);
assertWeight(buffer, 150);
- assertEquals("Index length", 0, buffer.get());
- assertEquals("Word length", 4, buffer.get());
- assertEquals("Word length", 4, buffer.remaining());
+ assertEquals(0, buffer.get(), "Index length");
+ assertEquals(4, buffer.get(), "Word length");
+ assertEquals(4, buffer.remaining(), "Word length");
assertEquals('t', buffer.get());
assertEquals('e', buffer.get());
assertEquals('s', buffer.get());
@@ -59,20 +59,20 @@ public class ItemEncodingTestCase {
}
@Test
- public void testStartHostMarkerEncoding() {
+ void testStartHostMarkerEncoding() {
WordItem word = MarkerWordItem.createStartOfHost();
ByteBuffer buffer = ByteBuffer.allocate(128);
int count = word.encode(buffer);
buffer.flip();
- assertEquals("Serialization count", 1, count);
+ assertEquals(1, count, "Serialization count");
assertType(buffer, 4, 0);
- assertEquals("Index length", 0, buffer.get());
- assertEquals("Word length", 9, buffer.get());
- assertEquals("Word length", 9, buffer.remaining());
+ assertEquals(0, buffer.get(), "Index length");
+ assertEquals(9, buffer.get(), "Word length");
+ assertEquals(9, buffer.remaining(), "Word length");
assertEquals('S', buffer.get());
assertEquals('t', buffer.get());
assertEquals('A', buffer.get());
@@ -85,7 +85,7 @@ public class ItemEncodingTestCase {
}
@Test
- public void testEndHostMarkerEncoding() {
+ void testEndHostMarkerEncoding() {
WordItem word = MarkerWordItem.createEndOfHost();
ByteBuffer buffer = ByteBuffer.allocate(128);
@@ -93,13 +93,13 @@ public class ItemEncodingTestCase {
buffer.flip();
- assertEquals("Serialization count", 1, count);
+ assertEquals(1, count, "Serialization count");
assertType(buffer, 4, 0);
- assertEquals("Index length", 0, buffer.get());
- assertEquals("Word length", 7, buffer.get());
- assertEquals("Word length", 7, buffer.remaining());
+ assertEquals(0, buffer.get(), "Index length");
+ assertEquals(7, buffer.get(), "Word length");
+ assertEquals(7, buffer.remaining(), "Word length");
assertEquals('E', buffer.get());
assertEquals('n', buffer.get());
assertEquals('D', buffer.get());
@@ -110,7 +110,7 @@ public class ItemEncodingTestCase {
}
@Test
- public void testFilterWordItemEncoding() {
+ void testFilterWordItemEncoding() {
WordItem word = new WordItem("test");
word.setFilter(true);
@@ -119,14 +119,14 @@ public class ItemEncodingTestCase {
buffer.flip();
- assertEquals("Serialization count", 1, count);
+ assertEquals(1, count, "Serialization count");
assertType(buffer, 4, 4);
assertEquals(0x08, buffer.get());
- assertEquals("Index length", 0, buffer.get());
- assertEquals("Word length", 4, buffer.get());
- assertEquals("Word length", 4, buffer.remaining());
+ assertEquals(0, buffer.get(), "Index length");
+ assertEquals(4, buffer.get(), "Word length");
+ assertEquals(4, buffer.remaining(), "Word length");
assertEquals('t', buffer.get());
assertEquals('e', buffer.get());
assertEquals('s', buffer.get());
@@ -134,7 +134,7 @@ public class ItemEncodingTestCase {
}
@Test
- public void testNoRankedNoPositionDataWordItemEncoding() {
+ void testNoRankedNoPositionDataWordItemEncoding() {
WordItem word = new WordItem("test");
word.setRanked(false);
word.setPositionData(false);
@@ -144,14 +144,14 @@ public class ItemEncodingTestCase {
buffer.flip();
- assertEquals("Serialization count", 1, count);
+ assertEquals(1, count, "Serialization count");
assertType(buffer, 4, 4);
assertEquals(0x05, buffer.get());
- assertEquals("Index length", 0, buffer.get());
- assertEquals("Word length", 4, buffer.get());
- assertEquals("Word length", 4, buffer.remaining());
+ assertEquals(0, buffer.get(), "Index length");
+ assertEquals(4, buffer.get(), "Word length");
+ assertEquals(4, buffer.remaining(), "Word length");
assertEquals('t', buffer.get());
assertEquals('e', buffer.get());
assertEquals('s', buffer.get());
@@ -159,10 +159,10 @@ public class ItemEncodingTestCase {
}
@Test
- public void testAndItemEncoding() {
+ void testAndItemEncoding() {
WordItem a = new WordItem("a");
WordItem b = new WordItem("b");
- AndItem and=new AndItem();
+ AndItem and = new AndItem();
and.addItem(a);
and.addItem(b);
@@ -171,21 +171,21 @@ public class ItemEncodingTestCase {
buffer.flip();
- assertEquals("Serialization count", 3, count);
+ assertEquals(3, count, "Serialization count");
assertType(buffer, 1, 0);
- assertEquals("And arity", 2, buffer.get());
+ assertEquals(2, buffer.get(), "And arity");
- assertWord(buffer,"a");
- assertWord(buffer,"b");
+ assertWord(buffer, "a");
+ assertWord(buffer, "b");
}
@Test
- public void testNearItemEncoding() {
+ void testNearItemEncoding() {
WordItem a = new WordItem("a");
WordItem b = new WordItem("b");
- NearItem near=new NearItem(7);
+ NearItem near = new NearItem(7);
near.addItem(a);
near.addItem(b);
@@ -194,22 +194,22 @@ public class ItemEncodingTestCase {
buffer.flip();
- assertEquals("Serialization count", 3, count);
+ assertEquals(3, count, "Serialization count");
assertType(buffer, 11, 0);
- assertEquals("Near arity", 2, buffer.get());
- assertEquals("Limit", 7, buffer.get());
+ assertEquals(2, buffer.get(), "Near arity");
+ assertEquals(7, buffer.get(), "Limit");
- assertWord(buffer,"a");
- assertWord(buffer,"b");
+ assertWord(buffer, "a");
+ assertWord(buffer, "b");
}
@Test
- public void testONearItemEncoding() {
+ void testONearItemEncoding() {
WordItem a = new WordItem("a");
WordItem b = new WordItem("b");
- NearItem onear=new ONearItem(7);
+ NearItem onear = new ONearItem(7);
onear.addItem(a);
onear.addItem(b);
@@ -218,18 +218,18 @@ public class ItemEncodingTestCase {
buffer.flip();
- assertEquals("Serialization count", 3, count);
+ assertEquals(3, count, "Serialization count");
assertType(buffer, 12, 0);
- assertEquals("Near arity", 2, buffer.get());
- assertEquals("Limit", 7, buffer.get());
+ assertEquals(2, buffer.get(), "Near arity");
+ assertEquals(7, buffer.get(), "Limit");
- assertWord(buffer,"a");
- assertWord(buffer,"b");
+ assertWord(buffer, "a");
+ assertWord(buffer, "b");
}
@Test
- public void testEquivItemEncoding() {
+ void testEquivItemEncoding() {
WordItem a = new WordItem("a");
WordItem b = new WordItem("b");
EquivItem equiv = new EquivItem();
@@ -241,17 +241,17 @@ public class ItemEncodingTestCase {
buffer.flip();
- assertEquals("Serialization count", 3, count);
+ assertEquals(3, count, "Serialization count");
assertType(buffer, 14, 0);
- assertEquals("Equiv arity", 2, buffer.get());
+ assertEquals(2, buffer.get(), "Equiv arity");
assertWord(buffer, "a");
assertWord(buffer, "b");
}
@Test
- public void testWandItemEncoding() {
+ void testWandItemEncoding() {
WordItem a = new WordItem("a");
WordItem b = new WordItem("b");
WeakAndItem wand = new WeakAndItem();
@@ -263,11 +263,11 @@ public class ItemEncodingTestCase {
buffer.flip();
- assertEquals("Serialization count", 3, count);
+ assertEquals(3, count, "Serialization count");
assertType(buffer, 16, 0);
- assertEquals("WeakAnd arity", 2, buffer.get());
- assertEquals("WeakAnd N", 100, buffer.getShort() & 0x3fff);
+ assertEquals(2, buffer.get(), "WeakAnd arity");
+ assertEquals(100, buffer.getShort() & 0x3fff, "WeakAnd N");
assertEquals(0, buffer.get());
assertWord(buffer, "a");
@@ -275,65 +275,66 @@ public class ItemEncodingTestCase {
}
@Test
- public void testPureWeightedStringEncoding() {
+ void testPureWeightedStringEncoding() {
PureWeightedString a = new PureWeightedString("a");
ByteBuffer buffer = ByteBuffer.allocate(128);
int count = a.encode(buffer);
buffer.flip();
- assertEquals("Serialization size", 3, buffer.remaining());
- assertEquals("Serialization count", 1, count);
+ assertEquals(3, buffer.remaining(), "Serialization size");
+ assertEquals(1, count, "Serialization count");
assertType(buffer, 19, 0);
assertString(buffer, a.getString());
}
@Test
- public void testPureWeightedStringEncodingWithNonDefaultWeight() {
+ void testPureWeightedStringEncodingWithNonDefaultWeight() {
PureWeightedString a = new PureWeightedString("a", 7);
ByteBuffer buffer = ByteBuffer.allocate(128);
int count = a.encode(buffer);
buffer.flip();
- assertEquals("Serialization size", 4, buffer.remaining());
- assertEquals("Serialization count", 1, count);
+ assertEquals(4, buffer.remaining(), "Serialization size");
+ assertEquals(1, count, "Serialization count");
assertType(buffer, 19, 1);
assertWeight(buffer, 7);
assertString(buffer, a.getString());
}
@Test
- public void testPureWeightedIntegerEncoding() {
+ void testPureWeightedIntegerEncoding() {
PureWeightedInteger a = new PureWeightedInteger(23432568763534865l);
ByteBuffer buffer = ByteBuffer.allocate(128);
int count = a.encode(buffer);
buffer.flip();
- assertEquals("Serialization size", 9, buffer.remaining());
- assertEquals("Serialization count", 1, count);
+ assertEquals(9, buffer.remaining(), "Serialization size");
+ assertEquals(1, count, "Serialization count");
assertType(buffer, 20, 0);
- assertEquals("Value", a.getValue(), buffer.getLong());
+ assertEquals(a.getValue(), buffer.getLong(), "Value");
}
@Test
- public void testPureWeightedLongEncodingWithNonDefaultWeight() {
+ void testPureWeightedLongEncodingWithNonDefaultWeight() {
PureWeightedInteger a = new PureWeightedInteger(23432568763534865l, 7);
ByteBuffer buffer = ByteBuffer.allocate(128);
int count = a.encode(buffer);
buffer.flip();
- assertEquals("Serialization size", 10, buffer.remaining());
- assertEquals("Serialization count", 1, count);
+ assertEquals(10, buffer.remaining(), "Serialization size");
+ assertEquals(1, count, "Serialization count");
assertType(buffer, 20, 1);
assertWeight(buffer, 7);
- assertEquals("Value", a.getValue(), buffer.getLong());;
+ assertEquals(a.getValue(), buffer.getLong(), "Value");
+ ;
}
private void assertString(ByteBuffer buffer, String word) {
- assertEquals("Word length", word.length(), buffer.get());
+ assertEquals(word.length(), buffer.get(), "Word length");
for (int i=0; i<word.length(); i++) {
- assertEquals("Character at " + i,word.charAt(i), buffer.get());
+ assertEquals(word.charAt(i), buffer.get(), "Character at " + i);
}
}
private void assertWord(ByteBuffer buffer,String word) {
assertType(buffer, 4, 0);
- assertEquals("Index length", 0, buffer.get());
+ assertEquals(0, buffer.get(), "Index length");
assertString(buffer, word);
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/test/PhraseItemTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/test/PhraseItemTestCase.java
index bd0bfd3f29a..1e4418f1b73 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/test/PhraseItemTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/test/PhraseItemTestCase.java
@@ -4,9 +4,9 @@ package com.yahoo.prelude.query.test;
import com.yahoo.prelude.query.PhraseItem;
import com.yahoo.prelude.query.PhraseSegmentItem;
import com.yahoo.prelude.query.WordItem;
-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 methods changing phrase items.
@@ -16,7 +16,7 @@ import static org.junit.Assert.assertEquals;
public class PhraseItemTestCase {
@Test
- public void testAddItem() {
+ void testAddItem() {
PhraseItem p = new PhraseItem();
PhraseSegmentItem pp = new PhraseSegmentItem("", false, false);
PhraseItem ppp = new PhraseItem();
@@ -32,7 +32,7 @@ public class PhraseItemTestCase {
}
@Test
- public void testAddItemWithIndex() {
+ void testAddItemWithIndex() {
PhraseItem p = new PhraseItem();
PhraseSegmentItem pp = new PhraseSegmentItem("", false, false);
PhraseItem ppp = new PhraseItem();
@@ -48,7 +48,7 @@ public class PhraseItemTestCase {
}
@Test
- public void testSetItem() {
+ void testSetItem() {
PhraseItem backup = new PhraseItem();
PhraseSegmentItem segment = new PhraseSegmentItem("", false, false);
PhraseItem innerPhrase = new PhraseItem();
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/test/PredicateQueryItemTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/test/PredicateQueryItemTestCase.java
index 1fe0ded8d6b..a27a11b8f15 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/test/PredicateQueryItemTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/test/PredicateQueryItemTestCase.java
@@ -3,14 +3,14 @@ package com.yahoo.prelude.query.test;
import com.yahoo.prelude.query.Item;
import com.yahoo.prelude.query.PredicateQueryItem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Iterator;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Magnar Nedland
@@ -18,7 +18,7 @@ import static org.junit.Assert.assertEquals;
public class PredicateQueryItemTestCase {
@Test
- public void requireThatItemConstantsAreSet() {
+ void requireThatItemConstantsAreSet() {
PredicateQueryItem item = new PredicateQueryItem();
assertEquals(Item.ItemType.PREDICATE_QUERY, item.getItemType());
assertEquals("PREDICATE_QUERY_ITEM", item.getName());
@@ -29,7 +29,7 @@ public class PredicateQueryItemTestCase {
}
@Test
- public void requireThatFeaturesCanBeAdded() {
+ void requireThatFeaturesCanBeAdded() {
PredicateQueryItem item = new PredicateQueryItem();
assertEquals(0, item.getFeatures().size());
item.addFeature("foo", "bar");
@@ -45,7 +45,7 @@ public class PredicateQueryItemTestCase {
}
@Test
- public void requireThatRangeFeaturesCanBeAdded() {
+ void requireThatRangeFeaturesCanBeAdded() {
PredicateQueryItem item = new PredicateQueryItem();
assertEquals(0, item.getRangeFeatures().size());
item.addRangeFeature("foo", 23);
@@ -61,7 +61,7 @@ public class PredicateQueryItemTestCase {
}
@Test
- public void requireThatToStringWorks() {
+ void requireThatToStringWorks() {
PredicateQueryItem item = new PredicateQueryItem();
assertEquals("PREDICATE_QUERY_ITEM ", item.toString());
item.addFeature("foo", "bar");
@@ -73,7 +73,7 @@ public class PredicateQueryItemTestCase {
}
@Test
- public void requireThatPredicateQueryItemCanBeEncoded() {
+ void requireThatPredicateQueryItemCanBeEncoded() {
PredicateQueryItem item = new PredicateQueryItem();
assertEquals("PREDICATE_QUERY_ITEM ", item.toString());
item.addFeature("foo", "bar");
@@ -84,12 +84,12 @@ public class PredicateQueryItemTestCase {
byte[] actual = new byte[buffer.remaining()];
buffer.get(actual);
assertArrayEquals(new byte[]{
- 23, // PREDICATE_QUERY code 23
- 9, 'p', 'r', 'e', 'd', 'i', 'c', 'a', 't', 'e',
- 2, // 2 features
- 3, 'f', 'o', 'o', 3, 'b', 'a', 'r', -1, -1, -1, -1, -1, -1, -1, -1, // key, value, subquery
- 3, 'f', 'o', 'o', 3, 'b', 'a', 'z', 0, 0, 0, 0, 0, 0, -1, -1, // key, value, subquery
- 0}, // no range features
+ 23, // PREDICATE_QUERY code 23
+ 9, 'p', 'r', 'e', 'd', 'i', 'c', 'a', 't', 'e',
+ 2, // 2 features
+ 3, 'f', 'o', 'o', 3, 'b', 'a', 'r', -1, -1, -1, -1, -1, -1, -1, -1, // key, value, subquery
+ 3, 'f', 'o', 'o', 3, 'b', 'a', 'z', 0, 0, 0, 0, 0, 0, -1, -1, // key, value, subquery
+ 0}, // no range features
actual);
item.addRangeFeature("foo", 23);
@@ -100,19 +100,19 @@ public class PredicateQueryItemTestCase {
actual = new byte[buffer.remaining()];
buffer.get(actual);
assertArrayEquals(new byte[]{
- 23, // PREDICATE_QUERY code 23
- 9, 'p', 'r', 'e', 'd', 'i', 'c', 'a', 't', 'e',
- 2, // 2 features
- 3, 'f', 'o', 'o', 3, 'b', 'a', 'r', -1, -1, -1, -1, -1, -1, -1, -1, // key, value, subquery
- 3, 'f', 'o', 'o', 3, 'b', 'a', 'z', 0, 0, 0, 0, 0, 0, -1, -1, // key, value, subquery
- 2, // 2 range features
- 3, 'f', 'o', 'o', 0, 0, 0, 0, 0, 0, 0, 23, -1, -1, -1, -1, -1, -1, -1, -1, // key, value, subquery
- 3, 'f', 'o', 'o', 0, 0, 0, 0, 0, 0, 0, 34, -1, -1, -1, -1, -1, -1, -1, -2}, // key, value, subquery
+ 23, // PREDICATE_QUERY code 23
+ 9, 'p', 'r', 'e', 'd', 'i', 'c', 'a', 't', 'e',
+ 2, // 2 features
+ 3, 'f', 'o', 'o', 3, 'b', 'a', 'r', -1, -1, -1, -1, -1, -1, -1, -1, // key, value, subquery
+ 3, 'f', 'o', 'o', 3, 'b', 'a', 'z', 0, 0, 0, 0, 0, 0, -1, -1, // key, value, subquery
+ 2, // 2 range features
+ 3, 'f', 'o', 'o', 0, 0, 0, 0, 0, 0, 0, 23, -1, -1, -1, -1, -1, -1, -1, -1, // key, value, subquery
+ 3, 'f', 'o', 'o', 0, 0, 0, 0, 0, 0, 0, 34, -1, -1, -1, -1, -1, -1, -1, -2}, // key, value, subquery
actual);
}
@Test
- public void requireThatPredicateQueryItemWithManyAttributesCanBeEncoded() {
+ void requireThatPredicateQueryItemWithManyAttributesCanBeEncoded() {
PredicateQueryItem item = new PredicateQueryItem();
assertEquals("PREDICATE_QUERY_ITEM ", item.toString());
for (int i = 0; i < 200; ++i) {
@@ -126,11 +126,11 @@ public class PredicateQueryItemTestCase {
byte [] expectedPrefix = new byte[]{
23, // PREDICATE_QUERY code 23
9, 'p', 'r', 'e', 'd', 'i', 'c', 'a', 't', 'e',
- (byte)0x80, (byte)0xc8, // 200 features (0x80c8 => 0xc8 == 200)
+ (byte) 0x80, (byte) 0xc8, // 200 features (0x80c8 => 0xc8 == 200)
3, 'f', 'o', 'o', 3, 'b', 'a', 'r', -1, -1, -1, -1, -1, -1, -1, -1, // key, value, subquery
3, 'f', 'o', 'o', 3, 'b', 'a', 'r', -1, -1, -1, -1, -1, -1, -1, -1, // key, value, subquery
3, 'f', 'o', 'o', 3, 'b', 'a', 'r', -1, -1, -1, -1, -1, -1, -1, -1, // key, value, subquery
- }; // ...
+ }; // ...
assertArrayEquals(expectedPrefix, Arrays.copyOfRange(actual, 0, expectedPrefix.length));
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/test/QueryCanonicalizerTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/test/QueryCanonicalizerTestCase.java
index cd8691d9db0..81aa28a5326 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/test/QueryCanonicalizerTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/test/QueryCanonicalizerTestCase.java
@@ -4,12 +4,9 @@ package com.yahoo.prelude.query.test;
import com.yahoo.prelude.query.*;
import com.yahoo.search.Query;
import com.yahoo.search.query.QueryTree;
-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.Assert.assertFalse;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -17,7 +14,7 @@ import static org.junit.Assert.assertFalse;
public class QueryCanonicalizerTestCase {
@Test
- public void testSingleLevelSingleItemComposite() {
+ void testSingleLevelSingleItemComposite() {
CompositeItem root = new AndItem();
root.addItem(new WordItem("word"));
@@ -25,7 +22,7 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testSingleLevelSingleItemNonReducibleComposite() {
+ void testSingleLevelSingleItemNonReducibleComposite() {
CompositeItem root = new WeakAndItem();
root.addItem(new WordItem("word"));
@@ -33,7 +30,7 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testMultilevelSingleItemComposite() {
+ void testMultilevelSingleItemComposite() {
CompositeItem root = new AndItem();
CompositeItem and1 = new AndItem();
CompositeItem and2 = new AndItem();
@@ -45,7 +42,7 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testMultilevelComposite() {
+ void testMultilevelComposite() {
// AND (RANK (AND a b c)) WAND(25,0.0,1.0)
AndItem and = new AndItem();
RankItem rank = new RankItem();
@@ -62,7 +59,7 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testMultilevelEmptyComposite() {
+ void testMultilevelEmptyComposite() {
CompositeItem root = new AndItem();
CompositeItem and1 = new AndItem();
CompositeItem and2 = new AndItem();
@@ -73,7 +70,7 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testMultilevelMultiBranchEmptyComposite() {
+ void testMultilevelMultiBranchEmptyComposite() {
CompositeItem root = new AndItem();
CompositeItem and1 = new AndItem();
CompositeItem and21 = new AndItem();
@@ -90,7 +87,7 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testMultilevelMultiBranchSingleItemComposite() {
+ void testMultilevelMultiBranchSingleItemComposite() {
CompositeItem root = new AndItem();
CompositeItem and1 = new AndItem();
CompositeItem and21 = new AndItem();
@@ -108,7 +105,7 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testMultilevelWeakAndCollapsing() {
+ void testMultilevelWeakAndCollapsing() {
CompositeItem root = new WeakAndItem();
CompositeItem l1 = new WeakAndItem();
CompositeItem l2 = new WeakAndItem();
@@ -132,7 +129,7 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testWeakAndCollapsingRequireSameNAndIndex() {
+ void testWeakAndCollapsingRequireSameNAndIndex() {
CompositeItem root = new WeakAndItem(10);
CompositeItem l1 = new WeakAndItem(100);
CompositeItem l2 = new WeakAndItem(100);
@@ -149,12 +146,12 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testNullRoot() {
+ void testNullRoot() {
assertCanonicalized(null, "No query", new Query());
}
@Test
- public void testNestedNull() {
+ void testNestedNull() {
CompositeItem root = new AndItem();
CompositeItem or = new AndItem();
CompositeItem and = new AndItem();
@@ -169,7 +166,7 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testNestedNullItem() {
+ void testNestedNullItem() {
CompositeItem root = new AndItem();
CompositeItem or = new AndItem();
CompositeItem and = new AndItem();
@@ -186,7 +183,7 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testNestedNullAndSingle() {
+ void testNestedNullAndSingle() {
CompositeItem root = new AndItem();
CompositeItem or = new OrItem();
@@ -199,7 +196,7 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testRemovalOfUnnecessaryComposites() {
+ void testRemovalOfUnnecessaryComposites() {
CompositeItem root = new AndItem();
CompositeItem or = new OrItem();
@@ -215,21 +212,21 @@ public class QueryCanonicalizerTestCase {
/** Multiple levels of the same AND/OR should collapse */
@Test
- public void testMultilevelCollapsing() {
+ void testMultilevelCollapsing() {
CompositeItem root = new AndItem();
CompositeItem l1 = new AndItem();
CompositeItem l2 = new AndItem();
CompositeItem l3 = new AndItem();
-
+
root.addItem(l1);
l1.addItem(new WordItem("l1i1"));
l1.addItem(l2);
-
+
l2.addItem(new WordItem("l2i1"));
l2.addItem(l3);
l2.addItem(new WordItem("l2i2"));
-
+
l3.addItem(new WordItem("l3i1"));
l3.addItem(new WordItem("l3i2"));
@@ -238,7 +235,7 @@ public class QueryCanonicalizerTestCase {
/** Multiple levels of different composites should not collapse */
@Test
- public void testMultilevelNonCollapsing() {
+ void testMultilevelNonCollapsing() {
CompositeItem root = new AndItem();
CompositeItem l1 = new AndItem();
CompositeItem l2 = new OrItem();
@@ -259,7 +256,7 @@ public class QueryCanonicalizerTestCase {
/** Multiple levels of RANK should collapse */
@Test
- public void testMultilevelRankCollapsing() {
+ void testMultilevelRankCollapsing() {
CompositeItem root = new RankItem();
CompositeItem l1 = new RankItem();
CompositeItem l2 = new RankItem();
@@ -283,7 +280,7 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testNegativeMustHaveNegatives() {
+ void testNegativeMustHaveNegatives() {
CompositeItem root = new NotItem();
root.addItem(new WordItem("positive"));
@@ -291,26 +288,26 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testNegative() {
+ void testNegative() {
NotItem root = new NotItem();
root.addNegativeItem(new WordItem("negative"));
- assertCanonicalized("-negative",null, root);
+ assertCanonicalized("-negative", null, root);
}
@Test
- public void testNegativeOnly() {
+ void testNegativeOnly() {
CompositeItem root = new AndItem();
NotItem not = new NotItem();
root.addItem(not);
root.addItem(new WordItem("word"));
not.addNegativeItem(new WordItem("negative"));
- assertCanonicalized("AND (-negative) word",null, root);
+ assertCanonicalized("AND (-negative) word", null, root);
}
@Test
- public void testCollapseFalseItemInAnd() {
+ void testCollapseFalseItemInAnd() {
CompositeItem root = new AndItem();
root.addItem(new WordItem("i1"));
root.addItem(new FalseItem());
@@ -318,7 +315,7 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testRemoveFalseItemInOr() {
+ void testRemoveFalseItemInOr() {
CompositeItem root = new OrItem();
AndItem and = new AndItem(); // this gets collapse to just FALSE, which is then removed
root.addItem(and);
@@ -329,7 +326,7 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testCollapseFalseItemInNot() {
+ void testCollapseFalseItemInNot() {
CompositeItem root = new NotItem();
root.addItem(new FalseItem()); // false ANDNOT ... is false
root.addItem(new WordItem("i1"));
@@ -337,7 +334,7 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testRemoveFalseItemInNot() {
+ void testRemoveFalseItemInNot() {
CompositeItem root = new NotItem();
root.addItem(new WordItem("i1"));
root.addItem(new FalseItem()); // ... ANDNOT false is redundant
@@ -345,7 +342,7 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testCollapseFalseItemInRank() {
+ void testCollapseFalseItemInRank() {
CompositeItem root = new RankItem();
root.addItem(new FalseItem()); // false RANK ... is false
root.addItem(new WordItem("i1"));
@@ -353,7 +350,7 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testRemoveFalseItemInRank() {
+ void testRemoveFalseItemInRank() {
CompositeItem root = new RankItem();
root.addItem(new WordItem("i1"));
root.addItem(new FalseItem()); // ... RANK false is redundant
@@ -365,13 +362,13 @@ public class QueryCanonicalizerTestCase {
* (which strictly is an implementation detail which we should rather hide).
*/
@Test
- public void testConnexityAndCloning() {
+ void testConnexityAndCloning() {
Query q = new Query("?query=a%20b");
CompositeItem root = (CompositeItem) q.getModel().getQueryTree().getRoot();
((WordItem) root.getItem(0)).setConnectivity(root.getItem(1), java.lang.Math.E);
q = q.clone();
- assertNull("Not prepared yet", q.getRanking().getProperties().get("vespa.term.1.connexity"));
+ assertNull(q.getRanking().getProperties().get("vespa.term.1.connexity"), "Not prepared yet");
q.prepare();
assertEquals("2", q.getRanking().getProperties().get("vespa.term.1.connexity").get(0));
assertEquals("2.718281828459045", q.getRanking().getProperties().get("vespa.term.1.connexity").get(1));
@@ -385,7 +382,7 @@ public class QueryCanonicalizerTestCase {
* (which strictly is an implementation detail which we should rather hide).
*/
@Test
- public void testSignificance() {
+ void testSignificance() {
Query q = new Query("?query=a%20b");
CompositeItem root = (CompositeItem) q.getModel().getQueryTree().getRoot();
((WordItem) root.getItem(0)).setSignificance(0.5);
@@ -396,7 +393,7 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testPhraseWeight() {
+ void testPhraseWeight() {
PhraseItem root = new PhraseItem();
root.setWeight(200);
root.addItem(new WordItem("a"));
@@ -404,7 +401,7 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testEquivDuplicateRemoval() {
+ void testEquivDuplicateRemoval() {
{
EquivItem root = new EquivItem();
root.addItem(new WordItem("a"));
@@ -470,7 +467,7 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void testRankDuplicateCheapification() {
+ void testRankDuplicateCheapification() {
AndItem and = new AndItem();
WordItem shoe = new WordItem("shoe", "prod");
and.addItem(shoe);
@@ -491,7 +488,7 @@ public class QueryCanonicalizerTestCase {
}
@Test
- public void queryTreeExceedsAllowedSize() {
+ void queryTreeExceedsAllowedSize() {
Query query = new Query();
QueryTree tree = query.getModel().getQueryTree();
tree.setRoot(new WordItem("A"));
@@ -513,7 +510,7 @@ public class QueryCanonicalizerTestCase {
assertEquals(expectedError, error);
if (canonicalForm == null) {
- assertNull(null, query.getModel().getQueryTree().getRoot());
+ assertNull(query.getModel().getQueryTree().getRoot());
} else {
assertEquals(canonicalForm, query.getModel().getQueryTree().getRoot().toString());
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/test/QueryLanguageTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/test/QueryLanguageTestCase.java
index a43f1a542c3..12d179b489e 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/test/QueryLanguageTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/test/QueryLanguageTestCase.java
@@ -6,9 +6,9 @@ import com.yahoo.prelude.query.NotItem;
import com.yahoo.prelude.query.PhraseItem;
import com.yahoo.prelude.query.WordItem;
import com.yahoo.search.Query;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* <p>Tests that the correct query language strings are generated for various
@@ -24,14 +24,14 @@ import static org.junit.Assert.assertEquals;
public class QueryLanguageTestCase {
@Test
- public void testWord() {
+ void testWord() {
WordItem w = new WordItem("test");
assertEquals("test", w.toString());
}
@Test
- public void testWordWithIndex() {
+ void testWordWithIndex() {
WordItem w = new WordItem("test");
w.setIndexName("test.index");
@@ -39,7 +39,7 @@ public class QueryLanguageTestCase {
}
@Test
- public void testPhrase() {
+ void testPhrase() {
PhraseItem p = new PhraseItem();
p.addItem(new WordItem("part"));
@@ -49,7 +49,7 @@ public class QueryLanguageTestCase {
}
@Test
- public void testPhraseWithIndex() {
+ void testPhraseWithIndex() {
PhraseItem p = new PhraseItem();
p.addItem(new WordItem("part"));
@@ -60,7 +60,7 @@ public class QueryLanguageTestCase {
}
@Test
- public void testNotItem() {
+ void testNotItem() {
NotItem n = new NotItem();
n.addNegativeItem(new WordItem("notthis"));
@@ -70,22 +70,22 @@ public class QueryLanguageTestCase {
}
@Test
- public void testLanguagesInQueryParameter() {
+ void testLanguagesInQueryParameter() {
// Right parameter is the parameter given in the query, as language=
// Left parameter is the language sent to linguistics
// Ancient
- assertLanguage(Language.CHINESE_SIMPLIFIED,"zh-cn");
- assertLanguage(Language.CHINESE_SIMPLIFIED,"zh-Hans");
- assertLanguage(Language.CHINESE_SIMPLIFIED,"zh-hans");
- assertLanguage(Language.CHINESE_TRADITIONAL,"zh-tw");
- assertLanguage(Language.CHINESE_TRADITIONAL,"zh-Hant");
- assertLanguage(Language.CHINESE_TRADITIONAL,"zh-hant");
- assertLanguage(Language.CHINESE_TRADITIONAL,"zh");
+ assertLanguage(Language.CHINESE_SIMPLIFIED, "zh-cn");
+ assertLanguage(Language.CHINESE_SIMPLIFIED, "zh-Hans");
+ assertLanguage(Language.CHINESE_SIMPLIFIED, "zh-hans");
+ assertLanguage(Language.CHINESE_TRADITIONAL, "zh-tw");
+ assertLanguage(Language.CHINESE_TRADITIONAL, "zh-Hant");
+ assertLanguage(Language.CHINESE_TRADITIONAL, "zh-hant");
+ assertLanguage(Language.CHINESE_TRADITIONAL, "zh");
assertLanguage(Language.ENGLISH, "en");
assertLanguage(Language.GERMAN, "de");
assertLanguage(Language.JAPANESE, "ja");
- assertLanguage(Language.fromLanguageTag("jp") ,"jp");
+ assertLanguage(Language.fromLanguageTag("jp"), "jp");
assertLanguage(Language.KOREAN, "ko");
// Since 2.0
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/test/QueryTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/test/QueryTestCase.java
index bfdc9ae1552..1abbc2d87dc 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/test/QueryTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/test/QueryTestCase.java
@@ -8,12 +8,12 @@ import com.yahoo.search.query.parser.Parsable;
import com.yahoo.search.query.parser.Parser;
import com.yahoo.search.query.parser.ParserEnvironment;
import com.yahoo.search.query.parser.ParserFactory;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Iterator;
-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 query trees
@@ -24,7 +24,7 @@ public class QueryTestCase {
/** Tests that query hash and equality is value dependent only */
@Test
- public void testQueryEquality() {
+ void testQueryEquality() {
String query = "RANK (+(AND \"baz gaz faz\" bazar) -\"foo bar foobar\") foofoo xyzzy";
String filter = "foofoo -\"foo bar foobar\" xyzzy +\"baz gaz faz\" +bazar";
@@ -37,11 +37,11 @@ public class QueryTestCase {
/** Check copy of query trees is a deep copy */
@Test
- public void testDeepCopy() {
+ void testDeepCopy() {
Item root1 = parseQuery("a and b and (c or d) and e rank f andnot g", null, Query.Type.ADVANCED);
Item root2 = root1.clone();
- assertTrue("Item.clone() should be a deep copy.",nonIdenticalTrees(root1, root2));
+ assertTrue(nonIdenticalTrees(root1, root2), "Item.clone() should be a deep copy.");
}
private static Item parseQuery(String query, String filter, Query.Type type) {
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/test/RangeItemTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/test/RangeItemTestCase.java
index 3032a7b625f..a2f5016645b 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/test/RangeItemTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/test/RangeItemTestCase.java
@@ -3,16 +3,16 @@ package com.yahoo.prelude.query.test;
import com.yahoo.prelude.query.IntItem;
import com.yahoo.prelude.query.RangeItem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class RangeItemTestCase {
@Test
- public void testRangeConstruction() {
+ void testRangeConstruction() {
verifyRange(new RangeItem(5, 7, 9, "a", true), 9, true);
verifyRange(new RangeItem(5, 7, "a", true), 0, true);
verifyRange(new RangeItem(5, 7, "a"), 0, false);
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/test/SameElementItemTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/test/SameElementItemTestCase.java
index c05d7d48f6b..198ad2b46f9 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/test/SameElementItemTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/test/SameElementItemTestCase.java
@@ -9,20 +9,18 @@ import com.yahoo.prelude.query.Substring;
import com.yahoo.prelude.query.TermItem;
import com.yahoo.prelude.query.WordAlternativesItem;
import com.yahoo.prelude.query.WordItem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
-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 SameElementItemTestCase {
@Test
- public void testAddItem() {
+ void testAddItem() {
SameElementItem s = new SameElementItem("structa");
s.addItem(new WordItem("b", "f1"));
s.addItem(new WordItem("c", "f2"));
@@ -31,18 +29,18 @@ public class SameElementItemTestCase {
}
@Test
- public void testClone() {
+ void testClone() {
SameElementItem s = new SameElementItem("structa");
s.addItem(new WordItem("b", "f1"));
s.addItem(new WordItem("c", "f2"));
s.addItem(new WordItem("d", "f3"));
assertEquals("structa:{f1:b f2:c f3:d}", s.toString());
- SameElementItem c = (SameElementItem)s.clone();
+ SameElementItem c = (SameElementItem) s.clone();
assertEquals("structa:{f1:b f2:c f3:d}", c.toString());
}
@Test
- public void requireAllChildrenHaveStructMemberNameSet() {
+ void requireAllChildrenHaveStructMemberNameSet() {
try {
SameElementItem s = new SameElementItem("structa");
s.addItem(new WordItem("b", "f1"));
@@ -55,7 +53,7 @@ public class SameElementItemTestCase {
}
@Test
- public void requireAllowCommonPrefix() {
+ void requireAllowCommonPrefix() {
SameElementItem s = new SameElementItem("structa");
s.addItem(new WordItem("b", "f1"));
s.addItem(new WordItem("c", "structaf2"));
@@ -63,7 +61,7 @@ public class SameElementItemTestCase {
}
@Test
- public void requireChildrenCanHavePrefixCommonWithParent() {
+ void requireChildrenCanHavePrefixCommonWithParent() {
SameElementItem s = new SameElementItem("structa");
s.addItem(new WordItem("b", "f1"));
s.addItem(new WordItem("c", "structa.f2"));
@@ -71,7 +69,7 @@ public class SameElementItemTestCase {
}
@Test
- public void requireAllChildrenHaveNonEmptyTerm() {
+ void requireAllChildrenHaveNonEmptyTerm() {
try {
SameElementItem s = new SameElementItem("structa");
s.addItem(new WordItem("", "f2"));
@@ -83,7 +81,7 @@ public class SameElementItemTestCase {
}
@Test
- public void requireNoChildrenAreWordAlternatives() {
+ void requireNoChildrenAreWordAlternatives() {
try {
SameElementItem s = new SameElementItem("structa");
s.addItem(new AndItem());
@@ -91,12 +89,12 @@ public class SameElementItemTestCase {
}
catch (IllegalArgumentException e) { // Success
assertEquals("Child item (AND ) should be an instance of class com.yahoo.prelude.query.TermItem but is class com.yahoo.prelude.query.AndItem",
- e.getMessage());
+ e.getMessage());
}
}
@Test
- public void requireAllChildrenAreTermItems() {
+ void requireAllChildrenAreTermItems() {
try {
SameElementItem s = new SameElementItem("structa");
s.addItem(new WordAlternativesItem("test", true, new Substring("origin"), List.of(new WordAlternativesItem.Alternative("a", 0.3))));
@@ -118,13 +116,13 @@ public class SameElementItemTestCase {
}
@Test
- public void requireExtractSingleItemToExtractSingles() {
+ void requireExtractSingleItemToExtractSingles() {
verifyExtractSingle(new WordItem("b", "f1"));
verifyExtractSingle(new IntItem("7", "f1"));
}
@Test
- public void requireExtractSingleItemToExtractSinglesOnly() {
+ void requireExtractSingleItemToExtractSinglesOnly() {
SameElementItem s = new SameElementItem("structa");
s.addItem(new WordItem("b", "f1"));
s.addItem(new WordItem("c", "f2"));
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/test/SegmentItemTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/test/SegmentItemTestCase.java
index 66653a95dbb..b0271bec896 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/test/SegmentItemTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/test/SegmentItemTestCase.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.prelude.query.test;
-import static org.junit.Assert.*;
-
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.yahoo.prelude.query.PhraseSegmentItem;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
import com.yahoo.prelude.query.WordItem;
/**
@@ -16,7 +15,7 @@ import com.yahoo.prelude.query.WordItem;
public class SegmentItemTestCase {
@Test
- public final void test() {
+ final void test() {
PhraseSegmentItem item = new PhraseSegmentItem("a b c", false, true);
item.addItem(new WordItem("a"));
item.addItem(new WordItem("b"));
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/test/WandItemTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/test/WandItemTestCase.java
index 6a13ea130bc..40753ee1533 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/test/WandItemTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/test/WandItemTestCase.java
@@ -6,14 +6,14 @@ import com.yahoo.prelude.query.PureWeightedString;
import com.yahoo.prelude.query.WandItem;
import com.yahoo.prelude.query.textualrepresentation.Discloser;
import com.yahoo.prelude.query.textualrepresentation.TextualQueryRepresentation;
-import org.junit.Test;
-
-import static org.junit.Assert.assertEquals;
+import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
/**
* Unit tests for WandItem.
*/
@@ -22,7 +22,7 @@ public class WandItemTestCase {
private static final double DELTA = 0.0000001;
@Test
- public void requireThatWandItemCanBeConstructed() {
+ void requireThatWandItemCanBeConstructed() {
WandItem item = new WandItem("myfield", 10);
assertEquals("myfield", item.getIndexName());
assertEquals(10, item.getTargetNumHits());
@@ -32,14 +32,14 @@ public class WandItemTestCase {
}
@Test
- public void requireThatEncodeIsWorking() {
+ void requireThatEncodeIsWorking() {
WandItem item = createSimpleItem();
ByteBuffer actual = ByteBuffer.allocate(128);
ByteBuffer expect = ByteBuffer.allocate(128);
expect.put((byte) 22).put((byte) 1);
Item.putString("myfield", expect);
- expect.put((byte)10); // targetNumHits
+ expect.put((byte) 10); // targetNumHits
expect.putDouble(20); // scoreThreshold
expect.putDouble(2.0); // thresholdBoostFactor
new PureWeightedString("foo", 30).encode(expect);
@@ -53,19 +53,24 @@ public class WandItemTestCase {
}
@Test
- public void requireThatToStringIsWorking() {
- assertEquals("WAND(10,20.0,2.0) myfield{[30]:\"foo\"}", createSimpleItem().toString());
+ void requireThatToStringIsWorking() {
+ assertEquals("WAND(10,20.0,2.0) myfield{[30]:\"foo\"}", createSimpleItem().toString());
}
@Test
- public void requireThatDiscloseIsWorking() {
+ void requireThatDiscloseIsWorking() {
class TestDiscloser implements Discloser {
public final Map<String, Object> props = new HashMap<>();
+
public void addProperty(String key, Object value) {
props.put(key, value);
}
- public void setValue(Object value) {}
- public void addChild(Item item) {}
+
+ public void setValue(Object value) {
+ }
+
+ public void addChild(Item item) {
+ }
}
TestDiscloser discloser = new TestDiscloser();
createSimpleItem().disclose(discloser);
@@ -76,17 +81,17 @@ public class WandItemTestCase {
}
@Test
- public void testTextualRepresentation() {
+ void testTextualRepresentation() {
WandItem item = new WandItem("myfield", 10);
item.addToken("term1", 10);
item.setScoreThreshold(20);
item.setThresholdBoostFactor(2.0);
assertEquals("WAND[index=\"myfield\" scoreThreshold=20.0 targetNumHits=10 thresholdBoostFactor=2.0]{\n" +
- " PURE_WEIGHTED_STRING[weight=10]{\n" +
- " \"term1\"\n" +
- " }\n" +
- "}\n",
- new TextualQueryRepresentation(item).toString());
+ " PURE_WEIGHTED_STRING[weight=10]{\n" +
+ " \"term1\"\n" +
+ " }\n" +
+ "}\n",
+ new TextualQueryRepresentation(item).toString());
}
private static WandItem createSimpleItem() {
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/test/WeightedSetItemTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/test/WeightedSetItemTestCase.java
index 8a335c9119d..1cd657a1940 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/test/WeightedSetItemTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/test/WeightedSetItemTestCase.java
@@ -6,19 +6,16 @@ import com.yahoo.prelude.query.Item;
import com.yahoo.prelude.query.PureWeightedString;
import com.yahoo.prelude.query.WeightedSetItem;
import com.yahoo.prelude.query.WordItem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
-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.*;
public class WeightedSetItemTestCase {
@Test
- public void testTokenAPI() {
+ void testTokenAPI() {
WeightedSetItem ws = new WeightedSetItem("index");
assertEquals(0, ws.getNumTokens());
assertNull(ws.getTokenWeight("bogus"));
@@ -55,11 +52,11 @@ public class WeightedSetItemTestCase {
}
@Test
- public void testNegativeWeight() {
+ void testNegativeWeight() {
WeightedSetItem ws = new WeightedSetItem("index");
assertEquals(Integer.valueOf(-10), ws.addToken("bad", -10));
assertEquals(1, ws.getNumTokens());
- assertEquals(Integer.valueOf(-10), ws.getTokenWeight("bad"));
+ assertEquals(Integer.valueOf(-10), ws.getTokenWeight("bad"));
}
static class FakeWSItem extends CompositeIndexedItem {
@@ -77,7 +74,7 @@ public class WeightedSetItemTestCase {
}
@Test
- public void testEncoding() {
+ void testEncoding() {
WeightedSetItem item = new WeightedSetItem("index");
// need 2 alternative reference encoding, as the encoding
// order is kept undefined to improve performance.
@@ -94,11 +91,11 @@ public class WeightedSetItemTestCase {
ByteBuffer actual = ByteBuffer.allocate(128);
ByteBuffer expect1 = ByteBuffer.allocate(128);
ByteBuffer expect2 = ByteBuffer.allocate(128);
- expect1.put((byte)15).put((byte)2);
+ expect1.put((byte) 15).put((byte) 2);
Item.putString("index", expect1);
new PureWeightedString("foo", 10).encode(expect1);
new PureWeightedString("bar", 20).encode(expect1);
- expect2.put((byte)15).put((byte)2);
+ expect2.put((byte) 15).put((byte) 2);
Item.putString("index", expect2);
new PureWeightedString("bar", 20).encode(expect2);
new PureWeightedString("foo", 10).encode(expect2);
@@ -110,9 +107,9 @@ public class WeightedSetItemTestCase {
expect2.flip();
if (actual.equals(expect1)) {
- assertFalse(actual.equals(expect2));
+ assertNotEquals(actual, expect2);
} else {
- assertTrue(actual.equals(expect2));
+ assertEquals(actual, expect2);
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/query/textualrepresentation/test/TextualQueryRepresentationTestCase.java b/container-search/src/test/java/com/yahoo/prelude/query/textualrepresentation/test/TextualQueryRepresentationTestCase.java
index 213f912c0a5..cf65205fe34 100644
--- a/container-search/src/test/java/com/yahoo/prelude/query/textualrepresentation/test/TextualQueryRepresentationTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/query/textualrepresentation/test/TextualQueryRepresentationTestCase.java
@@ -11,11 +11,11 @@ import java.util.HashSet;
import java.util.Map;
import com.yahoo.prelude.query.Item;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
import com.yahoo.prelude.query.textualrepresentation.Discloser;
import com.yahoo.prelude.query.textualrepresentation.TextualQueryRepresentation;
-import org.junit.Test;
-
-import static org.junit.Assert.assertEquals;
+import org.junit.jupiter.api.Test;
/**
* Test of TextualQueryRepresentation.
@@ -102,14 +102,14 @@ public class TextualQueryRepresentationTestCase {
}
@Test
- public void testBasic() throws Exception {
+ void testBasic() throws Exception {
String basicText = getTextualQueryRepresentation(basic);
assertEquals(getCorrect("basic.txt"), basicText);
}
@Test
- public void testComposite() throws Exception {
+ void testComposite() throws Exception {
String compositeText = getTextualQueryRepresentation(composite);
assertEquals(getCorrect("composite.txt"), compositeText);
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/CJKSearcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/CJKSearcherTestCase.java
index b3b96299b90..0c24da54ec4 100644
--- a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/CJKSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/CJKSearcherTestCase.java
@@ -18,10 +18,10 @@ import com.yahoo.search.query.parser.ParserEnvironment;
import com.yahoo.search.query.parser.ParserFactory;
import com.yahoo.search.searchchain.Execution;
-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 Steinar Knutsen
@@ -32,9 +32,9 @@ public class CJKSearcherTestCase {
"querytransform/test/cjk-index-info.cfg", null);
@Test
- public void testTermWeight() {
+ void testTermWeight() {
assertTransformed("efg!10", "SAND e!10 fg!10",
- Query.Type.ALL, Language.CHINESE_SIMPLIFIED, Language.CHINESE_TRADITIONAL, TestLinguistics.INSTANCE);
+ Query.Type.ALL, Language.CHINESE_SIMPLIFIED, Language.CHINESE_TRADITIONAL, TestLinguistics.INSTANCE);
}
/**
@@ -43,14 +43,14 @@ public class CJKSearcherTestCase {
* must combine overlapping tokens as PHRASE, not AND to avoid a too high recall because of the token overlap.
*/
@Test
- public void testCjkQueryWithOverlappingTokens() {
+ void testCjkQueryWithOverlappingTokens() {
// The test language segmenter will segment "bcd" into the overlapping tokens "bc" "cd"
assertTransformed("bcd", "SAND bc cd", Query.Type.ALL, Language.CHINESE_SIMPLIFIED, Language.CHINESE_TRADITIONAL,
- TestLinguistics.INSTANCE);
+ TestLinguistics.INSTANCE);
// While "efg" will be segmented into one of the standard options, "e" "fg"
assertTransformed("efg", "SAND e fg", Query.Type.ALL, Language.CHINESE_SIMPLIFIED, Language.CHINESE_TRADITIONAL,
- TestLinguistics.INSTANCE);
+ TestLinguistics.INSTANCE);
}
private void assertTransformed(String queryString, String expected, Query.Type mode, Language actualLanguage,
diff --git a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/CollapsePhraseSearcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/CollapsePhraseSearcherTestCase.java
index 498d6ca2980..3aaf941c6f5 100644
--- a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/CollapsePhraseSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/CollapsePhraseSearcherTestCase.java
@@ -9,12 +9,12 @@ import com.yahoo.prelude.query.PhraseItem;
import com.yahoo.prelude.query.WordItem;
import com.yahoo.prelude.querytransform.CollapsePhraseSearcher;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Check CollapsePhraseSearcher works and only is triggered when it
@@ -25,14 +25,14 @@ import static org.junit.Assert.assertEquals;
public class CollapsePhraseSearcherTestCase {
@Test
- public void testSimplePositive() {
+ void testSimplePositive() {
PhraseItem root = new PhraseItem();
root.addItem(new WordItem("abc"));
assertEquals("abc", transformQuery(root));
}
@Test
- public void testPositive1() {
+ void testPositive1() {
AndItem root = new AndItem();
root.addItem(new WordItem("a"));
PhraseItem embedded = new PhraseItem();
@@ -40,11 +40,11 @@ public class CollapsePhraseSearcherTestCase {
root.addItem(embedded);
root.addItem(new WordItem("e"));
assertEquals("AND a bcd e",
- transformQuery(root));
+ transformQuery(root));
}
@Test
- public void testPositive2() {
+ void testPositive2() {
AndItem root = new AndItem();
root.addItem(new WordItem("a"));
CompositeItem embedded = new AndItem();
@@ -55,21 +55,21 @@ public class CollapsePhraseSearcherTestCase {
root.addItem(embedded);
root.addItem(new WordItem("e"));
assertEquals("AND a (AND bcd def) e",
- transformQuery(root));
+ transformQuery(root));
}
@Test
- public void testNoTerms() {
+ void testNoTerms() {
assertEquals("NULL", transformQuery("?query=" + enc("\"\"")));
}
@Test
- public void testNegative1() {
+ void testNegative1() {
assertEquals("WEAKAND(100) \"abc def\"", transformQuery("?query=" + enc("\"abc def\"")));
}
@Test
- public void testNegative2() {
+ void testNegative2() {
assertEquals("WEAKAND(100) a \"abc def\" b", transformQuery("?query=" + enc("a \"abc def\" b")));
}
@@ -83,7 +83,7 @@ public class CollapsePhraseSearcherTestCase {
}
@Test
- public void testNegative3() {
+ void testNegative3() {
AndItem root = new AndItem();
root.addItem(new WordItem("a"));
CompositeItem embedded = new AndItem();
@@ -95,7 +95,7 @@ public class CollapsePhraseSearcherTestCase {
root.addItem(embedded);
root.addItem(new WordItem("e"));
assertEquals("AND a (AND bcd \"def ghi\") e",
- transformQuery(root));
+ transformQuery(root));
}
private String transformQuery(String rawQuery) {
diff --git a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/LiteralBoostSearcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/LiteralBoostSearcherTestCase.java
index a434fbd9949..16e27303fa8 100644
--- a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/LiteralBoostSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/LiteralBoostSearcherTestCase.java
@@ -10,11 +10,11 @@ import com.yahoo.search.Query;
import com.yahoo.prelude.querytransform.LiteralBoostSearcher;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.test.QueryTestCase;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.*;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Tests the complete field match query transformer
@@ -24,55 +24,55 @@ import static org.junit.Assert.assertEquals;
public class LiteralBoostSearcherTestCase {
@Test
- public void testSimpleQueryWithBoost() {
+ void testSimpleQueryWithBoost() {
assertEquals("RANK (WEAKAND(100) abc) default_literal:abc",
- transformQuery("?query=abc&source=cluster1&restrict=type1"));
+ transformQuery("?query=abc&source=cluster1&restrict=type1"));
}
@Test
- public void testSimpleQueryNoBoost() {
+ void testSimpleQueryNoBoost() {
assertEquals("WEAKAND(100) abc",
transformQuery("?query=abc&source=cluster1&restrict=type2"));
}
@Test
- public void testQueryWithExplicitIndex() {
+ void testQueryWithExplicitIndex() {
assertEquals("RANK (WEAKAND(100) absolute:abc) absolute_literal:abc",
transformQuery("?query=absolute:abc&source=cluster1&restrict=type1"));
}
@Test
- public void testQueryWithExplicitIndexNoBoost() {
+ void testQueryWithExplicitIndexNoBoost() {
assertEquals("WEAKAND(100) absolute:abc",
transformQuery("?query=absolute:abc&source=cluster1&restrict=type2"));
}
@Test
- public void testQueryWithNegativeBranch() {
- assertEquals("RANK (+(AND abc def) -ghi) "+
- "default_literal:abc default_literal:def",
- transformQuery("?query=abc and def andnot ghi&type=adv&source=cluster1&restrict=type1"));
+ void testQueryWithNegativeBranch() {
+ assertEquals("RANK (+(AND abc def) -ghi) " +
+ "default_literal:abc default_literal:def",
+ transformQuery("?query=abc and def andnot ghi&type=adv&source=cluster1&restrict=type1"));
}
@Test
- public void testJumbledQuery() {
+ void testJumbledQuery() {
assertEquals
- ("RANK (OR (+(OR abc def) -ghi) jkl) " +
- "default_literal:abc default_literal:def default_literal:jkl",
- transformQuery("?query=abc or def andnot ghi or jkl&type=adv&source=cluster1&restrict=type1"));
+ ("RANK (OR (+(OR abc def) -ghi) jkl) " +
+ "default_literal:abc default_literal:def default_literal:jkl",
+ transformQuery("?query=abc or def andnot ghi or jkl&type=adv&source=cluster1&restrict=type1"));
}
@Test
- public void testTermindexQuery() {
- assertEquals("RANK (+(WEAKAND(100) a b d) -c) default_literal:a "+
- "default_literal:b default_literal:d",
- transformQuery("?query=a b -c d&source=cluster1&restrict=type1"));
+ void testTermindexQuery() {
+ assertEquals("RANK (+(WEAKAND(100) a b d) -c) default_literal:a " +
+ "default_literal:b default_literal:d",
+ transformQuery("?query=a b -c d&source=cluster1&restrict=type1"));
}
@Test
- public void testQueryWithoutBoost() {
+ void testQueryWithoutBoost() {
assertEquals("RANK (AND nonexistant a nonexistant b) default_literal:nonexistant default_literal:a default_literal:nonexistant default_literal:b",
- transformQuery("?query=nonexistant:a nonexistant:b&source=cluster1&restrict=type1&type=all"));
+ transformQuery("?query=nonexistant:a nonexistant:b&source=cluster1&restrict=type1&type=all"));
}
private String transformQuery(String rawQuery) {
diff --git a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/NoRankingSearcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/NoRankingSearcherTestCase.java
index 107a82f3186..16d6bd40178 100644
--- a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/NoRankingSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/NoRankingSearcherTestCase.java
@@ -5,41 +5,41 @@ import com.yahoo.search.Query;
import com.yahoo.prelude.querytransform.NoRankingSearcher;
import com.yahoo.search.Searcher;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class NoRankingSearcherTestCase {
Searcher s = new NoRankingSearcher();
@Test
- public void testDoSearch() {
+ void testDoSearch() {
Query q = new Query("?query=a&sorting=%2ba%20-b&ranking=hello");
assertEquals("hello", q.getRanking().getProfile());
new Execution(s, Execution.Context.createContextStub()).search(q);
assertEquals("unranked", q.getRanking().getProfile());
- }
+ }
@Test
- public void testSortOnRelevanceAscending() {
+ void testSortOnRelevanceAscending() {
Query q = new Query("?query=a&sorting=%2ba%20-b%20-[rank]&ranking=hello");
new Execution(s, Execution.Context.createContextStub()).search(q);
assertEquals("hello", q.getRanking().getProfile());
- }
+ }
@Test
- public void testSortOnRelevanceDescending() {
+ void testSortOnRelevanceDescending() {
Query q = new Query("?query=a&sorting=%2ba%20-b%20-[rank]&ranking=hello");
new Execution(s, Execution.Context.createContextStub()).search(q);
assertEquals("hello", q.getRanking().getProfile());
- }
+ }
@Test
- public void testNoSorting() {
+ void testNoSorting() {
Query q = new Query("?query=a");
new Execution(s, Execution.Context.createContextStub()).search(q);
assertEquals("default", q.getRanking().getProfile());
- }
+ }
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/NonPhrasingSearcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/NonPhrasingSearcherTestCase.java
index 462e57a2b37..5a090a51415 100644
--- a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/NonPhrasingSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/NonPhrasingSearcherTestCase.java
@@ -7,9 +7,9 @@ import com.yahoo.prelude.query.WordItem;
import com.yahoo.prelude.querytransform.NonPhrasingSearcher;
import com.yahoo.search.Searcher;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Tests non-phrasing
@@ -21,58 +21,58 @@ public class NonPhrasingSearcherTestCase {
private Searcher searcher;
@Test
- public void testSingleWordNonPhrasing() {
- searcher=
- new NonPhrasingSearcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
+ void testSingleWordNonPhrasing() {
+ searcher =
+ new NonPhrasingSearcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
- Query query=new Query("?query=void+aword+kanoo");
+ Query query = new Query("?query=void+aword+kanoo");
new Execution(searcher, Execution.Context.createContextStub()).search(query);
assertEquals("WEAKAND(100) void kanoo", query.getModel().getQueryTree().getRoot().toString());
}
@Test
- public void testMultipleWordNonPhrasing() {
- searcher=
- new NonPhrasingSearcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
+ void testMultipleWordNonPhrasing() {
+ searcher =
+ new NonPhrasingSearcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
- Query query=new Query("?query=void+tudor+vidor+kanoo");
+ Query query = new Query("?query=void+tudor+vidor+kanoo");
new Execution(searcher, Execution.Context.createContextStub()).search(query);
- CompositeItem item=(CompositeItem) query.getModel().getQueryTree().getRoot();
- assertEquals(2,item.getItemCount());
- assertEquals("void",((WordItem)item.getItem(0)).getWord());
- assertEquals("kanoo",((WordItem)item.getItem(1)).getWord());
+ CompositeItem item = (CompositeItem) query.getModel().getQueryTree().getRoot();
+ assertEquals(2, item.getItemCount());
+ assertEquals("void", ((WordItem) item.getItem(0)).getWord());
+ assertEquals("kanoo", ((WordItem) item.getItem(1)).getWord());
}
@Test
- public void testNoNonPhrasingIfNoOtherPhrases() {
- searcher=
- new NonPhrasingSearcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
+ void testNoNonPhrasingIfNoOtherPhrases() {
+ searcher =
+ new NonPhrasingSearcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
- Query query=new Query("?query=tudor+vidor");
+ Query query = new Query("?query=tudor+vidor");
new Execution(searcher, Execution.Context.createContextStub()).search(query);
- CompositeItem item=(CompositeItem) query.getModel().getQueryTree().getRoot();
- assertEquals(2,item.getItemCount());
- assertEquals("tudor",((WordItem)item.getItem(0)).getWord());
- assertEquals("vidor",((WordItem)item.getItem(1)).getWord());
+ CompositeItem item = (CompositeItem) query.getModel().getQueryTree().getRoot();
+ assertEquals(2, item.getItemCount());
+ assertEquals("tudor", ((WordItem) item.getItem(0)).getWord());
+ assertEquals("vidor", ((WordItem) item.getItem(1)).getWord());
}
@Test
- public void testNoNonPhrasingIfSuggestOnly() {
- searcher=
- new NonPhrasingSearcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
+ void testNoNonPhrasingIfSuggestOnly() {
+ searcher =
+ new NonPhrasingSearcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
- Query query=new Query("?query=void+tudor+vidor+kanoo&suggestonly=true");
+ Query query = new Query("?query=void+tudor+vidor+kanoo&suggestonly=true");
new Execution(searcher, Execution.Context.createContextStub()).search(query);
- CompositeItem item=(CompositeItem) query.getModel().getQueryTree().getRoot();
- assertEquals(4,item.getItemCount());
- assertEquals("void",((WordItem)item.getItem(0)).getWord());
- assertEquals("tudor",((WordItem)item.getItem(1)).getWord());
- assertEquals("vidor",((WordItem)item.getItem(2)).getWord());
- assertEquals("kanoo",((WordItem)item.getItem(3)).getWord());
+ CompositeItem item = (CompositeItem) query.getModel().getQueryTree().getRoot();
+ assertEquals(4, item.getItemCount());
+ assertEquals("void", ((WordItem) item.getItem(0)).getWord());
+ assertEquals("tudor", ((WordItem) item.getItem(1)).getWord());
+ assertEquals("vidor", ((WordItem) item.getItem(2)).getWord());
+ assertEquals("kanoo", ((WordItem) item.getItem(3)).getWord());
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/NormalizingSearcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/NormalizingSearcherTestCase.java
index 7ab50118c6d..239f4500297 100644
--- a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/NormalizingSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/NormalizingSearcherTestCase.java
@@ -1,8 +1,8 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.querytransform.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;
import com.google.common.collect.ImmutableList;
import com.yahoo.language.Linguistics;
@@ -19,7 +19,7 @@ import com.yahoo.prelude.IndexModel;
import com.yahoo.prelude.querytransform.NormalizingSearcher;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
@@ -38,35 +38,35 @@ public class NormalizingSearcherTestCase {
private static final Linguistics linguistics = new SimpleLinguistics();
@Test
- public void testNoNormalizingNecssary() {
+ void testNoNormalizingNecssary() {
Query query = new Query("/search?query=bilen&search=cluster1&restrict=type1");
createExecution().search(query);
assertEquals("WEAKAND(100) bilen", query.getModel().getQueryTree().getRoot().toString());
}
@Test
- public void testAttributeQuery() {
+ void testAttributeQuery() {
Query query = new Query("/search?query=attribute:" + enc("b\u00e9yonc\u00e8 b\u00e9yonc\u00e8") + "&search=cluster1&restrict=type1");
createExecution().search(query);
assertEquals("WEAKAND(100) attribute:b\u00e9yonc\u00e8 beyonce", query.getModel().getQueryTree().getRoot().toString());
}
@Test
- public void testOneTermNormalizing() {
+ void testOneTermNormalizing() {
Query query = new Query("/search?query=b\u00e9yonc\u00e8&search=cluster1&restrict=type1");
createExecution().search(query);
assertEquals("WEAKAND(100) beyonce", query.getModel().getQueryTree().getRoot().toString());
}
@Test
- public void testOneTermNoNormalizingDifferentSearchDef() {
+ void testOneTermNoNormalizingDifferentSearchDef() {
Query query = new Query("/search?query=b\u00e9yonc\u00e8&search=cluster1&restrict=type2");
createExecution().search(query);
assertEquals("WEAKAND(100) béyoncè", query.getModel().getQueryTree().getRoot().toString());
}
@Test
- public void testTwoTermQuery() throws UnsupportedEncodingException {
+ void testTwoTermQuery() throws UnsupportedEncodingException {
Query query = new Query("/search?query=" + enc("b\u00e9yonc\u00e8 beyonc\u00e9") + "&search=cluster1&restrict=type1");
createExecution().search(query);
assertEquals("WEAKAND(100) beyonce beyonce", query.getModel().getQueryTree().getRoot().toString());
@@ -82,7 +82,7 @@ public class NormalizingSearcherTestCase {
}
@Test
- public void testPhraseQuery() {
+ void testPhraseQuery() {
Query query = new Query("/search?query=" + enc("\"b\u00e9yonc\u00e8 beyonc\u00e9\"") + "&search=cluster1&restrict=type1");
query.getTrace().setLevel(2);
createExecution().search(query);
@@ -90,7 +90,7 @@ public class NormalizingSearcherTestCase {
}
@Test
- public void testLiteralBoost() {
+ void testLiteralBoost() {
Query query = new Query("/search?query=nop&search=cluster1&restrict=type1");
List<WordAlternativesItem.Alternative> terms = new ArrayList<>();
Substring origin = new Substring(0, 5, "h\u00F4tels");
@@ -107,12 +107,12 @@ public class NormalizingSearcherTestCase {
assertEquals(.7d * .7d, a.exactness, 1e-15);
}
}
- assertTrue("Did not find the expected normalized form \"hotel\".", foundHotel);
+ assertTrue(foundHotel, "Did not find the expected normalized form \"hotel\".");
}
@Test
- public void testPhraseSegmentNormalization() {
+ void testPhraseSegmentNormalization() {
Query query = new Query("/search?query=&search=cluster1&restrict=type1");
PhraseSegmentItem phraseSegment = new PhraseSegmentItem("default", false, false);
phraseSegment.addItem(new WordItem("net"));
diff --git a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/PhraseMatcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/PhraseMatcherTestCase.java
index 623c480796c..da7b29272a2 100644
--- a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/PhraseMatcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/PhraseMatcherTestCase.java
@@ -5,14 +5,11 @@ import com.yahoo.prelude.query.AndItem;
import com.yahoo.prelude.query.IntItem;
import com.yahoo.prelude.query.WordItem;
import com.yahoo.prelude.querytransform.PhraseMatcher;
-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.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -20,118 +17,118 @@ import static org.junit.Assert.assertNull;
public class PhraseMatcherTestCase {
@Test
- public void testSingleItemMatching() {
- PhraseMatcher matcher=new PhraseMatcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
+ void testSingleItemMatching() {
+ PhraseMatcher matcher = new PhraseMatcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
matcher.setMatchSingleItems(true);
- List<?> matches=matcher.matchPhrases(new WordItem("aword"));
+ List<?> matches = matcher.matchPhrases(new WordItem("aword"));
assertNotNull(matches);
- assertEquals(1,matches.size());
- PhraseMatcher.Phrase match=(PhraseMatcher.Phrase)matches.get(0);
- assertEquals(1,match.getLength());
- assertEquals("",match.getData());
- assertEquals(null,match.getOwner());
- assertEquals(0,match.getStartIndex());
- PhraseMatcher.Phrase.MatchIterator i=match.itemIterator();
- assertEquals(new WordItem("aword"),i.next());
+ assertEquals(1, matches.size());
+ PhraseMatcher.Phrase match = (PhraseMatcher.Phrase) matches.get(0);
+ assertEquals(1, match.getLength());
+ assertEquals("", match.getData());
+ assertNull(match.getOwner());
+ assertEquals(0, match.getStartIndex());
+ PhraseMatcher.Phrase.MatchIterator i = match.itemIterator();
+ assertEquals(new WordItem("aword"), i.next());
assertNull(i.getReplace());
assertFalse(i.hasNext());
}
@Test
- public void testSingleItemMatchingCaseInsensitive() {
- PhraseMatcher matcher=new PhraseMatcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
+ void testSingleItemMatchingCaseInsensitive() {
+ PhraseMatcher matcher = new PhraseMatcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
matcher.setMatchSingleItems(true);
final String mixedCase = "aWoRD";
- List<?> matches=matcher.matchPhrases(new WordItem(mixedCase));
+ List<?> matches = matcher.matchPhrases(new WordItem(mixedCase));
assertNotNull(matches);
- assertEquals(1,matches.size());
- PhraseMatcher.Phrase match=(PhraseMatcher.Phrase)matches.get(0);
- assertEquals(1,match.getLength());
- assertEquals("",match.getData());
- assertEquals(null,match.getOwner());
- assertEquals(0,match.getStartIndex());
- PhraseMatcher.Phrase.MatchIterator i=match.itemIterator();
- assertEquals(new WordItem(mixedCase),i.next());
+ assertEquals(1, matches.size());
+ PhraseMatcher.Phrase match = (PhraseMatcher.Phrase) matches.get(0);
+ assertEquals(1, match.getLength());
+ assertEquals("", match.getData());
+ assertNull(match.getOwner());
+ assertEquals(0, match.getStartIndex());
+ PhraseMatcher.Phrase.MatchIterator i = match.itemIterator();
+ assertEquals(new WordItem(mixedCase), i.next());
assertNull(i.getReplace());
assertFalse(i.hasNext());
}
@Test
- public void testSingleItemMatchingWithPluralIgnore() {
- PhraseMatcher matcher=new PhraseMatcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa",true);
+ void testSingleItemMatchingWithPluralIgnore() {
+ PhraseMatcher matcher = new PhraseMatcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa", true);
matcher.setMatchSingleItems(true);
- List<?> matches=matcher.matchPhrases(new WordItem("awords"));
+ List<?> matches = matcher.matchPhrases(new WordItem("awords"));
assertNotNull(matches);
- assertEquals(1,matches.size());
- PhraseMatcher.Phrase match=(PhraseMatcher.Phrase)matches.get(0);
- assertEquals(1,match.getLength());
- assertEquals("",match.getData());
- assertEquals(null,match.getOwner());
- assertEquals(0,match.getStartIndex());
- PhraseMatcher.Phrase.MatchIterator i=match.itemIterator();
- assertEquals(new WordItem("awords"),i.next());
- assertEquals("aword",i.getReplace());
+ assertEquals(1, matches.size());
+ PhraseMatcher.Phrase match = (PhraseMatcher.Phrase) matches.get(0);
+ assertEquals(1, match.getLength());
+ assertEquals("", match.getData());
+ assertNull(match.getOwner());
+ assertEquals(0, match.getStartIndex());
+ PhraseMatcher.Phrase.MatchIterator i = match.itemIterator();
+ assertEquals(new WordItem("awords"), i.next());
+ assertEquals("aword", i.getReplace());
assertFalse(i.hasNext());
}
@Test
- public void testSingleItemMatchingCaseInsensitiveWithPluralIgnore() {
- PhraseMatcher matcher=new PhraseMatcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa",true);
+ void testSingleItemMatchingCaseInsensitiveWithPluralIgnore() {
+ PhraseMatcher matcher = new PhraseMatcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa", true);
matcher.setMatchSingleItems(true);
final String mixedCase = "aWoRDS";
- List<?> matches=matcher.matchPhrases(new WordItem(mixedCase));
+ List<?> matches = matcher.matchPhrases(new WordItem(mixedCase));
assertNotNull(matches);
- assertEquals(1,matches.size());
- PhraseMatcher.Phrase match=(PhraseMatcher.Phrase)matches.get(0);
- assertEquals(1,match.getLength());
- assertEquals("",match.getData());
- assertEquals(null,match.getOwner());
- assertEquals(0,match.getStartIndex());
- PhraseMatcher.Phrase.MatchIterator i=match.itemIterator();
- assertEquals(new WordItem(mixedCase),i.next());
- assertEquals("aword",i.getReplace());
+ assertEquals(1, matches.size());
+ PhraseMatcher.Phrase match = (PhraseMatcher.Phrase) matches.get(0);
+ assertEquals(1, match.getLength());
+ assertEquals("", match.getData());
+ assertNull(match.getOwner());
+ assertEquals(0, match.getStartIndex());
+ PhraseMatcher.Phrase.MatchIterator i = match.itemIterator();
+ assertEquals(new WordItem(mixedCase), i.next());
+ assertEquals("aword", i.getReplace());
assertFalse(i.hasNext());
}
@Test
- public void testPhraseMatching() {
- PhraseMatcher matcher=new PhraseMatcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa",true);
- AndItem and=new AndItem();
+ void testPhraseMatching() {
+ PhraseMatcher matcher = new PhraseMatcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa", true);
+ AndItem and = new AndItem();
and.addItem(new WordItem("noisebefore"));
and.addItem(new WordItem("this"));
and.addItem(new WordItem("is"));
and.addItem(new WordItem("a"));
and.addItem(new WordItem("test"));
and.addItem(new WordItem("noiseafter"));
- List<?> matches=matcher.matchPhrases(and);
+ List<?> matches = matcher.matchPhrases(and);
assertNotNull(matches);
- assertEquals(1,matches.size());
- PhraseMatcher.Phrase match=(PhraseMatcher.Phrase)matches.get(0);
- assertEquals(4,match.getLength());
- assertEquals("",match.getData());
- assertEquals(and,match.getOwner());
- assertEquals(1,match.getStartIndex());
- PhraseMatcher.Phrase.MatchIterator i=match.itemIterator();
- assertEquals(new WordItem("this"),i.next());
- assertEquals(null,i.getReplace());
- assertEquals(new WordItem("is"),i.next());
- assertEquals(null,i.getReplace());
- assertEquals(new WordItem("a"),i.next());
- assertEquals(null,i.getReplace());
- assertEquals(new WordItem("test"),i.next());
- assertEquals(null,i.getReplace());
+ assertEquals(1, matches.size());
+ PhraseMatcher.Phrase match = (PhraseMatcher.Phrase) matches.get(0);
+ assertEquals(4, match.getLength());
+ assertEquals("", match.getData());
+ assertEquals(and, match.getOwner());
+ assertEquals(1, match.getStartIndex());
+ PhraseMatcher.Phrase.MatchIterator i = match.itemIterator();
+ assertEquals(new WordItem("this"), i.next());
+ assertNull(i.getReplace());
+ assertEquals(new WordItem("is"), i.next());
+ assertNull(i.getReplace());
+ assertEquals(new WordItem("a"), i.next());
+ assertNull(i.getReplace());
+ assertEquals(new WordItem("test"), i.next());
+ assertNull(i.getReplace());
assertFalse(i.hasNext());
}
@Test
- public void testPhraseMatchingCaseInsensitive() {
- PhraseMatcher matcher=new PhraseMatcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa",true);
- AndItem and=new AndItem();
+ void testPhraseMatchingCaseInsensitive() {
+ PhraseMatcher matcher = new PhraseMatcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa", true);
+ AndItem and = new AndItem();
and.addItem(new WordItem("noisebefore"));
final String firstWord = "thIs";
and.addItem(new WordItem(firstWord));
@@ -142,93 +139,93 @@ public class PhraseMatcherTestCase {
final String fourthWord = "tEst";
and.addItem(new WordItem(fourthWord));
and.addItem(new WordItem("noiseafter"));
- List<?> matches=matcher.matchPhrases(and);
+ List<?> matches = matcher.matchPhrases(and);
assertNotNull(matches);
- assertEquals(1,matches.size());
- PhraseMatcher.Phrase match=(PhraseMatcher.Phrase)matches.get(0);
- assertEquals(4,match.getLength());
- assertEquals("",match.getData());
- assertEquals(and,match.getOwner());
- assertEquals(1,match.getStartIndex());
- PhraseMatcher.Phrase.MatchIterator i=match.itemIterator();
- assertEquals(new WordItem(firstWord),i.next());
- assertEquals(null,i.getReplace());
- assertEquals(new WordItem(secondWord),i.next());
- assertEquals(null,i.getReplace());
- assertEquals(new WordItem(thirdWord),i.next());
- assertEquals(null,i.getReplace());
- assertEquals(new WordItem(fourthWord),i.next());
- assertEquals(null,i.getReplace());
+ assertEquals(1, matches.size());
+ PhraseMatcher.Phrase match = (PhraseMatcher.Phrase) matches.get(0);
+ assertEquals(4, match.getLength());
+ assertEquals("", match.getData());
+ assertEquals(and, match.getOwner());
+ assertEquals(1, match.getStartIndex());
+ PhraseMatcher.Phrase.MatchIterator i = match.itemIterator();
+ assertEquals(new WordItem(firstWord), i.next());
+ assertNull(i.getReplace());
+ assertEquals(new WordItem(secondWord), i.next());
+ assertNull(i.getReplace());
+ assertEquals(new WordItem(thirdWord), i.next());
+ assertNull(i.getReplace());
+ assertEquals(new WordItem(fourthWord), i.next());
+ assertNull(i.getReplace());
assertFalse(i.hasNext());
}
@Test
- public void testPhraseMatchingWithNumber() {
- PhraseMatcher matcher=new PhraseMatcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa",true);
- AndItem and=new AndItem();
+ void testPhraseMatchingWithNumber() {
+ PhraseMatcher matcher = new PhraseMatcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa", true);
+ AndItem and = new AndItem();
and.addItem(new WordItem("noisebefore"));
and.addItem(new WordItem("this"));
and.addItem(new WordItem("is"));
and.addItem(new IntItem("3"));
and.addItem(new WordItem("tests"));
and.addItem(new WordItem("noiseafter"));
- List<?> matches=matcher.matchPhrases(and);
+ List<?> matches = matcher.matchPhrases(and);
assertNotNull(matches);
- assertEquals(1,matches.size());
- PhraseMatcher.Phrase match=(PhraseMatcher.Phrase)matches.get(0);
- assertEquals(4,match.getLength());
- assertEquals("",match.getData());
- assertEquals(and,match.getOwner());
- assertEquals(1,match.getStartIndex());
- PhraseMatcher.Phrase.MatchIterator i=match.itemIterator();
- assertEquals(new WordItem("this"),i.next());
- assertEquals(null,i.getReplace());
- assertEquals(new WordItem("is"),i.next());
- assertEquals(null,i.getReplace());
- assertEquals(new IntItem("3"),i.next());
- assertEquals(null,i.getReplace());
- assertEquals(new WordItem("tests"),i.next());
- assertEquals(null,i.getReplace());
+ assertEquals(1, matches.size());
+ PhraseMatcher.Phrase match = (PhraseMatcher.Phrase) matches.get(0);
+ assertEquals(4, match.getLength());
+ assertEquals("", match.getData());
+ assertEquals(and, match.getOwner());
+ assertEquals(1, match.getStartIndex());
+ PhraseMatcher.Phrase.MatchIterator i = match.itemIterator();
+ assertEquals(new WordItem("this"), i.next());
+ assertNull(i.getReplace());
+ assertEquals(new WordItem("is"), i.next());
+ assertNull(i.getReplace());
+ assertEquals(new IntItem("3"), i.next());
+ assertNull(i.getReplace());
+ assertEquals(new WordItem("tests"), i.next());
+ assertNull(i.getReplace());
assertFalse(i.hasNext());
}
@Test
- public void testPhraseMatchingWithPluralIgnore() {
- PhraseMatcher matcher=new PhraseMatcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa",true);
- AndItem and=new AndItem();
+ void testPhraseMatchingWithPluralIgnore() {
+ PhraseMatcher matcher = new PhraseMatcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa", true);
+ AndItem and = new AndItem();
and.addItem(new WordItem("noisebefore"));
and.addItem(new WordItem("thi"));
and.addItem(new WordItem("is"));
and.addItem(new WordItem("a"));
and.addItem(new WordItem("tests"));
and.addItem(new WordItem("noiseafter"));
- List<?> matches=matcher.matchPhrases(and);
+ List<?> matches = matcher.matchPhrases(and);
assertNotNull(matches);
- assertEquals(1,matches.size());
- PhraseMatcher.Phrase match=(PhraseMatcher.Phrase)matches.get(0);
- assertEquals(4,match.getLength());
- assertEquals("",match.getData());
- assertEquals(and,match.getOwner());
- assertEquals(1,match.getStartIndex());
- PhraseMatcher.Phrase.MatchIterator i=match.itemIterator();
- assertEquals(new WordItem("thi"),i.next());
- assertEquals("this",i.getReplace());
- assertEquals(new WordItem("is"),i.next());
- assertEquals(null,i.getReplace());
- assertEquals(new WordItem("a"),i.next());
- assertEquals(null,i.getReplace());
- assertEquals(new WordItem("tests"),i.next());
- assertEquals("test",i.getReplace());
+ assertEquals(1, matches.size());
+ PhraseMatcher.Phrase match = (PhraseMatcher.Phrase) matches.get(0);
+ assertEquals(4, match.getLength());
+ assertEquals("", match.getData());
+ assertEquals(and, match.getOwner());
+ assertEquals(1, match.getStartIndex());
+ PhraseMatcher.Phrase.MatchIterator i = match.itemIterator();
+ assertEquals(new WordItem("thi"), i.next());
+ assertEquals("this", i.getReplace());
+ assertEquals(new WordItem("is"), i.next());
+ assertNull(i.getReplace());
+ assertEquals(new WordItem("a"), i.next());
+ assertNull(i.getReplace());
+ assertEquals(new WordItem("tests"), i.next());
+ assertEquals("test", i.getReplace());
assertFalse(i.hasNext());
}
@Test
- public void testPhraseMatchingCaseInsensitiveWithPluralIgnore() {
- PhraseMatcher matcher=new PhraseMatcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa",true);
- AndItem and=new AndItem();
+ void testPhraseMatchingCaseInsensitiveWithPluralIgnore() {
+ PhraseMatcher matcher = new PhraseMatcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa", true);
+ AndItem and = new AndItem();
and.addItem(new WordItem("noisebefore"));
final String firstWord = "thI";
and.addItem(new WordItem(firstWord));
@@ -239,24 +236,24 @@ public class PhraseMatcherTestCase {
final String fourthWord = "tEsts";
and.addItem(new WordItem(fourthWord));
and.addItem(new WordItem("noiseafter"));
- List<?> matches=matcher.matchPhrases(and);
+ List<?> matches = matcher.matchPhrases(and);
assertNotNull(matches);
- assertEquals(1,matches.size());
- PhraseMatcher.Phrase match=(PhraseMatcher.Phrase)matches.get(0);
- assertEquals(4,match.getLength());
- assertEquals("",match.getData());
- assertEquals(and,match.getOwner());
- assertEquals(1,match.getStartIndex());
- PhraseMatcher.Phrase.MatchIterator i=match.itemIterator();
- assertEquals(new WordItem(firstWord),i.next());
- assertEquals("this",i.getReplace());
- assertEquals(new WordItem(secondWord),i.next());
- assertEquals(null,i.getReplace());
- assertEquals(new WordItem(thirdWord),i.next());
- assertEquals(null,i.getReplace());
- assertEquals(new WordItem(fourthWord),i.next());
- assertEquals("test",i.getReplace());
+ assertEquals(1, matches.size());
+ PhraseMatcher.Phrase match = (PhraseMatcher.Phrase) matches.get(0);
+ assertEquals(4, match.getLength());
+ assertEquals("", match.getData());
+ assertEquals(and, match.getOwner());
+ assertEquals(1, match.getStartIndex());
+ PhraseMatcher.Phrase.MatchIterator i = match.itemIterator();
+ assertEquals(new WordItem(firstWord), i.next());
+ assertEquals("this", i.getReplace());
+ assertEquals(new WordItem(secondWord), i.next());
+ assertNull(i.getReplace());
+ assertEquals(new WordItem(thirdWord), i.next());
+ assertNull(i.getReplace());
+ assertEquals(new WordItem(fourthWord), i.next());
+ assertEquals("test", i.getReplace());
assertFalse(i.hasNext());
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/PhrasingSearcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/PhrasingSearcherTestCase.java
index 8f2ae910d1b..9eca9a5fed8 100644
--- a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/PhrasingSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/PhrasingSearcherTestCase.java
@@ -11,10 +11,10 @@ import com.yahoo.prelude.query.WordItem;
import com.yahoo.prelude.querytransform.PhrasingSearcher;
import com.yahoo.search.Searcher;
import com.yahoo.search.searchchain.Execution;
-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 phrasing stuff
@@ -25,104 +25,104 @@ import static org.junit.Assert.assertTrue;
public class PhrasingSearcherTestCase {
@Test
- public void testTotalPhrasing() {
- Searcher searcher=
- new PhrasingSearcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
-
- Query query=new Query();
- AndItem andItem=new AndItem();
- andItem.addItem(new WordItem("tudor","someindex"));
- andItem.addItem(new WordItem("vidor","someindex"));
+ void testTotalPhrasing() {
+ Searcher searcher =
+ new PhrasingSearcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
+
+ Query query = new Query();
+ AndItem andItem = new AndItem();
+ andItem.addItem(new WordItem("tudor", "someindex"));
+ andItem.addItem(new WordItem("vidor", "someindex"));
query.getModel().getQueryTree().setRoot(andItem);
new Execution(searcher, Execution.Context.createContextStub()).search(query);
- Item item=((CompositeItem) query.getModel().getQueryTree().getRoot()).getItem(0);
+ Item item = ((CompositeItem) query.getModel().getQueryTree().getRoot()).getItem(0);
assertTrue(item instanceof PhraseItem);
- PhraseItem phrase=(PhraseItem)item;
- assertEquals(2,phrase.getItemCount());
- assertEquals("tudor",phrase.getWordItem(0).getWord());
- assertEquals("vidor",phrase.getWordItem(1).getWord());
- assertEquals("someindex",phrase.getIndexName());
+ PhraseItem phrase = (PhraseItem) item;
+ assertEquals(2, phrase.getItemCount());
+ assertEquals("tudor", phrase.getWordItem(0).getWord());
+ assertEquals("vidor", phrase.getWordItem(1).getWord());
+ assertEquals("someindex", phrase.getIndexName());
}
@Test
- public void testPartialPhrasing() {
- Searcher searcher=
- new PhrasingSearcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
+ void testPartialPhrasing() {
+ Searcher searcher =
+ new PhrasingSearcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
- Query query=new Query("?query=void%20tudor%20vidor%20kanoo");
+ Query query = new Query("?query=void%20tudor%20vidor%20kanoo");
new Execution(searcher, Execution.Context.createContextStub()).search(query);
- CompositeItem item=(CompositeItem) query.getModel().getQueryTree().getRoot();
- assertEquals("void",((WordItem)item.getItem(0)).getWord());
- assertEquals("kanoo",((WordItem)item.getItem(2)).getWord());
-
- PhraseItem phrase=(PhraseItem)item.getItem(1);
- assertEquals(2,phrase.getItemCount());
- assertEquals("tudor",phrase.getWordItem(0).getWord());
- assertEquals("vidor",phrase.getWordItem(1).getWord());
+ CompositeItem item = (CompositeItem) query.getModel().getQueryTree().getRoot();
+ assertEquals("void", ((WordItem) item.getItem(0)).getWord());
+ assertEquals("kanoo", ((WordItem) item.getItem(2)).getWord());
+
+ PhraseItem phrase = (PhraseItem) item.getItem(1);
+ assertEquals(2, phrase.getItemCount());
+ assertEquals("tudor", phrase.getWordItem(0).getWord());
+ assertEquals("vidor", phrase.getWordItem(1).getWord());
}
@Test
- public void testPartialPhrasingSuggestOnly() {
- Searcher searcher=
- new PhrasingSearcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
+ void testPartialPhrasingSuggestOnly() {
+ Searcher searcher =
+ new PhrasingSearcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
- Query query=new Query("?query=void%20tudor%20vidor%20kanoo&suggestonly=true");
+ Query query = new Query("?query=void%20tudor%20vidor%20kanoo&suggestonly=true");
new Execution(searcher, Execution.Context.createContextStub()).search(query);
- CompositeItem item=(CompositeItem) query.getModel().getQueryTree().getRoot();
- assertEquals("void", ((WordItem)item.getItem(0)).getWord());
- assertEquals("tudor",((WordItem)item.getItem(1)).getWord());
- assertEquals("vidor",((WordItem)item.getItem(2)).getWord());
- assertEquals("kanoo",((WordItem)item.getItem(3)).getWord());
+ CompositeItem item = (CompositeItem) query.getModel().getQueryTree().getRoot();
+ assertEquals("void", ((WordItem) item.getItem(0)).getWord());
+ assertEquals("tudor", ((WordItem) item.getItem(1)).getWord());
+ assertEquals("vidor", ((WordItem) item.getItem(2)).getWord());
+ assertEquals("kanoo", ((WordItem) item.getItem(3)).getWord());
}
@Test
- public void testNoPhrasingIfDifferentIndices() {
- Searcher searcher=
- new PhrasingSearcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
-
- Query query=new Query();
- AndItem andItem=new AndItem();
- andItem.addItem(new WordItem("tudor","someindex"));
- andItem.addItem(new WordItem("vidor","anotherindex"));
+ void testNoPhrasingIfDifferentIndices() {
+ Searcher searcher =
+ new PhrasingSearcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
+
+ Query query = new Query();
+ AndItem andItem = new AndItem();
+ andItem.addItem(new WordItem("tudor", "someindex"));
+ andItem.addItem(new WordItem("vidor", "anotherindex"));
query.getModel().getQueryTree().setRoot(andItem);
new Execution(searcher, Execution.Context.createContextStub()).search(query);
- CompositeItem item=(CompositeItem) query.getModel().getQueryTree().getRoot();
+ CompositeItem item = (CompositeItem) query.getModel().getQueryTree().getRoot();
assertTrue(item.getItem(0) instanceof WordItem);
- WordItem word=(WordItem)item.getItem(0);
- assertEquals("tudor",word.getWord());
+ WordItem word = (WordItem) item.getItem(0);
+ assertEquals("tudor", word.getWord());
assertTrue(item.getItem(1) instanceof WordItem);
- word=(WordItem)item.getItem(1);
- assertEquals("vidor",word.getWord());
+ word = (WordItem) item.getItem(1);
+ assertEquals("vidor", word.getWord());
}
@Test
- public void testMultiplePhrases() {
- Searcher searcher=
- new PhrasingSearcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
-
- Query query=new Query();
- AndItem andItem=new AndItem();
- andItem.addItem(new WordItem("tudor","someindex"));
- andItem.addItem(new WordItem("tudor","someindex"));
- andItem.addItem(new WordItem("vidor","someindex"));
- andItem.addItem(new WordItem("vidor","someindex"));
-
- OrItem orItem=new OrItem();
+ void testMultiplePhrases() {
+ Searcher searcher =
+ new PhrasingSearcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
+
+ Query query = new Query();
+ AndItem andItem = new AndItem();
+ andItem.addItem(new WordItem("tudor", "someindex"));
+ andItem.addItem(new WordItem("tudor", "someindex"));
+ andItem.addItem(new WordItem("vidor", "someindex"));
+ andItem.addItem(new WordItem("vidor", "someindex"));
+
+ OrItem orItem = new OrItem();
andItem.addItem(orItem);
orItem.addItem(new WordItem("tudor"));
- AndItem andItem2=new AndItem();
- andItem2.addItem(new WordItem("this","anotherindex"));
- andItem2.addItem(new WordItem("is","anotherindex"));
- andItem2.addItem(new WordItem("a","anotherindex"));
- andItem2.addItem(new WordItem("test","anotherindex"));
- andItem2.addItem(new WordItem("tudor","anotherindex"));
- andItem2.addItem(new WordItem("vidor","anotherindex"));
+ AndItem andItem2 = new AndItem();
+ andItem2.addItem(new WordItem("this", "anotherindex"));
+ andItem2.addItem(new WordItem("is", "anotherindex"));
+ andItem2.addItem(new WordItem("a", "anotherindex"));
+ andItem2.addItem(new WordItem("test", "anotherindex"));
+ andItem2.addItem(new WordItem("tudor", "anotherindex"));
+ andItem2.addItem(new WordItem("vidor", "anotherindex"));
orItem.addItem(andItem2);
orItem.addItem(new WordItem("vidor"));
@@ -134,12 +134,12 @@ public class PhrasingSearcherTestCase {
}
@Test
- public void testNoDetection() {
- Searcher searcher=
- new PhrasingSearcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
+ void testNoDetection() {
+ Searcher searcher =
+ new PhrasingSearcher("src/test/java/com/yahoo/prelude/querytransform/test/test-fsa.fsa");
- Query query=new Query();
- AndItem andItem=new AndItem();
+ Query query = new Query();
+ AndItem andItem = new AndItem();
andItem.addItem(new WordItem("no"));
andItem.addItem(new WordItem("such"));
andItem.addItem(new WordItem("phrase"));
@@ -152,11 +152,11 @@ public class PhrasingSearcherTestCase {
}
@Test
- public void testNoFileNoChange() {
+ void testNoFileNoChange() {
Searcher searcher = new PhrasingSearcher("");
- Query query=new Query();
- AndItem andItem=new AndItem();
+ Query query = new Query();
+ AndItem andItem = new AndItem();
andItem.addItem(new WordItem("no", "anindex"));
andItem.addItem(new WordItem("such", "anindex"));
andItem.addItem(new WordItem("phrase", "indexo"));
diff --git a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/QueryRewriteTestCase.java b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/QueryRewriteTestCase.java
index b8c5244fb98..16bfd5f315e 100644
--- a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/QueryRewriteTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/QueryRewriteTestCase.java
@@ -13,11 +13,9 @@ import com.yahoo.search.Query;
import com.yahoo.search.Result;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.test.QueryTestCase;
-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.*;
/**
* @author baldersheim
@@ -25,7 +23,7 @@ import static org.junit.Assert.assertTrue;
public class QueryRewriteTestCase {
@Test
- public void testOptimizeByRestrict() {
+ void testOptimizeByRestrict() {
Query query = new Query("?query=sddocname:music");
query.getModel().setRestrict("music");
QueryRewrite.optimizeByRestrict(query);
@@ -33,7 +31,7 @@ public class QueryRewriteTestCase {
}
@Test
- public void requireThatOptimizeByRestrictSimplifiesORItemsThatHaveFullRecallAndDontImpactRank() {
+ void requireThatOptimizeByRestrictSimplifiesORItemsThatHaveFullRecallAndDontImpactRank() {
assertRewritten("sddocname:foo OR sddocname:bar OR sddocname:baz", "foo", "sddocname:foo");
assertRewritten("sddocname:foo OR sddocname:bar OR sddocname:baz", "bar", "sddocname:bar");
assertRewritten("sddocname:foo OR sddocname:bar OR sddocname:baz", "baz", "sddocname:baz");
@@ -48,16 +46,16 @@ public class QueryRewriteTestCase {
}
@Test
- public void testRestrictRewriteDoesNotRemoveRankContributingTerms() {
+ void testRestrictRewriteDoesNotRemoveRankContributingTerms() {
Query query = query("sddocname:per OR foo OR bar", "per");
assertRewritten(query, "OR sddocname:per foo bar");
- ((OrItem)query.getModel().getQueryTree().getRoot()).getItem(2).setRanked(false); // set 'bar' unranked
+ ((OrItem) query.getModel().getQueryTree().getRoot()).getItem(2).setRanked(false); // set 'bar' unranked
assertRewritten(query, "OR sddocname:per foo");
assertRewritten("sddocname:per OR foo OR (bar AND fuz)", "per", "OR sddocname:per foo (AND bar fuz)");
}
@Test
- public void testRankContributingTermsAreNotRemovedOnFullRecall() {
+ void testRankContributingTermsAreNotRemovedOnFullRecall() {
Query query = new Query(QueryTestCase.httpEncode("?query=default:term1 OR default:term2 OR default:term3 OR sddocname:per&type=adv&recall=+id:1&restrict=per"));
RecallSearcher searcher = new RecallSearcher();
Result result = new Execution(searcher, Execution.Context.createContextStub()).search(query);
@@ -67,7 +65,7 @@ public class QueryRewriteTestCase {
}
@Test
- public void requireThatOptimizeByRestrictSimplifiesANDItemsThatHaveZeroRecall() {
+ void requireThatOptimizeByRestrictSimplifiesANDItemsThatHaveZeroRecall() {
assertRewritten("sddocname:foo AND bar AND baz", "cox", "NULL");
assertRewritten("foo AND sddocname:bar AND baz", "cox", "NULL");
assertRewritten("foo AND bar AND sddocname:baz", "cox", "NULL");
@@ -82,7 +80,7 @@ public class QueryRewriteTestCase {
}
@Test
- public void testRestrictRewrite() {
+ void testRestrictRewrite() {
assertRewritten("a AND b", "per", "AND a b");
assertRewritten("a OR b", "per", "OR a b");
assertRewritten("sddocname:per", "per", "sddocname:per");
@@ -94,9 +92,9 @@ public class QueryRewriteTestCase {
assertRewritten("sddocname:perder ANDNOT b", "per", "NULL");
assertRewritten("a ANDNOT sddocname:per a b", "per", "NULL");
}
-
+
@Test
- public void testRestrictRank() {
+ void testRestrictRank() {
assertRewritten("sddocname:per&filter=abc", "espen", "NULL");
assertRewritten("sddocname:per&filter=abc", "per", "RANK sddocname:per |abc");
assertRewritten("sddocname:per RANK bar", "per", "RANK sddocname:per bar");
@@ -119,7 +117,7 @@ public class QueryRewriteTestCase {
}
@Test
- public void assertAndNotMovedUp() {
+ void assertAndNotMovedUp() {
Query query = new Query();
NotItem not = new NotItem();
not.addPositiveItem(new WordItem("a"));
@@ -139,7 +137,7 @@ public class QueryRewriteTestCase {
}
@Test
- public void assertMultipleAndNotIsCollapsed() {
+ void assertMultipleAndNotIsCollapsed() {
Query query = new Query();
NotItem not1 = new NotItem();
not1.addPositiveItem(new WordItem("a"));
@@ -165,7 +163,7 @@ public class QueryRewriteTestCase {
AndItem a = (AndItem) n.getPositiveItem();
assertEquals(5, a.getItemCount());
assertEquals("na1", n.getItem(1).toString());
- assertEquals("na2",n.getItem(2).toString());
+ assertEquals("na2", n.getItem(2).toString());
assertEquals("nb", n.getItem(3).toString());
assertEquals("1", a.getItem(0).toString());
assertEquals("a", a.getItem(1).toString());
diff --git a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/RecallSearcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/RecallSearcherTestCase.java
index 409d01b5c46..e2d1555701c 100755
--- a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/RecallSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/RecallSearcherTestCase.java
@@ -16,12 +16,9 @@ import com.yahoo.prelude.query.NullItem;
import com.yahoo.prelude.query.WordItem;
import com.yahoo.prelude.querytransform.RecallSearcher;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-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 Simon Thoresen Hult
@@ -29,7 +26,7 @@ import static org.junit.Assert.fail;
public class RecallSearcherTestCase {
@Test
- public void testIgnoreEmptyProperty() {
+ void testIgnoreEmptyProperty() {
RecallSearcher searcher = new RecallSearcher();
Query query = new Query();
Result result = new Execution(searcher, Execution.Context.createContextStub()).search(query);
@@ -38,7 +35,7 @@ public class RecallSearcherTestCase {
}
@Test
- public void testDenyRankItems() {
+ void testDenyRankItems() {
RecallSearcher searcher = new RecallSearcher();
Query query = new Query("?recall=foo");
Result result = new Execution(searcher, Execution.Context.createContextStub()).search(query);
@@ -46,7 +43,7 @@ public class RecallSearcherTestCase {
}
@Test
- public void testParse() {
+ void testParse() {
List<String> empty = new ArrayList<>();
assertQueryTree("?query=foo", Arrays.asList("foo"), empty);
assertQueryTree("?recall=%2bfoo", empty, Arrays.asList("foo"));
diff --git a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/StemmingSearcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/StemmingSearcherTestCase.java
index 0d7b0caa65b..bcb243b4563 100644
--- a/container-search/src/test/java/com/yahoo/prelude/querytransform/test/StemmingSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/querytransform/test/StemmingSearcherTestCase.java
@@ -17,10 +17,10 @@ import com.yahoo.search.config.IndexInfoConfig;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.test.QueryTestCase;
-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;
/**
* @author <a href="mailto:mathiasm@yahoo-inc.com">Mathias M. Lidal</a>
@@ -32,13 +32,13 @@ public class StemmingSearcherTestCase {
"querytransform/test/", null);
@Test
- public void testStemOnlySomeTerms() {
+ void testStemOnlySomeTerms() {
assertStem("/search?query=Holes in CVS and Subversion nostem:Found",
- "WEAKAND(100) hole in cvs and subversion nostem:Found");
+ "WEAKAND(100) hole in cvs and subversion nostem:Found");
}
@Test
- public void testPhraseSegmentTransforms() {
+ void testPhraseSegmentTransforms() {
Query q1 = buildQueryWithSegmentPhrase();
executeStemming(q1);
assertEquals("AND a 'd e'", q1.getModel().getQueryTree().getRoot().toString());
@@ -61,65 +61,65 @@ public class StemmingSearcherTestCase {
}
@Test
- public void testPreserveConnectivityToPhrase() {
+ void testPreserveConnectivityToPhrase() {
Query q1 = buildQueryWithSegmentPhrase();
- CompositeItem r = (CompositeItem)q1.getModel().getQueryTree().getRoot();
- WordItem first = (WordItem)r.getItem(0);
- PhraseSegmentItem second = (PhraseSegmentItem)r.getItem(1);
+ CompositeItem r = (CompositeItem) q1.getModel().getQueryTree().getRoot();
+ WordItem first = (WordItem) r.getItem(0);
+ PhraseSegmentItem second = (PhraseSegmentItem) r.getItem(1);
first.setConnectivity(second, 1.0d);
executeStemming(q1);
assertEquals("AND a 'd e'", q1.getModel().getQueryTree().getRoot().toString());
- r = (CompositeItem)q1.getModel().getQueryTree().getRoot();
- first = (WordItem)r.getItem(0);
- second = (PhraseSegmentItem)r.getItem(1);
+ r = (CompositeItem) q1.getModel().getQueryTree().getRoot();
+ first = (WordItem) r.getItem(0);
+ second = (PhraseSegmentItem) r.getItem(1);
var origSecond = first.getConnectedItem();
- assertEquals("Connectivity incorrect.", second, first.getConnectedItem());
+ assertEquals(second, first.getConnectedItem(), "Connectivity incorrect.");
}
@Test
- public void testDontStemPrefixes() {
+ void testDontStemPrefixes() {
assertStem("/search?query=ist*&language=de", "WEAKAND(100) ist*");
}
@Test
- public void testStemming() {
+ void testStemming() {
Query query = new Query("/search?query=");
executeStemming(query);
assertTrue(query.getModel().getQueryTree().getRoot() instanceof NullItem);
}
@Test
- public void testNounStemming() {
+ void testNounStemming() {
assertStem("/search?query=noun:towers noun:tower noun:tow",
- "WEAKAND(100) noun:tower noun:tower noun:tow");
+ "WEAKAND(100) noun:tower noun:tower noun:tow");
assertStem("/search?query=notnoun:towers notnoun:tower notnoun:tow",
- "WEAKAND(100) notnoun:tower notnoun:tower notnoun:tow");
+ "WEAKAND(100) notnoun:tower notnoun:tower notnoun:tow");
}
@SuppressWarnings("deprecation")
@Test
- public void testEmptyIndexInfo() {
+ void testEmptyIndexInfo() {
String indexInfoConfigID = "file:src/test/java/com/yahoo/prelude/querytransform/test/emptyindexinfo.cfg";
ConfigGetter<IndexInfoConfig> getter = new ConfigGetter<>(IndexInfoConfig.class);
IndexInfoConfig config = getter.getConfig(indexInfoConfigID);
- IndexFacts indexFacts = new IndexFacts(new IndexModel(config, (QrSearchersConfig)null));
+ IndexFacts indexFacts = new IndexFacts(new IndexModel(config, (QrSearchersConfig) null));
Query q = new Query(QueryTestCase.httpEncode("?query=cars"));
new Execution(new Chain<Searcher>(new StemmingSearcher(linguistics)),
- Execution.Context.createContextStub(indexFacts, linguistics)).search(q);
+ Execution.Context.createContextStub(indexFacts, linguistics)).search(q);
assertEquals("WEAKAND(100) cars", q.getModel().getQueryTree().getRoot().toString());
}
@Test
- public void testLiteralBoost() {
+ void testLiteralBoost() {
Query q = new Query(QueryTestCase.httpEncode("/search?language=en&search=three"));
WordItem scratch = new WordItem("trees", true);
scratch.setStemmed(false);
q.getModel().getQueryTree().setRoot(scratch);
executeStemming(q);
- assertTrue("Expected a set of word alternatives as root.",
- q.getModel().getQueryTree().getRoot() instanceof WordAlternativesItem);
+ assertTrue(q.getModel().getQueryTree().getRoot() instanceof WordAlternativesItem,
+ "Expected a set of word alternatives as root.");
WordAlternativesItem w = (WordAlternativesItem) q.getModel().getQueryTree().getRoot();
boolean foundExpectedBaseForm = false;
for (WordAlternativesItem.Alternative a : w.getAlternatives()) {
@@ -128,16 +128,16 @@ public class StemmingSearcherTestCase {
foundExpectedBaseForm = true;
}
}
- assertTrue("Did not find original word form in query.", foundExpectedBaseForm);
+ assertTrue(foundExpectedBaseForm, "Did not find original word form in query.");
}
@Test
- public void testMultipleStemming() {
+ void testMultipleStemming() {
Query q = new Query(QueryTestCase.httpEncode("/search?language=en&search=four&query=trees \"nouns girls\" flowers \"a verbs a\" girls&default-index=foobar"));
executeStemming(q);
- assertEquals("WEAKAND(100) WORD_ALTERNATIVES foobar:[ tree(0.7) trees(1.0) ] "+
- "foobar:\"noun girl\" WORD_ALTERNATIVES foobar:[ flower(0.7) flowers(1.0) ] "+
- "foobar:\"a verb a\" WORD_ALTERNATIVES foobar:[ girl(0.7) girls(1.0) ]", q.getModel().getQueryTree().getRoot().toString());
+ assertEquals("WEAKAND(100) WORD_ALTERNATIVES foobar:[ tree(0.7) trees(1.0) ] " +
+ "foobar:\"noun girl\" WORD_ALTERNATIVES foobar:[ flower(0.7) flowers(1.0) ] " +
+ "foobar:\"a verb a\" WORD_ALTERNATIVES foobar:[ girl(0.7) girls(1.0) ]", q.getModel().getQueryTree().getRoot().toString());
}
private Execution.Context newExecutionContext() {
diff --git a/container-search/src/test/java/com/yahoo/prelude/searcher/test/BlendingSearcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/searcher/test/BlendingSearcherTestCase.java
index 4fffc450e74..156a0dcbb3e 100644
--- a/container-search/src/test/java/com/yahoo/prelude/searcher/test/BlendingSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/searcher/test/BlendingSearcherTestCase.java
@@ -31,12 +31,9 @@ import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.searchchain.SearchChain;
import com.yahoo.search.searchchain.SearchChainRegistry;
import com.yahoo.search.searchchain.testutil.DocumentSourceSearcher;
-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.*;
/**
* Tests the BlendingSearcher class
@@ -125,7 +122,7 @@ public class BlendingSearcherTestCase {
}
@Test
- public void testitTwoPhase() {
+ void testitTwoPhase() {
DocumentSourceSearcher chain1 = new DocumentSourceSearcher();
DocumentSourceSearcher chain2 = new DocumentSourceSearcher();
DocumentSourceSearcher chain3 = new DocumentSourceSearcher();
@@ -137,27 +134,63 @@ public class BlendingSearcherTestCase {
Result r3 = new Result(q);
r1.setTotalHitCount(13);
- r1.hits().add(new Hit("http://host1.com", 101){{setSource("one");}});
- r1.hits().add(new Hit("http://host2.com", 102){{setSource("one");}});
- r1.hits().add(new Hit("http://host3.com", 103){{setSource("one");}});
+ r1.hits().add(new Hit("http://host1.com", 101){
+ {
+ setSource("one");
+ }
+ });
+ r1.hits().add(new Hit("http://host2.com", 102){
+ {
+ setSource("one");
+ }
+ });
+ r1.hits().add(new Hit("http://host3.com", 103){
+ {
+ setSource("one");
+ }
+ });
chain1.addResult(q, r1);
r2.setTotalHitCount(17);
- r2.hits().add(new Hit("http://host1.com", 101){{setSource("two");}});
- r2.hits().add(new Hit("http://host2.com", 102){{setSource("two");}});
- r2.hits().add(new Hit("http://host4.com", 104){{setSource("two");}});
+ r2.hits().add(new Hit("http://host1.com", 101){
+ {
+ setSource("two");
+ }
+ });
+ r2.hits().add(new Hit("http://host2.com", 102){
+ {
+ setSource("two");
+ }
+ });
+ r2.hits().add(new Hit("http://host4.com", 104){
+ {
+ setSource("two");
+ }
+ });
chain2.addResult(q, r2);
r3.setTotalHitCount(37);
- r3.hits().add(new Hit("http://host5.com", 100){{setSource("three");}});
- r3.hits().add(new Hit("http://host6.com", 106){{setSource("three");}});
- r3.hits().add(new Hit("http://host7.com", 105){{setSource("three");}});
+ r3.hits().add(new Hit("http://host5.com", 100){
+ {
+ setSource("three");
+ }
+ });
+ r3.hits().add(new Hit("http://host6.com", 106){
+ {
+ setSource("three");
+ }
+ });
+ r3.hits().add(new Hit("http://host7.com", 105){
+ {
+ setSource("three");
+ }
+ });
chain3.addResult(q, r3);
BlendingSearcherWrapper blender1 = new BlendingSearcherWrapper();
blender1.addSource("one", chain1);
blender1.initialize();
- q.setWindow( 0, 10);
+ q.setWindow(0, 10);
Result br1 = new Execution(blender1, Execution.Context.createContextStub()).search(q);
assertEquals(3, br1.getHitCount());
assertEquals(13, br1.getTotalHitCount());
@@ -167,7 +200,7 @@ public class BlendingSearcherTestCase {
blender2.addSource("two", chain1);
blender2.addSource("three", chain2);
blender2.initialize();
- q.setWindow( 0, 10);
+ q.setWindow(0, 10);
Result br2 = new Execution(blender2, Execution.Context.createContextStub()).search(q);
assertEquals(6, br2.getHitCount());
assertEquals(30, br2.getTotalHitCount());
@@ -178,28 +211,28 @@ public class BlendingSearcherTestCase {
blender3.addSource("five", chain2);
blender3.addSource("six", chain3);
blender3.initialize();
- q.setWindow( 0, 10);
+ q.setWindow(0, 10);
Result br3 = new Execution(blender3, Execution.Context.createContextStub()).search(q);
assertEquals(9, br3.getHitCount());
assertEquals(67, br3.getTotalHitCount());
assertEquals("http://host6.com/", br3.hits().get(0).getId().toString());
- q.setWindow( 0, 10);
+ q.setWindow(0, 10);
Result br4 = new Execution(blender3, Execution.Context.createContextStub()).search(q);
assertEquals(9, br4.getHitCount());
assertEquals("http://host6.com/", br4.hits().get(0).getId().toString());
- q.setWindow( 3, 10);
+ q.setWindow(3, 10);
Result br5 = new Execution(blender3, Execution.Context.createContextStub()).search(q);
assertEquals(6, br5.getHitCount());
assertEquals("http://host3.com/", br5.hits().get(0).getId().toString());
- q.setWindow( 3, 10);
+ q.setWindow(3, 10);
br5 = new Execution(blender3, Execution.Context.createContextStub()).search(q);
assertEquals(6, br5.getHitCount());
assertEquals("http://host3.com/", br5.hits().get(0).getId().toString());
- q.setWindow( 3, 10);
+ q.setWindow(3, 10);
br5 = new Execution(blender3, Execution.Context.createContextStub()).search(q);
assertEquals(6, br5.getHitCount());
assertEquals("http://host3.com/", br5.hits().get(0).getId().toString());
@@ -207,7 +240,7 @@ public class BlendingSearcherTestCase {
}
@Test
- public void testMultipleBackendsWithDuplicateRemoval() {
+ void testMultipleBackendsWithDuplicateRemoval() {
DocumentSourceSearcher docSource1 = new DocumentSourceSearcher();
DocumentSourceSearcher docSource2 = new DocumentSourceSearcher();
Query q = new Query("/search?query=hannibal&search=a,b");
@@ -225,14 +258,14 @@ public class BlendingSearcherTestCase {
blender.addSource(new Chain<>("a", new FillSearcher(), docSource1));
blender.addSource(new Chain<>("b", new FillSearcher(), docSource2));
blender.initialize();
- q.setWindow( 0, 10);
+ q.setWindow(0, 10);
Result cr = new Execution(blender, Execution.Context.createContextStub()).search(q);
assertEquals(1, cr.getHitCount());
assertEquals(101, ((int) cr.hits().get(0).getRelevance().getScore()));
}
@Test
- public void testMultipleBackendsWithErrorMerging() {
+ void testMultipleBackendsWithErrorMerging() {
DocumentSourceSearcher docSource1 = new DocumentSourceSearcher();
DocumentSourceSearcher docSource2 = new DocumentSourceSearcher();
Query q = new Query("/search?query=hannibal&search=a,b");
@@ -249,25 +282,25 @@ public class BlendingSearcherTestCase {
blender.addSource(new Chain<>("a", new FillSearcher(), docSource1));
blender.addSource(new Chain<>("b", new FillSearcher(), docSource2));
blender.initialize();
- q.setWindow( 0, 10);
+ q.setWindow(0, 10);
Result cr = new Execution(blender, Execution.Context.createContextStub()).search(q);
assertEquals(2, cr.getHitCount());
assertEquals(1, cr.getConcreteHitCount());
com.yahoo.search.result.ErrorHit errorHit = cr.hits().getErrorHit();
Iterator errorIterator = errorHit.errorIterator();
List<String> errorList = Arrays.asList("Source 'a': No backends in service. Try later",
- "Source 'b': 2: Request too large");
+ "Source 'b': 2: Request too large");
String a = errorIterator.next().toString();
- assertTrue(a, errorList.contains(a));
+ assertTrue(errorList.contains(a), a);
String b = errorIterator.next().toString();
- assertTrue(a, errorList.contains(b));
+ assertTrue(errorList.contains(b), a);
assertFalse(errorIterator.hasNext());
assertEquals(102, ((int) cr.hits().get(1).getRelevance().getScore()));
assertEquals(com.yahoo.container.protect.Error.NO_BACKENDS_IN_SERVICE.code, cr.hits().getError().getCode());
}
@Test
- public void testBlendingWithSortSpec() {
+ void testBlendingWithSortSpec() {
DocumentSourceSearcher docSource1 = new DocumentSourceSearcher();
DocumentSourceSearcher docSource2 = new DocumentSourceSearcher();
@@ -310,7 +343,7 @@ public class BlendingSearcherTestCase {
blender.addSource(new Chain<>("a", new FillSearcher(), docSource1));
blender.addSource(new Chain<>("b", new FillSearcher(), docSource2));
blender.initialize();
- q.setWindow( 0, 10);
+ q.setWindow(0, 10);
Result br = new Execution(blender, Execution.Context.createContextStub()).search(q);
assertEquals(202, ((int) br.hits().get(0).getRelevance().getScore()));
assertEquals(103, ((int) br.hits().get(1).getRelevance().getScore()));
@@ -326,7 +359,7 @@ public class BlendingSearcherTestCase {
* But are we sure fsearch handles this case correctly?
*/
@Test
- public void testBlendingWithSortSpecAnd2Phase() {
+ void testBlendingWithSortSpecAnd2Phase() {
DocumentSourceSearcher docSource1 = new DocumentSourceSearcher();
DocumentSourceSearcher docSource2 = new DocumentSourceSearcher();
@@ -362,7 +395,7 @@ public class BlendingSearcherTestCase {
blender.addSource("chainedone", docSource1);
blender.addSource("chainedtwo", docSource2);
blender.initialize();
- q.setWindow( 0, 10);
+ q.setWindow(0, 10);
Result br = new Execution(blender, Execution.Context.createContextStub()).search(q);
assertEquals(202, ((int) br.hits().get(0).getRelevance().getScore()));
assertEquals(103, ((int) br.hits().get(1).getRelevance().getScore()));
@@ -400,7 +433,7 @@ public class BlendingSearcherTestCase {
}
@Test
- public void testOnlyFirstBackend() {
+ void testOnlyFirstBackend() {
BlendingSearcherWrapper searcher = setupFirstAndSecond();
Query query = new Query("/search?query=banana&search=first");
@@ -410,7 +443,7 @@ public class BlendingSearcherTestCase {
}
@Test
- public void testOnlySecondBackend() {
+ void testOnlySecondBackend() {
BlendingSearcherWrapper searcher = setupFirstAndSecond();
Query query = new Query("/search?query=banana&search=second");
@@ -421,7 +454,7 @@ public class BlendingSearcherTestCase {
}
@Test
- public void testBothBackendsExplicitly() {
+ void testBothBackendsExplicitly() {
BlendingSearcherWrapper searcher = setupFirstAndSecond();
Query query = new Query("/search?query=banana&search=first,second");
@@ -433,7 +466,7 @@ public class BlendingSearcherTestCase {
}
@Test
- public void testBothBackendsImplicitly() {
+ void testBothBackendsImplicitly() {
BlendingSearcherWrapper searcher = setupFirstAndSecond();
Query query = new Query("/search?query=banana");
@@ -445,7 +478,7 @@ public class BlendingSearcherTestCase {
}
@Test
- public void testNonexistingBackendCausesError() {
+ void testNonexistingBackendCausesError() {
BlendingSearcherWrapper searcher = setupFirstAndSecond();
Query query = new Query("/search?query=banana&search=nonesuch");
@@ -459,7 +492,7 @@ public class BlendingSearcherTestCase {
}
@Test
- public void testNonexistingBackendsCausesErrorOnFirst() {
+ void testNonexistingBackendsCausesErrorOnFirst() {
// Feel free to change to include all in the detail message...
BlendingSearcherWrapper searcher = setupFirstAndSecond();
Query query = new Query("/search?query=banana&search=nonesuch,orsuch");
@@ -471,11 +504,11 @@ public class BlendingSearcherTestCase {
assertEquals("Invalid query parameter", e.getMessage());
//TODO: Do not depend on sources order
assertEquals("4: Invalid query parameter: Could not resolve source ref 'nonesuch'. Could not resolve source ref 'orsuch'. Valid source refs are first, second.",
- e.toString());
+ e.toString());
}
@Test
- public void testExistingAndNonExistingBackendCausesBothErrorAndResult() {
+ void testExistingAndNonExistingBackendCausesBothErrorAndResult() {
BlendingSearcherWrapper searcher = setupFirstAndSecond();
Query query = new Query("/search?query=banana&search=first,nonesuch,second");
@@ -488,11 +521,11 @@ public class BlendingSearcherTestCase {
ErrorMessage e = result.hits().getError();
//TODO: Do not depend on sources order
assertEquals("Could not resolve source ref 'nonesuch'. Valid source refs are first, second.",
- e.getDetailedMessage());
+ e.getDetailedMessage());
}
@Test
- public void testBlendingFederationWithGrouping() {
+ void testBlendingFederationWithGrouping() {
DocumentSourceSearcher docSource1 = new DocumentSourceSearcher();
DocumentSourceSearcher docSource2 = new DocumentSourceSearcher();
@@ -528,22 +561,22 @@ public class BlendingSearcherTestCase {
blender.addSource(new Chain<>("a", new FillSearcher(), docSource1));
blender.addSource(new Chain<>("b", new FillSearcher(), docSource2));
blender.initialize();
- q.setWindow( 0, 10);
+ q.setWindow(0, 10);
Result result = new Execution(blender, Execution.Context.createContextStub()).search(q);
assertEquals(2, result.hits().size());
assertTrue(result.hits().get(0) instanceof RootGroup);
- RootGroup resultRoot1 = (RootGroup)result.hits().get(0);
+ RootGroup resultRoot1 = (RootGroup) result.hits().get(0);
assertEquals(1, resultRoot1.asList().size());
assertTrue(result.hits().get(1) instanceof RootGroup);
- RootGroup resultRoot2 = (RootGroup)result.hits().get(1);
+ RootGroup resultRoot2 = (RootGroup) result.hits().get(1);
assertEquals(2, resultRoot2.asList().size());
}
/** Multiple document types in the same cluster are returned without a top level group representing each */
@Test
- public void testBlendingMultipleDocumentTypesWithGrouping() {
+ void testBlendingMultipleDocumentTypesWithGrouping() {
DocumentSourceSearcher docSource = new DocumentSourceSearcher();
Query q = new Query("/search?query=test");
@@ -574,23 +607,23 @@ public class BlendingSearcherTestCase {
docSource.addResult(q, r);
Chain<Searcher> chain = new Chain<>("main",
- new FillSearcher(),
- new BlendingSearcher(ComponentId.fromString("test"), new QrSearchersConfig.Builder().build()),
- docSource);
- q.setWindow( 0, 10);
+ new FillSearcher(),
+ new BlendingSearcher(ComponentId.fromString("test"), new QrSearchersConfig.Builder().build()),
+ docSource);
+ q.setWindow(0, 10);
Result result = new Execution(chain, Execution.Context.createContextStub()).search(q);
assertEquals(3, result.hits().size());
assertTrue(result.hits().get(0) instanceof Group);
- Group resultSubGroup1 = (Group)result.hits().get(0);
+ Group resultSubGroup1 = (Group) result.hits().get(0);
assertEquals(4, resultSubGroup1.asList().size());
assertTrue(result.hits().get(1) instanceof Group);
- Group resultSubGroup2 = (Group)result.hits().get(1);
+ Group resultSubGroup2 = (Group) result.hits().get(1);
assertEquals(3, resultSubGroup2.asList().size());
assertTrue(result.hits().get(2) instanceof Group);
- Group resultSubGroup3 = (Group)result.hits().get(2);
+ Group resultSubGroup3 = (Group) result.hits().get(2);
assertEquals(2, resultSubGroup3.asList().size());
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/searcher/test/FieldCollapsingSearcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/searcher/test/FieldCollapsingSearcherTestCase.java
index de6a55354fd..4a2a34a64c2 100644
--- a/container-search/src/test/java/com/yahoo/prelude/searcher/test/FieldCollapsingSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/searcher/test/FieldCollapsingSearcherTestCase.java
@@ -21,18 +21,14 @@ import com.yahoo.search.result.HitGroup;
import com.yahoo.search.result.Relevance;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.searchchain.testutil.DocumentSourceSearcher;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-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.jupiter.api.Assertions.*;
/**
* Tests the FieldCollapsingSearcher class
@@ -42,7 +38,7 @@ import static org.junit.Assert.assertTrue;
public class FieldCollapsingSearcherTestCase {
@Test
- public void testFieldCollapsingWithoutHits() {
+ void testFieldCollapsingWithoutHits() {
// Set up
Map<Searcher, Searcher> chained = new HashMap<>();
@@ -59,7 +55,7 @@ public class FieldCollapsingSearcherTestCase {
}
@Test
- public void testFieldCollapsingWithoutHitsHugeOffset() {
+ void testFieldCollapsingWithoutHitsHugeOffset() {
Map<Searcher, Searcher> chained = new HashMap<>();
FieldCollapsingSearcher collapse = new FieldCollapsingSearcher("other");
@@ -75,7 +71,7 @@ public class FieldCollapsingSearcherTestCase {
}
@Test
- public void testFieldCollapsing() {
+ void testFieldCollapsing() {
Map<Searcher, Searcher> chained = new HashMap<>();
// Set up
@@ -89,7 +85,7 @@ public class FieldCollapsingSearcherTestCase {
// The searcher turns off collapsing further on in the chain
q.properties().set("collapse", "0");
Result r = new Result(q);
- r.hits().add(createHit("http://acme.org/a.html",10, 0));
+ r.hits().add(createHit("http://acme.org/a.html", 10, 0));
r.hits().add(createHit("http://acme.org/b.html", 9, 0));
r.hits().add(createHit("http://acme.org/c.html", 9, 1));
r.hits().add(createHit("http://acme.org/d.html", 8, 1));
@@ -106,14 +102,14 @@ public class FieldCollapsingSearcherTestCase {
assertEquals(4, r.getHitCount());
assertEquals(1, docsource.getQueryCount());
- assertHit("http://acme.org/a.html",10, 0, r.hits().get(0));
+ assertHit("http://acme.org/a.html", 10, 0, r.hits().get(0));
assertHit("http://acme.org/c.html", 9, 1, r.hits().get(1));
assertHit("http://acme.org/e.html", 8, 2, r.hits().get(2));
assertHit("http://acme.org/g.html", 7, 3, r.hits().get(3));
}
@Test
- public void testFieldCollapsingTwoPhase() {
+ void testFieldCollapsingTwoPhase() {
// Set up
Map<Searcher, Searcher> chained = new HashMap<>();
FieldCollapsingSearcher collapse = new FieldCollapsingSearcher("other");
@@ -125,7 +121,7 @@ public class FieldCollapsingSearcherTestCase {
// The searcher turns off collapsing further on in the chain
q.properties().set("collapse", "0");
Result r = new Result(q);
- r.hits().add(createHit("http://acme.org/a.html",10, 0));
+ r.hits().add(createHit("http://acme.org/a.html", 10, 0));
r.hits().add(createHit("http://acme.org/b.html", 9, 0));
r.hits().add(createHit("http://acme.org/c.html", 9, 1));
r.hits().add(createHit("http://acme.org/d.html", 8, 1));
@@ -142,14 +138,14 @@ public class FieldCollapsingSearcherTestCase {
assertEquals(4, r.getHitCount());
assertEquals(1, docsource.getQueryCount());
- assertHit("http://acme.org/a.html",10,0, r.hits().get(0));
- assertHit("http://acme.org/c.html", 9,1, r.hits().get(1));
- assertHit("http://acme.org/e.html", 8,2, r.hits().get(2));
- assertHit("http://acme.org/g.html", 7,3, r.hits().get(3));
+ assertHit("http://acme.org/a.html", 10, 0, r.hits().get(0));
+ assertHit("http://acme.org/c.html", 9, 1, r.hits().get(1));
+ assertHit("http://acme.org/e.html", 8, 2, r.hits().get(2));
+ assertHit("http://acme.org/g.html", 7, 3, r.hits().get(3));
}
@Test
- public void testNoCollapsingIfNotAskedTo() {
+ void testNoCollapsingIfNotAskedTo() {
// Set up
Map<Searcher, Searcher> chained = new HashMap<>();
FieldCollapsingSearcher collapse = new FieldCollapsingSearcher();
@@ -158,7 +154,7 @@ public class FieldCollapsingSearcherTestCase {
Query q = new Query("?query=test_collapse");
Result r = new Result(q);
- r.hits().add(createHit("http://acme.org/a.html",10, 0));
+ r.hits().add(createHit("http://acme.org/a.html", 10, 0));
r.hits().add(createHit("http://acme.org/b.html", 9, 0));
r.hits().add(createHit("http://acme.org/c.html", 9, 1));
r.hits().add(createHit("http://acme.org/d.html", 8, 1));
@@ -182,10 +178,10 @@ public class FieldCollapsingSearcherTestCase {
* an excessive number of backend requests
*/
@Test
- public void testCollapsingLargeCollection() {
+ void testCollapsingLargeCollection() {
// Set up
Map<Searcher, Searcher> chained = new HashMap<>();
- FieldCollapsingSearcher collapse = new FieldCollapsingSearcher(4,2.0,"amid");
+ FieldCollapsingSearcher collapse = new FieldCollapsingSearcher(4, 2.0, "amid");
DocumentSourceSearcher docsource = new DocumentSourceSearcher();
chained.put(collapse, docsource);
@@ -193,7 +189,7 @@ public class FieldCollapsingSearcherTestCase {
// The searcher turns off collapsing further on in the chain
q.properties().set("collapse", "0");
Result r = new Result(q);
- r.hits().add(createHit("http://acme.org/a.html",10, 0));
+ r.hits().add(createHit("http://acme.org/a.html", 10, 0));
r.hits().add(createHit("http://acme.org/b.html", 9, 0));
r.hits().add(createHit("http://acme.org/c.html", 9, 0));
r.hits().add(createHit("http://acme.org/d.html", 8, 0));
@@ -212,7 +208,7 @@ public class FieldCollapsingSearcherTestCase {
assertEquals(2, r.getHitCount());
assertEquals(2, docsource.getQueryCount());
- assertHit("http://acme.org/a.html",10, 0, r.hits().get(0));
+ assertHit("http://acme.org/a.html", 10, 0, r.hits().get(0));
assertHit("http://acme.org/i.html", 5, 1, r.hits().get(1));
// Next results
@@ -220,17 +216,17 @@ public class FieldCollapsingSearcherTestCase {
r = doSearch(collapse, q, 2, 2, chained);
assertEquals(1, r.getHitCount());
assertEquals(2, docsource.getQueryCount());
- assertHit("http://acme.org/j.html",4, 2, r.hits().get(0));
+ assertHit("http://acme.org/j.html", 4, 2, r.hits().get(0));
}
/**
* Tests collapsing of "messy" data
*/
@Test
- public void testCollapsingDispersedCollection() {
+ void testCollapsingDispersedCollection() {
// Set up
Map<Searcher, Searcher> chained = new HashMap<>();
- FieldCollapsingSearcher collapse = new FieldCollapsingSearcher(1,2.0,"amid");
+ FieldCollapsingSearcher collapse = new FieldCollapsingSearcher(1, 2.0, "amid");
DocumentSourceSearcher docsource = new DocumentSourceSearcher();
chained.put(collapse, docsource);
@@ -256,12 +252,12 @@ public class FieldCollapsingSearcherTestCase {
r = doSearch(collapse, q, 0, 3, chained);
assertEquals(2, r.getHitCount());
- assertHit("http://acme.org/a.html",10,1,r.hits().get(0));
- assertHit("http://acme.org/c.html",10,0,r.hits().get(1));
+ assertHit("http://acme.org/a.html", 10, 1, r.hits().get(0));
+ assertHit("http://acme.org/c.html", 10, 0, r.hits().get(1));
}
@Test
- public void testQueryTransformAndCollapsing() {
+ void testQueryTransformAndCollapsing() {
// Set up
Map<Searcher, Searcher> chained = new HashMap<>();
FieldCollapsingSearcher collapse = new FieldCollapsingSearcher("other");
@@ -277,14 +273,14 @@ public class FieldCollapsingSearcherTestCase {
// The searcher turns off collapsing further on in the chain
q.properties().set("collapse", "0");
Result r = new Result(q);
- r.hits().add(createHit("http://acme.org/a.html",10,0));
- r.hits().add(createHit("http://acme.org/b.html", 9,0));
- r.hits().add(createHit("http://acme.org/c.html", 9,0));
- r.hits().add(createHit("http://acme.org/d.html", 8,0));
- r.hits().add(createHit("http://acme.org/e.html", 8,0));
- r.hits().add(createHit("http://acme.org/f.html", 7,0));
- r.hits().add(createHit("http://acme.org/g.html", 7,0));
- r.hits().add(createHit("http://acme.org/h.html", 6,1));
+ r.hits().add(createHit("http://acme.org/a.html", 10, 0));
+ r.hits().add(createHit("http://acme.org/b.html", 9, 0));
+ r.hits().add(createHit("http://acme.org/c.html", 9, 0));
+ r.hits().add(createHit("http://acme.org/d.html", 8, 0));
+ r.hits().add(createHit("http://acme.org/e.html", 8, 0));
+ r.hits().add(createHit("http://acme.org/f.html", 7, 0));
+ r.hits().add(createHit("http://acme.org/g.html", 7, 0));
+ r.hits().add(createHit("http://acme.org/h.html", 6, 1));
r.setTotalHitCount(8);
docsource.addResult(q, r);
@@ -294,12 +290,12 @@ public class FieldCollapsingSearcherTestCase {
assertEquals(2, docsource.getQueryCount());
assertEquals(2, r.getHitCount());
- assertHit("http://acme.org/a.html",10, 0, r.hits().get(0));
+ assertHit("http://acme.org/a.html", 10, 0, r.hits().get(0));
assertHit("http://acme.org/h.html", 6, 1, r.hits().get(1));
}
@Test
- public void testFieldCollapsingTwoPhaseSelectSummary() {
+ void testFieldCollapsingTwoPhaseSelectSummary() {
// Set up
Map<Searcher, Searcher> chained = new HashMap<>();
FieldCollapsingSearcher collapse = new FieldCollapsingSearcher("other");
@@ -311,14 +307,14 @@ public class FieldCollapsingSearcherTestCase {
// The searcher turns off collapsing further on in the chain
q.properties().set("collapse", "0");
Result r = new Result(q);
- r.hits().add(createHit("http://acme.org/a.html",10,0));
- r.hits().add(createHit("http://acme.org/b.html", 9,0));
- r.hits().add(createHit("http://acme.org/c.html", 9,1));
- r.hits().add(createHit("http://acme.org/d.html", 8,1));
- r.hits().add(createHit("http://acme.org/e.html", 8,2));
- r.hits().add(createHit("http://acme.org/f.html", 7,2));
- r.hits().add(createHit("http://acme.org/g.html", 7,3));
- r.hits().add(createHit("http://acme.org/h.html", 6,3));
+ r.hits().add(createHit("http://acme.org/a.html", 10, 0));
+ r.hits().add(createHit("http://acme.org/b.html", 9, 0));
+ r.hits().add(createHit("http://acme.org/c.html", 9, 1));
+ r.hits().add(createHit("http://acme.org/d.html", 8, 1));
+ r.hits().add(createHit("http://acme.org/e.html", 8, 2));
+ r.hits().add(createHit("http://acme.org/f.html", 7, 2));
+ r.hits().add(createHit("http://acme.org/g.html", 7, 3));
+ r.hits().add(createHit("http://acme.org/h.html", 6, 3));
r.setTotalHitCount(8);
docsource.addResult(q, r);
@@ -329,7 +325,7 @@ public class FieldCollapsingSearcherTestCase {
assertEquals(4, r.getHitCount());
assertEquals(1, docsource.getQueryCount());
assertTrue(r.isFilled("placeholder"));
- assertHit("http://acme.org/a.html",10, 0, r.hits().get(0));
+ assertHit("http://acme.org/a.html", 10, 0, r.hits().get(0));
assertHit("http://acme.org/c.html", 9, 1, r.hits().get(1));
assertHit("http://acme.org/e.html", 8, 2, r.hits().get(2));
assertHit("http://acme.org/g.html", 7, 3, r.hits().get(3));
@@ -343,18 +339,18 @@ public class FieldCollapsingSearcherTestCase {
assertEquals(1, docsource.getQueryCount());
assertFalse(r.isFilled("placeholder"));
assertTrue(r.isFilled("short"));
- assertHit("http://acme.org/a.html",10, 0, r.hits().get(0));
+ assertHit("http://acme.org/a.html", 10, 0, r.hits().get(0));
assertHit("http://acme.org/c.html", 9, 1, r.hits().get(1));
assertHit("http://acme.org/e.html", 8, 2, r.hits().get(2));
assertHit("http://acme.org/g.html", 7, 3, r.hits().get(3));
}
@Test
- public void testFieldCollapsingWithGrouping() {
+ void testFieldCollapsingWithGrouping() {
// Set up
FieldCollapsingSearcher collapse = new FieldCollapsingSearcher("other");
DocumentSourceSearcher docsource = new DocumentSourceSearcher();
- Chain<Searcher> chain=new Chain<>(collapse,new AddAggregationStyleGroupingResultSearcher(),docsource);
+ Chain<Searcher> chain = new Chain<>(collapse, new AddAggregationStyleGroupingResultSearcher(), docsource);
// Caveat: Collapse is set to false, because that's what the
// collapser asks for
@@ -362,7 +358,7 @@ public class FieldCollapsingSearcherTestCase {
// The searcher turns off collapsing further on in the chain
q.properties().set("collapse", "0");
Result r = new Result(q);
- r.hits().add(createHit("http://acme.org/a.html",10, 0));
+ r.hits().add(createHit("http://acme.org/a.html", 10, 0));
r.hits().add(createHit("http://acme.org/b.html", 9, 0));
r.hits().add(createHit("http://acme.org/c.html", 9, 1));
r.hits().add(createHit("http://acme.org/d.html", 8, 1));
@@ -380,7 +376,7 @@ public class FieldCollapsingSearcherTestCase {
// Assert that the regular hits are collapsed
assertEquals(4 + 1, result.getHitCount());
assertEquals(1, docsource.getQueryCount());
- assertHit("http://acme.org/a.html",10, 0, result.hits().get(0));
+ assertHit("http://acme.org/a.html", 10, 0, result.hits().get(0));
assertHit("http://acme.org/c.html", 9, 1, result.hits().get(1));
assertHit("http://acme.org/e.html", 8, 2, result.hits().get(2));
assertHit("http://acme.org/g.html", 7, 3, result.hits().get(3));
@@ -388,12 +384,12 @@ public class FieldCollapsingSearcherTestCase {
// Assert that the aggregation group hierarchy is left intact
HitGroup root = getFirstGroupIn(result.hits());
assertNotNull(root);
- assertEquals("group:root:",root.getId().stringValue().substring(0, 11)); // The id ends by a global counter currently
+ assertEquals("group:root:", root.getId().stringValue().substring(0, 11)); // The id ends by a global counter currently
assertEquals(1, root.size());
- HitGroup groupList = (GroupList)root.get("grouplist:g1");
+ HitGroup groupList = (GroupList) root.get("grouplist:g1");
assertNotNull(groupList);
assertEquals(1, groupList.size());
- HitGroup group = (HitGroup)groupList.get("group:long:37");
+ HitGroup group = (HitGroup) groupList.get("group:long:37");
assertNotNull(group);
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/searcher/test/JSONDebugSearcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/searcher/test/JSONDebugSearcherTestCase.java
index 6a230da4950..a10ecfb99e0 100644
--- a/container-search/src/test/java/com/yahoo/prelude/searcher/test/JSONDebugSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/searcher/test/JSONDebugSearcherTestCase.java
@@ -14,10 +14,10 @@ import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.searchchain.testutil.DocumentSourceSearcher;
import com.yahoo.yolean.trace.TraceNode;
import com.yahoo.yolean.trace.TraceVisitor;
-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;
/**
* Visit the trace and check JSON payload is stored there when requested.
@@ -30,7 +30,7 @@ public class JSONDebugSearcherTestCase {
private static final String DUMPJSON = "?query=1&dumpjson=jsonfield&tracelevel=6";
@Test
- public void test() {
+ void test() {
Chain<Searcher> searchChain = makeSearchChain("{1: 2}", new JSONDebugSearcher());
Execution e = new Execution(searchChain, Execution.Context.createContextStub());
e.search(new Query(NODUMPJSON));
diff --git a/container-search/src/test/java/com/yahoo/prelude/searcher/test/JuniperSearcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/searcher/test/JuniperSearcherTestCase.java
index 706d217269b..bd72ed9fd08 100644
--- a/container-search/src/test/java/com/yahoo/prelude/searcher/test/JuniperSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/searcher/test/JuniperSearcherTestCase.java
@@ -1,9 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.searcher.test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.*;
import com.google.common.collect.ImmutableList;
import com.yahoo.component.ComponentId;
@@ -22,7 +20,7 @@ import com.yahoo.search.result.Relevance;
import com.yahoo.search.searchchain.testutil.DocumentSourceSearcher;
import com.yahoo.prelude.searcher.JuniperSearcher;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collection;
import java.util.LinkedHashMap;
@@ -113,19 +111,19 @@ public class JuniperSearcherTestCase {
}
@Test
- public void testFieldRewriting() {
+ void testFieldRewriting() {
Result check = createResult("\u001FXYZ\u001F\u001EQWE\u001FJKL\u001FASD&");
assertEquals(1, check.getHitCount());
assertEquals("<hi>XYZ</hi><sep />QWE<hi>JKL</hi>ASD&",
- check.hits().get(0).getField("dynteaser").toString());
+ check.hits().get(0).getField("dynteaser").toString());
check = createResult("a&b&c");
assertEquals(1, check.getHitCount());
assertEquals("a&b&c",
- check.hits().get(0).getField("dynteaser").toString());
+ check.hits().get(0).getField("dynteaser").toString());
}
@Test
- public void testNoRewritingDueToSearchDefinition() {
+ void testNoRewritingDueToSearchDefinition() {
Result check = createResult("two", "\u001FXYZ\u001F\u001EQWE\u001FJKL\u001FASD&");
assertEquals(1, check.getHitCount());
assertEquals("\u001FXYZ\u001F\u001EQWE\u001FJKL\u001FASD&",
@@ -137,20 +135,20 @@ public class JuniperSearcherTestCase {
}
@Test
- public void testBoldingEquals() {
+ void testBoldingEquals() {
assertNotEquals(new Query("?query=12"), new Query("?query=12&bolding=false"));
}
@Test
- public void testUnboldedRewriting() {
+ void testUnboldedRewriting() {
Result check = createResult("one", "\u001FXYZ\u001F\u001EQWE\u001FJKL\u001FASD&", false);
assertEquals(1, check.getHitCount());
assertEquals("XYZ...QWEJKLASD&",
- check.hits().get(0).getField("dynteaser").toString());
+ check.hits().get(0).getField("dynteaser").toString());
}
@Test
- public void testAnnotatedSummaryFields() {
+ void testAnnotatedSummaryFields() {
Result check = createResult("\uFFF9Feeding\uFFFAfeed\uFFFB \u001F\uFFF9documents\uFFFAdocument\uFFFB\u001F into Vespa \uFFF9is\uFFFAbe\u001Eincrement of a set of \u001F\uFFF9documents\uFFFAdocument\uFFFB\u001F fed into Vespa \uFFF9is\u001Efloat in XML when \u001Fdocument\u001F attribute \uFFF9is\uFFFAbe\uFFFB int\u001E");
assertEquals(1, check.getHitCount());
assertEquals("Feeding <hi>documents</hi> into Vespa is<sep />increment of a set of <hi>documents</hi> fed into Vespa <sep />float in XML when <hi>document</hi> attribute is int<sep />", check.hits().get(0).getField("dynteaser").toString());
@@ -185,7 +183,7 @@ public class JuniperSearcherTestCase {
}
@Test
- public void testThatIncompleteAnnotationWithHighlightIsIgnored() {
+ void testThatIncompleteAnnotationWithHighlightIsIgnored() {
// Look at bug 5707026 for details.
{
Result check = createResult("of\u001e\u001fyahoo\u001f\uFFFB! \uFFF9Angels\uFFFAangels\uFFFB \uFFF9\u001fYahoo\u001f\uFFFA\u001fyahoo\u001f\uFFFB! \uFFF9Angles\uFFFAangels\uFFFB \uFFF9is\uFFFAbe\u001e");
@@ -202,7 +200,7 @@ public class JuniperSearcherTestCase {
}
@Test
- public void testThatIncompleteAnnotationWithHighlightAtTheBeginningIsIgnored() {
+ void testThatIncompleteAnnotationWithHighlightAtTheBeginningIsIgnored() {
{
Result check = createResult("\u001e\u001fIncomplete\uFFFAincomplete\uFFFB\u001f \uFFF9Original\uFFFAstemmed\uFFFB\u001e");
assertEquals(1, check.getHitCount());
@@ -221,7 +219,7 @@ public class JuniperSearcherTestCase {
}
@Test
- public void testThatIncompleteAnnotationWithHighlightAtTheEndIsIgnored() {
+ void testThatIncompleteAnnotationWithHighlightAtTheEndIsIgnored() {
{
Result check = createResult("\u001e\uFFF9Original\uFFFAstemmed\uFFFB \u001f\uFFF9Incomplete\uFFFAincomplete\u001f\u001e");
assertEquals(1, check.getHitCount());
@@ -240,7 +238,7 @@ public class JuniperSearcherTestCase {
}
@Test
- public void testExplicitTwoPhase() {
+ void testExplicitTwoPhase() {
Chain<Searcher> searchChain = createSearchChain("one", "\u001e\uFFFAbe\uFFFB within the set of \u001f\uFFF9documents\uFFFAdocument\uFFFB\u001f. \uFFF9phrases\uFFFA\u001E\uFFFA\uFFFB to as a remedy). Each of the \u001fdocument\u001f \uFFF9fields\uFFFAfield\uFFFB in a catalog can be \uFFF9\u001e");
Query q = new Query("?query=12");
Result check = createExecution(searchChain).search(q);
@@ -252,7 +250,7 @@ public class JuniperSearcherTestCase {
}
@Test
- public void testCompoundWordsBolding() {
+ void testCompoundWordsBolding() {
Result check = createResult("\u001eTest \u001fkommunikations\u001f\u001ffehler\u001f");
assertEquals(1, check.getHitCount());
assertEquals("<sep />Test <hi>kommunikationsfehler</hi>", check.hits().get(0).getField("dynteaser").toString());
diff --git a/container-search/src/test/java/com/yahoo/prelude/searcher/test/MultipleResultsTestCase.java b/container-search/src/test/java/com/yahoo/prelude/searcher/test/MultipleResultsTestCase.java
index 0a250c9b973..0024bf9cd66 100644
--- a/container-search/src/test/java/com/yahoo/prelude/searcher/test/MultipleResultsTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/searcher/test/MultipleResultsTestCase.java
@@ -11,10 +11,10 @@ import com.yahoo.search.result.Hit;
import com.yahoo.search.result.HitGroup;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.searchchain.testutil.DocumentSourceSearcher;
-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;
/**
* Test of MultipleResultsSearcher
@@ -30,7 +30,7 @@ public class MultipleResultsTestCase {
private Chain<Searcher> chain;
- @Before
+ @BeforeEach
public void setUp() {
docSource=new DocumentSourceSearcher();
searcher=new MultipleResultsSearcher();
@@ -38,11 +38,11 @@ public class MultipleResultsTestCase {
}
@Test
- public void testRetrieveHeterogenousHits() {
+ void testRetrieveHeterogenousHits() {
Query query = createQuery();
Result originalResult = new Result(query);
- int n1 = 15, n2 = 25, n3 = 25, n4=25;
+ int n1 = 15, n2 = 25, n3 = 25, n4 = 25;
addHits(originalResult, "others", n1);
addHits(originalResult, "music", n2);
addHits(originalResult, "movies", n3);
@@ -51,23 +51,23 @@ public class MultipleResultsTestCase {
docSource.addResult(query, originalResult);
- query.setWindow(0,30);
+ query.setWindow(0, 30);
Result result = new Execution(chain, Execution.Context.createContextStub()).search(query);
- HitGroup musicGroup = (HitGroup)result.hits().get("music");
- HitGroup moviesGroup = (HitGroup)result.hits().get("movies");
+ HitGroup musicGroup = (HitGroup) result.hits().get("music");
+ HitGroup moviesGroup = (HitGroup) result.hits().get("movies");
- assertEquals( 15, musicGroup.size() );
- assertEquals( 15, moviesGroup.size() );
- assertEquals( 3, docSource.getQueryCount() );
+ assertEquals(15, musicGroup.size());
+ assertEquals(15, moviesGroup.size());
+ assertEquals(3, docSource.getQueryCount());
}
@Test
- public void testRetrieveHitsForGroup() {
+ void testRetrieveHitsForGroup() {
Query query = createQuery();
Result originalResult = new Result(query);
- int n1 = 200, n2=30;
+ int n1 = 200, n2 = 30;
addHits(originalResult, "music", n1, 1000);
addHits(originalResult, "movies", n2, 100);
originalResult.setTotalHitCount(n1 + n2);
@@ -81,18 +81,18 @@ public class MultipleResultsTestCase {
docSource.addResult(restrictedQuery, restrictedResult);
- query.setWindow(0,30);
+ query.setWindow(0, 30);
Result result = new Execution(chain, Execution.Context.createContextStub()).search(query);
- HitGroup musicGroup = (HitGroup)result.hits().get("music");
- HitGroup moviesGroup = (HitGroup)result.hits().get("movies");
+ HitGroup musicGroup = (HitGroup) result.hits().get("music");
+ HitGroup moviesGroup = (HitGroup) result.hits().get("movies");
- assertEquals( 15, musicGroup.size());
- assertEquals( 15, moviesGroup.size());
+ assertEquals(15, musicGroup.size());
+ assertEquals(15, moviesGroup.size());
}
@Test
- public void testNoHitsForResultSet() {
+ void testNoHitsForResultSet() {
Query query = createQuery();
Result originalResult = new Result(query);
@@ -104,14 +104,14 @@ public class MultipleResultsTestCase {
docSource.addResult(query, originalResult);
- query.setWindow(0,30);
+ query.setWindow(0, 30);
Result result = new Execution(chain, Execution.Context.createContextStub()).search(query);
- HitGroup musicGroup = (HitGroup)result.hits().get("music");
- HitGroup moviesGroup = (HitGroup)result.hits().get("movies");
+ HitGroup musicGroup = (HitGroup) result.hits().get("music");
+ HitGroup moviesGroup = (HitGroup) result.hits().get("movies");
- assertEquals( 15, musicGroup.size());
- assertEquals( 0, moviesGroup.size());
+ assertEquals(15, musicGroup.size());
+ assertEquals(0, moviesGroup.size());
}
private void addHits(Result result, String docName, int numHits,
diff --git a/container-search/src/test/java/com/yahoo/prelude/searcher/test/PosSearcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/searcher/test/PosSearcherTestCase.java
index 43911b33161..755a1c11d47 100644
--- a/container-search/src/test/java/com/yahoo/prelude/searcher/test/PosSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/searcher/test/PosSearcherTestCase.java
@@ -10,12 +10,12 @@ import com.yahoo.search.Searcher;
import com.yahoo.search.rendering.RendererRegistry;
import com.yahoo.search.result.ErrorHit;
import com.yahoo.search.searchchain.Execution;
-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.jupiter.api.Assertions.assertEquals;
/**
* Tests for the PosSearcher
@@ -31,7 +31,7 @@ public class PosSearcherTestCase {
* Tests basic lat/long input.
*/
@Test
- public void testBasics() {
+ void testBasics() {
Query q = new Query();
q.properties().set("pos.ll", "N0;E0");
doSearch(searcher, q, 0, 10);
@@ -47,44 +47,44 @@ public class PosSearcherTestCase {
* Tests basic bounding box input.
*/
@Test
- public void testBoundingBox() {
+ void testBoundingBox() {
Query q = new Query();
q.properties().set("pos.bb", "n=51.9,s=50.2,e=0.34,w=-10.01");
doSearch(searcher, q, 0, 10);
assertEquals("[2,-10010000,50200000,340000,51900000]",
- q.getRanking().getLocation().toString());
+ q.getRanking().getLocation().toString());
q = new Query();
q.properties().set("pos.bb", "n=0,s=0,e=123.456789,w=-123.456789");
doSearch(searcher, q, 0, 10);
assertEquals("[2,-123456789,0,123456789,0]",
- q.getRanking().getLocation().toString());
+ q.getRanking().getLocation().toString());
q = new Query();
q.properties().set("pos.bb", "n=12.345678,s=-12.345678,e=0,w=0");
doSearch(searcher, q, 0, 10);
assertEquals("[2,0,-12345678,0,12345678]",
- q.getRanking().getLocation().toString());
+ q.getRanking().getLocation().toString());
q = new Query();
q.properties().set("pos.bb", "n=0.000001,s=-0.000001,e=0.000001,w=-0.000001");
doSearch(searcher, q, 0, 10);
assertEquals("[2,-1,-1,1,1]",
- q.getRanking().getLocation().toString());
+ q.getRanking().getLocation().toString());
}
/**
* Tests basic bounding box input.
*/
@Test
- public void testBoundingBoxAndRadius() {
+ void testBoundingBoxAndRadius() {
Query q = new Query();
q.properties().set("pos.bb", "n=60.111,s=59.999,e=30.111,w=29.999");
q.properties().set("pos.ll", "N60;E30");
doSearch(searcher, q, 0, 10);
assertEquals(
"[2,29999000,59999000,30111000,60111000]" +
- "(2,30000000,60000000,450668,0,1,0,2147483647)",
+ "(2,30000000,60000000,450668,0,1,0,2147483647)",
q.getRanking().getLocation().toString());
}
@@ -92,7 +92,7 @@ public class PosSearcherTestCase {
* Tests different ways of specifying the radius.
*/
@Test
- public void testRadiusUnits() {
+ void testRadiusUnits() {
Query q = new Query();
q.properties().set("pos.ll", "N0;E0");
q.properties().set("pos.radius", "2km");
@@ -130,7 +130,7 @@ public class PosSearcherTestCase {
* Tests xy position (internal format).
*/
@Test
- public void testXY() {
+ void testXY() {
Query q = new Query();
q.properties().set("pos.xy", "22500;22500");
doSearch(searcher, q, 0, 10);
@@ -144,7 +144,7 @@ public class PosSearcherTestCase {
}
@Test
- public void testNotOverridingOldStyleParameters() {
+ void testNotOverridingOldStyleParameters() {
PosSearcher searcher = new PosSearcher();
Query q = new Query("?query=test&pos.ll=N10.15;E6.08&location=(2,-1100222,0,300,0,1,0,CalcLatLon)");
q.setTraceLevel(1);
@@ -156,7 +156,7 @@ public class PosSearcherTestCase {
* Tests input parameters that should report errors.
*/
@Test
- public void testInvalidInput() {
+ void testInvalidInput() {
PosSearcher searcher = new PosSearcher();
Result result;
@@ -164,18 +164,18 @@ public class PosSearcherTestCase {
q.properties().set("pos.ll", "NE74.14;E14.48");
result = doSearch(searcher, q, 0, 10);
assertEquals("Error in pos parameters: Unable to parse lat/long string 'NE74.14;E14.48': already set direction once, cannot add direction: E",
- ((ErrorHit)result.hits().get(0)).errors().iterator().next().getDetailedMessage());
+ ((ErrorHit) result.hits().get(0)).errors().iterator().next().getDetailedMessage());
q = new Query();
q.properties().set("pos.ll", "NE74.14;E14.48");
q.properties().set("pos.xy", "82400, 72800");
result = doSearch(searcher, q, 0, 10);
assertEquals("Error in pos parameters: Cannot handle both lat/long and xy coords at the same time",
- ((ErrorHit)result.hits().get(0)).errors().iterator().next().getDetailedMessage());
+ ((ErrorHit) result.hits().get(0)).errors().iterator().next().getDetailedMessage());
}
@Test
- public void testWrappingTheNorthPole() {
+ void testWrappingTheNorthPole() {
Query q = new Query();
q.properties().set("pos.ll", "N89.9985365158;E122.163600102");
q.properties().set("pos.radius", "20mi");
diff --git a/container-search/src/test/java/com/yahoo/prelude/searcher/test/QuotingSearcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/searcher/test/QuotingSearcherTestCase.java
index 0b926f5e9b7..be297b5d6c3 100644
--- a/container-search/src/test/java/com/yahoo/prelude/searcher/test/QuotingSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/searcher/test/QuotingSearcherTestCase.java
@@ -15,14 +15,15 @@ import com.yahoo.search.result.Hit;
import com.yahoo.search.result.Relevance;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.searchchain.testutil.DocumentSourceSearcher;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+
import java.util.ArrayList;
import java.util.HashMap;
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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Tests hit property quoting.
@@ -38,10 +39,10 @@ public class QuotingSearcherTestCase {
}
@Test
- public void testBasicQuoting() {
+ void testBasicQuoting() {
Map<Searcher, Searcher> chained = new HashMap<>();
Searcher s = createQuotingSearcher("file:src/test/java/com/yahoo/prelude/"
- + "searcher/test/testquoting.cfg");
+ + "searcher/test/testquoting.cfg");
DocumentSourceSearcher docsource = new DocumentSourceSearcher();
chained.put(s, docsource);
Query q = new Query("?query=a");
@@ -58,10 +59,10 @@ public class QuotingSearcherTestCase {
}
@Test
- public void testBasicQuotingWithNoisyStrings() {
+ void testBasicQuotingWithNoisyStrings() {
Map<Searcher, Searcher> chained = new HashMap<>();
Searcher s = createQuotingSearcher("file:src/test/java/com/yahoo/prelude/"
- + "searcher/test/testquoting.cfg");
+ + "searcher/test/testquoting.cfg");
DocumentSourceSearcher docsource = new DocumentSourceSearcher();
chained.put(s, docsource);
Query q = new Query("?query=a");
@@ -78,10 +79,10 @@ public class QuotingSearcherTestCase {
}
@Test
- public void testFieldQuotingWithNoisyStrings() {
+ void testFieldQuotingWithNoisyStrings() {
Map<Searcher, Searcher> chained = new HashMap<>();
Searcher s = createQuotingSearcher("file:src/test/java/com/yahoo/prelude/"
- + "searcher/test/testquoting.cfg");
+ + "searcher/test/testquoting.cfg");
DocumentSourceSearcher docsource = new DocumentSourceSearcher();
chained.put(s, docsource);
Query q = new Query("?query=a");
@@ -99,10 +100,10 @@ public class QuotingSearcherTestCase {
@Test
- public void testNoQuotingWithOtherTypes() {
+ void testNoQuotingWithOtherTypes() {
Map<Searcher, Searcher> chained = new HashMap<>();
Searcher s = createQuotingSearcher("file:src/test/java/com/yahoo/prelude/"
- + "searcher/test/testquoting.cfg");
+ + "searcher/test/testquoting.cfg");
DocumentSourceSearcher docsource = new DocumentSourceSearcher();
chained.put(s, docsource);
Query q = new Query("?query=a");
diff --git a/container-search/src/test/java/com/yahoo/prelude/searcher/test/ValidatePredicateSearcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/searcher/test/ValidatePredicateSearcherTestCase.java
index 061c9bc5681..9375dc2a4b2 100644
--- a/container-search/src/test/java/com/yahoo/prelude/searcher/test/ValidatePredicateSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/searcher/test/ValidatePredicateSearcherTestCase.java
@@ -17,10 +17,10 @@ import com.yahoo.search.rendering.RendererRegistry;
import com.yahoo.search.result.ErrorMessage;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.yql.YqlParser;
-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 Magnar Nedland
@@ -28,7 +28,7 @@ import static org.junit.Assert.assertNull;
public class ValidatePredicateSearcherTestCase {
@Test
- public void testValidQuery() {
+ void testValidQuery() {
ValidatePredicateSearcher searcher = new ValidatePredicateSearcher();
String q = "select * from sources * where predicate(predicate_field,0,{\"age\":20L})";
Result r = doSearch(searcher, q, "predicate-bounds [0..99]");
@@ -36,7 +36,7 @@ public class ValidatePredicateSearcherTestCase {
}
@Test
- public void testQueryOutOfBounds() {
+ void testQueryOutOfBounds() {
ValidatePredicateSearcher searcher = new ValidatePredicateSearcher();
String q = "select * from sources * where predicate(predicate_field,0,{\"age\":200L})";
Result r = doSearch(searcher, q, "predicate-bounds [0..99]");
@@ -44,7 +44,7 @@ public class ValidatePredicateSearcherTestCase {
}
@Test
- public void queryFailsWhenPredicateFieldIsUsedInTermSearch() {
+ void queryFailsWhenPredicateFieldIsUsedInTermSearch() {
ValidatePredicateSearcher searcher = new ValidatePredicateSearcher();
String q = "select * from sources * where predicate_field CONTAINS \"true\"";
Result r = doSearch(searcher, q, "predicate-bounds [0..99]");
diff --git a/container-search/src/test/java/com/yahoo/prelude/searcher/test/ValidateSortingSearcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/searcher/test/ValidateSortingSearcherTestCase.java
index 6b8c268f4ca..4090fbc5de3 100644
--- a/container-search/src/test/java/com/yahoo/prelude/searcher/test/ValidateSortingSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/searcher/test/ValidateSortingSearcherTestCase.java
@@ -12,13 +12,12 @@ import com.yahoo.search.config.ClusterConfig;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.test.QueryTestCase;
import com.yahoo.vespa.config.search.AttributesConfig;
-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.assertNull;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Check sorting validation behaves OK.
@@ -43,7 +42,7 @@ public class ValidateSortingSearcherTestCase {
}
@Test
- public void testBasicValidation() {
+ void testBasicValidation() {
assertNotNull(quoteAndTransform("+a -b +c"));
assertNotNull(quoteAndTransform("+a"));
assertNotNull(quoteAndTransform(null));
@@ -54,12 +53,12 @@ public class ValidateSortingSearcherTestCase {
}
@Test
- public void testInvalidSpec() {
+ void testInvalidSpec() {
assertNull(quoteAndTransform("+a -e +c"));
}
@Test
- public void testConfigOverride() {
+ void testConfigOverride() {
assertEquals("[ASCENDING:uca(title,en_US,TERTIARY)]", quoteAndTransform("title"));
assertEquals("[ASCENDING:uca(title,en_US,TERTIARY)]", quoteAndTransform("uca(title)"));
assertEquals("[ASCENDING:uca(title,en_US,TERTIARY)]", quoteAndTransform("+uca(title)"));
@@ -67,7 +66,7 @@ public class ValidateSortingSearcherTestCase {
}
@Test
- public void requireThatQueryLocaleIsDefault() {
+ void requireThatQueryLocaleIsDefault() {
assertEquals("[ASCENDING:lowercase(a)]", quoteAndTransform("a"));
assertEquals("[ASCENDING:uca(a,en_US,PRIMARY)]", transform("a", "en-US"));
assertEquals("[ASCENDING:uca(a,en_NO,PRIMARY)]", transform("a", "en-NO"));
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/parser/test/SemanticsParserTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/parser/test/SemanticsParserTestCase.java
index bf99a709df3..3a366882475 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/parser/test/SemanticsParserTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/parser/test/SemanticsParserTestCase.java
@@ -8,11 +8,9 @@ import com.yahoo.language.simple.SimpleLinguistics;
import com.yahoo.prelude.semantics.RuleBase;
import com.yahoo.prelude.semantics.RuleImporter;
import com.yahoo.prelude.semantics.parser.ParseException;
-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.jupiter.api.Assertions.*;
/**
* Tests parsing of semantic rules bases
@@ -24,33 +22,33 @@ public class SemanticsParserTestCase {
private final static String ROOT = "src/test/java/com/yahoo/prelude/semantics/parser/test/";
@Test
- public void testRuleReading() throws java.io.IOException, ParseException {
+ void testRuleReading() throws java.io.IOException, ParseException {
RuleBase rules = new RuleImporter(new SimpleLinguistics()).importFile(ROOT + "rules.sr");
Iterator<?> i = rules.ruleIterator();
assertEquals("[listing] [preposition] [place] -> listing:[listing] place:[place]!150",
- i.next().toString());
+ i.next().toString());
assertEquals("[listing] [place] +> place:[place]",
- i.next().toString());
+ i.next().toString());
assertEquals("[brand] -> brand:[brand]",
- i.next().toString());
+ i.next().toString());
assertEquals("[category] -> category:[category]",
- i.next().toString());
+ i.next().toString());
assertEquals("digital camera -> digicamera",
- i.next().toString());
+ i.next().toString());
assertEquals("(parameter.ranking='cat'), (parameter.ranking='cat0') -> one", i.next().toString());
assertFalse(i.hasNext());
i = rules.conditionIterator();
assertEquals("[listing] :- restaurant, shop, cafe, hotel",
- i.next().toString());
+ i.next().toString());
assertEquals("[preposition] :- in, at, near",
- i.next().toString());
+ i.next().toString());
assertEquals("[place] :- geary",
- i.next().toString());
+ i.next().toString());
assertEquals("[brand] :- sony, dell",
- i.next().toString());
+ i.next().toString());
assertEquals("[category] :- digital camera, camera, phone",
- i.next().toString());
+ i.next().toString());
assertFalse(i.hasNext());
assertTrue(rules.isDefault());
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/AlibabaTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/AlibabaTestCase.java
index d1000e031da..8ff14011483 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/AlibabaTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/AlibabaTestCase.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.prelude.semantics.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Test a case reported by Alibaba
@@ -15,23 +15,23 @@ public class AlibabaTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testNumberReplacement() {
- assertSemantics("AND nokia 3100","3100");
+ void testNumberReplacement() {
+ assertSemantics("AND nokia 3100", "3100");
}
@Test
- public void testRuleFollowingNumber() {
- assertSemantics("lenovo","legend");
+ void testRuleFollowingNumber() {
+ assertSemantics("lenovo", "legend");
}
@Test
- public void testCombinedNumberAndRegular1() {
- assertSemantics("AND lenovo nokia 3100","legend 3100");
+ void testCombinedNumberAndRegular1() {
+ assertSemantics("AND lenovo nokia 3100", "legend 3100");
}
@Test
- public void testCombinedNumberAndRegular2() {
- assertSemantics("AND nokia 3100 lenovo","3100 legend");
+ void testCombinedNumberAndRegular2() {
+ assertSemantics("AND nokia 3100 lenovo", "3100 legend");
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/AnchorTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/AnchorTestCase.java
index 9173053e660..dfba036efae 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/AnchorTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/AnchorTestCase.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.prelude.semantics.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Tests anchoring
@@ -15,7 +15,7 @@ public class AnchorTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testSingleWordAnchoredBothSides() {
+ void testSingleWordAnchoredBothSides() {
assertSemantics("anchor", "word");
assertSemantics("anchor", "anotherword");
assertSemantics("notthisword", "notthisword");
@@ -23,7 +23,7 @@ public class AnchorTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testMultiwordAnchored() {
+ void testMultiwordAnchored() {
assertSemantics("anchor", "this is complete");
assertSemantics("AND this is complete toomuch", "this is complete toomuch");
assertSemantics("anchor", "a phrase");
@@ -31,28 +31,28 @@ public class AnchorTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testFirstAnchored() {
- assertSemantics("anchor","first");
- assertSemantics("AND anchor andmore","first andmore");
- assertSemantics("AND before first","before first");
- assertSemantics("AND before first andmore","before first andmore");
+ void testFirstAnchored() {
+ assertSemantics("anchor", "first");
+ assertSemantics("AND anchor andmore", "first andmore");
+ assertSemantics("AND before first", "before first");
+ assertSemantics("AND before first andmore", "before first andmore");
}
@Test
- public void testLastAnchored() {
- assertSemantics("anchor","last");
- assertSemantics("AND andmore anchor","andmore last");
- assertSemantics("AND last after","last after");
- assertSemantics("AND andmore last after","andmore last after");
+ void testLastAnchored() {
+ assertSemantics("anchor", "last");
+ assertSemantics("AND andmore anchor", "andmore last");
+ assertSemantics("AND last after", "last after");
+ assertSemantics("AND andmore last after", "andmore last after");
}
@Test
- public void testFirstAndLastAnchored() {
- assertSemantics("AND anchor anchor","first last");
- assertSemantics("AND last first","last first");
- assertSemantics("AND anchor between anchor","first between last");
- assertSemantics("AND anchor last after","first last after");
- assertSemantics("AND before first anchor","before first last");
+ void testFirstAndLastAnchored() {
+ assertSemantics("AND anchor anchor", "first last");
+ assertSemantics("AND last first", "last first");
+ assertSemantics("AND anchor between anchor", "first between last");
+ assertSemantics("AND anchor last after", "first last after");
+ assertSemantics("AND before first anchor", "before first last");
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/AutomataNotTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/AutomataNotTestCase.java
index 4493038fc86..b138ba50ca9 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/AutomataNotTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/AutomataNotTestCase.java
@@ -1,8 +1,8 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.semantics.test;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
/**
* Tests that ![a] is interpreted as "default:![a]", not as "!default:[a]",
@@ -16,9 +16,10 @@ public class AutomataNotTestCase extends RuleBaseAbstractTestCase {
super("automatanot.sr", "semantics.fsa");
}
+ // TODO: MAKE THIS WORK!
@Test
- @Ignore // TODO: MAKE THIS WORK!
- public void testAutomataNot() {
+ @Disabled
+ void testAutomataNot() {
if (System.currentTimeMillis() > 0) return;
assertSemantics("carpenter", "carpenter");
assertSemantics("RANK brukbar busname:brukbar", "brukbar");
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/AutomataTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/AutomataTestCase.java
index 71e36e45acc..a9c7202f7cd 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/AutomataTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/AutomataTestCase.java
@@ -3,11 +3,11 @@ package com.yahoo.prelude.semantics.test;
import com.yahoo.search.Query;
import com.yahoo.prelude.semantics.RuleBase;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.Disabled;
+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 rule bases using automatas for matching
@@ -23,62 +23,63 @@ public class AutomataTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testAutomataRuleBase() {
- RuleBase ruleBase=searcher.getDefaultRuleBase();
- assertEquals(RuleBase.class,ruleBase.getClass());
+ void testAutomataRuleBase() {
+ RuleBase ruleBase = searcher.getDefaultRuleBase();
+ assertEquals(RuleBase.class, ruleBase.getClass());
assertTrue(ruleBase.getSource().endsWith(root + "automatarules.sr"));
- assertEquals(root + "semantics.fsa",ruleBase.getAutomataFile());
+ assertEquals(root + "semantics.fsa", ruleBase.getAutomataFile());
- Query query=new Query("?query=sony+digital+camera");
- ruleBase.analyze(query,0);
+ Query query = new Query("?query=sony+digital+camera");
+ ruleBase.analyze(query, 0);
assertEquals("RANK (WEAKAND(100) sony digital camera) dsp1:sony dsp5:digicamera", query.getModel().getQueryTree().getRoot().toString());
- query=new Query("?query=sony+digital+camera&rules.reload");
- ruleBase=searcher.getDefaultRuleBase();
+ query = new Query("?query=sony+digital+camera&rules.reload");
+ ruleBase = searcher.getDefaultRuleBase();
assertTrue(ruleBase.getSource().endsWith(root + "automatarules.sr"));
- assertEquals(root + "semantics.fsa",ruleBase.getAutomataFile());
- ruleBase.analyze(query,0);
+ assertEquals(root + "semantics.fsa", ruleBase.getAutomataFile());
+ ruleBase.analyze(query, 0);
assertEquals("RANK (WEAKAND(100) sony digital camera) dsp1:sony dsp5:digicamera", query.getModel().getQueryTree().getRoot().toString());
}
@Test
- public void testAutomataSingleQuery() {
- assertSemantics("RANK sony dsp1:sony","sony");
+ void testAutomataSingleQuery() {
+ assertSemantics("RANK sony dsp1:sony", "sony");
}
@Test
- public void testAutomataFilterIsIgnored() {
- assertSemantics("RANK sony |something dsp1:sony","sony&filter=something");
- assertSemantics("RANK something |sony","something&filter=sony");
+ void testAutomataFilterIsIgnored() {
+ assertSemantics("RANK sony |something dsp1:sony", "sony&filter=something");
+ assertSemantics("RANK something |sony", "something&filter=sony");
}
@Test
- public void testAutomataPluralMatches() {
- assertSemantics("RANK sonys dsp1:sony","sonys");
+ void testAutomataPluralMatches() {
+ assertSemantics("RANK sonys dsp1:sony", "sonys");
- assertSemantics("RANK (AND car cleaner) dsp1:\"car cleaners\" dsp5:\"car cleaners\"","car cleaner");
+ assertSemantics("RANK (AND car cleaner) dsp1:\"car cleaners\" dsp5:\"car cleaners\"", "car cleaner");
- assertSemantics("RANK (AND sony digitals cameras) dsp1:sony dsp5:digicamera","sony digitals cameras");
+ assertSemantics("RANK (AND sony digitals cameras) dsp1:sony dsp5:digicamera", "sony digitals cameras");
}
@Test
- public void testMatchingMultipleAutomataConditionsSingleWord() {
- assertSemantics("RANK carpenter dsp1:carpenter dsp5:carpenter","carpenter");
+ void testMatchingMultipleAutomataConditionsSingleWord() {
+ assertSemantics("RANK carpenter dsp1:carpenter dsp5:carpenter", "carpenter");
}
@Test
- public void testMatchingMultipleAutomataConditionsPhrase() {
- assertSemantics("RANK (AND car cleaners) dsp1:\"car cleaners\" dsp5:\"car cleaners\"","car cleaners");
+ void testMatchingMultipleAutomataConditionsPhrase() {
+ assertSemantics("RANK (AND car cleaners) dsp1:\"car cleaners\" dsp5:\"car cleaners\"", "car cleaners");
}
+ // TODO: Make this work again
@Test
- @Ignore // TODO: Make this work again
- public void testReplaceOnNoMatch() {
- assertSemantics("nomatch:sonny","sonny&donomatch");
- assertSemantics("RANK sony dsp1:sony","sony&donomatch");
- assertSemantics("RANK sonys dsp1:sony","sonys&donomatch");
- assertSemantics("AND nomatch:sonny nomatch:boy","sonny boy&donomatch");
- assertSemantics("RANK (AND sony nomatch:boy) dsp1:sony","sony boy&donomatch");
+ @Disabled
+ void testReplaceOnNoMatch() {
+ assertSemantics("nomatch:sonny", "sonny&donomatch");
+ assertSemantics("RANK sony dsp1:sony", "sony&donomatch");
+ assertSemantics("RANK sonys dsp1:sony", "sonys&donomatch");
+ assertSemantics("AND nomatch:sonny nomatch:boy", "sonny boy&donomatch");
+ assertSemantics("RANK (AND sony nomatch:boy) dsp1:sony", "sony boy&donomatch");
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/BacktrackingTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/BacktrackingTestCase.java
index 06f7112f851..3a4f0344994 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/BacktrackingTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/BacktrackingTestCase.java
@@ -5,6 +5,8 @@ import java.util.ArrayList;
import java.util.List;
import com.yahoo.component.chain.Chain;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
import com.yahoo.language.simple.SimpleLinguistics;
import com.yahoo.search.Query;
import com.yahoo.prelude.semantics.RuleImporter;
@@ -14,9 +16,7 @@ import com.yahoo.search.Searcher;
import com.yahoo.search.rendering.RendererRegistry;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.test.QueryTestCase;
-import org.junit.Test;
-
-import static org.junit.Assert.assertEquals;
+import org.junit.jupiter.api.Test;
/**
* @author bratseth
@@ -50,47 +50,47 @@ public class BacktrackingTestCase {
// Literal terms ---------------
@Test
- public void testMultilevelBacktrackingLiteralTerms() {
- assertSemantics("WEAKAND(100) replaced","word1 word2 word5 word8");
+ void testMultilevelBacktrackingLiteralTerms() {
+ assertSemantics("WEAKAND(100) replaced", "word1 word2 word5 word8");
}
@Test
- public void testMultilevelBacktrackingWontReorderOthertermsLiteralTerms() {
- assertSemantics("WEAKAND(100) other1 other2 other3 replaced","other1 other2 other3 word1 word2 word5 word8");
+ void testMultilevelBacktrackingWontReorderOthertermsLiteralTerms() {
+ assertSemantics("WEAKAND(100) other1 other2 other3 replaced", "other1 other2 other3 word1 word2 word5 word8");
}
@Test
- public void testMultilevelBacktrackingWithMulticompoundMatchLiteralTerms() {
- assertSemantics("WEAKAND(100) other1 other2 other3 replaced","other1 other2 other3 word1 word2 word5-word8");
+ void testMultilevelBacktrackingWithMulticompoundMatchLiteralTerms() {
+ assertSemantics("WEAKAND(100) other1 other2 other3 replaced", "other1 other2 other3 word1 word2 word5-word8");
}
@Test
- public void testMultilevelBacktrackingPreservePartialMatchBeforeLiteralTerms() {
- assertSemantics("WEAKAND(100) word1 word2 word5 replaced","word1 word2 word5 word1 word2 word5 word8");
+ void testMultilevelBacktrackingPreservePartialMatchBeforeLiteralTerms() {
+ assertSemantics("WEAKAND(100) word1 word2 word5 replaced", "word1 word2 word5 word1 word2 word5 word8");
}
@Test
- public void testMultilevelBacktrackingPreservePartialMatchAfterLiteralTerms() {
- assertSemantics("WEAKAND(100) replaced word1 word2 word5","word1 word2 word5 word8 word1 word2 word5 ");
+ void testMultilevelBacktrackingPreservePartialMatchAfterLiteralTerms() {
+ assertSemantics("WEAKAND(100) replaced word1 word2 word5", "word1 word2 word5 word8 word1 word2 word5 ");
}
// reference terms ---------------
@Test
- public void testMultilevelBacktrackingReferenceTerms() {
- assertSemantics("WEAKAND(100) ref:ref1 ref:ref2 ref:ref5 ref:ref8","ref1 ref2 ref5 ref8");
+ void testMultilevelBacktrackingReferenceTerms() {
+ assertSemantics("WEAKAND(100) ref:ref1 ref:ref2 ref:ref5 ref:ref8", "ref1 ref2 ref5 ref8");
}
@Test
- public void testMultilevelBacktrackingPreservePartialMatchBeforeReferenceTerms() {
+ void testMultilevelBacktrackingPreservePartialMatchBeforeReferenceTerms() {
assertSemantics("WEAKAND(100) ref1 ref2 ref5 ref:ref1 ref:ref2 ref:ref5 ref:ref8",
- "ref1 ref2 ref5 ref1 ref2 ref5 ref8");
+ "ref1 ref2 ref5 ref1 ref2 ref5 ref8");
}
@Test
- public void testMultilevelBacktrackingPreservePartialMatchAfterReferenceTerms() {
+ void testMultilevelBacktrackingPreservePartialMatchAfterReferenceTerms() {
assertSemantics("WEAKAND(100) ref:ref1 ref:ref2 ref:ref5 ref:ref8 ref1 ref2 ref5",
- "ref1 ref2 ref5 ref8 ref1 ref2 ref5");
+ "ref1 ref2 ref5 ref8 ref1 ref2 ref5");
}
private Result doSearch(Searcher searcher, Query query, int offset, int hits) {
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/BlendingTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/BlendingTestCase.java
index 9e590698f4a..334ff8d05a6 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/BlendingTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/BlendingTestCase.java
@@ -2,9 +2,9 @@
package com.yahoo.prelude.semantics.test;
import com.yahoo.search.Query;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Tests blending rules
@@ -19,9 +19,9 @@ public class BlendingTestCase extends RuleBaseAbstractTestCase {
/** Tests parameter literal matching */
@Test
- public void testLiteralEquals() {
- assertParameterSemantics("AND a sun came cd","a sun came cd","search","[music]");
- assertParameterSemantics("AND driving audi","driving audi","search","[cars]");
+ void testLiteralEquals() {
+ assertParameterSemantics("AND a sun came cd", "a sun came cd", "search", "[music]");
+ assertParameterSemantics("AND driving audi", "driving audi", "search", "[cars]");
//assertParameterSemantics("AND audi music quality","audi music quality","search","carstereos",1);
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/CJKTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/CJKTestCase.java
index 0aaa5f2cea7..457a2063173 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/CJKTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/CJKTestCase.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.prelude.semantics.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Tests that using rule bases containing cjk characters work
@@ -15,14 +15,14 @@ public class CJKTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testIt() {
- assertSemantics("\u7d22a","a\u7d22");
- assertSemantics("\u7d22a","\u7d22a");
- assertSemantics("brand:\u7d22\u5c3c","\u7d22\u5c3c");
- assertSemantics("brand:\u60e0\u666e","\u60e0\u666e");
- assertSemantics("brand:\u4f73\u80fd","\u4f73\u80fd");
- assertSemantics("AND brand:\u4f73\u80fd \u7d22a","\u4f73\u80fd a\u7d22");
- assertSemantics("\u4f73\u80fd\u7d22\u5c3c","\u4f73\u80fd\u7d22\u5c3c");
+ void testIt() {
+ assertSemantics("\u7d22a", "a\u7d22");
+ assertSemantics("\u7d22a", "\u7d22a");
+ assertSemantics("brand:\u7d22\u5c3c", "\u7d22\u5c3c");
+ assertSemantics("brand:\u60e0\u666e", "\u60e0\u666e");
+ assertSemantics("brand:\u4f73\u80fd", "\u4f73\u80fd");
+ assertSemantics("AND brand:\u4f73\u80fd \u7d22a", "\u4f73\u80fd a\u7d22");
+ assertSemantics("\u4f73\u80fd\u7d22\u5c3c", "\u4f73\u80fd\u7d22\u5c3c");
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/ComparisonTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/ComparisonTestCase.java
index 988d69a55d3..0c5447c120a 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/ComparisonTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/ComparisonTestCase.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.prelude.semantics.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* @author bratseth
@@ -17,30 +17,30 @@ public class ComparisonTestCase extends RuleBaseAbstractTestCase {
* different conditions (coffee, island)
*/
@Test
- public void testNamedConditionReturnComparison() {
+ void testNamedConditionReturnComparison() {
// Not sufficient that both conditions are matched
- assertSemantics("AND borneo arabica island:borneo coffee:arabica","borneo arabica");
+ assertSemantics("AND borneo arabica island:borneo coffee:arabica", "borneo arabica");
// They must match the same word
- assertSemantics("AND java noise island:java coffee:java control:ambigous off","java noise");
+ assertSemantics("AND java noise island:java coffee:java control:ambigous off", "java noise");
// Works also when there are other, not-equal matches
assertSemantics("AND borneo arabica java island:borneo island:java coffee:arabica coffee:java control:ambigous off",
- "borneo arabica java");
+ "borneo arabica java");
}
@Test
- public void testContainsAsSubstring() {
- assertSemantics("AND java island:java coffee:java control:ambigous off","java");
- assertSemantics("AND kanava island:kanava off","kanava");
- assertSemantics("AND borneo island:borneo","borneo");
+ void testContainsAsSubstring() {
+ assertSemantics("AND java island:java coffee:java control:ambigous off", "java");
+ assertSemantics("AND kanava island:kanava off", "kanava");
+ assertSemantics("AND borneo island:borneo", "borneo");
}
@Test
- public void testAlphanumericComparison() {
- assertSemantics("a","a");
- assertSemantics("AND z highletter","z");
- assertSemantics("AND p highletter","p");
+ void testAlphanumericComparison() {
+ assertSemantics("a", "a");
+ assertSemantics("AND z highletter", "z");
+ assertSemantics("AND p highletter", "p");
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/ComparisonsTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/ComparisonsTestCase.java
index a8fe78ac1ff..867a57aebeb 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/ComparisonsTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/ComparisonsTestCase.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.prelude.semantics.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* @author bratseth
@@ -13,11 +13,11 @@ public class ComparisonsTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testLiteralEquals() {
- assertSemantics("a","a");
- assertSemantics("RANK a foo:a","a&ranking=category");
- assertSemantics("a","a&ranking=somethingelse");
- assertSemantics("a","a&otherparam=category");
+ void testLiteralEquals() {
+ assertSemantics("a", "a");
+ assertSemantics("RANK a foo:a", "a&ranking=category");
+ assertSemantics("a", "a&ranking=somethingelse");
+ assertSemantics("a", "a&otherparam=category");
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/ConditionTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/ConditionTestCase.java
index 17eb4120b84..d7297bd79a4 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/ConditionTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/ConditionTestCase.java
@@ -14,10 +14,10 @@ import com.yahoo.prelude.semantics.rule.ProductionRule;
import com.yahoo.prelude.semantics.rule.ReplacingProductionRule;
import com.yahoo.prelude.semantics.rule.SequenceCondition;
import com.yahoo.prelude.semantics.rule.TermCondition;
-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
@@ -25,7 +25,7 @@ import static org.junit.Assert.assertTrue;
public class ConditionTestCase {
@Test
- public void testTermCondition() {
+ void testTermCondition() {
var linguistics = new RuleBaseLinguistics(new SimpleLinguistics());
TermCondition term = new TermCondition("foo", linguistics);
Query query = new Query("?query=foo");
@@ -33,23 +33,23 @@ public class ConditionTestCase {
}
@Test
- public void testSequenceCondition() {
+ void testSequenceCondition() {
var linguistics = new RuleBaseLinguistics(new SimpleLinguistics());
TermCondition term1 = new TermCondition("foo", linguistics);
- TermCondition term2 = new TermCondition("bar",linguistics);
+ TermCondition term2 = new TermCondition("bar", linguistics);
SequenceCondition sequence = new SequenceCondition();
sequence.addCondition(term1);
sequence.addCondition(term2);
Query query = new Query("?query=foo+bar");
- assertTrue(query + " matches " + sequence,sequence.matches(new Evaluation(query, null).freshRuleEvaluation()));
+ assertTrue(sequence.matches(new Evaluation(query, null).freshRuleEvaluation()), query + " matches " + sequence);
Query query2 = new Query("?query=foo");
- assertFalse(query2 + " does not match " + sequence,sequence.matches(new Evaluation(query2, null).freshRuleEvaluation()));
+ assertFalse(sequence.matches(new Evaluation(query2, null).freshRuleEvaluation()), query2 + " does not match " + sequence);
Query query3 = new Query("?query=bar");
- assertFalse(query3 + " does not match " + sequence,sequence.matches(new Evaluation(query3, null).freshRuleEvaluation()));
+ assertFalse(sequence.matches(new Evaluation(query3, null).freshRuleEvaluation()), query3 + " does not match " + sequence);
}
@Test
- public void testChoiceCondition() {
+ void testChoiceCondition() {
var linguistics = new RuleBaseLinguistics(new SimpleLinguistics());
TermCondition term1 = new TermCondition("foo", linguistics);
TermCondition term2 = new TermCondition("bar", linguistics);
@@ -57,18 +57,18 @@ public class ConditionTestCase {
choice.addCondition(term1);
choice.addCondition(term2);
Query query1 = new Query("?query=foo+bar");
- assertTrue(query1 + " matches " + choice, choice.matches(new Evaluation(query1, null).freshRuleEvaluation()));
+ assertTrue(choice.matches(new Evaluation(query1, null).freshRuleEvaluation()), query1 + " matches " + choice);
Query query2 = new Query("?query=foo");
- assertTrue(query2 + " matches " + choice, choice.matches(new Evaluation(query2, null).freshRuleEvaluation()));
+ assertTrue(choice.matches(new Evaluation(query2, null).freshRuleEvaluation()), query2 + " matches " + choice);
Query query3 = new Query("?query=bar");
- assertTrue(query3 + " matches " + choice, choice.matches(new Evaluation(query3, null).freshRuleEvaluation()));
+ assertTrue(choice.matches(new Evaluation(query3, null).freshRuleEvaluation()), query3 + " matches " + choice);
}
@Test
- public void testNamedConditionReference() {
+ void testNamedConditionReference() {
var linguistics = new RuleBaseLinguistics(new SimpleLinguistics());
TermCondition term = new TermCondition("foo", linguistics);
- NamedCondition named = new NamedCondition("cond",term);
+ NamedCondition named = new NamedCondition("cond", term);
ConditionReference reference = new ConditionReference("cond");
// To initialize the condition reference...
@@ -81,7 +81,7 @@ public class ConditionTestCase {
ruleBase.initialize();
Query query = new Query("?query=foo");
- assertTrue(query + " matches " + reference,reference.matches(new Evaluation(query, null).freshRuleEvaluation()));
+ assertTrue(reference.matches(new Evaluation(query, null).freshRuleEvaluation()), query + " matches " + reference);
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/ConfigurationTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/ConfigurationTestCase.java
index 7d9ea07339f..569ae569f18 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/ConfigurationTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/ConfigurationTestCase.java
@@ -13,13 +13,12 @@ import com.yahoo.search.Result;
import com.yahoo.search.Searcher;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.test.QueryTestCase;
-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.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Tests creating a set of rule bases (the same set as in inheritingrules) from config
@@ -52,7 +51,7 @@ public class ConfigurationTestCase {
}
@Test
- public void testReadingConfigurationRuleBase() {
+ void testReadingConfigurationRuleBase() {
RuleBase parent = searcher.getRuleBase("parent");
assertNotNull(parent);
assertEquals("parent", parent.getName());
@@ -60,7 +59,7 @@ public class ConfigurationTestCase {
}
@Test
- public void testParent() {
+ void testParent() {
assertSemantics("WEAKAND(100) vehiclebrand:audi", "audi cars", "parent");
assertSemantics("WEAKAND(100) vehiclebrand:alfa", "alfa bus", "parent");
assertSemantics("AND (WEAKAND(100) vehiclebrand:bmw) expensivetv", "bmw motorcycle", "parent.sr");
@@ -69,7 +68,7 @@ public class ConfigurationTestCase {
}
@Test
- public void testChild1() {
+ void testChild1() {
assertSemantics("WEAKAND(100) vehiclebrand:skoda", "audi cars", "child1.sr");
assertSemantics("WEAKAND(100) vehiclebrand:alfa", "alfa bus", "child1");
assertSemantics("AND (WEAKAND(100) vehiclebrand:bmw) expensivetv", "bmw motorcycle", "child1");
@@ -78,7 +77,7 @@ public class ConfigurationTestCase {
}
@Test
- public void testChild2() {
+ void testChild2() {
assertSemantics("WEAKAND(100) vehiclebrand:audi", "audi cars", "child2");
assertSemantics("WEAKAND(100) vehiclebrand:alfa", "alfa bus", "child2.sr");
assertSemantics("AND (WEAKAND(100) vehiclebrand:bmw) expensivetv", "bmw motorcycle", "child2.sr");
@@ -87,7 +86,7 @@ public class ConfigurationTestCase {
}
@Test
- public void testGrandchild() {
+ void testGrandchild() {
assertSemantics("WEAKAND(100) vehiclebrand:skoda", "audi cars", "grandchild.sr");
assertSemantics("WEAKAND(100) vehiclebrand:alfa", "alfa bus", "grandchild");
assertSemantics("AND (WEAKAND(100) vehiclebrand:bmw) expensivetv", "bmw motorcycle", "grandchild");
@@ -96,7 +95,7 @@ public class ConfigurationTestCase {
}
@Test
- public void testSearcher() {
+ void testSearcher() {
assertSemantics("WEAKAND(100) vehiclebrand:skoda", "vw cars", "grandchild");
assertSemantics("WEAKAND(100) vehiclebrand:skoda", "vw cars", "grandchild.sd");
try {
@@ -110,14 +109,14 @@ public class ConfigurationTestCase {
assertSemanticsRulesOff("WEAKAND(100) vw cars", "vw cars");
assertSemantics("WEAKAND(100) vw car", "vw cars", "child2");
- assertSemantics("WEAKAND(100) vehiclebrand:skoda","skoda cars","child2");
+ assertSemantics("WEAKAND(100) vehiclebrand:skoda", "skoda cars", "child2");
- assertSemantics("WEAKAND(100) vehiclebrand:skoda","audi cars", "child1");
- assertSemantics("WEAKAND(100) vehiclebrand:skoda","vw cars", "child1");
- assertSemantics("WEAKAND(100) skoda car", "skoda cars","child1");
+ assertSemantics("WEAKAND(100) vehiclebrand:skoda", "audi cars", "child1");
+ assertSemantics("WEAKAND(100) vehiclebrand:skoda", "vw cars", "child1");
+ assertSemantics("WEAKAND(100) skoda car", "skoda cars", "child1");
assertSemantics("WEAKAND(100) vw car", "vw cars", "parent");
- assertSemantics("WEAKAND(100) skoda car", "skoda cars","parent");
+ assertSemantics("WEAKAND(100) skoda car", "skoda cars", "parent");
}
private Result doSearch(Searcher searcher, Query query, int offset, int hits) {
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/DuplicateRuleTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/DuplicateRuleTestCase.java
index 76c8c3966b7..a692217fef6 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/DuplicateRuleTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/DuplicateRuleTestCase.java
@@ -5,10 +5,10 @@ import com.yahoo.language.simple.SimpleLinguistics;
import com.yahoo.prelude.semantics.RuleBaseException;
import com.yahoo.prelude.semantics.RuleImporter;
import com.yahoo.prelude.semantics.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
@@ -18,7 +18,7 @@ public class DuplicateRuleTestCase {
private final String root = "src/test/java/com/yahoo/prelude/semantics/test/rulebases/";
@Test
- public void testDuplicateRuleBaseLoading() throws java.io.IOException, ParseException {
+ void testDuplicateRuleBaseLoading() throws java.io.IOException, ParseException {
if (System.currentTimeMillis() > 0) return; // TODO: Include this test...
try {
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/Ellipsis2TestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/Ellipsis2TestCase.java
index 28ffe549711..0808092da65 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/Ellipsis2TestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/Ellipsis2TestCase.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.prelude.semantics.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* tersts the ellipsis rule base
@@ -15,8 +15,8 @@ public class Ellipsis2TestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testUnreferencedEllipsis() {
- assertSemantics("AND a b c someindex:\"a b c\"","a b c");
+ void testUnreferencedEllipsis() {
+ assertSemantics("AND a b c someindex:\"a b c\"", "a b c");
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/EllipsisTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/EllipsisTestCase.java
index 1c570220f52..d1fe2091bc2 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/EllipsisTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/EllipsisTestCase.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.prelude.semantics.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* tersts the ellipsis rule base
@@ -15,34 +15,34 @@ public class EllipsisTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testUnreferencedEllipsis() {
- assertSemantics("AND why is stench unpleasant about:stench","why is stench unpleasant");
- assertSemantics("AND why is the sky blue about:\"the sky\"","why is the sky blue");
+ void testUnreferencedEllipsis() {
+ assertSemantics("AND why is stench unpleasant about:stench", "why is stench unpleasant");
+ assertSemantics("AND why is the sky blue about:\"the sky\"", "why is the sky blue");
assertSemantics("AND why is aardwark almost always most relevant in dictionaries about:aardwark",
- "why is aardwark almost always most relevant in dictionaries");
+ "why is aardwark almost always most relevant in dictionaries");
}
@Test
- public void testReferencedEllipsis() {
- assertSemantics("album:parade","parade album");
- assertSemantics("album:\"a sun came\"","a sun came album");
- assertSemantics("album:parade","parade cd");
- assertSemantics("album:\"a sun came\"","a sun came cd");
+ void testReferencedEllipsis() {
+ assertSemantics("album:parade", "parade album");
+ assertSemantics("album:\"a sun came\"", "a sun came album");
+ assertSemantics("album:parade", "parade cd");
+ assertSemantics("album:\"a sun came\"", "a sun came cd");
}
@Test
- public void testEllipsisInNamedCondition() {
- assertSemantics("AND name:\"a sun came\" product:video","buy a sun came");
- assertSemantics("AND name:stalker product:video","buy stalker video");
- assertSemantics("AND name:\"the usual suspects\" product:video","buy the usual suspects video");
+ void testEllipsisInNamedCondition() {
+ assertSemantics("AND name:\"a sun came\" product:video", "buy a sun came");
+ assertSemantics("AND name:stalker product:video", "buy stalker video");
+ assertSemantics("AND name:\"the usual suspects\" product:video", "buy the usual suspects video");
}
@Test
- public void testMultipleEllipsis() {
- assertSemantics("AND from:paris to:texas","from paris to texas");
- assertSemantics("AND from:\"sao paulo\" to:\"real madrid\"","from sao paulo to real madrid");
- assertSemantics("AND from:\"from from\" to:oslo","from from from to oslo");
- assertSemantics("AND from:\"from from to\" to:koko","from from from to to koko"); // Matching is greedy left-right
+ void testMultipleEllipsis() {
+ assertSemantics("AND from:paris to:texas", "from paris to texas");
+ assertSemantics("AND from:\"sao paulo\" to:\"real madrid\"", "from sao paulo to real madrid");
+ assertSemantics("AND from:\"from from\" to:oslo", "from from from to oslo");
+ assertSemantics("AND from:\"from from to\" to:koko", "from from from to to koko"); // Matching is greedy left-right
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/ExactMatchTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/ExactMatchTestCase.java
index 8f9c33dab51..d04ea0eabf9 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/ExactMatchTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/ExactMatchTestCase.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.prelude.semantics.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* @author bratseth
@@ -13,8 +13,8 @@ public class ExactMatchTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testCompleteMatch() {
- assertSemantics("AND primetime in no time","primetime notime");
+ void testCompleteMatch() {
+ assertSemantics("AND primetime in no time", "primetime notime");
}
/*
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/ExactMatchTrickTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/ExactMatchTrickTestCase.java
index c566b05405d..6ca055ff980 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/ExactMatchTrickTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/ExactMatchTrickTestCase.java
@@ -3,7 +3,7 @@ package com.yahoo.prelude.semantics.test;
import com.yahoo.search.Query;
import com.yahoo.search.test.QueryTestCase;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* @author bratseth
@@ -15,20 +15,20 @@ public class ExactMatchTrickTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testCompleteMatch() {
+ void testCompleteMatch() {
assertSemantics("AND default:primetime default:in default:no default:time", "primetime notime");
}
@Test
- public void testCompleteMatchWithNegative() { // Notice ordering bug
+ void testCompleteMatchWithNegative() { // Notice ordering bug
assertSemantics("+(AND default:primetime default:in default:time default:no TRUE) -regionexcl:us",
- new Query(QueryTestCase.httpEncode("?query=primetime ANDNOT regionexcl:us&type=adv")));
+ new Query(QueryTestCase.httpEncode("?query=primetime ANDNOT regionexcl:us&type=adv")));
}
@Test
- public void testCompleteMatchWithFilterAndNegative() {
+ void testCompleteMatchWithFilterAndNegative() {
assertSemantics("AND (+(AND default:primetime default:in default:time default:no TRUE) -regionexcl:us) |lang:en",
- new Query(QueryTestCase.httpEncode("?query=primetime ANDNOT regionexcl:us&type=adv&filter=+lang:en")));
+ new Query(QueryTestCase.httpEncode("?query=primetime ANDNOT regionexcl:us&type=adv&filter=+lang:en")));
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/ExpansionTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/ExpansionTestCase.java
index 111f37bf8e4..13b65716ffc 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/ExpansionTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/ExpansionTestCase.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.prelude.semantics.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
public class ExpansionTestCase extends RuleBaseAbstractTestCase {
@@ -10,24 +10,24 @@ public class ExpansionTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testOrExpansion() {
+ void testOrExpansion() {
assertSemantics("OR or1 or2 or3", "or1");
}
@Test
- public void testEquivExpansion1() {
+ void testEquivExpansion1() {
assertSemantics("EQUIV equiv1 equiv2 equiv3", "equiv1");
}
@Test
- public void testEquivExpansion2() {
+ void testEquivExpansion2() {
assertSemantics("EQUIV testfield:e1 testfield:e2 testfield:e3", "testfield:foo");
}
@Test
- public void testEquivExpansion3() {
+ void testEquivExpansion3() {
assertSemantics("AND testfield:e1 testfield:e2 testfield:e3 testfield:e1 testfield:e2 testfield:e3",
- "testfield:foo testfield:bar");
+ "testfield:foo testfield:bar");
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/InheritanceTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/InheritanceTestCase.java
index baec0066fb3..e9fa8dfa4be 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/InheritanceTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/InheritanceTestCase.java
@@ -15,12 +15,9 @@ import com.yahoo.search.Result;
import com.yahoo.search.Searcher;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.test.QueryTestCase;
-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.*;
/**
* @author bratseth
@@ -58,7 +55,7 @@ public class InheritanceTestCase {
}
@Test
- public void testInclusion() {
+ void testInclusion() {
assertTrue(grandchild.includes("child1"));
assertTrue(grandchild.includes("child2"));
assertTrue(grandchild.includes("parent"));
@@ -74,8 +71,8 @@ public class InheritanceTestCase {
}
@Test
- public void testInclusionOrderAndContentDump() {
- StringTokenizer lines = new StringTokenizer(grandchild.toContentString(),"\n",false);
+ void testInclusionOrderAndContentDump() {
+ StringTokenizer lines = new StringTokenizer(grandchild.toContentString(), "\n", false);
assertEquals("vw -> audi", lines.nextToken());
assertEquals("car -> car", lines.nextToken());
assertEquals("[brand] [vehicle] -> vehiclebrand:[brand]", lines.nextToken());
@@ -88,7 +85,7 @@ public class InheritanceTestCase {
}
@Test
- public void testParent() {
+ void testParent() {
assertSemantics("WEAKAND(100) vehiclebrand:audi", "audi cars", parent);
assertSemantics("WEAKAND(100) vehiclebrand:alfa", "alfa bus", parent);
assertSemantics("AND (WEAKAND(100) vehiclebrand:bmw) expensivetv", "bmw motorcycle", parent);
@@ -97,7 +94,7 @@ public class InheritanceTestCase {
}
@Test
- public void testChild1() {
+ void testChild1() {
assertSemantics("WEAKAND(100) vehiclebrand:skoda", "audi cars", child1);
assertSemantics("WEAKAND(100) vehiclebrand:alfa", "alfa bus", child1);
assertSemantics("AND (WEAKAND(100) vehiclebrand:bmw) expensivetv", "bmw motorcycle", child1);
@@ -106,25 +103,25 @@ public class InheritanceTestCase {
}
@Test
- public void testChild2() {
- assertSemantics("WEAKAND(100) vehiclebrand:audi","audi cars", child2);
- assertSemantics("WEAKAND(100) vehiclebrand:alfa","alfa bus", child2);
- assertSemantics("AND (WEAKAND(100) vehiclebrand:bmw) expensivetv","bmw motorcycle", child2);
- assertSemantics("WEAKAND(100) vw car","vw cars", child2);
- assertSemantics("WEAKAND(100) vehiclebrand:skoda","skoda cars", child2);
+ void testChild2() {
+ assertSemantics("WEAKAND(100) vehiclebrand:audi", "audi cars", child2);
+ assertSemantics("WEAKAND(100) vehiclebrand:alfa", "alfa bus", child2);
+ assertSemantics("AND (WEAKAND(100) vehiclebrand:bmw) expensivetv", "bmw motorcycle", child2);
+ assertSemantics("WEAKAND(100) vw car", "vw cars", child2);
+ assertSemantics("WEAKAND(100) vehiclebrand:skoda", "skoda cars", child2);
}
@Test
- public void testGrandchild() {
- assertSemantics("WEAKAND(100) vehiclebrand:skoda","audi cars", grandchild);
- assertSemantics("WEAKAND(100) vehiclebrand:alfa","alfa bus", grandchild);
- assertSemantics("AND (WEAKAND(100) vehiclebrand:bmw) expensivetv","bmw motorcycle", grandchild);
- assertSemantics("WEAKAND(100) vehiclebrand:skoda","vw cars", grandchild);
- assertSemantics("WEAKAND(100) vehiclebrand:skoda","skoda cars", grandchild);
+ void testGrandchild() {
+ assertSemantics("WEAKAND(100) vehiclebrand:skoda", "audi cars", grandchild);
+ assertSemantics("WEAKAND(100) vehiclebrand:alfa", "alfa bus", grandchild);
+ assertSemantics("AND (WEAKAND(100) vehiclebrand:bmw) expensivetv", "bmw motorcycle", grandchild);
+ assertSemantics("WEAKAND(100) vehiclebrand:skoda", "vw cars", grandchild);
+ assertSemantics("WEAKAND(100) vehiclebrand:skoda", "skoda cars", grandchild);
}
@Test
- public void testRuleBaseNames() {
+ void testRuleBaseNames() {
assertEquals("parent", parent.getName());
assertEquals("child1", child1.getName());
assertEquals("child2", child2.getName());
@@ -132,10 +129,10 @@ public class InheritanceTestCase {
}
@Test
- public void testSearcher() {
- assertSemantics("WEAKAND(100) vehiclebrand:skoda","vw cars", "");
- assertSemantics("WEAKAND(100) vehiclebrand:skoda","vw cars", "&rules.rulebase=grandchild");
- assertSemantics("WEAKAND(100) vehiclebrand:skoda","vw cars", "&rules.rulebase=grandchild.sd");
+ void testSearcher() {
+ assertSemantics("WEAKAND(100) vehiclebrand:skoda", "vw cars", "");
+ assertSemantics("WEAKAND(100) vehiclebrand:skoda", "vw cars", "&rules.rulebase=grandchild");
+ assertSemantics("WEAKAND(100) vehiclebrand:skoda", "vw cars", "&rules.rulebase=grandchild.sd");
try {
assertSemantics("WEAKAND(100) vw cars", "vw cars", "&rules.rulebase=doesntexist");
fail("No exception on missing rule base");
@@ -147,14 +144,14 @@ public class InheritanceTestCase {
assertSemantics("WEAKAND(100) vw cars", "vw cars", "&rules.off");
assertSemantics("WEAKAND(100) vw car", "vw cars", "&rules.rulebase=child2");
- assertSemantics("WEAKAND(100) vehiclebrand:skoda","skoda cars","&rules.rulebase=child2");
+ assertSemantics("WEAKAND(100) vehiclebrand:skoda", "skoda cars", "&rules.rulebase=child2");
- assertSemantics("WEAKAND(100) vehiclebrand:skoda","audi cars", "&rules.rulebase=child1");
- assertSemantics("WEAKAND(100) vehiclebrand:skoda","vw cars", "&rules.rulebase=child1");
- assertSemantics("WEAKAND(100) skoda car", "skoda cars","&rules.rulebase=child1");
+ assertSemantics("WEAKAND(100) vehiclebrand:skoda", "audi cars", "&rules.rulebase=child1");
+ assertSemantics("WEAKAND(100) vehiclebrand:skoda", "vw cars", "&rules.rulebase=child1");
+ assertSemantics("WEAKAND(100) skoda car", "skoda cars", "&rules.rulebase=child1");
assertSemantics("WEAKAND(100) vw car", "vw cars", "&rules.rulebase=parent");
- assertSemantics("WEAKAND(100) skoda car", "skoda cars","&rules.rulebase=parent");
+ assertSemantics("WEAKAND(100) skoda car", "skoda cars", "&rules.rulebase=parent");
}
protected void assertSemantics(String result,String input,String ruleSelection) {
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/LabelMatchingTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/LabelMatchingTestCase.java
index d45e114e89f..0a12ea2c49f 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/LabelMatchingTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/LabelMatchingTestCase.java
@@ -4,7 +4,7 @@ package com.yahoo.prelude.semantics.test;
import java.io.IOException;
import com.yahoo.prelude.semantics.parser.ParseException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Tests label-dependent matching
@@ -19,30 +19,30 @@ public class LabelMatchingTestCase extends RuleBaseAbstractTestCase {
/** Tests that matching with no label matches the default label (index) only */
@Test
- public void testDefaultLabelMatching() throws IOException, ParseException {
- assertSemantics("matched:term","term");
- assertSemantics("alabel:term","alabel:term");
+ void testDefaultLabelMatching() throws IOException, ParseException {
+ assertSemantics("matched:term", "term");
+ assertSemantics("alabel:term", "alabel:term");
- assertSemantics("AND term2 hit","term2");
- assertSemantics("alabel:term2","alabel:term2");
+ assertSemantics("AND term2 hit", "term2");
+ assertSemantics("alabel:term2", "alabel:term2");
}
@Test
- public void testSpecificLabelMatchingInConditionReference() throws IOException, ParseException {
- assertSemantics("+dcattitle:restaurants -dcat:hotel","dcattitle:restaurants");
+ void testSpecificLabelMatchingInConditionReference() throws IOException, ParseException {
+ assertSemantics("+dcattitle:restaurants -dcat:hotel", "dcattitle:restaurants");
}
@Test
- public void testSpecificlabelMatchingInNestedCondition() throws IOException, ParseException {
- assertSemantics("three","foo:one");
- assertSemantics("three","foo:two");
- assertSemantics("bar:one","bar:one");
- assertSemantics("bar:two","bar:two");
- assertSemantics("foo:three","foo:three");
- assertSemantics("one","one");
- assertSemantics("two","two");
- assertSemantics("AND three three","foo:one foo:two");
- assertSemantics("AND bar:one bar:two","bar:one bar:two");
+ void testSpecificlabelMatchingInNestedCondition() throws IOException, ParseException {
+ assertSemantics("three", "foo:one");
+ assertSemantics("three", "foo:two");
+ assertSemantics("bar:one", "bar:one");
+ assertSemantics("bar:two", "bar:two");
+ assertSemantics("foo:three", "foo:three");
+ assertSemantics("one", "one");
+ assertSemantics("two", "two");
+ assertSemantics("AND three three", "foo:one foo:two");
+ assertSemantics("AND bar:one bar:two", "bar:one bar:two");
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/MatchAllTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/MatchAllTestCase.java
index 22b24e1a0b0..270c2789ec5 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/MatchAllTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/MatchAllTestCase.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.prelude.semantics.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* tersts the ellipsis rule base
@@ -15,17 +15,17 @@ public class MatchAllTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testMatchAll() {
- assertSemantics("RANK a normtitle:a","a");
- assertSemantics("RANK (AND a b) normtitle:\"a b\"","a b");
- assertSemantics("RANK (AND a a b a) normtitle:\"a a b a\"","a a b a");
+ void testMatchAll() {
+ assertSemantics("RANK a normtitle:a", "a");
+ assertSemantics("RANK (AND a b) normtitle:\"a b\"", "a b");
+ assertSemantics("RANK (AND a a b a) normtitle:\"a a b a\"", "a a b a");
}
@Test
- public void testMatchAllFilterIsIgnored() {
- assertSemantics("RANK a |b normtitle:a","a&filter=b");
- assertSemantics("RANK (AND a b) |b |c normtitle:\"a b\"","a b&filter=b c");
- assertSemantics("RANK (AND a a b a) |a |a |c |d |b normtitle:\"a a b a\"","a a b a&filter=a a c d b");
+ void testMatchAllFilterIsIgnored() {
+ assertSemantics("RANK a |b normtitle:a", "a&filter=b");
+ assertSemantics("RANK (AND a b) |b |c normtitle:\"a b\"", "a b&filter=b c");
+ assertSemantics("RANK (AND a a b a) |a |a |c |d |b normtitle:\"a a b a\"", "a a b a&filter=a a c d b");
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/MatchOnlyIfNotOnlyTermTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/MatchOnlyIfNotOnlyTermTestCase.java
index c398f0ed99e..30a88e74e91 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/MatchOnlyIfNotOnlyTermTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/MatchOnlyIfNotOnlyTermTestCase.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.prelude.semantics.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Experiments with a way to match only if it doesn't remove all hard conditions in the query.
@@ -16,13 +16,13 @@ public class MatchOnlyIfNotOnlyTermTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testMatch() {
+ void testMatch() {
assertSemantics("RANK showname:\"saturday night live\"!1000 (AND justin timberlake)", "justin timberlake snl");
assertSemantics("RANK showname:\"saturday night live\"!1000 (AND justin timberlake)", "justin timberlake saturday night live");
}
@Test
- public void testNoMatch() {
+ void testNoMatch() {
// TODO: This shows that we do match, i.e that currently the behavior is undesired
assertSemantics("showname:\"saturday night live\"!1000", "snl");
assertSemantics("showname:\"saturday night live\"!1000", "saturday night live");
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/MusicTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/MusicTestCase.java
index 006dcb3c714..49766cc027c 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/MusicTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/MusicTestCase.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.prelude.semantics.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Tests the rewriting in the semanticsearcher system test
@@ -11,7 +11,7 @@ import org.junit.Test;
public class MusicTestCase {
@Test
- public void testMusic() {
+ void testMusic() {
var tester = new RuleBaseTester("music.sr");
tester.assertSemantics("AND song:together artist:youngbloods", "together by youngbloods");
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/NoStemmingTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/NoStemmingTestCase.java
index fbdd72fe6ac..04bc3249efe 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/NoStemmingTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/NoStemmingTestCase.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.prelude.semantics.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Tests a case reported by tularam
@@ -16,20 +16,20 @@ public class NoStemmingTestCase extends RuleBaseAbstractTestCase {
/** Should rewrite correctly */
@Test
- public void testCorrectRewriting1() {
- assertSemantics("+(AND i:arts i:sciences TRUE) -i:b","i:as -i:b");
+ void testCorrectRewriting1() {
+ assertSemantics("+(AND i:arts i:sciences TRUE) -i:b", "i:as -i:b");
}
/** Should rewrite correctly too */
@Test
- public void testCorrectRewriting2() {
- assertSemantics("+(AND i:arts i:sciences i:crafts TRUE) -i:b","i:asc -i:b");
+ void testCorrectRewriting2() {
+ assertSemantics("+(AND i:arts i:sciences i:crafts TRUE) -i:b", "i:asc -i:b");
}
/** Should not rewrite */
@Test
- public void testNoRewriting() {
- assertSemantics("+i:a -i:s","i:a -i:s");
+ void testNoRewriting() {
+ assertSemantics("+i:a -i:s", "i:a -i:s");
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/NotTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/NotTestCase.java
index c76db0a7afd..0ec320c7780 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/NotTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/NotTestCase.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.prelude.semantics.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* @author bratseth
@@ -13,11 +13,11 @@ public class NotTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testLiteralEquals() {
- assertSemantics("RANK a foo:a","a");
- assertSemantics("a","a&ranking=category");
- assertSemantics("RANK a foo:a","a&ranking=somethingelse");
- assertSemantics("RANK a foo:a","a&otherparam=category");
+ void testLiteralEquals() {
+ assertSemantics("RANK a foo:a", "a");
+ assertSemantics("a", "a&ranking=category");
+ assertSemantics("RANK a foo:a", "a&ranking=somethingelse");
+ assertSemantics("RANK a foo:a", "a&otherparam=category");
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/NumbersTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/NumbersTestCase.java
index b18cafdd161..60ccaa35cc4 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/NumbersTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/NumbersTestCase.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.prelude.semantics.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Tests numbers as conditions and productions
@@ -15,13 +15,13 @@ public class NumbersTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testNumbers() {
- assertSemantics("elite","1337");
- assertSemantics("1","one");
- assertSemantics("AND bort ned","opp");
- assertSemantics("AND kanoo knagg","foo bar");
- assertSemantics("AND 3 three","two 2");
- assertSemantics("AND 1 elite","one 1337");
+ void testNumbers() {
+ assertSemantics("elite", "1337");
+ assertSemantics("1", "one");
+ assertSemantics("AND bort ned", "opp");
+ assertSemantics("AND kanoo knagg", "foo bar");
+ assertSemantics("AND 3 three", "two 2");
+ assertSemantics("AND 1 elite", "one 1337");
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/NumericTermsTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/NumericTermsTestCase.java
index f76deeacbb5..b63b3579c76 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/NumericTermsTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/NumericTermsTestCase.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.prelude.semantics.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Tests numeric terms
@@ -15,13 +15,13 @@ public class NumericTermsTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testNumericProduction() {
- assertSemantics("+restaurants -ycat2gc:96929265","restaurants");
+ void testNumericProduction() {
+ assertSemantics("+restaurants -ycat2gc:96929265", "restaurants");
}
@Test
- public void testNumericConditionAndProduction() {
- assertSemantics("48","49");
+ void testNumericConditionAndProduction() {
+ assertSemantics("48", "49");
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/OrPhraseTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/OrPhraseTestCase.java
index 1d6eea8d7de..045d8698547 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/OrPhraseTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/OrPhraseTestCase.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.prelude.semantics.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* @author bratseth
@@ -13,14 +13,14 @@ public class OrPhraseTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testReplacing1() {
- assertSemantics("OR title:\"software engineer\" (AND new york)","software engineer new york");
- assertSemantics("title:\"software engineer\"","software engineer"); // Skip or when there is nothing else
+ void testReplacing1() {
+ assertSemantics("OR title:\"software engineer\" (AND new york)", "software engineer new york");
+ assertSemantics("title:\"software engineer\"", "software engineer"); // Skip or when there is nothing else
}
@Test
- public void testReplacing2() {
- assertSemantics("OR lotr \"lord of the rings\"","lotr");
+ void testReplacing2() {
+ assertSemantics("OR lotr \"lord of the rings\"", "lotr");
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/Parameter2TestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/Parameter2TestCase.java
index 5b1c38b7752..b9332effcb7 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/Parameter2TestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/Parameter2TestCase.java
@@ -2,9 +2,9 @@
package com.yahoo.prelude.semantics.test;
import com.yahoo.search.Query;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Tests parameter matching and production
@@ -19,8 +19,8 @@ public class Parameter2TestCase extends RuleBaseAbstractTestCase {
/** Tests parameter production */
@Test
- public void testParameterProduction() {
- assertRankParameterSemantics("WEAKAND(100) a","a&ranking=usrank","date",0);
+ void testParameterProduction() {
+ assertRankParameterSemantics("WEAKAND(100) a", "a&ranking=usrank", "date", 0);
}
private void assertRankParameterSemantics(String producedQuery,String inputQuery,
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/ParameterTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/ParameterTestCase.java
index b597443d1d3..7df1ccbc156 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/ParameterTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/ParameterTestCase.java
@@ -2,9 +2,9 @@
package com.yahoo.prelude.semantics.test;
import com.yahoo.search.Query;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Tests parameter matching and production
@@ -19,7 +19,7 @@ public class ParameterTestCase extends RuleBaseAbstractTestCase {
/** Tests parameter literal matching */
@Test
- public void testLiteralEquals() {
+ void testLiteralEquals() {
assertSemantics("a", "a");
assertSemantics("RANK a foo:a", "a&ranking=category");
assertSemantics("a", "a&ranking=somethingelse");
@@ -28,7 +28,7 @@ public class ParameterTestCase extends RuleBaseAbstractTestCase {
/** Tests parameter matching of larger */
@Test
- public void testLarger() {
+ void testLarger() {
assertSemantics("a", "a");
assertSemantics("AND a largepage", "a&hits=11");
assertSemantics("AND a largepage", "a&hits=12");
@@ -36,8 +36,8 @@ public class ParameterTestCase extends RuleBaseAbstractTestCase {
/** Tests parameter containment matching */
@Test
- public void testContainsAsList() {
- assertSemantics("a","a");
+ void testContainsAsList() {
+ assertSemantics("a", "a");
assertSemantics("AND a intent:music", "a&search=music");
assertSemantics("AND a intent:music", "a&search=music,books");
assertSemantics("AND a intent:music", "a&search=kanoos,music,books");
@@ -45,7 +45,7 @@ public class ParameterTestCase extends RuleBaseAbstractTestCase {
/** Tests parameter production */
@Test
- public void testParameterProduction() {
+ void testParameterProduction() {
assertParameterSemantics("AND a b c", "a b c", "search", "[letters, alphabet]");
assertParameterSemantics("AND a c d", "a c d", "search", "[letters, someletters]");
assertParameterSemantics("+(AND a d e) -letter:c", "a d e", "search", "[someletters]");
@@ -54,7 +54,7 @@ public class ParameterTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testMultipleAlternativeParameterValuesInCondition() {
+ void testMultipleAlternativeParameterValuesInCondition() {
assertInputRankParameterSemantics("WEAKAND(100) one", "foo", "cat");
assertInputRankParameterSemantics("WEAKAND(100) one", "foo", "cat0");
assertInputRankParameterSemantics("WEAKAND(100) one", "bar", "cat");
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/PhraseMatchTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/PhraseMatchTestCase.java
index fd9003e0e05..9536c1bfb7c 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/PhraseMatchTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/PhraseMatchTestCase.java
@@ -1,8 +1,8 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.semantics.test;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
/**
* Tests that the phrase produced by an automata match can subsequently be replaced by an AND of the
@@ -16,14 +16,15 @@ public class PhraseMatchTestCase extends RuleBaseAbstractTestCase {
super("phrasematch.sr", "semantics.fsa");
}
+ // TODO: Work in progress
@Test
- @Ignore // TODO: Work in progress
- public void testLiteralEquals() {
- assertSemantics("AND retailer:digital retailer:camera","keyword:digital keyword:camera");
+ @Disabled
+ void testLiteralEquals() {
+ assertSemantics("AND retailer:digital retailer:camera", "keyword:digital keyword:camera");
}
@Test
- public void testMatchingPhrase() {
+ void testMatchingPhrase() {
assertSemantics("OR (AND iphone 7) i7", "iphone 7");
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/ProductionRuleTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/ProductionRuleTestCase.java
index e892adc3b1c..44ebd4f1995 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/ProductionRuleTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/ProductionRuleTestCase.java
@@ -15,10 +15,10 @@ import com.yahoo.prelude.semantics.rule.ReferenceTermProduction;
import com.yahoo.prelude.semantics.rule.ReplacingProductionRule;
import com.yahoo.prelude.semantics.rule.TermCondition;
import com.yahoo.prelude.semantics.rule.TermProduction;
-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;
/**
* @author bratseth
@@ -26,7 +26,7 @@ import static org.junit.Assert.assertTrue;
public class ProductionRuleTestCase {
@Test
- public void testProductionRule() {
+ void testProductionRule() {
var linguistics = new RuleBaseLinguistics(new SimpleLinguistics());
TermCondition term = new TermCondition("sony", linguistics);
NamedCondition named = new NamedCondition("brand", term);
@@ -46,7 +46,7 @@ public class ProductionRuleTestCase {
ruleBase.addRule(rule);
ruleBase.initialize();
- assertTrue("Brand is referenced", rule.matchReferences().contains("brand"));
+ assertTrue(rule.matchReferences().contains("brand"), "Brand is referenced");
Query query = new Query("?query=sony");
RuleEvaluation e = new Evaluation(query, null).freshRuleEvaluation();
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/RuleBaseAbstractTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/RuleBaseAbstractTestCase.java
index 84e47edae29..668251c0a1f 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/RuleBaseAbstractTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/RuleBaseAbstractTestCase.java
@@ -14,7 +14,7 @@ import com.yahoo.search.test.QueryTestCase;
import java.util.ArrayList;
import java.util.List;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* DO NOT USE. Use RuleBaseTester instead
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/RuleBaseTester.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/RuleBaseTester.java
index cc9e758a0e0..dc43ffc55e7 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/RuleBaseTester.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/RuleBaseTester.java
@@ -14,7 +14,7 @@ import com.yahoo.search.test.QueryTestCase;
import java.util.ArrayList;
import java.util.List;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Helper for testing with a rule base.
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/SegmentSubstitutionTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/SegmentSubstitutionTestCase.java
index 69faed1da90..8d7c16f5544 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/SegmentSubstitutionTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/SegmentSubstitutionTestCase.java
@@ -8,8 +8,7 @@ import com.yahoo.prelude.query.parser.TestLinguistics;
import com.yahoo.search.Query;
import com.yahoo.search.query.parser.Parsable;
import com.yahoo.search.query.parser.ParserEnvironment;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
public class SegmentSubstitutionTestCase extends RuleBaseAbstractTestCase {
@@ -18,7 +17,7 @@ public class SegmentSubstitutionTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testBasicSubstitution() {
+ void testBasicSubstitution() {
Item a = parseQuery("firstsecond");
Query q = new Query("?query=ignored&tracelevel=0&tracelevel.rules=0");
q.getModel().getQueryTree().setRoot(a);
@@ -27,7 +26,7 @@ public class SegmentSubstitutionTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testSubstitutionAndMoreTerms() {
+ void testSubstitutionAndMoreTerms() {
Item a = parseQuery("bcfirstsecondfg");
Query q = new Query("?query=ignored&tracelevel=0&tracelevel.rules=0");
q.getModel().getQueryTree().setRoot(a);
@@ -36,7 +35,7 @@ public class SegmentSubstitutionTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testSubstitutionAndNot() {
+ void testSubstitutionAndNot() {
Item a = parseQuery("-firstsecond bc");
Query q = new Query("?query=ignored&tracelevel=0&tracelevel.rules=0");
q.getModel().getQueryTree().setRoot(a);
@@ -45,7 +44,7 @@ public class SegmentSubstitutionTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testSubstitutionSomeNoise() {
+ void testSubstitutionSomeNoise() {
Item a = parseQuery("9270bcsecond2389");
Query q = new Query("?query=ignored&tracelevel=0&tracelevel.rules=0");
q.getModel().getQueryTree().setRoot(a);
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/SemanticSearcherTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/SemanticSearcherTestCase.java
index bee65db4347..489afcb3088 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/SemanticSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/SemanticSearcherTestCase.java
@@ -8,12 +8,12 @@ import com.yahoo.prelude.query.NullItem;
import com.yahoo.search.Result;
import com.yahoo.search.Searcher;
import com.yahoo.search.searchchain.Execution;
-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.jupiter.api.Assertions.assertEquals;
/**
* Tests semantic searching
@@ -27,128 +27,128 @@ public class SemanticSearcherTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testSingleShopping() {
+ void testSingleShopping() {
assertSemantics("brand:sony",
- "sony");
+ "sony");
assertSemantics("brand:sony!150",
- "sony!150");
+ "sony!150");
}
@Test
- public void testCombinedShopping() {
+ void testCombinedShopping() {
assertSemantics("AND brand:sony category:camera",
- "sony camera");
+ "sony camera");
}
@Test
- public void testPhrasedShopping() {
+ void testPhrasedShopping() {
assertSemantics("AND brand:sony category:\"digital camera\"",
- "sony digital camera");
+ "sony digital camera");
}
@Test
- public void testSimpleLocal() {
+ void testSimpleLocal() {
assertSemantics("AND listing:restaurant place:geary",
- "restaurant in geary");
+ "restaurant in geary");
}
@Test
- public void testLocal() {
+ void testLocal() {
assertSemantics("AND listing:restaurant place:\"geary street san francisco\"",
- "restaurant in geary street san francisco");
+ "restaurant in geary street san francisco");
}
@Test
- public void testLiteralReplacing() {
+ void testLiteralReplacing() {
assertSemantics("AND lord of rings", "lotr");
}
@Test
- public void testAddingAnd() {
+ void testAddingAnd() {
assertSemantics("AND bar foobar:bar",
- "bar");
+ "bar");
}
@Test
- public void testAddingRank() {
+ void testAddingRank() {
assertSemantics("RANK word foobar:word",
- "word");
+ "word");
}
@Test
- public void testFilterIsIgnored() {
+ void testFilterIsIgnored() {
assertSemantics("RANK word |a |word |b foobar:word",
- "word&filter=a word b");
+ "word&filter=a word b");
assertSemantics("RANK a |word |b",
- "a&filter=word b");
+ "a&filter=word b");
}
@Test
- public void testAddingNegative() {
+ void testAddingNegative() {
assertSemantics("+java -coffee",
- "java");
+ "java");
}
@Test
- public void testAddingNegativePluralToSingular() {
+ void testAddingNegativePluralToSingular() {
assertSemantics("+javas -coffee",
- "javas");
+ "javas");
}
@Test
- public void testCombined() {
+ void testCombined() {
assertSemantics("AND bar listing:restaurant place:\"geary street san francisco\" foobar:bar",
- "bar restaurant in geary street san francisco");
+ "bar restaurant in geary street san francisco");
}
@Test
- public void testStopWord() {
- assertSemantics("strokes","the strokes");
+ void testStopWord() {
+ assertSemantics("strokes", "the strokes");
}
@Test
- public void testStopWords1() {
- assertSemantics("strokes","be the strokes");
+ void testStopWords1() {
+ assertSemantics("strokes", "be the strokes");
}
@Test
- public void testStopWords2() {
- assertSemantics("strokes","the strokes be");
+ void testStopWords2() {
+ assertSemantics("strokes", "the strokes be");
}
@Test
- public void testDontRemoveEverything() {
- assertSemantics("the","the the the");
+ void testDontRemoveEverything() {
+ assertSemantics("the", "the the the");
}
@Test
- public void testMoreStopWordRemoval() {
- assertSemantics("hamlet","hamlet to be or not to be");
+ void testMoreStopWordRemoval() {
+ assertSemantics("hamlet", "hamlet to be or not to be");
}
@Test
- public void testTypeChange() {
- assertSemantics("RANK default:typechange doors","typechange doors");
+ void testTypeChange() {
+ assertSemantics("RANK default:typechange doors", "typechange doors");
}
@Test
- public void testTypeChangeWithSingularToPluralButNonReplaceWillNotSingularify() {
- assertSemantics("RANK default:typechange door","typechange door");
+ void testTypeChangeWithSingularToPluralButNonReplaceWillNotSingularify() {
+ assertSemantics("RANK default:typechange door", "typechange door");
}
@Test
- public void testExplicitContext() {
- assertSemantics("AND from:paris to:texas","paris to texas");
+ void testExplicitContext() {
+ assertSemantics("AND from:paris to:texas", "paris to texas");
}
@Test
- public void testOrProduction() {
+ void testOrProduction() {
assertSemantics("OR something somethingelse", "something");
}
// This test is order dependent. Fix it!!
@Test
- public void testWeightedSetItem() {
+ void testWeightedSetItem() {
Query q = new Query();
WeightedSetItem weightedSet = new WeightedSetItem("fieldName");
weightedSet.addToken("a", 1);
@@ -158,7 +158,7 @@ public class SemanticSearcherTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testNullQuery() {
+ void testNullQuery() {
Query query = new Query(""); // Causes a query containing a NullItem
doSearch(searcher, query, 0, 10);
assertEquals(NullItem.class, query.getModel().getQueryTree().getRoot().getClass()); // Still a NullItem
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/StemmingTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/StemmingTestCase.java
index b8efbf7422b..c5277bf6ef6 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/StemmingTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/StemmingTestCase.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.prelude.semantics.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Tests stemming.
@@ -11,43 +11,43 @@ import org.junit.Test;
public class StemmingTestCase {
@Test
- public void testRewritingDueToStemmingInQuery() {
+ void testRewritingDueToStemmingInQuery() {
var tester = new RuleBaseTester("stemming.sr");
tester.assertSemantics("+(AND i:vehicle TRUE) -i:s", "i:cars -i:s");
}
@Test
- public void testNoRewritingDueToStemmingInQueryWhenStemmingDisabled() {
+ void testNoRewritingDueToStemmingInQueryWhenStemmingDisabled() {
var tester = new RuleBaseTester("stemming-none.sr");
tester.assertSemantics("+i:cars -i:s", "i:cars -i:s");
}
@Test
- public void testRewritingDueToStemmingInRule() {
+ void testRewritingDueToStemmingInRule() {
var tester = new RuleBaseTester("stemming.sr");
tester.assertSemantics("+(AND i:animal TRUE) -i:s", "i:horse -i:s");
}
@Test
- public void testNoRewritingDueToStemmingInRuleWhenStemmingDisabled() {
+ void testNoRewritingDueToStemmingInRuleWhenStemmingDisabled() {
var tester = new RuleBaseTester("stemming-none.sr");
tester.assertSemantics("+i:horse -i:s", "i:horse -i:s");
}
@Test
- public void testRewritingDueToExactMatch() {
+ void testRewritingDueToExactMatch() {
var tester = new RuleBaseTester("stemming.sr");
tester.assertSemantics("+(AND i:arts i:sciences TRUE) -i:s", "i:as -i:s");
}
@Test
- public void testEnglishStemming() {
+ void testEnglishStemming() {
var tester = new RuleBaseTester("stemming.sr");
tester.assertSemantics("i:drive", "i:going");
}
@Test
- public void testFrenchStemming() {
+ void testFrenchStemming() {
var tester = new RuleBaseTester("stemming-french.sr");
tester.assertSemantics("i:going", "i:going");
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/StopwordTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/StopwordTestCase.java
index a0c2cf4545c..207ae7f8877 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/StopwordTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/StopwordTestCase.java
@@ -3,7 +3,7 @@ package com.yahoo.prelude.semantics.test;
import com.yahoo.search.Query;
import com.yahoo.search.test.QueryTestCase;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Tests numeric terms
@@ -17,21 +17,21 @@ public class StopwordTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testStopwords() {
+ void testStopwords() {
assertSemantics("WEAKAND(100) mlr:ve mlr:heard mlr:beautiful mlr:world",
- new Query(QueryTestCase.httpEncode("?query=i don't know if you've heard, but it's a beautiful world&default-index=mlr&tracelevel.rules=0")));
+ new Query(QueryTestCase.httpEncode("?query=i don't know if you've heard, but it's a beautiful world&default-index=mlr&tracelevel.rules=0")));
}
/** If the query contains nothing but stopwords, we won't remove them */
@Test
- public void testOnlyStopwords() {
+ void testOnlyStopwords() {
assertSemantics("WEAKAND(100) mlr:the", new Query(QueryTestCase.httpEncode("?query=the the&default-index=mlr&tracelevel.rules=0")));
}
@Test
- public void testStopwordsInPhrase() {
+ void testStopwordsInPhrase() {
assertSemantics("WEAKAND(100) mlr:\"ve heard\" mlr:beautiful mlr:world",
- new Query(QueryTestCase.httpEncode("?query=\"i don't know if you've heard\", but it's a beautiful world&default-index=mlr&tracelevel.rules=0")));
+ new Query(QueryTestCase.httpEncode("?query=\"i don't know if you've heard\", but it's a beautiful world&default-index=mlr&tracelevel.rules=0")));
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/SynonymTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/SynonymTestCase.java
index 8f69be2f710..65001cfcd44 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/SynonymTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/SynonymTestCase.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.prelude.semantics.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* @author bratseth
@@ -9,7 +9,7 @@ import org.junit.Test;
public class SynonymTestCase {
@Test
- public void testReplacingBySynonyms() {
+ void testReplacingBySynonyms() {
var tester = new RuleBaseTester("synonyms.sr");
tester.assertSemantics("EQUIV index1:foo index1:baz index1:bar", "index1:foo");
tester.assertSemantics("EQUIV index1:foo index1:baz index1:bar", "index1:bar");
@@ -20,7 +20,7 @@ public class SynonymTestCase {
}
@Test
- public void testAddingSynonyms() {
+ void testAddingSynonyms() {
var tester = new RuleBaseTester("synonyms.sr");
tester.assertSemantics("EQUIV index2:foo index2:baz index2:bar", "index2:foo");
tester.assertSemantics("EQUIV index2:bar index2:foo index2:baz", "index2:bar");
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/UrlTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/UrlTestCase.java
index 9bc64370030..c9eb30b3578 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/UrlTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/UrlTestCase.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.prelude.semantics.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Tests working with url indexes
@@ -15,8 +15,8 @@ public class UrlTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testFromDefaultToUrlIndex() {
- assertSemantics("fromurl:\"youtube com\"","youtube.com");
+ void testFromDefaultToUrlIndex() {
+ assertSemantics("fromurl:\"youtube com\"", "youtube.com");
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/semantics/test/WeightingTestCase.java b/container-search/src/test/java/com/yahoo/prelude/semantics/test/WeightingTestCase.java
index d89e6fdbfa3..e5d7408f3c0 100644
--- a/container-search/src/test/java/com/yahoo/prelude/semantics/test/WeightingTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/semantics/test/WeightingTestCase.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.prelude.semantics.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* @author bratseth
@@ -13,7 +13,7 @@ public class WeightingTestCase extends RuleBaseAbstractTestCase {
}
@Test
- public void testWeighting() {
+ void testWeighting() {
assertSemantics("foo!150", "foo");
assertSemantics("AND foo!150 snip", "foo snip");
assertSemantics("AND foo!150 bar", "foo bar");
diff --git a/container-search/src/test/java/com/yahoo/prelude/test/GetRawWordTestCase.java b/container-search/src/test/java/com/yahoo/prelude/test/GetRawWordTestCase.java
index 9ed84298838..edf039723fd 100644
--- a/container-search/src/test/java/com/yahoo/prelude/test/GetRawWordTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/test/GetRawWordTestCase.java
@@ -4,9 +4,9 @@ package com.yahoo.prelude.test;
import com.yahoo.prelude.query.AndItem;
import com.yahoo.prelude.query.WordItem;
import com.yahoo.search.Query;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Tests a case reported by MSBE
@@ -16,27 +16,28 @@ import static org.junit.Assert.assertEquals;
public class GetRawWordTestCase {
@Test
- public void testGetRawWord() {
+ void testGetRawWord() {
Query query = new Query("?query=%C4%B0%C5%9EBANKASI%20GAZ%C4%B0EM%C4%B0R&type=all&searchChain=vespa");
assertEquals("AND \u0130\u015EBANKASI GAZ\u0130EM\u0130R", query.getModel().getQueryTree().toString());
- AndItem root = (AndItem)query.getModel().getQueryTree().getRoot();
+ AndItem root = (AndItem) query.getModel().getQueryTree().getRoot();
{
- WordItem word = (WordItem)root.getItem(0);
+ WordItem word = (WordItem) root.getItem(0);
assertEquals("\u0130\u015EBANKASI", word.getRawWord());
assertEquals(0, word.getOrigin().start);
assertEquals(9, word.getOrigin().end);
}
{
- WordItem word = (WordItem)root.getItem(1);
+ WordItem word = (WordItem) root.getItem(1);
assertEquals("GAZ\u0130EM\u0130R", word.getRawWord());
assertEquals(10, word.getOrigin().start);
assertEquals(18, word.getOrigin().end);
}
- assertEquals("Total string is just these words",18,
- ((WordItem)root.getItem(0)).getOrigin().getSuperstring().length());
+ assertEquals(18,
+ ((WordItem) root.getItem(0)).getOrigin().getSuperstring().length(),
+ "Total string is just these words");
}
}
diff --git a/container-search/src/test/java/com/yahoo/prelude/test/IndexFactsTestCase.java b/container-search/src/test/java/com/yahoo/prelude/test/IndexFactsTestCase.java
index 6a54492f5e5..4b24ba3671e 100644
--- a/container-search/src/test/java/com/yahoo/prelude/test/IndexFactsTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/test/IndexFactsTestCase.java
@@ -11,7 +11,8 @@ import com.yahoo.prelude.SearchDefinition;
import com.yahoo.search.Query;
import com.yahoo.search.config.IndexInfoConfig;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
@@ -20,10 +21,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
-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 using synthetic index names for IndexFacts class.
@@ -58,7 +56,7 @@ public class IndexFactsTestCase {
}
@Test
- public void testBasicCases() {
+ void testBasicCases() {
// First check default behavior
IndexFacts indexFacts = createIndexFacts();
Query q = newQuery("?query=a:b", indexFacts);
@@ -68,7 +66,7 @@ public class IndexFactsTestCase {
}
@Test
- public void testDefaultPosition() {
+ void testDefaultPosition() {
Index a = new Index("a");
assertFalse(a.isDefaultPosition());
a.addCommand("any");
@@ -80,21 +78,21 @@ public class IndexFactsTestCase {
sd.addCommand("b", "any");
assertNull(sd.getDefaultPosition());
sd.addCommand("c", "default-position");
- assertTrue(sd.getDefaultPosition().equals("c"));
+ assertEquals(sd.getDefaultPosition(), "c");
SearchDefinition sd2 = new SearchDefinition("sd2");
sd2.addIndex(new Index("b").addCommand("any"));
assertNull(sd2.getDefaultPosition());
sd2.addIndex(a);
- assertTrue(sd2.getDefaultPosition().equals("a"));
+ assertEquals(sd2.getDefaultPosition(), "a");
IndexFacts indexFacts = createIndexFacts(ImmutableList.of(sd, sd2));
- assertTrue(indexFacts.getDefaultPosition(null).equals("a"));
- assertTrue(indexFacts.getDefaultPosition("sd").equals("c"));
+ assertEquals(indexFacts.getDefaultPosition(null), "a");
+ assertEquals(indexFacts.getDefaultPosition("sd"), "c");
}
@Test
- public void testIndicesInAnyConfigurationAreIndicesInDefault() {
+ void testIndicesInAnyConfigurationAreIndicesInDefault() {
IndexFacts.Session indexFacts = createIndexFacts().newSession(new Query());
assertTrue(indexFacts.isIndex("a"));
assertTrue(indexFacts.isIndex("b"));
@@ -104,21 +102,21 @@ public class IndexFactsTestCase {
}
@Test
- public void testDefaultIsUnionHostIndex() {
+ void testDefaultIsUnionHostIndex() {
IndexFacts.Session session = createIndexFacts().newSession(new Query());
assertTrue(session.getIndex("c").isHostIndex());
assertFalse(session.getIndex("a").isHostIndex());
}
@Test
- public void testDefaultIsUnionUriIndex() {
+ void testDefaultIsUnionUriIndex() {
IndexFacts indexFacts = createIndexFacts();
assertTrue(indexFacts.newSession(new Query()).getIndex("d").isUriIndex());
assertFalse(indexFacts.newSession(new Query()).getIndex("a").isUriIndex());
}
@Test
- public void testDefaultIsUnionStemMode() {
+ void testDefaultIsUnionStemMode() {
IndexFacts.Session session = createIndexFacts().newSession(new Query());
assertEquals(StemMode.NONE, session.getIndex("a").getStemMode());
assertEquals(StemMode.NONE, session.getIndex("b").getStemMode());
@@ -140,7 +138,7 @@ public class IndexFactsTestCase {
}
@Test
- public void testExactMatching() {
+ void testExactMatching() {
assertExactIsWorking("test");
assertExactIsWorking("artist_name_ft_norm1");
@@ -157,7 +155,7 @@ public class IndexFactsTestCase {
Index e = nullSession.getIndex("e");
assertTrue(e.isExact());
- assertEquals("kj(/&",e.getExactTerminator());
+ assertEquals("kj(/&", e.getExactTerminator());
Index a = nullSession.getIndex("a");
assertFalse(a.isExact());
@@ -169,7 +167,7 @@ public class IndexFactsTestCase {
}
@Test
- public void testComplexExactMatching() {
+ void testComplexExactMatching() {
SearchDefinition sd = new SearchDefinition("foobar");
String u_name = "foo_bar";
Index u_index = new Index(u_name);
@@ -190,7 +188,7 @@ public class IndexFactsTestCase {
// This is also backed by a system test on cause of complex config
@Test
- public void testRestrictLists1() {
+ void testRestrictLists1() {
Query query = new Query();
query.getModel().getSources().add("nalle");
query.getModel().getSources().add("one");
@@ -203,7 +201,7 @@ public class IndexFactsTestCase {
}
@Test
- public void testRestrictLists2() {
+ void testRestrictLists2() {
Query query = new Query();
query.getModel().getSources().add("clusterTwo");
query.getModel().getRestrict().add("three");
@@ -223,7 +221,7 @@ public class IndexFactsTestCase {
}
@Test
- public void testRestrictLists3() {
+ void testRestrictLists3() {
Query query = new Query();
query.getModel().getSources().add("clusterOne");
query.getModel().getRestrict().add("two");
@@ -242,7 +240,7 @@ public class IndexFactsTestCase {
}
@Test
- public void testPredicateBounds() {
+ void testPredicateBounds() {
Index index = new Index("a");
assertEquals(Long.MIN_VALUE, index.getPredicateLowerBound());
assertEquals(Long.MAX_VALUE, index.getPredicateUpperBound());
@@ -264,7 +262,7 @@ public class IndexFactsTestCase {
}
@Test
- public void testUriIndexAndRestrict() {
+ void testUriIndexAndRestrict() {
IndexInfoConfig.Builder b = new IndexInfoConfig.Builder();
IndexInfoConfig.Indexinfo.Builder b1 = new IndexInfoConfig.Indexinfo.Builder();
@@ -298,7 +296,7 @@ public class IndexFactsTestCase {
}
@Test
- public void testConflictingAliases() {
+ void testConflictingAliases() {
SearchDefinition first = new SearchDefinition("first");
Index field1 = new Index("field1");
first.addIndex(field1);
diff --git a/container-search/src/test/java/com/yahoo/prelude/test/IntegrationTestCase.java b/container-search/src/test/java/com/yahoo/prelude/test/IntegrationTestCase.java
index b34edbf208c..10573b63bdc 100644
--- a/container-search/src/test/java/com/yahoo/prelude/test/IntegrationTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/test/IntegrationTestCase.java
@@ -5,7 +5,7 @@ import com.yahoo.search.result.Hit;
import com.yahoo.search.Result;
import com.yahoo.search.Searcher;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Runs a query thru the configured search chain from a real http channel
@@ -32,8 +32,8 @@ public class IntegrationTestCase {
}
@Test
- public void testQuery() throws java.io.IOException {
- /*
+ void testQuery() throws java.io.IOException {
+ /*
TODO: (JSB) This blocks forever on Linux (not Windows) because
the ServerSocketChannel.accept method in Server
seems to starve the test running thread,
diff --git a/container-search/src/test/java/com/yahoo/prelude/test/LocationTestCase.java b/container-search/src/test/java/com/yahoo/prelude/test/LocationTestCase.java
index 07750613249..96a24ac92c8 100644
--- a/container-search/src/test/java/com/yahoo/prelude/test/LocationTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/test/LocationTestCase.java
@@ -2,9 +2,9 @@
package com.yahoo.prelude.test;
import com.yahoo.prelude.Location;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Tests the Location class. Currently does not test all "features" of Location class.
@@ -14,7 +14,7 @@ import static org.junit.Assert.assertEquals;
public class LocationTestCase {
@Test
- public void testAspect() {
+ void testAspect() {
//0 degrees latitude, on the equator
Location loc1 = new Location("[2,-1110000,330000,-1160000,340000](2,-1100222,0,300,0,1,0,CalcLatLon)");
assertEquals(loc1.toString(), "[2,-1110000,330000,-1160000,340000](2,-1100222,0,300,0,1,0,4294967295)");
diff --git a/container-search/src/test/java/com/yahoo/prelude/test/NullSetMemberTestCase.java b/container-search/src/test/java/com/yahoo/prelude/test/NullSetMemberTestCase.java
index e77f0d00578..495f11e0780 100644
--- a/container-search/src/test/java/com/yahoo/prelude/test/NullSetMemberTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/test/NullSetMemberTestCase.java
@@ -1,13 +1,11 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.prelude.test;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.HashSet;
-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 null members in HashSet
@@ -15,7 +13,7 @@ import static org.junit.Assert.assertTrue;
public class NullSetMemberTestCase {
@Test
- public void testNullMember() {
+ void testNullMember() {
HashSet<?> s = new HashSet<>();
assertEquals(s.size(), 0);
assertFalse(s.contains(null));
diff --git a/container-search/src/test/java/com/yahoo/prelude/test/QueryTestCase.java b/container-search/src/test/java/com/yahoo/prelude/test/QueryTestCase.java
index eaab7e12f33..95ecf3c2dba 100644
--- a/container-search/src/test/java/com/yahoo/prelude/test/QueryTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/test/QueryTestCase.java
@@ -14,12 +14,12 @@ import com.yahoo.search.Query;
import com.yahoo.search.query.Sorting;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.yolean.Exceptions;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
import java.util.List;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Tests for query class
@@ -29,7 +29,7 @@ import static org.junit.Assert.*;
public class QueryTestCase {
@Test
- public void testBoolItem() {
+ void testBoolItem() {
var original = new BoolItem(false);
var cloned = original.clone();
assertNotSame(original, cloned);
@@ -37,7 +37,7 @@ public class QueryTestCase {
}
@Test
- public void testSimpleQueryParsing () {
+ void testSimpleQueryParsing() {
Query q = newQuery("/search?query=foobar&offset=10&hits=20&type=all");
assertEquals("foobar", ((WordItem) q.getModel().getQueryTree().getRoot()).getWord());
assertEquals(10, q.getOffset());
@@ -45,7 +45,7 @@ public class QueryTestCase {
}
@Test
- public void testAdvancedQueryParsing () {
+ void testAdvancedQueryParsing() {
Query q = newQuery("/search?query=fOObar and kanoo&offset=10&hits=20&filter=-foo +bar&type=adv&suggestonly=true");
assertEquals("AND (+(AND fOObar kanoo) -|foo) |bar", q.getModel().getQueryTree().getRoot().toString());
assertEquals(10, q.getOffset());
@@ -54,7 +54,7 @@ public class QueryTestCase {
}
@Test
- public void testAnyQueryParsing () {
+ void testAnyQueryParsing() {
Query q = newQuery("/search?query=foobar and kanoo&offset=10&hits=10&type=any&suggestonly=true&filter=-fast.type:offensive&encoding=latin1");
assertEquals("+(OR foobar and kanoo) -|fast.type:offensive", q.getModel().getQueryTree().getRoot().toString());
assertEquals(10, q.getOffset());
@@ -64,13 +64,13 @@ public class QueryTestCase {
}
@Test
- public void testLongQueryParsing() {
+ void testLongQueryParsing() {
Query q = newQuery("/p13n?query=news"
- +"interest:cnn!254+interest:cnnfn!171+interest:cnn+"
- +"financial!96+interest:"
- +"yahoo+com!253+interest:www+yahoo!138+"
- +"interest:www+yahoo+com!136"
- +"&hits=20&offset=0&vectorranking=queryrank");
+ + "interest:cnn!254+interest:cnnfn!171+interest:cnn+"
+ + "financial!96+interest:"
+ + "yahoo+com!253+interest:www+yahoo!138+"
+ + "interest:www+yahoo+com!136"
+ + "&hits=20&offset=0&vectorranking=queryrank");
assertEquals("/p13n", q.getHttpRequest().getUri().getPath());
assertEquals(0, q.getOffset());
assertEquals(20, q.getHits());
@@ -83,9 +83,9 @@ public class QueryTestCase {
* is not a number.
*/
@Test
- public void testGetParamInt() {
+ void testGetParamInt() {
Query q = newQuery("/search?query=foo%20bar&someint=10&notint=hello");
- assertEquals(10, (int)q.properties().getInteger("someint"));
+ assertEquals(10, (int) q.properties().getInteger("someint"));
// provoke an exception. if exception is not triggered
// we fail the test.
@@ -98,13 +98,13 @@ public class QueryTestCase {
}
@Test
- public void testUtf8Decoding() {
+ void testUtf8Decoding() {
Query q = new Query("/?query=beyonc%C3%A9&type=all");
assertEquals("beyonc\u00e9", ((WordItem) q.getModel().getQueryTree().getRoot()).getWord());
}
@Test
- public void testSortSpec() {
+ void testSortSpec() {
Query q = newQuery("?query=test&sortspec=+a -b c +[rank]");
assertNotNull(q.getRanking().getSorting());
List<Sorting.FieldOrder> sortSpec = q.getRanking().getSorting().fieldOrders();
@@ -120,13 +120,13 @@ public class QueryTestCase {
}
@Test
- public void testSortSpecLowerCase() {
+ void testSortSpecLowerCase() {
Query q = newQuery("?query=test&sortspec=-lowercase(name)");
assertNotNull(q.getRanking().getSorting());
List<Sorting.FieldOrder> sortSpec = q.getRanking().getSorting().fieldOrders();
assertEquals(sortSpec.size(), 1);
assertEquals(Sorting.Order.DESCENDING,
- sortSpec.get(0).getSortOrder());
+ sortSpec.get(0).getSortOrder());
assertEquals("name", sortSpec.get(0).getFieldName());
assertTrue(sortSpec.get(0).getSorter() instanceof Sorting.LowerCaseSorter);
}
@@ -143,7 +143,7 @@ public class QueryTestCase {
}
@Test
- public void testSortSpecUca() {
+ void testSortSpecUca() {
checkUcaUS("?query=test&sortspec=-uca(name,en_US)");
checkUcaUS("?query=test&sortspec=-UCA(name,en_US)");
checkSortSpecUcaUSOptional("?query=test&sortspec=-uca(name,en_US,tertiary)");
@@ -151,21 +151,21 @@ public class QueryTestCase {
}
@Test
- public void testInvalidSortFunction() {
+ void testInvalidSortFunction() {
assertQueryError(
"?query=test&sortspec=-ucca(name,en_US)",
"Could not set 'ranking.sorting' to '-ucca(name,en_US)': Unknown sort function 'ucca'");
}
@Test
- public void testMissingSortFunction() {
+ void testMissingSortFunction() {
assertQueryError(
"?query=test&sortspec=-(name)",
"Could not set 'ranking.sorting' to '-(name)': No sort function specified");
}
@Test
- public void testInvalidUcaStrength() {
+ void testInvalidUcaStrength() {
assertQueryError(
"?query=test&sortspec=-uca(name,en_US,tertary)",
"Could not set 'ranking.sorting' to '-uca(name,en_US,tertary)': Unknown collation strength: 'tertary'");
@@ -189,7 +189,7 @@ public class QueryTestCase {
* Extremely simple for now, will be used for pathological cases.
*/
@Test
- public void testHashCode() {
+ void testHashCode() {
Query p = newQuery("?query=foo&type=any");
Query q = newQuery("?query=foo&type=all");
assertTrue(p.hashCode() != q.hashCode());
@@ -197,17 +197,17 @@ public class QueryTestCase {
/** Test using the defauultindex feature */
@Test
- public void testDefaultIndex() {
+ void testDefaultIndex() {
Query q = newQuery("?query=hi hello keyword:kanoo " +
- "default:munkz \"phrases too\"&default-index=def");
+ "default:munkz \"phrases too\"&default-index=def");
assertEquals("WEAKAND(100) def:hi def:hello keyword:kanoo " +
- "default:munkz def:\"phrases too\"",
- q.getModel().getQueryTree().getRoot().toString());
+ "default:munkz def:\"phrases too\"",
+ q.getModel().getQueryTree().getRoot().toString());
}
- /** Test that GET parameter names are case in-sensitive */
- @Test
- public void testGETParametersCase() {
+ /** Test that GET parameter names are case in-sensitive */
+ @Test
+ void testGETParametersCase() {
Query q = newQuery("?QUERY=testing&hits=10&oFfSeT=10");
assertEquals("testing", q.getModel().getQueryString());
@@ -217,108 +217,108 @@ public class QueryTestCase {
@Test
- public void testNegativeHitValue() {
+ void testNegativeHitValue() {
assertQueryError(
"?query=test&hits=-1",
"Could not set 'hits' to '-1': Must be a positive number");
}
@Test
- public void testNaNHitValue() {
+ void testNaNHitValue() {
assertQueryError(
"?query=test&hits=NaN",
"Could not set 'hits' to 'NaN': 'NaN' is not a valid integer");
}
@Test
- public void testNoneHitValue() {
+ void testNoneHitValue() {
assertQueryError(
"?query=test&hits=(none)",
"Could not set 'hits' to '(none)': '(none)' is not a valid integer");
}
@Test
- public void testNegativeOffsetValue() {
+ void testNegativeOffsetValue() {
assertQueryError(
"?query=test&offset=-1",
"Could not set 'offset' to '-1': Must be a positive number");
}
@Test
- public void testNaNOffsetValue() {
+ void testNaNOffsetValue() {
assertQueryError(
"?query=test&offset=NaN",
"Could not set 'offset' to 'NaN': 'NaN' is not a valid integer");
}
@Test
- public void testNoneOffsetValue() {
+ void testNoneOffsetValue() {
assertQueryError(
"?query=test&offset=(none)",
"Could not set 'offset' to '(none)': '(none)' is not a valid integer");
}
@Test
- public void testNoneHitsNegativeOffsetValue() {
+ void testNoneHitsNegativeOffsetValue() {
assertQueryError(
"?query=test&hits=(none)&offset=-10",
"Could not set 'hits' to '(none)': '(none)' is not a valid integer");
}
@Test
- public void testFeedbackIsTransferredToResult() {
+ void testFeedbackIsTransferredToResult() {
assertQueryError(
"?query=test&hits=(none)&offset=-10",
"Could not set 'hits' to '(none)': '(none)' is not a valid integer");
}
@Test
- public void testUnicodeNormalization() {
+ void testUnicodeNormalization() {
Linguistics linguistics = new SimpleLinguistics();
Query query = newQueryFromEncoded("?query=content:%EF%BC%B3%EF%BC%AF%EF%BC%AE%EF%BC%B9&type=all", Language.ENGLISH,
- linguistics);
+ linguistics);
assertEquals("SONY", ((WordItem) query.getModel().getQueryTree().getRoot()).getWord());
query = newQueryFromEncoded("?query=foo&filter=+%EF%BC%B3%EF%BC%AF%EF%BC%AE%EF%BC%B9&type=all", Language.ENGLISH,
- linguistics);
+ linguistics);
assertEquals("RANK foo |SONY", query.getModel().getQueryTree().getRoot().toString());
query = newQueryFromEncoded("?query=foo+AND+%EF%BC%B3%EF%BC%AF%EF%BC%AE%EF%BC%B9)&type=adv",
- Language.ENGLISH, linguistics);
+ Language.ENGLISH, linguistics);
assertEquals("AND foo SONY", query.getModel().getQueryTree().getRoot().toString());
}
/** Test a vertical specific patch, see Tokenizer */
@Test
- @Ignore
- public void testPrivateUseCharacterParsing() {
+ @Disabled
+ void testPrivateUseCharacterParsing() {
Query query = newQuery("?query=%EF%89%AB");
assertEquals(Character.UnicodeBlock.PRIVATE_USE_AREA,
- Character.UnicodeBlock.of(query.getModel().getQueryTree().getRoot().toString().charAt(0)));
+ Character.UnicodeBlock.of(query.getModel().getQueryTree().getRoot().toString().charAt(0)));
}
/** Test a vertical specific patch, see Tokenizer */
@Test
- @Ignore
- public void testOtherCharactersParsing() {
+ @Disabled
+ void testOtherCharactersParsing() {
Query query = newQuery(com.yahoo.search.test.QueryTestCase.httpEncode("?query=\u3007\u2e80\u2eff\u2ed0"));
assertEquals(Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION,
- Character.UnicodeBlock.of(query.getModel().getQueryTree().getRoot().toString().charAt(0)));
+ Character.UnicodeBlock.of(query.getModel().getQueryTree().getRoot().toString().charAt(0)));
assertEquals(Character.UnicodeBlock.CJK_RADICALS_SUPPLEMENT,
- Character.UnicodeBlock.of(query.getModel().getQueryTree().getRoot().toString().charAt(1)));
+ Character.UnicodeBlock.of(query.getModel().getQueryTree().getRoot().toString().charAt(1)));
assertEquals(Character.UnicodeBlock.CJK_RADICALS_SUPPLEMENT,
- Character.UnicodeBlock.of(query.getModel().getQueryTree().getRoot().toString().charAt(2)));
+ Character.UnicodeBlock.of(query.getModel().getQueryTree().getRoot().toString().charAt(2)));
assertEquals(Character.UnicodeBlock.CJK_RADICALS_SUPPLEMENT,
- Character.UnicodeBlock.of(query.getModel().getQueryTree().getRoot().toString().charAt(3)));
+ Character.UnicodeBlock.of(query.getModel().getQueryTree().getRoot().toString().charAt(3)));
}
@Test
- public void testFreshness() {
+ void testFreshness() {
Query query = newQuery("?query=test&datetime=103");
- assertTrue(query.getRanking().getFreshness().getRefTime()==103);
+ assertEquals(query.getRanking().getFreshness().getRefTime(), 103);
query.getRanking().setFreshness("193");
- assertTrue(query.getRanking().getFreshness().getRefTime()==193);
+ assertEquals(query.getRanking().getFreshness().getRefTime(), 193);
query.getRanking().setFreshness("now");
assertTrue(query.getRanking().getFreshness().getSystemTimeInSecondsSinceEpoch() >= query.getRanking().getFreshness().getRefTime());
@@ -330,10 +330,10 @@ public class QueryTestCase {
}
@Test
- public void testCopy() {
+ void testCopy() {
Query qs = newQuery("?query=test&rankfeature.something=2");
assertEquals("WEAKAND(100) test", qs.getModel().getQueryTree().toString());
- assertEquals((int)qs.properties().getInteger("rankfeature.something"),2);
+ assertEquals((int) qs.properties().getInteger("rankfeature.something"), 2);
Query qp = new Query(qs);
assertEquals("WEAKAND(100) test", qp.getModel().getQueryTree().getRoot().toString());
assertFalse(qp.getRanking().getFeatures().isEmpty());
diff --git a/container-search/src/test/java/com/yahoo/prelude/test/ResultTestCase.java b/container-search/src/test/java/com/yahoo/prelude/test/ResultTestCase.java
index edbfe558ffd..28afe0611d4 100644
--- a/container-search/src/test/java/com/yahoo/prelude/test/ResultTestCase.java
+++ b/container-search/src/test/java/com/yahoo/prelude/test/ResultTestCase.java
@@ -4,11 +4,11 @@ package com.yahoo.prelude.test;
import java.util.Iterator;
import com.yahoo.search.Query;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
import com.yahoo.search.result.Hit;
import com.yahoo.search.Result;
-import org.junit.Test;
-
-import static org.junit.Assert.assertEquals;
+import org.junit.jupiter.api.Test;
/**
* Tests the result class
@@ -18,16 +18,16 @@ import static org.junit.Assert.assertEquals;
public class ResultTestCase {
@Test
- public void testHitOrdering() {
- Result result=new Result(new Query("dummy"));
- result.hits().add(new Hit("test:hit1",80));
- result.hits().add(new Hit("test:hit2",90));
- result.hits().add(new Hit("test:hit3",70));
+ void testHitOrdering() {
+ Result result = new Result(new Query("dummy"));
+ result.hits().add(new Hit("test:hit1", 80));
+ result.hits().add(new Hit("test:hit2", 90));
+ result.hits().add(new Hit("test:hit3", 70));
- Iterator<?> hits= result.hits().deepIterator();
- assertEquals(new Hit("test:hit2",90),hits.next());
- assertEquals(new Hit("test:hit1",80),hits.next());
- assertEquals(new Hit("test:hit3",70),hits.next());
+ Iterator<?> hits = result.hits().deepIterator();
+ assertEquals(new Hit("test:hit2", 90), hits.next());
+ assertEquals(new Hit("test:hit1", 80), hits.next());
+ assertEquals(new Hit("test:hit3", 70), hits.next());
}
private void resultInit(Result result){
@@ -43,48 +43,48 @@ public class ResultTestCase {
}
@Test
- public void testHitTrimming(){
- Result result=new Result(new Query("dummy"));
+ void testHitTrimming() {
+ Result result = new Result(new Query("dummy"));
//case 1: keep some hits in the middle
resultInit(result);
result.hits().trim(3, 3);
- assertEquals(3,result.getHitCount());
- Iterator<Hit> hits= result.hits().deepIterator();
- assertEquals(new Hit("test:hit3",70),hits.next());
- assertEquals(new Hit("test:hit8",55),hits.next());
- assertEquals(new Hit("test:hit5",50),hits.next());
- assertEquals(false,hits.hasNext());
+ assertEquals(3, result.getHitCount());
+ Iterator<Hit> hits = result.hits().deepIterator();
+ assertEquals(new Hit("test:hit3", 70), hits.next());
+ assertEquals(new Hit("test:hit8", 55), hits.next());
+ assertEquals(new Hit("test:hit5", 50), hits.next());
+ assertEquals(false, hits.hasNext());
//case 2: keep some hits at the end
- result=new Result(new Query("dummy"));
+ result = new Result(new Query("dummy"));
resultInit(result);
result.hits().trim(5, 4);
- hits= result.hits().deepIterator();
- assertEquals(new Hit("test:hit5",50),hits.next());
- assertEquals(new Hit("test:hit4",40),hits.next());
- assertEquals(new Hit("test:hit6",20),hits.next());
- assertEquals(new Hit("test:hit7",20),hits.next());
- assertEquals(false,hits.hasNext());
+ hits = result.hits().deepIterator();
+ assertEquals(new Hit("test:hit5", 50), hits.next());
+ assertEquals(new Hit("test:hit4", 40), hits.next());
+ assertEquals(new Hit("test:hit6", 20), hits.next());
+ assertEquals(new Hit("test:hit7", 20), hits.next());
+ assertEquals(false, hits.hasNext());
//case 3: keep some hits at the beginning
- result=new Result(new Query("dummy"));
+ result = new Result(new Query("dummy"));
resultInit(result);
result.hits().trim(0, 4);
- hits= result.hits().deepIterator();
- assertEquals(new Hit("test:hit2",90),hits.next());
- assertEquals(new Hit("test:hit1",80),hits.next());
- assertEquals(new Hit("test:hit9",75),hits.next());
- assertEquals(new Hit("test:hit3",70),hits.next());
- assertEquals(false,hits.hasNext());
+ hits = result.hits().deepIterator();
+ assertEquals(new Hit("test:hit2", 90), hits.next());
+ assertEquals(new Hit("test:hit1", 80), hits.next());
+ assertEquals(new Hit("test:hit9", 75), hits.next());
+ assertEquals(new Hit("test:hit3", 70), hits.next());
+ assertEquals(false, hits.hasNext());
//case 4: keep no hits
- result=new Result(new Query("dummy"));
+ result = new Result(new Query("dummy"));
resultInit(result);
result.hits().trim(10, 4);
- hits= result.hits().deepIterator();
- assertEquals(false,hits.hasNext());
+ hits = result.hits().deepIterator();
+ assertEquals(false, hits.hasNext());
}
//This test is broken
diff --git a/container-search/src/test/java/com/yahoo/search/cluster/test/ClusterSearcherTestCase.java b/container-search/src/test/java/com/yahoo/search/cluster/test/ClusterSearcherTestCase.java
index bf44c57a777..33d86658f8e 100644
--- a/container-search/src/test/java/com/yahoo/search/cluster/test/ClusterSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/cluster/test/ClusterSearcherTestCase.java
@@ -5,6 +5,8 @@ import java.util.ArrayList;
import java.util.List;
import com.yahoo.component.ComponentId;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
import com.yahoo.prelude.Ping;
import com.yahoo.prelude.Pong;
import com.yahoo.search.Query;
@@ -16,9 +18,7 @@ import com.yahoo.search.cluster.PingableSearcher;
import com.yahoo.search.result.ErrorMessage;
import com.yahoo.search.result.Hit;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
-
-import static org.junit.Assert.assertEquals;
+import org.junit.jupiter.api.Test;
public class ClusterSearcherTestCase {
@@ -144,26 +144,26 @@ public class ClusterSearcherTestCase {
}
@Test
- public void testSimple() {
+ void testSimple() {
Hit blockingHit = new Hit("blocking");
Hit nonblockingHit = new Hit("nonblocking");
BlockingBackendSearcher blockingSearcher = new BlockingBackendSearcher(blockingHit);
- List<Searcher> searchers=new ArrayList<>();
+ List<Searcher> searchers = new ArrayList<>();
searchers.add(blockingSearcher);
searchers.add(new TestingBackendSearcher(nonblockingHit));
- ClusterSearcher<?> provider = new SearcherClusterSearcher(new ComponentId("simple"),searchers,new SimpleHasher<>());
+ ClusterSearcher<?> provider = new SearcherClusterSearcher(new ComponentId("simple"), searchers, new SimpleHasher<>());
Result blockingResult = new Execution(provider, Execution.Context.createContextStub()).search(new SimpleQuery(0));
- assertEquals(blockingHit,blockingResult.hits().get(0));
+ assertEquals(blockingHit, blockingResult.hits().get(0));
Result nonblockingResult = new Execution(provider, Execution.Context.createContextStub()).search(new SimpleQuery(1));
- assertEquals(nonblockingHit,nonblockingResult.hits().get(0));
+ assertEquals(nonblockingHit, nonblockingResult.hits().get(0));
blockingSearcher.setBlocking(true);
blockingResult = new Execution(provider, Execution.Context.createContextStub()).search(new SimpleQuery(0));
- assertEquals(blockingResult.hits().get(0),nonblockingHit);
+ assertEquals(blockingResult.hits().get(0), nonblockingHit);
nonblockingResult = new Execution(provider, Execution.Context.createContextStub()).search(new SimpleQuery(1));
- assertEquals(nonblockingResult.hits().get(0),nonblockingHit);
+ assertEquals(nonblockingResult.hits().get(0), nonblockingHit);
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/cluster/test/ClusteredConnectionTestCase.java b/container-search/src/test/java/com/yahoo/search/cluster/test/ClusteredConnectionTestCase.java
index fa8d237aee0..8c98b344394 100644
--- a/container-search/src/test/java/com/yahoo/search/cluster/test/ClusteredConnectionTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/cluster/test/ClusteredConnectionTestCase.java
@@ -12,14 +12,14 @@ import com.yahoo.search.cluster.Hasher;
import com.yahoo.search.result.ErrorMessage;
import com.yahoo.search.result.Hit;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
-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 bratseth
@@ -27,83 +27,83 @@ import static org.junit.Assert.assertNull;
public class ClusteredConnectionTestCase {
@Test
- public void testClustering() {
- Connection connection0=new Connection("0");
- Connection connection1=new Connection("1");
- Connection connection2=new Connection("2");
- List<Connection> connections=new ArrayList<>();
+ void testClustering() {
+ Connection connection0 = new Connection("0");
+ Connection connection1 = new Connection("1");
+ Connection connection2 = new Connection("2");
+ List<Connection> connections = new ArrayList<>();
connections.add(connection0);
connections.add(connection1);
connections.add(connection2);
MyBackend myBackend = new MyBackend(new ComponentId("test"), connections);
Result r;
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(0));
- assertEquals("from:0",r.hits().get(0).getId().stringValue());
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(1));
- assertEquals("from:2",r.hits().get(0).getId().stringValue());
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(2));
- assertEquals("from:1",r.hits().get(0).getId().stringValue());
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(3));
- assertEquals("from:0",r.hits().get(0).getId().stringValue());
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(0));
+ assertEquals("from:0", r.hits().get(0).getId().stringValue());
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(1));
+ assertEquals("from:2", r.hits().get(0).getId().stringValue());
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(2));
+ assertEquals("from:1", r.hits().get(0).getId().stringValue());
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(3));
+ assertEquals("from:0", r.hits().get(0).getId().stringValue());
connection2.setInService(false);
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(0));
- assertEquals("from:0",r.hits().get(0).getId().stringValue());
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(1));
- assertEquals("from:0",r.hits().get(0).getId().stringValue());
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(2));
- assertEquals("from:1",r.hits().get(0).getId().stringValue());
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(3));
- assertEquals("from:0",r.hits().get(0).getId().stringValue());
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(0));
+ assertEquals("from:0", r.hits().get(0).getId().stringValue());
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(1));
+ assertEquals("from:0", r.hits().get(0).getId().stringValue());
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(2));
+ assertEquals("from:1", r.hits().get(0).getId().stringValue());
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(3));
+ assertEquals("from:0", r.hits().get(0).getId().stringValue());
connection1.setInService(false);
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(0));
- assertEquals("from:0",r.hits().get(0).getId().stringValue());
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(1));
- assertEquals("from:0",r.hits().get(0).getId().stringValue());
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(2));
- assertEquals("from:0",r.hits().get(0).getId().stringValue());
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(3));
- assertEquals("from:0",r.hits().get(0).getId().stringValue());
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(0));
+ assertEquals("from:0", r.hits().get(0).getId().stringValue());
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(1));
+ assertEquals("from:0", r.hits().get(0).getId().stringValue());
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(2));
+ assertEquals("from:0", r.hits().get(0).getId().stringValue());
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(3));
+ assertEquals("from:0", r.hits().get(0).getId().stringValue());
connection0.setInService(false);
r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(0));
assertEquals("Failed calling connection '2' in searcher 'test' for query 'NULL': Connection failed",
- r.hits().getError().getDetailedMessage());
+ r.hits().getError().getDetailedMessage());
connection0.setInService(true);
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(0));
- assertEquals("from:0",r.hits().get(0).getId().stringValue());
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(1));
- assertEquals("from:0",r.hits().get(0).getId().stringValue());
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(2));
- assertEquals("from:0",r.hits().get(0).getId().stringValue());
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(3));
- assertEquals("from:0",r.hits().get(0).getId().stringValue());
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(0));
+ assertEquals("from:0", r.hits().get(0).getId().stringValue());
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(1));
+ assertEquals("from:0", r.hits().get(0).getId().stringValue());
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(2));
+ assertEquals("from:0", r.hits().get(0).getId().stringValue());
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(3));
+ assertEquals("from:0", r.hits().get(0).getId().stringValue());
connection1.setInService(true);
connection2.setInService(true);
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(0));
- assertEquals("from:0",r.hits().get(0).getId().stringValue());
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(1));
- assertEquals("from:2",r.hits().get(0).getId().stringValue());
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(2));
- assertEquals("from:1",r.hits().get(0).getId().stringValue());
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(3));
- assertEquals("from:0",r.hits().get(0).getId().stringValue());
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(0));
+ assertEquals("from:0", r.hits().get(0).getId().stringValue());
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(1));
+ assertEquals("from:2", r.hits().get(0).getId().stringValue());
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(2));
+ assertEquals("from:1", r.hits().get(0).getId().stringValue());
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(3));
+ assertEquals("from:0", r.hits().get(0).getId().stringValue());
}
@Test
- public void testClusteringWithPing() {
- Connection connection0=new Connection("0");
- Connection connection1=new Connection("1");
- Connection connection2=new Connection("2");
- List<Connection> connections=new ArrayList<>();
+ void testClusteringWithPing() {
+ Connection connection0 = new Connection("0");
+ Connection connection1 = new Connection("1");
+ Connection connection2 = new Connection("2");
+ List<Connection> connections = new ArrayList<>();
connections.add(connection0);
connections.add(connection1);
connections.add(connection2);
- MyBackend myBackend=new MyBackend(new ComponentId("test"),connections);
+ MyBackend myBackend = new MyBackend(new ComponentId("test"), connections);
Result r;
@@ -114,14 +114,14 @@ public class ClusteredConnectionTestCase {
connection1.setInService(false);
connection0.setInService(false);
forcePing(myBackend);
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(0));
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(0));
assertEquals("No backends in service. Try later", r.hits().getError().getMessage());
connection2.setInService(true);
connection1.setInService(true);
connection0.setInService(true);
forcePing(myBackend);
- r=new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(0));
+ r = new Execution(myBackend, Execution.Context.createContextStub()).search(new SimpleQuery(0));
assertNull(r.hits().getError());
}
diff --git a/container-search/src/test/java/com/yahoo/search/dispatch/DispatcherTest.java b/container-search/src/test/java/com/yahoo/search/dispatch/DispatcherTest.java
index 42df2a829e3..715154e85ba 100644
--- a/container-search/src/test/java/com/yahoo/search/dispatch/DispatcherTest.java
+++ b/container-search/src/test/java/com/yahoo/search/dispatch/DispatcherTest.java
@@ -12,17 +12,14 @@ import com.yahoo.search.dispatch.searchcluster.PingFactory;
import com.yahoo.search.dispatch.searchcluster.Pinger;
import com.yahoo.search.dispatch.searchcluster.PongHandler;
import com.yahoo.search.dispatch.searchcluster.SearchCluster;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Optional;
import java.util.OptionalInt;
import static com.yahoo.search.dispatch.MockSearchCluster.createDispatchConfig;
-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 ollivir
@@ -30,7 +27,7 @@ import static org.junit.Assert.fail;
public class DispatcherTest {
@Test
- public void requireThatDispatcherSupportsSearchPath() {
+ void requireThatDispatcherSupportsSearchPath() {
SearchCluster cl = new MockSearchCluster("1", 2, 2);
Query q = new Query();
q.getModel().setSearchPath("1/0"); // second node in first group
@@ -46,7 +43,7 @@ public class DispatcherTest {
}
@Test
- public void requireThatDispatcherSupportsSingleNodeDirectDispatch() {
+ void requireThatDispatcherSupportsSingleNodeDirectDispatch() {
SearchCluster cl = new MockSearchCluster("1", 0, 0) {
@Override
public Optional<Node> localCorpusDispatchTarget() {
@@ -61,7 +58,7 @@ public class DispatcherTest {
}
@Test
- public void requireThatInvokerConstructionIsRetriedAndLastAcceptsAnyCoverage() {
+ void requireThatInvokerConstructionIsRetriedAndLastAcceptsAnyCoverage() {
SearchCluster cl = new MockSearchCluster("1", 2, 1);
MockInvokerFactory invokerFactory = new MockInvokerFactory(cl, (n, acceptIncompleteCoverage) -> {
@@ -78,7 +75,7 @@ public class DispatcherTest {
}
@Test
- public void requireThatInvokerConstructionDoesNotRepeatGroups() {
+ void requireThatInvokerConstructionDoesNotRepeatGroups() {
try {
SearchCluster cl = new MockSearchCluster("1", 2, 1);
@@ -94,49 +91,49 @@ public class DispatcherTest {
}
@Test
- public void testGroup0IsSelected() {
+ void testGroup0IsSelected() {
SearchCluster cluster = new MockSearchCluster("1", 3, 1);
Dispatcher dispatcher = new Dispatcher(new ClusterMonitor(cluster, false), cluster, createDispatchConfig(), new MockInvokerFactory(cluster, (n, a) -> true), new MockMetric());
cluster.pingIterationCompleted();
assertEquals(0,
- dispatcher.getSearchInvoker(new Query(), null).distributionKey().get().longValue());
+ dispatcher.getSearchInvoker(new Query(), null).distributionKey().get().longValue());
dispatcher.deconstruct();
}
@Test
- public void testGroup0IsSkippedWhenItIsBlockingFeed() {
+ void testGroup0IsSkippedWhenItIsBlockingFeed() {
SearchCluster cluster = new MockSearchCluster("1", 3, 1);
Dispatcher dispatcher = new Dispatcher(new ClusterMonitor(cluster, false), cluster, createDispatchConfig(), new MockInvokerFactory(cluster, (n, a) -> true), new MockMetric());
cluster.group(0).get().nodes().get(0).setBlockingWrites(true);
cluster.pingIterationCompleted();
- assertEquals("Blocking group is avoided",
- 1,
- (dispatcher.getSearchInvoker(new Query(), null).distributionKey().get()).longValue());
+ assertEquals(1,
+ (dispatcher.getSearchInvoker(new Query(), null).distributionKey().get()).longValue(),
+ "Blocking group is avoided");
dispatcher.deconstruct();
}
@Test
- public void testGroup0IsSelectedWhenMoreAreBlockingFeed() {
+ void testGroup0IsSelectedWhenMoreAreBlockingFeed() {
SearchCluster cluster = new MockSearchCluster("1", 3, 1);
Dispatcher dispatcher = new Dispatcher(new ClusterMonitor(cluster, false), cluster, createDispatchConfig(), new MockInvokerFactory(cluster, (n, a) -> true), new MockMetric());
cluster.group(0).get().nodes().get(0).setBlockingWrites(true);
cluster.group(1).get().nodes().get(0).setBlockingWrites(true);
cluster.pingIterationCompleted();
- assertEquals("Blocking group is used when multiple groups are blocking",
- 0,
- dispatcher.getSearchInvoker(new Query(), null).distributionKey().get().longValue());
+ assertEquals(0,
+ dispatcher.getSearchInvoker(new Query(), null).distributionKey().get().longValue(),
+ "Blocking group is used when multiple groups are blocking");
dispatcher.deconstruct();
}
@Test
- public void testGroup0IsSelectedWhenItIsBlockingFeedWhenNoOthers() {
+ void testGroup0IsSelectedWhenItIsBlockingFeedWhenNoOthers() {
SearchCluster cluster = new MockSearchCluster("1", 1, 1);
Dispatcher dispatcher = new Dispatcher(new ClusterMonitor(cluster, false), cluster, createDispatchConfig(), new MockInvokerFactory(cluster, (n, a) -> true), new MockMetric());
cluster.group(0).get().nodes().get(0).setBlockingWrites(true);
cluster.pingIterationCompleted();
- assertEquals("Blocking group is used when there is no alternative",
- 0,
- (dispatcher.getSearchInvoker(new Query(), null).distributionKey().get()).longValue());
+ assertEquals(0,
+ (dispatcher.getSearchInvoker(new Query(), null).distributionKey().get()).longValue(),
+ "Blocking group is used when there is no alternative");
dispatcher.deconstruct();
}
diff --git a/container-search/src/test/java/com/yahoo/search/dispatch/InterleavedSearchInvokerTest.java b/container-search/src/test/java/com/yahoo/search/dispatch/InterleavedSearchInvokerTest.java
index e07d38fbf10..1293975deb5 100644
--- a/container-search/src/test/java/com/yahoo/search/dispatch/InterleavedSearchInvokerTest.java
+++ b/container-search/src/test/java/com/yahoo/search/dispatch/InterleavedSearchInvokerTest.java
@@ -20,7 +20,7 @@ import com.yahoo.searchlib.aggregation.MinAggregationResult;
import com.yahoo.searchlib.expression.IntegerResultNode;
import com.yahoo.searchlib.expression.StringResultNode;
import com.yahoo.test.ManualClock;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.time.Duration;
@@ -38,11 +38,7 @@ import java.util.stream.StreamSupport;
import static com.yahoo.container.handler.Coverage.DEGRADED_BY_MATCH_PHASE;
import static com.yahoo.container.handler.Coverage.DEGRADED_BY_TIMEOUT;
import static com.yahoo.search.dispatch.MockSearchCluster.createDispatchConfig;
-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.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author ollivir
@@ -55,7 +51,7 @@ public class InterleavedSearchInvokerTest {
private final List<SearchInvoker> invokers = new ArrayList<>();
@Test
- public void requireThatAdaptiveTimeoutsAreNotUsedWithFullCoverageRequirement() throws IOException {
+ void requireThatAdaptiveTimeoutsAreNotUsedWithFullCoverageRequirement() throws IOException {
SearchCluster cluster = new MockSearchCluster("!", createDispatchConfig(100.0), 1, 3);
SearchInvoker invoker = createInterleavedInvoker(cluster, new Group(0, List.of()), 3);
@@ -65,11 +61,11 @@ public class InterleavedSearchInvokerTest {
invoker.search(query, null);
- assertTrue("All test scenario events processed", expectedEvents.isEmpty());
+ assertTrue(expectedEvents.isEmpty(), "All test scenario events processed");
}
@Test
- public void requireThatTimeoutsAreNotMarkedAsAdaptive() throws IOException {
+ void requireThatTimeoutsAreNotMarkedAsAdaptive() throws IOException {
SearchCluster cluster = new MockSearchCluster("!", createDispatchConfig(100.0), 1, 3);
SearchInvoker invoker = createInterleavedInvoker(cluster, new Group(0, List.of()), 3);
@@ -79,15 +75,15 @@ public class InterleavedSearchInvokerTest {
Result result = invoker.search(query, null);
- assertTrue("All test scenario events processed", expectedEvents.isEmpty());
- assertNull("Result is not marked as an error", result.hits().getErrorHit());
+ assertTrue(expectedEvents.isEmpty(), "All test scenario events processed");
+ assertNull(result.hits().getErrorHit(), "Result is not marked as an error");
var message = findTrace(result, "Backend communication timeout");
- assertTrue("Timeout should be reported in a trace message", message.isPresent());
- assertTrue("Degradation reason is a normal timeout", result.getCoverage(false).isDegradedByTimeout());
+ assertTrue(message.isPresent(), "Timeout should be reported in a trace message");
+ assertTrue(result.getCoverage(false).isDegradedByTimeout(), "Degradation reason is a normal timeout");
}
@Test
- public void requireThatAdaptiveTimeoutDecreasesTimeoutWhenCoverageIsReached() throws IOException {
+ void requireThatAdaptiveTimeoutDecreasesTimeoutWhenCoverageIsReached() throws IOException {
SearchCluster cluster = new MockSearchCluster("!", createDispatchConfig(50.0), 1, 4);
SearchInvoker invoker = createInterleavedInvoker(cluster, new Group(0, List.of()), 4);
@@ -98,15 +94,15 @@ public class InterleavedSearchInvokerTest {
Result result = invoker.search(query, null);
- assertTrue("All test scenario events processed", expectedEvents.isEmpty());
- assertNull("Result is not marked as an error", result.hits().getErrorHit());
+ assertTrue(expectedEvents.isEmpty(), "All test scenario events processed");
+ assertNull(result.hits().getErrorHit(), "Result is not marked as an error");
var message = findTrace(result, "Backend communication timeout");
- assertTrue("Timeout should be reported in a trace message", message.isPresent());
- assertTrue("Degradataion reason is an adaptive timeout", result.getCoverage(false).isDegradedByAdapativeTimeout());
+ assertTrue(message.isPresent(), "Timeout should be reported in a trace message");
+ assertTrue(result.getCoverage(false).isDegradedByAdapativeTimeout(), "Degradataion reason is an adaptive timeout");
}
@Test
- public void requireCorrectCoverageCalculationWhenAllNodesOk() throws IOException {
+ void requireCorrectCoverageCalculationWhenAllNodesOk() throws IOException {
SearchCluster cluster = new MockSearchCluster("!", 1, 2);
invokers.add(new MockInvoker(0, createCoverage(50155, 50155, 50155, 1, 1, 0)));
invokers.add(new MockInvoker(1, createCoverage(49845, 49845, 49845, 1, 1, 0)));
@@ -127,7 +123,7 @@ public class InterleavedSearchInvokerTest {
}
@Test
- public void requireCorrectCoverageCalculationWhenResultsAreLimitedByMatchPhase() throws IOException {
+ void requireCorrectCoverageCalculationWhenResultsAreLimitedByMatchPhase() throws IOException {
SearchCluster cluster = new MockSearchCluster("!", 1, 2);
invokers.add(new MockInvoker(0, createCoverage(10101, 50155, 50155, 1, 1, DEGRADED_BY_MATCH_PHASE)));
invokers.add(new MockInvoker(1, createCoverage(13319, 49845, 49845, 1, 1, DEGRADED_BY_MATCH_PHASE)));
@@ -149,11 +145,11 @@ public class InterleavedSearchInvokerTest {
}
@Test
- public void requireCorrectCoverageCalculationWhenResultsAreLimitedBySoftTimeout() throws IOException {
+ void requireCorrectCoverageCalculationWhenResultsAreLimitedBySoftTimeout() throws IOException {
SearchCluster cluster = new MockSearchCluster("!", 1, 2);
invokers.add(new MockInvoker(0, createCoverage(5000, 50155, 50155, 1, 1, DEGRADED_BY_TIMEOUT)));
invokers.add(new MockInvoker(1, createCoverage(4900, 49845, 49845, 1, 1, DEGRADED_BY_TIMEOUT)));
- SearchInvoker invoker = createInterleavedInvoker(cluster, new Group(0, List.of()),0);
+ SearchInvoker invoker = createInterleavedInvoker(cluster, new Group(0, List.of()), 0);
expectedEvents.add(new Event(null, 100, 0));
expectedEvents.add(new Event(null, 200, 1));
@@ -171,7 +167,7 @@ public class InterleavedSearchInvokerTest {
}
@Test
- public void requireCorrectCoverageCalculationWhenOneNodeIsUnexpectedlyDown() throws IOException {
+ void requireCorrectCoverageCalculationWhenOneNodeIsUnexpectedlyDown() throws IOException {
SearchCluster cluster = new MockSearchCluster("!", 1, 2);
invokers.add(new MockInvoker(0, createCoverage(50155, 50155, 50155, 1, 1, 0)));
invokers.add(new MockInvoker(1, createCoverage(49845, 49845, 49845, 1, 1, 0)));
@@ -231,13 +227,13 @@ public class InterleavedSearchInvokerTest {
}
@Test
- public void requireThatTopKProbabilityOverrideTakesEffect() throws IOException {
+ void requireThatTopKProbabilityOverrideTakesEffect() throws IOException {
validateThatTopKProbabilityOverrideTakesEffect(null, 8, new Group(0, List.of()));
validateThatTopKProbabilityOverrideTakesEffect(0.8, 7, new Group(0, List.of()));
}
@Test
- public void requireThatTopKProbabilityOverrideIsDisabledOnContentSkew() throws IOException {
+ void requireThatTopKProbabilityOverrideIsDisabledOnContentSkew() throws IOException {
Node node0 = new Node(0, "host0", 0);
Node node1 = new Node(1, "host1", 0);
Group group = new Group(0, List.of(node0, node1));
@@ -249,7 +245,7 @@ public class InterleavedSearchInvokerTest {
}
@Test
- public void requireThatTopKProbabilityOverrideIsDisabledOnLittleContent() throws IOException {
+ void requireThatTopKProbabilityOverrideIsDisabledOnLittleContent() throws IOException {
Node node0 = new Node(0, "host0", 0);
Node node1 = new Node(1, "host1", 0);
Group group = new Group(0, List.of(node0, node1));
@@ -261,7 +257,7 @@ public class InterleavedSearchInvokerTest {
}
@Test
- public void requireThatMergeOfConcreteHitsObeySorting() throws IOException {
+ void requireThatMergeOfConcreteHitsObeySorting() throws IOException {
InterleavedSearchInvoker invoker = createInterLeavedTestInvoker(A5, B5, new Group(0, List.of()));
query.setHits(12);
Result result = invoker.search(query, null);
@@ -281,7 +277,7 @@ public class InterleavedSearchInvokerTest {
}
@Test
- public void requireThatMergeOfConcreteHitsObeyOffset() throws IOException {
+ void requireThatMergeOfConcreteHitsObeyOffset() throws IOException {
InterleavedSearchInvoker invoker = createInterLeavedTestInvoker(A5, B5, new Group(0, List.of()));
query.setHits(3);
query.setOffset(5);
@@ -303,7 +299,7 @@ public class InterleavedSearchInvokerTest {
}
@Test
- public void requireThatMergeOfConcreteHitsObeyOffsetWithAuxilliaryStuff() throws IOException {
+ void requireThatMergeOfConcreteHitsObeyOffsetWithAuxilliaryStuff() throws IOException {
InterleavedSearchInvoker invoker = createInterLeavedTestInvoker(A5Aux, B5Aux, new Group(0, List.of()));
query.setHits(3);
query.setOffset(5);
@@ -327,7 +323,7 @@ public class InterleavedSearchInvokerTest {
}
@Test
- public void requireThatGroupingsAreMerged() throws IOException {
+ void requireThatGroupingsAreMerged() throws IOException {
SearchCluster cluster = new MockSearchCluster("!", 1, 2);
List<SearchInvoker> invokers = new ArrayList<>();
@@ -386,7 +382,7 @@ public class InterleavedSearchInvokerTest {
}
@Test
- public void requireCorrectCoverageCalculationWhenDegradedCoverageIsExpected() throws IOException {
+ void requireCorrectCoverageCalculationWhenDegradedCoverageIsExpected() throws IOException {
SearchCluster cluster = new MockSearchCluster("!", 1, 2);
invokers.add(new MockInvoker(0, createCoverage(50155, 50155, 50155, 1, 1, 0)));
Coverage errorCoverage = new Coverage(0, 0, 0);
@@ -468,7 +464,7 @@ public class InterleavedSearchInvokerTest {
public SearchInvoker process(Query query, long currentTimeout) {
if (expectedTimeout != null) {
- assertEquals("Expecting timeout to be " + expectedTimeout, (long) expectedTimeout, currentTimeout);
+ assertEquals((long) expectedTimeout, currentTimeout, "Expecting timeout to be " + expectedTimeout);
}
clock.advance(Duration.ofMillis(delay));
if (query.getTimeLeft() < 0) {
diff --git a/container-search/src/test/java/com/yahoo/search/dispatch/LeanHitTest.java b/container-search/src/test/java/com/yahoo/search/dispatch/LeanHitTest.java
index a2080ce6b05..3d2ab17b15d 100644
--- a/container-search/src/test/java/com/yahoo/search/dispatch/LeanHitTest.java
+++ b/container-search/src/test/java/com/yahoo/search/dispatch/LeanHitTest.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.search.dispatch;
-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.jupiter.api.Assertions.*;
public class LeanHitTest {
private static final byte [] gidA = {'a'};
@@ -20,34 +18,39 @@ public class LeanHitTest {
assertTrue(c.compareTo(b) > 0);
assertTrue(c.compareTo(a) > 0);
}
+
@Test
- public void testOrderingByRelevance() {
+ void testOrderingByRelevance() {
assertEquals(0, new LeanHit(gidA, 0, 0, 1).compareTo(new LeanHit(gidA, 0, 0, 1)));
verifyTransitiveOrdering(new LeanHit(gidA, 0, 0, 1),
new LeanHit(gidA, 0, 0, 0),
new LeanHit(gidA, 0, 0, -1));
}
+
@Test
- public void testOrderingByGid() {
+ void testOrderingByGid() {
assertEquals(0, new LeanHit(gidA, 0, 0, 1).compareTo(new LeanHit(gidA, 0, 0, 1)));
verifyTransitiveOrdering(new LeanHit(gidA, 0, 0, 1),
new LeanHit(gidB, 0, 0, 1),
new LeanHit(gidC, 0, 0, 1));
}
+
@Test
- public void testOrderingBySortData() {
+ void testOrderingBySortData() {
assertEquals(0, new LeanHit(gidA, 0, 0, 0.0, gidA).compareTo(new LeanHit(gidA, 0, 0, 0.0, gidA)));
verifyTransitiveOrdering(new LeanHit(gidA, 0, 0, 0.0, gidA),
new LeanHit(gidA, 0, 0, 0.0, gidB),
new LeanHit(gidA, 0, 0, 0.0, gidC));
}
+
@Test
- public void testRelevanceIsKeptEvenWithBySortData() {
+ void testRelevanceIsKeptEvenWithBySortData() {
assertEquals(1.3, new LeanHit(gidA, 0, 0, 1.3, gidA).getRelevance(), 0.0);
}
+
@Test
- public void testNaN2negativeInfinity() {
+ void testNaN2negativeInfinity() {
LeanHit nan = new LeanHit(gidA, 0, 0, Double.NaN);
assertFalse(Double.isNaN(nan.getRelevance()));
assertTrue(Double.isInfinite(nan.getRelevance()));
diff --git a/container-search/src/test/java/com/yahoo/search/dispatch/LoadBalancerTest.java b/container-search/src/test/java/com/yahoo/search/dispatch/LoadBalancerTest.java
index e95fbc366a6..e9ed1c48302 100644
--- a/container-search/src/test/java/com/yahoo/search/dispatch/LoadBalancerTest.java
+++ b/container-search/src/test/java/com/yahoo/search/dispatch/LoadBalancerTest.java
@@ -6,8 +6,8 @@ import com.yahoo.search.dispatch.LoadBalancer.GroupStatus;
import com.yahoo.search.dispatch.searchcluster.Group;
import com.yahoo.search.dispatch.searchcluster.Node;
import com.yahoo.search.dispatch.searchcluster.SearchCluster;
-import junit.framework.AssertionFailedError;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.opentest4j.AssertionFailedError;
import java.util.ArrayList;
import java.util.Collections;
@@ -16,9 +16,9 @@ import java.util.Optional;
import java.util.Random;
import static com.yahoo.search.dispatch.MockSearchCluster.createDispatchConfig;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author ollivir
@@ -26,7 +26,7 @@ import static org.junit.Assert.assertTrue;
public class LoadBalancerTest {
@Test
- public void requireThatLoadBalancerServesSingleNodeSetups() {
+ void requireThatLoadBalancerServesSingleNodeSetups() {
Node n1 = new Node(0, "test-node1", 0);
SearchCluster cluster = new SearchCluster("a", createDispatchConfig(n1), null, null);
LoadBalancer lb = new LoadBalancer(cluster, true);
@@ -39,7 +39,7 @@ public class LoadBalancerTest {
}
@Test
- public void requireThatLoadBalancerServesMultiGroupSetups() {
+ void requireThatLoadBalancerServesMultiGroupSetups() {
Node n1 = new Node(0, "test-node1", 0);
Node n2 = new Node(1, "test-node2", 1);
SearchCluster cluster = new SearchCluster("a", createDispatchConfig(n1, n2), null, null);
@@ -53,7 +53,7 @@ public class LoadBalancerTest {
}
@Test
- public void requireThatLoadBalancerServesClusteredGroups() {
+ void requireThatLoadBalancerServesClusteredGroups() {
Node n1 = new Node(0, "test-node1", 0);
Node n2 = new Node(1, "test-node2", 0);
Node n3 = new Node(0, "test-node3", 1);
@@ -66,10 +66,10 @@ public class LoadBalancerTest {
}
@Test
- public void requireThatLoadBalancerReturnsDifferentGroups() {
+ void requireThatLoadBalancerReturnsDifferentGroups() {
Node n1 = new Node(0, "test-node1", 0);
Node n2 = new Node(1, "test-node2", 1);
- SearchCluster cluster = new SearchCluster("a", createDispatchConfig(n1, n2), null,null);
+ SearchCluster cluster = new SearchCluster("a", createDispatchConfig(n1, n2), null, null);
LoadBalancer lb = new LoadBalancer(cluster, true);
// get first group
@@ -86,7 +86,7 @@ public class LoadBalancerTest {
}
@Test
- public void requireCorrectAverageSearchTimeDecay() {
+ void requireCorrectAverageSearchTimeDecay() {
final double delta = 0.00001;
GroupStatus gs = newGroupStatus(1);
@@ -115,7 +115,7 @@ public class LoadBalancerTest {
}
@Test
- public void requireEqualDistributionInFlatWeightListWithAdaptiveScheduler() {
+ void requireEqualDistributionInFlatWeightListWithAdaptiveScheduler() {
List<GroupStatus> scoreboard = new ArrayList<>();
for (int i = 0; i < 5; i++) {
scoreboard.add(newGroupStatus(i));
@@ -134,7 +134,7 @@ public class LoadBalancerTest {
}
@Test
- public void requireThatAdaptiveSchedulerObeysWeights() {
+ void requireThatAdaptiveSchedulerObeysWeights() {
List<GroupStatus> scoreboard = new ArrayList<>();
for (int i = 0; i < 5; i++) {
GroupStatus gs = newGroupStatus(i);
diff --git a/container-search/src/test/java/com/yahoo/search/dispatch/SearchPathTest.java b/container-search/src/test/java/com/yahoo/search/dispatch/SearchPathTest.java
index 3a1a60df7af..12cbe488485 100644
--- a/container-search/src/test/java/com/yahoo/search/dispatch/SearchPathTest.java
+++ b/container-search/src/test/java/com/yahoo/search/dispatch/SearchPathTest.java
@@ -3,16 +3,13 @@ package com.yahoo.search.dispatch;
import com.yahoo.search.dispatch.SearchPath.InvalidSearchPathException;
import com.yahoo.search.dispatch.searchcluster.Node;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;
-import static org.junit.Assert.assertFalse;
-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 ollivir
@@ -20,7 +17,7 @@ import static org.junit.Assert.fail;
public class SearchPathTest {
@Test
- public void requreThatSearchPathsAreParsedCorrectly() {
+ void requreThatSearchPathsAreParsedCorrectly() {
assertEquals(SearchPath.fromString("0/0").get().toString(), "0/0");
assertEquals(SearchPath.fromString("1/0").get().toString(), "1/0");
assertEquals(SearchPath.fromString("0/1").get().toString(), "0/1");
@@ -43,7 +40,7 @@ public class SearchPathTest {
}
@Test
- public void requreThatWildcardsAreDetected() {
+ void requreThatWildcardsAreDetected() {
assertFalse(SearchPath.fromString("").isPresent());
assertFalse(SearchPath.fromString("*/*").isPresent());
assertFalse(SearchPath.fromString("/").isPresent());
@@ -52,7 +49,7 @@ public class SearchPathTest {
}
@Test
- public void invalidRangeMustThrowException() {
+ void invalidRangeMustThrowException() {
try {
SearchPath.fromString("[p,0>/0");
fail("Expected exception");
@@ -63,7 +60,7 @@ public class SearchPathTest {
}
@Test
- public void invalidPartMustThrowException() {
+ void invalidPartMustThrowException() {
try {
SearchPath.fromString("p/0");
fail("Expected exception");
@@ -74,7 +71,7 @@ public class SearchPathTest {
}
@Test
- public void invalidRowMustThrowException() {
+ void invalidRowMustThrowException() {
try {
SearchPath.fromString("1,2,3/r");
fail("Expected exception");
@@ -92,8 +89,8 @@ public class SearchPathTest {
}
@Test
- public void searchPathMustFilterNodesBasedOnDefinition() {
- MockSearchCluster cluster = new MockSearchCluster("a",3, 3);
+ void searchPathMustFilterNodesBasedOnDefinition() {
+ MockSearchCluster cluster = new MockSearchCluster("a", 3, 3);
assertEquals(distKeysAsString(SearchPath.selectNodes("1/1", cluster)), "4");
assertEquals(distKeysAsString(SearchPath.selectNodes("/1", cluster)), "3,4,5");
diff --git a/container-search/src/test/java/com/yahoo/search/dispatch/TopKEstimatorTest.java b/container-search/src/test/java/com/yahoo/search/dispatch/TopKEstimatorTest.java
index 5dfcd8901da..283596322e6 100644
--- a/container-search/src/test/java/com/yahoo/search/dispatch/TopKEstimatorTest.java
+++ b/container-search/src/test/java/com/yahoo/search/dispatch/TopKEstimatorTest.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.search.dispatch;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Locale;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class TopKEstimatorTest {
@Test
- public void requireHitsAreEstimatedAccordingToPartitionsAndProbability() {
+ void requireHitsAreEstimatedAccordingToPartitionsAndProbability() {
TopKEstimator estimator = new TopKEstimator(30, 0.999);
assertEquals(91.97368471911312, estimator.estimateExactK(200, 3), 0.0);
assertEquals(92, estimator.estimateK(200, 3));
@@ -27,8 +27,9 @@ public class TopKEstimatorTest {
assertEquals(44.909040374464155, estimator.estimateExactK(200, 10, 0.99999), 0.0);
assertEquals(45, estimator.estimateK(200, 10, 0.99999));
}
+
@Test
- public void requireHitsAreEstimatedAccordingToPartitionsAndProbabilityForVaryingN_K200() {
+ void requireHitsAreEstimatedAccordingToPartitionsAndProbabilityForVaryingN_K200() {
TopKEstimator estimator = new TopKEstimator(30, 0.99999);
assertEquals(200, estimator.estimateExactK(200, 1), 0.0);
assertEquals(200, estimator.estimateK(200, 1));
@@ -39,7 +40,7 @@ public class TopKEstimatorTest {
}
@Test
- public void requireHitsAreEstimatedAccordingToPartitionsAndProbabilityForVaryingN_K20() {
+ void requireHitsAreEstimatedAccordingToPartitionsAndProbabilityForVaryingN_K20() {
TopKEstimator estimator = new TopKEstimator(30, 0.99999);
assertEquals(20, estimator.estimateExactK(20, 1), 0.0);
assertEquals(20, estimator.estimateK(20, 1));
@@ -50,7 +51,7 @@ public class TopKEstimatorTest {
}
@Test
- public void requireHitsAreEstimatedAccordingToPartitionsAndProbabilityForVaryingN_K10_Five9() {
+ void requireHitsAreEstimatedAccordingToPartitionsAndProbabilityForVaryingN_K10_Five9() {
TopKEstimator estimator = new TopKEstimator(30, 0.99999);
assertEquals(10, estimator.estimateExactK(10, 1), 0.0);
assertEquals(10, estimator.estimateK(10, 1));
@@ -61,7 +62,7 @@ public class TopKEstimatorTest {
}
@Test
- public void requireHitsAreEstimatedAccordingToPartitionsAndProbabilityForVaryingN_K10_Four9() {
+ void requireHitsAreEstimatedAccordingToPartitionsAndProbabilityForVaryingN_K10_Four9() {
TopKEstimator estimator = new TopKEstimator(30, 0.9999);
assertEquals(10, estimator.estimateExactK(10, 1), 0.0);
assertEquals(10, estimator.estimateK(10, 1));
@@ -72,21 +73,21 @@ public class TopKEstimatorTest {
}
@Test
- public void requireEstimatesAreRoundeUp() {
+ void requireEstimatesAreRoundeUp() {
TopKEstimator estimator = new TopKEstimator(30, 0.9999);
assertEquals(5.794676146031378, estimator.estimateExactK(10, 10), 0.0);
assertEquals(6, estimator.estimateK(10, 10));
}
@Test
- public void requireEstimatesAreCappedAtInputK() {
+ void requireEstimatesAreCappedAtInputK() {
TopKEstimator estimator = new TopKEstimator(30, 0.9999);
assertEquals(12.087323848369289, estimator.estimateExactK(10, 2), 0.0);
assertEquals(10, estimator.estimateK(10, 2));
}
@Test
- public void requireThatLargeKAreSane() {
+ void requireThatLargeKAreSane() {
System.out.println(dumpProbability(10, 0.05));
TopKEstimator idealEstimator = new TopKEstimator(30, 0.9999);
TopKEstimator skewedEstimator = new TopKEstimator(30, 0.9999, 0.05);
@@ -100,23 +101,23 @@ public class TopKEstimatorTest {
String expected =
"Prob/Hits: 1.0000000000 0.9999000000 0.9999900000 0.9999990000 0.9999999000 0.9999999900 0.9999999990 0.9999999999\n" +
- " 10: 10.000 6.000 7.000 8.000 9.000 10.000 10.000 10.000\n" +
- " 20: 10.000 4.500 5.000 5.500 6.500 7.000 7.500 8.000\n" +
- " 40: 10.000 3.500 4.000 4.250 4.750 5.250 5.500 6.000\n" +
- " 80: 10.000 2.750 3.000 3.250 3.625 3.875 4.250 4.500\n" +
- " 100: 10.000 2.600 2.800 3.100 3.300 3.600 3.900 4.200\n" +
- " 200: 10.000 2.100 2.250 2.450 2.650 2.800 3.000 3.200\n" +
- " 400: 10.000 1.775 1.900 2.025 2.150 2.275 2.425 2.575\n" +
- " 800: 10.000 1.538 1.625 1.713 1.813 1.900 2.000 2.100\n" +
- " 1000: 10.000 1.480 1.560 1.640 1.720 1.810 1.890 1.990\n" +
- " 2000: 10.000 1.340 1.395 1.450 1.510 1.570 1.630 1.695\n" +
- " 4000: 10.000 1.240 1.280 1.320 1.360 1.403 1.445 1.493\n" +
- " 8000: 10.000 1.170 1.198 1.225 1.254 1.284 1.315 1.348\n" +
- " 10000: 10.000 1.152 1.177 1.202 1.227 1.254 1.282 1.311\n" +
- " 20000: 10.000 1.108 1.125 1.143 1.161 1.180 1.199 1.220\n" +
- " 40000: 10.000 1.076 1.088 1.101 1.114 1.127 1.141 1.156\n" +
- " 80000: 10.000 1.054 1.062 1.071 1.080 1.090 1.100 1.110\n" +
- " 100000: 10.000 1.048 1.056 1.064 1.072 1.080 1.089 1.098\n";
+ " 10: 10.000 6.000 7.000 8.000 9.000 10.000 10.000 10.000\n" +
+ " 20: 10.000 4.500 5.000 5.500 6.500 7.000 7.500 8.000\n" +
+ " 40: 10.000 3.500 4.000 4.250 4.750 5.250 5.500 6.000\n" +
+ " 80: 10.000 2.750 3.000 3.250 3.625 3.875 4.250 4.500\n" +
+ " 100: 10.000 2.600 2.800 3.100 3.300 3.600 3.900 4.200\n" +
+ " 200: 10.000 2.100 2.250 2.450 2.650 2.800 3.000 3.200\n" +
+ " 400: 10.000 1.775 1.900 2.025 2.150 2.275 2.425 2.575\n" +
+ " 800: 10.000 1.538 1.625 1.713 1.813 1.900 2.000 2.100\n" +
+ " 1000: 10.000 1.480 1.560 1.640 1.720 1.810 1.890 1.990\n" +
+ " 2000: 10.000 1.340 1.395 1.450 1.510 1.570 1.630 1.695\n" +
+ " 4000: 10.000 1.240 1.280 1.320 1.360 1.403 1.445 1.493\n" +
+ " 8000: 10.000 1.170 1.198 1.225 1.254 1.284 1.315 1.348\n" +
+ " 10000: 10.000 1.152 1.177 1.202 1.227 1.254 1.282 1.311\n" +
+ " 20000: 10.000 1.108 1.125 1.143 1.161 1.180 1.199 1.220\n" +
+ " 40000: 10.000 1.076 1.088 1.101 1.114 1.127 1.141 1.156\n" +
+ " 80000: 10.000 1.054 1.062 1.071 1.080 1.090 1.100 1.110\n" +
+ " 100000: 10.000 1.048 1.056 1.064 1.072 1.080 1.089 1.098\n";
assertEquals(expected, dumpProbability(10, 0.0));
String expectedSkew =
"Prob/Hits: 1.0000000000 0.9999000000 0.9999900000 0.9999990000 0.9999999000 0.9999999900 0.9999999990 0.9999999999\n" +
diff --git a/container-search/src/test/java/com/yahoo/search/dispatch/rpc/MatchFeatureDataTest.java b/container-search/src/test/java/com/yahoo/search/dispatch/rpc/MatchFeatureDataTest.java
index 6834a5edf9b..861ed4d165d 100644
--- a/container-search/src/test/java/com/yahoo/search/dispatch/rpc/MatchFeatureDataTest.java
+++ b/container-search/src/test/java/com/yahoo/search/dispatch/rpc/MatchFeatureDataTest.java
@@ -6,14 +6,12 @@ import com.yahoo.data.access.ArrayTraverser;
import com.yahoo.data.access.Inspector;
import com.yahoo.data.access.ObjectTraverser;
import com.yahoo.data.access.Type;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
-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 arnej
@@ -21,14 +19,14 @@ import static org.junit.Assert.assertTrue;
public class MatchFeatureDataTest {
@Test
- public void testHitValueAPI() {
+ void testHitValueAPI() {
List<String> names = List.of("foo", "bar", "baz", "qux", "quux");
var mf = new MatchFeatureData(names);
var hit = mf.addHit();
assertEquals(hit.type(), Type.OBJECT);
assertTrue(hit.valid());
hit.set(0, 1.0);
- byte[] somebytes = { 42, 0, 17 };
+ byte[] somebytes = {42, 0, 17};
hit.set(2, somebytes);
hit.set(4, 5.0);
hit.set(1, 2.0);
@@ -64,7 +62,7 @@ public class MatchFeatureDataTest {
var fields = hit.fields().iterator();
assertTrue(fields.hasNext());
- Map.Entry<String,Inspector> entry = fields.next();
+ Map.Entry<String, Inspector> entry = fields.next();
assertEquals("foo", entry.getKey());
assertEquals(f1.type(), entry.getValue().type());
assertEquals(f1.asDouble(), entry.getValue().asDouble(), 0.0);
@@ -94,9 +92,9 @@ public class MatchFeatureDataTest {
assertEquals(f5.asDouble(), entry.getValue().asDouble(), 0.0);
assertFalse(fields.hasNext());
-
+
assertEquals("{\"foo\":1.0,\"bar\":2.0,\"baz\":\"0x2A0011\",\"qux\":4.0,\"quux\":5.0}",
- hit.toString());
+ hit.toString());
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/dispatch/rpc/ProtobufSerializationTest.java b/container-search/src/test/java/com/yahoo/search/dispatch/rpc/ProtobufSerializationTest.java
index 9953d1467e1..72b3095b2f9 100644
--- a/container-search/src/test/java/com/yahoo/search/dispatch/rpc/ProtobufSerializationTest.java
+++ b/container-search/src/test/java/com/yahoo/search/dispatch/rpc/ProtobufSerializationTest.java
@@ -12,14 +12,12 @@ import com.yahoo.search.dispatch.InvokerResult;
import com.yahoo.search.dispatch.LeanHit;
import com.yahoo.search.query.profile.compiled.CompiledQueryProfileRegistry;
import com.yahoo.search.query.profile.config.QueryProfileXMLReader;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
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 ollivir
@@ -29,38 +27,38 @@ public class ProtobufSerializationTest {
static final double DELTA = 0.000000000001;
@Test
- public void testQuerySerialization() {
+ void testQuerySerialization() {
CompiledQueryProfileRegistry registry = new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/tensortypes").compile();
Query query = new Query.Builder().setQueryProfile(registry.getComponent("profile1"))
- .setRequest("?query=test&ranking.features.query(tensor_1)=[1.200]")
- .build();
+ .setRequest("?query=test&ranking.features.query(tensor_1)=[1.200]")
+ .build();
- SearchProtocol.SearchRequest request1 = ProtobufSerialization.convertFromQuery(query, 9,"serverId", 0.5);
+ SearchProtocol.SearchRequest request1 = ProtobufSerialization.convertFromQuery(query, 9, "serverId", 0.5);
assertEquals(9, request1.getHits());
assertEquals(0, request1.getRankPropertiesCount());
assertEquals(0, request1.getTensorRankPropertiesCount());
assertEquals(0, request1.getFeatureOverridesCount());
assertEquals(2, request1.getTensorFeatureOverridesCount());
assertEquals("\"\\001\\001\\003key\\001\\rpre_key1_post?\\360\\000\\000\\000\\000\\000\\000\"",
- contentsOf(request1.getTensorFeatureOverrides(0).getValue()));
+ contentsOf(request1.getTensorFeatureOverrides(0).getValue()));
assertEquals("\"\\006\\001\\001\\001x\\001?\\231\\231\\232\"",
- contentsOf(request1.getTensorFeatureOverrides(1).getValue()));
+ contentsOf(request1.getTensorFeatureOverrides(1).getValue()));
query.prepare(); // calling prepare() moves "overrides" to "features" - content stays the same
- SearchProtocol.SearchRequest request2 = ProtobufSerialization.convertFromQuery(query, 9,"serverId", 0.5);
+ SearchProtocol.SearchRequest request2 = ProtobufSerialization.convertFromQuery(query, 9, "serverId", 0.5);
assertEquals(9, request2.getHits());
assertEquals(0, request2.getRankPropertiesCount());
assertEquals(2, request2.getTensorRankPropertiesCount());
assertEquals("\"\\001\\001\\003key\\001\\rpre_key1_post?\\360\\000\\000\\000\\000\\000\\000\"",
- contentsOf(request2.getTensorRankProperties(0).getValue()));
+ contentsOf(request2.getTensorRankProperties(0).getValue()));
assertEquals("\"\\006\\001\\001\\001x\\001?\\231\\231\\232\"",
- contentsOf(request2.getTensorRankProperties(1).getValue()));
+ contentsOf(request2.getTensorRankProperties(1).getValue()));
assertEquals(0, request2.getFeatureOverridesCount());
assertEquals(0, request2.getTensorFeatureOverridesCount());
}
@Test
- public void testDocsumSerialization() {
+ void testDocsumSerialization() {
Query q = new Query("search/?query=test&hits=10&offset=3");
var builder = ProtobufSerialization.createDocsumRequestBuilder(q, "server", "summary", true, 0.5);
builder.setTimeout(0);
@@ -95,8 +93,9 @@ public class ProtobufSerializationTest {
}
return reply.build();
}
+
@Test
- public void testSearchReplyDecodingWithRelevance() {
+ void testSearchReplyDecodingWithRelevance() {
Query q = new Query("search/?query=test");
InvokerResult result = ProtobufSerialization.convertToResult(q, createSearchReply(5, false), null, 1, 2);
assertEquals(result.getResult().getTotalHitCount(), 7);
@@ -114,8 +113,9 @@ public class ProtobufSerializationTest {
hitNum++;
}
}
+
@Test
- public void testSearchReplyDecodingWithSortData() {
+ void testSearchReplyDecodingWithSortData() {
Query q = new Query("search/?query=test");
InvokerResult result = ProtobufSerialization.convertToResult(q, createSearchReply(5, true), null, 1, 2);
assertEquals(result.getResult().getTotalHitCount(), 7);
diff --git a/container-search/src/test/java/com/yahoo/search/dispatch/rpc/RpcSearchInvokerTest.java b/container-search/src/test/java/com/yahoo/search/dispatch/rpc/RpcSearchInvokerTest.java
index c26bef05fb6..6789d0347d5 100644
--- a/container-search/src/test/java/com/yahoo/search/dispatch/rpc/RpcSearchInvokerTest.java
+++ b/container-search/src/test/java/com/yahoo/search/dispatch/rpc/RpcSearchInvokerTest.java
@@ -11,17 +11,14 @@ import com.yahoo.search.Query;
import com.yahoo.search.Result;
import com.yahoo.search.dispatch.searchcluster.Node;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
-import static org.junit.Assert.assertEquals;
-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.*;
/**
* @author ollivir
@@ -29,7 +26,7 @@ import static org.junit.Assert.fail;
public class RpcSearchInvokerTest {
@Test
- public void testProtobufSerialization() throws IOException {
+ void testProtobufSerialization() throws IOException {
var compressionTypeHolder = new AtomicReference<CompressionType>();
var payloadHolder = new AtomicReference<byte[]>();
var lengthHolder = new AtomicInteger();
@@ -50,14 +47,14 @@ public class RpcSearchInvokerTest {
assertTrue(request.getQueryTreeBlob().size() > 0);
var invoker2 = new RpcSearchInvoker(mockSearcher(), new Node(8, "eight", 1), mockPool, 1000);
- RpcSearchInvoker.RpcContext context2 = (RpcSearchInvoker.RpcContext)invoker2.sendSearchRequest(q, context);
+ RpcSearchInvoker.RpcContext context2 = (RpcSearchInvoker.RpcContext) invoker2.sendSearchRequest(q, context);
assertSame(context, context2);
assertEquals(lengthHolder.get(), context.compressedPayload.uncompressedSize());
assertSame(context.compressedPayload.data(), payloadHolder.get());
}
@Test
- public void testProtobufSerializationWithMaxHitsSet() throws IOException {
+ void testProtobufSerializationWithMaxHitsSet() throws IOException {
int maxHits = 5;
var compressionTypeHolder = new AtomicReference<CompressionType>();
var payloadHolder = new AtomicReference<byte[]>();
diff --git a/container-search/src/test/java/com/yahoo/search/dispatch/searchcluster/SearchClusterCoverageTest.java b/container-search/src/test/java/com/yahoo/search/dispatch/searchcluster/SearchClusterCoverageTest.java
index c21bf623366..3d981c5e45a 100644
--- a/container-search/src/test/java/com/yahoo/search/dispatch/searchcluster/SearchClusterCoverageTest.java
+++ b/container-search/src/test/java/com/yahoo/search/dispatch/searchcluster/SearchClusterCoverageTest.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.search.dispatch.searchcluster;
-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
@@ -12,7 +12,7 @@ import static org.junit.Assert.assertTrue;
public class SearchClusterCoverageTest {
@Test
- public void two_groups_equal_docs() {
+ void two_groups_equal_docs() {
var tester = new SearchClusterTester(2, 3);
tester.setDocsPerNode(100, 0);
@@ -23,22 +23,22 @@ public class SearchClusterCoverageTest {
}
@Test
- public void two_groups_one_missing_docs() {
+ void two_groups_one_missing_docs() {
var tester = new SearchClusterTester(2, 3);
tester.setDocsPerNode(100, 0);
- tester.setDocsPerNode( 70, 1);
+ tester.setDocsPerNode(70, 1);
tester.pingIterationCompleted();
assertTrue(tester.group(0).hasSufficientCoverage());
assertFalse(tester.group(1).hasSufficientCoverage());
}
@Test
- public void three_groups_one_missing_docs() {
+ void three_groups_one_missing_docs() {
var tester = new SearchClusterTester(3, 3);
tester.setDocsPerNode(100, 0);
- tester.setDocsPerNode( 87, 1); // min is set to 88 in MockSearchCluster
+ tester.setDocsPerNode(87, 1); // min is set to 88 in MockSearchCluster
tester.setDocsPerNode(100, 2);
tester.pingIterationCompleted();
assertTrue(tester.group(0).hasSufficientCoverage());
@@ -47,11 +47,11 @@ public class SearchClusterCoverageTest {
}
@Test
- public void three_groups_one_missing_docs_but_too_few() {
+ void three_groups_one_missing_docs_but_too_few() {
var tester = new SearchClusterTester(3, 3);
tester.setDocsPerNode(100, 0);
- tester.setDocsPerNode( 89, 1); // min is set to 88 in MockSearchCluster
+ tester.setDocsPerNode(89, 1); // min is set to 88 in MockSearchCluster
tester.setDocsPerNode(100, 2);
tester.pingIterationCompleted();
assertTrue(tester.group(0).hasSufficientCoverage());
@@ -60,7 +60,7 @@ public class SearchClusterCoverageTest {
}
@Test
- public void three_groups_one_has_too_many_docs() {
+ void three_groups_one_has_too_many_docs() {
var tester = new SearchClusterTester(3, 3);
tester.setDocsPerNode(100, 0);
@@ -73,7 +73,7 @@ public class SearchClusterCoverageTest {
}
@Test
- public void three_groups_one_has_a_node_down() {
+ void three_groups_one_has_a_node_down() {
var tester = new SearchClusterTester(3, 3);
tester.setDocsPerNode(100, 0);
@@ -87,7 +87,7 @@ public class SearchClusterCoverageTest {
}
@Test
- public void three_groups_one_has_a_node_down_but_remaining_has_enough_docs() {
+ void three_groups_one_has_a_node_down_but_remaining_has_enough_docs() {
var tester = new SearchClusterTester(3, 3);
tester.setDocsPerNode(100, 0);
@@ -96,12 +96,12 @@ public class SearchClusterCoverageTest {
tester.setWorking(1, 1, false);
tester.pingIterationCompleted();
assertTrue(tester.group(0).hasSufficientCoverage());
- assertTrue("Sufficient documents on remaining two nodes", tester.group(1).hasSufficientCoverage());
+ assertTrue(tester.group(1).hasSufficientCoverage(), "Sufficient documents on remaining two nodes");
assertTrue(tester.group(2).hasSufficientCoverage());
}
@Test
- public void one_group_few_docs_unbalanced() {
+ void one_group_few_docs_unbalanced() {
var tester = new SearchClusterTester(1, 2);
Node node0 = tester.group(0).nodes().get(0);
@@ -120,7 +120,7 @@ public class SearchClusterCoverageTest {
}
@Test
- public void one_group_many_docs_unbalanced() {
+ void one_group_many_docs_unbalanced() {
var tester = new SearchClusterTester(1, 2);
Node node0 = tester.group(0).nodes().get(0);
diff --git a/container-search/src/test/java/com/yahoo/search/dispatch/searchcluster/SearchClusterTest.java b/container-search/src/test/java/com/yahoo/search/dispatch/searchcluster/SearchClusterTest.java
index 94df796b370..473b24af19f 100644
--- a/container-search/src/test/java/com/yahoo/search/dispatch/searchcluster/SearchClusterTest.java
+++ b/container-search/src/test/java/com/yahoo/search/dispatch/searchcluster/SearchClusterTest.java
@@ -9,7 +9,7 @@ import com.yahoo.prelude.Pong;
import com.yahoo.search.cluster.ClusterMonitor;
import com.yahoo.search.dispatch.MockSearchCluster;
import com.yahoo.search.result.ErrorMessage;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
@@ -19,9 +19,7 @@ import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
-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
@@ -151,7 +149,7 @@ public class SearchClusterTest {
}
@Test
- public void requireThatVipStatusIsDefaultDownButComesUpAfterPinging() {
+ void requireThatVipStatusIsDefaultDownButComesUpAfterPinging() {
try (State test = new State("cluster.1", 2, "a", "b")) {
assertTrue(test.searchCluster.localCorpusDispatchTarget().isEmpty());
@@ -162,7 +160,7 @@ public class SearchClusterTest {
}
@Test
- public void requireThatZeroDocsAreFine() {
+ void requireThatZeroDocsAreFine() {
try (State test = new State("cluster.1", 2, "a", "b")) {
test.waitOneFullPingRound();
@@ -180,7 +178,7 @@ public class SearchClusterTest {
}
@Test
- public void requireThatVipStatusIsDefaultDownWithLocalDispatch() {
+ void requireThatVipStatusIsDefaultDownWithLocalDispatch() {
try (State test = new State("cluster.1", 1, HostName.getLocalhost(), "b")) {
assertTrue(test.searchCluster.localCorpusDispatchTarget().isPresent());
@@ -191,7 +189,7 @@ public class SearchClusterTest {
}
@Test
- public void requireThatVipStatusStaysUpWithLocalDispatchAndClusterSize1() {
+ void requireThatVipStatusStaysUpWithLocalDispatchAndClusterSize1() {
try (State test = new State("cluster.1", 1, HostName.getLocalhost())) {
assertTrue(test.searchCluster.localCorpusDispatchTarget().isPresent());
@@ -205,7 +203,7 @@ public class SearchClusterTest {
}
@Test
- public void requireThatVipStatusIsDefaultDownWithLocalDispatchAndClusterSize2() {
+ void requireThatVipStatusIsDefaultDownWithLocalDispatchAndClusterSize2() {
try (State test = new State("cluster.1", 1, HostName.getLocalhost(), "otherhost")) {
assertTrue(test.searchCluster.localCorpusDispatchTarget().isPresent());
@@ -219,7 +217,7 @@ public class SearchClusterTest {
}
@Test
- public void requireThatVipStatusDownWhenLocalIsDown() {
+ void requireThatVipStatusDownWhenLocalIsDown() {
try (State test = new State("cluster.1", 1, HostName.getLocalhost(), "b")) {
test.waitOneFullPingRound();
@@ -276,8 +274,8 @@ public class SearchClusterTest {
}
@Test
- public void requireThatVipStatusDownRequireAllNodesDown() {
- verifyThatVipStatusDownRequireAllNodesDown(1,2);
+ void requireThatVipStatusDownRequireAllNodesDown() {
+ verifyThatVipStatusDownRequireAllNodesDown(1, 2);
verifyThatVipStatusDownRequireAllNodesDown(3, 3);
}
@@ -315,13 +313,13 @@ public class SearchClusterTest {
}
@Test
- public void requireThatVipStatusUpRequireOnlyOneOnlineNode() {
+ void requireThatVipStatusUpRequireOnlyOneOnlineNode() {
verifyThatVipStatusUpRequireOnlyOneOnlineNode(1, 2);
verifyThatVipStatusUpRequireOnlyOneOnlineNode(3, 3);
}
@Test
- public void requireThatPingSequenceIsUpHeld() {
+ void requireThatPingSequenceIsUpHeld() {
Node node = new Node(1, "n", 1);
assertEquals(1, node.createPingSequenceId());
assertEquals(2, node.createPingSequenceId());
@@ -335,7 +333,7 @@ public class SearchClusterTest {
}
@Test
- public void requireThatEmptyGroupIsInBalance() {
+ void requireThatEmptyGroupIsInBalance() {
Group group = new Group(0, new ArrayList<>());
assertTrue(group.isBalanced());
group.aggregateNodeValues();
@@ -343,7 +341,7 @@ public class SearchClusterTest {
}
@Test
- public void requireThatSingleNodeGroupIsInBalance() {
+ void requireThatSingleNodeGroupIsInBalance() {
Group group = new Group(0, Arrays.asList(new Node(1, "n", 1)));
group.nodes().forEach(node -> node.setWorking(true));
assertTrue(group.isBalanced());
@@ -355,7 +353,7 @@ public class SearchClusterTest {
}
@Test
- public void requireThatMultiNodeGroupDetectsBalance() {
+ void requireThatMultiNodeGroupDetectsBalance() {
Group group = new Group(0, Arrays.asList(new Node(1, "n1", 1), new Node(2, "n2", 1)));
assertTrue(group.isBalanced());
group.nodes().forEach(node -> node.setWorking(true));
diff --git a/container-search/src/test/java/com/yahoo/search/federation/DuplicateSourceTestCase.java b/container-search/src/test/java/com/yahoo/search/federation/DuplicateSourceTestCase.java
index da25baacd51..cb0d4ab923f 100644
--- a/container-search/src/test/java/com/yahoo/search/federation/DuplicateSourceTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/federation/DuplicateSourceTestCase.java
@@ -12,7 +12,7 @@ import com.yahoo.search.Searcher;
import com.yahoo.search.federation.sourceref.SearchChainResolver;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.searchchain.SearchChainRegistry;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.HashMap;
@@ -20,8 +20,8 @@ import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
/**
* Tests that sources representing document types which resolve to the same actual source
@@ -32,7 +32,7 @@ import static org.junit.Assert.assertEquals;
public class DuplicateSourceTestCase {
@Test
- public void testDuplicateSource() {
+ void testDuplicateSource() {
// Set up a single cluster and chain (chain1), containing a MockBackendSearcher and having 2 doc types (doc1, doc2)
MockBackendSearcher mockBackendSearcher = new MockBackendSearcher();
SearchChainRegistry searchChains = new SearchChainRegistry();
@@ -41,12 +41,12 @@ public class DuplicateSourceTestCase {
clusters.put("chain1", ImmutableList.of("doc1", "doc2"));
IndexFacts indexFacts = new IndexFacts(new IndexModel(clusters, Collections.emptyList()));
SearchChainResolver resolver = new SearchChainResolver.Builder()
- .addSearchChain(new ComponentId("chain1"), ImmutableList.of("doc1", "doc2"))
- .build();
+ .addSearchChain(new ComponentId("chain1"), ImmutableList.of("doc1", "doc2"))
+ .build();
FederationSearcher searcher = new FederationSearcher(new ComponentId("test"), resolver);
Result result = searcher.search(new Query("?query=test&sources=doc1%2cdoc2"),
- new Execution(Execution.Context.createContextStub(searchChains, indexFacts)));
+ new Execution(Execution.Context.createContextStub(searchChains, indexFacts)));
assertNull(result.hits().getError());
assertEquals(1, mockBackendSearcher.getInvocationCount());
diff --git a/container-search/src/test/java/com/yahoo/search/federation/FederationResultTest.java b/container-search/src/test/java/com/yahoo/search/federation/FederationResultTest.java
index a17104f888d..71004f5a98a 100644
--- a/container-search/src/test/java/com/yahoo/search/federation/FederationResultTest.java
+++ b/container-search/src/test/java/com/yahoo/search/federation/FederationResultTest.java
@@ -11,16 +11,14 @@ import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.searchchain.FutureResult;
import com.yahoo.search.searchchain.model.federation.FederationOptions;
import com.yahoo.test.ManualClock;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
-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 bratseth
@@ -34,7 +32,7 @@ public class FederationResultTest {
private final ManualClock clock = new ManualClock();
@Test
- public void testFederationResult() {
+ void testFederationResult() {
assertTimeout(ImmutableSet.of(), 100, 200, 180);
assertTimeout(ImmutableSet.of(), 480, 400, 400);
assertTimeout(ImmutableSet.of("dsp1"), 260, 280, 220);
@@ -56,9 +54,9 @@ public class FederationResultTest {
for (FederationResult.TargetResult targetResult : federationResult.all()) {
Result result = targetResult.getOrTimeoutError();
if (expectedTimeoutNames.contains(targetResult.target.getId().toString()))
- assertTrue(targetResult.target.getId() + " timed out", timedOut(result));
+ assertTrue(timedOut(result), targetResult.target.getId() + " timed out");
else
- assertFalse(targetResult.target.getId() + " did not time out", timedOut(result));
+ assertFalse(timedOut(result), targetResult.target.getId() + " did not time out");
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/federation/FederationSearcherTest.java b/container-search/src/test/java/com/yahoo/search/federation/FederationSearcherTest.java
index 4bb6db40c66..2c83bc8cc00 100644
--- a/container-search/src/test/java/com/yahoo/search/federation/FederationSearcherTest.java
+++ b/container-search/src/test/java/com/yahoo/search/federation/FederationSearcherTest.java
@@ -20,17 +20,14 @@ import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.searchchain.Execution.Context;
import com.yahoo.search.searchchain.model.federation.FederationOptions;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
-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 Tony Vaagenes
@@ -40,19 +37,19 @@ public class FederationSearcherTest {
private static final String hasBeenFilled = "hasBeenFilled";
@Test
- public void require_that_hits_are_not_automatically_filled() {
+ void require_that_hits_are_not_automatically_filled() {
Result result = federationToSingleAddHitSearcher().search();
assertNotFilled(firstHitInFirstGroup(result));
}
@Test
- public void require_that_hits_can_be_filled() {
+ void require_that_hits_can_be_filled() {
Result result = federationToSingleAddHitSearcher().searchAndFill();
assertFilled(firstHitInFirstGroup(result));
}
@Test
- public void require_that_hits_can_be_filled_when_moved() {
+ void require_that_hits_can_be_filled_when_moved() {
FederationTester tester = new FederationTester();
tester.addSearchChain("chain1", new AddHitSearcher());
tester.addSearchChain("chain2", new AddHitSearcher());
@@ -80,7 +77,7 @@ public class FederationSearcherTest {
}
@Test
- public void require_that_hits_can_be_filled_for_multiple_chains_and_queries() {
+ void require_that_hits_can_be_filled_for_multiple_chains_and_queries() {
FederationTester tester = new FederationTester();
tester.addSearchChain("chain1", new AddHitSearcher());
tester.addSearchChain("chain2", new ModifyQueryAndAddHitSearcher("modified1"));
@@ -89,12 +86,12 @@ public class FederationSearcherTest {
Result result = tester.search();
tester.fill(result);
assertEquals(3, result.hits().getConcreteSize());
- for (Iterator<Hit> i = result.hits().deepIterator(); i.hasNext();)
+ for (Iterator<Hit> i = result.hits().deepIterator(); i.hasNext(); )
assertFilled(i.next());
}
@Test
- public void require_that_hits_that_time_out_in_fill_are_removed() {
+ void require_that_hits_that_time_out_in_fill_are_removed() {
FederationTester tester = new FederationTester();
tester.addSearchChain("chain1", new AddHitSearcher());
tester.addSearchChain("chain2", new TimeoutInFillSearcher());
@@ -104,13 +101,13 @@ public class FederationSearcherTest {
Result result = tester.search(query);
tester.fill(result);
assertEquals(1, result.hits().getConcreteSize());
- for (Iterator<Hit> i = result.hits().deepIterator(); i.hasNext();)
+ for (Iterator<Hit> i = result.hits().deepIterator(); i.hasNext(); )
assertFilled(i.next());
assertEquals("Timed out", result.hits().getError().getMessage());
}
@Test
- public void require_that_optional_search_chains_does_not_delay_federation() {
+ void require_that_optional_search_chains_does_not_delay_federation() {
BlockingSearcher blockingSearcher = new BlockingSearcher();
FederationTester tester = new FederationTester();
@@ -121,8 +118,8 @@ public class FederationSearcherTest {
assertEquals(2, result.getHitCount());
assertTrue(result.hits().get(0) instanceof HitGroup);
assertTrue(result.hits().get(1) instanceof HitGroup);
- HitGroup chain1Result = (HitGroup)result.hits().get(0);
- HitGroup chain2Result = (HitGroup)result.hits().get(1);
+ HitGroup chain1Result = (HitGroup) result.hits().get(0);
+ HitGroup chain2Result = (HitGroup) result.hits().get(1);
// Verify chain1 result: One filled hit
assertEquals(1, chain1Result.size());
@@ -141,21 +138,21 @@ public class FederationSearcherTest {
}
@Test
- public void require_that_calling_a_single_slow_source_with_long_timeout_does_not_delay_federation() {
+ void require_that_calling_a_single_slow_source_with_long_timeout_does_not_delay_federation() {
FederationTester tester = new FederationTester();
tester.addSearchChain("chain1",
- new FederationOptions().setUseByDefault(true).setRequestTimeoutInMilliseconds(3600 * 1000),
- new BlockingSearcher() );
+ new FederationOptions().setUseByDefault(true).setRequestTimeoutInMilliseconds(3600 * 1000),
+ new BlockingSearcher());
Query query = new Query();
query.setTimeout(50); // make the test run faster
Result result = tester.search(query);
assertEquals(1, result.hits().size());
assertTrue(result.hits().get(0) instanceof HitGroup);
- HitGroup chain1Result = (HitGroup)result.hits().get(0);
+ HitGroup chain1Result = (HitGroup) result.hits().get(0);
assertEquals(1, chain1Result.size());
assertTrue(chain1Result.asList().get(0) instanceof ErrorHit);
- ErrorHit errorHit = (ErrorHit)chain1Result.get(0);
+ ErrorHit errorHit = (ErrorHit) chain1Result.get(0);
assertEquals(1, errorHit.errors().size());
ErrorMessage error = errorHit.errors().iterator().next();
assertEquals("chain1", error.getSource());
@@ -164,7 +161,7 @@ public class FederationSearcherTest {
}
@Test
- public void custom_federation_target() {
+ void custom_federation_target() {
ComponentId targetSelectorId = ComponentId.fromString("TargetSelector");
ComponentRegistry<TargetSelector> targetSelectors = new ComponentRegistry<>();
targetSelectors.register(targetSelectorId, new TestTargetSelector());
@@ -182,7 +179,7 @@ public class FederationSearcherTest {
}
@Test
- public void target_selectors_can_have_multiple_targets() {
+ void target_selectors_can_have_multiple_targets() {
ComponentId targetSelectorId = ComponentId.fromString("TestMultipleTargetSelector");
ComponentRegistry<TargetSelector> targetSelectors = new ComponentRegistry<>();
targetSelectors.register(targetSelectorId, new TestMultipleTargetSelector());
diff --git a/container-search/src/test/java/com/yahoo/search/federation/FederationSearcherTestCase.java b/container-search/src/test/java/com/yahoo/search/federation/FederationSearcherTestCase.java
index c2feb16df04..556cbea023f 100644
--- a/container-search/src/test/java/com/yahoo/search/federation/FederationSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/federation/FederationSearcherTestCase.java
@@ -19,17 +19,13 @@ import com.yahoo.search.test.QueryTestCase;
import com.yahoo.yolean.trace.TraceNode;
import com.yahoo.yolean.trace.TraceVisitor;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+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.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Test for federation searcher. The searcher is also tested in
@@ -60,13 +56,13 @@ public class FederationSearcherTestCase {
private FederationConfig.Builder builder;
private SearchChainRegistry chainRegistry;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
builder = new FederationConfig.Builder();
chainRegistry = new SearchChainRegistry();
}
- @After
+ @AfterEach
public void tearDown() {
builder = null;
chainRegistry = null;
@@ -93,7 +89,7 @@ public class FederationSearcherTestCase {
}
@Test
- public void testQueryProfileNestedReferencing() {
+ void testQueryProfileNestedReferencing() {
addChained(new MockSearcher(), "mySource1");
addChained(new MockSearcher(), "mySource2");
Chain<Searcher> mainChain = new Chain<>("default", createFederationSearcher());
@@ -110,7 +106,7 @@ public class FederationSearcherTestCase {
}
@Test
- public void testTraceTwoSources() {
+ void testTraceTwoSources() {
Chain<Searcher> mainChain = twoTracingSources(false);
Query q = new Query(com.yahoo.search.test.QueryTestCase.httpEncode("?query=test&traceLevel=1"));
@@ -148,7 +144,7 @@ public class FederationSearcherTestCase {
}
@Test
- public void testTraceOneSourceNoCloning() {
+ void testTraceOneSourceNoCloning() {
Chain<Searcher> mainChain = twoTracingSources(true);
Query q = new Query(com.yahoo.search.test.QueryTestCase.httpEncode("?query=test&traceLevel=1&sources=source1"));
@@ -163,7 +159,7 @@ public class FederationSearcherTestCase {
}
@Test
- public void testTraceOneSourceWithCloning() {
+ void testTraceOneSourceWithCloning() {
Chain<Searcher> mainChain = twoTracingSources(false);
Query q = new Query(com.yahoo.search.test.QueryTestCase.httpEncode("?query=test&traceLevel=1&sources=source1"));
@@ -179,7 +175,7 @@ public class FederationSearcherTestCase {
}
@Test
- public void testPropertyPropagation() {
+ void testPropertyPropagation() {
Result result = searchWithPropertyPropagation();
assertEquals("source:mySource1", result.hits().get(0).getId().stringValue());
@@ -210,7 +206,7 @@ public class FederationSearcherTestCase {
}
@Test
- public void testTopLevelHitGroupFieldPropagation() {
+ void testTopLevelHitGroupFieldPropagation() {
addChained(new MockSearcher(), "mySource1");
addChained(new AnotherMockSearcher(), "mySource2");
Chain<Searcher> mainChain = new Chain<>("default", createFederationSearcher());
@@ -256,7 +252,7 @@ public class FederationSearcherTestCase {
}
@Test
- public void testProviderSelectionFromQueryProperties() {
+ void testProviderSelectionFromQueryProperties() {
SearchChainRegistry registry = new SearchChainRegistry();
registry.register(new Chain<>("provider1", new MockProvider("provider1")));
registry.register(new Chain<>("provider2", new MockProvider("provider2")));
diff --git a/container-search/src/test/java/com/yahoo/search/federation/HitCountTestCase.java b/container-search/src/test/java/com/yahoo/search/federation/HitCountTestCase.java
index 6f1570b702f..59547ecdd35 100644
--- a/container-search/src/test/java/com/yahoo/search/federation/HitCountTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/federation/HitCountTestCase.java
@@ -5,13 +5,13 @@ import com.yahoo.search.Query;
import com.yahoo.search.Result;
import com.yahoo.search.result.Hit;
import com.yahoo.search.result.HitGroup;
-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.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Tony Vaagenes
@@ -19,7 +19,7 @@ import static org.junit.Assert.assertTrue;
public class HitCountTestCase {
@Test
- public void require_that_offset_and_hits_are_adjusted_when_federating() {
+ void require_that_offset_and_hits_are_adjusted_when_federating() {
final int chain1RelevanceMultiplier = 1;
final int chain2RelevanceMultiplier = 10;
@@ -38,7 +38,7 @@ public class HitCountTestCase {
}
@Test
- public void require_that_hit_counts_are_merged() {
+ void require_that_hit_counts_are_merged() {
final long chain1TotalHitCount = 3;
final long chain1DeepHitCount = 5;
@@ -56,7 +56,7 @@ public class HitCountTestCase {
}
@Test
- public void require_that_logging_hit_is_populated_with_result_count() {
+ void require_that_logging_hit_is_populated_with_result_count() {
final long chain1TotalHitCount = 9;
final long chain1DeepHitCount = 14;
diff --git a/container-search/src/test/java/com/yahoo/search/federation/sourceref/test/SearchChainResolverTestCase.java b/container-search/src/test/java/com/yahoo/search/federation/sourceref/test/SearchChainResolverTestCase.java
index 34224721487..5a551fdcdee 100644
--- a/container-search/src/test/java/com/yahoo/search/federation/sourceref/test/SearchChainResolverTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/federation/sourceref/test/SearchChainResolverTestCase.java
@@ -10,15 +10,13 @@ import com.yahoo.search.federation.sourceref.SearchChainResolver;
import com.yahoo.search.federation.sourceref.Target;
import com.yahoo.search.federation.sourceref.UnresolvedSearchChainException;
import com.yahoo.search.searchchain.model.federation.FederationOptions;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.Iterator;
import java.util.SortedSet;
-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 Tony Vaagenes
@@ -53,7 +51,7 @@ public class SearchChainResolverTestCase {
}
@Test
- public void check_default_search_chains() {
+ void check_default_search_chains() {
assertEquals(2, searchChainResolver.defaultTargets().size());
Iterator<Target> iterator = searchChainResolver.defaultTargets().iterator();
@@ -62,7 +60,7 @@ public class SearchChainResolverTestCase {
}
@Test
- public void require_error_message_for_invalid_source() {
+ void require_error_message_for_invalid_source() {
try {
resolve("no-such-source");
fail("Expected exception.");
@@ -72,7 +70,7 @@ public class SearchChainResolverTestCase {
}
@Test
- public void lookup_search_chain() throws Exception {
+ void lookup_search_chain() throws Exception {
SearchChainInvocationSpec res = resolve(searchChainId.getName());
assertEquals(searchChainId, res.searchChainId);
}
@@ -86,13 +84,13 @@ public class SearchChainResolverTestCase {
}
@Test
- public void lookup_source() throws Exception {
+ void lookup_source() throws Exception {
SearchChainInvocationSpec res = resolve(sourceId.getName());
assertIsSourceInProvider(res);
}
@Test
- public void lookup_source_search_chain_directly() throws Exception {
+ void lookup_source_search_chain_directly() throws Exception {
SearchChainInvocationSpec res = resolve(sourceChainInProviderId.stringValue());
assertIsSourceInProvider(res);
}
@@ -104,7 +102,7 @@ public class SearchChainResolverTestCase {
}
@Test
- public void lookup_source_for_provider2() throws Exception {
+ void lookup_source_for_provider2() throws Exception {
SearchChainInvocationSpec res = resolve(sourceId.getName(), provider2Id.getName());
assertEquals(provider2Id, res.provider);
assertEquals(sourceId, res.source);
@@ -112,7 +110,7 @@ public class SearchChainResolverTestCase {
}
@Test
- public void lists_source_ref_description_for_top_level_targets() {
+ void lists_source_ref_description_for_top_level_targets() {
SortedSet<Target> topLevelTargets = searchChainResolver.allTopLevelTargets();
assertEquals(3, topLevelTargets.size());
diff --git a/container-search/src/test/java/com/yahoo/search/federation/sourceref/test/SourceRefResolverTestCase.java b/container-search/src/test/java/com/yahoo/search/federation/sourceref/test/SourceRefResolverTestCase.java
index acb68175921..97c93ed09ed 100644
--- a/container-search/src/test/java/com/yahoo/search/federation/sourceref/test/SourceRefResolverTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/federation/sourceref/test/SourceRefResolverTestCase.java
@@ -10,7 +10,7 @@ import com.yahoo.search.federation.sourceref.SearchChainResolver;
import com.yahoo.search.federation.sourceref.SourceRefResolver;
import com.yahoo.search.federation.sourceref.UnresolvedSearchChainException;
import com.yahoo.search.searchchain.model.federation.FederationOptions;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Collections;
@@ -19,9 +19,7 @@ import java.util.Set;
import java.util.TreeMap;
import static com.yahoo.search.federation.sourceref.test.SearchChainResolverTestCase.emptySourceToProviderMap;
-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.*;
/**
* Test for SourceRefResolver.
@@ -60,38 +58,38 @@ public class SourceRefResolverTestCase {
}
@Test
- public void check_test_assumptions() {
+ void check_test_assumptions() {
assertTrue(indexFacts.clustersHavingSearchDefinition("document1").containsAll(List.of("cluster1", "cluster2")));
}
@Test
- public void lookup_search_chain() throws Exception {
+ void lookup_search_chain() throws Exception {
Set<SearchChainInvocationSpec> searchChains = resolve(cluster1);
assertEquals(1, searchChains.size());
assertTrue(searchChainIds(searchChains).contains(cluster1));
}
@Test
- public void lookup_search_chains_for_document1() throws Exception {
+ void lookup_search_chains_for_document1() throws Exception {
Set<SearchChainInvocationSpec> searchChains = resolve("document1");
assertEquals(2, searchChains.size());
assertTrue(searchChainIds(searchChains).containsAll(List.of(cluster1, cluster2)));
}
@Test
- public void error_when_document_gives_cluster_without_matching_search_chain() {
+ void error_when_document_gives_cluster_without_matching_search_chain() {
try {
resolve("document3");
fail("Expected exception");
} catch (UnresolvedSearchChainException e) {
assertEquals("Failed to resolve cluster search chain 'cluster3' " +
- "when using source ref 'document3' as a document name.",
- e.getMessage());
+ "when using source ref 'document3' as a document name.",
+ e.getMessage());
}
}
@Test
- public void error_when_no_document_or_search_chain() {
+ void error_when_no_document_or_search_chain() {
try {
resolve("document4");
fail("Expected exception");
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/ContinuationTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/ContinuationTestCase.java
index 217fd4af400..3dcfcb8480a 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/ContinuationTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/ContinuationTestCase.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.search.grouping;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* @author Simon Thoresen Hult
@@ -14,7 +14,7 @@ public class ContinuationTestCase {
private static final String KNOWN_CONTINUATION = "BCBCBCBEBGBCBKCBACBKCCK";
@Test
- public void requireThatToStringCanBeParsedByFromString() {
+ void requireThatToStringCanBeParsedByFromString() {
Continuation cnt = Continuation.fromString(KNOWN_CONTINUATION);
assertNotNull(cnt);
assertEquals(KNOWN_CONTINUATION, cnt.toString());
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/GroupingQueryParserTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/GroupingQueryParserTestCase.java
index bbb461a939c..4911a5b2543 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/GroupingQueryParserTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/GroupingQueryParserTestCase.java
@@ -7,13 +7,13 @@ import com.yahoo.search.grouping.request.EachOperation;
import com.yahoo.search.grouping.request.GroupingOperation;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.List;
import java.util.TimeZone;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -21,17 +21,17 @@ import static org.junit.Assert.*;
public class GroupingQueryParserTestCase {
@Test
- public void requireThatNoRequestIsSkipped() {
+ void requireThatNoRequestIsSkipped() {
assertEquals(Collections.emptyList(), executeQuery(null, null, null));
}
@Test
- public void requireThatEmptyRequestIsSkipped() {
+ void requireThatEmptyRequestIsSkipped() {
assertEquals(Collections.emptyList(), executeQuery("", null, null));
}
@Test
- public void requireThatRequestIsParsed() {
+ void requireThatRequestIsParsed() {
List<GroupingRequest> lst = executeQuery("all(group(foo) each(output(max(bar))))", null, null);
assertNotNull(lst);
assertEquals(1, lst.size());
@@ -41,7 +41,7 @@ public class GroupingQueryParserTestCase {
}
@Test
- public void requireThatRequestListIsParsed() {
+ void requireThatRequestListIsParsed() {
List<GroupingRequest> lst = executeQuery("all();each()", null, null);
assertNotNull(lst);
assertEquals(2, lst.size());
@@ -50,7 +50,7 @@ public class GroupingQueryParserTestCase {
}
@Test
- public void requireThatEachRightBelowAllParses() {
+ void requireThatEachRightBelowAllParses() {
List<GroupingRequest> lst = executeQuery("all(each(output(summary(bar))))",
null, null);
assertNotNull(lst);
@@ -64,9 +64,9 @@ public class GroupingQueryParserTestCase {
}
@Test
- public void requireThatContinuationListIsParsed() {
+ void requireThatContinuationListIsParsed() {
List<GroupingRequest> lst = executeQuery("all(group(foo) each(output(max(bar))))",
- "BCBCBCBEBGBCBKCBACBKCCK BCBBBBBDBF", null);
+ "BCBCBCBEBGBCBKCBACBKCCK BCBBBBBDBF", null);
assertNotNull(lst);
assertEquals(1, lst.size());
GroupingRequest req = lst.get(0);
@@ -76,7 +76,7 @@ public class GroupingQueryParserTestCase {
}
@Test
- public void requireThatTimeZoneIsParsed() {
+ void requireThatTimeZoneIsParsed() {
List<GroupingRequest> lst = executeQuery("all(group(foo) each(output(max(bar))))", null, "cet");
assertNotNull(lst);
assertEquals(1, lst.size());
@@ -88,7 +88,7 @@ public class GroupingQueryParserTestCase {
}
@Test
- public void requireThatTimeZoneHasUtcDefault() {
+ void requireThatTimeZoneHasUtcDefault() {
List<GroupingRequest> lst = executeQuery("all(group(foo) each(output(max(bar))))", null, null);
assertNotNull(lst);
assertEquals(1, lst.size());
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/GroupingRequestTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/GroupingRequestTestCase.java
index 4bc827dde7a..458039fb872 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/GroupingRequestTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/GroupingRequestTestCase.java
@@ -7,7 +7,7 @@ import com.yahoo.search.Result;
import com.yahoo.search.grouping.result.Group;
import com.yahoo.search.grouping.result.RootGroup;
import com.yahoo.search.result.Hit;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.lang.reflect.Field;
import java.util.ArrayList;
@@ -15,7 +15,7 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.List;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -23,7 +23,7 @@ import static org.junit.Assert.*;
public class GroupingRequestTestCase {
@Test
- public void requireThatContinuationListIsMutable() {
+ void requireThatContinuationListIsMutable() {
GroupingRequest req = GroupingRequest.newInstance(new Query());
assertTrue(req.continuations().isEmpty());
@@ -41,7 +41,7 @@ public class GroupingRequestTestCase {
}
@Test
- public void requireThatResultIsFound() {
+ void requireThatResultIsFound() {
Query query = new Query();
GroupingRequest req = GroupingRequest.newInstance(query);
Result res = new Result(query);
@@ -57,7 +57,7 @@ public class GroupingRequestTestCase {
}
@Test
- public void requireThatResultIsFoundAfterCloning() {
+ void requireThatResultIsFoundAfterCloning() {
Query query = new Query();
GroupingRequest req = GroupingRequest.newInstance(query);
Result res = new Result(query.clone());
@@ -73,7 +73,7 @@ public class GroupingRequestTestCase {
}
@Test
- public void requireThatParallelRequestsAreSupported() {
+ void requireThatParallelRequestsAreSupported() {
Query query = new Query();
Result res = new Result(query);
@@ -94,7 +94,7 @@ public class GroupingRequestTestCase {
}
@Test
- public void requireThatRemovedResultIsNull() {
+ void requireThatRemovedResultIsNull() {
Query query = new Query();
GroupingRequest req = GroupingRequest.newInstance(query);
Result res = new Result(query);
@@ -107,7 +107,7 @@ public class GroupingRequestTestCase {
}
@Test
- public void requireThatNonGroupResultIsNull() {
+ void requireThatNonGroupResultIsNull() {
Query query = new Query();
GroupingRequest req = GroupingRequest.newInstance(query);
Result res = new Result(query);
@@ -119,7 +119,7 @@ public class GroupingRequestTestCase {
}
@Test
- public void requireThatGetRequestsReturnsAllRequests() {
+ void requireThatGetRequestsReturnsAllRequests() {
Query query = new Query();
assertEquals(Collections.emptyList(), query.getSelect().getGrouping());
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/GroupingValidatorTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/GroupingValidatorTestCase.java
index 4f473b29918..4b5fb53b06a 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/GroupingValidatorTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/GroupingValidatorTestCase.java
@@ -7,13 +7,13 @@ import com.yahoo.search.Query;
import com.yahoo.search.config.ClusterConfig;
import com.yahoo.search.grouping.request.GroupingOperation;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collection;
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 Simon Thoresen Hult
@@ -21,13 +21,14 @@ import static org.junit.Assert.fail;
public class GroupingValidatorTestCase {
@Test
- public void requireThatAvailableAttributesDoNotThrow() {
+ void requireThatAvailableAttributesDoNotThrow() {
validateGrouping(List.of("foo", "bar"),
- "all(group(foo) each(output(max(bar))))");;
+ "all(group(foo) each(output(max(bar))))");
+ ;
}
@Test
- public void requireThatUnavailableAttributesThrow() {
+ void requireThatUnavailableAttributesThrow() {
try {
validateGrouping(List.of("foo"), "all(group(foo) each(output(max(bar))))");
fail("Excpected exception");
@@ -38,20 +39,20 @@ public class GroupingValidatorTestCase {
}
@Test
- public void requireThatEnableFlagPreventsThrow() {
+ void requireThatEnableFlagPreventsThrow() {
Query query = createQuery("all(group(foo) each(output(max(bar))))");
query.properties().set(GroupingValidator.PARAM_ENABLED, "false");
validateGrouping(List.of("foo"), query);
}
@Test
- public void available_primitive_map_attribute_does_not_throw() {
+ void available_primitive_map_attribute_does_not_throw() {
validateGrouping(List.of("map.key", "map.value"),
"all(group(map{\"foo\"}) each(output(count())))");
}
@Test
- public void unavailable_primitive_map_key_attribute_throws() {
+ void unavailable_primitive_map_key_attribute_throws() {
try {
validateGrouping(List.of("null"), "all(group(map{\"foo\"}) each(output(count())))");
fail("Expected exception");
@@ -62,7 +63,7 @@ public class GroupingValidatorTestCase {
}
@Test
- public void unavailable_primitive_map_value_attribute_throws() {
+ void unavailable_primitive_map_value_attribute_throws() {
try {
validateGrouping(List.of("map.key"), "all(group(map{\"foo\"}) each(output(count())))");
fail("Expected exception");
@@ -73,13 +74,13 @@ public class GroupingValidatorTestCase {
}
@Test
- public void available_struct_map_attribute_does_not_throw() {
+ void available_struct_map_attribute_does_not_throw() {
validateGrouping(List.of("map.key", "map.value.name"),
"all(group(map{\"foo\"}.name) each(output(count())))");
}
@Test
- public void unavailable_struct_map_key_attribute_throws() {
+ void unavailable_struct_map_key_attribute_throws() {
try {
validateGrouping(List.of("null"), "all(group(map{\"foo\"}.name) each(output(count())))");
fail("Expected exception");
@@ -90,7 +91,7 @@ public class GroupingValidatorTestCase {
}
@Test
- public void unavailable_struct_map_value_attribute_throws() {
+ void unavailable_struct_map_value_attribute_throws() {
try {
validateGrouping(List.of("map.key"), "all(group(map{\"foo\"}.name) each(output(count())))");
fail("Expected exception");
@@ -101,16 +102,16 @@ public class GroupingValidatorTestCase {
}
@Test
- public void available_key_source_attribute_does_not_throw() {
+ void available_key_source_attribute_does_not_throw() {
validateGrouping(List.of("map.key", "map.value", "key_source"),
"all(group(map{attribute(key_source)}) each(output(count())))");
}
@Test
- public void unavailable_key_source_attribute_throws() {
+ void unavailable_key_source_attribute_throws() {
try {
validateGrouping(List.of("map.key", "map.value"),
- "all(group(map{attribute(key_source)}) each(output(count())))");
+ "all(group(map{attribute(key_source)}) each(output(count())))");
fail("Expected exception");
}
catch (UnavailableAttributeException e) {
@@ -119,29 +120,29 @@ public class GroupingValidatorTestCase {
}
@Test
- public void key_source_attribute_with_mismatching_data_type_throws() {
+ void key_source_attribute_with_mismatching_data_type_throws() {
try {
validateGrouping(setupMismatchingKeySourceAttribute(false),
- "all(group(map{attribute(key_source)}) each(output(count())))");
+ "all(group(map{attribute(key_source)}) each(output(count())))");
fail("Expected exception");
}
catch (IllegalArgumentException e) {
assertEquals("Grouping request references key source attribute 'key_source' with data type 'INT32' " +
- "that is different than data type 'STRING' of key attribute 'map.key'",
- e.getMessage());
+ "that is different than data type 'STRING' of key attribute 'map.key'",
+ e.getMessage());
}
}
@Test
- public void key_source_attribute_with_multi_value_collection_type_throws() {
+ void key_source_attribute_with_multi_value_collection_type_throws() {
try {
validateGrouping(setupMismatchingKeySourceAttribute(true),
- "all(group(map{attribute(key_source)}) each(output(count())))");
+ "all(group(map{attribute(key_source)}) each(output(count())))");
fail("Expected exception");
}
catch (IllegalArgumentException e) {
assertEquals("Grouping request references key source attribute 'key_source' which is not of single value type",
- e.getMessage());
+ e.getMessage());
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/UniqueGroupingSearcherTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/UniqueGroupingSearcherTestCase.java
index cb771ecb678..ffb69267212 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/UniqueGroupingSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/UniqueGroupingSearcherTestCase.java
@@ -15,11 +15,9 @@ import com.yahoo.search.result.Hit;
import com.yahoo.search.result.Relevance;
import com.yahoo.search.searchchain.Execution;
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.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author andreer
@@ -27,21 +25,21 @@ import static org.junit.Assert.fail;
public class UniqueGroupingSearcherTestCase {
@Test
- public void testSkipGroupingBasedDedup() {
+ void testSkipGroupingBasedDedup() {
Result result = search("?query=foo",
- new MockResultProvider(0, false));
+ new MockResultProvider(0, false));
assertEquals(0, result.hits().size());
}
@Test
- public void testSkipGroupingBasedDedupIfMultiLevelSorting() {
+ void testSkipGroupingBasedDedupIfMultiLevelSorting() {
Result result = search("?query=foo&unique=fingerprint&sorting=-pubdate%20-[rank]",
- new MockResultProvider(0, false));
+ new MockResultProvider(0, false));
assertEquals(0, result.hits().size());
}
@Test
- public void testIllegalSortingSpec() {
+ void testIllegalSortingSpec() {
try {
search("?query=foo&unique=fingerprint&sorting=-1",
new MockResultProvider(0, true).addGroupList(new GroupList("fingerprint")));
@@ -49,31 +47,31 @@ public class UniqueGroupingSearcherTestCase {
} catch (IllegalArgumentException e) {
// As expected.
assertTrue(Exceptions.toMessageString(e).contains("Could not set 'ranking.sorting' to '-1': " +
- "Illegal attribute name '1' for sorting. " +
- "Requires '[\\[]*[a-zA-Z_][\\.a-zA-Z0-9_-]*[\\]]*'"));
+ "Illegal attribute name '1' for sorting. " +
+ "Requires '[\\[]*[a-zA-Z_][\\.a-zA-Z0-9_-]*[\\]]*'"));
}
}
@Test
- public void testGroupingBasedDedupNoGroupingHits() {
+ void testGroupingBasedDedupNoGroupingHits() {
Result result = search("?query=foo&unique=fingerprint",
- new MockResultProvider(0, true));
+ new MockResultProvider(0, true));
assertEquals(0, result.hits().size());
}
@Test
- public void testGroupingBasedDedupWithEmptyGroupingHitsList() {
+ void testGroupingBasedDedupWithEmptyGroupingHitsList() {
Result result = search("?query=foo&unique=fingerprint",
- new MockResultProvider(0, true).addGroupList(new GroupList("fingerprint")));
+ new MockResultProvider(0, true).addGroupList(new GroupList("fingerprint")));
assertEquals(0, result.hits().size());
assertEquals(0, result.getTotalHitCount());
}
@Test
- public void testGroupingBasedDedupWithNullGroupingResult() {
+ void testGroupingBasedDedupWithNullGroupingResult() {
try {
search("?query=foo&unique=fingerprint",
- new MockResultProvider(0, false));
+ new MockResultProvider(0, false));
fail();
} catch (IllegalStateException e) {
assertEquals("Failed to produce deduped result set.", e.getMessage());
@@ -81,7 +79,7 @@ public class UniqueGroupingSearcherTestCase {
}
@Test
- public void testGroupingBasedDedupWithGroupingHits() {
+ void testGroupingBasedDedupWithGroupingHits() {
GroupList fingerprint = new GroupList("fingerprint");
fingerprint.add(makeHitGroup("1"));
fingerprint.add(makeHitGroup("2"));
@@ -105,7 +103,7 @@ public class UniqueGroupingSearcherTestCase {
}
@Test
- public void testGroupingBasedDedupWithGroupingHitsAndSorting() {
+ void testGroupingBasedDedupWithGroupingHitsAndSorting() {
GroupList fingerprint = new GroupList("fingerprint");
fingerprint.add(makeSortingHitGroup("1"));
fingerprint.add(makeSortingHitGroup("2"));
@@ -130,29 +128,29 @@ public class UniqueGroupingSearcherTestCase {
}
@Test
- public void testBuildGroupingExpression() {
+ void testBuildGroupingExpression() {
assertEquals("all(group(title) max(11) output(count() as(uniqueCount)) each(max(1) each(output(summary())) " +
- "as(uniqueHits)))",
- UniqueGroupingSearcher
- .buildGroupingExpression("title", 11, null, null)
- .toString());
+ "as(uniqueHits)))",
+ UniqueGroupingSearcher
+ .buildGroupingExpression("title", 11, null, null)
+ .toString());
assertEquals("all(group(fingerprint) max(5) output(count() as(uniqueCount)) each(max(1) " +
- "each(output(summary(attributeprefetch))) as(uniqueHits)))",
- UniqueGroupingSearcher
- .buildGroupingExpression("fingerprint", 5, "attributeprefetch", null)
- .toString());
+ "each(output(summary(attributeprefetch))) as(uniqueHits)))",
+ UniqueGroupingSearcher
+ .buildGroupingExpression("fingerprint", 5, "attributeprefetch", null)
+ .toString());
assertEquals("all(group(fingerprint) max(5) order(neg(max(pubdate))) output(count() as(uniqueCount)) each(" +
- "all(group(neg(pubdate)) max(1) order(neg(max(pubdate))) each(each(output(summary())) " +
- "as(uniqueHits)) as(uniqueGroups))))",
- UniqueGroupingSearcher
- .buildGroupingExpression("fingerprint", 5, null, new Sorting("-pubdate"))
- .toString());
+ "all(group(neg(pubdate)) max(1) order(neg(max(pubdate))) each(each(output(summary())) " +
+ "as(uniqueHits)) as(uniqueGroups))))",
+ UniqueGroupingSearcher
+ .buildGroupingExpression("fingerprint", 5, null, new Sorting("-pubdate"))
+ .toString());
assertEquals("all(group(fingerprint) max(5) order(min(pubdate)) output(count() as(uniqueCount)) each(" +
- "all(group(pubdate) max(1) order(min(pubdate)) each(each(output(summary(attributeprefetch))) " +
- "as(uniqueHits)) as(uniqueGroups))))",
- UniqueGroupingSearcher
- .buildGroupingExpression("fingerprint", 5, "attributeprefetch", new Sorting("+pubdate"))
- .toString());
+ "all(group(pubdate) max(1) order(min(pubdate)) each(each(output(summary(attributeprefetch))) " +
+ "as(uniqueHits)) as(uniqueGroups))))",
+ UniqueGroupingSearcher
+ .buildGroupingExpression("fingerprint", 5, "attributeprefetch", new Sorting("+pubdate"))
+ .toString());
}
private static Group makeHitGroup(String name) {
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/request/BucketResolverTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/request/BucketResolverTestCase.java
index 50058f3777f..d7a888792d9 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/request/BucketResolverTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/request/BucketResolverTestCase.java
@@ -1,13 +1,13 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.grouping.request;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.text.ChoiceFormat;
import java.util.Arrays;
import java.util.List;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -22,7 +22,7 @@ public class BucketResolverTestCase {
// --------------------------------------------------------------------------------
@Test
- public void testResolve() {
+ void testResolve() {
BucketResolver resolver = new BucketResolver();
resolver.push(new StringValue("a"), true);
try {
@@ -71,32 +71,32 @@ public class BucketResolverTestCase {
}
@Test
- public void testBucketType() {
- checkPushFail(Arrays.asList((ConstantValue)new StringValue("a"), new LongValue(1L)),
- "Bucket type mismatch, expected 'StringValue' got 'LongValue'.");
- checkPushFail(Arrays.asList((ConstantValue)new StringValue("a"), new DoubleValue(1.0)),
- "Bucket type mismatch, expected 'StringValue' got 'DoubleValue'.");
- checkPushFail(Arrays.asList((ConstantValue)new LongValue(1L), new StringValue("a")),
- "Bucket type mismatch, expected 'LongValue' got 'StringValue'.");
- checkPushFail(Arrays.asList((ConstantValue)new LongValue(1L), new DoubleValue(1.0)),
- "Bucket type mismatch, expected 'LongValue' got 'DoubleValue'.");
- checkPushFail(Arrays.asList((ConstantValue)new DoubleValue(1.0), new StringValue("a")),
- "Bucket type mismatch, expected 'DoubleValue' got 'StringValue'.");
- checkPushFail(Arrays.asList((ConstantValue)new DoubleValue(1.0), new LongValue(1L)),
- "Bucket type mismatch, expected 'DoubleValue' got 'LongValue'.");
- checkPushFail(Arrays.asList((ConstantValue)new InfiniteValue(new Infinite(true)), new InfiniteValue(new Infinite(false))),
- "Bucket type mismatch, cannot both be infinity.");
+ void testBucketType() {
+ checkPushFail(Arrays.asList((ConstantValue) new StringValue("a"), new LongValue(1L)),
+ "Bucket type mismatch, expected 'StringValue' got 'LongValue'.");
+ checkPushFail(Arrays.asList((ConstantValue) new StringValue("a"), new DoubleValue(1.0)),
+ "Bucket type mismatch, expected 'StringValue' got 'DoubleValue'.");
+ checkPushFail(Arrays.asList((ConstantValue) new LongValue(1L), new StringValue("a")),
+ "Bucket type mismatch, expected 'LongValue' got 'StringValue'.");
+ checkPushFail(Arrays.asList((ConstantValue) new LongValue(1L), new DoubleValue(1.0)),
+ "Bucket type mismatch, expected 'LongValue' got 'DoubleValue'.");
+ checkPushFail(Arrays.asList((ConstantValue) new DoubleValue(1.0), new StringValue("a")),
+ "Bucket type mismatch, expected 'DoubleValue' got 'StringValue'.");
+ checkPushFail(Arrays.asList((ConstantValue) new DoubleValue(1.0), new LongValue(1L)),
+ "Bucket type mismatch, expected 'DoubleValue' got 'LongValue'.");
+ checkPushFail(Arrays.asList((ConstantValue) new InfiniteValue(new Infinite(true)), new InfiniteValue(new Infinite(false))),
+ "Bucket type mismatch, cannot both be infinity.");
}
@Test
- public void testBucketOrder() {
- checkPushFail(Arrays.asList((ConstantValue)new LongValue(2L), new LongValue(1L)),
- "Bucket to-value can not be less than from-value.");
- checkPushFail(Arrays.asList((ConstantValue)new DoubleValue(2.0), new DoubleValue(1.0)),
- "Bucket to-value can not be less than from-value.");
- checkPushFail(Arrays.asList((ConstantValue)new StringValue("b"), new StringValue("a")),
- "Bucket to-value can not be less than from-value.");
+ void testBucketOrder() {
+ checkPushFail(Arrays.asList((ConstantValue) new LongValue(2L), new LongValue(1L)),
+ "Bucket to-value can not be less than from-value.");
+ checkPushFail(Arrays.asList((ConstantValue) new DoubleValue(2.0), new DoubleValue(1.0)),
+ "Bucket to-value can not be less than from-value.");
+ checkPushFail(Arrays.asList((ConstantValue) new StringValue("b"), new StringValue("a")),
+ "Bucket to-value can not be less than from-value.");
}
public void assertBucketRange(BucketValue expected, ConstantValue from, boolean inclusiveFrom, ConstantValue to, boolean inclusiveTo) {
@@ -123,7 +123,7 @@ public class BucketResolverTestCase {
}
@Test
- public void requireThatBucketRangesWork() {
+ void requireThatBucketRangesWork() {
BucketValue expected = new LongBucket(2, 5);
assertBucketRange(expected, new LongValue(1), false, new LongValue(4), true);
assertBucketRange(expected, new LongValue(1), false, new LongValue(5), false);
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/request/ExpressionVisitorTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/request/ExpressionVisitorTestCase.java
index 24ce3cfea32..1f800b37ff0 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/request/ExpressionVisitorTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/request/ExpressionVisitorTestCase.java
@@ -1,13 +1,13 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.grouping.request;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.LinkedList;
import java.util.List;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Simon Thoresen Hult
@@ -15,7 +15,7 @@ import static org.junit.Assert.assertTrue;
public class ExpressionVisitorTestCase {
@Test
- public void requireThatExpressionsAreVisited() {
+ void requireThatExpressionsAreVisited() {
GroupingOperation op = new AllOperation();
final List<GroupingExpression> lst = new LinkedList<>();
@@ -38,7 +38,7 @@ public class ExpressionVisitorTestCase {
}
@Test
- public void requireThatChildOperationsAreVisited() {
+ void requireThatChildOperationsAreVisited() {
GroupingOperation root, parentA, childA1, childA2, parentB, childB1;
root = new AllOperation()
.addChild(parentA = new AllOperation()
@@ -69,7 +69,7 @@ public class ExpressionVisitorTestCase {
}
@Test
- public void requireThatExpressionsArgumentsAreVisited() {
+ void requireThatExpressionsArgumentsAreVisited() {
final List<GroupingExpression> lst = new LinkedList<>();
GroupingExpression arg1 = new AttributeValue("arg1");
lst.add(arg1);
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/request/GroupingOperationTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/request/GroupingOperationTestCase.java
index 0e89f348449..d1ab7117677 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/request/GroupingOperationTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/request/GroupingOperationTestCase.java
@@ -3,11 +3,11 @@ package com.yahoo.search.grouping.request;
import com.yahoo.search.grouping.request.parser.ParseException;
import com.yahoo.search.grouping.request.parser.TokenMgrException;
-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.*;
/**
* @author Simon Thoresen Hult
@@ -15,7 +15,7 @@ import static org.junit.Assert.*;
public class GroupingOperationTestCase {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
GroupingOperation op = new AllOperation();
GroupingExpression exp = new AttributeValue("alias");
op.putAlias("alias", exp);
@@ -88,7 +88,7 @@ public class GroupingOperationTestCase {
}
@Test
- public void requireThatFromStringAsListParsesAllOperations() {
+ void requireThatFromStringAsListParsesAllOperations() {
List<GroupingOperation> lst = GroupingOperation.fromStringAsList("");
assertTrue(lst.isEmpty());
@@ -107,7 +107,7 @@ public class GroupingOperationTestCase {
}
@Test
- public void requireThatFromStringAcceptsOnlyOneOperation() {
+ void requireThatFromStringAcceptsOnlyOneOperation() {
try {
GroupingOperation.fromString("");
fail();
@@ -125,7 +125,7 @@ public class GroupingOperationTestCase {
}
@Test
- public void requireThatParseExceptionsAreRethrown() {
+ void requireThatParseExceptionsAreRethrown() {
try {
GroupingOperation.fromString("all(foo)");
fail();
@@ -136,7 +136,7 @@ public class GroupingOperationTestCase {
}
@Test
- public void requireThatTokenErrorsAreRethrown() {
+ void requireThatTokenErrorsAreRethrown() {
try {
GroupingOperation.fromString("all(\\foo)");
fail();
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/request/MathFunctionsTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/request/MathFunctionsTestCase.java
index d22c2dee7b6..823993b6bc6 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/request/MathFunctionsTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/request/MathFunctionsTestCase.java
@@ -1,19 +1,17 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.grouping.request;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-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 Einar M R Rosenvinge
*/
public class MathFunctionsTestCase {
-
+
@Test
- public void testMathFunctions() {
+ void testMathFunctions() {
//if this fails, update the count AND add a test in each of the two blocks below
assertEquals(21, MathFunctions.Function.values().length);
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/request/MathResolverTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/request/MathResolverTestCase.java
index 734e2c6a0cb..39fdc7fc3a6 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/request/MathResolverTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/request/MathResolverTestCase.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.search.grouping.request;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* @author Simon Thoresen Hult
@@ -18,40 +18,40 @@ public class MathResolverTestCase {
// --------------------------------------------------------------------------------
@Test
- public void testOperators() {
+ void testOperators() {
MathResolver resolver = new MathResolver();
resolver.push(MathResolver.Type.ADD, new LongValue(1));
resolver.push(MathResolver.Type.ADD, new LongValue(2));
assertEquals("add(1, 2)",
- resolver.resolve().toString());
+ resolver.resolve().toString());
resolver = new MathResolver();
resolver.push(MathResolver.Type.ADD, new LongValue(1));
resolver.push(MathResolver.Type.SUB, new LongValue(2));
assertEquals("sub(1, 2)",
- resolver.resolve().toString());
+ resolver.resolve().toString());
resolver = new MathResolver();
resolver.push(MathResolver.Type.ADD, new LongValue(1));
resolver.push(MathResolver.Type.DIV, new LongValue(2));
assertEquals("div(1, 2)",
- resolver.resolve().toString());
+ resolver.resolve().toString());
resolver = new MathResolver();
resolver.push(MathResolver.Type.ADD, new LongValue(1));
resolver.push(MathResolver.Type.MOD, new LongValue(2));
assertEquals("mod(1, 2)",
- resolver.resolve().toString());
+ resolver.resolve().toString());
resolver = new MathResolver();
resolver.push(MathResolver.Type.ADD, new LongValue(1));
resolver.push(MathResolver.Type.MUL, new LongValue(2));
assertEquals("mul(1, 2)",
- resolver.resolve().toString());
+ resolver.resolve().toString());
}
@Test
- public void testOperatorPrecedence() {
+ void testOperatorPrecedence() {
assertResolve("add(add(1, 2), 3)", MathResolver.Type.ADD, MathResolver.Type.ADD);
assertResolve("add(1, sub(2, 3))", MathResolver.Type.ADD, MathResolver.Type.SUB);
assertResolve("add(1, div(2, 3))", MathResolver.Type.ADD, MathResolver.Type.DIV);
@@ -83,21 +83,21 @@ public class MathResolverTestCase {
assertResolve("mul(mul(1, 2), 3)", MathResolver.Type.MUL, MathResolver.Type.MUL);
assertResolve("add(1, sub(div(2, mod(3, mul(4, 5))), 6))",
- MathResolver.Type.ADD, MathResolver.Type.DIV, MathResolver.Type.MOD,
- MathResolver.Type.MUL, MathResolver.Type.SUB);
+ MathResolver.Type.ADD, MathResolver.Type.DIV, MathResolver.Type.MOD,
+ MathResolver.Type.MUL, MathResolver.Type.SUB);
assertResolve("add(sub(1, div(mod(mul(2, 3), 4), 5)), 6)",
- MathResolver.Type.SUB, MathResolver.Type.MUL, MathResolver.Type.MOD,
- MathResolver.Type.DIV, MathResolver.Type.ADD);
+ MathResolver.Type.SUB, MathResolver.Type.MUL, MathResolver.Type.MOD,
+ MathResolver.Type.DIV, MathResolver.Type.ADD);
assertResolve("add(1, sub(2, div(3, mod(4, mul(5, 6)))))",
- MathResolver.Type.ADD, MathResolver.Type.SUB, MathResolver.Type.DIV,
- MathResolver.Type.MOD, MathResolver.Type.MUL);
+ MathResolver.Type.ADD, MathResolver.Type.SUB, MathResolver.Type.DIV,
+ MathResolver.Type.MOD, MathResolver.Type.MUL);
assertResolve("add(sub(div(mod(mul(1, 2), 3), 4), 5), 6)",
- MathResolver.Type.MUL, MathResolver.Type.MOD, MathResolver.Type.DIV,
- MathResolver.Type.SUB, MathResolver.Type.ADD);
+ MathResolver.Type.MUL, MathResolver.Type.MOD, MathResolver.Type.DIV,
+ MathResolver.Type.SUB, MathResolver.Type.ADD);
}
@Test
- public void testOperatorSupport() {
+ void testOperatorSupport() {
MathResolver resolver = new MathResolver();
for (MathResolver.Type type : MathResolver.Type.values()) {
if (type == MathResolver.Type.ADD) {
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/request/RawBufferTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/request/RawBufferTestCase.java
index dfa297b4fa6..03223f786e8 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/request/RawBufferTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/request/RawBufferTestCase.java
@@ -1,13 +1,13 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.grouping.request;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Ulf Lilleengen
@@ -21,18 +21,18 @@ public class RawBufferTestCase {
// --------------------------------------------------------------------------------
@Test
- public void requireThatCompareWorks() {
+ void requireThatCompareWorks() {
RawBuffer buffer = new RawBuffer();
- buffer.put((byte)'a');
- buffer.put((byte)'b');
+ buffer.put((byte) 'a');
+ buffer.put((byte) 'b');
RawBuffer buffer2 = new RawBuffer();
- buffer2.put((byte)'k');
- buffer2.put((byte)'a');
+ buffer2.put((byte) 'k');
+ buffer2.put((byte) 'a');
ArrayList<Byte> backing = new ArrayList<>();
- backing.add((byte)'a');
- backing.add((byte)'b');
+ backing.add((byte) 'a');
+ backing.add((byte) 'b');
RawBuffer buffer3 = new RawBuffer(backing);
assertEquals(buffer.compareTo(buffer2), -1);
@@ -41,9 +41,9 @@ public class RawBufferTestCase {
}
@Test
- public void requireThatToStringWorks() {
+ void requireThatToStringWorks() {
assertToString(Arrays.asList("a".getBytes()[0], "b".getBytes()[0]), "{97,98}");
- assertToString(Arrays.asList((byte)2, (byte)6), "{2,6}");
+ assertToString(Arrays.asList((byte) 2, (byte) 6), "{2,6}");
}
public void assertToString(List<Byte> data, String expected) {
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/request/RequestTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/request/RequestTestCase.java
index c02e46fae98..e2b4dc4f34b 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/request/RequestTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/request/RequestTestCase.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.search.grouping.request;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -13,7 +13,7 @@ import static org.junit.Assert.*;
public class RequestTestCase {
@Test
- public void requireThatApiWorks() {
+ void requireThatApiWorks() {
GroupingOperation op = new AllOperation()
.setGroupBy(new AttributeValue("foo"))
.addOrderBy(new CountAggregator())
@@ -22,19 +22,19 @@ public class RequestTestCase {
.addOutput(new CountAggregator())
.addOutput(new MinAggregator(new AttributeValue("bar")))
.addChild(new EachOperation()
- .addOutput(new AddFunction(
- new LongValue(69),
- new AttributeValue("baz")))
- .addOutput(new SummaryValue("cox"))));
+ .addOutput(new AddFunction(
+ new LongValue(69),
+ new AttributeValue("baz")))
+ .addOutput(new SummaryValue("cox"))));
assertEquals("all(group(foo) order(count()) all() each() " +
- "each(output(count(), min(bar)) each(output(add(69, baz), summary(cox)))))",
- op.toString());
+ "each(output(count(), min(bar)) each(output(add(69, baz), summary(cox)))))",
+ op.toString());
op.resolveLevel(1);
GroupingExpression exp = op.getGroupBy();
assertNotNull(exp);
assertTrue(exp instanceof AttributeValue);
- assertEquals("foo", ((AttributeValue)exp).getAttributeName());
+ assertEquals("foo", ((AttributeValue) exp).getAttributeName());
assertEquals(1, op.getNumOrderBy());
assertNotNull(exp = op.getOrderBy(0));
assertTrue(exp instanceof CountAggregator);
@@ -49,9 +49,9 @@ public class RequestTestCase {
assertTrue(exp instanceof CountAggregator);
assertNotNull(exp = op.getOutput(1));
assertTrue(exp instanceof MinAggregator);
- assertNotNull(exp = ((MinAggregator)exp).getExpression());
+ assertNotNull(exp = ((MinAggregator) exp).getExpression());
assertTrue(exp instanceof AttributeValue);
- assertEquals("bar", ((AttributeValue)exp).getAttributeName());
+ assertEquals("bar", ((AttributeValue) exp).getAttributeName());
assertEquals(1, op.getNumChildren());
assertNotNull(op = op.getChild(0));
@@ -59,24 +59,24 @@ public class RequestTestCase {
assertEquals(2, op.getNumOutputs());
assertNotNull(exp = op.getOutput(0));
assertTrue(exp instanceof AddFunction);
- assertEquals(2, ((AddFunction)exp).getNumArgs());
- GroupingExpression arg = ((AddFunction)exp).getArg(0);
+ assertEquals(2, ((AddFunction) exp).getNumArgs());
+ GroupingExpression arg = ((AddFunction) exp).getArg(0);
assertNotNull(arg);
assertTrue(arg instanceof LongValue);
- assertEquals(69L, ((LongValue)arg).getValue().longValue());
- assertNotNull(arg = ((AddFunction)exp).getArg(1));
+ assertEquals(69L, ((LongValue) arg).getValue().longValue());
+ assertNotNull(arg = ((AddFunction) exp).getArg(1));
assertTrue(arg instanceof AttributeValue);
- assertEquals("baz", ((AttributeValue)arg).getAttributeName());
+ assertEquals("baz", ((AttributeValue) arg).getAttributeName());
assertNotNull(exp = op.getOutput(1));
assertTrue(exp instanceof SummaryValue);
- assertEquals("cox", ((SummaryValue)exp).getSummaryName());
+ assertEquals("cox", ((SummaryValue) exp).getSummaryName());
}
@Test
- public void requireThatPredefinedApiWorks() {
+ void requireThatPredefinedApiWorks() {
PredefinedFunction fnc = new LongPredefined(new AttributeValue("foo"),
- new LongBucket(1, 2),
- new LongBucket(3, 4));
+ new LongBucket(1, 2),
+ new LongBucket(3, 4));
assertEquals(2, fnc.getNumBuckets());
BucketValue bucket = fnc.getBucket(0);
assertNotNull(bucket);
@@ -91,7 +91,7 @@ public class RequestTestCase {
}
@Test
- public void requireThatBucketIntegrityIsChecked() {
+ void requireThatBucketIntegrityIsChecked() {
try {
new LongBucket(2, 1);
} catch (IllegalArgumentException e) {
@@ -99,37 +99,37 @@ public class RequestTestCase {
}
try {
new LongPredefined(new AttributeValue("foo"),
- new LongBucket(3, 4),
- new LongBucket(1, 2));
+ new LongBucket(3, 4),
+ new LongBucket(1, 2));
} catch (IllegalArgumentException e) {
assertEquals("Buckets must be monotonically increasing, got bucket[3, 4> before bucket[1, 2>.",
- e.getMessage());
+ e.getMessage());
}
}
@Test
- public void requireThatAliasWorks() {
+ void requireThatAliasWorks() {
GroupingOperation all = new AllOperation();
all.putAlias("myalias", new AttributeValue("foo"));
GroupingExpression exp = all.getAlias("myalias");
assertNotNull(exp);
assertTrue(exp instanceof AttributeValue);
- assertEquals("foo", ((AttributeValue)exp).getAttributeName());
+ assertEquals("foo", ((AttributeValue) exp).getAttributeName());
GroupingOperation each = new EachOperation();
all.addChild(each);
assertNotNull(exp = each.getAlias("myalias"));
assertTrue(exp instanceof AttributeValue);
- assertEquals("foo", ((AttributeValue)exp).getAttributeName());
+ assertEquals("foo", ((AttributeValue) exp).getAttributeName());
each.putAlias("myalias", new AttributeValue("bar"));
assertNotNull(exp = each.getAlias("myalias"));
assertTrue(exp instanceof AttributeValue);
- assertEquals("bar", ((AttributeValue)exp).getAttributeName());
+ assertEquals("bar", ((AttributeValue) exp).getAttributeName());
}
@Test
- public void testOrderBy() {
+ void testOrderBy() {
GroupingOperation all = new AllOperation();
all.addOrderBy(new AttributeValue("foo"));
try {
@@ -143,7 +143,7 @@ public class RequestTestCase {
}
@Test
- public void testMax() {
+ void testMax() {
GroupingOperation all = new AllOperation();
all.setMax(69);
try {
@@ -156,10 +156,10 @@ public class RequestTestCase {
}
@Test
- public void testAccuracy() {
+ void testAccuracy() {
GroupingOperation all = new AllOperation();
all.setAccuracy(0.53);
- assertEquals((long)(100.0 * all.getAccuracy()), 53);
+ assertEquals((long) (100.0 * all.getAccuracy()), 53);
try {
all.setAccuracy(1.2);
fail();
@@ -175,7 +175,7 @@ public class RequestTestCase {
}
@Test
- public void testLevelChange() {
+ void testLevelChange() {
GroupingOperation all = new AllOperation();
all.resolveLevel(0);
assertEquals(0, all.getLevel());
@@ -198,7 +198,7 @@ public class RequestTestCase {
}
@Test
- public void testLevelInheritance() {
+ void testLevelInheritance() {
GroupingOperation grandParent, parent, child, grandChild;
grandParent = new AllOperation()
.addChild(parent = new EachOperation()
@@ -213,7 +213,7 @@ public class RequestTestCase {
}
@Test
- public void testLevelPropagation() {
+ void testLevelPropagation() {
GroupingOperation all = new AllOperation()
.setGroupBy(new AttributeValue("foo"))
.addOrderBy(new MaxAggregator(new AttributeValue("bar")))
@@ -224,6 +224,6 @@ public class RequestTestCase {
assertEquals(0, all.getGroupBy().getLevel());
assertEquals(1, all.getOrderBy(0).getLevel());
assertEquals(1, all.getChild(0).getOutput(0).getLevel());
- assertEquals(0, ((AggregatorNode)all.getChild(0).getOutput(0)).getExpression().getLevel());
+ assertEquals(0, ((AggregatorNode) all.getChild(0).getOutput(0)).getExpression().getLevel());
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/request/parser/GroupingParserBenchmarkTest.java b/container-search/src/test/java/com/yahoo/search/grouping/request/parser/GroupingParserBenchmarkTest.java
index 56444a99ed3..c95451e991c 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/request/parser/GroupingParserBenchmarkTest.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/request/parser/GroupingParserBenchmarkTest.java
@@ -2,7 +2,7 @@
package com.yahoo.search.grouping.request.parser;
import com.yahoo.search.grouping.request.GroupingOperation;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.LinkedHashMap;
@@ -26,7 +26,7 @@ public class GroupingParserBenchmarkTest {
}
@Test
- public void requireThatGroupingParserIsFast() {
+ void requireThatGroupingParserIsFast() {
List<String> inputs = getInputs();
long ignore = 0;
long now = 0;
@@ -39,9 +39,9 @@ public class GroupingParserBenchmarkTest {
}
}
long micros = TimeUnit.NANOSECONDS.toMicros(System.nanoTime() - now);
- System.out.format("%d \u03bcs (avg %.2f)\n", micros, (double)micros / (NUM_RUNS * inputs.size()));
+ System.out.format("%d \u03bcs (avg %.2f)\n", micros, (double) micros / (NUM_RUNS * inputs.size()));
for (Map.Entry<String, Long> entry : PREV_RESULTS.entrySet()) {
- System.out.format("%-20s : %4.2f\n", entry.getKey(), (double)micros / entry.getValue());
+ System.out.format("%-20s : %4.2f\n", entry.getKey(), (double) micros / entry.getValue());
}
System.out.println("\nignore " + ignore);
}
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/request/parser/GroupingParserTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/request/parser/GroupingParserTestCase.java
index 0dfd4685c0f..dd55dd46e5e 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/request/parser/GroupingParserTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/request/parser/GroupingParserTestCase.java
@@ -9,17 +9,13 @@ import com.yahoo.search.query.parser.Parsable;
import com.yahoo.search.query.parser.ParserEnvironment;
import com.yahoo.search.yql.VespaGroupingStep;
import com.yahoo.search.yql.YqlParser;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
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.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -27,7 +23,7 @@ import static org.junit.Assert.fail;
public class GroupingParserTestCase {
@Test
- public void requireThatMathAllowsWhitespace() {
+ void requireThatMathAllowsWhitespace() {
for (String op : Arrays.asList("+", " +", " + ", "+ ",
"-", " -", " - ", "- ",
"*", " *", " * ", "* ",
@@ -41,7 +37,7 @@ public class GroupingParserTestCase {
}
@Test
- public void testRequestList() {
+ void testRequestList() {
List<GroupingOperation> lst = GroupingOperation.fromStringAsList("all();each();all() where(true);each()");
assertNotNull(lst);
assertEquals(4, lst.size());
@@ -52,113 +48,113 @@ public class GroupingParserTestCase {
}
@Test
- public void testAttributeFunctions() {
+ void testAttributeFunctions() {
assertParse("all(group(foo) each(output(sum(attribute(bar)))))",
- "all(group(foo) each(output(sum(attribute(bar)))))");
+ "all(group(foo) each(output(sum(attribute(bar)))))");
assertParse("all(group(foo) each(output(sum(interpolatedlookup(bar, 0.25)))))",
- "all(group(foo) each(output(sum(interpolatedlookup(bar, 0.25)))))");
+ "all(group(foo) each(output(sum(interpolatedlookup(bar, 0.25)))))");
assertParse("all(group(foo) each(output(sum(array.at(bar, 42.0)))))",
- "all(group(foo) each(output(sum(array.at(bar, 42.0)))))");
+ "all(group(foo) each(output(sum(array.at(bar, 42.0)))))");
}
@Test
- public void requireThatTokenImagesAreNotReservedWords() {
+ void requireThatTokenImagesAreNotReservedWords() {
List<String> images = Arrays.asList("acos",
- "acosh",
- "accuracy",
- "add",
- "alias",
- "all",
- "and",
- "array",
- "as",
- "at",
- "asin",
- "asinh",
- "atan",
- "atanh",
- "attribute",
- "avg",
- "bucket",
- "cat",
- "cbrt",
- "cos",
- "cosh",
- "count",
- "debugwait",
- "div",
- "docidnsspecific",
- "each",
- "exp",
- "fixedwidth",
- "floor",
- "group",
- "hint",
- "hypot",
- "log",
- "log1p",
- "log10",
- "math",
- "max",
- "md5",
- "min",
- "mod",
- "mul",
- "neg",
- "normalizesubject",
- "now",
- "or",
- "order",
- "output",
- "pow",
- "precision",
- "predefined",
- "relevance",
- "reverse",
- "sin",
- "sinh",
- "size",
- "sort",
- "stddev",
- "interpolatedlookup",
- "sqrt",
- "strcat",
- "strlen",
- "sub",
- "sum",
- "summary",
- "tan",
- "tanh",
- "time",
- "date",
- "dayofmonth",
- "dayofweek",
- "dayofyear",
- "hourofday",
- "minuteofhour",
- "monthofyear",
- "secondofminute",
- "year",
- "todouble",
- "tolong",
- "toraw",
- "tostring",
- "true",
- "false",
- "uca",
- "where",
- "x",
- "xor",
- "xorbit",
- "y",
- "zcurve");
+ "acosh",
+ "accuracy",
+ "add",
+ "alias",
+ "all",
+ "and",
+ "array",
+ "as",
+ "at",
+ "asin",
+ "asinh",
+ "atan",
+ "atanh",
+ "attribute",
+ "avg",
+ "bucket",
+ "cat",
+ "cbrt",
+ "cos",
+ "cosh",
+ "count",
+ "debugwait",
+ "div",
+ "docidnsspecific",
+ "each",
+ "exp",
+ "fixedwidth",
+ "floor",
+ "group",
+ "hint",
+ "hypot",
+ "log",
+ "log1p",
+ "log10",
+ "math",
+ "max",
+ "md5",
+ "min",
+ "mod",
+ "mul",
+ "neg",
+ "normalizesubject",
+ "now",
+ "or",
+ "order",
+ "output",
+ "pow",
+ "precision",
+ "predefined",
+ "relevance",
+ "reverse",
+ "sin",
+ "sinh",
+ "size",
+ "sort",
+ "stddev",
+ "interpolatedlookup",
+ "sqrt",
+ "strcat",
+ "strlen",
+ "sub",
+ "sum",
+ "summary",
+ "tan",
+ "tanh",
+ "time",
+ "date",
+ "dayofmonth",
+ "dayofweek",
+ "dayofyear",
+ "hourofday",
+ "minuteofhour",
+ "monthofyear",
+ "secondofminute",
+ "year",
+ "todouble",
+ "tolong",
+ "toraw",
+ "tostring",
+ "true",
+ "false",
+ "uca",
+ "where",
+ "x",
+ "xor",
+ "xorbit",
+ "y",
+ "zcurve");
for (String image : images) {
assertParse("all(group(" + image + "))", "all(group(" + image + "))");
}
}
@Test
- public void testTokenizedWhitespace() {
+ void testTokenizedWhitespace() {
String expected = "all(group(foo) each(output(max(bar))))";
assertParse(" all(group(foo)each(output(max(bar))))", expected);
@@ -182,7 +178,7 @@ public class GroupingParserTestCase {
}
@Test
- public void testOperationTypes() {
+ void testOperationTypes() {
assertParse("all()");
assertParse("each()");
assertParse("all(each())");
@@ -193,21 +189,21 @@ public class GroupingParserTestCase {
assertParse("all(each() each())");
assertParse("each(all() all())");
assertIllegalArgument("each(all() each())",
- "Operation 'each()' can not operate on single hit.");
+ "Operation 'each()' can not operate on single hit.");
assertIllegalArgument("each(group(foo) all() each())",
- "Operation 'each(group(foo) all() each())' can not group single hit.");
+ "Operation 'each(group(foo) all() each())' can not group single hit.");
assertIllegalArgument("each(each() all())",
- "Operation 'each()' can not operate on single hit.");
+ "Operation 'each()' can not operate on single hit.");
assertIllegalArgument("each(group(foo) each() all())",
- "Operation 'each(group(foo) each() all())' can not group single hit.");
+ "Operation 'each(group(foo) each() all())' can not group single hit.");
assertIllegalArgument("each(each() each())",
- "Operation 'each()' can not operate on single hit.");
+ "Operation 'each()' can not operate on single hit.");
assertIllegalArgument("each(group(foo) each() each())",
- "Operation 'each(group(foo) each() each())' can not group single hit.");
+ "Operation 'each(group(foo) each() each())' can not group single hit.");
}
@Test
- public void testOperationParts() {
+ void testOperationParts() {
assertParse("all(group(foo))");
assertParse("all(hint(foo))");
assertParse("all(hint(foo) hint(bar))");
@@ -232,7 +228,7 @@ public class GroupingParserTestCase {
}
@Test
- public void testComplexExpressionTypes() {
+ void testComplexExpressionTypes() {
// fixedwidth
assertParse("all(group(fixedwidth(foo, 1)))");
assertParse("all(group(fixedwidth(foo, 1.2)))");
@@ -315,43 +311,43 @@ public class GroupingParserTestCase {
assertParse("all(group(predefined(foo, bucket({'b', 'a'}, {'k', 'a'}), bucket({'k', 'a'}, {'u', 'b'}))))");
assertIllegalArgument("all(group(predefined(foo, bucket(1, 2.0))))",
- "Bucket type mismatch, expected 'LongValue' got 'DoubleValue'.");
+ "Bucket type mismatch, expected 'LongValue' got 'DoubleValue'.");
assertIllegalArgument("all(group(predefined(foo, bucket(1, '2'))))",
- "Bucket type mismatch, expected 'LongValue' got 'StringValue'.");
+ "Bucket type mismatch, expected 'LongValue' got 'StringValue'.");
assertIllegalArgument("all(group(predefined(foo, bucket(1, 2), bucket(3.0, 4.0))))",
- "Bucket type mismatch, expected 'LongValue' got 'DoubleValue'.");
+ "Bucket type mismatch, expected 'LongValue' got 'DoubleValue'.");
assertIllegalArgument("all(group(predefined(foo, bucket(1, 2), bucket('3', '4'))))",
- "Bucket type mismatch, expected 'LongValue' got 'StringValue'.");
+ "Bucket type mismatch, expected 'LongValue' got 'StringValue'.");
assertIllegalArgument("all(group(predefined(foo, bucket(1, 2), bucket(\"3\", \"4\"))))",
- "Bucket type mismatch, expected 'LongValue' got 'StringValue'.");
+ "Bucket type mismatch, expected 'LongValue' got 'StringValue'.");
assertIllegalArgument("all(group(predefined(foo, bucket(1, 2), bucket(three, four))))",
- "Bucket type mismatch, expected 'LongValue' got 'StringValue'.");
+ "Bucket type mismatch, expected 'LongValue' got 'StringValue'.");
assertIllegalArgument("all(group(predefined(foo, bucket<-inf, inf>)))",
- "Bucket type mismatch, cannot both be infinity");
+ "Bucket type mismatch, cannot both be infinity");
assertIllegalArgument("all(group(predefined(foo, bucket<inf, -inf>)))",
- "Encountered \" \"inf\" \"inf\"\" at line 1, column 34.");
+ "Encountered \" \"inf\" \"inf\"\" at line 1, column 34.");
assertIllegalArgument("all(group(predefined(foo, bucket(2, 1))))",
- "Bucket to-value can not be less than from-value.");
+ "Bucket to-value can not be less than from-value.");
assertIllegalArgument("all(group(predefined(foo, bucket(3, 4), bucket(1, 2))))",
- "Buckets must be monotonically increasing, got bucket[3, 4> before bucket[1, 2>.");
+ "Buckets must be monotonically increasing, got bucket[3, 4> before bucket[1, 2>.");
assertIllegalArgument("all(group(predefined(foo, bucket(b, a))))",
- "Bucket to-value can not be less than from-value.");
+ "Bucket to-value can not be less than from-value.");
assertIllegalArgument("all(group(predefined(foo, bucket(b, -inf))))",
- "Encountered \" \"-inf\" \"-inf\"\" at line 1, column 37.");
+ "Encountered \" \"-inf\" \"-inf\"\" at line 1, column 37.");
assertIllegalArgument("all(group(predefined(foo, bucket(c, d), bucket(a, b))))",
- "Buckets must be monotonically increasing, got bucket[\"c\", \"d\"> before bucket[\"a\", \"b\">.");
+ "Buckets must be monotonically increasing, got bucket[\"c\", \"d\"> before bucket[\"a\", \"b\">.");
assertIllegalArgument("all(group(predefined(foo, bucket(c, d), bucket(-inf, e))))",
- "Buckets must be monotonically increasing, got bucket[\"c\", \"d\"> before bucket[-inf, \"e\">.");
+ "Buckets must be monotonically increasing, got bucket[\"c\", \"d\"> before bucket[-inf, \"e\">.");
assertIllegalArgument("all(group(predefined(foo, bucket(u, inf), bucket(e, i))))",
- "Buckets must be monotonically increasing, got bucket[\"u\", inf> before bucket[\"e\", \"i\">.");
+ "Buckets must be monotonically increasing, got bucket[\"u\", inf> before bucket[\"e\", \"i\">.");
// xorbit
assertParse("all(group(xorbit(foo, 1)))");
}
@Test
- public void testInfixArithmetic() {
+ void testInfixArithmetic() {
assertParse("all(group(1))", "all(group(1))");
assertParse("all(group(1+2))", "all(group(add(1, 2)))");
assertParse("all(group(1-2))", "all(group(sub(1, 2)))");
@@ -371,16 +367,16 @@ public class GroupingParserTestCase {
}
@Test
- public void testOperationLabel() {
+ void testOperationLabel() {
assertParse("each() as(foo)",
- "each() as(foo)");
+ "each() as(foo)");
assertParse("all(each() as(foo)" +
- " each() as(bar))",
- "all(each() as(foo) each() as(bar))");
+ " each() as(bar))",
+ "all(each() as(foo) each() as(bar))");
assertParse("all(group(a) each(each() as(foo)" +
- " each() as(bar))" +
- " each() as(baz))",
- "all(group(a) each(each() as(foo) each() as(bar)) each() as(baz))");
+ " each() as(bar))" +
+ " each() as(baz))",
+ "all(group(a) each(each() as(foo) each() as(bar)) each() as(baz))");
assertIllegalArgument("all() as(foo)", "Encountered \" \"as\" \"as\"\" at line 1, column 7.");
assertIllegalArgument("all(all() as(foo))", "Encountered \" \"as\" \"as\"\" at line 1, column 11.");
@@ -388,58 +384,58 @@ public class GroupingParserTestCase {
}
@Test
- public void testAttributeName() {
+ void testAttributeName() {
assertParse("all(group(foo))");
assertIllegalArgument("all(group(foo.))",
- "Encountered \" \")\" \")\"\" at line 1, column 15.");
+ "Encountered \" \")\" \")\"\" at line 1, column 15.");
assertParse("all(group(foo.bar))");
assertIllegalArgument("all(group(foo.bar.))",
- "Encountered \" \")\" \")\"\" at line 1, column 19.");
+ "Encountered \" \")\" \")\"\" at line 1, column 19.");
assertParse("all(group(foo.bar.baz))");
}
@Test
- public void testOutputLabel() {
+ void testOutputLabel() {
assertParse("all(output(min(a) as(foo)))",
- "all(output(min(a) as(foo)))");
+ "all(output(min(a) as(foo)))");
assertParse("all(output(min(a) as(foo), max(b) as(bar)))",
- "all(output(min(a) as(foo), max(b) as(bar)))");
+ "all(output(min(a) as(foo), max(b) as(bar)))");
assertIllegalArgument("all(output(min(a)) as(foo))",
- "Encountered \" \"as\" \"as\"\" at line 1, column 20.");
+ "Encountered \" \"as\" \"as\"\" at line 1, column 20.");
}
@Test
- public void testRootWhere() {
+ void testRootWhere() {
String expected = "all(where(bar) all(group(foo)))";
assertParse("all(where(bar) all(group(foo)))", expected);
assertParse("all(group(foo)) where(bar)", expected);
}
@Test
- public void testParseBadRequest() {
+ void testParseBadRequest() {
assertIllegalArgument("output(count())",
- "Encountered \" \"output\" \"output\"\" at line 1, column 1.");
+ "Encountered \" \"output\" \"output\"\" at line 1, column 1.");
assertIllegalArgument("each(output(count()))",
- "Expression 'count()' not applicable for single hit.");
+ "Expression 'count()' not applicable for single hit.");
assertIllegalArgument("all(output(count())))",
- "Encountered \" \")\" \")\"\" at line 1, column 21.");
+ "Encountered \" \")\" \")\"\" at line 1, column 21.");
}
@Test
- public void testAttributeFunction() {
+ void testAttributeFunction() {
assertParse("all(group(attribute(foo)))");
assertParse("all(group(attribute(foo)) order(sum(attribute(a))))");
}
@Test
- public void testAccuracy() {
+ void testAccuracy() {
assertParse("all(accuracy(0.5))");
assertParse("all(group(foo) accuracy(1.0))");
}
@Test
- public void testMapSyntax() {
+ void testMapSyntax() {
assertParse("all(group(my.little{key}))", "all(group(my.little{\"key\"}))");
assertParse("all(group(my.little{key }))", "all(group(my.little{\"key\"}))");
assertParse("all(group(my.little{\"key\"}))", "all(group(my.little{\"key\"}))");
@@ -458,7 +454,7 @@ public class GroupingParserTestCase {
}
@Test
- public void testMapSyntaxWithKeySourceAttribute() {
+ void testMapSyntaxWithKeySourceAttribute() {
assertAttributeMapLookup("all(group(my_map{attribute(my_attr)}))",
"my_map.key", "my_map.value", "", "my_attr");
assertAttributeMapLookup("all(group(my_map{attribute(my_attr)}.name))",
@@ -487,7 +483,7 @@ public class GroupingParserTestCase {
}
@Test
- public void testMisc() {
+ void testMisc() {
for (String fnc : Arrays.asList("time.date",
"time.dayofmonth",
"time.dayofweek",
@@ -536,39 +532,39 @@ public class GroupingParserTestCase {
// TODO: assertParseRequest("all(group(a) each(output(xor(xorbit(b)) xor(xorbit(b, 64)))))");
assertParse("all(group(artist) each(each(output(summary()))))");
assertParse("all(group(artist) max(13) each(group(fixedwidth(year, 21.34)) max(55) output(count()) " +
- "each(each(output(summary())))))");
+ "each(each(output(summary())))))");
assertParse("all(group(artist) max(13) each(group(predefined(year, bucket(7, 19), bucket(90, 300))) " +
- "max(55) output(count()) each(each(output(summary())))))");
+ "max(55) output(count()) each(each(output(summary())))))");
assertParse("all(group(artist) max(13) each(group(predefined(year, bucket(7.1, 19.0), bucket(90.7, 300.0))) " +
- "max(55) output(count()) each(each(output(summary())))))");
+ "max(55) output(count()) each(each(output(summary())))))");
assertParse("all(group(artist) max(13) each(group(predefined(year, bucket('a', 'b'), bucket('cd'))) " +
- "max(55) output(count()) each(each(output(summary())))))");
+ "max(55) output(count()) each(each(output(summary())))))");
assertParse("all(output(count()))");
assertParse("all(group(album) output(count()))");
assertParse("all(group(album) each(output(count())))");
assertParse("all(group(artist) each(group(album) output(count()))" +
- " each(group(song) output(count())))");
+ " each(group(song) output(count())))");
assertParse("all(group(artist) output(count())" +
- " each(group(album) output(count())" +
- " each(group(song) output(count())" +
- " each(each(output(summary()))))))");
+ " each(group(album) output(count())" +
+ " each(group(song) output(count())" +
+ " each(each(output(summary()))))))");
assertParse("all(group(album) order(-$total=sum(length)) each(output($total)))");
assertParse("all(group(album) max(1) each(output(sum(length))))");
assertParse("all(group(artist) each(max(2) each(output(summary()))))");
assertParse("all(group(artist) max(3)" +
- " each(group(album as(albumsongs)) each(each(output(summary()))))" +
- " each(group(album as(albumlength)) output(sum(sum(length)))))");
+ " each(group(album as(albumsongs)) each(each(output(summary()))))" +
+ " each(group(album as(albumlength)) output(sum(sum(length)))))");
assertParse("all(group(artist) max(15)" +
- " each(group(album) " +
- " each(group(song)" +
- " each(max(2) each(output(summary()))))))");
+ " each(group(album) " +
+ " each(group(song)" +
+ " each(max(2) each(output(summary()))))))");
assertParse("all(group(artist) max(15)" +
- " each(group(album)" +
- " each(group(song)" +
- " each(max(2) each(output(summary())))))" +
- " each(group(song) max(5) order(sum(popularity))" +
- " each(output(sum(sold)) each(output(summary())))))");
+ " each(group(album)" +
+ " each(group(song)" +
+ " each(max(2) each(output(summary())))))" +
+ " each(group(song) max(5) order(sum(popularity))" +
+ " each(output(sum(sold)) each(output(summary())))))");
assertParse("all(group(artist) order(max(relevance) * count()) each(output(count())))");
assertParse("all(group(artist) each(output(sum(popularity) / count())))");
@@ -576,9 +572,9 @@ public class GroupingParserTestCase {
assertParse("all(group(debugwait(artist, 3.3, true)))");
assertParse("all(group(debugwait(artist, 3.3, false)))");
assertIllegalArgument("all(group(debugwait(artist, -3.3, true)))",
- "Encountered \" \"-\" \"-\"\" at line 1, column 29");
+ "Encountered \" \"-\" \"-\"\" at line 1, column 29");
assertIllegalArgument("all(group(debugwait(artist, 3.3, lol)))",
- "Encountered \" <IDENTIFIER> \"lol\"\" at line 1, column 34");
+ "Encountered \" <IDENTIFIER> \"lol\"\" at line 1, column 34");
assertParse("all(group(artist) each(output(stddev(simple))))");
// Test max()
@@ -588,35 +584,35 @@ public class GroupingParserTestCase {
}
@Test
- public void testBucket() {
+ void testBucket() {
List<GroupingOperation> operations = assertParse("all(group(predefined(artist, bucket('a'), bucket('c', 'z'))))");
assertEquals(1, operations.size());
assertEquals("all(group(predefined(artist, bucket[\"a\", \"a \">, bucket[\"c\", \"z\">)))",
- operations.get(0).toString());
+ operations.get(0).toString());
}
@Test
- public void requireThatParseExceptionMessagesContainErrorMarker() {
+ void requireThatParseExceptionMessagesContainErrorMarker() {
assertIllegalArgument("foo",
- "Encountered \" <IDENTIFIER> \"foo\"\" at line 1, column 1.\n\n" +
- "Was expecting one of:\n\n" +
- "<SPACE> ...\n" +
- " \"all\" ...\n" +
- " \"each\" ...\n" +
- " \n" +
- "At position:\n" +
- "foo\n" +
- "^");
+ "Encountered \" <IDENTIFIER> \"foo\"\" at line 1, column 1.\n\n" +
+ "Was expecting one of:\n\n" +
+ "<SPACE> ...\n" +
+ " \"all\" ...\n" +
+ " \"each\" ...\n" +
+ " \n" +
+ "At position:\n" +
+ "foo\n" +
+ "^");
assertIllegalArgument("\n foo",
- "Encountered \" <IDENTIFIER> \"foo\"\" at line 2, column 2.\n\n" +
- "Was expecting one of:\n\n" +
- "<SPACE> ...\n" +
- " \"all\" ...\n" +
- " \"each\" ...\n" +
- " \n" +
- "At position:\n" +
- " foo\n" +
- " ^");
+ "Encountered \" <IDENTIFIER> \"foo\"\" at line 2, column 2.\n\n" +
+ "Was expecting one of:\n\n" +
+ "<SPACE> ...\n" +
+ " \"all\" ...\n" +
+ " \"each\" ...\n" +
+ " \n" +
+ "At position:\n" +
+ " foo\n" +
+ " ^");
}
// --------------------------------------------------------------------------------
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/result/FlatteningSearcherTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/result/FlatteningSearcherTestCase.java
index c97bf150645..3e1cff54737 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/result/FlatteningSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/result/FlatteningSearcherTestCase.java
@@ -23,15 +23,15 @@ import com.yahoo.searchlib.aggregation.Grouping;
import com.yahoo.searchlib.aggregation.HitsAggregationResult;
import com.yahoo.searchlib.aggregation.hll.SparseSketch;
import com.yahoo.searchlib.expression.StringResultNode;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
-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 bratseth
@@ -39,42 +39,42 @@ import static org.junit.Assert.assertTrue;
public class FlatteningSearcherTestCase {
@Test
- public void testFlatteningSearcher() {
+ void testFlatteningSearcher() {
Query query = new Query("?query=test");
GroupingRequest req = GroupingRequest.newInstance(query);
req.setRootOperation(GroupingOperation.fromString("all(group(foo) output(count()) each(each(output(summary(bar)))))"));
Grouping group0 = new Grouping(0);
group0.setRoot(new Group()
- .addAggregationResult(new ExpressionCountAggregationResult(new SparseSketch(), sketch -> 69))
- .addChild(new Group().setId(new StringResultNode("unique1"))
- .addAggregationResult(new HitsAggregationResult(3, "bar")
- )
- )
- .addChild(new Group().setId(new StringResultNode("unique2"))
- .addAggregationResult(new HitsAggregationResult(3, "bar")
- )
- ));
+ .addAggregationResult(new ExpressionCountAggregationResult(new SparseSketch(), sketch -> 69))
+ .addChild(new Group().setId(new StringResultNode("unique1"))
+ .addAggregationResult(new HitsAggregationResult(3, "bar")
+ )
+ )
+ .addChild(new Group().setId(new StringResultNode("unique2"))
+ .addAggregationResult(new HitsAggregationResult(3, "bar")
+ )
+ ));
Grouping group1 = new Grouping(0);
group1.setRoot(new Group()
- .addChild(new Group().setId(new StringResultNode("unique1"))
- .addAggregationResult(new HitsAggregationResult(3, "bar")
- .addHit(fs4Hit(0.7))
- .addHit(fs4Hit(0.6))
- .addHit(fs4Hit(0.3))
- )
- )
- .addChild(new Group().setId(new StringResultNode("unique2"))
- .addAggregationResult(new HitsAggregationResult(3, "bar")
- .addHit(fs4Hit(0.5))
- .addHit(fs4Hit(0.4))
- )
- ));
+ .addChild(new Group().setId(new StringResultNode("unique1"))
+ .addAggregationResult(new HitsAggregationResult(3, "bar")
+ .addHit(fs4Hit(0.7))
+ .addHit(fs4Hit(0.6))
+ .addHit(fs4Hit(0.3))
+ )
+ )
+ .addChild(new Group().setId(new StringResultNode("unique2"))
+ .addAggregationResult(new HitsAggregationResult(3, "bar")
+ .addHit(fs4Hit(0.5))
+ .addHit(fs4Hit(0.4))
+ )
+ ));
Execution execution = newExecution(new FlatteningSearcher(),
- new GroupingExecutor(ComponentId.fromString("grouping")),
- new ResultProvider(Arrays.asList(
- new GroupingListHit(List.of(group0), null),
- new GroupingListHit(List.of(group1), null))));
+ new GroupingExecutor(ComponentId.fromString("grouping")),
+ new ResultProvider(Arrays.asList(
+ new GroupingListHit(List.of(group0), null),
+ new GroupingListHit(List.of(group1), null))));
Result result = execution.search(query);
assertEquals(5, result.hits().size());
assertFlat(result);
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/result/GroupIdTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/result/GroupIdTestCase.java
index 01eba55924f..7b2f0d52742 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/result/GroupIdTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/result/GroupIdTestCase.java
@@ -1,9 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.grouping.result;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -11,7 +11,7 @@ import static org.junit.Assert.*;
public class GroupIdTestCase {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
ValueGroupId valueId = new DoubleId(6.9);
assertEquals(6.9, valueId.getValue());
BucketGroupId rangeId = new DoubleBucketId(6.0, 9.0);
@@ -24,11 +24,11 @@ public class GroupIdTestCase {
assertEquals(6L, rangeId.getFrom());
assertEquals(9L, rangeId.getTo());
- valueId = new RawId(new byte[] { 6, 9 });
- assertArrayEquals(new byte[] { 6, 9 }, (byte[])valueId.getValue());
- rangeId = new RawBucketId(new byte[] { 6, 9 }, new byte[] { 9, 6 });
- assertArrayEquals(new byte[] { 6, 9 }, (byte[])rangeId.getFrom());
- assertArrayEquals(new byte[] { 9, 6 }, (byte[])rangeId.getTo());
+ valueId = new RawId(new byte[]{6, 9});
+ assertArrayEquals(new byte[]{6, 9}, (byte[]) valueId.getValue());
+ rangeId = new RawBucketId(new byte[]{6, 9}, new byte[]{9, 6});
+ assertArrayEquals(new byte[]{6, 9}, (byte[]) rangeId.getFrom());
+ assertArrayEquals(new byte[]{9, 6}, (byte[]) rangeId.getTo());
valueId = new StringId("69");
assertEquals("69", valueId.getValue());
@@ -41,14 +41,14 @@ public class GroupIdTestCase {
}
@Test
- public void requireThatToStringCorrespondsToType() {
+ void requireThatToStringCorrespondsToType() {
assertEquals("group:double:6.9", new DoubleId(6.9).toString());
assertEquals("group:double_bucket:6.0:9.0", new DoubleBucketId(6.0, 9.0).toString());
assertEquals("group:long:69", new LongId(69L).toString());
assertEquals("group:long_bucket:6:9", new LongBucketId(6L, 9L).toString());
assertEquals("group:null", new NullId().toString());
- assertEquals("group:raw:[6, 9]", new RawId(new byte[] { 6, 9 }).toString());
- assertEquals("group:raw_bucket:[6, 9]:[9, 6]", new RawBucketId(new byte[] { 6, 9 }, new byte[] { 9, 6 }).toString());
+ assertEquals("group:raw:[6, 9]", new RawId(new byte[]{6, 9}).toString());
+ assertEquals("group:raw_bucket:[6, 9]:[9, 6]", new RawBucketId(new byte[]{6, 9}, new byte[]{9, 6}).toString());
assertTrue(new RootId(0).toString().startsWith("group:root:"));
assertEquals("group:string:69", new StringId("69").toString());
assertEquals("group:string_bucket:6:9", new StringBucketId("6", "9").toString());
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/result/GroupListTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/result/GroupListTestCase.java
index 33e8f119ec9..3c583c88d5a 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/result/GroupListTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/result/GroupListTestCase.java
@@ -2,10 +2,10 @@
package com.yahoo.search.grouping.result;
import com.yahoo.search.grouping.Continuation;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-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 Simon Thoresen Hult
@@ -13,7 +13,7 @@ import static org.junit.Assert.assertSame;
public class GroupListTestCase {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
GroupList lst = new GroupList("foo");
assertEquals("foo", lst.getLabel());
assertEquals(0, lst.continuations().size());
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/result/GroupTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/result/GroupTestCase.java
index 47f82205689..4e359531b7a 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/result/GroupTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/result/GroupTestCase.java
@@ -3,10 +3,10 @@ package com.yahoo.search.grouping.result;
import com.yahoo.search.result.Hit;
import com.yahoo.search.result.Relevance;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-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;
/**
* @author Simon Thoresen Hult
@@ -14,7 +14,7 @@ import static org.junit.Assert.assertNull;
public class GroupTestCase {
@Test
- public void requireThatListsAreAccessibleByLabel() {
+ void requireThatListsAreAccessibleByLabel() {
Group grp = new Group(new LongId(69L), new Relevance(1));
grp.add(new Hit("hit"));
grp.add(new HitList("hitList"));
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/result/HitListTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/result/HitListTestCase.java
index 2404af09c7a..5f1d2d3f125 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/result/HitListTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/result/HitListTestCase.java
@@ -2,10 +2,10 @@
package com.yahoo.search.grouping.result;
import com.yahoo.search.grouping.Continuation;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-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 Simon Thoresen Hult
@@ -13,7 +13,7 @@ import static org.junit.Assert.assertSame;
public class HitListTestCase {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
HitList lst = new HitList("foo");
assertEquals("foo", lst.getLabel());
assertEquals(0, lst.continuations().size());
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/result/HitRendererTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/result/HitRendererTestCase.java
index 1035c9d9284..8e98f49df48 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/result/HitRendererTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/result/HitRendererTestCase.java
@@ -6,13 +6,13 @@ import com.yahoo.search.result.HitGroup;
import com.yahoo.search.result.Relevance;
import com.yahoo.text.Utf8;
import com.yahoo.text.XMLWriter;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.StringWriter;
-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
@@ -20,7 +20,7 @@ import static org.junit.Assert.fail;
public class HitRendererTestCase {
@Test
- public void requireThatGroupListsRenderAsExpected() {
+ void requireThatGroupListsRenderAsExpected() {
assertRender(new GroupList("foo"), "<grouplist label=\"foo\"></grouplist>\n");
assertRender(new GroupList("b\u00e6z"), "<grouplist label=\"b\u00e6z\"></grouplist>\n");
@@ -28,21 +28,21 @@ public class HitRendererTestCase {
lst.continuations().put("bar.key", new MyContinuation("bar.val"));
lst.continuations().put("baz.key", new MyContinuation("baz.val"));
assertRender(lst, "<grouplist label=\"foo\">\n" +
- "<continuation id=\"bar.key\">bar.val</continuation>\n" +
- "<continuation id=\"baz.key\">baz.val</continuation>\n" +
- "</grouplist>\n");
+ "<continuation id=\"bar.key\">bar.val</continuation>\n" +
+ "<continuation id=\"baz.key\">baz.val</continuation>\n" +
+ "</grouplist>\n");
}
@Test
- public void requireThatGroupIdsRenderAsExpected() {
+ void requireThatGroupIdsRenderAsExpected() {
assertRender(newGroup(new DoubleId(6.9)),
- "<group relevance=\"1.0\">\n" +
- "<id type=\"double\">6.9</id>\n" +
- "</group>\n");
+ "<group relevance=\"1.0\">\n" +
+ "<id type=\"double\">6.9</id>\n" +
+ "</group>\n");
assertRender(newGroup(new LongId(69L)),
- "<group relevance=\"1.0\">\n" +
- "<id type=\"long\">69</id>\n" +
- "</group>\n");
+ "<group relevance=\"1.0\">\n" +
+ "<id type=\"long\">69</id>\n" +
+ "</group>\n");
assertRender(newGroup(new BoolId(true)),
"<group relevance=\"1.0\">\n" +
"<id type=\"bool\">true</id>\n" +
@@ -52,89 +52,89 @@ public class HitRendererTestCase {
"<id type=\"bool\">false</id>\n" +
"</group>\n");
assertRender(newGroup(new NullId()),
- "<group relevance=\"1.0\">\n" +
- "<id type=\"null\"/>\n" +
- "</group>\n");
+ "<group relevance=\"1.0\">\n" +
+ "<id type=\"null\"/>\n" +
+ "</group>\n");
assertRender(newGroup(new RawId(Utf8.toBytes("foo"))),
- "<group relevance=\"1.0\">\n" +
- "<id type=\"raw\">[102, 111, 111]</id>\n" +
- "</group>\n");
+ "<group relevance=\"1.0\">\n" +
+ "<id type=\"raw\">[102, 111, 111]</id>\n" +
+ "</group>\n");
assertRender(newGroup(new StringId("foo")),
- "<group relevance=\"1.0\">\n" +
- "<id type=\"string\">foo</id>\n" +
- "</group>\n");
+ "<group relevance=\"1.0\">\n" +
+ "<id type=\"string\">foo</id>\n" +
+ "</group>\n");
assertRender(newGroup(new StringId("b\u00e6z")),
- "<group relevance=\"1.0\">\n" +
- "<id type=\"string\">b\u00e6z</id>\n" +
- "</group>\n");
+ "<group relevance=\"1.0\">\n" +
+ "<id type=\"string\">b\u00e6z</id>\n" +
+ "</group>\n");
assertRender(newGroup(new DoubleBucketId(6.9, 9.6)),
- "<group relevance=\"1.0\">\n" +
- "<id type=\"double_bucket\">\n<from>6.9</from>\n<to>9.6</to>\n</id>\n" +
- "</group>\n");
+ "<group relevance=\"1.0\">\n" +
+ "<id type=\"double_bucket\">\n<from>6.9</from>\n<to>9.6</to>\n</id>\n" +
+ "</group>\n");
assertRender(newGroup(new LongBucketId(6L, 9L)),
- "<group relevance=\"1.0\">\n" +
- "<id type=\"long_bucket\">\n<from>6</from>\n<to>9</to>\n</id>\n" +
- "</group>\n");
+ "<group relevance=\"1.0\">\n" +
+ "<id type=\"long_bucket\">\n<from>6</from>\n<to>9</to>\n</id>\n" +
+ "</group>\n");
assertRender(newGroup(new StringBucketId("bar", "baz")),
- "<group relevance=\"1.0\">\n" +
- "<id type=\"string_bucket\">\n<from>bar</from>\n<to>baz</to>\n</id>\n" +
- "</group>\n");
+ "<group relevance=\"1.0\">\n" +
+ "<id type=\"string_bucket\">\n<from>bar</from>\n<to>baz</to>\n</id>\n" +
+ "</group>\n");
assertRender(newGroup(new StringBucketId("b\u00e6r", "b\u00e6z")),
- "<group relevance=\"1.0\">\n" +
- "<id type=\"string_bucket\">\n<from>b\u00e6r</from>\n<to>b\u00e6z</to>\n</id>\n" +
- "</group>\n");
+ "<group relevance=\"1.0\">\n" +
+ "<id type=\"string_bucket\">\n<from>b\u00e6r</from>\n<to>b\u00e6z</to>\n</id>\n" +
+ "</group>\n");
assertRender(newGroup(new RawBucketId(Utf8.toBytes("bar"), Utf8.toBytes("baz"))),
- "<group relevance=\"1.0\">\n" +
- "<id type=\"raw_bucket\">\n<from>[98, 97, 114]</from>\n<to>[98, 97, 122]</to>\n</id>\n" +
- "</group>\n");
+ "<group relevance=\"1.0\">\n" +
+ "<id type=\"raw_bucket\">\n<from>[98, 97, 114]</from>\n<to>[98, 97, 122]</to>\n</id>\n" +
+ "</group>\n");
}
@Test
- public void requireThatGroupsRenderAsExpected() {
+ void requireThatGroupsRenderAsExpected() {
Group group = newGroup(new StringId("foo"));
group.setField("foo", "bar");
group.setField("baz", "cox");
assertRender(group, "<group relevance=\"1.0\">\n" +
- "<id type=\"string\">foo</id>\n" +
- "<output label=\"foo\">bar</output>\n" +
- "<output label=\"baz\">cox</output>\n" +
- "</group>\n");
+ "<id type=\"string\">foo</id>\n" +
+ "<output label=\"foo\">bar</output>\n" +
+ "<output label=\"baz\">cox</output>\n" +
+ "</group>\n");
group = newGroup(new StringId("foo"));
group.setField("foo", "b\u00e6r");
group.setField("b\u00e5z", "cox");
assertRender(group, "<group relevance=\"1.0\">\n" +
- "<id type=\"string\">foo</id>\n" +
- "<output label=\"foo\">b\u00e6r</output>\n" +
- "<output label=\"b\u00e5z\">cox</output>\n" +
- "</group>\n");
+ "<id type=\"string\">foo</id>\n" +
+ "<output label=\"foo\">b\u00e6r</output>\n" +
+ "<output label=\"b\u00e5z\">cox</output>\n" +
+ "</group>\n");
}
@Test
- public void requireThatRootGroupsRenderAsExpected() {
+ void requireThatRootGroupsRenderAsExpected() {
RootGroup group = new RootGroup(0, new MyContinuation("69"));
group.setField("foo", "bar");
group.setField("baz", "cox");
assertRender(group, "<group relevance=\"1.0\">\n" +
- "<id type=\"root\"/>\n" +
- "<continuation id=\"this\">69</continuation>\n" +
- "<output label=\"foo\">bar</output>\n" +
- "<output label=\"baz\">cox</output>\n" +
- "</group>\n");
+ "<id type=\"root\"/>\n" +
+ "<continuation id=\"this\">69</continuation>\n" +
+ "<output label=\"foo\">bar</output>\n" +
+ "<output label=\"baz\">cox</output>\n" +
+ "</group>\n");
group = new RootGroup(0, new MyContinuation("96"));
group.setField("foo", "b\u00e6r");
group.setField("b\u00e5z", "cox");
assertRender(group, "<group relevance=\"1.0\">\n" +
- "<id type=\"root\"/>\n" +
- "<continuation id=\"this\">96</continuation>\n" +
- "<output label=\"foo\">b\u00e6r</output>\n" +
- "<output label=\"b\u00e5z\">cox</output>\n" +
- "</group>\n");
+ "<id type=\"root\"/>\n" +
+ "<continuation id=\"this\">96</continuation>\n" +
+ "<output label=\"foo\">b\u00e6r</output>\n" +
+ "<output label=\"b\u00e5z\">cox</output>\n" +
+ "</group>\n");
}
@Test
- public void requireThatHitListsRenderAsExpected() {
+ void requireThatHitListsRenderAsExpected() {
assertRender(new HitList("foo"), "<hitlist label=\"foo\"></hitlist>\n");
assertRender(new HitList("b\u00e6z"), "<hitlist label=\"b\u00e6z\"></hitlist>\n");
@@ -142,10 +142,10 @@ public class HitRendererTestCase {
lst.continuations().put("bar.key", new MyContinuation("bar.val"));
lst.continuations().put("baz.key", new MyContinuation("baz.val"));
assertRender(lst, "<hitlist label=\"foo\">\n" +
- "<continuation id=\"bar.key\">bar.val</continuation>\n" +
- "<continuation id=\"baz.key\">baz.val</continuation>\n" +
- "</hitlist>\n");
-}
+ "<continuation id=\"bar.key\">bar.val</continuation>\n" +
+ "<continuation id=\"baz.key\">baz.val</continuation>\n" +
+ "</hitlist>\n");
+ }
private static Group newGroup(GroupId id) {
return new Group(id, new Relevance(1));
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/vespa/CompositeContinuationTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/vespa/CompositeContinuationTestCase.java
index a440fcaac7a..ee177709b59 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/vespa/CompositeContinuationTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/vespa/CompositeContinuationTestCase.java
@@ -2,11 +2,11 @@
package com.yahoo.search.grouping.vespa;
import com.yahoo.search.grouping.Continuation;
-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.*;
/**
* @author Simon Thoresen Hult
@@ -14,7 +14,7 @@ import static org.junit.Assert.*;
public class CompositeContinuationTestCase {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
CompositeContinuation cnt = new CompositeContinuation();
Iterator<EncodableContinuation> it = cnt.iterator();
assertFalse(it.hasNext());
@@ -37,51 +37,51 @@ public class CompositeContinuationTestCase {
}
@Test
- public void requireThatCompositeContinuationsAreFlattened() {
+ void requireThatCompositeContinuationsAreFlattened() {
assertEncode("BCBCBCBEBGBCBKCBACBKCCK",
- newComposite(newOffset(1, 1, 2, 3), newOffset(5, 8, 13, 21)));
+ newComposite(newOffset(1, 1, 2, 3), newOffset(5, 8, 13, 21)));
assertEncode("BCBBBBBDBFBCBJBPCBJCCJ",
- newComposite(newComposite(newOffset(-1, -1, -2, -3)), newComposite(newOffset(-5, -8, -13, -21))));
+ newComposite(newComposite(newOffset(-1, -1, -2, -3)), newComposite(newOffset(-5, -8, -13, -21))));
}
@Test
- public void requireThatEmptyStringCanBeDecoded() {
+ void requireThatEmptyStringCanBeDecoded() {
assertDecode("", new CompositeContinuation());
}
@Test
- public void requireThatCompositeContinuationsCanBeDecoded() {
+ void requireThatCompositeContinuationsCanBeDecoded() {
assertDecode("BCBCBCBEBGBCBKCBACBKCCK",
- newComposite(newOffset(1, 1, 2, 3), newOffset(5, 8, 13, 21)));
+ newComposite(newOffset(1, 1, 2, 3), newOffset(5, 8, 13, 21)));
assertDecode("BCBBBBBDBFBCBJBPCBJCCJ",
- newComposite(newOffset(-1, -1, -2, -3), newOffset(-5, -8, -13, -21)));
+ newComposite(newOffset(-1, -1, -2, -3), newOffset(-5, -8, -13, -21)));
}
@Test
- public void requireThatHashCodeIsImplemented() {
+ void requireThatHashCodeIsImplemented() {
assertEquals(newComposite().hashCode(), newComposite().hashCode());
}
@Test
- public void requireThatEqualsIsImplemented() {
+ void requireThatEqualsIsImplemented() {
CompositeContinuation cnt = newComposite();
- assertFalse(cnt.equals(new Object()));
+ assertNotEquals(cnt, new Object());
assertEquals(cnt, newComposite());
- assertFalse(cnt.equals(newComposite(newOffset(1, 1, 2, 3))));
- assertFalse(cnt.equals(newComposite(newOffset(1, 1, 2, 3), newOffset(5, 8, 13, 21))));
- assertFalse(cnt.equals(newComposite(newOffset(5, 8, 13, 21))));
+ assertNotEquals(cnt, newComposite(newOffset(1, 1, 2, 3)));
+ assertNotEquals(cnt, newComposite(newOffset(1, 1, 2, 3), newOffset(5, 8, 13, 21)));
+ assertNotEquals(cnt, newComposite(newOffset(5, 8, 13, 21)));
cnt = newComposite(newOffset(1, 1, 2, 3));
- assertFalse(cnt.equals(new Object()));
+ assertNotEquals(cnt, new Object());
assertEquals(cnt, newComposite(newOffset(1, 1, 2, 3)));
- assertFalse(cnt.equals(newComposite(newOffset(1, 1, 2, 3), newOffset(5, 8, 13, 21))));
- assertFalse(cnt.equals(newComposite(newOffset(5, 8, 13, 21))));
+ assertNotEquals(cnt, newComposite(newOffset(1, 1, 2, 3), newOffset(5, 8, 13, 21)));
+ assertNotEquals(cnt, newComposite(newOffset(5, 8, 13, 21)));
cnt = newComposite(newOffset(1, 1, 2, 3), newOffset(5, 8, 13, 21));
- assertFalse(cnt.equals(new Object()));
- assertFalse(cnt.equals(newComposite(newOffset(1, 1, 2, 3))));
+ assertNotEquals(cnt, new Object());
+ assertNotEquals(cnt, newComposite(newOffset(1, 1, 2, 3)));
assertEquals(cnt, newComposite(newOffset(1, 1, 2, 3), newOffset(5, 8, 13, 21)));
- assertFalse(cnt.equals(newComposite(newOffset(5, 8, 13, 21))));
+ assertNotEquals(cnt, newComposite(newOffset(5, 8, 13, 21)));
}
private static CompositeContinuation newComposite(EncodableContinuation... children) {
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/vespa/GroupingExecutorTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/vespa/GroupingExecutorTestCase.java
index 4a7c6179db7..268a3ceb635 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/vespa/GroupingExecutorTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/vespa/GroupingExecutorTestCase.java
@@ -34,7 +34,7 @@ import com.yahoo.searchlib.expression.ConstantNode;
import com.yahoo.searchlib.expression.IntegerResultNode;
import com.yahoo.searchlib.expression.StringResultNode;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
@@ -45,12 +45,7 @@ import java.util.List;
import java.util.Map;
import java.util.Queue;
-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 Simon Thoresen Hult
@@ -58,14 +53,14 @@ import static org.junit.Assert.fail;
public class GroupingExecutorTestCase {
@Test
- public void requireThatNullRequestsPass() {
+ void requireThatNullRequestsPass() {
Result res = newExecution(new GroupingExecutor()).search(newQuery());
assertNotNull(res);
assertEquals(0, res.hits().size());
}
@Test
- public void requireThatEmptyRequestsPass() {
+ void requireThatEmptyRequestsPass() {
Query query = newQuery();
GroupingRequest.newInstance(query).setRootOperation(new AllOperation());
Result res = newExecution(new GroupingExecutor()).search(query);
@@ -74,7 +69,7 @@ public class GroupingExecutorTestCase {
}
@Test
- public void requireThatRequestsAreTransformed() {
+ void requireThatRequestsAreTransformed() {
Query query = newQuery();
GroupingRequest req = GroupingRequest.newInstance(query);
req.setRootOperation(GroupingOperation.fromString("all(group(foo) each(output(max(bar))))"));
@@ -90,7 +85,7 @@ public class GroupingExecutorTestCase {
}
@Test
- public void requireThatEachBelowAllDoesNotBlowUp() {
+ void requireThatEachBelowAllDoesNotBlowUp() {
Query query = newQuery();
GroupingRequest req = GroupingRequest.newInstance(query);
req.setRootOperation(GroupingOperation.fromString("all(each(output(summary(bar))))"));
@@ -100,7 +95,7 @@ public class GroupingExecutorTestCase {
}
@Test
- public void requireThatSearchIsMultiPass() {
+ void requireThatSearchIsMultiPass() {
Query query = newQuery();
GroupingRequest req = GroupingRequest.newInstance(query);
req.setRootOperation(GroupingOperation.fromString("all(group(foo) each(output(max(bar))))"));
@@ -110,7 +105,7 @@ public class GroupingExecutorTestCase {
}
@Test
- public void requireThatPassRequestsSingleLevel() {
+ void requireThatPassRequestsSingleLevel() {
Query query = newQuery();
GroupingRequest req = GroupingRequest.newInstance(query);
req.setRootOperation(GroupingOperation.fromString("all(group(foo) each(output(max(bar))))"));
@@ -126,7 +121,7 @@ public class GroupingExecutorTestCase {
}
@Test
- public void requireThatAggregationPerHitWithoutGroupingDoesNotWorkYet() {
+ void requireThatAggregationPerHitWithoutGroupingDoesNotWorkYet() {
try {
execute("each(output(strlen(customer)))");
fail();
@@ -136,19 +131,19 @@ public class GroupingExecutorTestCase {
}
@Test
- public void requireThatAggregationWithoutGroupingWorks() {
- List<Grouping> groupings=execute("all(output(count()))");
- assertEquals(1,groupings.size());
+ void requireThatAggregationWithoutGroupingWorks() {
+ List<Grouping> groupings = execute("all(output(count()))");
+ assertEquals(1, groupings.size());
assertEquals(0, groupings.get(0).getLevels().size());
assertEquals(ConstantNode.class, groupings.get(0).getRoot().getAggregationResults().get(0).getExpression().getClass());
}
@Test
- public void requireThatGroupingIsParallel() {
+ void requireThatGroupingIsParallel() {
Query query = newQuery();
GroupingRequest req = GroupingRequest.newInstance(query);
req.setRootOperation(GroupingOperation.fromString("all(group(foo) each(output(max(bar))) as(max)" +
- " each(output(min(bar))) as(min))"));
+ " each(output(min(bar))) as(min))"));
GroupingCounter cnt = new GroupingCounter();
newExecution(new GroupingExecutor(), cnt).search(query);
assertEquals(2, cnt.passList.size());
@@ -157,11 +152,11 @@ public class GroupingExecutorTestCase {
}
@Test
- public void requireThatParallelGroupingIsNotRedundant() {
+ void requireThatParallelGroupingIsNotRedundant() {
Query query = newQuery();
GroupingRequest req = GroupingRequest.newInstance(query);
req.setRootOperation(GroupingOperation.fromString("all(group(foo) each(output(max(bar))) as(shallow)" +
- " each(group(baz) each(output(max(cox)))) as(deep))"));
+ " each(group(baz) each(output(max(cox)))) as(deep))"));
GroupingCounter cnt = new GroupingCounter();
newExecution(new GroupingExecutor(), cnt).search(query);
assertEquals(3, cnt.passList.size());
@@ -171,7 +166,7 @@ public class GroupingExecutorTestCase {
}
@Test
- public void requireThatPassResultsAreMerged() {
+ void requireThatPassResultsAreMerged() {
Query query = newQuery();
GroupingRequest req = GroupingRequest.newInstance(query);
req.setRootOperation(GroupingOperation.fromString("all(group(foo) each(output(min(bar), max(bar))))"));
@@ -187,14 +182,14 @@ public class GroupingExecutorTestCase {
.addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("common")).addAggregationResult(new MinAggregationResult().setMin(new IntegerResultNode(6)).setTag(3)))
);
Execution exec = newExecution(new GroupingExecutor(),
- new ResultProvider(Arrays.asList(
- new GroupingListHit(List.of(grpA), null),
- new GroupingListHit(List.of(grpB), null))));
+ new ResultProvider(Arrays.asList(
+ new GroupingListHit(List.of(grpA), null),
+ new GroupingListHit(List.of(grpB), null))));
Group grp = req.getResultGroup(exec.search(query));
assertEquals(1, grp.size());
Hit hit = grp.get(0);
assertTrue(hit instanceof GroupList);
- GroupList lst = (GroupList)hit;
+ GroupList lst = (GroupList) hit;
assertEquals(3, lst.size());
assertNotNull(hit = lst.get("group:string:uniqueA"));
assertEquals(6L, hit.getField("max(bar)"));
@@ -206,7 +201,7 @@ public class GroupingExecutorTestCase {
}
@Test
- public void requireThatUnexpectedGroupingResultsAreIgnored() {
+ void requireThatUnexpectedGroupingResultsAreIgnored() {
Query query = newQuery();
GroupingRequest req = GroupingRequest.newInstance(query);
req.setRootOperation(GroupingOperation.fromString("all(group(foo) each(output(max(bar))))"));
@@ -220,14 +215,14 @@ public class GroupingExecutorTestCase {
.addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("unexpected")).addAggregationResult(new MaxAggregationResult().setMax(new IntegerResultNode(96)).setTag(3)))
);
Execution exec = newExecution(new GroupingExecutor(),
- new ResultProvider(Arrays.asList(
- new GroupingListHit(List.of(grpExpected), null),
- new GroupingListHit(List.of(grpUnexpected), null))));
+ new ResultProvider(Arrays.asList(
+ new GroupingListHit(List.of(grpExpected), null),
+ new GroupingListHit(List.of(grpUnexpected), null))));
Group grp = req.getResultGroup(exec.search(query));
assertEquals(1, grp.size());
Hit hit = grp.get(0);
assertTrue(hit instanceof GroupList);
- GroupList lst = (GroupList)hit;
+ GroupList lst = (GroupList) hit;
assertEquals(1, lst.size());
assertNotNull(hit = lst.get("group:string:expected"));
assertEquals(69L, hit.getField("max(bar)"));
@@ -235,7 +230,7 @@ public class GroupingExecutorTestCase {
}
@Test
- public void requireThatHitsAreFilled() {
+ void requireThatHitsAreFilled() {
Query query = newQuery();
GroupingRequest req = GroupingRequest.newInstance(query);
req.setRootOperation(GroupingOperation.fromString("all(group(foo) each(each(output(summary(bar)))))"));
@@ -243,20 +238,20 @@ public class GroupingExecutorTestCase {
Grouping grp0 = new Grouping(0);
grp0.setRoot(new com.yahoo.searchlib.aggregation.Group()
.addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("foo"))
- .addAggregationResult(new HitsAggregationResult(1, "bar"))
- ));
+ .addAggregationResult(new HitsAggregationResult(1, "bar"))
+ ));
Grouping grp1 = new Grouping(0);
grp1.setRoot(new com.yahoo.searchlib.aggregation.Group()
.addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("foo"))
- .addAggregationResult(new HitsAggregationResult(1, "bar").addHit(new com.yahoo.searchlib.aggregation.FS4Hit()))
- ));
+ .addAggregationResult(new HitsAggregationResult(1, "bar").addHit(new com.yahoo.searchlib.aggregation.FS4Hit()))
+ ));
Execution exec = newExecution(new GroupingExecutor(),
- new ResultProvider(Arrays.asList(
- new GroupingListHit(List.of(grp0), null),
- new GroupingListHit(List.of(grp1), null))),
- new FillRequestThrower());
+ new ResultProvider(Arrays.asList(
+ new GroupingListHit(List.of(grp0), null),
+ new GroupingListHit(List.of(grp1), null))),
+ new FillRequestThrower());
Result res = exec.search(query);
-
+
// Fill with summary specified in grouping
try {
exec.fill(res);
@@ -275,59 +270,59 @@ public class GroupingExecutorTestCase {
}
@Test
- public void requireThatUnfilledHitsRenderError() {
+ void requireThatUnfilledHitsRenderError() {
Query query = newQuery();
GroupingRequest req = GroupingRequest.newInstance(query);
req.setRootOperation(GroupingOperation.fromString("all(group(foo) each(each(output(summary(bar)))))"));
Grouping grp0 = new Grouping(0);
grp0.setRoot(new com.yahoo.searchlib.aggregation.Group()
- .addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("foo"))
- .addAggregationResult(new HitsAggregationResult(1, "bar"))));
+ .addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("foo"))
+ .addAggregationResult(new HitsAggregationResult(1, "bar"))));
Grouping grp1 = new Grouping(0);
grp1.setRoot(new com.yahoo.searchlib.aggregation.Group()
- .addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("foo"))
- .addAggregationResult(
- new HitsAggregationResult(1, "bar")
- .addHit(new com.yahoo.searchlib.aggregation.FS4Hit()))));
+ .addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("foo"))
+ .addAggregationResult(
+ new HitsAggregationResult(1, "bar")
+ .addHit(new com.yahoo.searchlib.aggregation.FS4Hit()))));
Execution exec = newExecution(new GroupingExecutor(),
- new ResultProvider(Arrays.asList(
- new GroupingListHit(List.of(grp0), null),
- new GroupingListHit(List.of(grp1), null))),
- new FillErrorProvider());
+ new ResultProvider(Arrays.asList(
+ new GroupingListHit(List.of(grp0), null),
+ new GroupingListHit(List.of(grp1), null))),
+ new FillErrorProvider());
Result res = exec.search(query);
exec.fill(res);
assertNotNull(res.hits().getError());
}
@Test
- public void requireThatGroupRelevanceCanBeSynthesized() {
+ void requireThatGroupRelevanceCanBeSynthesized() {
Query query = newQuery();
GroupingRequest req = GroupingRequest.newInstance(query);
req.setRootOperation(GroupingOperation.fromString("all(group(foo) order(count()) each(output(count())))"));
Grouping grp = new Grouping(0);
grp.setRoot(new com.yahoo.searchlib.aggregation.Group()
- .addChild(new com.yahoo.searchlib.aggregation.Group()
- .setId(new StringResultNode("foo"))
- .addAggregationResult(new CountAggregationResult(1))
- .addOrderBy(new AggregationRefNode(0), true))
- .addChild(new com.yahoo.searchlib.aggregation.Group()
- .setId(new StringResultNode("bar"))
- .addAggregationResult(new CountAggregationResult(2))
- .addOrderBy(new AggregationRefNode(0), true)));
+ .addChild(new com.yahoo.searchlib.aggregation.Group()
+ .setId(new StringResultNode("foo"))
+ .addAggregationResult(new CountAggregationResult(1))
+ .addOrderBy(new AggregationRefNode(0), true))
+ .addChild(new com.yahoo.searchlib.aggregation.Group()
+ .setId(new StringResultNode("bar"))
+ .addAggregationResult(new CountAggregationResult(2))
+ .addOrderBy(new AggregationRefNode(0), true)));
Result res = newExecution(new GroupingExecutor(),
- new ResultProvider(Arrays.asList(
- new GroupingListHit(List.of(grp), null),
- new GroupingListHit(List.of(grp), null)))).search(query);
+ new ResultProvider(Arrays.asList(
+ new GroupingListHit(List.of(grp), null),
+ new GroupingListHit(List.of(grp), null)))).search(query);
- GroupList groupList = (GroupList)req.getResultGroup(res).get(0);
+ GroupList groupList = (GroupList) req.getResultGroup(res).get(0);
assertEquals(1.0, groupList.get(0).getRelevance().getScore(), 1E-6);
assertEquals(0.5, groupList.get(1).getRelevance().getScore(), 1E-6);
}
@Test
- public void requireThatErrorsAreHandled() {
+ void requireThatErrorsAreHandled() {
Query query = newQuery();
GroupingRequest req = GroupingRequest.newInstance(query);
req.setRootOperation(GroupingOperation.fromString("all(group(foo) each(each(output(summary(bar)))))"));
@@ -335,20 +330,20 @@ public class GroupingExecutorTestCase {
Grouping grp0 = new Grouping(0);
grp0.setRoot(new com.yahoo.searchlib.aggregation.Group()
.addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("foo"))
- .addAggregationResult(new HitsAggregationResult(1, "bar"))
- ));
+ .addAggregationResult(new HitsAggregationResult(1, "bar"))
+ ));
Grouping grp1 = new Grouping(0);
grp1.setRoot(new com.yahoo.searchlib.aggregation.Group()
.addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("foo"))
- .addAggregationResult(new HitsAggregationResult(1, "bar").addHit(new com.yahoo.searchlib.aggregation.FS4Hit()))
- ));
+ .addAggregationResult(new HitsAggregationResult(1, "bar").addHit(new com.yahoo.searchlib.aggregation.FS4Hit()))
+ ));
ErrorProvider err = new ErrorProvider(1);
Execution exec = newExecution(new GroupingExecutor(),
- err,
- new ResultProvider(Arrays.asList(
- new GroupingListHit(List.of(grp0), null),
- new GroupingListHit(List.of(grp1), null))));
+ err,
+ new ResultProvider(Arrays.asList(
+ new GroupingListHit(List.of(grp0), null),
+ new GroupingListHit(List.of(grp1), null))));
Result res = exec.search(query);
assertNotNull(res.hits().getError());
assertEquals(Error.TIMEOUT.code, res.hits().getError().getCode());
@@ -356,10 +351,10 @@ public class GroupingExecutorTestCase {
err = new ErrorProvider(0);
exec = newExecution(new GroupingExecutor(),
- err,
- new ResultProvider(Arrays.asList(
- new GroupingListHit(List.of(grp0), null),
- new GroupingListHit(List.of(grp1), null))));
+ err,
+ new ResultProvider(Arrays.asList(
+ new GroupingListHit(List.of(grp0), null),
+ new GroupingListHit(List.of(grp1), null))));
res = exec.search(query);
assertNotNull(res.hits().getError());
assertEquals(Error.TIMEOUT.code, res.hits().getError().getCode());
@@ -367,39 +362,39 @@ public class GroupingExecutorTestCase {
}
@Test
- public void requireThatHitsAreFilledWithCorrectSummary() {
+ void requireThatHitsAreFilledWithCorrectSummary() {
Query query = newQuery();
GroupingRequest req = GroupingRequest.newInstance(query);
req.setRootOperation(GroupingOperation.fromString("all(group(foo) each(each(output(summary(bar))) as(bar) " +
- " each(output(summary(baz))) as(baz)))"));
+ " each(output(summary(baz))) as(baz)))"));
Grouping pass0A = new Grouping(0);
pass0A.setRoot(new com.yahoo.searchlib.aggregation.Group()
.addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("foo"))
- .addAggregationResult(new HitsAggregationResult(1, "bar"))
- ));
+ .addAggregationResult(new HitsAggregationResult(1, "bar"))
+ ));
Grouping pass0B = new Grouping(1);
pass0B.setRoot(new com.yahoo.searchlib.aggregation.Group()
.addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("foo"))
- .addAggregationResult(new HitsAggregationResult(1, "baz"))
- ));
+ .addAggregationResult(new HitsAggregationResult(1, "baz"))
+ ));
GlobalId gid1 = new GlobalId((new DocumentId("id:ns:type::1")).getGlobalId());
GlobalId gid2 = new GlobalId((new DocumentId("id:ns:type::2")).getGlobalId());
Grouping pass1A = new Grouping(0);
pass1A.setRoot(new com.yahoo.searchlib.aggregation.Group()
.addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("foo"))
- .addAggregationResult(new HitsAggregationResult(1, "bar").addHit(new com.yahoo.searchlib.aggregation.FS4Hit(1, gid1, 3)))
- ));
+ .addAggregationResult(new HitsAggregationResult(1, "bar").addHit(new com.yahoo.searchlib.aggregation.FS4Hit(1, gid1, 3)))
+ ));
Grouping pass1B = new Grouping(1);
pass1B.setRoot(new com.yahoo.searchlib.aggregation.Group()
.addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("foo"))
- .addAggregationResult(new HitsAggregationResult(1, "baz").addHit(new com.yahoo.searchlib.aggregation.FS4Hit(4, gid2, 6)))
- ));
+ .addAggregationResult(new HitsAggregationResult(1, "baz").addHit(new com.yahoo.searchlib.aggregation.FS4Hit(4, gid2, 6)))
+ ));
SummaryMapper sm = new SummaryMapper();
Execution exec = newExecution(new GroupingExecutor(),
- new ResultProvider(Arrays.asList(
- new GroupingListHit(Arrays.asList(pass0A, pass0B), null),
- new GroupingListHit(Arrays.asList(pass1A, pass1B), null))),
- sm);
+ new ResultProvider(Arrays.asList(
+ new GroupingListHit(Arrays.asList(pass0A, pass0B), null),
+ new GroupingListHit(Arrays.asList(pass1A, pass1B), null))),
+ sm);
exec.fill(exec.search(query), "default");
assertEquals(2, sm.hitsBySummary.size());
@@ -408,51 +403,51 @@ public class GroupingExecutorTestCase {
assertEquals(1, lst.size());
Hit hit = lst.get(0);
assertTrue(hit instanceof FastHit);
- assertEquals(1, ((FastHit)hit).getPartId());
- assertEquals(gid1, ((FastHit)hit).getGlobalId());
+ assertEquals(1, ((FastHit) hit).getPartId());
+ assertEquals(gid1, ((FastHit) hit).getGlobalId());
assertNotNull(lst = sm.hitsBySummary.get("baz"));
assertNotNull(lst);
assertEquals(1, lst.size());
hit = lst.get(0);
assertTrue(hit instanceof FastHit);
- assertEquals(4, ((FastHit)hit).getPartId());
- assertEquals(gid2, ((FastHit)hit).getGlobalId());
+ assertEquals(4, ((FastHit) hit).getPartId());
+ assertEquals(gid2, ((FastHit) hit).getGlobalId());
}
@Test
- public void requireThatDefaultSummaryNameFillsHitsWithNull() {
+ void requireThatDefaultSummaryNameFillsHitsWithNull() {
Query query = newQuery();
GroupingRequest req = GroupingRequest.newInstance(query);
req.setRootOperation(GroupingOperation.fromString("all(group(foo) each(each(output(summary()))) as(foo))"));
Grouping pass0 = new Grouping(0);
pass0.setRoot(new com.yahoo.searchlib.aggregation.Group()
- .addChild(new com.yahoo.searchlib.aggregation.Group()
- .setId(new StringResultNode("foo"))
- .addAggregationResult(
- new HitsAggregationResult(1, ExpressionConverter.DEFAULT_SUMMARY_NAME))));
+ .addChild(new com.yahoo.searchlib.aggregation.Group()
+ .setId(new StringResultNode("foo"))
+ .addAggregationResult(
+ new HitsAggregationResult(1, ExpressionConverter.DEFAULT_SUMMARY_NAME))));
Grouping pass1 = new Grouping(0);
pass1.setRoot(new com.yahoo.searchlib.aggregation.Group()
- .addChild(new com.yahoo.searchlib.aggregation.Group()
- .setId(new StringResultNode("foo"))
- .addAggregationResult(
- new HitsAggregationResult(1, ExpressionConverter.DEFAULT_SUMMARY_NAME)
- .addHit(new com.yahoo.searchlib.aggregation.FS4Hit()))));
+ .addChild(new com.yahoo.searchlib.aggregation.Group()
+ .setId(new StringResultNode("foo"))
+ .addAggregationResult(
+ new HitsAggregationResult(1, ExpressionConverter.DEFAULT_SUMMARY_NAME)
+ .addHit(new com.yahoo.searchlib.aggregation.FS4Hit()))));
Execution exec = newExecution(new GroupingExecutor(),
- new ResultProvider(Arrays.asList(
- new GroupingListHit(List.of(pass0), null),
- new GroupingListHit(List.of(pass1), null))));
+ new ResultProvider(Arrays.asList(
+ new GroupingListHit(List.of(pass0), null),
+ new GroupingListHit(List.of(pass1), null))));
Result res = exec.search(query);
exec.fill(res);
- Hit hit = ((HitList)((Group)((GroupList)req.getResultGroup(res).get(0)).get(0)).get(0)).get(0);
+ Hit hit = ((HitList) ((Group) ((GroupList) req.getResultGroup(res).get(0)).get(0)).get(0)).get(0);
assertTrue(hit instanceof FastHit);
assertTrue(hit.isFilled(null));
}
@Test
- public void requireThatHitsAreAttachedToCorrectQuery() {
+ void requireThatHitsAreAttachedToCorrectQuery() {
Query queryA = newQuery();
GroupingRequest req = GroupingRequest.newInstance(queryA);
req.setRootOperation(GroupingOperation.fromString("all(group(foo) each(each(output(summary(bar)))))"));
@@ -460,24 +455,24 @@ public class GroupingExecutorTestCase {
Grouping grp = new Grouping(0);
grp.setRoot(new com.yahoo.searchlib.aggregation.Group()
.addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("foo"))
- .addAggregationResult(new HitsAggregationResult(1, "bar"))
- ));
+ .addAggregationResult(new HitsAggregationResult(1, "bar"))
+ ));
GroupingListHit pass0 = new GroupingListHit(List.of(grp), null);
GlobalId gid = new GlobalId((new DocumentId("id:ns:type::1")).getGlobalId());
grp = new Grouping(0);
grp.setRoot(new com.yahoo.searchlib.aggregation.Group()
.addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("foo"))
- .addAggregationResult(new HitsAggregationResult(1, "bar").addHit(new com.yahoo.searchlib.aggregation.FS4Hit(4, gid, 6)))
- ));
+ .addAggregationResult(new HitsAggregationResult(1, "bar").addHit(new com.yahoo.searchlib.aggregation.FS4Hit(4, gid, 6)))
+ ));
GroupingListHit pass1 = new GroupingListHit(List.of(grp), null);
Query queryB = newQuery(); // required by GroupingListHit.getSearchQuery()
pass1.setQuery(queryB);
QueryMapper qm = new QueryMapper();
Execution exec = newExecution(new GroupingExecutor(),
- new ResultProvider(Arrays.asList(pass0, pass1)),
- qm);
+ new ResultProvider(Arrays.asList(pass0, pass1)),
+ qm);
exec.fill(exec.search(queryA));
assertEquals(1, qm.hitsByQuery.size());
assertTrue(qm.hitsByQuery.containsKey(queryB));
@@ -488,7 +483,7 @@ public class GroupingExecutorTestCase {
* (triggered by the exc.search call in the below).
*/
@Test
- public void testRankProperties() {
+ void testRankProperties() {
final double delta = 0.000000001;
Execution exc = newExecution(new GroupingExecutor());
{
@@ -532,7 +527,7 @@ public class GroupingExecutorTestCase {
}
@Test
- public void testIllegalQuery() {
+ void testIllegalQuery() {
Execution exc = newExecution(new GroupingExecutor());
Query query = new Query();
@@ -541,14 +536,14 @@ public class GroupingExecutorTestCase {
Result result = exc.search(query);
com.yahoo.search.result.ErrorMessage message = result.hits().getError();
- assertNotNull("Got error", message);
+ assertNotNull(message, "Got error");
assertEquals("Illegal query", message.getMessage());
assertEquals("No query", message.getDetailedMessage());
assertEquals(3, message.getCode());
}
@Test
- public void testResultsFromMultipleDocumentTypes() {
+ void testResultsFromMultipleDocumentTypes() {
Query query = newQuery();
GroupingRequest request = GroupingRequest.newInstance(query);
request.setRootOperation(GroupingOperation.fromString("all(group(foo) each(output(min(bar), max(bar))))"));
@@ -556,38 +551,38 @@ public class GroupingExecutorTestCase {
Map<String, List<GroupingListHit>> resultsByDocumentType = new HashMap<>();
Grouping groupA1 = new Grouping(0);
groupA1.setRoot(new com.yahoo.searchlib.aggregation.Group()
- .addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("uniqueA")).addAggregationResult(new MaxAggregationResult().setMax(new IntegerResultNode(6)).setTag(4)))
- .addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("common")).addAggregationResult(new MaxAggregationResult().setMax(new IntegerResultNode(9)).setTag(4)))
+ .addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("uniqueA")).addAggregationResult(new MaxAggregationResult().setMax(new IntegerResultNode(6)).setTag(4)))
+ .addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("common")).addAggregationResult(new MaxAggregationResult().setMax(new IntegerResultNode(9)).setTag(4)))
);
Grouping groupA2 = new Grouping(0);
groupA2.setRoot(new com.yahoo.searchlib.aggregation.Group()
- .addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("uniqueB")).addAggregationResult(new MaxAggregationResult().setMax(new IntegerResultNode(9)).setTag(4)))
- .addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("common")).addAggregationResult(new MinAggregationResult().setMin(new IntegerResultNode(6)).setTag(3)))
+ .addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("uniqueB")).addAggregationResult(new MaxAggregationResult().setMax(new IntegerResultNode(9)).setTag(4)))
+ .addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("common")).addAggregationResult(new MinAggregationResult().setMin(new IntegerResultNode(6)).setTag(3)))
);
Grouping groupB1 = new Grouping(0);
groupB1.setRoot(new com.yahoo.searchlib.aggregation.Group()
- .addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("uniqueA")).addAggregationResult(new MaxAggregationResult().setMax(new IntegerResultNode(2)).setTag(4)))
- .addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("common")).addAggregationResult(new MaxAggregationResult().setMax(new IntegerResultNode(3)).setTag(4)))
+ .addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("uniqueA")).addAggregationResult(new MaxAggregationResult().setMax(new IntegerResultNode(2)).setTag(4)))
+ .addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("common")).addAggregationResult(new MaxAggregationResult().setMax(new IntegerResultNode(3)).setTag(4)))
);
Grouping groupB2 = new Grouping(0);
groupB2.setRoot(new com.yahoo.searchlib.aggregation.Group()
- .addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("uniqueC")).addAggregationResult(new MaxAggregationResult().setMax(new IntegerResultNode(7)).setTag(4)))
- .addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("common")).addAggregationResult(new MaxAggregationResult().setMax(new IntegerResultNode(11)).setTag(4)))
+ .addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("uniqueC")).addAggregationResult(new MaxAggregationResult().setMax(new IntegerResultNode(7)).setTag(4)))
+ .addChild(new com.yahoo.searchlib.aggregation.Group().setId(new StringResultNode("common")).addAggregationResult(new MaxAggregationResult().setMax(new IntegerResultNode(11)).setTag(4)))
);
resultsByDocumentType.put("typeA", List.of(new GroupingListHit(List.of(groupA1), null),
- new GroupingListHit(List.of(groupA2), null)));
+ new GroupingListHit(List.of(groupA2), null)));
resultsByDocumentType.put("typeB", List.of(new GroupingListHit(List.of(groupB1), null),
- new GroupingListHit(List.of(groupB2), null)));
+ new GroupingListHit(List.of(groupB2), null)));
Execution execution = newExecution(new GroupingExecutor(),
- new MockClusterSearcher(),
- new MultiDocumentTypeResultProvider(resultsByDocumentType));
+ new MockClusterSearcher(),
+ new MultiDocumentTypeResultProvider(resultsByDocumentType));
Result result = execution.search(query);
Group group = request.getResultGroup(result);
assertEquals(1, group.size());
Hit hit = group.get(0);
assertTrue(hit instanceof GroupList);
- GroupList list = (GroupList)hit;
+ GroupList list = (GroupList) hit;
assertEquals(4, list.size());
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/vespa/GroupingTransformTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/vespa/GroupingTransformTestCase.java
index c6503617da5..c41fb03f2f5 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/vespa/GroupingTransformTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/vespa/GroupingTransformTestCase.java
@@ -2,9 +2,9 @@
package com.yahoo.search.grouping.vespa;
import com.yahoo.search.grouping.Continuation;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -14,14 +14,14 @@ public class GroupingTransformTestCase {
private static final int REQUEST_ID = 0;
@Test
- public void requireThatLabelCanBeSet() {
+ void requireThatLabelCanBeSet() {
GroupingTransform transform = newTransform();
transform.putLabel(0, 1, "foo", "my_type");
assertEquals("foo", transform.getLabel(1));
}
@Test
- public void requireThatLabelCanNotBeReplaced() {
+ void requireThatLabelCanNotBeReplaced() {
GroupingTransform transform = newTransform();
transform.putLabel(0, 1, "foo", "my_type");
try {
@@ -29,12 +29,12 @@ public class GroupingTransformTestCase {
fail();
} catch (IllegalStateException e) {
assertEquals("Can not set label of my_type 1 to 'bar' because it is already set to 'foo'.",
- e.getMessage());
+ e.getMessage());
}
}
@Test
- public void requireThatLabelIsUniqueAmongSiblings() {
+ void requireThatLabelIsUniqueAmongSiblings() {
GroupingTransform transform = newTransform();
transform.putLabel(0, 1, "foo", "my_type");
try {
@@ -42,26 +42,26 @@ public class GroupingTransformTestCase {
fail();
} catch (UnsupportedOperationException e) {
assertEquals("Can not use my_type label 'foo' for multiple siblings.",
- e.getMessage());
+ e.getMessage());
}
}
@Test
- public void requireThatMaxDefaultsToZero() {
+ void requireThatMaxDefaultsToZero() {
GroupingTransform transform = newTransform();
assertEquals(0, transform.getMax(6));
assertEquals(0, transform.getMax(9));
}
@Test
- public void requireThatMaxCanBeSet() {
+ void requireThatMaxCanBeSet() {
GroupingTransform transform = newTransform();
transform.putMax(0, 69, "my_type");
assertEquals(69, transform.getMax(0));
}
@Test
- public void requireThatMaxCanNotBeReplaced() {
+ void requireThatMaxCanNotBeReplaced() {
GroupingTransform transform = newTransform();
transform.putMax(0, 6, "my_type");
try {
@@ -69,27 +69,27 @@ public class GroupingTransformTestCase {
fail();
} catch (IllegalStateException e) {
assertEquals("Can not set max of my_type 0 to 9 because it is already set to 6.",
- e.getMessage());
+ e.getMessage());
}
assertEquals(6, transform.getMax(0));
}
@Test
- public void requireThatOffsetDefaultsToZero() {
+ void requireThatOffsetDefaultsToZero() {
GroupingTransform transform = newTransform();
assertEquals(0, transform.getOffset(6));
assertEquals(0, transform.getOffset(9));
}
@Test
- public void requireThatOffsetContinuationsCanBeAdded() {
+ void requireThatOffsetContinuationsCanBeAdded() {
GroupingTransform transform = newTransform();
transform.addContinuation(newStableOffset(newResultId(), 6, 9));
assertEquals(9, transform.getOffset(6));
}
@Test
- public void requireThatOffsetByIdCanBeReplaced() {
+ void requireThatOffsetByIdCanBeReplaced() {
GroupingTransform transform = newTransform();
ResultId id = newResultId(6, 9);
transform.addContinuation(newStableOffset(id, 0, 6));
@@ -103,7 +103,7 @@ public class GroupingTransformTestCase {
}
@Test
- public void requireThatOffsetByTagEqualsHighestSibling() {
+ void requireThatOffsetByTagEqualsHighestSibling() {
GroupingTransform transform = newTransform();
transform.addContinuation(newStableOffset(newResultId(1), 69, 6));
assertEquals(6, transform.getOffset(69));
@@ -116,7 +116,7 @@ public class GroupingTransformTestCase {
}
@Test
- public void requireThatOffsetContinuationsCanBeReplaced() {
+ void requireThatOffsetContinuationsCanBeReplaced() {
GroupingTransform transform = newTransform();
ResultId id = newResultId(6, 9);
transform.addContinuation(newStableOffset(id, 1, 1));
@@ -136,7 +136,7 @@ public class GroupingTransformTestCase {
}
@Test
- public void requireThatUnstableOffsetsAreTracked() {
+ void requireThatUnstableOffsetsAreTracked() {
GroupingTransform transform = newTransform();
ResultId stableId = newResultId(6);
transform.addContinuation(newStableOffset(stableId, 1, 1));
@@ -148,17 +148,17 @@ public class GroupingTransformTestCase {
}
@Test
- public void requireThatCompositeContinuationsAreDecomposed() {
+ void requireThatCompositeContinuationsAreDecomposed() {
GroupingTransform transform = newTransform();
transform.addContinuation(new CompositeContinuation()
- .add(newStableOffset(newResultId(), 6, 9))
- .add(newStableOffset(newResultId(), 9, 6)));
+ .add(newStableOffset(newResultId(), 6, 9))
+ .add(newStableOffset(newResultId(), 9, 6)));
assertEquals(9, transform.getOffset(6));
assertEquals(6, transform.getOffset(9));
}
@Test
- public void requireThatUnsupportedContinuationsCanNotBeAdded() {
+ void requireThatUnsupportedContinuationsCanNotBeAdded() {
GroupingTransform transform = newTransform();
try {
transform.addContinuation(new Continuation() {
@@ -174,7 +174,7 @@ public class GroupingTransformTestCase {
}
@Test
- public void requireThatUnrelatedContinuationsAreIgnored() {
+ void requireThatUnrelatedContinuationsAreIgnored() {
GroupingTransform transform = new GroupingTransform(REQUEST_ID);
ResultId id = ResultId.valueOf(REQUEST_ID + 1, 1);
transform.addContinuation(new OffsetContinuation(id, 2, 3, OffsetContinuation.FLAG_UNSTABLE));
@@ -184,7 +184,7 @@ public class GroupingTransformTestCase {
}
@Test
- public void requireThatToStringIsVerbose() {
+ void requireThatToStringIsVerbose() {
GroupingTransform transform = new GroupingTransform(REQUEST_ID);
transform.putLabel(1, 1, "label1", "type1");
transform.putLabel(2, 2, "label2", "type2");
@@ -193,19 +193,19 @@ public class GroupingTransformTestCase {
transform.putMax(5, 5, "type5");
transform.putMax(6, 6, "type6");
assertEquals("groupingTransform {\n" +
- "\tlabels {\n" +
- "\t\t1 : label1\n" +
- "\t\t2 : label2\n" +
- "\t}\n" +
- "\toffsets {\n" +
- "\t\t3 : 3\n" +
- "\t\t4 : 4\n" +
- "\t}\n" +
- "\tmaxes {\n" +
- "\t\t5 : 5\n" +
- "\t\t6 : 6\n" +
- "\t}\n" +
- "}", transform.toString());
+ "\tlabels {\n" +
+ "\t\t1 : label1\n" +
+ "\t\t2 : label2\n" +
+ "\t}\n" +
+ "\toffsets {\n" +
+ "\t\t3 : 3\n" +
+ "\t\t4 : 4\n" +
+ "\t}\n" +
+ "\tmaxes {\n" +
+ "\t\t5 : 5\n" +
+ "\t\t6 : 6\n" +
+ "\t}\n" +
+ "}", transform.toString());
}
private static GroupingTransform newTransform() {
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/vespa/HitConverterTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/vespa/HitConverterTestCase.java
index b3afd8c5f50..5263583f771 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/vespa/HitConverterTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/vespa/HitConverterTestCase.java
@@ -17,11 +17,11 @@ import com.yahoo.search.schema.Schema;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.searchlib.aggregation.FS4Hit;
import com.yahoo.searchlib.aggregation.VdsHit;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -33,7 +33,7 @@ public class HitConverterTestCase {
}
@Test
- public void requireThatHitsAreConverted() {
+ void requireThatHitsAreConverted() {
HitConverter converter = new HitConverter(new MySearcher(), new Query());
Hit hit = converter.toSearchHit("default", new FS4Hit(1, createGlobalId(2), 3).setContext(context()));
assertNotNull(hit);
@@ -45,7 +45,7 @@ public class HitConverterTestCase {
}
@Test
- public void requireThatContextDataIsCopied() {
+ void requireThatContextDataIsCopied() {
Hit ctxHit = context();
ctxHit.setSource("69");
Query ctxQuery = new Query();
@@ -55,14 +55,14 @@ public class HitConverterTestCase {
Hit hit = converter.toSearchHit("default", new FS4Hit(1, createGlobalId(2), 3).setContext(ctxHit));
assertNotNull(hit);
assertTrue(hit instanceof FastHit);
- assertEquals(1, ((FastHit)hit).getPartId());
- assertEquals(createGlobalId(2), ((FastHit)hit).getGlobalId());
+ assertEquals(1, ((FastHit) hit).getPartId());
+ assertEquals(createGlobalId(2), ((FastHit) hit).getGlobalId());
assertSame(ctxQuery, hit.getQuery());
assertEquals(ctxHit.getSource(), hit.getSource());
}
@Test
- public void requireThatSummaryClassIsSet() {
+ void requireThatSummaryClassIsSet() {
Searcher searcher = new MySearcher();
HitConverter converter = new HitConverter(searcher, new Query());
Hit hit = converter.toSearchHit("69", new FS4Hit(1, createGlobalId(2), 3).setContext(context()));
@@ -72,7 +72,7 @@ public class HitConverterTestCase {
}
@Test
- public void requireThatHitHasContext() {
+ void requireThatHitHasContext() {
HitConverter converter = new HitConverter(new MySearcher(), new Query());
try {
converter.toSearchHit("69", new FS4Hit(1, createGlobalId(2), 3));
@@ -83,7 +83,7 @@ public class HitConverterTestCase {
}
@Test
- public void requireThatUnsupportedHitClassThrows() {
+ void requireThatUnsupportedHitClassThrows() {
HitConverter converter = new HitConverter(new MySearcher(), new Query());
try {
converter.toSearchHit("69", new com.yahoo.searchlib.aggregation.Hit() {
@@ -107,10 +107,10 @@ public class HitConverterTestCase {
}
@Test
- public void requireThatVdsHitCanBeConverted() {
+ void requireThatVdsHitCanBeConverted() {
HitConverter converter = new HitConverter(new MySearcher(), new Query());
GroupingListHit context = new GroupingListHit(null, sixtynine());
- VdsHit lowHit = new VdsHit("id:ns:type::", new byte[] { 0x55, 0x55, 0x55, 0x55 }, 1);
+ VdsHit lowHit = new VdsHit("id:ns:type::", new byte[]{0x55, 0x55, 0x55, 0x55}, 1);
lowHit.setContext(context);
Hit hit = converter.toSearchHit("69", lowHit);
assertNotNull(hit);
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/vespa/IntegerDecoderTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/vespa/IntegerDecoderTestCase.java
index 7d0827f0eb7..c574a99d2c0 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/vespa/IntegerDecoderTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/vespa/IntegerDecoderTestCase.java
@@ -1,10 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.grouping.vespa;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.*;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -12,7 +11,7 @@ import static org.junit.Assert.fail;
public class IntegerDecoderTestCase {
@Test
- public void requireThatIntDecoderWorksAsExpected() {
+ void requireThatIntDecoderWorksAsExpected() {
assertDecode("A", 0);
assertDecode("BC", 1);
assertDecode("CBI", 12);
@@ -29,7 +28,7 @@ public class IntegerDecoderTestCase {
}
@Test
- public void requireThatDecoderThrowsExceptionOnBadInput() {
+ void requireThatDecoderThrowsExceptionOnBadInput() {
try {
new IntegerDecoder("B").next();
fail();
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/vespa/IntegerEmbedderTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/vespa/IntegerEmbedderTestCase.java
index e7a4f1572c5..c644607b3ae 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/vespa/IntegerEmbedderTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/vespa/IntegerEmbedderTestCase.java
@@ -1,9 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.grouping.vespa;
-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 Simon Thoresen Hult
@@ -11,7 +11,7 @@ import static org.junit.Assert.assertEquals;
public class IntegerEmbedderTestCase {
@Test
- public void requireThatIntEncoderWorksAsExpected() {
+ void requireThatIntEncoderWorksAsExpected() {
assertEncode("A", 0);
assertEncode("BC", 1);
assertEncode("CBI", 12);
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/vespa/OffsetContinuationTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/vespa/OffsetContinuationTestCase.java
index 7242e5ba054..513f8c89f05 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/vespa/OffsetContinuationTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/vespa/OffsetContinuationTestCase.java
@@ -2,9 +2,9 @@
package com.yahoo.search.grouping.vespa;
import com.yahoo.search.grouping.Continuation;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -12,7 +12,7 @@ import static org.junit.Assert.*;
public class OffsetContinuationTestCase {
@Test
- public void requireThatNullResultIdThrowsException() {
+ void requireThatNullResultIdThrowsException() {
try {
new OffsetContinuation(null, 0, 0, 0);
fail();
@@ -22,7 +22,7 @@ public class OffsetContinuationTestCase {
}
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
OffsetContinuation cnt = new OffsetContinuation(ResultId.valueOf(1), 2, 3, 4);
assertEquals(ResultId.valueOf(1), cnt.getResultId());
assertEquals(2, cnt.getTag());
@@ -44,7 +44,7 @@ public class OffsetContinuationTestCase {
}
@Test
- public void requireThatOffsetContinuationsCanBeEncoded() {
+ void requireThatOffsetContinuationsCanBeEncoded() {
assertEncode("BCBCBCBEBG", newOffset(1, 1, 2, 3));
assertEncode("BCBKCBACBKCCK", newOffset(5, 8, 13, 21));
assertEncode("BCBBBBBDBF", newOffset(-1, -1, -2, -3));
@@ -52,7 +52,7 @@ public class OffsetContinuationTestCase {
}
@Test
- public void requireThatOffsetContinuationsCanBeDecoded() {
+ void requireThatOffsetContinuationsCanBeDecoded() {
assertDecode("BCBCBCBEBG", newOffset(1, 1, 2, 3));
assertDecode("BCBKCBACBKCCK", newOffset(5, 8, 13, 21));
assertDecode("BCBBBBBDBF", newOffset(-1, -1, -2, -3));
@@ -60,18 +60,18 @@ public class OffsetContinuationTestCase {
}
@Test
- public void requireThatHashCodeIsImplemented() {
+ void requireThatHashCodeIsImplemented() {
assertEquals(newOffset(1, 1, 2, 3).hashCode(), newOffset(1, 1, 2, 3).hashCode());
}
@Test
- public void requireThatEqualsIsImplemented() {
+ void requireThatEqualsIsImplemented() {
Continuation cnt = newOffset(1, 1, 2, 3);
- assertFalse(cnt.equals(new Object()));
- assertFalse(cnt.equals(newOffset(0, 1, 2, 3)));
- assertFalse(cnt.equals(newOffset(1, 0, 2, 3)));
- assertFalse(cnt.equals(newOffset(1, 1, 0, 3)));
- assertFalse(cnt.equals(newOffset(1, 1, 2, 0)));
+ assertNotEquals(cnt, new Object());
+ assertNotEquals(cnt, newOffset(0, 1, 2, 3));
+ assertNotEquals(cnt, newOffset(1, 0, 2, 3));
+ assertNotEquals(cnt, newOffset(1, 1, 0, 3));
+ assertNotEquals(cnt, newOffset(1, 1, 2, 0));
assertEquals(cnt, newOffset(1, 1, 2, 3));
}
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/vespa/RequestBuilderTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/vespa/RequestBuilderTestCase.java
index 5882c56c688..f8e67a10076 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/vespa/RequestBuilderTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/vespa/RequestBuilderTestCase.java
@@ -26,7 +26,7 @@ import com.yahoo.searchlib.expression.StringResultNode;
import com.yahoo.searchlib.expression.TimeStampFunctionNode;
import com.yahoo.searchlib.expression.ToStringFunctionNode;
import org.assertj.core.api.Assertions;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
@@ -34,9 +34,7 @@ import java.util.LinkedList;
import java.util.List;
import java.util.TimeZone;
-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
@@ -44,19 +42,19 @@ import static org.junit.Assert.fail;
public class RequestBuilderTestCase {
@Test
- public void requireThatAllAggregationResulsAreSupported() {
- assertLayout("all(group(a) each(output(avg(b))))", "[[{ Attribute, result = [Average] }]]");
- assertLayout("all(group(a) each(output(count())))", "[[{ Attribute, result = [Count] }]]");
- assertLayout("all(group(a) each(output(max(b))))", "[[{ Attribute, result = [Max] }]]");
- assertLayout("all(group(a) each(output(min(b))))", "[[{ Attribute, result = [Min] }]]");
- assertLayout("all(group(a) each(output(sum(b))))", "[[{ Attribute, result = [Sum] }]]");
- assertLayout("all(group(a) each(each(output(summary()))))", "[[{ Attribute, result = [Hits] }]]");
- assertLayout("all(group(a) each(output(xor(b))))", "[[{ Attribute, result = [Xor] }]]");
- assertLayout("all(group(a) each(output(stddev(b))))", "[[{ Attribute, result = [StandardDeviation] }]]");
+ void requireThatAllAggregationResulsAreSupported() {
+ assertLayout("all(group(a) each(output(avg(b))))", "[[{ Attribute, result = [Average] }]]");
+ assertLayout("all(group(a) each(output(count())))", "[[{ Attribute, result = [Count] }]]");
+ assertLayout("all(group(a) each(output(max(b))))", "[[{ Attribute, result = [Max] }]]");
+ assertLayout("all(group(a) each(output(min(b))))", "[[{ Attribute, result = [Min] }]]");
+ assertLayout("all(group(a) each(output(sum(b))))", "[[{ Attribute, result = [Sum] }]]");
+ assertLayout("all(group(a) each(each(output(summary()))))", "[[{ Attribute, result = [Hits] }]]");
+ assertLayout("all(group(a) each(output(xor(b))))", "[[{ Attribute, result = [Xor] }]]");
+ assertLayout("all(group(a) each(output(stddev(b))))", "[[{ Attribute, result = [StandardDeviation] }]]");
}
@Test
- public void requireThatExpressionCountAggregationResultIsSupported() {
+ void requireThatExpressionCountAggregationResultIsSupported() {
RequestBuilder builder = new RequestBuilder(0);
builder.setRootOperation(GroupingOperation.fromString("all(group(foo) output(count()))"));
builder.build();
@@ -73,28 +71,28 @@ public class RequestBuilderTestCase {
}
@Test
- public void requireThatTopNIsHonoured() {
+ void requireThatTopNIsHonoured() {
List<Grouping> gl = getRequestList("all(max(3) all(group(product_id) max(5) each(output(sum(price)))))");
assertEquals(1, gl.size());
assertEquals(3, gl.get(0).getTopN());
}
@Test
- public void requireThatTopNIsHonouredWhenNested() {
+ void requireThatTopNIsHonouredWhenNested() {
List<Grouping> gl = getRequestList("all( all(max(3) all(group(product_id) max(5) each(output(sum(price))))))");
assertEquals(1, gl.size());
assertEquals(3, gl.get(0).getTopN());
}
@Test
- public void requireThatTopNIsInherited() {
+ void requireThatTopNIsInherited() {
List<Grouping> gl = getRequestList("all(max(7) all( all(group(product_id) max(5) each(output(sum(price))))))");
assertEquals(1, gl.size());
assertEquals(7, gl.get(0).getTopN());
}
@Test
- public void requireThatTopNIsMinimum() {
+ void requireThatTopNIsMinimum() {
List<Grouping> gl = getRequestList("all(max(7) all(max(3) all(group(product_id) max(5) each(output(sum(price))))))");
assertEquals(1, gl.size());
assertEquals(3, gl.get(0).getTopN());
@@ -104,7 +102,7 @@ public class RequestBuilderTestCase {
}
@Test
- public void requireThatTopNIsIndividual() {
+ void requireThatTopNIsIndividual() {
List<Grouping> gl = getRequestList("all( all(max(3) all(group(product_id) max(5) each(output(sum(price))))) all(group(filter_cluster3) order(count()) each(output(count()))))");
assertEquals(2, gl.size());
assertEquals(3, gl.get(0).getTopN());
@@ -117,7 +115,7 @@ public class RequestBuilderTestCase {
}
@Test
- public void requireThatAllExpressionNodesAreSupported() {
+ void requireThatAllExpressionNodesAreSupported() {
assertLayout("all(group(add(a,b)) each(output(count())))", "[[{ Add, result = [Count] }]]");
assertLayout("all(group(and(a,b)) each(output(count())))", "[[{ And, result = [Count] }]]");
assertLayout("all(group(a) each(output(count())))", "[[{ Attribute, result = [Count] }]]");
@@ -188,22 +186,22 @@ public class RequestBuilderTestCase {
}
@Test
- public void requireThatForceSinglePassIsSupported() {
+ void requireThatForceSinglePassIsSupported() {
assertForceSinglePass("all(group(foo) each(output(count())))", "[false]");
assertForceSinglePass("all(group(foo) hint(singlepass) each(output(count())))", "[true]");
assertForceSinglePass("all(hint(singlepass) " +
- " all(group(foo) each(output(count())))" +
- " all(group(bar) each(output(count()))))",
- "[true, true]");
+ " all(group(foo) each(output(count())))" +
+ " all(group(bar) each(output(count()))))",
+ "[true, true]");
// it would be really nice if this test returned [true, true], but that is not how the AST is built
assertForceSinglePass("all(all(group(foo) hint(singlepass) each(output(count())))" +
- " all(group(bar) hint(singlepass) each(output(count()))))",
- "[false, false]");
+ " all(group(bar) hint(singlepass) each(output(count()))))",
+ "[false, false]");
}
@Test
- public void requireThatThereCanBeOnlyOneBuildCall() {
+ void requireThatThereCanBeOnlyOneBuildCall() {
RequestBuilder builder = new RequestBuilder(0);
builder.setRootOperation(GroupingOperation.fromString("all(group(foo) each(output(count())))"));
builder.build();
@@ -216,148 +214,148 @@ public class RequestBuilderTestCase {
}
@Test
- public void requireThatNullSummaryClassProvidesDefault() {
+ void requireThatNullSummaryClassProvidesDefault() {
RequestBuilder reqBuilder = new RequestBuilder(0);
reqBuilder.setRootOperation(new AllOperation()
- .setGroupBy(new AttributeValue("foo"))
- .addChild(new EachOperation()
- .addChild(new EachOperation()
- .addOutput(new SummaryValue()))));
+ .setGroupBy(new AttributeValue("foo"))
+ .addChild(new EachOperation()
+ .addChild(new EachOperation()
+ .addOutput(new SummaryValue()))));
reqBuilder.setDefaultSummaryName(null);
reqBuilder.build();
- HitsAggregationResult hits = (HitsAggregationResult)reqBuilder.getRequestList().get(0)
- .getLevels().get(0)
- .getGroupPrototype()
- .getAggregationResults().get(0);
+ HitsAggregationResult hits = (HitsAggregationResult) reqBuilder.getRequestList().get(0)
+ .getLevels().get(0)
+ .getGroupPrototype()
+ .getAggregationResults().get(0);
assertEquals(ExpressionConverter.DEFAULT_SUMMARY_NAME, hits.getSummaryClass());
}
@Test
- public void requireThatGroupOfGroupsAreNotSupported() {
+ void requireThatGroupOfGroupsAreNotSupported() {
// "Can not group list of groups."
assertBuildFail("all(group(a) all(group(avg(b)) each(each(each(output(summary()))))))",
"Can not operate on list of list of groups.");
}
@Test
- public void requireThatAnonymousListsAreNotSupported() {
+ void requireThatAnonymousListsAreNotSupported() {
assertBuildFail("all(group(a) all(each(each(output(summary())))))",
- "Can not create anonymous list of groups.");
+ "Can not create anonymous list of groups.");
}
@Test
- public void requireThatOffsetContinuationCanModifyGroupingLevel() {
+ void requireThatOffsetContinuationCanModifyGroupingLevel() {
assertOffset("all(group(a) max(5) each(output(count())))",
- newOffset(2, 5),
- "[[{ tag = 2, max = [5, 11], hits = [] }]]");
+ newOffset(2, 5),
+ "[[{ tag = 2, max = [5, 11], hits = [] }]]");
assertOffset("all(group(a) max(5) each(output(count())) as(foo)" +
- " each(output(count())) as(bar))",
- newOffset(2, 5),
- "[[{ tag = 2, max = [5, 11], hits = [] }]," +
- " [{ tag = 4, max = [5, 6], hits = [] }]]");
+ " each(output(count())) as(bar))",
+ newOffset(2, 5),
+ "[[{ tag = 2, max = [5, 11], hits = [] }]," +
+ " [{ tag = 4, max = [5, 6], hits = [] }]]");
assertOffset("all(group(a) max(5) each(output(count())) as(foo)" +
- " each(output(count())) as(bar))",
+ " each(output(count())) as(bar))",
newComposite(newOffset(2, 5), newOffset(4, 10)),
"[[{ tag = 2, max = [5, 11], hits = [] }]," +
" [{ tag = 4, max = [5, 16], hits = [] }]]");
}
@Test
- public void requireThatOffsetContinuationCanModifyHitAggregator() {
+ void requireThatOffsetContinuationCanModifyHitAggregator() {
assertOffset("all(group(a) each(max(5) each(output(summary()))))",
- newOffset(3, 5),
- "[[{ tag = 2, max = [0, -1], hits = [{ tag = 3, max = [5, 11] }] }]]");
+ newOffset(3, 5),
+ "[[{ tag = 2, max = [0, -1], hits = [{ tag = 3, max = [5, 11] }] }]]");
assertOffset("all(group(a) each(max(5) each(output(summary()))) as(foo)" +
- " each(max(5) each(output(summary()))) as(bar))",
- newOffset(3, 5),
- "[[{ tag = 2, max = [0, -1], hits = [{ tag = 3, max = [5, 11] }] }]," +
- " [{ tag = 4, max = [0, -1], hits = [{ tag = 5, max = [5, 6] }] }]]");
+ " each(max(5) each(output(summary()))) as(bar))",
+ newOffset(3, 5),
+ "[[{ tag = 2, max = [0, -1], hits = [{ tag = 3, max = [5, 11] }] }]," +
+ " [{ tag = 4, max = [0, -1], hits = [{ tag = 5, max = [5, 6] }] }]]");
assertOffset("all(group(a) each(max(5) each(output(summary()))) as(foo)" +
- " each(max(5) each(output(summary()))) as(bar))",
- newComposite(newOffset(3, 5), newOffset(5, 10)),
- "[[{ tag = 2, max = [0, -1], hits = [{ tag = 3, max = [5, 11] }] }]," +
- " [{ tag = 4, max = [0, -1], hits = [{ tag = 5, max = [5, 16] }] }]]");
+ " each(max(5) each(output(summary()))) as(bar))",
+ newComposite(newOffset(3, 5), newOffset(5, 10)),
+ "[[{ tag = 2, max = [0, -1], hits = [{ tag = 3, max = [5, 11] }] }]," +
+ " [{ tag = 4, max = [0, -1], hits = [{ tag = 5, max = [5, 16] }] }]]");
}
@Test
- public void requireThatOffsetContinuationIsNotAppliedToGroupingLevelWithoutMax() {
+ void requireThatOffsetContinuationIsNotAppliedToGroupingLevelWithoutMax() {
assertOffset("all(group(a) each(output(count())))",
- newOffset(2, 5),
- "[[{ tag = 2, max = [0, -1], hits = [] }]]");
+ newOffset(2, 5),
+ "[[{ tag = 2, max = [0, -1], hits = [] }]]");
}
@Test
- public void requireThatOffsetContinuationIsNotAppliedToHitAggregatorWithoutMax() {
+ void requireThatOffsetContinuationIsNotAppliedToHitAggregatorWithoutMax() {
assertOffset("all(group(a) each(each(output(summary()))))",
- newOffset(3, 5),
- "[[{ tag = 2, max = [0, -1], hits = [{ tag = 3, max = [0, -1] }] }]]");
+ newOffset(3, 5),
+ "[[{ tag = 2, max = [0, -1], hits = [{ tag = 3, max = [0, -1] }] }]]");
}
@Test
- public void requireThatUnstableContinuationsDoNotAffectRequestedGroupLists() {
+ void requireThatUnstableContinuationsDoNotAffectRequestedGroupLists() {
String request = "all(group(a) max(5) each(group(b) max(5) each(output(count())) as(a1_b1)" +
- " each(output(count())) as(a1_b2)) as(a1)" +
- " each(group(b) max(5) each(output(count())) as(a2_b1)" +
- " each(output(count())) as(a2_b2)) as(a2))";
+ " each(output(count())) as(a1_b2)) as(a1)" +
+ " each(group(b) max(5) each(output(count())) as(a2_b1)" +
+ " each(output(count())) as(a2_b2)) as(a2))";
CompositeContinuation session = newComposite(newOffset(2, 5), newOffset(3, 5), newOffset(5, 5),
- newOffset(7, 5), newOffset(8, 5), newOffset(10, 5));
+ newOffset(7, 5), newOffset(8, 5), newOffset(10, 5));
assertOffset(request, newComposite(session),
- "[[{ tag = 2, max = [5, 11], hits = [] }, { tag = 3, max = [5, 11], hits = [] }]," +
- " [{ tag = 2, max = [5, 11], hits = [] }, { tag = 5, max = [5, 11], hits = [] }]," +
- " [{ tag = 7, max = [5, 11], hits = [] }, { tag = 10, max = [5, 11], hits = [] }]," +
- " [{ tag = 7, max = [5, 11], hits = [] }, { tag = 8, max = [5, 11], hits = [] }]]");
+ "[[{ tag = 2, max = [5, 11], hits = [] }, { tag = 3, max = [5, 11], hits = [] }]," +
+ " [{ tag = 2, max = [5, 11], hits = [] }, { tag = 5, max = [5, 11], hits = [] }]," +
+ " [{ tag = 7, max = [5, 11], hits = [] }, { tag = 10, max = [5, 11], hits = [] }]," +
+ " [{ tag = 7, max = [5, 11], hits = [] }, { tag = 8, max = [5, 11], hits = [] }]]");
assertOffset(request, newComposite(session, newUnstableOffset(2, 10)),
- "[[{ tag = 2, max = [5, 16], hits = [] }, { tag = 3, max = [5, 11], hits = [] }]," +
- " [{ tag = 2, max = [5, 16], hits = [] }, { tag = 5, max = [5, 11], hits = [] }]," +
- " [{ tag = 7, max = [5, 11], hits = [] }, { tag = 10, max = [5, 11], hits = [] }]," +
- " [{ tag = 7, max = [5, 11], hits = [] }, { tag = 8, max = [5, 11], hits = [] }]]");
+ "[[{ tag = 2, max = [5, 16], hits = [] }, { tag = 3, max = [5, 11], hits = [] }]," +
+ " [{ tag = 2, max = [5, 16], hits = [] }, { tag = 5, max = [5, 11], hits = [] }]," +
+ " [{ tag = 7, max = [5, 11], hits = [] }, { tag = 10, max = [5, 11], hits = [] }]," +
+ " [{ tag = 7, max = [5, 11], hits = [] }, { tag = 8, max = [5, 11], hits = [] }]]");
assertOffset(request, newComposite(session, newUnstableOffset(7, 10)),
- "[[{ tag = 2, max = [5, 11], hits = [] }, { tag = 3, max = [5, 11], hits = [] }]," +
- " [{ tag = 2, max = [5, 11], hits = [] }, { tag = 5, max = [5, 11], hits = [] }]," +
- " [{ tag = 7, max = [5, 16], hits = [] }, { tag = 10, max = [5, 11], hits = [] }]," +
- " [{ tag = 7, max = [5, 16], hits = [] }, { tag = 8, max = [5, 11], hits = [] }]]");
+ "[[{ tag = 2, max = [5, 11], hits = [] }, { tag = 3, max = [5, 11], hits = [] }]," +
+ " [{ tag = 2, max = [5, 11], hits = [] }, { tag = 5, max = [5, 11], hits = [] }]," +
+ " [{ tag = 7, max = [5, 16], hits = [] }, { tag = 10, max = [5, 11], hits = [] }]," +
+ " [{ tag = 7, max = [5, 16], hits = [] }, { tag = 8, max = [5, 11], hits = [] }]]");
assertOffset(request, newComposite(session, newUnstableOffset(2, 10), newUnstableOffset(7, 10)),
- "[[{ tag = 2, max = [5, 16], hits = [] }, { tag = 3, max = [5, 11], hits = [] }]," +
- " [{ tag = 2, max = [5, 16], hits = [] }, { tag = 5, max = [5, 11], hits = [] }]," +
- " [{ tag = 7, max = [5, 16], hits = [] }, { tag = 10, max = [5, 11], hits = [] }]," +
- " [{ tag = 7, max = [5, 16], hits = [] }, { tag = 8, max = [5, 11], hits = [] }]]");
+ "[[{ tag = 2, max = [5, 16], hits = [] }, { tag = 3, max = [5, 11], hits = [] }]," +
+ " [{ tag = 2, max = [5, 16], hits = [] }, { tag = 5, max = [5, 11], hits = [] }]," +
+ " [{ tag = 7, max = [5, 16], hits = [] }, { tag = 10, max = [5, 11], hits = [] }]," +
+ " [{ tag = 7, max = [5, 16], hits = [] }, { tag = 8, max = [5, 11], hits = [] }]]");
}
@Test
- public void requireThatUnstableContinuationsDoNotAffectRequestedHitLists() {
+ void requireThatUnstableContinuationsDoNotAffectRequestedHitLists() {
String request = "all(group(a) max(5) each(max(5) each(output(summary())) as(a1_h1)" +
- " each(output(summary())) as(a1_h2)) as(a1)" +
- " each(max(5) each(output(summary())) as(a2_h1)" +
- " each(output(summary())) as(a2_h2)) as(a2))";
+ " each(output(summary())) as(a1_h2)) as(a1)" +
+ " each(max(5) each(output(summary())) as(a2_h1)" +
+ " each(output(summary())) as(a2_h2)) as(a2))";
CompositeContinuation session = newComposite(newOffset(2, 5), newOffset(3, 5), newOffset(4, 5),
- newOffset(5, 5), newOffset(6, 5), newOffset(7, 5));
+ newOffset(5, 5), newOffset(6, 5), newOffset(7, 5));
assertOffset(request, newComposite(session),
- "[[{ tag = 2, max = [5, 11], hits = [{ tag = 3, max = [5, 11] }] }]," +
- " [{ tag = 2, max = [5, 11], hits = [{ tag = 4, max = [5, 11] }] }]," +
- " [{ tag = 5, max = [5, 11], hits = [{ tag = 6, max = [5, 11] }] }]," +
- " [{ tag = 5, max = [5, 11], hits = [{ tag = 7, max = [5, 11] }] }]]");
+ "[[{ tag = 2, max = [5, 11], hits = [{ tag = 3, max = [5, 11] }] }]," +
+ " [{ tag = 2, max = [5, 11], hits = [{ tag = 4, max = [5, 11] }] }]," +
+ " [{ tag = 5, max = [5, 11], hits = [{ tag = 6, max = [5, 11] }] }]," +
+ " [{ tag = 5, max = [5, 11], hits = [{ tag = 7, max = [5, 11] }] }]]");
assertOffset(request, newComposite(session, newUnstableOffset(2, 10)),
- "[[{ tag = 2, max = [5, 16], hits = [{ tag = 3, max = [5, 11] }] }]," +
- " [{ tag = 2, max = [5, 16], hits = [{ tag = 4, max = [5, 11] }] }]," +
- " [{ tag = 5, max = [5, 11], hits = [{ tag = 6, max = [5, 11] }] }]," +
- " [{ tag = 5, max = [5, 11], hits = [{ tag = 7, max = [5, 11] }] }]]");
+ "[[{ tag = 2, max = [5, 16], hits = [{ tag = 3, max = [5, 11] }] }]," +
+ " [{ tag = 2, max = [5, 16], hits = [{ tag = 4, max = [5, 11] }] }]," +
+ " [{ tag = 5, max = [5, 11], hits = [{ tag = 6, max = [5, 11] }] }]," +
+ " [{ tag = 5, max = [5, 11], hits = [{ tag = 7, max = [5, 11] }] }]]");
assertOffset(request, newComposite(session, newUnstableOffset(5, 10)),
- "[[{ tag = 2, max = [5, 11], hits = [{ tag = 3, max = [5, 11] }] }]," +
- " [{ tag = 2, max = [5, 11], hits = [{ tag = 4, max = [5, 11] }] }]," +
- " [{ tag = 5, max = [5, 16], hits = [{ tag = 6, max = [5, 11] }] }]," +
- " [{ tag = 5, max = [5, 16], hits = [{ tag = 7, max = [5, 11] }] }]]");
+ "[[{ tag = 2, max = [5, 11], hits = [{ tag = 3, max = [5, 11] }] }]," +
+ " [{ tag = 2, max = [5, 11], hits = [{ tag = 4, max = [5, 11] }] }]," +
+ " [{ tag = 5, max = [5, 16], hits = [{ tag = 6, max = [5, 11] }] }]," +
+ " [{ tag = 5, max = [5, 16], hits = [{ tag = 7, max = [5, 11] }] }]]");
assertOffset(request, newComposite(session, newUnstableOffset(2, 10), newUnstableOffset(5, 10)),
- "[[{ tag = 2, max = [5, 16], hits = [{ tag = 3, max = [5, 11] }] }]," +
- " [{ tag = 2, max = [5, 16], hits = [{ tag = 4, max = [5, 11] }] }]," +
- " [{ tag = 5, max = [5, 16], hits = [{ tag = 6, max = [5, 11] }] }]," +
- " [{ tag = 5, max = [5, 16], hits = [{ tag = 7, max = [5, 11] }] }]]");
+ "[[{ tag = 2, max = [5, 16], hits = [{ tag = 3, max = [5, 11] }] }]," +
+ " [{ tag = 2, max = [5, 16], hits = [{ tag = 4, max = [5, 11] }] }]," +
+ " [{ tag = 5, max = [5, 16], hits = [{ tag = 6, max = [5, 11] }] }]," +
+ " [{ tag = 5, max = [5, 16], hits = [{ tag = 7, max = [5, 11] }] }]]");
}
@Test
- public void requireThatExpressionsCanBeAliased() {
+ void requireThatExpressionsCanBeAliased() {
OutputWriter writer = (groupingList, transform) -> groupingList.get(0).getLevels().get(0).getGroupPrototype().getAggregationResults().get(0)
- .toString();
+ .toString();
RequestTest test = new RequestTest();
test.expectedOutput = new SumAggregationResult().setTag(3).setExpression(new AttributeNode("price")).toString();
@@ -373,89 +371,89 @@ public class RequestBuilderTestCase {
}
@Test
- public void requireThatGroupingLayoutIsCorrect() {
+ void requireThatGroupingLayoutIsCorrect() {
assertLayout("all(group(artist) each(max(69) output(count()) each(output(summary()))))",
- "[[{ Attribute, result = [Count, Hits] }]]");
+ "[[{ Attribute, result = [Count, Hits] }]]");
assertLayout("all(group(artist) each(output(count()) all(group(album) each(output(count()) all(group(song) each(max(69) output(count()) each(output(summary()))))))))",
- "[[{ Attribute, result = [Count] }, { Attribute, result = [Count] }, { Attribute, result = [Count, Hits] }]]");
+ "[[{ Attribute, result = [Count] }, { Attribute, result = [Count] }, { Attribute, result = [Count, Hits] }]]");
assertLayout("all(group(artist) each(output(count())))",
- "[[{ Attribute, result = [Count] }]]");
+ "[[{ Attribute, result = [Count] }]]");
assertLayout("all(group(artist) order(sum(price)) each(output(count())))",
- "[[{ Attribute, result = [Count, Sum], order = [[1], [AggregationRef]] }]]");
+ "[[{ Attribute, result = [Count, Sum], order = [[1], [AggregationRef]] }]]");
assertLayout("all(group(artist) each(max(69) output(count()) each(output(summary(foo)))))",
- "[[{ Attribute, result = [Count, Hits] }]]");
+ "[[{ Attribute, result = [Count, Hits] }]]");
assertLayout("all(group(artist) each(output(count()) all(group(album) each(output(count())))))",
- "[[{ Attribute, result = [Count] }, { Attribute, result = [Count] }]]");
+ "[[{ Attribute, result = [Count] }, { Attribute, result = [Count] }]]");
assertLayout("all(group(artist) max(5) each(output(count()) all(group(album) max(3) each(output(count())))))",
- "[[{ Attribute, max = [6, 6], result = [Count] }, { Attribute, max = [4, 4], result = [Count] }]]");
+ "[[{ Attribute, max = [6, 6], result = [Count] }, { Attribute, max = [4, 4], result = [Count] }]]");
assertLayout("all(group(artist) max(5) each(output(count()) all(group(album) max(3) each(output(count())))))",
- "[[{ Attribute, max = [6, 6], result = [Count] }, { Attribute, max = [4, 4], result = [Count] }]]");
+ "[[{ Attribute, max = [6, 6], result = [Count] }, { Attribute, max = [4, 4], result = [Count] }]]");
assertLayout("all(group(foo) max(10) each(output(count()) all(group(bar) max(10) each(output(count())))))",
- "[[{ Attribute, max = [11, 11], result = [Count] }, { Attribute, max = [11, 11], result = [Count] }]]");
+ "[[{ Attribute, max = [11, 11], result = [Count] }, { Attribute, max = [11, 11], result = [Count] }]]");
assertLayout("all(group(a) max(5) each(max(69) output(count()) each(output(summary()))))",
- "[[{ Attribute, max = [6, 6], result = [Count, Hits] }]]");
+ "[[{ Attribute, max = [6, 6], result = [Count, Hits] }]]");
assertLayout("all(group(a) max(5) each(output(count()) all(group(b) max(5) each(max(69) output(count()) each(output(summary()))))))",
- "[[{ Attribute, max = [6, 6], result = [Count] }, { Attribute, max = [6, 6], result = [Count, Hits] }]]");
+ "[[{ Attribute, max = [6, 6], result = [Count] }, { Attribute, max = [6, 6], result = [Count, Hits] }]]");
assertLayout("all(group(a) max(5) each(output(count()) all(group(b) max(5) each(output(count()) all(group(c) max(5) each(max(69) output(count()) each(output(summary()))))))))",
- "[[{ Attribute, max = [6, 6], result = [Count] }, { Attribute, max = [6, 6], result = [Count] }, { Attribute, max = [6, 6], result = [Count, Hits] }]]");
+ "[[{ Attribute, max = [6, 6], result = [Count] }, { Attribute, max = [6, 6], result = [Count] }, { Attribute, max = [6, 6], result = [Count, Hits] }]]");
assertLayout("all(group(fixedwidth(n,3)) max(5) each(output(count()) all(group(a) max(2) each(output(count())))))",
- "[[{ FixedWidthBucket, max = [6, 6], result = [Count] }, { Attribute, max = [3, 3], result = [Count] }]]");
+ "[[{ FixedWidthBucket, max = [6, 6], result = [Count] }, { Attribute, max = [3, 3], result = [Count] }]]");
assertLayout("all(group(fixedwidth(n,3)) max(5) each(output(count()) all(group(a) max(2) each(output(count())))))",
- "[[{ FixedWidthBucket, max = [6, 6], result = [Count] }, { Attribute, max = [3, 3], result = [Count] }]]");
+ "[[{ FixedWidthBucket, max = [6, 6], result = [Count] }, { Attribute, max = [3, 3], result = [Count] }]]");
assertLayout("all(group(fixedwidth(n,3)) max(5) each(output(count()) all(group(a) max(2) each(max(1) output(count()) each(output(summary()))))))",
- "[[{ FixedWidthBucket, max = [6, 6], result = [Count] }, { Attribute, max = [3, 3], result = [Count, Hits] }]]");
+ "[[{ FixedWidthBucket, max = [6, 6], result = [Count] }, { Attribute, max = [3, 3], result = [Count, Hits] }]]");
assertLayout("all(group(predefined(n,bucket(1,3),bucket(6,9))) each(output(count())))",
- "[[{ RangeBucketPreDef, result = [Count] }]]");
+ "[[{ RangeBucketPreDef, result = [Count] }]]");
assertLayout("all(group(predefined(f,bucket(1.0,3.0),bucket(6.0,9.0))) each(output(count())))",
- "[[{ RangeBucketPreDef, result = [Count] }]]");
+ "[[{ RangeBucketPreDef, result = [Count] }]]");
assertLayout("all(group(predefined(s,bucket(\"ab\",\"cd\"),bucket(\"ef\",\"gh\"))) each(output(count())))",
- "[[{ RangeBucketPreDef, result = [Count] }]]");
+ "[[{ RangeBucketPreDef, result = [Count] }]]");
assertLayout("all(group(a) max(5) each(output(count())))",
- "[[{ Attribute, max = [6, 6], result = [Count] }]]");
+ "[[{ Attribute, max = [6, 6], result = [Count] }]]");
assertLayout("all(group(a) max(5) each(output(count())))",
- "[[{ Attribute, max = [6, 6], result = [Count] }]]");
+ "[[{ Attribute, max = [6, 6], result = [Count] }]]");
assertLayout("all(max(9) all(group(a) each(output(count()))))",
- "[[{ Attribute, result = [Count] }]]");
+ "[[{ Attribute, result = [Count] }]]");
assertLayout("all(where(true) all(group(a) each(output(count()))))",
- "[[{ Attribute, result = [Count] }]]");
+ "[[{ Attribute, result = [Count] }]]");
assertLayout("all(group(a) order(sum(n)) each(output(count())))",
- "[[{ Attribute, result = [Count, Sum], order = [[1], [AggregationRef]] }]]");
+ "[[{ Attribute, result = [Count, Sum], order = [[1], [AggregationRef]] }]]");
assertLayout("all(group(a) max(2) each(output(count())))",
- "[[{ Attribute, max = [3, 3], result = [Count] }]]");
+ "[[{ Attribute, max = [3, 3], result = [Count] }]]");
assertLayout("all(group(a) max(2) precision(10) each(output(count())))",
- "[[{ Attribute, max = [3, 10], result = [Count] }]]");
+ "[[{ Attribute, max = [3, 10], result = [Count] }]]");
assertLayout("all(group(fixedwidth(a,1)) each(output(count())))",
- "[[{ FixedWidthBucket, result = [Count] }]]");
+ "[[{ FixedWidthBucket, result = [Count] }]]");
}
@Test
- public void requireThatAggregatorCanBeUsedAsArgumentToOrderByFunction() {
+ void requireThatAggregatorCanBeUsedAsArgumentToOrderByFunction() {
assertLayout("all(group(a) order(sum(price) * count()) each(output(count())))",
- "[[{ Attribute, result = [Count, Sum], order = [[1], [Multiply]] }]]");
+ "[[{ Attribute, result = [Count, Sum], order = [[1], [Multiply]] }]]");
assertLayout("all(group(a) order(sum(price) + 4) each(output(sum(price))))",
- "[[{ Attribute, result = [Sum], order = [[1], [Add]] }]]");
+ "[[{ Attribute, result = [Sum], order = [[1], [Add]] }]]");
assertLayout("all(group(a) order(sum(price) + 4, count()) each(output(sum(price))))",
- "[[{ Attribute, result = [Sum, Count], order = [[1, 2], [Add, AggregationRef]] }]]");
+ "[[{ Attribute, result = [Sum, Count], order = [[1, 2], [Add, AggregationRef]] }]]");
assertLayout("all(group(a) order(sum(price) + 4, -count()) each(output(sum(price))))",
- "[[{ Attribute, result = [Sum, Count], order = [[1, -2], [Add, AggregationRef]] }]]");
+ "[[{ Attribute, result = [Sum, Count], order = [[1, -2], [Add, AggregationRef]] }]]");
}
@Test
- public void requireThatSameAggregatorCanBeUsedMultipleTimes() {
+ void requireThatSameAggregatorCanBeUsedMultipleTimes() {
assertLayout("all(group(a) each(output(count() as(b),count() as(c))))",
- "[[{ Attribute, result = [Count, Count] }]]");
+ "[[{ Attribute, result = [Count, Count] }]]");
}
@Test
- public void requireThatSiblingAggregatorsCanNotShareSameLabel() {
+ void requireThatSiblingAggregatorsCanNotShareSameLabel() {
assertBuildFail("all(group(a) each(output(count(),count())))",
- "Can not use output label 'count()' for multiple siblings.");
+ "Can not use output label 'count()' for multiple siblings.");
assertBuildFail("all(group(a) each(output(count() as(b),count() as(b))))",
"Can not use output label 'b' for multiple siblings.");
}
@Test
- public void requireThatOrderByReusesOutputResults() {
+ void requireThatOrderByReusesOutputResults() {
assertLayout("all(group(a) order(count()) each(output(count())))",
"[[{ Attribute, result = [Count], order = [[1], [AggregationRef]] }]]");
assertLayout("all(group(a) order(count()) each(output(count() as(b))))",
@@ -463,40 +461,40 @@ public class RequestBuilderTestCase {
}
@Test
- public void requireThatNoopBranchesArePruned() {
+ void requireThatNoopBranchesArePruned() {
assertLayout("all()", "[]");
assertLayout("all(group(a))", "[]");
assertLayout("all(group(a) each())", "[]");
String expectedA = "[{ Attribute, result = [Count] }]";
assertLayout("all(group(a) each(output(count())))",
- Arrays.asList(expectedA).toString());
+ Arrays.asList(expectedA).toString());
assertLayout("all(group(a) each(output(count()) all()))",
- Arrays.asList(expectedA).toString());
+ Arrays.asList(expectedA).toString());
assertLayout("all(group(a) each(output(count()) all(group(b))))",
- Arrays.asList(expectedA).toString());
+ Arrays.asList(expectedA).toString());
assertLayout("all(group(a) each(output(count()) all(group(b) each())))",
- Arrays.asList(expectedA).toString());
+ Arrays.asList(expectedA).toString());
assertLayout("all(group(a) each(output(count()) all(group(b) each())))",
- Arrays.asList(expectedA).toString());
+ Arrays.asList(expectedA).toString());
assertLayout("all(group(a) each(output(count()) all(group(b) each())) as(foo)" +
- " each())",
- Arrays.asList(expectedA).toString());
+ " each())",
+ Arrays.asList(expectedA).toString());
assertLayout("all(group(a) each(output(count()) all(group(b) each())) as(foo)" +
- " each(group(b)))",
- Arrays.asList(expectedA).toString());
+ " each(group(b)))",
+ Arrays.asList(expectedA).toString());
assertLayout("all(group(a) each(output(count()) all(group(b) each())) as(foo)" +
- " each(group(b) each()))",
- Arrays.asList(expectedA).toString());
+ " each(group(b) each()))",
+ Arrays.asList(expectedA).toString());
String expectedB = "[{ Attribute }, { Attribute, result = [Count] }]";
assertLayout("all(group(a) each(output(count()) all(group(b) each())) as(foo)" +
- " each(group(b) each(output(count()))))",
- Arrays.asList(expectedB, expectedA).toString());
+ " each(group(b) each(output(count()))))",
+ Arrays.asList(expectedB, expectedA).toString());
}
@Test
- public void requireThatAggregationLevelIsValidatedFails() {
+ void requireThatAggregationLevelIsValidatedFails() {
assertBuildFail("all(group(artist) output(sum(length)))",
"Expression 'length' not applicable for single group.");
assertBuild("all(group(artist) each(output(count())))");
@@ -506,46 +504,46 @@ public class RequestBuilderTestCase {
}
@Test
- public void requireThatCountOnListOfGroupsIsValidated() {
+ void requireThatCountOnListOfGroupsIsValidated() {
assertBuild("all(group(artist) output(count()))");
assertBuild("all(group(artist) each(group(album) output(count())))");
}
@Test
- public void requireThatGroupByIsValidated() {
+ void requireThatGroupByIsValidated() {
assertBuild("all(group(artist) each(output(count())))");
assertBuildFail("all(group(sum(artist)) each(output(count())))",
- "Expression 'sum(artist)' not applicable for single hit.");
+ "Expression 'sum(artist)' not applicable for single hit.");
assertBuild("all(group(artist) each(group(album) each(output(count()))))");
assertBuildFail("all(group(artist) each(group(sum(album)) each(output(count()))))",
- "Expression 'sum(album)' not applicable for single hit.");
+ "Expression 'sum(album)' not applicable for single hit.");
}
@Test
- public void requireThatGroupingLevelIsValidated() {
+ void requireThatGroupingLevelIsValidated() {
assertBuild("all(group(artist))");
assertBuild("all(group(artist) each(group(album)))");
assertBuildFail("all(group(artist) all(group(sum(price))))",
- "Can not operate on list of list of groups.");
+ "Can not operate on list of list of groups.");
assertBuild("all(group(artist) each(group(album) each(group(song))))");
assertBuildFail("all(group(artist) each(group(album) all(group(sum(price)))))",
- "Can not operate on list of list of groups.");
+ "Can not operate on list of list of groups.");
}
@Test
- public void requireThatOrderByIsValidated() {
+ void requireThatOrderByIsValidated() {
assertBuildFail("all(order(length))",
- "Can not order single group content.");
+ "Can not order single group content.");
assertBuild("all(group(artist) order(sum(length)))");
assertBuildFail("all(group(artist) each(order(length)))",
- "Can not order single group content.");
+ "Can not order single group content.");
assertBuild("all(group(artist) each(group(album) order(sum(length))))");
assertBuildFail("all(group(artist) each(group(album) each(order(length))))",
- "Can not order single group content.");
+ "Can not order single group content.");
}
@Test
- public void requireThatOrderByHasCorrectReference() {
+ void requireThatOrderByHasCorrectReference() {
assertOrderBy("all(group(a) order(count()) each(output(count())))", "[[[1]]]");
assertOrderBy("all(group(a) order(-count()) each(output(count())))", "[[[-1]]]");
assertOrderBy("all(group(a) order(count()) each(output(count(),sum(b))))", "[[[1]]]");
@@ -565,23 +563,23 @@ public class RequestBuilderTestCase {
assertOrderBy("all(group(a) order(-count(),-sum(b)) each(output(sum(b), count())))", "[[[-1, -2]]]");
assertOrderBy("all(group(a) order(count()) each(output(count())) as(foo)" +
- " each(output(sum(b))) as(bar))",
- "[[[1]], [[1]]]");
+ " each(output(sum(b))) as(bar))",
+ "[[[1]], [[1]]]");
}
@Test
- public void requireThatWhereIsValidated() {
+ void requireThatWhereIsValidated() {
assertBuild("all(where(true))");
assertBuild("all(where($query))");
assertBuildFail("all(where(foo))",
- "Operation 'where' does not support 'foo'.");
+ "Operation 'where' does not support 'foo'.");
assertBuildFail("all(group(artist) where(true))",
- "Can not apply 'where' to non-root group.");
+ "Can not apply 'where' to non-root group.");
}
@Test
- public void requireThatRootAggregationCanBeTransformed() {
+ void requireThatRootAggregationCanBeTransformed() {
RequestTest test = new RequestTest();
test.expectedOutput = CountAggregationResult.class.getName();
test.request = "all(output(count()))";
@@ -590,68 +588,68 @@ public class RequestBuilderTestCase {
}
@Test
- public void requireThatExpressionsCanBeLabeled() {
+ void requireThatExpressionsCanBeLabeled() {
assertLabel("all(group(a) each(output(count())))",
- "[[{ label = 'a', results = [count()] }]]");
+ "[[{ label = 'a', results = [count()] }]]");
assertLabel("all(group(a) each(output(count())) as(b))",
- "[[{ label = 'b', results = [count()] }]]");
+ "[[{ label = 'b', results = [count()] }]]");
assertLabel("all(group(a) each(group(b) each(output(count()))))",
- "[[{ label = 'a', results = [] }, { label = 'b', results = [count()] }]]");
+ "[[{ label = 'a', results = [] }, { label = 'b', results = [count()] }]]");
assertLabel("all(group(a) each(group(b) each(group(c) each(output(count())))))",
- "[[{ label = 'a', results = [] }, { label = 'b', results = [] }, { label = 'c', results = [count()] }]]");
+ "[[{ label = 'a', results = [] }, { label = 'b', results = [] }, { label = 'c', results = [count()] }]]");
assertBuildFail("all(group(a) each(output(count())) each(output(count())))",
- "Can not use group list label 'a' for multiple siblings.");
+ "Can not use group list label 'a' for multiple siblings.");
assertBuildFail("all(all(group(a) each(output(count())))" +
- " all(group(a) each(output(count()))))",
- "Can not use group list label 'a' for multiple siblings.");
+ " all(group(a) each(output(count()))))",
+ "Can not use group list label 'a' for multiple siblings.");
assertLabel("all(group(a) each(output(count())) as(a1)" +
- " each(output(count())) as(a2))",
- "[[{ label = 'a1', results = [count()] }], [{ label = 'a2', results = [count()] }]]");
+ " each(output(count())) as(a2))",
+ "[[{ label = 'a1', results = [count()] }], [{ label = 'a2', results = [count()] }]]");
assertLabel("all(group(a) each(all(group(b) each(output(count())))" +
- " all(group(c) each(output(count())))))",
- "[[{ label = 'a', results = [] }, { label = 'b', results = [count()] }], [{ label = 'a', results = [] }, { label = 'c', results = [count()] }]]");
+ " all(group(c) each(output(count())))))",
+ "[[{ label = 'a', results = [] }, { label = 'b', results = [count()] }], [{ label = 'a', results = [] }, { label = 'c', results = [count()] }]]");
assertLabel("all(group(a) each(group(b) each(output(count()))) as(a1)" +
- " each(group(b) each(output(count()))) as(a2))",
- "[[{ label = 'a1', results = [] }, { label = 'b', results = [count()] }], [{ label = 'a2', results = [] }, { label = 'b', results = [count()] }]]");
+ " each(group(b) each(output(count()))) as(a2))",
+ "[[{ label = 'a1', results = [] }, { label = 'b', results = [count()] }], [{ label = 'a2', results = [] }, { label = 'b', results = [count()] }]]");
assertLabel("all(group(a) each(group(b) each(group(c) each(output(count())))) as(a1)" +
- " each(group(b) each(group(e) each(output(count())))) as(a2))",
- "[[{ label = 'a1', results = [] }, { label = 'b', results = [] }, { label = 'c', results = [count()] }]," +
- " [{ label = 'a2', results = [] }, { label = 'b', results = [] }, { label = 'e', results = [count()] }]]");
+ " each(group(b) each(group(e) each(output(count())))) as(a2))",
+ "[[{ label = 'a1', results = [] }, { label = 'b', results = [] }, { label = 'c', results = [count()] }]," +
+ " [{ label = 'a2', results = [] }, { label = 'b', results = [] }, { label = 'e', results = [count()] }]]");
assertLabel("all(group(a) each(group(b) each(output(count())) as(b1)" +
- " each(output(count())) as(b2)))",
- "[[{ label = 'a', results = [] }, { label = 'b1', results = [count()] }]," +
- " [{ label = 'a', results = [] }, { label = 'b2', results = [count()] }]]");
+ " each(output(count())) as(b2)))",
+ "[[{ label = 'a', results = [] }, { label = 'b1', results = [count()] }]," +
+ " [{ label = 'a', results = [] }, { label = 'b2', results = [count()] }]]");
assertBuildFail("all(group(a) each(each(output(summary() as(foo)))))",
- "Can not label expression 'summary()'.");
+ "Can not label expression 'summary()'.");
assertLabel("all(group(foo) each(each(output(summary()))))",
- "[[{ label = 'foo', results = [hits] }]]");
+ "[[{ label = 'foo', results = [hits] }]]");
assertLabel("all(group(foo) each(each(output(summary())) as(bar)))",
- "[[{ label = 'foo', results = [bar] }]]");
+ "[[{ label = 'foo', results = [bar] }]]");
assertLabel("all(group(foo) each(each(output(summary())) as(bar)) as(baz))",
- "[[{ label = 'baz', results = [bar] }]]");
+ "[[{ label = 'baz', results = [bar] }]]");
assertLabel("all(group(foo) each(each(output(summary())) as(bar)" +
- " each(output(summary())) as(baz)))",
- "[[{ label = 'foo', results = [bar] }]," +
- " [{ label = 'foo', results = [baz] }]]");
+ " each(output(summary())) as(baz)))",
+ "[[{ label = 'foo', results = [bar] }]," +
+ " [{ label = 'foo', results = [baz] }]]");
assertLabel("all(group(foo) each(each(output(summary())))" +
- " each(each(output(summary()))) as(bar))",
- "[[{ label = 'bar', results = [hits] }]," +
- " [{ label = 'foo', results = [hits] }]]");
+ " each(each(output(summary()))) as(bar))",
+ "[[{ label = 'bar', results = [hits] }]," +
+ " [{ label = 'foo', results = [hits] }]]");
}
@Test
- public void requireThatOrderByResultsAreNotLabeled() {
+ void requireThatOrderByResultsAreNotLabeled() {
assertLabel("all(group(a) each(output(min(b), max(b), avg(b))))",
- "[[{ label = 'a', results = [min(b), max(b), avg(b)] }]]");
+ "[[{ label = 'a', results = [min(b), max(b), avg(b)] }]]");
assertLabel("all(group(a) order(min(b)) each(output(max(b), avg(b))))",
- "[[{ label = 'a', results = [max(b), avg(b), null] }]]");
+ "[[{ label = 'a', results = [max(b), avg(b), null] }]]");
assertLabel("all(group(a) order(min(b), max(b)) each(output(avg(b))))",
- "[[{ label = 'a', results = [avg(b), null, null] }]]");
+ "[[{ label = 'a', results = [avg(b), null, null] }]]");
}
@Test
- public void requireThatTimeZoneIsAppliedToTimeFunctions() {
+ void requireThatTimeZoneIsAppliedToTimeFunctions() {
for (String timePart : Arrays.asList("dayofmonth", "dayofweek", "dayofyear", "hourofday",
"minuteofhour", "monthofyear", "secondofminute", "year"))
{
@@ -665,17 +663,17 @@ public class RequestBuilderTestCase {
}
@Test
- public void requireThatTimeDateIsExpanded() {
+ void requireThatTimeDateIsExpanded() {
RequestTest test = new RequestTest();
test.expectedOutput = new StrCatFunctionNode()
.addArg(new ToStringFunctionNode(new TimeStampFunctionNode(new AttributeNode("foo"),
- TimeStampFunctionNode.TimePart.Year, true)))
+ TimeStampFunctionNode.TimePart.Year, true)))
.addArg(new ConstantNode(new StringResultNode("-")))
.addArg(new ToStringFunctionNode(new TimeStampFunctionNode(new AttributeNode("foo"),
- TimeStampFunctionNode.TimePart.Month, true)))
+ TimeStampFunctionNode.TimePart.Month, true)))
.addArg(new ConstantNode(new StringResultNode("-")))
.addArg(new ToStringFunctionNode(new TimeStampFunctionNode(new AttributeNode("foo"),
- TimeStampFunctionNode.TimePart.MonthDay, true)))
+ TimeStampFunctionNode.TimePart.MonthDay, true)))
.toString();
test.request = "all(output(avg(time.date(foo))))";
test.outputWriter = (groupingList, transform) -> groupingList.get(0).getRoot().getAggregationResults().get(0).getExpression().toString();
@@ -683,7 +681,7 @@ public class RequestBuilderTestCase {
}
@Test
- public void requireThatNowIsResolvedToCurrentTime() {
+ void requireThatNowIsResolvedToCurrentTime() {
RequestTest test = new RequestTest();
test.expectedOutput = Boolean.toString(true);
test.request = "all(output(avg(now() - foo)))";
@@ -693,8 +691,8 @@ public class RequestBuilderTestCase {
@Override
public String write(List<Grouping> groupingList, GroupingTransform transform) {
AddFunctionNode add =
- (AddFunctionNode)groupingList.get(0).getRoot().getAggregationResults().get(0).getExpression();
- long nowValue = ((ConstantNode)add.getArg(0)).getValue().getInteger();
+ (AddFunctionNode) groupingList.get(0).getRoot().getAggregationResults().get(0).getExpression();
+ long nowValue = ((ConstantNode) add.getArg(0)).getValue().getInteger();
boolean preCond = nowValue >= (before / 1000);
long after = System.currentTimeMillis();
boolean postCond = nowValue <= (after / 1000);
@@ -706,7 +704,7 @@ public class RequestBuilderTestCase {
}
@Test
- public void requireThatAttributeMapLookupNodeIsCreatedFromKey() {
+ void requireThatAttributeMapLookupNodeIsCreatedFromKey() {
RequestTest test = new RequestTest();
test.expectedOutput = AttributeMapLookupNode.fromKey("map{\"my_key\"}", "map.key", "map.value", "my_key").toString();
test.request = "all(group(map{\"my_key\"}) each(output(count())))";
@@ -715,7 +713,7 @@ public class RequestBuilderTestCase {
}
@Test
- public void requireThatAttributeMapLookupNodeIsCreatedFromKeySourceAttribute() {
+ void requireThatAttributeMapLookupNodeIsCreatedFromKeySourceAttribute() {
RequestTest test = new RequestTest();
test.expectedOutput = AttributeMapLookupNode.fromKeySourceAttribute("map{attribute(key_source)}", "map.key", "map.value", "key_source").toString();
test.request = "all(group(map{attribute(key_source)}) each(output(count())))";
@@ -724,7 +722,7 @@ public class RequestBuilderTestCase {
}
@Test
- public void require_that_default_max_values_from_request_builder_restricts_max_groups_and_hits() {
+ void require_that_default_max_values_from_request_builder_restricts_max_groups_and_hits() {
int defaultMaxHits = 19;
int defaultMaxGroups = 7;
RequestBuilder builder = new RequestBuilder(0)
@@ -735,12 +733,12 @@ public class RequestBuilderTestCase {
List<Grouping> requests = builder.getRequestList();
assertEquals(defaultMaxGroups + 1, requests.get(0).getLevels().get(0).getMaxGroups());
HitsAggregationResult hitsAggregation =
- (HitsAggregationResult)requests.get(0).getLevels().get(0).getGroupPrototype().getAggregationResults().get(0);
+ (HitsAggregationResult) requests.get(0).getLevels().get(0).getGroupPrototype().getAggregationResults().get(0);
assertEquals(defaultMaxHits + 1, hitsAggregation.getMaxHits());
}
@Test
- public void require_that_default_max_values_from_request_builder_respects_explicit_max() {
+ void require_that_default_max_values_from_request_builder_respects_explicit_max() {
{
RequestBuilder builder = new RequestBuilder(0)
.setDefaultMaxGroups(7)
@@ -750,7 +748,7 @@ public class RequestBuilderTestCase {
List<Grouping> requests = builder.getRequestList();
assertEquals(12, requests.get(0).getLevels().get(0).getMaxGroups());
HitsAggregationResult hitsAggregation =
- (HitsAggregationResult)requests.get(0).getLevels().get(0).getGroupPrototype().getAggregationResults().get(0);
+ (HitsAggregationResult) requests.get(0).getLevels().get(0).getGroupPrototype().getAggregationResults().get(0);
assertEquals(22, hitsAggregation.getMaxHits());
}
{
@@ -762,21 +760,21 @@ public class RequestBuilderTestCase {
List<Grouping> requests = builder.getRequestList();
assertEquals(-1, requests.get(0).getLevels().get(0).getMaxGroups());
HitsAggregationResult hitsAggregation =
- (HitsAggregationResult)requests.get(0).getLevels().get(0).getGroupPrototype().getAggregationResults().get(0);
+ (HitsAggregationResult) requests.get(0).getLevels().get(0).getGroupPrototype().getAggregationResults().get(0);
assertEquals(-1, hitsAggregation.getMaxHits());
}
}
@Test
- public void require_that_total_groups_and_summaries_calculation_is_correct() {
+ void require_that_total_groups_and_summaries_calculation_is_correct() {
assertTotalGroupsAndSummaries(5, "all(group(a) max(5) each(output(count())))");
- assertTotalGroupsAndSummaries(5+5*7, "all(group(a) max(5) each(max(7) each(output(summary()))))");
- assertTotalGroupsAndSummaries(3+3*5+3*5*7+3*5*7*11,
+ assertTotalGroupsAndSummaries(5 + 5 * 7, "all(group(a) max(5) each(max(7) each(output(summary()))))");
+ assertTotalGroupsAndSummaries(3 + 3 * 5 + 3 * 5 * 7 + 3 * 5 * 7 * 11,
"all( group(a) max(3) each(output(count())" +
- " all(group(b) max(5) each(output(count())" +
- " all(group(c) max(7) each(max(11) output(count())" +
- " each(output(summary()))))))))");
- assertTotalGroupsAndSummaries(2*(3+3*5),
+ " all(group(b) max(5) each(output(count())" +
+ " all(group(c) max(7) each(max(11) output(count())" +
+ " each(output(summary()))))))))");
+ assertTotalGroupsAndSummaries(2 * (3 + 3 * 5),
"all(" +
" all(group(a) max(3) each(output(count()) max(5) each(output(summary())))) " +
" all(group(b) max(3) each(output(count()) max(5) each(output(summary())))))");
@@ -784,24 +782,24 @@ public class RequestBuilderTestCase {
}
@Test
- public void require_that_total_groups_restriction_can_be_disabled() {
- assertTotalGroupsAndSummaries(3+3*5+3*5*7+3*5*7*100,
- -1, // disable
- "all( group(a) max(3) each(output(count())" +
- " all(group(b) max(5) each(output(count())" +
- " all(group(c) max(7) each(max(100) output(count())" +
- " each(output(summary()))))))))");
+ void require_that_total_groups_restriction_can_be_disabled() {
+ assertTotalGroupsAndSummaries(3 + 3 * 5 + 3 * 5 * 7 + 3 * 5 * 7 * 100,
+ -1, // disable
+ "all( group(a) max(3) each(output(count())" +
+ " all(group(b) max(5) each(output(count())" +
+ " all(group(c) max(7) each(max(100) output(count())" +
+ " each(output(summary()))))))))");
}
@Test
- public void require_that_unbounded_queries_fails_when_global_max_is_enabled() {
+ void require_that_unbounded_queries_fails_when_global_max_is_enabled() {
assertQueryFailsOnGlobalMax(4, "all(group(a) max(5) each(output(count())))", "5 > 4");
assertQueryFailsOnGlobalMax(Long.MAX_VALUE, "all(group(a) each(output(count())))", "unbounded number of groups");
assertQueryFailsOnGlobalMax(Long.MAX_VALUE, "all(group(a) max(5) each(each(output(summary()))))", "unbounded number of summaries");
}
@Test
- public void require_that_default_precision_factor_overrides_implicit_precision() {
+ void require_that_default_precision_factor_overrides_implicit_precision() {
int factor = 3;
RequestBuilder builder = new RequestBuilder(0)
.setDefaultPrecisionFactor(factor)
@@ -811,7 +809,7 @@ public class RequestBuilderTestCase {
}
@Test
- public void require_that_explicit_precision_has_precedence() {
+ void require_that_explicit_precision_has_precedence() {
RequestBuilder builder = new RequestBuilder(0)
.setDefaultPrecisionFactor(3)
.setRootOperation(GroupingOperation.fromString("all(group(foo)max(5)precision(10)each(output(count())))"));
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/vespa/ResultBuilderTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/vespa/ResultBuilderTestCase.java
index 3bc5a7c245c..019a022b7e6 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/vespa/ResultBuilderTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/vespa/ResultBuilderTestCase.java
@@ -13,12 +13,12 @@ import com.yahoo.search.result.Relevance;
import com.yahoo.searchlib.aggregation.*;
import com.yahoo.searchlib.aggregation.hll.SparseSketch;
import com.yahoo.searchlib.expression.*;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.*;
-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
@@ -29,28 +29,28 @@ public class ResultBuilderTestCase {
private static final int ROOT_IDX = 0;
@Test
- public void requireThatAllGroupIdsCanBeConverted() {
+ void requireThatAllGroupIdsCanBeConverted() {
assertGroupId("group:6.9", new FloatResultNode(6.9));
assertGroupId("group:69", new IntegerResultNode(69));
assertGroupId("group:null", new NullResultNode());
- assertGroupId("group:[6, 9]", new RawResultNode(new byte[] { 6, 9 }));
+ assertGroupId("group:[6, 9]", new RawResultNode(new byte[]{6, 9}));
assertGroupId("group:a", new StringResultNode("a"));
assertGroupId("group:6.9:9.6", new FloatBucketResultNode(6.9, 9.6));
assertGroupId("group:6:9", new IntegerBucketResultNode(6, 9));
assertGroupId("group:a:b", new StringBucketResultNode("a", "b"));
- assertGroupId("group:[6, 9]:[9, 6]", new RawBucketResultNode(new RawResultNode(new byte[] { 6, 9 }),
- new RawResultNode(new byte[] { 9, 6 })));
+ assertGroupId("group:[6, 9]:[9, 6]", new RawBucketResultNode(new RawResultNode(new byte[]{6, 9}),
+ new RawResultNode(new byte[]{9, 6})));
}
@Test
- public void requireThatUnknownGroupIdThrows() {
+ void requireThatUnknownGroupIdThrows() {
assertBuildFail("all(group(a) each(output(count())))",
- Arrays.asList(newGrouping(new Group().setTag(2).setId(new MyResultNode()))),
- "com.yahoo.search.grouping.vespa.ResultBuilderTestCase$MyResultNode");
+ Arrays.asList(newGrouping(new Group().setTag(2).setId(new MyResultNode()))),
+ "com.yahoo.search.grouping.vespa.ResultBuilderTestCase$MyResultNode");
}
@Test
- public void requireThatAllExpressionNodesCanBeConverted() {
+ void requireThatAllExpressionNodesCanBeConverted() {
assertResult("0", new AverageAggregationResult(new IntegerResultNode(6), 9));
assertResult("69", new CountAggregationResult(69));
assertResult("69", new MaxAggregationResult(new IntegerResultNode(69)));
@@ -61,89 +61,89 @@ public class ResultBuilderTestCase {
}
@Test
- public void requireThatUnknownExpressionNodeThrows() {
+ void requireThatUnknownExpressionNodeThrows() {
assertBuildFail("all(group(a) each(output(count())))",
- Arrays.asList(newGrouping(newGroup(2, 2, new MyAggregationResult().setTag(3)))),
- "com.yahoo.search.grouping.vespa.ResultBuilderTestCase$MyAggregationResult");
+ Arrays.asList(newGrouping(newGroup(2, 2, new MyAggregationResult().setTag(3)))),
+ "com.yahoo.search.grouping.vespa.ResultBuilderTestCase$MyAggregationResult");
}
@Test
- public void requireThatRootResultsAreIncluded() {
+ void requireThatRootResultsAreIncluded() {
assertLayout("all(output(count()))",
- new Grouping().setRoot(newGroup(1, new CountAggregationResult(69).setTag(2))),
- "RootGroup{id=group:root, count()=69}[]");
+ new Grouping().setRoot(newGroup(1, new CountAggregationResult(69).setTag(2))),
+ "RootGroup{id=group:root, count()=69}[]");
}
@Test
- public void requireThatRootResultsAreIncludedUsingExpressionCountAggregationResult() {
+ void requireThatRootResultsAreIncludedUsingExpressionCountAggregationResult() {
assertLayout("all(group(a) output(count()))",
new Grouping().setRoot(newGroup(1, new ExpressionCountAggregationResult(new SparseSketch(), sketch -> 69).setTag(2))),
"RootGroup{id=group:root, count()=69}[]");
}
@Test
- public void requireThatNestedGroupingResultsCanBeTransformed() {
+ void requireThatNestedGroupingResultsCanBeTransformed() {
Grouping grouping = new Grouping()
.setRoot(new Group()
- .setTag(1)
- .addChild(new Group()
- .setTag(2)
- .setId(new StringResultNode("foo"))
- .addAggregationResult(new CountAggregationResult(10).setTag(3))
- .addChild(new Group()
- .setTag(4)
- .setId(new StringResultNode("foo_a"))
- .addAggregationResult(new CountAggregationResult(15)
- .setTag(5)))
- .addChild(new Group()
- .setTag(4)
- .setId(new StringResultNode("foo_b"))
- .addAggregationResult(new CountAggregationResult(16)
- .setTag(5))))
- .addChild(new Group()
- .setTag(2)
- .setId(new StringResultNode("bar"))
- .addAggregationResult(new CountAggregationResult(20).setTag(3))
- .addChild(new Group()
- .setTag(4)
- .setId(new StringResultNode("bar_a"))
- .addAggregationResult(
- new CountAggregationResult(25)
- .setTag(5)))
- .addChild(new Group()
- .setTag(4)
- .setId(new StringResultNode("bar_b"))
- .addAggregationResult(
- new CountAggregationResult(26)
- .setTag(5)))));
+ .setTag(1)
+ .addChild(new Group()
+ .setTag(2)
+ .setId(new StringResultNode("foo"))
+ .addAggregationResult(new CountAggregationResult(10).setTag(3))
+ .addChild(new Group()
+ .setTag(4)
+ .setId(new StringResultNode("foo_a"))
+ .addAggregationResult(new CountAggregationResult(15)
+ .setTag(5)))
+ .addChild(new Group()
+ .setTag(4)
+ .setId(new StringResultNode("foo_b"))
+ .addAggregationResult(new CountAggregationResult(16)
+ .setTag(5))))
+ .addChild(new Group()
+ .setTag(2)
+ .setId(new StringResultNode("bar"))
+ .addAggregationResult(new CountAggregationResult(20).setTag(3))
+ .addChild(new Group()
+ .setTag(4)
+ .setId(new StringResultNode("bar_a"))
+ .addAggregationResult(
+ new CountAggregationResult(25)
+ .setTag(5)))
+ .addChild(new Group()
+ .setTag(4)
+ .setId(new StringResultNode("bar_b"))
+ .addAggregationResult(
+ new CountAggregationResult(26)
+ .setTag(5)))));
assertLayout("all(group(artist) max(5) each(output(count() as(baz)) all(group(album) " +
- "max(5) each(output(count() as(cox))) as(group_album))) as(group_artist))",
- grouping,
- "RootGroup{id=group:root}[GroupList{label=group_artist}[" +
- "Group{id=group:foo, baz=10}[GroupList{label=group_album}[Group{id=group:foo_a, cox=15}[], Group{id=group:foo_b, cox=16}[]]], " +
- "Group{id=group:bar, baz=20}[GroupList{label=group_album}[Group{id=group:bar_a, cox=25}[], Group{id=group:bar_b, cox=26}[]]]]]");
+ "max(5) each(output(count() as(cox))) as(group_album))) as(group_artist))",
+ grouping,
+ "RootGroup{id=group:root}[GroupList{label=group_artist}[" +
+ "Group{id=group:foo, baz=10}[GroupList{label=group_album}[Group{id=group:foo_a, cox=15}[], Group{id=group:foo_b, cox=16}[]]], " +
+ "Group{id=group:bar, baz=20}[GroupList{label=group_album}[Group{id=group:bar_a, cox=25}[], Group{id=group:bar_b, cox=26}[]]]]]");
}
@Test
- public void requireThatParallelResultsAreTransformed() {
+ void requireThatParallelResultsAreTransformed() {
assertBuild("all(group(foo) each(output(count())) as(bar) each(output(count())) as(baz))",
- Arrays.asList(new Grouping().setRoot(newGroup(1, 0)),
- new Grouping().setRoot(newGroup(1, 0))));
+ Arrays.asList(new Grouping().setRoot(newGroup(1, 0)),
+ new Grouping().setRoot(newGroup(1, 0))));
assertBuildFail("all(group(foo) each(output(count())) as(bar) each(output(count())) as(baz))",
- Arrays.asList(new Grouping().setRoot(newGroup(2)),
- new Grouping().setRoot(newGroup(3))),
- "Expected 1 group, got 2.");
+ Arrays.asList(new Grouping().setRoot(newGroup(2)),
+ new Grouping().setRoot(newGroup(3))),
+ "Expected 1 group, got 2.");
}
@Test
- public void requireThatTagsAreHandledCorrectly() {
+ void requireThatTagsAreHandledCorrectly() {
assertBuild("all(group(a) each(output(count())))",
Arrays.asList(newGrouping(
newGroup(7, new CountAggregationResult(0)))));
}
@Test
- public void requireThatEmptyBranchesArePruned() {
+ void requireThatEmptyBranchesArePruned() {
assertBuildFail("all()", Collections.<Grouping>emptyList(), "Expected 1 group, got 0.");
assertBuildFail("all(group(a))", Collections.<Grouping>emptyList(), "Expected 1 group, got 0.");
assertBuildFail("all(group(a) each())", Collections.<Grouping>emptyList(), "Expected 1 group, got 0.");
@@ -156,71 +156,71 @@ public class ResultBuilderTestCase {
assertLayout("all(group(a) each(output(count()) all(group(b) each())))", grouping, expectedOutput);
assertLayout("all(group(a) each(output(count()) all(group(b) each())))", grouping, expectedOutput);
assertLayout("all(group(a) each(output(count()) all(group(b) each()))" +
- " each() as(foo))", grouping, expectedOutput);
+ " each() as(foo))", grouping, expectedOutput);
assertLayout("all(group(a) each(output(count()) all(group(b) each()))" +
- " each(group(b)) as(foo))", grouping, expectedOutput);
+ " each(group(b)) as(foo))", grouping, expectedOutput);
assertLayout("all(group(a) each(output(count()) all(group(b) each()))" +
- " each(group(b) each()) as(foo))", grouping, expectedOutput);
+ " each(group(b) each()) as(foo))", grouping, expectedOutput);
}
@Test
- public void requireThatGroupListsAreLabeled() {
+ void requireThatGroupListsAreLabeled() {
assertLayout("all(group(a) each(output(count())))",
- newGrouping(newGroup(2, new CountAggregationResult(69).setTag(3))),
- "RootGroup{id=group:root}[GroupList{label=a}[Group{id=group:2, count()=69}[]]]");
+ newGrouping(newGroup(2, new CountAggregationResult(69).setTag(3))),
+ "RootGroup{id=group:root}[GroupList{label=a}[Group{id=group:2, count()=69}[]]]");
assertLayout("all(group(a) each(output(count())) as(bar))",
- newGrouping(newGroup(2, new CountAggregationResult(69).setTag(3))),
- "RootGroup{id=group:root}[GroupList{label=bar}[Group{id=group:2, count()=69}[]]]");
+ newGrouping(newGroup(2, new CountAggregationResult(69).setTag(3))),
+ "RootGroup{id=group:root}[GroupList{label=bar}[Group{id=group:2, count()=69}[]]]");
}
@Test
- public void requireThatHitListsAreLabeled() {
+ void requireThatHitListsAreLabeled() {
assertLayout("all(group(foo) each(each(output(summary()))))",
- newGrouping(newGroup(2, newHitList(3, 2))),
- "RootGroup{id=group:root}[GroupList{label=foo}[Group{id=group:2}[" +
- "HitList{label=hits}[Hit{id=hit:1}, Hit{id=hit:2}]]]]");
+ newGrouping(newGroup(2, newHitList(3, 2))),
+ "RootGroup{id=group:root}[GroupList{label=foo}[Group{id=group:2}[" +
+ "HitList{label=hits}[Hit{id=hit:1}, Hit{id=hit:2}]]]]");
assertLayout("all(group(foo) each(each(output(summary())) as(bar)))",
- newGrouping(newGroup(2, newHitList(3, 2))),
- "RootGroup{id=group:root}[GroupList{label=foo}[Group{id=group:2}[" +
- "HitList{label=bar}[Hit{id=hit:1}, Hit{id=hit:2}]]]]");
+ newGrouping(newGroup(2, newHitList(3, 2))),
+ "RootGroup{id=group:root}[GroupList{label=foo}[Group{id=group:2}[" +
+ "HitList{label=bar}[Hit{id=hit:1}, Hit{id=hit:2}]]]]");
assertLayout("all(group(foo) each(each(output(summary())) as(bar)) as(baz))",
- newGrouping(newGroup(2, newHitList(3, 2))),
- "RootGroup{id=group:root}[GroupList{label=baz}[Group{id=group:2}[" +
- "HitList{label=bar}[Hit{id=hit:1}, Hit{id=hit:2}]]]]");
+ newGrouping(newGroup(2, newHitList(3, 2))),
+ "RootGroup{id=group:root}[GroupList{label=baz}[Group{id=group:2}[" +
+ "HitList{label=bar}[Hit{id=hit:1}, Hit{id=hit:2}]]]]");
assertLayout("all(group(foo) each(each(output(summary())) as(bar)" +
- " each(output(summary())) as(baz)))",
- Arrays.asList(newGrouping(newGroup(2, newHitList(3, 2))),
- newGrouping(newGroup(2, newHitList(4, 2)))),
- "RootGroup{id=group:root}[GroupList{label=foo}[Group{id=group:2}[" +
- "HitList{label=bar}[Hit{id=hit:1}, Hit{id=hit:2}], " +
- "HitList{label=baz}[Hit{id=hit:1}, Hit{id=hit:2}]]]]");
+ " each(output(summary())) as(baz)))",
+ Arrays.asList(newGrouping(newGroup(2, newHitList(3, 2))),
+ newGrouping(newGroup(2, newHitList(4, 2)))),
+ "RootGroup{id=group:root}[GroupList{label=foo}[Group{id=group:2}[" +
+ "HitList{label=bar}[Hit{id=hit:1}, Hit{id=hit:2}], " +
+ "HitList{label=baz}[Hit{id=hit:1}, Hit{id=hit:2}]]]]");
assertLayout("all(group(foo) each(each(output(summary())))" +
- " each(each(output(summary()))) as(bar))",
- Arrays.asList(newGrouping(newGroup(2, newHitList(3, 2))),
- newGrouping(newGroup(4, newHitList(5, 2)))),
- "RootGroup{id=group:root}[" +
- "GroupList{label=foo}[Group{id=group:2}[HitList{label=hits}[Hit{id=hit:1}, Hit{id=hit:2}]]], " +
- "GroupList{label=bar}[Group{id=group:4}[HitList{label=hits}[Hit{id=hit:1}, Hit{id=hit:2}]]]]");
+ " each(each(output(summary()))) as(bar))",
+ Arrays.asList(newGrouping(newGroup(2, newHitList(3, 2))),
+ newGrouping(newGroup(4, newHitList(5, 2)))),
+ "RootGroup{id=group:root}[" +
+ "GroupList{label=foo}[Group{id=group:2}[HitList{label=hits}[Hit{id=hit:1}, Hit{id=hit:2}]]], " +
+ "GroupList{label=bar}[Group{id=group:4}[HitList{label=hits}[Hit{id=hit:1}, Hit{id=hit:2}]]]]");
}
@Test
- public void requireThatOutputsAreLabeled() {
+ void requireThatOutputsAreLabeled() {
assertLayout("all(output(count()))",
- new Grouping().setRoot(newGroup(1, new CountAggregationResult(69).setTag(2))),
- "RootGroup{id=group:root, count()=69}[]");
+ new Grouping().setRoot(newGroup(1, new CountAggregationResult(69).setTag(2))),
+ "RootGroup{id=group:root, count()=69}[]");
assertLayout("all(output(count() as(foo)))",
- new Grouping().setRoot(newGroup(1, new CountAggregationResult(69).setTag(2))),
- "RootGroup{id=group:root, foo=69}[]");
+ new Grouping().setRoot(newGroup(1, new CountAggregationResult(69).setTag(2))),
+ "RootGroup{id=group:root, foo=69}[]");
assertLayout("all(group(a) each(output(count())))",
- newGrouping(newGroup(2, new CountAggregationResult(69).setTag(3))),
- "RootGroup{id=group:root}[GroupList{label=a}[Group{id=group:2, count()=69}[]]]");
+ newGrouping(newGroup(2, new CountAggregationResult(69).setTag(3))),
+ "RootGroup{id=group:root}[GroupList{label=a}[Group{id=group:2, count()=69}[]]]");
assertLayout("all(group(a) each(output(count() as(foo))))",
- newGrouping(newGroup(2, new CountAggregationResult(69).setTag(3))),
- "RootGroup{id=group:root}[GroupList{label=a}[Group{id=group:2, foo=69}[]]]");
+ newGrouping(newGroup(2, new CountAggregationResult(69).setTag(3))),
+ "RootGroup{id=group:root}[GroupList{label=a}[Group{id=group:2, foo=69}[]]]");
}
@Test
- public void requireThatExpressionCountCanUseExactGroupCount() {
+ void requireThatExpressionCountCanUseExactGroupCount() {
Group root1 = newGroup(1, new ExpressionCountAggregationResult(new SparseSketch(), sketch -> 42).setTag(2));
Grouping grouping1 = new Grouping().setRoot(root1);
@@ -260,35 +260,35 @@ public class ResultBuilderTestCase {
@Test
- public void requireThatResultContinuationContainsCurrentPages() {
+ void requireThatResultContinuationContainsCurrentPages() {
String request = "all(group(a) max(2) each(output(count())))";
Grouping result = newGrouping(newGroup(2, 1, new CountAggregationResult(1)),
- newGroup(2, 2, new CountAggregationResult(2)),
- newGroup(2, 3, new CountAggregationResult(3)),
- newGroup(2, 4, new CountAggregationResult(4)));
+ newGroup(2, 2, new CountAggregationResult(2)),
+ newGroup(2, 3, new CountAggregationResult(3)),
+ newGroup(2, 4, new CountAggregationResult(4)));
assertResultCont(request, result, newOffset(newResultId(0), 2, 0), "[]");
assertResultCont(request, result, newOffset(newResultId(0), 2, 1), "[0=1]");
assertResultCont(request, result, newOffset(newResultId(0), 2, 2), "[0=2]");
assertResultCont(request, result, newOffset(newResultId(0), 2, 3), "[0=3]");
assertResultCont("all(group(a) max(2) each(output(count())) as(foo)" +
- " each(output(count())) as(bar))",
- Arrays.asList(newGrouping(newGroup(2, 1, new CountAggregationResult(1))),
- newGrouping(newGroup(4, 2, new CountAggregationResult(4)))),
- "[]");
+ " each(output(count())) as(bar))",
+ Arrays.asList(newGrouping(newGroup(2, 1, new CountAggregationResult(1))),
+ newGrouping(newGroup(4, 2, new CountAggregationResult(4)))),
+ "[]");
assertResultCont("all(group(a) max(2) each(output(count())) as(foo)" +
- " each(output(count())) as(bar))",
- Arrays.asList(newGrouping(newGroup(2, 1, new CountAggregationResult(1))),
- newGrouping(newGroup(4, 2, new CountAggregationResult(4)))),
- newOffset(newResultId(0), 2, 1),
- "[0=1]");
+ " each(output(count())) as(bar))",
+ Arrays.asList(newGrouping(newGroup(2, 1, new CountAggregationResult(1))),
+ newGrouping(newGroup(4, 2, new CountAggregationResult(4)))),
+ newOffset(newResultId(0), 2, 1),
+ "[0=1]");
assertResultCont("all(group(a) max(2) each(output(count())) as(foo)" +
- " each(output(count())) as(bar))",
- Arrays.asList(newGrouping(newGroup(2, 1, new CountAggregationResult(1))),
- newGrouping(newGroup(4, 2, new CountAggregationResult(4)))),
- newComposite(newOffset(newResultId(0), 2, 2),
- newOffset(newResultId(1), 4, 1)),
- "[0=2, 1=1]");
+ " each(output(count())) as(bar))",
+ Arrays.asList(newGrouping(newGroup(2, 1, new CountAggregationResult(1))),
+ newGrouping(newGroup(4, 2, new CountAggregationResult(4)))),
+ newComposite(newOffset(newResultId(0), 2, 2),
+ newOffset(newResultId(1), 4, 1)),
+ "[0=2, 1=1]");
request = "all(group(a) each(max(2) each(output(summary()))))";
result = newGrouping(newGroup(2, newHitList(3, 4)));
@@ -298,436 +298,436 @@ public class ResultBuilderTestCase {
assertResultCont(request, result, newOffset(newResultId(0, 0, 0), 3, 3), "[0.0.0=3]");
assertResultCont("all(group(a) each(max(2) each(output(summary()))) as(foo)" +
- " each(max(2) each(output(summary()))) as(bar))",
- Arrays.asList(newGrouping(newGroup(2, newHitList(3, 4))),
- newGrouping(newGroup(4, newHitList(5, 4)))),
- "[]");
+ " each(max(2) each(output(summary()))) as(bar))",
+ Arrays.asList(newGrouping(newGroup(2, newHitList(3, 4))),
+ newGrouping(newGroup(4, newHitList(5, 4)))),
+ "[]");
assertResultCont("all(group(a) each(max(2) each(output(summary()))) as(foo)" +
- " each(max(2) each(output(summary()))) as(bar))",
- Arrays.asList(newGrouping(newGroup(2, newHitList(3, 4))),
- newGrouping(newGroup(4, newHitList(5, 4)))),
- newOffset(newResultId(0, 0, 0), 3, 1),
- "[0.0.0=1]");
+ " each(max(2) each(output(summary()))) as(bar))",
+ Arrays.asList(newGrouping(newGroup(2, newHitList(3, 4))),
+ newGrouping(newGroup(4, newHitList(5, 4)))),
+ newOffset(newResultId(0, 0, 0), 3, 1),
+ "[0.0.0=1]");
assertResultCont("all(group(a) each(max(2) each(output(summary()))) as(foo)" +
- " each(max(2) each(output(summary()))) as(bar))",
- Arrays.asList(newGrouping(newGroup(2, newHitList(3, 4))),
- newGrouping(newGroup(4, newHitList(5, 4)))),
- newComposite(newOffset(newResultId(0, 0, 0), 3, 2),
- newOffset(newResultId(1, 0, 0), 5, 1)),
- "[0.0.0=2, 1.0.0=1]");
+ " each(max(2) each(output(summary()))) as(bar))",
+ Arrays.asList(newGrouping(newGroup(2, newHitList(3, 4))),
+ newGrouping(newGroup(4, newHitList(5, 4)))),
+ newComposite(newOffset(newResultId(0, 0, 0), 3, 2),
+ newOffset(newResultId(1, 0, 0), 5, 1)),
+ "[0.0.0=2, 1.0.0=1]");
}
@Test
- public void requireThatGroupListContinuationsAreNotCreatedWhenUnlessMaxIsSet() {
+ void requireThatGroupListContinuationsAreNotCreatedWhenUnlessMaxIsSet() {
assertContinuation("all(group(a) each(output(count())))",
- newGrouping(newGroup(2, 1, new CountAggregationResult(1)),
- newGroup(2, 2, new CountAggregationResult(2)),
- newGroup(2, 3, new CountAggregationResult(3)),
- newGroup(2, 4, new CountAggregationResult(4))),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:1', {}, [] }, { 'group:2', {}, [] }, { 'group:3', {}, [] }, { 'group:4', {}, [] }] }] }");
+ newGrouping(newGroup(2, 1, new CountAggregationResult(1)),
+ newGroup(2, 2, new CountAggregationResult(2)),
+ newGroup(2, 3, new CountAggregationResult(3)),
+ newGroup(2, 4, new CountAggregationResult(4))),
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:1', {}, [] }, { 'group:2', {}, [] }, { 'group:3', {}, [] }, { 'group:4', {}, [] }] }] }");
}
@Test
- public void requireThatGroupListContinuationsCanBeSet() {
+ void requireThatGroupListContinuationsCanBeSet() {
String request = "all(group(a) max(2) each(output(count())))";
Grouping result = newGrouping(newGroup(2, 1, new CountAggregationResult(1)),
- newGroup(2, 2, new CountAggregationResult(2)),
- newGroup(2, 3, new CountAggregationResult(3)),
- newGroup(2, 4, new CountAggregationResult(4)));
+ newGroup(2, 2, new CountAggregationResult(2)),
+ newGroup(2, 3, new CountAggregationResult(3)),
+ newGroup(2, 4, new CountAggregationResult(4)));
assertContinuation(request, result, newOffset(newResultId(0), 2, 0),
- "{ 'group:root', {}, [{ 'grouplist:a', {next=2}, [" +
- "{ 'group:1', {}, [] }, { 'group:2', {}, [] }] }] }");
+ "{ 'group:root', {}, [{ 'grouplist:a', {next=2}, [" +
+ "{ 'group:1', {}, [] }, { 'group:2', {}, [] }] }] }");
assertContinuation(request, result, newOffset(newResultId(0), 2, 1),
- "{ 'group:root', {}, [{ 'grouplist:a', {next=3, prev=0}, [" +
- "{ 'group:2', {}, [] }, { 'group:3', {}, [] }] }] }");
+ "{ 'group:root', {}, [{ 'grouplist:a', {next=3, prev=0}, [" +
+ "{ 'group:2', {}, [] }, { 'group:3', {}, [] }] }] }");
assertContinuation(request, result, newOffset(newResultId(0), 2, 2),
- "{ 'group:root', {}, [{ 'grouplist:a', {prev=0}, [" +
- "{ 'group:3', {}, [] }, { 'group:4', {}, [] }] }] }");
+ "{ 'group:root', {}, [{ 'grouplist:a', {prev=0}, [" +
+ "{ 'group:3', {}, [] }, { 'group:4', {}, [] }] }] }");
assertContinuation(request, result, newOffset(newResultId(0), 2, 3),
- "{ 'group:root', {}, [{ 'grouplist:a', {prev=1}, [" +
- "{ 'group:4', {}, [] }] }] }");
+ "{ 'group:root', {}, [{ 'grouplist:a', {prev=1}, [" +
+ "{ 'group:4', {}, [] }] }] }");
assertContinuation(request, result, newOffset(newResultId(0), 2, 4),
- "{ 'group:root', {}, [{ 'grouplist:a', {prev=2}, [" +
- "] }] }");
+ "{ 'group:root', {}, [{ 'grouplist:a', {prev=2}, [" +
+ "] }] }");
assertContinuation(request, result, newOffset(newResultId(0), 2, 5),
- "{ 'group:root', {}, [{ 'grouplist:a', {prev=2}, [" +
- "] }] }");
+ "{ 'group:root', {}, [{ 'grouplist:a', {prev=2}, [" +
+ "] }] }");
}
@Test
- public void requireThatGroupListContinuationsCanBeSetInSiblingGroups() {
+ void requireThatGroupListContinuationsCanBeSetInSiblingGroups() {
String request = "all(group(a) each(group(b) max(2) each(output(count()))))";
Grouping result = newGrouping(newGroup(2, 201,
- newGroup(3, 301, new CountAggregationResult(1)),
- newGroup(3, 302, new CountAggregationResult(2)),
- newGroup(3, 303, new CountAggregationResult(3)),
- newGroup(3, 304, new CountAggregationResult(4))),
- newGroup(2, 202,
- newGroup(3, 305, new CountAggregationResult(5)),
- newGroup(3, 306, new CountAggregationResult(6)),
- newGroup(3, 307, new CountAggregationResult(7)),
- newGroup(3, 308, new CountAggregationResult(8))));
+ newGroup(3, 301, new CountAggregationResult(1)),
+ newGroup(3, 302, new CountAggregationResult(2)),
+ newGroup(3, 303, new CountAggregationResult(3)),
+ newGroup(3, 304, new CountAggregationResult(4))),
+ newGroup(2, 202,
+ newGroup(3, 305, new CountAggregationResult(5)),
+ newGroup(3, 306, new CountAggregationResult(6)),
+ newGroup(3, 307, new CountAggregationResult(7)),
+ newGroup(3, 308, new CountAggregationResult(8))));
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 0, 0), 2, 0),
- newOffset(newResultId(0, 1, 0), 2, 5)),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'grouplist:b', {next=2}, [{ 'group:301', {}, [] }, { 'group:302', {}, [] }] }] }, " +
- "{ 'group:202', {}, [{ 'grouplist:b', {prev=2}, [] }] }] }] }");
+ newOffset(newResultId(0, 1, 0), 2, 5)),
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'grouplist:b', {next=2}, [{ 'group:301', {}, [] }, { 'group:302', {}, [] }] }] }, " +
+ "{ 'group:202', {}, [{ 'grouplist:b', {prev=2}, [] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 0, 0), 2, 1),
- newOffset(newResultId(0, 1, 0), 2, 4)),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'grouplist:b', {next=3, prev=0}, [{ 'group:302', {}, [] }, { 'group:303', {}, [] }] }] }, " +
- "{ 'group:202', {}, [{ 'grouplist:b', {prev=2}, [] }] }] }] }");
+ newOffset(newResultId(0, 1, 0), 2, 4)),
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'grouplist:b', {next=3, prev=0}, [{ 'group:302', {}, [] }, { 'group:303', {}, [] }] }] }, " +
+ "{ 'group:202', {}, [{ 'grouplist:b', {prev=2}, [] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 0, 0), 2, 2),
- newOffset(newResultId(0, 1, 0), 2, 3)),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'grouplist:b', {prev=0}, [{ 'group:303', {}, [] }, { 'group:304', {}, [] }] }] }, " +
- "{ 'group:202', {}, [{ 'grouplist:b', {prev=1}, [{ 'group:308', {}, [] }] }] }] }] }");
+ newOffset(newResultId(0, 1, 0), 2, 3)),
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'grouplist:b', {prev=0}, [{ 'group:303', {}, [] }, { 'group:304', {}, [] }] }] }, " +
+ "{ 'group:202', {}, [{ 'grouplist:b', {prev=1}, [{ 'group:308', {}, [] }] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 0, 0), 2, 3),
- newOffset(newResultId(0, 1, 0), 2, 2)),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'grouplist:b', {prev=1}, [{ 'group:304', {}, [] }] }] }, " +
- "{ 'group:202', {}, [{ 'grouplist:b', {prev=0}, [{ 'group:307', {}, [] }, { 'group:308', {}, [] }] }] }] }] }");
+ newOffset(newResultId(0, 1, 0), 2, 2)),
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'grouplist:b', {prev=1}, [{ 'group:304', {}, [] }] }] }, " +
+ "{ 'group:202', {}, [{ 'grouplist:b', {prev=0}, [{ 'group:307', {}, [] }, { 'group:308', {}, [] }] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 0, 0), 2, 4),
- newOffset(newResultId(0, 1, 0), 2, 1)),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'grouplist:b', {prev=2}, [] }] }, " +
- "{ 'group:202', {}, [{ 'grouplist:b', {next=3, prev=0}, [{ 'group:306', {}, [] }, { 'group:307', {}, [] }] }] }] }] }");
+ newOffset(newResultId(0, 1, 0), 2, 1)),
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'grouplist:b', {prev=2}, [] }] }, " +
+ "{ 'group:202', {}, [{ 'grouplist:b', {next=3, prev=0}, [{ 'group:306', {}, [] }, { 'group:307', {}, [] }] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 0, 0), 2, 5),
- newOffset(newResultId(0, 1, 0), 2, 0)),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'grouplist:b', {prev=2}, [] }] }, " +
- "{ 'group:202', {}, [{ 'grouplist:b', {next=2}, [{ 'group:305', {}, [] }, { 'group:306', {}, [] }] }] }] }] }");
+ newOffset(newResultId(0, 1, 0), 2, 0)),
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'grouplist:b', {prev=2}, [] }] }, " +
+ "{ 'group:202', {}, [{ 'grouplist:b', {next=2}, [{ 'group:305', {}, [] }, { 'group:306', {}, [] }] }] }] }] }");
}
@Test
- public void requireThatGroupListContinuationsCanBeSetInSiblingGroupLists() {
+ void requireThatGroupListContinuationsCanBeSetInSiblingGroupLists() {
String request = "all(group(a) max(2) each(output(count())) as(foo)" +
- " each(output(count())) as(bar))";
+ " each(output(count())) as(bar))";
List<Grouping> result = Arrays.asList(newGrouping(newGroup(2, 1, new CountAggregationResult(1)),
- newGroup(2, 2, new CountAggregationResult(2)),
- newGroup(2, 3, new CountAggregationResult(3)),
- newGroup(2, 4, new CountAggregationResult(4))),
- newGrouping(newGroup(4, 1, new CountAggregationResult(1)),
- newGroup(4, 2, new CountAggregationResult(2)),
- newGroup(4, 3, new CountAggregationResult(3)),
- newGroup(4, 4, new CountAggregationResult(4))));
+ newGroup(2, 2, new CountAggregationResult(2)),
+ newGroup(2, 3, new CountAggregationResult(3)),
+ newGroup(2, 4, new CountAggregationResult(4))),
+ newGrouping(newGroup(4, 1, new CountAggregationResult(1)),
+ newGroup(4, 2, new CountAggregationResult(2)),
+ newGroup(4, 3, new CountAggregationResult(3)),
+ newGroup(4, 4, new CountAggregationResult(4))));
assertContinuation(request, result, newComposite(newOffset(newResultId(0), 2, 0),
- newOffset(newResultId(1), 4, 5)),
- "{ 'group:root', {}, [" +
- "{ 'grouplist:foo', {next=2}, [{ 'group:1', {}, [] }, { 'group:2', {}, [] }] }, " +
- "{ 'grouplist:bar', {prev=2}, [] }] }");
+ newOffset(newResultId(1), 4, 5)),
+ "{ 'group:root', {}, [" +
+ "{ 'grouplist:foo', {next=2}, [{ 'group:1', {}, [] }, { 'group:2', {}, [] }] }, " +
+ "{ 'grouplist:bar', {prev=2}, [] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0), 2, 1),
- newOffset(newResultId(1), 4, 4)),
- "{ 'group:root', {}, [" +
- "{ 'grouplist:foo', {next=3, prev=0}, [{ 'group:2', {}, [] }, { 'group:3', {}, [] }] }, " +
- "{ 'grouplist:bar', {prev=2}, [] }] }");
+ newOffset(newResultId(1), 4, 4)),
+ "{ 'group:root', {}, [" +
+ "{ 'grouplist:foo', {next=3, prev=0}, [{ 'group:2', {}, [] }, { 'group:3', {}, [] }] }, " +
+ "{ 'grouplist:bar', {prev=2}, [] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0), 2, 2),
- newOffset(newResultId(1), 4, 3)),
- "{ 'group:root', {}, [" +
- "{ 'grouplist:foo', {prev=0}, [{ 'group:3', {}, [] }, { 'group:4', {}, [] }] }, " +
- "{ 'grouplist:bar', {prev=1}, [{ 'group:4', {}, [] }] }] }");
+ newOffset(newResultId(1), 4, 3)),
+ "{ 'group:root', {}, [" +
+ "{ 'grouplist:foo', {prev=0}, [{ 'group:3', {}, [] }, { 'group:4', {}, [] }] }, " +
+ "{ 'grouplist:bar', {prev=1}, [{ 'group:4', {}, [] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0), 2, 3),
- newOffset(newResultId(1), 4, 2)),
- "{ 'group:root', {}, [" +
- "{ 'grouplist:foo', {prev=1}, [{ 'group:4', {}, [] }] }, " +
- "{ 'grouplist:bar', {prev=0}, [{ 'group:3', {}, [] }, { 'group:4', {}, [] }] }] }");
+ newOffset(newResultId(1), 4, 2)),
+ "{ 'group:root', {}, [" +
+ "{ 'grouplist:foo', {prev=1}, [{ 'group:4', {}, [] }] }, " +
+ "{ 'grouplist:bar', {prev=0}, [{ 'group:3', {}, [] }, { 'group:4', {}, [] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0), 2, 4),
- newOffset(newResultId(1), 4, 1)),
- "{ 'group:root', {}, [" +
- "{ 'grouplist:foo', {prev=2}, [] }, " +
- "{ 'grouplist:bar', {next=3, prev=0}, [{ 'group:2', {}, [] }, { 'group:3', {}, [] }] }] }");
+ newOffset(newResultId(1), 4, 1)),
+ "{ 'group:root', {}, [" +
+ "{ 'grouplist:foo', {prev=2}, [] }, " +
+ "{ 'grouplist:bar', {next=3, prev=0}, [{ 'group:2', {}, [] }, { 'group:3', {}, [] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0), 2, 5),
- newOffset(newResultId(1), 4, 0)),
- "{ 'group:root', {}, [" +
- "{ 'grouplist:foo', {prev=2}, [] }, " +
- "{ 'grouplist:bar', {next=2}, [{ 'group:1', {}, [] }, { 'group:2', {}, [] }] }] }");
+ newOffset(newResultId(1), 4, 0)),
+ "{ 'group:root', {}, [" +
+ "{ 'grouplist:foo', {prev=2}, [] }, " +
+ "{ 'grouplist:bar', {next=2}, [{ 'group:1', {}, [] }, { 'group:2', {}, [] }] }] }");
}
@Test
- public void requireThatUnstableContinuationsDoNotAffectSiblingGroupLists() {
+ void requireThatUnstableContinuationsDoNotAffectSiblingGroupLists() {
String request = "all(group(a) each(group(b) max(2) each(group(c) max(2) each(output(count())))))";
Grouping result = newGrouping(newGroup(2, 201,
- newGroup(3, 301,
- newGroup(4, 401, new CountAggregationResult(1)),
- newGroup(4, 402, new CountAggregationResult(1)),
- newGroup(4, 403, new CountAggregationResult(1)),
- newGroup(4, 404, new CountAggregationResult(1))),
- newGroup(3, 302,
- newGroup(4, 405, new CountAggregationResult(1)),
- newGroup(4, 406, new CountAggregationResult(1)),
- newGroup(4, 407, new CountAggregationResult(1)),
- newGroup(4, 408, new CountAggregationResult(1))),
- newGroup(3, 303,
- newGroup(4, 409, new CountAggregationResult(1)),
- newGroup(4, 410, new CountAggregationResult(1)),
- newGroup(4, 411, new CountAggregationResult(1)),
- newGroup(4, 412, new CountAggregationResult(1))),
- newGroup(3, 304,
- newGroup(4, 413, new CountAggregationResult(1)),
- newGroup(4, 414, new CountAggregationResult(1)),
- newGroup(4, 415, new CountAggregationResult(1)),
- newGroup(4, 416, new CountAggregationResult(1)))),
- newGroup(2, 202,
- newGroup(3, 305,
- newGroup(4, 417, new CountAggregationResult(1)),
- newGroup(4, 418, new CountAggregationResult(1)),
- newGroup(4, 419, new CountAggregationResult(1)),
- newGroup(4, 420, new CountAggregationResult(1))),
- newGroup(3, 306,
- newGroup(4, 421, new CountAggregationResult(1)),
- newGroup(4, 422, new CountAggregationResult(1)),
- newGroup(4, 423, new CountAggregationResult(1)),
- newGroup(4, 424, new CountAggregationResult(1))),
- newGroup(3, 307,
- newGroup(4, 425, new CountAggregationResult(1)),
- newGroup(4, 426, new CountAggregationResult(1)),
- newGroup(4, 427, new CountAggregationResult(1)),
- newGroup(4, 428, new CountAggregationResult(1))),
- newGroup(3, 308,
- newGroup(4, 429, new CountAggregationResult(1)),
- newGroup(4, 430, new CountAggregationResult(1)),
- newGroup(4, 431, new CountAggregationResult(1)),
- newGroup(4, 432, new CountAggregationResult(1)))));
+ newGroup(3, 301,
+ newGroup(4, 401, new CountAggregationResult(1)),
+ newGroup(4, 402, new CountAggregationResult(1)),
+ newGroup(4, 403, new CountAggregationResult(1)),
+ newGroup(4, 404, new CountAggregationResult(1))),
+ newGroup(3, 302,
+ newGroup(4, 405, new CountAggregationResult(1)),
+ newGroup(4, 406, new CountAggregationResult(1)),
+ newGroup(4, 407, new CountAggregationResult(1)),
+ newGroup(4, 408, new CountAggregationResult(1))),
+ newGroup(3, 303,
+ newGroup(4, 409, new CountAggregationResult(1)),
+ newGroup(4, 410, new CountAggregationResult(1)),
+ newGroup(4, 411, new CountAggregationResult(1)),
+ newGroup(4, 412, new CountAggregationResult(1))),
+ newGroup(3, 304,
+ newGroup(4, 413, new CountAggregationResult(1)),
+ newGroup(4, 414, new CountAggregationResult(1)),
+ newGroup(4, 415, new CountAggregationResult(1)),
+ newGroup(4, 416, new CountAggregationResult(1)))),
+ newGroup(2, 202,
+ newGroup(3, 305,
+ newGroup(4, 417, new CountAggregationResult(1)),
+ newGroup(4, 418, new CountAggregationResult(1)),
+ newGroup(4, 419, new CountAggregationResult(1)),
+ newGroup(4, 420, new CountAggregationResult(1))),
+ newGroup(3, 306,
+ newGroup(4, 421, new CountAggregationResult(1)),
+ newGroup(4, 422, new CountAggregationResult(1)),
+ newGroup(4, 423, new CountAggregationResult(1)),
+ newGroup(4, 424, new CountAggregationResult(1))),
+ newGroup(3, 307,
+ newGroup(4, 425, new CountAggregationResult(1)),
+ newGroup(4, 426, new CountAggregationResult(1)),
+ newGroup(4, 427, new CountAggregationResult(1)),
+ newGroup(4, 428, new CountAggregationResult(1))),
+ newGroup(3, 308,
+ newGroup(4, 429, new CountAggregationResult(1)),
+ newGroup(4, 430, new CountAggregationResult(1)),
+ newGroup(4, 431, new CountAggregationResult(1)),
+ newGroup(4, 432, new CountAggregationResult(1)))));
assertContinuation(request, result, newComposite(),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'grouplist:b', {next=2}, [" +
- "{ 'group:301', {}, [{ 'grouplist:c', {next=2}, [{ 'group:401', {}, [] }, { 'group:402', {}, [] }] }] }, " +
- "{ 'group:302', {}, [{ 'grouplist:c', {next=2}, [{ 'group:405', {}, [] }, { 'group:406', {}, [] }] }] }] }] }, " +
- "{ 'group:202', {}, [{ 'grouplist:b', {next=2}, [" +
- "{ 'group:305', {}, [{ 'grouplist:c', {next=2}, [{ 'group:417', {}, [] }, { 'group:418', {}, [] }] }] }, " +
- "{ 'group:306', {}, [{ 'grouplist:c', {next=2}, [{ 'group:421', {}, [] }, { 'group:422', {}, [] }] }] }] }] }] }] }");
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'grouplist:b', {next=2}, [" +
+ "{ 'group:301', {}, [{ 'grouplist:c', {next=2}, [{ 'group:401', {}, [] }, { 'group:402', {}, [] }] }] }, " +
+ "{ 'group:302', {}, [{ 'grouplist:c', {next=2}, [{ 'group:405', {}, [] }, { 'group:406', {}, [] }] }] }] }] }, " +
+ "{ 'group:202', {}, [{ 'grouplist:b', {next=2}, [" +
+ "{ 'group:305', {}, [{ 'grouplist:c', {next=2}, [{ 'group:417', {}, [] }, { 'group:418', {}, [] }] }] }, " +
+ "{ 'group:306', {}, [{ 'grouplist:c', {next=2}, [{ 'group:421', {}, [] }, { 'group:422', {}, [] }] }] }] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 1, 0, 1, 0), 4, 2)),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'grouplist:b', {next=2}, [" +
- "{ 'group:301', {}, [{ 'grouplist:c', {next=2}, [{ 'group:401', {}, [] }, { 'group:402', {}, [] }] }] }, " +
- "{ 'group:302', {}, [{ 'grouplist:c', {next=2}, [{ 'group:405', {}, [] }, { 'group:406', {}, [] }] }] }] }] }, " +
- "{ 'group:202', {}, [{ 'grouplist:b', {next=2}, [" +
- "{ 'group:305', {}, [{ 'grouplist:c', {next=2}, [{ 'group:417', {}, [] }, { 'group:418', {}, [] }] }] }, " +
- "{ 'group:306', {}, [{ 'grouplist:c', {prev=0}, [{ 'group:423', {}, [] }, { 'group:424', {}, [] }] }] }] }] }] }] }");
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'grouplist:b', {next=2}, [" +
+ "{ 'group:301', {}, [{ 'grouplist:c', {next=2}, [{ 'group:401', {}, [] }, { 'group:402', {}, [] }] }] }, " +
+ "{ 'group:302', {}, [{ 'grouplist:c', {next=2}, [{ 'group:405', {}, [] }, { 'group:406', {}, [] }] }] }] }] }, " +
+ "{ 'group:202', {}, [{ 'grouplist:b', {next=2}, [" +
+ "{ 'group:305', {}, [{ 'grouplist:c', {next=2}, [{ 'group:417', {}, [] }, { 'group:418', {}, [] }] }] }, " +
+ "{ 'group:306', {}, [{ 'grouplist:c', {prev=0}, [{ 'group:423', {}, [] }, { 'group:424', {}, [] }] }] }] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 1, 0, 1, 0), 4, 2),
- newOffset(newResultId(0, 0, 0), 2, 2)),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'grouplist:b', {prev=0}, [" +
- "{ 'group:303', {}, [{ 'grouplist:c', {next=2}, [{ 'group:409', {}, [] }, { 'group:410', {}, [] }] }] }, " +
- "{ 'group:304', {}, [{ 'grouplist:c', {next=2}, [{ 'group:413', {}, [] }, { 'group:414', {}, [] }] }] }] }] }, " +
- "{ 'group:202', {}, [{ 'grouplist:b', {next=2}, [" +
- "{ 'group:305', {}, [{ 'grouplist:c', {next=2}, [{ 'group:417', {}, [] }, { 'group:418', {}, [] }] }] }, " +
- "{ 'group:306', {}, [{ 'grouplist:c', {prev=0}, [{ 'group:423', {}, [] }, { 'group:424', {}, [] }] }] }] }] }] }] }");
+ newOffset(newResultId(0, 0, 0), 2, 2)),
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'grouplist:b', {prev=0}, [" +
+ "{ 'group:303', {}, [{ 'grouplist:c', {next=2}, [{ 'group:409', {}, [] }, { 'group:410', {}, [] }] }] }, " +
+ "{ 'group:304', {}, [{ 'grouplist:c', {next=2}, [{ 'group:413', {}, [] }, { 'group:414', {}, [] }] }] }] }] }, " +
+ "{ 'group:202', {}, [{ 'grouplist:b', {next=2}, [" +
+ "{ 'group:305', {}, [{ 'grouplist:c', {next=2}, [{ 'group:417', {}, [] }, { 'group:418', {}, [] }] }] }, " +
+ "{ 'group:306', {}, [{ 'grouplist:c', {prev=0}, [{ 'group:423', {}, [] }, { 'group:424', {}, [] }] }] }] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 1, 0, 1, 0), 4, 2),
- newOffset(newResultId(0, 0, 0), 2, 2),
- newUnstableOffset(newResultId(0, 1, 0), 2, 1)),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'grouplist:b', {prev=0}, [" +
- "{ 'group:303', {}, [{ 'grouplist:c', {next=2}, [{ 'group:409', {}, [] }, { 'group:410', {}, [] }] }] }, " +
- "{ 'group:304', {}, [{ 'grouplist:c', {next=2}, [{ 'group:413', {}, [] }, { 'group:414', {}, [] }] }] }] }] }, " +
- "{ 'group:202', {}, [{ 'grouplist:b', {next=3, prev=0}, [" +
- "{ 'group:306', {}, [{ 'grouplist:c', {next=2}, [{ 'group:421', {}, [] }, { 'group:422', {}, [] }] }] }, " +
- "{ 'group:307', {}, [{ 'grouplist:c', {next=2}, [{ 'group:425', {}, [] }, { 'group:426', {}, [] }] }] }] }] }] }] }");
+ newOffset(newResultId(0, 0, 0), 2, 2),
+ newUnstableOffset(newResultId(0, 1, 0), 2, 1)),
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'grouplist:b', {prev=0}, [" +
+ "{ 'group:303', {}, [{ 'grouplist:c', {next=2}, [{ 'group:409', {}, [] }, { 'group:410', {}, [] }] }] }, " +
+ "{ 'group:304', {}, [{ 'grouplist:c', {next=2}, [{ 'group:413', {}, [] }, { 'group:414', {}, [] }] }] }] }] }, " +
+ "{ 'group:202', {}, [{ 'grouplist:b', {next=3, prev=0}, [" +
+ "{ 'group:306', {}, [{ 'grouplist:c', {next=2}, [{ 'group:421', {}, [] }, { 'group:422', {}, [] }] }] }, " +
+ "{ 'group:307', {}, [{ 'grouplist:c', {next=2}, [{ 'group:425', {}, [] }, { 'group:426', {}, [] }] }] }] }] }] }] }");
}
@Test
- public void requireThatUnstableContinuationsAffectAllDecendants() {
+ void requireThatUnstableContinuationsAffectAllDecendants() {
String request = "all(group(a) each(group(b) max(1) each(group(c) max(1) each(group(d) max(1) each(output(count()))))))";
Grouping result = newGrouping(newGroup(2, 201,
- newGroup(3, 301,
- newGroup(4, 401,
- newGroup(5, 501, new CountAggregationResult(1)),
- newGroup(5, 502, new CountAggregationResult(1))),
- newGroup(4, 402,
- newGroup(5, 503, new CountAggregationResult(1)),
- newGroup(5, 504, new CountAggregationResult(1)))),
- newGroup(3, 302,
- newGroup(4, 403,
- newGroup(5, 505, new CountAggregationResult(1)),
- newGroup(5, 506, new CountAggregationResult(1))),
- newGroup(4, 404,
- newGroup(5, 507, new CountAggregationResult(1)),
- newGroup(5, 508, new CountAggregationResult(1))))));
+ newGroup(3, 301,
+ newGroup(4, 401,
+ newGroup(5, 501, new CountAggregationResult(1)),
+ newGroup(5, 502, new CountAggregationResult(1))),
+ newGroup(4, 402,
+ newGroup(5, 503, new CountAggregationResult(1)),
+ newGroup(5, 504, new CountAggregationResult(1)))),
+ newGroup(3, 302,
+ newGroup(4, 403,
+ newGroup(5, 505, new CountAggregationResult(1)),
+ newGroup(5, 506, new CountAggregationResult(1))),
+ newGroup(4, 404,
+ newGroup(5, 507, new CountAggregationResult(1)),
+ newGroup(5, 508, new CountAggregationResult(1))))));
assertContinuation(request, result, newComposite(),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'grouplist:b', {next=1}, [" +
- "{ 'group:301', {}, [{ 'grouplist:c', {next=1}, [" +
- "{ 'group:401', {}, [{ 'grouplist:d', {next=1}, [" +
- "{ 'group:501', {}, [] }] }] }] }] }] }] }] }] }");
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'grouplist:b', {next=1}, [" +
+ "{ 'group:301', {}, [{ 'grouplist:c', {next=1}, [" +
+ "{ 'group:401', {}, [{ 'grouplist:d', {next=1}, [" +
+ "{ 'group:501', {}, [] }] }] }] }] }] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 0, 0, 0, 0, 0, 0), 5, 1)),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'grouplist:b', {next=1}, [" +
- "{ 'group:301', {}, [{ 'grouplist:c', {next=1}, [" +
- "{ 'group:401', {}, [{ 'grouplist:d', {prev=0}, [" +
- "{ 'group:502', {}, [] }] }] }] }] }] }] }] }] }");
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'grouplist:b', {next=1}, [" +
+ "{ 'group:301', {}, [{ 'grouplist:c', {next=1}, [" +
+ "{ 'group:401', {}, [{ 'grouplist:d', {prev=0}, [" +
+ "{ 'group:502', {}, [] }] }] }] }] }] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 0, 0, 0, 0, 0, 0), 5, 1),
- newUnstableOffset(newResultId(0, 0, 0, 0, 0), 4, 1)),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'grouplist:b', {next=1}, [" +
- "{ 'group:301', {}, [{ 'grouplist:c', {prev=0}, [" +
- "{ 'group:402', {}, [{ 'grouplist:d', {next=1}, [" +
- "{ 'group:503', {}, [] }] }] }] }] }] }] }] }] }");
+ newUnstableOffset(newResultId(0, 0, 0, 0, 0), 4, 1)),
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'grouplist:b', {next=1}, [" +
+ "{ 'group:301', {}, [{ 'grouplist:c', {prev=0}, [" +
+ "{ 'group:402', {}, [{ 'grouplist:d', {next=1}, [" +
+ "{ 'group:503', {}, [] }] }] }] }] }] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 0, 0, 0, 0, 0, 0), 5, 1),
- newUnstableOffset(newResultId(0, 0, 0, 0, 0), 4, 1),
- newUnstableOffset(newResultId(0, 0, 0), 3, 1)),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'grouplist:b', {prev=0}, [" +
- "{ 'group:302', {}, [{ 'grouplist:c', {next=1}, [" +
- "{ 'group:403', {}, [{ 'grouplist:d', {next=1}, [" +
- "{ 'group:505', {}, [] }] }] }] }] }] }] }] }] }");
+ newUnstableOffset(newResultId(0, 0, 0, 0, 0), 4, 1),
+ newUnstableOffset(newResultId(0, 0, 0), 3, 1)),
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'grouplist:b', {prev=0}, [" +
+ "{ 'group:302', {}, [{ 'grouplist:c', {next=1}, [" +
+ "{ 'group:403', {}, [{ 'grouplist:d', {next=1}, [" +
+ "{ 'group:505', {}, [] }] }] }] }] }] }] }] }] }");
}
@Test
- public void requireThatHitListContinuationsAreNotCreatedUnlessMaxIsSet() {
+ void requireThatHitListContinuationsAreNotCreatedUnlessMaxIsSet() {
assertContinuation("all(group(a) each(each(output(summary()))))",
- newGrouping(newGroup(2, newHitList(3, 4))),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:2', {}, [{ 'hitlist:hits', {}, [hit:1, hit:2, hit:3, hit:4] }] }] }] }");
+ newGrouping(newGroup(2, newHitList(3, 4))),
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:2', {}, [{ 'hitlist:hits', {}, [hit:1, hit:2, hit:3, hit:4] }] }] }] }");
}
@Test
- public void requireThatHitListContinuationsCanBeSet() {
+ void requireThatHitListContinuationsCanBeSet() {
String request = "all(group(a) each(max(2) each(output(summary()))))";
Grouping result = newGrouping(newGroup(2, newHitList(3, 4)));
assertContinuation(request, result, newOffset(newResultId(0, 0, 0), 3, 0),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:2', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }] }] }");
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:2', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }] }] }");
assertContinuation(request, result, newOffset(newResultId(0, 0, 0), 3, 1),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:2', {}, [{ 'hitlist:hits', {next=3, prev=0}, [hit:2, hit:3] }] }] }] }");
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:2', {}, [{ 'hitlist:hits', {next=3, prev=0}, [hit:2, hit:3] }] }] }] }");
assertContinuation(request, result, newOffset(newResultId(0, 0, 0), 3, 2),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:2', {}, [{ 'hitlist:hits', {prev=0}, [hit:3, hit:4] }] }] }] }");
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:2', {}, [{ 'hitlist:hits', {prev=0}, [hit:3, hit:4] }] }] }] }");
assertContinuation(request, result, newOffset(newResultId(0, 0, 0), 3, 3),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:2', {}, [{ 'hitlist:hits', {prev=1}, [hit:4] }] }] }] }");
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:2', {}, [{ 'hitlist:hits', {prev=1}, [hit:4] }] }] }] }");
assertContinuation(request, result, newOffset(newResultId(0, 0, 0), 3, 4),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:2', {}, [{ 'hitlist:hits', {prev=2}, [] }] }] }] }");
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:2', {}, [{ 'hitlist:hits', {prev=2}, [] }] }] }] }");
assertContinuation(request, result, newOffset(newResultId(0, 0, 0), 3, 5),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:2', {}, [{ 'hitlist:hits', {prev=2}, [] }] }] }] }");
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:2', {}, [{ 'hitlist:hits', {prev=2}, [] }] }] }] }");
}
@Test
- public void requireThatHitListContinuationsCanBeSetInSiblingGroups() {
+ void requireThatHitListContinuationsCanBeSetInSiblingGroups() {
String request = "all(group(a) each(max(2) each(output(summary()))))";
Grouping result = newGrouping(newGroup(2, 201, newHitList(3, 4)),
- newGroup(2, 202, newHitList(3, 4)));
+ newGroup(2, 202, newHitList(3, 4)));
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 0, 0), 3, 0),
- newOffset(newResultId(0, 1, 0), 3, 5)),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }, " +
- "{ 'group:202', {}, [{ 'hitlist:hits', {prev=2}, [] }] }] }] }");
+ newOffset(newResultId(0, 1, 0), 3, 5)),
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }, " +
+ "{ 'group:202', {}, [{ 'hitlist:hits', {prev=2}, [] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 0, 0), 3, 1),
- newOffset(newResultId(0, 1, 0), 3, 4)),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'hitlist:hits', {next=3, prev=0}, [hit:2, hit:3] }] }, " +
- "{ 'group:202', {}, [{ 'hitlist:hits', {prev=2}, [] }] }] }] }");
+ newOffset(newResultId(0, 1, 0), 3, 4)),
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'hitlist:hits', {next=3, prev=0}, [hit:2, hit:3] }] }, " +
+ "{ 'group:202', {}, [{ 'hitlist:hits', {prev=2}, [] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 0, 0), 3, 2),
- newOffset(newResultId(0, 1, 0), 3, 3)),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'hitlist:hits', {prev=0}, [hit:3, hit:4] }] }, " +
- "{ 'group:202', {}, [{ 'hitlist:hits', {prev=1}, [hit:4] }] }] }] }");
+ newOffset(newResultId(0, 1, 0), 3, 3)),
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'hitlist:hits', {prev=0}, [hit:3, hit:4] }] }, " +
+ "{ 'group:202', {}, [{ 'hitlist:hits', {prev=1}, [hit:4] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 0, 0), 3, 3),
- newOffset(newResultId(0, 1, 0), 3, 2)),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'hitlist:hits', {prev=1}, [hit:4] }] }, " +
- "{ 'group:202', {}, [{ 'hitlist:hits', {prev=0}, [hit:3, hit:4] }] }] }] }");
+ newOffset(newResultId(0, 1, 0), 3, 2)),
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'hitlist:hits', {prev=1}, [hit:4] }] }, " +
+ "{ 'group:202', {}, [{ 'hitlist:hits', {prev=0}, [hit:3, hit:4] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 0, 0), 3, 4),
- newOffset(newResultId(0, 1, 0), 3, 1)),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'hitlist:hits', {prev=2}, [] }] }, " +
- "{ 'group:202', {}, [{ 'hitlist:hits', {next=3, prev=0}, [hit:2, hit:3] }] }] }] }");
+ newOffset(newResultId(0, 1, 0), 3, 1)),
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'hitlist:hits', {prev=2}, [] }] }, " +
+ "{ 'group:202', {}, [{ 'hitlist:hits', {next=3, prev=0}, [hit:2, hit:3] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 0, 0), 3, 5),
- newOffset(newResultId(0, 1, 0), 3, 0)),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'hitlist:hits', {prev=2}, [] }] }, " +
- "{ 'group:202', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }] }] }");
+ newOffset(newResultId(0, 1, 0), 3, 0)),
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'hitlist:hits', {prev=2}, [] }] }, " +
+ "{ 'group:202', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }] }] }");
}
@Test
- public void requireThatHitListContinuationsCanBeSetInSiblingHitLists() {
+ void requireThatHitListContinuationsCanBeSetInSiblingHitLists() {
String request = "all(group(a) each(max(2) each(output(summary()))) as(foo)" +
- " each(max(2) each(output(summary()))) as(bar))";
+ " each(max(2) each(output(summary()))) as(bar))";
List<Grouping> result = Arrays.asList(newGrouping(newGroup(2, newHitList(3, 4))),
- newGrouping(newGroup(4, newHitList(5, 4))));
+ newGrouping(newGroup(4, newHitList(5, 4))));
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 0, 0), 3, 0),
- newOffset(newResultId(1, 0, 0), 5, 5)),
- "{ 'group:root', {}, [" +
- "{ 'grouplist:foo', {}, [{ 'group:2', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }] }, " +
- "{ 'grouplist:bar', {}, [{ 'group:4', {}, [{ 'hitlist:hits', {prev=2}, [] }] }] }] }");
+ newOffset(newResultId(1, 0, 0), 5, 5)),
+ "{ 'group:root', {}, [" +
+ "{ 'grouplist:foo', {}, [{ 'group:2', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }] }, " +
+ "{ 'grouplist:bar', {}, [{ 'group:4', {}, [{ 'hitlist:hits', {prev=2}, [] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 0, 0), 3, 1),
- newOffset(newResultId(1, 0, 0), 5, 4)),
- "{ 'group:root', {}, [" +
- "{ 'grouplist:foo', {}, [{ 'group:2', {}, [{ 'hitlist:hits', {next=3, prev=0}, [hit:2, hit:3] }] }] }, " +
- "{ 'grouplist:bar', {}, [{ 'group:4', {}, [{ 'hitlist:hits', {prev=2}, [] }] }] }] }");
+ newOffset(newResultId(1, 0, 0), 5, 4)),
+ "{ 'group:root', {}, [" +
+ "{ 'grouplist:foo', {}, [{ 'group:2', {}, [{ 'hitlist:hits', {next=3, prev=0}, [hit:2, hit:3] }] }] }, " +
+ "{ 'grouplist:bar', {}, [{ 'group:4', {}, [{ 'hitlist:hits', {prev=2}, [] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 0, 0), 3, 2),
- newOffset(newResultId(1, 0, 0), 5, 3)),
- "{ 'group:root', {}, [" +
- "{ 'grouplist:foo', {}, [{ 'group:2', {}, [{ 'hitlist:hits', {prev=0}, [hit:3, hit:4] }] }] }, " +
- "{ 'grouplist:bar', {}, [{ 'group:4', {}, [{ 'hitlist:hits', {prev=1}, [hit:4] }] }] }] }");
+ newOffset(newResultId(1, 0, 0), 5, 3)),
+ "{ 'group:root', {}, [" +
+ "{ 'grouplist:foo', {}, [{ 'group:2', {}, [{ 'hitlist:hits', {prev=0}, [hit:3, hit:4] }] }] }, " +
+ "{ 'grouplist:bar', {}, [{ 'group:4', {}, [{ 'hitlist:hits', {prev=1}, [hit:4] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 0, 0), 3, 3),
- newOffset(newResultId(1, 0, 0), 5, 2)),
- "{ 'group:root', {}, [" +
- "{ 'grouplist:foo', {}, [{ 'group:2', {}, [{ 'hitlist:hits', {prev=1}, [hit:4] }] }] }, " +
- "{ 'grouplist:bar', {}, [{ 'group:4', {}, [{ 'hitlist:hits', {prev=0}, [hit:3, hit:4] }] }] }] }");
+ newOffset(newResultId(1, 0, 0), 5, 2)),
+ "{ 'group:root', {}, [" +
+ "{ 'grouplist:foo', {}, [{ 'group:2', {}, [{ 'hitlist:hits', {prev=1}, [hit:4] }] }] }, " +
+ "{ 'grouplist:bar', {}, [{ 'group:4', {}, [{ 'hitlist:hits', {prev=0}, [hit:3, hit:4] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 0, 0), 3, 4),
- newOffset(newResultId(1, 0, 0), 5, 1)),
- "{ 'group:root', {}, [" +
- "{ 'grouplist:foo', {}, [{ 'group:2', {}, [{ 'hitlist:hits', {prev=2}, [] }] }] }, " +
- "{ 'grouplist:bar', {}, [{ 'group:4', {}, [{ 'hitlist:hits', {next=3, prev=0}, [hit:2, hit:3] }] }] }] }");
+ newOffset(newResultId(1, 0, 0), 5, 1)),
+ "{ 'group:root', {}, [" +
+ "{ 'grouplist:foo', {}, [{ 'group:2', {}, [{ 'hitlist:hits', {prev=2}, [] }] }] }, " +
+ "{ 'grouplist:bar', {}, [{ 'group:4', {}, [{ 'hitlist:hits', {next=3, prev=0}, [hit:2, hit:3] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 0, 0), 3, 5),
- newOffset(newResultId(1, 0, 0), 5, 0)),
- "{ 'group:root', {}, [" +
- "{ 'grouplist:foo', {}, [{ 'group:2', {}, [{ 'hitlist:hits', {prev=2}, [] }] }] }, " +
- "{ 'grouplist:bar', {}, [{ 'group:4', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }] }] }");
+ newOffset(newResultId(1, 0, 0), 5, 0)),
+ "{ 'group:root', {}, [" +
+ "{ 'grouplist:foo', {}, [{ 'group:2', {}, [{ 'hitlist:hits', {prev=2}, [] }] }] }, " +
+ "{ 'grouplist:bar', {}, [{ 'group:4', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }] }] }");
}
@Test
- public void requireThatUnstableContinuationsDoNotAffectSiblingHitLists() {
+ void requireThatUnstableContinuationsDoNotAffectSiblingHitLists() {
String request = "all(group(a) each(group(b) max(2) each(max(2) each(output(summary())))))";
Grouping result = newGrouping(newGroup(2, 201,
- newGroup(3, 301, newHitList(4, 4)),
- newGroup(3, 302, newHitList(4, 4)),
- newGroup(3, 303, newHitList(4, 4)),
- newGroup(3, 304, newHitList(4, 4))),
- newGroup(2, 202,
- newGroup(3, 305, newHitList(4, 4)),
- newGroup(3, 306, newHitList(4, 4)),
- newGroup(3, 307, newHitList(4, 4)),
- newGroup(3, 308, newHitList(4, 4))));
+ newGroup(3, 301, newHitList(4, 4)),
+ newGroup(3, 302, newHitList(4, 4)),
+ newGroup(3, 303, newHitList(4, 4)),
+ newGroup(3, 304, newHitList(4, 4))),
+ newGroup(2, 202,
+ newGroup(3, 305, newHitList(4, 4)),
+ newGroup(3, 306, newHitList(4, 4)),
+ newGroup(3, 307, newHitList(4, 4)),
+ newGroup(3, 308, newHitList(4, 4))));
assertContinuation(request, result, newComposite(),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'grouplist:b', {next=2}, [" +
- "{ 'group:301', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }, " +
- "{ 'group:302', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }] }] }, " +
- "{ 'group:202', {}, [{ 'grouplist:b', {next=2}, [" +
- "{ 'group:305', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }, " +
- "{ 'group:306', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }] }] }] }] }");
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'grouplist:b', {next=2}, [" +
+ "{ 'group:301', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }, " +
+ "{ 'group:302', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }] }] }, " +
+ "{ 'group:202', {}, [{ 'grouplist:b', {next=2}, [" +
+ "{ 'group:305', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }, " +
+ "{ 'group:306', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 1, 0, 1, 0), 4, 2)),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'grouplist:b', {next=2}, [" +
- "{ 'group:301', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }, " +
- "{ 'group:302', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }] }] }, " +
- "{ 'group:202', {}, [{ 'grouplist:b', {next=2}, [" +
- "{ 'group:305', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }, " +
- "{ 'group:306', {}, [{ 'hitlist:hits', {prev=0}, [hit:3, hit:4] }] }] }] }] }] }");
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'grouplist:b', {next=2}, [" +
+ "{ 'group:301', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }, " +
+ "{ 'group:302', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }] }] }, " +
+ "{ 'group:202', {}, [{ 'grouplist:b', {next=2}, [" +
+ "{ 'group:305', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }, " +
+ "{ 'group:306', {}, [{ 'hitlist:hits', {prev=0}, [hit:3, hit:4] }] }] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 1, 0, 1, 0), 4, 2),
- newOffset(newResultId(0, 0, 0), 2, 2)),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'grouplist:b', {prev=0}, [" +
- "{ 'group:303', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }, " +
- "{ 'group:304', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }] }] }, " +
- "{ 'group:202', {}, [{ 'grouplist:b', {next=2}, [" +
- "{ 'group:305', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }, " +
- "{ 'group:306', {}, [{ 'hitlist:hits', {prev=0}, [hit:3, hit:4] }] }] }] }] }] }");
+ newOffset(newResultId(0, 0, 0), 2, 2)),
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'grouplist:b', {prev=0}, [" +
+ "{ 'group:303', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }, " +
+ "{ 'group:304', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }] }] }, " +
+ "{ 'group:202', {}, [{ 'grouplist:b', {next=2}, [" +
+ "{ 'group:305', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }, " +
+ "{ 'group:306', {}, [{ 'hitlist:hits', {prev=0}, [hit:3, hit:4] }] }] }] }] }] }");
assertContinuation(request, result, newComposite(newOffset(newResultId(0, 1, 0, 1, 0), 4, 2),
- newOffset(newResultId(0, 0, 0), 2, 2),
- newUnstableOffset(newResultId(0, 1, 0), 2, 1)),
- "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
- "{ 'group:201', {}, [{ 'grouplist:b', {prev=0}, [" +
- "{ 'group:303', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }, " +
- "{ 'group:304', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }] }] }, " +
- "{ 'group:202', {}, [{ 'grouplist:b', {next=3, prev=0}, [" +
- "{ 'group:306', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }, " +
- "{ 'group:307', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }] }] }] }] }");
+ newOffset(newResultId(0, 0, 0), 2, 2),
+ newUnstableOffset(newResultId(0, 1, 0), 2, 1)),
+ "{ 'group:root', {}, [{ 'grouplist:a', {}, [" +
+ "{ 'group:201', {}, [{ 'grouplist:b', {prev=0}, [" +
+ "{ 'group:303', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }, " +
+ "{ 'group:304', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }] }] }, " +
+ "{ 'group:202', {}, [{ 'grouplist:b', {next=3, prev=0}, [" +
+ "{ 'group:306', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }, " +
+ "{ 'group:307', {}, [{ 'hitlist:hits', {next=2}, [hit:1, hit:2] }] }] }] }] }] }");
}
// --------------------------------------------------------------------------------
diff --git a/container-search/src/test/java/com/yahoo/search/grouping/vespa/ResultIdTestCase.java b/container-search/src/test/java/com/yahoo/search/grouping/vespa/ResultIdTestCase.java
index 8afaa4922ec..0e38e688258 100644
--- a/container-search/src/test/java/com/yahoo/search/grouping/vespa/ResultIdTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/grouping/vespa/ResultIdTestCase.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.search.grouping.vespa;
-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.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -13,7 +11,7 @@ import static org.junit.Assert.assertTrue;
public class ResultIdTestCase {
@Test
- public void requireThatStartsWithWorks() {
+ void requireThatStartsWithWorks() {
assertFalse(ResultId.valueOf().startsWith(1, 1, 2, 3));
assertFalse(ResultId.valueOf(1).startsWith(1, 1, 2, 3));
assertFalse(ResultId.valueOf(1, 1).startsWith(1, 1, 2, 3));
@@ -26,32 +24,32 @@ public class ResultIdTestCase {
}
@Test
- public void requireThatChildIdStartsWithParentId() {
+ void requireThatChildIdStartsWithParentId() {
ResultId parentId = ResultId.valueOf(1, 1, 2);
ResultId childId = parentId.newChildId(3);
assertTrue(childId.startsWith(1, 1, 2));
}
@Test
- public void requireThatHashCodeIsImplemented() {
+ void requireThatHashCodeIsImplemented() {
assertEquals(ResultId.valueOf(1, 1, 2, 3).hashCode(), ResultId.valueOf(1, 1, 2, 3).hashCode());
- assertFalse(ResultId.valueOf(1, 1, 2, 3).hashCode() == ResultId.valueOf(5, 8, 13, 21).hashCode());
+ assertNotNull(ResultId.valueOf(5, 8, 13, 21).hashCode());
}
@Test
- public void requireThatEqualsIsImplemented() {
+ void requireThatEqualsIsImplemented() {
assertEquals(ResultId.valueOf(1, 1, 2, 3), ResultId.valueOf(1, 1, 2, 3));
- assertFalse(ResultId.valueOf(1, 1, 2, 3).equals(ResultId.valueOf(5, 8, 13, 21)));
+ assertNotEquals(ResultId.valueOf(1, 1, 2, 3), ResultId.valueOf(5, 8, 13, 21));
}
@Test
- public void requireThatResultIdCanBeEncoded() {
+ void requireThatResultIdCanBeEncoded() {
assertEncode("BIBCBCBEBG", ResultId.valueOf(1, 1, 2, 3));
assertEncode("BIBKCBACBKCCK", ResultId.valueOf(5, 8, 13, 21));
}
@Test
- public void requireThatResultIdCanBeDecoded() {
+ void requireThatResultIdCanBeDecoded() {
assertDecode(ResultId.valueOf(1, 1, 2, 3), "BIBCBCBEBG");
assertDecode(ResultId.valueOf(5, 8, 13, 21), "BIBKCBACBKCCK");
}
diff --git a/container-search/src/test/java/com/yahoo/search/handler/JSONSearchHandlerTestCase.java b/container-search/src/test/java/com/yahoo/search/handler/JSONSearchHandlerTestCase.java
index b0b88bf8190..83022ccf3ff 100644
--- a/container-search/src/test/java/com/yahoo/search/handler/JSONSearchHandlerTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/handler/JSONSearchHandlerTestCase.java
@@ -17,12 +17,11 @@ import com.yahoo.slime.Inspector;
import com.yahoo.slime.SlimeUtils;
import com.yahoo.test.json.JsonTestHelper;
import org.assertj.core.api.Assertions;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import java.io.ByteArrayInputStream;
import java.io.File;
@@ -32,12 +31,12 @@ import java.util.Map;
import java.util.Random;
import static com.yahoo.jdisc.http.HttpRequest.Method.GET;
-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.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.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Tests submitting the query as JSON.
@@ -56,16 +55,16 @@ public class JSONSearchHandlerTestCase {
private static final String uri = "http://localhost?";
private static final String JSON_CONTENT_TYPE = "application/json";
- @Rule
- public TemporaryFolder tempfolder = new TemporaryFolder();
+ @TempDir
+ public File tempfolder;
private RequestHandlerTestDriver driver = null;
private HandlersConfigurerTestWrapper configurer = null;
private SearchHandler searchHandler;
- @Before
+ @BeforeEach
public void startUp() throws IOException {
- File cfgDir = tempfolder.newFolder("SearchHandlerTestCase");
+ File cfgDir = newFolder(tempfolder, "SearchHandlerTestCase");
tempDir = cfgDir.getAbsolutePath();
String configId = "dir:" + tempDir;
@@ -77,7 +76,7 @@ public class JSONSearchHandlerTestCase {
driver = new RequestHandlerTestDriver(searchHandler);
}
- @After
+ @AfterEach
public void shutDown() {
if (configurer != null) configurer.shutdown();
if (driver != null) driver.close();
@@ -96,7 +95,7 @@ public class JSONSearchHandlerTestCase {
}
@Test
- public void testBadJSON() {
+ void testBadJSON() {
String json = "Not a valid JSON-string";
RequestHandlerTestDriver.MockResponseHandler responseHandler = driver.sendRequest(uri, com.yahoo.jdisc.http.HttpRequest.Method.POST, json, JSON_CONTENT_TYPE);
String response = responseHandler.readAll();
@@ -106,7 +105,7 @@ public class JSONSearchHandlerTestCase {
}
@Test
- public void testFailing() {
+ void testFailing() {
ObjectNode json = jsonMapper.createObjectNode();
json.put("query", "test");
json.put("searchChain", "classLoadingError");
@@ -115,7 +114,7 @@ public class JSONSearchHandlerTestCase {
@Test
- public synchronized void testPluginError() {
+ synchronized void testPluginError() {
ObjectNode json = jsonMapper.createObjectNode();
json.put("query", "test");
json.put("searchChain", "exceptionInPlugin");
@@ -123,7 +122,7 @@ public class JSONSearchHandlerTestCase {
}
@Test
- public synchronized void testWorkingReconfiguration() throws IOException {
+ synchronized void testWorkingReconfiguration() throws IOException {
ObjectNode json = jsonMapper.createObjectNode();
json.put("query", "abc");
assertJsonResult(json, driver);
@@ -135,22 +134,22 @@ public class JSONSearchHandlerTestCase {
// ...and check the resulting config
SearchHandler newSearchHandler = fetchSearchHandler(configurer);
- assertNotSame("Have a new instance of the search handler", searchHandler, newSearchHandler);
- assertNotNull("Have the new search chain", fetchSearchHandler(configurer).getSearchChainRegistry().getChain("hello"));
- assertNull("Don't have the new search chain", fetchSearchHandler(configurer).getSearchChainRegistry().getChain("classLoadingError"));
+ assertNotSame(searchHandler, newSearchHandler, "Have a new instance of the search handler");
+ assertNotNull(fetchSearchHandler(configurer).getSearchChainRegistry().getChain("hello"), "Have the new search chain");
+ assertNull(fetchSearchHandler(configurer).getSearchChainRegistry().getChain("classLoadingError"), "Don't have the new search chain");
try (RequestHandlerTestDriver newDriver = new RequestHandlerTestDriver(newSearchHandler)) {
assertJsonResult(json, newDriver);
}
}
@Test
- public void testInvalidYqlQuery() throws IOException {
+ void testInvalidYqlQuery() throws IOException {
IOUtils.copyDirectory(new File(testDir, "config_yql"), new File(tempDir), 1);
generateComponentsConfigForActive();
configurer.reloadConfig();
SearchHandler newSearchHandler = fetchSearchHandler(configurer);
- assertTrue("Do I have a new instance of the search handler?", searchHandler != newSearchHandler);
+ assertTrue(searchHandler != newSearchHandler, "Do I have a new instance of the search handler?");
try (RequestHandlerTestDriver newDriver = new RequestHandlerTestDriver(newSearchHandler)) {
ObjectNode json = jsonMapper.createObjectNode();
json.put("yql", "selectz * from foo where bar > 1453501295");
@@ -162,7 +161,7 @@ public class JSONSearchHandlerTestCase {
// Query handling takes a different code path when a query profile is active, so we test both paths.
@Test
- public void testInvalidQueryParamWithQueryProfile() throws IOException {
+ void testInvalidQueryParamWithQueryProfile() throws IOException {
try (RequestHandlerTestDriver newDriver = driverWithConfig("config_invalid_param")) {
testInvalidQueryParam(newDriver);
}
@@ -182,7 +181,7 @@ public class JSONSearchHandlerTestCase {
}
@Test
- public void testNormalResultJsonAliasRendering() {
+ void testNormalResultJsonAliasRendering() {
ObjectNode json = jsonMapper.createObjectNode();
json.put("format", "json");
json.put("query", "abc");
@@ -190,7 +189,7 @@ public class JSONSearchHandlerTestCase {
}
@Test
- public void testNullQuery() {
+ void testNullQuery() {
ObjectNode json = jsonMapper.createObjectNode();
json.put("format", "xml");
@@ -204,7 +203,7 @@ public class JSONSearchHandlerTestCase {
}
@Test
- public void testWebServiceStatus() {
+ void testWebServiceStatus() {
ObjectNode json = jsonMapper.createObjectNode();
json.put("query", "web_service_status_code");
RequestHandlerTestDriver.MockResponseHandler responseHandler =
@@ -215,14 +214,14 @@ public class JSONSearchHandlerTestCase {
}
@Test
- public void testNormalResultImplicitDefaultRendering() {
+ void testNormalResultImplicitDefaultRendering() {
ObjectNode json = jsonMapper.createObjectNode();
json.put("query", "abc");
assertJsonResult(json, driver);
}
@Test
- public void testNormalResultExplicitDefaultRendering() {
+ void testNormalResultExplicitDefaultRendering() {
ObjectNode json = jsonMapper.createObjectNode();
json.put("query", "abc");
json.put("format", "default");
@@ -230,7 +229,7 @@ public class JSONSearchHandlerTestCase {
}
@Test
- public void testNormalResultXmlAliasRendering() {
+ void testNormalResultXmlAliasRendering() {
ObjectNode json = jsonMapper.createObjectNode();
json.put("query", "abc");
json.put("format", "xml");
@@ -238,7 +237,7 @@ public class JSONSearchHandlerTestCase {
}
@Test
- public void testNormalResultExplicitDefaultRenderingFullRendererName1() {
+ void testNormalResultExplicitDefaultRenderingFullRendererName1() {
ObjectNode json = jsonMapper.createObjectNode();
json.put("query", "abc");
json.put("format", "XmlRenderer");
@@ -246,7 +245,7 @@ public class JSONSearchHandlerTestCase {
}
@Test
- public void testNormalResultExplicitDefaultRenderingFullRendererName2() {
+ void testNormalResultExplicitDefaultRenderingFullRendererName2() {
ObjectNode json = jsonMapper.createObjectNode();
json.put("query", "abc");
json.put("format", "JsonRenderer");
@@ -303,12 +302,12 @@ public class JSONSearchHandlerTestCase {
configurer.reloadConfig();
SearchHandler newSearchHandler = fetchSearchHandler(configurer);
- assertTrue("Do I have a new instance of the search handler?", searchHandler != newSearchHandler);
+ assertTrue(searchHandler != newSearchHandler, "Do I have a new instance of the search handler?");
return new RequestHandlerTestDriver(newSearchHandler);
}
@Test
- public void testSelectParameters() throws IOException {
+ void testSelectParameters() throws IOException {
ObjectNode json = jsonMapper.createObjectNode();
ObjectNode select = jsonMapper.createObjectNode();
@@ -335,7 +334,7 @@ public class JSONSearchHandlerTestCase {
}
@Test
- public void testJsonQueryWithSelectWhere() {
+ void testJsonQueryWithSelectWhere() {
ObjectNode root = jsonMapper.createObjectNode();
ObjectNode select = jsonMapper.createObjectNode();
ObjectNode where = jsonMapper.createObjectNode();
@@ -349,28 +348,28 @@ public class JSONSearchHandlerTestCase {
// Run query
String result = driver.sendRequest(uri + "searchChain=echoingQuery", com.yahoo.jdisc.http.HttpRequest.Method.POST, root.toString(), JSON_CONTENT_TYPE).readAll();
assertEquals("{\"root\":{\"id\":\"toplevel\",\"relevance\":1.0,\"fields\":{\"totalCount\":0},\"children\":[{\"id\":\"Query\",\"relevance\":1.0,\"fields\":{\"query\":\"select * from sources * where default contains \\\"bad\\\"\"}}]}}",
- result);
+ result);
}
@Test
- public void testJsonWithWhereAndGroupingUnderSelect() {
+ void testJsonWithWhereAndGroupingUnderSelect() {
String query = "{\n" +
- " \"select\": {\n" +
- " \"where\": {\n" +
- " \"contains\": [\n" +
- " \"field\",\n" +
- " \"term\"\n" +
- " ]\n" +
- " },\n" +
- " \"grouping\":[\n" +
- " {\n" +
- " \"all\": {\n" +
- " \"output\": \"count()\"\n" +
- " }\n" +
- " }\n" +
- " ]\n" +
- " }\n" +
- "}\n";
+ " \"select\": {\n" +
+ " \"where\": {\n" +
+ " \"contains\": [\n" +
+ " \"field\",\n" +
+ " \"term\"\n" +
+ " ]\n" +
+ " },\n" +
+ " \"grouping\":[\n" +
+ " {\n" +
+ " \"all\": {\n" +
+ " \"output\": \"count()\"\n" +
+ " }\n" +
+ " }\n" +
+ " ]\n" +
+ " }\n" +
+ "}\n";
String result = driver.sendRequest(uri + "searchChain=echoingQuery", com.yahoo.jdisc.http.HttpRequest.Method.POST, query, JSON_CONTENT_TYPE).readAll();
String expected = "{\"root\":{\"id\":\"toplevel\",\"relevance\":1.0,\"fields\":{\"totalCount\":0},\"children\":[{\"id\":\"Query\",\"relevance\":1.0,\"fields\":{\"query\":\"select * from sources * where field contains \\\"term\\\" | all(output(count()))\"}}]}}";
@@ -378,22 +377,22 @@ public class JSONSearchHandlerTestCase {
}
@Test
- public void testJsonWithWhereAndGroupingSeparate() {
+ void testJsonWithWhereAndGroupingSeparate() {
String query = "{\n" +
- " \"select.where\": {\n" +
- " \"contains\": [\n" +
- " \"field\",\n" +
- " \"term\"\n" +
- " ]\n" +
- " },\n" +
- " \"select.grouping\":[\n" +
- " {\n" +
- " \"all\": {\n" +
- " \"output\": \"count()\"\n" +
- " }\n" +
- " }\n" +
- " ]\n" +
- "}\n";
+ " \"select.where\": {\n" +
+ " \"contains\": [\n" +
+ " \"field\",\n" +
+ " \"term\"\n" +
+ " ]\n" +
+ " },\n" +
+ " \"select.grouping\":[\n" +
+ " {\n" +
+ " \"all\": {\n" +
+ " \"output\": \"count()\"\n" +
+ " }\n" +
+ " }\n" +
+ " ]\n" +
+ "}\n";
String result = driver.sendRequest(uri + "searchChain=echoingQuery", com.yahoo.jdisc.http.HttpRequest.Method.POST, query, JSON_CONTENT_TYPE).readAll();
String expected = "{\"root\":{\"id\":\"toplevel\",\"relevance\":1.0,\"fields\":{\"totalCount\":0},\"children\":[{\"id\":\"Query\",\"relevance\":1.0,\"fields\":{\"query\":\"select * from sources * where field contains \\\"term\\\" | all(output(count()))\"}}]}}";
@@ -401,18 +400,18 @@ public class JSONSearchHandlerTestCase {
}
@Test
- public void testJsonQueryWithYQL() {
+ void testJsonQueryWithYQL() {
ObjectNode root = jsonMapper.createObjectNode();
root.put("yql", "select * from sources * where default contains 'bad';");
// Run query
String result = driver.sendRequest(uri + "searchChain=echoingQuery", com.yahoo.jdisc.http.HttpRequest.Method.POST, root.toString(), JSON_CONTENT_TYPE).readAll();
assertEquals("{\"root\":{\"id\":\"toplevel\",\"relevance\":1.0,\"fields\":{\"totalCount\":0},\"children\":[{\"id\":\"Query\",\"relevance\":1.0,\"fields\":{\"query\":\"select * from sources * where default contains \\\"bad\\\"\"}}]}}",
- result);
+ result);
}
@Test
- public void testRequestMapping() {
+ void testRequestMapping() {
ObjectNode json = jsonMapper.createObjectNode();
json.put("yql", "select * from sources * where sddocname contains \"blog_post\" limit 0 | all(group(date) max(3) order(-count())each(output(count())))");
json.put("hits", 10);
@@ -529,7 +528,7 @@ public class JSONSearchHandlerTestCase {
}
@Test
- public void testContentTypeParsing() {
+ void testContentTypeParsing() {
ObjectNode json = jsonMapper.createObjectNode();
json.put("query", "abc");
assertOkResult(driver.sendRequest(uri, com.yahoo.jdisc.http.HttpRequest.Method.POST, json.toString(), "Application/JSON; charset=utf-8"), jsonResult);
@@ -546,7 +545,7 @@ public class JSONSearchHandlerTestCase {
sb.append("]}");
return sb.toString();
}
- @Ignore
+ @Disabled
public void benchmarkJsonParsing() {
String request = createBenchmarkRequest(768);
for (int i=0; i < 10000; i++) {
@@ -558,4 +557,13 @@ public class JSONSearchHandlerTestCase {
}
}
+ 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/container-search/src/test/java/com/yahoo/search/handler/Json2SinglelevelMapTestCase.java b/container-search/src/test/java/com/yahoo/search/handler/Json2SinglelevelMapTestCase.java
index c50b063ff44..e421365b541 100644
--- a/container-search/src/test/java/com/yahoo/search/handler/Json2SinglelevelMapTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/handler/Json2SinglelevelMapTestCase.java
@@ -1,17 +1,17 @@
package com.yahoo.search.handler;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;
-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 Json2SinglelevelMapTestCase {
@Test
- public void testDecodeString() {
+ void testDecodeString() {
Map<String, String> m = new Json2SingleLevelMap(new ByteArrayInputStream("{\"yql\":\"text\", \"f1\":7.3, \"i1\":7, \"t\":true, \"f\":false, \"n\":null, \"a\":[0.786, 0.193]}".getBytes(StandardCharsets.UTF_8))).parse();
assertEquals(7, m.size());
assertTrue(m.containsKey("yql"));
@@ -29,8 +29,9 @@ public class Json2SinglelevelMapTestCase {
assertEquals("null", m.get("n"));
assertEquals("[0.786, 0.193]", m.get("a"));
}
+
@Test
- public void testThatWeAllowSingleQuotes() {
+ void testThatWeAllowSingleQuotes() {
Map<String, String> m = new Json2SingleLevelMap(new ByteArrayInputStream("{'yql':'text'}".getBytes(StandardCharsets.UTF_8))).parse();
assertTrue(m.containsKey("yql"));
assertEquals("text", m.get("yql"));
diff --git a/container-search/src/test/java/com/yahoo/search/handler/SearchHandlerTest.java b/container-search/src/test/java/com/yahoo/search/handler/SearchHandlerTest.java
index a0374570b69..eb461d6211f 100644
--- a/container-search/src/test/java/com/yahoo/search/handler/SearchHandlerTest.java
+++ b/container-search/src/test/java/com/yahoo/search/handler/SearchHandlerTest.java
@@ -23,12 +23,11 @@ import com.yahoo.search.result.Hit;
import com.yahoo.search.result.Relevance;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.searchchain.config.test.SearchChainConfigurerTestCase;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import java.io.ByteArrayInputStream;
import java.io.File;
@@ -37,13 +36,7 @@ import java.net.URI;
import java.util.concurrent.Executors;
import static com.yahoo.yolean.Exceptions.uncheckInterrupted;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertNull;
-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.*;
/**
* @author bratseth
@@ -56,17 +49,17 @@ public class SearchHandlerTest {
private static String tempDir = "";
- @Rule
- public TemporaryFolder tempfolder = new TemporaryFolder();
+ @TempDir
+ public File tempfolder;
private RequestHandlerTestDriver driver = null;
private HandlersConfigurerTestWrapper configurer = null;
private MockMetric metric;
private SearchHandler searchHandler;
- @Before
+ @BeforeEach
public void startUp() throws IOException {
- File cfgDir = tempfolder.newFolder("SearchHandlerTestCase");
+ File cfgDir = newFolder(tempfolder, "SearchHandlerTestCase");
tempDir = cfgDir.getAbsolutePath();
String configId = "dir:" + tempDir;
@@ -79,7 +72,7 @@ public class SearchHandlerTest {
driver = new RequestHandlerTestDriver(searchHandler);
}
- @After
+ @AfterEach
public void shutDown() {
if (configurer != null) configurer.shutdown();
if (driver != null) driver.close();
@@ -98,30 +91,30 @@ public class SearchHandlerTest {
}
@Test
- public void testNullQuery() {
+ void testNullQuery() {
assertEquals("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" +
- "<result total-hit-count=\"0\">\n" +
- " <hit relevancy=\"1.0\">\n" +
- " <field name=\"relevancy\">1.0</field>\n" +
- " <field name=\"uri\">testHit</field>\n" +
- " </hit>\n" +
- "</result>\n",
- driver.sendRequest("http://localhost?format=xml").readAll()
- );
+ "<result total-hit-count=\"0\">\n" +
+ " <hit relevancy=\"1.0\">\n" +
+ " <field name=\"relevancy\">1.0</field>\n" +
+ " <field name=\"uri\">testHit</field>\n" +
+ " </hit>\n" +
+ "</result>\n",
+ driver.sendRequest("http://localhost?format=xml").readAll()
+ );
}
@Test
- public void testFailing() {
- assertTrue(driver.sendRequest("http://localhost?query=test&searchChain=classLoadingError").readAll().contains("NoClassDefFoundError"));
+ void testFailing() {
+ assertTrue(driver.sendRequest("http://localhost?query=test&searchChain=classLoadingError").readAll().contains("NoClassDefFoundError"));
}
@Test
- public synchronized void testPluginError() {
+ synchronized void testPluginError() {
assertTrue(driver.sendRequest("http://localhost?query=test&searchChain=exceptionInPlugin").readAll().contains("NullPointerException"));
}
@Test
- public synchronized void testWorkingReconfiguration() throws Exception {
+ synchronized void testWorkingReconfiguration() throws Exception {
assertJsonResult("http://localhost?query=abc", driver);
// reconfiguration
@@ -131,17 +124,17 @@ public class SearchHandlerTest {
// ...and check the resulting config
SearchHandler newSearchHandler = fetchSearchHandler(configurer);
- assertNotSame("Have a new instance of the search handler", searchHandler, newSearchHandler);
- assertNotNull("Have the new search chain", fetchSearchHandler(configurer).getSearchChainRegistry().getChain("hello"));
- assertNull("Don't have the new search chain", fetchSearchHandler(configurer).getSearchChainRegistry().getChain("classLoadingError"));
+ assertNotSame(searchHandler, newSearchHandler, "Have a new instance of the search handler");
+ assertNotNull(fetchSearchHandler(configurer).getSearchChainRegistry().getChain("hello"), "Have the new search chain");
+ assertNull(fetchSearchHandler(configurer).getSearchChainRegistry().getChain("classLoadingError"), "Don't have the new search chain");
try (RequestHandlerTestDriver newDriver = new RequestHandlerTestDriver(newSearchHandler)) {
assertJsonResult("http://localhost?query=abc", newDriver);
}
}
@Test
- @Ignore //TODO: Must be done at the ConfiguredApplication level, not handlers configurer? Also, this must be rewritten as the above
- public synchronized void testFailedReconfiguration() throws Exception {
+ @Disabled //TODO: Must be done at the ConfiguredApplication level, not handlers configurer? Also, this must be rewritten as the above
+ synchronized void testFailedReconfiguration() throws Exception {
assertXmlResult(driver);
// attempt reconfiguration
@@ -150,15 +143,15 @@ public class SearchHandlerTest {
configurer.reloadConfig();
SearchHandler newSearchHandler = fetchSearchHandler(configurer);
RequestHandler newMockHandler = configurer.getRequestHandlerRegistry().getComponent("com.yahoo.search.handler.test.MockHandler");
- assertSame("Reconfiguration failed: Kept the existing instance of the search handler", searchHandler, newSearchHandler);
- assertNull("Reconfiguration failed: No mock handler", newMockHandler);
+ assertSame(searchHandler, newSearchHandler, "Reconfiguration failed: Kept the existing instance of the search handler");
+ assertNull(newMockHandler, "Reconfiguration failed: No mock handler");
try (RequestHandlerTestDriver newDriver = new RequestHandlerTestDriver(searchHandler)) {
assertXmlResult(newDriver);
}
}
@Test
- public void testResponseBasics() {
+ void testResponseBasics() {
Query q = new Query("?query=dummy&tracelevel=3");
q.trace("nalle", 1);
Result r = new Result(q);
@@ -172,13 +165,13 @@ public class SearchHandlerTest {
}
@Test
- public void testInvalidYqlQuery() throws Exception {
+ void testInvalidYqlQuery() throws Exception {
IOUtils.copyDirectory(new File(testDir, "config_yql"), new File(tempDir), 1);
generateComponentsConfigForActive();
configurer.reloadConfig();
SearchHandler newSearchHandler = fetchSearchHandler(configurer);
- assertNotSame("Have a new instance of the search handler", searchHandler, newSearchHandler);
+ assertNotSame(searchHandler, newSearchHandler, "Have a new instance of the search handler");
try (RequestHandlerTestDriver newDriver = new RequestHandlerTestDriver(newSearchHandler)) {
RequestHandlerTestDriver.MockResponseHandler responseHandler = newDriver.sendRequest(
"http://localhost/search/?yql=select%20*%20from%20foo%20where%20bar%20%3E%201453501295%27%3B");
@@ -189,7 +182,7 @@ public class SearchHandlerTest {
}
@Test
- public void testRequestType() throws Exception {
+ void testRequestType() throws Exception {
IOUtils.copyDirectory(new File(testDir, "config_yql"), new File(tempDir), 1);
generateComponentsConfigForActive();
configurer.reloadConfig();
@@ -205,14 +198,14 @@ public class SearchHandlerTest {
// Query handling takes a different code path when a query profile is active, so we test both paths.
@Test
- public void testInvalidQueryParamWithQueryProfile() throws Exception {
+ void testInvalidQueryParamWithQueryProfile() throws Exception {
try (RequestHandlerTestDriver newDriver = driverWithConfig("config_invalid_param")) {
testInvalidQueryParam(newDriver);
}
}
@Test
- public void testInvalidQueryParamWithoutQueryProfile() {
+ void testInvalidQueryParamWithoutQueryProfile() {
testInvalidQueryParam(driver);
}
private void testInvalidQueryParam(final RequestHandlerTestDriver testDriver) {
@@ -225,7 +218,7 @@ public class SearchHandlerTest {
}
@Test
- public void testResultStatus() {
+ void testResultStatus() {
assertEquals(200, httpStatus(result().build()));
assertEquals(200, httpStatus(result().withHit().build()));
assertEquals(200, httpStatus(result().withGroups().build()));
@@ -238,7 +231,7 @@ public class SearchHandlerTest {
}
@Test
- public void testWebServiceStatus() {
+ void testWebServiceStatus() {
RequestHandlerTestDriver.MockResponseHandler responseHandler =
driver.sendRequest("http://localhost/search/?query=web_service_status_code");
String response = responseHandler.readAll();
@@ -247,32 +240,32 @@ public class SearchHandlerTest {
}
@Test
- public void testNormalResultImplicitDefaultRendering() {
+ void testNormalResultImplicitDefaultRendering() {
assertJsonResult("http://localhost?query=abc", driver);
}
@Test
- public void testNormalResultExplicitDefaultRendering() {
+ void testNormalResultExplicitDefaultRendering() {
assertJsonResult("http://localhost?query=abc&format=default", driver);
}
@Test
- public void testNormalResultXmlAliasRendering() {
+ void testNormalResultXmlAliasRendering() {
assertXmlResult("http://localhost?query=abc&format=xml", driver);
}
@Test
- public void testNormalResultJsonAliasRendering() {
+ void testNormalResultJsonAliasRendering() {
assertJsonResult("http://localhost?query=abc&format=json", driver);
}
@Test
- public void testNormalResultExplicitDefaultRenderingFullRendererName1() {
+ void testNormalResultExplicitDefaultRenderingFullRendererName1() {
assertXmlResult("http://localhost?query=abc&format=XmlRenderer", driver);
}
@Test
- public void testNormalResultExplicitDefaultRenderingFullRendererName2() {
+ void testNormalResultExplicitDefaultRenderingFullRendererName2() {
assertJsonResult("http://localhost?query=abc&format=JsonRenderer", driver);
}
@@ -319,7 +312,7 @@ public class SearchHandlerTest {
}
@Test
- public void testFaultyHandlers() throws Exception {
+ void testFaultyHandlers() throws Exception {
assertHandlerResponse(500, null, "NullReturning");
assertHandlerResponse(500, null, "NullReturningAsync");
assertHandlerResponse(500, null, "Throwing");
@@ -327,7 +320,7 @@ public class SearchHandlerTest {
}
@Test
- public void testForwardingHandlers() throws Exception {
+ void testForwardingHandlers() throws Exception {
assertHandlerResponse(200, jsonResult, "ForwardingAsync");
// Fails because we are forwarding from a sync to an async handler -
@@ -341,9 +334,9 @@ public class SearchHandlerTest {
try (RequestHandlerTestDriver forwardingDriver = new RequestHandlerTestDriver(forwardingHandler)) {
RequestHandlerTestDriver.MockResponseHandler response = forwardingDriver.sendRequest("http://localhost/" + handlerName + "?query=test");
response.awaitResponse();
- assertEquals("Expected HTTP status", status, response.getStatus());
+ assertEquals(status, response.getStatus(), "Expected HTTP status");
if (responseData == null)
- assertNull("Connection closed with no data", response.read());
+ assertNull(response.read(), "Connection closed with no data");
else
assertEquals(responseData, response.readAll());
}
@@ -355,7 +348,7 @@ public class SearchHandlerTest {
configurer.reloadConfig();
SearchHandler newSearchHandler = fetchSearchHandler(configurer);
- assertNotSame("Should have a new instance of the search handler", searchHandler, newSearchHandler);
+ assertNotSame(searchHandler, newSearchHandler, "Should have a new instance of the search handler");
return new RequestHandlerTestDriver(newSearchHandler);
}
@@ -387,6 +380,15 @@ public class SearchHandlerTest {
return result;
}
+
+ 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;
+ }
}
/** Referenced from config */
@@ -396,6 +398,15 @@ public class SearchHandlerTest {
public Result search(Query query, Execution execution) {
throw new NoClassDefFoundError(); // Simulate typical OSGi problem
}
+
+ 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;
+ }
}
/** Referenced from config */
@@ -411,6 +422,15 @@ public class SearchHandlerTest {
}
return result;
}
+
+ 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;
+ }
}
/** Referenced from config */
@@ -422,6 +442,15 @@ public class SearchHandlerTest {
result.hits().add(new Hit("HelloWorld"));
return result;
}
+
+ 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;
+ }
}
/** Referenced from config */
@@ -435,6 +464,15 @@ public class SearchHandlerTest {
result.hits().add(hit);
return result;
}
+
+ 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;
+ }
}
/** Referenced from config */
@@ -459,6 +497,15 @@ public class SearchHandlerTest {
}
}
+ 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;
+ }
+
}
/** Referenced from config */
@@ -483,6 +530,15 @@ public class SearchHandlerTest {
}
}
+ 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;
+ }
+
}
/** Referenced from config */
@@ -497,6 +553,15 @@ public class SearchHandlerTest {
return null;
}
+ 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;
+ }
+
}
/** Referenced from config */
@@ -511,6 +576,15 @@ public class SearchHandlerTest {
return null;
}
+ 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;
+ }
+
}
/** Referenced from config */
@@ -525,6 +599,15 @@ public class SearchHandlerTest {
throw new RuntimeException();
}
+ 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;
+ }
+
}
/** Referenced from config */
@@ -539,6 +622,15 @@ public class SearchHandlerTest {
throw new RuntimeException();
}
+ 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;
+ }
+
}
private ResultBuilder result() { return new ResultBuilder(); }
@@ -564,6 +656,24 @@ public class SearchHandlerTest {
public Result build() { return result; }
+ 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;
+ }
+
+ }
+
+ 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/container-search/src/test/java/com/yahoo/search/match/test/DocumentDbTest.java b/container-search/src/test/java/com/yahoo/search/match/test/DocumentDbTest.java
index eff9c2f558f..4df45b26191 100644
--- a/container-search/src/test/java/com/yahoo/search/match/test/DocumentDbTest.java
+++ b/container-search/src/test/java/com/yahoo/search/match/test/DocumentDbTest.java
@@ -6,17 +6,16 @@ import com.yahoo.document.datatypes.WeightedSet;
import com.yahoo.search.Result;
import com.yahoo.search.match.DocumentDb;
import com.yahoo.text.MapParser;
-import org.junit.Ignore;
-import org.junit.Test;
-import static org.junit.Assert.*;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
public class DocumentDbTest {
@Test
- @Ignore
- public void testWand() {
+ @Disabled
+ void testWand() {
DocumentDb db = new DocumentDb();
- db.put(createFeatureDocument("1","[a:7, b:5, c:3]"));
+ db.put(createFeatureDocument("1", "[a:7, b:5, c:3]"));
db.put(createFeatureDocument("2", "[a:2, b:1, c:4]"));
//Result r = execute(createWandQuery("[a:1, b:3, c:5]"));
//assertEquals(67,r.hits().get(0).getRelevance());
diff --git a/container-search/src/test/java/com/yahoo/search/pagetemplates/config/test/MapPageTemplateXMLReadingTestCase.java b/container-search/src/test/java/com/yahoo/search/pagetemplates/config/test/MapPageTemplateXMLReadingTestCase.java
index b8457344944..5b4f4e82221 100644
--- a/container-search/src/test/java/com/yahoo/search/pagetemplates/config/test/MapPageTemplateXMLReadingTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/pagetemplates/config/test/MapPageTemplateXMLReadingTestCase.java
@@ -8,13 +8,11 @@ import com.yahoo.search.pagetemplates.model.MapChoice;
import com.yahoo.search.pagetemplates.model.Placeholder;
import com.yahoo.search.pagetemplates.model.Section;
import com.yahoo.search.pagetemplates.model.Source;
-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.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -24,13 +22,13 @@ public class MapPageTemplateXMLReadingTestCase {
private String root="src/test/java/com/yahoo/search/pagetemplates/config/test/examples/mapexamples/";
@Test
- public void testMap1() {
- PageTemplateRegistry registry=new PageTemplateXMLReader().read(root);
+ void testMap1() {
+ PageTemplateRegistry registry = new PageTemplateXMLReader().read(root);
assertCorrectMap1(registry.getComponent("map1"));
}
private void assertCorrectMap1(PageTemplate page) {
- assertNotNull("map1 was read",page);
+ assertNotNull(page,"map1 was read");
Section root=page.getSection();
assertTrue(((Section)((Section)root.elements(Section.class).get(0)).elements(Section.class).get(0)).elements().get(0) instanceof Placeholder);
assertTrue(((Section)((Section)root.elements(Section.class).get(0)).elements(Section.class).get(1)).elements().get(0) instanceof Placeholder);
diff --git a/container-search/src/test/java/com/yahoo/search/pagetemplates/config/test/PageTemplateXMLReadingTestCase.java b/container-search/src/test/java/com/yahoo/search/pagetemplates/config/test/PageTemplateXMLReadingTestCase.java
index 1b845802ec3..5994cad468d 100644
--- a/container-search/src/test/java/com/yahoo/search/pagetemplates/config/test/PageTemplateXMLReadingTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/pagetemplates/config/test/PageTemplateXMLReadingTestCase.java
@@ -13,15 +13,12 @@ import com.yahoo.search.pagetemplates.model.Choice;
import com.yahoo.search.pagetemplates.model.Renderer;
import com.yahoo.search.pagetemplates.model.Section;
import com.yahoo.search.pagetemplates.model.Source;
-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.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -31,8 +28,8 @@ public class PageTemplateXMLReadingTestCase {
private String root="src/test/java/com/yahoo/search/pagetemplates/config/test/";
@Test
- public void testExamples() {
- PageTemplateRegistry registry=new PageTemplateXMLReader().read(root + "examples");
+ void testExamples() {
+ PageTemplateRegistry registry = new PageTemplateXMLReader().read(root + "examples");
assertCorrectSerp(registry.getComponent("serp"));
assertCorrectSlottingSerp(registry.getComponent("slottingSerp"));
assertCorrectRichSerp(registry.getComponent("richSerp"));
@@ -42,7 +39,7 @@ public class PageTemplateXMLReadingTestCase {
}
@Test
- public void testConfigReading() {
+ void testConfigReading() {
PageTemplatesConfig config = new PageTemplatesConfig(new PageTemplatesConfig.Builder()
.page("<page id=\"slottingSerp\" layout=\"mainAndRight\">\n <section layout=\"column\" region=\"main\" source=\"*\" order=\"-[rank]\"/>\n <section layout=\"column\" region=\"right\" source=\"ads\"/>\n</page>\n")
.page("<page id=\"richSerp\" layout=\"mainAndRight\">\n <section layout=\"row\" region=\"main\">\n <section layout=\"column\" description=\"left main pane\">\n <section layout=\"row\" max=\"5\" description=\"Bar of images, from one of two possible sources\">\n <choice method=\"annealing\">\n <source name=\"images\"/>\n <source name=\"flickr\"/>\n </choice>\n </section>\n <section max=\"1\" source=\"local map video ticker weather\" description=\"A single relevant graphically rich element\"/>\n <section order=\"-[rank]\" max=\"10\" source=\"web news\" description=\"Various kinds of traditional search results\"/>\n </section>\n <section layout=\"column\" order=\"[source]\" source=\"answers blogs twitter\" description=\"right main pane, ugc stuff, grouped by source\"/>\n </section>\n <section layout=\"column\" source=\"ads\" region=\"right\"/>\n</page>\n")
@@ -57,19 +54,19 @@ public class PageTemplateXMLReadingTestCase {
}
@Test
- public void testInvalidFilename() {
+ void testInvalidFilename() {
try {
- PageTemplateRegistry registry=new PageTemplateXMLReader().read(root + "examples/invalidfilename");
- assertEquals(0,registry.allComponents().size());
+ PageTemplateRegistry registry = new PageTemplateXMLReader().read(root + "examples/invalidfilename");
+ assertEquals(0, registry.allComponents().size());
fail("Should have caused an exception");
}
catch (IllegalArgumentException e) {
- assertEquals("The file name of page template 'notinvalid' must be 'notinvalid.xml' but was 'invalid.xml'",e.getMessage());
+ assertEquals("The file name of page template 'notinvalid' must be 'notinvalid.xml' but was 'invalid.xml'", e.getMessage());
}
}
protected void assertCorrectSerp(PageTemplate page) {
- assertNotNull("'serp' was read",page);
+ assertNotNull(page,"'serp' was read");
Section rootSection=page.getSection();
assertNotNull(rootSection);
assertEquals("mainAndRight",rootSection.getLayout().getName());
@@ -84,7 +81,7 @@ public class PageTemplateXMLReadingTestCase {
}
protected void assertCorrectSlottingSerp(PageTemplate page) {
- assertNotNull("'slotting serp' was read",page);
+ assertNotNull(page,"'slotting serp' was read");
Section rootSection=page.getSection();
Section main=(Section)rootSection.elements(Section.class).get(0);
assertEquals("-[rank]",main.getOrder().toString());
@@ -94,7 +91,7 @@ public class PageTemplateXMLReadingTestCase {
}
protected void assertCorrectRichSerp(PageTemplate page) {
- assertNotNull("'rich serp' was read",page);
+ assertNotNull(page,"'rich serp' was read");
Section rootSection=page.getSection();
assertNotNull(rootSection);
assertEquals("mainAndRight",rootSection.getLayout().getName());
@@ -129,7 +126,7 @@ public class PageTemplateXMLReadingTestCase {
}
protected void assertCorrectRicherSerp(PageTemplate page) {
- assertNotNull("'richer serp' was read",page);
+ assertNotNull(page,"'richer serp' was read");
// Check resolution as we go
Resolver resolver=new DeterministicResolver();
@@ -139,7 +136,7 @@ public class PageTemplateXMLReadingTestCase {
assertNotNull(root);
assertEquals("column",root.getLayout().getName());
- assertEquals("Sections was correctly imported and combined with the section in this",4,root.elements(Section.class).size());
+ assertEquals(4,root.elements(Section.class).size(),"Sections was correctly imported and combined with the section in this");
assertCorrectHeader((Section)root.elements(Section.class).get(0));
@@ -218,14 +215,13 @@ public class PageTemplateXMLReadingTestCase {
Set<String> sourceNames=new HashSet<>();
for (Source source : page.getSources())
sourceNames.add(source.getName());
- assertEquals("Expected " + expectedSourceNames.length + " elements in " + sourceNames,
- expectedSourceNames.length,sourceNames.size());
+ assertEquals(expectedSourceNames.length,sourceNames.size(),"Expected " + expectedSourceNames.length + " elements in " + sourceNames);
for (String expectedSourceName : expectedSourceNames)
- assertTrue("Sources did not include '" + expectedSourceName+ "'",sourceNames.contains(expectedSourceName));
+ assertTrue(sourceNames.contains(expectedSourceName),"Sources did not include '" + expectedSourceName+ "'");
}
protected void assertCorrectIncluder(PageTemplate page) {
- assertNotNull("'includer' was read",page);
+ assertNotNull(page,"'includer' was read");
Resolution resolution=new DeterministicResolver().resolve(Choice.createSingleton(page),null,null);
diff --git a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/AnySourceTestCase.java b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/AnySourceTestCase.java
index 4ee07db691b..7e72a57b1dc 100644
--- a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/AnySourceTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/AnySourceTestCase.java
@@ -9,9 +9,9 @@ import com.yahoo.search.pagetemplates.engine.Resolver;
import com.yahoo.search.pagetemplates.engine.resolvers.DeterministicResolver;
import com.yahoo.search.pagetemplates.model.Choice;
import com.yahoo.search.result.HitGroup;
-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 bratseth
@@ -19,41 +19,41 @@ import static org.junit.Assert.assertEquals;
public class AnySourceTestCase extends ExecutionAbstractTestCase {
@Test
- public void testExecution() {
+ void testExecution() {
// Create the page template
- Choice page=Choice.createSingleton(importPage("AnySource.xml"));
+ Choice page = Choice.createSingleton(importPage("AnySource.xml"));
// Create a federated result
- Query query=new Query();
- Result result=new Result(query);
- result.hits().add(createHits("source1",3));
- result.hits().add(createHits("source2",3));
- result.hits().add(createHits("source3",3));
+ Query query = new Query();
+ Result result = new Result(query);
+ result.hits().add(createHits("source1", 3));
+ result.hits().add(createHits("source2", 3));
+ result.hits().add(createHits("source3", 3));
// Resolve (noop here)
- Resolver resolver=new DeterministicResolver();
- Resolution resolution=resolver.resolve(page,query,result);
+ Resolver resolver = new DeterministicResolver();
+ Resolution resolution = resolver.resolve(page, query, result);
// Execute
- Organizer organizer =new Organizer();
- organizer.organize(page,resolution,result);
+ Organizer organizer = new Organizer();
+ organizer.organize(page, resolution, result);
// Check execution:
// all three sources, ordered by relevance, source 3 first in each relevance group
- HitGroup hits=result.hits();
- assertEquals(9,hits.size());
- assertEquals("source3-1",hits.get(0).getId().stringValue());
- assertEquals("source1-1",hits.get(1).getId().stringValue());
- assertEquals("source2-1",hits.get(2).getId().stringValue());
- assertEquals("source3-2",hits.get(3).getId().stringValue());
- assertEquals("source1-2",hits.get(4).getId().stringValue());
- assertEquals("source2-2",hits.get(5).getId().stringValue());
- assertEquals("source3-3",hits.get(6).getId().stringValue());
- assertEquals("source1-3",hits.get(7).getId().stringValue());
- assertEquals("source2-3",hits.get(8).getId().stringValue());
+ HitGroup hits = result.hits();
+ assertEquals(9, hits.size());
+ assertEquals("source3-1", hits.get(0).getId().stringValue());
+ assertEquals("source1-1", hits.get(1).getId().stringValue());
+ assertEquals("source2-1", hits.get(2).getId().stringValue());
+ assertEquals("source3-2", hits.get(3).getId().stringValue());
+ assertEquals("source1-2", hits.get(4).getId().stringValue());
+ assertEquals("source2-2", hits.get(5).getId().stringValue());
+ assertEquals("source3-3", hits.get(6).getId().stringValue());
+ assertEquals("source1-3", hits.get(7).getId().stringValue());
+ assertEquals("source2-3", hits.get(8).getId().stringValue());
// Check rendering
- assertRendered(result,"AnySourceResult.xml");
+ assertRendered(result, "AnySourceResult.xml");
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ChoiceOfRenderersTestCase.java b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ChoiceOfRenderersTestCase.java
index b495f68464e..227afbce9dc 100644
--- a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ChoiceOfRenderersTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ChoiceOfRenderersTestCase.java
@@ -10,9 +10,9 @@ import com.yahoo.search.pagetemplates.engine.Resolver;
import com.yahoo.search.pagetemplates.engine.resolvers.DeterministicResolver;
import com.yahoo.search.pagetemplates.model.Choice;
import com.yahoo.search.pagetemplates.model.Renderer;
-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 bratseth
@@ -21,31 +21,31 @@ public class ChoiceOfRenderersTestCase extends ExecutionAbstractTestCase {
//This test is order dependent. Fix this!!
@Test
- public void testExecution() {
+ void testExecution() {
// Create the page template
- Choice page=Choice.createSingleton(importPage("ChoiceOfRenderers.xml"));
+ Choice page = Choice.createSingleton(importPage("ChoiceOfRenderers.xml"));
// Create a federated result
- Query query=new Query();
- Result result=new Result(query);
- result.hits().add(createHits("source1",3));
- result.hits().add(createHits("source2",3));
- result.hits().add(createHits("source3",3));
+ Query query = new Query();
+ Result result = new Result(query);
+ result.hits().add(createHits("source1", 3));
+ result.hits().add(createHits("source2", 3));
+ result.hits().add(createHits("source3", 3));
// Resolve
- Resolver resolver=new DeterministicResolver();
- Resolution resolution=resolver.resolve(page,query,result);
- assertEquals(1,resolution.getResolution((Choice)((PageTemplate)page.get(0).get(0)).getSection().elements(Renderer.class).get(0)));
- assertEquals(2,resolution.getResolution((Choice)((PageTemplate)page.get(0).get(0)).getSection().elements(Renderer.class).get(1)));
+ Resolver resolver = new DeterministicResolver();
+ Resolution resolution = resolver.resolve(page, query, result);
+ assertEquals(1, resolution.getResolution((Choice) ((PageTemplate) page.get(0).get(0)).getSection().elements(Renderer.class).get(0)));
+ assertEquals(2, resolution.getResolution((Choice) ((PageTemplate) page.get(0).get(0)).getSection().elements(Renderer.class).get(1)));
// Execute
- Organizer organizer =new Organizer();
- organizer.organize(page,resolution,result);
+ Organizer organizer = new Organizer();
+ organizer.organize(page, resolution, result);
- assertEquals(6,result.getConcreteHitCount());
- assertEquals(6,result.getHitCount());
+ assertEquals(6, result.getConcreteHitCount());
+ assertEquals(6, result.getHitCount());
// Check rendering
- assertRendered(result,"ChoiceOfRenderersResult.xml");
+ assertRendered(result, "ChoiceOfRenderersResult.xml");
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ChoiceOfSubsectionsTestCase.java b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ChoiceOfSubsectionsTestCase.java
index 332d8612954..50db2810630 100644
--- a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ChoiceOfSubsectionsTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ChoiceOfSubsectionsTestCase.java
@@ -8,12 +8,12 @@ import com.yahoo.search.pagetemplates.engine.Resolution;
import com.yahoo.search.pagetemplates.engine.resolvers.DeterministicResolver;
import com.yahoo.search.pagetemplates.model.Choice;
import com.yahoo.search.result.HitGroup;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.stream.Collectors;
-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 ChoiceOfSubsectionsTestCase extends ExecutionAbstractTestCase {
@Test
- public void testExecution() {
+ void testExecution() {
// Create the page template
Choice page = Choice.createSingleton(importPage("ChoiceOfSubsections.xml"));
@@ -38,8 +38,8 @@ public class ChoiceOfSubsectionsTestCase extends ExecutionAbstractTestCase {
// Check execution:
// Two subsections with one source each
assertEquals(2, result.hits().size());
- HitGroup section1 = (HitGroup)result.hits().get(0);
- HitGroup section2 = (HitGroup)result.hits().get(1);
+ HitGroup section1 = (HitGroup) result.hits().get(0);
+ HitGroup section2 = (HitGroup) result.hits().get(1);
assertEquals("section", section1.types().stream().collect(Collectors.joining(", ")));
assertEquals("section", section2.types().stream().collect(Collectors.joining(", ")));
assertEqualHitGroups(createHits("source2", 3), section1);
diff --git a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ChoiceOfTwoSourcesTestCase.java b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ChoiceOfTwoSourcesTestCase.java
index b7fb22713f2..8849f73cfb6 100644
--- a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ChoiceOfTwoSourcesTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ChoiceOfTwoSourcesTestCase.java
@@ -10,9 +10,9 @@ import com.yahoo.search.pagetemplates.engine.Resolver;
import com.yahoo.search.pagetemplates.engine.resolvers.DeterministicResolver;
import com.yahoo.search.pagetemplates.model.Choice;
import com.yahoo.search.pagetemplates.model.Source;
-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 bratseth
@@ -20,32 +20,32 @@ import static org.junit.Assert.assertEquals;
public class ChoiceOfTwoSourcesTestCase extends ExecutionAbstractTestCase {
@Test
- public void testExecution() {
+ void testExecution() {
// Create the page template
- Choice page=Choice.createSingleton(importPage("ChoiceOfTwoSources.xml"));
+ Choice page = Choice.createSingleton(importPage("ChoiceOfTwoSources.xml"));
// Create a federated result
- Query query=new Query();
- Result result=new Result(query);
- result.hits().add(createHits("source1",3));
- result.hits().add(createHits("source2",3));
- result.hits().add(createHits("source3",3));
+ Query query = new Query();
+ Result result = new Result(query);
+ result.hits().add(createHits("source1", 3));
+ result.hits().add(createHits("source2", 3));
+ result.hits().add(createHits("source3", 3));
// Resolve
- Resolver resolver=new DeterministicResolver();
- Resolution resolution=resolver.resolve(page,query,result);
- assertEquals(1,resolution.getResolution((Choice)((PageTemplate)page.get(0).get(0)).getSection().elements(Source.class).get(0)));
+ Resolver resolver = new DeterministicResolver();
+ Resolution resolution = resolver.resolve(page, query, result);
+ assertEquals(1, resolution.getResolution((Choice) ((PageTemplate) page.get(0).get(0)).getSection().elements(Source.class).get(0)));
// Execute
- Organizer organizer =new Organizer();
- organizer.organize(page,resolution,result);
+ Organizer organizer = new Organizer();
+ organizer.organize(page, resolution, result);
// Check execution:
// No subsections: Last choice (source2) used
- assertEqualHitGroups(createHits("source2",3),result.hits());
+ assertEqualHitGroups(createHits("source2", 3), result.hits());
// Check rendering
- assertRendered(result,"ChoiceOfTwoSourcesResult.xml");
+ assertRendered(result, "ChoiceOfTwoSourcesResult.xml");
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ChoicesTestCase.java b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ChoicesTestCase.java
index 629d690fda2..17d59b3e22f 100644
--- a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ChoicesTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ChoicesTestCase.java
@@ -9,7 +9,7 @@ import com.yahoo.search.pagetemplates.engine.Resolver;
import com.yahoo.search.pagetemplates.engine.resolvers.DeterministicResolver;
import com.yahoo.search.pagetemplates.model.Choice;
import com.yahoo.search.pagetemplates.model.PageElement;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
@@ -20,31 +20,31 @@ import java.util.List;
public class ChoicesTestCase extends ExecutionAbstractTestCase {
@Test
- public void testExecution() {
+ void testExecution() {
// Create the page template (second alternative will be chosen)
- List<PageElement> pages=new ArrayList<>();
+ List<PageElement> pages = new ArrayList<>();
pages.add(importPage("AnySource.xml"));
pages.add(importPage("Choices.xml"));
- Choice page=Choice.createSingletons(pages);
+ Choice page = Choice.createSingletons(pages);
// Create a federated result
- Query query=new Query();
- Result result=new Result(query);
- result.hits().add(createHits("news",3));
- result.hits().add(createHits("web",3));
- result.hits().add(createHits("blog",3));
- result.hits().add(createHits("images",3));
+ Query query = new Query();
+ Result result = new Result(query);
+ result.hits().add(createHits("news", 3));
+ result.hits().add(createHits("web", 3));
+ result.hits().add(createHits("blog", 3));
+ result.hits().add(createHits("images", 3));
// Resolve
- Resolver resolver=new DeterministicResolver();
- Resolution resolution=resolver.resolve(page,query,result);
+ Resolver resolver = new DeterministicResolver();
+ Resolution resolution = resolver.resolve(page, query, result);
// Execute
- Organizer organizer =new Organizer();
- organizer.organize(page,resolution,result);
+ Organizer organizer = new Organizer();
+ organizer.organize(page, resolution, result);
// Check rendering
- assertRendered(result,"ChoicesResult.xml");
+ assertRendered(result, "ChoicesResult.xml");
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ExecutionAbstractTestCase.java b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ExecutionAbstractTestCase.java
index 5a8a4dfa9d2..3645b0efe37 100644
--- a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ExecutionAbstractTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/ExecutionAbstractTestCase.java
@@ -14,7 +14,7 @@ import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.concurrent.CompletableFuture;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -25,7 +25,7 @@ public class ExecutionAbstractTestCase {
protected PageTemplate importPage(String name) {
PageTemplate template=new PageTemplateXMLReader().readFile(root + name);
- assertNotNull("Could look up page template '" + name + "'",template);
+ assertNotNull(template,"Could look up page template '" + name + "'");
return template;
}
diff --git a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/MapSectionsToSectionsTestCase.java b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/MapSectionsToSectionsTestCase.java
index 770e7f524e8..284c719b05e 100644
--- a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/MapSectionsToSectionsTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/MapSectionsToSectionsTestCase.java
@@ -13,13 +13,13 @@ import com.yahoo.search.pagetemplates.model.MapChoice;
import com.yahoo.search.pagetemplates.model.PageElement;
import com.yahoo.search.pagetemplates.model.Section;
import com.yahoo.search.result.HitGroup;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
-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
@@ -27,52 +27,52 @@ import static org.junit.Assert.assertNotNull;
public class MapSectionsToSectionsTestCase extends ExecutionAbstractTestCase {
@Test
- public void testExecution() {
+ void testExecution() {
// Create the page template
- Choice page=Choice.createSingleton(importPage("MapSectionsToSections.xml"));
+ Choice page = Choice.createSingleton(importPage("MapSectionsToSections.xml"));
// Create a federated result
- Query query=new Query();
- Result result=new Result(query);
- result.hits().add(createHits("source1",3));
- result.hits().add(createHits("source2",4));
- result.hits().add(createHits("source3",5));
- result.hits().add(createHits("source4",6));
- result.hits().add(createHits("source5",7));
+ Query query = new Query();
+ Result result = new Result(query);
+ result.hits().add(createHits("source1", 3));
+ result.hits().add(createHits("source2", 4));
+ result.hits().add(createHits("source3", 5));
+ result.hits().add(createHits("source4", 6));
+ result.hits().add(createHits("source5", 7));
// Resolve
- Resolver resolver=new DeterministicResolverAssertingMethod();
- Resolution resolution=resolver.resolve(page,query,result);
- Map<String, List<PageElement>> mapping=
- resolution.getResolution((MapChoice)((PageTemplate)page.get(0).get(0)).getSection().elements().get(2));
+ Resolver resolver = new DeterministicResolverAssertingMethod();
+ Resolution resolution = resolver.resolve(page, query, result);
+ Map<String, List<PageElement>> mapping =
+ resolution.getResolution((MapChoice) ((PageTemplate) page.get(0).get(0)).getSection().elements().get(2));
assertNotNull(mapping);
- assertEquals("box1",((Section)mapping.get("box1holder").get(0)).getId());
- assertEquals("box2",((Section)mapping.get("box2holder").get(0)).getId());
- assertEquals("box3",((Section)mapping.get("box3holder").get(0)).getId());
- assertEquals("box4",((Section)mapping.get("box4holder").get(0)).getId());
+ assertEquals("box1", ((Section) mapping.get("box1holder").get(0)).getId());
+ assertEquals("box2", ((Section) mapping.get("box2holder").get(0)).getId());
+ assertEquals("box3", ((Section) mapping.get("box3holder").get(0)).getId());
+ assertEquals("box4", ((Section) mapping.get("box4holder").get(0)).getId());
// Execute
- Organizer organizer =new Organizer();
- organizer.organize(page,resolution,result);
+ Organizer organizer = new Organizer();
+ organizer.organize(page, resolution, result);
// Check execution:
// Two subsections, each containing two sub-subsections with one source each
- assertEquals(2,result.hits().size());
- HitGroup row1=(HitGroup)result.hits().get(0);
- HitGroup column11=(HitGroup)row1.get(0);
- HitGroup column12=(HitGroup)row1.get(1);
- HitGroup row2=(HitGroup)result.hits().get(1);
- HitGroup column21a=(HitGroup)row2.get(0);
- HitGroup column21b=(HitGroup)row2.get(1);
- HitGroup column22=(HitGroup)row2.get(2);
- assertEqualHitGroups(createHits("source1",3),column11);
- assertEqualHitGroups(createHits("source2",4),column12);
- assertEqualHitGroups(createHits("source3",5),column21a);
- assertEqualHitGroups(createHits("source5",7),column21b);
- assertEqualHitGroups(createHits("source4",6),column22);
+ assertEquals(2, result.hits().size());
+ HitGroup row1 = (HitGroup) result.hits().get(0);
+ HitGroup column11 = (HitGroup) row1.get(0);
+ HitGroup column12 = (HitGroup) row1.get(1);
+ HitGroup row2 = (HitGroup) result.hits().get(1);
+ HitGroup column21a = (HitGroup) row2.get(0);
+ HitGroup column21b = (HitGroup) row2.get(1);
+ HitGroup column22 = (HitGroup) row2.get(2);
+ assertEqualHitGroups(createHits("source1", 3), column11);
+ assertEqualHitGroups(createHits("source2", 4), column12);
+ assertEqualHitGroups(createHits("source3", 5), column21a);
+ assertEqualHitGroups(createHits("source5", 7), column21b);
+ assertEqualHitGroups(createHits("source4", 6), column22);
// Check rendering
- assertRendered(result,"MapSectionsToSectionsResult.xml");
+ assertRendered(result, "MapSectionsToSectionsResult.xml");
}
/** Same as deterministic resolver, but asserts that it received the correct method names for each map choice */
diff --git a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/MapSourcesToSectionsTestCase.java b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/MapSourcesToSectionsTestCase.java
index 8d8e39bd934..4d844c50cc9 100644
--- a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/MapSourcesToSectionsTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/MapSourcesToSectionsTestCase.java
@@ -13,13 +13,13 @@ import com.yahoo.search.pagetemplates.model.MapChoice;
import com.yahoo.search.pagetemplates.model.PageElement;
import com.yahoo.search.pagetemplates.model.Source;
import com.yahoo.search.result.HitGroup;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
-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
@@ -27,50 +27,50 @@ import static org.junit.Assert.assertNotNull;
public class MapSourcesToSectionsTestCase extends ExecutionAbstractTestCase {
@Test
- public void testExecution() {
+ void testExecution() {
// Create the page template
- Choice page=Choice.createSingleton(importPage("MapSourcesToSections.xml"));
+ Choice page = Choice.createSingleton(importPage("MapSourcesToSections.xml"));
// Create a federated result
- Query query=new Query();
- Result result=new Result(query);
- result.hits().add(createHits("source1",3));
- result.hits().add(createHits("source2",4));
- result.hits().add(createHits("source3",5));
- result.hits().add(createHits("source4",6));
- result.hits().add(createHits("source5",7));
+ Query query = new Query();
+ Result result = new Result(query);
+ result.hits().add(createHits("source1", 3));
+ result.hits().add(createHits("source2", 4));
+ result.hits().add(createHits("source3", 5));
+ result.hits().add(createHits("source4", 6));
+ result.hits().add(createHits("source5", 7));
// Resolve
- Resolver resolver=new DeterministicResolverAssertingMethod();
- Resolution resolution=resolver.resolve(page,query,result);
- Map<String, List<PageElement>> mapping=
- resolution.getResolution((MapChoice)((PageTemplate)page.get(0).get(0)).getSection().elements().get(2));
+ Resolver resolver = new DeterministicResolverAssertingMethod();
+ Resolution resolution = resolver.resolve(page, query, result);
+ Map<String, List<PageElement>> mapping =
+ resolution.getResolution((MapChoice) ((PageTemplate) page.get(0).get(0)).getSection().elements().get(2));
assertNotNull(mapping);
- assertEquals("source1",((Source)mapping.get("box1source").get(0)).getName());
- assertEquals("source2",((Source)mapping.get("box2source").get(0)).getName());
- assertEquals("source3",((Source)mapping.get("box3source").get(0)).getName());
- assertEquals("source4",((Source)mapping.get("box4source").get(0)).getName());
+ assertEquals("source1", ((Source) mapping.get("box1source").get(0)).getName());
+ assertEquals("source2", ((Source) mapping.get("box2source").get(0)).getName());
+ assertEquals("source3", ((Source) mapping.get("box3source").get(0)).getName());
+ assertEquals("source4", ((Source) mapping.get("box4source").get(0)).getName());
// Execute
- Organizer organizer =new Organizer();
- organizer.organize(page,resolution,result);
+ Organizer organizer = new Organizer();
+ organizer.organize(page, resolution, result);
// Check execution:
// Two subsections, each containing two sub-subsections with one source each
- assertEquals(2,result.hits().size());
- HitGroup row1=(HitGroup)result.hits().get(0);
- HitGroup column11=(HitGroup)row1.get(0);
- HitGroup column12=(HitGroup)row1.get(1);
- HitGroup row2=(HitGroup)result.hits().get(1);
- HitGroup column21=(HitGroup)row2.get(0);
- HitGroup column22=(HitGroup)row2.get(1);
- assertEqualHitGroups(createHits("source1",3),column11);
- assertEqualHitGroups(createHits("source2",4),column12);
- assertEqualHitGroups(createHits("source3",5),column21);
- assertEqualHitGroups(createHits("source4",6),column22);
+ assertEquals(2, result.hits().size());
+ HitGroup row1 = (HitGroup) result.hits().get(0);
+ HitGroup column11 = (HitGroup) row1.get(0);
+ HitGroup column12 = (HitGroup) row1.get(1);
+ HitGroup row2 = (HitGroup) result.hits().get(1);
+ HitGroup column21 = (HitGroup) row2.get(0);
+ HitGroup column22 = (HitGroup) row2.get(1);
+ assertEqualHitGroups(createHits("source1", 3), column11);
+ assertEqualHitGroups(createHits("source2", 4), column12);
+ assertEqualHitGroups(createHits("source3", 5), column21);
+ assertEqualHitGroups(createHits("source4", 6), column22);
// Check rendering
- assertRendered(result,"MapSourcesToSectionsResult.xml");
+ assertRendered(result, "MapSourcesToSectionsResult.xml");
}
/** Same as deterministic resolver, but asserts that it received the correct method names for each map choice */
diff --git a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/PageTestCase.java b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/PageTestCase.java
index 6a86f4f81aa..a985c7435d8 100644
--- a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/PageTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/PageTestCase.java
@@ -8,7 +8,7 @@ import com.yahoo.search.pagetemplates.engine.Resolution;
import com.yahoo.search.pagetemplates.engine.Resolver;
import com.yahoo.search.pagetemplates.engine.resolvers.DeterministicResolver;
import com.yahoo.search.pagetemplates.model.Choice;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Tests an example page.
@@ -18,7 +18,7 @@ import org.junit.Test;
public class PageTestCase extends ExecutionAbstractTestCase {
@Test
- public void testExecution() {
+ void testExecution() {
// Create the page template
Choice page = Choice.createSingleton(importPage("Page.xml"));
diff --git a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/PageWithBlendingTestCase.java b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/PageWithBlendingTestCase.java
index 69d35eb2b69..a4166b6d90f 100644
--- a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/PageWithBlendingTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/PageWithBlendingTestCase.java
@@ -8,7 +8,7 @@ import com.yahoo.search.pagetemplates.engine.Resolution;
import com.yahoo.search.pagetemplates.engine.Resolver;
import com.yahoo.search.pagetemplates.engine.resolvers.DeterministicResolver;
import com.yahoo.search.pagetemplates.model.Choice;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Tests an expanded example.
@@ -18,7 +18,7 @@ import org.junit.Test;
public class PageWithBlendingTestCase extends ExecutionAbstractTestCase {
@Test
- public void testExecution() {
+ void testExecution() {
// Create the page template
Choice page = Choice.createSingleton(importPage("PageWithBlending.xml"));
diff --git a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/PageWithSourceRendererTestCase.java b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/PageWithSourceRendererTestCase.java
index 8cb35bf5e4f..7becf7f1895 100644
--- a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/PageWithSourceRendererTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/PageWithSourceRendererTestCase.java
@@ -8,7 +8,7 @@ import com.yahoo.search.pagetemplates.engine.Resolution;
import com.yahoo.search.pagetemplates.engine.Resolver;
import com.yahoo.search.pagetemplates.engine.resolvers.DeterministicResolver;
import com.yahoo.search.pagetemplates.model.Choice;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Tests an example with two data sources with a renderer each.
@@ -18,7 +18,7 @@ import org.junit.Test;
public class PageWithSourceRendererTestCase extends ExecutionAbstractTestCase {
@Test
- public void testExecution() {
+ void testExecution() {
// Create the page template
Choice page = Choice.createSingleton(importPage("PageWithSourceRenderer.xml"));
diff --git a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/SourceChoiceTestCase.java b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/SourceChoiceTestCase.java
index bcd6a462a62..349c39514ba 100644
--- a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/SourceChoiceTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/SourceChoiceTestCase.java
@@ -8,7 +8,7 @@ import com.yahoo.search.pagetemplates.engine.Resolution;
import com.yahoo.search.pagetemplates.engine.Resolver;
import com.yahoo.search.pagetemplates.engine.resolvers.DeterministicResolver;
import com.yahoo.search.pagetemplates.model.Choice;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* @author bratseth
@@ -16,7 +16,7 @@ import org.junit.Test;
public class SourceChoiceTestCase extends ExecutionAbstractTestCase {
@Test
- public void testExecution() {
+ void testExecution() {
// Create the page template
Choice page = Choice.createSingleton(importPage("SourceChoice.xml"));
@@ -29,14 +29,14 @@ public class SourceChoiceTestCase extends ExecutionAbstractTestCase {
// Resolve (noop here)
Resolver resolver = new DeterministicResolver();
- Resolution resolution = resolver.resolve(page,query,result);
+ Resolution resolution = resolver.resolve(page, query, result);
// Execute
Organizer organizer = new Organizer();
organizer.organize(page, resolution, result);
// Check rendering
- assertRendered(result,"SourceChoiceResult.xml", false);
+ assertRendered(result, "SourceChoiceResult.xml", false);
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/TwoSectionsFourSourcesTestCase.java b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/TwoSectionsFourSourcesTestCase.java
index 8413b43e662..43bb16f8b14 100644
--- a/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/TwoSectionsFourSourcesTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/pagetemplates/engine/test/TwoSectionsFourSourcesTestCase.java
@@ -8,11 +8,11 @@ import com.yahoo.search.pagetemplates.engine.resolvers.DeterministicResolver;
import com.yahoo.search.pagetemplates.model.Choice;
import com.yahoo.search.result.Hit;
import com.yahoo.search.result.HitGroup;
-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 bratseth
@@ -20,95 +20,95 @@ import static org.junit.Assert.assertEquals;
public class TwoSectionsFourSourcesTestCase extends ExecutionAbstractTestCase {
@Test
- public void testExecution() {
+ void testExecution() {
// Create the page template
- Choice page=Choice.createSingleton(importPage("TwoSectionsFourSources.xml"));
+ Choice page = Choice.createSingleton(importPage("TwoSectionsFourSources.xml"));
// Create a federated result
- Query query=new Query();
- Result result=new Result(query);
- result.hits().add(createHits("source1",3));
- result.hits().add(createHits("source2",4));
- result.hits().add(createHits("source3",12));
- result.hits().add(createHits("source4",13));
+ Query query = new Query();
+ Result result = new Result(query);
+ result.hits().add(createHits("source1", 3));
+ result.hits().add(createHits("source2", 4));
+ result.hits().add(createHits("source3", 12));
+ result.hits().add(createHits("source4", 13));
- new Organizer().organize(page,new DeterministicResolver().resolve(page,query,result),result);
+ new Organizer().organize(page, new DeterministicResolver().resolve(page, query, result), result);
// Check execution:
// Two subsections with two sources each, the first grouped the second blended
- assertEquals(2,result.hits().size());
- HitGroup section1=(HitGroup)result.hits().get(0);
- HitGroup section2=(HitGroup)result.hits().get(1);
+ assertEquals(2, result.hits().size());
+ HitGroup section1 = (HitGroup) result.hits().get(0);
+ HitGroup section2 = (HitGroup) result.hits().get(1);
assertGroupedSource3Source1(section1.asList());
assertBlendedSource4Source2(section2.asList());
// Check rendering
- assertRendered(result,"TwoSectionsFourSourcesResult.xml");
+ assertRendered(result, "TwoSectionsFourSourcesResult.xml");
}
@Test
- public void testExecutionMissingOneSource() {
+ void testExecutionMissingOneSource() {
// Create the page template
- Choice page=Choice.createSingleton(importPage("TwoSectionsFourSources.xml"));
+ Choice page = Choice.createSingleton(importPage("TwoSectionsFourSources.xml"));
// Create a federated result
- Query query=new Query();
- Result result=new Result(query);
- result.hits().add(createHits("source1",3));
- result.hits().add(createHits("source3",12));
- result.hits().add(createHits("source4",13));
+ Query query = new Query();
+ Result result = new Result(query);
+ result.hits().add(createHits("source1", 3));
+ result.hits().add(createHits("source3", 12));
+ result.hits().add(createHits("source4", 13));
- new Organizer().organize(page,new DeterministicResolver().resolve(page,query,result),result);
+ new Organizer().organize(page, new DeterministicResolver().resolve(page, query, result), result);
// Check execution:
// Two subsections with two sources each, the first grouped the second blended
- assertEquals(2,result.hits().size());
- HitGroup section1=(HitGroup)result.hits().get(0);
- HitGroup section2=(HitGroup)result.hits().get(1);
+ assertEquals(2, result.hits().size());
+ HitGroup section1 = (HitGroup) result.hits().get(0);
+ HitGroup section2 = (HitGroup) result.hits().get(1);
assertGroupedSource3Source1(section1.asList());
- assertEqualHitGroups(createHits("source4",10),section2);
+ assertEqualHitGroups(createHits("source4", 10), section2);
}
@Test
- public void testExecutionMissingTwoSources() {
+ void testExecutionMissingTwoSources() {
// Create the page template
- Choice page=Choice.createSingleton(importPage("TwoSectionsFourSources.xml"));
+ Choice page = Choice.createSingleton(importPage("TwoSectionsFourSources.xml"));
// Create a federated result
- Query query=new Query();
- Result result=new Result(query);
- result.hits().add(createHits("source1",3));
- result.hits().add(createHits("source3",12));
+ Query query = new Query();
+ Result result = new Result(query);
+ result.hits().add(createHits("source1", 3));
+ result.hits().add(createHits("source3", 12));
- new Organizer().organize(page,new DeterministicResolver().resolve(page,query,result),result);
+ new Organizer().organize(page, new DeterministicResolver().resolve(page, query, result), result);
// Check execution:
// Two subsections with two sources each, the first grouped the second blended
- assertEquals(2,result.hits().size());
- HitGroup section1=(HitGroup)result.hits().get(0);
- HitGroup section2=(HitGroup)result.hits().get(1);
+ assertEquals(2, result.hits().size());
+ HitGroup section1 = (HitGroup) result.hits().get(0);
+ HitGroup section2 = (HitGroup) result.hits().get(1);
assertGroupedSource3Source1(section1.asList());
- assertEquals(0,section2.size());
+ assertEquals(0, section2.size());
}
@Test
- public void testExecutionMissingAllSources() {
+ void testExecutionMissingAllSources() {
// Create the page template
- Choice page=Choice.createSingleton(importPage("TwoSectionsFourSources.xml"));
+ Choice page = Choice.createSingleton(importPage("TwoSectionsFourSources.xml"));
// Create a federated result
- Query query=new Query();
- Result result=new Result(query);
+ Query query = new Query();
+ Result result = new Result(query);
- new Organizer().organize(page,new DeterministicResolver().resolve(page,query,result),result);
+ new Organizer().organize(page, new DeterministicResolver().resolve(page, query, result), result);
// Check execution:
// Two subsections with two sources each, the first grouped the second blended
- assertEquals(2,result.hits().size());
- HitGroup section1=(HitGroup)result.hits().get(0);
- HitGroup section2=(HitGroup)result.hits().get(1);
- assertEquals(0,section1.size());
- assertEquals(0,section2.size());
+ assertEquals(2, result.hits().size());
+ HitGroup section1 = (HitGroup) result.hits().get(0);
+ HitGroup section2 = (HitGroup) result.hits().get(1);
+ assertEquals(0, section1.size());
+ assertEquals(0, section2.size());
}
private void assertGroupedSource3Source1(List<Hit> hits) {
diff --git a/container-search/src/test/java/com/yahoo/search/pagetemplates/test/PageTemplateSearcherTestCase.java b/container-search/src/test/java/com/yahoo/search/pagetemplates/test/PageTemplateSearcherTestCase.java
index 7b10966a675..a38c3f164b9 100644
--- a/container-search/src/test/java/com/yahoo/search/pagetemplates/test/PageTemplateSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/pagetemplates/test/PageTemplateSearcherTestCase.java
@@ -18,15 +18,11 @@ import com.yahoo.search.result.Hit;
import com.yahoo.search.result.HitGroup;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.text.interpretation.Interpretation;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.*;
-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.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -34,50 +30,50 @@ import static org.junit.Assert.fail;
public class PageTemplateSearcherTestCase {
@Test
- public void testSearcher() {
+ void testSearcher() {
PageTemplateSearcher s = new PageTemplateSearcher(createPageTemplateRegistry(), new FirstChoiceResolver());
- Chain<Searcher> chain = new Chain<>(s,new MockFederator());
+ Chain<Searcher> chain = new Chain<>(s, new MockFederator());
{
// No template specified, should use default
- Result result=new Execution(chain, Execution.Context.createContextStub()).search(new Query("?query=foo&page.resolver=native.deterministic"));
- assertSources("source1 source2",result);
+ Result result = new Execution(chain, Execution.Context.createContextStub()).search(new Query("?query=foo&page.resolver=native.deterministic"));
+ assertSources("source1 source2", result);
}
{
- Result result=new Execution(chain, Execution.Context.createContextStub()).search(new Query("?query=foo&page.id=oneSource&page.resolver=native.deterministic"));
- assertSources("source1",result);
+ Result result = new Execution(chain, Execution.Context.createContextStub()).search(new Query("?query=foo&page.id=oneSource&page.resolver=native.deterministic"));
+ assertSources("source1", result);
}
{
- Result result=new Execution(chain, Execution.Context.createContextStub()).search(new Query("?query=foo&page.id=twoSources&model.sources=source1&page.resolver=native.deterministic"));
- assertSources("source1",result);
+ Result result = new Execution(chain, Execution.Context.createContextStub()).search(new Query("?query=foo&page.id=twoSources&model.sources=source1&page.resolver=native.deterministic"));
+ assertSources("source1", result);
}
{
- Query query=new Query("?query=foo&page.resolver=native.deterministic");
+ Query query = new Query("?query=foo&page.resolver=native.deterministic");
addIntentModelSpecifyingSource3(query);
- Result result=new Execution(chain, Execution.Context.createContextStub()).search(query);
- assertSources("source1 source2",result);
+ Result result = new Execution(chain, Execution.Context.createContextStub()).search(query);
+ assertSources("source1 source2", result);
}
{
- Query query=new Query("?query=foo&page.id=twoSourcesAndAny&page.resolver=native.deterministic");
+ Query query = new Query("?query=foo&page.id=twoSourcesAndAny&page.resolver=native.deterministic");
addIntentModelSpecifyingSource3(query);
- Result result=new Execution(chain, Execution.Context.createContextStub()).search(query);
- assertSources("source1 source2 source3",result);
+ Result result = new Execution(chain, Execution.Context.createContextStub()).search(query);
+ assertSources("source1 source2 source3", result);
}
{
- Query query=new Query("?query=foo&page.id=anySource&page.resolver=native.deterministic");
+ Query query = new Query("?query=foo&page.id=anySource&page.resolver=native.deterministic");
addIntentModelSpecifyingSource3(query);
- Result result=new Execution(chain, Execution.Context.createContextStub()).search(query);
- assertSources("source3",result);
+ Result result = new Execution(chain, Execution.Context.createContextStub()).search(query);
+ assertSources("source3", result);
}
{
- Query query=new Query("?query=foo&page.id=anySource&page.resolver=native.deterministic");
- Result result=new Execution(chain, Execution.Context.createContextStub()).search(query);
+ Query query = new Query("?query=foo&page.id=anySource&page.resolver=native.deterministic");
+ Result result = new Execution(chain, Execution.Context.createContextStub()).search(query);
assertTrue(query.getModel().getSources().isEmpty());
assertNotNull(result.hits().get("source1"));
assertNotNull(result.hits().get("source2"));
@@ -85,38 +81,38 @@ public class PageTemplateSearcherTestCase {
}
{
- Query query=new Query("?query=foo&page.id=choiceOfSources&page.resolver=native.deterministic");
- Result result=new Execution(chain, Execution.Context.createContextStub()).search(query);
- assertSources("source1 source2","source2",result);
+ Query query = new Query("?query=foo&page.id=choiceOfSources&page.resolver=native.deterministic");
+ Result result = new Execution(chain, Execution.Context.createContextStub()).search(query);
+ assertSources("source1 source2", "source2", result);
}
{
- Query query=new Query("?query=foo&page.id=choiceOfSources&page.resolver=test.firstChoice");
- Result result=new Execution(chain, Execution.Context.createContextStub()).search(query);
- assertSources("source1 source2","source1",result);
+ Query query = new Query("?query=foo&page.id=choiceOfSources&page.resolver=test.firstChoice");
+ Result result = new Execution(chain, Execution.Context.createContextStub()).search(query);
+ assertSources("source1 source2", "source1", result);
}
{ // Specifying two templates, should pick the last
- Query query=new Query("?query=foo&page.id=threeSources+oneSource&page.resolver=native.deterministic");
- Result result=new Execution(chain, Execution.Context.createContextStub()).search(query);
- assertSources("source1 source2 source3","source1",result);
+ Query query = new Query("?query=foo&page.id=threeSources+oneSource&page.resolver=native.deterministic");
+ Result result = new Execution(chain, Execution.Context.createContextStub()).search(query);
+ assertSources("source1 source2 source3", "source1", result);
}
{ // Specifying two templates as a list, should override the page.id setting
- Query query=new Query("?query=foo&page.id=anySource&page.resolver=native.deterministic");
- query.properties().set("page.idList",Arrays.asList("oneSource","threeSources"));
- Result result=new Execution(chain, Execution.Context.createContextStub()).search(query);
- assertSources("source1 source2 source3","source1 source2 source3",result);
+ Query query = new Query("?query=foo&page.id=anySource&page.resolver=native.deterministic");
+ query.properties().set("page.idList", Arrays.asList("oneSource", "threeSources"));
+ Result result = new Execution(chain, Execution.Context.createContextStub()).search(query);
+ assertSources("source1 source2 source3", "source1 source2 source3", result);
}
{
try {
- Query query=new Query("?query=foo&page.id=oneSource+choiceOfSources&page.resolver=noneSuch");
+ Query query = new Query("?query=foo&page.id=oneSource+choiceOfSources&page.resolver=noneSuch");
new Execution(chain, Execution.Context.createContextStub()).search(query);
fail("Expected exception");
}
catch (IllegalArgumentException e) {
- assertEquals("No page template resolver 'noneSuch'",e.getMessage());
+ assertEquals("No page template resolver 'noneSuch'", e.getMessage());
}
}
@@ -182,9 +178,9 @@ public class PageTemplateSearcherTestCase {
Set<String> expectedResultSources=new HashSet<>(Arrays.asList(expectedResultSourceString.split(" ")));
for (String sourceName : Arrays.asList("source1 source2 source3".split(" "))) {
if (expectedResultSources.contains(sourceName))
- assertNotNull("Result contains '" + sourceName + "'",result.hits().get(sourceName));
+ assertNotNull(result.hits().get(sourceName),"Result contains '" + sourceName + "'");
else
- assertNull("Result does not contain '" + sourceName + "'",result.hits().get(sourceName));
+ assertNull(result.hits().get(sourceName),"Result does not contain '" + sourceName + "'");
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/pagetemplates/test/SourceParametersTestCase.java b/container-search/src/test/java/com/yahoo/search/pagetemplates/test/SourceParametersTestCase.java
index 0606636d0cb..50a19753e0c 100644
--- a/container-search/src/test/java/com/yahoo/search/pagetemplates/test/SourceParametersTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/pagetemplates/test/SourceParametersTestCase.java
@@ -7,10 +7,10 @@ import com.yahoo.search.pagetemplates.PageTemplateRegistry;
import com.yahoo.search.pagetemplates.PageTemplateSearcher;
import com.yahoo.search.pagetemplates.config.PageTemplateXMLReader;
import com.yahoo.search.searchchain.Execution;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* @author bratseth
@@ -20,40 +20,40 @@ public class SourceParametersTestCase {
private static final String root="src/test/java/com/yahoo/search/pagetemplates/test/";
@Test
- public void testSourceParametersWithSourcesDeterminedByTemplate() {
+ void testSourceParametersWithSourcesDeterminedByTemplate() {
// Create the page template
- PageTemplateRegistry pageTemplateRegistry=new PageTemplateRegistry();
- PageTemplate page=importPage("SourceParameters.xml");
+ PageTemplateRegistry pageTemplateRegistry = new PageTemplateRegistry();
+ PageTemplate page = importPage("SourceParameters.xml");
pageTemplateRegistry.register(page);
- PageTemplateSearcher s=new PageTemplateSearcher(pageTemplateRegistry);
- Query query=new Query("?query=foo&page.id=SourceParameters&page.resolver=native.deterministic");
+ PageTemplateSearcher s = new PageTemplateSearcher(pageTemplateRegistry);
+ Query query = new Query("?query=foo&page.id=SourceParameters&page.resolver=native.deterministic");
new Execution(s, Execution.Context.createContextStub()).search(query);
- assertEquals("source1p1Value",query.properties().get("source.source1.p1"));
- assertEquals("source1p1Value",query.properties().get("source.source1.p1"));
- assertEquals("source2p1Value",query.properties().get("source.source2.p1"));
- assertEquals("source2p3Value",query.properties().get("source.source2.p3"));
- assertEquals("source3p1Value",query.properties().get("source.source3.p1"));
- assertEquals("We get the correct number of parameters",5,query.properties().listProperties("source").size());
+ assertEquals("source1p1Value", query.properties().get("source.source1.p1"));
+ assertEquals("source1p1Value", query.properties().get("source.source1.p1"));
+ assertEquals("source2p1Value", query.properties().get("source.source2.p1"));
+ assertEquals("source2p3Value", query.properties().get("source.source2.p3"));
+ assertEquals("source3p1Value", query.properties().get("source.source3.p1"));
+ assertEquals(5, query.properties().listProperties("source").size(), "We get the correct number of parameters");
}
@Test
- public void testSourceParametersWithSourcesDeterminedByParameter() {
+ void testSourceParametersWithSourcesDeterminedByParameter() {
// Create the page template
- PageTemplateRegistry pageTemplateRegistry=new PageTemplateRegistry();
- PageTemplate page=importPage("SourceParameters.xml");
+ PageTemplateRegistry pageTemplateRegistry = new PageTemplateRegistry();
+ PageTemplate page = importPage("SourceParameters.xml");
pageTemplateRegistry.register(page);
- PageTemplateSearcher s=new PageTemplateSearcher(pageTemplateRegistry);
- Query query=new Query("?query=foo&page.id=SourceParameters&model.sources=source1,source3&page.resolver=native.deterministic");
+ PageTemplateSearcher s = new PageTemplateSearcher(pageTemplateRegistry);
+ Query query = new Query("?query=foo&page.id=SourceParameters&model.sources=source1,source3&page.resolver=native.deterministic");
new Execution(s, Execution.Context.createContextStub()).search(query);
- assertEquals("source1p1Value",query.properties().get("source.source1.p1"));
- assertEquals("source1p1Value",query.properties().get("source.source1.p1"));
- assertEquals("source3p1Value",query.properties().get("source.source3.p1"));
- assertEquals("We get the correct number of parameters",3,query.properties().listProperties("source").size());
+ assertEquals("source1p1Value", query.properties().get("source.source1.p1"));
+ assertEquals("source1p1Value", query.properties().get("source.source1.p1"));
+ assertEquals("source3p1Value", query.properties().get("source.source3.p1"));
+ assertEquals(3, query.properties().listProperties("source").size(), "We get the correct number of parameters");
}
protected PageTemplate importPage(String name) {
PageTemplate template=new PageTemplateXMLReader().readFile(root + name);
- assertNotNull("Could look up read template '" + name + "'",template);
+ assertNotNull(template,"Could look up read template '" + name + "'");
return template;
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/MatchingTestCase.java b/container-search/src/test/java/com/yahoo/search/query/MatchingTestCase.java
index 9eb44eb0dc4..e3a1eb18a33 100644
--- a/container-search/src/test/java/com/yahoo/search/query/MatchingTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/MatchingTestCase.java
@@ -2,10 +2,9 @@
package com.yahoo.search.query;
import com.yahoo.search.Query;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.*;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author baldersheim
@@ -13,7 +12,7 @@ import static org.junit.Assert.assertEquals;
public class MatchingTestCase {
@Test
- public void testDefaultsInQuery() {
+ void testDefaultsInQuery() {
Query query = new Query("?query=test");
assertNull(query.getRanking().getMatching().getTermwiseLimit());
assertNull(query.getRanking().getMatching().getNumThreadsPerSearch());
@@ -24,7 +23,7 @@ public class MatchingTestCase {
}
@Test
- public void testQueryOverrides() {
+ void testQueryOverrides() {
Query query = new Query("?query=test" +
"&ranking.matching.termwiseLimit=0.7" +
"&ranking.matching.numThreadsPerSearch=17" +
@@ -49,7 +48,7 @@ public class MatchingTestCase {
}
@Test
- public void testBackwardsCompatibleQueryOverrides() {
+ void testBackwardsCompatibleQueryOverrides() {
// The lowercase aliases are supported to provide backwards compatibility of the properties that was wrongly named in the first place.
Query query = new Query("?query=test" +
"&ranking.matching.termwiselimit=0.7" +
@@ -73,7 +72,7 @@ public class MatchingTestCase {
}
@Test
- public void testLimits() {
+ void testLimits() {
verifyException("termwiselimit", "-0.1");
verifyException("termwiselimit", "1.1");
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/QueryTreeTest.java b/container-search/src/test/java/com/yahoo/search/query/QueryTreeTest.java
index 6c73937f4fa..4badb16f20c 100644
--- a/container-search/src/test/java/com/yahoo/search/query/QueryTreeTest.java
+++ b/container-search/src/test/java/com/yahoo/search/query/QueryTreeTest.java
@@ -4,9 +4,9 @@ package com.yahoo.search.query;
import com.yahoo.prelude.query.NotItem;
import com.yahoo.prelude.query.NullItem;
import com.yahoo.prelude.query.WordItem;
-import org.junit.Assert;
-import org.junit.Test;
-import static org.junit.Assert.assertEquals;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bratseth
@@ -14,53 +14,53 @@ import static org.junit.Assert.assertEquals;
public class QueryTreeTest {
@Test
- public void testAddQueryItemWithRoot() {
- Assert.assertEquals("AND a b",
- new QueryTree(new WordItem("a")).and(new WordItem("b")).toString());
+ void testAddQueryItemWithRoot() {
+ assertEquals("AND a b",
+ new QueryTree(new WordItem("a")).and(new WordItem("b")).toString());
NotItem not = new NotItem();
not.addNegativeItem(new WordItem("b"));
assertEquals("+a -b",
- new QueryTree(new WordItem("a")).and(not).toString());
- }
+ new QueryTree(new WordItem("a")).and(not).toString());
+ }
- @Test
- public void addNotToNot() {
- NotItem not1 = new NotItem();
- not1.addPositiveItem(new WordItem("p1"));
- not1.addNegativeItem(new WordItem("n1.1"));
- not1.addNegativeItem(new WordItem("n1.2"));
+ @Test
+ void addNotToNot() {
+ NotItem not1 = new NotItem();
+ not1.addPositiveItem(new WordItem("p1"));
+ not1.addNegativeItem(new WordItem("n1.1"));
+ not1.addNegativeItem(new WordItem("n1.2"));
- NotItem not2 = new NotItem();
- not2.addPositiveItem(new WordItem("p2"));
- not2.addNegativeItem(new WordItem("n2.1"));
- not2.addNegativeItem(new WordItem("n2.2"));
+ NotItem not2 = new NotItem();
+ not2.addPositiveItem(new WordItem("p2"));
+ not2.addNegativeItem(new WordItem("n2.1"));
+ not2.addNegativeItem(new WordItem("n2.2"));
- QueryTree tree = new QueryTree(not1);
- tree.and(not2);
+ QueryTree tree = new QueryTree(not1);
+ tree.and(not2);
- assertEquals("+(AND p1 p2) -n1.1 -n1.2 -n2.1 -n2.2", tree.toString());
- }
+ assertEquals("+(AND p1 p2) -n1.1 -n1.2 -n2.1 -n2.2", tree.toString());
+ }
- @Test
- public void getCorrectTreeSize() {
+ @Test
+ void getCorrectTreeSize() {
QueryTree nullTree = new QueryTree(new NullItem());
assertEquals(0, nullTree.treeSize());
- NotItem not1 = new NotItem();
- not1.addPositiveItem(new WordItem("p1"));
- not1.addNegativeItem(new WordItem("n1.1"));
- not1.addNegativeItem(new WordItem("n1.2"));
+ NotItem not1 = new NotItem();
+ not1.addPositiveItem(new WordItem("p1"));
+ not1.addNegativeItem(new WordItem("n1.1"));
+ not1.addNegativeItem(new WordItem("n1.2"));
- NotItem not2 = new NotItem();
- not2.addPositiveItem(new WordItem("p2"));
- not2.addNegativeItem(new WordItem("n2.1"));
- not2.addNegativeItem(new WordItem("n2.2"));
+ NotItem not2 = new NotItem();
+ not2.addPositiveItem(new WordItem("p2"));
+ not2.addNegativeItem(new WordItem("n2.1"));
+ not2.addNegativeItem(new WordItem("n2.2"));
- QueryTree tree = new QueryTree(not1);
- tree.and(not2);
+ QueryTree tree = new QueryTree(not1);
+ tree.and(not2);
- assertEquals(8, tree.treeSize());
- }
+ assertEquals(8, tree.treeSize());
+ }
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/RankProfileInputTest.java b/container-search/src/test/java/com/yahoo/search/query/RankProfileInputTest.java
index e30e8bf119a..da1d09fec1e 100644
--- a/container-search/src/test/java/com/yahoo/search/query/RankProfileInputTest.java
+++ b/container-search/src/test/java/com/yahoo/search/query/RankProfileInputTest.java
@@ -14,7 +14,7 @@ import com.yahoo.search.query.profile.compiled.CompiledQueryProfile;
import com.yahoo.tensor.Tensor;
import com.yahoo.tensor.TensorType;
import com.yahoo.yolean.Exceptions;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
@@ -23,9 +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.assertThrows;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Tests queries towards rank profiles using input declarations.
@@ -35,7 +33,7 @@ import static org.junit.Assert.fail;
public class RankProfileInputTest {
@Test
- public void testTensorRankFeatureInRequest() {
+ void testTensorRankFeatureInRequest() {
String tensorString = "{{a:a1, b:b1}:1.0, {a:a2, b:b1}:2.0}}";
{
@@ -55,13 +53,12 @@ public class RankProfileInputTest {
{ // Resolution is limited to the correct sources
Query query = createTensor1Query(tensorString, "bOnly", "sources=a");
assertEquals(0, query.errors().size());
- assertEquals("Not converted to tensor",
- tensorString, query.properties().get("ranking.features.query(myTensor1)"));
+ assertEquals(tensorString, query.properties().get("ranking.features.query(myTensor1)"), "Not converted to tensor");
}
}
@Test
- public void testTensorRankFeatureInRequestInconsistentInput() {
+ void testTensorRankFeatureInRequestInconsistentInput() {
String tensorString = "{{a:a1, b:b1}:1.0, {a:a2, b:b1}:2.0}}";
try {
createTensor1Query(tensorString, "inconsistent", "");
@@ -69,14 +66,14 @@ public class RankProfileInputTest {
}
catch (IllegalArgumentException e) {
assertEquals("Conflicting input type declarations for 'query(myTensor1)': " +
- "Declared as tensor(a{},b{}) in rank profile 'inconsistent' in schema 'a', " +
- "and as tensor(x[10]) in rank profile 'inconsistent' in schema 'b'",
- Exceptions.toMessageString(e));
+ "Declared as tensor(a{},b{}) in rank profile 'inconsistent' in schema 'a', " +
+ "and as tensor(x[10]) in rank profile 'inconsistent' in schema 'b'",
+ Exceptions.toMessageString(e));
}
}
@Test
- public void testTensorRankFeatureWithSourceResolution() {
+ void testTensorRankFeatureWithSourceResolution() {
String tensorString = "{{a:a1, b:b1}:1.0, {a:a2, b:b1}:2.0}}";
{
@@ -99,14 +96,14 @@ public class RankProfileInputTest {
}
@Test
- public void testTensorRankFeatureSetProgrammatically() {
+ void testTensorRankFeatureSetProgrammatically() {
String tensorString = "{{a:a1, b:b1}:1.0, {a:a2, b:b1}:2.0}}";
Query query = new Query.Builder()
.setSchemaInfo(createSchemaInfo())
.setQueryProfile(createQueryProfile()) // Use the instantiation path with query profiles
.setRequest(HttpRequest.createTestRequest("?" +
- "&ranking=commonProfile",
- com.yahoo.jdisc.http.HttpRequest.Method.GET))
+ "&ranking=commonProfile",
+ com.yahoo.jdisc.http.HttpRequest.Method.GET))
.build();
query.properties().set("ranking.features.query(myTensor1)", Tensor.from(tensorString));
@@ -114,24 +111,24 @@ public class RankProfileInputTest {
}
@Test
- public void testTensorRankFeatureSetProgrammaticallyWithWrongType() {
+ void testTensorRankFeatureSetProgrammaticallyWithWrongType() {
Query query = new Query.Builder()
.setSchemaInfo(createSchemaInfo())
.setQueryProfile(createQueryProfile()) // Use the instantiation path with query profiles
.setRequest(HttpRequest.createTestRequest("?" +
- "&ranking=commonProfile",
- com.yahoo.jdisc.http.HttpRequest.Method.GET))
+ "&ranking=commonProfile",
+ com.yahoo.jdisc.http.HttpRequest.Method.GET))
.build();
String tensorString = "tensor(x[3]):[0.1, 0.2, 0.3]";
try {
- query.getRanking().getFeatures().put("query(myTensor1)",Tensor.from(tensorString));
+ query.getRanking().getFeatures().put("query(myTensor1)", Tensor.from(tensorString));
fail("Expected exception");
}
catch (IllegalArgumentException e) {
assertEquals("Could not set 'ranking.features.query(myTensor1)' to 'tensor(x[3]):[0.1, 0.2, 0.3]': " +
- "This input is declared in rank profile 'commonProfile' as tensor(a{},b{})",
- Exceptions.toMessageString(e));
+ "This input is declared in rank profile 'commonProfile' as tensor(a{},b{})",
+ Exceptions.toMessageString(e));
}
try {
query.properties().set("ranking.features.query(myTensor1)", Tensor.from(tensorString));
@@ -139,13 +136,13 @@ public class RankProfileInputTest {
}
catch (IllegalArgumentException e) {
assertEquals("Could not set 'ranking.features.query(myTensor1)' to 'tensor(x[3]):[0.1, 0.2, 0.3]': " +
- "Require a tensor of type tensor(a{},b{})",
- Exceptions.toMessageString(e));
+ "Require a tensor of type tensor(a{},b{})",
+ Exceptions.toMessageString(e));
}
}
@Test
- public void testUnembeddedTensorRankFeatureInRequest() {
+ void testUnembeddedTensorRankFeatureInRequest() {
String text = "text to embed into a tensor";
Tensor embedding1 = Tensor.from("tensor<float>(x[5]):[3,7,4,0,0]]");
Tensor embedding2 = Tensor.from("tensor<float>(x[5]):[1,2,3,4,0]]");
@@ -159,7 +156,7 @@ public class RankProfileInputTest {
assertEmbedQuery("embed(emb1, '" + text + "')", embedding1, embedders);
assertEmbedQuery("embed(emb1, \"" + text + "\")", embedding1, embedders);
assertEmbedQueryFails("embed(emb2, \"" + text + "\")", embedding1, embedders,
- "Can't find embedder 'emb2'. Valid embedders are emb1");
+ "Can't find embedder 'emb2'. Valid embedders are emb1");
embedders = Map.of(
"emb1", new MockEmbedder(text, Language.UNKNOWN, embedding1),
@@ -168,7 +165,7 @@ public class RankProfileInputTest {
assertEmbedQuery("embed(emb1, '" + text + "')", embedding1, embedders);
assertEmbedQuery("embed(emb2, '" + text + "')", embedding2, embedders);
assertEmbedQueryFails("embed(emb3, \"" + text + "\")", embedding1, embedders,
- "Can't find embedder 'emb3'. Valid embedders are emb1,emb2");
+ "Can't find embedder 'emb3'. Valid embedders are emb1,emb2");
// And with specified language
embedders = Map.of(
diff --git a/container-search/src/test/java/com/yahoo/search/query/SoftTimeoutTestCase.java b/container-search/src/test/java/com/yahoo/search/query/SoftTimeoutTestCase.java
index f8874040cb2..2decb3fb26a 100644
--- a/container-search/src/test/java/com/yahoo/search/query/SoftTimeoutTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/SoftTimeoutTestCase.java
@@ -2,8 +2,9 @@
package com.yahoo.search.query;
import com.yahoo.search.Query;
-import org.junit.Test;
-import static org.junit.Assert.*;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author baldersheim
@@ -11,7 +12,7 @@ import static org.junit.Assert.*;
public class SoftTimeoutTestCase {
@Test
- public void testDefaultsInQuery() {
+ void testDefaultsInQuery() {
Query query = new Query("?query=test");
assertTrue(query.getRanking().getSoftTimeout().getEnable());
assertNull(query.getRanking().getSoftTimeout().getFactor());
@@ -19,7 +20,7 @@ public class SoftTimeoutTestCase {
}
@Test
- public void testQueryOverride() {
+ void testQueryOverride() {
Query query = new Query("?query=test&ranking.softtimeout.factor=0.7&ranking.softtimeout.tailcost=0.3");
assertTrue(query.getRanking().getSoftTimeout().getEnable());
assertEquals(Double.valueOf(0.7), query.getRanking().getSoftTimeout().getFactor());
@@ -31,16 +32,16 @@ public class SoftTimeoutTestCase {
}
@Test
- public void testDisable() {
- Query query=new Query("?query=test&ranking.softtimeout.enable=false");
+ void testDisable() {
+ Query query = new Query("?query=test&ranking.softtimeout.enable=false");
assertFalse(query.getRanking().getSoftTimeout().getEnable());
query.prepare();
assertEquals("false", query.getRanking().getProperties().get("vespa.softtimeout.enable").get(0));
}
@Test
- public void testEnable() {
- Query query=new Query("?query=test&ranking.softtimeout.enable=true");
+ void testEnable() {
+ Query query = new Query("?query=test&ranking.softtimeout.enable=true");
assertTrue(query.getRanking().getSoftTimeout().getEnable());
query.prepare();
assertEquals("true", query.getRanking().getProperties().get("vespa.softtimeout.enable").get(0));
@@ -57,7 +58,7 @@ public class SoftTimeoutTestCase {
}
@Test
- public void testLimits() {
+ void testLimits() {
verifyException("factor", "-0.1");
verifyException("factor", "1.1");
verifyException("tailcost", "-0.1");
diff --git a/container-search/src/test/java/com/yahoo/search/query/SortingTestCase.java b/container-search/src/test/java/com/yahoo/search/query/SortingTestCase.java
index 4f14ae066cb..facb620b63b 100644
--- a/container-search/src/test/java/com/yahoo/search/query/SortingTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/SortingTestCase.java
@@ -5,20 +5,19 @@ import com.ibm.icu.lang.UScript;
import com.ibm.icu.text.Collator;
import com.ibm.icu.text.RuleBasedCollator;
import com.ibm.icu.util.ULocale;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
-import static org.junit.Assert.*;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author baldersheim
*/
public class SortingTestCase {
@Test
- public void validAttributeName() {
+ void validAttributeName() {
assertNotNull(Sorting.fromString("a"));
assertNotNull(Sorting.fromString("_a"));
assertNotNull(Sorting.fromString("+a"));
@@ -33,8 +32,9 @@ public class SortingTestCase {
fail("I only expect 'IllegalArgumentException', not: + " + e.toString());
}
}
+
@Test
- public void requireThatChineseSortCorrect() {
+ void requireThatChineseSortCorrect() {
requireThatChineseHasCorrectRules(Collator.getInstance(new ULocale("zh")));
Sorting ch = Sorting.fromString("uca(a,zh)");
assertEquals(1, ch.fieldOrders().size());
@@ -69,9 +69,10 @@ public class SortingTestCase {
assertNotEquals("", ((RuleBasedCollator) col).getRules());
}
+
@Test
- @Ignore
- public void requireThatArabicSortCorrect() {
+ @Disabled
+ void requireThatArabicSortCorrect() {
requireThatArabicHasCorrectRules(Collator.getInstance(new ULocale("ar")));
Sorting ar = Sorting.fromString("uca(a,ar)");
assertEquals(1, ar.fieldOrders().size());
diff --git a/container-search/src/test/java/com/yahoo/search/query/context/test/LoggingTestCase.java b/container-search/src/test/java/com/yahoo/search/query/context/test/LoggingTestCase.java
index 0152367915a..d4f1e814980 100644
--- a/container-search/src/test/java/com/yahoo/search/query/context/test/LoggingTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/context/test/LoggingTestCase.java
@@ -8,10 +8,10 @@ import java.util.Set;
import com.yahoo.processing.execution.Execution;
import com.yahoo.search.Query;
import com.yahoo.search.query.context.QueryContext;
-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;
/**
* @author bratseth
@@ -19,34 +19,34 @@ import static org.junit.Assert.assertTrue;
public class LoggingTestCase {
@Test
- public void testLogging() {
- Query query=new Query();
+ void testLogging() {
+ Query query = new Query();
QueryContext queryContext = query.getContext(true);
- queryContext.logValue("a","a1");
+ queryContext.logValue("a", "a1");
queryContext.trace("first message", 2);
- queryContext.logValue("a","a2");
- queryContext.logValue("b","b1");
+ queryContext.logValue("a", "a2");
+ queryContext.logValue("b", "b1");
QueryContext h2 = query.clone().getContext(true);
- h2.logValue("b","b2");
+ h2.logValue("b", "b2");
h2.trace("second message", 2);
- h2.logValue("b","b3");
- queryContext.logValue("b","b4");
+ h2.logValue("b", "b3");
+ queryContext.logValue("b", "b4");
QueryContext h3 = query.clone().getContext(true);
- h3.logValue("b","b5");
- h3.logValue("c","c1");
+ h3.logValue("b", "b5");
+ h3.logValue("c", "c1");
h3.trace("third message", 2);
- h2.logValue("c","c2");
+ h2.logValue("c", "c2");
queryContext.trace("fourth message", 2);
- queryContext.logValue("d","d1");
+ queryContext.logValue("d", "d1");
h2.trace("fifth message", 2);
- h2.logValue("c","c3");
- queryContext.logValue("c","c4");
+ h2.logValue("c", "c3");
+ queryContext.logValue("c", "c4");
// Assert that all of the above is in the log, in some undefined order
- Set<String> logValues=new HashSet<>();
- for (Iterator<Execution.Trace.LogValue> logValueIterator=queryContext.logValueIterator(); logValueIterator.hasNext(); )
+ Set<String> logValues = new HashSet<>();
+ for (Iterator<Execution.Trace.LogValue> logValueIterator = queryContext.logValueIterator(); logValueIterator.hasNext(); )
logValues.add(logValueIterator.next().toString());
- assertEquals(12,logValues.size());
+ assertEquals(12, logValues.size());
assertTrue(logValues.contains("a=a1"));
assertTrue(logValues.contains("a=a2"));
assertTrue(logValues.contains("b=b1"));
diff --git a/container-search/src/test/java/com/yahoo/search/query/context/test/PropertiesTestCase.java b/container-search/src/test/java/com/yahoo/search/query/context/test/PropertiesTestCase.java
index 61e1f06ed28..8505da0e814 100644
--- a/container-search/src/test/java/com/yahoo/search/query/context/test/PropertiesTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/context/test/PropertiesTestCase.java
@@ -3,10 +3,10 @@ package com.yahoo.search.query.context.test;
import com.yahoo.search.Query;
import com.yahoo.search.query.context.QueryContext;
-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 bratseth
@@ -14,34 +14,34 @@ import static org.junit.Assert.assertNull;
public class PropertiesTestCase {
@Test
- public void testProperties() {
- Query query=new Query();
+ void testProperties() {
+ Query query = new Query();
QueryContext h = query.getContext(true);
- h.setProperty("a","a1");
+ h.setProperty("a", "a1");
h.trace("first message", 2);
- h.setProperty("a","a2");
- h.setProperty("b","b1");
+ h.setProperty("a", "a2");
+ h.setProperty("b", "b1");
query.clone();
QueryContext h2 = query.clone().getContext(true);
- h2.setProperty("b","b2");
+ h2.setProperty("b", "b2");
h2.trace("second message", 2);
- h2.setProperty("b","b3");
- h.setProperty("b","b4");
+ h2.setProperty("b", "b3");
+ h.setProperty("b", "b4");
QueryContext h3 = query.clone().getContext(true);
- h3.setProperty("b","b5");
- h3.setProperty("c","c1");
+ h3.setProperty("b", "b5");
+ h3.setProperty("c", "c1");
h3.trace("third message", 2);
- h2.setProperty("c","c2");
+ h2.setProperty("c", "c2");
h.trace("fourth message", 2);
- h.setProperty("d","d1");
+ h.setProperty("d", "d1");
h2.trace("fifth message", 2);
- h2.setProperty("c","c3");
- h.setProperty("c","c4");
+ h2.setProperty("c", "c3");
+ h.setProperty("c", "c4");
- assertEquals("a2",h.getProperty("a"));
- assertEquals("b5",h.getProperty("b"));
- assertEquals("c4",h.getProperty("c"));
- assertEquals("d1",h.getProperty("d"));
+ assertEquals("a2", h.getProperty("a"));
+ assertEquals("b5", h.getProperty("b"));
+ assertEquals("c4", h.getProperty("c"));
+ assertEquals("d1", h.getProperty("d"));
assertNull(h.getProperty("e"));
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/context/test/TraceTestCase.java b/container-search/src/test/java/com/yahoo/search/query/context/test/TraceTestCase.java
index 76f243e4592..a340e83a77c 100644
--- a/container-search/src/test/java/com/yahoo/search/query/context/test/TraceTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/context/test/TraceTestCase.java
@@ -3,15 +3,15 @@ package com.yahoo.search.query.context.test;
import com.yahoo.search.Query;
import com.yahoo.search.query.context.QueryContext;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Iterator;
-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 Steinar Knutsen
@@ -19,8 +19,8 @@ import static org.junit.Assert.assertTrue;
public class TraceTestCase {
@Test
- public void testBasicTracing() {
- Query query=new Query();
+ void testBasicTracing() {
+ Query query = new Query();
QueryContext h = query.getContext(true);
h.trace("first message", 0);
h.trace("second message", 0);
@@ -28,8 +28,8 @@ public class TraceTestCase {
}
@Test
- public void testCloning() throws IOException {
- Query query=new Query();
+ void testCloning() throws IOException {
+ Query query = new Query();
QueryContext h = query.getContext(true);
h.trace("first message", 0);
QueryContext h2 = query.clone().getContext(true);
@@ -49,19 +49,19 @@ public class TraceTestCase {
assertEquals(toplevel, finishedBelow);
// basic sanity test
assertEquals("trace: [ [ " +
- "first message second message third message " +
- "fourth message fifth message ] ]",h.toString());
+ "first message second message third message " +
+ "fourth message fifth message ] ]", h.toString());
Iterator<String> i = h.getTrace().traceNode().root().descendants(String.class).iterator();
- assertEquals("first message",i.next());
- assertEquals("second message",i.next());
- assertEquals("third message",i.next());
- assertEquals("fourth message",i.next());
- assertEquals("fifth message",i.next());
+ assertEquals("first message", i.next());
+ assertEquals("second message", i.next());
+ assertEquals("third message", i.next());
+ assertEquals("fourth message", i.next());
+ assertEquals("fifth message", i.next());
}
@Test
- public void testEmpty() throws IOException {
- Query query=new Query();
+ void testEmpty() throws IOException {
+ Query query = new Query();
QueryContext h = query.getContext(true);
Writer w = new StringWriter();
h.render(w);
@@ -69,20 +69,20 @@ public class TraceTestCase {
}
@Test
- public void testEmptySubSequence() {
- Query query=new Query();
+ void testEmptySubSequence() {
+ Query query = new Query();
QueryContext h = query.getContext(true);
query.clone().getContext(true);
Writer w = new StringWriter();
try {
h.render(w);
} catch (IOException e) {
- assertTrue("rendering empty subsequence crashed", false);
+ assertTrue(false, "rendering empty subsequence crashed");
}
}
@Test
- public void testAttachedTraces() throws IOException {
+ void testAttachedTraces() throws IOException {
String needle0 = "nalle";
String needle1 = "tralle";
String needle2 = "trolle";
@@ -101,10 +101,10 @@ public class TraceTestCase {
int tralle = trace.indexOf(needle1);
int trolle = trace.indexOf(needle2);
int bamse = trace.indexOf(needle3);
- assertTrue("Could not find first manual context to main query.", nalle > 0);
- assertTrue("Could not find second manual context to main query.", bamse > 0);
- assertTrue("Could not find first manual context to attached query.", tralle > 0);
- assertTrue("Could not find second manual context to attached query.", trolle > 0);
+ assertTrue(nalle > 0, "Could not find first manual context to main query.");
+ assertTrue(bamse > 0, "Could not find second manual context to main query.");
+ assertTrue(tralle > 0, "Could not find first manual context to attached query.");
+ assertTrue(trolle > 0, "Could not find second manual context to attached query.");
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/ChainedMapTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/ChainedMapTestCase.java
index 22847772ff3..a73d12a5a4e 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/ChainedMapTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/ChainedMapTestCase.java
@@ -1,28 +1,27 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.query.profile;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
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.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author baldersheim
*/
public class ChainedMapTestCase {
@Test
- public void testIsEmpty() {
+ void testIsEmpty() {
assertTrue(new ChainedMap<String, String>(Map.of(), Map.of()).isEmpty());
assertFalse(new ChainedMap<>(Map.of("k", "v"), Map.of()).isEmpty());
assertFalse(new ChainedMap<>(Map.of(), Map.of("k", "v")).isEmpty());
assertFalse(new ChainedMap<>(Map.of("k", "v"), Map.of("k", "v")).isEmpty());
}
+
@Test
- public void testSize() {
+ void testSize() {
assertEquals(0, new ChainedMap<String, String>(Map.of(), Map.of()).size());
assertEquals(1, new ChainedMap<>(Map.of("k", "v"), Map.of()).size());
assertEquals(1, new ChainedMap<>(Map.of(), Map.of("k", "v")).size());
@@ -30,8 +29,9 @@ public class ChainedMapTestCase {
assertEquals(2, new ChainedMap<>(Map.of("k", "v"), Map.of("K", "v")).size());
assertEquals(2, new ChainedMap<>(Map.of("k", "v"), Map.of("K", "v", "k", "v")).size());
}
+
@Test
- public void testGetUsesBoth() {
+ void testGetUsesBoth() {
Map<String, String> a = Map.of("a", "a_1");
Map<String, String> b = Map.of("b", "b_1");
Map<String, String> ab = Map.of("a", "a_2", "b", "b_2");
@@ -53,7 +53,7 @@ public class ChainedMapTestCase {
}
@Test
- public void testKeySet() {
+ void testKeySet() {
assertTrue(new ChainedMap<String, String>(Map.of(), Map.of()).keySet().isEmpty());
Map<String, String> a = Map.of("a", "a_1");
Map<String, String> b = Map.of("b", "b_1");
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/compiled/BindingTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/compiled/BindingTestCase.java
index bebdda15983..013de292cb7 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/compiled/BindingTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/compiled/BindingTestCase.java
@@ -2,13 +2,13 @@
package com.yahoo.search.query.profile.compiled;
import com.yahoo.search.query.profile.DimensionBinding;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
-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
@@ -16,7 +16,7 @@ import static org.junit.Assert.assertTrue;
public class BindingTestCase {
@Test
- public void testGeneralizes() {
+ void testGeneralizes() {
Map<String, String> m1 = new HashMap<>();
m1.put("a", "a1");
m1.put("b", "b1");
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/compiled/CompiledQueryProfileRegistryTest.java b/container-search/src/test/java/com/yahoo/search/query/profile/compiled/CompiledQueryProfileRegistryTest.java
index 511921ac047..c2faeb899c9 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/compiled/CompiledQueryProfileRegistryTest.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/compiled/CompiledQueryProfileRegistryTest.java
@@ -2,12 +2,12 @@
package com.yahoo.search.query.profile.compiled;
import com.yahoo.search.query.profile.config.QueryProfilesConfig;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.Executors;
-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
@@ -15,13 +15,13 @@ import static org.junit.Assert.assertTrue;
public class CompiledQueryProfileRegistryTest {
@Test
- public void registry_can_be_created_from_config() {
+ void registry_can_be_created_from_config() {
var config = new QueryProfilesConfig.Builder()
.queryprofile(new QueryProfilesConfig.Queryprofile.Builder()
- .id("profile1")
- .property(new QueryProfilesConfig.Queryprofile.Property.Builder()
- .name("hits")
- .value("5")))
+ .id("profile1")
+ .property(new QueryProfilesConfig.Queryprofile.Property.Builder()
+ .name("hits")
+ .value("5")))
.build();
var executor = Executors.newCachedThreadPool();
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/config/test/MultiProfileTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/config/test/MultiProfileTestCase.java
index 21f20e70ddb..ebe9c9d3c04 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/config/test/MultiProfileTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/config/test/MultiProfileTestCase.java
@@ -7,10 +7,10 @@ import java.util.Map;
import com.yahoo.search.query.profile.QueryProfile;
import com.yahoo.search.query.profile.QueryProfileRegistry;
import com.yahoo.search.query.profile.config.QueryProfileXMLReader;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* @author bratseth
@@ -18,31 +18,31 @@ import static org.junit.Assert.assertNotNull;
public class MultiProfileTestCase {
@Test
- public void testValid() {
- QueryProfileRegistry registry=
+ void testValid() {
+ QueryProfileRegistry registry =
new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/multiprofile");
- QueryProfile multiprofile1=registry.getComponent("multiprofile1");
+ QueryProfile multiprofile1 = registry.getComponent("multiprofile1");
assertNotNull(multiprofile1);
- assertGet("general-a","a",new String[] {null,null,null},multiprofile1);
- assertGet("us-nokia-test1-a","a",new String[] {"us","nok ia","test1"},multiprofile1);
- assertGet("us-nokia-b","b",new String[] {"us","nok ia","test1"},multiprofile1);
- assertGet("us-a","a",new String[] {"us",null,null},multiprofile1);
- assertGet("us-b","b",new String[] {"us",null,null},multiprofile1);
- assertGet("us-nokia-a","a",new String[] {"us","nok ia",null},multiprofile1);
- assertGet("us-test1-a","a",new String[] {"us",null,"test1"},multiprofile1);
- assertGet("us-test1-b","b",new String[] {"us",null,"test1"},multiprofile1);
+ assertGet("general-a", "a", new String[]{null, null, null}, multiprofile1);
+ assertGet("us-nokia-test1-a", "a", new String[]{"us", "nok ia", "test1"}, multiprofile1);
+ assertGet("us-nokia-b", "b", new String[]{"us", "nok ia", "test1"}, multiprofile1);
+ assertGet("us-a", "a", new String[]{"us", null, null}, multiprofile1);
+ assertGet("us-b", "b", new String[]{"us", null, null}, multiprofile1);
+ assertGet("us-nokia-a", "a", new String[]{"us", "nok ia", null}, multiprofile1);
+ assertGet("us-test1-a", "a", new String[]{"us", null, "test1"}, multiprofile1);
+ assertGet("us-test1-b", "b", new String[]{"us", null, "test1"}, multiprofile1);
- assertGet("us-a","a",new String[] {"us","unspecified","unspecified"},multiprofile1);
- assertGet("us-nokia-a","a",new String[] {"us","nok ia","unspecified"},multiprofile1);
- assertGet("us-test1-a","a",new String[] {"us","unspecified","test1"},multiprofile1);
- assertGet("us-nokia-b","b",new String[] {"us","nok ia","test1"},multiprofile1);
+ assertGet("us-a", "a", new String[]{"us", "unspecified", "unspecified"}, multiprofile1);
+ assertGet("us-nokia-a", "a", new String[]{"us", "nok ia", "unspecified"}, multiprofile1);
+ assertGet("us-test1-a", "a", new String[]{"us", "unspecified", "test1"}, multiprofile1);
+ assertGet("us-nokia-b", "b", new String[]{"us", "nok ia", "test1"}, multiprofile1);
// ...inherited
- assertGet("parent1-value","parent1",new String[] { "us","nok ia","-" }, multiprofile1);
- assertGet("parent2-value","parent2",new String[] { "us","nok ia","-" }, multiprofile1);
- assertGet(null,"parent1",new String[] { "us","-","-" }, multiprofile1);
- assertGet(null,"parent2",new String[] { "us","-","-" }, multiprofile1);
+ assertGet("parent1-value", "parent1", new String[]{"us", "nok ia", "-"}, multiprofile1);
+ assertGet("parent2-value", "parent2", new String[]{"us", "nok ia", "-"}, multiprofile1);
+ assertGet(null, "parent1", new String[]{"us", "-", "-"}, multiprofile1);
+ assertGet(null, "parent2", new String[]{"us", "-", "-"}, multiprofile1);
}
private void assertGet(String expectedValue,String parameter,String[] dimensionValues,QueryProfile profile) {
@@ -50,7 +50,7 @@ public class MultiProfileTestCase {
context.put("region",dimensionValues[0]);
context.put("model",dimensionValues[1]);
context.put("bucket",dimensionValues[2]);
- assertEquals("Looking up '" + parameter + "' for '" + toString(dimensionValues) + "'",expectedValue,profile.get(parameter,context,null));
+ assertEquals(expectedValue,profile.get(parameter,context,null),"Looking up '" + parameter + "' for '" + toString(dimensionValues) + "'");
}
private String toString(String[] array) {
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/config/test/QueryProfileConfigurationTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/config/test/QueryProfileConfigurationTestCase.java
index 29a8969233b..bf3afecc115 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/config/test/QueryProfileConfigurationTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/config/test/QueryProfileConfigurationTestCase.java
@@ -7,15 +7,13 @@ import com.yahoo.search.query.profile.QueryProfileProperties;
import com.yahoo.search.query.profile.compiled.CompiledQueryProfile;
import com.yahoo.search.query.profile.config.QueryProfileConfigurer;
import com.yahoo.search.test.QueryTestCase;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -25,9 +23,9 @@ public class QueryProfileConfigurationTestCase {
public final String CONFIG_DIR ="src/test/java/com/yahoo/search/query/profile/config/test/";
@Test
- public void testConfiguration() {
+ void testConfiguration() {
var profile = QueryProfileConfigurer.createFromConfigId("file:" + CONFIG_DIR + "query-profiles-configuration.cfg")
- .getComponent("default");
+ .getComponent("default");
assertEquals("a-value", profile.get("a"));
assertEquals("b-value", profile.get("b"));
@@ -43,9 +41,9 @@ public class QueryProfileConfigurationTestCase {
}
@Test
- public void testBug3197426() {
+ void testBug3197426() {
var profile = QueryProfileConfigurer.createFromConfigId("file:" + CONFIG_DIR + "bug3197426.cfg")
- .getComponent("default").compile(null);
+ .getComponent("default").compile(null);
Map<String, Object> properties = new QueryProfileProperties(profile).listProperties("source.image");
assertEquals("yes", properties.get("mlr"));
@@ -63,42 +61,42 @@ public class QueryProfileConfigurationTestCase {
}
@Test
- public void testVariantConfiguration() {
+ void testVariantConfiguration() {
var registry = QueryProfileConfigurer.createFromConfigId("file:" + CONFIG_DIR + "query-profile-variants-configuration.cfg");
// Variant 1
QueryProfile variants1 = registry.getComponent("variants1");
- assertGet("x1.y1.a", "a", new String[] { "x1","y1" }, variants1);
- assertGet("x1.y1.b", "b", new String[] { "x1","y1" }, variants1);
- assertGet("x1.y?.a", "a", new String[] { "x1","zz" }, variants1);
- assertGet("x?.y1.a", "a", new String[] { "zz","y1" }, variants1);
- assertGet("a-deflt", "a", new String[] { "z1","z2" }, variants1);
+ assertGet("x1.y1.a", "a", new String[]{"x1", "y1"}, variants1);
+ assertGet("x1.y1.b", "b", new String[]{"x1", "y1"}, variants1);
+ assertGet("x1.y?.a", "a", new String[]{"x1", "zz"}, variants1);
+ assertGet("x?.y1.a", "a", new String[]{"zz", "y1"}, variants1);
+ assertGet("a-deflt", "a", new String[]{"z1", "z2"}, variants1);
// ...inherited
- assertGet("parent1-value", "parent1", new String[] { "x1","y1" }, variants1);
- assertGet("parent2-value", "parent2", new String[] { "x1","y1" }, variants1);
- assertGet(null, "parent1", new String[] { "x1","y2" }, variants1);
- assertGet(null, "parent2", new String[] { "x1","y2" }, variants1);
+ assertGet("parent1-value", "parent1", new String[]{"x1", "y1"}, variants1);
+ assertGet("parent2-value", "parent2", new String[]{"x1", "y1"}, variants1);
+ assertGet(null, "parent1", new String[]{"x1", "y2"}, variants1);
+ assertGet(null, "parent2", new String[]{"x1", "y2"}, variants1);
// Variant 2
QueryProfile variants2 = registry.getComponent("variants2");
- assertGet("variant2:y1.c", "c", new String[] { "*","y1" }, variants2);
- assertGet("variant2:y2.c", "c", new String[] { "*","y2" }, variants2);
- assertGet("variant2:c-df", "c", new String[] { "*","z1" }, variants2);
- assertGet("variant2:c-df", "c", new String[] { }, variants2);
- assertGet("variant2:c-df", "c", new String[] { "*" }, variants2);
- assertGet(null, "d", new String[] { "*","y1" }, variants2);
+ assertGet("variant2:y1.c", "c", new String[]{"*", "y1"}, variants2);
+ assertGet("variant2:y2.c", "c", new String[]{"*", "y2"}, variants2);
+ assertGet("variant2:c-df", "c", new String[]{"*", "z1"}, variants2);
+ assertGet("variant2:c-df", "c", new String[]{ }, variants2);
+ assertGet("variant2:c-df", "c", new String[]{"*" }, variants2);
+ assertGet(null, "d", new String[]{"*", "y1"}, variants2);
// Reference following from variant 1
- assertGet("variant2:y1.c", "toVariants.c", new String[] { "**", "y1" } , variants1);
- assertGet("variant3:c-df", "toVariants.c", new String[] { "x1", "**" } , variants1);
- assertGet("variant3:y1.c", "toVariants.c", new String[] { "x1", "y1" } , variants1); // variant3 by order priority
- assertGet("variant3:y2.c", "toVariants.c", new String[] { "x1", "y2" } , variants1);
+ assertGet("variant2:y1.c", "toVariants.c", new String[]{"**", "y1"}, variants1);
+ assertGet("variant3:c-df", "toVariants.c", new String[]{"x1", "**"}, variants1);
+ assertGet("variant3:y1.c", "toVariants.c", new String[]{"x1", "y1"}, variants1); // variant3 by order priority
+ assertGet("variant3:y2.c", "toVariants.c", new String[]{"x1", "y2"}, variants1);
}
@Test
- public void testVariantConfigurationThroughQueryLookup() {
+ void testVariantConfigurationThroughQueryLookup() {
var registry = QueryProfileConfigurer.createFromConfigId("file:" + CONFIG_DIR + "query-profile-variants-configuration.cfg")
- .compile();
+ .compile();
CompiledQueryProfile variants1 = registry.getComponent("variants1");
@@ -107,7 +105,7 @@ public class QueryProfileConfigurationTestCase {
assertEquals("x1.y1.b", new Query(QueryTestCase.httpEncode("?query=foo&x=x1&y=y1"), variants1).properties().get("b"));
assertEquals("x1.y1.defaultIndex", new Query(QueryTestCase.httpEncode("?query=foo&x=x1&y=y1"), variants1).getModel().getDefaultIndex());
assertEquals("x1.y?.a", new Query(QueryTestCase.httpEncode("?query=foo&x=x1&y=zz"), variants1).properties().get("a"));
- assertEquals("x1.y?.defaultIndex", new Query(QueryTestCase.httpEncode("?query=foo&x=x1&y=zz"),variants1).getModel().getDefaultIndex());
+ assertEquals("x1.y?.defaultIndex", new Query(QueryTestCase.httpEncode("?query=foo&x=x1&y=zz"), variants1).getModel().getDefaultIndex());
assertEquals("x?.y1.a", new Query(QueryTestCase.httpEncode("?query=foo&x=zz&y=y1"), variants1).properties().get("a"));
assertEquals("x?.y1.defaultIndex", new Query(QueryTestCase.httpEncode("?query=foo&x=zz&y=y1"), variants1).getModel().getDefaultIndex());
assertEquals("x?.y1.filter", new Query(QueryTestCase.httpEncode("?query=foo&x=zz&y=y1"), variants1).getModel().getFilter());
@@ -130,14 +128,14 @@ public class QueryProfileConfigurationTestCase {
}
@Test
- public void testVariant2ConfigurationThroughQueryLookup() {
+ void testVariant2ConfigurationThroughQueryLookup() {
final double delta = 0.0000001;
var registry = QueryProfileConfigurer.createFromConfigId("file:" + CONFIG_DIR + "query-profile-variants2.cfg")
- .compile();
+ .compile();
Query query = new Query(QueryTestCase.httpEncode("?query=heh&queryProfile=multi&myindex=default&myquery=lo ve&tracelevel=5"),
- registry.findQueryProfile("multi"));
+ registry.findQueryProfile("multi"));
assertEquals("love", query.properties().get("model.queryString"));
assertEquals("default", query.properties().get("model.defaultIndex"));
@@ -152,8 +150,7 @@ public class QueryProfileConfigurationTestCase {
Map<String, String> context = new HashMap<>();
for (int i = 0; i<dimensionValues.length; i++)
context.put(profile.getVariants().getDimensions().get(i), dimensionValues[i]); // Lookup dim. names to ease test...
- assertEquals("Looking up '" + parameter + "' for '" + Arrays.toString(dimensionValues) + "'",
- expectedValue, profile.get(parameter, context, null));
+ assertEquals(expectedValue, profile.get(parameter, context, null), "Looking up '" + parameter + "' for '" + Arrays.toString(dimensionValues) + "'");
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/config/test/QueryProfileIntegrationTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/config/test/QueryProfileIntegrationTestCase.java
index c64d5df64f9..ce6f6264623 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/config/test/QueryProfileIntegrationTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/config/test/QueryProfileIntegrationTestCase.java
@@ -14,10 +14,10 @@ import com.yahoo.search.handler.HttpSearchResponse;
import com.yahoo.search.handler.SearchHandler;
import com.yahoo.search.result.Hit;
import com.yahoo.search.searchchain.Execution;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* Tests using query profiles in searches
@@ -26,13 +26,13 @@ import static org.junit.Assert.assertNotNull;
*/
public class QueryProfileIntegrationTestCase {
- @org.junit.After
+ @org.junit.jupiter.api.AfterEach
public void tearDown() {
System.getProperties().remove("config.id");
}
@Test
- public void testUntyped() {
+ void testUntyped() {
String configId = "dir:src/test/java/com/yahoo/search/query/profile/config/test/untyped";
System.setProperty("config.id", configId);
Container container = new Container();
@@ -41,79 +41,79 @@ public class QueryProfileIntegrationTestCase {
// Should get "default" query profile containing the "test" search chain containing the "test" searcher
HttpRequest request = HttpRequest.createTestRequest("search", Method.GET);
- HttpSearchResponse response = (HttpSearchResponse)searchHandler.handle(request); // Cast to access content directly
+ HttpSearchResponse response = (HttpSearchResponse) searchHandler.handle(request); // Cast to access content directly
assertNotNull(response.getResult().hits().get("from:test"));
// Should get the "test' query profile containing the "default" search chain containing the "default" searcher
request = HttpRequest.createTestRequest("search?queryProfile=test", Method.GET);
- response = (HttpSearchResponse)searchHandler.handle(request); // Cast to access content directly
+ response = (HttpSearchResponse) searchHandler.handle(request); // Cast to access content directly
assertNotNull(response.getResult().hits().get("from:default"));
// Should get "default" query profile, but override the search chain to default
request = HttpRequest.createTestRequest("search?searchChain=default", Method.GET);
- response = (HttpSearchResponse)searchHandler.handle(request); // Cast to access content directly
+ response = (HttpSearchResponse) searchHandler.handle(request); // Cast to access content directly
assertNotNull(response.getResult().hits().get("from:default"));
// Tests a profile setting hits and offset
request = HttpRequest.createTestRequest("search?queryProfile=hitsoffset", Method.GET);
- response = (HttpSearchResponse)searchHandler.handle(request); // Cast to access content directly
+ response = (HttpSearchResponse) searchHandler.handle(request); // Cast to access content directly
assertEquals(20, response.getQuery().getHits());
assertEquals(80, response.getQuery().getOffset());
// Tests a non-resolved profile request
request = HttpRequest.createTestRequest("search?queryProfile=none", Method.GET);
- response = (HttpSearchResponse)searchHandler.handle(request); // Cast to access content directly
- assertNotNull("Got an error", response.getResult().hits().getError());
+ response = (HttpSearchResponse) searchHandler.handle(request); // Cast to access content directly
+ assertNotNull(response.getResult().hits().getError(), "Got an error");
assertEquals("Could not resolve query profile 'none'", response.getResult().hits().getError().getDetailedMessage());
// Tests that properties in objects owned by query is handled correctly
request = HttpRequest.createTestRequest("search?query=word&queryProfile=test", Method.GET);
- response = (HttpSearchResponse)searchHandler.handle(request); // Cast to access content directly
- assertEquals("index" ,response.getQuery().getModel().getDefaultIndex());
+ response = (HttpSearchResponse) searchHandler.handle(request); // Cast to access content directly
+ assertEquals("index", response.getQuery().getModel().getDefaultIndex());
assertEquals("WEAKAND(100) index:word", response.getQuery().getModel().getQueryTree().toString());
configurer.shutdown();
}
@Test
- public void testTyped() {
+ void testTyped() {
String configId = "dir:src/test/java/com/yahoo/search/query/profile/config/test/typed";
System.setProperty("config.id", configId);
Container container = new Container();
HandlersConfigurerTestWrapper configurer = new HandlersConfigurerTestWrapper(container, configId);
- SearchHandler searchHandler = (SearchHandler)configurer.getRequestHandlerRegistry().getComponent(SearchHandler.class.getName());
+ SearchHandler searchHandler = (SearchHandler) configurer.getRequestHandlerRegistry().getComponent(SearchHandler.class.getName());
// Should get "default" query profile containing the "test" search chain containing the "test" searcher
HttpRequest request = HttpRequest.createTestRequest("search", Method.GET);
- HttpSearchResponse response = (HttpSearchResponse)searchHandler.handle(request); // Cast to access content directly
+ HttpSearchResponse response = (HttpSearchResponse) searchHandler.handle(request); // Cast to access content directly
assertNotNull(response.getResult().hits().get("from:test"));
// Should get the "test' query profile containing the "default" search chain containing the "default" searcher
request = HttpRequest.createTestRequest("search?queryProfile=test", Method.GET);
- response = (HttpSearchResponse)searchHandler.handle(request); // Cast to access content directly
+ response = (HttpSearchResponse) searchHandler.handle(request); // Cast to access content directly
assertNotNull(response.getResult().hits().get("from:default"));
// Should get "default" query profile, but override the search chain to default
request = HttpRequest.createTestRequest("search?searchChain=default", Method.GET);
- response = (HttpSearchResponse)searchHandler.handle(request); // Cast to access content directly
+ response = (HttpSearchResponse) searchHandler.handle(request); // Cast to access content directly
assertNotNull(response.getResult().hits().get("from:default"));
// Tests a profile setting hits and offset
request = HttpRequest.createTestRequest("search?queryProfile=hitsoffset", Method.GET);
- response = (HttpSearchResponse)searchHandler.handle(request); // Cast to access content directly
- assertEquals(22,response.getQuery().getHits());
- assertEquals(80,response.getQuery().getOffset());
+ response = (HttpSearchResponse) searchHandler.handle(request); // Cast to access content directly
+ assertEquals(22, response.getQuery().getHits());
+ assertEquals(80, response.getQuery().getOffset());
// Tests a non-resolved profile request
request = HttpRequest.createTestRequest("search?queryProfile=none", Method.GET);
- response = (HttpSearchResponse)searchHandler.handle(request); // Cast to access content directly
- assertNotNull("Got an error",response.getResult().hits().getError());
- assertEquals("Could not resolve query profile 'none'",response.getResult().hits().getError().getDetailedMessage());
+ response = (HttpSearchResponse) searchHandler.handle(request); // Cast to access content directly
+ assertNotNull(response.getResult().hits().getError(), "Got an error");
+ assertEquals("Could not resolve query profile 'none'", response.getResult().hits().getError().getDetailedMessage());
// Test overriding a sub-profile in the request
request = HttpRequest.createTestRequest("search?queryProfile=root&sub=newsub", Method.GET);
- response = (HttpSearchResponse)searchHandler.handle(request); // Cast to access content directly
- assertEquals("newsubvalue1",response.getQuery().properties().get("sub.value1"));
- assertEquals("newsubvalue2",response.getQuery().properties().get("sub.value2"));
+ response = (HttpSearchResponse) searchHandler.handle(request); // Cast to access content directly
+ assertEquals("newsubvalue1", response.getQuery().properties().get("sub.value1"));
+ assertEquals("newsubvalue2", response.getQuery().properties().get("sub.value2"));
configurer.shutdown();
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/config/test/TypedProfilesConfigurationTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/config/test/TypedProfilesConfigurationTestCase.java
index 944ee6d79ef..de46e6ee77c 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/config/test/TypedProfilesConfigurationTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/config/test/TypedProfilesConfigurationTestCase.java
@@ -4,11 +4,9 @@ package com.yahoo.search.query.profile.config.test;
import com.yahoo.search.query.profile.config.QueryProfileConfigurer;
import com.yahoo.search.query.profile.types.FieldDescription;
import com.yahoo.search.query.profile.types.QueryProfileType;
-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.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -17,7 +15,7 @@ public class TypedProfilesConfigurationTestCase {
/** Asserts that everything is read correctly from this configuration */
@Test
- public void testIt() {
+ void testIt() {
var registry = QueryProfileConfigurer.createFromConfigId("file:src/test/java/com/yahoo/search/query/profile/config/test/typed-profiles.cfg");
var types = registry.getTypeRegistry();
@@ -33,19 +31,19 @@ public class TypedProfilesConfigurationTestCase {
assertTrue(testType.getField("myString").isOverridable());
assertFalse(testType.getField("myInteger").isMandatory());
assertFalse(testType.getField("myInteger").isOverridable());
- FieldDescription field= testType.getField("myUserQueryProfile");
+ FieldDescription field = testType.getField("myUserQueryProfile");
assertEquals("reference to a query profile of type 'user'", field.getType().toInstanceDescription());
assertTrue(field.getAliases().contains("myqp"));
assertTrue(field.getAliases().contains("user-profile"));
- QueryProfileType testTypeStrict=types.getComponent("testtypestrict");
+ QueryProfileType testTypeStrict = types.getComponent("testtypestrict");
assertTrue(testTypeStrict.isStrict());
assertTrue(testTypeStrict.getMatchAsPath());
assertEquals(7, testTypeStrict.fields().size());
assertEquals("reference to a query profile of type 'userstrict'",
- testTypeStrict.getField("myUserQueryProfile").getType().toInstanceDescription());
+ testTypeStrict.getField("myUserQueryProfile").getType().toInstanceDescription());
- QueryProfileType user=types.getComponent("user");
+ QueryProfileType user = types.getComponent("user");
assertFalse(user.isStrict());
assertFalse(user.getMatchAsPath());
assertEquals(2, user.fields().size());
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/config/test/XmlReadingTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/config/test/XmlReadingTestCase.java
index 62bc89c8453..dcb41dc5e31 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/config/test/XmlReadingTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/config/test/XmlReadingTestCase.java
@@ -19,17 +19,13 @@ import com.yahoo.search.query.profile.compiled.CompiledQueryProfileRegistry;
import com.yahoo.search.query.profile.config.QueryProfileXMLReader;
import com.yahoo.search.query.profile.types.FieldDescription;
import com.yahoo.search.query.profile.types.QueryProfileType;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-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.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -37,7 +33,7 @@ import static org.junit.Assert.fail;
public class XmlReadingTestCase {
@Test
- public void testInheritance() {
+ void testInheritance() {
QueryProfileRegistry registry =
new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/inheritance");
@@ -48,7 +44,7 @@ public class XmlReadingTestCase {
}
@Test
- public void testValid() {
+ void testValid() {
QueryProfileRegistry registry =
new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/validxml");
CompiledQueryProfileRegistry cRegistry = registry.compile();
@@ -106,8 +102,8 @@ public class XmlReadingTestCase {
assertEquals(3, query.getTrace().getLevel());
QueryProfile someUser = registry.getComponent("someUser");
- assertEquals("5",someUser.get("sub.test"));
- assertEquals(18,someUser.get("age"));
+ assertEquals("5", someUser.get("sub.test"));
+ assertEquals(18, someUser.get("age"));
// aliases
assertEquals(18, someUser.get("alder"));
@@ -129,19 +125,19 @@ public class XmlReadingTestCase {
}
@Test
- public void testBasicsNoProfile() {
- Query q=new Query(HttpRequest.createTestRequest("?query=test", Method.GET));
- assertEquals("test",q.properties().get("query"));
- assertEquals("test",q.properties().get("QueRY"));
- assertEquals("test",q.properties().get("model.queryString"));
- assertEquals("test",q.getModel().getQueryString());
+ void testBasicsNoProfile() {
+ Query q = new Query(HttpRequest.createTestRequest("?query=test", Method.GET));
+ assertEquals("test", q.properties().get("query"));
+ assertEquals("test", q.properties().get("QueRY"));
+ assertEquals("test", q.properties().get("model.queryString"));
+ assertEquals("test", q.getModel().getQueryString());
}
@Test
- public void testBasicsWithProfile() {
+ void testBasicsWithProfile() {
QueryProfile p = new QueryProfile("default");
p.set("a", "foo", null);
- Query q=new Query(HttpRequest.createTestRequest("?query=test", Method.GET), p.compile(null));
+ Query q = new Query(HttpRequest.createTestRequest("?query=test", Method.GET), p.compile(null));
assertEquals("test", q.properties().get("query"));
assertEquals("test", q.properties().get("QueRY"));
assertEquals("test", q.properties().get("model.queryString"));
@@ -150,7 +146,7 @@ public class XmlReadingTestCase {
/** Tests a subset of the configuration in the system test of this */
@Test
- public void testSystemtest() {
+ void testSystemtest() {
String queryString = "?query=test";
QueryProfileXMLReader reader = new QueryProfileXMLReader();
@@ -170,7 +166,7 @@ public class XmlReadingTestCase {
assertEquals("le", p.get("subst.end"));
assertEquals("title", p.get("model.defaultIndex"));
- Map<String,Object> ps = p.listProperties();
+ Map<String, Object> ps = p.listProperties();
assertEquals("bar", ps.get("foo"));
assertEquals(5, ps.get("hits"));
assertEquals("tit", ps.get("subst"));
@@ -180,7 +176,7 @@ public class XmlReadingTestCase {
}
@Test
- public void testInvalid1() {
+ void testInvalid1() {
try {
new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/invalidxml1");
fail("Should have failed");
@@ -191,7 +187,7 @@ public class XmlReadingTestCase {
}
@Test
- public void testInvalid2() {
+ void testInvalid2() {
try {
new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/invalidxml2");
fail("Should have failed");
@@ -202,7 +198,7 @@ public class XmlReadingTestCase {
}
@Test
- public void testInvalid3() {
+ void testInvalid3() {
try {
new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/invalidxml3");
fail("Should have failed");
@@ -213,7 +209,7 @@ public class XmlReadingTestCase {
}
@Test
- public void testQueryProfileVariants() {
+ void testQueryProfileVariants() {
String query = "?query=test&dim1=yahoo&dim2=uk&dim3=test";
QueryProfileXMLReader reader = new QueryProfileXMLReader();
@@ -227,7 +223,7 @@ public class XmlReadingTestCase {
}
@Test
- public void testQueryProfileVariantsWithOverridableFalse() {
+ void testQueryProfileVariantsWithOverridableFalse() {
QueryProfileXMLReader reader = new QueryProfileXMLReader();
CompiledQueryProfileRegistry registry = reader.read("src/test/java/com/yahoo/search/query/profile/config/test/variants/").compile();
CompiledQueryProfile profile = registry.findQueryProfile("default");
@@ -240,156 +236,156 @@ public class XmlReadingTestCase {
}
@Test
- public void testNewsFE1() {
- CompiledQueryProfileRegistry registry=new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/newsfe").compile();
+ void testNewsFE1() {
+ CompiledQueryProfileRegistry registry = new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/newsfe").compile();
- String queryString="tiled?vertical=news&query=barack&intl=us&resulttypes=article&testid=&clientintl=us&SpellState=&rss=0&tracelevel=5";
+ String queryString = "tiled?vertical=news&query=barack&intl=us&resulttypes=article&testid=&clientintl=us&SpellState=&rss=0&tracelevel=5";
- Query query=new Query(HttpRequest.createTestRequest(queryString, Method.GET), registry.getComponent("default"));
- assertEquals("13",query.properties().listProperties().get("source.news.discovery.sources.count"));
- assertEquals("13",query.properties().get("source.news.discovery.sources.count"));
- assertEquals("sources",query.properties().listProperties().get("source.news.discovery"));
- assertEquals("sources",query.properties().get("source.news.discovery"));
+ Query query = new Query(HttpRequest.createTestRequest(queryString, Method.GET), registry.getComponent("default"));
+ assertEquals("13", query.properties().listProperties().get("source.news.discovery.sources.count"));
+ assertEquals("13", query.properties().get("source.news.discovery.sources.count"));
+ assertEquals("sources", query.properties().listProperties().get("source.news.discovery"));
+ assertEquals("sources", query.properties().get("source.news.discovery"));
}
@Test
- public void testQueryProfileVariants2() {
+ void testQueryProfileVariants2() {
CompiledQueryProfileRegistry registry = new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/queryprofilevariants2").compile();
CompiledQueryProfile multi = registry.getComponent("multi");
{
- Query query=new Query(HttpRequest.createTestRequest("?queryProfile=multi", Method.GET), multi);
+ Query query = new Query(HttpRequest.createTestRequest("?queryProfile=multi", Method.GET), multi);
query.validate();
- assertEquals("best",query.properties().get("model.queryString"));
- assertEquals("best",query.getModel().getQueryString());
+ assertEquals("best", query.properties().get("model.queryString"));
+ assertEquals("best", query.getModel().getQueryString());
}
{
- Query query=new Query(HttpRequest.createTestRequest("?queryProfile=multi&myindex=default", Method.GET), multi);
+ Query query = new Query(HttpRequest.createTestRequest("?queryProfile=multi&myindex=default", Method.GET), multi);
query.validate();
assertEquals("best", query.properties().get("model.queryString"));
assertEquals("best", query.getModel().getQueryString());
assertEquals("default", query.getModel().getDefaultIndex());
}
{
- Query query=new Query(HttpRequest.createTestRequest("?queryProfile=multi&myindex=default&myquery=love", Method.GET), multi);
+ Query query = new Query(HttpRequest.createTestRequest("?queryProfile=multi&myindex=default&myquery=love", Method.GET), multi);
query.validate();
assertEquals("love", query.properties().get("model.queryString"));
assertEquals("love", query.getModel().getQueryString());
assertEquals("default", query.getModel().getDefaultIndex());
}
{
- Query query=new Query(HttpRequest.createTestRequest("?model=querybest", Method.GET), multi);
+ Query query = new Query(HttpRequest.createTestRequest("?model=querybest", Method.GET), multi);
query.validate();
- assertEquals("best",query.getModel().getQueryString());
- assertEquals("title",query.properties().get("model.defaultIndex"));
- assertEquals("title",query.getModel().getDefaultIndex());
+ assertEquals("best", query.getModel().getQueryString());
+ assertEquals("title", query.properties().get("model.defaultIndex"));
+ assertEquals("title", query.getModel().getDefaultIndex());
}
}
@Test
- public void testKlee() {
- QueryProfileRegistry registry=
+ void testKlee() {
+ QueryProfileRegistry registry =
new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/klee");
- QueryProfile pv=registry.getComponent("twitter_dd-us:0.2.4");
- assertEquals("0.2.4",pv.getId().getVersion().toString());
- assertEquals("[query profile 'production']",pv.inherited().toString());
+ QueryProfile pv = registry.getComponent("twitter_dd-us:0.2.4");
+ assertEquals("0.2.4", pv.getId().getVersion().toString());
+ assertEquals("[query profile 'production']", pv.inherited().toString());
- QueryProfile p=registry.getComponent("twitter_dd-us:0.0.0");
- assertEquals("",p.getId().getVersion().toString()); // that is 0.0.0
- assertEquals("[query profile 'twitter_dd']",p.inherited().toString());
+ QueryProfile p = registry.getComponent("twitter_dd-us:0.0.0");
+ assertEquals("", p.getId().getVersion().toString()); // that is 0.0.0
+ assertEquals("[query profile 'twitter_dd']", p.inherited().toString());
}
@Test
- public void testVersions() {
- QueryProfileRegistry registry=
+ void testVersions() {
+ QueryProfileRegistry registry =
new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/versions");
registry.freeze();
- assertEquals("1.20.100",registry.findQueryProfile("testprofile:1.20.100").getId().getVersion().toString());
- assertEquals("1.20.100",registry.findQueryProfile("testprofile:1.20").getId().getVersion().toString());
- assertEquals("1.20.100",registry.findQueryProfile("testprofile:1").getId().getVersion().toString());
- assertEquals("1.20.100",registry.findQueryProfile("testprofile").getId().getVersion().toString());
+ assertEquals("1.20.100", registry.findQueryProfile("testprofile:1.20.100").getId().getVersion().toString());
+ assertEquals("1.20.100", registry.findQueryProfile("testprofile:1.20").getId().getVersion().toString());
+ assertEquals("1.20.100", registry.findQueryProfile("testprofile:1").getId().getVersion().toString());
+ assertEquals("1.20.100", registry.findQueryProfile("testprofile").getId().getVersion().toString());
}
@Test
- public void testNewsFE2() {
- CompiledQueryProfileRegistry registry=new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/newsfe2").compile();
+ void testNewsFE2() {
+ CompiledQueryProfileRegistry registry = new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/newsfe2").compile();
- String queryString="tiled?query=a&intl=tw&mode=adv&mode=adv";
+ String queryString = "tiled?query=a&intl=tw&mode=adv&mode=adv";
- Query query=new Query(HttpRequest.createTestRequest(queryString, Method.GET),registry.getComponent("default"));
- assertEquals("news_adv",query.properties().listProperties().get("provider"));
- assertEquals("news_adv",query.properties().get("provider"));
+ Query query = new Query(HttpRequest.createTestRequest(queryString, Method.GET), registry.getComponent("default"));
+ assertEquals("news_adv", query.properties().listProperties().get("provider"));
+ assertEquals("news_adv", query.properties().get("provider"));
}
@Test
- public void testSourceProvider() {
- CompiledQueryProfileRegistry registry=new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/sourceprovider").compile();
+ void testSourceProvider() {
+ CompiledQueryProfileRegistry registry = new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/sourceprovider").compile();
- String queryString="tiled?query=india&queryProfile=myprofile&source.common.intl=tw&source.common.mode=adv";
+ String queryString = "tiled?query=india&queryProfile=myprofile&source.common.intl=tw&source.common.mode=adv";
- Query query=new Query(HttpRequest.createTestRequest(queryString, Method.GET), registry.getComponent("myprofile"));
- assertEquals("news",query.properties().listProperties().get("source.common.provider"));
- assertEquals("news",query.properties().get("source.common.provider"));
+ Query query = new Query(HttpRequest.createTestRequest(queryString, Method.GET), registry.getComponent("myprofile"));
+ assertEquals("news", query.properties().listProperties().get("source.common.provider"));
+ assertEquals("news", query.properties().get("source.common.provider"));
}
@Test
- public void testNewsCase1() {
+ void testNewsCase1() {
CompiledQueryProfileRegistry registry = new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/newscase1").compile();
Query query;
query = new Query(HttpRequest.createTestRequest("?query=test&custid_1=parent", Method.GET),
- registry.getComponent("default"));
+ registry.getComponent("default"));
assertEquals(0.0, query.properties().get("ranking.features.b"));
assertEquals("0.0", query.properties().listProperties().get("ranking.features.b"));
query = new Query(HttpRequest.createTestRequest("?query=test&custid_1=parent&custid_2=child", Method.GET),
- registry.getComponent("default"));
+ registry.getComponent("default"));
assertEquals(0.1, query.properties().get("ranking.features.b"));
assertEquals("0.1", query.properties().listProperties().get("ranking.features.b"));
}
@Test
- public void testNewsCase2() {
+ void testNewsCase2() {
CompiledQueryProfileRegistry registry = new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/newscase2").compile();
Query query;
query = new Query(HttpRequest.createTestRequest("?query=test&custid_1=parent", Method.GET),
- registry.getComponent("default"));
+ registry.getComponent("default"));
assertEquals("0.0", query.properties().get("a.features.b"));
assertEquals("0.0", query.properties().listProperties().get("a.features.b"));
query = new Query(HttpRequest.createTestRequest("?query=test&custid_1=parent&custid_2=child", Method.GET),
- registry.getComponent("default"));
+ registry.getComponent("default"));
assertEquals("0.1", query.properties().get("a.features.b"));
assertEquals("0.1", query.properties().listProperties().get("a.features.b"));
}
@Test
- public void testNewsCase3() {
+ void testNewsCase3() {
CompiledQueryProfileRegistry registry = new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/newscase3").compile();
Query query = new Query(HttpRequest.createTestRequest("?query=test&custid_1=parent", Method.GET),
- registry.getComponent("default"));
- assertEquals("0.0",query.properties().get("a.features"));
+ registry.getComponent("default"));
+ assertEquals("0.0", query.properties().get("a.features"));
query = new Query(HttpRequest.createTestRequest("?query=test&custid_1=parent&custid_2=child", Method.GET),
- registry.getComponent("default"));
- assertEquals("0.1",query.properties().get("a.features"));
+ registry.getComponent("default"));
+ assertEquals("0.1", query.properties().get("a.features"));
}
@Test
- public void testNewsCase4() {
+ void testNewsCase4() {
CompiledQueryProfileRegistry registry = new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/newscase4").compile();
Query query = new Query(HttpRequest.createTestRequest("?query=test&custid_1=parent", Method.GET),
- registry.getComponent("default"));
+ registry.getComponent("default"));
assertEquals(0.0, query.properties().get("ranking.features.foo"));
query = new Query(HttpRequest.createTestRequest("?query=test&custid_1=parent&custid_2=child", Method.GET),
- registry.getComponent("default"));
+ registry.getComponent("default"));
assertEquals(0.1, query.properties().get("ranking.features.foo"));
}
@Test
- public void testVersionRefs() {
+ void testVersionRefs() {
CompiledQueryProfileRegistry registry = new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/versionrefs").compile();
Query query = new Query(HttpRequest.createTestRequest("?query=test", Method.GET), registry.getComponent("default"));
@@ -397,14 +393,14 @@ public class XmlReadingTestCase {
}
@Test
- public void testRefOverride() {
+ void testRefOverride() {
CompiledQueryProfileRegistry registry = new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/refoverride").compile();
{
// Original reference
Query query = new Query(HttpRequest.createTestRequest("?query=test", Method.GET),
- registry.getComponent("default"));
- assertEquals(null, query.properties().get("profileRef"));
+ registry.getComponent("default"));
+ assertNull(query.properties().get("profileRef"));
assertEquals("MyProfile1", query.properties().get("profileRef.name"));
assertEquals("myProfile1Only", query.properties().get("profileRef.myProfile1Only"));
assertNull(query.properties().get("profileRef.myProfile2Only"));
@@ -412,8 +408,8 @@ public class XmlReadingTestCase {
{
// Overridden reference
- Query query = new Query(HttpRequest.createTestRequest("?query=test&profileRef=ref:MyProfile2", Method.GET),registry.getComponent("default"));
- assertEquals(null,query.properties().get("profileRef"));
+ Query query = new Query(HttpRequest.createTestRequest("?query=test&profileRef=ref:MyProfile2", Method.GET), registry.getComponent("default"));
+ assertNull(query.properties().get("profileRef"));
assertEquals("MyProfile2", query.properties().get("profileRef.name"));
assertEquals("myProfile2Only", query.properties().get("profileRef.myProfile2Only"));
assertNull(query.properties().get("profileRef.myProfile1Only"));
@@ -423,20 +419,20 @@ public class XmlReadingTestCase {
assertEquals("newName", query.properties().get("profileRef.name"));
// ...will not impact others
query = new Query(HttpRequest.createTestRequest("?query=test&profileRef=ref:MyProfile2", Method.GET),
- registry.getComponent("default"));
+ registry.getComponent("default"));
assertEquals("MyProfile2", query.properties().get("profileRef.name"));
}
}
@Test
- public void testRefOverrideTyped() {
+ void testRefOverrideTyped() {
CompiledQueryProfileRegistry registry = new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/refoverridetyped").compile();
{
// Original reference
Query query = new Query(HttpRequest.createTestRequest("?query=test", Method.GET), registry.getComponent("default"));
- assertEquals(null, query.properties().get("profileRef"));
+ assertNull(query.properties().get("profileRef"));
assertEquals("MyProfile1", query.properties().get("profileRef.name"));
assertEquals("myProfile1Only", query.properties().get("profileRef.myProfile1Only"));
assertNull(query.properties().get("profileRef.myProfile2Only"));
@@ -445,7 +441,7 @@ public class XmlReadingTestCase {
{
// Overridden reference
Query query = new Query(HttpRequest.createTestRequest("?query=test&profileRef=MyProfile2", Method.GET), registry.getComponent("default"));
- assertEquals(null, query.properties().get("profileRef"));
+ assertNull(query.properties().get("profileRef"));
assertEquals("MyProfile2", query.properties().get("profileRef.name"));
assertEquals("myProfile2Only", query.properties().get("profileRef.myProfile2Only"));
assertNull(query.properties().get("profileRef.myProfile1Only"));
@@ -461,7 +457,7 @@ public class XmlReadingTestCase {
}
@Test
- public void testAnonymousIdsAreStableBetweenImports() {
+ void testAnonymousIdsAreStableBetweenImports() {
QueryProfileRegistry registry1 = new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/typedinheritance");
var childIn1 = registry1.findQueryProfile("child");
var childTypeIn1 = registry1.getType("childType");
@@ -470,50 +466,50 @@ public class XmlReadingTestCase {
var childIn2 = registry2.findQueryProfile("child");
var childTypeIn2 = registry2.getType("childType");
- assertEquals(((QueryProfile)childIn1.lookup("a", Map.of())).getId().stringValue(),
- ((QueryProfile)childIn2.lookup("a", Map.of())).getId().stringValue());
+ assertEquals(((QueryProfile) childIn1.lookup("a", Map.of())).getId().stringValue(),
+ ((QueryProfile) childIn2.lookup("a", Map.of())).getId().stringValue());
assertEquals(childTypeIn1.getType("a").getId().stringValue(),
- childTypeIn2.getType("a").getId().stringValue());
+ childTypeIn2.getType("a").getId().stringValue());
}
@Test
- public void testTensorTypes() {
+ void testTensorTypes() {
CompiledQueryProfileRegistry registry = new QueryProfileXMLReader().read("src/test/java/com/yahoo/search/query/profile/config/test/tensortypes").compile();
QueryProfileType type1 = registry.getTypeRegistry().getComponent("type1");
assertEquals(TensorType.fromSpec("tensor<float>(x[1])"),
- type1.getFieldType(new CompoundName("ranking.features.query(tensor_1)")).asTensorType());
+ type1.getFieldType(new CompoundName("ranking.features.query(tensor_1)")).asTensorType());
assertNull(type1.getFieldType(new CompoundName("ranking.features.query(tensor_2)")));
assertNull(type1.getFieldType(new CompoundName("ranking.features.query(tensor_3)")));
assertEquals(TensorType.fromSpec("tensor(key{})"),
- type1.getFieldType(new CompoundName("ranking.features.query(tensor_4)")).asTensorType());
+ type1.getFieldType(new CompoundName("ranking.features.query(tensor_4)")).asTensorType());
QueryProfileType type2 = registry.getTypeRegistry().getComponent("type2");
assertNull(type2.getFieldType(new CompoundName("ranking.features.query(tensor_1)")));
assertEquals(TensorType.fromSpec("tensor<float>(x[2])"),
- type2.getFieldType(new CompoundName("ranking.features.query(tensor_2)")).asTensorType());
+ type2.getFieldType(new CompoundName("ranking.features.query(tensor_2)")).asTensorType());
assertEquals(TensorType.fromSpec("tensor<float>(x[3])"),
- type2.getFieldType(new CompoundName("ranking.features.query(tensor_3)")).asTensorType());
+ type2.getFieldType(new CompoundName("ranking.features.query(tensor_3)")).asTensorType());
Query queryProfile1 = new Query.Builder().setQueryProfile(registry.getComponent("profile1"))
- .setRequest("?query=test&ranking.features.query(tensor_1)=[1.200]")
- .build();
- assertEquals("tensor_1 received as a tensor tensor",
- Tensor.from("tensor<float>(x[1]):[1.2]"),
- queryProfile1.properties().get("ranking.features.query(tensor_1)"));
- assertEquals("tensor_4 contained in the profile is a tensor",
- Tensor.from("tensor(key{}):{pre_key1_post:1.0}"),
- queryProfile1.properties().get("ranking.features.query(tensor_4)"));
+ .setRequest("?query=test&ranking.features.query(tensor_1)=[1.200]")
+ .build();
+ assertEquals(Tensor.from("tensor<float>(x[1]):[1.2]"),
+ queryProfile1.properties().get("ranking.features.query(tensor_1)"),
+ "tensor_1 received as a tensor tensor");
+ assertEquals(Tensor.from("tensor(key{}):{pre_key1_post:1.0}"),
+ queryProfile1.properties().get("ranking.features.query(tensor_4)"),
+ "tensor_4 contained in the profile is a tensor");
Query queryProfile2 = new Query.Builder().setQueryProfile(registry.getComponent("profile2"))
- .setEmbedder(new MockEmbedder("text-to-embed",
- Tensor.from("tensor(x[3]):[1, 2, 3]")))
- .setRequest("?query=test&ranking.features.query(tensor_1)=[1.200]")
- .build();
- assertEquals("tensor_1 received as a string as it is not in type2",
- "[1.200]",
- queryProfile2.properties().get("ranking.features.query(tensor_1)"));
+ .setEmbedder(new MockEmbedder("text-to-embed",
+ Tensor.from("tensor(x[3]):[1, 2, 3]")))
+ .setRequest("?query=test&ranking.features.query(tensor_1)=[1.200]")
+ .build();
+ assertEquals("[1.200]",
+ queryProfile2.properties().get("ranking.features.query(tensor_1)"),
+ "tensor_1 received as a string as it is not in type2");
//assertEquals(Tensor.from("tensor(x[3]):[1, 2, 3]"),
// queryProfile2.properties().get("ranking.features.query(tensor_3)"));
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/test/CloningTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/test/CloningTestCase.java
index 433b87363b3..437d5e3b943 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/test/CloningTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/test/CloningTestCase.java
@@ -6,9 +6,9 @@ import com.yahoo.search.Query;
import com.yahoo.search.query.profile.QueryProfile;
import com.yahoo.search.query.profile.QueryProfileRegistry;
import com.yahoo.jdisc.http.HttpRequest.Method;
-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 bratseth
@@ -16,185 +16,185 @@ import static org.junit.Assert.assertEquals;
public class CloningTestCase {
@Test
- public void testCloningWithVariants() {
+ void testCloningWithVariants() {
QueryProfile test = new QueryProfile("test");
- test.setDimensions(new String[] {"x"} );
+ test.setDimensions(new String[]{"x"});
test.freeze();
Query q1 = new Query(HttpRequest.createTestRequest("?query=q&x=x1", Method.GET), test.compile(null));
- q1.properties().set("a","a1");
+ q1.properties().set("a", "a1");
Query q2 = q1.clone();
- q2.properties().set("a","a2");
- assertEquals("a1",q1.properties().get("a"));
- assertEquals("a2",q2.properties().get("a"));
+ q2.properties().set("a", "a2");
+ assertEquals("a1", q1.properties().get("a"));
+ assertEquals("a2", q2.properties().get("a"));
}
@Test
- public void testShallowCloning() {
+ void testShallowCloning() {
QueryProfile test = new QueryProfile("test");
test.freeze();
Query q1 = new Query(HttpRequest.createTestRequest("?query=q", Method.GET), test.compile(null));
- q1.properties().set("a",new MutableString("a1"));
+ q1.properties().set("a", new MutableString("a1"));
Query q2 = q1.clone();
- ((MutableString)q2.properties().get("a")).set("a2");
- assertEquals("a2",q1.properties().get("a").toString());
- assertEquals("a2",q2.properties().get("a").toString());
+ ((MutableString) q2.properties().get("a")).set("a2");
+ assertEquals("a2", q1.properties().get("a").toString());
+ assertEquals("a2", q2.properties().get("a").toString());
}
@Test
- public void testShallowCloningWithVariants() {
+ void testShallowCloningWithVariants() {
QueryProfile test = new QueryProfile("test");
- test.setDimensions(new String[] {"x"} );
+ test.setDimensions(new String[]{"x"});
test.freeze();
Query q1 = new Query(HttpRequest.createTestRequest("?query=q&x=x1", Method.GET), test.compile(null));
- q1.properties().set("a",new MutableString("a1"));
+ q1.properties().set("a", new MutableString("a1"));
Query q2 = q1.clone();
- ((MutableString)q2.properties().get("a")).set("a2");
- assertEquals("a2",q1.properties().get("a").toString());
- assertEquals("a2",q2.properties().get("a").toString());
+ ((MutableString) q2.properties().get("a")).set("a2");
+ assertEquals("a2", q1.properties().get("a").toString());
+ assertEquals("a2", q2.properties().get("a").toString());
}
@Test
- public void testDeepCloning() {
- QueryProfile test=new QueryProfile("test");
+ void testDeepCloning() {
+ QueryProfile test = new QueryProfile("test");
test.freeze();
Query q1 = new Query(HttpRequest.createTestRequest("?query=q", Method.GET), test.compile(null));
- q1.properties().set("a",new CloneableMutableString("a1"));
- Query q2=q1.clone();
- ((MutableString)q2.properties().get("a")).set("a2");
- assertEquals("a1",q1.properties().get("a").toString());
- assertEquals("a2",q2.properties().get("a").toString());
+ q1.properties().set("a", new CloneableMutableString("a1"));
+ Query q2 = q1.clone();
+ ((MutableString) q2.properties().get("a")).set("a2");
+ assertEquals("a1", q1.properties().get("a").toString());
+ assertEquals("a2", q2.properties().get("a").toString());
}
@Test
- public void testDeepCloningWithVariants() {
- QueryProfile test=new QueryProfile("test");
- test.setDimensions(new String[] {"x"} );
+ void testDeepCloningWithVariants() {
+ QueryProfile test = new QueryProfile("test");
+ test.setDimensions(new String[]{"x"});
test.freeze();
Query q1 = new Query(HttpRequest.createTestRequest("?query=q&x=x1", Method.GET), test.compile(null));
- q1.properties().set("a",new CloneableMutableString("a1"));
- Query q2=q1.clone();
- ((MutableString)q2.properties().get("a")).set("a2");
- assertEquals("a1",q1.properties().get("a").toString());
- assertEquals("a2",q2.properties().get("a").toString());
+ q1.properties().set("a", new CloneableMutableString("a1"));
+ Query q2 = q1.clone();
+ ((MutableString) q2.properties().get("a")).set("a2");
+ assertEquals("a1", q1.properties().get("a").toString());
+ assertEquals("a2", q2.properties().get("a").toString());
}
@Test
- public void testReAssignment() {
- QueryProfile test=new QueryProfile("test");
- test.setDimensions(new String[] {"x"} );
+ void testReAssignment() {
+ QueryProfile test = new QueryProfile("test");
+ test.setDimensions(new String[]{"x"});
test.freeze();
Query q1 = new Query(HttpRequest.createTestRequest("?query=q&x=x1", Method.GET), test.compile(null));
- q1.properties().set("a","a1");
- q1.properties().set("a","a2");
- assertEquals("a2",q1.properties().get("a"));
+ q1.properties().set("a", "a1");
+ q1.properties().set("a", "a2");
+ assertEquals("a2", q1.properties().get("a"));
}
@Test
- public void testThreeLevelsOfCloning() {
+ void testThreeLevelsOfCloning() {
QueryProfile test = new QueryProfile("test");
- test.set("a", "config-a", (QueryProfileRegistry)null);
+ test.set("a", "config-a", (QueryProfileRegistry) null);
test.freeze();
Query q1 = new Query(HttpRequest.createTestRequest("?query=q", Method.GET), test.compile(null));
- q1.properties().set("a","q1-a");
- Query q2=q1.clone();
- q2.properties().set("a","q2-a");
- Query q31=q2.clone();
- q31.properties().set("a","q31-a");
- Query q32=q2.clone();
- q32.properties().set("a","q32-a");
-
- assertEquals("q1-a",q1.properties().get("a").toString());
- assertEquals("q2-a",q2.properties().get("a").toString());
- assertEquals("q31-a",q31.properties().get("a").toString());
- assertEquals("q32-a",q32.properties().get("a").toString());
- q2.properties().set("a","q2-a-2");
- assertEquals("q1-a",q1.properties().get("a").toString());
- assertEquals("q2-a-2",q2.properties().get("a").toString());
- assertEquals("q31-a",q31.properties().get("a").toString());
- assertEquals("q32-a",q32.properties().get("a").toString());
+ q1.properties().set("a", "q1-a");
+ Query q2 = q1.clone();
+ q2.properties().set("a", "q2-a");
+ Query q31 = q2.clone();
+ q31.properties().set("a", "q31-a");
+ Query q32 = q2.clone();
+ q32.properties().set("a", "q32-a");
+
+ assertEquals("q1-a", q1.properties().get("a").toString());
+ assertEquals("q2-a", q2.properties().get("a").toString());
+ assertEquals("q31-a", q31.properties().get("a").toString());
+ assertEquals("q32-a", q32.properties().get("a").toString());
+ q2.properties().set("a", "q2-a-2");
+ assertEquals("q1-a", q1.properties().get("a").toString());
+ assertEquals("q2-a-2", q2.properties().get("a").toString());
+ assertEquals("q31-a", q31.properties().get("a").toString());
+ assertEquals("q32-a", q32.properties().get("a").toString());
}
@Test
- public void testThreeLevelsOfCloningReverseSetOrder() {
+ void testThreeLevelsOfCloningReverseSetOrder() {
QueryProfile test = new QueryProfile("test");
- test.set("a", "config-a", (QueryProfileRegistry)null);
+ test.set("a", "config-a", (QueryProfileRegistry) null);
test.freeze();
Query q1 = new Query(HttpRequest.createTestRequest("?query=q", Method.GET), test.compile(null));
- Query q2=q1.clone();
- Query q31=q2.clone();
- Query q32=q2.clone();
- q32.properties().set("a","q32-a");
- q31.properties().set("a","q31-a");
- q2.properties().set("a","q2-a");
- q1.properties().set("a","q1-a");
-
- assertEquals("q1-a",q1.properties().get("a").toString());
- assertEquals("q2-a",q2.properties().get("a").toString());
- assertEquals("q31-a",q31.properties().get("a").toString());
- assertEquals("q32-a",q32.properties().get("a").toString());
- q2.properties().set("a","q2-a-2");
- assertEquals("q1-a",q1.properties().get("a").toString());
- assertEquals("q2-a-2",q2.properties().get("a").toString());
- assertEquals("q31-a",q31.properties().get("a").toString());
- assertEquals("q32-a",q32.properties().get("a").toString());
+ Query q2 = q1.clone();
+ Query q31 = q2.clone();
+ Query q32 = q2.clone();
+ q32.properties().set("a", "q32-a");
+ q31.properties().set("a", "q31-a");
+ q2.properties().set("a", "q2-a");
+ q1.properties().set("a", "q1-a");
+
+ assertEquals("q1-a", q1.properties().get("a").toString());
+ assertEquals("q2-a", q2.properties().get("a").toString());
+ assertEquals("q31-a", q31.properties().get("a").toString());
+ assertEquals("q32-a", q32.properties().get("a").toString());
+ q2.properties().set("a", "q2-a-2");
+ assertEquals("q1-a", q1.properties().get("a").toString());
+ assertEquals("q2-a-2", q2.properties().get("a").toString());
+ assertEquals("q31-a", q31.properties().get("a").toString());
+ assertEquals("q32-a", q32.properties().get("a").toString());
}
@Test
- public void testThreeLevelsOfCloningMiddleFirstSetOrder1() {
+ void testThreeLevelsOfCloningMiddleFirstSetOrder1() {
QueryProfile test = new QueryProfile("test");
- test.set("a", "config-a", (QueryProfileRegistry)null);
+ test.set("a", "config-a", (QueryProfileRegistry) null);
test.freeze();
Query q1 = new Query(HttpRequest.createTestRequest("?query=q", Method.GET), test.compile(null));
- Query q2=q1.clone();
- Query q31=q2.clone();
- Query q32=q2.clone();
- q2.properties().set("a","q2-a");
- q32.properties().set("a","q32-a");
- q31.properties().set("a","q31-a");
- q1.properties().set("a","q1-a");
-
- assertEquals("q1-a",q1.properties().get("a").toString());
- assertEquals("q2-a",q2.properties().get("a").toString());
- assertEquals("q31-a",q31.properties().get("a").toString());
- assertEquals("q32-a",q32.properties().get("a").toString());
- q2.properties().set("a","q2-a-2");
- assertEquals("q1-a",q1.properties().get("a").toString());
- assertEquals("q2-a-2",q2.properties().get("a").toString());
- assertEquals("q31-a",q31.properties().get("a").toString());
- assertEquals("q32-a",q32.properties().get("a").toString());
+ Query q2 = q1.clone();
+ Query q31 = q2.clone();
+ Query q32 = q2.clone();
+ q2.properties().set("a", "q2-a");
+ q32.properties().set("a", "q32-a");
+ q31.properties().set("a", "q31-a");
+ q1.properties().set("a", "q1-a");
+
+ assertEquals("q1-a", q1.properties().get("a").toString());
+ assertEquals("q2-a", q2.properties().get("a").toString());
+ assertEquals("q31-a", q31.properties().get("a").toString());
+ assertEquals("q32-a", q32.properties().get("a").toString());
+ q2.properties().set("a", "q2-a-2");
+ assertEquals("q1-a", q1.properties().get("a").toString());
+ assertEquals("q2-a-2", q2.properties().get("a").toString());
+ assertEquals("q31-a", q31.properties().get("a").toString());
+ assertEquals("q32-a", q32.properties().get("a").toString());
}
@Test
- public void testThreeLevelsOfCloningMiddleFirstSetOrder2() {
+ void testThreeLevelsOfCloningMiddleFirstSetOrder2() {
QueryProfile test = new QueryProfile("test");
- test.set("a", "config-a", (QueryProfileRegistry)null);
+ test.set("a", "config-a", (QueryProfileRegistry) null);
test.freeze();
Query q1 = new Query(HttpRequest.createTestRequest("?query=q", Method.GET), test.compile(null));
- Query q2=q1.clone();
- Query q31=q2.clone();
- Query q32=q2.clone();
- q2.properties().set("a","q2-a");
- q31.properties().set("a","q31-a");
- q1.properties().set("a","q1-a");
-
- assertEquals("q1-a",q1.properties().get("a").toString());
- assertEquals("q2-a",q2.properties().get("a").toString());
- assertEquals("q31-a",q31.properties().get("a").toString());
- assertEquals("config-a",q32.properties().get("a").toString());
- q1.properties().set("a","q1-a-2");
- assertEquals("q1-a-2",q1.properties().get("a").toString());
- assertEquals("q2-a",q2.properties().get("a").toString());
- assertEquals("q31-a",q31.properties().get("a").toString());
- assertEquals("config-a",q32.properties().get("a").toString());
- q2.properties().set("a","q2-a-2");
- assertEquals("q1-a-2",q1.properties().get("a").toString());
- assertEquals("q2-a-2",q2.properties().get("a").toString());
- assertEquals("q31-a",q31.properties().get("a").toString());
- assertEquals("config-a",q32.properties().get("a").toString());
+ Query q2 = q1.clone();
+ Query q31 = q2.clone();
+ Query q32 = q2.clone();
+ q2.properties().set("a", "q2-a");
+ q31.properties().set("a", "q31-a");
+ q1.properties().set("a", "q1-a");
+
+ assertEquals("q1-a", q1.properties().get("a").toString());
+ assertEquals("q2-a", q2.properties().get("a").toString());
+ assertEquals("q31-a", q31.properties().get("a").toString());
+ assertEquals("config-a", q32.properties().get("a").toString());
+ q1.properties().set("a", "q1-a-2");
+ assertEquals("q1-a-2", q1.properties().get("a").toString());
+ assertEquals("q2-a", q2.properties().get("a").toString());
+ assertEquals("q31-a", q31.properties().get("a").toString());
+ assertEquals("config-a", q32.properties().get("a").toString());
+ q2.properties().set("a", "q2-a-2");
+ assertEquals("q1-a-2", q1.properties().get("a").toString());
+ assertEquals("q2-a-2", q2.properties().get("a").toString());
+ assertEquals("q31-a", q31.properties().get("a").toString());
+ assertEquals("config-a", q32.properties().get("a").toString());
}
public static class MutableString {
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/test/DimensionBindingTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/test/DimensionBindingTestCase.java
index 0fca7a566e2..62ed8413d92 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/test/DimensionBindingTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/test/DimensionBindingTestCase.java
@@ -2,14 +2,14 @@
package com.yahoo.search.query.profile.test;
import com.yahoo.search.query.profile.DimensionBinding;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bratseth
@@ -17,47 +17,47 @@ import static org.junit.Assert.*;
public class DimensionBindingTestCase {
@Test
- public void testCombining() {
+ void testCombining() {
assertEquals(binding("a, b, c", "a=1", "b=1", "c=1"),
- binding("a, b", "a=1", "b=1").combineWith(binding("c", "c=1")));
+ binding("a, b", "a=1", "b=1").combineWith(binding("c", "c=1")));
assertEquals(binding("a, b, c", "a=1", "b=1", "c=1"),
- binding("a, b", "a=1", "b=1").combineWith(binding("a, c", "a=1", "c=1")));
+ binding("a, b", "a=1", "b=1").combineWith(binding("a, c", "a=1", "c=1")));
assertEquals(binding("c, a, b", "c=1", "a=1", "b=1"),
- binding("a, b", "a=1", "b=1").combineWith(binding("c, a", "a=1", "c=1")));
+ binding("a, b", "a=1", "b=1").combineWith(binding("c, a", "a=1", "c=1")));
assertEquals(binding("a, b", "a=1", "b=1"),
- binding("a, b", "a=1", "b=1").combineWith(binding("a, b", "a=1", "b=1")));
+ binding("a, b", "a=1", "b=1").combineWith(binding("a, b", "a=1", "b=1")));
assertEquals(DimensionBinding.invalidBinding,
- binding("a, b", "a=1", "b=1").combineWith(binding("b, a", "a=1", "b=1")));
+ binding("a, b", "a=1", "b=1").combineWith(binding("b, a", "a=1", "b=1")));
assertEquals(binding("a, b", "a=1", "b=1"),
- binding("a, b", "a=1", "b=1").combineWith(binding("b", "b=1")));
+ binding("a, b", "a=1", "b=1").combineWith(binding("b", "b=1")));
assertEquals(binding("a, b, c", "a=1", "b=1", "c=1"),
- binding("a, b, c", "a=1", "c=1").combineWith(binding("a, b, c", "a=1", "b=1", "c=1")));
+ binding("a, b, c", "a=1", "c=1").combineWith(binding("a, b, c", "a=1", "b=1", "c=1")));
assertEquals(binding("a, b, c", "a=1", "b=1", "c=1"),
- binding("a, c", "a=1", "c=1").combineWith(binding("a, b, c", "a=1", "b=1", "c=1")));
+ binding("a, c", "a=1", "c=1").combineWith(binding("a, b, c", "a=1", "b=1", "c=1")));
}
// found DimensionBinding [custid_1=yahoo, custid_2=ca, custid_3=sc, custid_4=null, custid_5=null, custid_6=null], combined with DimensionBinding [custid_1=yahoo, custid_2=null, custid_3=sc, custid_4=null, custid_5=null, custid_6=null] to Invalid DimensionBinding
@Test
- public void testCombiningBindingsWithNull() {
+ void testCombiningBindingsWithNull() {
List<String> dimensions = list("a,b");
Map<String, String> map1 = new HashMap<>();
- map1.put("a","a1");
- map1.put("b","b1");
+ map1.put("a", "a1");
+ map1.put("b", "b1");
Map<String, String> map2 = new HashMap<>();
- map2.put("a","a1");
- map2.put("b",null);
+ map2.put("a", "a1");
+ map2.put("b", null);
assertEquals(DimensionBinding.createFrom(dimensions, map1),
- DimensionBinding.createFrom(dimensions, map1).combineWith(DimensionBinding.createFrom(dimensions, map2)));
+ DimensionBinding.createFrom(dimensions, map1).combineWith(DimensionBinding.createFrom(dimensions, map2)));
}
private DimensionBinding binding(String dimensions, String ... dimensionPoints) {
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/test/DumpToolTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/test/DumpToolTestCase.java
index 3ed044601f0..00e48a639c1 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/test/DumpToolTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/test/DumpToolTestCase.java
@@ -2,9 +2,9 @@
package com.yahoo.search.query.profile.test;
import com.yahoo.search.query.profile.DumpTool;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author bratseth
@@ -14,28 +14,28 @@ public class DumpToolTestCase {
private final String profileDir = "src/test/java/com/yahoo/search/query/profile/config/test/multiprofile";
@Test
- public void testNoParameters() {
+ void testNoParameters() {
assertTrue(new DumpTool().resolveAndDump().startsWith("Dumps all resolved"));
}
@Test
- public void testHelpParameter() {
+ void testHelpParameter() {
assertTrue(new DumpTool().resolveAndDump("-help").startsWith("Dumps all resolved"));
}
@Test
- public void testNoDimensionValues() {
+ void testNoDimensionValues() {
System.out.println(new DumpTool().resolveAndDump("multiprofile1", profileDir));
assertTrue(new DumpTool().resolveAndDump("multiprofile1", profileDir).contains("a=general-a\n"));
}
@Test
- public void testAllParametersSet() {
+ void testAllParametersSet() {
assertTrue(new DumpTool().resolveAndDump("multiprofile1", profileDir, "").contains("a=general-a\n"));
}
@Test
- public void testVariant() {
+ void testVariant() {
String result = new DumpTool().resolveAndDump("multiprofile1", profileDir, "region=us");
assertTrue(result.contains("a=us-a"));
assertTrue(result.contains("b=us-b"));
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryFromProfileTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryFromProfileTestCase.java
index 7a92aa8081b..6a9896188f9 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryFromProfileTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryFromProfileTestCase.java
@@ -8,9 +8,9 @@ import com.yahoo.search.Query;
import com.yahoo.search.query.profile.QueryProfileRegistry;
import com.yahoo.search.query.profile.compiled.CompiledQueryProfileRegistry;
import com.yahoo.search.query.profile.types.QueryProfileType;
-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 using the profile to set the query to execute
@@ -20,7 +20,7 @@ import static org.junit.Assert.assertEquals;
public class QueryFromProfileTestCase {
@Test
- public void testQueryFromProfile1() {
+ void testQueryFromProfile1() {
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfile topLevel = new QueryProfile("topLevel");
topLevel.setType(registry.getTypeRegistry().getComponent("native"));
@@ -39,7 +39,7 @@ public class QueryFromProfileTestCase {
}
@Test
- public void testQueryFromProfile2() {
+ void testQueryFromProfile2() {
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfileType rootType = new QueryProfileType("root");
rootType.inherited().add(registry.getTypeRegistry().getComponent("native"));
@@ -49,7 +49,7 @@ public class QueryFromProfileTestCase {
root.setType(rootType);
registry.register(root);
- QueryProfile queryBest=new QueryProfile("querybest");
+ QueryProfile queryBest = new QueryProfile("querybest");
queryBest.setType(registry.getTypeRegistry().getComponent("model"));
queryBest.set("queryString", "best", registry);
registry.register(queryBest);
@@ -62,7 +62,7 @@ public class QueryFromProfileTestCase {
}
@Test
- public void testQueryFromProfile3() {
+ void testQueryFromProfile3() {
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfileType rootType = new QueryProfileType("root");
rootType.inherited().add(registry.getTypeRegistry().getComponent("native"));
@@ -72,7 +72,7 @@ public class QueryFromProfileTestCase {
root.setType(rootType);
registry.register(root);
- QueryProfile queryBest=new QueryProfile("querybest");
+ QueryProfile queryBest = new QueryProfile("querybest");
queryBest.setType(registry.getTypeRegistry().getComponent("model"));
queryBest.set("queryString", "best", registry);
registry.register(queryBest);
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileSubstitutionTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileSubstitutionTestCase.java
index 2173d72cab9..9c162df02bf 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileSubstitutionTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileSubstitutionTestCase.java
@@ -6,10 +6,10 @@ import com.yahoo.yolean.Exceptions;
import com.yahoo.search.query.profile.QueryProfile;
import com.yahoo.search.query.profile.QueryProfileProperties;
import com.yahoo.search.query.profile.compiled.CompiledQueryProfile;
-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
@@ -17,17 +17,17 @@ import static org.junit.Assert.fail;
public class QueryProfileSubstitutionTestCase {
@Test
- public void testSubstitutionOnly() {
+ void testSubstitutionOnly() {
QueryProfile p = new QueryProfile("test");
- p.set("message","%{world}", null);
+ p.set("message", "%{world}", null);
p.set("world", "world", null);
assertEquals("world", p.compile(null).get("message"));
}
@Test
- public void testSingleSubstitution() {
+ void testSingleSubstitution() {
QueryProfile p = new QueryProfile("test");
- p.set("message","Hello %{world}!", null);
+ p.set("message", "Hello %{world}!", null);
p.set("world", "world", null);
assertEquals("Hello world!", p.compile(null).get("message"));
@@ -38,15 +38,15 @@ public class QueryProfileSubstitutionTestCase {
}
@Test
- public void testRelativeSubstitution() {
+ void testRelativeSubstitution() {
QueryProfile p = new QueryProfile("test");
- p.set("message","Hello %{.world}!", null);
+ p.set("message", "Hello %{.world}!", null);
p.set("world", "world", null);
assertEquals("Hello world!", p.compile(null).get("message"));
}
@Test
- public void testRelativeSubstitutionNotFound() {
+ void testRelativeSubstitutionNotFound() {
try {
QueryProfile p = new QueryProfile("test");
p.set("message", "Hello %{.world}!", null);
@@ -55,80 +55,80 @@ public class QueryProfileSubstitutionTestCase {
}
catch (IllegalArgumentException e) {
assertEquals("Invalid query profile 'test': Could not resolve local substitution 'world' in variant []",
- Exceptions.toMessageString(e));
+ Exceptions.toMessageString(e));
}
}
@Test
- public void testMultipleSubstitutions() {
+ void testMultipleSubstitutions() {
QueryProfile p = new QueryProfile("test");
- p.set("message","%{greeting} %{entity}%{exclamation}", null);
- p.set("greeting","Hola", null);
- p.set("entity","local group", null);
- p.set("exclamation","?", null);
+ p.set("message", "%{greeting} %{entity}%{exclamation}", null);
+ p.set("greeting", "Hola", null);
+ p.set("entity", "local group", null);
+ p.set("exclamation", "?", null);
assertEquals("Hola local group?", p.compile(null).get("message"));
QueryProfile p2 = new QueryProfile("test2");
p2.addInherited(p);
- p2.set("entity","milky way", null);
+ p2.set("entity", "milky way", null);
assertEquals("Hola milky way?", p2.compile(null).get("message"));
}
@Test
- public void testUnclosedSubstitution1() {
+ void testUnclosedSubstitution1() {
try {
QueryProfile p = new QueryProfile("test");
- p.set("message1","%{greeting} %{entity}%{exclamation", null);
+ p.set("message1", "%{greeting} %{entity}%{exclamation", null);
fail("Should have produced an exception");
}
catch (IllegalArgumentException e) {
assertEquals("Could not set 'message1' to '%{greeting} %{entity}%{exclamation': Unterminated value substitution '%{exclamation'",
- Exceptions.toMessageString(e));
+ Exceptions.toMessageString(e));
}
}
@Test
- public void testUnclosedSubstitution2() {
+ void testUnclosedSubstitution2() {
try {
QueryProfile p = new QueryProfile("test");
- p.set("message1","%{greeting} %{entity%{exclamation}", null);
+ p.set("message1", "%{greeting} %{entity%{exclamation}", null);
fail("Should have produced an exception");
}
catch (IllegalArgumentException e) {
assertEquals("Could not set 'message1' to '%{greeting} %{entity%{exclamation}': Unterminated value substitution '%{entity%{exclamation}'",
- Exceptions.toMessageString(e));
+ Exceptions.toMessageString(e));
}
}
@Test
- public void testNullSubstitution() {
+ void testNullSubstitution() {
QueryProfile p = new QueryProfile("test");
- p.set("message","%{greeting} %{entity}%{exclamation}", null);
- p.set("greeting","Hola", null);
+ p.set("message", "%{greeting} %{entity}%{exclamation}", null);
+ p.set("greeting", "Hola", null);
assertEquals("Hola ", p.compile(null).get("message"));
QueryProfile p2 = new QueryProfile("test2");
p2.addInherited(p);
- p2.set("greeting","Hola", null);
+ p2.set("greeting", "Hola", null);
p2.set("exclamation", "?", null);
assertEquals("Hola ?", p2.compile(null).get("message"));
}
@Test
- public void testNoOverridingOfPropertiesSetAtRuntime() {
+ void testNoOverridingOfPropertiesSetAtRuntime() {
QueryProfile p = new QueryProfile("test");
- p.set("message","Hello %{world}!", null);
- p.set("world","world", null);
+ p.set("message", "Hello %{world}!", null);
+ p.set("world", "world", null);
p.freeze();
Properties runtime = new QueryProfileProperties(p.compile(null));
- runtime.set("runtimeMessage","Hello %{world}!");
+ runtime.set("runtimeMessage", "Hello %{world}!");
assertEquals("Hello world!", runtime.get("message"));
- assertEquals("Hello %{world}!",runtime.get("runtimeMessage"));
+ assertEquals("Hello %{world}!", runtime.get("runtimeMessage"));
}
@Test
- public void testButPropertiesSetAtRuntimeAreUsedInSubstitutions() {
+ void testButPropertiesSetAtRuntimeAreUsedInSubstitutions() {
QueryProfile p = new QueryProfile("test");
p.set("message", "Hello %{world}!", null);
p.set("world", "world", null);
@@ -139,21 +139,22 @@ public class QueryProfileSubstitutionTestCase {
}
@Test
- public void testInspection() {
+ void testInspection() {
QueryProfile p = new QueryProfile("test");
p.set("message", "%{greeting} %{entity}%{exclamation}", null);
- assertEquals("message","%{greeting} %{entity}%{exclamation}",
- p.declaredContent().entrySet().iterator().next().getValue().toString());
+ assertEquals("%{greeting} %{entity}%{exclamation}",
+ p.declaredContent().entrySet().iterator().next().getValue().toString(),
+ "message");
}
@Test
- public void testVariants() {
+ void testVariants() {
QueryProfile p = new QueryProfile("test");
- p.set("message","Hello %{world}!", null);
- p.set("world","world", null);
- p.setDimensions(new String[] {"x"});
- p.set("message","Halo %{world}!",new String[] {"x1"}, null);
- p.set("world","Europe",new String[] {"x2"}, null);
+ p.set("message", "Hello %{world}!", null);
+ p.set("world", "world", null);
+ p.setDimensions(new String[]{"x"});
+ p.set("message", "Halo %{world}!", new String[]{"x1"}, null);
+ p.set("world", "Europe", new String[]{"x2"}, null);
CompiledQueryProfile cp = p.compile(null);
assertEquals("Hello world!", cp.get("message", QueryProfileVariantsTestCase.toMap("x=x?")));
@@ -162,12 +163,12 @@ public class QueryProfileSubstitutionTestCase {
}
@Test
- public void testRecursion() {
+ void testRecursion() {
QueryProfile p = new QueryProfile("test");
- p.set("message","Hello %{world}!", null);
- p.set("world","sol planet number %{number}", null);
- p.set("number",3, null);
- assertEquals("Hello sol planet number 3!",p.compile(null).get("message"));
+ p.set("message", "Hello %{world}!", null);
+ p.set("world", "sol planet number %{number}", null);
+ p.set("number", 3, null);
+ assertEquals("Hello sol planet number 3!", p.compile(null).get("message"));
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileTestCase.java
index 39ed9b829d2..7a4247f2584 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileTestCase.java
@@ -13,7 +13,7 @@ import com.yahoo.search.query.profile.QueryProfileRegistry;
import com.yahoo.search.query.profile.compiled.CompiledQueryProfile;
import com.yahoo.search.query.profile.compiled.ValueWithSource;
import com.yahoo.yolean.trace.TraceNode;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.HashMap;
@@ -21,11 +21,7 @@ import java.util.HashSet;
import java.util.List;
import java.util.Map;
-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.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Tests untyped query profiles
@@ -35,60 +31,60 @@ import static org.junit.Assert.fail;
public class QueryProfileTestCase {
@Test
- public void testBasics() {
+ void testBasics() {
QueryProfile profile = new QueryProfile("test");
- profile.set("a","a-value", null);
- profile.set("b.c","b.c-value", null);
- profile.set("d.e.f","d.e.f-value", null);
+ profile.set("a", "a-value", null);
+ profile.set("b.c", "b.c-value", null);
+ profile.set("d.e.f", "d.e.f-value", null);
CompiledQueryProfile cprofile = profile.compile(null);
- assertEquals("a-value",cprofile.get("a"));
- assertEquals("b.c-value",cprofile.get("b.c"));
- assertEquals("d.e.f-value",cprofile.get("d.e.f"));
+ assertEquals("a-value", cprofile.get("a"));
+ assertEquals("b.c-value", cprofile.get("b.c"));
+ assertEquals("d.e.f-value", cprofile.get("d.e.f"));
assertNull(cprofile.get("nonexistent"));
assertNull(cprofile.get("nested.nonexistent"));
- assertTrue(profile.lookup("b",null).getClass()==QueryProfile.class);
- assertTrue(profile.lookup("b",null).getClass()==QueryProfile.class);
+ assertEquals(profile.lookup("b", null).getClass(), QueryProfile.class);
+ assertEquals(profile.lookup("b", null).getClass(), QueryProfile.class);
}
/** Tests cloning, with wrappers used in production in place */
@Test
- public void testCloning() {
+ void testCloning() {
QueryProfile classProfile = new QueryProfile("test");
- classProfile.set("a","aValue", null);
- classProfile.set("b",3, null);
+ classProfile.set("a", "aValue", null);
+ classProfile.set("b", 3, null);
Properties properties = new QueryProfileProperties(classProfile.compile(null));
- Properties propertiesClone=properties.clone();
- assertEquals("aValue",propertiesClone.get("a"));
- assertEquals(3,propertiesClone.get("b"));
- properties.set("a","aNewValue");
- assertEquals("aNewValue",properties.get("a"));
- assertEquals("aValue",propertiesClone.get("a"));
+ Properties propertiesClone = properties.clone();
+ assertEquals("aValue", propertiesClone.get("a"));
+ assertEquals(3, propertiesClone.get("b"));
+ properties.set("a", "aNewValue");
+ assertEquals("aNewValue", properties.get("a"));
+ assertEquals("aValue", propertiesClone.get("a"));
}
@Test
- public void testFreezing() {
+ void testFreezing() {
QueryProfile profile = new QueryProfile("test");
- profile.set("a","a-value", null);
- profile.set("b.c","b.c-value", null);
- profile.set("d.e.f","d.e.f-value", null);
+ profile.set("a", "a-value", null);
+ profile.set("b.c", "b.c-value", null);
+ profile.set("d.e.f", "d.e.f-value", null);
assertFalse(profile.isFrozen());
- assertEquals("a-value",profile.get("a"));
+ assertEquals("a-value", profile.get("a"));
profile.freeze();
assertTrue(profile.isFrozen());
- assertTrue(((QueryProfile)profile.lookup("b",null)).isFrozen());
- assertTrue(((QueryProfile)profile.lookup("d.e",null)).isFrozen());
+ assertTrue(((QueryProfile) profile.lookup("b", null)).isFrozen());
+ assertTrue(((QueryProfile) profile.lookup("d.e", null)).isFrozen());
try {
- profile.set("a","value", null);
+ profile.set("a", "value", null);
fail("Expected exception");
}
catch (IllegalStateException e) {
@@ -97,15 +93,15 @@ public class QueryProfileTestCase {
private void assertSameObjects(CompiledQueryProfile profile, String path, List<String> expectedKeys) {
Map<String, Object> subObjects = profile.listValues(path);
- assertEquals("Sub-objects list equal for path " + path, new HashSet<>(expectedKeys), subObjects.keySet());
+ assertEquals(new HashSet<>(expectedKeys), subObjects.keySet(), "Sub-objects list equal for path " + path);
for(String key : expectedKeys) {
- assertEquals("Equal for key " + key, profile.get(key),subObjects.get(path + "." + key));
+ assertEquals(profile.get(key),subObjects.get(path + "." + key),"Equal for key " + key);
}
}
@Test
- public void testGetSubObjects() {
+ void testGetSubObjects() {
QueryProfile barn = new QueryProfile("barn");
QueryProfile mor = new QueryProfile("mor");
QueryProfile far = new QueryProfile("far");
@@ -117,21 +113,21 @@ public class QueryProfileTestCase {
far.addInherited(farfar);
barn.addInherited(mor);
barn.addInherited(far);
- mormor.set("a.mormor","a.mormor", null);
- barn.set("a.barn","a.barn", null);
+ mormor.set("a.mormor", "a.mormor", null);
+ barn.set("a.barn", "a.barn", null);
mor.set("b.mor", "b.mor", null);
far.set("b.far", "b.far", null);
- far.set("a.far","a.far", null);
+ far.set("a.far", "a.far", null);
CompiledQueryProfile cbarn = barn.compile(null);
- assertSameObjects(cbarn, "a", Arrays.asList("mormor","far","barn"));
+ assertSameObjects(cbarn, "a", Arrays.asList("mormor", "far", "barn"));
assertEquals("b.mor", cbarn.get("b.mor"));
assertEquals("b.far", cbarn.get("b.far"));
}
@Test
- public void testInheritance() {
+ void testInheritance() {
QueryProfile barn = new QueryProfile("barn");
QueryProfile mor = new QueryProfile("mor");
QueryProfile far = new QueryProfile("far");
@@ -144,24 +140,24 @@ public class QueryProfileTestCase {
mor.addInherited(morfar);
far.addInherited(farfar);
- morfar.set("a","morfar-a", null);
- mormor.set("a","mormor-a", null);
- farfar.set("a","farfar-a", null);
- mor.set("a","mor-a", null);
- far.set("a","far-a", null);
- barn.set("a","barn-a", null);
+ morfar.set("a", "morfar-a", null);
+ mormor.set("a", "mormor-a", null);
+ farfar.set("a", "farfar-a", null);
+ mor.set("a", "mor-a", null);
+ far.set("a", "far-a", null);
+ barn.set("a", "barn-a", null);
- mormor.set("b","mormor-b", null);
- far.set("b","far-b", null);
+ mormor.set("b", "mormor-b", null);
+ far.set("b", "far-b", null);
- mor.set("c","mor-c", null);
- far.set("c","far-c", null);
+ mor.set("c", "mor-c", null);
+ far.set("c", "far-c", null);
- mor.set("d.a","mor-d.a", null);
- barn.set("d.b","barn-d.b", null);
+ mor.set("d.a", "mor-d.a", null);
+ barn.set("d.b", "barn-d.b", null);
- QueryProfile annetBarn=new QueryProfile("annetBarn");
- annetBarn.set("venn",barn, null);
+ QueryProfile annetBarn = new QueryProfile("annetBarn");
+ annetBarn.set("venn", barn, null);
CompiledQueryProfile cbarn = barn.compile(null);
CompiledQueryProfile cannetBarn = annetBarn.compile(null);
@@ -179,7 +175,7 @@ public class QueryProfileTestCase {
}
@Test
- public void testInheritance2Level() {
+ void testInheritance2Level() {
QueryProfile barn = new QueryProfile("barn");
QueryProfile mor = new QueryProfile("mor");
QueryProfile far = new QueryProfile("far");
@@ -192,24 +188,24 @@ public class QueryProfileTestCase {
mor.addInherited(morfar);
far.addInherited(farfar);
- morfar.set("a.x","morfar-a", null);
- mormor.set("a.x","mormor-a", null);
- farfar.set("a.x","farfar-a", null);
- mor.set("a.x","mor-a", null);
- far.set("a.x","far-a", null);
- barn.set("a.x","barn-a", null);
+ morfar.set("a.x", "morfar-a", null);
+ mormor.set("a.x", "mormor-a", null);
+ farfar.set("a.x", "farfar-a", null);
+ mor.set("a.x", "mor-a", null);
+ far.set("a.x", "far-a", null);
+ barn.set("a.x", "barn-a", null);
- mormor.set("b.x","mormor-b", null);
- far.set("b.x","far-b", null);
+ mormor.set("b.x", "mormor-b", null);
+ far.set("b.x", "far-b", null);
- mor.set("c.x","mor-c", null);
- far.set("c.x","far-c", null);
+ mor.set("c.x", "mor-c", null);
+ far.set("c.x", "far-c", null);
- mor.set("d.a.x","mor-d.a", null);
- barn.set("d.b.x","barn-d.b", null);
+ mor.set("d.a.x", "mor-d.a", null);
+ barn.set("d.b.x", "barn-d.b", null);
- QueryProfile annetBarn=new QueryProfile("annetBarn");
- annetBarn.set("venn",barn, null);
+ QueryProfile annetBarn = new QueryProfile("annetBarn");
+ annetBarn.set("venn", barn, null);
CompiledQueryProfile cbarn = barn.compile(null);
CompiledQueryProfile cannetBarn = annetBarn.compile(null);
@@ -227,7 +223,7 @@ public class QueryProfileTestCase {
}
@Test
- public void testInheritance3Level() {
+ void testInheritance3Level() {
QueryProfile barn = new QueryProfile("barn");
QueryProfile mor = new QueryProfile("mor");
QueryProfile far = new QueryProfile("far");
@@ -240,24 +236,24 @@ public class QueryProfileTestCase {
mor.addInherited(morfar);
far.addInherited(farfar);
- morfar.set("y.a.x","morfar-a", null);
- mormor.set("y.a.x","mormor-a", null);
- farfar.set("y.a.x","farfar-a", null);
- mor.set("y.a.x","mor-a", null);
- far.set("y.a.x","far-a", null);
- barn.set("y.a.x","barn-a", null);
+ morfar.set("y.a.x", "morfar-a", null);
+ mormor.set("y.a.x", "mormor-a", null);
+ farfar.set("y.a.x", "farfar-a", null);
+ mor.set("y.a.x", "mor-a", null);
+ far.set("y.a.x", "far-a", null);
+ barn.set("y.a.x", "barn-a", null);
- mormor.set("y.b.x","mormor-b", null);
- far.set("y.b.x","far-b", null);
+ mormor.set("y.b.x", "mormor-b", null);
+ far.set("y.b.x", "far-b", null);
- mor.set("y.c.x","mor-c", null);
- far.set("y.c.x","far-c", null);
+ mor.set("y.c.x", "mor-c", null);
+ far.set("y.c.x", "far-c", null);
- mor.set("y.d.a.x","mor-d.a", null);
- barn.set("y.d.b.x","barn-d.b", null);
+ mor.set("y.d.a.x", "mor-d.a", null);
+ barn.set("y.d.b.x", "barn-d.b", null);
- QueryProfile annetBarn=new QueryProfile("annetBarn");
- annetBarn.set("venn",barn, null);
+ QueryProfile annetBarn = new QueryProfile("annetBarn");
+ annetBarn.set("venn", barn, null);
CompiledQueryProfile cbarn = barn.compile(null);
CompiledQueryProfile cannetBarn = annetBarn.compile(null);
@@ -275,7 +271,7 @@ public class QueryProfileTestCase {
}
@Test
- public void testListProperties() {
+ void testListProperties() {
QueryProfile barn = new QueryProfile("barn");
QueryProfile mor = new QueryProfile("mor");
QueryProfile far = new QueryProfile("far");
@@ -288,18 +284,18 @@ public class QueryProfileTestCase {
mor.addInherited(morfar);
far.addInherited(farfar);
- morfar.set("a","morfar-a", null);
- morfar.set("model.b","morfar-model.b", null);
- mormor.set("a","mormor-a", null);
- mormor.set("model.b","mormor-model.b", null);
- farfar.set("a","farfar-a", null);
- mor.set("a","mor-a", null);
- far.set("a","far-a", null);
- barn.set("a","barn-a", null);
- mormor.set("b","mormor-b", null);
- far.set("b","far-b", null);
- mor.set("c","mor-c", null);
- far.set("c","far-c", null);
+ morfar.set("a", "morfar-a", null);
+ morfar.set("model.b", "morfar-model.b", null);
+ mormor.set("a", "mormor-a", null);
+ mormor.set("model.b", "mormor-model.b", null);
+ farfar.set("a", "farfar-a", null);
+ mor.set("a", "mor-a", null);
+ far.set("a", "far-a", null);
+ barn.set("a", "barn-a", null);
+ mormor.set("b", "mormor-b", null);
+ far.set("b", "far-b", null);
+ mor.set("c", "mor-c", null);
+ far.set("c", "far-c", null);
CompiledQueryProfile cbarn = barn.compile(null);
@@ -316,8 +312,8 @@ public class QueryProfileTestCase {
Map<String, Object> modelMap = properties.listProperties("model");
assertEquals("mormor-model.b", modelMap.get("b"));
- QueryProfile annetBarn=new QueryProfile("annetBarn");
- annetBarn.set("venn", barn, (QueryProfileRegistry)null);
+ QueryProfile annetBarn = new QueryProfile("annetBarn");
+ annetBarn.set("venn", barn, (QueryProfileRegistry) null);
CompiledQueryProfile cannetBarn = annetBarn.compile(null);
Map<String, Object> annetBarnMap = new QueryProfileProperties(cannetBarn).listProperties();
@@ -329,12 +325,12 @@ public class QueryProfileTestCase {
/** Dots are followed when setting overridability */
@Test
- public void testInstanceOverridable() {
+ void testInstanceOverridable() {
QueryProfile profile = new QueryProfile("root/unoverridableIndex");
- profile.set("model.defaultIndex","default", null);
+ profile.set("model.defaultIndex", "default", null);
profile.setOverridable("model.defaultIndex", false, DimensionValues.empty);
- assertFalse(profile.isDeclaredOverridable("model.defaultIndex",null));
+ assertFalse(profile.isDeclaredOverridable("model.defaultIndex", null));
// Parameters should be ignored
Query query = new Query(HttpRequest.createTestRequest("?model.defaultIndex=title", Method.GET), profile.compile(null));
@@ -348,13 +344,13 @@ public class QueryProfileTestCase {
/** Dots are followed when setting overridability, also with variants */
@Test
- public void testInstanceOverridableWithVariants() {
+ void testInstanceOverridableWithVariants() {
QueryProfile profile = new QueryProfile("root/unoverridableIndex");
- profile.setDimensions(new String[] {"x"});
- profile.set("model.defaultIndex","default", null);
+ profile.setDimensions(new String[]{"x"});
+ profile.set("model.defaultIndex", "default", null);
profile.setOverridable("model.defaultIndex", false, DimensionValues.empty);
- assertFalse(profile.isDeclaredOverridable("model.defaultIndex",null));
+ assertFalse(profile.isDeclaredOverridable("model.defaultIndex", null));
// Parameters should be ignored
Query query = new Query(HttpRequest.createTestRequest("?x=x1&model.defaultIndex=title", Method.GET), profile.compile(null));
@@ -367,47 +363,47 @@ public class QueryProfileTestCase {
}
@Test
- public void testSimpleInstanceOverridableWithVariants1() {
- QueryProfile profile=new QueryProfile("test");
- profile.setDimensions(new String[] {"x"});
- profile.set("a","original", null);
+ void testSimpleInstanceOverridableWithVariants1() {
+ QueryProfile profile = new QueryProfile("test");
+ profile.setDimensions(new String[]{"x"});
+ profile.set("a", "original", null);
profile.setOverridable("a", false, DimensionValues.empty);
- assertFalse(profile.isDeclaredOverridable("a",null));
+ assertFalse(profile.isDeclaredOverridable("a", null));
Query query = new Query(HttpRequest.createTestRequest("?x=x1&a=overridden", Method.GET), profile.compile(null));
assertEquals("original", query.properties().get("a"));
}
@Test
- public void testSimpleInstanceOverridableWithVariants2() {
+ void testSimpleInstanceOverridableWithVariants2() {
QueryProfile profile = new QueryProfile("test");
- profile.setDimensions(new String[] {"x"});
- profile.set("a", "original", new String[] {"x1"}, null);
+ profile.setDimensions(new String[]{"x"});
+ profile.set("a", "original", new String[]{"x1"}, null);
profile.setOverridable("a", false, DimensionValues.empty);
assertFalse(profile.isDeclaredOverridable("a", null));
Query query = new Query(HttpRequest.createTestRequest("?x=x1&a=overridden", Method.GET), profile.compile(null));
- assertEquals("original",query.properties().get("a"));
+ assertEquals("original", query.properties().get("a"));
}
/** Tests having both an explicit reference and an override */
@Test
- public void testExplicitReferenceOverride() {
+ void testExplicitReferenceOverride() {
QueryProfile a1 = new QueryProfile("a1");
- a1.set("b","a1.b", null);
+ a1.set("b", "a1.b", null);
QueryProfile profile = new QueryProfile("test");
- profile.set("a",a1, null);
- profile.set("a.b","a.b", null);
+ profile.set("a", a1, null);
+ profile.set("a.b", "a.b", null);
assertEquals("a.b", profile.compile(null).get("a.b"));
}
@Test
- public void testSettingNonLeaf1() {
- QueryProfile p=new QueryProfile("test");
- p.set("a","a-value", null);
- p.set("a.b","a.b-value", null);
+ void testSettingNonLeaf1() {
+ QueryProfile p = new QueryProfile("test");
+ p.set("a", "a-value", null);
+ p.set("a.b", "a.b-value", null);
QueryProfileProperties cp = new QueryProfileProperties(p.compile(null));
assertEquals("a-value", cp.get("a"));
@@ -415,10 +411,10 @@ public class QueryProfileTestCase {
}
@Test
- public void testSettingNonLeaf2() {
+ void testSettingNonLeaf2() {
QueryProfile p = new QueryProfile("test");
- p.set("a.b","a.b-value", null);
- p.set("a","a-value", null);
+ p.set("a.b", "a.b-value", null);
+ p.set("a", "a-value", null);
QueryProfileProperties cp = new QueryProfileProperties(p.compile(null));
assertEquals("a-value", cp.get("a"));
@@ -426,48 +422,48 @@ public class QueryProfileTestCase {
}
@Test
- public void testSettingNonLeaf3a() {
+ void testSettingNonLeaf3a() {
QueryProfile p = new QueryProfile("test");
- p.setDimensions(new String[] {"x"});
- p.set("a.b","a.b-value", null);
- p.set("a","a-value",new String[] {"x1"}, null);
+ p.setDimensions(new String[]{"x"});
+ p.set("a.b", "a.b-value", null);
+ p.set("a", "a-value", new String[]{"x1"}, null);
QueryProfileProperties cp = new QueryProfileProperties(p.compile(null));
assertNull(p.get("a"));
assertEquals("a.b-value", cp.get("a.b"));
- assertEquals("a-value", cp.get("a", QueryProfileVariantsTestCase.toMap(p, new String[] {"x1"})));
- assertEquals("a.b-value", cp.get("a.b", new String[] {"x1"}));
+ assertEquals("a-value", cp.get("a", QueryProfileVariantsTestCase.toMap(p, new String[]{"x1"})));
+ assertEquals("a.b-value", cp.get("a.b", new String[]{"x1"}));
}
@Test
- public void testSettingNonLeaf3b() {
+ void testSettingNonLeaf3b() {
QueryProfile p = new QueryProfile("test");
- p.setDimensions(new String[] {"x"});
- p.set("a","a-value",new String[] {"x1"}, null);
- p.set("a.b","a.b-value", null);
+ p.setDimensions(new String[]{"x"});
+ p.set("a", "a-value", new String[]{"x1"}, null);
+ p.set("a.b", "a.b-value", null);
QueryProfileProperties cp = new QueryProfileProperties(p.compile(null));
assertNull(cp.get("a"));
assertEquals("a.b-value", cp.get("a.b"));
- assertEquals("a-value", cp.get("a", QueryProfileVariantsTestCase.toMap(p, new String[] {"x1"})));
- assertEquals("a.b-value", cp.get("a.b",new String[] {"x1"}));
+ assertEquals("a-value", cp.get("a", QueryProfileVariantsTestCase.toMap(p, new String[]{"x1"})));
+ assertEquals("a.b-value", cp.get("a.b", new String[]{"x1"}));
}
@Test
- public void testSettingNonLeaf4a() {
+ void testSettingNonLeaf4a() {
QueryProfile p = new QueryProfile("test");
- p.setDimensions(new String[] {"x"});
- p.set("a.b","a.b-value",new String[] {"x1"}, null);
- p.set("a","a-value", null);
+ p.setDimensions(new String[]{"x"});
+ p.set("a.b", "a.b-value", new String[]{"x1"}, null);
+ p.set("a", "a-value", null);
QueryProfileProperties cp = new QueryProfileProperties(p.compile(null));
assertEquals("a-value", cp.get("a"));
assertNull(cp.get("a.b"));
- assertEquals("a-value", cp.get("a",new String[] {"x1"}));
- assertEquals("a.b-value", cp.get("a.b", QueryProfileVariantsTestCase.toMap(p, new String[] {"x1"})));
+ assertEquals("a-value", cp.get("a", new String[]{"x1"}));
+ assertEquals("a.b-value", cp.get("a.b", QueryProfileVariantsTestCase.toMap(p, new String[]{"x1"})));
}
public void testSettingNonLeaf4b() {
@@ -485,36 +481,36 @@ public class QueryProfileTestCase {
}
@Test
- public void testSettingNonLeaf5() {
+ void testSettingNonLeaf5() {
QueryProfile p = new QueryProfile("test");
- p.setDimensions(new String[] {"x"});
- p.set("a.b","a.b-value",new String[] {"x1"}, null);
- p.set("a","a-value",new String[] {"x1"}, null);
+ p.setDimensions(new String[]{"x"});
+ p.set("a.b", "a.b-value", new String[]{"x1"}, null);
+ p.set("a", "a-value", new String[]{"x1"}, null);
QueryProfileProperties cp = new QueryProfileProperties(p.compile(null));
assertNull(cp.get("a"));
assertNull(cp.get("a.b"));
- assertEquals("a-value", cp.get("a", QueryProfileVariantsTestCase.toMap(p, new String[] {"x1"})));
- assertEquals("a.b-value", cp.get("a.b", QueryProfileVariantsTestCase.toMap(p, new String[] {"x1"})));
+ assertEquals("a-value", cp.get("a", QueryProfileVariantsTestCase.toMap(p, new String[]{"x1"})));
+ assertEquals("a.b-value", cp.get("a.b", QueryProfileVariantsTestCase.toMap(p, new String[]{"x1"})));
}
@Test
- public void testListingWithNonLeafs() {
+ void testListingWithNonLeafs() {
QueryProfile p = new QueryProfile("test");
- p.set("a","a-value", null);
- p.set("a.b","a.b-value", null);
+ p.set("a", "a-value", null);
+ p.set("a.b", "a.b-value", null);
Map<String, Object> values = p.compile(null).listValues("a");
assertEquals(2, values.size());
- p.set("a","a-value", null);
+ p.set("a", "a-value", null);
assertEquals("a.b-value", values.get("b"));
}
@Test
- public void testListingSources() {
+ void testListingSources() {
QueryProfile p = new QueryProfile("test");
- p.set("a","a-value", null);
- p.set("a.b","a.b-value", null);
+ p.set("a", "a-value", null);
+ p.set("a.b", "a.b-value", null);
{
Map<String, ValueWithSource> values = p.compile(null).listValuesWithSources(new CompoundName(""), new HashMap<>(), null);
@@ -534,30 +530,30 @@ public class QueryProfileTestCase {
}
@Test
- public void testRankTypeNames() {
- QueryProfile p = new QueryProfile("test");
- p.set("a.$b","foo", null);
- p.set("a.query(b)", "bar", null);
- p.set("a.b.default-index", "fuu", null);
- CompiledQueryProfile cp = p.compile(null);
-
- assertEquals("foo", cp.get("a.$b"));
- assertEquals("bar", cp.get("a.query(b)"));
- assertEquals("fuu", cp.get("a.b.default-index"));
-
- Map<String,Object> p1 = cp.listValues("");
- assertEquals("foo", p1.get("a.$b"));
- assertEquals("bar", p1.get("a.query(b)"));
- assertEquals("fuu", p1.get("a.b.default-index"));
-
- Map<String,Object> p2 = cp.listValues("a");
- assertEquals("foo", p2.get("$b"));
- assertEquals("bar", p2.get("query(b)"));
- assertEquals("fuu", p2.get("b.default-index"));
+ void testRankTypeNames() {
+ QueryProfile p = new QueryProfile("test");
+ p.set("a.$b", "foo", null);
+ p.set("a.query(b)", "bar", null);
+ p.set("a.b.default-index", "fuu", null);
+ CompiledQueryProfile cp = p.compile(null);
+
+ assertEquals("foo", cp.get("a.$b"));
+ assertEquals("bar", cp.get("a.query(b)"));
+ assertEquals("fuu", cp.get("a.b.default-index"));
+
+ Map<String, Object> p1 = cp.listValues("");
+ assertEquals("foo", p1.get("a.$b"));
+ assertEquals("bar", p1.get("a.query(b)"));
+ assertEquals("fuu", p1.get("a.b.default-index"));
+
+ Map<String, Object> p2 = cp.listValues("a");
+ assertEquals("foo", p2.get("$b"));
+ assertEquals("bar", p2.get("query(b)"));
+ assertEquals("fuu", p2.get("b.default-index"));
}
@Test
- public void testQueryProfileInlineValueReassignment() {
+ void testQueryProfileInlineValueReassignment() {
QueryProfile p = new QueryProfile("test");
p.set("source.rel.params.query", "%{model.queryString}", null);
p.freeze();
@@ -570,9 +566,9 @@ public class QueryProfileTestCase {
}
@Test
- public void testQueryProfileInlineValueReassignmentSimpleName() {
+ void testQueryProfileInlineValueReassignmentSimpleName() {
QueryProfile p = new QueryProfile("test");
- p.set("key","%{model.queryString}", null);
+ p.set("key", "%{model.queryString}", null);
p.freeze();
Query q = new Query(HttpRequest.createTestRequest("?query=foo", Method.GET), p.compile(null));
assertEquals("foo", q.properties().get("key"));
@@ -583,7 +579,7 @@ public class QueryProfileTestCase {
}
@Test
- public void testQueryProfileInlineValueReassignmentSimpleNameGenericProperty() {
+ void testQueryProfileInlineValueReassignmentSimpleNameGenericProperty() {
QueryProfile p = new QueryProfile("test");
p.set("key", "%{value}", null);
p.freeze();
@@ -596,7 +592,7 @@ public class QueryProfileTestCase {
}
@Test
- public void testQueryProfileModelValueListing() {
+ void testQueryProfileModelValueListing() {
QueryProfile p = new QueryProfile("test");
p.freeze();
Query q = new Query(HttpRequest.createTestRequest("?query=bar", Method.GET), p.compile(null));
@@ -608,21 +604,21 @@ public class QueryProfileTestCase {
}
@Test
- public void testEmptyBoolean() {
+ void testEmptyBoolean() {
QueryProfile p = new QueryProfile("test");
- p.setDimensions(new String[] {"x","y"});
- p.set("clustering.something","bar", null);
- p.set("clustering.something","bar", new String[] {"x1","y1"}, null);
+ p.setDimensions(new String[]{"x", "y"});
+ p.set("clustering.something", "bar", null);
+ p.set("clustering.something", "bar", new String[]{"x1", "y1"}, null);
p.freeze();
Query q = new Query(HttpRequest.createTestRequest("?x=x1&y=y1&query=bar&clustering.timeline.kano=tur&" +
- "clustering.enable=true&clustering.timeline.bucketspec=-" +
- "7d/3h&clustering.timeline.tophit=false&clustering.timeli" +
- "ne=true", Method.GET), p.compile(null));
+ "clustering.enable=true&clustering.timeline.bucketspec=-" +
+ "7d/3h&clustering.timeline.tophit=false&clustering.timeli" +
+ "ne=true", Method.GET), p.compile(null));
assertTrue(q.properties().getBoolean("clustering.timeline", false));
}
@Test
- public void testSubstitutionInTrace() {
+ void testSubstitutionInTrace() {
QueryProfile profile = new QueryProfile("test");
profile.set("property", "%{foo}", null);
CompiledQueryProfile cProfile = profile.compile(null);
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileVariantsCloneTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileVariantsCloneTestCase.java
index 3e1a101628c..43078db66d0 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileVariantsCloneTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileVariantsCloneTestCase.java
@@ -5,13 +5,13 @@ package com.yahoo.search.query.profile.test;
import com.yahoo.search.query.profile.DimensionValues;
import com.yahoo.search.query.profile.QueryProfile;
import com.yahoo.search.query.profile.compiled.CompiledQueryProfile;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Tony Vaagenes
@@ -19,7 +19,7 @@ import static org.junit.Assert.assertEquals;
public class QueryProfileVariantsCloneTestCase {
@Test
- public void test_that_interior_and_leaf_values_on_a_path_are_preserved_when_cloning() {
+ void test_that_interior_and_leaf_values_on_a_path_are_preserved_when_cloning() {
Map<String, String> dimensionBinding = createDimensionBinding("location", "norway");
QueryProfile profile = new QueryProfile("profile");
@@ -32,10 +32,10 @@ public class QueryProfileVariantsCloneTestCase {
CompiledQueryProfile clone = profile.compile(null).clone();
assertEquals(profile.get("interior", dimensionBinding, null),
- clone.get("interior", dimensionBinding));
+ clone.get("interior", dimensionBinding));
assertEquals(profile.get("interior.leaf", dimensionBinding, null),
- clone.get("interior.leaf", dimensionBinding));
+ clone.get("interior.leaf", dimensionBinding));
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileVariantsTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileVariantsTestCase.java
index 3cf2949f33c..1a6cfee75a5 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileVariantsTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/test/QueryProfileVariantsTestCase.java
@@ -19,8 +19,8 @@ import com.yahoo.search.query.profile.QueryProfileVariant;
import com.yahoo.search.query.profile.compiled.CompiledQueryProfile;
import com.yahoo.search.query.profile.compiled.CompiledQueryProfileRegistry;
import com.yahoo.search.query.profile.compiled.ValueWithSource;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.HashMap;
@@ -28,9 +28,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.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -38,75 +36,75 @@ import static org.junit.Assert.assertTrue;
public class QueryProfileVariantsTestCase {
@Test
- public void testSimple() {
+ void testSimple() {
QueryProfile profile = new QueryProfile("a");
- profile.set("a","a.deflt", null);
- profile.setDimensions(new String[] {"x","y","z"});
- profile.set("a","a.1.*.*", new String[] {"x1",null,null}, null);
- profile.set("a","a.1.*.1", new String[] {"x1",null,"z1"}, null);
- profile.set("a","a.1.*.5", new String[] {"x1",null,"z5"}, null);
- profile.set("a","a.1.1.*", new String[] {"x1","y1",null}, null);
- profile.set("a","a.1.5.*", new String[] {"x1","y5",null}, null);
- profile.set("a","a.1.1.1", new String[] {"x1","y1","z1"}, null);
- profile.set("a","a.2.1.1", new String[] {"x2","y1","z1"}, null);
- profile.set("a","a.1.2.2", new String[] {"x1","y2","z2"}, null);
- profile.set("a","a.1.2.3", new String[] {"x1","y2","z3"}, null);
- profile.set("a","a.2.*.*", new String[] {"x2" }, null); // Same as ,null,null
+ profile.set("a", "a.deflt", null);
+ profile.setDimensions(new String[]{"x", "y", "z"});
+ profile.set("a", "a.1.*.*", new String[]{"x1", null, null}, null);
+ profile.set("a", "a.1.*.1", new String[]{"x1", null, "z1"}, null);
+ profile.set("a", "a.1.*.5", new String[]{"x1", null, "z5"}, null);
+ profile.set("a", "a.1.1.*", new String[]{"x1", "y1", null}, null);
+ profile.set("a", "a.1.5.*", new String[]{"x1", "y5", null}, null);
+ profile.set("a", "a.1.1.1", new String[]{"x1", "y1", "z1"}, null);
+ profile.set("a", "a.2.1.1", new String[]{"x2", "y1", "z1"}, null);
+ profile.set("a", "a.1.2.2", new String[]{"x1", "y2", "z2"}, null);
+ profile.set("a", "a.1.2.3", new String[]{"x1", "y2", "z3"}, null);
+ profile.set("a", "a.2.*.*", new String[]{"x2" }, null); // Same as ,null,null
CompiledQueryProfile cprofile = profile.compile(null);
// Perfect matches
- assertGet("a.deflt","a", new String[] {null,null,null}, profile, cprofile);
- assertGet("a.1.*.*","a", new String[] {"x1",null,null}, profile, cprofile);
- assertGet("a.1.1.*","a", new String[] {"x1","y1",null}, profile, cprofile);
- assertGet("a.1.5.*","a", new String[] {"x1","y5",null}, profile, cprofile);
- assertGet("a.1.*.1","a", new String[] {"x1",null,"z1"}, profile, cprofile);
- assertGet("a.1.*.5","a", new String[] {"x1",null,"z5"}, profile, cprofile);
- assertGet("a.1.1.1","a", new String[] {"x1","y1","z1"}, profile, cprofile);
- assertGet("a.2.1.1","a", new String[] {"x2","y1","z1"}, profile, cprofile);
- assertGet("a.1.2.2","a", new String[] {"x1","y2","z2"}, profile, cprofile);
- assertGet("a.1.2.3","a", new String[] {"x1","y2","z3"}, profile, cprofile);
- assertGet("a.2.*.*","a", new String[] {"x2",null,null}, profile, cprofile);
+ assertGet("a.deflt", "a", new String[]{null, null, null}, profile, cprofile);
+ assertGet("a.1.*.*", "a", new String[]{"x1", null, null}, profile, cprofile);
+ assertGet("a.1.1.*", "a", new String[]{"x1", "y1", null}, profile, cprofile);
+ assertGet("a.1.5.*", "a", new String[]{"x1", "y5", null}, profile, cprofile);
+ assertGet("a.1.*.1", "a", new String[]{"x1", null, "z1"}, profile, cprofile);
+ assertGet("a.1.*.5", "a", new String[]{"x1", null, "z5"}, profile, cprofile);
+ assertGet("a.1.1.1", "a", new String[]{"x1", "y1", "z1"}, profile, cprofile);
+ assertGet("a.2.1.1", "a", new String[]{"x2", "y1", "z1"}, profile, cprofile);
+ assertGet("a.1.2.2", "a", new String[]{"x1", "y2", "z2"}, profile, cprofile);
+ assertGet("a.1.2.3", "a", new String[]{"x1", "y2", "z3"}, profile, cprofile);
+ assertGet("a.2.*.*", "a", new String[]{"x2", null, null}, profile, cprofile);
// Wildcard matches
- assertGet("a.deflt","a", new String[] {"x?","y?","z?"}, profile, cprofile);
- assertGet("a.deflt","a", new String[] {"x?","y1","z1"}, profile, cprofile);
- assertGet("a.1.*.*","a", new String[] {"x1","y?","z?"}, profile, cprofile);
- assertGet("a.1.*.*","a", new String[] {"x1","y?","z?"}, profile, cprofile);
- assertGet("a.1.1.*","a", new String[] {"x1","y1","z?"}, profile, cprofile);
- assertGet("a.1.*.1","a", new String[] {"x1","y?","z1"}, profile, cprofile);
- assertGet("a.1.5.*","a", new String[] {"x1","y5","z?"}, profile, cprofile);
- assertGet("a.1.*.5","a", new String[] {"x1","y?","z5"}, profile, cprofile);
- assertGet("a.1.5.*","a", new String[] {"x1","y5","z5"}, profile, cprofile); // Left dimension gets precedence
- assertGet("a.2.*.*","a", new String[] {"x2","y?","z?"}, profile, cprofile);
+ assertGet("a.deflt", "a", new String[]{"x?", "y?", "z?"}, profile, cprofile);
+ assertGet("a.deflt", "a", new String[]{"x?", "y1", "z1"}, profile, cprofile);
+ assertGet("a.1.*.*", "a", new String[]{"x1", "y?", "z?"}, profile, cprofile);
+ assertGet("a.1.*.*", "a", new String[]{"x1", "y?", "z?"}, profile, cprofile);
+ assertGet("a.1.1.*", "a", new String[]{"x1", "y1", "z?"}, profile, cprofile);
+ assertGet("a.1.*.1", "a", new String[]{"x1", "y?", "z1"}, profile, cprofile);
+ assertGet("a.1.5.*", "a", new String[]{"x1", "y5", "z?"}, profile, cprofile);
+ assertGet("a.1.*.5", "a", new String[]{"x1", "y?", "z5"}, profile, cprofile);
+ assertGet("a.1.5.*", "a", new String[]{"x1", "y5", "z5"}, profile, cprofile); // Left dimension gets precedence
+ assertGet("a.2.*.*", "a", new String[]{"x2", "y?", "z?"}, profile, cprofile);
}
@Test
- public void testReferenceInVariant() {
+ void testReferenceInVariant() {
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfile test = new QueryProfile("test");
- test.setDimensions(new String[] { "d1" });
+ test.setDimensions(new String[]{"d1"});
registry.register(test);
QueryProfile references = new QueryProfile("referenced");
- references.setDimensions(new String[] { "d1" });
+ references.setDimensions(new String[]{"d1"});
registry.register(references);
QueryProfile other = new QueryProfile("other");
- other.setDimensions(new String[] { "d1" });
+ other.setDimensions(new String[]{"d1"});
registry.register(other);
- test.set( "a", references, new String[] { "d1v"}, registry);
- test.set( "a.b", "test-value", new String[] { "d1v"}, registry);
- other.set( "a", references, new String[] { "d1v"}, registry);
- other.set("a.b", "other-value", new String[] { "d1v"}, registry);
+ test.set("a", references, new String[]{"d1v"}, registry);
+ test.set("a.b", "test-value", new String[]{"d1v"}, registry);
+ other.set("a", references, new String[]{"d1v"}, registry);
+ other.set("a.b", "other-value", new String[]{"d1v"}, registry);
- assertEquals("test-value", test.get("a.b", new String[] { "d1v"}));
- assertEquals("other-value", other.get("a.b", new String[] { "d1v"}));
- assertNull(references.get("b", new String[] { "d1v"}));
+ assertEquals("test-value", test.get("a.b", new String[]{"d1v"}));
+ assertEquals("other-value", other.get("a.b", new String[]{"d1v"}));
+ assertNull(references.get("b", new String[]{"d1v"}));
var cRegistry = registry.compile();
assertEquals("test-value",
- cRegistry.getComponent("test").get("a.b", Map.of("d1", "d1v")));
+ cRegistry.getComponent("test").get("a.b", Map.of("d1", "d1v")));
}
/**
@@ -114,7 +112,7 @@ public class QueryProfileVariantsTestCase {
* and also setting a value within that variants subspace.
*/
@Test
- public void testVariantReference() {
+ void testVariantReference() {
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfile parent = new QueryProfile("parent");
@@ -123,24 +121,24 @@ public class QueryProfileVariantsTestCase {
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);
- assertEquals("Variant dimensions are not overridden by the referenced dimensions",
- "[d1, d2, d3]",
- ((QueryProfile)base.getVariants().getVariants().get(0).values().get("a")).getDimensions().toString());
- base.set("a.b", 1, new String[] {null, null, "d3-val"}, registry);
+ base.set("a", referenced, new String[]{null, null, "d3-val"}, registry);
+ assertEquals("[d1, d2, d3]",
+ ((QueryProfile) base.getVariants().getVariants().get(0).values().get("a")).getDimensions().toString(),
+ "Variant dimensions are not overridden by the referenced dimensions");
+ base.set("a.b", 1, new String[]{null, null, "d3-val"}, registry);
QueryProfileVariant aVariants = base.getVariants().getVariants().get(0);
- assertEquals("Variant dimensions are not overridden by the referenced dimensions",
- "[d1, d2, d3]",
- ((QueryProfile)base.getVariants().getVariants().get(0).values().get("a")).getDimensions().toString());
+ assertEquals("[d1, d2, d3]",
+ ((QueryProfile) base.getVariants().getVariants().get(0).values().get("a")).getDimensions().toString(),
+ "Variant dimensions are not overridden by the referenced dimensions");
}
@Test
- public void testReference() {
+ void testReference() {
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfile test = new QueryProfile("test");
registry.register(test);
@@ -151,9 +149,9 @@ public class QueryProfileVariantsTestCase {
QueryProfile other = new QueryProfile("other");
registry.register(other);
- test.set( "a", references, registry);
- test.set( "a.b", "test-value", registry);
- other.set( "a", references, registry);
+ test.set("a", references, registry);
+ test.set("a.b", "test-value", registry);
+ other.set("a", references, registry);
other.set("a.b", "other-value", registry);
assertEquals("test-value", test.get("a.b"));
@@ -162,21 +160,21 @@ public class QueryProfileVariantsTestCase {
}
@Test
- public void testVariantInReferencedAndParentWithOtherMatchingVariant() {
+ void testVariantInReferencedAndParentWithOtherMatchingVariant() {
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfile parent = new QueryProfile("parent");
- parent.setDimensions(new String[] { "x", "y" } );
- parent.set("other", "otherValue", new String[] { "x1", "y1" }, registry );
+ parent.setDimensions(new String[]{"x", "y"});
+ parent.set("other", "otherValue", new String[]{"x1", "y1"}, registry);
QueryProfile profile = new QueryProfile("test");
profile.addInherited(parent);
QueryProfile referenced = new QueryProfile("referenced");
- referenced.setDimensions(new String[] { "x", "y", "z" });
+ referenced.setDimensions(new String[]{"x", "y", "z"});
registry.register(parent);
registry.register(profile);
registry.register(referenced);
profile.set("a.b", referenced, registry);
referenced.set("c", "default_value", registry);
- referenced.set("c", "variant_value", new String[] { "x1", null, "z1" }, registry);
+ referenced.set("c", "variant_value", new String[]{"x1", null, "z1"}, registry);
CompiledQueryProfileRegistry cRegistry = registry.compile();
CompiledQueryProfile cTest = cRegistry.findQueryProfile("test");
@@ -186,9 +184,9 @@ public class QueryProfileVariantsTestCase {
{
Map<String, ValueWithSource> values = cRegistry.findQueryProfile("test")
- .listValuesWithSources(new CompoundName(""),
- new HashMap<>(),
- null);
+ .listValuesWithSources(new CompoundName(""),
+ new HashMap<>(),
+ null);
assertEquals(1, values.size());
assertEquals("default_value", values.get("a.b.c").value());
assertEquals("referenced", values.get("a.b.c").source());
@@ -197,9 +195,9 @@ public class QueryProfileVariantsTestCase {
{
Map<String, ValueWithSource> values = cRegistry.findQueryProfile("test")
- .listValuesWithSources(new CompoundName(""),
- toMap("x=x1", "y=y1", "z=z1"),
- null);
+ .listValuesWithSources(new CompoundName(""),
+ toMap("x=x1", "y=y1", "z=z1"),
+ null);
assertEquals(2, values.size());
assertEquals("variant_value", values.get("a.b.c").value());
assertEquals("referenced", values.get("a.b.c").source());
@@ -212,16 +210,16 @@ public class QueryProfileVariantsTestCase {
}
@Test
- public void testSwitchingDimensionOrderInReferencedVariantWithFullOverlap() {
+ void testSwitchingDimensionOrderInReferencedVariantWithFullOverlap() {
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfile profile = new QueryProfile("test");
- profile.setDimensions(new String[] { "x", "i", "j", "y" });
+ profile.setDimensions(new String[]{"x", "i", "j", "y"});
QueryProfile referenced = new QueryProfile("referenced");
- referenced.setDimensions(new String[] { "y", "x" });
+ referenced.setDimensions(new String[]{"y", "x"});
registry.register(profile);
registry.register(referenced);
- profile.set("a.b", referenced, new String[] { "x1", "i1", "j1", "y1" }, registry);
- referenced.set("c", "variant_value", new String[] { "y1" }, registry);
+ profile.set("a.b", referenced, new String[]{"x1", "i1", "j1", "y1"}, registry);
+ referenced.set("c", "variant_value", new String[]{"y1"}, registry);
CompiledQueryProfileRegistry cRegistry = registry.compile();
CompiledQueryProfile cTest = cRegistry.findQueryProfile("test");
@@ -230,16 +228,16 @@ public class QueryProfileVariantsTestCase {
}
@Test
- public void testSameDimensionOrderInReferencedVariantWithPartialOverlap() {
+ void testSameDimensionOrderInReferencedVariantWithPartialOverlap() {
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfile profile = new QueryProfile("test");
- profile.setDimensions(new String[] { "x", "i", "j", "y" });
+ profile.setDimensions(new String[]{"x", "i", "j", "y"});
QueryProfile referenced = new QueryProfile("referenced");
- referenced.setDimensions(new String[] { "x", "y" });
+ referenced.setDimensions(new String[]{"x", "y"});
registry.register(profile);
registry.register(referenced);
- profile.set("a.b", referenced, new String[] { "x1", "i1", "j1" }, registry);
- referenced.set("c", "variant_value", new String[] { null, "y1" }, registry);
+ profile.set("a.b", referenced, new String[]{"x1", "i1", "j1"}, registry);
+ referenced.set("c", "variant_value", new String[]{null, "y1"}, registry);
CompiledQueryProfileRegistry cRegistry = registry.compile();
CompiledQueryProfile cTest = cRegistry.findQueryProfile("test");
@@ -247,18 +245,19 @@ public class QueryProfileVariantsTestCase {
assertEquals("variant_value", new Query("?x=x1&i=i1&j=j1&y=y1", cTest).properties().get("a.b.c"));
}
+ // Switching order is not supported
@Test
- @Ignore // Switching order is not supported
- public void testSwitchingDimensionOrderInReferencedVariantWithPartialOverlap() {
+ @Disabled
+ void testSwitchingDimensionOrderInReferencedVariantWithPartialOverlap() {
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfile profile = new QueryProfile("test");
- profile.setDimensions(new String[] { "x", "i", "j", "y" });
+ profile.setDimensions(new String[]{"x", "i", "j", "y"});
QueryProfile referenced = new QueryProfile("referenced");
- referenced.setDimensions(new String[] { "y", "x" });
+ referenced.setDimensions(new String[]{"y", "x"});
registry.register(profile);
registry.register(referenced);
- profile.set("a.b", referenced, new String[] { "x1", "i1", "j1" }, registry);
- referenced.set("c", "variant_value", new String[] { "y1" }, registry);
+ profile.set("a.b", referenced, new String[]{"x1", "i1", "j1"}, registry);
+ referenced.set("c", "variant_value", new String[]{"y1"}, registry);
CompiledQueryProfileRegistry cRegistry = registry.compile();
CompiledQueryProfile cTest = cRegistry.findQueryProfile("test");
@@ -267,12 +266,12 @@ public class QueryProfileVariantsTestCase {
}
@Test
- public void testMultipleMatchingVariantsAndDefault() {
+ void testMultipleMatchingVariantsAndDefault() {
QueryProfile profile = new QueryProfile("test");
- profile.setDimensions(new String[] { "a", "b" });
+ profile.setDimensions(new String[]{"a", "b"});
profile.set("property1", "property1_default", null);
- profile.set("property1", "property1_variantB", new String[] { null, "b1" }, null);
- profile.set("property2", "property2_variantA", new String[] { "a1", null }, null);
+ profile.set("property1", "property1_variantB", new String[]{null, "b1"}, null);
+ profile.set("property2", "property2_variantA", new String[]{"a1", null}, null);
CompiledQueryProfile cProfile = profile.compile(null);
Query query = new Query("?a=a1&b=b1&b=b1", cProfile);
@@ -281,16 +280,16 @@ public class QueryProfileVariantsTestCase {
}
@Test
- public void testInheritedVariants() {
+ void testInheritedVariants() {
QueryProfile parent = new QueryProfile("parent");
- parent.setDimensions(new String[] { "parentDim" });
+ parent.setDimensions(new String[]{"parentDim"});
parent.set("property", "defaultValue", null);
- parent.set("property", "variantValue", new String[] { "V2" }, null);
+ parent.set("property", "variantValue", new String[]{"V2"}, null);
QueryProfile child = new QueryProfile("child");
child.addInherited(parent);
- child.setDimensions(new String[] { "childDim" });
- child.set("otherProperty", "otherPropertyValue", new String[] { "V1" }, null);
+ child.setDimensions(new String[]{"childDim"});
+ child.set("otherProperty", "otherPropertyValue", new String[]{"V1"}, null);
CompiledQueryProfile cchild = child.compile(null);
assertEquals("defaultValue", new Query("?query=test", cchild).properties().get("property"));
@@ -301,19 +300,19 @@ public class QueryProfileVariantsTestCase {
}
@Test
- public void testInheritedVariantsMultipleInheritance() {
+ void testInheritedVariantsMultipleInheritance() {
QueryProfile parent = new QueryProfile("parent");
- parent.setDimensions(new String[] { "parentDim" });
+ parent.setDimensions(new String[]{"parentDim"});
parent.set("property", "defaultValue", null);
- parent.set("property", "variantValue", new String[] { "V2" }, null);
+ parent.set("property", "variantValue", new String[]{"V2"}, null);
QueryProfile otherParent = new QueryProfile("otherParent");
QueryProfile child = new QueryProfile("child");
child.addInherited(parent);
child.addInherited(otherParent);
- child.setDimensions(new String[] { "childDim" });
- child.set("otherProperty", "otherPropertyValue", new String[] { "V1" }, null);
+ child.setDimensions(new String[]{"childDim"});
+ child.set("otherProperty", "otherPropertyValue", new String[]{"V1"}, null);
CompiledQueryProfile cchild = child.compile(null);
assertEquals("defaultValue", new Query("?query=test", cchild).properties().get("property"));
@@ -324,12 +323,12 @@ public class QueryProfileVariantsTestCase {
}
@Test
- public void testVariantsOfInlineCompound() {
+ void testVariantsOfInlineCompound() {
QueryProfile profile = new QueryProfile("test");
- profile.setDimensions(new String[] {"x"});
+ profile.setDimensions(new String[]{"x"});
profile.set("a.b", "a.b", null);
- profile.set("a.b", "a.b.x1", new String[] {"x1"}, null);
- profile.set("a.b", "a.b.x2", new String[] {"x2"}, null);
+ profile.set("a.b", "a.b.x1", new String[]{"x1"}, null);
+ profile.set("a.b", "a.b.x2", new String[]{"x2"}, null);
CompiledQueryProfile cprofile = profile.compile(null);
@@ -339,13 +338,13 @@ public class QueryProfileVariantsTestCase {
}
@Test
- public void testOverlappingProfiles() {
+ void testOverlappingProfiles() {
QueryProfile profile = new QueryProfile("test");
- profile.setDimensions(new String[] {"region", "model", "bucket"});
- profile.set("a", "us,nokia,* : a", new String[] {"us", "nokia", null }, null);
- profile.set("b", "us,nokia,* : b", new String[] {"us", "nokia", null }, null);
- profile.set("c", "us,*,bucket1: c", new String[] {"us", null, "bucket1"}, null);
- profile.set("d", "us,*,bucket1: d", new String[] {"us", null, "bucket1"}, null);
+ profile.setDimensions(new String[]{"region", "model", "bucket"});
+ profile.set("a", "us,nokia,* : a", new String[]{"us", "nokia", null }, null);
+ profile.set("b", "us,nokia,* : b", new String[]{"us", "nokia", null }, null);
+ profile.set("c", "us,*,bucket1: c", new String[]{"us", null, "bucket1"}, null);
+ profile.set("d", "us,*,bucket1: d", new String[]{"us", null, "bucket1"}, null);
CompiledQueryProfile cprofile = profile.compile(null);
var parameters = toMap("region=us", "model=nokia", "bucket=bucket1");
@@ -360,15 +359,15 @@ public class QueryProfileVariantsTestCase {
}
@Test
- public void testVariantsOfExplicitCompound() {
+ void testVariantsOfExplicitCompound() {
QueryProfile a1 = new QueryProfile("a1");
a1.set("b", "a.b", null);
QueryProfile profile = new QueryProfile("test");
- profile.setDimensions(new String[] {"x"});
+ profile.setDimensions(new String[]{"x"});
profile.set("a", a1, null);
- profile.set("a.b", "a.b.x1", new String[] {"x1"}, null);
- profile.set("a.b", "a.b.x2", new String[] {"x2"}, null);
+ profile.set("a.b", "a.b.x1", new String[]{"x1"}, null);
+ profile.set("a.b", "a.b.x2", new String[]{"x2"}, null);
CompiledQueryProfile cprofile = profile.compile(null);
@@ -378,11 +377,11 @@ public class QueryProfileVariantsTestCase {
}
@Test
- public void testCompound() {
+ void testCompound() {
// Configuration phase
QueryProfile profile = new QueryProfile("test");
- profile.setDimensions(new String[] {"x","y"});
+ profile.setDimensions(new String[]{"x", "y"});
QueryProfile a1 = new QueryProfile("a1");
a1.set("b", "a1.b.default", null);
@@ -396,23 +395,23 @@ public class QueryProfileVariantsTestCase {
a2.set("d", "a2.d.default", null);
a2.set("e", "a2.e.default", null);
- profile.set("a",a1, null); // Must set profile references before overrides
+ profile.set("a", a1, null); // Must set profile references before overrides
profile.set("a.b", "a.b.default-override", null);
profile.set("a.c", "a.c.default-override", null);
profile.set("a.d", "a.d.default-override", null);
profile.set("a.g", "a.g.default-override", null);
- String[] d1 = new String[] { "x1","y1" };
+ String[] d1 = new String[]{"x1", "y1"};
profile.set("a", a1, d1, null);
profile.set("a.b", "x1.y1.a.b.default-override", d1, null);
profile.set("a.c", "x1.y1.a.c.default-override", d1, null);
profile.set("a.g", "x1.y1.a.g.default-override", d1, null); // This value is never manifest because the runtime override overrides all variants
- String[] d2 = new String[] { "x1","y2" };
- profile.set("a.b","x1.y2.a.b.default-override", d2, null);
- profile.set("a.c","x1.y2.a.c.default-override", d2, null);
+ String[] d2 = new String[]{"x1", "y2"};
+ profile.set("a.b", "x1.y2.a.b.default-override", d2, null);
+ profile.set("a.c", "x1.y2.a.c.default-override", d2, null);
- String[] d3 = new String[] { "x2","y1" };
+ String[] d3 = new String[]{"x2", "y1"};
profile.set("a", a2, d3, null);
profile.set("a.b", "x2.y1.a.b.default-override", d3, null);
profile.set("a.c", "x2.y1.a.c.default-override", d3, null);
@@ -466,39 +465,39 @@ public class QueryProfileVariantsTestCase {
}
@Test
- public void testVariantNotInBase() {
+ void testVariantNotInBase() {
QueryProfile test = new QueryProfile("test");
- test.setDimensions(new String[] {"x"});
- test.set("InX1Only", "x1", new String[] { "x1" }, null);
+ test.setDimensions(new String[]{"x"});
+ test.set("InX1Only", "x1", new String[]{"x1"}, null);
CompiledQueryProfile ctest = test.compile(null);
assertEquals("x1", ctest.get("InX1Only", toMap("x=x1")));
- assertEquals(null, ctest.get("InX1Only", toMap("x=x2")));
- assertEquals(null, ctest.get("InX1Only"));
+ assertNull(ctest.get("InX1Only", toMap("x=x2")));
+ assertNull(ctest.get("InX1Only"));
}
@Test
- public void testVariantNotInBaseSpaceVariantValue() {
+ void testVariantNotInBaseSpaceVariantValue() {
QueryProfile test = new QueryProfile("test");
- test.setDimensions(new String[] { "x" });
- test.set("InX1Only", "x1", new String[] { "x 1" }, null);
+ test.setDimensions(new String[]{"x"});
+ test.set("InX1Only", "x1", new String[]{"x 1"}, null);
CompiledQueryProfile ctest = test.compile(null);
assertEquals("x1", ctest.get("InX1Only", toMap("x=x 1")));
- assertEquals(null, ctest.get("InX1Only", toMap("x=x 2")));
- assertEquals(null, ctest.get("InX1Only"));
+ assertNull(ctest.get("InX1Only", toMap("x=x 2")));
+ assertNull(ctest.get("InX1Only"));
}
@Test
- public void testDimensionsInSuperType() {
+ void testDimensionsInSuperType() {
QueryProfile parent = new QueryProfile("parent");
- parent.setDimensions(new String[] {"x", "y"});
+ parent.setDimensions(new String[]{"x", "y"});
QueryProfile child = new QueryProfile("child");
child.addInherited(parent);
child.set("a", "a.default", null);
- child.set("a", "a.x1.y1", new String[] {"x1", "y1"}, null);
- child.set("a", "a.x1.y2", new String[] {"x1", "y2"}, null);
+ child.set("a", "a.x1.y1", new String[]{"x1", "y1"}, null);
+ child.set("a", "a.x1.y2", new String[]{"x1", "y2"}, null);
CompiledQueryProfile cchild = child.compile(null);
@@ -508,15 +507,15 @@ public class QueryProfileVariantsTestCase {
}
@Test
- public void testDimensionsInSuperTypeRuntime() {
+ void testDimensionsInSuperTypeRuntime() {
QueryProfile parent = new QueryProfile("parent");
- parent.setDimensions(new String[] { "x", "y" });
+ parent.setDimensions(new String[]{"x", "y"});
QueryProfile child = new QueryProfile("child");
child.addInherited(parent);
child.set("a", "a.default", null);
child.set("a", "a.x1.y1", new String[]{"x1", "y1"}, null);
child.set("a", "a.x1.y2", new String[]{"x1", "y2"}, null);
- Properties overridable=new QueryProfileProperties(child.compile(null));
+ Properties overridable = new QueryProfileProperties(child.compile(null));
assertEquals("a.default", child.get("a"));
assertEquals("a.x1.y1", overridable.get("a", toMap("x=x1", "y=y1")));
@@ -524,220 +523,220 @@ public class QueryProfileVariantsTestCase {
}
@Test
- public void testVariantsAreResolvedBeforeInheritance() {
- QueryProfile parent=new QueryProfile("parent");
- parent.setDimensions(new String[] {"x","y"});
- parent.set("a","p.a.default", null);
- parent.set("a","p.a.x1.y1",new String[] {"x1","y1"}, null);
- parent.set("a","p.a.x1.y2",new String[] {"x1","y2"}, null);
- parent.set("b","p.b.default", null);
- parent.set("b","p.b.x1.y1",new String[] {"x1","y1"}, null);
- parent.set("b","p.b.x1.y2",new String[] {"x1","y2"}, null);
- QueryProfile child=new QueryProfile("child");
- child.setDimensions(new String[] {"x","y"});
+ void testVariantsAreResolvedBeforeInheritance() {
+ QueryProfile parent = new QueryProfile("parent");
+ parent.setDimensions(new String[]{"x", "y"});
+ parent.set("a", "p.a.default", null);
+ parent.set("a", "p.a.x1.y1", new String[]{"x1", "y1"}, null);
+ parent.set("a", "p.a.x1.y2", new String[]{"x1", "y2"}, null);
+ parent.set("b", "p.b.default", null);
+ parent.set("b", "p.b.x1.y1", new String[]{"x1", "y1"}, null);
+ parent.set("b", "p.b.x1.y2", new String[]{"x1", "y2"}, null);
+ QueryProfile child = new QueryProfile("child");
+ child.setDimensions(new String[]{"x", "y"});
child.addInherited(parent);
- child.set("a","c.a.default", null);
- child.set("a","c.a.x1.y1",new String[] {"x1","y1"}, null);
+ child.set("a", "c.a.default", null);
+ child.set("a", "c.a.x1.y1", new String[]{"x1", "y1"}, null);
CompiledQueryProfile cchild = child.compile(null);
- assertEquals("c.a.default",cchild.get("a"));
- assertEquals("c.a.x1.y1",cchild.get("a", toMap("x=x1", "y=y1")));
- assertEquals("c.a.default",cchild.get("a", toMap("x=x1", "y=y2")));
- assertEquals("p.b.default",cchild.get("b"));
- assertEquals("p.b.x1.y1",cchild.get("b", toMap("x=x1", "y=y1")));
- assertEquals("p.b.x1.y2",cchild.get("b", toMap("x=x1", "y=y2")));
+ assertEquals("c.a.default", cchild.get("a"));
+ assertEquals("c.a.x1.y1", cchild.get("a", toMap("x=x1", "y=y1")));
+ assertEquals("c.a.default", cchild.get("a", toMap("x=x1", "y=y2")));
+ assertEquals("p.b.default", cchild.get("b"));
+ assertEquals("p.b.x1.y1", cchild.get("b", toMap("x=x1", "y=y1")));
+ assertEquals("p.b.x1.y2", cchild.get("b", toMap("x=x1", "y=y2")));
}
@Test
- public void testVariantsAreResolvedBeforeInheritanceSimplified() {
- QueryProfile parent=new QueryProfile("parent");
- parent.setDimensions(new String[] {"x","y"});
- parent.set("a","p.a.x1.y2",new String[] {"x1","y2"}, null);
+ void testVariantsAreResolvedBeforeInheritanceSimplified() {
+ QueryProfile parent = new QueryProfile("parent");
+ parent.setDimensions(new String[]{"x", "y"});
+ parent.set("a", "p.a.x1.y2", new String[]{"x1", "y2"}, null);
- QueryProfile child=new QueryProfile("child");
- child.setDimensions(new String[] {"x","y"});
+ QueryProfile child = new QueryProfile("child");
+ child.setDimensions(new String[]{"x", "y"});
child.addInherited(parent);
- child.set("a","c.a.default", null);
+ child.set("a", "c.a.default", null);
- assertEquals("c.a.default",child.compile(null).get("a", toMap("x=x1", "y=y2")));
+ assertEquals("c.a.default", child.compile(null).get("a", toMap("x=x1", "y=y2")));
}
@Test
- public void testVariantInheritance() {
- QueryProfile test=new QueryProfile("test");
- test.setDimensions(new String[] {"x","y"});
- QueryProfile defaultParent=new QueryProfile("defaultParent");
- defaultParent.set("a","a-default", null);
- QueryProfile x1Parent=new QueryProfile("x1Parent");
- x1Parent.set("a","a-x1", null);
- x1Parent.set("d","d-x1", null);
- x1Parent.set("e","e-x1", null);
- QueryProfile x1y1Parent=new QueryProfile("x1y1Parent");
- x1y1Parent.set("a","a-x1y1", null);
- QueryProfile x1y2Parent=new QueryProfile("x1y2Parent");
- x1y2Parent.set("a","a-x1y2", null);
- x1y2Parent.set("b","b-x1y2", null);
- x1y2Parent.set("c","c-x1y2", null);
+ void testVariantInheritance() {
+ QueryProfile test = new QueryProfile("test");
+ test.setDimensions(new String[]{"x", "y"});
+ QueryProfile defaultParent = new QueryProfile("defaultParent");
+ defaultParent.set("a", "a-default", null);
+ QueryProfile x1Parent = new QueryProfile("x1Parent");
+ x1Parent.set("a", "a-x1", null);
+ x1Parent.set("d", "d-x1", null);
+ x1Parent.set("e", "e-x1", null);
+ QueryProfile x1y1Parent = new QueryProfile("x1y1Parent");
+ x1y1Parent.set("a", "a-x1y1", null);
+ QueryProfile x1y2Parent = new QueryProfile("x1y2Parent");
+ x1y2Parent.set("a", "a-x1y2", null);
+ x1y2Parent.set("b", "b-x1y2", null);
+ x1y2Parent.set("c", "c-x1y2", null);
test.addInherited(defaultParent);
- test.addInherited(x1Parent,new String[] {"x1"});
- test.addInherited(x1y1Parent,new String[] {"x1","y1"});
- test.addInherited(x1y2Parent,new String[] {"x1","y2"});
- test.set("c","c-x1",new String[] {"x1"}, null);
- test.set("e","e-x1y2",new String[] {"x1","y2"}, null);
+ test.addInherited(x1Parent, new String[]{"x1"});
+ test.addInherited(x1y1Parent, new String[]{"x1", "y1"});
+ test.addInherited(x1y2Parent, new String[]{"x1", "y2"});
+ test.set("c", "c-x1", new String[]{"x1"}, null);
+ test.set("e", "e-x1y2", new String[]{"x1", "y2"}, null);
CompiledQueryProfile ctest = test.compile(null);
- assertEquals("a-default",ctest.get("a"));
- assertEquals("a-x1",ctest.get("a", toMap("x=x1")));
- assertEquals("a-x1y1",ctest.get("a", toMap("x=x1", "y=y1")));
- assertEquals("a-x1y2",ctest.get("a", toMap("x=x1", "y=y2")));
+ assertEquals("a-default", ctest.get("a"));
+ assertEquals("a-x1", ctest.get("a", toMap("x=x1")));
+ assertEquals("a-x1y1", ctest.get("a", toMap("x=x1", "y=y1")));
+ assertEquals("a-x1y2", ctest.get("a", toMap("x=x1", "y=y2")));
- assertEquals(null,ctest.get("b"));
- assertEquals(null,ctest.get("b", toMap("x=x1")));
- assertEquals(null,ctest.get("b", toMap("x=x1", "y=y1")));
- assertEquals("b-x1y2",ctest.get("b", toMap("x=x1", "y=y2")));
+ assertNull(ctest.get("b"));
+ assertNull(ctest.get("b", toMap("x=x1")));
+ assertNull(ctest.get("b", toMap("x=x1", "y=y1")));
+ assertEquals("b-x1y2", ctest.get("b", toMap("x=x1", "y=y2")));
- assertEquals(null,ctest.get("c"));
- assertEquals("c-x1",ctest.get("c", toMap("x=x1")));
- assertEquals("c-x1",ctest.get("c", toMap("x=x1", "y=y1")));
- assertEquals("c-x1y2",ctest.get("c", toMap("x=x1", "y=y2")));
+ assertNull(ctest.get("c"));
+ assertEquals("c-x1", ctest.get("c", toMap("x=x1")));
+ assertEquals("c-x1", ctest.get("c", toMap("x=x1", "y=y1")));
+ assertEquals("c-x1y2", ctest.get("c", toMap("x=x1", "y=y2")));
- assertEquals(null,ctest.get("d"));
- assertEquals("d-x1",ctest.get("d", toMap("x=x1")));
+ assertNull(ctest.get("d"));
+ assertEquals("d-x1", ctest.get("d", toMap("x=x1")));
- assertEquals("d-x1",ctest.get("d", toMap("x=x1", "y=y1")));
- assertEquals("d-x1",ctest.get("d", toMap("x=x1", "y=y2")));
+ assertEquals("d-x1", ctest.get("d", toMap("x=x1", "y=y1")));
+ assertEquals("d-x1", ctest.get("d", toMap("x=x1", "y=y2")));
- assertEquals(null,ctest.get("d"));
- assertEquals("e-x1",ctest.get("e", toMap("x=x1")));
- assertEquals("e-x1",ctest.get("e", toMap("x=x1", "y=y1")));
- assertEquals("e-x1y2",ctest.get("e", toMap("x=x1", "y=y2")));
+ assertNull(ctest.get("d"));
+ assertEquals("e-x1", ctest.get("e", toMap("x=x1")));
+ assertEquals("e-x1", ctest.get("e", toMap("x=x1", "y=y1")));
+ assertEquals("e-x1y2", ctest.get("e", toMap("x=x1", "y=y2")));
}
@Test
- public void testVariantInheritanceSimplified() {
- QueryProfile test=new QueryProfile("test");
- test.setDimensions(new String[] {"x","y"});
- QueryProfile x1y2Parent=new QueryProfile("x1y2Parent");
- x1y2Parent.set("c","c-x1y2", null);
- test.addInherited(x1y2Parent,new String[] {"x1","y2"});
- test.set("c","c-x1",new String[] {"x1"}, null);
+ void testVariantInheritanceSimplified() {
+ QueryProfile test = new QueryProfile("test");
+ test.setDimensions(new String[]{"x", "y"});
+ QueryProfile x1y2Parent = new QueryProfile("x1y2Parent");
+ x1y2Parent.set("c", "c-x1y2", null);
+ test.addInherited(x1y2Parent, new String[]{"x1", "y2"});
+ test.set("c", "c-x1", new String[]{"x1"}, null);
CompiledQueryProfile ctest = test.compile(null);
- assertEquals(null,ctest.get("c"));
- assertEquals("c-x1",ctest.get("c", toMap("x=x1")));
+ assertNull(ctest.get("c"));
+ assertEquals("c-x1", ctest.get("c", toMap("x=x1")));
assertEquals("c-x1", ctest.get("c", toMap("x=x1", "y=y1")));
- assertEquals("c-x1y2",ctest.get("c", toMap("x=x1", "y=y2")));
+ assertEquals("c-x1y2", ctest.get("c", toMap("x=x1", "y=y2")));
}
@Test
- public void testVariantInheritanceWithCompoundReferences() {
- QueryProfile test=new QueryProfile("test");
- test.setDimensions(new String[] {"x"});
- test.set("a.b","default-a.b", null);
+ void testVariantInheritanceWithCompoundReferences() {
+ QueryProfile test = new QueryProfile("test");
+ test.setDimensions(new String[]{"x"});
+ test.set("a.b", "default-a.b", null);
- QueryProfile ac=new QueryProfile("ac");
- ac.set("a.c","referenced-a.c", null);
- test.addInherited(ac,new String[] {"x1"});
- test.set("a.b","x1-a.b",new String[] {"x1"}, null);
+ QueryProfile ac = new QueryProfile("ac");
+ ac.set("a.c", "referenced-a.c", null);
+ test.addInherited(ac, new String[]{"x1"});
+ test.set("a.b", "x1-a.b", new String[]{"x1"}, null);
CompiledQueryProfile ctest = test.compile(null);
- assertEquals("Basic functionality","default-a.b",ctest.get("a.b"));
- assertEquals("Inherited variance reference works","referenced-a.c",ctest.get("a.c", toMap("x=x1")));
- assertEquals("Inherited variance reference overriding works","x1-a.b",ctest.get("a.b", toMap("x=x1")));
+ assertEquals("default-a.b", ctest.get("a.b"), "Basic functionality");
+ assertEquals("referenced-a.c", ctest.get("a.c", toMap("x=x1")), "Inherited variance reference works");
+ assertEquals("x1-a.b", ctest.get("a.b", toMap("x=x1")), "Inherited variance reference overriding works");
}
@Test
- public void testVariantInheritanceWithTwoLevelCompoundReferencesVariantAtFirstLevel() {
- QueryProfile test=new QueryProfile("test");
- test.setDimensions(new String[] {"x"});
- test.set("o.a.b","default-a.b", null);
+ void testVariantInheritanceWithTwoLevelCompoundReferencesVariantAtFirstLevel() {
+ QueryProfile test = new QueryProfile("test");
+ test.setDimensions(new String[]{"x"});
+ test.set("o.a.b", "default-a.b", null);
- QueryProfile ac=new QueryProfile("ac");
- ac.set("o.a.c","referenced-a.c", null);
- test.addInherited(ac,new String[] {"x1"});
- test.set("o.a.b","x1-a.b",new String[] {"x1"}, null);
+ QueryProfile ac = new QueryProfile("ac");
+ ac.set("o.a.c", "referenced-a.c", null);
+ test.addInherited(ac, new String[]{"x1"});
+ test.set("o.a.b", "x1-a.b", new String[]{"x1"}, null);
CompiledQueryProfile ctest = test.compile(null);
- assertEquals("Basic functionality","default-a.b",ctest.get("o.a.b"));
- assertEquals("Inherited variance reference works","referenced-a.c",ctest.get("o.a.c", toMap("x=x1")));
- assertEquals("Inherited variance reference overriding works","x1-a.b",ctest.get("o.a.b", toMap("x=x1")));
+ assertEquals("default-a.b", ctest.get("o.a.b"), "Basic functionality");
+ assertEquals("referenced-a.c", ctest.get("o.a.c", toMap("x=x1")), "Inherited variance reference works");
+ assertEquals("x1-a.b", ctest.get("o.a.b", toMap("x=x1")), "Inherited variance reference overriding works");
}
@Test
- public void testVariantInheritanceWithTwoLevelCompoundReferencesVariantAtSecondLevel() {
- QueryProfile test=new QueryProfile("test");
- test.setDimensions(new String[] {"x"});
+ void testVariantInheritanceWithTwoLevelCompoundReferencesVariantAtSecondLevel() {
+ QueryProfile test = new QueryProfile("test");
+ test.setDimensions(new String[]{"x"});
- QueryProfile ac=new QueryProfile("ac");
- ac.set("a.c","referenced-a.c", null);
- test.addInherited(ac,new String[] {"x1"});
- test.set("a.b","x1-a.b",new String[] {"x1"}, null);
+ QueryProfile ac = new QueryProfile("ac");
+ ac.set("a.c", "referenced-a.c", null);
+ test.addInherited(ac, new String[]{"x1"});
+ test.set("a.b", "x1-a.b", new String[]{"x1"}, null);
- QueryProfile top=new QueryProfile("top");
- top.set("o.a.b","default-a.b", null);
- top.set("o",test, null);
+ QueryProfile top = new QueryProfile("top");
+ top.set("o.a.b", "default-a.b", null);
+ top.set("o", test, null);
CompiledQueryProfile ctop = top.compile(null);
- assertEquals("Basic functionality","default-a.b",ctop.get("o.a.b"));
- assertEquals("Inherited variance reference works","referenced-a.c",ctop.get("o.a.c", toMap("x=x1")));
- assertEquals("Inherited variance reference does not override value set in referent","default-a.b",ctop.get("o.a.b", toMap("x=x1"))); // Note: Changed from x1-a.b in 4.2.3
+ assertEquals("default-a.b", ctop.get("o.a.b"), "Basic functionality");
+ assertEquals("referenced-a.c", ctop.get("o.a.c", toMap("x=x1")), "Inherited variance reference works");
+ assertEquals("default-a.b", ctop.get("o.a.b", toMap("x=x1")), "Inherited variance reference does not override value set in referent"); // Note: Changed from x1-a.b in 4.2.3
}
@Test
- public void testVariantInheritanceOverridesBaseInheritance1() {
- QueryProfile test=new QueryProfile("test");
- QueryProfile baseInherited=new QueryProfile("baseInherited");
- baseInherited.set("a.b","baseInherited-a.b", null);
- QueryProfile variantInherited=new QueryProfile("variantInherited");
- variantInherited.set("a.b","variantInherited-a.b", null);
- test.setDimensions(new String[] {"x"});
+ void testVariantInheritanceOverridesBaseInheritance1() {
+ QueryProfile test = new QueryProfile("test");
+ QueryProfile baseInherited = new QueryProfile("baseInherited");
+ baseInherited.set("a.b", "baseInherited-a.b", null);
+ QueryProfile variantInherited = new QueryProfile("variantInherited");
+ variantInherited.set("a.b", "variantInherited-a.b", null);
+ test.setDimensions(new String[]{"x"});
test.addInherited(baseInherited);
- test.addInherited(variantInherited,new String[] {"x1"});
+ test.addInherited(variantInherited, new String[]{"x1"});
CompiledQueryProfile ctest = test.compile(null);
- assertEquals("baseInherited-a.b",ctest.get("a.b"));
- assertEquals("variantInherited-a.b",ctest.get("a.b",toMap("x=x1")));
+ assertEquals("baseInherited-a.b", ctest.get("a.b"));
+ assertEquals("variantInherited-a.b", ctest.get("a.b", toMap("x=x1")));
}
@Test
- public void testVariantInheritanceOverridesBaseInheritance2() {
- QueryProfile test=new QueryProfile("test");
- QueryProfile baseInherited=new QueryProfile("baseInherited");
- baseInherited.set("a.b","baseInherited-a.b", null);
- QueryProfile variantInherited=new QueryProfile("variantInherited");
- variantInherited.set("a.b","variantInherited-a.b", null);
- test.setDimensions(new String[] {"x"});
+ void testVariantInheritanceOverridesBaseInheritance2() {
+ QueryProfile test = new QueryProfile("test");
+ QueryProfile baseInherited = new QueryProfile("baseInherited");
+ baseInherited.set("a.b", "baseInherited-a.b", null);
+ QueryProfile variantInherited = new QueryProfile("variantInherited");
+ variantInherited.set("a.b", "variantInherited-a.b", null);
+ test.setDimensions(new String[]{"x"});
test.addInherited(baseInherited);
- test.addInherited(variantInherited,new String[] {"x1"});
- test.set("a.c","variant-a.c",new String[] {"x1"}, null);
+ test.addInherited(variantInherited, new String[]{"x1"});
+ test.set("a.c", "variant-a.c", new String[]{"x1"}, null);
CompiledQueryProfile ctest = test.compile(null);
- assertEquals("baseInherited-a.b",ctest.get("a.b"));
- assertEquals("variantInherited-a.b",ctest.get("a.b", toMap("x=x1")));
- assertEquals("variant-a.c",ctest.get("a.c", toMap("x=x1")));
+ assertEquals("baseInherited-a.b", ctest.get("a.b"));
+ assertEquals("variantInherited-a.b", ctest.get("a.b", toMap("x=x1")));
+ assertEquals("variant-a.c", ctest.get("a.c", toMap("x=x1")));
}
@Test
- public void testVariantInheritanceOverridesBaseInheritanceComplex() {
- QueryProfile defaultQP=new QueryProfile("default");
- defaultQP.set("model.defaultIndex","title", null);
+ void testVariantInheritanceOverridesBaseInheritanceComplex() {
+ QueryProfile defaultQP = new QueryProfile("default");
+ defaultQP.set("model.defaultIndex", "title", null);
- QueryProfile root=new QueryProfile("root");
+ QueryProfile root = new QueryProfile("root");
root.addInherited(defaultQP);
- root.set("model.defaultIndex","default", null);
+ root.set("model.defaultIndex", "default", null);
- QueryProfile querybest=new QueryProfile("querybest");
- querybest.set("defaultIndex","title", null);
- querybest.set("queryString","best", null);
+ QueryProfile querybest = new QueryProfile("querybest");
+ querybest.set("defaultIndex", "title", null);
+ querybest.set("queryString", "best", null);
- QueryProfile multi=new QueryProfile("multi");
- multi.setDimensions(new String[] {"x"});
+ QueryProfile multi = new QueryProfile("multi");
+ multi.setDimensions(new String[]{"x"});
multi.addInherited(defaultQP);
- multi.set("model",querybest, null);
- multi.addInherited(root,new String[] {"x1"});
- multi.set("model.queryString","love",new String[] {"x1"}, null);
+ multi.set("model", querybest, null);
+ multi.addInherited(root, new String[]{"x1"});
+ multi.set("model.queryString", "love", new String[]{"x1"}, null);
// Rumtimize
defaultQP.freeze();
@@ -746,461 +745,461 @@ public class QueryProfileVariantsTestCase {
multi.freeze();
Properties runtime = new QueryProfileProperties(multi.compile(null));
- assertEquals("default",runtime.get("model.defaultIndex", toMap("x=x1")));
- assertEquals("love",runtime.get("model.queryString", toMap("x=x1")));
+ assertEquals("default", runtime.get("model.defaultIndex", toMap("x=x1")));
+ assertEquals("love", runtime.get("model.queryString", toMap("x=x1")));
}
@Test
- public void testVariantInheritanceOverridesBaseInheritanceComplexSimplified() {
- QueryProfile root=new QueryProfile("root");
- root.set("model.defaultIndex","default", null);
+ void testVariantInheritanceOverridesBaseInheritanceComplexSimplified() {
+ QueryProfile root = new QueryProfile("root");
+ root.set("model.defaultIndex", "default", null);
- QueryProfile multi=new QueryProfile("multi");
- multi.setDimensions(new String[] {"x"});
- multi.set("model.defaultIndex","title", null);
- multi.addInherited(root,new String[] {"x1"});
+ QueryProfile multi = new QueryProfile("multi");
+ multi.setDimensions(new String[]{"x"});
+ multi.set("model.defaultIndex", "title", null);
+ multi.addInherited(root, new String[]{"x1"});
- assertEquals("default",multi.compile(null).get("model.defaultIndex", toMap("x=x1")));
+ assertEquals("default", multi.compile(null).get("model.defaultIndex", toMap("x=x1")));
}
@Test
- public void testVariantInheritanceOverridesBaseInheritanceMixed() {
- QueryProfile root=new QueryProfile("root");
- root.set("model.defaultIndex","default", null);
+ void testVariantInheritanceOverridesBaseInheritanceMixed() {
+ QueryProfile root = new QueryProfile("root");
+ root.set("model.defaultIndex", "default", null);
- QueryProfile multi=new QueryProfile("multi");
- multi.setDimensions(new String[] {"x"});
- multi.set("model.defaultIndex","title", null);
- multi.set("model.queryString","modelQuery", null);
- multi.addInherited(root,new String[] {"x1"});
- multi.set("model.queryString","modelVariantQuery",new String[] {"x1"}, null);
+ QueryProfile multi = new QueryProfile("multi");
+ multi.setDimensions(new String[]{"x"});
+ multi.set("model.defaultIndex", "title", null);
+ multi.set("model.queryString", "modelQuery", null);
+ multi.addInherited(root, new String[]{"x1"});
+ multi.set("model.queryString", "modelVariantQuery", new String[]{"x1"}, null);
CompiledQueryProfile cmulti = multi.compile(null);
- assertEquals("default",cmulti.get("model.defaultIndex", toMap("x=x1")));
- assertEquals("modelVariantQuery",cmulti.get("model.queryString", toMap("x=x1")));
+ assertEquals("default", cmulti.get("model.defaultIndex", toMap("x=x1")));
+ assertEquals("modelVariantQuery", cmulti.get("model.queryString", toMap("x=x1")));
}
@Test
- public void testListVariantPropertiesNoCompounds() {
- QueryProfile parent1=new QueryProfile("parent1");
- parent1.set("a","parent1-a", null); // Defined everywhere
- parent1.set("b","parent1-b", null); // Defined everywhere, but no variants
- parent1.set("c","parent1-c", null); // Defined in both parents only
-
- QueryProfile parent2=new QueryProfile("parent2");
- parent2.set("a","parent2-a", null);
- parent2.set("b","parent2-b", null);
- parent2.set("c","parent2-c", null);
- parent2.set("d","parent2-d", null); // Defined in second parent only
-
- QueryProfile main=new QueryProfile("main");
- main.setDimensions(new String[] {"x","y"});
+ void testListVariantPropertiesNoCompounds() {
+ QueryProfile parent1 = new QueryProfile("parent1");
+ parent1.set("a", "parent1-a", null); // Defined everywhere
+ parent1.set("b", "parent1-b", null); // Defined everywhere, but no variants
+ parent1.set("c", "parent1-c", null); // Defined in both parents only
+
+ QueryProfile parent2 = new QueryProfile("parent2");
+ parent2.set("a", "parent2-a", null);
+ parent2.set("b", "parent2-b", null);
+ parent2.set("c", "parent2-c", null);
+ parent2.set("d", "parent2-d", null); // Defined in second parent only
+
+ QueryProfile main = new QueryProfile("main");
+ main.setDimensions(new String[]{"x", "y"});
main.addInherited(parent1);
main.addInherited(parent2);
- main.set("a","main-a", null);
- main.set("a","main-a-x1",new String[] {"x1"}, null);
- main.set("e","main-e-x1",new String[] {"x1"}, null); // Defined in two variants only
- main.set("f","main-f-x1",new String[] {"x1"}, null); // Defined in one variants only
- main.set("a","main-a-x1.y1",new String[] {"x1","y1"}, null);
- main.set("a","main-a-x1.y2",new String[] {"x1","y2"}, null);
- main.set("e","main-e-x1.y2",new String[] {"x1","y2"}, null);
- main.set("g","main-g-x1.y2",new String[] {"x1","y2"}, null); // Defined in one variant only
- main.set("b","main-b", null);
-
- QueryProfile inheritedVariant1=new QueryProfile("inheritedVariant1");
- inheritedVariant1.set("a","inheritedVariant1-a", null);
- inheritedVariant1.set("h","inheritedVariant1-h", null); // Only defined in two inherited variants
-
- QueryProfile inheritedVariant2=new QueryProfile("inheritedVariant2");
- inheritedVariant2.set("a","inheritedVariant2-a", null);
- inheritedVariant2.set("h","inheritedVariant2-h", null); // Only defined in two inherited variants
- inheritedVariant2.set("i","inheritedVariant2-i", null); // Only defined in one inherited variant
-
- QueryProfile inheritedVariant3=new QueryProfile("inheritedVariant3");
- inheritedVariant3.set("j","inheritedVariant3-j", null); // Only defined in one inherited variant, but inherited twice
-
- main.addInherited(inheritedVariant1,new String[] {"x1"});
- main.addInherited(inheritedVariant3,new String[] {"x1"});
- main.addInherited(inheritedVariant2,new String[] {"x1","y2"});
- main.addInherited(inheritedVariant3,new String[] {"x1","y2"});
+ main.set("a", "main-a", null);
+ main.set("a", "main-a-x1", new String[]{"x1"}, null);
+ main.set("e", "main-e-x1", new String[]{"x1"}, null); // Defined in two variants only
+ main.set("f", "main-f-x1", new String[]{"x1"}, null); // Defined in one variants only
+ main.set("a", "main-a-x1.y1", new String[]{"x1", "y1"}, null);
+ main.set("a", "main-a-x1.y2", new String[]{"x1", "y2"}, null);
+ main.set("e", "main-e-x1.y2", new String[]{"x1", "y2"}, null);
+ main.set("g", "main-g-x1.y2", new String[]{"x1", "y2"}, null); // Defined in one variant only
+ main.set("b", "main-b", null);
+
+ QueryProfile inheritedVariant1 = new QueryProfile("inheritedVariant1");
+ inheritedVariant1.set("a", "inheritedVariant1-a", null);
+ inheritedVariant1.set("h", "inheritedVariant1-h", null); // Only defined in two inherited variants
+
+ QueryProfile inheritedVariant2 = new QueryProfile("inheritedVariant2");
+ inheritedVariant2.set("a", "inheritedVariant2-a", null);
+ inheritedVariant2.set("h", "inheritedVariant2-h", null); // Only defined in two inherited variants
+ inheritedVariant2.set("i", "inheritedVariant2-i", null); // Only defined in one inherited variant
+
+ QueryProfile inheritedVariant3 = new QueryProfile("inheritedVariant3");
+ inheritedVariant3.set("j", "inheritedVariant3-j", null); // Only defined in one inherited variant, but inherited twice
+
+ main.addInherited(inheritedVariant1, new String[]{"x1"});
+ main.addInherited(inheritedVariant3, new String[]{"x1"});
+ main.addInherited(inheritedVariant2, new String[]{"x1", "y2"});
+ main.addInherited(inheritedVariant3, new String[]{"x1", "y2"});
// Runtime-ify
- Properties properties=new QueryProfileProperties(main.compile(null));
+ Properties properties = new QueryProfileProperties(main.compile(null));
- int expectedBaseSize=4;
+ int expectedBaseSize = 4;
// No context
- Map<String,Object> listed=properties.listProperties();
- assertEquals(expectedBaseSize,listed.size());
- assertEquals("main-a",listed.get("a"));
- assertEquals("main-b",listed.get("b"));
- assertEquals("parent1-c",listed.get("c"));
- assertEquals("parent2-d",listed.get("d"));
+ Map<String, Object> listed = properties.listProperties();
+ assertEquals(expectedBaseSize, listed.size());
+ assertEquals("main-a", listed.get("a"));
+ assertEquals("main-b", listed.get("b"));
+ assertEquals("parent1-c", listed.get("c"));
+ assertEquals("parent2-d", listed.get("d"));
// Context x=x1
- listed=properties.listProperties(toMap(main, new String[] {"x1"}));
- assertEquals(expectedBaseSize+4,listed.size());
- assertEquals("main-a-x1",listed.get("a"));
- assertEquals("main-b",listed.get("b"));
- assertEquals("parent1-c",listed.get("c"));
- assertEquals("parent2-d",listed.get("d"));
- assertEquals("main-e-x1",listed.get("e"));
- assertEquals("main-f-x1",listed.get("f"));
- assertEquals("inheritedVariant1-h",listed.get("h"));
- assertEquals("inheritedVariant3-j",listed.get("j"));
+ listed = properties.listProperties(toMap(main, new String[]{"x1"}));
+ assertEquals(expectedBaseSize + 4, listed.size());
+ assertEquals("main-a-x1", listed.get("a"));
+ assertEquals("main-b", listed.get("b"));
+ assertEquals("parent1-c", listed.get("c"));
+ assertEquals("parent2-d", listed.get("d"));
+ assertEquals("main-e-x1", listed.get("e"));
+ assertEquals("main-f-x1", listed.get("f"));
+ assertEquals("inheritedVariant1-h", listed.get("h"));
+ assertEquals("inheritedVariant3-j", listed.get("j"));
// Context x=x1,y=y1
- listed=properties.listProperties(toMap(main, new String[] {"x1","y1"}));
- assertEquals(expectedBaseSize+4,listed.size());
- assertEquals("main-a-x1.y1",listed.get("a"));
- assertEquals("main-b",listed.get("b"));
- assertEquals("parent1-c",listed.get("c"));
- assertEquals("parent2-d",listed.get("d"));
- assertEquals("main-e-x1",listed.get("e"));
- assertEquals("main-f-x1",listed.get("f"));
- assertEquals("inheritedVariant1-h",listed.get("h"));
- assertEquals("inheritedVariant3-j",listed.get("j"));
+ listed = properties.listProperties(toMap(main, new String[]{"x1", "y1"}));
+ assertEquals(expectedBaseSize + 4, listed.size());
+ assertEquals("main-a-x1.y1", listed.get("a"));
+ assertEquals("main-b", listed.get("b"));
+ assertEquals("parent1-c", listed.get("c"));
+ assertEquals("parent2-d", listed.get("d"));
+ assertEquals("main-e-x1", listed.get("e"));
+ assertEquals("main-f-x1", listed.get("f"));
+ assertEquals("inheritedVariant1-h", listed.get("h"));
+ assertEquals("inheritedVariant3-j", listed.get("j"));
// Context x=x1,y=y2
- listed=properties.listProperties(toMap(main, new String[] {"x1","y2"}));
- assertEquals(expectedBaseSize+6,listed.size());
- assertEquals("main-a-x1.y2",listed.get("a"));
- assertEquals("main-b",listed.get("b"));
- assertEquals("parent1-c",listed.get("c"));
- assertEquals("parent2-d",listed.get("d"));
- assertEquals("main-e-x1.y2",listed.get("e"));
- assertEquals("main-f-x1",listed.get("f"));
- assertEquals("main-g-x1.y2",listed.get("g"));
- assertEquals("inheritedVariant2-h",listed.get("h"));
- assertEquals("inheritedVariant2-i",listed.get("i"));
- assertEquals("inheritedVariant3-j",listed.get("j"));
+ listed = properties.listProperties(toMap(main, new String[]{"x1", "y2"}));
+ assertEquals(expectedBaseSize + 6, listed.size());
+ assertEquals("main-a-x1.y2", listed.get("a"));
+ assertEquals("main-b", listed.get("b"));
+ assertEquals("parent1-c", listed.get("c"));
+ assertEquals("parent2-d", listed.get("d"));
+ assertEquals("main-e-x1.y2", listed.get("e"));
+ assertEquals("main-f-x1", listed.get("f"));
+ assertEquals("main-g-x1.y2", listed.get("g"));
+ assertEquals("inheritedVariant2-h", listed.get("h"));
+ assertEquals("inheritedVariant2-i", listed.get("i"));
+ assertEquals("inheritedVariant3-j", listed.get("j"));
// Context x=x1,y=y3
- listed=properties.listProperties(toMap(main, new String[] {"x1","y3"}));
- assertEquals(expectedBaseSize+4,listed.size());
- assertEquals("main-a-x1",listed.get("a"));
- assertEquals("main-b",listed.get("b"));
- assertEquals("parent1-c",listed.get("c"));
- assertEquals("parent2-d",listed.get("d"));
- assertEquals("main-e-x1",listed.get("e"));
- assertEquals("main-f-x1",listed.get("f"));
- assertEquals("inheritedVariant1-h",listed.get("h"));
- assertEquals("inheritedVariant3-j",listed.get("j"));
+ listed = properties.listProperties(toMap(main, new String[]{"x1", "y3"}));
+ assertEquals(expectedBaseSize + 4, listed.size());
+ assertEquals("main-a-x1", listed.get("a"));
+ assertEquals("main-b", listed.get("b"));
+ assertEquals("parent1-c", listed.get("c"));
+ assertEquals("parent2-d", listed.get("d"));
+ assertEquals("main-e-x1", listed.get("e"));
+ assertEquals("main-f-x1", listed.get("f"));
+ assertEquals("inheritedVariant1-h", listed.get("h"));
+ assertEquals("inheritedVariant3-j", listed.get("j"));
// Context x=x2,y=y1
- listed=properties.listProperties(toMap(main, new String[] {"x2","y1"}));
- assertEquals(expectedBaseSize,listed.size());
- assertEquals("main-a",listed.get("a"));
- assertEquals("main-b",listed.get("b"));
- assertEquals("parent1-c",listed.get("c"));
- assertEquals("parent2-d",listed.get("d"));
+ listed = properties.listProperties(toMap(main, new String[]{"x2", "y1"}));
+ assertEquals(expectedBaseSize, listed.size());
+ assertEquals("main-a", listed.get("a"));
+ assertEquals("main-b", listed.get("b"));
+ assertEquals("parent1-c", listed.get("c"));
+ assertEquals("parent2-d", listed.get("d"));
}
@Test
- public void testListVariantPropertiesCompounds1Simplified() {
- QueryProfile main=new QueryProfile("main");
- main.setDimensions(new String[] {"x","y"});
- main.set("a.p1","main-a-x1",new String[] {"x1"}, null);
+ void testListVariantPropertiesCompounds1Simplified() {
+ QueryProfile main = new QueryProfile("main");
+ main.setDimensions(new String[]{"x", "y"});
+ main.set("a.p1", "main-a-x1", new String[]{"x1"}, null);
- QueryProfile inheritedVariant1=new QueryProfile("inheritedVariant1");
- inheritedVariant1.set("a.p1","inheritedVariant1-a", null);
- main.addInherited(inheritedVariant1,new String[] {"x1"});
+ QueryProfile inheritedVariant1 = new QueryProfile("inheritedVariant1");
+ inheritedVariant1.set("a.p1", "inheritedVariant1-a", null);
+ main.addInherited(inheritedVariant1, new String[]{"x1"});
- Properties properties=new QueryProfileProperties(main.compile(null));
+ Properties properties = new QueryProfileProperties(main.compile(null));
// Context x=x1
- Map<String,Object> listed=properties.listProperties(toMap(main,new String[] {"x1"}));
- assertEquals("main-a-x1",listed.get("a.p1"));
+ Map<String, Object> listed = properties.listProperties(toMap(main, new String[]{"x1"}));
+ assertEquals("main-a-x1", listed.get("a.p1"));
}
@Test
- public void testListVariantPropertiesCompounds1() {
- QueryProfile parent1=new QueryProfile("parent1");
- parent1.set("a.p1","parent1-a", null); // Defined everywhere
- parent1.set("b.p1","parent1-b", null); // Defined everywhere, but no variants
- parent1.set("c.p1","parent1-c", null); // Defined in both parents only
-
- QueryProfile parent2=new QueryProfile("parent2");
- parent2.set("a.p1","parent2-a", null);
- parent2.set("b.p1","parent2-b", null);
- parent2.set("c.p1","parent2-c", null);
- parent2.set("d.p1","parent2-d", null); // Defined in second parent only
-
- QueryProfile main=new QueryProfile("main");
- main.setDimensions(new String[] {"x","y"});
+ void testListVariantPropertiesCompounds1() {
+ QueryProfile parent1 = new QueryProfile("parent1");
+ parent1.set("a.p1", "parent1-a", null); // Defined everywhere
+ parent1.set("b.p1", "parent1-b", null); // Defined everywhere, but no variants
+ parent1.set("c.p1", "parent1-c", null); // Defined in both parents only
+
+ QueryProfile parent2 = new QueryProfile("parent2");
+ parent2.set("a.p1", "parent2-a", null);
+ parent2.set("b.p1", "parent2-b", null);
+ parent2.set("c.p1", "parent2-c", null);
+ parent2.set("d.p1", "parent2-d", null); // Defined in second parent only
+
+ QueryProfile main = new QueryProfile("main");
+ main.setDimensions(new String[]{"x", "y"});
main.addInherited(parent1);
main.addInherited(parent2);
- main.set("a.p1","main-a", null);
- main.set("a.p1","main-a-x1",new String[] {"x1"}, null);
- main.set("e.p1","main-e-x1",new String[] {"x1"}, null); // Defined in two variants only
- main.set("f.p1","main-f-x1",new String[] {"x1"}, null); // Defined in one variants only
- main.set("a.p1","main-a-x1.y1",new String[] {"x1","y1"}, null);
- main.set("a.p1","main-a-x1.y2",new String[] {"x1","y2"}, null);
- main.set("e.p1","main-e-x1.y2",new String[] {"x1","y2"}, null);
- main.set("g.p1","main-g-x1.y2",new String[] {"x1","y2"}, null); // Defined in one variant only
- main.set("b.p1","main-b", null);
+ main.set("a.p1", "main-a", null);
+ main.set("a.p1", "main-a-x1", new String[]{"x1"}, null);
+ main.set("e.p1", "main-e-x1", new String[]{"x1"}, null); // Defined in two variants only
+ main.set("f.p1", "main-f-x1", new String[]{"x1"}, null); // Defined in one variants only
+ main.set("a.p1", "main-a-x1.y1", new String[]{"x1", "y1"}, null);
+ main.set("a.p1", "main-a-x1.y2", new String[]{"x1", "y2"}, null);
+ main.set("e.p1", "main-e-x1.y2", new String[]{"x1", "y2"}, null);
+ main.set("g.p1", "main-g-x1.y2", new String[]{"x1", "y2"}, null); // Defined in one variant only
+ main.set("b.p1", "main-b", null);
+
+ QueryProfile inheritedVariant1 = new QueryProfile("inheritedVariant1");
+ inheritedVariant1.set("a.p1", "inheritedVariant1-a", null);
+ inheritedVariant1.set("h.p1", "inheritedVariant1-h", null); // Only defined in two inherited variants
+
+ QueryProfile inheritedVariant2 = new QueryProfile("inheritedVariant2");
+ inheritedVariant2.set("a.p1", "inheritedVariant2-a", null);
+ inheritedVariant2.set("h.p1", "inheritedVariant2-h", null); // Only defined in two inherited variants
+ inheritedVariant2.set("i.p1", "inheritedVariant2-i", null); // Only defined in one inherited variant
+
+ QueryProfile inheritedVariant3 = new QueryProfile("inheritedVariant3");
+ inheritedVariant3.set("j.p1", "inheritedVariant3-j", null); // Only defined in one inherited variant, but inherited twice
+
+ main.addInherited(inheritedVariant1, new String[]{"x1"});
+ main.addInherited(inheritedVariant3, new String[]{"x1"});
+ main.addInherited(inheritedVariant2, new String[]{"x1", "y2"});
+ main.addInherited(inheritedVariant3, new String[]{"x1", "y2"});
- QueryProfile inheritedVariant1=new QueryProfile("inheritedVariant1");
- inheritedVariant1.set("a.p1","inheritedVariant1-a", null);
- inheritedVariant1.set("h.p1","inheritedVariant1-h", null); // Only defined in two inherited variants
-
- QueryProfile inheritedVariant2=new QueryProfile("inheritedVariant2");
- inheritedVariant2.set("a.p1","inheritedVariant2-a", null);
- inheritedVariant2.set("h.p1","inheritedVariant2-h", null); // Only defined in two inherited variants
- inheritedVariant2.set("i.p1","inheritedVariant2-i", null); // Only defined in one inherited variant
-
- QueryProfile inheritedVariant3=new QueryProfile("inheritedVariant3");
- inheritedVariant3.set("j.p1","inheritedVariant3-j", null); // Only defined in one inherited variant, but inherited twice
-
- main.addInherited(inheritedVariant1,new String[] {"x1"});
- main.addInherited(inheritedVariant3,new String[] {"x1"});
- main.addInherited(inheritedVariant2,new String[] {"x1","y2"});
- main.addInherited(inheritedVariant3,new String[] {"x1","y2"});
-
- Properties properties=new QueryProfileProperties(main.compile(null));
+ Properties properties = new QueryProfileProperties(main.compile(null));
- int expectedBaseSize=4;
+ int expectedBaseSize = 4;
// No context
- Map<String,Object> listed=properties.listProperties();
- assertEquals(expectedBaseSize,listed.size());
- assertEquals("main-a",listed.get("a.p1"));
- assertEquals("main-b",listed.get("b.p1"));
- assertEquals("parent1-c",listed.get("c.p1"));
- assertEquals("parent2-d",listed.get("d.p1"));
+ Map<String, Object> listed = properties.listProperties();
+ assertEquals(expectedBaseSize, listed.size());
+ assertEquals("main-a", listed.get("a.p1"));
+ assertEquals("main-b", listed.get("b.p1"));
+ assertEquals("parent1-c", listed.get("c.p1"));
+ assertEquals("parent2-d", listed.get("d.p1"));
// Context x=x1
- listed=properties.listProperties(toMap(main,new String[] {"x1"}));
- assertEquals(expectedBaseSize+4,listed.size());
- assertEquals("main-a-x1",listed.get("a.p1"));
- assertEquals("main-b",listed.get("b.p1"));
- assertEquals("parent1-c",listed.get("c.p1"));
- assertEquals("parent2-d",listed.get("d.p1"));
- assertEquals("main-e-x1",listed.get("e.p1"));
- assertEquals("main-f-x1",listed.get("f.p1"));
- assertEquals("inheritedVariant1-h",listed.get("h.p1"));
- assertEquals("inheritedVariant3-j",listed.get("j.p1"));
+ listed = properties.listProperties(toMap(main, new String[]{"x1"}));
+ assertEquals(expectedBaseSize + 4, listed.size());
+ assertEquals("main-a-x1", listed.get("a.p1"));
+ assertEquals("main-b", listed.get("b.p1"));
+ assertEquals("parent1-c", listed.get("c.p1"));
+ assertEquals("parent2-d", listed.get("d.p1"));
+ assertEquals("main-e-x1", listed.get("e.p1"));
+ assertEquals("main-f-x1", listed.get("f.p1"));
+ assertEquals("inheritedVariant1-h", listed.get("h.p1"));
+ assertEquals("inheritedVariant3-j", listed.get("j.p1"));
// Context x=x1,y=y1
- listed=properties.listProperties(toMap(main,new String[] {"x1","y1"}));
- assertEquals(expectedBaseSize+4,listed.size());
- assertEquals("main-a-x1.y1",listed.get("a.p1"));
- assertEquals("main-b",listed.get("b.p1"));
- assertEquals("parent1-c",listed.get("c.p1"));
- assertEquals("parent2-d",listed.get("d.p1"));
- assertEquals("main-e-x1",listed.get("e.p1"));
- assertEquals("main-f-x1",listed.get("f.p1"));
- assertEquals("inheritedVariant1-h",listed.get("h.p1"));
- assertEquals("inheritedVariant3-j",listed.get("j.p1"));
+ listed = properties.listProperties(toMap(main, new String[]{"x1", "y1"}));
+ assertEquals(expectedBaseSize + 4, listed.size());
+ assertEquals("main-a-x1.y1", listed.get("a.p1"));
+ assertEquals("main-b", listed.get("b.p1"));
+ assertEquals("parent1-c", listed.get("c.p1"));
+ assertEquals("parent2-d", listed.get("d.p1"));
+ assertEquals("main-e-x1", listed.get("e.p1"));
+ assertEquals("main-f-x1", listed.get("f.p1"));
+ assertEquals("inheritedVariant1-h", listed.get("h.p1"));
+ assertEquals("inheritedVariant3-j", listed.get("j.p1"));
// Context x=x1,y=y2
- listed=properties.listProperties(toMap(main,new String[] {"x1","y2"}));
- assertEquals(expectedBaseSize+6,listed.size());
- assertEquals("main-a-x1.y2",listed.get("a.p1"));
- assertEquals("main-b",listed.get("b.p1"));
- assertEquals("parent1-c",listed.get("c.p1"));
- assertEquals("parent2-d",listed.get("d.p1"));
- assertEquals("main-e-x1.y2",listed.get("e.p1"));
- assertEquals("main-f-x1",listed.get("f.p1"));
- assertEquals("main-g-x1.y2",listed.get("g.p1"));
- assertEquals("inheritedVariant2-h",listed.get("h.p1"));
- assertEquals("inheritedVariant2-i",listed.get("i.p1"));
- assertEquals("inheritedVariant3-j",listed.get("j.p1"));
+ listed = properties.listProperties(toMap(main, new String[]{"x1", "y2"}));
+ assertEquals(expectedBaseSize + 6, listed.size());
+ assertEquals("main-a-x1.y2", listed.get("a.p1"));
+ assertEquals("main-b", listed.get("b.p1"));
+ assertEquals("parent1-c", listed.get("c.p1"));
+ assertEquals("parent2-d", listed.get("d.p1"));
+ assertEquals("main-e-x1.y2", listed.get("e.p1"));
+ assertEquals("main-f-x1", listed.get("f.p1"));
+ assertEquals("main-g-x1.y2", listed.get("g.p1"));
+ assertEquals("inheritedVariant2-h", listed.get("h.p1"));
+ assertEquals("inheritedVariant2-i", listed.get("i.p1"));
+ assertEquals("inheritedVariant3-j", listed.get("j.p1"));
// Context x=x1,y=y3
- listed=properties.listProperties(toMap(main,new String[] {"x1","y3"}));
- assertEquals(expectedBaseSize+4,listed.size());
- assertEquals("main-a-x1",listed.get("a.p1"));
- assertEquals("main-b",listed.get("b.p1"));
- assertEquals("parent1-c",listed.get("c.p1"));
- assertEquals("parent2-d",listed.get("d.p1"));
- assertEquals("main-e-x1",listed.get("e.p1"));
- assertEquals("main-f-x1",listed.get("f.p1"));
- assertEquals("inheritedVariant1-h",listed.get("h.p1"));
- assertEquals("inheritedVariant3-j",listed.get("j.p1"));
+ listed = properties.listProperties(toMap(main, new String[]{"x1", "y3"}));
+ assertEquals(expectedBaseSize + 4, listed.size());
+ assertEquals("main-a-x1", listed.get("a.p1"));
+ assertEquals("main-b", listed.get("b.p1"));
+ assertEquals("parent1-c", listed.get("c.p1"));
+ assertEquals("parent2-d", listed.get("d.p1"));
+ assertEquals("main-e-x1", listed.get("e.p1"));
+ assertEquals("main-f-x1", listed.get("f.p1"));
+ assertEquals("inheritedVariant1-h", listed.get("h.p1"));
+ assertEquals("inheritedVariant3-j", listed.get("j.p1"));
// Context x=x2,y=y1
- listed=properties.listProperties(toMap(main,new String[] {"x2","y1"}));
- assertEquals(expectedBaseSize,listed.size());
- assertEquals("main-a",listed.get("a.p1"));
- assertEquals("main-b",listed.get("b.p1"));
- assertEquals("parent1-c",listed.get("c.p1"));
- assertEquals("parent2-d",listed.get("d.p1"));
+ listed = properties.listProperties(toMap(main, new String[]{"x2", "y1"}));
+ assertEquals(expectedBaseSize, listed.size());
+ assertEquals("main-a", listed.get("a.p1"));
+ assertEquals("main-b", listed.get("b.p1"));
+ assertEquals("parent1-c", listed.get("c.p1"));
+ assertEquals("parent2-d", listed.get("d.p1"));
}
@Test
- public void testListVariantPropertiesCompounds2() {
- QueryProfile parent1=new QueryProfile("parent1");
- parent1.set("p1.a","parent1-a", null); // Defined everywhere
- parent1.set("p1.b","parent1-b", null); // Defined everywhere, but no variants
- parent1.set("p1.c","parent1-c", null); // Defined in both parents only
-
- QueryProfile parent2=new QueryProfile("parent2");
- parent2.set("p1.a","parent2-a", null);
- parent2.set("p1.b","parent2-b", null);
- parent2.set("p1.c","parent2-c", null);
- parent2.set("p1.d","parent2-d", null); // Defined in second parent only
-
- QueryProfile main=new QueryProfile("main");
- main.setDimensions(new String[] {"x","y"});
+ void testListVariantPropertiesCompounds2() {
+ QueryProfile parent1 = new QueryProfile("parent1");
+ parent1.set("p1.a", "parent1-a", null); // Defined everywhere
+ parent1.set("p1.b", "parent1-b", null); // Defined everywhere, but no variants
+ parent1.set("p1.c", "parent1-c", null); // Defined in both parents only
+
+ QueryProfile parent2 = new QueryProfile("parent2");
+ parent2.set("p1.a", "parent2-a", null);
+ parent2.set("p1.b", "parent2-b", null);
+ parent2.set("p1.c", "parent2-c", null);
+ parent2.set("p1.d", "parent2-d", null); // Defined in second parent only
+
+ QueryProfile main = new QueryProfile("main");
+ main.setDimensions(new String[]{"x", "y"});
main.addInherited(parent1);
main.addInherited(parent2);
- main.set("p1.a","main-a", null);
- main.set("p1.a","main-a-x1",new String[] {"x1"}, null);
- main.set("p1.e","main-e-x1",new String[] {"x1"}, null); // Defined in two variants only
- main.set("p1.f","main-f-x1",new String[] {"x1"}, null); // Defined in one variants only
- main.set("p1.a","main-a-x1.y1",new String[] {"x1","y1"}, null);
- main.set("p1.a","main-a-x1.y2",new String[] {"x1","y2"}, null);
- main.set("p1.e","main-e-x1.y2",new String[] {"x1","y2"}, null);
- main.set("p1.g","main-g-x1.y2",new String[] {"x1","y2"}, null); // Defined in one variant only
- main.set("p1.b","main-b", null);
-
- QueryProfile inheritedVariant1=new QueryProfile("inheritedVariant1");
- inheritedVariant1.set("p1.a","inheritedVariant1-a", null);
- inheritedVariant1.set("p1.h","inheritedVariant1-h", null); // Only defined in two inherited variants
-
- QueryProfile inheritedVariant2=new QueryProfile("inheritedVariant2");
- inheritedVariant2.set("p1.a","inheritedVariant2-a", null);
- inheritedVariant2.set("p1.h","inheritedVariant2-h", null); // Only defined in two inherited variants
- inheritedVariant2.set("p1.i","inheritedVariant2-i", null); // Only defined in one inherited variant
-
- QueryProfile inheritedVariant3=new QueryProfile("inheritedVariant3");
- inheritedVariant3.set("p1.j","inheritedVariant3-j", null); // Only defined in one inherited variant, but inherited twice
+ main.set("p1.a", "main-a", null);
+ main.set("p1.a", "main-a-x1", new String[]{"x1"}, null);
+ main.set("p1.e", "main-e-x1", new String[]{"x1"}, null); // Defined in two variants only
+ main.set("p1.f", "main-f-x1", new String[]{"x1"}, null); // Defined in one variants only
+ main.set("p1.a", "main-a-x1.y1", new String[]{"x1", "y1"}, null);
+ main.set("p1.a", "main-a-x1.y2", new String[]{"x1", "y2"}, null);
+ main.set("p1.e", "main-e-x1.y2", new String[]{"x1", "y2"}, null);
+ main.set("p1.g", "main-g-x1.y2", new String[]{"x1", "y2"}, null); // Defined in one variant only
+ main.set("p1.b", "main-b", null);
+
+ QueryProfile inheritedVariant1 = new QueryProfile("inheritedVariant1");
+ inheritedVariant1.set("p1.a", "inheritedVariant1-a", null);
+ inheritedVariant1.set("p1.h", "inheritedVariant1-h", null); // Only defined in two inherited variants
+
+ QueryProfile inheritedVariant2 = new QueryProfile("inheritedVariant2");
+ inheritedVariant2.set("p1.a", "inheritedVariant2-a", null);
+ inheritedVariant2.set("p1.h", "inheritedVariant2-h", null); // Only defined in two inherited variants
+ inheritedVariant2.set("p1.i", "inheritedVariant2-i", null); // Only defined in one inherited variant
+
+ QueryProfile inheritedVariant3 = new QueryProfile("inheritedVariant3");
+ inheritedVariant3.set("p1.j", "inheritedVariant3-j", null); // Only defined in one inherited variant, but inherited twice
+
+ main.addInherited(inheritedVariant1, new String[]{"x1"});
+ main.addInherited(inheritedVariant3, new String[]{"x1"});
+ main.addInherited(inheritedVariant2, new String[]{"x1", "y2"});
+ main.addInherited(inheritedVariant3, new String[]{"x1", "y2"});
- main.addInherited(inheritedVariant1,new String[] {"x1"});
- main.addInherited(inheritedVariant3,new String[] {"x1"});
- main.addInherited(inheritedVariant2,new String[] {"x1","y2"});
- main.addInherited(inheritedVariant3,new String[] {"x1","y2"});
-
- Properties properties=new QueryProfileProperties(main.compile(null));
+ Properties properties = new QueryProfileProperties(main.compile(null));
- int expectedBaseSize=4;
+ int expectedBaseSize = 4;
// No context
- Map<String,Object> listed=properties.listProperties();
- assertEquals(expectedBaseSize,listed.size());
- assertEquals("main-a",listed.get("p1.a"));
- assertEquals("main-b",listed.get("p1.b"));
- assertEquals("parent1-c",listed.get("p1.c"));
- assertEquals("parent2-d",listed.get("p1.d"));
+ Map<String, Object> listed = properties.listProperties();
+ assertEquals(expectedBaseSize, listed.size());
+ assertEquals("main-a", listed.get("p1.a"));
+ assertEquals("main-b", listed.get("p1.b"));
+ assertEquals("parent1-c", listed.get("p1.c"));
+ assertEquals("parent2-d", listed.get("p1.d"));
// Context x=x1
- listed=properties.listProperties(toMap(main,new String[] {"x1"}));
- assertEquals(expectedBaseSize+4,listed.size());
- assertEquals("main-a-x1",listed.get("p1.a"));
- assertEquals("main-b",listed.get("p1.b"));
- assertEquals("parent1-c",listed.get("p1.c"));
- assertEquals("parent2-d",listed.get("p1.d"));
- assertEquals("main-e-x1",listed.get("p1.e"));
- assertEquals("main-f-x1",listed.get("p1.f"));
- assertEquals("inheritedVariant1-h",listed.get("p1.h"));
- assertEquals("inheritedVariant3-j",listed.get("p1.j"));
+ listed = properties.listProperties(toMap(main, new String[]{"x1"}));
+ assertEquals(expectedBaseSize + 4, listed.size());
+ assertEquals("main-a-x1", listed.get("p1.a"));
+ assertEquals("main-b", listed.get("p1.b"));
+ assertEquals("parent1-c", listed.get("p1.c"));
+ assertEquals("parent2-d", listed.get("p1.d"));
+ assertEquals("main-e-x1", listed.get("p1.e"));
+ assertEquals("main-f-x1", listed.get("p1.f"));
+ assertEquals("inheritedVariant1-h", listed.get("p1.h"));
+ assertEquals("inheritedVariant3-j", listed.get("p1.j"));
// Context x=x1,y=y1
- listed=properties.listProperties(toMap(main,new String[] {"x1","y1"}));
- assertEquals(expectedBaseSize+4,listed.size());
- assertEquals("main-a-x1.y1",listed.get("p1.a"));
- assertEquals("main-b",listed.get("p1.b"));
- assertEquals("parent1-c",listed.get("p1.c"));
- assertEquals("parent2-d",listed.get("p1.d"));
- assertEquals("main-e-x1",listed.get("p1.e"));
- assertEquals("main-f-x1",listed.get("p1.f"));
- assertEquals("inheritedVariant1-h",listed.get("p1.h"));
- assertEquals("inheritedVariant3-j",listed.get("p1.j"));
+ listed = properties.listProperties(toMap(main, new String[]{"x1", "y1"}));
+ assertEquals(expectedBaseSize + 4, listed.size());
+ assertEquals("main-a-x1.y1", listed.get("p1.a"));
+ assertEquals("main-b", listed.get("p1.b"));
+ assertEquals("parent1-c", listed.get("p1.c"));
+ assertEquals("parent2-d", listed.get("p1.d"));
+ assertEquals("main-e-x1", listed.get("p1.e"));
+ assertEquals("main-f-x1", listed.get("p1.f"));
+ assertEquals("inheritedVariant1-h", listed.get("p1.h"));
+ assertEquals("inheritedVariant3-j", listed.get("p1.j"));
// Context x=x1,y=y2
- listed=properties.listProperties(toMap(main,new String[] {"x1","y2"}));
- assertEquals(expectedBaseSize+6,listed.size());
- assertEquals("main-a-x1.y2",listed.get("p1.a"));
- assertEquals("main-b",listed.get("p1.b"));
- assertEquals("parent1-c",listed.get("p1.c"));
- assertEquals("parent2-d",listed.get("p1.d"));
- assertEquals("main-e-x1.y2",listed.get("p1.e"));
- assertEquals("main-f-x1",listed.get("p1.f"));
- assertEquals("main-g-x1.y2",listed.get("p1.g"));
- assertEquals("inheritedVariant2-h",listed.get("p1.h"));
- assertEquals("inheritedVariant2-i",listed.get("p1.i"));
- assertEquals("inheritedVariant3-j",listed.get("p1.j"));
+ listed = properties.listProperties(toMap(main, new String[]{"x1", "y2"}));
+ assertEquals(expectedBaseSize + 6, listed.size());
+ assertEquals("main-a-x1.y2", listed.get("p1.a"));
+ assertEquals("main-b", listed.get("p1.b"));
+ assertEquals("parent1-c", listed.get("p1.c"));
+ assertEquals("parent2-d", listed.get("p1.d"));
+ assertEquals("main-e-x1.y2", listed.get("p1.e"));
+ assertEquals("main-f-x1", listed.get("p1.f"));
+ assertEquals("main-g-x1.y2", listed.get("p1.g"));
+ assertEquals("inheritedVariant2-h", listed.get("p1.h"));
+ assertEquals("inheritedVariant2-i", listed.get("p1.i"));
+ assertEquals("inheritedVariant3-j", listed.get("p1.j"));
// Context x=x1,y=y3
- listed=properties.listProperties(toMap(main,new String[] {"x1","y3"}));
- assertEquals(expectedBaseSize+4,listed.size());
- assertEquals("main-a-x1",listed.get("p1.a"));
- assertEquals("main-b",listed.get("p1.b"));
- assertEquals("parent1-c",listed.get("p1.c"));
- assertEquals("parent2-d",listed.get("p1.d"));
- assertEquals("main-e-x1",listed.get("p1.e"));
- assertEquals("main-f-x1",listed.get("p1.f"));
- assertEquals("inheritedVariant1-h",listed.get("p1.h"));
- assertEquals("inheritedVariant3-j",listed.get("p1.j"));
+ listed = properties.listProperties(toMap(main, new String[]{"x1", "y3"}));
+ assertEquals(expectedBaseSize + 4, listed.size());
+ assertEquals("main-a-x1", listed.get("p1.a"));
+ assertEquals("main-b", listed.get("p1.b"));
+ assertEquals("parent1-c", listed.get("p1.c"));
+ assertEquals("parent2-d", listed.get("p1.d"));
+ assertEquals("main-e-x1", listed.get("p1.e"));
+ assertEquals("main-f-x1", listed.get("p1.f"));
+ assertEquals("inheritedVariant1-h", listed.get("p1.h"));
+ assertEquals("inheritedVariant3-j", listed.get("p1.j"));
// Context x=x2,y=y1
- listed=properties.listProperties(toMap(main,new String[] {"x2","y1"}));
- assertEquals(expectedBaseSize,listed.size());
- assertEquals("main-a",listed.get("p1.a"));
- assertEquals("main-b",listed.get("p1.b"));
- assertEquals("parent1-c",listed.get("p1.c"));
- assertEquals("parent2-d",listed.get("p1.d"));
+ listed = properties.listProperties(toMap(main, new String[]{"x2", "y1"}));
+ assertEquals(expectedBaseSize, listed.size());
+ assertEquals("main-a", listed.get("p1.a"));
+ assertEquals("main-b", listed.get("p1.b"));
+ assertEquals("parent1-c", listed.get("p1.c"));
+ assertEquals("parent2-d", listed.get("p1.d"));
}
@Test
- public void testQueryProfileReferences() {
- QueryProfile main=new QueryProfile("main");
- main.setDimensions(new String[] {"x1"});
- QueryProfile referencedMain=new QueryProfile("referencedMain");
- referencedMain.set("r1","mainReferenced-r1", null); // In both
- referencedMain.set("r2","mainReferenced-r2", null); // Only in this
- QueryProfile referencedVariant=new QueryProfile("referencedVariant");
- referencedVariant.set("r1","variantReferenced-r1", null); // In both
- referencedVariant.set("r3","variantReferenced-r3", null); // Only in this
+ void testQueryProfileReferences() {
+ QueryProfile main = new QueryProfile("main");
+ main.setDimensions(new String[]{"x1"});
+ QueryProfile referencedMain = new QueryProfile("referencedMain");
+ referencedMain.set("r1", "mainReferenced-r1", null); // In both
+ referencedMain.set("r2", "mainReferenced-r2", null); // Only in this
+ QueryProfile referencedVariant = new QueryProfile("referencedVariant");
+ referencedVariant.set("r1", "variantReferenced-r1", null); // In both
+ referencedVariant.set("r3", "variantReferenced-r3", null); // Only in this
- main.set("a",referencedMain, null);
- main.set("a",referencedVariant,new String[] {"x1"}, null);
+ main.set("a", referencedMain, null);
+ main.set("a", referencedVariant, new String[]{"x1"}, null);
- Properties properties=new QueryProfileProperties(main.compile(null));
+ Properties properties = new QueryProfileProperties(main.compile(null));
// No context
- Map<String,Object> listed=properties.listProperties();
- assertEquals(2,listed.size());
- assertEquals("mainReferenced-r1",listed.get("a.r1"));
- assertEquals("mainReferenced-r2",listed.get("a.r2"));
+ Map<String, Object> listed = properties.listProperties();
+ assertEquals(2, listed.size());
+ assertEquals("mainReferenced-r1", listed.get("a.r1"));
+ assertEquals("mainReferenced-r2", listed.get("a.r2"));
// Context x=x1
- listed=properties.listProperties(toMap(main,new String[] {"x1"}));
- assertEquals(3,listed.size());
- assertEquals("variantReferenced-r1",listed.get("a.r1"));
- assertEquals("mainReferenced-r2",listed.get("a.r2"));
- assertEquals("variantReferenced-r3",listed.get("a.r3"));
+ listed = properties.listProperties(toMap(main, new String[]{"x1"}));
+ assertEquals(3, listed.size());
+ assertEquals("variantReferenced-r1", listed.get("a.r1"));
+ assertEquals("mainReferenced-r2", listed.get("a.r2"));
+ assertEquals("variantReferenced-r3", listed.get("a.r3"));
}
@Test
- public void testQueryProfileReferencesWithSubstitution() {
+ void testQueryProfileReferencesWithSubstitution() {
QueryProfile main = new QueryProfile("main");
- main.setDimensions(new String[] {"x1"});
+ main.setDimensions(new String[]{"x1"});
QueryProfile referencedMain = new QueryProfile("referencedMain");
- referencedMain.set("r1","%{prefix}mainReferenced-r1", null); // In both
- referencedMain.set("r2","%{prefix}mainReferenced-r2", null); // Only in this
+ referencedMain.set("r1", "%{prefix}mainReferenced-r1", null); // In both
+ referencedMain.set("r2", "%{prefix}mainReferenced-r2", null); // Only in this
QueryProfile referencedVariant = new QueryProfile("referencedVariant");
- referencedVariant.set("r1","%{prefix}variantReferenced-r1", null); // In both
- referencedVariant.set("r3","%{prefix}variantReferenced-r3", null); // Only in this
+ referencedVariant.set("r1", "%{prefix}variantReferenced-r1", null); // In both
+ referencedVariant.set("r3", "%{prefix}variantReferenced-r3", null); // Only in this
referencedVariant.set("inthis", "local value", null);
- referencedVariant.set("r4","This has %{.inthis}", null); // Relative
+ referencedVariant.set("r4", "This has %{.inthis}", null); // Relative
main.set("a", referencedMain, null);
- main.set("a", referencedVariant,new String[] {"x1"}, null);
+ main.set("a", referencedVariant, new String[]{"x1"}, null);
main.set("prefix", "mainPrefix:", null);
- main.set("prefix", "variantPrefix:", new String[] {"x1"}, null);
+ main.set("prefix", "variantPrefix:", new String[]{"x1"}, null);
Properties properties = new QueryProfileProperties(main.compile(null));
// No context
- Map<String,Object> listed = properties.listProperties();
+ Map<String, Object> listed = properties.listProperties();
assertEquals(3, listed.size());
assertEquals("mainPrefix:mainReferenced-r1", listed.get("a.r1"));
assertEquals("mainPrefix:mainReferenced-r2", listed.get("a.r2"));
// Context x=x1
- listed = properties.listProperties(toMap(main, new String[] {"x1"}));
+ listed = properties.listProperties(toMap(main, new String[]{"x1"}));
assertEquals(6, listed.size());
assertEquals("variantPrefix:variantReferenced-r1", listed.get("a.r1"));
assertEquals("variantPrefix:mainReferenced-r2", listed.get("a.r2"));
@@ -1209,17 +1208,17 @@ public class QueryProfileVariantsTestCase {
}
@Test
- public void testNewsCase1() {
+ void testNewsCase1() {
QueryProfile shortcuts = new QueryProfile("shortcuts");
- shortcuts.setDimensions(new String[] {"custid_1", "custid_2", "custid_3", "custid_4", "custid_5", "custid_6"});
+ shortcuts.setDimensions(new String[]{"custid_1", "custid_2", "custid_3", "custid_4", "custid_5", "custid_6"});
shortcuts.set("testout", "outside", null);
shortcuts.set("test.out", "dotoutside", null);
- shortcuts.set("testin", "inside", new String[] {"yahoo","ca","sc"}, null);
- shortcuts.set("test.in", "dotinside", new String[] {"yahoo","ca","sc"}, null);
+ shortcuts.set("testin", "inside", new String[]{"yahoo", "ca", "sc"}, null);
+ shortcuts.set("test.in", "dotinside", new String[]{"yahoo", "ca", "sc"}, null);
- QueryProfile profile=new QueryProfile("default");
- profile.setDimensions(new String[] {"custid_1","custid_2","custid_3","custid_4","custid_5","custid_6"});
- profile.addInherited(shortcuts, new String[] {"yahoo",null,"sc"});
+ QueryProfile profile = new QueryProfile("default");
+ profile.setDimensions(new String[]{"custid_1", "custid_2", "custid_3", "custid_4", "custid_5", "custid_6"});
+ profile.addInherited(shortcuts, new String[]{"yahoo", null, "sc"});
profile.freeze();
Query query = new Query(HttpRequest.createTestRequest("?query=test&custid_1=yahoo&custid_2=ca&custid_3=sc", Method.GET), profile.compile(null));
@@ -1231,103 +1230,103 @@ public class QueryProfileVariantsTestCase {
}
@Test
- public void testNewsCase2() {
- QueryProfile test=new QueryProfile("test");
+ void testNewsCase2() {
+ QueryProfile test = new QueryProfile("test");
test.setDimensions("sort,resulttypes,rss,age,intl,testid".split(","));
- String[] dimensionValues=new String[] {null,null,"0"};
- test.set("discovery","sources",dimensionValues, null);
- test.set("discoverytypes","article",dimensionValues, null);
- test.set("discovery.sources.count","10",dimensionValues, null);
+ String[] dimensionValues = new String[]{null, null, "0"};
+ test.set("discovery", "sources", dimensionValues, null);
+ test.set("discoverytypes", "article", dimensionValues, null);
+ test.set("discovery.sources.count", "10", dimensionValues, null);
CompiledQueryProfile ctest = test.compile(null);
- assertEquals("sources",ctest.get("discovery", toMap(test, dimensionValues)));
- assertEquals("article",ctest.get("discoverytypes", toMap(test, dimensionValues)));
- assertEquals("10",ctest.get("discovery.sources.count", toMap(test, dimensionValues)));
+ assertEquals("sources", ctest.get("discovery", toMap(test, dimensionValues)));
+ assertEquals("article", ctest.get("discoverytypes", toMap(test, dimensionValues)));
+ assertEquals("10", ctest.get("discovery.sources.count", toMap(test, dimensionValues)));
- Map<String,Object> values=ctest.listValues("",toMap(test,dimensionValues));
- assertEquals(3,values.size());
- assertEquals("sources",values.get("discovery"));
- assertEquals("article",values.get("discoverytypes"));
- assertEquals("10",values.get("discovery.sources.count"));
+ Map<String, Object> values = ctest.listValues("", toMap(test, dimensionValues));
+ assertEquals(3, values.size());
+ assertEquals("sources", values.get("discovery"));
+ assertEquals("article", values.get("discoverytypes"));
+ assertEquals("10", values.get("discovery.sources.count"));
- Map<String,Object> sourceValues=ctest.listValues("discovery.sources",toMap(test,dimensionValues));
- assertEquals(1,sourceValues.size());
- assertEquals("10",sourceValues.get("count"));
+ Map<String, Object> sourceValues = ctest.listValues("discovery.sources", toMap(test, dimensionValues));
+ assertEquals(1, sourceValues.size());
+ assertEquals("10", sourceValues.get("count"));
}
@Test
- public void testRuntimeAssignmentInClone() {
- QueryProfile test=new QueryProfile("test");
- test.setDimensions(new String[] {"x"});
- String[] x1=new String[] {"x1"};
- Map<String,String> x1m=toMap(test,x1);
- test.set("a","30",x1, null);
- test.set("a.b","20",x1, null);
- test.set("a.b.c","10",x1, null);
+ void testRuntimeAssignmentInClone() {
+ QueryProfile test = new QueryProfile("test");
+ test.setDimensions(new String[]{"x"});
+ String[] x1 = new String[]{"x1"};
+ Map<String, String> x1m = toMap(test, x1);
+ test.set("a", "30", x1, null);
+ test.set("a.b", "20", x1, null);
+ test.set("a.b.c", "10", x1, null);
// Setting in one profile works
Query qMain = new Query(HttpRequest.createTestRequest("?query=test", Method.GET), test.compile(null));
- qMain.properties().set("a.b","50",x1m);
- assertEquals("50",qMain.properties().get("a.b",x1m));
+ qMain.properties().set("a.b", "50", x1m);
+ assertEquals("50", qMain.properties().get("a.b", x1m));
// Cloning
- Query qBranch=qMain.clone();
+ Query qBranch = qMain.clone();
// Setting in main still works
- qMain.properties().set("a.b","51",x1m);
- assertEquals("51",qMain.properties().get("a.b",x1m));
+ qMain.properties().set("a.b", "51", x1m);
+ assertEquals("51", qMain.properties().get("a.b", x1m));
// Clone is not affected by change in original
- assertEquals("50",qBranch.properties().get("a.b",x1m));
+ assertEquals("50", qBranch.properties().get("a.b", x1m));
// Setting in clone works
- qBranch.properties().set("a.b","70",x1m);
- assertEquals("70",qBranch.properties().get("a.b",x1m));
+ qBranch.properties().set("a.b", "70", x1m);
+ assertEquals("70", qBranch.properties().get("a.b", x1m));
// Setting in clone does not affect original
- assertEquals("51",qMain.properties().get("a.b",x1m));
+ assertEquals("51", qMain.properties().get("a.b", x1m));
}
@Test
- public void testIncompatibleDimensions() {
+ void testIncompatibleDimensions() {
QueryProfile alert = new QueryProfile("alert");
QueryProfile backendBase = new QueryProfile("backendBase");
- backendBase.setDimensions(new String[] { "sort", "resulttypes", "rss" });
+ backendBase.setDimensions(new String[]{"sort", "resulttypes", "rss"});
backendBase.set("custid", "s", null);
QueryProfile backend = new QueryProfile("backend");
- backend.setDimensions(new String[] { "sort", "offset", "resulttypes", "rss", "age", "lang", "fr", "entry" });
+ backend.setDimensions(new String[]{"sort", "offset", "resulttypes", "rss", "age", "lang", "fr", "entry"});
backend.addInherited(backendBase);
QueryProfile web = new QueryProfile("web");
- web.setDimensions(new String[] { "entry", "recency" });
- web.set("fr", "alerts", new String[] { "alert" }, null);
+ web.setDimensions(new String[]{"entry", "recency"});
+ web.set("fr", "alerts", new String[]{"alert"}, null);
alert.set("config.backend.vertical.news", backend, null);
alert.set("config.backend.multimedia", web, null);
- backend.set("custid", "yahoo/alerts", new String[] { null, null, null, null, null, "en-US", null, "alert"}, null);
+ backend.set("custid", "yahoo/alerts", new String[]{null, null, null, null, null, "en-US", null, "alert"}, null);
CompiledQueryProfile cAlert = alert.compile(null);
assertEquals("yahoo/alerts", cAlert.get("config.backend.vertical.news.custid", toMap("entry=alert", "intl=us", "lang=en-US")));
}
@Test
- public void testIncompatibleDimensionsSimplified() {
+ void testIncompatibleDimensionsSimplified() {
QueryProfile alert = new QueryProfile("alert");
QueryProfile backendBase = new QueryProfile("backendBase");
backendBase.set("custid", "s", null);
QueryProfile backend = new QueryProfile("backend");
- backend.setDimensions(new String[] { "sort", "lang", "fr", "entry" });
- backend.set("custid", "yahoo/alerts", new String[] { null, "en-US", null, "alert"}, null);
+ backend.setDimensions(new String[]{"sort", "lang", "fr", "entry"});
+ backend.set("custid", "yahoo/alerts", new String[]{null, "en-US", null, "alert"}, null);
backend.addInherited(backendBase);
QueryProfile web = new QueryProfile("web");
- web.setDimensions(new String[] { "entry", "recency" });
- web.set("fr", "alerts", new String[] { "alert" }, null);
+ web.setDimensions(new String[]{"entry", "recency"});
+ web.set("fr", "alerts", new String[]{"alert"}, null);
alert.set("vertical", backend, null);
alert.set("multimedia", web, null);
@@ -1337,23 +1336,23 @@ public class QueryProfileVariantsTestCase {
}
@Test
- public void testZoneInfoInContext() {
+ void testZoneInfoInContext() {
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfile profile = new QueryProfile("test");
- profile.setDimensions(new String[] { "environment", "region", "instance" });
+ profile.setDimensions(new String[]{"environment", "region", "instance"});
profile.set("value", "default", registry);
profile.set("value", "prod-region1-instance1",
- toMap("environment=prod", "region=region1", "instance=instance1"),
- registry);
+ toMap("environment=prod", "region=region1", "instance=instance1"),
+ registry);
profile.set("value", "prod-instance2",
- toMap("environment=prod", "instance=instance2"),
- registry);
+ toMap("environment=prod", "instance=instance2"),
+ registry);
profile.set("value", "prod-region3",
- toMap("environment=prod", "region=region3"),
- registry);
+ toMap("environment=prod", "region=region3"),
+ registry);
profile.set("value", "dev",
- toMap("environment=dev"),
- registry);
+ toMap("environment=dev"),
+ registry);
registry.register(profile);
CompiledQueryProfileRegistry cRegistry = registry.compile();
@@ -1361,36 +1360,36 @@ public class QueryProfileVariantsTestCase {
assertValueForZone("default", ZoneInfo.defaultInfo(), null, cTest);
assertValueForZone("prod-region1-instance1",
- new ZoneInfo(new ApplicationId("tenant1", "application1", "instance1"),
- new Zone(Environment.prod, "region1")),
- null,
- cTest);
+ new ZoneInfo(new ApplicationId("tenant1", "application1", "instance1"),
+ new Zone(Environment.prod, "region1")),
+ null,
+ cTest);
assertValueForZone("prod-instance2",
- new ZoneInfo(new ApplicationId("tenant2", "application2", "instance2"),
- new Zone(Environment.prod, "region1")),
- null,
- cTest);
+ new ZoneInfo(new ApplicationId("tenant2", "application2", "instance2"),
+ new Zone(Environment.prod, "region1")),
+ null,
+ cTest);
assertValueForZone("prod-region3",
- new ZoneInfo(new ApplicationId("tenant3", "application3", "instance3"),
- new Zone(Environment.prod, "region3")),
- null,
- cTest);
+ new ZoneInfo(new ApplicationId("tenant3", "application3", "instance3"),
+ new Zone(Environment.prod, "region3")),
+ null,
+ cTest);
assertValueForZone("dev",
- new ZoneInfo(new ApplicationId("tenant4", "application4", "instance4"),
- new Zone(Environment.dev, "region4")),
- null,
- cTest);
+ new ZoneInfo(new ApplicationId("tenant4", "application4", "instance4"),
+ new Zone(Environment.dev, "region4")),
+ null,
+ cTest);
}
@Test
- public void testZoneInfoInContextWithUnoverridability() {
+ void testZoneInfoInContextWithUnoverridability() {
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfile profile = new QueryProfile("test");
- profile.setDimensions(new String[] { "instance", "environment", "region" });
+ profile.setDimensions(new String[]{"instance", "environment", "region"});
profile.set("value", "default", registry);
profile.set("value", "prod-beta",
- toMap("environment=prod", "instance=beta"),
- registry);
+ toMap("environment=prod", "instance=beta"),
+ registry);
profile.setOverridable("value", false, toMap("environment=prod", "instance=beta"));
registry.register(profile);
@@ -1398,10 +1397,10 @@ public class QueryProfileVariantsTestCase {
CompiledQueryProfile cTest = cRegistry.findQueryProfile("test");
assertValueForZone("prod-beta",
- new ZoneInfo(new ApplicationId("tenant1", "application1", "beta"),
- new Zone(Environment.prod, "region1")),
- "fromRequest",
- cTest);
+ new ZoneInfo(new ApplicationId("tenant1", "application1", "beta"),
+ new Zone(Environment.prod, "region1")),
+ "fromRequest",
+ cTest);
}
@@ -1413,23 +1412,23 @@ public class QueryProfileVariantsTestCase {
}
@Test
- public void testZoneInfoInContextSettingNativeProperty() {
+ void testZoneInfoInContextSettingNativeProperty() {
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfile profile = new QueryProfile("test");
- profile.setDimensions(new String[] { "instance", "environment", "region" });
+ profile.setDimensions(new String[]{"instance", "environment", "region"});
profile.set("timeout", "0.3",
- toMap("environment=prod", "instance=beta"),
- registry);
+ toMap("environment=prod", "instance=beta"),
+ registry);
registry.register(profile);
CompiledQueryProfileRegistry cRegistry = registry.compile();
CompiledQueryProfile cTest = cRegistry.findQueryProfile("test");
assertTimeoutForZone(300,
- new ZoneInfo(new ApplicationId("tenant1", "application1", "beta"),
- new Zone(Environment.prod, "region1")),
- null,
- cTest);
+ new ZoneInfo(new ApplicationId("tenant1", "application1", "beta"),
+ new Zone(Environment.prod, "region1")),
+ null,
+ cTest);
}
private void assertTimeoutForZone(int expected, ZoneInfo zoneInfo, String requestValue, CompiledQueryProfile cTest) {
@@ -1441,8 +1440,7 @@ public class QueryProfileVariantsTestCase {
private void assertGet(String expectedValue, String parameter, String[] dimensionValues, QueryProfile profile, CompiledQueryProfile cprofile) {
Map<String, String> context = toMap(profile,dimensionValues);
- assertEquals("Looking up '" + parameter + "' for '" + Arrays.toString(dimensionValues) + "'",
- expectedValue, cprofile.get(parameter,context));
+ assertEquals(expectedValue, cprofile.get(parameter,context), "Looking up '" + parameter + "' for '" + Arrays.toString(dimensionValues) + "'");
}
public static Map<String,String> toMap(QueryProfile profile, String[] dimensionValues) {
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/types/test/FieldTypeTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/types/test/FieldTypeTestCase.java
index 0ace8f93f1d..b245648b861 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/types/test/FieldTypeTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/types/test/FieldTypeTestCase.java
@@ -4,9 +4,9 @@ package com.yahoo.search.query.profile.types.test;
import com.yahoo.search.query.profile.types.FieldType;
import com.yahoo.search.query.profile.types.QueryProfileType;
import com.yahoo.search.query.profile.types.QueryProfileTypeRegistry;
-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 bratseth
@@ -14,14 +14,14 @@ import static org.junit.Assert.assertEquals;
public class FieldTypeTestCase {
@Test
- public void testConvertToFromString() {
- QueryProfileTypeRegistry registry=new QueryProfileTypeRegistry();
+ void testConvertToFromString() {
+ QueryProfileTypeRegistry registry = new QueryProfileTypeRegistry();
registry.register(new QueryProfileType("foo"));
- assertEquals("string", FieldType.fromString("string",registry).stringValue());
- assertEquals("boolean", FieldType.fromString("boolean",registry).stringValue());
- assertEquals("query-profile", FieldType.fromString("query-profile",registry).stringValue());
- assertEquals("query-profile:foo", FieldType.fromString("query-profile:foo",registry).stringValue());
+ assertEquals("string", FieldType.fromString("string", registry).stringValue());
+ assertEquals("boolean", FieldType.fromString("boolean", registry).stringValue());
+ assertEquals("query-profile", FieldType.fromString("query-profile", registry).stringValue());
+ assertEquals("query-profile:foo", FieldType.fromString("query-profile:foo", registry).stringValue());
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/types/test/MandatoryTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/types/test/MandatoryTestCase.java
index dfe4b24e256..5bde89d0282 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/types/test/MandatoryTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/types/test/MandatoryTestCase.java
@@ -13,9 +13,9 @@ import com.yahoo.search.query.profile.types.FieldType;
import com.yahoo.search.query.profile.types.QueryProfileType;
import com.yahoo.search.query.profile.types.QueryProfileTypeRegistry;
import com.yahoo.search.test.QueryTestCase;
-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 bratseth
@@ -55,18 +55,18 @@ public class MandatoryTestCase {
}
@Test
- public void testMandatoryFullySpecifiedQueryProfile() {
+ void testMandatoryFullySpecifiedQueryProfile() {
Fixture1 fixture = new Fixture1();
- QueryProfile test=new QueryProfile("test");
+ QueryProfile test = new QueryProfile("test");
test.setType(fixture.type);
test.set("myString", "aString", fixture.registry);
fixture.registry.register(test);
- QueryProfile myUser=new QueryProfile("user");
+ QueryProfile myUser = new QueryProfile("user");
myUser.setType(fixture.user);
- myUser.set("myUserInteger",1, fixture.registry);
- myUser.set("myUserString",1, fixture.registry);
+ myUser.set("myUserInteger", 1, fixture.registry);
+ myUser.set("myUserString", 1, fixture.registry);
test.set("myUserQueryProfile", myUser, fixture.registry);
fixture.registry.register(myUser);
@@ -77,7 +77,7 @@ public class MandatoryTestCase {
}
@Test
- public void testMandatoryRequestPropertiesNeeded() {
+ void testMandatoryRequestPropertiesNeeded() {
Fixture1 fixture = new Fixture1();
QueryProfile test = new QueryProfile("test");
@@ -94,11 +94,11 @@ public class MandatoryTestCase {
// Underspecified request 1
assertError("Incomplete query: Parameter 'myString' is mandatory in query profile 'test' of type 'testtype' but is not set",
- new Query(HttpRequest.createTestRequest("", Method.GET), cRegistry.getComponent("test")));
+ new Query(HttpRequest.createTestRequest("", Method.GET), cRegistry.getComponent("test")));
// Underspecified request 2
assertError("Incomplete query: Parameter 'myUserQueryProfile.myUserString' is mandatory in query profile 'test' of type 'testtype' but is not set",
- new Query(HttpRequest.createTestRequest("?myString=aString", Method.GET), cRegistry.getComponent("test")));
+ new Query(HttpRequest.createTestRequest("?myString=aString", Method.GET), cRegistry.getComponent("test")));
// Fully specified request
assertError(null, new Query(HttpRequest.createTestRequest("?myString=aString&myUserQueryProfile.myUserString=userString", Method.GET), cRegistry.getComponent("test")));
@@ -106,7 +106,7 @@ public class MandatoryTestCase {
/** Same as above except the whole thing is nested in maps */
@Test
- public void testMandatoryNestedInMaps() {
+ void testMandatoryNestedInMaps() {
Fixture1 fixture = new Fixture1();
QueryProfile topMap = new QueryProfile("topMap");
@@ -123,7 +123,7 @@ public class MandatoryTestCase {
QueryProfile myUser = new QueryProfile("user");
myUser.setType(fixture.user);
- myUser.set("myUserInteger",1, fixture.registry);
+ myUser.set("myUserInteger", 1, fixture.registry);
test.set("myUserQueryProfile", myUser, fixture.registry);
fixture.registry.register(myUser);
@@ -132,11 +132,11 @@ public class MandatoryTestCase {
// Underspecified request 1
assertError("Incomplete query: Parameter 'subMap.test.myString' is mandatory in query profile 'topMap' but is not set",
- new Query(HttpRequest.createTestRequest("", Method.GET), cRegistry.getComponent("topMap")));
+ new Query(HttpRequest.createTestRequest("", Method.GET), cRegistry.getComponent("topMap")));
// Underspecified request 2
assertError("Incomplete query: Parameter 'subMap.test.myUserQueryProfile.myUserString' is mandatory in query profile 'topMap' but is not set",
- new Query(HttpRequest.createTestRequest("?subMap.test.myString=aString", Method.GET), cRegistry.getComponent("topMap")));
+ new Query(HttpRequest.createTestRequest("?subMap.test.myString=aString", Method.GET), cRegistry.getComponent("topMap")));
// Fully specified request
assertError(null, new Query(HttpRequest.createTestRequest("?subMap.test.myString=aString&subMap.test.myUserQueryProfile.myUserString=userString", Method.GET), cRegistry.getComponent("topMap")));
@@ -144,7 +144,7 @@ public class MandatoryTestCase {
/** Here, no user query profile is referenced in the query profile, but one is chosen in the request */
@Test
- public void testMandatoryUserProfileSetInRequest() {
+ void testMandatoryUserProfileSetInRequest() {
Fixture1 fixture = new Fixture1();
QueryProfile test = new QueryProfile("test");
@@ -161,11 +161,11 @@ public class MandatoryTestCase {
// Underspecified request 1
assertError("Incomplete query: Parameter 'myUserQueryProfile' is mandatory in query profile 'test' of type 'testtype' but is not set",
- new Query(HttpRequest.createTestRequest("?myString=aString", Method.GET), cRegistry.getComponent("test")));
+ new Query(HttpRequest.createTestRequest("?myString=aString", Method.GET), cRegistry.getComponent("test")));
// Underspecified request 1
assertError("Incomplete query: Parameter 'myUserQueryProfile.myUserString' is mandatory in query profile 'test' of type 'testtype' but is not set",
- new Query(HttpRequest.createTestRequest("?myString=aString&myUserQueryProfile=user", Method.GET), cRegistry.getComponent("test")));
+ new Query(HttpRequest.createTestRequest("?myString=aString&myUserQueryProfile=user", Method.GET), cRegistry.getComponent("test")));
// Fully specified request
assertError(null, new Query(HttpRequest.createTestRequest("?myString=aString&myUserQueryProfile=user&myUserQueryProfile.myUserString=userString", Method.GET), cRegistry.getComponent("test")));
@@ -173,7 +173,7 @@ public class MandatoryTestCase {
/** Here, a partially specified query profile is added to a non-mandatory field, making the request underspecified */
@Test
- public void testNonMandatoryUnderspecifiedUserProfileSetInRequest() {
+ void testNonMandatoryUnderspecifiedUserProfileSetInRequest() {
Fixture1 fixture = new Fixture1();
QueryProfile test = new QueryProfile("test");
@@ -199,7 +199,7 @@ public class MandatoryTestCase {
// Underspecified because an underspecified profile is added
assertError("Incomplete query: Parameter 'myQueryProfile.myUserString' is mandatory in query profile 'test' of type 'testtype' but is not set",
- new Query(HttpRequest.createTestRequest("?myString=aString&myQueryProfile=otherUser", Method.GET), cRegistry.getComponent("test")));
+ new Query(HttpRequest.createTestRequest("?myString=aString&myQueryProfile=otherUser", Method.GET), cRegistry.getComponent("test")));
// Back to fully specified
assertError(null, new Query(HttpRequest.createTestRequest("?myString=aString&myQueryProfile=otherUser&myQueryProfile.myUserString=userString", Method.GET), cRegistry.getComponent("test")));
@@ -223,7 +223,7 @@ public class MandatoryTestCase {
}
@Test
- public void testMandatoryInParentType() {
+ void testMandatoryInParentType() {
Fixture2 fixture = new Fixture2();
QueryProfile defaultProfile = new QueryProfile("default");
@@ -237,11 +237,11 @@ public class MandatoryTestCase {
CompiledQueryProfileRegistry cRegistry = fixture.registry.compile();
assertError("Incomplete query: Parameter 'foobar' is mandatory in query profile 'mandatory' of type 'mandatory-type' but is not set",
- new Query(QueryTestCase.httpEncode("?queryProfile=mandatory"), cRegistry.getComponent("mandatory")));
+ new Query(QueryTestCase.httpEncode("?queryProfile=mandatory"), cRegistry.getComponent("mandatory")));
}
@Test
- public void testMandatoryInParentTypeWithInheritance() {
+ void testMandatoryInParentTypeWithInheritance() {
Fixture2 fixture = new Fixture2();
QueryProfile defaultProfile = new QueryProfile("default");
@@ -256,7 +256,7 @@ public class MandatoryTestCase {
CompiledQueryProfileRegistry cRegistry = fixture.registry.compile();
assertError("Incomplete query: Parameter 'foobar' is mandatory in query profile 'mandatory' of type 'mandatory-type' but is not set",
- new Query(QueryTestCase.httpEncode("?queryProfile=mandatory"), cRegistry.getComponent("mandatory")));
+ new Query(QueryTestCase.httpEncode("?queryProfile=mandatory"), cRegistry.getComponent("mandatory")));
}
private void assertError(String message,Query query) {
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/types/test/NameTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/types/test/NameTestCase.java
index fa7508ea5ac..37991f7f14f 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/types/test/NameTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/types/test/NameTestCase.java
@@ -8,10 +8,10 @@ import com.yahoo.search.query.profile.QueryProfile;
import com.yahoo.search.query.profile.types.FieldDescription;
import com.yahoo.search.query.profile.types.FieldType;
import com.yahoo.search.query.profile.types.QueryProfileType;
-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 creating invalid names
@@ -21,7 +21,7 @@ import static org.junit.Assert.fail;
public class NameTestCase {
@Test
- public void testNames() {
+ void testNames() {
assertLegalName("aB");
assertIllegalName("a.");
assertLegalName("_a_b");
@@ -33,11 +33,11 @@ public class NameTestCase {
}
@Test
- public void testFieldNames() {
+ void testFieldNames() {
assertLegalFieldName("aB");
try {
- QueryProfile profile=new QueryProfile("test");
- profile.set("a.","anyValue", (QueryProfileRegistry)null);
+ QueryProfile profile = new QueryProfile("test");
+ profile.set("a.", "anyValue", (QueryProfileRegistry) null);
fail("Should have failed");
} catch (IllegalArgumentException e) {
assertEquals("'a.' is not a legal compound name. Names can not end with a dot.", e.getMessage());
@@ -48,12 +48,12 @@ public class NameTestCase {
assertLegalFieldName("/a/b");
assertLegalFieldName("/a/b/");
assertIllegalFieldName("aBc.dooEee.ce_d.-some-other.moreHere",
- "Could not set 'aBc.dooEee.ce_d.-some-other.moreHere' to 'anyValue'",
- "Illegal name '-some-other'");
+ "Could not set 'aBc.dooEee.ce_d.-some-other.moreHere' to 'anyValue'",
+ "Illegal name '-some-other'");
}
@Test
- public void testComponentIdAsCompoundName() {
+ void testComponentIdAsCompoundName() {
String name = "a/b";
assertEquals(new CompoundName(name), new QueryProfileType(name).getComponentIdAsCompoundName());
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/types/test/NativePropertiesTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/types/test/NativePropertiesTestCase.java
index 6f884650b5d..72499002ba9 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/types/test/NativePropertiesTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/types/test/NativePropertiesTestCase.java
@@ -7,10 +7,10 @@ import com.yahoo.search.Query;
import com.yahoo.search.query.profile.QueryProfile;
import com.yahoo.search.query.profile.types.QueryProfileType;
import com.yahoo.yolean.Exceptions;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-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;
/**
* Tests that properties can not be set even if they are native, if declared not settable in the query profile
@@ -20,7 +20,7 @@ import static org.junit.Assert.fail;
public class NativePropertiesTestCase {
@Test
- public void testNativeInStrict() {
+ void testNativeInStrict() {
QueryProfileType strictType = new QueryProfileType("strict");
strictType.setStrict(true);
QueryProfile strict = new QueryProfile("profile");
@@ -39,7 +39,7 @@ public class NativePropertiesTestCase {
} catch (IllegalArgumentException e) {
// As expected.
assertTrue(Exceptions.toMessageString(e).contains(
- "Could not set 'notnative' to '5':"
+ "Could not set 'notnative' to '5':"
+ " 'notnative' is not declared in query profile type 'strict', and the type is strict"));
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/types/test/OverrideTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/types/test/OverrideTestCase.java
index 906d43790bd..69d577719c5 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/types/test/OverrideTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/types/test/OverrideTestCase.java
@@ -13,10 +13,10 @@ import com.yahoo.search.query.profile.types.FieldDescription;
import com.yahoo.search.query.profile.types.FieldType;
import com.yahoo.search.query.profile.types.QueryProfileType;
import com.yahoo.search.query.profile.types.QueryProfileTypeRegistry;
-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;
/**
* Tests overriding of field values
@@ -29,7 +29,7 @@ public class OverrideTestCase {
private QueryProfileType type, user;
- @Before
+ @BeforeEach
public void setUp() {
type=new QueryProfileType(new ComponentId("testtype"));
user=new QueryProfileType(new ComponentId("user"));
@@ -60,38 +60,38 @@ public class OverrideTestCase {
/** Check that a simple non-overridable string cannot be overridden */
@Test
- public void testSimpleUnoverridable() {
+ void testSimpleUnoverridable() {
QueryProfileRegistry registry = new QueryProfileRegistry();
- QueryProfile test=new QueryProfile("test");
+ QueryProfile test = new QueryProfile("test");
test.setType(type);
- test.set("myString","finalString", (QueryProfileRegistry)null);
+ test.set("myString", "finalString", (QueryProfileRegistry) null);
registry.register(test);
registry.freeze();
// Assert request assignment does not work
Query query = new Query(HttpRequest.createTestRequest("?myString=newValue", Method.GET), registry.compile().getComponent("test"));
- assertEquals(0,query.errors().size());
- assertEquals("finalString",query.properties().get("myString"));
+ assertEquals(0, query.errors().size());
+ assertEquals("finalString", query.properties().get("myString"));
// Assert direct assignment does not work
- query.properties().set("myString","newValue");
- assertEquals("finalString",query.properties().get("myString"));
+ query.properties().set("myString", "newValue");
+ assertEquals("finalString", query.properties().get("myString"));
}
/** Check that a query profile cannot be overridden */
@Test
- public void testUnoverridableQueryProfile() {
+ void testUnoverridableQueryProfile() {
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfile test = new QueryProfile("test");
test.setType(type);
registry.register(test);
- QueryProfile myUser=new QueryProfile("user");
+ QueryProfile myUser = new QueryProfile("user");
myUser.setType(user);
- myUser.set("myUserInteger",1, registry);
- myUser.set("myUserString","userValue", registry);
- test.set("myUserQueryProfile",myUser, registry);
+ myUser.set("myUserInteger", 1, registry);
+ myUser.set("myUserString", "userValue", registry);
+ test.set("myUserQueryProfile", myUser, registry);
registry.register(myUser);
QueryProfile otherUser = new QueryProfile("otherUser");
@@ -102,52 +102,52 @@ public class OverrideTestCase {
CompiledQueryProfileRegistry cRegistry = registry.compile();
Query query = new Query(HttpRequest.createTestRequest("?myUserQueryprofile=otherUser", Method.GET), cRegistry.getComponent("test"));
- assertEquals(0,query.errors().size());
- assertEquals(1,query.properties().get("myUserQueryProfile.myUserInteger"));
+ assertEquals(0, query.errors().size());
+ assertEquals(1, query.properties().get("myUserQueryProfile.myUserInteger"));
}
/** Check that non-overridables are protected also in nested untyped references */
@Test
- public void testUntypedNestedUnoverridable() {
+ void testUntypedNestedUnoverridable() {
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfile topMap = new QueryProfile("topMap");
registry.register(topMap);
- QueryProfile subMap=new QueryProfile("topSubMap");
- topMap.set("subMap",subMap, registry);
+ QueryProfile subMap = new QueryProfile("topSubMap");
+ topMap.set("subMap", subMap, registry);
registry.register(subMap);
QueryProfile test = new QueryProfile("test");
test.setType(type);
- subMap.set("test",test, registry);
+ subMap.set("test", test, registry);
registry.register(test);
- QueryProfile myUser=new QueryProfile("user");
+ QueryProfile myUser = new QueryProfile("user");
myUser.setType(user);
- myUser.set("myUserString","finalValue", registry);
- test.set("myUserQueryProfile",myUser, registry);
+ myUser.set("myUserString", "finalValue", registry);
+ test.set("myUserQueryProfile", myUser, registry);
registry.register(myUser);
registry.freeze();
Query query = new Query(HttpRequest.createTestRequest("?subMap.test.myUserQueryProfile.myUserString=newValue", Method.GET), registry.compile().getComponent("topMap"));
- assertEquals(0,query.errors().size());
- assertEquals("finalValue",query.properties().get("subMap.test.myUserQueryProfile.myUserString"));
+ assertEquals(0, query.errors().size());
+ assertEquals("finalValue", query.properties().get("subMap.test.myUserQueryProfile.myUserString"));
- query.properties().set("subMap.test.myUserQueryProfile.myUserString","newValue");
- assertEquals("finalValue",query.properties().get("subMap.test.myUserQueryProfile.myUserString"));
+ query.properties().set("subMap.test.myUserQueryProfile.myUserString", "newValue");
+ assertEquals("finalValue", query.properties().get("subMap.test.myUserQueryProfile.myUserString"));
}
/** Tests overridability in an inherited field */
@Test
- public void testInheritedNonOverridableInType() {
+ void testInheritedNonOverridableInType() {
QueryProfileRegistry registry = new QueryProfileRegistry();
- QueryProfile test=new QueryProfile("test");
+ QueryProfile test = new QueryProfile("test");
test.setType(type);
- test.set("myString","finalString", (QueryProfileRegistry)null);
+ test.set("myString", "finalString", (QueryProfileRegistry) null);
registry.register(test);
- QueryProfile profile=new QueryProfile("profile");
+ QueryProfile profile = new QueryProfile("profile");
profile.addInherited(test);
registry.register(profile);
@@ -155,16 +155,16 @@ public class OverrideTestCase {
Query query = new Query(HttpRequest.createTestRequest("?myString=newString", Method.GET), registry.compile().getComponent("test"));
- assertEquals(0,query.errors().size());
- assertEquals("finalString",query.properties().get("myString"));
+ assertEquals(0, query.errors().size());
+ assertEquals("finalString", query.properties().get("myString"));
- query.properties().set("myString","newString");
- assertEquals("finalString",query.properties().get("myString"));
+ query.properties().set("myString", "newString");
+ assertEquals("finalString", query.properties().get("myString"));
}
/** Tests overridability in an inherited field */
@Test
- public void testInheritedNonOverridableInProfile() {
+ void testInheritedNonOverridableInProfile() {
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfile test = new QueryProfile("test");
test.setType(type);
@@ -172,7 +172,7 @@ public class OverrideTestCase {
test.setOverridable("myInteger", false, DimensionValues.empty);
registry.register(test);
- QueryProfile profile=new QueryProfile("profile");
+ QueryProfile profile = new QueryProfile("profile");
profile.addInherited(test);
registry.register(profile);
@@ -180,11 +180,11 @@ public class OverrideTestCase {
Query query = new Query(HttpRequest.createTestRequest("?myInteger=32", Method.GET), registry.compile().getComponent("test"));
- assertEquals(0,query.errors().size());
- assertEquals(1,query.properties().get("myInteger"));
+ assertEquals(0, query.errors().size());
+ assertEquals(1, query.properties().get("myInteger"));
- query.properties().set("myInteger",32);
- assertEquals(1,query.properties().get("myInteger"));
+ query.properties().set("myInteger", 32);
+ assertEquals(1, query.properties().get("myInteger"));
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/types/test/PatchMatchingTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/types/test/PatchMatchingTestCase.java
index d39bfa13126..58d92d84e94 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/types/test/PatchMatchingTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/types/test/PatchMatchingTestCase.java
@@ -4,10 +4,10 @@ package com.yahoo.search.query.profile.types.test;
import com.yahoo.search.query.profile.QueryProfile;
import com.yahoo.search.query.profile.QueryProfileRegistry;
import com.yahoo.search.query.profile.types.QueryProfileType;
-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;
/**
* Tests that matching query profiles by path name works
@@ -17,62 +17,62 @@ import static org.junit.Assert.assertNull;
public class PatchMatchingTestCase {
@Test
- public void testPatchMatching() {
- QueryProfileType type=new QueryProfileType("type");
+ void testPatchMatching() {
+ QueryProfileType type = new QueryProfileType("type");
type.setMatchAsPath(true);
- QueryProfile a=new QueryProfile("a");
+ QueryProfile a = new QueryProfile("a");
a.setType(type);
- QueryProfile abee=new QueryProfile("a/bee");
+ QueryProfile abee = new QueryProfile("a/bee");
abee.setType(type);
abee.addInherited(a);
- QueryProfile abeece=new QueryProfile("a/bee/ce");
+ QueryProfile abeece = new QueryProfile("a/bee/ce");
abeece.setType(type);
abeece.addInherited(abee);
- QueryProfileRegistry registry=new QueryProfileRegistry();
+ QueryProfileRegistry registry = new QueryProfileRegistry();
registry.register(a);
registry.register(abee);
registry.register(abeece);
registry.freeze();
assertNull(registry.findQueryProfile(null)); // No "default" registered
- assertEquals("a",registry.findQueryProfile("a").getId().getName());
- assertEquals("a/bee",registry.findQueryProfile("a/bee").getId().getName());
- assertEquals("a/bee/ce",registry.findQueryProfile("a/bee/ce").getId().getName());
- assertEquals("a/bee/ce",registry.findQueryProfile("a/bee/ce/dee").getId().getName());
- assertEquals("a/bee/ce",registry.findQueryProfile("a/bee/ce/dee/eee/").getId().getName());
- assertEquals("a/bee",registry.findQueryProfile("a/bee/cede").getId().getName());
- assertEquals("a",registry.findQueryProfile("a/foo/bee/cede").getId().getName());
+ assertEquals("a", registry.findQueryProfile("a").getId().getName());
+ assertEquals("a/bee", registry.findQueryProfile("a/bee").getId().getName());
+ assertEquals("a/bee/ce", registry.findQueryProfile("a/bee/ce").getId().getName());
+ assertEquals("a/bee/ce", registry.findQueryProfile("a/bee/ce/dee").getId().getName());
+ assertEquals("a/bee/ce", registry.findQueryProfile("a/bee/ce/dee/eee/").getId().getName());
+ assertEquals("a/bee", registry.findQueryProfile("a/bee/cede").getId().getName());
+ assertEquals("a", registry.findQueryProfile("a/foo/bee/cede").getId().getName());
assertNull(registry.findQueryProfile("abee"));
}
@Test
- public void testNoPatchMatching() {
- QueryProfileType type=new QueryProfileType("type");
+ void testNoPatchMatching() {
+ QueryProfileType type = new QueryProfileType("type");
type.setMatchAsPath(false); // Default, but set here for clarity
- QueryProfile a=new QueryProfile("a");
+ QueryProfile a = new QueryProfile("a");
a.setType(type);
- QueryProfile abee=new QueryProfile("a/bee");
+ QueryProfile abee = new QueryProfile("a/bee");
abee.setType(type);
abee.addInherited(a);
- QueryProfile abeece=new QueryProfile("a/bee/ce");
+ QueryProfile abeece = new QueryProfile("a/bee/ce");
abeece.setType(type);
abeece.addInherited(abee);
- QueryProfileRegistry registry=new QueryProfileRegistry();
+ QueryProfileRegistry registry = new QueryProfileRegistry();
registry.register(a);
registry.register(abee);
registry.register(abeece);
registry.freeze();
assertNull(registry.findQueryProfile(null)); // No "default" registered
- assertEquals("a",registry.findQueryProfile("a").getId().getName());
- assertEquals("a/bee",registry.findQueryProfile("a/bee").getId().getName());
- assertEquals("a/bee/ce",registry.findQueryProfile("a/bee/ce").getId().getName());
+ assertEquals("a", registry.findQueryProfile("a").getId().getName());
+ assertEquals("a/bee", registry.findQueryProfile("a/bee").getId().getName());
+ assertEquals("a/bee/ce", registry.findQueryProfile("a/bee/ce").getId().getName());
assertNull(registry.findQueryProfile("a/bee/ce/dee")); // Different from test above
assertNull(registry.findQueryProfile("a/bee/ce/dee/eee/")); // Different from test above
assertNull(registry.findQueryProfile("a/bee/cede")); // Different from test above
@@ -82,59 +82,59 @@ public class PatchMatchingTestCase {
/** Check that the path matching property is inherited to subtypes */
@Test
- public void testPatchMatchingInheritance() {
- QueryProfileType type=new QueryProfileType("type");
- QueryProfileType subType=new QueryProfileType("subType");
+ void testPatchMatchingInheritance() {
+ QueryProfileType type = new QueryProfileType("type");
+ QueryProfileType subType = new QueryProfileType("subType");
subType.inherited().add(type);
type.setMatchAsPath(true); // Supertype only
- QueryProfile a=new QueryProfile("a");
+ QueryProfile a = new QueryProfile("a");
a.setType(type);
- QueryProfile abee=new QueryProfile("a/bee");
+ QueryProfile abee = new QueryProfile("a/bee");
abee.setType(subType);
abee.addInherited(a);
- QueryProfile abeece=new QueryProfile("a/bee/ce");
+ QueryProfile abeece = new QueryProfile("a/bee/ce");
abeece.setType(subType);
abeece.addInherited(abee);
- QueryProfileRegistry registry=new QueryProfileRegistry();
+ QueryProfileRegistry registry = new QueryProfileRegistry();
registry.register(a);
registry.register(abee);
registry.register(abeece);
registry.freeze();
assertNull(registry.findQueryProfile(null)); // No "default" registered
- assertEquals("a",registry.findQueryProfile("a").getId().getName());
- assertEquals("a/bee",registry.findQueryProfile("a/bee").getId().getName());
- assertEquals("a/bee/ce",registry.findQueryProfile("a/bee/ce").getId().getName());
- assertEquals("a/bee/ce",registry.findQueryProfile("a/bee/ce/dee").getId().getName());
- assertEquals("a/bee/ce",registry.findQueryProfile("a/bee/ce/dee/eee/").getId().getName());
- assertEquals("a/bee",registry.findQueryProfile("a/bee/cede").getId().getName());
- assertEquals("a",registry.findQueryProfile("a/foo/bee/cede").getId().getName());
+ assertEquals("a", registry.findQueryProfile("a").getId().getName());
+ assertEquals("a/bee", registry.findQueryProfile("a/bee").getId().getName());
+ assertEquals("a/bee/ce", registry.findQueryProfile("a/bee/ce").getId().getName());
+ assertEquals("a/bee/ce", registry.findQueryProfile("a/bee/ce/dee").getId().getName());
+ assertEquals("a/bee/ce", registry.findQueryProfile("a/bee/ce/dee/eee/").getId().getName());
+ assertEquals("a/bee", registry.findQueryProfile("a/bee/cede").getId().getName());
+ assertEquals("a", registry.findQueryProfile("a/foo/bee/cede").getId().getName());
assertNull(registry.findQueryProfile("abee"));
}
/** Check that the path matching works with versioned profiles */
@Test
- public void testPatchMatchingVersions() {
- QueryProfileType type=new QueryProfileType("type");
+ void testPatchMatchingVersions() {
+ QueryProfileType type = new QueryProfileType("type");
type.setMatchAsPath(true);
- QueryProfile a=new QueryProfile("a");
+ QueryProfile a = new QueryProfile("a");
a.setType(type);
- QueryProfile abee11=new QueryProfile("a/bee:1.1");
+ QueryProfile abee11 = new QueryProfile("a/bee:1.1");
abee11.setType(type);
abee11.addInherited(a);
- QueryProfile abee13=new QueryProfile("a/bee:1.3");
+ QueryProfile abee13 = new QueryProfile("a/bee:1.3");
abee13.setType(type);
abee13.addInherited(a);
- QueryProfile abeece=new QueryProfile("a/bee/ce");
+ QueryProfile abeece = new QueryProfile("a/bee/ce");
abeece.setType(type);
abeece.addInherited(abee13);
- QueryProfileRegistry registry=new QueryProfileRegistry();
+ QueryProfileRegistry registry = new QueryProfileRegistry();
registry.register(a);
registry.register(abee11);
registry.register(abee13);
@@ -142,52 +142,52 @@ public class PatchMatchingTestCase {
registry.freeze();
assertNull(registry.findQueryProfile(null)); // No "default" registered
- assertEquals("a",registry.findQueryProfile("a").getId().getName());
- assertEquals("a/bee:1.1",registry.findQueryProfile("a/bee:1.1").getId().toString());
- assertEquals("a/bee:1.3",registry.findQueryProfile("a/bee").getId().toString());
- assertEquals("a/bee:1.3",registry.findQueryProfile("a/bee:1").getId().toString());
- assertEquals("a/bee/ce",registry.findQueryProfile("a/bee/ce").getId().getName());
- assertEquals("a/bee/ce",registry.findQueryProfile("a/bee/ce/dee").getId().getName());
- assertEquals("a/bee/ce",registry.findQueryProfile("a/bee/ce/dee/eee/").getId().getName());
- assertEquals("a/bee:1.1",registry.findQueryProfile("a/bee/cede:1.1").getId().toString());
- assertEquals("a/bee:1.3",registry.findQueryProfile("a/bee/cede").getId().toString());
- assertEquals("a/bee:1.3",registry.findQueryProfile("a/bee/cede:1").getId().toString());
- assertEquals("a",registry.findQueryProfile("a/foo/bee/cede").getId().getName());
+ assertEquals("a", registry.findQueryProfile("a").getId().getName());
+ assertEquals("a/bee:1.1", registry.findQueryProfile("a/bee:1.1").getId().toString());
+ assertEquals("a/bee:1.3", registry.findQueryProfile("a/bee").getId().toString());
+ assertEquals("a/bee:1.3", registry.findQueryProfile("a/bee:1").getId().toString());
+ assertEquals("a/bee/ce", registry.findQueryProfile("a/bee/ce").getId().getName());
+ assertEquals("a/bee/ce", registry.findQueryProfile("a/bee/ce/dee").getId().getName());
+ assertEquals("a/bee/ce", registry.findQueryProfile("a/bee/ce/dee/eee/").getId().getName());
+ assertEquals("a/bee:1.1", registry.findQueryProfile("a/bee/cede:1.1").getId().toString());
+ assertEquals("a/bee:1.3", registry.findQueryProfile("a/bee/cede").getId().toString());
+ assertEquals("a/bee:1.3", registry.findQueryProfile("a/bee/cede:1").getId().toString());
+ assertEquals("a", registry.findQueryProfile("a/foo/bee/cede").getId().getName());
assertNull(registry.findQueryProfile("abee"));
}
@Test
- public void testQuirkyNames() {
- QueryProfileType type=new QueryProfileType("type");
+ void testQuirkyNames() {
+ QueryProfileType type = new QueryProfileType("type");
type.setMatchAsPath(true);
- QueryProfile a=new QueryProfile("/a");
+ QueryProfile a = new QueryProfile("/a");
a.setType(type);
- QueryProfile abee=new QueryProfile("/a//bee");
+ QueryProfile abee = new QueryProfile("/a//bee");
abee.setType(type);
abee.addInherited(a);
- QueryProfile abeece=new QueryProfile("/a//bee/ce/");
+ QueryProfile abeece = new QueryProfile("/a//bee/ce/");
abeece.setType(type);
abeece.addInherited(abee);
- QueryProfileRegistry registry=new QueryProfileRegistry();
+ QueryProfileRegistry registry = new QueryProfileRegistry();
registry.register(a);
registry.register(abee);
registry.register(abeece);
registry.freeze();
assertNull(registry.findQueryProfile(null)); // No "default" registered
- assertEquals("/a",registry.findQueryProfile("/a").getId().getName());
+ assertEquals("/a", registry.findQueryProfile("/a").getId().getName());
assertNull(registry.findQueryProfile("a"));
- assertEquals("/a//bee",registry.findQueryProfile("/a//bee").getId().getName());
- assertEquals("/a//bee/ce/",registry.findQueryProfile("/a//bee/ce/").getId().getName());
- assertEquals("/a//bee/ce/",registry.findQueryProfile("/a//bee/ce").getId().getName());
- assertEquals("/a//bee/ce/",registry.findQueryProfile("/a//bee/ce/dee").getId().getName());
- assertEquals("/a//bee/ce/",registry.findQueryProfile("/a//bee/ce/dee/eee/").getId().getName());
- assertEquals("/a//bee",registry.findQueryProfile("/a//bee/cede").getId().getName());
- assertEquals("/a",registry.findQueryProfile("/a/foo/bee/cede").getId().getName());
- assertEquals("/a",registry.findQueryProfile("/a/bee").getId().getName());
+ assertEquals("/a//bee", registry.findQueryProfile("/a//bee").getId().getName());
+ assertEquals("/a//bee/ce/", registry.findQueryProfile("/a//bee/ce/").getId().getName());
+ assertEquals("/a//bee/ce/", registry.findQueryProfile("/a//bee/ce").getId().getName());
+ assertEquals("/a//bee/ce/", registry.findQueryProfile("/a//bee/ce/dee").getId().getName());
+ assertEquals("/a//bee/ce/", registry.findQueryProfile("/a//bee/ce/dee/eee/").getId().getName());
+ assertEquals("/a//bee", registry.findQueryProfile("/a//bee/cede").getId().getName());
+ assertEquals("/a", registry.findQueryProfile("/a/foo/bee/cede").getId().getName());
+ assertEquals("/a", registry.findQueryProfile("/a/bee").getId().getName());
assertNull(registry.findQueryProfile("abee"));
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/types/test/QueryProfileTypeInheritanceTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/types/test/QueryProfileTypeInheritanceTestCase.java
index 62551447017..cc7b5c4d666 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/types/test/QueryProfileTypeInheritanceTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/types/test/QueryProfileTypeInheritanceTestCase.java
@@ -9,13 +9,10 @@ import com.yahoo.search.query.profile.types.FieldDescription;
import com.yahoo.search.query.profile.types.FieldType;
import com.yahoo.search.query.profile.types.QueryProfileType;
import com.yahoo.search.query.profile.types.QueryProfileTypeRegistry;
-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.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -26,7 +23,7 @@ public class QueryProfileTypeInheritanceTestCase {
private QueryProfileType type, typeStrict, user, userStrict;
- @Before
+ @BeforeEach
public void setUp() {
type=new QueryProfileType(new ComponentId("testtype"));
typeStrict=new QueryProfileType(new ComponentId("testtypeStrict"));
@@ -63,7 +60,7 @@ public class QueryProfileTypeInheritanceTestCase {
}
@Test
- public void testInheritance() {
+ void testInheritance() {
type.inherited().add(user);
type.freeze();
user.freeze();
@@ -71,11 +68,11 @@ public class QueryProfileTypeInheritanceTestCase {
assertFalse(type.isOverridable("myUserString"));
assertEquals("myUserInteger", type.getField("myUserInteger").getName());
- QueryProfile test=new QueryProfile("test");
+ QueryProfile test = new QueryProfile("test");
test.setType(type);
- test.set("myUserInteger","37", (QueryProfileRegistry)null);
- test.set("myUnknownInteger","38", (QueryProfileRegistry)null);
+ test.set("myUserInteger", "37", (QueryProfileRegistry) null);
+ test.set("myUnknownInteger", "38", (QueryProfileRegistry) null);
CompiledQueryProfile ctest = test.compile(null);
assertEquals(37, ctest.get("myUserInteger"));
@@ -83,45 +80,45 @@ public class QueryProfileTypeInheritanceTestCase {
}
@Test
- public void testInheritanceStrict() {
+ void testInheritanceStrict() {
typeStrict.inherited().add(userStrict);
typeStrict.freeze();
userStrict.freeze();
- QueryProfile test=new QueryProfile("test");
+ QueryProfile test = new QueryProfile("test");
test.setType(typeStrict);
- test.set("myUserInteger","37", (QueryProfileRegistry)null);
+ test.set("myUserInteger", "37", (QueryProfileRegistry) null);
try {
- test.set("myUnknownInteger","38", (QueryProfileRegistry)null);
+ test.set("myUnknownInteger", "38", (QueryProfileRegistry) null);
fail("Should have failed");
}
catch (IllegalArgumentException e) {
assertEquals("'myUnknownInteger' is not declared in query profile type 'testtypeStrict', and the type is strict",
- e.getCause().getMessage());
+ e.getCause().getMessage());
}
- assertEquals(37,test.get("myUserInteger"));
+ assertEquals(37, test.get("myUserInteger"));
assertNull(test.get("myUnknownInteger"));
}
@Test
- public void testStrictIsInherited() {
+ void testStrictIsInherited() {
type.inherited().add(userStrict);
type.freeze();
userStrict.freeze();
- QueryProfile test=new QueryProfile("test");
+ QueryProfile test = new QueryProfile("test");
test.setType(type);
- test.set("myUserInteger","37", (QueryProfileRegistry)null);
+ test.set("myUserInteger", "37", (QueryProfileRegistry) null);
try {
- test.set("myUnknownInteger","38", (QueryProfileRegistry)null);
+ test.set("myUnknownInteger", "38", (QueryProfileRegistry) null);
fail("Should have failed");
}
catch (IllegalArgumentException e) {
assertEquals("'myUnknownInteger' is not declared in query profile type 'testtype', and the type is strict",
- e.getCause().getMessage());
+ e.getCause().getMessage());
}
CompiledQueryProfile ctest = test.compile(null);
diff --git a/container-search/src/test/java/com/yahoo/search/query/profile/types/test/QueryProfileTypeTestCase.java b/container-search/src/test/java/com/yahoo/search/query/profile/types/test/QueryProfileTypeTestCase.java
index a77de954b3a..21a9b2fe399 100644
--- a/container-search/src/test/java/com/yahoo/search/query/profile/types/test/QueryProfileTypeTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/profile/types/test/QueryProfileTypeTestCase.java
@@ -19,19 +19,15 @@ import com.yahoo.search.query.profile.types.FieldDescription;
import com.yahoo.search.query.profile.types.FieldType;
import com.yahoo.search.query.profile.types.QueryProfileType;
import com.yahoo.search.query.profile.types.QueryProfileTypeRegistry;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertThrows;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* tests query profiles with/and types
@@ -44,7 +40,7 @@ public class QueryProfileTypeTestCase {
private QueryProfileType testtype, emptyInheritingTesttype, testtypeStrict, user, userStrict;
- @Before
+ @BeforeEach
public void setUp() {
registry = new QueryProfileRegistry();
@@ -95,24 +91,24 @@ public class QueryProfileTypeTestCase {
}
@Test
- public void testTypedOfPrimitivesAssignmentNonStrict() {
+ void testTypedOfPrimitivesAssignmentNonStrict() {
QueryProfile profile = new QueryProfile("test");
profile.setType(testtype);
registry.register(profile);
profile.set("myString", "anyValue", registry);
profile.set("nontypedString", "anyValueToo", registry); // legal because this is not strict
- assertWrongType(profile,"integer", "myInteger","notInteger");
+ assertWrongType(profile, "integer", "myInteger", "notInteger");
assertWrongType(profile, "integer", "myInteger", "1.5");
profile.set("myInteger", 3, registry);
- assertWrongType(profile,"long","myLong","notLong");
+ assertWrongType(profile, "long", "myLong", "notLong");
assertWrongType(profile, "long", "myLong", "1.5");
profile.set("myLong", 4000000000000L, registry);
assertWrongType(profile, "float", "myFloat", "notFloat");
profile.set("myFloat", 3.14f, registry);
assertWrongType(profile, "double", "myDouble", "notDouble");
- profile.set("myDouble",2.18, registry);
- profile.set("myBoolean",true, registry);
+ profile.set("myDouble", 2.18, registry);
+ profile.set("myBoolean", true, registry);
String tensorString1 = "{{a:a1, b:b1}:1.0, {a:a2, b:b1}:2.0}}";
profile.set("ranking.features.query(myTensor1)", tensorString1, registry);
@@ -122,12 +118,12 @@ public class QueryProfileTypeTestCase {
profile.set("ranking.features.query(myTensor3)", tensorString3, registry);
profile.set("myQuery", "...", registry); // TODO
- profile.set("myQueryProfile.anyString","value1", registry);
- profile.set("myQueryProfile.anyDouble",8.76, registry);
- profile.set("myUserQueryProfile.myUserString","value2", registry);
+ profile.set("myQueryProfile.anyString", "value1", registry);
+ profile.set("myQueryProfile.anyDouble", 8.76, registry);
+ profile.set("myUserQueryProfile.myUserString", "value2", registry);
profile.set("myUserQueryProfile.anyString", "value3", registry); // Legal because user is not strict
assertWrongType(profile, "integer", "myUserQueryProfile.myUserInteger", "notInteger");
- profile.set("myUserQueryProfile.uint",1337, registry); // Set using alias
+ profile.set("myUserQueryProfile.uint", 1337, registry); // Set using alias
profile.set("myUserQueryProfile.anyDouble", 9.13, registry); // Legal because user is not strict
CompiledQueryProfileRegistry cRegistry = registry.compile();
@@ -162,22 +158,22 @@ public class QueryProfileTypeTestCase {
}
@Test
- public void testTypedOfPrimitivesAssignmentStrict() {
+ void testTypedOfPrimitivesAssignmentStrict() {
QueryProfile profile = new QueryProfile("test");
profile.setType(testtypeStrict);
profile.set("myString", "anyValue", registry);
assertNotPermitted(profile, "nontypedString", "anyValueToo"); // Illegal because this is strict
- assertWrongType(profile,"integer","myInteger","notInteger");
+ assertWrongType(profile, "integer", "myInteger", "notInteger");
assertWrongType(profile, "integer", "myInteger", "1.5");
profile.set("myInteger", 3, registry);
- assertWrongType(profile,"long","myLong","notLong");
+ assertWrongType(profile, "long", "myLong", "notLong");
assertWrongType(profile, "long", "myLong", "1.5");
profile.set("myLong", 4000000000000L, registry);
assertWrongType(profile, "float", "myFloat", "notFloat");
profile.set("myFloat", 3.14f, registry);
assertWrongType(profile, "double", "myDouble", "notDouble");
- profile.set("myDouble",2.18, registry);
+ profile.set("myDouble", 2.18, registry);
profile.set("myQueryProfile.anyString", "value1", registry);
profile.set("myQueryProfile.anyDouble", 8.76, registry);
profile.set("myUserQueryProfile.myUserString", "value2", registry);
@@ -204,22 +200,22 @@ public class QueryProfileTypeTestCase {
/** Tests assigning a subprofile directly */
@Test
- public void testTypedAssignmentOfQueryProfilesNonStrict() {
+ void testTypedAssignmentOfQueryProfilesNonStrict() {
QueryProfile profile = new QueryProfile("test");
profile.setType(testtype);
- QueryProfile map1=new QueryProfile("myMap1");
+ QueryProfile map1 = new QueryProfile("myMap1");
map1.set("key1", "value1", registry);
- QueryProfile map2=new QueryProfile("myMap2");
+ QueryProfile map2 = new QueryProfile("myMap2");
map2.set("key2", "value2", registry);
- QueryProfile myUser=new QueryProfile("myUser");
+ QueryProfile myUser = new QueryProfile("myUser");
myUser.setType(user);
myUser.set("myUserString", "userValue1", registry);
myUser.set("myUserInteger", 442, registry);
- assertWrongType(profile,"reference to a query profile","myQueryProfile","aString");
+ assertWrongType(profile, "reference to a query profile", "myQueryProfile", "aString");
profile.set("myQueryProfile", map1, registry);
profile.set("someMap", map2, registry); // Legal because this is not strict
assertWrongType(profile, "reference to a query profile of type 'user'", "myUserQueryProfile", map1);
@@ -235,14 +231,14 @@ public class QueryProfileTypeTestCase {
/** Tests assigning a subprofile directly */
@Test
- public void testTypedAssignmentOfQueryProfilesStrict() {
+ void testTypedAssignmentOfQueryProfilesStrict() {
QueryProfile profile = new QueryProfile("test");
profile.setType(testtypeStrict);
- QueryProfile map1=new QueryProfile("myMap1");
+ QueryProfile map1 = new QueryProfile("myMap1");
map1.set("key1", "value1", registry);
- QueryProfile map2=new QueryProfile("myMap2");
+ QueryProfile map2 = new QueryProfile("myMap2");
map2.set("key2", "value2", registry);
QueryProfile myUser = new QueryProfile("myUser");
@@ -250,10 +246,10 @@ public class QueryProfileTypeTestCase {
myUser.set("myUserString", "userValue1", registry);
myUser.set("myUserInteger", 442, registry);
- assertWrongType(profile,"reference to a query profile","myQueryProfile","aString");
+ assertWrongType(profile, "reference to a query profile", "myQueryProfile", "aString");
profile.set("myQueryProfile", map1, registry);
- assertNotPermitted(profile,"someMap", map2);
- assertWrongType(profile,"reference to a query profile of type 'userStrict'", "myUserQueryProfile", map1);
+ assertNotPermitted(profile, "someMap", map2);
+ assertWrongType(profile, "reference to a query profile of type 'userStrict'", "myUserQueryProfile", map1);
profile.set("myUserQueryProfile", myUser, registry);
CompiledQueryProfile cprofile = profile.compile(null);
@@ -266,7 +262,7 @@ public class QueryProfileTypeTestCase {
/** Tests assigning a subprofile as an id string */
@Test
- public void testTypedAssignmentOfQueryProfileReferencesNonStrict() {
+ void testTypedAssignmentOfQueryProfileReferencesNonStrict() {
QueryProfile profile = new QueryProfile("test");
profile.setType(testtype);
@@ -286,21 +282,21 @@ public class QueryProfileTypeTestCase {
registry.register(map2);
registry.register(myUser);
- assertWrongType(profile,"reference to a query profile", "myQueryProfile", "aString");
+ assertWrongType(profile, "reference to a query profile", "myQueryProfile", "aString");
registry.register(map1);
profile.set("myQueryProfile", "myMap1", registry);
registry.register(map2);
profile.set("someMap", "myMap2", registry); // NOTICE: Will set as a string because we cannot know this is a reference
assertWrongType(profile, "reference to a query profile of type 'user'", "myUserQueryProfile", "myMap1");
registry.register(myUser);
- profile.set("myUserQueryProfile","myUser", registry);
+ profile.set("myUserQueryProfile", "myUser", registry);
CompiledQueryProfileRegistry cRegistry = registry.compile();
CompiledQueryProfile cprofile = cRegistry.getComponent("test");
assertEquals("value1", cprofile.get("myQueryProfile.key1"));
assertEquals("myMap2", cprofile.get("someMap"));
- assertNull("Asking for an value which cannot be completely resolved returns null", cprofile.get("someMap.key2"));
+ assertNull(cprofile.get("someMap.key2"), "Asking for an value which cannot be completely resolved returns null");
assertEquals("userValue1", cprofile.get("myUserQueryProfile.myUserString"));
assertEquals(442, cprofile.get("myUserQueryProfile.myUserInteger"));
}
@@ -310,11 +306,11 @@ public class QueryProfileTypeTestCase {
* Here there exists a user profile already, and then a new one is overwritten
*/
@Test
- public void testTypedOverridingOfQueryProfileReferencesNonStrictThroughQuery() {
+ void testTypedOverridingOfQueryProfileReferencesNonStrictThroughQuery() {
QueryProfile profile = new QueryProfile("test");
profile.setType(testtype);
- QueryProfile myUser=new QueryProfile("myUser");
+ QueryProfile myUser = new QueryProfile("myUser");
myUser.setType(user);
myUser.set("myUserString", "userValue1", registry);
myUser.set("myUserInteger", 442, registry);
@@ -332,8 +328,8 @@ public class QueryProfileTypeTestCase {
CompiledQueryProfile cprofile = cRegistry.getComponent("test");
Query query = new Query(HttpRequest.createTestRequest("?myUserQueryProfile=newUser",
- com.yahoo.jdisc.http.HttpRequest.Method.GET),
- cprofile);
+ com.yahoo.jdisc.http.HttpRequest.Method.GET),
+ cprofile);
assertEquals(0, query.errors().size());
@@ -346,7 +342,7 @@ public class QueryProfileTypeTestCase {
* Here no user profile is set before it is assigned in the query
*/
@Test
- public void testTypedAssignmentOfQueryProfileReferencesNonStrictThroughQuery() {
+ void testTypedAssignmentOfQueryProfileReferencesNonStrictThroughQuery() {
QueryProfile profile = new QueryProfile("test");
profile.setType(testtype);
@@ -361,8 +357,8 @@ public class QueryProfileTypeTestCase {
CompiledQueryProfile cprofile = cRegistry.getComponent("test");
Query query = new Query(HttpRequest.createTestRequest("?myUserQueryProfile=newUser",
- com.yahoo.jdisc.http.HttpRequest.Method.GET),
- cprofile);
+ com.yahoo.jdisc.http.HttpRequest.Method.GET),
+ cprofile);
assertEquals(0, query.errors().size());
@@ -375,7 +371,7 @@ public class QueryProfileTypeTestCase {
* Here no user profile is set before it is assigned in the query
*/
@Test
- public void testTypedAssignmentOfQueryProfileReferencesStrictThroughQuery() {
+ void testTypedAssignmentOfQueryProfileReferencesStrictThroughQuery() {
QueryProfile profile = new QueryProfile("test");
profile.setType(testtypeStrict);
@@ -401,13 +397,13 @@ public class QueryProfileTypeTestCase {
}
catch (IllegalArgumentException e) {
assertEquals("Could not set 'myUserQueryProfile.someKey' to 'value': 'someKey' is not declared in query profile type 'userStrict', and the type is strict",
- Exceptions.toMessageString(e));
+ Exceptions.toMessageString(e));
}
}
@Test
- public void testTensorRankFeatureInRequest() {
+ void testTensorRankFeatureInRequest() {
QueryProfile profile = new QueryProfile("test");
profile.setType(testtype);
registry.register(profile);
@@ -415,16 +411,16 @@ public class QueryProfileTypeTestCase {
CompiledQueryProfileRegistry cRegistry = registry.compile();
String tensorString = "{{a:a1, b:b1}:1.0, {a:a2, b:b1}:2.0}}";
Query query = new Query(HttpRequest.createTestRequest("?" + urlEncode("ranking.features.query(myTensor1)") +
- "=" + urlEncode(tensorString),
- com.yahoo.jdisc.http.HttpRequest.Method.GET),
- cRegistry.getComponent("test"));
+ "=" + urlEncode(tensorString),
+ com.yahoo.jdisc.http.HttpRequest.Method.GET),
+ cRegistry.getComponent("test"));
assertEquals(0, query.errors().size());
assertEquals(Tensor.from(tensorString), query.properties().get("ranking.features.query(myTensor1)"));
assertEquals(Tensor.from(tensorString), query.getRanking().getFeatures().getTensor("query(myTensor1)").get());
}
@Test
- public void testTensorRankFeatureSetProgrammatically() {
+ void testTensorRankFeatureSetProgrammatically() {
QueryProfile profile = new QueryProfile("test");
profile.setType(testtype);
registry.register(profile);
@@ -432,13 +428,13 @@ public class QueryProfileTypeTestCase {
CompiledQueryProfileRegistry cRegistry = registry.compile();
String tensorString = "{{a:a1, b:b1}:1.0, {a:a2, b:b1}:2.0}}";
Query query = new Query(HttpRequest.createTestRequest("?", com.yahoo.jdisc.http.HttpRequest.Method.GET),
- cRegistry.getComponent("test"));
+ cRegistry.getComponent("test"));
query.properties().set("ranking.features.query(myTensor1)", Tensor.from(tensorString));
assertEquals(Tensor.from(tensorString), query.getRanking().getFeatures().getTensor("query(myTensor1)").get());
}
@Test
- public void testTensorRankFeatureSetProgrammaticallyWithWrongType() {
+ void testTensorRankFeatureSetProgrammaticallyWithWrongType() {
QueryProfile profile = new QueryProfile("test");
profile.setType(testtype);
registry.register(profile);
@@ -446,15 +442,15 @@ public class QueryProfileTypeTestCase {
CompiledQueryProfileRegistry cRegistry = registry.compile();
String tensorString = "tensor(x[3]):[0.1, 0.2, 0.3]";
Query query = new Query(HttpRequest.createTestRequest("?", com.yahoo.jdisc.http.HttpRequest.Method.GET),
- cRegistry.getComponent("test"));
+ cRegistry.getComponent("test"));
try {
- query.getRanking().getFeatures().put("query(myTensor1)",Tensor.from(tensorString));
+ query.getRanking().getFeatures().put("query(myTensor1)", Tensor.from(tensorString));
fail("Expected exception");
}
catch (IllegalArgumentException e) {
assertEquals("Could not set 'ranking.features.query(myTensor1)' to 'tensor(x[3]):[0.1, 0.2, 0.3]': " +
- "Require a tensor of type tensor(a{},b{})",
- Exceptions.toMessageString(e));
+ "Require a tensor of type tensor(a{},b{})",
+ Exceptions.toMessageString(e));
}
try {
query.properties().set("ranking.features.query(myTensor1)", Tensor.from(tensorString));
@@ -462,14 +458,14 @@ public class QueryProfileTypeTestCase {
}
catch (IllegalArgumentException e) {
assertEquals("Could not set 'ranking.features.query(myTensor1)' to 'tensor(x[3]):[0.1, 0.2, 0.3]': " +
- "Require a tensor of type tensor(a{},b{})",
- Exceptions.toMessageString(e));
+ "Require a tensor of type tensor(a{},b{})",
+ Exceptions.toMessageString(e));
}
}
// Expected to work exactly as testTensorRankFeatureInRequest
@Test
- public void testTensorRankFeatureInRequestWithInheritedQueryProfileType() {
+ void testTensorRankFeatureInRequestWithInheritedQueryProfileType() {
QueryProfile profile = new QueryProfile("test");
profile.setType(emptyInheritingTesttype);
registry.register(profile);
@@ -477,16 +473,16 @@ public class QueryProfileTypeTestCase {
CompiledQueryProfileRegistry cRegistry = registry.compile();
String tensorString = "{{a:a1, b:b1}:1.0, {a:a2, b:b1}:2.0}}";
Query query = new Query(HttpRequest.createTestRequest("?" + urlEncode("ranking.features.query(myTensor1)") +
- "=" + urlEncode(tensorString),
- com.yahoo.jdisc.http.HttpRequest.Method.GET),
- cRegistry.getComponent("test"));
+ "=" + urlEncode(tensorString),
+ com.yahoo.jdisc.http.HttpRequest.Method.GET),
+ cRegistry.getComponent("test"));
assertEquals(0, query.errors().size());
assertEquals(Tensor.from(tensorString), query.properties().get("ranking.features.query(myTensor1)"));
assertEquals(Tensor.from(tensorString), query.getRanking().getFeatures().getTensor("query(myTensor1)").get());
}
@Test
- public void testUnembeddedTensorRankFeatureInRequest() {
+ void testUnembeddedTensorRankFeatureInRequest() {
String text = "text to embed into a tensor";
Tensor embedding1 = Tensor.from("tensor<float>(x[5]):[3,7,4,0,0]]");
Tensor embedding2 = Tensor.from("tensor<float>(x[5]):[1,2,3,4,0]]");
@@ -500,7 +496,7 @@ public class QueryProfileTypeTestCase {
assertEmbedQuery("embed(emb1, '" + text + "')", embedding1, embedders);
assertEmbedQuery("embed(emb1, \"" + text + "\")", embedding1, embedders);
assertEmbedQueryFails("embed(emb2, \"" + text + "\")", embedding1, embedders,
- "Can't find embedder 'emb2'. Valid embedders are emb1");
+ "Can't find embedder 'emb2'. Valid embedders are emb1");
embedders = Map.of(
"emb1", new MockEmbedder(text, Language.UNKNOWN, embedding1),
@@ -530,7 +526,7 @@ public class QueryProfileTypeTestCase {
}
@Test
- public void testIllegalStrictAssignmentFromRequest() {
+ void testIllegalStrictAssignmentFromRequest() {
QueryProfile profile = new QueryProfile("test");
profile.setType(testtypeStrict);
@@ -541,13 +537,13 @@ public class QueryProfileTypeTestCase {
try {
new Query(HttpRequest.createTestRequest("?myUserQueryProfile.nondeclared=someValue",
- com.yahoo.jdisc.http.HttpRequest.Method.GET),
- profile.compile(null));
+ com.yahoo.jdisc.http.HttpRequest.Method.GET),
+ profile.compile(null));
fail("Above statement should throw");
} catch (IllegalArgumentException e) {
// As expected.
assertTrue(Exceptions.toMessageString(e).contains(
- "Could not set 'myUserQueryProfile.nondeclared' to 'someValue': 'nondeclared' is not declared in query profile type 'userStrict', and the type is strict"));
+ "Could not set 'myUserQueryProfile.nondeclared' to 'someValue': 'nondeclared' is not declared in query profile type 'userStrict', and the type is strict"));
}
}
@@ -557,7 +553,7 @@ public class QueryProfileTypeTestCase {
* The whole thing is accessed through a two levels of nontyped top-level profiles
*/
@Test
- public void testTypedOverridingOfQueryProfileReferencesNonStrictThroughQueryNestedInAnUntypedProfile() {
+ void testTypedOverridingOfQueryProfileReferencesNonStrictThroughQueryNestedInAnUntypedProfile() {
QueryProfile topMap = new QueryProfile("topMap");
QueryProfile subMap = new QueryProfile("topSubMap");
@@ -586,8 +582,8 @@ public class QueryProfileTypeTestCase {
CompiledQueryProfileRegistry cRegistry = registry.compile();
Query query = new Query(HttpRequest.createTestRequest("?subMap.typeProfile.myUserQueryProfile=newUser",
- com.yahoo.jdisc.http.HttpRequest.Method.GET),
- cRegistry.getComponent("topMap"));
+ com.yahoo.jdisc.http.HttpRequest.Method.GET),
+ cRegistry.getComponent("topMap"));
assertEquals(0, query.errors().size());
@@ -599,7 +595,7 @@ public class QueryProfileTypeTestCase {
* Same as previous test but using the untyped myQueryProfile reference instead of the typed myUserQueryProfile
*/
@Test
- public void testAnonTypedOverridingOfQueryProfileReferencesNonStrictThroughQueryNestedInAnUntypedProfile() {
+ void testAnonTypedOverridingOfQueryProfileReferencesNonStrictThroughQueryNestedInAnUntypedProfile() {
QueryProfile topMap = new QueryProfile("topMap");
QueryProfile subMap = new QueryProfile("topSubMap");
@@ -630,15 +626,15 @@ public class QueryProfileTypeTestCase {
Query query = new Query(HttpRequest.createTestRequest("?subMap.typeProfile.myQueryProfile=newUser", com.yahoo.jdisc.http.HttpRequest.Method.GET), cRegistry.getComponent("topMap"));
assertEquals(0, query.errors().size());
- assertEquals("newUserValue1",query.properties().get("subMap.typeProfile.myQueryProfile.myUserString"));
- assertEquals(845,query.properties().get("subMap.typeProfile.myQueryProfile.myUserInteger"));
+ assertEquals("newUserValue1", query.properties().get("subMap.typeProfile.myQueryProfile.myUserString"));
+ assertEquals(845, query.properties().get("subMap.typeProfile.myQueryProfile.myUserInteger"));
}
/**
* Tests setting a illegal value in a strict profile nested under untyped maps
*/
@Test
- public void testSettingValueInStrictTypeNestedUnderUntypedMaps() {
+ void testSettingValueInStrictTypeNestedUnderUntypedMaps() {
QueryProfile topMap = new QueryProfile("topMap");
QueryProfile subMap = new QueryProfile("topSubMap");
@@ -656,13 +652,13 @@ public class QueryProfileTypeTestCase {
try {
new Query(
HttpRequest.createTestRequest("?subMap.typeProfile.someValue=value",
- com.yahoo.jdisc.http.HttpRequest.Method.GET),
+ com.yahoo.jdisc.http.HttpRequest.Method.GET),
cRegistry.getComponent("topMap"));
fail("Above statement should throw");
} catch (IllegalArgumentException e) {
// As expected.
assertTrue(Exceptions.toMessageString(e).contains(
- "Could not set 'subMap.typeProfile.someValue' to 'value': 'someValue' is not declared in query profile type 'testtypeStrict', and the type is strict"));
+ "Could not set 'subMap.typeProfile.someValue' to 'value': 'someValue' is not declared in query profile type 'testtypeStrict', and the type is strict"));
}
}
@@ -672,15 +668,15 @@ public class QueryProfileTypeTestCase {
* The whole thing is accessed through a two levels of nontyped top-level profiles
*/
@Test
- public void testTypedSettingOfQueryProfileReferencesNonStrictThroughQueryNestedInAnUntypedProfile() {
+ void testTypedSettingOfQueryProfileReferencesNonStrictThroughQueryNestedInAnUntypedProfile() {
QueryProfile topMap = new QueryProfile("topMap");
QueryProfile subMap = new QueryProfile("topSubMap");
- topMap.set("subMap",subMap, registry);
+ topMap.set("subMap", subMap, registry);
QueryProfile test = new QueryProfile("test");
test.setType(testtype);
- subMap.set("typeProfile",test, registry);
+ subMap.set("typeProfile", test, registry);
QueryProfile newUser = new QueryProfile("newUser");
newUser.setType(user);
@@ -694,8 +690,8 @@ public class QueryProfileTypeTestCase {
CompiledQueryProfileRegistry cRegistry = registry.compile();
Query query = new Query(HttpRequest.createTestRequest("?subMap.typeProfile.myUserQueryProfile=newUser",
- com.yahoo.jdisc.http.HttpRequest.Method.GET),
- cRegistry.getComponent("topMap"));
+ com.yahoo.jdisc.http.HttpRequest.Method.GET),
+ cRegistry.getComponent("topMap"));
assertEquals(0, query.errors().size());
assertEquals("newUserValue1", query.properties().get("subMap.typeProfile.myUserQueryProfile.myUserString"));
@@ -703,14 +699,14 @@ public class QueryProfileTypeTestCase {
}
@Test
- public void testNestedTypeName() {
+ void testNestedTypeName() {
ComponentId.resetGlobalCountersForTests();
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfileType type = new QueryProfileType("testType");
registry.getTypeRegistry().register(type);
type.addField(new FieldDescription("ranking.features.query(embedding_profile)",
- "tensor<float>(model{},x[128])"),
- registry.getTypeRegistry());
+ "tensor<float>(model{},x[128])"),
+ registry.getTypeRegistry());
QueryProfile test = new QueryProfile("test");
registry.register(test);
test.setType(type);
@@ -723,15 +719,15 @@ public class QueryProfileTypeTestCase {
}
@Test
- public void testNestedTypeNameUsingBuiltInTypes() {
+ void testNestedTypeNameUsingBuiltInTypes() {
ComponentId.resetGlobalCountersForTests();
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfileType type = new QueryProfileType("testType");
type.inherited().add(Query.getArgumentType()); // Include native type checking
registry.getTypeRegistry().register(type);
type.addField(new FieldDescription("ranking.features.query(embedding_profile)",
- "tensor<float>(model{},x[128])"),
- registry.getTypeRegistry());
+ "tensor<float>(model{},x[128])"),
+ registry.getTypeRegistry());
QueryProfile test = new QueryProfile("test");
registry.register(test);
test.setType(type);
@@ -745,7 +741,7 @@ public class QueryProfileTypeTestCase {
}
catch (IllegalArgumentException e) {
assertEquals("'foo' is not a valid property in 'ranking'. See the query api for valid keys starting by 'ranking'.",
- e.getCause().getMessage());
+ e.getCause().getMessage());
}
// With a prefix we're not in the built-in type space
diff --git a/container-search/src/test/java/com/yahoo/search/query/properties/test/PropertyMapTestCase.java b/container-search/src/test/java/com/yahoo/search/query/properties/test/PropertyMapTestCase.java
index 5fbe8858186..46859ab1cbe 100644
--- a/container-search/src/test/java/com/yahoo/search/query/properties/test/PropertyMapTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/properties/test/PropertyMapTestCase.java
@@ -2,13 +2,12 @@
package com.yahoo.search.query.properties.test;
import com.yahoo.processing.request.properties.PropertyMap;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.List;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -16,24 +15,24 @@ import static org.junit.Assert.assertTrue;
public class PropertyMapTestCase {
@Test
- public void testCloning() {
+ void testCloning() {
PropertyMap map = new PropertyMap();
map.set("clonable", new ClonableObject());
map.set("nonclonable", new NonClonableObject());
- map.set("clonableArray", new ClonableObject[] {new ClonableObject()});
- map.set("nonclonableArray", new NonClonableObject[] {new NonClonableObject()});
+ map.set("clonableArray", new ClonableObject[]{new ClonableObject()});
+ map.set("nonclonableArray", new NonClonableObject[]{new NonClonableObject()});
map.set("clonableList", Collections.singletonList(new ClonableObject()));
map.set("nonclonableList", Collections.singletonList(new NonClonableObject()));
assertNotNull(map.get("clonable"));
assertNotNull(map.get("nonclonable"));
- PropertyMap mapClone=map.clone();
+ PropertyMap mapClone = map.clone();
assertTrue(map.get("clonable") != mapClone.get("clonable"));
- assertTrue(map.get("nonclonable") == mapClone.get("nonclonable"));
+ assertEquals(map.get("nonclonable"), mapClone.get("nonclonable"));
assertTrue(map.get("clonableArray") != mapClone.get("clonableArray"));
assertTrue(first(map.get("clonableArray")) != first(mapClone.get("clonableArray")));
- assertTrue(first(map.get("nonclonableArray")) == first(mapClone.get("nonclonableArray")));
+ assertEquals(first(map.get("nonclonableArray")), first(mapClone.get("nonclonableArray")));
}
private Object first(Object object) {
diff --git a/container-search/src/test/java/com/yahoo/search/query/properties/test/RequestContextPropertiesTestCase.java b/container-search/src/test/java/com/yahoo/search/query/properties/test/RequestContextPropertiesTestCase.java
index 2a123b4bbda..23b41092660 100644
--- a/container-search/src/test/java/com/yahoo/search/query/properties/test/RequestContextPropertiesTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/properties/test/RequestContextPropertiesTestCase.java
@@ -5,9 +5,9 @@ import com.yahoo.search.Query;
import com.yahoo.search.query.profile.QueryProfile;
import com.yahoo.search.query.profile.QueryProfileRegistry;
import com.yahoo.search.test.QueryTestCase;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Tests that dimension arguments in queries are transferred correctly to dimension values
@@ -17,18 +17,18 @@ import static org.junit.Assert.assertEquals;
public class RequestContextPropertiesTestCase {
@Test
- public void testIt() {
- QueryProfile p=new QueryProfile("test");
- p.setDimensions(new String[] {"x"});
- p.set("a","a-default", (QueryProfileRegistry)null);
- p.set("a","a-x1",new String[] {"x1"}, null);
- p.set("a","a-+x1",new String[] {"+x1"}, null);
+ void testIt() {
+ QueryProfile p = new QueryProfile("test");
+ p.setDimensions(new String[]{"x"});
+ p.set("a", "a-default", (QueryProfileRegistry) null);
+ p.set("a", "a-x1", new String[]{"x1"}, null);
+ p.set("a", "a-+x1", new String[]{"+x1"}, null);
Query q1 = new Query(QueryTestCase.httpEncode("?query=foo"), p.compile(null));
- assertEquals("a-default",q1.properties().get("a"));
- Query q2 = new Query(QueryTestCase.httpEncode("?query=foo&x=x1"),p.compile(null));
- assertEquals("a-x1",q2.properties().get("a"));
- Query q3 = new Query(QueryTestCase.httpEncode("?query=foo&x=+x1"),p.compile(null));
- assertEquals("a-+x1",q3.properties().get("a"));
+ assertEquals("a-default", q1.properties().get("a"));
+ Query q2 = new Query(QueryTestCase.httpEncode("?query=foo&x=x1"), p.compile(null));
+ assertEquals("a-x1", q2.properties().get("a"));
+ Query q3 = new Query(QueryTestCase.httpEncode("?query=foo&x=+x1"), p.compile(null));
+ assertEquals("a-+x1", q3.properties().get("a"));
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/properties/test/SubPropertiesTestCase.java b/container-search/src/test/java/com/yahoo/search/query/properties/test/SubPropertiesTestCase.java
index 11c249c5cdb..0e9bf8d41ec 100644
--- a/container-search/src/test/java/com/yahoo/search/query/properties/test/SubPropertiesTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/properties/test/SubPropertiesTestCase.java
@@ -1,15 +1,14 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.query.properties.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;
import java.util.Arrays;
import java.util.HashSet;
import com.yahoo.processing.request.properties.PropertyMap;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.yahoo.search.query.properties.SubProperties;
/**
@@ -18,19 +17,21 @@ import com.yahoo.search.query.properties.SubProperties;
public class SubPropertiesTestCase {
@Test
- public void testSubProperties() {
- PropertyMap map = new PropertyMap() {{
- set("a.e","1");
- set("a.f",2);
- set("b.e","3");
- set("f",3);
- set("e","2");
- set("d","a");
- }};
+ void testSubProperties() {
+ PropertyMap map = new PropertyMap() {
+ {
+ set("a.e", "1");
+ set("a.f", 2);
+ set("b.e", "3");
+ set("f", 3);
+ set("e", "2");
+ set("d", "a");
+ }
+ };
SubProperties sub = new SubProperties("a", map);
- assertEquals("1",sub.get("e"));
- assertEquals(2,sub.get("f"));
+ assertEquals("1", sub.get("e"));
+ assertEquals(2, sub.get("f"));
assertNull(sub.get("d"));
assertEquals(new HashSet<>(Arrays.asList("e", "f")), sub.listProperties("").keySet());
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/rewrite/RewriterFeaturesTestCase.java b/container-search/src/test/java/com/yahoo/search/query/rewrite/RewriterFeaturesTestCase.java
index 72b77377bf2..e502cf538aa 100644
--- a/container-search/src/test/java/com/yahoo/search/query/rewrite/RewriterFeaturesTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/rewrite/RewriterFeaturesTestCase.java
@@ -1,12 +1,13 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.query.rewrite;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertSame;
import com.yahoo.prelude.query.WeakAndItem;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.yahoo.prelude.query.AndItem;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
import com.yahoo.prelude.query.CompositeItem;
import com.yahoo.prelude.query.Item;
import com.yahoo.language.process.SpecialTokenRegistry;
@@ -25,7 +26,7 @@ public class RewriterFeaturesTestCase {
private static final String ASCII_ELLIPSIS = "...";
@Test
- public final void testConvertStringToQTree() {
+ final void testConvertStringToQTree() {
Execution placeholder = new Execution(Context.createContextStub());
SpecialTokenRegistry tokenRegistry = new SpecialTokenRegistry(
new SpecialtokensConfig(
diff --git a/container-search/src/test/java/com/yahoo/search/query/rewrite/test/GenericExpansionRewriterTestCase.java b/container-search/src/test/java/com/yahoo/search/query/rewrite/test/GenericExpansionRewriterTestCase.java
index d9a3603bdaf..668d070b3e2 100644
--- a/container-search/src/test/java/com/yahoo/search/query/rewrite/test/GenericExpansionRewriterTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/rewrite/test/GenericExpansionRewriterTestCase.java
@@ -8,8 +8,8 @@ import com.yahoo.search.searchchain.*;
import com.yahoo.search.query.rewrite.*;
import com.yahoo.search.query.rewrite.rewriters.*;
import com.yahoo.search.query.rewrite.RewritesConfig;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
/**
* Test Cases for GenericExpansionRewriter
@@ -29,7 +29,7 @@ public class GenericExpansionRewriterTestCase {
* Load the GenericExpansionRewriterSearcher and prepare the
* execution object
*/
- @Before
+ @BeforeEach
public void setUp() {
RewritesConfig config = QueryRewriteSearcherTestUtils.createConfigObj(CONFIG_PATH);
HashMap<String, File> fileList = new HashMap<>();
@@ -44,149 +44,149 @@ public class GenericExpansionRewriterTestCase {
* MaxRewrites=3, PartialPhraseMatch is on, type=adv case
*/
@Test
- public void testPartialPhraseMaxRewriteAdvType() {
+ void testPartialPhraseMaxRewriteAdvType() {
utils.assertRewrittenQuery("?query=(modern new york city travel phone number) OR (travel agency) OR travel&type=adv&" +
- REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=true&" +
- REWRITER_NAME + "." + RewriterConstants.MAX_REWRITES + "=3",
- "query 'OR (AND modern (OR (AND rewrite11 rewrite12) rewrite2 rewrite3 " +
- "(AND new york city travel)) (OR pn (AND phone number))) ta (AND travel agency) " +
- "tr travel'");
+ REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=true&" +
+ REWRITER_NAME + "." + RewriterConstants.MAX_REWRITES + "=3",
+ "query 'OR (AND modern (OR (AND rewrite11 rewrite12) rewrite2 rewrite3 " +
+ "(AND new york city travel)) (OR pn (AND phone number))) ta (AND travel agency) " +
+ "tr travel'");
}
/**
* PartialPhraseMatch is off, type=adv case
*/
@Test
- public void testPartialPhraseNoMaxRewriteAdvType() {
+ void testPartialPhraseNoMaxRewriteAdvType() {
utils.assertRewrittenQuery("?query=(modern new york city travel phone number) OR (travel agency) OR travel&type=adv&" +
- REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=false",
- "query 'OR (AND modern new york city travel phone number) " +
- "ta (AND travel agency) tr travel'");
+ REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=false",
+ "query 'OR (AND modern new york city travel phone number) " +
+ "ta (AND travel agency) tr travel'");
}
/**
* No MaxRewrites, PartialPhraseMatch is off, type=adv, added filter case
*/
@Test
- public void testFullPhraseNoMaxRewriteAdvTypeFilter() {
+ void testFullPhraseNoMaxRewriteAdvTypeFilter() {
utils.assertRewrittenQuery("?query=ca OR (modern new york city travel phone number) OR (travel agency) OR travel&" +
- "type=adv&filter=citystate:santa clara ca&" +
- REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=false",
- "query 'RANK (OR california ca (AND modern new york city travel phone number) " +
- "ta (AND travel agency) tr travel) |citystate:santa |clara |ca'");
+ "type=adv&filter=citystate:santa clara ca&" +
+ REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=false",
+ "query 'RANK (OR california ca (AND modern new york city travel phone number) " +
+ "ta (AND travel agency) tr travel) |citystate:santa |clara |ca'");
}
/**
* MaxRewrites=0 (i.e No MaxRewrites), PartialPhraseMatch is on, type=adv, added filter case
*/
@Test
- public void testPartialPhraseNoMaxRewriteAdvTypeFilter() {
+ void testPartialPhraseNoMaxRewriteAdvTypeFilter() {
utils.assertRewrittenQuery("?query=ca OR (modern new york city travel phone number) OR (travel agency) OR travel&" +
- "type=adv&filter=citystate:santa clara ca&" +
- REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=true&" +
- REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV + "=true&" +
- REWRITER_NAME + "." + RewriterConstants.MAX_REWRITES + "=0",
- "query 'RANK (OR california ca (AND modern (OR \"rewrite11 rewrite12\" " +
- "rewrite2 rewrite3 rewrite4 rewrite5 (AND new york city travel)) " +
- "(OR pn (AND phone number))) ta (AND travel agency) tr travel) " +
- "|citystate:santa |clara |ca'");
+ "type=adv&filter=citystate:santa clara ca&" +
+ REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=true&" +
+ REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV + "=true&" +
+ REWRITER_NAME + "." + RewriterConstants.MAX_REWRITES + "=0",
+ "query 'RANK (OR california ca (AND modern (OR \"rewrite11 rewrite12\" " +
+ "rewrite2 rewrite3 rewrite4 rewrite5 (AND new york city travel)) " +
+ "(OR pn (AND phone number))) ta (AND travel agency) tr travel) " +
+ "|citystate:santa |clara |ca'");
}
/**
* No MaxRewrites, PartialPhraseMatch is off, single word, added filter case
*/
@Test
- public void testFullPhraseNoMaxRewriteSingleWordFilter() {
+ void testFullPhraseNoMaxRewriteSingleWordFilter() {
utils.assertRewrittenQuery("?query=ca&type=all&" +
- "filter=citystate:santa clara ca&" +
- REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=false",
- "query 'RANK (OR california ca) |citystate:santa |clara |ca'");
+ "filter=citystate:santa clara ca&" +
+ REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=false",
+ "query 'RANK (OR california ca) |citystate:santa |clara |ca'");
}
/**
* No MaxRewrites, PartialPhraseMatch is on, single word, added filter case
*/
@Test
- public void testPartialPhraseNoMaxRewriteSingleWordFilter() {
+ void testPartialPhraseNoMaxRewriteSingleWordFilter() {
utils.assertRewrittenQuery("?query=ca&type=all&" +
- "filter=citystate:santa clara ca&" +
- REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=true",
- "query 'RANK (OR california ca) |citystate:santa |clara |ca'");
+ "filter=citystate:santa clara ca&" +
+ REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=true",
+ "query 'RANK (OR california ca) |citystate:santa |clara |ca'");
}
/**
* No MaxRewrites, PartialPhraseMatch is off, multi word, added filter case
*/
@Test
- public void testFullPhraseNoMaxRewriteMultiWordFilter() {
+ void testFullPhraseNoMaxRewriteMultiWordFilter() {
utils.assertRewrittenQuery("?query=travel agency&type=all&" +
- "filter=citystate:santa clara ca&" +
- REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=false",
- "query 'RANK (OR ta (AND travel agency)) |citystate:santa |clara |ca'");
+ "filter=citystate:santa clara ca&" +
+ REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=false",
+ "query 'RANK (OR ta (AND travel agency)) |citystate:santa |clara |ca'");
}
/**
* No MaxRewrites, PartialPhraseMatch is on, multi word, added filter case
*/
@Test
- public void testPartialPhraseNoMaxRewriteMultiWordFilter() {
+ void testPartialPhraseNoMaxRewriteMultiWordFilter() {
utils.assertRewrittenQuery("?query=modern new york city travel phone number&" +
- "filter=citystate:santa clara ca&type=all&" +
- REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=true",
- "query 'RANK (AND modern (OR (AND rewrite11 rewrite12) rewrite2 rewrite3 " +
- "rewrite4 rewrite5 (AND new york city travel)) (OR pn (AND phone number))) " +
- "|citystate:santa |clara |ca'");
+ "filter=citystate:santa clara ca&type=all&" +
+ REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=true",
+ "query 'RANK (AND modern (OR (AND rewrite11 rewrite12) rewrite2 rewrite3 " +
+ "rewrite4 rewrite5 (AND new york city travel)) (OR pn (AND phone number))) " +
+ "|citystate:santa |clara |ca'");
}
/**
* No MaxRewrites, PartialPhraseMatch is off, single word
*/
@Test
- public void testFullPhraseNoMaxRewriteSingleWord() {
+ void testFullPhraseNoMaxRewriteSingleWord() {
utils.assertRewrittenQuery("?query=ca&type=all&" +
- REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=false",
- "query 'OR california ca'");
+ REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=false",
+ "query 'OR california ca'");
}
/**
* No MaxRewrites, PartialPhraseMatch is on, single word
*/
@Test
- public void testPartialPhraseNoMaxRewriteSingleWord() {
+ void testPartialPhraseNoMaxRewriteSingleWord() {
utils.assertRewrittenQuery("?query=ca&type=all&" +
- REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=true",
- "query 'OR california ca'");
+ REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=true",
+ "query 'OR california ca'");
}
/**
* No MaxRewrites, PartialPhraseMatch is off, multi word
*/
@Test
- public void testFullPhraseNoMaxRewriteMultiWord() {
+ void testFullPhraseNoMaxRewriteMultiWord() {
utils.assertRewrittenQuery("?query=travel agency&type=all&" +
- REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=false",
- "query 'OR ta (AND travel agency)'");
+ REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=false",
+ "query 'OR ta (AND travel agency)'");
}
/**
* No MaxRewrites, PartialPhraseMatch is off, multi word, no full match
*/
@Test
- public void testFullPhraseNoMaxRewriteMultiWordNoMatch() {
+ void testFullPhraseNoMaxRewriteMultiWordNoMatch() {
utils.assertRewrittenQuery("?query=nyc travel agency&type=all&" +
- REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=false",
- "query 'AND nyc travel agency'");
+ REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=false",
+ "query 'AND nyc travel agency'");
}
/**
* No MaxRewrites, PartialPhraseMatch is on, multi word
*/
@Test
- public void testPartialPhraseNoMaxRewriteMultiWord() {
+ void testPartialPhraseNoMaxRewriteMultiWord() {
utils.assertRewrittenQuery("?query=modern new york city travel phone number&type=all&" +
- REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=true",
- "query 'AND modern (OR (AND rewrite11 rewrite12) rewrite2 rewrite3 rewrite4 rewrite5 "+
- "(AND new york city travel)) (OR pn (AND phone number))'");
+ REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=true",
+ "query 'AND modern (OR (AND rewrite11 rewrite12) rewrite2 rewrite3 rewrite4 rewrite5 " +
+ "(AND new york city travel)) (OR pn (AND phone number))'");
}
/**
@@ -195,10 +195,10 @@ public class GenericExpansionRewriterTestCase {
* Should rewrite travel but not travel agency in this case
*/
@Test
- public void testPartialPhraseMultiWordRankTree() {
+ void testPartialPhraseMultiWordRankTree() {
utils.assertRewrittenQuery("?query=travel RANK agency&type=adv&" +
- REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=true",
- "query 'RANK (OR tr travel) agency'");
+ REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=true",
+ "query 'RANK (OR tr travel) agency'");
}
/**
@@ -207,10 +207,10 @@ public class GenericExpansionRewriterTestCase {
* Should rewrite travel but not travel agency in this case
*/
@Test
- public void testFullPhraseMultiWordRankTree() {
+ void testFullPhraseMultiWordRankTree() {
utils.assertRewrittenQuery("?query=travel RANK agency&type=adv&" +
- REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=true",
- "query 'RANK (OR tr travel) agency'");
+ REWRITER_NAME + "." + RewriterConstants.PARTIAL_PHRASE_MATCH + "=true",
+ "query 'RANK (OR tr travel) agency'");
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/rewrite/test/MisspellRewriterTestCase.java b/container-search/src/test/java/com/yahoo/search/query/rewrite/test/MisspellRewriterTestCase.java
index 6c9f9c248ea..36eb06a3a92 100644
--- a/container-search/src/test/java/com/yahoo/search/query/rewrite/test/MisspellRewriterTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/rewrite/test/MisspellRewriterTestCase.java
@@ -6,10 +6,10 @@ import com.yahoo.search.searchchain.*;
import com.yahoo.search.intent.model.*;
import com.yahoo.search.query.rewrite.*;
import com.yahoo.search.query.rewrite.rewriters.*;
-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.fail;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* Test Cases for MisspellRewriter
@@ -25,7 +25,7 @@ public class MisspellRewriterTestCase {
* Load the QueryRewriteSearcher and prepare the
* execution object
*/
- @Before
+ @BeforeEach
public void setUp() {
MisspellRewriter searcher = new MisspellRewriter();
Execution execution = QueryRewriteSearcherTestUtils.createExecutionObj(searcher);
@@ -37,18 +37,18 @@ public class MisspellRewriterTestCase {
* QLAS returns spell correction: qss_rw=0.9 qss_sugg=1.0
*/
@Test
- public void testQSSRewriteQSSSuggestWithRewrite() {
+ void testQSSRewriteQSSSuggestWithRewrite() {
IntentModel intentModel = new IntentModel(
- utils.createInterpretation("will smith rw", 0.9,
- true, false),
- utils.createInterpretation("will smith sugg", 1.0,
- false, true));
+ utils.createInterpretation("will smith rw", 0.9,
+ true, false),
+ utils.createInterpretation("will smith sugg", 1.0,
+ false, true));
utils.assertRewrittenQuery("?query=willl+smith&" +
- REWRITER_NAME + "." + RewriterConstants.QSS_RW + "=true&" +
- REWRITER_NAME + "." + RewriterConstants.QSS_SUGG + "=true",
- "query 'OR (WEAKAND(100) willl smith) (WEAKAND(100) will smith sugg)'",
- intentModel);
+ REWRITER_NAME + "." + RewriterConstants.QSS_RW + "=true&" +
+ REWRITER_NAME + "." + RewriterConstants.QSS_SUGG + "=true",
+ "query 'OR (WEAKAND(100) willl smith) (WEAKAND(100) will smith sugg)'",
+ intentModel);
}
/**
@@ -56,19 +56,19 @@ public class MisspellRewriterTestCase {
* QLAS returns spell correction: qss_rw=0.9 qss_rw=0.9 qss_sugg=1.0
*/
@Test
- public void testQSSRewriteWithRewrite() {
+ void testQSSRewriteWithRewrite() {
IntentModel intentModel = new IntentModel(
- utils.createInterpretation("will smith rw1", 0.9,
- true, false),
- utils.createInterpretation("will smith rw2", 0.9,
- true, false),
- utils.createInterpretation("will smith sugg", 1.0,
- false, true));
+ utils.createInterpretation("will smith rw1", 0.9,
+ true, false),
+ utils.createInterpretation("will smith rw2", 0.9,
+ true, false),
+ utils.createInterpretation("will smith sugg", 1.0,
+ false, true));
utils.assertRewrittenQuery("?query=willl+smith&" +
- REWRITER_NAME + "." + RewriterConstants.QSS_RW + "=true",
- "query 'OR (WEAKAND(100) willl smith) (WEAKAND(100) will smith rw1)'",
- intentModel);
+ REWRITER_NAME + "." + RewriterConstants.QSS_RW + "=true",
+ "query 'OR (WEAKAND(100) willl smith) (WEAKAND(100) will smith rw1)'",
+ intentModel);
}
/**
@@ -76,19 +76,19 @@ public class MisspellRewriterTestCase {
* QLAS returns spell correction: qss_rw=1.0 qss_sugg=0.9 qss_sugg=0.8
*/
@Test
- public void testQSSSuggWithRewrite() {
+ void testQSSSuggWithRewrite() {
IntentModel intentModel = new IntentModel(
- utils.createInterpretation("will smith rw", 1.0,
- true, false),
- utils.createInterpretation("will smith sugg1", 0.9,
- false, true),
- utils.createInterpretation("will smith sugg2", 0.8,
- false, true));
+ utils.createInterpretation("will smith rw", 1.0,
+ true, false),
+ utils.createInterpretation("will smith sugg1", 0.9,
+ false, true),
+ utils.createInterpretation("will smith sugg2", 0.8,
+ false, true));
utils.assertRewrittenQuery("?query=willl+smith&" +
- REWRITER_NAME + "." + RewriterConstants.QSS_SUGG + "=true",
- "query 'OR (WEAKAND(100) willl smith) (WEAKAND(100) will smith sugg1)'",
- intentModel);
+ REWRITER_NAME + "." + RewriterConstants.QSS_SUGG + "=true",
+ "query 'OR (WEAKAND(100) willl smith) (WEAKAND(100) will smith sugg1)'",
+ intentModel);
}
/**
@@ -96,16 +96,16 @@ public class MisspellRewriterTestCase {
* QLAS returns spell correction: qss_rw=1.0 qss_sugg=1.0
*/
@Test
- public void testFeautureOffWithRewrite() {
+ void testFeautureOffWithRewrite() {
IntentModel intentModel = new IntentModel(
- utils.createInterpretation("will smith rw", 1.0,
- true, false),
- utils.createInterpretation("will smith sugg", 1.0,
- false, true));
+ utils.createInterpretation("will smith rw", 1.0,
+ true, false),
+ utils.createInterpretation("will smith sugg", 1.0,
+ false, true));
utils.assertRewrittenQuery("?query=willl+smith",
- "query 'WEAKAND(100) willl smith'",
- intentModel);
+ "query 'WEAKAND(100) willl smith'",
+ intentModel);
}
/**
@@ -113,18 +113,18 @@ public class MisspellRewriterTestCase {
* QLAS returns no spell correction
*/
@Test
- public void testQSSRewriteQSSSuggWithoutRewrite() {
+ void testQSSRewriteQSSSuggWithoutRewrite() {
IntentModel intentModel = new IntentModel(
- utils.createInterpretation("use diff query for testing", 1.0,
- false, false),
- utils.createInterpretation("use diff query for testing", 1.0,
- false, false));
+ utils.createInterpretation("use diff query for testing", 1.0,
+ false, false),
+ utils.createInterpretation("use diff query for testing", 1.0,
+ false, false));
utils.assertRewrittenQuery("?query=will+smith&" +
- REWRITER_NAME + "." + RewriterConstants.QSS_RW + "=true&" +
- REWRITER_NAME + "." + RewriterConstants.QSS_SUGG + "=true",
- "query 'WEAKAND(100) will smith'",
- intentModel);
+ REWRITER_NAME + "." + RewriterConstants.QSS_RW + "=true&" +
+ REWRITER_NAME + "." + RewriterConstants.QSS_SUGG + "=true",
+ "query 'WEAKAND(100) will smith'",
+ intentModel);
}
/**
@@ -132,7 +132,7 @@ public class MisspellRewriterTestCase {
* It should throw exception
*/
@Test
- public void testNullIntentModelException() {
+ void testNullIntentModelException() {
try {
RewriterUtils.getSpellCorrected(new Query("willl smith"), true, true);
fail();
diff --git a/container-search/src/test/java/com/yahoo/search/query/rewrite/test/NameRewriterTestCase.java b/container-search/src/test/java/com/yahoo/search/query/rewrite/test/NameRewriterTestCase.java
index c99ddcd6c62..98a93a572e9 100644
--- a/container-search/src/test/java/com/yahoo/search/query/rewrite/test/NameRewriterTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/rewrite/test/NameRewriterTestCase.java
@@ -8,8 +8,8 @@ import com.yahoo.search.searchchain.*;
import com.yahoo.search.query.rewrite.*;
import com.yahoo.search.query.rewrite.rewriters.*;
import com.yahoo.search.query.rewrite.RewritesConfig;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
/**
* Test Cases for NameRewriter
@@ -29,7 +29,7 @@ public class NameRewriterTestCase {
* Load the NameRewriterSearcher and prepare the
* execution object
*/
- @Before
+ @BeforeEach
public void setUp() {
RewritesConfig config = QueryRewriteSearcherTestUtils.createConfigObj(CONFIG_PATH);
HashMap<String, File> fileList = new HashMap<>();
@@ -44,29 +44,29 @@ public class NameRewriterTestCase {
* RewritesAsEquiv and OriginalAsUnit are on
*/
@Test
- public void testRewritesAsEquivAndOriginalAsUnit() {
+ void testRewritesAsEquivAndOriginalAsUnit() {
utils.assertRewrittenQuery("?query=will smith&type=all&" +
- REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_EQUIV + "=true&" +
- REWRITER_NAME + "." + RewriterConstants.ORIGINAL_AS_UNIT + "=true",
- "query 'OR \"will smith\" (AND will smith movies) " +
- "(AND will smith news) (AND will smith imdb) " +
- "(AND will smith lyrics) (AND will smith dead) " +
- "(AND will smith nfl) (AND will smith new movie hancock) " +
- "(AND will smith biography)'");
+ REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_EQUIV + "=true&" +
+ REWRITER_NAME + "." + RewriterConstants.ORIGINAL_AS_UNIT + "=true",
+ "query 'OR \"will smith\" (AND will smith movies) " +
+ "(AND will smith news) (AND will smith imdb) " +
+ "(AND will smith lyrics) (AND will smith dead) " +
+ "(AND will smith nfl) (AND will smith new movie hancock) " +
+ "(AND will smith biography)'");
}
/**
* RewritesAsEquiv is on
*/
@Test
- public void testRewritesAsEquiv() {
+ void testRewritesAsEquiv() {
utils.assertRewrittenQuery("?query=will smith&type=all&" +
- REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_EQUIV + "=true&",
- "query 'OR (AND will smith) (AND will smith movies) " +
- "(AND will smith news) (AND will smith imdb) " +
- "(AND will smith lyrics) (AND will smith dead) " +
- "(AND will smith nfl) (AND will smith new movie hancock) " +
- "(AND will smith biography)'");
+ REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_EQUIV + "=true&",
+ "query 'OR (AND will smith) (AND will smith movies) " +
+ "(AND will smith news) (AND will smith imdb) " +
+ "(AND will smith lyrics) (AND will smith dead) " +
+ "(AND will smith nfl) (AND will smith new movie hancock) " +
+ "(AND will smith biography)'");
}
/**
@@ -74,57 +74,57 @@ public class NameRewriterTestCase {
* Should not rewrite
*/
@Test
- public void testComplextQueryRewritesAsEquiv() {
+ void testComplextQueryRewritesAsEquiv() {
utils.assertRewrittenQuery("?query=((will smith) OR (willl smith)) AND (tom cruise)&type=adv&" +
- REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_EQUIV + "=true&",
- "query 'AND (OR (AND will smith) (AND willl smith)) (AND tom cruise)'");
+ REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_EQUIV + "=true&",
+ "query 'AND (OR (AND will smith) (AND willl smith)) (AND tom cruise)'");
}
/**
* Single word query for RewritesAsEquiv and OriginalAsUnit on case
*/
@Test
- public void testSingleWordForRewritesAsEquivAndOriginalAsUnit() {
+ void testSingleWordForRewritesAsEquivAndOriginalAsUnit() {
utils.assertRewrittenQuery("?query=obama&type=all&" +
- REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_EQUIV + "=true&" +
- REWRITER_NAME + "." + RewriterConstants.ORIGINAL_AS_UNIT + "=true",
- "query 'OR obama (AND obama \"nobel peace prize\") " +
- "(AND obama wiki) (AND obama nobel prize) " +
- "(AND obama nobel peace prize) (AND obama wears mom jeans) " +
- "(AND obama sucks) (AND obama news) (AND malia obama) " +
- "(AND obama speech) (AND obama nobel) (AND obama wikipedia) " +
- "(AND barack obama biography) (AND obama snl) " +
- "(AND obama peace prize) (AND michelle obama) (AND barack obama)'");
+ REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_EQUIV + "=true&" +
+ REWRITER_NAME + "." + RewriterConstants.ORIGINAL_AS_UNIT + "=true",
+ "query 'OR obama (AND obama \"nobel peace prize\") " +
+ "(AND obama wiki) (AND obama nobel prize) " +
+ "(AND obama nobel peace prize) (AND obama wears mom jeans) " +
+ "(AND obama sucks) (AND obama news) (AND malia obama) " +
+ "(AND obama speech) (AND obama nobel) (AND obama wikipedia) " +
+ "(AND barack obama biography) (AND obama snl) " +
+ "(AND obama peace prize) (AND michelle obama) (AND barack obama)'");
}
/**
* RewritesAsUnitEquiv and OriginalAsUnitEquiv are on
*/
@Test
- public void testRewritesAsUnitEquivAndOriginalAsUnitEquiv() {
+ void testRewritesAsUnitEquivAndOriginalAsUnitEquiv() {
utils.assertRewrittenQuery("?query=will smith&type=all&" +
- REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV +
- "=true&" +
- REWRITER_NAME + "." + RewriterConstants.ORIGINAL_AS_UNIT_EQUIV +
- "=true",
- "query 'OR (AND will smith) \"will smith\" \"will smith movies\" " +
- "\"will smith news\" \"will smith imdb\" " +
- "\"will smith lyrics\" \"will smith dead\" " +
- "\"will smith nfl\" \"will smith new movie hancock\" " +
- "\"will smith biography\"'");
+ REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV +
+ "=true&" +
+ REWRITER_NAME + "." + RewriterConstants.ORIGINAL_AS_UNIT_EQUIV +
+ "=true",
+ "query 'OR (AND will smith) \"will smith\" \"will smith movies\" " +
+ "\"will smith news\" \"will smith imdb\" " +
+ "\"will smith lyrics\" \"will smith dead\" " +
+ "\"will smith nfl\" \"will smith new movie hancock\" " +
+ "\"will smith biography\"'");
}
/**
* Single word query for RewritesAsUnitEquiv and OriginalAsUnitEquiv on case
*/
@Test
- public void testSingleWordForRewritesAsUnitEquivAndOriginalAsUnitEquiv() {
+ void testSingleWordForRewritesAsUnitEquivAndOriginalAsUnitEquiv() {
utils.assertRewrittenQuery("?query=obama&type=all&" +
- REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV +
- "=true&" +
- REWRITER_NAME + "." + RewriterConstants.ORIGINAL_AS_UNIT_EQUIV +
- "=true",
- "query 'OR obama \"obama nobel peace prize\" \"obama wiki\" \"obama nobel prize\" \"obama nobel peace prize\" \"obama wears mom jeans\" \"obama sucks\" \"obama news\" \"malia obama\" \"obama speech\" \"obama nobel\" \"obama wikipedia\" \"barack obama biography\" \"obama snl\" \"obama peace prize\" \"michelle obama\" \"barack obama\"'");
+ REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV +
+ "=true&" +
+ REWRITER_NAME + "." + RewriterConstants.ORIGINAL_AS_UNIT_EQUIV +
+ "=true",
+ "query 'OR obama \"obama nobel peace prize\" \"obama wiki\" \"obama nobel prize\" \"obama nobel peace prize\" \"obama wears mom jeans\" \"obama sucks\" \"obama news\" \"malia obama\" \"obama speech\" \"obama nobel\" \"obama wikipedia\" \"barack obama biography\" \"obama snl\" \"obama peace prize\" \"michelle obama\" \"barack obama\"'");
}
/**
@@ -132,11 +132,11 @@ public class NameRewriterTestCase {
* for RewritesAsEquiv and OriginalAsUnit on case
*/
@Test
- public void testBoostingQueryForRewritesAsEquivAndOriginalAsUnit() {
+ void testBoostingQueryForRewritesAsEquivAndOriginalAsUnit() {
utils.assertRewrittenQuery("?query=angelina jolie&type=all&" +
- REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_EQUIV + "=true&" +
- REWRITER_NAME + "." + RewriterConstants.ORIGINAL_AS_UNIT + "=true",
- "query '\"angelina jolie\"'");
+ REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_EQUIV + "=true&" +
+ REWRITER_NAME + "." + RewriterConstants.ORIGINAL_AS_UNIT + "=true",
+ "query '\"angelina jolie\"'");
}
/**
@@ -144,39 +144,39 @@ public class NameRewriterTestCase {
* RewritesAsEquiv and OriginalAsUnit on case
*/
@Test
- public void testFSANoMatchForRewritesAsEquivAndOriginalAsUnit() {
+ void testFSANoMatchForRewritesAsEquivAndOriginalAsUnit() {
utils.assertRewrittenQuery("?query=tom cruise&type=all&" +
- REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_EQUIV + "=true&" +
- REWRITER_NAME + "." + RewriterConstants.ORIGINAL_AS_UNIT + "=true",
- "query 'AND tom cruise'");
+ REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_EQUIV + "=true&" +
+ REWRITER_NAME + "." + RewriterConstants.ORIGINAL_AS_UNIT + "=true",
+ "query 'AND tom cruise'");
}
/**
* RewritesAsUnitEquiv is on
*/
@Test
- public void testRewritesAsUnitEquiv() {
+ void testRewritesAsUnitEquiv() {
utils.assertRewrittenQuery("?query=will smith&type=all&" +
- REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV +
- "=true",
- "query 'OR (AND will smith) \"will smith movies\" " +
- "\"will smith news\" \"will smith imdb\" " +
- "\"will smith lyrics\" \"will smith dead\" " +
- "\"will smith nfl\" \"will smith new movie hancock\" " +
- "\"will smith biography\"'");
+ REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV +
+ "=true",
+ "query 'OR (AND will smith) \"will smith movies\" " +
+ "\"will smith news\" \"will smith imdb\" " +
+ "\"will smith lyrics\" \"will smith dead\" " +
+ "\"will smith nfl\" \"will smith new movie hancock\" " +
+ "\"will smith biography\"'");
}
/**
* RewritesAsUnitEquiv is on and MaxRewrites is set to 2
*/
@Test
- public void testRewritesAsUnitEquivAndMaxRewrites() {
+ void testRewritesAsUnitEquivAndMaxRewrites() {
utils.assertRewrittenQuery("?query=will smith&type=all&" +
- REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV +
- "=true&" +
- REWRITER_NAME + "." + RewriterConstants.MAX_REWRITES + "=2",
- "query 'OR (AND will smith) \"will smith movies\" " +
- "\"will smith news\"'");
+ REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV +
+ "=true&" +
+ REWRITER_NAME + "." + RewriterConstants.MAX_REWRITES + "=2",
+ "query 'OR (AND will smith) \"will smith movies\" " +
+ "\"will smith news\"'");
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/rewrite/test/QueryRewriteSearcherTestCase.java b/container-search/src/test/java/com/yahoo/search/query/rewrite/test/QueryRewriteSearcherTestCase.java
index 8906dbfa386..4848483688e 100644
--- a/container-search/src/test/java/com/yahoo/search/query/rewrite/test/QueryRewriteSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/rewrite/test/QueryRewriteSearcherTestCase.java
@@ -10,8 +10,8 @@ import com.yahoo.search.intent.model.*;
import com.yahoo.search.query.rewrite.RewritesConfig;
import com.yahoo.search.query.rewrite.*;
import com.yahoo.search.query.rewrite.rewriters.*;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
/**
* Generic Test Cases for QueryRewriteSearcher
@@ -36,7 +36,7 @@ public class QueryRewriteSearcherTestCase {
* Load the QueryRewriteSearcher and prepare the
* execution object
*/
- @Before
+ @BeforeEach
public void setUp() {
// Instantiate Name Rewriter
RewritesConfig config = QueryRewriteSearcherTestUtils.createConfigObj(NAME_REWRITER_CONFIG_PATH);
@@ -61,7 +61,7 @@ public class QueryRewriteSearcherTestCase {
* Query will be passed to next rewriter
*/
@Test
- public void testInvalidFSAConfigPath() {
+ void testInvalidFSAConfigPath() {
// Instantiate Name Rewriter with fake FSA path
RewritesConfig config = QueryRewriteSearcherTestUtils.createConfigObj(FAKE_FSA_CONFIG_PATH);
HashMap<String, File> fileList = new HashMap<>();
@@ -80,9 +80,9 @@ public class QueryRewriteSearcherTestCase {
QueryRewriteSearcherTestUtils utilsWithFakePath = new QueryRewriteSearcherTestUtils(execution);
utilsWithFakePath.assertRewrittenQuery("?query=will smith&type=all&" +
- NAME_REWRITER_NAME + "." +
- RewriterConstants.REWRITES_AS_UNIT_EQUIV + "=true",
- "query 'AND will smith'");
+ NAME_REWRITER_NAME + "." +
+ RewriterConstants.REWRITES_AS_UNIT_EQUIV + "=true",
+ "query 'AND will smith'");
}
/**
@@ -90,19 +90,19 @@ public class QueryRewriteSearcherTestCase {
* It should skip to the next rewriter
*/
@Test
- public void testExceptionInRewriter() {
+ void testExceptionInRewriter() {
utils.assertRewrittenQuery("?query=will smith&type=all&" +
- MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_RW + "=true&" +
- MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_SUGG + "=true&" +
- NAME_REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV +
- "=true&" +
- NAME_REWRITER_NAME + "." + RewriterConstants.ORIGINAL_AS_UNIT_EQUIV + "=true",
- "query 'OR (AND will smith) " +
- "\"will smith\" \"will smith movies\" " +
- "\"will smith news\" \"will smith imdb\" " +
- "\"will smith lyrics\" \"will smith dead\" " +
- "\"will smith nfl\" \"will smith new movie hancock\" " +
- "\"will smith biography\"'");
+ MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_RW + "=true&" +
+ MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_SUGG + "=true&" +
+ NAME_REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV +
+ "=true&" +
+ NAME_REWRITER_NAME + "." + RewriterConstants.ORIGINAL_AS_UNIT_EQUIV + "=true",
+ "query 'OR (AND will smith) " +
+ "\"will smith\" \"will smith movies\" " +
+ "\"will smith news\" \"will smith imdb\" " +
+ "\"will smith lyrics\" \"will smith dead\" " +
+ "\"will smith nfl\" \"will smith new movie hancock\" " +
+ "\"will smith biography\"'");
}
/**
@@ -110,26 +110,26 @@ public class QueryRewriteSearcherTestCase {
* Query will be rewritten twice
*/
@Test
- public void testTwoRewritersInChain() {
+ void testTwoRewritersInChain() {
IntentModel intentModel = new IntentModel(
- utils.createInterpretation("wills smith", 0.9,
- true, false),
- utils.createInterpretation("will smith", 1.0,
- false, true));
+ utils.createInterpretation("wills smith", 0.9,
+ true, false),
+ utils.createInterpretation("will smith", 1.0,
+ false, true));
utils.assertRewrittenQuery("?query=willl+smith&type=all&" +
- MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_RW + "=true&" +
- MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_SUGG + "=true&" +
- NAME_REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV +
- "=true&" +
- NAME_REWRITER_NAME + "." + RewriterConstants.ORIGINAL_AS_UNIT_EQUIV + "=true",
- "query 'OR (AND willl smith) (AND will smith) " +
- "\"will smith\" \"will smith movies\" " +
- "\"will smith news\" \"will smith imdb\" " +
- "\"will smith lyrics\" \"will smith dead\" " +
- "\"will smith nfl\" \"will smith new movie hancock\" " +
- "\"will smith biography\"'",
- intentModel);
+ MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_RW + "=true&" +
+ MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_SUGG + "=true&" +
+ NAME_REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV +
+ "=true&" +
+ NAME_REWRITER_NAME + "." + RewriterConstants.ORIGINAL_AS_UNIT_EQUIV + "=true",
+ "query 'OR (AND willl smith) (AND will smith) " +
+ "\"will smith\" \"will smith movies\" " +
+ "\"will smith news\" \"will smith imdb\" " +
+ "\"will smith lyrics\" \"will smith dead\" " +
+ "\"will smith nfl\" \"will smith new movie hancock\" " +
+ "\"will smith biography\"'",
+ intentModel);
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/rewrite/test/QueryRewriteSearcherTestUtils.java b/container-search/src/test/java/com/yahoo/search/query/rewrite/test/QueryRewriteSearcherTestUtils.java
index c12a3fb0e14..960eea5bba7 100644
--- a/container-search/src/test/java/com/yahoo/search/query/rewrite/test/QueryRewriteSearcherTestUtils.java
+++ b/container-search/src/test/java/com/yahoo/search/query/rewrite/test/QueryRewriteSearcherTestUtils.java
@@ -13,10 +13,11 @@ import com.yahoo.text.interpretation.Interpretation;
import com.yahoo.text.interpretation.Annotations;
import com.yahoo.config.subscription.ConfigGetter;
import com.yahoo.component.chain.Chain;
-import org.junit.Assert;
import java.util.List;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
/**
* Test utilities for QueryRewriteSearcher
*
@@ -73,7 +74,7 @@ public class QueryRewriteSearcherTestUtils {
public void assertRewrittenQuery(String origQuery, String finalQuery) {
Query query = new Query(QueryTestCase.httpEncode(origQuery));
Result result = execution.search(query);
- Assert.assertEquals(finalQuery, result.getQuery().toString());
+ assertEquals(finalQuery, result.getQuery().toString());
}
/**
@@ -89,7 +90,7 @@ public class QueryRewriteSearcherTestUtils {
Query query = new Query(origQuery);
intentModel.setTo(query);
Result result = execution.search(query);
- Assert.assertEquals(finalQuery, result.getQuery().toString());
+ assertEquals(finalQuery, result.getQuery().toString());
}
/**
diff --git a/container-search/src/test/java/com/yahoo/search/query/rewrite/test/SearchChainDispatcherSearcherTestCase.java b/container-search/src/test/java/com/yahoo/search/query/rewrite/test/SearchChainDispatcherSearcherTestCase.java
index 96626738c35..56797768f56 100644
--- a/container-search/src/test/java/com/yahoo/search/query/rewrite/test/SearchChainDispatcherSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/rewrite/test/SearchChainDispatcherSearcherTestCase.java
@@ -12,8 +12,8 @@ import com.yahoo.search.searchchain.SearchChainRegistry;
import com.yahoo.search.query.rewrite.RewritesConfig;
import com.yahoo.search.intent.model.*;
import com.yahoo.component.chain.Chain;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
/**
* Test Cases for SearchChainDispatcherSearcher
@@ -35,7 +35,7 @@ public class SearchChainDispatcherSearcherTestCase {
* Load the QueryRewriteSearcher and prepare the
* execution object
*/
- @Before
+ @BeforeEach
public void setUp() {
// Instantiate Name Rewriter
RewritesConfig config = QueryRewriteSearcherTestUtils.createConfigObj(NAME_REWRITER_CONFIG_PATH);
@@ -70,26 +70,26 @@ public class SearchChainDispatcherSearcherTestCase {
* Query will be rewritten twice
*/
@Test
- public void testMarketChain() {
+ void testMarketChain() {
IntentModel intentModel = new IntentModel(
- utils.createInterpretation("wills smith", 0.9,
- true, false),
- utils.createInterpretation("will smith", 1.0,
- false, true));
+ utils.createInterpretation("wills smith", 0.9,
+ true, false),
+ utils.createInterpretation("will smith", 1.0,
+ false, true));
utils.assertRewrittenQuery("?query=willl+smith&type=all&QRWChain=" + US_MARKET_SEARCH_CHAIN + "&" +
- MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_RW + "=true&" +
- MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_SUGG + "=true&" +
- NAME_REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV +
- "=true&" +
- NAME_REWRITER_NAME + "." + RewriterConstants.ORIGINAL_AS_UNIT_EQUIV + "=true",
- "query 'OR (AND willl smith) (AND will smith) " +
- "\"will smith\" \"will smith movies\" " +
- "\"will smith news\" \"will smith imdb\" " +
- "\"will smith lyrics\" \"will smith dead\" " +
- "\"will smith nfl\" \"will smith new movie hancock\" " +
- "\"will smith biography\"'",
- intentModel);
+ MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_RW + "=true&" +
+ MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_SUGG + "=true&" +
+ NAME_REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV +
+ "=true&" +
+ NAME_REWRITER_NAME + "." + RewriterConstants.ORIGINAL_AS_UNIT_EQUIV + "=true",
+ "query 'OR (AND willl smith) (AND will smith) " +
+ "\"will smith\" \"will smith movies\" " +
+ "\"will smith news\" \"will smith imdb\" " +
+ "\"will smith lyrics\" \"will smith dead\" " +
+ "\"will smith nfl\" \"will smith new movie hancock\" " +
+ "\"will smith biography\"'",
+ intentModel);
}
/**
@@ -97,13 +97,13 @@ public class SearchChainDispatcherSearcherTestCase {
* Query will be passed to next rewriter
*/
@Test
- public void testInvalidMarketChain() {
+ void testInvalidMarketChain() {
utils.assertRewrittenQuery("?query=will smith&type=all&QRWChain=abc&" +
- MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_RW + "=true&" +
- MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_SUGG + "=true&" +
- NAME_REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV +
- "=true",
- "query 'AND will smith'");
+ MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_RW + "=true&" +
+ MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_SUGG + "=true&" +
+ NAME_REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV +
+ "=true",
+ "query 'AND will smith'");
}
/**
@@ -111,13 +111,13 @@ public class SearchChainDispatcherSearcherTestCase {
* Query will be passed to next rewriter
*/
@Test
- public void testEmptyMarketChain() {
+ void testEmptyMarketChain() {
utils.assertRewrittenQuery("?query=will smith&type=all&QRWChain=&" +
- MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_RW + "=true&" +
- MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_SUGG + "=true&" +
- NAME_REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV +
- "=true",
- "query 'AND will smith'");
+ MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_RW + "=true&" +
+ MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_SUGG + "=true&" +
+ NAME_REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV +
+ "=true",
+ "query 'AND will smith'");
}
/**
@@ -125,7 +125,7 @@ public class SearchChainDispatcherSearcherTestCase {
* should be executed
*/
@Test
- public void testChainContinuation() {
+ void testChainContinuation() {
// Instantiate Name Rewriter
RewritesConfig config = QueryRewriteSearcherTestUtils.createConfigObj(NAME_REWRITER_CONFIG_PATH);
HashMap<String, File> fileList = new HashMap<>();
@@ -156,24 +156,24 @@ public class SearchChainDispatcherSearcherTestCase {
new QueryRewriteSearcherTestUtils(execution);
IntentModel intentModel = new IntentModel(
- utils.createInterpretation("wills smith", 0.9,
- true, false),
- utils.createInterpretation("will smith", 1.0,
- false, true));
+ utils.createInterpretation("wills smith", 0.9,
+ true, false),
+ utils.createInterpretation("will smith", 1.0,
+ false, true));
utils.assertRewrittenQuery("?query=willl+smith&type=all&QRWChain=" + US_MARKET_SEARCH_CHAIN + "&" +
- MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_RW + "=true&" +
- MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_SUGG + "=true&" +
- NAME_REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV +
- "=true&" +
- NAME_REWRITER_NAME + "." + RewriterConstants.ORIGINAL_AS_UNIT_EQUIV + "=true",
- "query 'OR (AND willl smith) (AND will smith) " +
- "\"will smith\" \"will smith movies\" " +
- "\"will smith news\" \"will smith imdb\" " +
- "\"will smith lyrics\" \"will smith dead\" " +
- "\"will smith nfl\" \"will smith new movie hancock\" " +
- "\"will smith biography\"'",
- intentModel);
+ MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_RW + "=true&" +
+ MISSPELL_REWRITER_NAME + "." + RewriterConstants.QSS_SUGG + "=true&" +
+ NAME_REWRITER_NAME + "." + RewriterConstants.REWRITES_AS_UNIT_EQUIV +
+ "=true&" +
+ NAME_REWRITER_NAME + "." + RewriterConstants.ORIGINAL_AS_UNIT_EQUIV + "=true",
+ "query 'OR (AND willl smith) (AND will smith) " +
+ "\"will smith\" \"will smith movies\" " +
+ "\"will smith news\" \"will smith imdb\" " +
+ "\"will smith lyrics\" \"will smith dead\" " +
+ "\"will smith nfl\" \"will smith new movie hancock\" " +
+ "\"will smith biography\"'",
+ intentModel);
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/test/ModelTestCase.java b/container-search/src/test/java/com/yahoo/search/query/test/ModelTestCase.java
index 6f856144b8a..49d43bdc4c2 100644
--- a/container-search/src/test/java/com/yahoo/search/query/test/ModelTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/test/ModelTestCase.java
@@ -4,18 +4,16 @@ package com.yahoo.search.query.test;
import com.yahoo.prelude.query.Item;
import com.yahoo.search.Query;
import com.yahoo.search.query.Model;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.LinkedHashSet;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
@@ -25,13 +23,13 @@ public class ModelTestCase {
String oldConfigId;
- @Before
+ @BeforeEach
public void setUp() {
oldConfigId = System.getProperty("config.id");
System.setProperty("config.id", "file:src/test/java/com/yahoo/prelude/test/fieldtypes/field-info.cfg");
}
- @After
+ @AfterEach
public void tearDown() {
if (oldConfigId == null)
System.getProperties().remove("config.id");
@@ -40,30 +38,30 @@ public class ModelTestCase {
}
@Test
- public void testCopyParameters() {
+ void testCopyParameters() {
Query q1 = new Query("?query=test1&filter=test2&default-index=content&default-index=lala&encoding=iso8859-1");
Query q2 = q1.clone();
Model r1 = q1.getModel();
Model r2 = q2.getModel();
assertTrue(r1 != r2);
- assertEquals(r1,r2);
- assertEquals("test1",r2.getQueryString());
+ assertEquals(r1, r2);
+ assertEquals("test1", r2.getQueryString());
}
@Test
- public void testSetQuery() {
+ void testSetQuery() {
Query q1 = new Query("?query=test1");
Item r1 = q1.getModel().getQueryTree();
- q1.properties().set("query","test2");
+ q1.properties().set("query", "test2");
q1.getModel().setQueryString(q1.getModel().getQueryString()); // Force reparse
- assertNotSame(r1,q1.getModel().getQueryTree());
- q1.properties().set("query","test1");
+ assertNotSame(r1, q1.getModel().getQueryTree());
+ q1.properties().set("query", "test1");
q1.getModel().setQueryString(q1.getModel().getQueryString()); // Force reparse
- assertEquals(r1,q1.getModel().getQueryTree());
+ assertEquals(r1, q1.getModel().getQueryTree());
}
@Test
- public void testSetofSetters() {
+ void testSetofSetters() {
Query q1 = new Query("?query=test1&encoding=iso-8859-1&language=en&default-index=subject&filter=" + enc("\u00C5"));
Model r1 = q1.getModel();
assertEquals(r1.getQueryString(), "test1");
@@ -82,23 +80,23 @@ public class ModelTestCase {
}
@Test
- public void testSearchPath() {
- assertEquals("c6/r8",new Query("?query=test1&model.searchPath=c6/r8").getModel().getSearchPath());
- assertEquals("c6/r8",new Query("?query=test1&searchpath=c6/r8").getModel().getSearchPath());
+ void testSearchPath() {
+ assertEquals("c6/r8", new Query("?query=test1&model.searchPath=c6/r8").getModel().getSearchPath());
+ assertEquals("c6/r8", new Query("?query=test1&searchpath=c6/r8").getModel().getSearchPath());
}
@Test
- public void testClone() {
- Query q= new Query();
+ void testClone() {
+ Query q = new Query();
Model sr = new Model(q);
sr.setRestrict("music, cheese,other");
sr.setSources("cluster1");
assertEquals(sr.getSources(), new LinkedHashSet<>(Arrays.asList(new String[]{"cluster1"})));
- assertEquals(sr.getRestrict(),new LinkedHashSet<>(Arrays.asList(new String[]{"cheese","music","other"})));
+ assertEquals(sr.getRestrict(), new LinkedHashSet<>(Arrays.asList(new String[]{"cheese", "music", "other"})));
}
@Test
- public void testEquals() {
+ void testEquals() {
Query q = new Query();
Model sra = new Model(q);
sra.setRestrict("music,cheese");
@@ -107,20 +105,20 @@ public class ModelTestCase {
Model srb = new Model(q);
srb.setRestrict(" cheese , music");
srb.setSources("cluster1,cluster2");
- assertEquals(sra,srb);
+ assertEquals(sra, srb);
srb.setRestrict("music,cheese");
- assertNotSame(sra,srb);
+ assertNotSame(sra, srb);
}
@Test
- public void testSearchRestrictQueryParameters() {
- Query query=new Query("?query=test&search=news,archive&restrict=fish,bird");
+ void testSearchRestrictQueryParameters() {
+ Query query = new Query("?query=test&search=news,archive&restrict=fish,bird");
assertTrue(query.getModel().getSources().contains("news"));
assertTrue(query.getModel().getSources().contains("archive"));
- assertEquals(2,query.getModel().getSources().size());
+ assertEquals(2, query.getModel().getSources().size());
assertTrue(query.getModel().getRestrict().contains("fish"));
assertTrue(query.getModel().getRestrict().contains("bird"));
- assertEquals(2,query.getModel().getRestrict().size());
+ assertEquals(2, query.getModel().getRestrict().size());
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/test/ParametersTestCase.java b/container-search/src/test/java/com/yahoo/search/query/test/ParametersTestCase.java
index c28e64196a2..df97c03ae68 100644
--- a/container-search/src/test/java/com/yahoo/search/query/test/ParametersTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/test/ParametersTestCase.java
@@ -6,10 +6,10 @@ import com.yahoo.search.Query;
import com.yahoo.search.query.profile.QueryProfile;
import com.yahoo.search.query.profile.QueryProfileRegistry;
import com.yahoo.search.query.profile.compiled.CompiledQueryProfile;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static com.yahoo.jdisc.http.HttpRequest.Method;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bratseth
@@ -19,49 +19,49 @@ public class ParametersTestCase {
private final double delta = 0.000001;
@Test
- public void testSettingRankProperty() {
+ void testSettingRankProperty() {
Query query = new Query("?query=test&ranking.properties.dotProduct.X=(a:1,b:2)");
assertEquals("[(a:1,b:2)]", query.getRanking().getProperties().get("dotProduct.X").toString());
}
@Test
- public void testSettingRankPropertyAsAlias() {
+ void testSettingRankPropertyAsAlias() {
Query query = new Query("?query=test&rankproperty.dotProduct.X=(a:1,b:2)");
assertEquals("[(a:1,b:2)]", query.getRanking().getProperties().get("dotProduct.X").toString());
}
@Test
- public void testSettingRankFeature() {
+ void testSettingRankFeature() {
Query query = new Query("?query=test&ranking.features.matches=3");
assertEquals(3, query.getRanking().getFeatures().getDouble("matches").getAsDouble(), delta);
}
@Test
- public void testSettingRankFeatureAsAlias() {
+ void testSettingRankFeatureAsAlias() {
Query query = new Query("?query=test&rankfeature.matches=3");
assertEquals(3, query.getRanking().getFeatures().getDouble("matches").getAsDouble(), delta);
}
@Test
- public void testSettingRankPropertyWithQueryProfile() {
+ void testSettingRankPropertyWithQueryProfile() {
Query query = new Query(HttpRequest.createTestRequest("?query=test&ranking.properties.dotProduct.X=(a:1,b:2)", Method.GET), createProfile());
assertEquals("[(a:1,b:2)]", query.getRanking().getProperties().get("dotProduct.X").toString());
}
@Test
- public void testSettingRankPropertyAsAliasWithQueryProfile() {
+ void testSettingRankPropertyAsAliasWithQueryProfile() {
Query query = new Query(HttpRequest.createTestRequest("?query=test&rankproperty.dotProduct.X=(a:1,b:2)", Method.GET), createProfile());
assertEquals("[(a:1,b:2)]", query.getRanking().getProperties().get("dotProduct.X").toString());
}
@Test
- public void testSettingRankFeatureWithQueryProfile() {
+ void testSettingRankFeatureWithQueryProfile() {
Query query = new Query(HttpRequest.createTestRequest("?query=test&ranking.features.matches=3", Method.GET), createProfile());
assertEquals(3, query.getRanking().getFeatures().getDouble("matches").getAsDouble(), delta);
}
@Test
- public void testSettingRankFeatureAsAliasWithQueryProfile() {
+ void testSettingRankFeatureAsAliasWithQueryProfile() {
Query query = new Query(HttpRequest.createTestRequest("?query=test&rankfeature.matches=3", Method.GET), createProfile());
assertEquals(3, query.getRanking().getFeatures().getDouble("matches").getAsDouble(), delta);
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/test/PresentationTestCase.java b/container-search/src/test/java/com/yahoo/search/query/test/PresentationTestCase.java
index aafbeaf5825..4aefd3c82e0 100644
--- a/container-search/src/test/java/com/yahoo/search/query/test/PresentationTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/test/PresentationTestCase.java
@@ -4,11 +4,9 @@ package com.yahoo.search.query.test;
import com.yahoo.prelude.query.Highlight;
import com.yahoo.search.Query;
import com.yahoo.search.query.Presentation;
-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.jupiter.api.Assertions.*;
/**
* @author Arne Bergene Fossaa
@@ -16,20 +14,20 @@ import static org.junit.Assert.assertTrue;
public class PresentationTestCase {
@Test
- public void testClone() {
- Query q= new Query("");
+ void testClone() {
+ Query q = new Query("");
Presentation p = new Presentation(q);
p.setBolding(true);
Highlight h = new Highlight();
- h.addHighlightTerm("date","today");
+ h.addHighlightTerm("date", "today");
p.setHighlight(h);
- Presentation pc = (Presentation)p.clone();
- h.addHighlightTerm("title","Hello");
+ Presentation pc = (Presentation) p.clone();
+ h.addHighlightTerm("title", "Hello");
assertTrue(pc.getBolding());
pc.getHighlight().getHighlightItems();
assertTrue(pc.getHighlight().getHighlightItems().containsKey("date"));
assertFalse(pc.getHighlight().getHighlightItems().containsKey("title"));
- assertEquals(p,pc);
+ assertEquals(p, pc);
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/test/RankFeaturesTestCase.java b/container-search/src/test/java/com/yahoo/search/query/test/RankFeaturesTestCase.java
index 0644a2b02e8..b1e406c47d7 100644
--- a/container-search/src/test/java/com/yahoo/search/query/test/RankFeaturesTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/test/RankFeaturesTestCase.java
@@ -10,7 +10,7 @@ import com.yahoo.tensor.Tensor;
import com.yahoo.tensor.TensorType;
import com.yahoo.tensor.serialization.TypedBinaryFormat;
import com.yahoo.text.Utf8;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
import java.util.Arrays;
@@ -19,7 +19,7 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author geirst
@@ -27,7 +27,7 @@ import static org.junit.Assert.assertEquals;
public class RankFeaturesTestCase {
@Test
- public void requireThatRankPropertiesTakesBothStringAndObject() {
+ void requireThatRankPropertiesTakesBothStringAndObject() {
RankProperties p = new RankProperties();
p.put("string", "b");
p.put("object", 7);
@@ -37,7 +37,7 @@ public class RankFeaturesTestCase {
@Test
@SuppressWarnings("deprecation")
- public void requireThatRankFeaturesUsingDoubleAndDoubleToStringEncodeTheSameWay() {
+ void requireThatRankFeaturesUsingDoubleAndDoubleToStringEncodeTheSameWay() {
RankFeatures withDouble = new RankFeatures(new Ranking(new Query()));
withDouble.put("query(myDouble)", 3.8);
assertEquals(3.8, withDouble.getDouble("query(myDouble)").getAsDouble(), 0.000001);
@@ -56,7 +56,7 @@ public class RankFeaturesTestCase {
}
@Test
- public void requireThatSingleTensorIsBinaryEncoded() {
+ void requireThatSingleTensorIsBinaryEncoded() {
TensorType type = new TensorType.Builder().mapped("x").mapped("y").mapped("z").build();
Tensor tensor = Tensor.from(type, "{ {x:a, y:b, z:c}:2.0, {x:a, y:b, z:c2}:3.0 }");
assertTensorEncodingAndDecoding(type, "query(my_tensor)", "my_tensor", tensor);
@@ -64,7 +64,7 @@ public class RankFeaturesTestCase {
}
@Test
- public void requireThatMultipleTensorsAreBinaryEncoded() {
+ void requireThatMultipleTensorsAreBinaryEncoded() {
TensorType type = new TensorType.Builder().mapped("x").mapped("y").mapped("z").build();
Tensor tensor1 = Tensor.from(type, "{ {x:a, y:b, z:c}:2.0, {x:a, y:b, z:c2}:3.0 }");
Tensor tensor2 = Tensor.from(type, "{ {x:a, y:b, z:c}:5.0 }");
diff --git a/container-search/src/test/java/com/yahoo/search/query/test/RankingTestCase.java b/container-search/src/test/java/com/yahoo/search/query/test/RankingTestCase.java
index 7a9080f46db..a6bc7460f2e 100644
--- a/container-search/src/test/java/com/yahoo/search/query/test/RankingTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/test/RankingTestCase.java
@@ -3,10 +3,10 @@ package com.yahoo.search.query.test;
import com.yahoo.search.Query;
import com.yahoo.search.query.Sorting;
-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.assertNotNull;
/**
* @author Arne Bergene Fossaa
@@ -17,7 +17,7 @@ public class RankingTestCase {
/** Tests setting rank feature values */
@Test
- public void testRankFeatures() {
+ void testRankFeatures() {
// Check initializing from query
Query query = new Query("?query=test&ranking.features.query(name)=0.1&ranking.features.fieldMatch(foo)=0.2");
assertEquals(0.1, query.getRanking().getFeatures().getDouble("query(name)").getAsDouble(), delta);
@@ -30,8 +30,8 @@ public class RankingTestCase {
assertEquals(0.2, query.getRanking().getFeatures().getDouble("fieldMatch(foo)").getAsDouble(), delta);
// Check programmatic setting + that the clone really has a separate object
- assertFalse(clone.getRanking().getFeatures() == query.getRanking().getFeatures());
- clone.properties().set("ranking.features.query(name)","0.3");
+ assertNotNull(query.getRanking().getFeatures());
+ clone.properties().set("ranking.features.query(name)", "0.3");
assertEquals(0.3, clone.getRanking().getFeatures().getDouble("query(name)").getAsDouble(), delta);
assertEquals(0.1, query.getRanking().getFeatures().getDouble("query(name)").getAsDouble(), delta);
@@ -47,7 +47,7 @@ public class RankingTestCase {
// This test is order dependent. Fix this!!
@Test
- public void test_setting_rank_feature_values() {
+ void test_setting_rank_feature_values() {
// Check initializing from query
Query query = new Query("?query=test&ranking.properties.foo=bar1&ranking.properties.foo2=bar2&ranking.properties.other=10");
assertEquals("bar1", query.getRanking().getProperties().get("foo").get(0));
@@ -57,13 +57,13 @@ public class RankingTestCase {
// Test cloning
Query clone = query.clone();
- assertFalse(clone.getRanking().getProperties() == query.getRanking().getProperties());
+ assertNotNull(query.getRanking().getProperties());
assertEquals("bar1", clone.getRanking().getProperties().get("foo").get(0));
assertEquals("bar2", clone.getRanking().getProperties().get("foo2").get(0));
assertEquals("10", clone.getRanking().getProperties().get("other").get(0));
// Check programmatic setting mean addition
- clone.properties().set("ranking.properties.other","12");
+ clone.properties().set("ranking.properties.other", "12");
assertEquals("[10, 12]", clone.getRanking().getProperties().get("other").toString());
assertEquals("[10]", query.getRanking().getProperties().get("other").toString());
@@ -74,14 +74,14 @@ public class RankingTestCase {
/** Test setting sorting to null does not cause an exception. */
@Test
- public void testResetSorting() {
+ void testResetSorting() {
Query q = new Query();
- q.getRanking().setSorting((Sorting)null);
- q.getRanking().setSorting((String)null);
+ q.getRanking().setSorting((Sorting) null);
+ q.getRanking().setSorting((String) null);
}
@Test
- public void testStructuredRankProperty() {
+ void testStructuredRankProperty() {
Query query = new Query("?query=abc&rankproperty.distanceToPath(gps_position).path=(0,0,10,0,10,5,20,5)");
assertEquals("(0,0,10,0,10,5,20,5)", query.getRanking().getProperties().get("distanceToPath(gps_position).path").get(0));
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/textserialize/item/test/ParseItemTestCase.java b/container-search/src/test/java/com/yahoo/search/query/textserialize/item/test/ParseItemTestCase.java
index b351bfb927a..07beabe14f3 100644
--- a/container-search/src/test/java/com/yahoo/search/query/textserialize/item/test/ParseItemTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/textserialize/item/test/ParseItemTestCase.java
@@ -19,13 +19,11 @@ import com.yahoo.search.query.textserialize.item.ItemContext;
import com.yahoo.search.query.textserialize.item.ItemFormHandler;
import com.yahoo.search.query.textserialize.parser.ParseException;
import com.yahoo.search.query.textserialize.parser.Parser;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.StringReader;
-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 Tony Vaagenes
@@ -40,12 +38,12 @@ public class ParseItemTestCase {
}
@Test
- public void parse_and() throws ParseException {
+ void parse_and() throws ParseException {
assertTrue(parse("(AND)") instanceof AndItem);
}
@Test
- public void parse_and_with_children() throws ParseException {
+ void parse_and_with_children() throws ParseException {
AndItem andItem = (AndItem) parse("(AND (WORD 'first') (WORD 'second'))");
assertEquals(2, andItem.getItemCount());
@@ -53,116 +51,120 @@ public class ParseItemTestCase {
}
@Test
- public void parse_or() throws ParseException {
+ void parse_or() throws ParseException {
assertTrue(parse("(OR)") instanceof OrItem);
}
@Test
- public void parse_and_not_rest() throws ParseException {
+ void parse_and_not_rest() throws ParseException {
assertTrue(parse("(AND-NOT-REST)") instanceof NotItem);
}
@Test
- public void parse_and_not_rest_with_children() throws ParseException {
+ void parse_and_not_rest_with_children() throws ParseException {
NotItem notItem = (NotItem) parse("(AND-NOT-REST (WORD 'positive') (WORD 'negative'))");
assertEquals("positive", getWord(notItem.getPositiveItem()));
assertEquals("negative", getWord(notItem.getItem(1)));
}
@Test
- public void parse_and_not_rest_with_only_negated_children() throws ParseException {
+ void parse_and_not_rest_with_only_negated_children() throws ParseException {
NotItem notItem = (NotItem) parse("(AND-NOT-REST null (WORD 'negated-item'))");
assertTrue(notItem.getPositiveItem() instanceof TrueItem);
assertTrue(notItem.getItem(1) instanceof WordItem);
}
@Test
- public void parse_rank() throws ParseException {
+ void parse_rank() throws ParseException {
assertTrue(parse("(RANK (WORD 'first'))") instanceof RankItem);
}
@Test
- public void parse_word() throws ParseException {
+ void parse_word() throws ParseException {
WordItem wordItem = (WordItem) parse("(WORD 'text')");
assertEquals("text", wordItem.getWord());
}
- @Test(expected = IllegalArgumentException.class)
- public void fail_when_word_given_multiple_strings() throws ParseException {
- parse("(WORD 'one' 'invalid')");
+ @Test
+ void fail_when_word_given_multiple_strings() throws ParseException {
+ assertThrows(IllegalArgumentException.class, () -> {
+ parse("(WORD 'one' 'invalid')");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void fail_when_word_given_no_string() throws ParseException {
- parse("(WORD)");
+ @Test
+ void fail_when_word_given_no_string() throws ParseException {
+ assertThrows(IllegalArgumentException.class, () -> {
+ parse("(WORD)");
+ });
}
@Test
- public void parse_int() throws ParseException {
+ void parse_int() throws ParseException {
IntItem intItem = (IntItem) parse("(INT '[42;]')");
assertEquals("[42;]", intItem.getNumber());
}
@Test
- public void parse_range() throws ParseException {
+ void parse_range() throws ParseException {
IntItem intItem = (IntItem) parse("(INT '[42;73]')");
assertEquals("[42;73]", intItem.getNumber());
}
@Test
- public void parse_range_withlimit() throws ParseException {
+ void parse_range_withlimit() throws ParseException {
IntItem intItem = (IntItem) parse("(INT '[42;73;32]')");
assertEquals("[42;73;32]", intItem.getNumber());
}
@Test
- public void parse_prefix() throws ParseException {
+ void parse_prefix() throws ParseException {
PrefixItem prefixItem = (PrefixItem) parse("(PREFIX 'word')");
assertEquals("word", prefixItem.getWord());
}
@Test
- public void parse_subString() throws ParseException {
+ void parse_subString() throws ParseException {
SubstringItem subStringItem = (SubstringItem) parse("(SUBSTRING 'word')");
assertEquals("word", subStringItem.getWord());
}
@Test
- public void parse_exactString() throws ParseException {
+ void parse_exactString() throws ParseException {
ExactStringItem subStringItem = (ExactStringItem) parse("(EXACT 'word')");
assertEquals("word", subStringItem.getWord());
}
@Test
- public void parse_suffix() throws ParseException {
+ void parse_suffix() throws ParseException {
SuffixItem suffixItem = (SuffixItem) parse("(SUFFIX 'word')");
assertEquals("word", suffixItem.getWord());
}
@Test
- public void parse_phrase() throws ParseException {
+ void parse_phrase() throws ParseException {
PhraseItem phraseItem = (PhraseItem) parse("(PHRASE (WORD 'word'))");
assertTrue(phraseItem.getItem(0) instanceof WordItem);
}
@Test
- public void parse_near() throws ParseException {
+ void parse_near() throws ParseException {
assertTrue(parse("(NEAR)") instanceof NearItem);
}
@Test
- public void parse_onear() throws ParseException {
+ void parse_onear() throws ParseException {
assertTrue(parse("(ONEAR)") instanceof ONearItem);
}
@Test
- public void parse_near_with_distance() throws ParseException {
+ void parse_near_with_distance() throws ParseException {
NearItem nearItem = (NearItem) parse("(NEAR {'distance' 42} (WORD 'first'))");
assertEquals(42, nearItem.getDistance());
}
@Test
- public void parse_items_with_connectivity() throws ParseException {
+ void parse_items_with_connectivity() throws ParseException {
AndItem andItem = (AndItem) parse("(AND (WORD {'id' '1'} 'first') (WORD {'connectivity' ['1' 23.5]} 'second'))");
WordItem secondItem = (WordItem) andItem.getItem(1);
@@ -171,13 +173,13 @@ public class ParseItemTestCase {
}
@Test
- public void parse_word_with_index() throws ParseException {
+ void parse_word_with_index() throws ParseException {
WordItem wordItem = (WordItem) parse("(WORD {'index' 'someIndex'} 'text')");
assertEquals("someIndex", wordItem.getIndexName());
}
@Test
- public void parse_unicode_word() throws ParseException {
+ void parse_unicode_word() throws ParseException {
WordItem wordItem = (WordItem) parse("(WORD 'trăm')");
assertEquals("trăm", wordItem.getWord());
}
diff --git a/container-search/src/test/java/com/yahoo/search/query/textserialize/serializer/test/SerializeItemTestCase.java b/container-search/src/test/java/com/yahoo/search/query/textserialize/serializer/test/SerializeItemTestCase.java
index 133382cbe91..65458cfb8ee 100644
--- a/container-search/src/test/java/com/yahoo/search/query/textserialize/serializer/test/SerializeItemTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/query/textserialize/serializer/test/SerializeItemTestCase.java
@@ -11,12 +11,12 @@ import com.yahoo.prelude.query.PhraseItem;
import com.yahoo.prelude.query.WordItem;
import com.yahoo.search.query.textserialize.parser.ParseException;
import com.yahoo.search.query.textserialize.serializer.QueryTreeSerializer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static com.yahoo.search.query.textserialize.item.test.ParseItemTestCase.parse;
import static com.yahoo.search.query.textserialize.item.test.ParseItemTestCase.getWord;
-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 Tony Vaagenes
@@ -24,7 +24,7 @@ import static org.junit.Assert.assertTrue;
public class SerializeItemTestCase {
@Test
- public void serialize_word_item() {
+ void serialize_word_item() {
WordItem item = new WordItem("test that \" and \\ works");
item.setIndexName("index\"Name");
@@ -34,7 +34,7 @@ public class SerializeItemTestCase {
}
@Test
- public void serialize_and_item() {
+ void serialize_and_item() {
AndItem andItem = new AndItem();
andItem.addItem(new WordItem("first"));
andItem.addItem(new WordItem("second"));
@@ -46,12 +46,12 @@ public class SerializeItemTestCase {
}
@Test
- public void serialize_or_item() {
+ void serialize_or_item() {
assertTrue(serializeThenParse(new OrItem()) instanceof OrItem);
}
@Test
- public void serialize_not_item() {
+ void serialize_not_item() {
NotItem notItem = new NotItem();
{
notItem.addItem(new WordItem("first"));
@@ -62,7 +62,7 @@ public class SerializeItemTestCase {
}
@Test
- public void serialize_near_item() {
+ void serialize_near_item() {
int distance = 23;
NearItem nearItem = new NearItem(distance);
{
@@ -77,8 +77,8 @@ public class SerializeItemTestCase {
}
@Test
- public void serialize_phrase_item() throws ParseException {
- PhraseItem phraseItem = new PhraseItem(new String[] {"first", "second"});
+ void serialize_phrase_item() throws ParseException {
+ PhraseItem phraseItem = new PhraseItem(new String[]{"first", "second"});
phraseItem.setIndexName("indexName");
PhraseItem deSerialized = serializeThenParse(phraseItem);
@@ -88,7 +88,7 @@ public class SerializeItemTestCase {
}
@Test
- public void serialize_equiv_item() {
+ void serialize_equiv_item() {
EquivItem equivItem = new EquivItem();
equivItem.addItem(new WordItem("first"));
@@ -97,7 +97,7 @@ public class SerializeItemTestCase {
}
@Test
- public void serialize_connectivity() {
+ void serialize_connectivity() {
OrItem orItem = new OrItem();
{
WordItem first = new WordItem("first");
@@ -117,7 +117,7 @@ public class SerializeItemTestCase {
}
@Test
- public void serialize_significance() {
+ void serialize_significance() {
EquivItem equivItem = new EquivItem();
equivItem.setSignificance(24.2);
@@ -126,7 +126,7 @@ public class SerializeItemTestCase {
}
@Test
- public void serialize_unique_id() {
+ void serialize_unique_id() {
EquivItem equivItem = new EquivItem();
equivItem.setUniqueID(42);
@@ -135,7 +135,7 @@ public class SerializeItemTestCase {
}
@Test
- public void serialize_weight() {
+ void serialize_weight() {
EquivItem equivItem = new EquivItem();
equivItem.setWeight(42);
diff --git a/container-search/src/test/java/com/yahoo/search/querytransform/BooleanAttributeParserTest.java b/container-search/src/test/java/com/yahoo/search/querytransform/BooleanAttributeParserTest.java
index 66fdbdcb267..9889c479b84 100644
--- a/container-search/src/test/java/com/yahoo/search/querytransform/BooleanAttributeParserTest.java
+++ b/container-search/src/test/java/com/yahoo/search/querytransform/BooleanAttributeParserTest.java
@@ -2,13 +2,13 @@
package com.yahoo.search.querytransform;
import com.yahoo.prelude.query.PredicateQueryItem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.math.BigInteger;
import java.util.Iterator;
-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 magnarn
@@ -16,7 +16,7 @@ import static org.junit.Assert.fail;
public class BooleanAttributeParserTest {
@Test
- public void requireThatParseHandlesAllFormats() {
+ void requireThatParseHandlesAllFormats() {
assertParse(null, 0);
assertParse("{}", 0);
assertParse("{foo:bar}", 1);
@@ -37,7 +37,7 @@ public class BooleanAttributeParserTest {
}
@Test
- public void requireThatIllegalStringsFail() {
+ void requireThatIllegalStringsFail() {
assertException("{foo:[bar:[baz]}");
assertException("{foo:[bar:baz}");
assertException("{foo:bar:[0,1,2}");
@@ -60,7 +60,7 @@ public class BooleanAttributeParserTest {
}
@Test
- public void requireThatTermsCanHaveBitmaps() {
+ void requireThatTermsCanHaveBitmaps() {
PredicateQueryItem q = assertParse("{foo:bar:0x1}", 1);
PredicateQueryItem.Entry[] features = new PredicateQueryItem.Entry[q.getFeatures().size()];
q.getFeatures().toArray(features);
diff --git a/container-search/src/test/java/com/yahoo/search/querytransform/BooleanSearcherTestCase.java b/container-search/src/test/java/com/yahoo/search/querytransform/BooleanSearcherTestCase.java
index 599b0ca4443..247c96f0676 100644
--- a/container-search/src/test/java/com/yahoo/search/querytransform/BooleanSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/querytransform/BooleanSearcherTestCase.java
@@ -8,12 +8,12 @@ import com.yahoo.search.Query;
import com.yahoo.search.Result;
import com.yahoo.search.Searcher;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.util.Collection;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Test BooleanSearcher
@@ -27,13 +27,13 @@ public class BooleanSearcherTestCase {
Execution.Context.createContextStub());
}
- @Before
+ @BeforeEach
public void setUp() throws Exception {
exec = buildExec();
}
@Test
- public void requireThatAttributeMapToSingleFeature() {
+ void requireThatAttributeMapToSingleFeature() {
PredicateQueryItem item = buildPredicateQueryItem("{gender:female}", null);
assertEquals(1, item.getFeatures().size());
assertEquals(0, item.getRangeFeatures().size());
@@ -43,7 +43,7 @@ public class BooleanSearcherTestCase {
}
@Test
- public void requireThatAttributeListMapToMultipleFeatures() {
+ void requireThatAttributeListMapToMultipleFeatures() {
PredicateQueryItem item = buildPredicateQueryItem("{gender:[female,male]}", null);
assertEquals(2, item.getFeatures().size());
assertEquals(0, item.getRangeFeatures().size());
@@ -51,7 +51,7 @@ public class BooleanSearcherTestCase {
}
@Test
- public void requireThatRangeAttributesMapToRangeTerm() {
+ void requireThatRangeAttributesMapToRangeTerm() {
PredicateQueryItem item = buildPredicateQueryItem(null, "{age:25}");
assertEquals(0, item.getFeatures().size());
assertEquals(1, item.getRangeFeatures().size());
@@ -63,17 +63,17 @@ public class BooleanSearcherTestCase {
}
@Test
- public void requireThatQueryWithoutBooleanPropertiesIsUnchanged() {
+ void requireThatQueryWithoutBooleanPropertiesIsUnchanged() {
Query q = new Query("");
q.getModel().getQueryTree().setRoot(new WordItem("foo", "otherfield"));
Result r = exec.search(q);
- WordItem root = (WordItem)r.getQuery().getModel().getQueryTree().getRoot();
+ WordItem root = (WordItem) r.getQuery().getModel().getQueryTree().getRoot();
assertEquals("foo", root.getWord());
}
@Test
- public void requireThatBooleanSearcherCanBuildPredicateQueryItem() {
+ void requireThatBooleanSearcherCanBuildPredicateQueryItem() {
PredicateQueryItem root = buildPredicateQueryItem("{gender:female}", "{age:23:[2, 3, 5]}");
Collection<PredicateQueryItem.Entry> features = root.getFeatures();
@@ -92,7 +92,7 @@ public class BooleanSearcherTestCase {
}
@Test
- public void requireThatKeysAndValuesCanContainSpaces() {
+ void requireThatKeysAndValuesCanContainSpaces() {
PredicateQueryItem item = buildPredicateQueryItem("{'My Key':'My Value'}", null);
assertEquals(1, item.getFeatures().size());
assertEquals(0, item.getRangeFeatures().size());
diff --git a/container-search/src/test/java/com/yahoo/search/querytransform/LowercasingTestCase.java b/container-search/src/test/java/com/yahoo/search/querytransform/LowercasingTestCase.java
index 025c3ff7a32..3a8442bc12d 100644
--- a/container-search/src/test/java/com/yahoo/search/querytransform/LowercasingTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/querytransform/LowercasingTestCase.java
@@ -2,19 +2,16 @@
package com.yahoo.search.querytransform;
-import static org.junit.Assert.assertEquals;
-
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.yahoo.prelude.IndexModel;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
import com.yahoo.prelude.SearchDefinition;
import com.yahoo.prelude.query.SameElementItem;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.yahoo.component.chain.Chain;
import com.yahoo.prelude.Index;
import com.yahoo.prelude.IndexFacts;
@@ -69,7 +66,7 @@ public class LowercasingTestCase {
}
@Test
- public void simple() {
+ void simple() {
Query q = new Query();
AndItem root = new AndItem();
WordItem tmp;
@@ -92,7 +89,7 @@ public class LowercasingTestCase {
}
@Test
- public void slightlyMoreComplexTree() {
+ void slightlyMoreComplexTree() {
Query q = new Query();
AndItem a0 = new AndItem();
OrItem o0 = new OrItem();
@@ -148,7 +145,7 @@ public class LowercasingTestCase {
}
@Test
- public void testWeightedSet() {
+ void testWeightedSet() {
Query q = new Query();
AndItem root = new AndItem();
WeightedSetItem tmp;
@@ -170,11 +167,11 @@ public class LowercasingTestCase {
}
@Test
- public void testDisableLowercasingWeightedSet() {
+ void testDisableLowercasingWeightedSet() {
Execution execution = new Execution(new Chain<Searcher>(
- new VespaLowercasingSearcher(new LowercasingConfig(
- new LowercasingConfig.Builder()
- .transform_weighted_sets(false)))),
+ new VespaLowercasingSearcher(new LowercasingConfig(
+ new LowercasingConfig.Builder()
+ .transform_weighted_sets(false)))),
Execution.Context.createContextStub(createIndexFacts()));
Query q = new Query();
@@ -198,7 +195,7 @@ public class LowercasingTestCase {
}
@Test
- public void testLowercasingWordAlternatives() {
+ void testLowercasingWordAlternatives() {
Execution execution = new Execution(new Chain<Searcher>(new VespaLowercasingSearcher(new LowercasingConfig(
new LowercasingConfig.Builder().transform_weighted_sets(false)))), Execution.Context.createContextStub(createIndexFacts()));
@@ -221,7 +218,7 @@ public class LowercasingTestCase {
}
@Test
- public void testLowercasingSameElement() {
+ void testLowercasingSameElement() {
Query q = new Query();
SameElementItem root = new SameElementItem(SARR);
root.addItem(new WordItem("ABC", BAMSE, true));
diff --git a/container-search/src/test/java/com/yahoo/search/querytransform/WandSearcherTestCase.java b/container-search/src/test/java/com/yahoo/search/querytransform/WandSearcherTestCase.java
index d2010ec852e..438f36b32a6 100644
--- a/container-search/src/test/java/com/yahoo/search/querytransform/WandSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/querytransform/WandSearcherTestCase.java
@@ -19,17 +19,14 @@ import com.yahoo.search.Query;
import com.yahoo.search.Result;
import com.yahoo.search.Searcher;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.ListIterator;
import static com.yahoo.container.protect.Error.INVALID_QUERY_PARAMETER;
-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.*;
/**
* Testing of WandSearcher.
@@ -88,17 +85,17 @@ public class WandSearcherTestCase {
assertEquals(expWeight, wordItem.getWeight());
}
- @Before
+ @BeforeEach
public void setUp() throws Exception {
exec = buildExec();
}
@Test
- public void requireThatVespaWandCanBeSpecified() {
+ void requireThatVespaWandCanBeSpecified() {
Query q = buildDefaultQuery();
Result r = exec.search(q);
- WeakAndItem root = (WeakAndItem)TestUtils.getQueryTreeRoot(r);
+ WeakAndItem root = (WeakAndItem) TestUtils.getQueryTreeRoot(r);
assertEquals(100, root.getN());
assertEquals(3, root.getItemCount());
ListIterator<Item> itr = root.getItemIterator();
@@ -109,21 +106,21 @@ public class WandSearcherTestCase {
}
@Test
- public void requireThatVespaWandHeapSizeCanBeSpecified() {
+ void requireThatVespaWandHeapSizeCanBeSpecified() {
Query q = buildDefaultQuery(VESPA_FIELD, "50");
Result r = exec.search(q);
- WeakAndItem root = (WeakAndItem)TestUtils.getQueryTreeRoot(r);
+ WeakAndItem root = (WeakAndItem) TestUtils.getQueryTreeRoot(r);
assertEquals(50, root.getN());
}
@Test
- public void requireThatWandCanBeSpecifiedTogetherWithNonAndQueryRoot() {
+ void requireThatWandCanBeSpecifiedTogetherWithNonAndQueryRoot() {
Query q = buildDefaultQuery();
q.getModel().getQueryTree().setRoot(new WordItem("foo", "otherfield"));
Result r = exec.search(q);
- AndItem root = (AndItem)TestUtils.getQueryTreeRoot(r);
+ AndItem root = (AndItem) TestUtils.getQueryTreeRoot(r);
assertEquals(2, root.getItemCount());
ListIterator<Item> itr = root.getItemIterator();
assertTrue(itr.next() instanceof WordItem);
@@ -132,7 +129,7 @@ public class WandSearcherTestCase {
}
@Test
- public void requireThatWandCanBeSpecifiedTogetherWithAndQueryRoot() {
+ void requireThatWandCanBeSpecifiedTogetherWithAndQueryRoot() {
Query q = buildDefaultQuery();
{
AndItem root = new AndItem();
@@ -142,7 +139,7 @@ public class WandSearcherTestCase {
}
Result r = exec.search(q);
- AndItem root = (AndItem)TestUtils.getQueryTreeRoot(r);
+ AndItem root = (AndItem) TestUtils.getQueryTreeRoot(r);
assertEquals(3, root.getItemCount());
ListIterator<Item> itr = root.getItemIterator();
assertTrue(itr.next() instanceof WordItem);
@@ -153,42 +150,42 @@ public class WandSearcherTestCase {
@Test
- public void requireThatNothingIsAddedWithoutWandPropertiesSet() {
+ void requireThatNothingIsAddedWithoutWandPropertiesSet() {
Query foo = new Query("");
foo.getModel().getQueryTree().setRoot(new WordItem("foo", "otherfield"));
Result r = exec.search(foo);
- WordItem root = (WordItem)TestUtils.getQueryTreeRoot(r);
+ WordItem root = (WordItem) TestUtils.getQueryTreeRoot(r);
assertEquals("foo", root.getWord());
}
@Test
- public void requireThatErrorIsReturnedOnInvalidTokenList() {
+ void requireThatErrorIsReturnedOnInvalidTokenList() {
Query q = buildQuery(VESPA_FIELD, "{a1,b:1}", null, null, null, null);
Result r = exec.search(q);
ErrorMessage msg = r.hits().getError();
assertNotNull(msg);
assertEquals(INVALID_QUERY_PARAMETER.code, msg.getCode());
- assertEquals("'{a1,b:1}' is not a legal sparse vector string: Expected ':' starting at position 3 but was ','",msg.getDetailedMessage());
+ assertEquals("'{a1,b:1}' is not a legal sparse vector string: Expected ':' starting at position 3 but was ','", msg.getDetailedMessage());
}
@Test
- public void requireThatErrorIsReturnedOnUnknownField() {
+ void requireThatErrorIsReturnedOnUnknownField() {
Query q = buildDefaultQuery("unknown", "50");
Result r = exec.search(q);
ErrorMessage msg = r.hits().getError();
assertNotNull(msg);
assertEquals(INVALID_QUERY_PARAMETER.code, msg.getCode());
- assertEquals("Field 'unknown' was not found in index facts for search definitions [test]",msg.getDetailedMessage());
+ assertEquals("Field 'unknown' was not found in index facts for search definitions [test]", msg.getDetailedMessage());
}
@Test
- public void requireThatVespaOrCanBeSpecified() {
+ void requireThatVespaOrCanBeSpecified() {
Query q = buildQuery(VESPA_FIELD, "{a:1,b:2,c:3}", null, "or", null, null);
Result r = exec.search(q);
- OrItem root = (OrItem)TestUtils.getQueryTreeRoot(r);
+ OrItem root = (OrItem) TestUtils.getQueryTreeRoot(r);
assertEquals(3, root.getItemCount());
ListIterator<Item> itr = root.getItemIterator();
assertWordItem("a", VESPA_FIELD, 1, itr.next());
@@ -205,11 +202,11 @@ public class WandSearcherTestCase {
}
@Test
- public void requireThatDefaultParallelWandCanBeSpecified() {
+ void requireThatDefaultParallelWandCanBeSpecified() {
Query q = buildQuery(VESPA_FIELD, "{a:1,b:2,c:3}", null, "parallel", null, null);
Result r = exec.search(q);
- WandItem root = (WandItem)TestUtils.getQueryTreeRoot(r);
+ WandItem root = (WandItem) TestUtils.getQueryTreeRoot(r);
assertEquals(VESPA_FIELD, root.getIndexName());
assertEquals(100, root.getTargetNumHits());
assertEquals(0.0, root.getScoreThreshold(), delta);
@@ -218,11 +215,11 @@ public class WandSearcherTestCase {
}
@Test
- public void requireThatParallelWandCanBeSpecified() {
+ void requireThatParallelWandCanBeSpecified() {
Query q = buildQuery(VESPA_FIELD, "{a:1,b:2,c:3}", "50", "parallel", "70.5", "2.3");
Result r = exec.search(q);
- WandItem root = (WandItem)TestUtils.getQueryTreeRoot(r);
+ WandItem root = (WandItem) TestUtils.getQueryTreeRoot(r);
assertEquals(VESPA_FIELD, root.getIndexName());
assertEquals(50, root.getTargetNumHits());
assertEquals(70.5, root.getScoreThreshold(), delta);
@@ -231,11 +228,11 @@ public class WandSearcherTestCase {
}
@Test
- public void requireThatDotProductCanBeSpecified() {
+ void requireThatDotProductCanBeSpecified() {
Query q = buildQuery(VESPA_FIELD, "{a:1,b:2,c:3}", null, "dotProduct", null, null);
Result r = exec.search(q);
- DotProductItem root = (DotProductItem)TestUtils.getQueryTreeRoot(r);
+ DotProductItem root = (DotProductItem) TestUtils.getQueryTreeRoot(r);
assertEquals(VESPA_FIELD, root.getIndexName());
assertWeightedSetItem(root);
}
diff --git a/container-search/src/test/java/com/yahoo/search/querytransform/WeakAndReplacementSearcherTestCase.java b/container-search/src/test/java/com/yahoo/search/querytransform/WeakAndReplacementSearcherTestCase.java
index 54f6bcd4c23..30d06510409 100644
--- a/container-search/src/test/java/com/yahoo/search/querytransform/WeakAndReplacementSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/querytransform/WeakAndReplacementSearcherTestCase.java
@@ -8,11 +8,11 @@ import com.yahoo.search.Query;
import com.yahoo.search.Result;
import com.yahoo.search.Searcher;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.stream.IntStream;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
public class WeakAndReplacementSearcherTestCase {
@@ -42,20 +42,18 @@ public class WeakAndReplacementSearcherTestCase {
}
-
-
@Test
- public void requireOrItemsToBeReplaced() {
+ void requireOrItemsToBeReplaced() {
Query query = buildDefaultQuery(true);
Result result = buildExec().search(query);
Item root = TestUtils.getQueryTreeRoot(result);
assertFalse(orItemsExist(root));
assertTrue(root instanceof WeakAndItem);
- assertEquals(N, ((WeakAndItem)root).getN());
+ assertEquals(N, ((WeakAndItem) root).getN());
}
@Test
- public void requireQueryPropertyToWork() {
+ void requireQueryPropertyToWork() {
Query query = buildDefaultQuery(false);
Item preRoot = query.getModel().getQueryTree().getRoot();
Result result = buildExec().search(query);
@@ -65,7 +63,7 @@ public class WeakAndReplacementSearcherTestCase {
}
@Test
- public void requireDoNothingOnNoOrItems() {
+ void requireDoNothingOnNoOrItems() {
Query query = new Query();
query.properties().set(WEAKAND_REPLACE, true);
AndItem andItem = new AndItem();
@@ -78,7 +76,7 @@ public class WeakAndReplacementSearcherTestCase {
}
@Test
- public void requireChildrenAreTheSame() {
+ void requireChildrenAreTheSame() {
Query query = new Query();
query.properties().set(WEAKAND_REPLACE, true);
OrItem preRoot = new OrItem();
@@ -87,7 +85,7 @@ public class WeakAndReplacementSearcherTestCase {
query.getModel().getQueryTree().setRoot(preRoot);
Result result = buildExec().search(query);
- WeakAndItem root = (WeakAndItem)TestUtils.getQueryTreeRoot(result);
+ WeakAndItem root = (WeakAndItem) TestUtils.getQueryTreeRoot(result);
assertEquals(preRoot.getItem(0), root.getItem(0));
assertEquals(preRoot.getItem(1), root.getItem(1));
}
diff --git a/container-search/src/test/java/com/yahoo/search/querytransform/test/NGramSearcherTestCase.java b/container-search/src/test/java/com/yahoo/search/querytransform/test/NGramSearcherTestCase.java
index 460ae1f641c..8dccf7d0f38 100644
--- a/container-search/src/test/java/com/yahoo/search/querytransform/test/NGramSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/querytransform/test/NGramSearcherTestCase.java
@@ -33,12 +33,10 @@ import com.yahoo.search.querytransform.NGramSearcher;
import com.yahoo.search.result.Hit;
import com.yahoo.search.result.HitGroup;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static com.yahoo.search.searchchain.Execution.Context.createContextStub;
-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 bratseth
@@ -103,7 +101,7 @@ public class NGramSearcherTestCase {
}
@Test
- public void testMixedDocTypes() {
+ void testMixedDocTypes() {
{
Query q = new Query("?query=abc&restrict=song");
createMixedSetupExecution().search(q);
@@ -127,7 +125,7 @@ public class NGramSearcherTestCase {
}
@Test
- public void testMixedClusters() {
+ void testMixedClusters() {
{
Query q = new Query("?query=abc&search=songOnly");
createMixedSetupExecution().search(q);
@@ -151,42 +149,42 @@ public class NGramSearcherTestCase {
}
@Test
- public void testNGramRewritingMixedQuery() {
+ void testNGramRewritingMixedQuery() {
Query q = new Query("?query=foo+gram3:engul+test:bar");
createExecution().search(q);
assertEquals("WEAKAND(100) foo (AND gram3:eng gram3:ngu gram3:gul) test:bar", q.getModel().getQueryTree().toString());
}
@Test
- public void testNGramRewritingNGramOnly() {
+ void testNGramRewritingNGramOnly() {
Query q = new Query("?query=gram3:engul");
createExecution().search(q);
assertEquals("WEAKAND(100) (AND gram3:eng gram3:ngu gram3:gul)", q.getModel().getQueryTree().toString());
}
@Test
- public void testNGramRewriting2NGramsOnly() {
+ void testNGramRewriting2NGramsOnly() {
Query q = new Query("?query=gram3:engul+gram2:123");
createExecution().search(q);
assertEquals("WEAKAND(100) (AND gram3:eng gram3:ngu gram3:gul) (AND gram2:12 gram2:23)", q.getModel().getQueryTree().toString());
}
@Test
- public void testNGramRewritingShortOnly() {
+ void testNGramRewritingShortOnly() {
Query q = new Query("?query=gram3:en");
createExecution().search(q);
assertEquals("WEAKAND(100) gram3:en", q.getModel().getQueryTree().toString());
}
@Test
- public void testNGramRewritingShortInMixes() {
+ void testNGramRewritingShortInMixes() {
Query q = new Query("?query=test:a+gram3:en");
createExecution().search(q);
assertEquals("WEAKAND(100) test:a gram3:en", q.getModel().getQueryTree().toString());
}
@Test
- public void testNGramRewritingPhrase() {
+ void testNGramRewritingPhrase() {
Query q = new Query("?query=gram3:%22engul+a+holi%22");
createExecution().search(q);
assertEquals("WEAKAND(100) gram3:\"eng ngu gul a hol oli\"", q.getModel().getQueryTree().toString());
@@ -197,19 +195,19 @@ public class NGramSearcherTestCase {
* so the ngram rewriter cannot know to keep the grams as a phrase in this case.
*/
@Test
- public void testNGramRewritingPhraseSingleTerm() {
+ void testNGramRewritingPhraseSingleTerm() {
Query q = new Query("?query=gram3:%22engul%22");
createExecution().search(q);
assertEquals("WEAKAND(100) (AND gram3:eng gram3:ngu gram3:gul)", q.getModel().getQueryTree().toString());
}
@Test
- public void testNGramRewritingAdditionalTermInfo() {
+ void testNGramRewritingAdditionalTermInfo() {
Query q = new Query("?query=gram3:engul!50+foo+gram2:123!150");
createExecution().search(q);
- WeakAndItem root = (WeakAndItem)q.getModel().getQueryTree().getRoot();
- AndItem gram3And = (AndItem)root.getItem(0);
- AndItem gram2And = (AndItem)root.getItem(2);
+ WeakAndItem root = (WeakAndItem) q.getModel().getQueryTree().getRoot();
+ AndItem gram3And = (AndItem) root.getItem(0);
+ AndItem gram2And = (AndItem) root.getItem(2);
assertExtraTermInfo(50, "engul", gram3And.getItem(0));
assertExtraTermInfo(50, "engul", gram3And.getItem(1));
@@ -227,21 +225,21 @@ public class NGramSearcherTestCase {
}
@Test
- public void testNGramRewritingExplicitDefault() {
+ void testNGramRewritingExplicitDefault() {
Query q = new Query("?query=default:engul");
createExecution().search(q);
- assertEquals("WEAKAND(100) (AND default:eng default:ngu default:gul)" ,q.getModel().getQueryTree().toString());
+ assertEquals("WEAKAND(100) (AND default:eng default:ngu default:gul)", q.getModel().getQueryTree().toString());
}
@Test
- public void testNGramRewritingImplicitDefault() {
+ void testNGramRewritingImplicitDefault() {
Query q = new Query("?query=engul");
createExecution().search(q);
assertEquals("WEAKAND(100) (AND eng ngu gul)", q.getModel().getQueryTree().toString());
}
@Test
- public void testGramsWithSegmentation() {
+ void testGramsWithSegmentation() {
Searcher searcher = createSearcher();
assertGramsWithSegmentation(new Chain<>(searcher));
assertGramsWithSegmentation(new Chain<>(new CJKSearcher(), searcher));
@@ -259,7 +257,7 @@ public class NGramSearcherTestCase {
}
@Test
- public void testGramsWithSegmentationSingleSegment() {
+ void testGramsWithSegmentationSingleSegment() {
Searcher searcher = createSearcher();
assertGramsWithSegmentationSingleSegment(new Chain<>(searcher));
assertGramsWithSegmentationSingleSegment(new Chain<>(new CJKSearcher(), searcher));
@@ -277,7 +275,7 @@ public class NGramSearcherTestCase {
}
@Test
- public void testGramsWithSegmentationSubstringSegmented() {
+ void testGramsWithSegmentationSubstringSegmented() {
Searcher searcher = createSearcher();
assertGramsWithSegmentationSubstringSegmented(new Chain<>(searcher));
assertGramsWithSegmentationSubstringSegmented(new Chain<>(new CJKSearcher(), searcher));
@@ -296,7 +294,7 @@ public class NGramSearcherTestCase {
}
@Test
- public void testGramsWithSegmentationMixed() {
+ void testGramsWithSegmentationMixed() {
Searcher searcher = createSearcher();
assertGramsWithSegmentationMixed(new Chain<>(searcher));
assertGramsWithSegmentationMixed(new Chain<>(new CJKSearcher(), searcher));
@@ -315,7 +313,7 @@ public class NGramSearcherTestCase {
}
@Test
- public void testGramsWithSegmentationMixedAndPhrases() {
+ void testGramsWithSegmentationMixedAndPhrases() {
Searcher searcher = createSearcher();
assertGramsWithSegmentationMixedAndPhrases(new Chain<>(searcher));
assertGramsWithSegmentationMixedAndPhrases(new Chain<>(new CJKSearcher(), searcher));
@@ -334,19 +332,20 @@ public class NGramSearcherTestCase {
}
@Test
- public void testNGramRecombining() {
+ void testNGramRecombining() {
Query q = new Query("?query=ignored");
Result r = new Execution(new Chain<>(createSearcher(), new MockBackend1()), createContextStub(createIndexFacts())).search(q);
Hit h1 = r.hits().get("hit1");
assertEquals("Should be untouched,\u001feven if containing \u001f",
- h1.getField("test").toString());
+ h1.getField("test").toString());
assertTrue(h1.getField("test") instanceof String);
- assertEquals("Blue red Ed A",h1.getField("gram2").toString());
+ assertEquals("Blue red Ed A", h1.getField("gram2").toString());
assertTrue(h1.getField("gram2") instanceof XMLString);
- assertEquals("Separators on borders work","Blue red ed a\u001f",
- h1.getField("gram3").toString());
+ assertEquals("Blue red ed a\u001f",
+ h1.getField("gram3").toString(),
+ "Separators on borders work");
assertTrue(h1.getField("gram3") instanceof String);
Hit h2 = r.hits().get("hit2");
@@ -356,7 +355,7 @@ public class NGramSearcherTestCase {
Hit h3 = r.hits().get("hit3");
assertEquals("\u001ffin\u001f \u001fen\u001f \u001fa\u001f", h3.getField("gram2").toString());
assertEquals("#Logging in #Java is like that \"Judean P\u001fopul\u001far Front\" scene from \"Life of Brian\".",
- h3.getField("gram3").toString());
+ h3.getField("gram3").toString());
}
private Item parseQuery(String query, Query.Type type) {
diff --git a/container-search/src/test/java/com/yahoo/search/querytransform/test/RangeQueryOptimizerTestCase.java b/container-search/src/test/java/com/yahoo/search/querytransform/test/RangeQueryOptimizerTestCase.java
index df6cd046b74..927a891a797 100644
--- a/container-search/src/test/java/com/yahoo/search/querytransform/test/RangeQueryOptimizerTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/querytransform/test/RangeQueryOptimizerTestCase.java
@@ -19,12 +19,12 @@ import com.yahoo.search.query.parser.ParserEnvironment;
import com.yahoo.search.query.parser.ParserFactory;
import com.yahoo.search.querytransform.RangeQueryOptimizer;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.Iterator;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -35,9 +35,9 @@ public class RangeQueryOptimizerTestCase {
private static IndexFacts indexFacts = createIndexFacts();
@Test
- public void testRangeOptimizing() {
+ void testRangeOptimizing() {
assertOptimized("s:<15", "s:<15");
- assertOptimized("AND a s:[1999;2002]","a AND s:[1999;2002]");
+ assertOptimized("AND a s:[1999;2002]", "a AND s:[1999;2002]");
assertOptimized("AND s:<10;15>", "s:<15 AND s:>10");
assertOptimized("AND s:give s:5 s:me", "s:give s:5 s:me");
assertOptimized("AND s:[;15> b:<10;]", "s:<15 AND b:>10");
@@ -59,7 +59,7 @@ public class RangeQueryOptimizerTestCase {
}
@Test
- public void testRangeOptimizingCarriesOverItemAttributesWhenNotOptimized() {
+ void testRangeOptimizingCarriesOverItemAttributesWhenNotOptimized() {
Query query = new Query();
AndItem root = new AndItem();
query.getModel().getQueryTree().setRoot(root);
@@ -69,14 +69,14 @@ public class RangeQueryOptimizerTestCase {
intItem.setRanked(false);
root.addItem(intItem);
assertOptimized("Not optimized", "AND |s:<15;]!500", query);
- IntItem transformedIntItem = (IntItem)((AndItem)query.getModel().getQueryTree().getRoot()).getItem(0);
- assertTrue("Filter was carried over", transformedIntItem.isFilter());
- assertFalse("Ranked was carried over", transformedIntItem.isRanked());
- assertEquals("Weight was carried over", 500, transformedIntItem.getWeight());
+ IntItem transformedIntItem = (IntItem) ((AndItem) query.getModel().getQueryTree().getRoot()).getItem(0);
+ assertTrue(transformedIntItem.isFilter(), "Filter was carried over");
+ assertFalse(transformedIntItem.isRanked(), "Ranked was carried over");
+ assertEquals(500, transformedIntItem.getWeight(), "Weight was carried over");
}
@Test
- public void testRangeOptimizingCarriesOverItemAttributesWhenOptimized() {
+ void testRangeOptimizingCarriesOverItemAttributesWhenOptimized() {
Query query = new Query();
AndItem root = new AndItem();
query.getModel().getQueryTree().setRoot(root);
@@ -94,14 +94,14 @@ public class RangeQueryOptimizerTestCase {
root.addItem(intItem2);
assertOptimized("Optimized", "AND |s:<15;30>!500", query);
- IntItem transformedIntItem = (IntItem)((AndItem)query.getModel().getQueryTree().getRoot()).getItem(0);
- assertTrue("Filter was carried over", transformedIntItem.isFilter());
- assertFalse("Ranked was carried over", transformedIntItem.isRanked());
- assertEquals("Weight was carried over", 500, transformedIntItem.getWeight());
+ IntItem transformedIntItem = (IntItem) ((AndItem) query.getModel().getQueryTree().getRoot()).getItem(0);
+ assertTrue(transformedIntItem.isFilter(), "Filter was carried over");
+ assertFalse(transformedIntItem.isRanked(), "Ranked was carried over");
+ assertEquals(500, transformedIntItem.getWeight(), "Weight was carried over");
}
@Test
- public void testNoRangeOptimizingWhenAttributesAreIncompatible() {
+ void testNoRangeOptimizingWhenAttributesAreIncompatible() {
Query query = new Query();
AndItem root = new AndItem();
query.getModel().getQueryTree().setRoot(root);
@@ -120,19 +120,19 @@ public class RangeQueryOptimizerTestCase {
assertOptimized("Not optimized", "AND |s:<15;]!500 s:[;30>!500", query);
- IntItem transformedIntItem1 = (IntItem)((AndItem)query.getModel().getQueryTree().getRoot()).getItem(0);
- assertTrue("Filter was carried over", transformedIntItem1.isFilter());
- assertFalse("Ranked was carried over", transformedIntItem1.isRanked());
- assertEquals("Weight was carried over", 500, transformedIntItem1.getWeight());
+ IntItem transformedIntItem1 = (IntItem) ((AndItem) query.getModel().getQueryTree().getRoot()).getItem(0);
+ assertTrue(transformedIntItem1.isFilter(), "Filter was carried over");
+ assertFalse(transformedIntItem1.isRanked(), "Ranked was carried over");
+ assertEquals(500, transformedIntItem1.getWeight(), "Weight was carried over");
- IntItem transformedIntItem2 = (IntItem)((AndItem)query.getModel().getQueryTree().getRoot()).getItem(1);
- assertFalse("Filter was carried over", transformedIntItem2.isFilter());
- assertFalse("Ranked was carried over", transformedIntItem2.isRanked());
- assertEquals("Weight was carried over", 500, transformedIntItem2.getWeight());
+ IntItem transformedIntItem2 = (IntItem) ((AndItem) query.getModel().getQueryTree().getRoot()).getItem(1);
+ assertFalse(transformedIntItem2.isFilter(), "Filter was carried over");
+ assertFalse(transformedIntItem2.isRanked(), "Ranked was carried over");
+ assertEquals(500, transformedIntItem2.getWeight(), "Weight was carried over");
}
@Test
- public void testDifferentCompatibleRangesPerFieldAreOptimizedSeparately() {
+ void testDifferentCompatibleRangesPerFieldAreOptimizedSeparately() {
Query query = new Query();
AndItem root = new AndItem();
query.getModel().getQueryTree().setRoot(root);
@@ -155,21 +155,21 @@ public class RangeQueryOptimizerTestCase {
assertOptimized("Optimized", "AND s:<15;30> s:<100;150>", query);
- IntItem transformedIntItem1 = (IntItem)((AndItem)query.getModel().getQueryTree().getRoot()).getItem(0);
- assertFalse("Ranked was carried over", transformedIntItem1.isRanked());
+ IntItem transformedIntItem1 = (IntItem) ((AndItem) query.getModel().getQueryTree().getRoot()).getItem(0);
+ assertFalse(transformedIntItem1.isRanked(), "Ranked was carried over");
- IntItem transformedIntItem2 = (IntItem)((AndItem)query.getModel().getQueryTree().getRoot()).getItem(1);
- assertTrue("Ranked was carried over", transformedIntItem2.isRanked());
+ IntItem transformedIntItem2 = (IntItem) ((AndItem) query.getModel().getQueryTree().getRoot()).getItem(1);
+ assertTrue(transformedIntItem2.isRanked(), "Ranked was carried over");
}
@Test
- public void assertOptmimizedYQLQuery() {
+ void assertOptmimizedYQLQuery() {
Query query = new Query("/?query=select%20%2A%20from%20sources%20%2A%20where%20%28range%28s%2C%20100000%2C%20100000%29%20OR%20range%28t%2C%20-20000000000L%2C%20-20000000000L%29%20OR%20range%28t%2C%2030%2C%2030%29%29%3B&type=yql");
assertOptimized("YQL usage of the IntItem API works", "OR s:100000 t:-20000000000 t:30", query);
}
@Test
- public void testTracing() {
+ void testTracing() {
Query notOptimized = new Query("/?tracelevel=2");
notOptimized.getModel().getQueryTree().setRoot(parseQuery("s:<15"));
assertOptimized("", "s:<15", notOptimized);
@@ -200,7 +200,7 @@ public class RangeQueryOptimizerTestCase {
private Query assertOptimized(String explanation, String expected, Query query) {
Chain<Searcher> chain = new Chain<>("test", new RangeQueryOptimizer());
new Execution(chain, Execution.Context.createContextStub(indexFacts)).search(query);
- assertEquals(explanation, expected, query.getModel().getQueryTree().getRoot().toString());
+ assertEquals(expected, query.getModel().getQueryTree().getRoot().toString(), explanation);
return query;
}
diff --git a/container-search/src/test/java/com/yahoo/search/querytransform/test/SortingDegraderTestCase.java b/container-search/src/test/java/com/yahoo/search/querytransform/test/SortingDegraderTestCase.java
index ccdb612b9ba..3b9c2651bf6 100644
--- a/container-search/src/test/java/com/yahoo/search/querytransform/test/SortingDegraderTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/querytransform/test/SortingDegraderTestCase.java
@@ -13,9 +13,9 @@ import com.yahoo.search.grouping.GroupingQueryParser;
import com.yahoo.search.query.properties.DefaultProperties;
import com.yahoo.search.querytransform.SortingDegrader;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -23,7 +23,7 @@ import static org.junit.Assert.*;
public class SortingDegraderTestCase {
@Test
- public void testDegradingAscending() {
+ void testDegradingAscending() {
Query query = new Query("?ranking.sorting=%2ba1%20-a2");
execute(query);
assertEquals("a1", query.getRanking().getMatchPhase().getAttribute());
@@ -33,7 +33,7 @@ public class SortingDegraderTestCase {
}
@Test
- public void testDegradingDescending() {
+ void testDegradingDescending() {
Query query = new Query("?ranking.sorting=-a1%20-a2");
execute(query);
assertEquals("a1", query.getRanking().getMatchPhase().getAttribute());
@@ -42,7 +42,7 @@ public class SortingDegraderTestCase {
}
@Test
- public void testDegradingNonDefaultMaxHits() {
+ void testDegradingNonDefaultMaxHits() {
Query query = new Query("?ranking.sorting=-a1%20-a2&ranking.matchPhase.maxHits=37");
execute(query);
assertEquals("a1", query.getRanking().getMatchPhase().getAttribute());
@@ -51,7 +51,7 @@ public class SortingDegraderTestCase {
}
@Test
- public void testDegradingNonDefaultMaxFilterCoverage() {
+ void testDegradingNonDefaultMaxFilterCoverage() {
Query query = new Query("?ranking.sorting=-a1%20-a2&ranking.matchPhase.maxFilterCoverage=0.37");
execute(query);
assertEquals("a1", query.getRanking().getMatchPhase().getAttribute());
@@ -60,7 +60,7 @@ public class SortingDegraderTestCase {
}
@Test
- public void testDegradingNonDefaultIllegalMaxFilterCoverage() {
+ void testDegradingNonDefaultIllegalMaxFilterCoverage() {
try {
Query query = new Query("?ranking.sorting=-a1%20-a2&ranking.matchPhase.maxFilterCoverage=37");
assertTrue(false);
@@ -75,7 +75,7 @@ public class SortingDegraderTestCase {
}
@Test
- public void testNoDegradingWhenGrouping() {
+ void testNoDegradingWhenGrouping() {
Query query = new Query("?ranking.sorting=%2ba1%20-a2&select=all(group(a1)%20each(output(a1)))");
execute(query);
assertNull(query.getRanking().getMatchPhase().getAttribute());
@@ -83,28 +83,28 @@ public class SortingDegraderTestCase {
}
@Test
- public void testNoDegradingWhenNonFastSearchAttribute() {
+ void testNoDegradingWhenNonFastSearchAttribute() {
Query query = new Query("?ranking.sorting=%2bnonFastSearchAttribute%20-a2");
execute(query);
assertNull(query.getRanking().getMatchPhase().getAttribute());
}
@Test
- public void testNoDegradingWhenNonNumericalAttribute() {
+ void testNoDegradingWhenNonNumericalAttribute() {
Query query = new Query("?ranking.sorting=%2bstringAttribute%20-a2");
execute(query);
assertNull(query.getRanking().getMatchPhase().getAttribute());
}
@Test
- public void testNoDegradingWhenTurnedOff() {
+ void testNoDegradingWhenTurnedOff() {
Query query = new Query("?ranking.sorting=-a1%20-a2&sorting.degrading=false");
execute(query);
assertNull(query.getRanking().getMatchPhase().getAttribute());
}
@Test
- public void testAccessAllDegradingParametersInQuery() {
+ void testAccessAllDegradingParametersInQuery() {
Query query = new Query("?ranking.matchPhase.maxHits=555&ranking.matchPhase.attribute=foo&ranking.matchPhase.ascending=true");
execute(query);
@@ -118,7 +118,7 @@ public class SortingDegraderTestCase {
}
@Test
- public void testDegradingWithLargeMaxHits() {
+ void testDegradingWithLargeMaxHits() {
Query query = new Query("?ranking.sorting=%2ba1%20-a2");
query.properties().set(DefaultProperties.MAX_HITS, 13 * 1000);
query.properties().set(DefaultProperties.MAX_OFFSET, 8 * 1000);
@@ -129,7 +129,7 @@ public class SortingDegraderTestCase {
}
@Test
- public void testDegradingWithoutPaginationSupport() {
+ void testDegradingWithoutPaginationSupport() {
Query query = new Query("?ranking.sorting=%2ba1%20-a2&hits=7&offset=1");
query.properties().set(DefaultProperties.MAX_HITS, 13 * 1000);
query.properties().set(DefaultProperties.MAX_OFFSET, 8 * 1000);
diff --git a/container-search/src/test/java/com/yahoo/search/rendering/AsyncGroupPopulationTestCase.java b/container-search/src/test/java/com/yahoo/search/rendering/AsyncGroupPopulationTestCase.java
index 7db29568d5b..c038b3c67c9 100644
--- a/container-search/src/test/java/com/yahoo/search/rendering/AsyncGroupPopulationTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/rendering/AsyncGroupPopulationTestCase.java
@@ -13,7 +13,7 @@ import com.yahoo.search.result.HitGroup;
import com.yahoo.search.result.Relevance;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.text.Utf8;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -25,8 +25,8 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.function.BiConsumer;
-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 adding hits to a hit group during rendering.
@@ -98,7 +98,7 @@ public class AsyncGroupPopulationTestCase {
}
@Test
- public final void test() throws InterruptedException, ExecutionException,
+ final void test() throws InterruptedException, ExecutionException,
IOException {
String rawExpected = "{"
+ " \"root\": {"
diff --git a/container-search/src/test/java/com/yahoo/search/rendering/JsonRendererTestCase.java b/container-search/src/test/java/com/yahoo/search/rendering/JsonRendererTestCase.java
index 7ddc087feb7..9486eeb92de 100644
--- a/container-search/src/test/java/com/yahoo/search/rendering/JsonRendererTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/rendering/JsonRendererTestCase.java
@@ -56,13 +56,12 @@ import com.yahoo.tensor.serialization.TypedBinaryFormat;
import com.yahoo.text.Utf8;
import com.yahoo.yolean.Exceptions;
import com.yahoo.yolean.trace.TraceNode;
-import org.junit.After;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.Timeout;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -78,9 +77,9 @@ import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* Functional testing of {@link JsonRenderer}.
@@ -92,14 +91,11 @@ public class JsonRendererTestCase {
private static final ObjectMapper jsonMapper = new ObjectMapper();
- @Rule
- public Timeout globalTimeout = Timeout.seconds(300);
-
private static ThreadPoolExecutor executor;
private static JsonRenderer blueprint;
private JsonRenderer renderer;
- @BeforeClass
+ @BeforeAll
public static void createExecutorAndBlueprint() {
ThreadFactory threadFactory = ThreadFactoryFactory.getThreadFactory("test-rendering");
executor = new ThreadPoolExecutor(4, 4, 1L, TimeUnit.MINUTES, new LinkedBlockingQueue<>(), threadFactory);
@@ -107,14 +103,14 @@ public class JsonRendererTestCase {
blueprint = new JsonRenderer(executor);
}
- @Before
+ @BeforeEach
public void createClone() {
// Use the shared renderer as a prototype object, as specified in the API contract
renderer = (JsonRenderer) blueprint.clone();
renderer.init();
}
- @After
+ @AfterEach
public void deconstructClone() {
if (renderer != null) {
renderer.deconstruct();
@@ -122,7 +118,7 @@ public class JsonRendererTestCase {
}
}
- @AfterClass
+ @AfterAll
public static void deconstructBlueprintAndExecutor() throws InterruptedException {
blueprint.deconstruct();
blueprint = null;
@@ -134,7 +130,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testDocumentId() throws IOException, InterruptedException, ExecutionException {
+ @Timeout(300)
+ void testDocumentId() throws IOException, InterruptedException, ExecutionException {
String expected = "{"
+ " \"root\": {"
+ " \"children\": ["
@@ -163,30 +160,31 @@ public class JsonRendererTestCase {
}
@Test
- public void testTensorShortForm() throws ExecutionException, InterruptedException, IOException {
+ @Timeout(300)
+ void testTensorShortForm() throws ExecutionException, InterruptedException, IOException {
String expected = "{" +
"\"root\":{" +
- "\"id\":\"toplevel\"," +
- "\"relevance\":1.0," +
- "\"fields\":{" +
- "\"totalCount\":1" +
- "}," +
- "\"children\":[{" +
- "\"id\":\"tensors\"," +
- "\"relevance\":1.0," +
- "\"fields\":{" +
- "\"tensor_standard\":{\"type\":\"tensor(x{},y{})\",\"cells\":[{\"address\":{\"x\":\"a\",\"y\":\"0\"},\"value\":1.0},{\"address\":{\"x\":\"b\",\"y\":\"1\"},\"value\":2.0}]}," +
- "\"tensor_indexed\":{\"type\":\"tensor(x[2],y[3])\",\"values\":[[1.0,2.0,3.0],[4.0,5.0,6.0]]}," +
- "\"tensor_single_mapped\":{\"type\":\"tensor(x{})\",\"cells\":{\"a\":1.0,\"b\":2.0}}," +
- "\"tensor_mixed\":{\"type\":\"tensor(x{},y[2])\",\"blocks\":{\"a\":[1.0,2.0],\"b\":[3.0,4.0]}}," +
- "\"summaryfeatures\":{" +
- "\"tensor_standard\":{\"type\":\"tensor(x{},y{})\",\"cells\":[{\"address\":{\"x\":\"a\",\"y\":\"0\"},\"value\":1.0},{\"address\":{\"x\":\"b\",\"y\":\"1\"},\"value\":2.0}]}," +
- "\"tensor_indexed\":{\"type\":\"tensor(x[2],y[3])\",\"values\":[[1.0,2.0,3.0],[4.0,5.0,6.0]]}," +
- "\"tensor_single_mapped\":{\"type\":\"tensor(x{})\",\"cells\":{\"a\":1.0,\"b\":2.0}}," +
- "\"tensor_mixed\":{\"type\":\"tensor(x{},y[2])\",\"blocks\":{\"a\":[1.0,2.0],\"b\":[3.0,4.0]}}" +
- "}" +
- "}" +
- "}]" +
+ "\"id\":\"toplevel\"," +
+ "\"relevance\":1.0," +
+ "\"fields\":{" +
+ "\"totalCount\":1" +
+ "}," +
+ "\"children\":[{" +
+ "\"id\":\"tensors\"," +
+ "\"relevance\":1.0," +
+ "\"fields\":{" +
+ "\"tensor_standard\":{\"type\":\"tensor(x{},y{})\",\"cells\":[{\"address\":{\"x\":\"a\",\"y\":\"0\"},\"value\":1.0},{\"address\":{\"x\":\"b\",\"y\":\"1\"},\"value\":2.0}]}," +
+ "\"tensor_indexed\":{\"type\":\"tensor(x[2],y[3])\",\"values\":[[1.0,2.0,3.0],[4.0,5.0,6.0]]}," +
+ "\"tensor_single_mapped\":{\"type\":\"tensor(x{})\",\"cells\":{\"a\":1.0,\"b\":2.0}}," +
+ "\"tensor_mixed\":{\"type\":\"tensor(x{},y[2])\",\"blocks\":{\"a\":[1.0,2.0],\"b\":[3.0,4.0]}}," +
+ "\"summaryfeatures\":{" +
+ "\"tensor_standard\":{\"type\":\"tensor(x{},y{})\",\"cells\":[{\"address\":{\"x\":\"a\",\"y\":\"0\"},\"value\":1.0},{\"address\":{\"x\":\"b\",\"y\":\"1\"},\"value\":2.0}]}," +
+ "\"tensor_indexed\":{\"type\":\"tensor(x[2],y[3])\",\"values\":[[1.0,2.0,3.0],[4.0,5.0,6.0]]}," +
+ "\"tensor_single_mapped\":{\"type\":\"tensor(x{})\",\"cells\":{\"a\":1.0,\"b\":2.0}}," +
+ "\"tensor_mixed\":{\"type\":\"tensor(x{},y[2])\",\"blocks\":{\"a\":[1.0,2.0],\"b\":[3.0,4.0]}}" +
+ "}" +
+ "}" +
+ "}]" +
"}}\n";
Slime slime = new Slime();
@@ -222,12 +220,13 @@ public class JsonRendererTestCase {
}
catch (IllegalArgumentException e) {
assertEquals("Could not set 'presentation.format.tensors' to 'unknown': Value must be 'long' or 'short', not 'unknown'",
- Exceptions.toMessageString(e));
+ Exceptions.toMessageString(e));
}
}
@Test
- public void testDataTypes() throws IOException, InterruptedException, ExecutionException {
+ @Timeout(300)
+ void testDataTypes() throws IOException, InterruptedException, ExecutionException {
String expected = "{"
+ " \"root\": {"
+ " \"children\": ["
@@ -298,7 +297,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testTracing() throws IOException, InterruptedException, ExecutionException {
+ @Timeout(300)
+ void testTracing() throws IOException, InterruptedException, ExecutionException {
// which clearly shows a trace child is created once too often...
String expected = "{"
+ " \"root\": {"
@@ -353,7 +353,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testTracingOfSlime() throws IOException, InterruptedException, ExecutionException {
+ @Timeout(300)
+ void testTracingOfSlime() throws IOException, InterruptedException, ExecutionException {
// which clearly shows a trace child is created once too often...
String expected = "{"
+ " \"root\": {"
@@ -406,10 +407,10 @@ public class JsonRendererTestCase {
e2.search(subQuery);
Value.ArrayValue access = new Value.ArrayValue();
Slime slime = new Slime();
- slime.setObject().setString("colour","yellow");
+ slime.setObject().setString("colour", "yellow");
access.add(new SlimeAdapter(slime.get()));
slime = new Slime();
- slime.setObject().setString("colour","green");
+ slime.setObject().setString("colour", "green");
access.add(new SlimeAdapter(slime.get()));
subQuery.trace(access, 1);
q.trace("marker", 1);
@@ -418,7 +419,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testEmptyTracing() throws IOException, InterruptedException, ExecutionException {
+ @Timeout(300)
+ void testEmptyTracing() throws IOException, InterruptedException, ExecutionException {
String expected = "{"
+ " \"root\": {"
+ " \"fields\": {"
@@ -444,7 +446,8 @@ public class JsonRendererTestCase {
@SuppressWarnings({"unchecked"})
@Test
- public void testTracingWithEmptySubtree() throws IOException, InterruptedException, ExecutionException {
+ @Timeout(300)
+ void testTracingWithEmptySubtree() throws IOException, InterruptedException, ExecutionException {
String expected = "{"
+ " \"root\": {"
+ " \"fields\": {"
@@ -495,17 +498,18 @@ public class JsonRendererTestCase {
}
@Test
- public void trace_is_not_included_if_tracelevel_0() throws IOException, ExecutionException, InterruptedException {
+ @Timeout(300)
+ void trace_is_not_included_if_tracelevel_0() throws IOException, ExecutionException, InterruptedException {
String expected =
"{" +
- " \"root\": {" +
- " \"id\": \"toplevel\"," +
- " \"relevance\": 1.0," +
- " \"fields\": {" +
- " \"totalCount\": 0" +
- " }" +
- " }" +
- "}";
+ " \"root\": {" +
+ " \"id\": \"toplevel\"," +
+ " \"relevance\": 1.0," +
+ " \"fields\": {" +
+ " \"totalCount\": 0" +
+ " }" +
+ " }" +
+ "}";
Query q = new Query("/?query=a&tracelevel=0");
Execution execution = new Execution(Execution.Context.createContextStub());
Result r = new Result(q);
@@ -516,7 +520,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testTracingOfNodesWithBothChildrenAndData() throws IOException, InterruptedException, ExecutionException {
+ @Timeout(300)
+ void testTracingOfNodesWithBothChildrenAndData() throws IOException, InterruptedException, ExecutionException {
String expected = "{"
+ " \"root\": {"
+ " \"fields\": {"
@@ -561,7 +566,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testTracingOfNodesWithBothChildrenAndDataAndEmptySubnode() throws IOException, InterruptedException, ExecutionException {
+ @Timeout(300)
+ void testTracingOfNodesWithBothChildrenAndDataAndEmptySubnode() throws IOException, InterruptedException, ExecutionException {
String expected = "{"
+ " \"root\": {"
+ " \"fields\": {"
@@ -602,7 +608,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testTracingOfNestedNodesWithDataAndSubnodes() throws IOException, InterruptedException, ExecutionException {
+ @Timeout(300)
+ void testTracingOfNestedNodesWithDataAndSubnodes() throws IOException, InterruptedException, ExecutionException {
String expected = "{"
+ " \"root\": {"
+ " \"fields\": {"
@@ -650,7 +657,8 @@ public class JsonRendererTestCase {
}
@Test
- public void test() throws IOException, InterruptedException, ExecutionException {
+ @Timeout(300)
+ void test() throws IOException, InterruptedException, ExecutionException {
String expected = "{"
+ " \"root\": {"
+ " \"children\": ["
@@ -716,7 +724,7 @@ public class JsonRendererTestCase {
Query q = new Query("/?query=a&tracelevel=5");
Execution execution = new Execution(Execution.Context.createContextStub());
Result r = new Result(q);
- r.setCoverage(new Coverage(500, 500,1,1));
+ r.setCoverage(new Coverage(500, 500, 1, 1));
FastHit h = new FastHit("http://localhost/", .95);
h.setField("$a", "Hello, world.");
@@ -737,7 +745,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testCoverage() throws InterruptedException, ExecutionException, IOException {
+ @Timeout(300)
+ void testCoverage() throws InterruptedException, ExecutionException, IOException {
String expected = "{"
+ " \"root\": {"
+ " \"coverage\": {"
@@ -771,7 +780,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testMoreTypes() throws InterruptedException, ExecutionException, IOException {
+ @Timeout(300)
+ void testMoreTypes() throws InterruptedException, ExecutionException, IOException {
String expected = "{"
+ " \"root\": {"
+ " \"children\": ["
@@ -795,8 +805,8 @@ public class JsonRendererTestCase {
+ "}";
Result r = newEmptyResult();
Hit h = new Hit("moredatatypestuff");
- h.setField("byte", (byte)8);
- h.setField("short", (short)16);
+ h.setField("byte", (byte) 8);
+ h.setField("short", (short) 16);
h.setField("bigInteger", new BigInteger("340282366920938463463374607431768211455"));
h.setField("bigDecimal", new BigDecimal("340282366920938463463374607431768211456.5"));
h.setField("nanNumber", NanNumber.NaN);
@@ -807,7 +817,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testNullField() throws InterruptedException, ExecutionException, IOException {
+ @Timeout(300)
+ void testNullField() throws InterruptedException, ExecutionException, IOException {
String expected = "{"
+ " \"root\": {"
+ " \"children\": ["
@@ -836,7 +847,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testHitWithSource() throws IOException, InterruptedException, ExecutionException {
+ @Timeout(300)
+ void testHitWithSource() throws IOException, InterruptedException, ExecutionException {
String expected = "{"
+ " \"root\": {"
+ " \"children\": ["
@@ -863,7 +875,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testErrorWithStackTrace() throws InterruptedException, ExecutionException, IOException {
+ @Timeout(300)
+ void testErrorWithStackTrace() throws InterruptedException, ExecutionException, IOException {
String expected = "{"
+ " \"root\": {"
+ " \"errors\": ["
@@ -896,13 +909,15 @@ public class JsonRendererTestCase {
}
@Test
- public void testContentHeader() {
+ @Timeout(300)
+ void testContentHeader() {
assertEquals("utf-8", renderer.getEncoding());
assertEquals("application/json", renderer.getMimeType());
}
@Test
- public void testGrouping() throws InterruptedException, ExecutionException, IOException {
+ @Timeout(300)
+ void testGrouping() throws InterruptedException, ExecutionException, IOException {
String expected = "{"
+ " \"root\": {"
+ " \"children\": ["
@@ -988,7 +1003,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testGroupingWithBucket() throws InterruptedException, ExecutionException, IOException {
+ @Timeout(300)
+ void testGroupingWithBucket() throws InterruptedException, ExecutionException, IOException {
String expected = "{"
+ " \"root\": {"
+ " \"children\": ["
@@ -1051,7 +1067,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testJsonObjects() throws InterruptedException, ExecutionException, IOException {
+ @Timeout(300)
+ void testJsonObjects() throws InterruptedException, ExecutionException, IOException {
String expected = "{"
+ " \"root\": {"
+ " \"children\": ["
@@ -1097,7 +1114,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testFieldValueInHit() throws IOException, InterruptedException, ExecutionException {
+ @Timeout(300)
+ void testFieldValueInHit() throws IOException, InterruptedException, ExecutionException {
String expected = "{"
+ " \"root\": {"
+ " \"children\": ["
@@ -1132,7 +1150,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testHiddenFields() throws IOException, InterruptedException, ExecutionException {
+ @Timeout(300)
+ void testHiddenFields() throws IOException, InterruptedException, ExecutionException {
String expected = "{"
+ " \"root\": {"
+ " \"children\": ["
@@ -1157,7 +1176,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testDebugRendering() throws IOException, InterruptedException, ExecutionException {
+ @Timeout(300)
+ void testDebugRendering() throws IOException, InterruptedException, ExecutionException {
String expected = "{"
+ " \"root\": {"
+ " \"children\": ["
@@ -1188,7 +1208,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testTimingRendering() throws InterruptedException, ExecutionException, IOException {
+ @Timeout(300)
+ void testTimingRendering() throws InterruptedException, ExecutionException, IOException {
String expected = "{"
+ " \"root\": {"
+ " \"fields\": {"
@@ -1208,7 +1229,7 @@ public class JsonRendererTestCase {
new UselessSearcher("first"), new UselessSearcher("second"),
new UselessSearcher("third")));
ElapsedTimeTestCase.doInjectTimeSource(t, new CreativeTimeSource(
- new long[] { 1L, 2L, 3L, 4L, 5L, 6L, 7L }));
+ new long[]{1L, 2L, 3L, 4L, 5L, 6L, 7L}));
t.sampleSearch(0, true);
t.sampleSearch(1, true);
t.sampleSearch(2, true);
@@ -1223,7 +1244,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testJsonCallback() throws IOException, InterruptedException, ExecutionException {
+ @Timeout(300)
+ void testJsonCallback() throws IOException, InterruptedException, ExecutionException {
String expected = "{"
+ " \"root\": {"
+ " \"children\": ["
@@ -1244,7 +1266,7 @@ public class JsonRendererTestCase {
+ "}";
String jsonCallback = "some_function_name";
- Result r = newEmptyResult(new String[] {"query=a", "jsoncallback="+jsonCallback} );
+ Result r = newEmptyResult(new String[]{"query=a", "jsoncallback=" + jsonCallback});
Hit h = new Hit("jsonCallbackTest");
h.setField("documentid", new DocumentId("id:unittest:smoke::whee"));
r.hits().add(h);
@@ -1261,7 +1283,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testMapInField() throws IOException, InterruptedException, ExecutionException {
+ @Timeout(300)
+ void testMapInField() throws IOException, InterruptedException, ExecutionException {
String expected = "{"
+ " \"root\": {"
+ " \"children\": ["
@@ -1288,18 +1311,18 @@ public class JsonRendererTestCase {
Hit h = new Hit("MapInField");
Value.ArrayValue atop = new Value.ArrayValue();
atop.add(new Value.ObjectValue()
- .put("key", new Value.StringValue("foo"))
- .put("value", new Value.StringValue("string foo")))
- .add(new Value.ObjectValue()
- .put("key", new Value.StringValue("bar"))
- .put("value", new Value.ArrayValue()
- .add(new Value.StringValue("array bar elem 1"))
- .add(new Value.StringValue("array bar elem 2"))))
- .add(new Value.ObjectValue()
- .put("key", new Value.StringValue("baz"))
- .put("value", new Value.ObjectValue()
- .put("f1", new Value.StringValue("object baz field 1"))
- .put("f2", new Value.StringValue("object baz field 2"))));
+ .put("key", new Value.StringValue("foo"))
+ .put("value", new Value.StringValue("string foo")))
+ .add(new Value.ObjectValue()
+ .put("key", new Value.StringValue("bar"))
+ .put("value", new Value.ArrayValue()
+ .add(new Value.StringValue("array bar elem 1"))
+ .add(new Value.StringValue("array bar elem 2"))))
+ .add(new Value.ObjectValue()
+ .put("key", new Value.StringValue("baz"))
+ .put("value", new Value.ObjectValue()
+ .put("f1", new Value.StringValue("object baz field 1"))
+ .put("f2", new Value.StringValue("object baz field 2"))));
h.setField("structured", atop);
r.hits().add(h);
r.setTotalHitCount(1L);
@@ -1314,21 +1337,22 @@ public class JsonRendererTestCase {
}
@Test
- public void testMapDeepInFields() throws IOException, InterruptedException, ExecutionException {
+ @Timeout(300)
+ void testMapDeepInFields() throws IOException, InterruptedException, ExecutionException {
Result r = new Result(new Query("/?renderer.json.jsonMaps=true"));
var expected = dataFromSimplified(
"{root: { id:'toplevel', relevance:1.0, fields: { totalCount: 1 }," +
- " children: [ { id: 'myHitName', relevance: 1.0," +
- " fields: { " +
- " f1: [ 'v1', { mykey1: 'myvalue1', mykey2: 'myvalue2' } ]," +
- " f2: { i1: 'v2', i2: { mykey3: 'myvalue3' }, i3: 'v3' }," +
- " f3: { j1: 42, j2: 17.75, j3: [ 'v4', 'v5' ] }," +
- " f4: { mykey4: 'myvalue4', mykey5: 'myvalue5' }," +
- " f5: { '10001': 'myvalue6', '10002': 'myvalue7' }," +
- " f6: { i4: 'v6', i5: { '-17': 'myvalue8', '-42': 'myvalue9' } }" +
- " }" +
- " } ]" +
- "}}");
+ " children: [ { id: 'myHitName', relevance: 1.0," +
+ " fields: { " +
+ " f1: [ 'v1', { mykey1: 'myvalue1', mykey2: 'myvalue2' } ]," +
+ " f2: { i1: 'v2', i2: { mykey3: 'myvalue3' }, i3: 'v3' }," +
+ " f3: { j1: 42, j2: 17.75, j3: [ 'v4', 'v5' ] }," +
+ " f4: { mykey4: 'myvalue4', mykey5: 'myvalue5' }," +
+ " f5: { '10001': 'myvalue6', '10002': 'myvalue7' }," +
+ " f6: { i4: 'v6', i5: { '-17': 'myvalue8', '-42': 'myvalue9' } }" +
+ " }" +
+ " } ]" +
+ "}}");
Hit h = new Hit("myHitName");
h.setField("f1", dataFromSimplified("[ 'v1', [ { key: 'mykey1', value: 'myvalue1' }, { key: 'mykey2', value: 'myvalue2' } ] ]"));
h.setField("f2", dataFromSimplified("{ i1: 'v2', i2: [ { key: 'mykey3', value: 'myvalue3' } ], i3: 'v3' }"));
@@ -1349,17 +1373,17 @@ public class JsonRendererTestCase {
r = new Result(new Query("/?renderer.json.jsonMaps=false"));
expected = dataFromSimplified(
"{root:{id:'toplevel',relevance:1.0,fields:{totalCount:1}," +
- " children: [ { id: 'myHitName', relevance: 1.0," +
- " fields: { " +
- " f1: [ 'v1', [ { key: 'mykey1', value: 'myvalue1' }, { key: 'mykey2', value: 'myvalue2' } ] ]," +
- " f2: { i1: 'v2', i2: [ { key: 'mykey3', value: 'myvalue3' } ], i3: 'v3' }," +
- " f3: { j1: 42, j2: 17.75, j3: [ 'v4', 'v5' ] }," +
- " f4: { mykey4: 'myvalue4', mykey5: 'myvalue5' }," +
- " f5: [ { key: 10001, value: 'myvalue6' }, { key: 10002, value: 'myvalue7' } ]," +
- " f6: { i4: 'v6', i5: [ { key: -17, value: 'myvalue8' }, { key: -42, value: 'myvalue9' } ] }" +
- " }" +
- " } ]" +
- "}}");
+ " children: [ { id: 'myHitName', relevance: 1.0," +
+ " fields: { " +
+ " f1: [ 'v1', [ { key: 'mykey1', value: 'myvalue1' }, { key: 'mykey2', value: 'myvalue2' } ] ]," +
+ " f2: { i1: 'v2', i2: [ { key: 'mykey3', value: 'myvalue3' } ], i3: 'v3' }," +
+ " f3: { j1: 42, j2: 17.75, j3: [ 'v4', 'v5' ] }," +
+ " f4: { mykey4: 'myvalue4', mykey5: 'myvalue5' }," +
+ " f5: [ { key: 10001, value: 'myvalue6' }, { key: 10002, value: 'myvalue7' } ]," +
+ " f6: { i4: 'v6', i5: [ { key: -17, value: 'myvalue8' }, { key: -42, value: 'myvalue9' } ] }" +
+ " }" +
+ " } ]" +
+ "}}");
r.hits().add(h);
r.setTotalHitCount(1L);
summary = render(r);
@@ -1367,19 +1391,20 @@ public class JsonRendererTestCase {
}
@Test
- public void testWsetInFields() throws IOException, InterruptedException, ExecutionException {
+ @Timeout(300)
+ void testWsetInFields() throws IOException, InterruptedException, ExecutionException {
Result r = new Result(new Query("/?renderer.json.jsonWsets=true"));
var expected = dataFromSimplified(
"{root: { id:'toplevel', relevance:1.0, fields: { totalCount: 1 }," +
- " children: [ { id: 'myHitName', relevance: 1.0," +
- " fields: { " +
- " f1: [ 'v1', { mykey1: 10, mykey2: 20 } ]," +
- " f2: { i1: 'v2', i2: { mykey3: 30 }, i3: 'v3' }," +
- " f3: { j1: 42, j2: 17.75, j3: [ 'v4', 'v5' ] }," +
- " f4: { mykey4: 40, mykey5: 50 }" +
- " }" +
- " } ]" +
- "}}");
+ " children: [ { id: 'myHitName', relevance: 1.0," +
+ " fields: { " +
+ " f1: [ 'v1', { mykey1: 10, mykey2: 20 } ]," +
+ " f2: { i1: 'v2', i2: { mykey3: 30 }, i3: 'v3' }," +
+ " f3: { j1: 42, j2: 17.75, j3: [ 'v4', 'v5' ] }," +
+ " f4: { mykey4: 40, mykey5: 50 }" +
+ " }" +
+ " } ]" +
+ "}}");
Hit h = new Hit("myHitName");
h.setField("f1", dataFromSimplified("[ 'v1', [ { item: 'mykey1', weight: 10 }, { item: 'mykey2', weight: 20 } ] ]"));
h.setField("f2", dataFromSimplified("{ i1: 'v2', i2: [ { item: 'mykey3', weight: 30 } ], i3: 'v3' }"));
@@ -1393,15 +1418,15 @@ public class JsonRendererTestCase {
r = new Result(new Query("/?renderer.json.jsonWsets=false"));
expected = dataFromSimplified(
"{root:{id:'toplevel',relevance:1.0,fields:{totalCount:1}," +
- " children: [ { id: 'myHitName', relevance: 1.0," +
- " fields: { " +
- " f1: [ 'v1', [ { item: 'mykey1', weight: 10 }, { item: 'mykey2', weight: 20 } ] ]," +
- " f2: { i1: 'v2', i2: [ { item: 'mykey3', weight: 30 } ], i3: 'v3' }," +
- " f3: { j1: 42, j2: 17.75, j3: [ 'v4', 'v5' ] }," +
- " f4: [ { item: 'mykey4', weight: 40 }, { item: 'mykey5', weight: 50 } ]" +
- " }" +
- " } ]" +
- "}}");
+ " children: [ { id: 'myHitName', relevance: 1.0," +
+ " fields: { " +
+ " f1: [ 'v1', [ { item: 'mykey1', weight: 10 }, { item: 'mykey2', weight: 20 } ] ]," +
+ " f2: { i1: 'v2', i2: [ { item: 'mykey3', weight: 30 } ], i3: 'v3' }," +
+ " f3: { j1: 42, j2: 17.75, j3: [ 'v4', 'v5' ] }," +
+ " f4: [ { item: 'mykey4', weight: 40 }, { item: 'mykey5', weight: 50 } ]" +
+ " }" +
+ " } ]" +
+ "}}");
r.hits().add(h);
r.setTotalHitCount(1L);
summary = render(r);
@@ -1409,7 +1434,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testThatTheJsonValidatorCanCatchErrors() {
+ @Timeout(300)
+ void testThatTheJsonValidatorCanCatchErrors() {
String json = "{"
+ " \"root\": {"
+ " \"invalidvalue\": 1adsf,"
@@ -1422,7 +1448,8 @@ public class JsonRendererTestCase {
}
@Test
- public void testDynamicSummary() throws Exception {
+ @Timeout(300)
+ void testDynamicSummary() throws Exception {
String content = "\uFFF9Feeding\uFFFAfeed\uFFFB \u001F\uFFF9documents\uFFFAdocument\uFFFB\u001F into Vespa \uFFF9is\uFFFAbe\u001Eincrement of a set of \u001F\uFFF9documents\uFFFAdocument\uFFFB\u001F fed into Vespa \uFFF9is\u001Efloat in XML when \u001Fdocument\u001F attribute \uFFF9is\uFFFAbe\uFFFB int\u001E";
Result result = createResult("one", content, true);
@@ -1430,24 +1457,24 @@ public class JsonRendererTestCase {
String expected =
"{ " +
- " \"root\":{ " +
- " \"id\":\"toplevel\"," +
- " \"relevance\":1.0," +
- " \"fields\":{ " +
- " \"totalCount\":0" +
- " }," +
- " \"children\":[ " +
- " { " +
- " \"id\":\"http://abc.html/\"," +
- " \"relevance\":1.0," +
- " \"fields\":{ " +
- " \"sddocname\":\"one\"," +
- " \"dynteaser\":\"Feeding <hi>documents</hi> into Vespa is<sep />increment of a set of <hi>documents</hi> fed into Vespa <sep />float in XML when <hi>document</hi> attribute is int<sep />\"" +
- " }" +
- " }" +
- " ]" +
- " }" +
- "}";
+ " \"root\":{ " +
+ " \"id\":\"toplevel\"," +
+ " \"relevance\":1.0," +
+ " \"fields\":{ " +
+ " \"totalCount\":0" +
+ " }," +
+ " \"children\":[ " +
+ " { " +
+ " \"id\":\"http://abc.html/\"," +
+ " \"relevance\":1.0," +
+ " \"fields\":{ " +
+ " \"sddocname\":\"one\"," +
+ " \"dynteaser\":\"Feeding <hi>documents</hi> into Vespa is<sep />increment of a set of <hi>documents</hi> fed into Vespa <sep />float in XML when <hi>document</hi> attribute is int<sep />\"" +
+ " }" +
+ " }" +
+ " ]" +
+ " }" +
+ "}";
assertEqualJson(expected, summary);
}
diff --git a/container-search/src/test/java/com/yahoo/search/rendering/SyncDefaultRendererTestCase.java b/container-search/src/test/java/com/yahoo/search/rendering/SyncDefaultRendererTestCase.java
index 2166000cf7a..c473c11005d 100644
--- a/container-search/src/test/java/com/yahoo/search/rendering/SyncDefaultRendererTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/rendering/SyncDefaultRendererTestCase.java
@@ -14,16 +14,16 @@ import com.yahoo.search.statistics.ElapsedTimeTestCase.CreativeTimeSource;
import com.yahoo.search.statistics.ElapsedTimeTestCase.UselessSearcher;
import com.yahoo.search.statistics.TimeTracker;
import com.yahoo.text.Utf8;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
-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;
/**
* Check the legacy sync default renderer doesn't spontaneously combust.
@@ -34,28 +34,28 @@ public class SyncDefaultRendererTestCase {
SyncDefaultRenderer d;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
d = new SyncDefaultRenderer();
d.init();
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
}
@Test
- public final void testGetEncoding() {
+ final void testGetEncoding() {
assertEquals("utf-8", d.getEncoding());
}
@Test
- public final void testGetMimeType() {
+ final void testGetMimeType() {
assertEquals("text/xml", d.getMimeType());
}
@Test
- public void testRenderWriterResult() throws InterruptedException, ExecutionException {
+ void testRenderWriterResult() throws InterruptedException, ExecutionException {
Query q = new Query("/?query=a&tracelevel=5");
q.getPresentation().setTiming(true);
Result r = new Result(q);
@@ -65,7 +65,7 @@ public class SyncDefaultRendererTestCase {
new UselessSearcher("first"), new UselessSearcher("second"),
new UselessSearcher("third")));
ElapsedTimeTestCase.doInjectTimeSource(t, new CreativeTimeSource(
- new long[] { 1L, 2L, 3L, 4L, 5L, 6L, 7L }));
+ new long[]{1L, 2L, 3L, 4L, 5L, 6L, 7L}));
t.sampleSearch(0, true);
t.sampleSearch(1, true);
t.sampleSearch(2, true);
diff --git a/container-search/src/test/java/com/yahoo/search/rendering/XMLRendererTestCase.java b/container-search/src/test/java/com/yahoo/search/rendering/XMLRendererTestCase.java
index a8b38130333..50234e4022c 100644
--- a/container-search/src/test/java/com/yahoo/search/rendering/XMLRendererTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/rendering/XMLRendererTestCase.java
@@ -24,13 +24,13 @@ import com.yahoo.search.statistics.ElapsedTimeTestCase;
import com.yahoo.search.statistics.ElapsedTimeTestCase.CreativeTimeSource;
import com.yahoo.search.statistics.TimeTracker;
import com.yahoo.text.Utf8;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.util.concurrent.CompletableFuture;
-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 the XML renderer
@@ -41,21 +41,21 @@ import static org.junit.Assert.assertTrue;
public class XMLRendererTestCase {
@Test
- public void testGetEncoding() {
+ void testGetEncoding() {
XmlRenderer renderer = new XmlRenderer();
renderer.init();
assertEquals("utf-8", renderer.getEncoding());
}
@Test
- public void testGetMimeType() {
+ void testGetMimeType() {
XmlRenderer renderer = new XmlRenderer();
renderer.init();
assertEquals("text/xml", renderer.getMimeType());
}
@Test
- public void testXmlRendering() throws Exception {
+ void testXmlRendering() throws Exception {
Query q = new Query("/?query=a");
Result result = new Result(q);
@@ -82,31 +82,31 @@ public class XMLRendererTestCase {
String expected =
"<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" +
- "<result total-hit-count=\"0\" coverage-docs=\"500\" coverage-nodes=\"1\" coverage-full=\"false\" coverage=\"0\" results-full=\"0\" results=\"1\">\n" +
- " <error code=\"18\">Internal server error.</error>\n" +
- " <errordetails>\n" +
- " <error error=\"Internal server error.\" code=\"18\">message</error>\n" +
- " </errordetails>\n" +
- " <group relevancy=\"1.0\">\n" +
- " <hit type=\"summary\" relevancy=\"0.9\">\n" +
- " <field name=\"relevancy\">0.9</field>\n" +
- " <field name=\"c\">d</field>\n" +
- " </hit>\n" +
- " </group>\n" +
- " <hit type=\"grouphit\" relevancy=\"1.0\">\n" +
- " <id>type grouphit</id>\n" +
- " </hit>\n" +
- " <hit type=\"summary\" relevancy=\"0.95\">\n" +
- " <field name=\"relevancy\">0.95</field>\n" +
- " <field name=\"b\">foo</field>\n" +
- " </hit>\n" +
- "</result>\n";
+ "<result total-hit-count=\"0\" coverage-docs=\"500\" coverage-nodes=\"1\" coverage-full=\"false\" coverage=\"0\" results-full=\"0\" results=\"1\">\n" +
+ " <error code=\"18\">Internal server error.</error>\n" +
+ " <errordetails>\n" +
+ " <error error=\"Internal server error.\" code=\"18\">message</error>\n" +
+ " </errordetails>\n" +
+ " <group relevancy=\"1.0\">\n" +
+ " <hit type=\"summary\" relevancy=\"0.9\">\n" +
+ " <field name=\"relevancy\">0.9</field>\n" +
+ " <field name=\"c\">d</field>\n" +
+ " </hit>\n" +
+ " </group>\n" +
+ " <hit type=\"grouphit\" relevancy=\"1.0\">\n" +
+ " <id>type grouphit</id>\n" +
+ " </hit>\n" +
+ " <hit type=\"summary\" relevancy=\"0.95\">\n" +
+ " <field name=\"relevancy\">0.95</field>\n" +
+ " <field name=\"b\">foo</field>\n" +
+ " </hit>\n" +
+ "</result>\n";
assertEquals(expected, summary);
}
@Test
- public void testXmlRenderingOfDynamicSummary() throws Exception {
+ void testXmlRenderingOfDynamicSummary() throws Exception {
String content = "\uFFF9Feeding\uFFFAfeed\uFFFB \u001F\uFFF9documents\uFFFAdocument\uFFFB\u001F into Vespa \uFFF9is\uFFFAbe\u001Eincrement of a set of \u001F\uFFF9documents\uFFFAdocument\uFFFB\u001F fed into Vespa \uFFF9is\u001Efloat in XML when \u001Fdocument\u001F attribute \uFFF9is\uFFFAbe\uFFFB int\u001E";
Result result = createResult("one", content, true);
@@ -114,18 +114,18 @@ public class XMLRendererTestCase {
String expected =
"<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n" +
- "<result total-hit-count=\"0\">\n" +
- " <hit relevancy=\"1.0\">\n" +
- " <field name=\"relevancy\">1.0</field>\n" +
- " <field name=\"sddocname\">one</field>\n" +
- " <field name=\"dynteaser\">Feeding <hi>documents</hi> into Vespa is<sep />increment of a set of <hi>documents</hi> fed into Vespa <sep />float in XML when <hi>document</hi> attribute is int<sep /></field>\n" +
- " </hit>\n" +
- "</result>\n";
+ "<result total-hit-count=\"0\">\n" +
+ " <hit relevancy=\"1.0\">\n" +
+ " <field name=\"relevancy\">1.0</field>\n" +
+ " <field name=\"sddocname\">one</field>\n" +
+ " <field name=\"dynteaser\">Feeding <hi>documents</hi> into Vespa is<sep />increment of a set of <hi>documents</hi> fed into Vespa <sep />float in XML when <hi>document</hi> attribute is int<sep /></field>\n" +
+ " </hit>\n" +
+ "</result>\n";
assertEquals(expected, summary);
}
@Test
- public void testXmlRenderingWithTimeTracking() throws Exception {
+ void testXmlRenderingWithTimeTracking() throws Exception {
Query q = new Query("/?query=a&tracelevel=5");
q.getPresentation().setTiming(true);
@@ -133,9 +133,9 @@ public class XMLRendererTestCase {
result.setCoverage(new Coverage(500, 1));
TimeTracker t = new TimeTracker(new Chain<Searcher>(new NoopSearcher("first"),
- new NoopSearcher("second"),
- new NoopSearcher("third")));
- ElapsedTimeTestCase.doInjectTimeSource(t, new CreativeTimeSource(new long[] { 1L, 2L, 3L, 4L, 5L, 6L, 7L }));
+ new NoopSearcher("second"),
+ new NoopSearcher("third")));
+ ElapsedTimeTestCase.doInjectTimeSource(t, new CreativeTimeSource(new long[]{1L, 2L, 3L, 4L, 5L, 6L, 7L}));
t.sampleSearch(0, true);
t.sampleSearch(1, true);
t.sampleSearch(2, true);
@@ -148,7 +148,7 @@ public class XMLRendererTestCase {
String summary = render(result);
assertEquals("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<result total-hit-count=\"0\"",
- summary.substring(0, 67));
+ summary.substring(0, 67));
assertTrue(summary.contains("querytime="));
assertTrue(summary.contains("summaryfetchtime="));
assertTrue(summary.contains("searchtime="));
diff --git a/container-search/src/test/java/com/yahoo/search/result/DefaultErrorHitTestCase.java b/container-search/src/test/java/com/yahoo/search/result/DefaultErrorHitTestCase.java
index 5c9af0c756e..42095e263dd 100644
--- a/container-search/src/test/java/com/yahoo/search/result/DefaultErrorHitTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/result/DefaultErrorHitTestCase.java
@@ -1,13 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.result;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
import java.util.Iterator;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
/**
* @author Steinar Knutsen
@@ -17,13 +16,13 @@ public class DefaultErrorHitTestCase {
private static final String SOURCE = "nalle";
DefaultErrorHit de;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
de = new DefaultErrorHit(SOURCE, ErrorMessage.createUnspecifiedError("DefaultErrorHitTestCase"));
}
@Test
- public void testSetSourceTakeTwo() {
+ void testSetSourceTakeTwo() {
assertEquals(SOURCE, de.getSource());
de.setSource(null);
assertNull(de.getSource());
@@ -36,19 +35,19 @@ public class DefaultErrorHitTestCase {
}
@Test
- public void testToString() {
+ void testToString() {
assertEquals("Error: Source 'nalle': 5: Unspecified error: DefaultErrorHitTestCase", de.toString());
}
@Test
- public void testSetMainError() {
+ void testSetMainError() {
ErrorMessage e = ErrorMessage.createBackendCommunicationError("abc");
assertNull(e.getSource());
de.addError(e);
assertEquals(SOURCE, e.getSource());
boolean caught = false;
try {
- new DefaultErrorHit(SOURCE, (ErrorMessage)null);
+ new DefaultErrorHit(SOURCE, (ErrorMessage) null);
} catch (NullPointerException ex) {
caught = true;
}
@@ -64,7 +63,7 @@ public class DefaultErrorHitTestCase {
}
@Test
- public void testAddError() {
+ void testAddError() {
ErrorMessage e = ErrorMessage.createBackendCommunicationError("ljkhlkjh");
assertNull(e.getSource());
de.addError(e);
@@ -79,7 +78,7 @@ public class DefaultErrorHitTestCase {
}
@Test
- public void testAddErrors() {
+ void testAddErrors() {
DefaultErrorHit other = new DefaultErrorHit("abc", ErrorMessage.createBadRequest("sdasd"));
de.addErrors(other);
int i = 0;
@@ -98,7 +97,7 @@ public class DefaultErrorHitTestCase {
}
@Test
- public void testHasOnlyErrorCode() {
+ void testHasOnlyErrorCode() {
assertTrue(de.hasOnlyErrorCode(com.yahoo.container.protect.Error.UNSPECIFIED.code));
assertFalse(de.hasOnlyErrorCode(com.yahoo.container.protect.Error.BACKEND_COMMUNICATION_ERROR.code));
diff --git a/container-search/src/test/java/com/yahoo/search/result/FeatureDataTestCase.java b/container-search/src/test/java/com/yahoo/search/result/FeatureDataTestCase.java
index f7b9817437f..5d423eceb98 100644
--- a/container-search/src/test/java/com/yahoo/search/result/FeatureDataTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/result/FeatureDataTestCase.java
@@ -6,12 +6,12 @@ import com.yahoo.slime.Cursor;
import com.yahoo.slime.Slime;
import com.yahoo.tensor.Tensor;
import com.yahoo.tensor.serialization.TypedBinaryFormat;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.stream.Collectors;
-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 bratseth
@@ -21,7 +21,7 @@ public class FeatureDataTestCase {
private static final double delta = 0.00000001;
@Test
- public void testFeatureData() {
+ void testFeatureData() {
Cursor features = new Slime().setObject();
features.setDouble("scalar1", 1.5);
features.setDouble("scalar2", 2.5);
@@ -32,11 +32,11 @@ public class FeatureDataTestCase {
FeatureData featureData = new FeatureData(new SlimeAdapter(features));
assertEquals("scalar1,scalar2,tensor1,tensor2",
- featureData.featureNames().stream().sorted().collect(Collectors.joining(",")));
+ featureData.featureNames().stream().sorted().collect(Collectors.joining(",")));
assertNull(featureData.getDouble("nosuch1"));
assertEquals(1.5, featureData.getDouble("scalar1"), delta);
assertEquals(2.5, featureData.getDouble("scalar2"), delta);
- assertEquals("Cached lookup", 2.5, featureData.getDouble("scalar2"), delta);
+ assertEquals(2.5, featureData.getDouble("scalar2"), delta, "Cached lookup");
assertNull(featureData.getDouble("nosuch2"));
assertNull(featureData.getDouble("nosuch2"));
@@ -45,17 +45,17 @@ public class FeatureDataTestCase {
assertEquals(Tensor.from(2.5), featureData.getTensor("scalar2"));
assertEquals(tensor1, featureData.getTensor("tensor1"));
assertEquals(tensor2, featureData.getTensor("tensor2"));
- assertEquals("Cached lookup", tensor2, featureData.getTensor("tensor2"));
+ assertEquals(tensor2, featureData.getTensor("tensor2"), "Cached lookup");
assertNull(featureData.getTensor("nosuch2"));
assertNull(featureData.getTensor("nosuch2"));
String expectedJson =
"{" +
- "\"scalar1\":1.5," +
- "\"scalar2\":2.5," +
- "\"tensor1\":{\"type\":\"tensor(x[3])\",\"cells\":[{\"address\":{\"x\":\"0\"},\"value\":1.5},{\"address\":{\"x\":\"1\"},\"value\":2.0},{\"address\":{\"x\":\"2\"},\"value\":2.5}]}," +
- "\"tensor2\":{\"type\":\"tensor()\",\"cells\":[{\"address\":{},\"value\":0.5}]}" +
- "}";
+ "\"scalar1\":1.5," +
+ "\"scalar2\":2.5," +
+ "\"tensor1\":{\"type\":\"tensor(x[3])\",\"cells\":[{\"address\":{\"x\":\"0\"},\"value\":1.5},{\"address\":{\"x\":\"1\"},\"value\":2.0},{\"address\":{\"x\":\"2\"},\"value\":2.5}]}," +
+ "\"tensor2\":{\"type\":\"tensor()\",\"cells\":[{\"address\":{},\"value\":0.5}]}" +
+ "}";
assertEquals(expectedJson, featureData.toJson());
}
diff --git a/container-search/src/test/java/com/yahoo/search/result/NanNumberTestCase.java b/container-search/src/test/java/com/yahoo/search/result/NanNumberTestCase.java
index c6e5c87efb2..0790b6754fe 100644
--- a/container-search/src/test/java/com/yahoo/search/result/NanNumberTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/result/NanNumberTestCase.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.search.result;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Integrity test for representation of undefined numeric field values.
@@ -14,27 +15,27 @@ public class NanNumberTestCase {
@Test
- public final void testIntValue() {
+ final void testIntValue() {
assertEquals(0, NanNumber.NaN.intValue());
}
@Test
- public final void testLongValue() {
+ final void testLongValue() {
assertEquals(0L, NanNumber.NaN.longValue());
}
@Test
- public final void testFloatValue() {
+ final void testFloatValue() {
assertTrue(Float.isNaN(NanNumber.NaN.floatValue()));
}
@Test
- public final void testDoubleValue() {
+ final void testDoubleValue() {
assertTrue(Double.isNaN(NanNumber.NaN.doubleValue()));
}
@Test
- public final void testToString() {
+ final void testToString() {
assertEquals("", NanNumber.NaN.toString());
}
diff --git a/container-search/src/test/java/com/yahoo/search/result/PositionsDataTestCase.java b/container-search/src/test/java/com/yahoo/search/result/PositionsDataTestCase.java
index 96039beafa5..a112cb41a64 100644
--- a/container-search/src/test/java/com/yahoo/search/result/PositionsDataTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/result/PositionsDataTestCase.java
@@ -3,9 +3,9 @@ package com.yahoo.search.result;
import com.yahoo.data.access.simple.Value;
-import static org.junit.Assert.*;
+import org.junit.jupiter.api.Test;
-import org.junit.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Arne Juul
@@ -13,7 +13,7 @@ import org.junit.Test;
public class PositionsDataTestCase {
@Test
- public void testRenderingOfSinglePosition() {
+ void testRenderingOfSinglePosition() {
Value.ObjectValue pos = createPosition(-122057174, 37374821, "N37.374821;W122.057174");
PositionsData pd = new PositionsData(pos.inspect());
@@ -23,7 +23,7 @@ public class PositionsDataTestCase {
}
@Test
- public void testRenderingOfMultiplePositions() {
+ void testRenderingOfMultiplePositions() {
Value.ArrayValue arr = new Value.ArrayValue();
arr.add(createPosition(-122057174, 37374821, "N37.374821;W122.057174"));
arr.add(createPosition(3, -7, "S0.000007;E0.000003"));
@@ -31,9 +31,9 @@ public class PositionsDataTestCase {
PositionsData pd = new PositionsData(arr.inspect());
assertXml("<position x=\"-122057174\" y=\"37374821\" latlong=\"N37.374821;W122.057174\" />" +
- "<position x=\"3\" y=\"-7\" latlong=\"S0.000007;E0.000003\" />", pd);
+ "<position x=\"3\" y=\"-7\" latlong=\"S0.000007;E0.000003\" />", pd);
assertJson("[{\"x\":-122057174,\"y\":37374821,\"latlong\":\"N37.374821;W122.057174\"}," +
- "{\"x\":3,\"y\":-7,\"latlong\":\"S0.000007;E0.000003\"}]", pd);
+ "{\"x\":3,\"y\":-7,\"latlong\":\"S0.000007;E0.000003\"}]", pd);
}
private Value.ObjectValue createPosition(long x, long y, String latlong) {
diff --git a/container-search/src/test/java/com/yahoo/search/result/test/CoverageTestCase.java b/container-search/src/test/java/com/yahoo/search/result/test/CoverageTestCase.java
index d95a8068570..c0b0a90b682 100644
--- a/container-search/src/test/java/com/yahoo/search/result/test/CoverageTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/result/test/CoverageTestCase.java
@@ -4,10 +4,10 @@ package com.yahoo.search.result.test;
import com.yahoo.search.Query;
import com.yahoo.search.Result;
import com.yahoo.search.result.Coverage;
-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 Steinar Knutsen
@@ -15,14 +15,14 @@ import static org.junit.Assert.assertNull;
public class CoverageTestCase {
@Test
- public void testZeroCoverage() {
+ void testZeroCoverage() {
Coverage c = new Coverage(0L, 0, 0, 0);
assertEquals(0, c.getResultPercentage());
assertEquals(0, c.getResultSets());
}
@Test
- public void testActiveCoverage() {
+ void testActiveCoverage() {
Coverage c = new Coverage(6, 5);
assertEquals(5, c.getActive());
assertEquals(6, c.getDocs());
@@ -34,7 +34,7 @@ public class CoverageTestCase {
}
@Test
- public void testDefaultCoverage() {
+ void testDefaultCoverage() {
boolean create = true;
Result r1 = new Result(new Query());
@@ -46,18 +46,18 @@ public class CoverageTestCase {
}
@Test
- public void testDefaultSearchScenario() {
+ void testDefaultSearchScenario() {
boolean create = true;
Result federationSearcherResult = new Result(new Query());
Result singleSourceResult = new Result(new Query());
federationSearcherResult.mergeWith(singleSourceResult);
- assertNull(federationSearcherResult.getCoverage( !create));
+ assertNull(federationSearcherResult.getCoverage(!create));
assertEquals(0, federationSearcherResult.getCoverage(create).getResultSets());
}
@Test
- public void testRequestingCoverageSearchScenario() {
+ void testRequestingCoverageSearchScenario() {
boolean create = true;
Result federationSearcherResult = new Result(new Query());
@@ -68,7 +68,7 @@ public class CoverageTestCase {
}
@Test
- public void testCoverageConversion() {
+ void testCoverageConversion() {
Coverage c = new Coverage(6, 10);
c.setDegradedReason(7);
com.yahoo.container.logging.Coverage lc = c.toLoggingCoverage();
diff --git a/container-search/src/test/java/com/yahoo/search/result/test/DeepHitIteratorTestCase.java b/container-search/src/test/java/com/yahoo/search/result/test/DeepHitIteratorTestCase.java
index 1147cd67460..21a10bf8325 100644
--- a/container-search/src/test/java/com/yahoo/search/result/test/DeepHitIteratorTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/result/test/DeepHitIteratorTestCase.java
@@ -7,12 +7,9 @@ import java.util.NoSuchElementException;
import com.yahoo.search.result.DeepHitIterator;
import com.yahoo.search.result.Hit;
import com.yahoo.search.result.HitGroup;
-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.*;
/**
* Ensure that the {@link DeepHitIterator} works as intended.
@@ -22,7 +19,7 @@ import static org.junit.Assert.fail;
public class DeepHitIteratorTestCase {
@Test
- public void testEmpty() {
+ void testEmpty() {
HitGroup hits = new HitGroup();
Iterator<Hit> it = hits.deepIterator();
assertFalse(it.hasNext());
@@ -35,7 +32,7 @@ public class DeepHitIteratorTestCase {
}
@Test
- public void testRemove() {
+ void testRemove() {
HitGroup hits = new HitGroup();
hits.add(new Hit("foo"));
hits.add(new Hit("bar"));
@@ -62,7 +59,7 @@ public class DeepHitIteratorTestCase {
}
@Test
- public void testShallow() {
+ void testShallow() {
HitGroup hits = new HitGroup();
hits.add(new Hit("foo"));
hits.add(new Hit("bar"));
@@ -79,7 +76,7 @@ public class DeepHitIteratorTestCase {
}
@Test
- public void testDeep() {
+ void testDeep() {
HitGroup grandParent = new HitGroup();
grandParent.add(new Hit("a"));
HitGroup parent = new HitGroup();
@@ -114,7 +111,7 @@ public class DeepHitIteratorTestCase {
}
@Test
- public void testFirstHitIsGroup() {
+ void testFirstHitIsGroup() {
HitGroup root = new HitGroup();
HitGroup group = new HitGroup();
group.add(new Hit("foo"));
@@ -130,7 +127,7 @@ public class DeepHitIteratorTestCase {
}
@Test
- public void testSecondHitIsGroup() {
+ void testSecondHitIsGroup() {
HitGroup root = new HitGroup();
root.add(new Hit("foo"));
HitGroup group = new HitGroup();
@@ -146,7 +143,7 @@ public class DeepHitIteratorTestCase {
}
@Test
- public void testOrder() {
+ void testOrder() {
HitGroup root = new HitGroup();
MyHitGroup group = new MyHitGroup();
group.add(new Hit("foo"));
diff --git a/container-search/src/test/java/com/yahoo/search/result/test/FillingTestCase.java b/container-search/src/test/java/com/yahoo/search/result/test/FillingTestCase.java
index ea5c11cb055..8c833ca76f3 100644
--- a/container-search/src/test/java/com/yahoo/search/result/test/FillingTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/result/test/FillingTestCase.java
@@ -3,13 +3,11 @@ package com.yahoo.search.result.test;
import com.yahoo.search.result.Hit;
import com.yahoo.search.result.HitGroup;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
-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 bratseth
@@ -17,16 +15,16 @@ import static org.junit.Assert.assertTrue;
public class FillingTestCase {
@Test
- public void testFillingAPIConsistency() {
- HitGroup group=new HitGroup();
+ void testFillingAPIConsistency() {
+ HitGroup group = new HitGroup();
group.add(new Hit("hit:1"));
group.add(new Hit("hit:2"));
assertTrue(group.isFilled("summary"));
}
@Test
- public void testFillingAPIConsistencyTwoPhase() {
- HitGroup group=new HitGroup();
+ void testFillingAPIConsistencyTwoPhase() {
+ HitGroup group = new HitGroup();
group.add(createNonFilled("hit:1"));
group.add(createNonFilled("hit:2"));
assertFalse(group.isFilled("summary"));
@@ -36,8 +34,8 @@ public class FillingTestCase {
}
@Test
- public void testFillingAPIConsistencyThreePhase() {
- HitGroup group=new HitGroup();
+ void testFillingAPIConsistencyThreePhase() {
+ HitGroup group = new HitGroup();
group.add(createNonFilled("hit:1"));
group.add(createNonFilled("hit:2"));
assertFalse(group.isFilled("summary"));
@@ -54,7 +52,7 @@ public class FillingTestCase {
}
@Test
- public void testPartiallyFilledWith2Hits() {
+ void testPartiallyFilledWith2Hits() {
Hit hit1 = new Hit("id1");
Hit hit2 = new Hit("id2");
@@ -69,7 +67,7 @@ public class FillingTestCase {
}
@Test
- public void testPartiallyFilledDiverse() {
+ void testPartiallyFilledDiverse() {
Hit hit1 = new Hit("id1");
Hit hit2 = new Hit("id2");
Hit hit3 = new Hit("id3");
diff --git a/container-search/src/test/java/com/yahoo/search/result/test/HitGroupTestCase.java b/container-search/src/test/java/com/yahoo/search/result/test/HitGroupTestCase.java
index 8196cf4ac74..cc4e6193103 100644
--- a/container-search/src/test/java/com/yahoo/search/result/test/HitGroupTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/result/test/HitGroupTestCase.java
@@ -7,17 +7,13 @@ import com.yahoo.search.result.ErrorHit;
import com.yahoo.search.result.ErrorMessage;
import com.yahoo.search.result.Hit;
import com.yahoo.search.result.HitGroup;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
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.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -25,21 +21,21 @@ import static org.junit.Assert.assertTrue;
public class HitGroupTestCase {
@Test
- public void testErrorsConsistencyUsingErrorOperations() {
+ void testErrorsConsistencyUsingErrorOperations() {
HitGroup hits = new HitGroup();
Query query = new Query();
query.errors().add(ErrorMessage.createIllegalQuery("test1"));
query.errors().add(ErrorMessage.createTimeout("test2"));
hits.setQuery(query);
-
+
hits.addError(ErrorMessage.createForbidden("test3"));
hits.addError(ErrorMessage.createUnspecifiedError("test4"));
-
+
assertEquals(4, hits.getErrorHit().errors().size());
assertEquals(0, query.errors().size());
assertEquals(Optional.of(hits.getErrorHit()), errorHitIn(hits.asList()));
-
+
DefaultErrorHit removedErrors = hits.removeErrorHit();
assertNotNull(removedErrors);
assertEquals(4, removedErrors.errors().size());
@@ -50,7 +46,7 @@ public class HitGroupTestCase {
}
@Test
- public void testErrorsConsistencyUsingHitOperations() {
+ void testErrorsConsistencyUsingHitOperations() {
HitGroup hits = new HitGroup();
Query query = new Query();
@@ -66,7 +62,7 @@ public class HitGroupTestCase {
assertEquals(0, query.errors().size());
assertEquals(Optional.of(hits.getErrorHit()), errorHitIn(hits.asList()));
- DefaultErrorHit removedErrors = (DefaultErrorHit)hits.remove(errors.getId());
+ DefaultErrorHit removedErrors = (DefaultErrorHit) hits.remove(errors.getId());
assertNotNull(removedErrors);
assertEquals(4, removedErrors.errors().size());
assertNull(hits.get(removedErrors.getId().toString()));
@@ -76,39 +72,39 @@ public class HitGroupTestCase {
}
@Test
- public void testRecursiveGet() {
+ void testRecursiveGet() {
// Level 1
- HitGroup g1=new HitGroup();
+ HitGroup g1 = new HitGroup();
g1.add(new Hit("1"));
// Level 2
- HitGroup g1_1=new HitGroup();
+ HitGroup g1_1 = new HitGroup();
g1_1.add(new Hit("1.1"));
g1.add(g1_1);
- HitGroup g1_2=new HitGroup();
+ HitGroup g1_2 = new HitGroup();
g1_2.add(new Hit("1.2"));
g1.add(g1_2);
// Level 3
- HitGroup g1_1_1=new HitGroup();
+ HitGroup g1_1_1 = new HitGroup();
g1_1_1.add(new Hit("1.1.1"));
g1_1.add(g1_1_1);
- HitGroup g1_1_2=new HitGroup();
+ HitGroup g1_1_2 = new HitGroup();
g1_1_2.add(new Hit("1.1.2"));
g1_1.add(g1_1_2);
- HitGroup g1_2_1=new HitGroup();
+ HitGroup g1_2_1 = new HitGroup();
g1_2_1.add(new Hit("1.2.1"));
g1_2.add(g1_2_1);
- HitGroup g1_2_2=new HitGroup();
+ HitGroup g1_2_2 = new HitGroup();
g1_2_2.add(new Hit("1.2.2"));
g1_2.add(g1_2_2);
// Level 4
- HitGroup g1_1_1_1=new HitGroup();
+ HitGroup g1_1_1_1 = new HitGroup();
g1_1_1_1.add(new Hit("1.1.1.1"));
g1_1_1.add(g1_1_1_1);
@@ -121,49 +117,49 @@ public class HitGroupTestCase {
assertNotNull(g1.get("1.2.2"));
assertNotNull(g1.get("1.1.1.1"));
- assertNotNull(g1.get("1",-1));
- assertNotNull(g1.get("1.1",-1));
- assertNotNull(g1.get("1.2",-1));
- assertNotNull(g1.get("1.1.1",-1));
- assertNotNull(g1.get("1.1.2",-1));
- assertNotNull(g1.get("1.2.1",-1));
- assertNotNull(g1.get("1.2.2",-1));
- assertNotNull(g1.get("1.1.1.1",-1));
-
- assertNotNull(g1.get("1",0));
- assertNull(g1.get("1.1",0));
- assertNull(g1.get("1.2",0));
- assertNull(g1.get("1.1.1",0));
- assertNull(g1.get("1.1.2",0));
- assertNull(g1.get("1.2.1",0));
- assertNull(g1.get("1.2.2",0));
- assertNull(g1.get("1.1.1.1",0));
-
- assertNotNull(g1.get("1",1));
- assertNotNull(g1.get("1.1",1));
- assertNotNull(g1.get("1.2",1));
- assertNull(g1.get("1.1.1",1));
- assertNull(g1.get("1.1.2",1));
- assertNull(g1.get("1.2.1",1));
- assertNull(g1.get("1.2.2",1));
- assertNull(g1.get("1.1.1.1",1));
-
- assertNotNull(g1.get("1",2));
- assertNotNull(g1.get("1.1",2));
- assertNotNull(g1.get("1.2",2));
- assertNotNull(g1.get("1.1.1",2));
- assertNotNull(g1.get("1.1.2",2));
- assertNotNull(g1.get("1.2.1",2));
- assertNotNull(g1.get("1.2.2",2));
- assertNull(g1.get("1.1.1.1",2));
-
- assertNotNull(g1.get("1.1.1.1",3));
-
- assertNull(g1.get("3",2));
+ assertNotNull(g1.get("1", -1));
+ assertNotNull(g1.get("1.1", -1));
+ assertNotNull(g1.get("1.2", -1));
+ assertNotNull(g1.get("1.1.1", -1));
+ assertNotNull(g1.get("1.1.2", -1));
+ assertNotNull(g1.get("1.2.1", -1));
+ assertNotNull(g1.get("1.2.2", -1));
+ assertNotNull(g1.get("1.1.1.1", -1));
+
+ assertNotNull(g1.get("1", 0));
+ assertNull(g1.get("1.1", 0));
+ assertNull(g1.get("1.2", 0));
+ assertNull(g1.get("1.1.1", 0));
+ assertNull(g1.get("1.1.2", 0));
+ assertNull(g1.get("1.2.1", 0));
+ assertNull(g1.get("1.2.2", 0));
+ assertNull(g1.get("1.1.1.1", 0));
+
+ assertNotNull(g1.get("1", 1));
+ assertNotNull(g1.get("1.1", 1));
+ assertNotNull(g1.get("1.2", 1));
+ assertNull(g1.get("1.1.1", 1));
+ assertNull(g1.get("1.1.2", 1));
+ assertNull(g1.get("1.2.1", 1));
+ assertNull(g1.get("1.2.2", 1));
+ assertNull(g1.get("1.1.1.1", 1));
+
+ assertNotNull(g1.get("1", 2));
+ assertNotNull(g1.get("1.1", 2));
+ assertNotNull(g1.get("1.2", 2));
+ assertNotNull(g1.get("1.1.1", 2));
+ assertNotNull(g1.get("1.1.2", 2));
+ assertNotNull(g1.get("1.2.1", 2));
+ assertNotNull(g1.get("1.2.2", 2));
+ assertNull(g1.get("1.1.1.1", 2));
+
+ assertNotNull(g1.get("1.1.1.1", 3));
+
+ assertNull(g1.get("3", 2));
}
@Test
- public void testThatHitGroupIsUnFillable() {
+ void testThatHitGroupIsUnFillable() {
HitGroup hg = new HitGroup("test");
{
Hit hit = new Hit("http://nalle.balle/1.html", 832);
@@ -185,7 +181,7 @@ public class HitGroupTestCase {
}
@Test
- public void testThatHitGroupIsFillable() {
+ void testThatHitGroupIsFillable() {
HitGroup hg = new HitGroup("test");
{
Hit hit = new Hit("http://nalle.balle/1.html", 832);
@@ -209,7 +205,7 @@ public class HitGroupTestCase {
}
@Test
- public void testThatHitGroupIsFillableAfterFillableChangeunderTheHood() {
+ void testThatHitGroupIsFillableAfterFillableChangeunderTheHood() {
HitGroup hg = new HitGroup("test");
{
Hit hit = new Hit("http://nalle.balle/1.html", 832);
diff --git a/container-search/src/test/java/com/yahoo/search/schema/SchemaInfoTest.java b/container-search/src/test/java/com/yahoo/search/schema/SchemaInfoTest.java
index d2cd2c4bb33..40d6f19c275 100644
--- a/container-search/src/test/java/com/yahoo/search/schema/SchemaInfoTest.java
+++ b/container-search/src/test/java/com/yahoo/search/schema/SchemaInfoTest.java
@@ -2,9 +2,9 @@
package com.yahoo.search.schema;
import com.yahoo.tensor.TensorType;
-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 bratseth
@@ -12,38 +12,38 @@ import static org.junit.Assert.assertEquals;
public class SchemaInfoTest {
@Test
- public void testSchemaInfoConfiguration() {
+ void testSchemaInfoConfiguration() {
assertEquals(SchemaInfoTester.createSchemaInfoFromConfig(), SchemaInfoTester.createSchemaInfo());
}
@Test
- public void testInputResolution() {
+ void testInputResolution() {
var tester = new SchemaInfoTester();
tester.assertInput(TensorType.fromSpec("tensor(a{},b{})"),
- "", "", "commonProfile", "query(myTensor1)");
+ "", "", "commonProfile", "query(myTensor1)");
tester.assertInput(TensorType.fromSpec("tensor(a{},b{})"),
- "ab", "", "commonProfile", "query(myTensor1)");
+ "ab", "", "commonProfile", "query(myTensor1)");
tester.assertInput(TensorType.fromSpec("tensor(a{},b{})"),
- "a", "", "commonProfile", "query(myTensor1)");
+ "a", "", "commonProfile", "query(myTensor1)");
tester.assertInput(TensorType.fromSpec("tensor(a{},b{})"),
- "b", "", "commonProfile", "query(myTensor1)");
+ "b", "", "commonProfile", "query(myTensor1)");
tester.assertInputConflict(TensorType.fromSpec("tensor(a{},b{})"),
- "", "", "inconsistent", "query(myTensor1)");
+ "", "", "inconsistent", "query(myTensor1)");
tester.assertInputConflict(TensorType.fromSpec("tensor(a{},b{})"),
- "ab", "", "inconsistent", "query(myTensor1)");
+ "ab", "", "inconsistent", "query(myTensor1)");
tester.assertInput(TensorType.fromSpec("tensor(a{},b{})"),
- "ab", "a", "inconsistent", "query(myTensor1)");
+ "ab", "a", "inconsistent", "query(myTensor1)");
tester.assertInput(TensorType.fromSpec("tensor(x[10])"),
- "ab", "b", "inconsistent", "query(myTensor1)");
+ "ab", "b", "inconsistent", "query(myTensor1)");
tester.assertInput(TensorType.fromSpec("tensor(a{},b{})"),
- "a", "", "inconsistent", "query(myTensor1)");
+ "a", "", "inconsistent", "query(myTensor1)");
tester.assertInput(TensorType.fromSpec("tensor(x[10])"),
- "b", "", "inconsistent", "query(myTensor1)");
+ "b", "", "inconsistent", "query(myTensor1)");
tester.assertInput(null,
- "a", "", "bOnly", "query(myTensor1)");
+ "a", "", "bOnly", "query(myTensor1)");
tester.assertInput(TensorType.fromSpec("tensor(a{},b{})"),
- "ab", "", "bOnly", "query(myTensor1)");
+ "ab", "", "bOnly", "query(myTensor1)");
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/schema/SchemaInfoTester.java b/container-search/src/test/java/com/yahoo/search/schema/SchemaInfoTester.java
index 45bf5af5258..4e7dc27e73c 100644
--- a/container-search/src/test/java/com/yahoo/search/schema/SchemaInfoTester.java
+++ b/container-search/src/test/java/com/yahoo/search/schema/SchemaInfoTester.java
@@ -15,7 +15,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 bratseth
diff --git a/container-search/src/test/java/com/yahoo/search/searchchain/AsyncExecutionOfOneChainTestCase.java b/container-search/src/test/java/com/yahoo/search/searchchain/AsyncExecutionOfOneChainTestCase.java
index f0be6a25f92..298bcc82d99 100644
--- a/container-search/src/test/java/com/yahoo/search/searchchain/AsyncExecutionOfOneChainTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/searchchain/AsyncExecutionOfOneChainTestCase.java
@@ -7,7 +7,7 @@ import com.yahoo.search.Result;
import com.yahoo.search.Searcher;
import com.yahoo.search.result.Hit;
import com.yahoo.search.result.HitGroup;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Iterator;
@@ -17,7 +17,7 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bratseth
@@ -28,16 +28,16 @@ public class AsyncExecutionOfOneChainTestCase {
/** Tests having a result with some slow source data which should pass directly to rendering */
@Test
- public void testParallelExecutionOfOneChain() {
+ void testParallelExecutionOfOneChain() {
ExecutorService executor = Executors.newFixedThreadPool(16);
// Setup
- Chain<Searcher> mainChain=new Chain<>(new ParallelExecutor(executor),new ResultProcessor(),new RegularProvider());
+ Chain<Searcher> mainChain = new Chain<>(new ParallelExecutor(executor), new ResultProcessor(), new RegularProvider());
// Execute
- Result result=new Execution(mainChain, Execution.Context.createContextStub()).search(new Query());
+ Result result = new Execution(mainChain, Execution.Context.createContextStub()).search(new Query());
// Verify
- assertEquals("Received 2 hits from 3 threads",3*2,result.hits().size());
+ assertEquals(3 * 2, result.hits().size(), "Received 2 hits from 3 threads");
assertEquals(1.0, result.hits().get("thread-0:hit-0").getRelevance().getScore(), delta);
assertEquals(1.0, result.hits().get("thread-1:hit-0").getRelevance().getScore(), delta);
assertEquals(1.0, result.hits().get("thread-2:hit-0").getRelevance().getScore(), delta);
diff --git a/container-search/src/test/java/com/yahoo/search/searchchain/AsyncExecutionTestCase.java b/container-search/src/test/java/com/yahoo/search/searchchain/AsyncExecutionTestCase.java
index 8f23c7eef83..0e4d1350a03 100644
--- a/container-search/src/test/java/com/yahoo/search/searchchain/AsyncExecutionTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/searchchain/AsyncExecutionTestCase.java
@@ -7,17 +7,14 @@ import com.yahoo.search.Query;
import com.yahoo.search.Result;
import com.yahoo.search.Searcher;
import com.yahoo.search.result.Hit;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
-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.*;
/**
* Test for aynchrounous execution
@@ -56,10 +53,10 @@ public class AsyncExecutionTestCase {
// This should take ~50+ ms
@Test
- public void testAsync() {
+ void testAsync() {
List<Searcher> searchList = new ArrayList<>();
- searchList.add(new WaitingSearcher("one",60000));
- searchList.add(new WaitingSearcher("two",0));
+ searchList.add(new WaitingSearcher("one", 60000));
+ searchList.add(new WaitingSearcher("two", 0));
Chain<Searcher> searchChain = new Chain<>(new ComponentId("chain"), searchList);
AsyncExecution asyncExecution = new AsyncExecution(searchChain, Execution.Context.createContextStub());
@@ -70,23 +67,23 @@ public class AsyncExecutionTestCase {
}
@Test
- public void testWaitForAll() {
+ void testWaitForAll() {
Chain<Searcher> slowChain = new Chain<>(
new ComponentId("slow"),
- Arrays.asList(new Searcher[]{new WaitingSearcher("slow",30000)}
+ Arrays.asList(new Searcher[]{new WaitingSearcher("slow", 30000)}
)
);
Chain<Searcher> fastChain = new Chain<>(
new ComponentId("fast"),
Arrays.asList(new Searcher[]{new SimpleSearcher()})
- );
+ );
FutureResult slowFuture = new AsyncExecution(slowChain, Execution.Context.createContextStub()).search(new Query("?hits=0"));
FutureResult fastFuture = new AsyncExecution(fastChain, Execution.Context.createContextStub()).search(new Query("?hits=0"));
fastFuture.get();
- FutureResult [] reslist = new FutureResult[]{slowFuture,fastFuture};
- List<Result> results = AsyncExecution.waitForAll(Arrays.asList(reslist),0);
+ FutureResult [] reslist = new FutureResult[]{slowFuture, fastFuture};
+ List<Result> results = AsyncExecution.waitForAll(Arrays.asList(reslist), 0);
//assertTrue(slowFuture.isCancelled());
assertTrue(fastFuture.isDone() && !fastFuture.isCancelled());
@@ -96,27 +93,27 @@ public class AsyncExecutionTestCase {
}
@Test
- public void testSync() {
- Query query=new Query("?query=test");
- Searcher searcher=new ResultProducingSearcher();
- Result result=new Execution(searcher, Execution.Context.createContextStub()).search(query);
+ void testSync() {
+ Query query = new Query("?query=test");
+ Searcher searcher = new ResultProducingSearcher();
+ Result result = new Execution(searcher, Execution.Context.createContextStub()).search(query);
- assertEquals(1,result.hits().size());
- assertEquals("hello",result.hits().get(0).getField("test"));
+ assertEquals(1, result.hits().size());
+ assertEquals("hello", result.hits().get(0).getField("test"));
}
@Test
- public void testSyncThroughSync() {
- Query query=new Query("?query=test");
- Searcher searcher=new ResultProducingSearcher();
- Result result=new Execution(new Execution(searcher, Execution.Context.createContextStub())).search(query);
+ void testSyncThroughSync() {
+ Query query = new Query("?query=test");
+ Searcher searcher = new ResultProducingSearcher();
+ Result result = new Execution(new Execution(searcher, Execution.Context.createContextStub())).search(query);
- assertEquals(1,result.hits().size());
- assertEquals("hello",result.hits().get(0).getField("test"));
+ assertEquals(1, result.hits().size());
+ assertEquals("hello", result.hits().get(0).getField("test"));
}
@Test
- public void testAsyncThroughSync() {
+ void testAsyncThroughSync() {
Query query = new Query("?query=test");
Searcher searcher = new ResultProducingSearcher();
FutureResult futureResult = new AsyncExecution(new Execution(searcher, Execution.Context.createContextStub())).search(query);
@@ -144,7 +141,7 @@ public class AsyncExecutionTestCase {
}
@Test
- public void testAsyncExecutionTimeout() {
+ void testAsyncExecutionTimeout() {
Chain<Searcher> chain = new Chain<>(new Searcher() {
@Override
public Result search(Query query, Execution execution) {
diff --git a/container-search/src/test/java/com/yahoo/search/searchchain/VespaAsyncSearcherTest.java b/container-search/src/test/java/com/yahoo/search/searchchain/VespaAsyncSearcherTest.java
index 341e55df777..e25a946c18b 100644
--- a/container-search/src/test/java/com/yahoo/search/searchchain/VespaAsyncSearcherTest.java
+++ b/container-search/src/test/java/com/yahoo/search/searchchain/VespaAsyncSearcherTest.java
@@ -5,16 +5,16 @@ import com.yahoo.component.chain.Chain;
import com.yahoo.search.Query;
import com.yahoo.search.Result;
import com.yahoo.search.Searcher;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Tests async execution of search chains.
@@ -26,12 +26,12 @@ public class VespaAsyncSearcherTest {
private ExecutorService executor;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
executor = Executors.newFixedThreadPool(16);
}
- @After
+ @AfterEach
public void tearDown() {
assertEquals(0, executor.shutdownNow().size());
}
@@ -69,7 +69,7 @@ public class VespaAsyncSearcherTest {
}
@Test
- public void testAsyncExecution() {
+ void testAsyncExecution() {
Chain<Searcher> chain = new Chain<>(new FirstSearcher(), new SecondSearcher());
Execution execution = new Execution(chain, Execution.Context.createContextStub());
Query query = new Query();
diff --git a/container-search/src/test/java/com/yahoo/search/searchchain/config/test/DependencyConfigTestCase.java b/container-search/src/test/java/com/yahoo/search/searchchain/config/test/DependencyConfigTestCase.java
index 553a9233bf1..614d481cf77 100644
--- a/container-search/src/test/java/com/yahoo/search/searchchain/config/test/DependencyConfigTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/searchchain/config/test/DependencyConfigTestCase.java
@@ -6,6 +6,8 @@ import java.io.IOException;
import java.util.Arrays;
import com.yahoo.component.chain.dependencies.After;
+
+import static org.junit.jupiter.api.Assertions.assertTrue;
import com.yahoo.component.chain.dependencies.Before;
import com.yahoo.component.chain.dependencies.Dependencies;
import com.yahoo.component.chain.dependencies.Provides;
@@ -17,11 +19,9 @@ import com.yahoo.search.handler.SearchHandler;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.searchchain.SearchChainRegistry;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
-
-import static org.junit.Assert.assertTrue;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
/**
* @author Tony Vaagenes
@@ -34,14 +34,14 @@ public class DependencyConfigTestCase {
public static final String root = "src/test/java/com/yahoo/search/searchchain/config/test/dependencyConfig";
- @BeforeClass
+ @BeforeAll
public static void createComponentsConfig() throws IOException {
SearchChainConfigurerTestCase.
createComponentsConfig(root + "/chains.cfg", root + "/handlers.cfg", root + "/components.cfg");
setUp();
}
- @AfterClass
+ @AfterAll
public static void removeComponentsConfig() {
new File(root + "/components.cfg").delete();
tearDown();
@@ -69,7 +69,7 @@ public class DependencyConfigTestCase {
}
@Test
- public void test() {
+ void test() {
Dependencies dependencies = registry.getSearcherRegistry().getComponent(Searcher1.class.getName()).getDependencies();
assertTrue(dependencies.provides().containsAll(Arrays.asList("P", "P1", "P2", Searcher1.class.getSimpleName())));
diff --git a/container-search/src/test/java/com/yahoo/search/searchchain/config/test/SearchChainConfigurerTestCase.java b/container-search/src/test/java/com/yahoo/search/searchchain/config/test/SearchChainConfigurerTestCase.java
index 781370d9e25..e851d221116 100644
--- a/container-search/src/test/java/com/yahoo/search/searchchain/config/test/SearchChainConfigurerTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/searchchain/config/test/SearchChainConfigurerTestCase.java
@@ -14,9 +14,9 @@ import com.yahoo.search.searchchain.ExecutionFactory;
import com.yahoo.search.searchchain.SearchChain;
import com.yahoo.search.searchchain.SearchChainRegistry;
import com.yahoo.search.searchchain.SearcherRegistry;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
import java.io.BufferedReader;
import java.io.File;
@@ -36,13 +36,7 @@ import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bratseth
@@ -65,12 +59,12 @@ public class SearchChainConfigurerTestCase {
}
}
- @BeforeClass
+ @BeforeAll
public static void createDefaultComponentsConfigs() throws IOException {
createComponentsConfig(testDir + "chains.cfg", testDir + "handlers.cfg", testDir + "components.cfg");
}
- @AfterClass
+ @AfterAll
public static void removeDefaultComponentsConfigs() {
new File(testDir + "components.cfg").delete();
}
@@ -81,7 +75,7 @@ public class SearchChainConfigurerTestCase {
}
@Test
- public synchronized void testConfiguration() {
+ synchronized void testConfiguration() {
HandlersConfigurerTestWrapper configurer = new HandlersConfigurerTestWrapper("dir:" + testDir);
SearchChain simple = getSearchChainRegistryFrom(configurer).getComponent("simple");
@@ -130,7 +124,7 @@ public class SearchChainConfigurerTestCase {
public static final class DeclaredTestSearcher extends TestSearcher {}
@Test
- public void testConfigurableSearcher() {
+ void testConfigurableSearcher() {
HandlersConfigurerTestWrapper configurer = new HandlersConfigurerTestWrapper("dir:" + testDir);
SearchChain configurable = getSearchChainRegistryFrom(configurer).getComponent("configurable");
@@ -138,9 +132,9 @@ public class SearchChainConfigurerTestCase {
Searcher s = configurable.searchers().get(0);
assertTrue(s instanceof ConfigurableSearcher);
- ConfigurableSearcher searcher = (ConfigurableSearcher)s;
- assertEquals("Value from int.cfg file", 7, searcher.intConfig.intVal());
- assertEquals("Value from string.cfg file", "com.yahoo.search.searchchain.config.test", searcher.stringConfig.stringVal());
+ ConfigurableSearcher searcher = (ConfigurableSearcher) s;
+ assertEquals(7, searcher.intConfig.intVal(), "Value from int.cfg file");
+ assertEquals("com.yahoo.search.searchchain.config.test", searcher.stringConfig.stringVal(), "Value from string.cfg file");
configurer.shutdown();
}
@@ -149,7 +143,7 @@ public class SearchChainConfigurerTestCase {
* that does not contain any bootstrap configs.
*/
@Test
- public void testSearcherConfigUpdate() throws IOException {
+ void testSearcherConfigUpdate() throws IOException {
File cfgDir = getCfgDir();
copyFile(testDir + "handlers.cfg", cfgDir + "/handlers.cfg");
copyFile(testDir + "qr-search.cfg", cfgDir + "/qr-search.cfg");
@@ -167,11 +161,11 @@ public class SearchChainConfigurerTestCase {
SearcherRegistry searchers = getSearchChainRegistryFrom(configurer).getSearcherRegistry();
assertEquals(3, searchers.getComponentCount());
- IntSearcher intSearcher = (IntSearcher)searchers.getComponent(IntSearcher.class.getName());
+ IntSearcher intSearcher = (IntSearcher) searchers.getComponent(IntSearcher.class.getName());
assertEquals(16, intSearcher.intConfig.intVal());
- StringSearcher stringSearcher = (StringSearcher)searchers.getComponent(StringSearcher.class.getName());
+ StringSearcher stringSearcher = (StringSearcher) searchers.getComponent(StringSearcher.class.getName());
DeclaredTestSearcher noConfigSearcher =
- (DeclaredTestSearcher)searchers.getComponent(DeclaredTestSearcher.class.getName());
+ (DeclaredTestSearcher) searchers.getComponent(DeclaredTestSearcher.class.getName());
// Update int config for IntSearcher,
printFile(new File(cfgDir + "/int.cfg"), "intVal 17\n");
@@ -183,7 +177,7 @@ public class SearchChainConfigurerTestCase {
assertEquals(3, searchers.getComponentCount());
// Searcher with updated config is re-instantiated.
- IntSearcher intSearcher2 = (IntSearcher)searchers.getComponent(IntSearcher.class.getName());
+ IntSearcher intSearcher2 = (IntSearcher) searchers.getComponent(IntSearcher.class.getName());
assertNotSame(intSearcher, intSearcher2);
assertEquals(17, intSearcher2.intConfig.intVal());
@@ -203,7 +197,7 @@ public class SearchChainConfigurerTestCase {
* and that a searcher that has been removed from the configuration is not in the new registry.
*/
@Test
- public void testChainsConfigUpdate() throws IOException {
+ void testChainsConfigUpdate() throws IOException {
File cfgDir = getCfgDir();
copyFile(testDir + "handlers.cfg", cfgDir + "/handlers.cfg");
copyFile(testDir + "qr-search.cfg", cfgDir + "/qr-search.cfg");
@@ -225,7 +219,7 @@ public class SearchChainConfigurerTestCase {
assertNull(searchers.getComponent(ConfigurableSearcher.class.getName()));
assertNull(searchers.getComponent(DeclaredTestSearcher.class.getName()));
- IntSearcher intSearcher = (IntSearcher)searchers.getComponent(IntSearcher.class.getName());
+ IntSearcher intSearcher = (IntSearcher) searchers.getComponent(IntSearcher.class.getName());
// Update chains config
copyFile(testDir + "chainsConfigUpdate_2.cfg", cfgDir + "/chains.cfg");
diff --git a/container-search/src/test/java/com/yahoo/search/searchchain/test/ExecutionTestCase.java b/container-search/src/test/java/com/yahoo/search/searchchain/test/ExecutionTestCase.java
index 129437a5429..bc535e4e214 100644
--- a/container-search/src/test/java/com/yahoo/search/searchchain/test/ExecutionTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/searchchain/test/ExecutionTestCase.java
@@ -17,14 +17,9 @@ import com.yahoo.search.Result;
import com.yahoo.search.Searcher;
import com.yahoo.search.result.Hit;
import com.yahoo.search.searchchain.Execution;
-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.Assert.assertNotSame;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* Tests basic search chain execution functionality
@@ -34,31 +29,31 @@ import static org.junit.Assert.assertTrue;
public class ExecutionTestCase {
@Test
- public void testLinearExecutions() {
+ void testLinearExecutions() {
// Make a chain
- List<Searcher> searchers1=new ArrayList<>();
+ List<Searcher> searchers1 = new ArrayList<>();
searchers1.add(new TestSearcher("searcher1"));
searchers1.add(new TestSearcher("searcher2"));
searchers1.add(new TestSearcher("searcher3"));
searchers1.add(new TestSearcher("searcher4"));
- Chain<Searcher> chain1=new Chain<>(new ComponentId("chain1"), searchers1);
+ Chain<Searcher> chain1 = new Chain<>(new ComponentId("chain1"), searchers1);
// Make another chain containing two of the same searcher instances and two new
- List<Searcher> searchers2=new ArrayList<>(searchers1);
- searchers2.set(1,new TestSearcher("searcher5"));
- searchers2.set(3,new TestSearcher("searcher6"));
- Chain<Searcher> chain2=new Chain<>(new ComponentId("chain2"), searchers2);
+ List<Searcher> searchers2 = new ArrayList<>(searchers1);
+ searchers2.set(1, new TestSearcher("searcher5"));
+ searchers2.set(3, new TestSearcher("searcher6"));
+ Chain<Searcher> chain2 = new Chain<>(new ComponentId("chain2"), searchers2);
// Execute both
- Query query=new Query("test");
- Result result1=new Execution(chain1, Execution.Context.createContextStub()).search(query);
- Result result2=new Execution(chain2, Execution.Context.createContextStub()).search(query);
+ Query query = new Query("test");
+ Result result1 = new Execution(chain1, Execution.Context.createContextStub()).search(query);
+ Result result2 = new Execution(chain2, Execution.Context.createContextStub()).search(query);
// Verify results
- assertEquals(4,result1.getConcreteHitCount());
+ assertEquals(4, result1.getConcreteHitCount());
assertNotNull(result1.hits().get("searcher1-1"));
assertNotNull(result1.hits().get("searcher2-1"));
assertNotNull(result1.hits().get("searcher3-1"));
assertNotNull(result1.hits().get("searcher4-1"));
- assertEquals(4,result2.getConcreteHitCount());
+ assertEquals(4, result2.getConcreteHitCount());
assertNotNull(result2.hits().get("searcher1-2"));
assertNotNull(result2.hits().get("searcher5-1"));
assertNotNull(result2.hits().get("searcher3-2"));
@@ -66,20 +61,20 @@ public class ExecutionTestCase {
}
@Test
- public void testNestedExecution() {
+ void testNestedExecution() {
// Make a chain
- List<Searcher> searchers1=new ArrayList<>();
+ List<Searcher> searchers1 = new ArrayList<>();
searchers1.add(new FillableTestSearcher("searcher1"));
searchers1.add(new WorkflowSearcher());
searchers1.add(new TestSearcher("searcher2"));
searchers1.add(new FillingSearcher());
searchers1.add(new FillableTestSearcherAtTheEnd("searcher3"));
- Chain<Searcher> chain1=new Chain<>(new ComponentId("chain1"), searchers1);
+ Chain<Searcher> chain1 = new Chain<>(new ComponentId("chain1"), searchers1);
// Execute it
- Query query=new Query("test");
- Result result1=new Execution(chain1, Execution.Context.createContextStub()).search(query);
+ Query query = new Query("test");
+ Result result1 = new Execution(chain1, Execution.Context.createContextStub()).search(query);
// Verify results
- assertEquals(7,result1.getConcreteHitCount());
+ assertEquals(7, result1.getConcreteHitCount());
assertNotNull(result1.hits().get("searcher1-1"));
assertNotNull(result1.hits().get("searcher2-1"));
assertNotNull(result1.hits().get("searcher3-1"));
@@ -90,7 +85,7 @@ public class ExecutionTestCase {
}
@Test
- public void testContextCacheSingleLengthSearchChain() {
+ void testContextCacheSingleLengthSearchChain() {
IndexFacts[] contextsBefore = new IndexFacts[1];
IndexFacts[] contextsAfter = new IndexFacts[1];
List<Searcher> l = new ArrayList<>(1);
@@ -103,7 +98,7 @@ public class ExecutionTestCase {
}
@Test
- public void testContextCache() {
+ void testContextCache() {
IndexFacts[] contextsBefore = new IndexFacts[5];
IndexFacts[] contextsAfter = new IndexFacts[5];
List<Searcher> l = new ArrayList<>(5);
@@ -129,7 +124,7 @@ public class ExecutionTestCase {
}
@Test
- public void testContextCacheMoreSearchers() {
+ void testContextCacheMoreSearchers() {
IndexFacts[] contextsBefore = new IndexFacts[7];
IndexFacts[] contextsAfter = new IndexFacts[7];
List<Searcher> l = new ArrayList<>(7);
@@ -161,7 +156,7 @@ public class ExecutionTestCase {
}
@Test
- public void testBasicFill() {
+ void testBasicFill() {
Chain<Searcher> chain = new Chain<Searcher>(new FillableResultSearcher());
Execution execution = new Execution(chain, Execution.Context.createContextStub());
diff --git a/container-search/src/test/java/com/yahoo/search/searchchain/test/FutureDataTestCase.java b/container-search/src/test/java/com/yahoo/search/searchchain/test/FutureDataTestCase.java
index 15517270cb9..c78c0d75477 100644
--- a/container-search/src/test/java/com/yahoo/search/searchchain/test/FutureDataTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/searchchain/test/FutureDataTestCase.java
@@ -14,16 +14,15 @@ import com.yahoo.search.result.HitGroup;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.searchchain.SearchChainRegistry;
import com.yahoo.search.searchchain.model.federation.FederationOptions;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
-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.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Tests using the async capabilities of the Processing parent framework of searchers.
@@ -33,16 +32,16 @@ import static org.junit.Assert.assertTrue;
public class FutureDataTestCase {
@Test
- public void testAsyncFederation() throws InterruptedException, ExecutionException {
+ void testAsyncFederation() throws InterruptedException, ExecutionException {
// Setup environment
AsyncProviderSearcher asyncProviderSearcher = new AsyncProviderSearcher();
Searcher syncProviderSearcher = new SyncProviderSearcher();
Chain<Searcher> asyncSource = new Chain<>(new ComponentId("async"), asyncProviderSearcher);
Chain<Searcher> syncSource = new Chain<>(new ComponentId("sync"), syncProviderSearcher);
- SearchChainResolver searchChainResolver=
+ SearchChainResolver searchChainResolver =
new SearchChainResolver.Builder().addSearchChain(new ComponentId("sync"), new FederationOptions().setUseByDefault(true)).
- addSearchChain(new ComponentId("async"), new FederationOptions().setUseByDefault(true)).
- build();
+ addSearchChain(new ComponentId("async"), new FederationOptions().setUseByDefault(true)).
+ build();
Chain<Searcher> main = new Chain<>(new FederationSearcher(new ComponentId("federator"), searchChainResolver));
SearchChainRegistry searchChainRegistry = new SearchChainRegistry();
searchChainRegistry.register(main);
@@ -54,32 +53,32 @@ public class FutureDataTestCase {
Result result = new Execution(main, Execution.Context.createContextStub(searchChainRegistry)).search(query);
assertNotNull(result);
- HitGroup syncGroup = (HitGroup)result.hits().get("source:sync");
+ HitGroup syncGroup = (HitGroup) result.hits().get("source:sync");
assertNotNull(syncGroup);
- HitGroup asyncGroup = (HitGroup)result.hits().get("source:async");
+ HitGroup asyncGroup = (HitGroup) result.hits().get("source:async");
assertNotNull(asyncGroup);
- assertEquals("Got all sync data", 3, syncGroup.size());
+ assertEquals(3, syncGroup.size(), "Got all sync data");
assertEquals("sync:0", syncGroup.get(0).getId().toString());
assertEquals("sync:1", syncGroup.get(1).getId().toString());
assertEquals("sync:2", syncGroup.get(2).getId().toString());
- assertTrue(asyncGroup.incoming()==asyncProviderSearcher.incomingData);
- assertEquals("Got no async data yet", 0, asyncGroup.size());
+ assertEquals(asyncGroup.incoming(), asyncProviderSearcher.incomingData);
+ assertEquals(0, asyncGroup.size(), "Got no async data yet");
asyncProviderSearcher.simulateOneHitIOComplete(new Hit("async:0"));
- assertEquals("Got no async data yet, as we haven't completed the incoming buffer and there is no data listener", 0, asyncGroup.size());
+ assertEquals(0, asyncGroup.size(), "Got no async data yet, as we haven't completed the incoming buffer and there is no data listener");
asyncProviderSearcher.simulateOneHitIOComplete(new Hit("async:1"));
asyncProviderSearcher.simulateAllHitsIOComplete();
- assertEquals("Got no async data yet, as we haven't pulled it", 0, asyncGroup.size());
+ assertEquals(0, asyncGroup.size(), "Got no async data yet, as we haven't pulled it");
asyncGroup.completeFuture().get();
- assertEquals("Completed, so we have the data", 2, asyncGroup.size());
+ assertEquals(2, asyncGroup.size(), "Completed, so we have the data");
assertEquals("async:0", asyncGroup.get(0).getId().toString());
assertEquals("async:1", asyncGroup.get(1).getId().toString());
}
@Test
- public void testFutureData() throws InterruptedException, ExecutionException, TimeoutException {
+ void testFutureData() throws InterruptedException, ExecutionException, TimeoutException {
// Set up
AsyncProviderSearcher futureDataSource = new AsyncProviderSearcher();
Chain<Searcher> chain = new Chain<>(Collections.<Searcher>singletonList(futureDataSource));
@@ -89,16 +88,14 @@ public class FutureDataTestCase {
Result result = new Execution(chain, Execution.Context.createContextStub()).search(query);
// Verify the result prior to completion of delayed data
- assertEquals("The result has been returned, but no hits are available yet",
- 0, result.hits().getConcreteSize());
+ assertEquals(0, result.hits().getConcreteSize(), "The result has been returned, but no hits are available yet");
// pretend we're the IO layer and complete delayed data - this is typically done in a callback from jDisc
futureDataSource.simulateOneHitIOComplete(new Hit("hit:0"));
futureDataSource.simulateOneHitIOComplete(new Hit("hit:1"));
futureDataSource.simulateAllHitsIOComplete();
- assertEquals("Async arriving hits are still not visible because we haven't asked for them",
- 0, result.hits().getConcreteSize());
+ assertEquals(0, result.hits().getConcreteSize(), "Async arriving hits are still not visible because we haven't asked for them");
// Results with future hit groups will be passed to rendering directly and start rendering immediately.
// For this test we block and wait for the data instead:
diff --git a/container-search/src/test/java/com/yahoo/search/searchchain/test/SearchChainTestCase.java b/container-search/src/test/java/com/yahoo/search/searchchain/test/SearchChainTestCase.java
index d7fd73a81e6..3e7a152122e 100644
--- a/container-search/src/test/java/com/yahoo/search/searchchain/test/SearchChainTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/searchchain/test/SearchChainTestCase.java
@@ -2,7 +2,7 @@
package com.yahoo.search.searchchain.test;
import static com.yahoo.search.searchchain.test.SimpleSearchChain.searchChain;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
@@ -19,7 +19,7 @@ import com.yahoo.search.Result;
import com.yahoo.search.Searcher;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.searchchain.SearchChain;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* Tests basic search chain functionality - creation, inheritance and ordering
@@ -30,17 +30,17 @@ import org.junit.Test;
public class SearchChainTestCase {
@Test
- public void testEmptySearchChain() {
+ void testEmptySearchChain() {
SearchChain empty = new SearchChain(new ComponentId("empty"));
assertEquals("empty", empty.getId().getName());
}
@Test
- public void testSearchChainCreation() {
- assertEquals("test",searchChain.getId().stringValue());
- assertEquals("test",searchChain.getId().getName());
+ void testSearchChainCreation() {
+ assertEquals("test", searchChain.getId().stringValue());
+ assertEquals("test", searchChain.getId().getName());
assertEquals(Version.emptyVersion, searchChain.getId().getVersion());
- assertEquals(new Version(),searchChain.getId().getVersion());
+ assertEquals(new Version(), searchChain.getId().getVersion());
assertEqualMembers(Arrays.asList("one", "two"), searcherNames(searchChain.searchers()));
}
@@ -60,28 +60,28 @@ public class SearchChainTestCase {
}
@Test
- public void testSearchChainToStringEmpty() {
+ void testSearchChainToStringEmpty() {
assertEquals("chain 'test' []", new Chain<>(new ComponentId("test"), createSearchers(0)).toString());
}
@Test
- public void testSearchChainToStringVeryShort() {
- assertEquals("chain 'test' [s1]", new Chain<>(new ComponentId("test"),createSearchers(1)).toString());
+ void testSearchChainToStringVeryShort() {
+ assertEquals("chain 'test' [s1]", new Chain<>(new ComponentId("test"), createSearchers(1)).toString());
}
@Test
- public void testSearchChainToStringShort() {
- assertEquals("chain 'test' [s1 -> s2 -> s3]", new Chain<>(new ComponentId("test"),createSearchers(3)).toString());
+ void testSearchChainToStringShort() {
+ assertEquals("chain 'test' [s1 -> s2 -> s3]", new Chain<>(new ComponentId("test"), createSearchers(3)).toString());
}
@Test
- public void testSearchChainToStringLong() {
- assertEquals("chain 'test' [s1 -> s2 -> ... -> s4]", new Chain<>(new ComponentId("test"),createSearchers(4)).toString());
+ void testSearchChainToStringLong() {
+ assertEquals("chain 'test' [s1 -> s2 -> ... -> s4]", new Chain<>(new ComponentId("test"), createSearchers(4)).toString());
}
@Test
- public void testSearchChainToStringVeryLong() {
- assertEquals("chain 'test' [s1 -> s2 -> ... -> s10]", new Chain<>(new ComponentId("test"),createSearchers(10)).toString());
+ void testSearchChainToStringVeryLong() {
+ assertEquals("chain 'test' [s1 -> s2 -> ... -> s10]", new Chain<>(new ComponentId("test"), createSearchers(10)).toString());
}
private List<Searcher> createSearchers(int count) {
diff --git a/container-search/src/test/java/com/yahoo/search/searchchain/test/TraceTestCase.java b/container-search/src/test/java/com/yahoo/search/searchchain/test/TraceTestCase.java
index 04b1fd85872..f2c8551126b 100644
--- a/container-search/src/test/java/com/yahoo/search/searchchain/test/TraceTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/searchchain/test/TraceTestCase.java
@@ -10,7 +10,7 @@ import com.yahoo.search.result.Hit;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.yolean.trace.TraceNode;
import com.yahoo.yolean.trace.TraceVisitor;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.StringWriter;
@@ -19,8 +19,8 @@ import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
-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 tracing scenarios where traces from multiple executions over the same query are involved.
@@ -30,27 +30,27 @@ import static org.junit.Assert.assertFalse;
public class TraceTestCase {
@Test
- public void testTracingOnCorrectAPIUseNonParallel() {
- assertTracing(true,false);
+ void testTracingOnCorrectAPIUseNonParallel() {
+ assertTracing(true, false);
}
@Test
- public void testTracingOnIncorrectAPIUseNonParallel() {
- assertTracing(false,false);
+ void testTracingOnIncorrectAPIUseNonParallel() {
+ assertTracing(false, false);
}
@Test
- public void testTracingOnCorrectAPIUseParallel() {
+ void testTracingOnCorrectAPIUseParallel() {
assertTracing(true, true);
}
@Test
- public void testTracingOnIncorrectAPIUseParallel() {
- assertTracing(false,true);
+ void testTracingOnIncorrectAPIUseParallel() {
+ assertTracing(false, true);
}
@Test
- public void testTraceWithQuery() {
+ void testTraceWithQuery() {
testQueryInTrace(true, "trace.query=true");
testQueryInTrace(false, "trace.query=false");
testQueryInTrace(true, "");
@@ -71,13 +71,13 @@ public class TraceTestCase {
assertEquals(" During tracer1: 0", trace.next());
}
- @Test
- public void testTraceInvocationsUnfillableHits() {
+ @Test
+ void testTraceInvocationsUnfillableHits() {
final int traceLevel = 5;
Query query = new Query("?trace.level=" + traceLevel);
- Chain<Searcher> forkingChain = new Chain<>(new Tracer("tracer1"),
- new Tracer("tracer2"),
- new Backend("backend1", false));
+ Chain<Searcher> forkingChain = new Chain<>(new Tracer("tracer1"),
+ new Tracer("tracer2"),
+ new Backend("backend1", false));
Execution execution = new Execution(forkingChain, Execution.Context.createContextStub());
Result result = execution.search(query);
execution.fill(result, "mySummary");
@@ -104,12 +104,12 @@ public class TraceTestCase {
}
@Test
- public void testTraceInvocationsFillableHits() {
+ void testTraceInvocationsFillableHits() {
final int traceLevel = 5;
Query query = new Query("?tracelevel=" + traceLevel);
Chain<Searcher> forkingChain = new Chain<>(new Tracer("tracer1"),
- new Tracer("tracer2"),
- new Backend("backend1", true));
+ new Tracer("tracer2"),
+ new Backend("backend1", true));
Execution execution = new Execution(forkingChain, Execution.Context.createContextStub());
Result result = execution.search(query);
execution.fill(result, "mySummary");
diff --git a/container-search/src/test/java/com/yahoo/search/searchers/ValidateFuzzySearcherTestCase.java b/container-search/src/test/java/com/yahoo/search/searchers/ValidateFuzzySearcherTestCase.java
index 577963ef2b3..1cf8159e19e 100644
--- a/container-search/src/test/java/com/yahoo/search/searchers/ValidateFuzzySearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/searchers/ValidateFuzzySearcherTestCase.java
@@ -14,13 +14,14 @@ import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.yql.YqlParser;
import com.yahoo.vespa.config.search.AttributesConfig;
import com.yahoo.vespa.config.search.AttributesConfig.Attribute;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
-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 alexeyche
@@ -64,10 +65,10 @@ public class ValidateFuzzySearcherTestCase {
@Test
- public void testQueriesToAllAttributes() {
+ void testQueriesToAllAttributes() {
final Set<String> validAttributes = Set.of("string_single", "string_array", "string_weightedset");
- for (String attribute: attributes) {
+ for (String attribute : attributes) {
String q = makeQuery(attribute, "fuzzy");
Result r = doSearch(searcher, q);
if (validAttributes.contains(attribute)) {
@@ -79,28 +80,28 @@ public class ValidateFuzzySearcherTestCase {
}
@Test
- public void testInvalidEmptyStringQuery() {
+ void testInvalidEmptyStringQuery() {
String q = makeQuery("string_single", "");
Result r = doSearch(searcher, q);
assertErrMsg("FUZZY(,2,0) string_single: fuzzy query must be non-empty", r);
}
@Test
- public void testInvalidQueryWrongMaxEditDistance() {
+ void testInvalidQueryWrongMaxEditDistance() {
String q = makeQuery("string_single", "fuzzy", -1, 0);
Result r = doSearch(searcher, q);
assertErrMsg("FUZZY(fuzzy,-1,0) string_single:fuzzy has invalid maxEditDistance -1: Must be >= 0", r);
}
@Test
- public void testInvalidQueryWrongPrefixLength() {
+ void testInvalidQueryWrongPrefixLength() {
String q = makeQuery("string_single", "fuzzy", 2, -1);
Result r = doSearch(searcher, q);
assertErrMsg("FUZZY(fuzzy,2,-1) string_single:fuzzy has invalid prefixLength -1: Must be >= 0", r);
}
@Test
- public void testInvalidQueryWrongAttributeName() {
+ void testInvalidQueryWrongAttributeName() {
String q = makeQuery("wrong_name", "fuzzy");
Result r = doSearch(searcher, q);
assertErrMsg("FUZZY(fuzzy,2,0) wrong_name:fuzzy field is not a string attribute", r);
diff --git a/container-search/src/test/java/com/yahoo/search/searchers/ValidateNearestNeighborTestCase.java b/container-search/src/test/java/com/yahoo/search/searchers/ValidateNearestNeighborTestCase.java
index c2f4ee31aa8..b8be0b3dd43 100644
--- a/container-search/src/test/java/com/yahoo/search/searchers/ValidateNearestNeighborTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/searchers/ValidateNearestNeighborTestCase.java
@@ -16,10 +16,10 @@ import com.yahoo.search.yql.YqlParser;
import com.yahoo.tensor.Tensor;
import com.yahoo.tensor.TensorType;
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.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
/**
* @author arnej
@@ -103,7 +103,7 @@ public class ValidateNearestNeighborTestCase {
}
@Test
- public void testValidQueryDoubleVectors() {
+ void testValidQueryDoubleVectors() {
String q = makeQuery("dvector", "qvector");
Tensor t = makeTensor(tt_dense_dvector_3);
Result r = doSearch(searcher, q, t);
@@ -111,7 +111,7 @@ public class ValidateNearestNeighborTestCase {
}
@Test
- public void testValidQueryFloatVectors() {
+ void testValidQueryFloatVectors() {
String q = makeQuery("fvector", "qvector");
Tensor t = makeTensor(tt_dense_fvector_3);
Result r = doSearch(searcher, q, t);
@@ -119,7 +119,7 @@ public class ValidateNearestNeighborTestCase {
}
@Test
- public void testValidQueryDoubleVectorAgainstFloatVector() {
+ void testValidQueryDoubleVectorAgainstFloatVector() {
String q = makeQuery("dvector", "qvector");
Tensor t = makeTensor(tt_dense_fvector_3);
Result r = doSearch(searcher, q, t);
@@ -127,7 +127,7 @@ public class ValidateNearestNeighborTestCase {
}
@Test
- public void testValidQueryFloatVectorAgainstDoubleVector() {
+ void testValidQueryFloatVectorAgainstDoubleVector() {
String q = makeQuery("fvector", "qvector");
Tensor t = makeTensor(tt_dense_dvector_3);
Result r = doSearch(searcher, q, t);
@@ -152,7 +152,7 @@ public class ValidateNearestNeighborTestCase {
}
@Test
- public void testMissingTargetNumHits() {
+ void testMissingTargetNumHits() {
String q = "select * from sources * where nearestNeighbor(dvector,qvector)";
Tensor t = makeTensor(tt_dense_dvector_3);
Result r = doSearch(searcher, q, t);
@@ -160,7 +160,7 @@ public class ValidateNearestNeighborTestCase {
}
@Test
- public void testMissingQueryTensor() {
+ void testMissingQueryTensor() {
String q = makeQuery("dvector", "foo");
Tensor t = makeTensor(tt_dense_dvector_3);
Result r = doSearch(searcher, q, t);
@@ -168,7 +168,7 @@ public class ValidateNearestNeighborTestCase {
}
@Test
- public void testWrongTensorType() {
+ void testWrongTensorType() {
String q = makeQuery("dvector", "qvector");
Tensor t = makeTensor(tt_dense_dvector_2, 2);
Result r = doSearch(searcher, q, t);
@@ -176,7 +176,7 @@ public class ValidateNearestNeighborTestCase {
}
@Test
- public void testNotAttribute() {
+ void testNotAttribute() {
String q = makeQuery("foo", "qvector");
Tensor t = makeTensor(tt_dense_dvector_3);
Result r = doSearch(searcher, q, t);
@@ -184,7 +184,7 @@ public class ValidateNearestNeighborTestCase {
}
@Test
- public void testWrongAttributeType() {
+ void testWrongAttributeType() {
String q = makeQuery("simple", "qvector");
Tensor t = makeTensor(tt_dense_dvector_3);
Result r = doSearch(searcher, q, t);
@@ -192,7 +192,7 @@ public class ValidateNearestNeighborTestCase {
}
@Test
- public void testSeveralAttributesWithSameName() {
+ void testSeveralAttributesWithSameName() {
String q = makeQuery("threetypes", "qvector");
Tensor t1 = makeTensor(tt_dense_fvector_3);
Result r1 = doSearch(searcher, q, t1);
@@ -206,7 +206,7 @@ public class ValidateNearestNeighborTestCase {
}
@Test
- public void testSparseTensor() {
+ void testSparseTensor() {
String q = makeQuery("sparse", "qvector");
Tensor t = makeTensor(tt_sparse_vector_x);
Result r = doSearch(searcher, q, t);
@@ -214,7 +214,7 @@ public class ValidateNearestNeighborTestCase {
}
@Test
- public void testMatrix() {
+ void testMatrix() {
String q = makeQuery("matrix", "qvector");
Tensor t = makeMatrix(tt_dense_matrix_xy);
Result r = doSearch(searcher, q, t);
diff --git a/container-search/src/test/java/com/yahoo/search/searchers/test/CacheControlSearcherTestCase.java b/container-search/src/test/java/com/yahoo/search/searchers/test/CacheControlSearcherTestCase.java
index b0fd77897fc..dc99185f4b8 100644
--- a/container-search/src/test/java/com/yahoo/search/searchers/test/CacheControlSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/searchers/test/CacheControlSearcherTestCase.java
@@ -8,15 +8,12 @@ import com.yahoo.search.Searcher;
import com.yahoo.search.result.Hit;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.searchers.CacheControlSearcher;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import static com.yahoo.search.searchers.CacheControlSearcher.CACHE_CONTROL_HEADER;
-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.*;
/**
* Unit test cases for CacheControlSearcher.
@@ -54,17 +51,17 @@ public class CacheControlSearcherTestCase {
* @param cacheheaders - The "Cache-Control" headers from the response ListMap
*/
private void assertCacheHeaders(String[] values, List<String> cacheheaders) {
- assertNotNull("No headers to test for (was null)", values);
- assertTrue("No headers to test for (no elements in array)", values.length > 0);
- assertNotNull("No cache headers set in response", cacheheaders);
+ assertNotNull(values, "No headers to test for (was null)");
+ assertTrue(values.length > 0, "No headers to test for (no elements in array)");
+ assertNotNull(cacheheaders, "No cache headers set in response");
assertEquals(values.length, cacheheaders.size());
for (String header : values) {
- assertTrue("Cache header does not contain header '" + header + "'", cacheheaders.contains(header));
+ assertTrue(cacheheaders.contains(header), "Cache header does not contain header '" + header + "'");
}
}
@Test
- public void testNoHeader() {
+ void testNoHeader() {
Chain<Searcher> chain = getSearchChain();
Query query = new Query("?query=foo&custid=foo");
Result result = new Execution(chain, Execution.Context.createContextStub()).search(query);
@@ -72,7 +69,7 @@ public class CacheControlSearcherTestCase {
}
@Test
- public void testInvalidAgeParams() {
+ void testInvalidAgeParams() {
Chain<Searcher> chain = getSearchChain();
try {
@@ -97,7 +94,7 @@ public class CacheControlSearcherTestCase {
}
@Test
- public void testMaxAge() {
+ void testMaxAge() {
Chain<Searcher> chain = getSearchChain();
Query query = new Query("?query=foo&custid=foo&cachecontrol.maxage=120");
@@ -106,7 +103,7 @@ public class CacheControlSearcherTestCase {
}
@Test
- public void testNoCache() {
+ void testNoCache() {
Chain<Searcher> chain = getSearchChain();
Query query = new Query("?query=foo&custid=foo&cachecontrol.maxage=120&noCache");
@@ -119,7 +116,7 @@ public class CacheControlSearcherTestCase {
}
@Test
- public void testStateWhileRevalidate() {
+ void testStateWhileRevalidate() {
Chain<Searcher> chain = getSearchChain();
Query query = new Query("?query=foo&custid=foo&cachecontrol.staleage=3600");
@@ -128,7 +125,7 @@ public class CacheControlSearcherTestCase {
}
@Test
- public void testStaleAndMaxAge() {
+ void testStaleAndMaxAge() {
Chain<Searcher> chain = getSearchChain();
Query query = new Query("?query=foo&custid=foo&cachecontrol.maxage=60&cachecontrol.staleage=3600");
diff --git a/container-search/src/test/java/com/yahoo/search/searchers/test/ConnectionControlSearcherTestCase.java b/container-search/src/test/java/com/yahoo/search/searchers/test/ConnectionControlSearcherTestCase.java
index 48dc0975efe..5323149ae1d 100644
--- a/container-search/src/test/java/com/yahoo/search/searchers/test/ConnectionControlSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/searchers/test/ConnectionControlSearcherTestCase.java
@@ -1,8 +1,8 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.searchers.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;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -12,8 +12,7 @@ import java.net.SocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.yahoo.component.chain.Chain;
import com.yahoo.container.jdisc.HttpRequest;
import com.yahoo.jdisc.Container;
@@ -35,7 +34,7 @@ import com.yahoo.search.searchers.ConnectionControlSearcher;
public class ConnectionControlSearcherTestCase {
@Test
- public final void test() throws URISyntaxException {
+ final void test() throws URISyntaxException {
URI uri = new URI("http://finance.yahoo.com/?connectioncontrol.maxlifetime=1");
long connectedAtMillis = 0L;
long nowMillis = 2L * 1000L;
@@ -44,7 +43,7 @@ public class ConnectionControlSearcherTestCase {
}
@Test
- public final void testForcedClose() throws URISyntaxException {
+ final void testForcedClose() throws URISyntaxException {
URI uri = new URI("http://finance.yahoo.com/?connectioncontrol.maxlifetime=0");
long connectedAtMillis = 0L;
long nowMillis = 0L;
@@ -53,7 +52,7 @@ public class ConnectionControlSearcherTestCase {
}
@Test
- public final void testNormalCloseWithoutJdisc() {
+ final void testNormalCloseWithoutJdisc() {
long nowMillis = 2L;
Query query = new Query("/?connectioncontrol.maxlifetime=1");
Execution e = new Execution(new Chain<Searcher>(ConnectionControlSearcher.createTestInstance(() -> nowMillis)),
@@ -63,7 +62,7 @@ public class ConnectionControlSearcherTestCase {
}
@Test
- public final void testNoMaxLifetime() throws URISyntaxException {
+ final void testNoMaxLifetime() throws URISyntaxException {
URI uri = new URI("http://finance.yahoo.com/");
long connectedAtMillis = 0L;
long nowMillis = 0L;
@@ -72,7 +71,7 @@ public class ConnectionControlSearcherTestCase {
}
@Test
- public final void testYoungEnoughConnection() throws URISyntaxException {
+ final void testYoungEnoughConnection() throws URISyntaxException {
URI uri = new URI("http://finance.yahoo.com/?connectioncontrol.maxlifetime=1");
long connectedAtMillis = 0L;
long nowMillis = 500L;
diff --git a/container-search/src/test/java/com/yahoo/search/searchers/test/InputCheckingSearcherTestCase.java b/container-search/src/test/java/com/yahoo/search/searchers/test/InputCheckingSearcherTestCase.java
index 91784c82800..2cd65f65209 100644
--- a/container-search/src/test/java/com/yahoo/search/searchers/test/InputCheckingSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/searchers/test/InputCheckingSearcherTestCase.java
@@ -1,16 +1,15 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.searchers.test;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import com.yahoo.component.chain.Chain;
import com.yahoo.metrics.simple.MetricReceiver;
import com.yahoo.prelude.IndexFacts;
@@ -30,44 +29,44 @@ public class InputCheckingSearcherTestCase {
Execution execution;
- @Before
+ @BeforeEach
public void setUp() {
execution = new Execution(new Chain<Searcher>(new InputCheckingSearcher(MetricReceiver.nullImplementation)),
Execution.Context.createContextStub());
}
- @After
+ @AfterEach
public void tearDown() {
execution = null;
}
@Test
- public void testCommonCase() {
+ void testCommonCase() {
Result r = execution.search(new Query("/search/?query=three+blind+mice"));
assertNull(r.hits().getErrorHit());
}
@Test
- public void candidateButAsciiOnly() {
+ void candidateButAsciiOnly() {
Result r = execution.search(new Query("/search/?query=a+a+a+a+a+a"));
assertNull(r.hits().getErrorHit());
}
@Test
- public void candidateButValid() throws UnsupportedEncodingException {
+ void candidateButValid() throws UnsupportedEncodingException {
Result r = execution.search(new Query("/search/?query=" + URLEncoder.encode("å å å å å å", "UTF-8")));
assertNull(r.hits().getErrorHit());
}
@Test
- public void candidateButValidAndOutsideFirst256() throws UnsupportedEncodingException {
+ void candidateButValidAndOutsideFirst256() throws UnsupportedEncodingException {
Result r = execution.search(new Query("/search/?query=" + URLEncoder.encode("œ œ œ œ œ œ", "UTF-8")));
assertNull(r.hits().getErrorHit());
}
@Test
- public void testDoubleEncoded() throws UnsupportedEncodingException {
+ void testDoubleEncoded() throws UnsupportedEncodingException {
String rawQuery = "å å å å å å";
byte[] encodedOnce = Utf8.toBytes(rawQuery);
char[] secondEncodingBuffer = new char[encodedOnce.length];
@@ -80,37 +79,37 @@ public class InputCheckingSearcherTestCase {
}
@Test
- public void testRepeatedConsecutiveTermsInPhrase() {
+ void testRepeatedConsecutiveTermsInPhrase() {
Result r = execution.search(new Query("/search/?query=%22a.b.0.0.0.0.0.c%22"));
assertNull(r.hits().getErrorHit());
r = execution.search(new Query("/search/?query=%22a.b.0.0.0.0.0.0.c%22"));
assertNotNull(r.hits().getErrorHit());
assertEquals("More than 5 occurrences of term '0' in a row detected in phrase : \"a b 0 0 0 0 0 0 c\"",
- r.hits().getErrorHit().errorIterator().next().getDetailedMessage());
+ r.hits().getErrorHit().errorIterator().next().getDetailedMessage());
r = execution.search(new Query("/search/?query=a.b.0.0.0.1.0.0.0.c"));
assertNull(r.hits().getErrorHit());
}
@Test
- public void testThatMaxRepeatedConsecutiveTermsInPhraseIs5() {
+ void testThatMaxRepeatedConsecutiveTermsInPhraseIs5() {
Result r = execution.search(new Query("/search/?query=%22a.b.0.0.0.0.0.c%22"));
assertNull(r.hits().getErrorHit());
r = execution.search(new Query("/search/?query=%22a.b.0.0.0.0.0.0.c%22"));
assertNotNull(r.hits().getErrorHit());
assertEquals("More than 5 occurrences of term '0' in a row detected in phrase : \"a b 0 0 0 0 0 0 c\"",
- r.hits().getErrorHit().errorIterator().next().getDetailedMessage());
+ r.hits().getErrorHit().errorIterator().next().getDetailedMessage());
r = execution.search(new Query("/search/?query=%22a.b.0.0.0.1.0.0.0.c%22"));
assertNull(r.hits().getErrorHit());
}
@Test
- public void testThatMaxRepeatedTermsInPhraseIs10() {
+ void testThatMaxRepeatedTermsInPhraseIs10() {
Result r = execution.search(new Query("/search/?query=%220.a.1.a.2.a.3.a.4.a.5.a.6.a.7.a.9.a%22"));
assertNull(r.hits().getErrorHit());
r = execution.search(new Query("/search/?query=%220.a.1.a.2.a.3.a.4.a.5.a.6.a.7.a.8.a.9.a.10.a%22"));
assertNotNull(r.hits().getErrorHit());
assertEquals("Phrase contains more than 10 occurrences of term 'a' in phrase : \"0 a 1 a 2 a 3 a 4 a 5 a 6 a 7 a 8 a 9 a 10 a\"",
- r.hits().getErrorHit().errorIterator().next().getDetailedMessage());
+ r.hits().getErrorHit().errorIterator().next().getDetailedMessage());
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/searchers/test/QueryValidatorTestCase.java b/container-search/src/test/java/com/yahoo/search/searchers/test/QueryValidatorTestCase.java
index d5fb1c0cfe3..64fb4354003 100644
--- a/container-search/src/test/java/com/yahoo/search/searchers/test/QueryValidatorTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/searchers/test/QueryValidatorTestCase.java
@@ -7,10 +7,10 @@ import com.yahoo.prelude.SearchDefinition;
import com.yahoo.search.Query;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.searchers.QueryValidator;
-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 QueryValidatorTestCase {
@Test
- public void testValidation() {
+ void testValidation() {
SearchDefinition sd = new SearchDefinition("test");
sd.addCommand("mytensor1", "type tensor(x[100]");
sd.addCommand("mytensor2", "type tensor<float>(x[100]");
diff --git a/container-search/src/test/java/com/yahoo/search/searchers/test/RateLimitingSearcherTestCase.java b/container-search/src/test/java/com/yahoo/search/searchers/test/RateLimitingSearcherTestCase.java
index 4ee57112960..102f9bda5dc 100755
--- a/container-search/src/test/java/com/yahoo/search/searchers/test/RateLimitingSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/searchers/test/RateLimitingSearcherTestCase.java
@@ -14,15 +14,13 @@ import com.yahoo.search.config.RateLimitingConfig;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.searchers.RateLimitingSearcher;
import com.yahoo.yolean.chain.After;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import com.yahoo.test.ManualClock;
import java.time.Duration;
import java.util.Map;
-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.*;
/**
* Unit tests for RateLimitingSearcher
@@ -32,7 +30,7 @@ import static org.junit.Assert.assertFalse;
public class RateLimitingSearcherTestCase {
@Test
- public void testRateLimiting() {
+ void testRateLimiting() {
RateLimitingConfig.Builder rateLimitingConfig = new RateLimitingConfig.Builder();
rateLimitingConfig.maxAvailableCapacity(4);
rateLimitingConfig.capacityIncrement(2);
@@ -46,36 +44,36 @@ public class RateLimitingSearcherTestCase {
MetricReceiver.MockReceiver metric = new MetricReceiver.MockReceiver();
Chain<Searcher> chain = new Chain<>("test", new RateLimitingSearcher(new RateLimitingConfig(rateLimitingConfig),
- new ClusterInfoConfig(clusterInfoConfig),
- metric, clock),
- new CostSettingSearcher());
- assertEquals("'rate' request are available initially", 2, tryRequests(chain, "id1"));
- assertTrue("However, don't reject if we dryRun", executeWasAllowed(chain, "id1", true));
+ new ClusterInfoConfig(clusterInfoConfig),
+ metric, clock),
+ new CostSettingSearcher());
+ assertEquals(2, tryRequests(chain, "id1"), "'rate' request are available initially");
+ assertTrue(executeWasAllowed(chain, "id1", true), "However, don't reject if we dryRun");
clock.advance(Duration.ofMillis(1500)); // causes 2 new requests to become available
- assertEquals("'rate' new requests became available", 2, tryRequests(chain, "id1"));
+ assertEquals(2, tryRequests(chain, "id1"), "'rate' new requests became available");
- assertEquals("Another id", 2, tryRequests(chain, "id2"));
+ assertEquals(2, tryRequests(chain, "id2"), "Another id");
clock.advance(Duration.ofMillis(1000000));
- assertEquals("'maxAvailableCapacity' request became available", 4, tryRequests(chain, "id2"));
+ assertEquals(4, tryRequests(chain, "id2"), "'maxAvailableCapacity' request became available");
- assertFalse("If quota is set to 0, all requests are rejected, even initially", executeWasAllowed(chain, "id3", 0));
+ assertFalse(executeWasAllowed(chain, "id3", 0), "If quota is set to 0, all requests are rejected, even initially");
clock.advance(Duration.ofMillis(1000000));
- assertTrue("A single query which costs more than capacity is allowed as cost is calculated after allowing it",
- executeWasAllowed(chain, "id1", 8, 8, false));
- assertFalse("capacity is -4: disallowing", executeWasAllowed(chain, "id1"));
+ assertTrue(executeWasAllowed(chain, "id1", 8, 8, false),
+ "A single query which costs more than capacity is allowed as cost is calculated after allowing it");
+ assertFalse(executeWasAllowed(chain, "id1"), "capacity is -4: disallowing");
clock.advance(Duration.ofMillis(1000));
- assertFalse("capacity is -2: disallowing", executeWasAllowed(chain, "id1"));
+ assertFalse(executeWasAllowed(chain, "id1"), "capacity is -2: disallowing");
clock.advance(Duration.ofMillis(1000));
- assertFalse("capacity is 0: disallowing", executeWasAllowed(chain, "id1"));
+ assertFalse(executeWasAllowed(chain, "id1"), "capacity is 0: disallowing");
clock.advance(Duration.ofMillis(1000));
assertTrue(executeWasAllowed(chain, "id1"));
// check metrics
- Map<Point,UntypedMetric> map = metric.getSnapshot().getMapForMetric("requestsOverQuota");
- assertEquals(requestsToTry-2 + 1 + requestsToTry-2 + 3, map.get(metric.point("id", "id1")).getCount());
- assertEquals(requestsToTry-2 + requestsToTry-4, map.get(metric.point("id", "id2")).getCount());
+ Map<Point, UntypedMetric> map = metric.getSnapshot().getMapForMetric("requestsOverQuota");
+ assertEquals(requestsToTry - 2 + 1 + requestsToTry - 2 + 3, map.get(metric.point("id", "id1")).getCount());
+ assertEquals(requestsToTry - 2 + requestsToTry - 4, map.get(metric.point("id", "id2")).getCount());
}
private int requestsToTry = 50;
diff --git a/container-search/src/test/java/com/yahoo/search/searchers/test/ValidateMatchPhaseSearcherTestCase.java b/container-search/src/test/java/com/yahoo/search/searchers/test/ValidateMatchPhaseSearcherTestCase.java
index 1b3689a94b0..a040575c4b4 100644
--- a/container-search/src/test/java/com/yahoo/search/searchers/test/ValidateMatchPhaseSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/searchers/test/ValidateMatchPhaseSearcherTestCase.java
@@ -9,12 +9,12 @@ import com.yahoo.search.searchers.ValidateMatchPhaseSearcher;
import com.yahoo.search.Query;
import com.yahoo.search.Result;
import com.yahoo.vespa.config.search.AttributesConfig;
-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.jupiter.api.Assertions.assertEquals;
/**
* @author baldersheim
@@ -61,7 +61,7 @@ public class ValidateMatchPhaseSearcherTestCase {
}
@Test
- public void testMatchPhaseAttribute() {
+ void testMatchPhaseAttribute() {
assertEquals("", search(""));
assertEquals("", match("ok"));
assertEquals(getErrorMatch("not_numeric"), match("not_numeric"));
@@ -71,7 +71,7 @@ public class ValidateMatchPhaseSearcherTestCase {
}
@Test
- public void testDiversityAttribute() {
+ void testDiversityAttribute() {
assertEquals("", search(""));
assertEquals("", diversify("ok"));
assertEquals("", diversify("not_numeric"));
diff --git a/container-search/src/test/java/com/yahoo/search/statistics/ElapsedTimeTestCase.java b/container-search/src/test/java/com/yahoo/search/statistics/ElapsedTimeTestCase.java
index c7983a55e8b..4d6b2e4cbe3 100644
--- a/container-search/src/test/java/com/yahoo/search/statistics/ElapsedTimeTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/statistics/ElapsedTimeTestCase.java
@@ -10,11 +10,9 @@ import com.yahoo.search.result.Hit;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.search.statistics.TimeTracker.Activity;
import com.yahoo.search.statistics.TimeTracker.SearcherTimer;
-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.*;
/**
* Check sanity of TimeTracker and ElapsedTime.
@@ -145,9 +143,9 @@ public class ElapsedTimeTestCase {
}
@Test
- public void testBasic() {
+ void testBasic() {
TimeTracker t = new TimeTracker(null);
- t.injectTimeSource(new CreativeTimeSource(new long[] {1L, 2L, 3L, 4L}));
+ t.injectTimeSource(new CreativeTimeSource(new long[]{1L, 2L, 3L, 4L}));
Query q = new Query();
Result r = new Result(q);
t.sampleSearch(0, false);
@@ -164,9 +162,9 @@ public class ElapsedTimeTestCase {
}
@Test
- public void testMultiSearchAndPing() {
+ void testMultiSearchAndPing() {
TimeTracker t = new TimeTracker(null);
- t.injectTimeSource(new CreativeTimeSource(new long[] {1L, 4L, 16L, 32L, 64L, 128L, 256L}));
+ t.injectTimeSource(new CreativeTimeSource(new long[]{1L, 4L, 16L, 32L, 64L, 128L, 256L}));
Query q = new Query();
Result r = new Result(q);
t.sampleSearch(0, false);
@@ -189,7 +187,7 @@ public class ElapsedTimeTestCase {
// multiple adds is supposed to be safe
assertEquals(255L, t.totalTime());
TimeTracker tx = new TimeTracker(null);
- tx.injectTimeSource(new CreativeTimeSource(new long[] {1L, 2L, 3L, 4L}));
+ tx.injectTimeSource(new CreativeTimeSource(new long[]{1L, 2L, 3L, 4L}));
Query qx = new Query();
Result rx = new Result(qx);
tx.sampleSearch(0, false);
@@ -203,12 +201,12 @@ public class ElapsedTimeTestCase {
}
@Test
- public void testBasicBreakdown() {
+ void testBasicBreakdown() {
TimeTracker t = new TimeTracker(new Chain<Searcher>(
new UselessSearcher("first"), new UselessSearcher("second"),
new UselessSearcher("third")));
- t.injectTimeSource(new CreativeTimeSource(new long[] { 1L, 2L, 3L,
- 4L, 5L, 6L, 7L }));
+ t.injectTimeSource(new CreativeTimeSource(new long[]{1L, 2L, 3L,
+ 4L, 5L, 6L, 7L}));
t.sampleSearch(0, true);
t.sampleSearch(1, true);
t.sampleSearch(2, true);
@@ -223,7 +221,7 @@ public class ElapsedTimeTestCase {
// This test is to make sure the other tests correctly simulate the call
// order into the TimeTracker
@Test
- public void testBasicBreakdownFullyWiredIn() {
+ void testBasicBreakdownFullyWiredIn() {
Chain<? extends Searcher> chain = new Chain<Searcher>(
new UselessSearcher("first"), new UselessSearcher("second"),
new UselessSearcher("third"));
@@ -250,7 +248,7 @@ public class ElapsedTimeTestCase {
}
@Test
- public void testBasicBreakdownWithFillFullyWiredIn() {
+ void testBasicBreakdownWithFillFullyWiredIn() {
Chain<? extends Searcher> chain = new Chain<>(
new UselessSearcher("first"), new UselessSearcher("second"),
new AlmostUselessSearcher("third"));
@@ -279,7 +277,7 @@ public class ElapsedTimeTestCase {
}
@Test
- public void testBasicBreakdownFullyWiredInFirstSearcherNotFirstInChain() {
+ void testBasicBreakdownFullyWiredInFirstSearcherNotFirstInChain() {
Chain<? extends Searcher> chain = new Chain<>(
new TestingSearcher(),
new UselessSearcher("first"), new UselessSearcher("second"),
@@ -289,7 +287,7 @@ public class ElapsedTimeTestCase {
}
@Test
- public void testBasicBreakdownWithFillFullyWiredInFirstSearcherNotFirstInChain() {
+ void testBasicBreakdownWithFillFullyWiredInFirstSearcherNotFirstInChain() {
Chain<? extends Searcher> chain = new Chain<>(
new SecondTestingSearcher(),
new UselessSearcher("first"), new UselessSearcher("second"),
@@ -299,7 +297,7 @@ public class ElapsedTimeTestCase {
}
@Test
- public void testTimingWithShortChain() {
+ void testTimingWithShortChain() {
Chain<? extends Searcher> chain = new Chain<>(
new ShortChainTestingSearcher(),
new NoForwardSearcher());
@@ -308,12 +306,12 @@ public class ElapsedTimeTestCase {
}
@Test
- public void testBasicBreakdownReturnInsideSearchChain() {
+ void testBasicBreakdownReturnInsideSearchChain() {
TimeTracker t = new TimeTracker(new Chain<Searcher>(
new UselessSearcher("first"), new UselessSearcher("second"),
new UselessSearcher("third")));
- t.injectTimeSource(new CreativeTimeSource(new long[] { 1L, 2L, 3L,
- 4L, 5L, 6L }));
+ t.injectTimeSource(new CreativeTimeSource(new long[]{1L, 2L, 3L,
+ 4L, 5L, 6L}));
t.sampleSearch(0, true);
t.sampleSearch(1, true);
t.sampleSearch(2, true);
@@ -325,16 +323,16 @@ public class ElapsedTimeTestCase {
assertEquals(Long.valueOf(1L), searchers[1].getInvoking(Activity.SEARCH));
assertEquals(Long.valueOf(1L), searchers[2].getInvoking(Activity.SEARCH));
assertNull(searchers[2].getReturning(Activity.SEARCH));
- assertEquals(Long.valueOf(1L) ,searchers[1].getReturning(Activity.SEARCH));
- assertEquals(Long.valueOf(1L) ,searchers[0].getReturning(Activity.SEARCH));
+ assertEquals(Long.valueOf(1L), searchers[1].getReturning(Activity.SEARCH));
+ assertEquals(Long.valueOf(1L), searchers[0].getReturning(Activity.SEARCH));
}
@Test
- public void testBasicBreakdownWithFill() {
+ void testBasicBreakdownWithFill() {
TimeTracker t = new TimeTracker(new Chain<Searcher>(
new UselessSearcher("first"), new UselessSearcher("second"),
new UselessSearcher("third")));
- t.injectTimeSource(new CreativeTimeSource(new long[] { 1L, 2L, 3L,
+ t.injectTimeSource(new CreativeTimeSource(new long[]{1L, 2L, 3L,
4L, 5L, 6L, 7L, 7L, 8L, 9L, 10L}));
t.sampleSearch(0, true);
t.sampleSearch(1, true);
@@ -400,7 +398,7 @@ public class ElapsedTimeTestCase {
}
@Test
- public void testMixedActivity() {
+ void testMixedActivity() {
TimeTracker t = new TimeTracker(new Chain<Searcher>(
new UselessSearcher("first"), new UselessSearcher("second"),
new UselessSearcher("third")));
@@ -424,7 +422,7 @@ public class ElapsedTimeTestCase {
}
@Test
- public void testReportGeneration() {
+ void testReportGeneration() {
TimeTracker t = new TimeTracker(new Chain<Searcher>(
new UselessSearcher("first"), new UselessSearcher("second"),
new UselessSearcher("third")));
diff --git a/container-search/src/test/java/com/yahoo/search/test/QueryTestCase.java b/container-search/src/test/java/com/yahoo/search/test/QueryTestCase.java
index 7cd7e20b76f..f8a77445a40 100644
--- a/container-search/src/test/java/com/yahoo/search/test/QueryTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/test/QueryTestCase.java
@@ -45,8 +45,8 @@ import com.yahoo.search.result.Hit;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.yolean.Exceptions;
import org.json.JSONObject;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
@@ -59,14 +59,7 @@ import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
-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.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.*;
/**
* @author bratseth
@@ -74,10 +67,10 @@ import static org.junit.Assert.fail;
public class QueryTestCase {
@Test
- public void testIt() throws Exception {
+ void testIt() throws Exception {
JSONObject newroot = new JSONObject("{\"key\": 3}");
var hit = new FastHit();
- hit.setField("data", (JsonProducer)s -> s.append(newroot));
+ hit.setField("data", (JsonProducer) s -> s.append(newroot));
var field = hit.getField("data");
if (field instanceof JsonProducer) {
System.out.println((((JsonProducer) field).toJson()));
@@ -85,7 +78,7 @@ public class QueryTestCase {
}
@Test
- public void testSimpleFunctionality() {
+ void testSimpleFunctionality() {
Query q = new Query(QueryTestCase.httpEncode("/sdfsd.html?query=this is a simple query&aParameter"));
assertEquals("this is a simple query", q.getModel().getQueryString());
assertNotNull(q.getModel().getQueryTree());
@@ -105,23 +98,23 @@ public class QueryTestCase {
}
// TODO: YQL work in progress (jon)
- @Ignore
+ @Disabled
@Test
- public void testSimpleProgram() {
+ void testSimpleProgram() {
Query q = new Query(httpEncode("?program=select * from * where myfield contains(word)"));
assertEquals("", q.getModel().getQueryTree().toString());
}
// TODO: YQL work in progress (jon)
- @Ignore
+ @Disabled
@Test
- public void testSimpleProgramParameterAlias() {
+ void testSimpleProgramParameterAlias() {
Query q = new Query(httpEncode("/sdfsd.html?yql=select * from source where myfield contains(word)"));
assertEquals("", q.getModel().getQueryTree().toString());
}
@Test
- public void testClone() {
+ void testClone() {
Query q = new Query(httpEncode("/sdfsd.html?query=this+is+a+simple+query&aParameter"));
q.getPresentation().setHighlight(new Highlight());
Query p = q.clone();
@@ -157,10 +150,10 @@ public class QueryTestCase {
}
@Test
- public void testCloneWithConnectivity() {
+ void testCloneWithConnectivity() {
List<String> l = List.of("a", "b", "c", "a");
printIt(l.stream().filter(i -> isA(i)).collect(Collectors.toList()));
- printIt(l.stream().filter(i -> ! isA(i)).collect(Collectors.toList()));
+ printIt(l.stream().filter(i -> !isA(i)).collect(Collectors.toList()));
Query q = new Query();
WordItem a = new WordItem("a");
@@ -200,18 +193,18 @@ public class QueryTestCase {
Query qClone = q.clone();
assertEquals(q, qClone);
- RankItem rankClone = (RankItem)qClone.getModel().getQueryTree().getRoot();
- AndItem and1Clone = (AndItem)rankClone.getItem(0);
- AndItem and2Clone = (AndItem)rankClone.getItem(1);
- OrItem orClone = (OrItem)and1Clone.getItem(2);
+ RankItem rankClone = (RankItem) qClone.getModel().getQueryTree().getRoot();
+ AndItem and1Clone = (AndItem) rankClone.getItem(0);
+ AndItem and2Clone = (AndItem) rankClone.getItem(1);
+ OrItem orClone = (OrItem) and1Clone.getItem(2);
- WordItem aClone = (WordItem)and1Clone.getItem(0);
- WordItem bClone = (WordItem)and1Clone.getItem(1);
- WordItem cClone = (WordItem)orClone.getItem(0);
- WordItem dClone = (WordItem)orClone.getItem(1);
- WordItem eClone = (WordItem)and1Clone.getItem(3);
- WordItem fClone = (WordItem)and2Clone.getItem(0);
- WordItem gClone = (WordItem)and2Clone.getItem(1);
+ WordItem aClone = (WordItem) and1Clone.getItem(0);
+ WordItem bClone = (WordItem) and1Clone.getItem(1);
+ WordItem cClone = (WordItem) orClone.getItem(0);
+ WordItem dClone = (WordItem) orClone.getItem(1);
+ WordItem eClone = (WordItem) and1Clone.getItem(3);
+ WordItem fClone = (WordItem) and2Clone.getItem(0);
+ WordItem gClone = (WordItem) and2Clone.getItem(1);
assertTrue(rankClone != rank);
assertTrue(and1Clone != and1);
@@ -226,12 +219,12 @@ public class QueryTestCase {
assertTrue(fClone != f);
assertTrue(gClone != g);
- assertTrue(aClone.getConnectedItem() == bClone);
- assertTrue(bClone.getConnectedItem() == cClone);
- assertTrue(cClone.getConnectedItem() == dClone);
- assertTrue(dClone.getConnectedItem() == eClone);
- assertTrue(eClone.getConnectedItem() == fClone);
- assertTrue(fClone.getConnectedItem() == gClone);
+ assertEquals(aClone.getConnectedItem(), bClone);
+ assertEquals(bClone.getConnectedItem(), cClone);
+ assertEquals(cClone.getConnectedItem(), dClone);
+ assertEquals(dClone.getConnectedItem(), eClone);
+ assertEquals(eClone.getConnectedItem(), fClone);
+ assertEquals(fClone.getConnectedItem(), gClone);
double delta = 0.0000001;
assertEquals(0.1, aClone.getConnectivity(), delta);
@@ -243,7 +236,7 @@ public class QueryTestCase {
}
@Test
- public void test_that_cloning_preserves_timeout() {
+ void test_that_cloning_preserves_timeout() {
Query original = new Query();
original.setTimeout(9876L);
@@ -252,7 +245,7 @@ public class QueryTestCase {
}
@Test
- public void testTimeout() {
+ void testTimeout() {
// yes, this test depends on numbers which have exact IEEE representations
Query q = new Query(httpEncode("/search?timeout=500"));
assertEquals(500000L, q.getTimeout());
@@ -283,20 +276,20 @@ public class QueryTestCase {
assertEquals(42000, q.getTimeout());
assertEquals(0, q.errors().size());
- q=new Query();
+ q = new Query();
q.setTimeout(53L);
assertEquals(53L, q.properties().get("timeout"));
assertEquals(53L, q.getTimeout());
// This is the unfortunate consequence of this legacy:
- q=new Query();
+ q = new Query();
q.properties().set("timeout", 53L);
assertEquals(53L * 1000, q.properties().get("timeout"));
assertEquals(53L * 1000, q.getTimeout());
}
@Test
- public void testUnparseableTimeout() {
+ void testUnparseableTimeout() {
try {
new Query(httpEncode("/search?timeout=nalle"));
fail("Above statement should throw");
@@ -307,7 +300,7 @@ public class QueryTestCase {
}
@Test
- public void testCloneTimeout() {
+ void testCloneTimeout() {
Query q = new Query(httpEncode("/search?timeout=300ms"));
assertEquals(300, q.getTimeout());
Query clonedQ = q.clone();
@@ -315,7 +308,7 @@ public class QueryTestCase {
}
@Test
- public void testQueryProfileSubstitution1() {
+ void testQueryProfileSubstitution1() {
QueryProfile profile = new QueryProfile("myProfile");
profile.set("myField", "Profile: %{queryProfile}", null);
Query q = new Query(QueryTestCase.httpEncode("/search?queryProfile=myProfile"), profile.compile(null));
@@ -323,7 +316,7 @@ public class QueryTestCase {
}
@Test
- public void testQueryProfileSourceAccess() {
+ void testQueryProfileSourceAccess() {
QueryProfile profile = new QueryProfile("myProfile");
profile.set("myField", "Profile: %{queryProfile}", null);
Query query = new Query(QueryTestCase.httpEncode("/search?queryProfile=myProfile"), profile.compile(null));
@@ -333,7 +326,7 @@ public class QueryTestCase {
}
@Test
- public void testBooleanParameter() {
+ void testBooleanParameter() {
QueryProfile profile = new QueryProfile("myProfile");
Query query = new Query("/?query=something&ranking.softtimeout.enable=false", profile.compile(null));
assertFalse(query.properties().getBoolean("ranking.softtimeout.enable"));
@@ -341,7 +334,7 @@ public class QueryTestCase {
}
@Test
- public void testQueryProfileSubstitution2() {
+ void testQueryProfileSubstitution2() {
QueryProfile profile = new QueryProfile("myProfile");
profile.set("model.language", "en-US", null);
profile.set("myField", "Language: %{lang}", null);
@@ -350,7 +343,7 @@ public class QueryTestCase {
}
@Test
- public void testQueryProfileSubstitution3() {
+ void testQueryProfileSubstitution3() {
QueryProfile profile = new QueryProfile("myProfile");
profile.set("model.locale", "en-US", null);
profile.set("myField", "Language: %{lang}, locale: %{locale}", null);
@@ -359,7 +352,7 @@ public class QueryTestCase {
}
@Test
- public void testTimeoutInRequestOverridesQueryProfile() {
+ void testTimeoutInRequestOverridesQueryProfile() {
QueryProfile profile = new QueryProfile("test");
profile.set("timeout", 318, null);
Query q = new Query(QueryTestCase.httpEncode("/search?timeout=500"), profile.compile(null));
@@ -367,7 +360,7 @@ public class QueryTestCase {
}
@Test
- public void testQueryProfileClearAndSet() {
+ void testQueryProfileClearAndSet() {
QueryProfile profile = new QueryProfile("myProfile");
profile.set("b", "b-value", null);
Query q = new Query(QueryTestCase.httpEncode("/search?queryProfile=myProfile"), profile.compile(null));
@@ -375,7 +368,7 @@ public class QueryTestCase {
assertContains(q.properties().listProperties("b"), "b-value");
q.properties().set("b", null, null);
- assertContains(q.properties().listProperties("b"), (Object)null);
+ assertContains(q.properties().listProperties("b"), (Object) null);
q.properties().set("b", "b-value", null);
assertEquals("b-value", q.properties().get("b"));
@@ -383,7 +376,7 @@ public class QueryTestCase {
}
@Test
- public void testQueryProfileClearValue() {
+ void testQueryProfileClearValue() {
QueryProfile profile = new QueryProfile("myProfile");
profile.set("a", "a-value", null);
profile.set("b", "b-value", null);
@@ -397,10 +390,10 @@ public class QueryTestCase {
assertContains(q.properties().listProperties("b"), "b-value", "b.c-value", "b.d-value");
q.properties().set("a", null, null);
- assertEquals(null, q.properties().get("a"));
+ assertNull(q.properties().get("a"));
q.properties().set("b", null, null);
- assertEquals(null, q.properties().get("b"));
+ assertNull(q.properties().get("b"));
assertEquals("b.c-value", q.properties().get("b.c"));
assertEquals("b.d-value", q.properties().get("b.d"));
assertContains(q.properties().listProperties("b"), null, "b.c-value", "b.d-value");
@@ -413,67 +406,67 @@ public class QueryTestCase {
assertContains(q.properties().listProperties("b"), "b-value", "b.c-value", "b.d-value", "b.e-value", "b.f-value");
q.properties().clearAll("b");
- assertEquals(null, q.properties().get("b"));
- assertEquals(null, q.properties().get("b.c"));
- assertEquals(null, q.properties().get("b.d"));
- assertEquals(null, q.properties().get("b.e"));
- assertEquals(null, q.properties().get("b.f"));
- assertContains(q.properties().listProperties("b"), (Object)null);
+ assertNull(q.properties().get("b"));
+ assertNull(q.properties().get("b.c"));
+ assertNull(q.properties().get("b.d"));
+ assertNull(q.properties().get("b.e"));
+ assertNull(q.properties().get("b.f"));
+ assertContains(q.properties().listProperties("b"), (Object) null);
}
@Test
- public void testNotEqual() {
+ void testNotEqual() {
Query q = new Query("/?query=something+test&nocache");
Query p = new Query("/?query=something+test");
- assertEquals(q,p);
- assertEquals(q.hashCode(),p.hashCode());
+ assertEquals(q, p);
+ assertEquals(q.hashCode(), p.hashCode());
Query r = new Query("?query=something+test&hits=5");
- assertNotSame(q,r);
- assertNotSame(q.hashCode(),r.hashCode());
+ assertNotSame(q, r);
+ assertNotSame(q.hashCode(), r.hashCode());
}
@Test
- public void testEqual() {
- assertEquals(new Query("?query=12").hashCode(),new Query("?query=12").hashCode());
- assertEquals(new Query("?query=12"),new Query("?query=12"));
+ void testEqual() {
+ assertEquals(new Query("?query=12").hashCode(), new Query("?query=12").hashCode());
+ assertEquals(new Query("?query=12"), new Query("?query=12"));
}
@Test
- public void testUtf8Decoding() {
+ void testUtf8Decoding() {
Query q = new Query("/?query=beyonc%C3%A9");
assertEquals("WEAKAND(100) beyonc\u00e9", q.getModel().getQueryTree().toString());
}
@Test
- public void testQueryProfileInSubstitution() {
+ void testQueryProfileInSubstitution() {
QueryProfile testProfile = new QueryProfile("test");
testProfile.setOverridable("u", false, DimensionValues.empty);
- testProfile.set("d","e", null);
- testProfile.set("u","11", null);
+ testProfile.set("d", "e", null);
+ testProfile.set("u", "11", null);
testProfile.set("foo.bar", "wiz", null);
Query q = new Query(QueryTestCase.httpEncode("?query=a:>5&a=b&traceLevel=5&sources=a,b&u=12&foo.bar2=wiz2&c.d=foo&queryProfile=test"),
- testProfile.compile(null));
+ testProfile.compile(null));
String trace = q.getContext(false).getTrace().toString();
String[] traceLines = trace.split("\n");
}
@Test
- public void testDefaultIndex() {
+ void testDefaultIndex() {
Query q = new Query("?query=hi%20hello%20keyword:kanoo%20" +
- "default:munkz%20%22phrases+too%22&default-index=def");
+ "default:munkz%20%22phrases+too%22&default-index=def");
assertEquals("WEAKAND(100) def:hi def:hello keyword:kanoo default:munkz def:\"phrases too\"",
- q.getModel().getQueryTree().toString());
+ q.getModel().getQueryTree().toString());
}
@Test
- public void testHashCode() {
+ void testHashCode() {
Query p = new Query("?query=foo&type=any");
Query q = new Query("?query=foo&type=all");
assertTrue(p.hashCode() != q.hashCode());
}
@Test
- public void testSimpleQueryParsing() {
+ void testSimpleQueryParsing() {
Query q = new Query("/search?query=foobar&offset=10&hits=20");
assertEquals("WEAKAND(100) foobar", q.getModel().getQueryTree().toString());
assertEquals(10, q.getOffset());
@@ -482,15 +475,15 @@ public class QueryTestCase {
/** "input.*" is an alias for "ranking.feature.*", but just "input" is not */
@Test
- public void testPrefixAlias() {
+ void testPrefixAlias() {
Query q = new Query("/search?query=foobar&input=foo",
- new QueryProfile("test").compile(null));
+ new QueryProfile("test").compile(null));
assertEquals("foo", q.properties().get("input"));
}
/** Test that GET parameter names are case in-sensitive */
@Test
- public void testGETParametersCase() {
+ void testGETParametersCase() {
Query q = new Query("?QUERY=testing&hits=10&oFfSeT=10");
assertEquals("testing", q.getModel().getQueryString());
assertEquals(10, q.getHits());
@@ -499,19 +492,19 @@ public class QueryTestCase {
/** Test that we get the last value if a parameter is assigned multiple times */
@Test
- public void testRepeatedParameter() {
+ void testRepeatedParameter() {
Query q = new Query("?query=test&hits=5&hits=10");
assertEquals(10, q.getHits());
}
@Test
- public void testNoCache() {
+ void testNoCache() {
Query q = new Query("search?query=foobar&nocache");
assertTrue(q.getNoCache());
}
@Test
- public void testSessionCache() {
+ void testSessionCache() {
Query q = new Query("search?query=foobar&groupingSessionCache");
assertTrue(q.getGroupingSessionCache());
q = new Query("search?query=foobar");
@@ -531,7 +524,7 @@ public class QueryTestCase {
}
@Test
- public void testSetting() {
+ void testSetting() {
Query q = new Query();
q.properties().set("test", "test");
assertEquals(q.properties().get("test"), "test");
@@ -544,21 +537,21 @@ public class QueryTestCase {
}
@Test
- public void testAlias() {
+ void testAlias() {
Query q = new Query("search?query=testing&language=en");
assertEquals(q.getModel().getLanguage(), q.properties().get("model.language"));
}
@Test
- public void testTracing() {
+ void testTracing() {
Query q = new Query("?query=foo&type=all&traceLevel=2");
assertEquals(2, q.getTrace().getLevel());
q.trace(true, 1, "trace1");
- q.trace(false,2, "trace2");
+ q.trace(false, 2, "trace2");
q.trace(true, 3, "Ignored");
q.trace(true, 2, "trace3-1", ", ", "trace3-2");
- q.trace(false,1, "trace4-1", ", ", "trace4-2");
- q.trace(false,3, "Ignored-1", "Ignored-2");
+ q.trace(false, 1, "trace4-1", ", ", "trace4-2");
+ q.trace(false, 3, "Ignored-1", "Ignored-2");
Set<String> traces = new HashSet<>();
for (String trace : q.getContext(true).getTrace().traceNode().descendants(String.class))
traces.add(trace);
@@ -569,10 +562,10 @@ public class QueryTestCase {
}
@Test
- public void testNullTracing() {
+ void testNullTracing() {
Query q = new Query("?query=foo&traceLevel=2");
assertEquals(2, q.getTrace().getLevel());
- q.trace(false,2, "trace2 ", null);
+ q.trace(false, 2, "trace2 ", null);
Set<String> traces = new HashSet<>();
for (String trace : q.getContext(true).getTrace().traceNode().descendants(String.class))
traces.add(trace);
@@ -580,20 +573,20 @@ public class QueryTestCase {
}
@Test
- public void testExplain() {
+ void testExplain() {
Query q = new Query("?query=foo&explainLevel=2");
assertEquals(2, q.getTrace().getExplainLevel());
assertEquals(0, q.getTrace().getLevel());
}
@Test
- public void testQueryPropertyResolveTracing() {
+ void testQueryPropertyResolveTracing() {
QueryProfile testProfile = new QueryProfile("test");
testProfile.setOverridable("u", false, DimensionValues.empty);
- testProfile.set("d","e", null);
- testProfile.set("u","11", null);
+ testProfile.set("d", "e", null);
+ testProfile.set("u", "11", null);
testProfile.set("foo.bar", "wiz", null);
- Query q = new Query(QueryTestCase.httpEncode("?query=a:>5&a=b&traceLevel=5&sources=a,b&u=12&foo.bar2=wiz2&c.d=foo&queryProfile=test"),testProfile.compile(null));
+ Query q = new Query(QueryTestCase.httpEncode("?query=a:>5&a=b&traceLevel=5&sources=a,b&u=12&foo.bar2=wiz2&c.d=foo&queryProfile=test"), testProfile.compile(null));
String trace = q.getContext(false).getTrace().toString();
String[] traceLines = trace.split("\n");
assertTrue(contains("query: a:>5 (from request)", traceLines));
@@ -605,7 +598,7 @@ public class QueryTestCase {
}
@Test
- public void testNonleafInRequestDoesNotOverrideProfile() {
+ void testNonleafInRequestDoesNotOverrideProfile() {
QueryProfile testProfile = new QueryProfile("test");
testProfile.set("a.b", "foo", null);
testProfile.freeze();
@@ -622,7 +615,7 @@ public class QueryTestCase {
}
@Test
- public void testQueryPropertyResolveTracing2() {
+ void testQueryPropertyResolveTracing2() {
QueryProfile defaultProfile = new QueryProfile("default");
defaultProfile.freeze();
Query q = new Query(QueryTestCase.httpEncode("?query=dvd&a.b=foo&tracelevel=9"), defaultProfile.compile(null));
@@ -633,7 +626,7 @@ public class QueryTestCase {
}
@Test
- public void testNativeProperties() {
+ void testNativeProperties() {
Set<String> nativeProperties = Query.nativeProperties.stream().map(CompoundName::toString).collect(Collectors.toSet());
// Sample the content
assertTrue(nativeProperties.contains("hits"));
@@ -642,16 +635,16 @@ public class QueryTestCase {
}
@Test
- public void testQueryPropertyListingAndTrace() {
+ void testQueryPropertyListingAndTrace() {
QueryProfile defaultProfile = new QueryProfile("default");
defaultProfile.setDimensions(new String[]{"x"});
- defaultProfile.set("a.b","a.b-x1-value", new String[] {"x1"}, null);
+ defaultProfile.set("a.b", "a.b-x1-value", new String[]{"x1"}, null);
defaultProfile.set("a.b", "a.b-x2-value", new String[]{"x2"}, null);
defaultProfile.freeze();
{
- Query q = new Query(QueryTestCase.httpEncode("?tracelevel=9&x=x1"),defaultProfile.compile(null));
- Map<String,Object> propertyList = q.properties().listProperties();
+ Query q = new Query(QueryTestCase.httpEncode("?tracelevel=9&x=x1"), defaultProfile.compile(null));
+ Map<String, Object> propertyList = q.properties().listProperties();
assertEquals("a.b-x1-value", propertyList.get("a.b"));
String trace = q.getContext(false).getTrace().toString();
String[] traceLines = trace.split("\n");
@@ -660,14 +653,14 @@ public class QueryTestCase {
{
Query q = new Query(QueryTestCase.httpEncode("?tracelevel=9&x=x1"), defaultProfile.compile(null));
- Map<String,Object> propertyList = q.properties().listProperties("a");
+ Map<String, Object> propertyList = q.properties().listProperties("a");
assertEquals(1, propertyList.size());
assertEquals("a.b-x1-value", propertyList.get("b"));
}
{
- Query q = new Query(QueryTestCase.httpEncode("?tracelevel=9&x=x2"),defaultProfile.compile(null));
- Map<String,Object> propertyList = q.properties().listProperties();
+ Query q = new Query(QueryTestCase.httpEncode("?tracelevel=9&x=x2"), defaultProfile.compile(null));
+ Map<String, Object> propertyList = q.properties().listProperties();
assertEquals("a.b-x2-value", propertyList.get("a.b"));
String trace = q.getContext(false).getTrace().toString();
String[] traceLines = trace.split("\n");
@@ -676,45 +669,45 @@ public class QueryTestCase {
}
@Test
- public void testQueryPropertyListingThreeLevel() {
+ void testQueryPropertyListingThreeLevel() {
QueryProfile defaultProfile = new QueryProfile("default");
- defaultProfile.setDimensions(new String[] {"x"});
+ defaultProfile.setDimensions(new String[]{"x"});
defaultProfile.set("a.b.c", "a.b.c-x1-value", new String[]{"x1"}, null);
defaultProfile.set("a.b.c", "a.b.c-x2-value", new String[]{"x2"}, null);
defaultProfile.freeze();
{
- Query q = new Query(QueryTestCase.httpEncode("?tracelevel=9&x=x1"),defaultProfile.compile(null));
- Map<String,Object> propertyList = q.properties().listProperties();
+ Query q = new Query(QueryTestCase.httpEncode("?tracelevel=9&x=x1"), defaultProfile.compile(null));
+ Map<String, Object> propertyList = q.properties().listProperties();
assertEquals("a.b.c-x1-value", propertyList.get("a.b.c"));
}
{
- Query q = new Query(QueryTestCase.httpEncode("?tracelevel=9&x=x1"),defaultProfile.compile(null));
- Map<String,Object> propertyList = q.properties().listProperties("a");
+ Query q = new Query(QueryTestCase.httpEncode("?tracelevel=9&x=x1"), defaultProfile.compile(null));
+ Map<String, Object> propertyList = q.properties().listProperties("a");
assertEquals(1, propertyList.size());
assertEquals("a.b.c-x1-value", propertyList.get("b.c"));
}
{
- Query q = new Query(QueryTestCase.httpEncode("?tracelevel=9&x=x1"),defaultProfile.compile(null));
- Map<String,Object> propertyList = q.properties().listProperties("a.b");
+ Query q = new Query(QueryTestCase.httpEncode("?tracelevel=9&x=x1"), defaultProfile.compile(null));
+ Map<String, Object> propertyList = q.properties().listProperties("a.b");
assertEquals(1, propertyList.size());
assertEquals("a.b.c-x1-value", propertyList.get("c"));
}
{
- Query q = new Query(QueryTestCase.httpEncode("?tracelevel=9&x=x2"),defaultProfile.compile(null));
- Map<String,Object> propertyList = q.properties().listProperties();
+ Query q = new Query(QueryTestCase.httpEncode("?tracelevel=9&x=x2"), defaultProfile.compile(null));
+ Map<String, Object> propertyList = q.properties().listProperties();
assertEquals("a.b.c-x2-value", propertyList.get("a.b.c"));
}
}
@Test
- public void testQueryPropertyReplacement() {
+ void testQueryPropertyReplacement() {
QueryProfile defaultProfile = new QueryProfile("default");
- defaultProfile.set("model.queryString","myquery", null);
- defaultProfile.set("queryUrl","http://provider:80?query=%{model.queryString}", null);
+ defaultProfile.set("model.queryString", "myquery", null);
+ defaultProfile.set("queryUrl", "http://provider:80?query=%{model.queryString}", null);
defaultProfile.freeze();
Query q1 = new Query(QueryTestCase.httpEncode(""), defaultProfile.compile(null));
@@ -725,17 +718,17 @@ public class QueryTestCase {
assertEquals("foo", q2.getModel().getQueryString());
assertEquals("http://provider:80?query=foo", q2.properties().get("queryUrl"));
- Query q3 = new Query(QueryTestCase.httpEncode("?query=foo"),defaultProfile.compile(null));
- assertEquals("foo",q3.getModel().getQueryString());
- assertEquals("http://provider:80?query=foo",q3.properties().get("queryUrl"));
+ Query q3 = new Query(QueryTestCase.httpEncode("?query=foo"), defaultProfile.compile(null));
+ assertEquals("foo", q3.getModel().getQueryString());
+ assertEquals("http://provider:80?query=foo", q3.properties().get("queryUrl"));
- Query q4 = new Query(QueryTestCase.httpEncode("?query=foo"),defaultProfile.compile(null));
+ Query q4 = new Query(QueryTestCase.httpEncode("?query=foo"), defaultProfile.compile(null));
q4.getModel().setQueryString("bar");
- assertEquals("http://provider:80?query=bar",q4.properties().get("queryUrl"));
+ assertEquals("http://provider:80?query=bar", q4.properties().get("queryUrl"));
}
@Test
- public void testNoQueryString() {
+ void testNoQueryString() {
Query q = new Query(httpEncode("?tracelevel=1"));
Chain<Searcher> chain = new Chain<>(new RandomSearcher());
new Execution(chain, Execution.Context.createContextStub()).search(q);
@@ -743,7 +736,7 @@ public class QueryTestCase {
}
@Test
- public void testSetCollapseField() {
+ void testSetCollapseField() {
Query q = new Query(httpEncode("?collapsefield=foo&presentation.format=tiled"));
assertEquals("foo", q.properties().get("collapsefield"));
assertEquals("tiled", q.properties().get("presentation.format"));
@@ -751,44 +744,44 @@ public class QueryTestCase {
}
@Test
- public void testSetNullProperty() {
+ void testSetNullProperty() {
QueryProfile profile = new QueryProfile("test");
- profile.set("property","initialValue", null);
+ profile.set("property", "initialValue", null);
Query query = new Query(httpEncode("?query=test"), profile.compile(null));
- assertEquals("initialValue",query.properties().get("property"));
+ assertEquals("initialValue", query.properties().get("property"));
query.properties().set("property", null);
assertNull(query.properties().get("property"));
}
@Test
- public void testSetNullPropertyNoQueryProfile() {
+ void testSetNullPropertyNoQueryProfile() {
Query query = new Query();
query.properties().set("a", null);
assertNull(query.properties().get("a"));
}
@Test
- public void testMissingParameter() {
+ void testMissingParameter() {
Query q = new Query("?query=foo&hits=");
assertEquals(0, q.errors().size());
}
@Test
- public void testModelProperties() {
+ void testModelProperties() {
{
Query query = new Query();
query.properties().set("model.searchPath", "foo");
- assertEquals("Set dynamic get dynamic works","foo", query.properties().get("model.searchPath"));
- assertEquals("Set dynamic get static works","foo", query.getModel().getSearchPath());
+ assertEquals("foo", query.properties().get("model.searchPath"), "Set dynamic get dynamic works");
+ assertEquals("foo", query.getModel().getSearchPath(), "Set dynamic get static works");
Map<String, Object> properties = query.properties().listProperties();
- assertEquals("Listing built-in properties works", "foo", properties.get("model.searchPath"));
+ assertEquals("foo", properties.get("model.searchPath"), "Listing built-in properties works");
}
{
Query query = new Query();
query.getModel().setSearchPath("foo");
- assertEquals("Set static get dynamic works","foo", query.properties().get("model.searchPath"));
- assertEquals("Set static get static works","foo", query.getModel().getSearchPath());
+ assertEquals("foo", query.properties().get("model.searchPath"), "Set static get dynamic works");
+ assertEquals("foo", query.getModel().getSearchPath(), "Set static get static works");
}
{
@@ -801,7 +794,7 @@ public class QueryTestCase {
}
@Test
- public void testThatSessionIdIsUniquePerQuery() {
+ void testThatSessionIdIsUniquePerQuery() {
Query q = new Query();
assertNull(q.getSessionId());
assertNull(q.getSessionId());
@@ -816,8 +809,9 @@ public class QueryTestCase {
assertNotEquals(q.getSessionId(), q2.getSessionId("node-0"));
assertNotEquals(q.getSessionId().toString(), q2.getSessionId("node-0").toString());
}
+
@Test
- public void testThatCloneGetANewSessionId() {
+ void testThatCloneGetANewSessionId() {
Query q = new Query();
q.getSessionId("node-0");
Query clonedQ = q.clone();
@@ -826,7 +820,7 @@ public class QueryTestCase {
}
@Test
- public void testThatSessionIdIsUniquePerRankProfilePerQuery() {
+ void testThatSessionIdIsUniquePerRankProfilePerQuery() {
Query q = new Query();
SessionId s1 = q.getSessionId("node-0");
q.getRanking().setProfile("my-profile");
@@ -835,7 +829,7 @@ public class QueryTestCase {
}
@Test
- public void testThatSessionIdIsNotSharedIfCreatedAfterClone() {
+ void testThatSessionIdIsNotSharedIfCreatedAfterClone() {
Query q = new Query();
Query q2 = q.clone();
assertNull(q.getSessionId());
@@ -849,7 +843,7 @@ public class QueryTestCase {
}
@Test
- public void testPositiveTerms() {
+ void testPositiveTerms() {
Query q = new Query(httpEncode("/?query=-a \"b c\" d e"));
Item i = q.getModel().getQueryTree().getRoot();
List<IndexedItem> l = QueryTree.getPositiveTerms(i);
@@ -857,18 +851,18 @@ public class QueryTestCase {
}
@Test
- public void testHeuristicLanguageDetectionTextExtraction() {
+ void testHeuristicLanguageDetectionTextExtraction() {
assertDetectionText("b ", "a:b", "text:a", "text:default");
assertDetectionText("b ", "b", "text:default");
- assertDetectionText("b ", "b","text:b", "text:default");
- assertDetectionText("a b ", "a:b","text:b", "text:default");
- assertDetectionText("foo bar fuz ", "foo a:bar --() fuz","text:a", "text:default");
- assertDetectionText(" 彭 博士 觀 風向 彭 博士 觀 風向 彭 博士 觀 風向 ","headline:\"彭 博士 觀 風向\" content:\"彭 博士 觀 風向\" description:\"彭 博士 觀 風向\" sddocname:contentindexing!0 embargo:<1484665288753!0 expires:>1484665288753!0",
- "text:headline", "text:content", "text:description", "text:default", "nontext:tags", "nontext:sddocname", "nontext:embargo", "nontext:expires");
+ assertDetectionText("b ", "b", "text:b", "text:default");
+ assertDetectionText("a b ", "a:b", "text:b", "text:default");
+ assertDetectionText("foo bar fuz ", "foo a:bar --() fuz", "text:a", "text:default");
+ assertDetectionText(" 彭 博士 觀 風向 彭 博士 觀 風向 彭 博士 觀 風向 ", "headline:\"彭 博士 觀 風向\" content:\"彭 博士 觀 風向\" description:\"彭 博士 觀 風向\" sddocname:contentindexing!0 embargo:<1484665288753!0 expires:>1484665288753!0",
+ "text:headline", "text:content", "text:description", "text:default", "nontext:tags", "nontext:sddocname", "nontext:embargo", "nontext:expires");
}
@Test
- public void testCompositeChildVerification() {
+ void testCompositeChildVerification() {
CompositeItem root = new AndItem();
try {
root.addItem(null);
@@ -908,7 +902,7 @@ public class QueryTestCase {
}
@Test
- public void queryLanguageAlternatives() {
+ void queryLanguageAlternatives() {
// Given:
// Person = {
// Name: 'Joe',
@@ -967,13 +961,13 @@ public class QueryTestCase {
}
@Test
- public void testImplicitPhraseIsDefault() {
+ void testImplicitPhraseIsDefault() {
Query query = new Query(httpEncode("?query=it's fine"));
assertEquals("WEAKAND(100) (SAND it s) fine", query.getModel().getQueryTree().toString());
}
@Test
- public void testImplicitPhrase() {
+ void testImplicitPhrase() {
Query query = new Query(httpEncode("?query=myfield:it's myfield:a.b myfield:c&type=all"));
SearchDefinition test = new SearchDefinition("test");
@@ -988,7 +982,7 @@ public class QueryTestCase {
}
@Test
- public void testImplicitAnd() {
+ void testImplicitAnd() {
Query query = new Query(httpEncode("?query=myfield:it's myfield:a.b myfield:c"));
SearchDefinition test = new SearchDefinition("test");
@@ -1001,18 +995,18 @@ public class QueryTestCase {
assertEquals("WEAKAND(100) (SAND myfield:it myfield:s) (AND myfield:a myfield:b) myfield:c", query.getModel().getQueryTree().toString());
// 'it' and 's' should have connectivity 1
- WeakAndItem root = (WeakAndItem)query.getModel().getQueryTree().getRoot();
- AndSegmentItem sand = (AndSegmentItem)root.getItem(0);
- WordItem it = (WordItem)sand.getItem(0);
+ WeakAndItem root = (WeakAndItem) query.getModel().getQueryTree().getRoot();
+ AndSegmentItem sand = (AndSegmentItem) root.getItem(0);
+ WordItem it = (WordItem) sand.getItem(0);
assertEquals("it", it.getWord());
- WordItem s = (WordItem)sand.getItem(1);
+ WordItem s = (WordItem) sand.getItem(1);
assertEquals("s", s.getWord());
assertEquals(s, it.getConnectedItem());
assertEquals(1.0, it.getConnectivity(), 0.00000001);
}
@Test
- public void testImplicitAndConnectivity() {
+ void testImplicitAndConnectivity() {
SearchDefinition test = new SearchDefinition("test");
Index myField = new Index("myfield");
myField.addCommand("phrase-segmenting false");
@@ -1024,7 +1018,7 @@ public class QueryTestCase {
query.getModel().setExecution(new Execution(Execution.Context.createContextStub(new IndexFacts(indexModel))));
assertEquals("WEAKAND(100) (AND myfield:b myfield:c myfield:d)", query.getModel().getQueryTree().toString());
WeakAndItem root = (WeakAndItem) query.getModel().getQueryTree().getRoot();
- AndItem and = (AndItem)root.getItem(0);
+ AndItem and = (AndItem) root.getItem(0);
WordItem b = (WordItem) and.getItem(0);
WordItem c = (WordItem) and.getItem(1);
WordItem d = (WordItem) and.getItem(2);
@@ -1040,7 +1034,7 @@ public class QueryTestCase {
assertEquals("WEAKAND(100) myfield:a (AND myfield:b myfield:c myfield:d) myfield:e", query.getModel().getQueryTree().toString());
WeakAndItem root = (WeakAndItem) query.getModel().getQueryTree().getRoot();
WordItem a = (WordItem) root.getItem(0);
- AndItem and = (AndItem)root.getItem(1);
+ AndItem and = (AndItem) root.getItem(1);
WordItem b = (WordItem) and.getItem(0);
WordItem c = (WordItem) and.getItem(1);
WordItem d = (WordItem) and.getItem(2);
@@ -1056,7 +1050,7 @@ public class QueryTestCase {
}
@Test
- public void testImplicitAndInPhrase() {
+ void testImplicitAndInPhrase() {
Query query = new Query(httpEncode("?query=myfield:\"it's fine\""));
SearchDefinition test = new SearchDefinition("test");
@@ -1071,7 +1065,7 @@ public class QueryTestCase {
}
@Test
- public void testOldStyleSelect() {
+ void testOldStyleSelect() {
// The same as testOldStyleSelectAndNativeQueryProfileType but not inheriting native
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfileType type = new QueryProfileType("mytype");
@@ -1081,15 +1075,15 @@ public class QueryTestCase {
registry.getTypeRegistry().register(type);
CompiledQueryProfileRegistry cRegistry = registry.compile();
Query query = new Query(httpEncode("?query=sddocname:sentence&select=all(group(context_id) max(10) each(each(output(summary()))))"),
- cRegistry.findQueryProfile("default"));
+ cRegistry.findQueryProfile("default"));
GroupingQueryParser parser = new GroupingQueryParser();
parser.search(query, new Execution(parser, Execution.Context.createContextStub()));
assertEquals("[all(group(context_id) max(10) each(each(output(summary())))), all(group(context_id) max(10) each(each(output(summary()))))]",
- query.getSelect().getGrouping().toString());
+ query.getSelect().getGrouping().toString());
}
@Test
- public void testOldStyleSelectAndNativeQueryProfileType() {
+ void testOldStyleSelectAndNativeQueryProfileType() {
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfileType type = new QueryProfileType("mytype");
type.inherited().add(registry.getType("native"));
@@ -1099,11 +1093,11 @@ public class QueryTestCase {
registry.getTypeRegistry().register(type);
CompiledQueryProfileRegistry cRegistry = registry.compile();
Query query = new Query(httpEncode("?query=sddocname:sentence&select=all(group(context_id) max(10) each(each(output(summary()))))"),
- cRegistry.findQueryProfile("default"));
+ cRegistry.findQueryProfile("default"));
GroupingQueryParser parser = new GroupingQueryParser();
parser.search(query, new Execution(parser, Execution.Context.createContextStub()));
assertEquals("[all(group(context_id) max(10) each(each(output(summary())))), all(group(context_id) max(10) each(each(output(summary()))))]",
- query.getSelect().getGrouping().toString());
+ query.getSelect().getGrouping().toString());
}
/**
@@ -1111,7 +1105,7 @@ public class QueryTestCase {
* This is special because presentation.format is a native query profile.
*/
@Test
- public void testSettingNativeQueryProfileValueInQueryProfile() {
+ void testSettingNativeQueryProfileValueInQueryProfile() {
{
QueryProfileRegistry registry = new QueryProfileRegistry();
QueryProfile profile = new QueryProfile("default");
@@ -1140,7 +1134,7 @@ public class QueryTestCase {
type.inherited().add(registry.getType("native"));
registry.getTypeRegistry().register(type);
type.addField(new FieldDescription("ranking.features.query(embedding)", "tensor(x[5])"),
- registry.getTypeRegistry());
+ registry.getTypeRegistry());
QueryProfile profile = new QueryProfile("default");
profile.setType(type);
registry.register(profile);
@@ -1169,13 +1163,12 @@ public class QueryTestCase {
private void assertContains(Map<String, Object> properties, Object ... expectedValues) {
if (expectedValues == null) {
assertEquals(1, properties.size());
- assertTrue("Contains value null", properties.containsValue(null));
+ assertTrue(properties.containsValue(null), "Contains value null");
}
else {
- assertEquals(properties + " contains values " + Arrays.toString(expectedValues),
- expectedValues.length, properties.size());
+ assertEquals(expectedValues.length, properties.size(), properties + " contains values " + Arrays.toString(expectedValues));
for (Object expectedValue : expectedValues)
- assertTrue("Contains value " + expectedValue, properties.containsValue(expectedValue));
+ assertTrue(properties.containsValue(expectedValue), "Contains value " + expectedValue);
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/test/RequestParameterPreservationTestCase.java b/container-search/src/test/java/com/yahoo/search/test/RequestParameterPreservationTestCase.java
index cc47ec813df..a1f3a3a5a1c 100644
--- a/container-search/src/test/java/com/yahoo/search/test/RequestParameterPreservationTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/test/RequestParameterPreservationTestCase.java
@@ -2,9 +2,9 @@
package com.yahoo.search.test;
import com.yahoo.search.Query;
-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 bratseth
@@ -12,14 +12,14 @@ import static org.junit.Assert.assertEquals;
public class RequestParameterPreservationTestCase {
@Test
- public void testPreservation() {
- Query query=new Query("?query=test...&offset=15&hits=10");
- query.setWindow(25,13);
- assertEquals(25,query.getOffset());
- assertEquals(13,query.getHits());
+ void testPreservation() {
+ Query query = new Query("?query=test...&offset=15&hits=10");
+ query.setWindow(25, 13);
+ assertEquals(25, query.getOffset());
+ assertEquals(13, query.getHits());
assertEquals("15", query.getHttpRequest().getProperty("offset"));
assertEquals("10", query.getHttpRequest().getProperty("hits"));
- assertEquals("test...",query.getHttpRequest().getProperty("query"));
+ assertEquals("test...", query.getHttpRequest().getProperty("query"));
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/yql/FieldFilterTestCase.java b/container-search/src/test/java/com/yahoo/search/yql/FieldFilterTestCase.java
index 8a6a48afd9f..3d4f52472a8 100644
--- a/container-search/src/test/java/com/yahoo/search/yql/FieldFilterTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/yql/FieldFilterTestCase.java
@@ -1,13 +1,11 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.yql;
-import static org.junit.Assert.*;
-
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import static org.junit.jupiter.api.Assertions.*;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import com.yahoo.component.chain.Chain;
import com.yahoo.prelude.fastsearch.FastHit;
import com.yahoo.search.Query;
@@ -31,7 +29,7 @@ public class FieldFilterTestCase {
private Execution.Context context;
private Execution execution;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
Query query = new Query("?query=test");
@@ -58,7 +56,7 @@ public class FieldFilterTestCase {
return h;
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
searchChain = null;
context = null;
@@ -66,7 +64,7 @@ public class FieldFilterTestCase {
}
@Test
- public final void testBasic() {
+ final void testBasic() {
final Query query = new Query("?query=test&presentation.summaryFields=" + FIELD_B);
Result result = execution.search(query);
execution.fill(result);
@@ -77,7 +75,7 @@ public class FieldFilterTestCase {
}
@Test
- public final void testNoFiltering() {
+ final void testNoFiltering() {
final Query query = new Query("?query=test");
Result result = execution.search(query);
execution.fill(result);
diff --git a/container-search/src/test/java/com/yahoo/search/yql/MinimalQueryInserterTestCase.java b/container-search/src/test/java/com/yahoo/search/yql/MinimalQueryInserterTestCase.java
index 1ef9fe5832f..1e6e29bb700 100644
--- a/container-search/src/test/java/com/yahoo/search/yql/MinimalQueryInserterTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/yql/MinimalQueryInserterTestCase.java
@@ -18,19 +18,17 @@ import com.yahoo.search.query.Sorting.UcaSorter;
import com.yahoo.search.result.ErrorMessage;
import com.yahoo.search.searchchain.Execution;
import org.apache.http.client.utils.URIBuilder;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
-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.*;
/**
* Smoke test for first generation YQL+ integration.
@@ -41,14 +39,14 @@ public class MinimalQueryInserterTestCase {
private Execution.Context context;
private Execution execution;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
searchChain = new Chain<>(new MinimalQueryInserter());
context = Execution.Context.createContextStub();
execution = new Execution(searchChain, context);
}
- @After
+ @AfterEach
public void tearDown() {
searchChain = null;
context = null;
@@ -56,7 +54,7 @@ public class MinimalQueryInserterTestCase {
}
@Test
- public void requireThatGroupingStepsAreAttachedToQuery() {
+ void requireThatGroupingStepsAreAttachedToQuery() {
URIBuilder builder = new URIBuilder();
builder.setPath("search/");
@@ -70,24 +68,24 @@ public class MinimalQueryInserterTestCase {
assertEquals("foo", query.getPresentation().getSummaryFields().toArray(new String[1])[0]);
builder.setParameter("yql", "select foo from bar where baz contains 'cox' " +
- "| all(group(a) each(output(count())))");
+ "| all(group(a) each(output(count())))");
query = new Query(builder.toString());
execution.search(query);
assertEquals("baz:cox", query.getModel().getQueryTree().toString());
assertGrouping("[[]all(group(a) each(output(count())))]", query);
builder.setParameter("yql", "select foo from bar where baz contains 'cox' " +
- "| all(group(a) each(output(count()))) " +
- "| all(group(b) each(output(count())))");
+ "| all(group(a) each(output(count()))) " +
+ "| all(group(b) each(output(count())))");
query = new Query(builder.toString());
execution.search(query);
assertEquals("baz:cox", query.getModel().getQueryTree().toString());
assertGrouping("[[]all(group(a) each(output(count())))," +
- " []all(group(b) each(output(count())))]", query);
+ " []all(group(b) each(output(count())))]", query);
}
@Test
- public void requireThatGroupingContinuationsAreAttachedToQuery() {
+ void requireThatGroupingContinuationsAreAttachedToQuery() {
URIBuilder builder = new URIBuilder();
builder.setPath("search/");
@@ -98,36 +96,36 @@ public class MinimalQueryInserterTestCase {
assertGrouping("[]", query);
builder.setParameter("yql", "select foo from bar where baz contains 'cox' " +
- "| { continuations:['BCBCBCBEBG', 'BCBKCBACBKCCK'] }" +
- "all(group(a) each(output(count())))");
+ "| { continuations:['BCBCBCBEBG', 'BCBKCBACBKCCK'] }" +
+ "all(group(a) each(output(count())))");
query = new Query(builder.toString());
execution.search(query);
assertEquals("baz:cox", query.getModel().getQueryTree().toString());
assertGrouping("[[BCBCBCBEBG, BCBKCBACBKCCK]all(group(a) each(output(count())))]", query);
builder.setParameter("yql", "select foo from bar where baz contains 'cox' " +
- "| { continuations:['BCBCBCBEBG', 'BCBKCBACBKCCK'] }" +
- "all(group(a) each(output(count()))) " +
- "| { continuations:['BCBBBBBDBF', 'BCBJBPCBJCCJ'] }" +
- "all(group(b) each(output(count())))");
+ "| { continuations:['BCBCBCBEBG', 'BCBKCBACBKCCK'] }" +
+ "all(group(a) each(output(count()))) " +
+ "| { continuations:['BCBBBBBDBF', 'BCBJBPCBJCCJ'] }" +
+ "all(group(b) each(output(count())))");
query = new Query(builder.toString());
execution.search(query);
assertEquals("baz:cox", query.getModel().getQueryTree().toString());
assertGrouping("[[BCBCBCBEBG, BCBKCBACBKCCK]all(group(a) each(output(count())))," +
- " [BCBBBBBDBF, BCBJBPCBJCCJ]all(group(b) each(output(count())))]", query);
+ " [BCBBBBBDBF, BCBJBPCBJCCJ]all(group(b) each(output(count())))]", query);
}
- @Test
- @Ignore
// TODO: YQL work in progress (jon)
- public void testTmp() {
+ @Test
+ @Disabled
+ void testTmp() {
Query query = new Query("search/?query=easilyRecognizedString&yql=select%20ignoredfield%20from%20ignoredsource%20where%20title%20contains%20%22madonna%22%20and%20userQuery()");
//execution.search(query);
assertEquals("AND title:madonna easilyRecognizedString", query.getModel().getQueryTree().toString());
}
@Test
- public void testSearch() {
+ void testSearch() {
Query query = new Query("search/?query=easilyRecognizedString&yql=select%20ignoredfield%20from%20ignoredsource%20where%20title%20contains%20%22madonna%22%20and%20userQuery()");
execution.search(query);
assertEquals("AND title:madonna (WEAKAND(100) easilyRecognizedString)", query.getModel().getQueryTree().toString());
@@ -135,25 +133,25 @@ public class MinimalQueryInserterTestCase {
}
@Test
- public void testExplicitLanguageIsHonoredWithVerbatimQuery() {
+ void testExplicitLanguageIsHonoredWithVerbatimQuery() {
String japaneseWord = "\u30ab\u30bf\u30ab\u30ca";
Query query = new Query("search/?language=ja" + "&yql=select%20ignoredField%20from%20ignoredsource%20where%20title%20contains%20%22" + encode(japaneseWord) + "%22");
execution.search(query);
assertEquals(Language.JAPANESE, query.getModel().getParsingLanguage());
- assertEquals("title:"+ japaneseWord, query.getModel().getQueryTree().toString());
+ assertEquals("title:" + japaneseWord, query.getModel().getQueryTree().toString());
}
@Test
- public void testUserLanguageIsDetectedWithVerbatimQuery() {
+ void testUserLanguageIsDetectedWithVerbatimQuery() {
String japaneseWord = "\u30ab\u30bf\u30ab\u30ca";
Query query = new Query("search/?yql=select%20ignoredField%20from%20ignoredsource%20where%20title%20contains%20%22" + encode(japaneseWord) + "%22");
execution.search(query);
assertEquals(Language.JAPANESE, query.getModel().getParsingLanguage());
- assertEquals("title:"+ japaneseWord, query.getModel().getQueryTree().toString());
+ assertEquals("title:" + japaneseWord, query.getModel().getQueryTree().toString());
}
@Test
- public void testUserLanguageIsDetectedWithUserInput() {
+ void testUserLanguageIsDetectedWithUserInput() {
String japaneseWord = "\u30ab\u30bf\u30ab\u30ca";
Query query = new Query("search/?userString=" + encode(japaneseWord) + "&yql=select%20ignoredfield%20from%20ignoredsource%20where%20title%20contains%20%22madonna%22%20and%20userInput(@userString)");
execution.search(query);
@@ -162,7 +160,7 @@ public class MinimalQueryInserterTestCase {
}
@Test
- public void testUserLanguageIsDetectedWithUserQuery() {
+ void testUserLanguageIsDetectedWithUserQuery() {
String japaneseWord = "\u30ab\u30bf\u30ab\u30ca";
Query query = new Query("search/?query=" + encode(japaneseWord) + "&yql=select%20ignoredfield%20from%20ignoredsource%20where%20title%20contains%20%22madonna%22%20and%20userQuery()");
execution.search(query);
@@ -171,14 +169,14 @@ public class MinimalQueryInserterTestCase {
}
@Test
- public void testUserQueryFailsWithoutArgument() {
+ void testUserQueryFailsWithoutArgument() {
Query query = new Query("search/?query=easilyRecognizedString&yql=select%20ignoredfield%20from%20ignoredsource%20where%20title%20contains%20%22madonna%22%20and%20userQuery()");
execution.search(query);
assertEquals("AND title:madonna (WEAKAND(100) easilyRecognizedString)", query.getModel().getQueryTree().toString());
}
@Test
- public void testSearchFromAllSourcesWithUserSource() {
+ void testSearchFromAllSourcesWithUserSource() {
Query query = new Query("search/?query=easilyRecognizedString&sources=abc&yql=select%20ignoredfield%20from%20sources%20*%20where%20title%20contains%20%22madonna%22%20and%20userQuery()");
execution.search(query);
assertEquals("AND title:madonna (WEAKAND(100) easilyRecognizedString)", query.getModel().getQueryTree().toString());
@@ -186,7 +184,7 @@ public class MinimalQueryInserterTestCase {
}
@Test
- public void testSearchFromAllSourcesWithoutUserSource() {
+ void testSearchFromAllSourcesWithoutUserSource() {
Query query = new Query("search/?query=easilyRecognizedString&yql=select%20ignoredfield%20from%20sources%20*%20where%20title%20contains%20%22madonna%22%20and%20userQuery()");
execution.search(query);
assertEquals("AND title:madonna (WEAKAND(100) easilyRecognizedString)", query.getModel().getQueryTree().toString());
@@ -194,7 +192,7 @@ public class MinimalQueryInserterTestCase {
}
@Test
- public void testSearchFromSomeSourcesWithoutUserSource() {
+ void testSearchFromSomeSourcesWithoutUserSource() {
Query query = new Query("search/?query=easilyRecognizedString&yql=select%20ignoredfield%20from%20sources%20sourceA,%20sourceB%20where%20title%20contains%20%22madonna%22%20and%20userQuery()");
execution.search(query);
assertEquals("AND title:madonna (WEAKAND(100) easilyRecognizedString)", query.getModel().getQueryTree().toString());
@@ -204,7 +202,7 @@ public class MinimalQueryInserterTestCase {
}
@Test
- public void testSearchFromSomeSourcesWithUserSource() {
+ void testSearchFromSomeSourcesWithUserSource() {
Query query = new Query("search/?query=easilyRecognizedString&sources=abc&yql=select%20ignoredfield%20from%20sources%20sourceA,%20sourceB%20where%20title%20contains%20%22madonna%22%20and%20userQuery()");
execution.search(query);
assertEquals("AND title:madonna (WEAKAND(100) easilyRecognizedString)", query.getModel().getQueryTree().toString());
@@ -215,7 +213,7 @@ public class MinimalQueryInserterTestCase {
}
@Test
- public final void testSearchFromSomeSourcesWithOverlappingUserSource() {
+ final void testSearchFromSomeSourcesWithOverlappingUserSource() {
final Query query = new Query("search/?query=easilyRecognizedString&sources=abc,sourceA&yql=select%20ignoredfield%20from%20sources%20sourceA,%20sourceB%20where%20title%20contains%20%22madonna%22%20and%20userQuery()");
execution.search(query);
assertEquals("AND title:madonna (WEAKAND(100) easilyRecognizedString)", query.getModel().getQueryTree().toString());
@@ -226,17 +224,17 @@ public class MinimalQueryInserterTestCase {
}
@Test
- public void testLimitAndOffset() {
+ void testLimitAndOffset() {
Query query = new Query("search/?yql=select%20*%20from%20sources%20*%20where%20title%20contains%20%22madonna%22%20limit%2031offset%207");
execution.search(query);
assertEquals(7, query.getOffset());
assertEquals(24, query.getHits());
assertEquals("select * from sources * where title contains \"madonna\" limit 31 offset 7",
- query.yqlRepresentation());
+ query.yqlRepresentation());
}
@Test
- public void testMaxOffset() {
+ void testMaxOffset() {
Query query = new Query("search/?yql=select%20*%20from%20sources%20*%20where%20title%20contains%20%22madonna%22%20limit%2040031offset%2040000");
Result r = execution.search(query);
assertEquals(1, r.hits().getErrorHit().errors().size());
@@ -246,7 +244,7 @@ public class MinimalQueryInserterTestCase {
}
@Test
- public void testMaxLimit() {
+ void testMaxLimit() {
Query query = new Query("search/?yql=select%20*%20from%20sources%20*%20where%20title%20contains%20%22madonna%22%20limit%2040000offset%207");
Result r = execution.search(query);
assertEquals(1, r.hits().getErrorHit().errors().size());
@@ -256,7 +254,7 @@ public class MinimalQueryInserterTestCase {
}
@Test
- public void testTimeout() {
+ void testTimeout() {
Query query = new Query("search/?yql=select%20*%20from%20sources%20*%20where%20title%20contains%20%22madonna%22%20timeout%2051");
execution.search(query);
assertEquals(51L, query.getTimeout());
@@ -264,12 +262,12 @@ public class MinimalQueryInserterTestCase {
}
@Test
- public void testTimeoutWithGrouping() {
+ void testTimeoutWithGrouping() {
var select = "select x, y, z from sources * "
+ "where (x > 0 AND y contains \"foo\" AND z contains \"bar\") "
+ "order by x limit 20 offset 10 timeout 30 "
+ "| all(group(y) max(3) each(output(count())))";
- Query query = new Query("search/?yql="+ URLEncoder.encode(select, Charsets.UTF_8));
+ Query query = new Query("search/?yql=" + URLEncoder.encode(select, Charsets.UTF_8));
execution.search(query);
assertEquals(10, query.getHits());
@@ -281,7 +279,7 @@ public class MinimalQueryInserterTestCase {
}
@Test
- public void testOrdering() {
+ void testOrdering() {
{
String yql = "select%20ignoredfield%20from%20ignoredsource%20where%20title%20contains%20%22madonna%22%20order%20by%20something%2C%20shoesize%20desc%20limit%20300%20timeout%203";
Query query = new Query("search/?yql=" + yql);
@@ -335,28 +333,28 @@ public class MinimalQueryInserterTestCase {
}
@Test
- public void testStringRepresentation() {
+ void testStringRepresentation() {
String yql = "select%20ignoredfield%20from%20ignoredsource%20where%20title%20contains%20%22madonna%22%20order%20by%20something%2C%20shoesize%20desc%20limit%20300%20timeout%203";
Query query = new Query("search/?yql=" + yql);
execution.search(query);
assertEquals("select ignoredfield from ignoredsource where title contains \"madonna\" order by something, shoesize desc limit 300 timeout 3",
- query.yqlRepresentation());
+ query.yqlRepresentation());
}
@Test
- public void testAndSegmenting() {
+ void testAndSegmenting() {
Query query = new Query("?yql=select%20%2A%20from%20sources%20%2A%20where%20%5B%7B%22defaultIndex%22%3A%20%22default%22%2C%22grammar%22%3A%20%22web%22%2C%22stem%22%3A%20true%2C%22allowEmpty%22%3A%20true%7D%5DuserInput%28%40animal%29%3B&animal=m%26m%27s&tracelevel=3");
execution.search(query);
assertEquals("select * from sources * where (default contains \"m\" AND default contains ({origin: {original: \"m\\'s\", offset: 0, length: 3}, andSegmenting: true}phrase(\"m\", \"s\")))",
- query.yqlRepresentation());
+ query.yqlRepresentation());
}
@Test
- public void globalMaxGroupsIsCarriedOver() {
+ void globalMaxGroupsIsCarriedOver() {
URIBuilder builder = new URIBuilder();
builder.setPath("search/");
builder.setParameter("yql", "select foo from bar where baz contains 'cox' " +
- "| all(group(a) each(output(count())))");
+ "| all(group(a) each(output(count())))");
Query query = new Query(builder.toString());
query.properties().set("grouping.globalMaxGroups", -1);
execution.search(query);
@@ -365,12 +363,12 @@ public class MinimalQueryInserterTestCase {
}
@Test
- public void globalMaxGroupsCannotBeSetInRequest() {
+ void globalMaxGroupsCannotBeSetInRequest() {
try {
URIBuilder builder = new URIBuilder();
builder.setPath("search/");
builder.setParameter("yql", "select foo from bar where baz contains 'cox' " +
- "| all(group(a) each(output(count())))");
+ "| all(group(a) each(output(count())))");
builder.setParameter("grouping.globalMaxGroups", "-1");
Query query = new Query(builder.toString());
execution.search(query);
@@ -382,7 +380,7 @@ public class MinimalQueryInserterTestCase {
}
@Test
- public void verifyThatWarmupIsSane() {
+ void verifyThatWarmupIsSane() {
assertTrue(MinimalQueryInserter.warmup());
}
diff --git a/container-search/src/test/java/com/yahoo/search/yql/ParameterListParserTestCase.java b/container-search/src/test/java/com/yahoo/search/yql/ParameterListParserTestCase.java
index 44f784e96f3..8037ea097ab 100644
--- a/container-search/src/test/java/com/yahoo/search/yql/ParameterListParserTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/yql/ParameterListParserTestCase.java
@@ -2,11 +2,11 @@
package com.yahoo.search.yql;
import com.yahoo.prelude.query.WeightedSetItem;
-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 bratseth
@@ -14,7 +14,7 @@ import static org.junit.Assert.assertEquals;
public class ParameterListParserTestCase {
@Test
- public void testMapParsing() {
+ void testMapParsing() {
assertParsed("{}", Map.of());
assertParsed("{a:12}", Map.of("a", 12));
assertParsed("{'a':12}", Map.of("a", 12));
@@ -27,7 +27,7 @@ public class ParameterListParserTestCase {
}
@Test
- public void testArrayParsing() {
+ void testArrayParsing() {
assertParsed("[]", Map.of());
assertParsed("[[0,12]]", Map.of(0L, 12));
assertParsed("[[0,12],[1,13]]", Map.of(0L, 12, 1L, 13));
@@ -39,9 +39,9 @@ public class ParameterListParserTestCase {
WeightedSetItem item = new WeightedSetItem("test");
ParameterListParser.addItemsFromString(string, item);
for (var entry : expected.entrySet()) {
- assertEquals("Key '" + entry.getKey() + "'", entry.getValue(), item.getTokenWeight(entry.getKey()));
+ assertEquals(entry.getValue(), item.getTokenWeight(entry.getKey()), "Key '" + entry.getKey() + "'");
}
- assertEquals("Token count is correct", expected.size(), item.getNumTokens());
+ assertEquals(expected.size(), item.getNumTokens(), "Token count is correct");
}
}
diff --git a/container-search/src/test/java/com/yahoo/search/yql/TermListTestCase.java b/container-search/src/test/java/com/yahoo/search/yql/TermListTestCase.java
index 30254aa5738..3f04f36f64e 100644
--- a/container-search/src/test/java/com/yahoo/search/yql/TermListTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/yql/TermListTestCase.java
@@ -6,12 +6,12 @@ import com.yahoo.search.Query;
import com.yahoo.search.Result;
import com.yahoo.search.searchchain.Execution;
import org.apache.http.client.utils.URIBuilder;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
-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;
/**
* Tests YQL expressions where a list of terms are supplied by indirection
@@ -21,33 +21,33 @@ import static org.junit.Assert.assertNull;
public class TermListTestCase {
@Test
- public void testTermListInWeightedSet() {
+ void testTermListInWeightedSet() {
URIBuilder builder = searchUri();
builder.setParameter("myTerms", "{'1':1, '2':1, 3:1}");
builder.setParameter("yql", "select * from sources * where weightedSet(user_id, @myTerms)");
Query query = searchAndAssertNoErrors(builder);
assertEquals("select * from sources * where weightedSet(user_id, {\"1\": 1, \"2\": 1, \"3\": 1})",
- query.yqlRepresentation());
+ query.yqlRepresentation());
}
@Test
- public void testTermListInWand() {
+ void testTermListInWand() {
URIBuilder builder = searchUri();
builder.setParameter("myTerms", "{'1':1, 2:1, '3':1}");
builder.setParameter("yql", "select * from sources * where wand(user_id, @myTerms)");
Query query = searchAndAssertNoErrors(builder);
assertEquals("select * from sources * where wand(user_id, {\"1\": 1, \"2\": 1, \"3\": 1})",
- query.yqlRepresentation());
+ query.yqlRepresentation());
}
@Test
- public void testTermListInDotProduct() {
+ void testTermListInDotProduct() {
URIBuilder builder = searchUri();
builder.setParameter("myTerms", "{'1':1, '2':1, '3':1}");
builder.setParameter("yql", "select * from sources * where dotProduct(user_id, @myTerms)");
Query query = searchAndAssertNoErrors(builder);
assertEquals("select * from sources * where dotProduct(user_id, {\"1\": 1, \"2\": 1, \"3\": 1})",
- query.yqlRepresentation());
+ query.yqlRepresentation());
}
private Query searchAndAssertNoErrors(URIBuilder builder) {
@@ -57,9 +57,9 @@ public class TermListTestCase {
var execution = new Execution(searchChain, context);
Result r = execution.search(query);
var exception = exceptionOf(r);
- assertNull(exception == null ? "No error":
- exception.getMessage() + "\n" + Arrays.toString(exception.getStackTrace()),
- r.hits().getError());
+ assertNull(r.hits().getError(),
+ exception == null ? "No error":
+ exception.getMessage() + "\n" + Arrays.toString(exception.getStackTrace()));
return query;
}
diff --git a/container-search/src/test/java/com/yahoo/search/yql/UserInputTestCase.java b/container-search/src/test/java/com/yahoo/search/yql/UserInputTestCase.java
index 4af29822a26..8fe451dd095 100644
--- a/container-search/src/test/java/com/yahoo/search/yql/UserInputTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/yql/UserInputTestCase.java
@@ -1,14 +1,13 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.yql;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
import com.yahoo.search.query.QueryTree;
import org.apache.http.client.utils.URIBuilder;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import com.yahoo.component.chain.Chain;
import com.yahoo.search.Query;
import com.yahoo.search.Result;
@@ -30,14 +29,14 @@ public class UserInputTestCase {
private Execution.Context context;
private Execution execution;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
searchChain = new Chain<>(new MinimalQueryInserter());
context = Execution.Context.createContextStub();
execution = new Execution(searchChain, context);
}
- @After
+ @AfterEach
public void tearDown() {
searchChain = null;
context = null;
@@ -45,7 +44,7 @@ public class UserInputTestCase {
}
@Test
- public void testSimpleUserInput() {
+ void testSimpleUserInput() {
{
URIBuilder builder = searchUri();
builder.setParameter("yql", "select * from sources * where userInput(\"nalle\")");
@@ -70,7 +69,7 @@ public class UserInputTestCase {
}
@Test
- public void testRawUserInput() {
+ void testRawUserInput() {
URIBuilder builder = searchUri();
builder.setParameter("yql", "select * from sources * where {grammar: \"raw\"}userInput(\"nal le\")");
Query query = searchAndAssertNoErrors(builder);
@@ -78,7 +77,7 @@ public class UserInputTestCase {
}
@Test
- public void testSegmentedUserInput() {
+ void testSegmentedUserInput() {
URIBuilder builder = searchUri();
builder.setParameter("yql",
"select * from sources * where {grammar: \"segment\"}userInput(\"nal le\")");
@@ -87,7 +86,7 @@ public class UserInputTestCase {
}
@Test
- public void testSegmentedNoiseUserInput() {
+ void testSegmentedNoiseUserInput() {
URIBuilder builder = searchUri();
builder.setParameter("yql",
"select * from sources * where {grammar: \"segment\"}userInput(\"^^^^^^^^\")");
@@ -96,45 +95,45 @@ public class UserInputTestCase {
}
@Test
- public void testAnyParsedUserInput() {
+ void testAnyParsedUserInput() {
URIBuilder builder = searchUri();
builder.setParameter("yql", "select * from sources * where {grammar: \"any\"}userInput('foo bar')");
Query query = searchAndAssertNoErrors(builder);
assertEquals("select * from sources * where (default contains \"foo\" OR default contains \"bar\")",
- query.yqlRepresentation());
+ query.yqlRepresentation());
}
@Test
- public void testAllParsedUserInput() {
+ void testAllParsedUserInput() {
URIBuilder builder = searchUri();
builder.setParameter("yql", "select * from sources * where {grammar: \"all\"}userInput('foo bar')");
Query query = searchAndAssertNoErrors(builder);
assertEquals("select * from sources * where (default contains \"foo\" AND default contains \"bar\")",
- query.yqlRepresentation());
+ query.yqlRepresentation());
}
@Test
- public void testWeakAndParsedUserInput() {
+ void testWeakAndParsedUserInput() {
URIBuilder builder = searchUri();
builder.setParameter("yql", "select * from sources * where {grammar: \"weakAnd\"}userInput('foo bar')");
Query query = searchAndAssertNoErrors(builder);
assertEquals("select * from sources * where weakAnd(default contains \"foo\", default contains \"bar\")",
- query.yqlRepresentation());
+ query.yqlRepresentation());
}
@Test
- public void testIllegalGrammar() {
+ void testIllegalGrammar() {
URIBuilder builder = searchUri();
builder.setParameter("yql", "select * from sources * where {grammar: \"nonesuch\"}userInput('foo bar')");
Query query = new Query(builder.toString());
Result r = execution.search(query);
assertNotNull(r.hits().getError());
assertEquals("Could not create query from YQL: No query type 'nonesuch'",
- r.hits().getError().getDetailedMessage());
+ r.hits().getError().getDetailedMessage());
}
@Test
- public void testCustomDefaultIndexUserInput() {
+ void testCustomDefaultIndexUserInput() {
URIBuilder builder = searchUri();
builder.setParameter("yql",
"select * from sources * where {defaultIndex: \"glompf\"}userInput(\"nalle\")");
@@ -143,7 +142,7 @@ public class UserInputTestCase {
}
@Test
- public void testAnnotatedUserInputStemming() {
+ void testAnnotatedUserInputStemming() {
URIBuilder builder = searchUri();
builder.setParameter("yql",
"select * from sources * where {stem: false}userInput(\"nalle\")");
@@ -154,18 +153,18 @@ public class UserInputTestCase {
}
@Test
- public void testNegativeNumberComparison() {
+ void testNegativeNumberComparison() {
URIBuilder builder = searchUri();
builder.setParameter("myinput", "-5");
builder.setParameter("yql",
- "select * from ecitem where rank(({defaultIndex:\"myfield\"}(userInput(@myinput))))");
+ "select * from ecitem where rank(({defaultIndex:\"myfield\"}(userInput(@myinput))))");
Query query = searchAndAssertNoErrors(builder);
assertEquals("select * from ecitem where rank(weakAnd(myfield = (-5)))", query.yqlRepresentation());
assertEquals("RANK (WEAKAND(100) myfield:-5)", query.getModel().getQueryTree().getRoot().toString());
}
@Test
- public void testAnnotatedUserInputUnrankedTerms() {
+ void testAnnotatedUserInputUnrankedTerms() {
URIBuilder builder = searchUri();
builder.setParameter("yql",
"select * from sources * where {ranked: false}userInput(\"nalle\")");
@@ -176,7 +175,7 @@ public class UserInputTestCase {
}
@Test
- public void testAnnotatedUserInputFiltersTerms() {
+ void testAnnotatedUserInputFiltersTerms() {
URIBuilder builder = searchUri();
builder.setParameter("yql",
"select * from sources * where {filter: true}userInput(\"nalle\")");
@@ -187,7 +186,7 @@ public class UserInputTestCase {
}
@Test
- public void testAnnotatedUserInputCaseNormalization() {
+ void testAnnotatedUserInputCaseNormalization() {
URIBuilder builder = searchUri();
builder.setParameter(
"yql",
@@ -199,7 +198,7 @@ public class UserInputTestCase {
}
@Test
- public void testAnnotatedUserInputAccentRemoval() {
+ void testAnnotatedUserInputAccentRemoval() {
URIBuilder builder = searchUri();
builder.setParameter("yql",
"select * from sources * where {accentDrop: false}userInput(\"nalle\")");
@@ -210,7 +209,7 @@ public class UserInputTestCase {
}
@Test
- public void testAnnotatedUserInputPositionData() {
+ void testAnnotatedUserInputPositionData() {
URIBuilder builder = searchUri();
builder.setParameter("yql",
"select * from sources * where {usePositionData: false}userInput(\"nalle\")");
@@ -221,7 +220,7 @@ public class UserInputTestCase {
}
@Test
- public void testQueryPropertiesAsStringArguments() {
+ void testQueryPropertiesAsStringArguments() {
URIBuilder builder = searchUri();
builder.setParameter("nalle", "bamse");
builder.setParameter("meta", "syntactic");
@@ -232,7 +231,7 @@ public class UserInputTestCase {
}
@Test
- public void testReferenceInComparison() {
+ void testReferenceInComparison() {
URIBuilder builder = searchUri();
builder.setParameter("varref", "1980");
builder.setParameter("yql", "select * from sources * where year > @varref");
@@ -241,22 +240,22 @@ public class UserInputTestCase {
}
@Test
- public void testReferenceInContinuation() {
+ void testReferenceInContinuation() {
URIBuilder builder = searchUri();
builder.setParameter("continuation", "BCBCBCBEBG");
builder.setParameter("yql",
- "select * from sources * where myfield contains 'token'" +
- "| {'continuations':[@continuation, 'BCBKCBACBKCCK'] }all(group(f) each(output(count())))");
+ "select * from sources * where myfield contains 'token'" +
+ "| {'continuations':[@continuation, 'BCBKCBACBKCCK'] }all(group(f) each(output(count())))");
Query query = searchAndAssertNoErrors(builder);
assertEquals("select * from sources * where myfield contains \"token\" | { continuations:['BCBCBCBEBG', 'BCBKCBACBKCCK'] }all(group(f) each(output(count())))", query.yqlRepresentation());
}
@Test
- public void testReferenceInEquiv() {
+ void testReferenceInEquiv() {
URIBuilder builder = searchUri();
builder.setParameter("term", "A");
builder.setParameter("yql",
- "select foo from bar where fieldName contains equiv(@term,'B')");
+ "select foo from bar where fieldName contains equiv(@term,'B')");
Query query = searchAndAssertNoErrors(builder);
assertEquals("select foo from bar where fieldName contains equiv(\"A\", \"B\")", query.yqlRepresentation());
}
@@ -264,7 +263,7 @@ public class UserInputTestCase {
private Query searchAndAssertNoErrors(URIBuilder builder) {
Query query = new Query(builder.toString());
Result r = execution.search(query);
- assertNull(stackTraceIfAny(r), r.hits().getError());
+ assertNull(r.hits().getError(), stackTraceIfAny(r));
return query;
}
@@ -281,14 +280,14 @@ public class UserInputTestCase {
}
@Test
- public void testEmptyUserInput() {
+ void testEmptyUserInput() {
URIBuilder builder = searchUri();
builder.setParameter("yql", "select * from sources * where userInput(\"\")");
assertQueryFails(builder);
}
@Test
- public void testEmptyUserInputFromQueryProperty() {
+ void testEmptyUserInputFromQueryProperty() {
URIBuilder builder = searchUri();
builder.setParameter("foo", "");
builder.setParameter("yql", "select * from sources * where userInput(@foo)");
@@ -296,7 +295,7 @@ public class UserInputTestCase {
}
@Test
- public void testEmptyQueryProperty() {
+ void testEmptyQueryProperty() {
URIBuilder builder = searchUri();
builder.setParameter("foo", "");
builder.setParameter("yql", "select * from sources * where bar contains \"a\" and nonEmpty(foo contains @foo)");
@@ -304,7 +303,7 @@ public class UserInputTestCase {
}
@Test
- public void testEmptyQueryPropertyInsideExpression() {
+ void testEmptyQueryPropertyInsideExpression() {
URIBuilder builder = searchUri();
builder.setParameter("foo", "");
builder.setParameter("yql",
@@ -313,7 +312,7 @@ public class UserInputTestCase {
}
@Test
- public void testCompositeWithoutArguments() {
+ void testCompositeWithoutArguments() {
URIBuilder builder = searchUri();
builder.setParameter("yql", "select * from sources * where bar contains \"a\" and foo contains phrase()");
searchAndAssertNoErrors(builder);
@@ -323,7 +322,7 @@ public class UserInputTestCase {
}
@Test
- public void testAnnoyingPlacementOfNonEmpty() {
+ void testAnnoyingPlacementOfNonEmpty() {
URIBuilder builder = searchUri();
builder.setParameter("yql",
"select * from sources * where bar contains \"a\" and foo contains nonEmpty(phrase(\"a\", \"b\"))");
@@ -336,7 +335,7 @@ public class UserInputTestCase {
}
@Test
- public void testAllowEmptyUserInput() {
+ void testAllowEmptyUserInput() {
URIBuilder builder = searchUri();
builder.setParameter("foo", "");
builder.setParameter("yql", "select * from sources * where [{allowEmpty: true}]userInput(@foo)");
@@ -344,7 +343,7 @@ public class UserInputTestCase {
}
@Test
- public void testAllowEmptyNullFromQueryParsing() {
+ void testAllowEmptyNullFromQueryParsing() {
URIBuilder builder = searchUri();
builder.setParameter("foo", ",,,,,,,,");
builder.setParameter("yql", "select * from sources * where [{allowEmpty: true}]userInput(@foo)");
@@ -352,7 +351,7 @@ public class UserInputTestCase {
}
@Test
- public void testDisallowEmptyNullFromQueryParsing() {
+ void testDisallowEmptyNullFromQueryParsing() {
URIBuilder builder = searchUri();
builder.setParameter("foo", ",,,,,,,,");
builder.setParameter("yql", "select * from sources * where userInput(@foo)");
@@ -360,7 +359,7 @@ public class UserInputTestCase {
}
@Test
- public void testUserInputWithEmptyRangeStart() {
+ void testUserInputWithEmptyRangeStart() {
URIBuilder builder = searchUri();
builder.setParameter("wql", "[;boom]");
builder.setParameter("yql", "select * from sources * where ([{\"defaultIndex\": \"text_field\",\"grammar\": \"any\"}]userInput(@wql))");
diff --git a/container-search/src/test/java/com/yahoo/search/yql/VespaSerializerTestCase.java b/container-search/src/test/java/com/yahoo/search/yql/VespaSerializerTestCase.java
index 553c3a3e583..9e5cde76c82 100644
--- a/container-search/src/test/java/com/yahoo/search/yql/VespaSerializerTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/yql/VespaSerializerTestCase.java
@@ -1,8 +1,6 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.yql;
-import static org.junit.Assert.*;
-
import com.yahoo.prelude.query.SameElementItem;
import com.yahoo.search.Query;
import com.yahoo.search.grouping.Continuation;
@@ -12,10 +10,9 @@ import com.yahoo.search.grouping.request.AttributeFunction;
import com.yahoo.search.grouping.request.CountAggregator;
import com.yahoo.search.grouping.request.EachOperation;
import com.yahoo.search.grouping.request.GroupingOperation;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import com.yahoo.prelude.query.AndSegmentItem;
import com.yahoo.prelude.query.Item;
import com.yahoo.prelude.query.MarkerWordItem;
@@ -28,73 +25,75 @@ import com.yahoo.search.query.parser.ParserEnvironment;
import java.util.Arrays;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
public class VespaSerializerTestCase {
private static final String SELECT = "select ignoredfield from sourceA where ";
private YqlParser parser;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
ParserEnvironment env = new ParserEnvironment();
parser = new YqlParser(env);
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
parser = null;
}
@Test
- public void requireThatGroupingRequestsAreSerialized() {
+ void requireThatGroupingRequestsAreSerialized() {
Query query = new Query();
query.getModel().getQueryTree().setRoot(new WordItem("foo"));
assertEquals("default contains ({implicitTransforms: false}\"foo\")",
- VespaSerializer.serialize(query));
+ VespaSerializer.serialize(query));
newGroupingRequest(query, new AllOperation().setGroupBy(new AttributeFunction("a"))
- .addChild(new EachOperation().addOutput(new CountAggregator())));
+ .addChild(new EachOperation().addOutput(new CountAggregator())));
assertEquals("default contains ({implicitTransforms: false}\"foo\") " +
- "| all(group(attribute(a)) each(output(count())))",
- VespaSerializer.serialize(query));
+ "| all(group(attribute(a)) each(output(count())))",
+ VespaSerializer.serialize(query));
newGroupingRequest(query, new AllOperation().setGroupBy(new AttributeFunction("b"))
- .addChild(new EachOperation().addOutput(new CountAggregator())));
+ .addChild(new EachOperation().addOutput(new CountAggregator())));
assertEquals("default contains ({implicitTransforms: false}\"foo\") " +
- "| all(group(attribute(a)) each(output(count()))) " +
- "| all(group(attribute(b)) each(output(count())))",
- VespaSerializer.serialize(query));
+ "| all(group(attribute(a)) each(output(count()))) " +
+ "| all(group(attribute(b)) each(output(count())))",
+ VespaSerializer.serialize(query));
}
@Test
- public void requireThatGroupingContinuationsAreSerialized() {
+ void requireThatGroupingContinuationsAreSerialized() {
Query query = new Query();
query.getModel().getQueryTree().setRoot(new WordItem("foo"));
assertEquals("default contains ({implicitTransforms: false}\"foo\")",
- VespaSerializer.serialize(query));
+ VespaSerializer.serialize(query));
newGroupingRequest(query, new AllOperation().setGroupBy(new AttributeFunction("a"))
- .addChild(new EachOperation().addOutput(new CountAggregator())),
- Continuation.fromString("BCBCBCBEBG"),
- Continuation.fromString("BCBKCBACBKCCK"));
+ .addChild(new EachOperation().addOutput(new CountAggregator())),
+ Continuation.fromString("BCBCBCBEBG"),
+ Continuation.fromString("BCBKCBACBKCCK"));
assertEquals("default contains ({implicitTransforms: false}\"foo\") " +
- "| { continuations:['BCBCBCBEBG', 'BCBKCBACBKCCK'] }" +
- "all(group(attribute(a)) each(output(count())))",
- VespaSerializer.serialize(query));
+ "| { continuations:['BCBCBCBEBG', 'BCBKCBACBKCCK'] }" +
+ "all(group(attribute(a)) each(output(count())))",
+ VespaSerializer.serialize(query));
newGroupingRequest(query, new AllOperation().setGroupBy(new AttributeFunction("b"))
- .addChild(new EachOperation().addOutput(new CountAggregator())),
- Continuation.fromString("BCBBBBBDBF"),
- Continuation.fromString("BCBJBPCBJCCJ"));
+ .addChild(new EachOperation().addOutput(new CountAggregator())),
+ Continuation.fromString("BCBBBBBDBF"),
+ Continuation.fromString("BCBJBPCBJCCJ"));
assertEquals("default contains ({implicitTransforms: false}\"foo\") " +
- "| { continuations:['BCBCBCBEBG', 'BCBKCBACBKCCK'] }" +
- "all(group(attribute(a)) each(output(count()))) " +
- "| { continuations:['BCBBBBBDBF', 'BCBJBPCBJCCJ'] }" +
- "all(group(attribute(b)) each(output(count())))",
- VespaSerializer.serialize(query));
+ "| { continuations:['BCBCBCBEBG', 'BCBKCBACBKCCK'] }" +
+ "all(group(attribute(a)) each(output(count()))) " +
+ "| { continuations:['BCBBBBBDBF', 'BCBJBPCBJCCJ'] }" +
+ "all(group(attribute(b)) each(output(count())))",
+ VespaSerializer.serialize(query));
}
@Test
- public void testAnd() {
+ void testAnd() {
parseAndConfirm("(description contains \"a\" AND title contains \"that\")");
}
@@ -109,17 +108,17 @@ public class VespaSerializerTestCase {
}
@Test
- public void testAndNot() {
+ void testAndNot() {
parseAndConfirm("(description contains \"a\") AND !(title contains \"that\")");
}
@Test
- public void testEquiv() {
+ void testEquiv() {
parseAndConfirm("title contains equiv(\"a\", \"b\")");
}
@Test
- public void testGeoLocation() {
+ void testGeoLocation() {
parseAndConfirm("geoLocation(workplace, 63.418417, 10.433033, \"0.5 deg\")");
parseAndConfirm("geoLocation(headquarters, 37.41638, -122.024683, \"180.0 deg\")");
parseAndConfirm("geoLocation(home, -17.0, 42.0, \"0.0 deg\")");
@@ -127,13 +126,13 @@ public class VespaSerializerTestCase {
}
@Test
- public void testNear() {
+ void testNear() {
parseAndConfirm("title contains near(\"a\", \"b\")");
parseAndConfirm("title contains ({distance: 50}near(\"a\", \"b\"))");
}
@Test
- public void testNearestNeighbor() {
+ void testNearestNeighbor() {
parseAndConfirm("{label: \"foo\", targetNumHits: 1000}nearestNeighbor(semantic_embedding, my_property)");
parseAndConfirm("{targetNumHits: 42}nearestNeighbor(semantic_embedding, my_property)");
parseAndConfirm("{targetNumHits: 1, hnsw.exploreAdditionalHits: 76}nearestNeighbor(semantic_embedding, my_property)");
@@ -143,26 +142,26 @@ public class VespaSerializerTestCase {
}
@Test
- public void testTrueAndFalse() {
+ void testTrueAndFalse() {
parseAndConfirm("true");
parseAndConfirm("false");
}
@Test
- public void testNumbers() {
+ void testNumbers() {
parseAndConfirm("title = 500");
parseAndConfirm("title > 500");
parseAndConfirm("title < 500");
}
@Test
- public void testBoolean() {
+ void testBoolean() {
parseAndConfirm("flag = true");
parseAndConfirm("flag = false");
}
@Test
- public void testAnnotatedNumbers() {
+ void testAnnotatedNumbers() {
parseAndConfirm("title = ({filter: true}500)");
parseAndConfirm("title > ({filter: true}500)");
parseAndConfirm("title < ({filter: true}(-500))");
@@ -171,32 +170,32 @@ public class VespaSerializerTestCase {
}
@Test
- public void testRange() {
+ void testRange() {
parseAndConfirm("range(title, 1, 500)");
}
@Test
- public void testAnnotatedRange() {
+ void testAnnotatedRange() {
parseAndConfirm("{filter: true}range(title, 1, 500)");
}
@Test
- public void testOrderedNear() {
+ void testOrderedNear() {
parseAndConfirm("title contains onear(\"a\", \"b\")");
}
@Test
- public void testOr() {
+ void testOr() {
parseAndConfirm("(description contains \"a\" OR title contains \"that\")");
}
@Test
- public void testDotProduct() {
+ void testDotProduct() {
parseAndConfirm("dotProduct(description, {\"a\": 1, \"b\": 2})");
}
@Test
- public void testPredicate() {
+ void testPredicate() {
parseAndConfirm("predicate(boolean,{\"gender\":\"male\"},{\"age\":25L})");
parseAndConfirm("predicate(boolean,{\"gender\":\"male\",\"hobby\":\"music\",\"hobby\":\"hiking\"}," +
"{\"age\":25L})",
@@ -204,37 +203,37 @@ public class VespaSerializerTestCase {
parseAndConfirm("predicate(boolean,{\"0x3\":{\"gender\":\"male\"},\"0x1\":{\"hobby\":\"music\"},\"0x1\":{\"hobby\":\"hiking\"}},{\"0x80ffffffffffffff\":{\"age\":23L}})",
"predicate(boolean,{\"0x3\":{\"gender\":\"male\"},\"0x1\":{\"hobby\":[\"music\",\"hiking\"]}},{\"0x80ffffffffffffff\":{\"age\":23L}})");
parseAndConfirm("predicate(boolean,0,0)");
- parseAndConfirm("predicate(boolean,0,0)","predicate(boolean,null,void)");
- parseAndConfirm("predicate(boolean,0,0)","predicate(boolean,{},{})");
+ parseAndConfirm("predicate(boolean,0,0)", "predicate(boolean,null,void)");
+ parseAndConfirm("predicate(boolean,0,0)", "predicate(boolean,{},{})");
}
@Test
- public void testPhrase() {
+ void testPhrase() {
parseAndConfirm("description contains phrase(\"a\", \"b\")");
}
@Test
- public void testAnnotatedPhrase() {
+ void testAnnotatedPhrase() {
parseAndConfirm("description contains ({id: 1}phrase(\"a\", \"b\"))");
}
@Test
- public void testAnnotatedNear() {
+ void testAnnotatedNear() {
parseAndConfirm("description contains ({distance: 37}near(\"a\", \"b\"))");
}
@Test
- public void testAnnotatedOnear() {
+ void testAnnotatedOnear() {
parseAndConfirm("description contains ({distance: 37}onear(\"a\", \"b\"))");
}
@Test
- public void testAnnotatedEquiv() {
+ void testAnnotatedEquiv() {
parseAndConfirm("description contains ({id: 1}equiv(\"a\", \"b\"))");
}
@Test
- public void testAnnotatedPhraseSegment() {
+ void testAnnotatedPhraseSegment() {
PhraseSegmentItem phraseSegment = new PhraseSegmentItem("abc", true, false);
phraseSegment.addItem(new WordItem("a", "indexNamePlaceholder"));
phraseSegment.addItem(new WordItem("b", "indexNamePlaceholder"));
@@ -246,7 +245,7 @@ public class VespaSerializerTestCase {
}
@Test
- public void testSameElement() {
+ void testSameElement() {
SameElementItem sameElement = new SameElementItem("ss");
sameElement.addItem(new WordItem("a", "f1"));
sameElement.addItem(new WordItem("b", "f2"));
@@ -254,8 +253,9 @@ public class VespaSerializerTestCase {
assertEquals("ss contains sameElement(f1 contains ({implicitTransforms: false}\"a\"), f2 contains ({implicitTransforms: false}\"b\"))", VespaSerializer.serialize(sameElement));
}
+
@Test
- public void testAnnotatedAndSegment() {
+ void testAnnotatedAndSegment() {
AndSegmentItem andSegment = new AndSegmentItem("abc", true, false);
andSegment.addItem(new WordItem("a", "indexNamePlaceholder"));
andSegment.addItem(new WordItem("b", "indexNamePlaceholder"));
@@ -270,42 +270,42 @@ public class VespaSerializerTestCase {
}
@Test
- public void testPhraseWithAnnotations() {
+ void testPhraseWithAnnotations() {
parseAndConfirm("description contains phrase(({id: 15}\"a\"), \"b\")");
}
@Test
- public void testPhraseSegmentInPhrase() {
+ void testPhraseSegmentInPhrase() {
parseAndConfirm("description contains phrase(\"a\", \"b\", ({origin: {original: \"c d\", offset: 0, length: 3}}phrase(\"c\", \"d\")))");
}
@Test
- public void testRank() {
+ void testRank() {
parseAndConfirm("rank(a contains \"A\", b contains \"B\")");
}
@Test
- public void testWand() {
+ void testWand() {
parseAndConfirm("wand(description, {\"a\": 1, \"b\": 2})");
}
@Test
- public void testWeakAnd() {
+ void testWeakAnd() {
parseAndConfirm("weakAnd(a contains \"A\", b contains \"B\")");
}
@Test
- public void testAnnotatedWeakAnd() {
+ void testAnnotatedWeakAnd() {
parseAndConfirm("({" + YqlParser.TARGET_NUM_HITS + ": 10}weakAnd(a contains \"A\", b contains \"B\"))");
}
@Test
- public void testWeightedSet() {
+ void testWeightedSet() {
parseAndConfirm("weightedSet(description, {\"a\": 1, \"b\": 2})");
}
@Test
- public void testAnnotatedWord() {
+ void testAnnotatedWord() {
parseAndConfirm("description contains ({andSegmenting: true}\"a\")");
parseAndConfirm("description contains ({weight: 37}\"a\")");
parseAndConfirm("description contains ({id: 37}\"a\")");
@@ -317,29 +317,29 @@ public class VespaSerializerTestCase {
}
@Test
- public void testPrefix() {
+ void testPrefix() {
parseAndConfirm("description contains ({prefix: true}\"a\")");
}
@Test
- public void testSuffix() {
+ void testSuffix() {
parseAndConfirm("description contains ({suffix: true}\"a\")");
}
@Test
- public void testSubstring() {
+ void testSubstring() {
parseAndConfirm("description contains ({substring: true}\"a\")");
}
@Test
- public void testExoticItemTypes() {
+ void testExoticItemTypes() {
Item item = MarkerWordItem.createEndOfHost();
String q = VespaSerializer.serialize(item);
assertEquals("default contains ({implicitTransforms: false}\"$\")", q);
}
@Test
- public void testEmptyIndex() {
+ void testEmptyIndex() {
Item item = new WordItem("nalle", true);
String q = VespaSerializer.serialize(item);
assertEquals("default contains \"nalle\"", q);
@@ -347,7 +347,7 @@ public class VespaSerializerTestCase {
@Test
- public void testLongAndNot() {
+ void testLongAndNot() {
NotItem item = new NotItem();
item.addItem(new WordItem("a"));
item.addItem(new WordItem("b"));
@@ -358,7 +358,7 @@ public class VespaSerializerTestCase {
}
@Test
- public void testPhraseAsOperatorArgument() {
+ void testPhraseAsOperatorArgument() {
// flattening phrases is a feature, not a bug
parseAndConfirm("description contains phrase(\"a\", \"b\", \"c\")",
"description contains phrase(\"a\", phrase(\"b\", \"c\"))");
@@ -372,7 +372,7 @@ public class VespaSerializerTestCase {
}
@Test
- public void testNumberTypeInt() {
+ void testNumberTypeInt() {
parseAndConfirm("title = 500");
parseAndConfirm("title > 500");
parseAndConfirm("title < (-500)");
@@ -382,7 +382,7 @@ public class VespaSerializerTestCase {
}
@Test
- public void testNumberTypeLong() {
+ void testNumberTypeLong() {
parseAndConfirm("title = 549755813888L");
parseAndConfirm("title > 549755813888L");
parseAndConfirm("title < (-549755813888L)");
@@ -392,7 +392,7 @@ public class VespaSerializerTestCase {
}
@Test
- public void testNumberTypeFloat() {
+ void testNumberTypeFloat() {
parseAndConfirm("title = 500.0"); // silly
parseAndConfirm("title > 500.0");
parseAndConfirm("title < (-500.0)");
@@ -402,19 +402,19 @@ public class VespaSerializerTestCase {
}
@Test
- public void testAnnotatedLong() {
+ void testAnnotatedLong() {
parseAndConfirm("title >= ({id: 2014}(-549755813888L))");
}
@Test
- public void testHitLimit() {
+ void testHitLimit() {
parseAndConfirm("title <= ({hitLimit: 89}(-500))");
parseAndConfirm("title <= ({hitLimit: 89}(-500))");
parseAndConfirm("{hitLimit: 89}range(title, 1, 500)");
}
@Test
- public void testOpenIntervals() {
+ void testOpenIntervals() {
parseAndConfirm("range(title, 0.0, 500.0)");
parseAndConfirm("({bounds: \"open\"}range(title, 0.0, 500.0))");
parseAndConfirm("({bounds: \"leftOpen\"}range(title, 0.0, 500.0))");
@@ -423,18 +423,18 @@ public class VespaSerializerTestCase {
}
@Test
- public void testRegExp() {
+ void testRegExp() {
parseAndConfirm("foo matches \"a b\"");
}
@Test
- public void testWordAlternatives() {
+ void testWordAlternatives() {
parseAndConfirm("foo contains" + " ({origin: {original: \" trees \", offset: 1, length: 5}}"
+ "alternatives({\"trees\": 1.0, \"tree\": 0.7}))");
}
@Test
- public void testWordAlternativesInPhrase() {
+ void testWordAlternativesInPhrase() {
parseAndConfirm("foo contains phrase(\"forest\","
+ " ({origin: {original: \" trees \", offset: 1, length: 5}}"
+ "alternatives({\"trees\": 1.0, \"tree\": 0.7}))"
@@ -442,12 +442,12 @@ public class VespaSerializerTestCase {
}
@Test
- public void testFuzzy() {
+ void testFuzzy() {
parseAndConfirm("foo contains fuzzy(\"a\")");
}
@Test
- public void testFuzzyAnnotations() {
+ void testFuzzyAnnotations() {
parseAndConfirm("foo contains ({maxEditDistance:3,prefixLength:5}fuzzy(\"a\"))");
}
diff --git a/container-search/src/test/java/com/yahoo/search/yql/YqlFieldAndSourceTestCase.java b/container-search/src/test/java/com/yahoo/search/yql/YqlFieldAndSourceTestCase.java
index ee933a86578..cf3c7911d0e 100644
--- a/container-search/src/test/java/com/yahoo/search/yql/YqlFieldAndSourceTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/yql/YqlFieldAndSourceTestCase.java
@@ -1,9 +1,7 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.yql;
-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.*;
import java.util.Arrays;
import java.util.List;
@@ -12,10 +10,9 @@ import java.util.Map;
import com.yahoo.search.schema.DocumentSummary;
import com.yahoo.search.schema.Schema;
import com.yahoo.search.schema.SchemaInfo;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import com.yahoo.component.chain.Chain;
import com.yahoo.search.Query;
import com.yahoo.search.Result;
@@ -41,7 +38,7 @@ public class YqlFieldAndSourceTestCase {
private Execution.Context context;
private Execution execution;
- @Before
+ @BeforeEach
public void setUp() throws Exception {
Query query = new Query("?query=test");
@@ -80,7 +77,7 @@ public class YqlFieldAndSourceTestCase {
return new SchemaInfo(List.of(schema.build()), Map.of());
}
- @After
+ @AfterEach
public void tearDown() throws Exception {
searchChain = null;
context = null;
@@ -88,7 +85,7 @@ public class YqlFieldAndSourceTestCase {
}
@Test
- public final void testTrivial() {
+ final void testTrivial() {
final Query query = new Query("?query=test&presentation.summaryFields=" + FIELD1);
Result result = execution.search(query);
execution.fill(result);
@@ -98,7 +95,7 @@ public class YqlFieldAndSourceTestCase {
}
@Test
- public final void testWithOnlyAttribute() {
+ final void testWithOnlyAttribute() {
final Query query = new Query("?query=test&presentation.summaryFields=" + FIELD2);
Result result = execution.search(query);
execution.fill(result, THIRD_OPTION);
@@ -109,7 +106,7 @@ public class YqlFieldAndSourceTestCase {
}
@Test
- public final void testWithOnlyDiskfieldCorrectClassRequested() {
+ final void testWithOnlyDiskfieldCorrectClassRequested() {
final Query query = new Query("?query=test&presentation.summaryFields=" + FIELD3);
Result result = execution.search(query);
execution.fill(result, THIRD_OPTION);
@@ -120,7 +117,7 @@ public class YqlFieldAndSourceTestCase {
}
@Test
- public final void testTrivialCaseWithOnlyDiskfieldWrongClassRequested() {
+ final void testTrivialCaseWithOnlyDiskfieldWrongClassRequested() {
final Query query = new Query("?query=test&presentation.summaryFields=" + FIELD1);
Result result = execution.search(query);
execution.fill(result, THIRD_OPTION);
diff --git a/container-search/src/test/java/com/yahoo/search/yql/YqlParserTestCase.java b/container-search/src/test/java/com/yahoo/search/yql/YqlParserTestCase.java
index 299a7ff9d30..935b1aa62f9 100644
--- a/container-search/src/test/java/com/yahoo/search/yql/YqlParserTestCase.java
+++ b/container-search/src/test/java/com/yahoo/search/yql/YqlParserTestCase.java
@@ -44,19 +44,15 @@ import com.yahoo.search.query.Sorting.UcaSorter;
import com.yahoo.search.query.parser.Parsable;
import com.yahoo.search.query.parser.ParserEnvironment;
import com.yahoo.search.searchchain.Execution;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-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.*;
/**
* Specification for the conversion of YQL+ expressions to Vespa search queries.
@@ -68,286 +64,288 @@ public class YqlParserTestCase {
private final YqlParser parser = new YqlParser(new ParserEnvironment());
- @Test(timeout = 120_000)
- public void failsGracefullyOnMissingQuoteEscapingAndSubsequentUnicodeCharacter() {
+ @Test
+ @Timeout(120_000)
+ void failsGracefullyOnMissingQuoteEscapingAndSubsequentUnicodeCharacter() {
assertParseFail("select * from bar where rank(ids contains 'http://en.wikipedia.org/wiki/Hors_d'œuvre') limit 10",
new IllegalInputException("com.yahoo.search.yql.ProgramCompileException: query:L1:79 token recognition error at: 'œ'"));
}
@Test
- public void testParserDefaults() {
+ void testParserDefaults() {
assertTrue(parser.isQueryParser());
assertNull(parser.getDocTypes());
}
-
+
@Test
- public void testLanguageDetection() {
+ void testLanguageDetection() {
// SimpleDetector used here can detect japanese and will set that as language at the root of the user input
QueryTree tree = parse("select * from sources * where userInput(\"\u30ab\u30bf\u30ab\u30ca\")");
assertEquals(Language.JAPANESE, tree.getRoot().getLanguage());
}
@Test
- public void testGroupingStep() {
+ void testGroupingStep() {
assertParse("select foo from bar where baz contains 'cox'",
- "baz:cox");
+ "baz:cox");
assertEquals("[]",
- toString(parser.getGroupingSteps()));
+ toString(parser.getGroupingSteps()));
assertParse("select foo from bar where baz contains 'cox' " +
- "| all(group(a) each(output(count())))",
- "baz:cox");
+ "| all(group(a) each(output(count())))",
+ "baz:cox");
assertEquals("[[]all(group(a) each(output(count())))]",
- toString(parser.getGroupingSteps()));
+ toString(parser.getGroupingSteps()));
assertParse("select foo from bar where baz contains 'cox' " +
- "| all(group(a) each(output(count()))) " +
- "| all(group(b) each(output(count())))",
- "baz:cox");
+ "| all(group(a) each(output(count()))) " +
+ "| all(group(b) each(output(count())))",
+ "baz:cox");
assertEquals("[[]all(group(a) each(output(count())))," +
- " []all(group(b) each(output(count())))]",
- toString(parser.getGroupingSteps()));
+ " []all(group(b) each(output(count())))]",
+ toString(parser.getGroupingSteps()));
}
@Test
- public void testGroupingContinuation() {
+ void testGroupingContinuation() {
assertParse("select foo from bar where baz contains 'cox' " +
- "| { 'continuations': ['BCBCBCBEBG', 'BCBKCBACBKCCK'] }all(group(a) each(output(count())))",
- "baz:cox");
+ "| { 'continuations': ['BCBCBCBEBG', 'BCBKCBACBKCCK'] }all(group(a) each(output(count())))",
+ "baz:cox");
assertEquals("[[BCBCBCBEBG, BCBKCBACBKCCK]all(group(a) each(output(count())))]",
- toString(parser.getGroupingSteps()));
+ toString(parser.getGroupingSteps()));
assertParse("select foo from bar where baz contains 'cox' " +
- "| { 'continuations': ['BCBCBCBEBG', 'BCBKCBACBKCCK'] }all(group(a) each(output(count()))) " +
- "| { 'continuations': ['BCBBBBBDBF', 'BCBJBPCBJCCJ'] }all(group(b) each(output(count())))",
- "baz:cox");
+ "| { 'continuations': ['BCBCBCBEBG', 'BCBKCBACBKCCK'] }all(group(a) each(output(count()))) " +
+ "| { 'continuations': ['BCBBBBBDBF', 'BCBJBPCBJCCJ'] }all(group(b) each(output(count())))",
+ "baz:cox");
assertEquals("[[BCBCBCBEBG, BCBKCBACBKCCK]all(group(a) each(output(count())))," +
- " [BCBBBBBDBF, BCBJBPCBJCCJ]all(group(b) each(output(count())))]",
- toString(parser.getGroupingSteps()));
+ " [BCBBBBBDBF, BCBJBPCBJCCJ]all(group(b) each(output(count())))]",
+ toString(parser.getGroupingSteps()));
}
@Test
- public void testHitLimit() {
+ void testHitLimit() {
assertParse("select artist_name, track_name, track_uri from sources * where (myField contains ({prefix:true}\"m\") and ({hitLimit: 5000, descending: true}range(static_score,0,Infinity))) limit 30 offset 0",
- "AND myField:m* static_score:[0;;-5000]");
+ "AND myField:m* static_score:[0;;-5000]");
}
@Test
- public void test() {
+ void test() {
assertParse("select foo from bar where title contains \"madonna\"",
- "title:madonna");
+ "title:madonna");
}
@Test
- public void testKeywordAsFieldName() {
+ void testKeywordAsFieldName() {
assertParse("select * from sources * where cast contains sameElement(id contains '16')",
- "cast:{id:16}");
+ "cast:{id:16}");
}
@Test
- public void testComplexExpression() {
+ void testComplexExpression() {
String queryTreeYql = "rank((((filter contains ({origin: {original: \"filter:VideoAdsCappingTestCPM\", \"offset\": 7, length: 22}, normalizeCase: false, id: 1}\"videoadscappingtestcpm\") AND hasRankRestriction contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 2}\"0\") AND ((objective contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 3}\"install_app\") AND availableExtendedFields contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 4}\"cpiparams\")) OR (availableExtendedFields contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 5}\"appinstallinfo\") AND availableExtendedFields contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 6}\"appmetroplexinfo\")) OR (dummyField contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 7}\"default\")) AND !(objective contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 8}\"install_app\"))) AND advt_age = ({\"id\": 9}2147483647) AND advt_gender contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 10}\"all\") AND advt_all_segments = ({\"id\": 11}2147483647) AND advt_keywords contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 12}\"all\") AND advMobilePlatform = ({\"id\": 13}2147483647) AND advMobileDeviceType = ({\"id\": 14}2147483647) AND advMobileCon = ({\"id\": 15}2147483647) AND advMobileOSVersions = ({\"id\": 16}2147483647) AND advCarrier = ({\"id\": 17}2147483647) AND ({\"id\": 18}weightedSet(advt_supply, {\"all\": 1, \"pub223\": 1, \"sec223\": 1, \"site223\": 1})) AND (advt_day_parting contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 19, \"weight\": 1}\"adv_tuesday\") OR advt_day_parting contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 20, \"weight\": 1}\"adv_tuesday_17\") OR advt_day_parting contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 21, \"weight\": 1}\"adv_tuesday_17_forty_five\") OR advt_day_parting contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 22}\"all\")) AND isAppReengagementAd = ({\"id\": 23}0) AND dummyField contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 24}\"default\") AND serveWithPromotionOnly = ({\"id\": 26}0) AND budgetAdvertiserThrottleRateFilter = ({\"id\": 27}0) AND budgetResellerThrottleRateFilter = ({\"id\": 28}0) AND (isMystiqueRequired = ({\"id\": 29}0) OR (isMystiqueRequired = ({\"id\": 30}1) AND useBcFactorFilter = ({\"id\": 31}1))) AND (((budgetCampaignThrottleRateBits = ({\"id\": 32}55) AND dummyField contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 33}\"default\"))) AND !(useBcFactorFilter = ({\"id\": 34}1)) OR ((useBcFactorFilter = ({\"id\": 35}1) AND dummyField contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 36}\"default\") AND (bcFactorTiers = ({\"id\": 38}127) OR bcFactorTiers = ({\"id\": 39}0)) AND ((firstPriceEnforced = ({\"id\": 40}0) AND (secondPriceEnforced = ({\"id\": 41}1) OR isPrivateDeal = ({\"id\": 42}0) OR (dummyField contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 43}\"default\")) AND !(bcActiveTier = ({\"id\": 44}0)))) OR mystiqueCampaignThrottleRateBits = ({\"id\": 45}18)))) AND !(isOutOfDailyBudget = ({\"id\": 37}1))) AND testCreative = ({\"id\": 46}0) AND advt_geo = ({\"id\": 47}2147483647) AND ((adType contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 48}\"strm_video\") AND isPortraitVideo = ({\"id\": 49}0)) OR adType contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 50}\"stream_ad\")) AND ((isCPM = ({\"id\": 51}0) AND isOCPC = ({\"id\": 52}0) AND isECPC = ({\"id\": 53}0) AND ((priceType contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 54}\"cpcv\") AND bid >= ({\"id\": 55}0.005)) OR (priceType contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 56}\"cpv\") AND bid >= ({\"id\": 57}0.01)) OR (priceType contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 58}\"cpc\") AND bid >= ({\"id\": 59}0.05)) OR (objective contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 60}\"promote_content\") AND bid >= ({\"id\": 61}0.01)) OR hasFloorPriceUsd = ({\"id\": 62}1))) OR isECPC = ({\"id\": 63}1) OR (isCPM = ({\"id\": 64}1) AND isOCPM = ({\"id\": 65}0) AND (({\"id\": 66}range(bid, 0.25, Infinity)) OR hasFloorPriceUsd = ({\"id\": 67}1)))) AND start_date <= ({\"id\": 68}1572976776299L) AND end_date >= ({\"id\": 69}1572976776299L))) AND !(isHoldoutAd = ({\"id\": 25}1))) AND !((disclaimerExtensionsTypes contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 70}\"pharma\") OR ({\"id\": 71}weightedSet(exclusion_advt_supply, {\"extsite223\": 1, \"pub223\": 1, \"sec223\": 1, \"site223\": 1})) OR isPersonalized = ({\"id\": 72}1) OR blocked_section_ids contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 73}\"223\") OR blocked_publisher_ids contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 74}\"223\") OR blocked_site_ids contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 75}\"223\"))), {\"id\": 76, \"label\": \"ad_ocpc_max_cpc\"}dotProduct(ocpc_max_cpc, {\"0\": 1}), {\"id\": 77, \"label\": \"ad_ocpc_min_cpc\"}dotProduct(ocpc_min_cpc, {\"0\": 1}), {\"id\": 78, \"label\": \"ad_ocpc_max_alpha\"}dotProduct(ocpc_max_alpha, {\"0\": 1}), {\"id\": 79, \"label\": \"ad_ocpc_min_alpha\"}dotProduct(ocpc_min_alpha, {\"0\": 1}), {\"id\": 80, \"label\": \"ad_ocpc_alpha_0\"}dotProduct(ocpc_alpha_0, {\"0\": 1}), {\"id\": 81, \"label\": \"ad_ocpc_alpha_1\"}dotProduct(ocpc_alpha_1, {\"0\": 1}), (bidAdjustmentDayParting contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 82, \"weight\": 1}\"adv_tuesday\") OR bidAdjustmentDayParting contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 83, \"weight\": 1}\"adv_tuesday_17\") OR bidAdjustmentDayParting contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 84, \"weight\": 1}\"adv_tuesday_17_forty_five\") OR bidAdjustmentDayPartingForCostCap contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 85, \"weight\": 1}\"adv_tuesday\") OR bidAdjustmentDayPartingForCostCap contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 86, \"weight\": 1}\"adv_tuesday_17\") OR bidAdjustmentDayPartingForCostCap contains ({\"normalizeCase\": false, \"implicitTransforms\": false, \"id\": 87, \"weight\": 1}\"adv_tuesday_17_forty_five\")), bidAdjustmentForCpi = ({\"id\": 88, \"weight\": 1}223), {\"id\": 89, \"label\": \"boostingForBackfill\"}dotProduct(boostingForBackfill, {\"priority\": 1000})) limit 0 timeout 3980 | all(group(adTypeForGrouping) each(group(advertiser_id) max(11) output(count() as(groupingCounter)) each(max(1) each(output(summary())))))";
QueryTree parsed = assertParse("select * from sources * where " + queryTreeYql + ";",
- "RANK (+(+(AND filter:VideoAdsCappingTestCPM hasRankRestriction:0 (OR (AND objective:install_app availableExtendedFields:cpiparams) (AND availableExtendedFields:appinstallinfo availableExtendedFields:appmetroplexinfo) (+dummyField:default -objective:install_app)) advt_age:2147483647 advt_gender:all advt_all_segments:2147483647 advt_keywords:all advMobilePlatform:2147483647 advMobileDeviceType:2147483647 advMobileCon:2147483647 advMobileOSVersions:2147483647 advCarrier:2147483647 WEIGHTEDSET advt_supply{[1]:\"site223\",[1]:\"pub223\",[1]:\"all\",[1]:\"sec223\"} (OR advt_day_parting:adv_tuesday!1 advt_day_parting:adv_tuesday_17!1 advt_day_parting:adv_tuesday_17_forty_five!1 advt_day_parting:all) isAppReengagementAd:0 dummyField:default serveWithPromotionOnly:0 budgetAdvertiserThrottleRateFilter:0 budgetResellerThrottleRateFilter:0 (OR isMystiqueRequired:0 (AND isMystiqueRequired:1 useBcFactorFilter:1)) (OR (+(AND budgetCampaignThrottleRateBits:55 dummyField:default) -useBcFactorFilter:1) (+(AND useBcFactorFilter:1 dummyField:default (OR bcFactorTiers:127 bcFactorTiers:0) (OR (AND firstPriceEnforced:0 (OR secondPriceEnforced:1 isPrivateDeal:0 (+dummyField:default -bcActiveTier:0))) mystiqueCampaignThrottleRateBits:18)) -isOutOfDailyBudget:1)) testCreative:0 advt_geo:2147483647 (OR (AND adType:strm_video isPortraitVideo:0) adType:stream_ad) (OR (AND isCPM:0 isOCPC:0 isECPC:0 (OR (AND priceType:cpcv bid:[0.005;]) (AND priceType:cpv bid:[0.01;]) (AND priceType:cpc bid:[0.05;]) (AND objective:promote_content bid:[0.01;]) hasFloorPriceUsd:1)) isECPC:1 (AND isCPM:1 isOCPM:0 (OR bid:[0.25;] hasFloorPriceUsd:1))) start_date:[;1572976776299] end_date:[1572976776299;]) -isHoldoutAd:1) -(OR disclaimerExtensionsTypes:pharma WEIGHTEDSET exclusion_advt_supply{[1]:\"extsite223\",[1]:\"site223\",[1]:\"pub223\",[1]:\"sec223\"} isPersonalized:1 blocked_section_ids:223 blocked_publisher_ids:223 blocked_site_ids:223)) DOTPRODUCT ocpc_max_cpc{[1]:\"0\"} DOTPRODUCT ocpc_min_cpc{[1]:\"0\"} DOTPRODUCT ocpc_max_alpha{[1]:\"0\"} DOTPRODUCT ocpc_min_alpha{[1]:\"0\"} DOTPRODUCT ocpc_alpha_0{[1]:\"0\"} DOTPRODUCT ocpc_alpha_1{[1]:\"0\"} (OR bidAdjustmentDayParting:adv_tuesday!1 bidAdjustmentDayParting:adv_tuesday_17!1 bidAdjustmentDayParting:adv_tuesday_17_forty_five!1 bidAdjustmentDayPartingForCostCap:adv_tuesday!1 bidAdjustmentDayPartingForCostCap:adv_tuesday_17!1 bidAdjustmentDayPartingForCostCap:adv_tuesday_17_forty_five!1) bidAdjustmentForCpi:223!1 DOTPRODUCT boostingForBackfill{[1000]:\"priority\"}");
+ "RANK (+(+(AND filter:VideoAdsCappingTestCPM hasRankRestriction:0 (OR (AND objective:install_app availableExtendedFields:cpiparams) (AND availableExtendedFields:appinstallinfo availableExtendedFields:appmetroplexinfo) (+dummyField:default -objective:install_app)) advt_age:2147483647 advt_gender:all advt_all_segments:2147483647 advt_keywords:all advMobilePlatform:2147483647 advMobileDeviceType:2147483647 advMobileCon:2147483647 advMobileOSVersions:2147483647 advCarrier:2147483647 WEIGHTEDSET advt_supply{[1]:\"site223\",[1]:\"pub223\",[1]:\"all\",[1]:\"sec223\"} (OR advt_day_parting:adv_tuesday!1 advt_day_parting:adv_tuesday_17!1 advt_day_parting:adv_tuesday_17_forty_five!1 advt_day_parting:all) isAppReengagementAd:0 dummyField:default serveWithPromotionOnly:0 budgetAdvertiserThrottleRateFilter:0 budgetResellerThrottleRateFilter:0 (OR isMystiqueRequired:0 (AND isMystiqueRequired:1 useBcFactorFilter:1)) (OR (+(AND budgetCampaignThrottleRateBits:55 dummyField:default) -useBcFactorFilter:1) (+(AND useBcFactorFilter:1 dummyField:default (OR bcFactorTiers:127 bcFactorTiers:0) (OR (AND firstPriceEnforced:0 (OR secondPriceEnforced:1 isPrivateDeal:0 (+dummyField:default -bcActiveTier:0))) mystiqueCampaignThrottleRateBits:18)) -isOutOfDailyBudget:1)) testCreative:0 advt_geo:2147483647 (OR (AND adType:strm_video isPortraitVideo:0) adType:stream_ad) (OR (AND isCPM:0 isOCPC:0 isECPC:0 (OR (AND priceType:cpcv bid:[0.005;]) (AND priceType:cpv bid:[0.01;]) (AND priceType:cpc bid:[0.05;]) (AND objective:promote_content bid:[0.01;]) hasFloorPriceUsd:1)) isECPC:1 (AND isCPM:1 isOCPM:0 (OR bid:[0.25;] hasFloorPriceUsd:1))) start_date:[;1572976776299] end_date:[1572976776299;]) -isHoldoutAd:1) -(OR disclaimerExtensionsTypes:pharma WEIGHTEDSET exclusion_advt_supply{[1]:\"extsite223\",[1]:\"site223\",[1]:\"pub223\",[1]:\"sec223\"} isPersonalized:1 blocked_section_ids:223 blocked_publisher_ids:223 blocked_site_ids:223)) DOTPRODUCT ocpc_max_cpc{[1]:\"0\"} DOTPRODUCT ocpc_min_cpc{[1]:\"0\"} DOTPRODUCT ocpc_max_alpha{[1]:\"0\"} DOTPRODUCT ocpc_min_alpha{[1]:\"0\"} DOTPRODUCT ocpc_alpha_0{[1]:\"0\"} DOTPRODUCT ocpc_alpha_1{[1]:\"0\"} (OR bidAdjustmentDayParting:adv_tuesday!1 bidAdjustmentDayParting:adv_tuesday_17!1 bidAdjustmentDayParting:adv_tuesday_17_forty_five!1 bidAdjustmentDayPartingForCostCap:adv_tuesday!1 bidAdjustmentDayPartingForCostCap:adv_tuesday_17!1 bidAdjustmentDayPartingForCostCap:adv_tuesday_17_forty_five!1) bidAdjustmentForCpi:223!1 DOTPRODUCT boostingForBackfill{[1000]:\"priority\"}");
String serializedQueryTreeYql = VespaSerializer.serialize(parsed);
// Note: All the details here are not verified
assertEquals("rank((((filter contains ({normalizeCase: false, id: 1}\"VideoAdsCappingTestCPM\") AND hasRankRestriction contains ({normalizeCase: false, implicitTransforms: false, id: 2}\"0\") AND ((objective contains ({normalizeCase: false, implicitTransforms: false, id: 3}\"install_app\") AND availableExtendedFields contains ({normalizeCase: false, implicitTransforms: false, id: 4}\"cpiparams\")) OR (availableExtendedFields contains ({normalizeCase: false, implicitTransforms: false, id: 5}\"appinstallinfo\") AND availableExtendedFields contains ({normalizeCase: false, implicitTransforms: false, id: 6}\"appmetroplexinfo\")) OR (dummyField contains ({normalizeCase: false, implicitTransforms: false, id: 7}\"default\")) AND !(objective contains ({normalizeCase: false, implicitTransforms: false, id: 8}\"install_app\"))) AND advt_age = ({id: 9}2147483647) AND advt_gender contains ({normalizeCase: false, implicitTransforms: false, id: 10}\"all\") AND advt_all_segments = ({id: 11}2147483647) AND advt_keywords contains ({normalizeCase: false, implicitTransforms: false, id: 12}\"all\") AND advMobilePlatform = ({id: 13}2147483647) AND advMobileDeviceType = ({id: 14}2147483647) AND advMobileCon = ({id: 15}2147483647) AND advMobileOSVersions = ({id: 16}2147483647) AND advCarrier = ({id: 17}2147483647) AND ({id: 18}weightedSet(advt_supply, {\"all\": 1, \"pub223\": 1, \"sec223\": 1, \"site223\": 1})) AND (advt_day_parting contains ({normalizeCase: false, implicitTransforms: false, id: 19, weight: 1}\"adv_tuesday\") OR advt_day_parting contains ({normalizeCase: false, implicitTransforms: false, id: 20, weight: 1}\"adv_tuesday_17\") OR advt_day_parting contains ({normalizeCase: false, implicitTransforms: false, id: 21, weight: 1}\"adv_tuesday_17_forty_five\") OR advt_day_parting contains ({normalizeCase: false, implicitTransforms: false, id: 22}\"all\")) AND isAppReengagementAd = ({id: 23}0) AND dummyField contains ({normalizeCase: false, implicitTransforms: false, id: 24}\"default\") AND serveWithPromotionOnly = ({id: 26}0) AND budgetAdvertiserThrottleRateFilter = ({id: 27}0) AND budgetResellerThrottleRateFilter = ({id: 28}0) AND (isMystiqueRequired = ({id: 29}0) OR (isMystiqueRequired = ({id: 30}1) AND useBcFactorFilter = ({id: 31}1))) AND (((budgetCampaignThrottleRateBits = ({id: 32}55) AND dummyField contains ({normalizeCase: false, implicitTransforms: false, id: 33}\"default\"))) AND !(useBcFactorFilter = ({id: 34}1)) OR ((useBcFactorFilter = ({id: 35}1) AND dummyField contains ({normalizeCase: false, implicitTransforms: false, id: 36}\"default\") AND (bcFactorTiers = ({id: 38}127) OR bcFactorTiers = ({id: 39}0)) AND ((firstPriceEnforced = ({id: 40}0) AND (secondPriceEnforced = ({id: 41}1) OR isPrivateDeal = ({id: 42}0) OR (dummyField contains ({normalizeCase: false, implicitTransforms: false, id: 43}\"default\")) AND !(bcActiveTier = ({id: 44}0)))) OR mystiqueCampaignThrottleRateBits = ({id: 45}18)))) AND !(isOutOfDailyBudget = ({id: 37}1))) AND testCreative = ({id: 46}0) AND advt_geo = ({id: 47}2147483647) AND ((adType contains ({normalizeCase: false, implicitTransforms: false, id: 48}\"strm_video\") AND isPortraitVideo = ({id: 49}0)) OR adType contains ({normalizeCase: false, implicitTransforms: false, id: 50}\"stream_ad\")) AND ((isCPM = ({id: 51}0) AND isOCPC = ({id: 52}0) AND isECPC = ({id: 53}0) AND ((priceType contains ({normalizeCase: false, implicitTransforms: false, id: 54}\"cpcv\") AND bid >= ({id: 55}0.005)) OR (priceType contains ({normalizeCase: false, implicitTransforms: false, id: 56}\"cpv\") AND bid >= ({id: 57}0.01)) OR (priceType contains ({normalizeCase: false, implicitTransforms: false, id: 58}\"cpc\") AND bid >= ({id: 59}0.05)) OR (objective contains ({normalizeCase: false, implicitTransforms: false, id: 60}\"promote_content\") AND bid >= ({id: 61}0.01)) OR hasFloorPriceUsd = ({id: 62}1))) OR isECPC = ({id: 63}1) OR (isCPM = ({id: 64}1) AND isOCPM = ({id: 65}0) AND ({id: 66}range(bid, 0.25, Infinity) OR hasFloorPriceUsd = ({id: 67}1)))) AND start_date <= ({id: 68}1572976776299L) AND end_date >= ({id: 69}1572976776299L))) AND !(isHoldoutAd = ({id: 25}1))) AND !((disclaimerExtensionsTypes contains ({normalizeCase: false, implicitTransforms: false, id: 70}\"pharma\") OR ({id: 71}weightedSet(exclusion_advt_supply, {\"extsite223\": 1, \"pub223\": 1, \"sec223\": 1, \"site223\": 1})) OR isPersonalized = ({id: 72}1) OR blocked_section_ids contains ({normalizeCase: false, implicitTransforms: false, id: 73}\"223\") OR blocked_publisher_ids contains ({normalizeCase: false, implicitTransforms: false, id: 74}\"223\") OR blocked_site_ids contains ({normalizeCase: false, implicitTransforms: false, id: 75}\"223\"))), ({id: 76, label: \"ad_ocpc_max_cpc\"}dotProduct(ocpc_max_cpc, {\"0\": 1})), ({id: 77, label: \"ad_ocpc_min_cpc\"}dotProduct(ocpc_min_cpc, {\"0\": 1})), ({id: 78, label: \"ad_ocpc_max_alpha\"}dotProduct(ocpc_max_alpha, {\"0\": 1})), ({id: 79, label: \"ad_ocpc_min_alpha\"}dotProduct(ocpc_min_alpha, {\"0\": 1})), ({id: 80, label: \"ad_ocpc_alpha_0\"}dotProduct(ocpc_alpha_0, {\"0\": 1})), ({id: 81, label: \"ad_ocpc_alpha_1\"}dotProduct(ocpc_alpha_1, {\"0\": 1})), (bidAdjustmentDayParting contains ({normalizeCase: false, implicitTransforms: false, id: 82, weight: 1}\"adv_tuesday\") OR bidAdjustmentDayParting contains ({normalizeCase: false, implicitTransforms: false, id: 83, weight: 1}\"adv_tuesday_17\") OR bidAdjustmentDayParting contains ({normalizeCase: false, implicitTransforms: false, id: 84, weight: 1}\"adv_tuesday_17_forty_five\") OR bidAdjustmentDayPartingForCostCap contains ({normalizeCase: false, implicitTransforms: false, id: 85, weight: 1}\"adv_tuesday\") OR bidAdjustmentDayPartingForCostCap contains ({normalizeCase: false, implicitTransforms: false, id: 86, weight: 1}\"adv_tuesday_17\") OR bidAdjustmentDayPartingForCostCap contains ({normalizeCase: false, implicitTransforms: false, id: 87, weight: 1}\"adv_tuesday_17_forty_five\")), bidAdjustmentForCpi = ({id: 88, weight: 1}223), ({id: 89, label: \"boostingForBackfill\"}dotProduct(boostingForBackfill, {\"priority\": 1000})))",
- serializedQueryTreeYql);
+ serializedQueryTreeYql);
}
@Test
- public void testDottedFieldNames() {
+ void testDottedFieldNames() {
assertParse("select foo from bar where my.nested.title contains \"madonna\"",
"my.nested.title:madonna");
}
+
@Test
- public void testDottedNestedFieldNames() {
+ void testDottedNestedFieldNames() {
assertParse("select foo from bar where my.title contains \"madonna\"",
"my.title:madonna");
}
@Test
- public void testOr() {
+ void testOr() {
assertParse("select foo from bar where title contains \"madonna\" or title contains \"saint\"",
- "OR title:madonna title:saint");
+ "OR title:madonna title:saint");
assertParse("select foo from bar where title contains \"madonna\" or title contains \"saint\" or title " +
- "contains \"angel\"",
- "OR title:madonna title:saint title:angel");
+ "contains \"angel\"",
+ "OR title:madonna title:saint title:angel");
}
@Test
- public void testAnd() {
+ void testAnd() {
assertParse("select foo from bar where title contains \"madonna\" and title contains \"saint\"",
- "AND title:madonna title:saint");
+ "AND title:madonna title:saint");
assertParse("select foo from bar where title contains \"madonna\" and title contains \"saint\" and title " +
- "contains \"angel\"",
- "AND title:madonna title:saint title:angel");
+ "contains \"angel\"",
+ "AND title:madonna title:saint title:angel");
}
@Test
- public void testAndNot() {
+ void testAndNot() {
assertParse("select foo from bar where title contains \"madonna\" and !(title contains \"saint\")",
- "+title:madonna -title:saint");
+ "+title:madonna -title:saint");
}
@Test
- public void testSingleNot() {
+ void testSingleNot() {
assertParse("select foo from bar where !(title contains \"saint\")",
- "-title:saint");
+ "-title:saint");
}
@Test
- public void testMultipleNot() {
+ void testMultipleNot() {
assertParse("select foo from bar where !(title contains \"saint\") AND !(title contains \"etienne\")",
- "-title:saint -title:etienne");
+ "-title:saint -title:etienne");
}
@Test
- public void testLessThan() {
+ void testLessThan() {
assertParse("select foo from bar where price < 500", "price:<500");
assertParse("select foo from bar where 500 < price", "price:>500");
}
@Test
- public void testGreaterThan() {
+ void testGreaterThan() {
assertParse("select foo from bar where price > 500", "price:>500");
assertParse("select foo from bar where 500 > price", "price:<500");
}
@Test
- public void testLessThanOrEqual() {
+ void testLessThanOrEqual() {
assertParse("select foo from bar where price <= 500", "price:[;500]");
assertParse("select foo from bar where 500 <= price", "price:[500;]");
}
@Test
- public void testGreaterThanOrEqual() {
+ void testGreaterThanOrEqual() {
assertParse("select foo from bar where price >= 500", "price:[500;]");
assertParse("select foo from bar where 500 >= price", "price:[;500]");
}
@Test
- public void testEquality() {
+ void testEquality() {
assertParse("select foo from bar where price = 500", "price:500");
assertParse("select foo from bar where 500 = price", "price:500");
}
@Test
- public void testNegativeLessThan() {
+ void testNegativeLessThan() {
assertParse("select foo from bar where price < -500", "price:<-500");
assertParse("select foo from bar where -500 < price", "price:>-500");
}
@Test
- public void testNegativeGreaterThan() {
+ void testNegativeGreaterThan() {
assertParse("select foo from bar where price > -500", "price:>-500");
assertParse("select foo from bar where -500 > price", "price:<-500");
}
@Test
- public void testNegativeLessThanOrEqual() {
+ void testNegativeLessThanOrEqual() {
assertParse("select foo from bar where price <= -500", "price:[;-500]");
assertParse("select foo from bar where -500 <= price", "price:[-500;]");
}
@Test
- public void testNegativeGreaterThanOrEqual() {
+ void testNegativeGreaterThanOrEqual() {
assertParse("select foo from bar where price >= -500", "price:[-500;]");
assertParse("select foo from bar where -500 >= price", "price:[;-500]");
}
@Test
- public void testNegativeEquality() {
+ void testNegativeEquality() {
assertParse("select foo from bar where price = -500", "price:-500");
assertParse("select foo from bar where -500 = price", "price:-500");
}
@Test
- public void testAnnotatedLessThan() {
+ void testAnnotatedLessThan() {
assertParse("select foo from bar where price < ({filter: true}(-500))", "|price:<-500");
assertParse("select foo from bar where ({filter: true}500) < price", "|price:>500");
}
@Test
- public void testAnnotatedGreaterThan() {
+ void testAnnotatedGreaterThan() {
assertParse("select foo from bar where price > ({filter: true}500)", "|price:>500");
assertParse("select foo from bar where ({filter: true}(-500)) > price", "|price:<-500");
}
@Test
- public void testAnnotatedLessThanOrEqual() {
+ void testAnnotatedLessThanOrEqual() {
assertParse("select foo from bar where price <= ({filter: true}(-500))", "|price:[;-500]");
assertParse("select foo from bar where ({filter: true}500) <= price", "|price:[500;]");
}
@Test
- public void testAnnotatedGreaterThanOrEqual() {
+ void testAnnotatedGreaterThanOrEqual() {
assertParse("select foo from bar where price >= ({filter: true}500)", "|price:[500;]");
assertParse("select foo from bar where ({filter: true}(-500)) >= price", "|price:[;-500]");
}
@Test
- public void testAnnotatedEquality() {
+ void testAnnotatedEquality() {
assertParse("select foo from bar where price = ({filter: true}(-500))", "|price:-500");
assertParse("select foo from bar where ({filter: true}500) = price", "|price:500");
}
@Test
- public void testBoolean() {
+ void testBoolean() {
assertParse("select foo from bar where flag = true;", "flag:true");
QueryTree query = assertParse("select foo from bar where flag = false;", "flag:false");
assertEquals(BoolItem.class, query.getRoot().getClass());
- BoolItem item = (BoolItem)query.getRoot();
+ BoolItem item = (BoolItem) query.getRoot();
assertEquals("flag", item.getIndexName());
assertEquals(false, item.value());
}
@Test
- public void testTermAnnotations() {
+ void testTermAnnotations() {
assertEquals("merkelapp",
- getRootWord("select foo from bar where baz contains " +
- "({label: \"merkelapp\"}\"colors\")").getLabel());
+ getRootWord("select foo from bar where baz contains " +
+ "({label: \"merkelapp\"}\"colors\")").getLabel());
assertEquals("another",
- getRootWord("select foo from bar where baz contains " +
- "({annotations: {cox: \"another\"}}\"colors\")").getAnnotation("cox"));
+ getRootWord("select foo from bar where baz contains " +
+ "({annotations: {cox: \"another\"}}\"colors\")").getAnnotation("cox"));
assertEquals(23.0, getRootWord("select foo from bar where baz contains " +
- "({significance: 23.0}\"colors\")").getSignificance(), 1E-6);
+ "({significance: 23.0}\"colors\")").getSignificance(), 1E-6);
assertEquals(23, getRootWord("select foo from bar where baz contains " +
- "({id: 23}\"colors\")").getUniqueID());
+ "({id: 23}\"colors\")").getUniqueID());
assertEquals(150, getRootWord("select foo from bar where baz contains " +
- "({weight: 150}\"colors\")").getWeight());
+ "({weight: 150}\"colors\")").getWeight());
assertFalse(getRootWord("select foo from bar where baz contains " +
- "({usePositionData: false}\"colors\")").usePositionData());
+ "({usePositionData: false}\"colors\")").usePositionData());
assertTrue(getRootWord("select foo from bar where baz contains " +
- "({filter: true}\"colors\")").isFilter());
+ "({filter: true}\"colors\")").isFilter());
assertFalse(getRootWord("select foo from bar where baz contains " +
- "({ranked: false}\"colors\")").isRanked());
+ "({ranked: false}\"colors\")").isRanked());
Substring origin = getRootWord("select foo from bar where baz contains " +
- "({origin: {original: \"abc\", offset: 1, length: 2}}" +
- "\"colors\")").getOrigin();
+ "({origin: {original: \"abc\", offset: 1, length: 2}}" +
+ "\"colors\")").getOrigin();
assertEquals("abc", origin.string);
assertEquals(1, origin.start);
assertEquals(3, origin.end);
}
@Test
- public void testAnnotationsCanBeInBrackets() {
+ void testAnnotationsCanBeInBrackets() {
assertEquals("merkelapp",
- getRootWord("select foo from bar where baz contains " +
- "([ {label: \"merkelapp\"} ]\"colors\")").getLabel());
+ getRootWord("select foo from bar where baz contains " +
+ "([ {label: \"merkelapp\"} ]\"colors\")").getLabel());
}
@Test
- public void testValuesCanBeQuoted() {
+ void testValuesCanBeQuoted() {
assertEquals("merkelapp",
- getRootWord("select foo from bar where baz contains " +
- "( {label: \"merkelapp\"} \"colors\")").getLabel());
+ getRootWord("select foo from bar where baz contains " +
+ "( {label: \"merkelapp\"} \"colors\")").getLabel());
}
@Test
- public void testSameElement() {
+ void testSameElement() {
assertParse("select foo from bar where baz contains sameElement(f1 contains \"a\", f2 contains \"b\")",
"baz:{f1:a f2:b}");
assertParse("select foo from bar where baz contains sameElement(f1 contains \"a\", f2 = 10)",
@@ -361,27 +359,27 @@ public class YqlParserTestCase {
}
@Test
- public void testPhrase() {
+ void testPhrase() {
assertParse("select foo from bar where baz contains phrase(\"a\", \"b\")",
- "baz:\"a b\"");
+ "baz:\"a b\"");
}
@Test
- public void testNestedPhrase() {
+ void testNestedPhrase() {
assertParse("select foo from bar where baz contains phrase(\"a\", \"b\", phrase(\"c\", \"d\"))",
- "baz:\"a b c d\"");
+ "baz:\"a b c d\"");
}
@Test
- public void testNestedPhraseSegment() {
+ void testNestedPhraseSegment() {
assertParse("select foo from bar where baz contains " +
- "phrase(\"a\", \"b\", [ {origin: {original: \"c d\", offset: 0, length: 3}} ]" +
- "phrase(\"c\", \"d\"));",
- "baz:\"a b 'c d'\"");
+ "phrase(\"a\", \"b\", [ {origin: {original: \"c d\", offset: 0, length: 3}} ]" +
+ "phrase(\"c\", \"d\"));",
+ "baz:\"a b 'c d'\"");
}
@Test
- public void testFuzzy() {
+ void testFuzzy() {
QueryTree x = parse("select foo from bar where baz contains fuzzy(\"a b\")");
Item root = x.getRoot();
assertSame(FuzzyItem.class, root.getClass());
@@ -392,7 +390,7 @@ public class YqlParserTestCase {
}
@Test
- public void testFuzzyAnnotations() {
+ void testFuzzyAnnotations() {
QueryTree x = parse(
"select foo from bar where baz contains ({maxEditDistance: 3, prefixLength: 10}fuzzy(\"a b\"))"
);
@@ -405,17 +403,17 @@ public class YqlParserTestCase {
}
@Test
- public void testStemming() {
+ void testStemming() {
assertTrue(getRootWord("select foo from bar where baz contains " +
- "([ {stem: false} ]\"colors\")").isStemmed());
+ "([ {stem: false} ]\"colors\")").isStemmed());
assertFalse(getRootWord("select foo from bar where baz contains " +
- "([ {stem: true} ]\"colors\")").isStemmed());
+ "([ {stem: true} ]\"colors\")").isStemmed());
assertFalse(getRootWord("select foo from bar where baz contains " +
- "\"colors\"").isStemmed());
+ "\"colors\"").isStemmed());
}
@Test
- public void testRaw() {
+ void testRaw() {
// Default: Not raw, for comparison
Item root = parse("select foo from bar where baz contains (\"yoni jo dima\")").getRoot();
assertEquals("baz:'yoni jo dima'", root.toString());
@@ -426,7 +424,7 @@ public class YqlParserTestCase {
assertEquals("baz:yoni jo dima", root.toString());
assertTrue(root instanceof WordItem);
assertFalse(root instanceof ExactStringItem);
- assertEquals("yoni jo dima", ((WordItem)root).getWord());
+ assertEquals("yoni jo dima", ((WordItem) root).getWord());
root = parse("select foo from bar where {grammar:\"all\"}userInput(\"yoni jo dima\")").getRoot();
assertTrue(root instanceof AndItem);
@@ -436,232 +434,232 @@ public class YqlParserTestCase {
root = parse("select foo from bar where {grammar:\"raw\"}userInput(\"yoni jo dima\")").getRoot();
assertTrue(root instanceof WordItem);
assertTrue(root instanceof ExactStringItem);
- assertEquals("yoni jo dima", ((WordItem)root).getWord());
+ assertEquals("yoni jo dima", ((WordItem) root).getWord());
}
@Test
- public void testAccentDropping() {
+ void testAccentDropping() {
assertFalse(getRootWord("select foo from bar where baz contains " +
- "( {accentDrop: false} \"colors\")").isNormalizable());
+ "( {accentDrop: false} \"colors\")").isNormalizable());
assertTrue(getRootWord("select foo from bar where baz contains " +
- "( {accentDrop: true} \"colors\")").isNormalizable());
+ "( {accentDrop: true} \"colors\")").isNormalizable());
assertTrue(getRootWord("select foo from bar where baz contains " +
- "\"colors\"").isNormalizable());
+ "\"colors\"").isNormalizable());
}
@Test
- public void testCaseNormalization() {
+ void testCaseNormalization() {
assertTrue(getRootWord("select foo from bar where baz contains " +
- "( {normalizeCase: false} \"colors\")").isLowercased());
+ "( {normalizeCase: false} \"colors\")").isLowercased());
assertFalse(getRootWord("select foo from bar where baz contains " +
- "( {normalizeCase: true} \"colors\")").isLowercased());
+ "( {normalizeCase: true} \"colors\")").isLowercased());
assertFalse(getRootWord("select foo from bar where baz contains " +
- "\"colors\"").isLowercased());
+ "\"colors\"").isLowercased());
}
@Test
- public void testSegmentingRule() {
+ void testSegmentingRule() {
assertEquals(SegmentingRule.PHRASE,
- getRootWord("select foo from bar where baz contains " +
- "( {andSegmenting: false} \"colors\")").getSegmentingRule());
+ getRootWord("select foo from bar where baz contains " +
+ "( {andSegmenting: false} \"colors\")").getSegmentingRule());
assertEquals(SegmentingRule.BOOLEAN_AND,
- getRootWord("select foo from bar where baz contains " +
- "( {andSegmenting: true} \"colors\")").getSegmentingRule());
+ getRootWord("select foo from bar where baz contains " +
+ "( {andSegmenting: true} \"colors\")").getSegmentingRule());
assertEquals(SegmentingRule.LANGUAGE_DEFAULT,
- getRootWord("select foo from bar where baz contains " +
- "\"colors\"").getSegmentingRule());
+ getRootWord("select foo from bar where baz contains " +
+ "\"colors\"").getSegmentingRule());
}
@Test
- public void testNfkc() {
+ void testNfkc() {
assertEquals("a\u030a",
- getRootWord("select foo from bar where baz contains " +
- "( {nfkc: false} \"a\\u030a\")").getWord());
+ getRootWord("select foo from bar where baz contains " +
+ "( {nfkc: false} \"a\\u030a\")").getWord());
assertEquals("\u00e5",
- getRootWord("select foo from bar where baz contains " +
- "( {nfkc: true} \"a\\u030a\")").getWord());
- assertEquals("No NKFC by default",
- "a\u030a",
- getRootWord("select foo from bar where baz contains " +
- "(\"a\\u030a\")").getWord());
+ getRootWord("select foo from bar where baz contains " +
+ "( {nfkc: true} \"a\\u030a\")").getWord());
+ assertEquals("a\u030a",
+ getRootWord("select foo from bar where baz contains " +
+ "(\"a\\u030a\")").getWord(),
+ "No NKFC by default");
}
@Test
- public void testImplicitTransforms() {
+ void testImplicitTransforms() {
assertFalse(getRootWord("select foo from bar where baz contains ({implicitTransforms: " +
- "false} \"cox\")").isFromQuery());
+ "false} \"cox\")").isFromQuery());
assertTrue(getRootWord("select foo from bar where baz contains ({implicitTransforms: " +
- "true} \"cox\")").isFromQuery());
+ "true} \"cox\")").isFromQuery());
assertTrue(getRootWord("select foo from bar where baz contains \"cox\"").isFromQuery());
}
@Test
- public void testConnectivity() {
+ void testConnectivity() {
QueryTree parsed = parse("select foo from bar where " +
- "title contains ({id: 1, connectivity: {\"id\": 3, weight: 7.0}}\"madonna\") " +
- "and title contains ({id: 2}\"saint\") " +
- "and title contains ({id: 3}\"angel\")");
+ "title contains ({id: 1, connectivity: {\"id\": 3, weight: 7.0}}\"madonna\") " +
+ "and title contains ({id: 2}\"saint\") " +
+ "and title contains ({id: 3}\"angel\")");
assertEquals("AND title:madonna title:saint title:angel",
- parsed.toString());
- AndItem root = (AndItem)parsed.getRoot();
- WordItem first = (WordItem)root.getItem(0);
- WordItem second = (WordItem)root.getItem(1);
- WordItem third = (WordItem)root.getItem(2);
- assertTrue(first.getConnectedItem() == third);
+ parsed.toString());
+ AndItem root = (AndItem) parsed.getRoot();
+ WordItem first = (WordItem) root.getItem(0);
+ WordItem second = (WordItem) root.getItem(1);
+ WordItem third = (WordItem) root.getItem(2);
+ assertEquals(first.getConnectedItem(), third);
assertEquals(first.getConnectivity(), 7.0d, 1E-6);
assertNull(second.getConnectedItem());
assertParseFail("select foo from bar where " +
- "title contains ({id: 1, connectivity: {id: 4, weight: 7.0}}\"madonna\") " +
- "and title contains ({id: 2}\"saint\") " +
- "and title contains ({id: 3}\"angel\")",
- new IllegalArgumentException("Item 'title:madonna' was specified to connect to item with ID 4, " +
- "which does not exist in the query."));
+ "title contains ({id: 1, connectivity: {id: 4, weight: 7.0}}\"madonna\") " +
+ "and title contains ({id: 2}\"saint\") " +
+ "and title contains ({id: 3}\"angel\")",
+ new IllegalArgumentException("Item 'title:madonna' was specified to connect to item with ID 4, " +
+ "which does not exist in the query."));
}
@Test
- public void testAnnotatedPhrase() {
+ void testAnnotatedPhrase() {
QueryTree parsed =
parse("select foo from bar where baz contains ({label: \"hello world\"}phrase(\"a\", \"b\"))");
assertEquals("baz:\"a b\"", parsed.toString());
- PhraseItem phrase = (PhraseItem)parsed.getRoot();
+ PhraseItem phrase = (PhraseItem) parsed.getRoot();
assertEquals("hello world", phrase.getLabel());
}
@Test
- public void testRange() {
+ void testRange() {
QueryTree parsed = parse("select foo from bar where range(baz,1,8)");
assertEquals("baz:[1;8]", parsed.toString());
}
@Test
- public void testRangeWithEndInfinity() {
+ void testRangeWithEndInfinity() {
QueryTree parsed = parse("select foo from bar where range(baz,1,Infinity)");
assertEquals("baz:[1;]", parsed.toString());
}
@Test
- public void testRangeWithStartInfinity() {
+ void testRangeWithStartInfinity() {
QueryTree parsed = parse("select foo from bar where range(baz,-Infinity,8)");
assertEquals("baz:[;8]", parsed.toString());
}
@Test
- public void testNegativeRange() {
+ void testNegativeRange() {
QueryTree parsed = parse("select foo from bar where range(baz,-8,-1)");
assertEquals("baz:[-8;-1]", parsed.toString());
}
@Test
- public void testRangeIllegalArguments() {
+ void testRangeIllegalArguments() {
assertParseFail("select foo from bar where range(baz,cox,8)",
- new IllegalArgumentException("Expected a numerical argument (or 'Infinity') to range but got 'cox'"));
+ new IllegalArgumentException("Expected a numerical argument (or 'Infinity') to range but got 'cox'"));
}
@Test
- public void testNear() {
+ void testNear() {
assertParse("select foo from bar where description contains near(\"a\", \"b\")",
- "NEAR(2) description:a description:b");
+ "NEAR(2) description:a description:b");
assertParse("select foo from bar where description contains ({distance: 100} near(\"a\", \"b\"))",
- "NEAR(100) description:a description:b");
+ "NEAR(100) description:a description:b");
}
@Test
- public void testOrderedNear() {
+ void testOrderedNear() {
assertParse("select foo from bar where description contains onear(\"a\", \"b\");",
- "ONEAR(2) description:a description:b");
+ "ONEAR(2) description:a description:b");
assertParse("select foo from bar where description contains ({distance: 100} onear(\"a\", \"b\"))",
- "ONEAR(100) description:a description:b");
+ "ONEAR(100) description:a description:b");
}
@Test
- public void testWand() {
+ void testWand() {
assertParse("select foo from bar where wand(description, {\"a\":1, \"b\":2});",
"WAND(10,0.0,1.0) description{[1]:\"a\",[2]:\"b\"}");
assertParse("select foo from bar where {scoreThreshold : 13.3, targetHits: 7, " +
- "thresholdBoostFactor: 2.3} wand(description, {\"a\":1, \"b\":2})",
- "WAND(7,13.3,2.3) description{[1]:\"a\",[2]:\"b\"}");
+ "thresholdBoostFactor: 2.3} wand(description, {\"a\":1, \"b\":2})",
+ "WAND(7,13.3,2.3) description{[1]:\"a\",[2]:\"b\"}");
}
@Test
- public void testQuotedAnnotations() {
+ void testQuotedAnnotations() {
assertParse("select foo from bar where {\"scoreThreshold\": 13.3, \"targetHits\": 7, " +
- "'thresholdBoostFactor': 2.3} wand(description, {\"a\":1})",
- "WAND(7,13.3,2.3) description{[1]:\"a\"}");
+ "'thresholdBoostFactor': 2.3} wand(description, {\"a\":1})",
+ "WAND(7,13.3,2.3) description{[1]:\"a\"}");
}
@Test
- public void testNumericWand() {
+ void testNumericWand() {
String numWand = "WAND(10,0.0,1.0) description{[1]:\"11\",[2]:\"37\"}";
assertParse("select foo from bar where wand(description, [[11,1], [37,2]])", numWand);
assertParse("select foo from bar where wand(description, [[11L,1], [37L,2]])", numWand);
assertParseFail("select foo from bar where wand(description, 12);",
- new IllegalArgumentException("Expected ARRAY or MAP, got LITERAL."));
+ new IllegalArgumentException("Expected ARRAY or MAP, got LITERAL."));
}
- @Test
//This test is order dependent. Fix it!
- public void testWeightedSet() {
+ @Test
+ void testWeightedSet() {
assertParse("select foo from bar where weightedSet(description, {\"a\":1, \"b\":2})",
- "WEIGHTEDSET description{[1]:\"a\",[2]:\"b\"}");
+ "WEIGHTEDSET description{[1]:\"a\",[2]:\"b\"}");
assertParseFail("select foo from bar where weightedSet(description, {\"a\":g, \"b\":2})",
- new IllegalInputException("com.yahoo.search.yql.ProgramCompileException: " +
- "query:L1:56 no viable alternative at input 'weightedSet(description, {\"a\":g'"));
+ new IllegalInputException("com.yahoo.search.yql.ProgramCompileException: " +
+ "query:L1:56 no viable alternative at input 'weightedSet(description, {\"a\":g'"));
assertParseFail("select foo from bar where weightedSet(description);",
- new IllegalArgumentException("Expected 2 arguments, got 1."));
+ new IllegalArgumentException("Expected 2 arguments, got 1."));
}
//This test is order dependent. Fix it!
@Test
- public void testDotProduct() {
+ void testDotProduct() {
assertParse("select foo from bar where dotProduct(description, {\"a\":1, \"b\":2})",
- "DOTPRODUCT description{[1]:\"a\",[2]:\"b\"}");
+ "DOTPRODUCT description{[1]:\"a\",[2]:\"b\"}");
assertParse("select foo from bar where dotProduct(description, {\"a\":2})",
- "DOTPRODUCT description{[2]:\"a\"}");
+ "DOTPRODUCT description{[2]:\"a\"}");
}
@Test
- public void testGeoLocation() {
+ void testGeoLocation() {
assertParse("select foo from bar where geoLocation(workplace, 63.418417, 10.433033, \"0.5 deg\")",
- "GEO_LOCATION workplace:(2,10433033,63418417,500000,0,1,0,1921876103)");
+ "GEO_LOCATION workplace:(2,10433033,63418417,500000,0,1,0,1921876103)");
assertParse("select foo from bar where geoLocation(headquarters, \"37.416383\", \"-122.024683\", \"100 miles\")",
- "GEO_LOCATION headquarters:(2,-122024683,37416383,1450561,0,1,0,3411238761)");
+ "GEO_LOCATION headquarters:(2,-122024683,37416383,1450561,0,1,0,3411238761)");
assertParse("select foo from bar where geoLocation(home, \"E10.433033\", \"N63.418417\", \"5km\")",
- "GEO_LOCATION home:(2,10433033,63418417,45066,0,1,0,1921876103)");
+ "GEO_LOCATION home:(2,10433033,63418417,45066,0,1,0,1921876103)");
assertParseFail("select foo from bar where geoLocation(qux, 1, 2)",
- new IllegalArgumentException("Expected 4 arguments, got 3."));
+ new IllegalArgumentException("Expected 4 arguments, got 3."));
assertParseFail("select foo from bar where geoLocation(qux, 2.0, \"N5.0\", \"0.5 deg\");",
- new IllegalArgumentException(
- "Invalid geoLocation coordinates 'Latitude: 2.0 degrees' and 'Latitude: 5.0 degrees'"));
+ new IllegalArgumentException(
+ "Invalid geoLocation coordinates 'Latitude: 2.0 degrees' and 'Latitude: 5.0 degrees'"));
assertParse("select foo from bar where geoLocation(workplace, -12, -34, \"-77 d\")",
- "GEO_LOCATION workplace:(2,-34000000,-12000000,-1,0,1,0,4201111954)");
+ "GEO_LOCATION workplace:(2,-34000000,-12000000,-1,0,1,0,4201111954)");
}
@Test
- public void testNearestNeighbor() {
+ void testNearestNeighbor() {
assertParse("select foo from bar where nearestNeighbor(semantic_embedding, my_vector);",
- "NEAREST_NEIGHBOR {field=semantic_embedding,queryTensorName=my_vector,hnsw.exploreAdditionalHits=0,distanceThreshold=Infinity,approximate=true,targetHits=0}");
+ "NEAREST_NEIGHBOR {field=semantic_embedding,queryTensorName=my_vector,hnsw.exploreAdditionalHits=0,distanceThreshold=Infinity,approximate=true,targetHits=0}");
assertParse("select foo from bar where {targetHits: 37} nearestNeighbor(semantic_embedding, my_vector)",
- "NEAREST_NEIGHBOR {field=semantic_embedding,queryTensorName=my_vector,hnsw.exploreAdditionalHits=0,distanceThreshold=Infinity,approximate=true,targetHits=37}");
+ "NEAREST_NEIGHBOR {field=semantic_embedding,queryTensorName=my_vector,hnsw.exploreAdditionalHits=0,distanceThreshold=Infinity,approximate=true,targetHits=37}");
assertParse("select foo from bar where {approximate: false, hnsw.exploreAdditionalHits: 8, targetHits: 3} nearestNeighbor(semantic_embedding, my_vector)",
- "NEAREST_NEIGHBOR {field=semantic_embedding,queryTensorName=my_vector,hnsw.exploreAdditionalHits=8,distanceThreshold=Infinity,approximate=false,targetHits=3}");
+ "NEAREST_NEIGHBOR {field=semantic_embedding,queryTensorName=my_vector,hnsw.exploreAdditionalHits=8,distanceThreshold=Infinity,approximate=false,targetHits=3}");
assertParse("select foo from bar where {targetHits: 7, distanceThreshold: 100100.25} nearestNeighbor(semantic_embedding, my_vector)",
- "NEAREST_NEIGHBOR {field=semantic_embedding,queryTensorName=my_vector,hnsw.exploreAdditionalHits=0,distanceThreshold=100100.25,approximate=true,targetHits=7}");
+ "NEAREST_NEIGHBOR {field=semantic_embedding,queryTensorName=my_vector,hnsw.exploreAdditionalHits=0,distanceThreshold=100100.25,approximate=true,targetHits=7}");
}
@Test
- public void testTrueAndFalse() {
+ void testTrueAndFalse() {
assertParse("select foo from bar where true", "TRUE");
assertParse("select foo from bar where false", "FALSE");
assertParse("select foo from bar where ((title contains \"foo\") AND true) AND !((title contains \"bar\") or false)",
- "+(AND title:foo TRUE) -(OR title:bar FALSE)");
+ "+(AND title:foo TRUE) -(OR title:bar FALSE)");
}
@Test
- public void testPredicate() {
+ void testPredicate() {
assertParse("select foo from bar where predicate(predicate_field, " +
"{\"gender\":\"male\", \"hobby\":[\"music\", \"hiking\"]}, {\"age\":23L})",
"PREDICATE_QUERY_ITEM gender=male, hobby=music, hobby=hiking, age:23");
@@ -673,113 +671,113 @@ public class YqlParserTestCase {
}
@Test
- public void testPredicateWithSubQueries() {
+ void testPredicateWithSubQueries() {
assertParse("select foo from bar where predicate(predicate_field, " +
"{\"0x03\":{\"gender\":\"male\"},\"0x01\":{\"hobby\":[\"music\", \"hiking\"]}}, {\"0x80ffffffffffffff\":{\"age\":23L}})",
"PREDICATE_QUERY_ITEM gender=male[0x3], hobby=music[0x1], hobby=hiking[0x1], age:23[0x80ffffffffffffff]");
assertParseFail("select foo from bar where predicate(foo, null, {\"0x80000000000000000\":{\"age\":23}})",
new NumberFormatException("Too long subquery string: 0x80000000000000000"));
assertParse("select foo from bar where predicate(predicate_field, " +
- "{\"[0,1]\":{\"gender\":\"male\"},\"[0]\":{\"hobby\":[\"music\", \"hiking\"]}}, {\"[62, 63]\":{\"age\":23L}})",
+ "{\"[0,1]\":{\"gender\":\"male\"},\"[0]\":{\"hobby\":[\"music\", \"hiking\"]}}, {\"[62, 63]\":{\"age\":23L}})",
"PREDICATE_QUERY_ITEM gender=male[0x3], hobby=music[0x1], hobby=hiking[0x1], age:23[0xc000000000000000]");
}
@Test
- public void testRank() {
+ void testRank() {
assertParse("select foo from bar where rank(a contains \"A\", b contains \"B\")",
- "RANK a:A b:B");
+ "RANK a:A b:B");
assertParse("select foo from bar where rank(a contains \"A\", b contains \"B\", c " +
- "contains \"C\")",
- "RANK a:A b:B c:C");
+ "contains \"C\")",
+ "RANK a:A b:B c:C");
assertParse("select foo from bar where rank(a contains \"A\", b contains \"B\" or c " +
- "contains \"C\")",
- "RANK a:A (OR b:B c:C)");
+ "contains \"C\")",
+ "RANK a:A (OR b:B c:C)");
}
@Test
@SuppressWarnings("deprecation")
- public void testWeakAnd() {
+ void testWeakAnd() {
assertParse("select foo from bar where weakAnd(a contains \"A\", b contains \"B\")",
- "WEAKAND(100) a:A b:B");
+ "WEAKAND(100) a:A b:B");
assertParse("select foo from bar where {targetHits: 37}weakAnd(a contains \"A\", " +
- "b contains \"B\")",
- "WEAKAND(37) a:A b:B");
+ "b contains \"B\")",
+ "WEAKAND(37) a:A b:B");
QueryTree tree = parse("select foo from bar where weakAnd(a " +
- "contains \"A\", b contains \"B\")");
+ "contains \"A\", b contains \"B\")");
assertEquals("WEAKAND(100) a:A b:B", tree.toString());
assertEquals(WeakAndItem.class, tree.getRoot().getClass());
}
@Test
- public void testEquiv() {
+ void testEquiv() {
assertParse("select foo from bar where fieldName contains equiv(\"A\",\"B\")",
- "EQUIV fieldName:A fieldName:B");
+ "EQUIV fieldName:A fieldName:B");
assertParse("select foo from bar where fieldName contains " +
- "equiv(\"ny\",phrase(\"new\",\"york\"));",
- "EQUIV fieldName:ny fieldName:\"new york\"");
+ "equiv(\"ny\",phrase(\"new\",\"york\"));",
+ "EQUIV fieldName:ny fieldName:\"new york\"");
assertParseFail("select foo from bar where fieldName contains equiv(\"ny\")",
- new IllegalArgumentException("Expected 2 or more arguments, got 1."));
+ new IllegalArgumentException("Expected 2 or more arguments, got 1."));
assertParseFail("select foo from bar where fieldName contains equiv(\"ny\", nalle(void))",
- new IllegalArgumentException("Expected function 'phrase', got 'nalle'."));
+ new IllegalArgumentException("Expected function 'phrase', got 'nalle'."));
assertParseFail("select foo from bar where fieldName contains equiv(\"ny\", 42)",
- new ClassCastException("Cannot cast java.lang.Integer to java.lang.String"));
+ new ClassCastException("Cannot cast java.lang.Integer to java.lang.String"));
}
@Test
- public void testAffixItems() {
+ void testAffixItems() {
assertRootClass("select foo from bar where baz contains ({suffix: true}\"colors\")",
- SuffixItem.class);
+ SuffixItem.class);
assertRootClass("select foo from bar where baz contains ({prefix: true}\"colors\")",
- PrefixItem.class);
+ PrefixItem.class);
assertRootClass("select foo from bar where baz contains ({substring: true}\"colors\")",
- SubstringItem.class);
+ SubstringItem.class);
assertParseFail("select foo from bar where description contains ({suffix: true, " +
- "prefix: true}\"colors\")",
- new IllegalArgumentException("Only one of prefix, substring and suffix can be set."));
+ "prefix: true}\"colors\")",
+ new IllegalArgumentException("Only one of prefix, substring and suffix can be set."));
assertParseFail("select foo from bar where description contains ({suffix: true, " +
- "substring: true}\"colors\")",
- new IllegalArgumentException("Only one of prefix, substring and suffix can be set."));
+ "substring: true}\"colors\")",
+ new IllegalArgumentException("Only one of prefix, substring and suffix can be set."));
}
@Test
- public void testLongNumberInSimpleExpression() {
+ void testLongNumberInSimpleExpression() {
assertParse("select foo from bar where price = 8589934592L", "price:8589934592");
assertParse("select foo from bar where price = 8589934592", "price:8589934592");
}
@Test
- public void testNegativeLongNumberInSimpleExpression() {
+ void testNegativeLongNumberInSimpleExpression() {
assertParse("select foo from bar where price = -8589934592L", "price:-8589934592");
}
@Test
- public void testSources() {
+ void testSources() {
assertSources("select foo from sourceA where price <= 500", List.of("sourceA"));
}
@Test
- public void testQueryWithSemicolon() {
+ void testQueryWithSemicolon() {
assertParse("select foo from bar where price = 1", "price:1");
}
@Test
- public void testSourcesWithDash() {
+ void testSourcesWithDash() {
assertSources("select foo from source-a where price <= 500", List.of("source-a"));
}
@Test
- public void testWildCardSources() {
+ void testWildCardSources() {
assertSources("select foo from sources * where price <= 500", List.of());
}
@Test
- public void testMultiSources() {
+ void testMultiSources() {
assertSources("select foo from sources sourceA, sourceB where price <= 500", List.of("sourceA", "sourceB"));
}
@Test
- public void testFields() {
+ void testFields() {
assertSummaryFields("select fieldA from bar where price <= 500", List.of("fieldA"));
assertSummaryFields("select fieldA, fieldB from bar where price <= 500", List.of("fieldA", "fieldB"));
assertSummaryFields("select fieldA, fieldB, fieldC from bar where price <= 500", List.of("fieldA", "fieldB", "fieldC"));
@@ -787,37 +785,37 @@ public class YqlParserTestCase {
}
@Test
- public void testFieldsRoot() {
+ void testFieldsRoot() {
assertParse("select * from bar where price <= 500", "price:[;500]");
}
@Test
- public void testOffset() {
+ void testOffset() {
assertParse("select foo from bar where title contains \"madonna\" offset 37", "title:madonna");
assertEquals(Integer.valueOf(37), parser.getOffset());
}
@Test
- public void testLimit() {
+ void testLimit() {
assertParse("select foo from bar where title contains \"madonna\" limit 29", "title:madonna");
assertEquals(Integer.valueOf(29), parser.getHits());
}
@Test
- public void testOffsetAndLimit() {
+ void testOffsetAndLimit() {
assertParse("select foo from bar where title contains \"madonna\" limit 31 offset 29",
- "title:madonna");
+ "title:madonna");
assertEquals(Integer.valueOf(29), parser.getOffset());
assertEquals(Integer.valueOf(2), parser.getHits());
assertParse("select * from bar where title contains \"madonna\" limit 41 offset 37",
- "title:madonna");
+ "title:madonna");
assertEquals(Integer.valueOf(37), parser.getOffset());
assertEquals(Integer.valueOf(4), parser.getHits());
}
@Test
- public void testTimeout() {
+ void testTimeout() {
assertParse("select * from bar where title contains \"madonna\" timeout 7", "title:madonna");
assertEquals(Integer.valueOf(7), parser.getTimeout());
@@ -826,10 +824,10 @@ public class YqlParserTestCase {
}
@Test
- public void testOrdering() {
+ void testOrdering() {
assertParse("select foo from bar where title contains \"madonna\" order by something asc, " +
- "shoesize desc limit 600 timeout 3",
- "title:madonna");
+ "shoesize desc limit 600 timeout 3",
+ "title:madonna");
assertEquals(2, parser.getSorting().fieldOrders().size());
assertEquals("something", parser.getSorting().fieldOrders().get(0).getFieldName());
assertEquals(Order.ASCENDING, parser.getSorting().fieldOrders().get(0).getSortOrder());
@@ -837,14 +835,14 @@ public class YqlParserTestCase {
assertEquals(Order.DESCENDING, parser.getSorting().fieldOrders().get(1).getSortOrder());
assertParse("select foo from bar where title contains \"madonna\" order by other limit 600 " +
- "timeout 3",
- "title:madonna");
+ "timeout 3",
+ "title:madonna");
assertEquals("other", parser.getSorting().fieldOrders().get(0).getFieldName());
assertEquals(Order.ASCENDING, parser.getSorting().fieldOrders().get(0).getSortOrder());
}
@Test
- public void testAnnotatedOrdering() {
+ void testAnnotatedOrdering() {
assertParse(
"select foo from bar where title contains \"madonna\""
+ " order by {function: \"uca\", locale: \"en_US\", strength: \"IDENTICAL\"}other desc"
@@ -860,7 +858,7 @@ public class YqlParserTestCase {
}
@Test
- public void testMultipleAnnotatedOrdering() {
+ void testMultipleAnnotatedOrdering() {
assertParse(
"select foo from bar where title contains \"madonna\""
+ " order by {\"function\": \"uca\", \"locale\": \"en_US\", \"strength\": \"IDENTICAL\"}other desc,"
@@ -886,40 +884,40 @@ public class YqlParserTestCase {
}
@Test
- public void testSegmenting() {
+ void testSegmenting() {
assertParse("select * from bar where title contains 'foo.bar'", "title:'foo bar'");
assertParse("select * from bar where title contains 'foo&123'", "title:'foo 123'");
}
@Test
- public void testNegativeHitLimit() {
+ void testNegativeHitLimit() {
assertParse("select * from sources * where {hitLimit: -38}range(foo, 0, 1)", "foo:[0;1;-38]");
}
@Test
- public void testRangeSearchHitPopulationOrdering() {
+ void testRangeSearchHitPopulationOrdering() {
assertParse("select * from sources * where {hitLimit: 38, ascending: true}range(foo, 0, 1)",
- "foo:[0;1;38]");
+ "foo:[0;1;38]");
assertParse("select * from sources * where {hitLimit: 38, ascending: false}range(foo, 0, 1)",
- "foo:[0;1;-38]");
+ "foo:[0;1;-38]");
assertParse("select * from sources * where {hitLimit: 38, descending: true}range(foo, 0, 1)",
- "foo:[0;1;-38]");
+ "foo:[0;1;-38]");
assertParse("select * from sources * where {hitLimit: 38, descending: false}range(foo, 0, 1)",
- "foo:[0;1;38]");
+ "foo:[0;1;38]");
boolean gotExceptionFromParse = false;
try {
parse("select * from sources * where {hitLimit: 38, ascending: true, descending: false}range(foo, 0, 1)");
} catch (IllegalArgumentException e) {
- assertTrue("Expected information about abuse of settings.",
- e.getMessage().contains("both ascending and descending ordering set"));
+ assertTrue(e.getMessage().contains("both ascending and descending ordering set"),
+ "Expected information about abuse of settings.");
gotExceptionFromParse = true;
}
assertTrue(gotExceptionFromParse);
}
@Test
- public void testOpenIntervals() {
+ void testOpenIntervals() {
assertParse("select * from sources * where range(title, 0.0, 500.0)",
"title:[0.0;500.0]");
assertParse(
@@ -934,7 +932,7 @@ public class YqlParserTestCase {
}
@Test
- public void testInheritedAnnotations() {
+ void testInheritedAnnotations() {
{
QueryTree x = parse("select * from sources * where ({ranked: false}(foo contains \"a\" and bar contains \"b\")) or foor contains ({ranked: false}\"c\")");
List<IndexedItem> terms = QueryTree.getPositiveTerms(x);
@@ -954,12 +952,12 @@ public class YqlParserTestCase {
}
@Test
- public void testMoreInheritedAnnotations() {
+ void testMoreInheritedAnnotations() {
String yqlQuery = "select * from sources * where " +
- "({ranked: false}(foo contains \"a\" " +
- "and ({ranked: true}(bar contains \"b\" " +
- "or ({ranked: false}(foo contains \"c\" " +
- "and foo contains ({ranked: true}\"d\")))))))";
+ "({ranked: false}(foo contains \"a\" " +
+ "and ({ranked: true}(bar contains \"b\" " +
+ "or ({ranked: false}(foo contains \"c\" " +
+ "and foo contains ({ranked: true}\"d\")))))))";
QueryTree x = parse(yqlQuery);
List<IndexedItem> terms = QueryTree.getPositiveTerms(x);
assertEquals(4, terms.size());
@@ -980,11 +978,11 @@ public class YqlParserTestCase {
}
@Test
- public void testFieldAliases() {
+ void testFieldAliases() {
IndexInfoConfig modelConfig = new IndexInfoConfig(new IndexInfoConfig.Builder().indexinfo(new Indexinfo.Builder()
.name("music").command(new Command.Builder().indexname("title").command("index"))
.alias(new Alias.Builder().alias("song").indexname("title"))));
- IndexModel model = new IndexModel(modelConfig, (QrSearchersConfig)null);
+ IndexModel model = new IndexModel(modelConfig, (QrSearchersConfig) null);
IndexFacts indexFacts = new IndexFacts(model);
ParserEnvironment parserEnvironment = new ParserEnvironment().setIndexFacts(indexFacts);
@@ -999,7 +997,7 @@ public class YqlParserTestCase {
}
@Test
- public void testRegexp() {
+ void testRegexp() {
QueryTree x = parse("select * from sources * where foo matches \"a b\"");
Item root = x.getRoot();
assertSame(RegExpItem.class, root.getClass());
@@ -1007,7 +1005,7 @@ public class YqlParserTestCase {
}
@Test
- public void testWordAlternatives() {
+ void testWordAlternatives() {
QueryTree x = parse("select * from sources * where foo contains alternatives({trees: 1.0, \"tree\": 0.7})");
Item root = x.getRoot();
assertSame(WordAlternativesItem.class, root.getClass());
@@ -1016,10 +1014,10 @@ public class YqlParserTestCase {
}
@Test
- public void testWordAlternativesWithOrigin() {
+ void testWordAlternativesWithOrigin() {
QueryTree q = parse("select * from sources * where foo contains" +
- " ({origin: {original: \" trees \", offset: 1, length: 5}}" +
- "alternatives({trees: 1.0, tree: 0.7}))");
+ " ({origin: {original: \" trees \", offset: 1, length: 5}}" +
+ "alternatives({trees: 1.0, tree: 0.7}))");
Item root = q.getRoot();
assertSame(WordAlternativesItem.class, root.getClass());
WordAlternativesItem alternatives = (WordAlternativesItem) root;
@@ -1032,9 +1030,9 @@ public class YqlParserTestCase {
}
@Test
- public void testWordAlternativesInPhrase() {
+ void testWordAlternativesInPhrase() {
QueryTree q = parse("select * from sources * where" +
- " foo contains phrase(\"forest\", alternatives({trees: 1.0, tree: 0.7}))");
+ " foo contains phrase(\"forest\", alternatives({trees: 1.0, tree: 0.7}))");
Item root = q.getRoot();
assertSame(PhraseItem.class, root.getClass());
PhraseItem phrase = (PhraseItem) root;
@@ -1046,7 +1044,7 @@ public class YqlParserTestCase {
/** Verifies that we can search for a backslash */
@Test
- public void testBackslash() {
+ void testBackslash() {
{
String queryString = "select * from testtype where title contains \"\\\\\""; // Java escaping * YQL escaping
@@ -1063,7 +1061,7 @@ public class YqlParserTestCase {
}
@Test
- public void testUrlHostSearchingDefaultAnchors() {
+ void testUrlHostSearchingDefaultAnchors() {
// Simple query syntax, for reference
assertUrlQuery("urlfield.hostname", new Query("?query=urlfield.hostname:google.com&type=all"), false, true, true);
@@ -1074,7 +1072,7 @@ public class YqlParserTestCase {
}
@Test
- public void testUrlHostSearchingNoAnchors() {
+ void testUrlHostSearchingNoAnchors() {
// Simple query syntax, for reference
assertUrlQuery("urlfield.hostname", new Query("?query=urlfield.hostname:google.com*&type=all"), false, false, true);
@@ -1085,7 +1083,7 @@ public class YqlParserTestCase {
}
@Test
- public void testUrlHostSearchingBothAnchors() {
+ void testUrlHostSearchingBothAnchors() {
// Simple query syntax, for reference
assertUrlQuery("urlfield.hostname", new Query("?query=urlfield.hostname:%5Egoogle.com&type=all"), true, true, true); // %5E = ^
@@ -1096,7 +1094,7 @@ public class YqlParserTestCase {
}
@Test
- public void testUriNonHostDoesNotCreateAnchors() {
+ void testUriNonHostDoesNotCreateAnchors() {
// Simple query syntax, for reference
assertUrlQuery("urlfield", new Query("?query=urlfield:google.com&type=all"), false, false, false);
@@ -1107,13 +1105,13 @@ public class YqlParserTestCase {
}
@Test
- public void testReservedWordInSource() {
+ void testReservedWordInSource() {
parse("select * from sources like where text contains \"test\"");
// success: parsed without exception
}
@Test
- public void testAndSegmenting() {
+ void testAndSegmenting() {
parse("select * from sources * where (default contains ({stem: false}\"m\") AND default contains ({origin: {original: \"m\'s\", offset: 0, length: 3}, andSegmenting: true}phrase(\"m\", \"s\"))) timeout 472");
}
@@ -1198,11 +1196,11 @@ public class YqlParserTestCase {
assertEquals(2, alternatives.getAlternatives().size());
for (WordAlternativesItem.Alternative alternative : alternatives.getAlternatives()) {
if (tree.equals(alternative.word)) {
- assertFalse("Duplicate term introduced", seenTree);
+ assertFalse(seenTree, "Duplicate term introduced");
seenTree = true;
assertEquals(.7d, alternative.exactness, 1e-15d);
} else if (forest.equals(alternative.word)) {
- assertFalse("Duplicate term introduced", seenForest);
+ assertFalse(seenForest, "Duplicate term introduced");
seenForest = true;
assertEquals(1.0d, alternative.exactness, 1e-15d);
} else {
diff --git a/container-search/src/test/java/com/yahoo/select/SelectTestCase.java b/container-search/src/test/java/com/yahoo/select/SelectTestCase.java
index 6ebcc3a1aae..887a1a3a033 100644
--- a/container-search/src/test/java/com/yahoo/select/SelectTestCase.java
+++ b/container-search/src/test/java/com/yahoo/select/SelectTestCase.java
@@ -33,18 +33,12 @@ import com.yahoo.search.query.SelectParser;
import com.yahoo.search.query.parser.Parsable;
import com.yahoo.search.query.parser.ParserEnvironment;
import com.yahoo.search.yql.VespaGroupingStep;
-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.assertFalse;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertNull;
-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.*;
/**
* Tests Query.Select
@@ -61,7 +55,7 @@ public class SelectTestCase {
//------------------------------------------------------------------- "where" tests
@Test
- public void test_contains() {
+ void test_contains() {
ObjectNode json = jsonMapper.createObjectNode();
ArrayNode arrayNode = jsonMapper.createArrayNode();
arrayNode.add("default").add("foo");
@@ -70,22 +64,21 @@ public class SelectTestCase {
}
@Test
- public void test() {
+ void test() {
assertParse("{'contains' : ['title', 'madonna']}",
"title:madonna");
}
@Test
- public void testDottedFieldNames() {
+ void testDottedFieldNames() {
assertParse("{ 'contains' : ['my.nested.title', 'madonna']}",
"my.nested.title:madonna");
}
-
@Test
- public void testOr() throws Exception {
+ void testOr() throws Exception {
ObjectNode json_two_or = jsonMapper.createObjectNode();
ObjectNode json_three_or = jsonMapper.createObjectNode();
ArrayNode contains1 = jsonMapper.createArrayNode().add("title").add("madonna");
@@ -107,7 +100,7 @@ public class SelectTestCase {
}
@Test
- public void testAnd() throws Exception{
+ void testAnd() throws Exception {
ObjectNode json_two_and = jsonMapper.createObjectNode();
ObjectNode json_three_and = jsonMapper.createObjectNode();
ArrayNode contains1 = jsonMapper.createArrayNode().add("title").add("madonna");
@@ -129,7 +122,7 @@ public class SelectTestCase {
}
@Test
- public void testAndNot() {
+ void testAndNot() {
ObjectNode json_and_not = jsonMapper.createObjectNode();
ArrayNode contains1 = jsonMapper.createArrayNode().add("title").add("madonna");
ArrayNode contains2 = jsonMapper.createArrayNode().add("title").add("saint");
@@ -146,7 +139,7 @@ public class SelectTestCase {
}
@Test
- public void testLessThan() {
+ void testLessThan() {
ObjectNode range_json = jsonMapper.createObjectNode();
ObjectNode operators = jsonMapper.createObjectNode();
operators.put("<", 500);
@@ -160,7 +153,7 @@ public class SelectTestCase {
}
@Test
- public void testGreaterThan() {
+ void testGreaterThan() {
ObjectNode range_json = jsonMapper.createObjectNode();
ObjectNode operators = jsonMapper.createObjectNode();
operators.put(">", 500);
@@ -174,7 +167,7 @@ public class SelectTestCase {
}
@Test
- public void testLessThanOrEqual() {
+ void testLessThanOrEqual() {
ObjectNode range_json = jsonMapper.createObjectNode();
ObjectNode operators = jsonMapper.createObjectNode();
operators.put("<=", 500);
@@ -188,7 +181,7 @@ public class SelectTestCase {
}
@Test
- public void testGreaterThanOrEqual() {
+ void testGreaterThanOrEqual() {
ObjectNode range_json = jsonMapper.createObjectNode();
ObjectNode operators = jsonMapper.createObjectNode();
operators.put(">=", 500);
@@ -202,7 +195,7 @@ public class SelectTestCase {
}
@Test
- public void testEquality() {
+ void testEquality() {
ObjectNode range_json = jsonMapper.createObjectNode();
ObjectNode operators = jsonMapper.createObjectNode();
operators.put("=", 500);
@@ -216,7 +209,7 @@ public class SelectTestCase {
}
@Test
- public void testNegativeLessThan() {
+ void testNegativeLessThan() {
ObjectNode range_json = jsonMapper.createObjectNode();
ObjectNode operators = jsonMapper.createObjectNode();
operators.put("<", -500);
@@ -230,7 +223,7 @@ public class SelectTestCase {
}
@Test
- public void testNegativeGreaterThan() {
+ void testNegativeGreaterThan() {
ObjectNode range_json = jsonMapper.createObjectNode();
ObjectNode operators = jsonMapper.createObjectNode();
operators.put(">", -500);
@@ -244,7 +237,7 @@ public class SelectTestCase {
}
@Test
- public void testNegativeLessThanOrEqual() {
+ void testNegativeLessThanOrEqual() {
ObjectNode range_json = jsonMapper.createObjectNode();
ObjectNode operators = jsonMapper.createObjectNode();
operators.put("<=", -500);
@@ -258,7 +251,7 @@ public class SelectTestCase {
}
@Test
- public void testNegativeGreaterThanOrEqual() {
+ void testNegativeGreaterThanOrEqual() {
ObjectNode range_json = jsonMapper.createObjectNode();
ObjectNode operators = jsonMapper.createObjectNode();
operators.put(">=", -500);
@@ -272,7 +265,7 @@ public class SelectTestCase {
}
@Test
- public void testNegativeEquality() {
+ void testNegativeEquality() {
ObjectNode range_json = jsonMapper.createObjectNode();
ObjectNode operators = jsonMapper.createObjectNode();
operators.put("=", -500);
@@ -286,38 +279,38 @@ public class SelectTestCase {
}
@Test
- public void testAnnotatedLessThan() {
+ void testAnnotatedLessThan() {
String jsonString = "{ \"range\": { \"children\" : [\"price\", {\"<\" : -500}], \"attributes\" : {\"filter\" : true} } }";
assertParse(jsonString, "|price:<-500");
}
@Test
- public void testAnnotatedGreaterThan() {
+ void testAnnotatedGreaterThan() {
String jsonString = "{ \"range\": { \"children\" : [\"price\", {\">\" : 500}], \"attributes\" : {\"filter\" : true} } }";
assertParse(jsonString, "|price:>500");
}
@Test
- public void testAnnotatedLessThanOrEqual() {
+ void testAnnotatedLessThanOrEqual() {
String jsonString = "{ \"range\": { \"children\" : [\"price\", {\"<=\" : -500}], \"attributes\" : {\"filter\" : true} } }";
assertParse(jsonString, "|price:[;-500]");
}
@Test
- public void testAnnotatedGreaterThanOrEqual() {
+ void testAnnotatedGreaterThanOrEqual() {
String jsonString = "{ \"range\": { \"children\" : [\"price\", {\">=\" : 500}], \"attributes\" : {\"filter\" : true} } }";
assertParse(jsonString, "|price:[500;]");
}
@Test
- public void testAnnotatedEquality() {
+ void testAnnotatedEquality() {
String jsonString = "{ \"range\": { \"children\" : [\"price\", {\"=\" : -500}], \"attributes\" : {\"filter\" : true} } }";
assertParse(jsonString, "|price:-500");
}
@Test
- public void testTermAnnotations() {
+ void testTermAnnotations() {
assertEquals("merkelapp",
getRootWord("{ \"contains\": { \"children\" : [\"baz\", \"colors\"], \"attributes\" : {\"label\" : \"merkelapp\"} } }").getLabel());
assertEquals("another",
@@ -334,7 +327,7 @@ public class SelectTestCase {
}
@Test
- public void testSameElement() {
+ void testSameElement() {
assertParse("{ \"contains\": [ \"baz\", {\"sameElement\" : [ { \"contains\" : [\"f1\", \"a\"] }, { \"contains\" : [\"f2\", \"b\"] } ]} ] }",
"baz:{f1:a f2:b}");
@@ -346,53 +339,53 @@ public class SelectTestCase {
}
@Test
- public void testPhrase() {
+ void testPhrase() {
assertParse("{ \"contains\": [ \"baz\", {\"phrase\" : [ \"a\", \"b\"] } ] }",
"baz:\"a b\"");
}
@Test
- public void testNestedPhrase() {
+ void testNestedPhrase() {
assertParse("{ \"contains\": [ \"baz\", {\"phrase\" : [ \"a\", \"b\", {\"phrase\" : [ \"c\", \"d\"] }] } ] }",
"baz:\"a b c d\"");
}
@Test
- public void testStemming() {
+ void testStemming() {
assertTrue(getRootWord("{ \"contains\": { \"children\" : [\"baz\", \"colors\"], \"attributes\" : {\"stem\" : false} } }").isStemmed());
assertFalse(getRootWord("{ \"contains\": { \"children\" : [\"baz\", \"colors\"], \"attributes\" : {\"stem\" : true} } }").isStemmed());
assertFalse(getRootWord("{ \"contains\": [\"baz\", \"colors\"] }").isStemmed());
}
@Test
- public void testRaw() {
+ void testRaw() {
Item root = parseWhere("{ \"contains\":[ \"baz\", \"yoni jo dima\" ] }").getRoot();
assertTrue(root instanceof WordItem);
assertFalse(root instanceof ExactStringItem);
- assertEquals("yoni jo dima", ((WordItem)root).getWord());
+ assertEquals("yoni jo dima", ((WordItem) root).getWord());
root = parseWhere("{ \"contains\": { \"children\" : [\"baz\", \"yoni jo dima\"], \"attributes\" : {\"grammar\" : \"raw\"} } }").getRoot();
assertTrue(root instanceof WordItem);
assertFalse(root instanceof ExactStringItem);
- assertEquals("yoni jo dima", ((WordItem)root).getWord());
+ assertEquals("yoni jo dima", ((WordItem) root).getWord());
}
@Test
- public void testAccentDropping() {
+ void testAccentDropping() {
assertFalse(getRootWord("{ \"contains\": { \"children\" : [\"baz\", \"colors\"], \"attributes\" : {\"accentDrop\" : false} } }").isNormalizable());
assertTrue(getRootWord("{ \"contains\": { \"children\" : [\"baz\", \"colors\"], \"attributes\" : {\"accentDrop\" : true} } }").isNormalizable());
assertTrue(getRootWord("{ \"contains\": { \"children\" : [\"baz\", \"colors\"] } }").isNormalizable());
}
@Test
- public void testCaseNormalization() {
+ void testCaseNormalization() {
assertTrue(getRootWord("{ \"contains\": { \"children\" : [\"baz\", \"colors\"], \"attributes\" : {\"normalizeCase\" : false} } }").isLowercased());
assertFalse(getRootWord("{ \"contains\": { \"children\" : [\"baz\", \"colors\"], \"attributes\" : {\"normalizeCase\" : true} } }").isLowercased());
assertFalse(getRootWord("{ \"contains\": { \"children\" : [\"baz\", \"colors\"] } }").isLowercased());
}
@Test
- public void testSegmentingRule() {
+ void testSegmentingRule() {
assertEquals(SegmentingRule.PHRASE,
getRootWord("{ \"contains\": { \"children\" : [\"baz\", \"colors\"], \"attributes\" : {\"andSegmenting\" : false} } }").getSegmentingRule());
assertEquals(SegmentingRule.BOOLEAN_AND,
@@ -402,30 +395,30 @@ public class SelectTestCase {
}
@Test
- public void testNfkc() {
+ void testNfkc() {
assertEquals("a\u030a", getRootWord("{ \"contains\": { \"children\" : [\"baz\", \"a\\u030a\"], \"attributes\" : {\"nfkc\" : false} } }").getWord());
assertEquals("\u00e5", getRootWord("{ \"contains\": { \"children\" : [\"baz\", \"a\\u030a\"], \"attributes\" : {\"nfkc\" : true} } }").getWord());
- assertEquals("No NKFC by default", "a\u030a", getRootWord("{ \"contains\": { \"children\" : [\"baz\", \"a\\u030a\"] } } ").getWord());
+ assertEquals("a\u030a", getRootWord("{ \"contains\": { \"children\" : [\"baz\", \"a\\u030a\"] } } ").getWord(), "No NKFC by default");
}
@Test
- public void testImplicitTransforms() {
+ void testImplicitTransforms() {
assertFalse(getRootWord("{ \"contains\": { \"children\" : [\"baz\", \"cox\"], \"attributes\" : {\"implicitTransforms\" : false} } }").isFromQuery());
assertTrue(getRootWord("{ \"contains\": { \"children\" : [\"baz\", \"cox\"], \"attributes\" : {\"implicitTransforms\" : true} } }").isFromQuery());
assertTrue(getRootWord("{ \"contains\": { \"children\" : [\"baz\", \"cox\"] } }").isFromQuery());
}
@Test
- public void testConnectivity() {
+ void testConnectivity() {
QueryTree parsed = parseWhere("{ \"and\": [ {\"contains\" : { \"children\" : [\"title\", \"madonna\"], \"attributes\" : {\"id\": 1, \"connectivity\": {\"id\": 3, \"weight\": 7.0}} } }, " +
"{ \"contains\" : { \"children\" : [\"title\", \"saint\"], \"attributes\" : {\"id\": 2} } }, " +
"{ \"contains\" : { \"children\" : [\"title\", \"angel\"], \"attributes\" : {\"id\": 3} } } ] }");
assertEquals("AND title:madonna title:saint title:angel", parsed.toString());
- AndItem root = (AndItem)parsed.getRoot();
- WordItem first = (WordItem)root.getItem(0);
- WordItem second = (WordItem)root.getItem(1);
- WordItem third = (WordItem)root.getItem(2);
+ AndItem root = (AndItem) parsed.getRoot();
+ WordItem first = (WordItem) root.getItem(0);
+ WordItem second = (WordItem) root.getItem(1);
+ WordItem third = (WordItem) root.getItem(2);
assertEquals(third, first.getConnectedItem());
assertEquals(first.getConnectivity(), 7.0d, 1E-6);
assertNull(second.getConnectedItem());
@@ -434,37 +427,37 @@ public class SelectTestCase {
"{ \"contains\" : { \"children\" : [\"title\", \"saint\"], \"attributes\" : {\"id\": 2} } }, " +
"{ \"contains\" : { \"children\" : [\"title\", \"angel\"], \"attributes\" : {\"id\": 3} } } ] }",
new IllegalArgumentException("Item 'title:madonna' was specified to connect to item with ID 4, " +
- "which does not exist in the query."));
+ "which does not exist in the query."));
}
@Test
- public void testAnnotatedPhrase() {
+ void testAnnotatedPhrase() {
QueryTree parsed = parseWhere("{ \"contains\": [\"baz\", { \"phrase\": { \"children\": [\"a\", \"b\"], \"attributes\": { \"label\": \"hello world\" } } }] }");
assertEquals("baz:\"a b\"", parsed.toString());
- PhraseItem phrase = (PhraseItem)parsed.getRoot();
+ PhraseItem phrase = (PhraseItem) parsed.getRoot();
assertEquals("hello world", phrase.getLabel());
}
@Test
- public void testRange() {
+ void testRange() {
QueryTree parsed = parseWhere("{ \"range\": [\"baz\", { \">=\": 1, \"<=\": 8 }] }");
assertEquals("baz:[1;8]", parsed.toString());
}
@Test
- public void testNegativeRange() {
+ void testNegativeRange() {
QueryTree parsed = parseWhere("{ \"range\": [\"baz\", { \">=\": -8, \"<=\": -1 }] }");
assertEquals("baz:[-8;-1]", parsed.toString());
}
@Test
- public void testRangeIllegalArguments() {
+ void testRangeIllegalArguments() {
assertParseFail("{ \"range\": [\"baz\", { \">=\": \"cox\", \"<=\": -1 }] }",
new IllegalArgumentException("Expected a numeric argument to range, but got the string 'cox'"));
}
@Test
- public void testNear() {
+ void testNear() {
assertParse("{ \"contains\": [\"description\", { \"near\": [\"a\", \"b\"] }] }",
"NEAR(2) description:a description:b");
assertParse("{ \"contains\": [\"description\", { \"near\": { \"children\": [\"a\", \"b\"], \"attributes\": { \"distance\": 100 } } } ] }",
@@ -472,7 +465,7 @@ public class SelectTestCase {
}
@Test
- public void testOrderedNear() {
+ void testOrderedNear() {
assertParse("{ \"contains\": [\"description\", { \"onear\": [\"a\", \"b\"] }] }",
"ONEAR(2) description:a description:b");
assertParse("{ \"contains\": [\"description\", { \"onear\": { \"children\": [\"a\", \"b\"], \"attributes\": { \"distance\": 100 } } } ] }",
@@ -480,7 +473,7 @@ public class SelectTestCase {
}
@Test
- public void testWand() {
+ void testWand() {
assertParse("{ \"wand\": [\"description\", { \"a\": 1, \"b\": 2 }] }",
"WAND(10,0.0,1.0) description{[1]:\"a\",[2]:\"b\"}");
assertParse("{ \"wand\": { \"children\": [\"description\", { \"a\": 1, \"b\": 2 }], \"attributes\": { \"scoreThreshold\": 13.3, \"targetHits\": 7, \"thresholdBoostFactor\": 2.3 } } }",
@@ -488,7 +481,7 @@ public class SelectTestCase {
}
@Test
- public void testNumericWand() {
+ void testNumericWand() {
String numWand = "WAND(10,0.0,1.0) description{[1]:\"11\",[2]:\"37\"}";
assertParse("{ \"wand\" : [\"description\", [[11,1], [37,2]] ]}", numWand);
assertParseFail("{ \"wand\" : [\"description\", 12] }",
@@ -496,7 +489,7 @@ public class SelectTestCase {
}
@Test
- public void testWeightedSet() {
+ void testWeightedSet() {
assertParse("{ \"weightedSet\" : [\"description\", {\"a\":1, \"b\":2} ]}",
"WEIGHTEDSET description{[1]:\"a\",[2]:\"b\"}");
assertParseFail("{ \"weightedSet\" : [\"description\", {\"a\":\"g\", \"b\":2} ]}",
@@ -506,7 +499,7 @@ public class SelectTestCase {
}
@Test
- public void testDotProduct() {
+ void testDotProduct() {
assertParse("{ \"dotProduct\" : [\"description\", {\"a\":1, \"b\":2} ]}",
"DOTPRODUCT description{[1]:\"a\",[2]:\"b\"}");
assertParse("{ \"dotProduct\" : [\"description\", {\"a\":2} ]}",
@@ -514,7 +507,7 @@ public class SelectTestCase {
}
@Test
- public void testPredicate() {
+ void testPredicate() {
assertParse("{ \"predicate\" : [\"predicate_field\", {\"gender\":\"male\", \"hobby\":[\"music\", \"hiking\"]}, {\"age\":23} ]}",
"PREDICATE_QUERY_ITEM gender=male, hobby=music, hobby=hiking, age:23");
assertParse("{ \"predicate\" : [\"predicate_field\", 0, \"void\" ]}",
@@ -522,7 +515,7 @@ public class SelectTestCase {
}
@Test
- public void testRank() {
+ void testRank() {
assertParse("{ \"rank\": [{ \"contains\": [\"a\", \"A\"] }, { \"contains\": [\"b\", \"B\"] } ] }",
"RANK a:A b:B");
assertParse("{ \"rank\": [{ \"contains\": [\"a\", \"A\"] }, { \"contains\": [\"b\", \"B\"] }, { \"contains\": [\"c\", \"C\"] } ] }",
@@ -532,19 +525,19 @@ public class SelectTestCase {
}
@Test
- public void testGeoLocation() {
+ void testGeoLocation() {
assertParse("{ \"geoLocation\": [ \"workplace\", 63.418417, 10.433033, \"0.5 deg\" ] }",
- "GEO_LOCATION workplace:(2,10433033,63418417,500000,0,1,0,1921876103)");
+ "GEO_LOCATION workplace:(2,10433033,63418417,500000,0,1,0,1921876103)");
assertParse("{ \"geoLocation\": [ \"headquarters\", \"37.416383\", \"-122.024683\", \"100 miles\" ] }",
- "GEO_LOCATION headquarters:(2,-122024683,37416383,1450561,0,1,0,3411238761)");
+ "GEO_LOCATION headquarters:(2,-122024683,37416383,1450561,0,1,0,3411238761)");
assertParse("{ \"geoLocation\": [ \"home\", \"E10.433033\", \"N63.418417\", \"5km\" ] }",
- "GEO_LOCATION home:(2,10433033,63418417,45066,0,1,0,1921876103)");
+ "GEO_LOCATION home:(2,10433033,63418417,45066,0,1,0,1921876103)");
assertParse("{ \"geoLocation\": [ \"workplace\", -12.0, -34.0, \"-77 deg\" ] }",
- "GEO_LOCATION workplace:(2,-34000000,-12000000,-1,0,1,0,4201111954)");
+ "GEO_LOCATION workplace:(2,-34000000,-12000000,-1,0,1,0,4201111954)");
}
@Test
- public void testNearestNeighbor() {
+ void testNearestNeighbor() {
assertParse("{ \"nearestNeighbor\": [ \"f1field\", \"q2prop\" ] }",
"NEAREST_NEIGHBOR {field=f1field,queryTensorName=q2prop,hnsw.exploreAdditionalHits=0,distanceThreshold=Infinity,approximate=true,targetHits=0}");
@@ -554,7 +547,7 @@ public class SelectTestCase {
@Test
@SuppressWarnings("deprecation")
- public void testWeakAnd() {
+ void testWeakAnd() {
assertParse("{ \"weakAnd\": [{ \"contains\": [\"a\", \"A\"] }, { \"contains\": [\"b\", \"B\"] } ] }",
"WEAKAND(100) a:A b:B");
assertParse("{ \"weakAnd\": { \"children\" : [{ \"contains\": [\"a\", \"A\"] }, { \"contains\": [\"b\", \"B\"] } ], \"attributes\" : {\"targetHits\": 37} }}",
@@ -566,7 +559,7 @@ public class SelectTestCase {
}
@Test
- public void testEquiv() {
+ void testEquiv() {
assertParse("{ \"contains\" : [\"fieldName\", {\"equiv\" : [\"A\",\"B\"]}]}",
"EQUIV fieldName:A fieldName:B");
@@ -582,42 +575,42 @@ public class SelectTestCase {
}
@Test
- public void testAffixItems() {
+ void testAffixItems() {
assertRootClass("{ \"contains\" : { \"children\" : [\"baz\", \"colors\"], \"attributes\" : {\"suffix\": true} } }",
- SuffixItem.class);
+ SuffixItem.class);
assertRootClass("{ \"contains\" : { \"children\" : [\"baz\", \"colors\"], \"attributes\" : {\"prefix\": true} } }",
- PrefixItem.class);
+ PrefixItem.class);
assertRootClass("{ \"contains\" : { \"children\" : [\"baz\", \"colors\"], \"attributes\" : {\"substring\": true} } }",
- SubstringItem.class);
+ SubstringItem.class);
assertParseFail("{ \"contains\" : { \"children\" : [\"baz\", \"colors\"], \"attributes\" : {\"suffix\": true, \"prefix\" : true} } }",
- new IllegalArgumentException("Only one of prefix, substring and suffix can be set."));
+ new IllegalArgumentException("Only one of prefix, substring and suffix can be set."));
assertParseFail("{ \"contains\" : { \"children\" : [\"baz\", \"colors\"], \"attributes\" : {\"suffix\": true, \"substring\" : true} } }",
- new IllegalArgumentException("Only one of prefix, substring and suffix can be set."));
+ new IllegalArgumentException("Only one of prefix, substring and suffix can be set."));
}
@Test
- public void testLongNumberInSimpleExpression() {
+ void testLongNumberInSimpleExpression() {
assertParse("{ \"range\" : [ \"price\", { \"=\" : 8589934592 }]}",
"price:8589934592");
}
@Test
- public void testNegativeLongNumberInSimpleExpression() {
+ void testNegativeLongNumberInSimpleExpression() {
assertParse("{ \"range\" : [ \"price\", { \"=\" : -8589934592 }]}",
"price:-8589934592");
}
@Test
- public void testNegativeHitLimit() {
+ void testNegativeHitLimit() {
assertParse(
"{ \"range\" : { \"children\":[ \"foo\", { \">=\" : 0, \"<=\" : 1 }], \"attributes\" : {\"hitLimit\": -38 } } }",
"foo:[0;1;-38]");
}
@Test
- public void testRangeSearchHitPopulationOrdering() {
+ void testRangeSearchHitPopulationOrdering() {
assertParse("{ \"range\" : { \"children\":[ \"foo\", { \">=\" : 0, \"<=\" : 1 }], \"attributes\" : {\"hitLimit\": 38 ,\"ascending\": true} } }", "foo:[0;1;38]");
assertParse("{ \"range\" : { \"children\":[ \"foo\", { \">=\" : 0, \"<=\" : 1 }], \"attributes\" : {\"hitLimit\": 38 ,\"ascending\": false} } }", "foo:[0;1;-38]");
assertParse("{ \"range\" : { \"children\":[ \"foo\", { \">=\" : 0, \"<=\" : 1 }], \"attributes\" : {\"hitLimit\": 38 ,\"descending\": true} } }", "foo:[0;1;-38]");
@@ -627,8 +620,8 @@ public class SelectTestCase {
try {
parseWhere("{ \"range\" : { \"children\":[ \"foo\", { \">=\" : 0, \"<=\" : 1 }], \"attributes\" : {\"hitLimit\": 38, \"ascending\": true, \"descending\": false} } }");
} catch (IllegalArgumentException e) {
- assertTrue("Expected information about abuse of settings.",
- e.getCause().getMessage().contains("both ascending and descending ordering set"));
+ assertTrue(e.getCause().getMessage().contains("both ascending and descending ordering set"),
+ "Expected information about abuse of settings.");
gotExceptionFromParse = true;
}
assertTrue(gotExceptionFromParse);
@@ -636,9 +629,9 @@ public class SelectTestCase {
// NB: Uses operator-keys to set bounds, not annotations
@Test
- public void testOpenIntervals() {
+ void testOpenIntervals() {
assertParse("{ \"range\" : { \"children\":[ \"title\", { \">=\" : 0.0, \"<=\" : 500.0 }] } }" +
- "select * from sources * where range(title, 0.0, 500.0)",
+ "select * from sources * where range(title, 0.0, 500.0)",
"title:[0.0;500.0]");
assertParse(
"{ \"range\" : { \"children\":[ \"title\", { \">\" : 0.0, \"<\" : 500.0 }] } }",
@@ -652,13 +645,13 @@ public class SelectTestCase {
}
@Test
- public void testEquals() {
- assertParse("{\"equals\": [\"public\",true]}","public:true");
- assertParse("{\"equals\": [\"public\",5]}","public:5");
+ void testEquals() {
+ assertParse("{\"equals\": [\"public\",true]}", "public:true");
+ assertParse("{\"equals\": [\"public\",5]}", "public:5");
}
@Test
- public void testRegexp() {
+ void testRegexp() {
QueryTree x = parseWhere("{ \"matches\" : [\"foo\", \"a b\"]}");
Item root = x.getRoot();
assertSame(RegExpItem.class, root.getClass());
@@ -666,7 +659,7 @@ public class SelectTestCase {
}
@Test
- public void testWordAlternatives() {
+ void testWordAlternatives() {
QueryTree x = parseWhere("{\"contains\" : [\"foo\", {\"alternatives\" : [{\"trees\": 1.0, \"tree\": 0.7}]}]}");
Item root = x.getRoot();
assertSame(WordAlternativesItem.class, root.getClass());
@@ -675,7 +668,7 @@ public class SelectTestCase {
}
@Test
- public void testFuzzy() {
+ void testFuzzy() {
QueryTree x = parseWhere("{ \"contains\": [\"description\", { \"fuzzy\": [\"a b\"] }] }");
Item root = x.getRoot();
assertSame(FuzzyItem.class, root.getClass());
@@ -686,14 +679,14 @@ public class SelectTestCase {
//------------------------------------------------------------------- grouping tests
@Test
- public void testGrouping(){
+ void testGrouping() {
String grouping = "[ { \"all\" : { \"group\" : \"time.year(a)\", \"each\" : { \"output\" : \"count()\" } } } ]";
String expected = "[[]all(group(time.year(a)) each(output(count())))]";
assertGrouping(expected, parseGrouping(grouping));
}
@Test
- public void testMultipleGroupings() {
+ void testMultipleGroupings() {
String grouping = "[ { \"all\" : { \"group\" : \"a\", \"each\" : { \"output\" : \"count()\"}}}, { \"all\" : { \"group\" : \"b\", \"each\" : { \"output\" : \"count()\"}}} ]";
String expected = "[[]all(group(a) each(output(count()))), []all(group(b) each(output(count())))]";
@@ -701,14 +694,14 @@ public class SelectTestCase {
}
@Test
- public void testGroupingWithPredefinedBuckets() {
+ void testGroupingWithPredefinedBuckets() {
String grouping = "[ { \"all\" : { \"group\" : { \"predefined\" : [ \"foo\", { \"bucket\": [1,2]}, { \"bucket\": [3,4]} ] } } } ]";
String expected = "[[]all(group(predefined(foo, bucket[1, 2>, bucket[3, 4>)))]";
assertGrouping(expected, parseGrouping(grouping));
}
@Test
- public void testMultipleOutputs() {
+ void testMultipleOutputs() {
String grouping = "[ { \"all\" : { \"group\" : \"b\", \"each\" : {\"output\": [ \"count()\", \"avg(foo)\" ] } } } ]";
String expected = "[[]all(group(b) each(output(count(), avg(foo))))]";
assertGrouping(expected, parseGrouping(grouping));
@@ -717,7 +710,7 @@ public class SelectTestCase {
//------------------------------------------------------------------- Other tests
@Test
- public void testOverridingOtherQueryTree() {
+ void testOverridingOtherQueryTree() {
Query query = new Query("?query=default:query");
assertEquals("WEAKAND(100) default:query", query.getModel().getQueryTree().toString());
assertEquals(Query.Type.WEAKAND, query.getModel().getType());
@@ -728,7 +721,7 @@ public class SelectTestCase {
}
@Test
- public void testOverridingWhereQueryTree() {
+ void testOverridingWhereQueryTree() {
Query query = new Query("?query=default:query");
query.getSelect().setWhereString("{\"contains\" : [\"default\", \"select\"] }");
assertEquals("default:select", query.getModel().getQueryTree().toString());
@@ -741,7 +734,7 @@ public class SelectTestCase {
}
@Test
- public void testProgrammaticAssignment() {
+ void testProgrammaticAssignment() {
Query query = new Query();
query.getSelect().setGroupingString("[ { \"all\" : { \"group\" : \"time.year(a)\", \"each\" : { \"output\" : \"count()\" } } } ]");
assertEquals(1, query.getSelect().getGrouping().size());
@@ -754,7 +747,7 @@ public class SelectTestCase {
}
@Test
- public void testConstructionAndClone() {
+ void testConstructionAndClone() {
Query query = new Query();
query.getSelect().setWhereString("{\"contains\" : [\"default\", \"select\"] }");
query.getSelect().setGroupingString("[ { \"all\" : { \"group\" : \"time.dayofmonth(a)\", \"each\" : { \"output\" : \"count()\" } } } ]");
@@ -776,7 +769,7 @@ public class SelectTestCase {
}
@Test
- public void testCloneWithGroupingExpressionString() {
+ void testCloneWithGroupingExpressionString() {
Query query = new Query();
query.getSelect().setGroupingExpressionString("all(group(foo) each(output(count())))");
@@ -785,12 +778,12 @@ public class SelectTestCase {
}
@Test
- public void testProgrammaticBuilding() {
+ void testProgrammaticBuilding() {
String expected =
"all(group(myfield) max(10000) each(" +
- "output(min(foo), max(bar)) " +
- "all(group(foo) max(10000) output(count()))" +
- "))";
+ "output(min(foo), max(bar)) " +
+ "all(group(foo) max(10000) output(count()))" +
+ "))";
Query query = new Query();
GroupingRequest grouping = GroupingRequest.newInstance(query);
AllOperation root = new AllOperation();
@@ -871,11 +864,11 @@ public class SelectTestCase {
assertEquals(2, alternatives.getAlternatives().size());
for (WordAlternativesItem.Alternative alternative : alternatives.getAlternatives()) {
if (tree.equals(alternative.word)) {
- assertFalse("Duplicate term introduced", seenTree);
+ assertFalse(seenTree, "Duplicate term introduced");
seenTree = true;
assertEquals(.7d, alternative.exactness, 1e-15d);
} else if (forest.equals(alternative.word)) {
- assertFalse("Duplicate term introduced", seenForest);
+ assertFalse(seenForest, "Duplicate term introduced");
seenForest = true;
assertEquals(1.0d, alternative.exactness, 1e-15d);
} else {
diff --git a/container-search/src/test/java/com/yahoo/text/interpretation/test/AnnotationTestCase.java b/container-search/src/test/java/com/yahoo/text/interpretation/test/AnnotationTestCase.java
index f439db390ee..fcb77851f0f 100644
--- a/container-search/src/test/java/com/yahoo/text/interpretation/test/AnnotationTestCase.java
+++ b/container-search/src/test/java/com/yahoo/text/interpretation/test/AnnotationTestCase.java
@@ -11,12 +11,9 @@ import com.yahoo.text.interpretation.AnnotationClass;
import com.yahoo.text.interpretation.Annotations;
import com.yahoo.text.interpretation.Interpretation;
import com.yahoo.text.interpretation.Span;
-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.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Arne Bergene Fossaa
@@ -24,12 +21,12 @@ import static org.junit.Assert.assertTrue;
public class AnnotationTestCase {
@Test
- public void testSimpleAnnotations() {
- Interpretation i= new Interpretation("new york hotel");
- i.annotate("sentence").put("isValid",true);
- i.annotate(0,3,"token");
- i.annotate(0,8,"place_name").put("^taxonomy:place_category","city");
- i.annotate(0,8,"place_name").put("woeid","12345678");
+ void testSimpleAnnotations() {
+ Interpretation i = new Interpretation("new york hotel");
+ i.annotate("sentence").put("isValid", true);
+ i.annotate(0, 3, "token");
+ i.annotate(0, 8, "place_name").put("^taxonomy:place_category", "city");
+ i.annotate(0, 8, "place_name").put("woeid", "12345678");
//i.getInterpretationAnnotation().put("domain","jaffa");
i.setProbability(0.5);
@@ -37,32 +34,32 @@ public class AnnotationTestCase {
}
@Test
- public void testAnnotationAPI() {
+ void testAnnotationAPI() {
Interpretation a = new Interpretation("new york hotel");
- a.annotate(0,3,"token");
- a.annotate(0,8,"state").put("name","New York");
- a.annotate(0,8,"state").put("country","US");
- a.annotate(0,8,"state").put("coast","east");
- a.annotate(9,14,"business");
- a.annotate(4,8,"token");
- a.annotate(9,14,"token");
+ a.annotate(0, 3, "token");
+ a.annotate(0, 8, "state").put("name", "New York");
+ a.annotate(0, 8, "state").put("country", "US");
+ a.annotate(0, 8, "state").put("coast", "east");
+ a.annotate(9, 14, "business");
+ a.annotate(4, 8, "token");
+ a.annotate(9, 14, "token");
- for(Span span : a.getTokens()) {
+ for (Span span : a.getTokens()) {
assertTrue(span.hasClass(new AnnotationClass("token")));
}
- Set<AnnotationClass> annotationClasses = a.getClasses(0,3);
+ Set<AnnotationClass> annotationClasses = a.getClasses(0, 3);
Set<AnnotationClass> testClass = new HashSet<>(Arrays.asList(
new AnnotationClass("token"), new AnnotationClass("state")));
- assertEquals(testClass,annotationClasses);
+ assertEquals(testClass, annotationClasses);
- assertNull(a.get("state","country"));
- assertEquals("US", a.get(0,8,"state","country"));
+ assertNull(a.get("state", "country"));
+ assertEquals("US", a.get(0, 8, "state", "country"));
assertEquals("new york", a.root().getSubSpans().get(0).getText());
assertEquals("hotel", a.root().getSubSpans().get(1).getText());
- assertEquals(2,a.root().getSubSpans().size());
+ assertEquals(2, a.root().getSubSpans().size());
//Test scoring
@@ -77,37 +74,37 @@ public class AnnotationTestCase {
//This is bad about the API, getTokens may not necessairily return what a user thinks a token is
//But it should still be tested
- a.annotate(0,1,"n");
- Set<String> testSet = new HashSet<>(Arrays.asList("n","york","hotel"));
- for(Span span:a.getTokens()) {
+ a.annotate(0, 1, "n");
+ Set<String> testSet = new HashSet<>(Arrays.asList("n", "york", "hotel"));
+ for (Span span :a.getTokens()) {
assertTrue(testSet.remove(span.getText()));
}
- assertEquals(0,testSet.size());
+ assertEquals(0, testSet.size());
}
//The following testcase is a test with the api on a use_case, no cornercases here
@Test
- public void testUsability() {
+ void testUsability() {
Interpretation interpretation = new Interpretation("new york crab pizza");
- interpretation.annotate(0,8,"place_name").put("^taxonomy:place_category","city");
- interpretation.annotate(0,8,"place_name").put("woe_id",2459115);
- interpretation.annotate(9,13,"food");
- interpretation.annotate(14,19,"food");
+ interpretation.annotate(0, 8, "place_name").put("^taxonomy:place_category", "city");
+ interpretation.annotate(0, 8, "place_name").put("woe_id", 2459115);
+ interpretation.annotate(9, 13, "food");
+ interpretation.annotate(14, 19, "food");
//Here we want to write code that finds out if the interpretation
//matches pizza and toppings.
List<Span> pizzaSpans = interpretation.getTermSpans("pizza");
- if(pizzaSpans.size() > 0) {
+ if (pizzaSpans.size() > 0) {
//We know that we have pizza, now we want to get some topping
//In a perfect world, pizza topping would have its own annotation class
//but for now, we'll just accept terms that have been tokenized with food
List<String> toppings = new ArrayList<>();
- for(Annotations annotations :interpretation.getAll("food")) {
- if(!annotations.getSubString().equalsIgnoreCase("pizza")) {
+ for (Annotations annotations :interpretation.getAll("food")) {
+ if (!annotations.getSubString().equalsIgnoreCase("pizza")) {
toppings.add(annotations.getSubString());
}
}
@@ -116,13 +113,13 @@ public class AnnotationTestCase {
//that all spans that has the annotation "place_name" has a "woe_id".
int woe_id = 0;
- for(Annotations annotations :interpretation.getAll("place_name")) {
+ for (Annotations annotations :interpretation.getAll("place_name")) {
//This will return either 0 or throw a bad exception
//if a number is not found
woe_id = annotations.getInteger("woe_id");
}
- assertEquals(Arrays.asList("crab"),toppings);
- assertEquals(2459115,woe_id);
+ assertEquals(Arrays.asList("crab"), toppings);
+ assertEquals(2459115, woe_id);
}
}
diff --git a/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/ListMergerTestCase.java b/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/ListMergerTestCase.java
index 5523fe3c893..97dc2674256 100644
--- a/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/ListMergerTestCase.java
+++ b/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/ListMergerTestCase.java
@@ -1,12 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.streamingvisitors;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.LinkedList;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Ulf Carlin
@@ -31,9 +31,9 @@ public class ListMergerTestCase {
}
@Test
- public void testMergeLists() {
+ void testMergeLists() {
int entryCount = 6;
- int padding = (int)Math.log10(entryCount) + 1;
+ int padding = (int) Math.log10(entryCount) + 1;
List<String> list1 = new LinkedList<>();
List<String> list2 = new LinkedList<>();
@@ -42,17 +42,17 @@ public class ListMergerTestCase {
List<String> newList = ListMerger.mergeIntoArrayList(list1, list2);
verifyList(newList, entryCount, padding);
- newList = ListMerger.mergeIntoArrayList(list1, list2, entryCount/2);
- verifyList(newList, entryCount/2, padding);
+ newList = ListMerger.mergeIntoArrayList(list1, list2, entryCount / 2);
+ verifyList(newList, entryCount / 2, padding);
- ListMerger.mergeLinkedLists(list1, list2, entryCount/2);
- verifyList(list1, entryCount/2, padding);
+ ListMerger.mergeLinkedLists(list1, list2, entryCount / 2);
+ verifyList(list1, entryCount / 2, padding);
}
@Test
- public void testMergeListsReversed() {
+ void testMergeListsReversed() {
int entryCount = 6;
- int padding = (int)Math.log10(entryCount) + 1;
+ int padding = (int) Math.log10(entryCount) + 1;
List<String> list1 = new LinkedList<>();
List<String> list2 = new LinkedList<>();
@@ -61,11 +61,11 @@ public class ListMergerTestCase {
List<String> newList = ListMerger.mergeIntoArrayList(list1, list2);
verifyList(newList, entryCount, padding);
- newList = ListMerger.mergeIntoArrayList(list1, list2, entryCount/2);
- verifyList(newList, entryCount/2, padding);
+ newList = ListMerger.mergeIntoArrayList(list1, list2, entryCount / 2);
+ verifyList(newList, entryCount / 2, padding);
- ListMerger.mergeLinkedLists(list1, list2, entryCount/2);
- verifyList(list1, entryCount/2, padding);
+ ListMerger.mergeLinkedLists(list1, list2, entryCount / 2);
+ verifyList(list1, entryCount / 2, padding);
}
}
diff --git a/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/MetricsSearcherTestCase.java b/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/MetricsSearcherTestCase.java
index c407945ee15..8e2380f72c2 100644
--- a/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/MetricsSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/MetricsSearcherTestCase.java
@@ -9,11 +9,9 @@ import com.yahoo.search.result.ErrorMessage;
import com.yahoo.search.result.Hit;
import com.yahoo.search.searchchain.Execution;
import com.yahoo.vdslib.VisitorStatistics;
-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.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Ulf Carlin
@@ -36,12 +34,12 @@ public class MetricsSearcherTestCase {
assertEquals("news:0", result.hits().get(0).getId().toString());
} else {
assertNotNull(result.hits().getError());
- assertTrue("Expected '" + message + "' to be contained in '"
- + result.hits().getErrorHit().errors().iterator().next().getMessage() + "'",
- result.hits().getErrorHit().errors().iterator().next().getMessage().contains(message));
- assertTrue("Expected '" + detailedMessage + "' to be contained in '"
- + result.hits().getErrorHit().errors().iterator().next().getDetailedMessage() + "'",
- result.hits().getErrorHit().errors().iterator().next().getDetailedMessage().contains(detailedMessage));
+ assertTrue(result.hits().getErrorHit().errors().iterator().next().getMessage().contains(message),
+ "Expected '" + message + "' to be contained in '"
+ + result.hits().getErrorHit().errors().iterator().next().getMessage() + "'");
+ assertTrue(result.hits().getErrorHit().errors().iterator().next().getDetailedMessage().contains(detailedMessage),
+ "Expected '" + detailedMessage + "' to be contained in '"
+ + result.hits().getErrorHit().errors().iterator().next().getDetailedMessage() + "'");
}
if (metricParam == null) {
@@ -77,21 +75,21 @@ public class MetricsSearcherTestCase {
}
@Test
- public void testBasics() {
+ void testBasics() {
// Start counting at -1 since count is reset upon the first query by MetricsSearcher.search
expStatsLt1.count--;
- String[] loadTypes = { LOADTYPE1, LOADTYPE2};
+ String[] loadTypes = {LOADTYPE1, LOADTYPE2};
for (String loadType : loadTypes) {
- verifySearch("streaming.loadtype="+loadType, null, null);
- verifySearch("metricsearcher.id="+loadType, null, null);
+ verifySearch("streaming.loadtype=" + loadType, null, null);
+ verifySearch("metricsearcher.id=" + loadType, null, null);
verifySearch(null, null, null);
- verifySearch("streaming.loadtype="+loadType, "Backend communication error", "Detailed error message");
+ verifySearch("streaming.loadtype=" + loadType, "Backend communication error", "Detailed error message");
}
}
@Test
- public void searcherDoesNotTryToDereferenceNullQueryContext() {
+ void searcherDoesNotTryToDereferenceNullQueryContext() {
backend.setImplicitlyCreateContext(false);
// This will crash with an NPE if the searcher does not cope with null
// query contexts.
diff --git a/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/VdsStreamingSearcherTestCase.java b/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/VdsStreamingSearcherTestCase.java
index 3cf2a38982a..0ecf1db01e5 100644
--- a/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/VdsStreamingSearcherTestCase.java
+++ b/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/VdsStreamingSearcherTestCase.java
@@ -23,7 +23,7 @@ import com.yahoo.vespa.streamingvisitors.tracing.MockUtils;
import com.yahoo.vespa.streamingvisitors.tracing.MonotonicNanoClock;
import com.yahoo.vespa.streamingvisitors.tracing.SamplingStrategy;
import com.yahoo.vespa.streamingvisitors.tracing.TraceExporter;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashMap;
@@ -31,11 +31,7 @@ import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
-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.Assert.assertFalse;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
@@ -185,12 +181,12 @@ public class VdsStreamingSearcherTestCase {
for (Query query : generateTestQueries(queryString)) {
Result result = executeQuery(searcher, query);
assertNotNull(result.hits().getError());
- assertTrue("Expected '" + message + "' to be contained in '"
- + result.hits().getErrorHit().errors().iterator().next().getMessage() + "'",
- result.hits().getErrorHit().errors().iterator().next().getMessage().contains(message));
- assertTrue("Expected '" + detailedMessage + "' to be contained in '"
- + result.hits().getErrorHit().errors().iterator().next().getDetailedMessage() + "'",
- result.hits().getErrorHit().errors().iterator().next().getDetailedMessage().contains(detailedMessage));
+ assertTrue(result.hits().getErrorHit().errors().iterator().next().getMessage().contains(message),
+ "Expected '" + message + "' to be contained in '"
+ + result.hits().getErrorHit().errors().iterator().next().getMessage() + "'");
+ assertTrue(result.hits().getErrorHit().errors().iterator().next().getDetailedMessage().contains(detailedMessage),
+ "Expected '" + detailedMessage + "' to be contained in '"
+ + result.hits().getErrorHit().errors().iterator().next().getDetailedMessage() + "'");
}
}
@@ -217,17 +213,17 @@ public class VdsStreamingSearcherTestCase {
}
@Test
- public void testBasics() {
+ void testBasics() {
MockVisitorFactory factory = new MockVisitorFactory();
VdsStreamingSearcher searcher = new VdsStreamingSearcher(factory);
var schema = new Schema.Builder("test");
schema.add(new com.yahoo.search.schema.DocumentSummary.Builder("default").build());
searcher.init("container.0",
- new SummaryParameters("default"),
- new ClusterParams("clusterName"),
- new DocumentdbInfoConfig.Builder().documentdb(new DocumentdbInfoConfig.Documentdb.Builder().name("test")).build(),
- new SchemaInfo(List.of(schema.build()), Map.of()));
+ new SummaryParameters("default"),
+ new ClusterParams("clusterName"),
+ new DocumentdbInfoConfig.Builder().documentdb(new DocumentdbInfoConfig.Documentdb.Builder().name("test")).build(),
+ new SchemaInfo(List.of(schema.build()), Map.of()));
// Magic query values are used to trigger specific behaviors from mock visitor.
checkError(searcher, "/?query=noselection",
@@ -256,7 +252,7 @@ public class VdsStreamingSearcherTestCase {
}
@Test
- public void testVerifyDocId() {
+ void testVerifyDocId() {
Query generalQuery = new Query("/?streaming.selection=true&query=test");
Query user1Query = new Query("/?streaming.userid=1&query=test");
Query group1Query = new Query("/?streaming.groupname=group1&query=test");
@@ -321,7 +317,7 @@ public class VdsStreamingSearcherTestCase {
}
@Test
- public void trace_level_set_if_sampling_strategy_returns_true() {
+ void trace_level_set_if_sampling_strategy_returns_true() {
var f = TraceFixture.withSampledTrace(true);
executeQuery(f.searcher, new Query("/?streaming.userid=1&query=timeoutexception"));
@@ -330,7 +326,7 @@ public class VdsStreamingSearcherTestCase {
}
@Test
- public void trace_level_not_set_if_sampling_strategy_returns_false() {
+ void trace_level_not_set_if_sampling_strategy_returns_false() {
var f = TraceFixture.withSampledTrace(false);
executeQuery(f.searcher, new Query("/?streaming.userid=1&query=timeoutexception"));
@@ -339,7 +335,7 @@ public class VdsStreamingSearcherTestCase {
}
@Test
- public void trace_is_exported_if_timed_out_beyond_threshold() {
+ void trace_is_exported_if_timed_out_beyond_threshold() {
// Default mock timeout threshold is 2x timeout
var f = TraceFixture.withTracingAndClockSampledAt(1000, 3001);
executeQuery(f.searcher, new Query("/?streaming.userid=1&query=timeoutexception&timeout=1.0"));
@@ -348,7 +344,7 @@ public class VdsStreamingSearcherTestCase {
}
@Test
- public void trace_is_not_exported_if_timed_out_less_than_threshold() {
+ void trace_is_not_exported_if_timed_out_less_than_threshold() {
// Default mock timeout threshold is 2x timeout
var f = TraceFixture.withTracingAndClockSampledAt(1000, 2999);
executeQuery(f.searcher, new Query("/?streaming.userid=1&query=timeoutexception&timeout=1.0"));
diff --git a/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/VdsVisitorTestCase.java b/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/VdsVisitorTestCase.java
index 19fa8c50424..0e3ecf1c8cc 100644
--- a/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/VdsVisitorTestCase.java
+++ b/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/VdsVisitorTestCase.java
@@ -19,13 +19,13 @@ import com.yahoo.text.Utf8String;
import com.yahoo.vdslib.DocumentSummary;
import com.yahoo.vdslib.SearchResult;
import com.yahoo.vespa.objects.BufferSerializer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author <a href="mailto:ulf@yahoo-inc.com">Ulf Carlin</a>
@@ -280,13 +280,13 @@ public class VdsVisitorTestCase {
}
@Test
- public void testGetQueryFlags() {
+ void testGetQueryFlags() {
assertEquals(0x00028000, VdsVisitor.getQueryFlags(new Query("/?query=test")));
assertEquals(0x00028080, VdsVisitor.getQueryFlags(new Query("/?query=test&hitcountestimate=true")));
assertEquals(0x00068000, VdsVisitor.getQueryFlags(new Query("/?query=test&rankfeatures=true")));
assertEquals(0x00068080, VdsVisitor.getQueryFlags(new Query("/?query=test&hitcountestimate=true&rankfeatures=true")));
- Query query= new Query("/?query=test");
+ Query query = new Query("/?query=test");
assertEquals(0x00028000, VdsVisitor.getQueryFlags(query));
query.setNoCache(true);
assertEquals(0x00038000, VdsVisitor.getQueryFlags(query));
@@ -295,7 +295,7 @@ public class VdsVisitorTestCase {
}
@Test
- public void testBasics() throws Exception {
+ void testBasics() throws Exception {
Route route = Route.parse("storageClusterRouteSpec");
String searchCluster = "searchClusterConfigId";
MockVisitorSessionFactory factory = new MockVisitorSessionFactory();
@@ -318,7 +318,7 @@ public class VdsVisitorTestCase {
}
@Test
- public void testFailures() throws Exception {
+ void testFailures() throws Exception {
Route route = Route.parse("storageClusterRouteSpec");
String searchCluster = "searchClusterConfigId";
MockVisitorSessionFactory factory = new MockVisitorSessionFactory();
@@ -346,11 +346,11 @@ public class VdsVisitorTestCase {
VdsVisitor visitor = new VdsVisitor(buildQuery(qa), searchCluster, route, "mytype", factory, 0);
try {
visitor.doSearch();
- assertTrue("Visitor did not fail", false);
+ assertTrue(false, "Visitor did not fail");
} catch (TimeoutException te) {
- assertTrue("Got TimeoutException unexpectedly", factory.timeoutQuery);
+ assertTrue(factory.timeoutQuery, "Got TimeoutException unexpectedly");
} catch (IllegalArgumentException iae) {
- assertTrue("Got IllegalArgumentException unexpectedly", factory.failQuery);
+ assertTrue(factory.failQuery, "Got IllegalArgumentException unexpectedly");
}
}
@@ -363,7 +363,7 @@ public class VdsVisitorTestCase {
visitor.onMessage(createDSM("id:ns:type::2"), ackToken);
try {
visitor.onMessage(createM(), ackToken);
- assertTrue("Unsupported message did not cause exception", false);
+ assertTrue(false, "Unsupported message did not cause exception");
} catch (UnsupportedOperationException uoe) {
assertTrue(uoe.getMessage().contains("VdsVisitor can only accept query result, search result, and documentsummary messages"));
}
@@ -389,10 +389,10 @@ public class VdsVisitorTestCase {
assertEquals("id:ns:type::0", hit.getDocId());
assertEquals(0.3, hit.getRank(), 0.01);
} else {
- assertTrue("Got too many hits", false);
+ assertTrue(false, "Got too many hits");
}
DocumentSummary.Summary summary = visitor.getSummaryMap().get(hit.getDocId());
- assertNotNull("Did not find summary for " + hit.getDocId(), summary);
+ assertNotNull(summary, "Did not find summary for " + hit.getDocId());
}
}
diff --git a/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/tracing/MaxSamplesPerPeriodTest.java b/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/tracing/MaxSamplesPerPeriodTest.java
index cd951e83699..349bedafcce 100644
--- a/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/tracing/MaxSamplesPerPeriodTest.java
+++ b/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/tracing/MaxSamplesPerPeriodTest.java
@@ -1,22 +1,22 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.streamingvisitors.tracing;
-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;
public class MaxSamplesPerPeriodTest {
@Test
- public void first_sample_in_period_returns_true() {
+ void first_sample_in_period_returns_true() {
var clock = MockUtils.mockedClockReturning(1000L);
var sampler = new MaxSamplesPerPeriod(clock, 1000L, 1L);
assertTrue(sampler.shouldSample());
}
@Test
- public void samples_exceeding_period_count_return_false() {
+ void samples_exceeding_period_count_return_false() {
var clock = MockUtils.mockedClockReturning(1000L, 1100L, 1200L);
var sampler = new MaxSamplesPerPeriod(clock, 1000L, 2L);
assertTrue(sampler.shouldSample());
@@ -25,7 +25,7 @@ public class MaxSamplesPerPeriodTest {
}
@Test
- public void sample_in_new_period_returns_true() {
+ void sample_in_new_period_returns_true() {
var clock = MockUtils.mockedClockReturning(1000L, 1900L, 2000L, 2900L);
var sampler = new MaxSamplesPerPeriod(clock, 1000L, 1L);
assertTrue(sampler.shouldSample());
diff --git a/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/tracing/ProbabilisticSampleRateTest.java b/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/tracing/ProbabilisticSampleRateTest.java
index 1ce05df5f26..f5576d5d512 100644
--- a/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/tracing/ProbabilisticSampleRateTest.java
+++ b/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/tracing/ProbabilisticSampleRateTest.java
@@ -1,12 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.streamingvisitors.tracing;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.TimeUnit;
-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 ProbabilisticSampleRateTest {
@@ -15,7 +15,7 @@ public class ProbabilisticSampleRateTest {
}
@Test
- public void samples_are_rate_limited_per_second() {
+ void samples_are_rate_limited_per_second() {
var clock = MockUtils.mockedClockReturning(ms2ns(10_000), ms2ns(10_500), ms2ns(10_500), ms2ns(10_501));
var rng = MockUtils.mockedRandomReturning(0.1, 0.51, 0.49, 0.01);
var sampler = new ProbabilisticSampleRate(clock, () -> rng, 1.0);
@@ -30,7 +30,7 @@ public class ProbabilisticSampleRateTest {
}
@Test
- public void zero_desired_sample_rate_returns_false() {
+ void zero_desired_sample_rate_returns_false() {
var clock = MockUtils.mockedClockReturning(ms2ns(10_000));
var rng = MockUtils.mockedRandomReturning(0.99999999); // [0, 1)
var sampler = new ProbabilisticSampleRate(clock, () -> rng, 0.0);
diff --git a/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/tracing/SamplingTraceExporterTest.java b/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/tracing/SamplingTraceExporterTest.java
index 36b6ed35213..f143efbf786 100644
--- a/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/tracing/SamplingTraceExporterTest.java
+++ b/container-search/src/test/java/com/yahoo/vespa/streamingvisitors/tracing/SamplingTraceExporterTest.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.vespa.streamingvisitors.tracing;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
@@ -12,7 +12,7 @@ import static org.mockito.Mockito.when;
public class SamplingTraceExporterTest {
@Test
- public void sampling_decision_is_deferred_to_provided_sampler() {
+ void sampling_decision_is_deferred_to_provided_sampler() {
var exporter = mock(TraceExporter.class);
var sampler = mock(SamplingStrategy.class);
when(sampler.shouldSample()).thenReturn(true, false);
diff --git a/controller-api/pom.xml b/controller-api/pom.xml
index f7057c93561..c7ac5d3518a 100644
--- a/controller-api/pom.xml
+++ b/controller-api/pom.xml
@@ -85,17 +85,21 @@
<!-- test -->
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
-
- <dependency>
<groupId>com.yahoo.vespa</groupId>
<artifactId>configdefinitions</artifactId>
<version>${project.version}</version>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
+ </dependency>
<dependency>
<groupId>org.mockito</groupId>
diff --git a/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/vcmr/VespaChangeRequest.java b/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/vcmr/VespaChangeRequest.java
index 781be9a6c13..e0f867b97be 100644
--- a/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/vcmr/VespaChangeRequest.java
+++ b/controller-api/src/main/java/com/yahoo/vespa/hosted/controller/api/integration/vcmr/VespaChangeRequest.java
@@ -48,6 +48,10 @@ public class VespaChangeRequest extends ChangeRequest {
return new VespaChangeRequest(getId(), source, getImpactedSwitches(), getImpactedHosts(), getApproval(), getImpact(), status, hostActionPlan, zoneId);
}
+ public VespaChangeRequest withImpact(Impact impact) {
+ return new VespaChangeRequest(getId(), getChangeRequestSource(), getImpactedSwitches(), getImpactedHosts(), getApproval(), impact, status, hostActionPlan, zoneId);
+ }
+
public VespaChangeRequest withApproval(Approval approval) {
return new VespaChangeRequest(getId(), getChangeRequestSource(), getImpactedSwitches(), getImpactedHosts(), approval, getImpact(), status, hostActionPlan, zoneId);
}
diff --git a/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/identifiers/IdentifierTest.java b/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/identifiers/IdentifierTest.java
index 0dcb800ca04..902d260c86d 100644
--- a/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/identifiers/IdentifierTest.java
+++ b/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/identifiers/IdentifierTest.java
@@ -2,129 +2,168 @@
package com.yahoo.vespa.hosted.controller.api.identifiers;
import com.yahoo.config.provision.zone.ZoneId;
-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;
/**
* @author smorgrav
*/
public class IdentifierTest {
- @Test(expected = IllegalArgumentException.class)
- public void existing_tenant_id_not_empty() {
- new TenantId("");
+ @Test
+ void existing_tenant_id_not_empty() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new TenantId("");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void existing_tenant_id_must_check_pattern() {
- new TenantId("`");
+ @Test
+ void existing_tenant_id_must_check_pattern() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new TenantId("`");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void default_not_allowed_for_tenants() {
- new TenantId("default");
+ @Test
+ void default_not_allowed_for_tenants() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new TenantId("default");
+ });
}
@Test
- public void existing_tenant_id_must_accept_valid_id() {
+ void existing_tenant_id_must_accept_valid_id() {
new TenantId("msbe");
}
- @Test(expected = IllegalArgumentException.class)
- public void existing_tenant_id_cannot_be_uppercase() {
- new TenantId("MixedCaseTenant");
+ @Test
+ void existing_tenant_id_cannot_be_uppercase() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new TenantId("MixedCaseTenant");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void existing_tenant_id_cannot_contain_dots() {
- new TenantId("tenant.with.dots");
+ @Test
+ void existing_tenant_id_cannot_contain_dots() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new TenantId("tenant.with.dots");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void new_tenant_id_cannot_contain_underscore() {
- TenantId.validate("underscore_tenant");
+ @Test
+ void new_tenant_id_cannot_contain_underscore() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ TenantId.validate("underscore_tenant");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void new_tenant_id_cannot_contain_dot() {
- TenantId.validate("tenant.with.dots");
+ @Test
+ void new_tenant_id_cannot_contain_dot() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ TenantId.validate("tenant.with.dots");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void new_tenant_id_cannot_contain_uppercase() {
- TenantId.validate("UppercaseTenant");
+ @Test
+ void new_tenant_id_cannot_contain_uppercase() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ TenantId.validate("UppercaseTenant");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void new_tenant_id_cannot_start_with_dash() {
- TenantId.validate("-tenant");
+ @Test
+ void new_tenant_id_cannot_start_with_dash() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ TenantId.validate("-tenant");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void new_tenant_id_cannot_end_with_dash() {
- TenantId.validate("tenant-");
+ @Test
+ void new_tenant_id_cannot_end_with_dash() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ TenantId.validate("tenant-");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void existing_application_id_cannot_be_uppercase() {
- new ApplicationId("MixedCaseApplication");
+ @Test
+ void existing_application_id_cannot_be_uppercase() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new ApplicationId("MixedCaseApplication");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void existing_application_id_cannot_contain_dots() {
- new ApplicationId("application.with.dots");
+ @Test
+ void existing_application_id_cannot_contain_dots() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new ApplicationId("application.with.dots");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void new_application_id_cannot_contain_underscore() {
- ApplicationId.validate("underscore_application");
+ @Test
+ void new_application_id_cannot_contain_underscore() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ ApplicationId.validate("underscore_application");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void new_application_id_cannot_contain_dot() {
- ApplicationId.validate("application.with.dots");
+ @Test
+ void new_application_id_cannot_contain_dot() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ ApplicationId.validate("application.with.dots");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void new_application_id_cannot_contain_uppercase() {
- ApplicationId.validate("UppercaseApplication");
+ @Test
+ void new_application_id_cannot_contain_uppercase() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ ApplicationId.validate("UppercaseApplication");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void new_application_id_cannot_start_with_dash() {
- ApplicationId.validate("-application");
+ @Test
+ void new_application_id_cannot_start_with_dash() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ ApplicationId.validate("-application");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void new_application_id_cannot_end_with_dash() {
- ApplicationId.validate("application-");
+ @Test
+ void new_application_id_cannot_end_with_dash() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ ApplicationId.validate("application-");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void instance_id_cannot_be_uppercase() {
- new InstanceId("MixedCaseInstance");
+ @Test
+ void instance_id_cannot_be_uppercase() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new InstanceId("MixedCaseInstance");
+ });
}
@Test
- public void dns_names_has_no_underscore() {
+ void dns_names_has_no_underscore() {
assertEquals("a-b-c", new ApplicationId("a_b_c").toDns());
}
- @Test(expected = IllegalArgumentException.class)
- public void identifiers_cannot_be_named_api() {
- new ApplicationId("api");
+ @Test
+ void identifiers_cannot_be_named_api() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new ApplicationId("api");
+ });
}
@Test
- public void application_instance_id_dotted_string_is_subindentifers_concatinated_with_dots() {
+ void application_instance_id_dotted_string_is_subindentifers_concatinated_with_dots() {
DeploymentId id = new DeploymentId(com.yahoo.config.provision.ApplicationId.from("tenant", "application", "instance"),
- ZoneId.from("prod", "region"));
+ ZoneId.from("prod", "region"));
assertEquals("tenant.application.prod.region.instance", id.dottedString());
}
@Test
- public void revision_id_can_contain_application_version_number() {
+ void revision_id_can_contain_application_version_number() {
new RevisionId("1.0.1078-24825d1f6");
}
}
diff --git a/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/integration/deployment/JobTypeTest.java b/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/integration/deployment/JobTypeTest.java
index bbe0c2bd458..1693f752b89 100644
--- a/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/integration/deployment/JobTypeTest.java
+++ b/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/integration/deployment/JobTypeTest.java
@@ -2,11 +2,11 @@
package com.yahoo.vespa.hosted.controller.api.integration.deployment;
import com.yahoo.config.provision.zone.ZoneId;
-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.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author jonmv
@@ -14,7 +14,7 @@ import static org.junit.Assert.assertTrue;
public class JobTypeTest {
@Test
- public void test() {
+ void test() {
assertEquals(JobType.test("us-east-3"), JobType.ofSerialized("prod.us-east-3.test"));
assertEquals(JobType.dev("aws-us-east-1c"), JobType.ofSerialized("dev.aws-us-east-1c"));
diff --git a/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/integration/dns/AliasTargetTest.java b/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/integration/dns/AliasTargetTest.java
index 35d2ad1ffca..9cbba8107ef 100644
--- a/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/integration/dns/AliasTargetTest.java
+++ b/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/integration/dns/AliasTargetTest.java
@@ -3,12 +3,12 @@ package com.yahoo.vespa.hosted.controller.api.integration.dns;
import com.yahoo.config.provision.HostName;
import com.yahoo.config.provision.zone.ZoneId;
-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;
/**
* @author mpolden
@@ -16,7 +16,7 @@ import static org.junit.Assert.fail;
public class AliasTargetTest {
@Test
- public void packing() {
+ void packing() {
List<AliasTarget> tests = List.of(
new LatencyAliasTarget(HostName.of("foo.example.com"), "dns-zone-1", ZoneId.from("prod.us-north-1")),
new WeightedAliasTarget(HostName.of("bar.example.com"), "dns-zone-2", ZoneId.from("prod.us-north-2"), 50)
diff --git a/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/integration/maven/MetadataTest.java b/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/integration/maven/MetadataTest.java
index 55f33d7e3e1..4cec90eb48d 100644
--- a/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/integration/maven/MetadataTest.java
+++ b/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/integration/maven/MetadataTest.java
@@ -2,14 +2,14 @@
package com.yahoo.vespa.hosted.controller.api.integration.maven;
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.jupiter.api.Assertions.assertEquals;
public class MetadataTest {
@Test
- public void testParsing() {
+ void testParsing() {
Metadata metadata = Metadata.fromXml(metadataXml);
assertEquals("com.yahoo.vespa", metadata.id().groupId());
assertEquals("tenant-base", metadata.id().artifactId());
diff --git a/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/integration/user/RolesTest.java b/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/integration/user/RolesTest.java
index 9e128a17c13..59484fbb0ce 100644
--- a/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/integration/user/RolesTest.java
+++ b/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/integration/user/RolesTest.java
@@ -6,9 +6,10 @@ import com.yahoo.config.provision.TenantName;
import com.yahoo.vespa.hosted.controller.api.role.ApplicationRole;
import com.yahoo.vespa.hosted.controller.api.role.Role;
import com.yahoo.vespa.hosted.controller.api.role.TenantRole;
-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;
/**
* @author jonmv
@@ -16,7 +17,7 @@ import static org.junit.Assert.assertEquals;
public class RolesTest {
@Test
- public void testSerialization() {
+ void testSerialization() {
TenantName tenant = TenantName.from("my-tenant");
for (TenantRole role : Roles.tenantRoles(tenant))
assertEquals(role, Roles.toRole(Roles.valueOf(role)));
@@ -26,38 +27,48 @@ public class RolesTest {
assertEquals(role, Roles.toRole(Roles.valueOf(role)));
assertEquals(Role.hostedOperator(),
- Roles.toRole("hostedOperator"));
+ Roles.toRole("hostedOperator"));
assertEquals(Role.hostedSupporter(),
- Roles.toRole("hostedSupporter"));
+ Roles.toRole("hostedSupporter"));
assertEquals(Role.administrator(tenant), Roles.toRole("my-tenant.administrator"));
assertEquals(Role.developer(tenant), Roles.toRole("my-tenant.developer"));
assertEquals(Role.reader(tenant), Roles.toRole("my-tenant.reader"));
assertEquals(Role.headless(tenant, application), Roles.toRole("my-tenant.my-application.headless"));
}
- @Test(expected = IllegalArgumentException.class)
- public void illegalTenantName() {
- Roles.valueOf(Role.developer(TenantName.from("my.tenant")));
+ @Test
+ void illegalTenantName() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ Roles.valueOf(Role.developer(TenantName.from("my.tenant")));
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void illegalApplicationName() {
- Roles.valueOf(Role.headless(TenantName.from("my-tenant"), ApplicationName.from("my.app")));
+ @Test
+ void illegalApplicationName() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ Roles.valueOf(Role.headless(TenantName.from("my-tenant"), ApplicationName.from("my.app")));
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void illegalRoleValue() {
- Roles.toRole("my-tenant.awesomePerson");
+ @Test
+ void illegalRoleValue() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ Roles.toRole("my-tenant.awesomePerson");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void illegalCombination() {
- Roles.toRole("my-tenant.my-application.tenantOwner");
+ @Test
+ void illegalCombination() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ Roles.toRole("my-tenant.my-application.tenantOwner");
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void illegalValue() {
- Roles.toRole("everyone");
+ @Test
+ void illegalValue() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ Roles.toRole("everyone");
+ });
}
}
diff --git a/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/role/PathGroupTest.java b/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/role/PathGroupTest.java
index 1923365976e..4a8e9785c88 100644
--- a/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/role/PathGroupTest.java
+++ b/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/role/PathGroupTest.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.hosted.controller.api.role;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;
-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 jonmv
@@ -17,7 +17,7 @@ import static org.junit.Assert.fail;
public class PathGroupTest {
@Test
- public void uniqueMatches() {
+ void uniqueMatches() {
// Ensure that each path group contains at most one match for any given path, to avoid undefined context extraction.
Set<String> checkedAgainstSelf = new HashSet<>();
for (PathGroup group1 : PathGroup.values())
@@ -37,29 +37,29 @@ public class PathGroupTest {
// and the other doesn't end with a wildcard matcher ...
// and the longest one isn't just one wildcard longer ...
// then one is strictly longer than the other, and it's not a match.
- if (end < parts1.length && (end == 0 || ! parts2[end - 1].equals("{*}")) && ! parts1[end].equals("{*}")) continue;
- if (end < parts2.length && (end == 0 || ! parts1[end - 1].equals("{*}")) && ! parts2[end].equals("{*}")) continue;
+ if (end < parts1.length && (end == 0 || !parts2[end - 1].equals("{*}")) && !parts1[end].equals("{*}")) continue;
+ if (end < parts2.length && (end == 0 || !parts1[end - 1].equals("{*}")) && !parts2[end].equals("{*}")) continue;
int i;
for (i = 0; i < end; i++)
if ( ! parts1[i].equals(parts2[i])
- && ! (parts1[i].startsWith("{") && parts1[i].endsWith("}"))
- && ! (parts2[i].startsWith("{") && parts2[i].endsWith("}"))) break;
+ && !(parts1[i].startsWith("{") && parts1[i].endsWith("}"))
+ && !(parts2[i].startsWith("{") && parts2[i].endsWith("}"))) break;
if (i == end) fail("Paths '" + path1 + "' and '" + path2 + "' overlap.");
}
assertEquals(PathGroup.all().stream().mapToInt(group -> group.pathSpecs.size()).sum(),
- checkedAgainstSelf.size());
+ checkedAgainstSelf.size());
}
@Test
- public void contextMatches() {
+ void contextMatches() {
for (PathGroup group : PathGroup.values())
for (String spec : group.pathSpecs) {
for (PathGroup.Matcher matcher : PathGroup.Matcher.values()) {
if (group.matchers.contains(matcher)) {
- if ( ! spec.contains(matcher.pattern))
+ if (!spec.contains(matcher.pattern))
fail("Spec '" + spec + "' in '" + group.name() + "' should contain matcher '" + matcher.pattern + "'.");
if (spec.replaceFirst(Pattern.quote(matcher.pattern), "").contains(matcher.pattern))
fail("Spec '" + spec + "' in '" + group.name() + "' contains more than one instance of '" + matcher.pattern + "'.");
diff --git a/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/role/RoleTest.java b/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/role/RoleTest.java
index 872f74ca1ab..9dac13482e0 100644
--- a/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/role/RoleTest.java
+++ b/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/role/RoleTest.java
@@ -4,14 +4,14 @@ package com.yahoo.vespa.hosted.controller.api.role;
import com.yahoo.config.provision.ApplicationName;
import com.yahoo.config.provision.SystemName;
import com.yahoo.config.provision.TenantName;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.util.List;
import java.util.stream.Stream;
-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 mpolden
@@ -23,7 +23,7 @@ public class RoleTest {
private static final Enforcer publicCdEnforcer = new Enforcer(SystemName.PublicCd);
@Test
- public void operator_membership() {
+ void operator_membership() {
Role role = Role.hostedOperator();
// Operator actions
@@ -39,7 +39,7 @@ public class RoleTest {
}
@Test
- public void supporter_membership() {
+ void supporter_membership() {
Role role = Role.hostedSupporter();
// No create update or delete
@@ -64,11 +64,11 @@ public class RoleTest {
}
@Test
- public void tenant_membership() {
+ void tenant_membership() {
Role role = Role.athenzTenantAdmin(TenantName.from("t1"));
assertFalse(mainEnforcer.allows(role, Action.create, URI.create("/not/explicitly/defined")));
- assertFalse("Deny access to operator API", mainEnforcer.allows(role, Action.create, URI.create("/controller/v1/foo")));
- assertFalse("Deny access to other tenant and app", mainEnforcer.allows(role, Action.update, URI.create("/application/v4/tenant/t2/application/a2")));
+ assertFalse(mainEnforcer.allows(role, Action.create, URI.create("/controller/v1/foo")), "Deny access to operator API");
+ assertFalse(mainEnforcer.allows(role, Action.update, URI.create("/application/v4/tenant/t2/application/a2")), "Deny access to other tenant and app");
assertTrue(mainEnforcer.allows(role, Action.update, URI.create("/application/v4/tenant/t1/application/a1")));
Role publicSystem = Role.athenzTenantAdmin(TenantName.from("t1"));
@@ -78,16 +78,16 @@ public class RoleTest {
}
@Test
- public void build_service_membership() {
+ void build_service_membership() {
Role role = Role.buildService(TenantName.from("t1"), ApplicationName.from("a1"));
assertFalse(publicEnforcer.allows(role, Action.create, URI.create("/not/explicitly/defined")));
assertFalse(publicEnforcer.allows(role, Action.update, URI.create("/application/v4/tenant/t1/application/a1")));
assertTrue(publicEnforcer.allows(role, Action.create, URI.create("/application/v4/tenant/t1/application/a1/submit")));
- assertFalse("No global read access", publicEnforcer.allows(role, Action.read, URI.create("/controller/v1/foo")));
+ assertFalse(publicEnforcer.allows(role, Action.read, URI.create("/controller/v1/foo")), "No global read access");
}
@Test
- public void new_implications() {
+ void new_implications() {
TenantName tenant1 = TenantName.from("t1");
ApplicationName application1 = ApplicationName.from("a1");
ApplicationName application2 = ApplicationName.from("a2");
@@ -103,7 +103,7 @@ public class RoleTest {
}
@Test
- public void system_flags() {
+ void system_flags() {
URI deployUri = URI.create("/system-flags/v1/deploy");
Action action = Action.update;
assertTrue(mainEnforcer.allows(Role.systemFlagsDeployer(), action, deployUri));
@@ -121,7 +121,7 @@ public class RoleTest {
}
@Test
- public void routing() {
+ void routing() {
var tenantUrl = URI.create("/routing/v1/status/tenant/t1");
var applicationUrl = URI.create("/routing/v1/status/tenant/t1/application/a1");
var instanceUrl = URI.create("/routing/v1/status/tenant/t1/application/a1/instance/i1");
@@ -130,8 +130,8 @@ public class RoleTest {
for (var url : List.of(tenantUrl, applicationUrl, instanceUrl, deploymentUrl)) {
var allowedRole = Role.reader(TenantName.from("t1"));
var disallowedRole = Role.reader(TenantName.from("t2"));
- assertTrue(allowedRole + " can read " + url, mainEnforcer.allows(allowedRole, Action.read, url));
- assertFalse(disallowedRole + " cannot read " + url, mainEnforcer.allows(disallowedRole, Action.read, url));
+ assertTrue(mainEnforcer.allows(allowedRole, Action.read, url), allowedRole + " can read " + url);
+ assertFalse(mainEnforcer.allows(disallowedRole, Action.read, url), disallowedRole + " cannot read " + url);
}
// Write
@@ -139,15 +139,15 @@ public class RoleTest {
var url = URI.create("/routing/v1/inactive/tenant/t1/application/a1/instance/i1/environment/prod/region/us-north-1");
var allowedRole = Role.developer(TenantName.from("t1"));
var disallowedRole = Role.developer(TenantName.from("t2"));
- assertTrue(allowedRole + " can override status at " + url, mainEnforcer.allows(allowedRole, Action.create, url));
- assertTrue(allowedRole + " can clear status at " + url, mainEnforcer.allows(allowedRole, Action.delete, url));
- assertFalse(disallowedRole + " cannot override status at " + url, mainEnforcer.allows(disallowedRole, Action.create, url));
- assertFalse(disallowedRole + " cannot clear status at " + url, mainEnforcer.allows(disallowedRole, Action.delete, url));
+ assertTrue(mainEnforcer.allows(allowedRole, Action.create, url), allowedRole + " can override status at " + url);
+ assertTrue(mainEnforcer.allows(allowedRole, Action.delete, url), allowedRole + " can clear status at " + url);
+ assertFalse(mainEnforcer.allows(disallowedRole, Action.create, url), disallowedRole + " cannot override status at " + url);
+ assertFalse(mainEnforcer.allows(disallowedRole, Action.delete, url), disallowedRole + " cannot clear status at " + url);
}
}
@Test
- public void payment_instrument() {
+ void payment_instrument() {
URI paymentInstrumentUri = URI.create("/billing/v1/tenant/t1/instrument/foobar");
URI tenantPaymentInstrumentUri = URI.create("/billing/v1/tenant/t1/instrument");
URI tokenUri = URI.create("/billing/v1/tenant/t1/token");
@@ -172,7 +172,7 @@ public class RoleTest {
}
@Test
- public void billing_tenant() {
+ void billing_tenant() {
URI billing = URI.create("/billing/v1/tenant/t1/billing");
Role user = Role.reader(TenantName.from("t1"));
@@ -189,7 +189,7 @@ public class RoleTest {
}
@Test
- public void billing_test() {
+ void billing_test() {
var tester = new EnforcerTester(publicEnforcer);
var accountant = Role.hostedAccountant();
@@ -302,12 +302,12 @@ public class RoleTest {
allowed.forEach(action -> {
var msg = String.format("%s should be allowed to %s on %s", role, action, resource);
- assertTrue(msg, enforcer.allows(role, action, resource));
+ assertTrue(enforcer.allows(role, action, resource), msg);
});
Action.all().stream().filter(a -> ! allowed.contains(a)).forEach(action -> {
var msg = String.format("%s should not be allowed to %s on %s", role, action, resource);
- assertFalse(msg, enforcer.allows(role, action, resource));
+ assertFalse(enforcer.allows(role, action, resource), msg);
});
return this;
diff --git a/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/systemflags/v1/SystemFlagsDataArchiveTest.java b/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/systemflags/v1/SystemFlagsDataArchiveTest.java
index ce2746f92e0..c40788ecb3f 100644
--- a/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/systemflags/v1/SystemFlagsDataArchiveTest.java
+++ b/controller-api/src/test/java/com/yahoo/vespa/hosted/controller/api/systemflags/v1/SystemFlagsDataArchiveTest.java
@@ -16,10 +16,8 @@ import com.yahoo.vespa.flags.FlagId;
import com.yahoo.vespa.flags.RawFlag;
import com.yahoo.vespa.flags.json.FlagData;
import com.yahoo.vespa.hosted.controller.api.integration.zone.ZoneRegistry;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
@@ -37,9 +35,10 @@ import java.util.Map;
import java.util.Set;
import static java.util.stream.Collectors.toList;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -53,12 +52,8 @@ public class SystemFlagsDataArchiveTest {
private static final FlagId MY_TEST_FLAG = new FlagId("my-test-flag");
private static final FlagId FLAG_WITH_EMPTY_DATA = new FlagId("flag-with-empty-data");
- @Rule
- public final TemporaryFolder temporaryFolder = new TemporaryFolder();
-
- @SuppressWarnings("deprecation")
- @Rule
- public final ExpectedException expectedException = ExpectedException.none();
+ @TempDir
+ public File temporaryFolder;
private static final FlagsTarget mainControllerTarget = FlagsTarget.forController(SYSTEM);
private static final FlagsTarget cdControllerTarget = FlagsTarget.forController(SystemName.cd);
@@ -75,8 +70,8 @@ public class SystemFlagsDataArchiveTest {
}
@Test
- public void can_serialize_and_deserialize_archive() throws IOException {
- File tempFile = temporaryFolder.newFile("serialized-flags-archive");
+ void can_serialize_and_deserialize_archive() throws IOException {
+ File tempFile = File.createTempFile("serialized-flags-archive", null, temporaryFolder);
try (OutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile))) {
var archive = SystemFlagsDataArchive.fromDirectory(Paths.get("src/test/resources/system-flags/"));
archive.toZip(out);
@@ -88,26 +83,27 @@ public class SystemFlagsDataArchiveTest {
}
@Test
- public void retrieves_correct_flag_data_for_target() {
+ void retrieves_correct_flag_data_for_target() {
var archive = SystemFlagsDataArchive.fromDirectory(Paths.get("src/test/resources/system-flags/"));
assertArchiveReturnsCorrectTestFlagDataForTarget(archive);
}
@Test
- public void supports_multi_level_flags_directory() {
+ void supports_multi_level_flags_directory() {
var archive = SystemFlagsDataArchive.fromDirectory(Paths.get("src/test/resources/system-flags-multi-level/"));
assertFlagDataHasValue(archive, MY_TEST_FLAG, mainControllerTarget, "default");
}
@Test
- public void duplicated_flagdata_is_detected() {
- expectedException.expect(IllegalArgumentException.class);
- expectedException.expectMessage("contains redundant flag data for id 'my-test-flag' already set in another directory!");
- var archive = SystemFlagsDataArchive.fromDirectory(Paths.get("src/test/resources/system-flags-multi-level-with-duplicated-flagdata/"));
+ void duplicated_flagdata_is_detected() {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ var archive = SystemFlagsDataArchive.fromDirectory(Paths.get("src/test/resources/system-flags-multi-level-with-duplicated-flagdata/"));
+ });
+ assertTrue(exception.getMessage().contains("contains redundant flag data for id 'my-test-flag' already set in another directory!"));
}
@Test
- public void empty_files_are_handled_as_no_flag_data_for_target() {
+ void empty_files_are_handled_as_no_flag_data_for_target() {
var archive = SystemFlagsDataArchive.fromDirectory(Paths.get("src/test/resources/system-flags/"));
assertNoFlagData(archive, FLAG_WITH_EMPTY_DATA, mainControllerTarget);
assertFlagDataHasValue(archive, FLAG_WITH_EMPTY_DATA, prodUsWestCfgTarget, "main.prod.us-west-1");
@@ -116,43 +112,45 @@ public class SystemFlagsDataArchiveTest {
}
@Test
- public void throws_exception_on_non_json_file() {
- expectedException.expect(IllegalArgumentException.class);
- expectedException.expectMessage("Only JSON files are allowed in 'flags/' directory (found 'flags/my-test-flag/file-name-without-dot-json')");
- SystemFlagsDataArchive.fromDirectory(Paths.get("src/test/resources/system-flags-with-invalid-file-name/"));
+ void throws_exception_on_non_json_file() {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ SystemFlagsDataArchive.fromDirectory(Paths.get("src/test/resources/system-flags-with-invalid-file-name/"));
+ });
+ assertTrue(exception.getMessage().contains("Only JSON files are allowed in 'flags/' directory (found 'flags/my-test-flag/file-name-without-dot-json')"));
}
@Test
- public void throws_exception_on_unknown_file() {
- SystemFlagsDataArchive archive = SystemFlagsDataArchive.fromDirectory(Paths.get("src/test/resources/system-flags-with-unknown-file-name/"));
- expectedException.expect(IllegalArgumentException.class);
- expectedException.expectMessage("Unknown flag file: flags/my-test-flag/main.prod.unknown-region.json");
- archive.validateAllFilesAreForTargets(SystemName.main, Set.of(mainControllerTarget, prodUsWestCfgTarget));
+ void throws_exception_on_unknown_file() {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ SystemFlagsDataArchive archive = SystemFlagsDataArchive.fromDirectory(Paths.get("src/test/resources/system-flags-with-unknown-file-name/"));
+ archive.validateAllFilesAreForTargets(SystemName.main, Set.of(mainControllerTarget, prodUsWestCfgTarget));
+ });
+ assertTrue(exception.getMessage().contains("Unknown flag file: flags/my-test-flag/main.prod.unknown-region.json"));
}
@Test
- public void throws_exception_on_unknown_region() {
- Path directory = Paths.get("src/test/resources/system-flags-with-unknown-file-name/");
- expectedException.expect(IllegalArgumentException.class);
- expectedException.expectMessage(
- "Environment or zone in filename 'main.prod.unknown-region.json' does not exist");
- SystemFlagsDataArchive.fromDirectoryAndSystem(directory, createZoneRegistryMock());
+ void throws_exception_on_unknown_region() {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ Path directory = Paths.get("src/test/resources/system-flags-with-unknown-file-name/");
+ SystemFlagsDataArchive.fromDirectoryAndSystem(directory, createZoneRegistryMock());
+ });
+ assertTrue(exception.getMessage().contains("Environment or zone in filename 'main.prod.unknown-region.json' does not exist"));
}
@Test
- public void throws_on_unknown_field() {
- expectedException.expect(IllegalArgumentException.class);
- expectedException.expectMessage(
- "flags/my-test-flag/main.prod.us-west-1.json contains unknown non-comment fields: after removing any comment fields the JSON is:\n" +
+ void throws_on_unknown_field() {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ SystemFlagsDataArchive.fromDirectory(Paths.get("src/test/resources/system-flags-with-unknown-field-name/"));
+ });
+ assertTrue(exception.getMessage().contains("flags/my-test-flag/main.prod.us-west-1.json contains unknown non-comment fields: after removing any comment fields the JSON is:\n" +
" {\"id\":\"my-test-flag\",\"rules\":[{\"condition\":[{\"type\":\"whitelist\",\"dimension\":\"hostname\",\"values\":[\"foo.com\"]}],\"value\":\"default\"}]}\n" +
"but deserializing this ended up with a JSON that are missing some of the fields:\n" +
" {\"id\":\"my-test-flag\",\"rules\":[{\"value\":\"default\"}]}\n" +
- "See https://git.ouroath.com/vespa/hosted-feature-flags for more info on the JSON syntax");
- SystemFlagsDataArchive.fromDirectory(Paths.get("src/test/resources/system-flags-with-unknown-field-name/"));
+ "See https://git.ouroath.com/vespa/hosted-feature-flags for more info on the JSON syntax"));
}
@Test
- public void remove_comments() {
+ void remove_comments() {
assertTrue(JSON.equals("{\n" +
" \"a\": {\n" +
" \"b\": 1\n" +
@@ -184,7 +182,7 @@ public class SystemFlagsDataArchiveTest {
}
@Test
- public void normalize_json_fail_on_invalid_application() {
+ void normalize_json_fail_on_invalid_application() {
try {
SystemFlagsDataArchive.normalizeJson("{\n" +
" \"id\": \"foo\",\n" +
@@ -208,7 +206,7 @@ public class SystemFlagsDataArchiveTest {
}
@Test
- public void normalize_json_fail_on_invalid_node_type() {
+ void normalize_json_fail_on_invalid_node_type() {
try {
SystemFlagsDataArchive.normalizeJson("{\n" +
" \"id\": \"foo\",\n" +
@@ -232,7 +230,7 @@ public class SystemFlagsDataArchiveTest {
}
@Test
- public void normalize_json_fail_on_invalid_email() {
+ void normalize_json_fail_on_invalid_email() {
try {
SystemFlagsDataArchive.normalizeJson("{\n" +
" \"id\": \"foo\",\n" +
@@ -256,7 +254,7 @@ public class SystemFlagsDataArchiveTest {
}
@Test
- public void normalize_json_fail_on_invalid_tenant_id() {
+ void normalize_json_fail_on_invalid_tenant_id() {
try {
SystemFlagsDataArchive.normalizeJson("{\n" +
" \"id\": \"foo\",\n" +
@@ -280,7 +278,7 @@ public class SystemFlagsDataArchiveTest {
}
@Test
- public void ignores_files_not_related_to_specified_system_definition() {
+ void ignores_files_not_related_to_specified_system_definition() {
ZoneRegistry registry = createZoneRegistryMock();
Path testDirectory = Paths.get("src/test/resources/system-flags-for-multiple-systems/");
var archive = SystemFlagsDataArchive.fromDirectoryAndSystem(testDirectory, registry);
diff --git a/controller-server/pom.xml b/controller-server/pom.xml
index 773d63202b6..3e889d926b1 100644
--- a/controller-server/pom.xml
+++ b/controller-server/pom.xml
@@ -169,12 +169,6 @@
<!-- test -->
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
-
- <dependency>
<groupId>com.yahoo.vespa</groupId>
<artifactId>application</artifactId>
<version>${project.version}</version>
@@ -186,11 +180,25 @@
<artifactId>testutil</artifactId>
<version>${project.version}</version>
<scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-core</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-library</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>com.github.tomakehurst</groupId>
- <artifactId>wiremock-standalone</artifactId>
+ <artifactId>wiremock-jre8-standalone</artifactId>
<scope>test</scope>
</dependency>
@@ -199,6 +207,16 @@
<artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
+ </dependency>
<dependency>
<groupId>org.mockito</groupId>
diff --git a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentStatus.java b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentStatus.java
index 24cd92d005f..1d7d75d9193 100644
--- a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentStatus.java
+++ b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentStatus.java
@@ -544,7 +544,9 @@ public class DeploymentStatus {
if (job.type().isProduction() && job.type().isDeployment()) {
declaredTest(job.application(), testType).ifPresent(testJob -> {
for (Job productionJob : versionsList)
- if (allJobs.successOn(testType, productionJob.versions()).asList().isEmpty())
+ if (allJobs.successOn(testType, productionJob.versions())
+ .instance(testJob.application().instance())
+ .asList().isEmpty())
testJobs.merge(testJob, List.of(new Job(testJob.type(),
productionJob.versions(),
jobSteps().get(testJob).readyAt(productionJob.change),
diff --git a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/Versions.java b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/Versions.java
index f4c4b8bebd4..d683f1cb5c7 100644
--- a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/Versions.java
+++ b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/Versions.java
@@ -76,7 +76,7 @@ public class Versions {
targetRevision.equals(versions.targetRevision());
}
- /** Returns wheter this change could result in the given target versions. */
+ /** Returns whether this change could result in the given target versions. */
public boolean targetsMatch(Change change) {
return change.platform().map(targetPlatform::equals).orElse(true)
&& change.revision().map(targetRevision::equals).orElse(true);
diff --git a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/ChangeRequestMaintainer.java b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/ChangeRequestMaintainer.java
index aa36d204c09..a279cf46415 100644
--- a/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/ChangeRequestMaintainer.java
+++ b/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/maintenance/ChangeRequestMaintainer.java
@@ -70,6 +70,7 @@ public class ChangeRequestMaintainer extends ControllerMaintainer {
var vcmr = existingChangeRequests
.getOrDefault(changeRequest.getId(), new VespaChangeRequest(changeRequest, zone))
.withSource(changeRequest.getChangeRequestSource())
+ .withImpact(changeRequest.getImpact())
.withApproval(changeRequest.getApproval());
logger.fine(() -> "Storing " + vcmr);
curator.writeChangeRequest(vcmr);
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/ControllerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/ControllerTest.java
index a8c18957773..b5177cd1d3e 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/ControllerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/ControllerTest.java
@@ -49,7 +49,7 @@ import com.yahoo.vespa.hosted.controller.routing.context.DeploymentRoutingContex
import com.yahoo.vespa.hosted.controller.routing.rotation.RotationId;
import com.yahoo.vespa.hosted.controller.routing.rotation.RotationLock;
import com.yahoo.vespa.hosted.rotation.config.RotationsConfig;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
@@ -69,13 +69,13 @@ import static com.yahoo.vespa.hosted.controller.deployment.DeploymentContext.pro
import static com.yahoo.vespa.hosted.controller.deployment.DeploymentContext.productionUsWest1;
import static com.yahoo.vespa.hosted.controller.deployment.DeploymentContext.stagingTest;
import static com.yahoo.vespa.hosted.controller.deployment.DeploymentContext.systemTest;
-import static org.junit.Assert.assertArrayEquals;
-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.assertArrayEquals;
+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.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author bratseth
@@ -86,7 +86,7 @@ public class ControllerTest {
private final DeploymentTester tester = new DeploymentTester();
@Test
- public void testDeployment() {
+ void testDeployment() {
// Setup system
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.region("us-west-1")
@@ -97,14 +97,14 @@ public class ControllerTest {
Version version1 = tester.configServer().initialVersion();
var context = tester.newDeploymentContext();
context.submit(applicationPackage);
- assertEquals("Application version is known from completion of initial job",
- ApplicationVersion.from(RevisionId.forProduction(1), DeploymentContext.defaultSourceRevision, "a@b", new Version("6.1"), Instant.ofEpochSecond(1)),
- context.application().revisions().get(context.instance().change().revision().get()));
+ assertEquals(ApplicationVersion.from(RevisionId.forProduction(1), DeploymentContext.defaultSourceRevision, "a@b", new Version("6.1"), Instant.ofEpochSecond(1)),
+ context.application().revisions().get(context.instance().change().revision().get()),
+ "Application version is known from completion of initial job");
context.runJob(systemTest);
context.runJob(stagingTest);
RevisionId applicationVersion = context.instance().change().revision().get();
- assertTrue("Application version has been set during deployment", applicationVersion.isProduction());
+ assertTrue(applicationVersion.isProduction(), "Application version has been set during deployment");
tester.triggerJobs();
// Causes first deployment job to be triggered
@@ -171,11 +171,11 @@ public class ControllerTest {
}
catch (IllegalArgumentException e) {
assertEquals("deployment-removal: application 'tenant.application' is deployed in us-west-1, but does not include this zone in deployment.xml. " +
- ValidationOverrides.toAllowMessage(ValidationId.deploymentRemoval),
- e.getMessage());
+ ValidationOverrides.toAllowMessage(ValidationId.deploymentRemoval),
+ e.getMessage());
}
- assertNotNull("Zone was not removed",
- context.instance().deployments().get(productionUsWest1.zone()));
+ assertNotNull(context.instance().deployments().get(productionUsWest1.zone()),
+ "Zone was not removed");
// prod zone removal is allowed with override
applicationPackage = new ApplicationPackageBuilder()
@@ -184,14 +184,14 @@ public class ControllerTest {
.region("us-east-3")
.build();
context.submit(applicationPackage);
- assertNull("Zone was removed",
- context.instance().deployments().get(productionUsWest1.zone()));
- assertNull("Deployment job was removed", context.instanceJobs().get(productionUsWest1));
+ assertNull(context.instance().deployments().get(productionUsWest1.zone()),
+ "Zone was removed");
+ assertNull(context.instanceJobs().get(productionUsWest1), "Deployment job was removed");
// Submission has stored application meta.
assertNotNull(tester.controllerTester().serviceRegistry().applicationStore()
- .getMeta(context.instanceId())
- .get(tester.clock().instant()));
+ .getMeta(context.instanceId())
+ .get(tester.clock().instant()));
// Meta data tombstone placed on delete
tester.clock().advance(Duration.ofSeconds(1));
@@ -199,18 +199,18 @@ public class ControllerTest {
tester.clock().advance(Duration.ofSeconds(1));
context.submit(ApplicationPackage.deploymentRemoval());
tester.applications().deleteApplication(context.application().id(),
- tester.controllerTester().credentialsFor(context.instanceId().tenant()));
+ tester.controllerTester().credentialsFor(context.instanceId().tenant()));
assertArrayEquals(new byte[0],
- tester.controllerTester().serviceRegistry().applicationStore()
- .getMeta(context.instanceId())
- .get(tester.clock().instant()));
+ tester.controllerTester().serviceRegistry().applicationStore()
+ .getMeta(context.instanceId())
+ .get(tester.clock().instant()));
assertNull(tester.controllerTester().serviceRegistry().applicationStore()
- .getMeta(context.deploymentIdIn(productionUsWest1.zone())));
+ .getMeta(context.deploymentIdIn(productionUsWest1.zone())));
}
@Test
- public void testGlobalRotationStatus() {
+ void testGlobalRotationStatus() {
var context = tester.newDeploymentContext();
var zone1 = ZoneId.from("prod", "us-west-1");
var zone2 = ZoneId.from("prod", "us-east-3");
@@ -238,7 +238,7 @@ public class ControllerTest {
}
@Test
- public void testDnsUpdatesForGlobalEndpoint() {
+ void testDnsUpdatesForGlobalEndpoint() {
var betaContext = tester.newDeploymentContext("tenant1", "app1", "beta");
var defaultContext = tester.newDeploymentContext("tenant1", "app1", "default");
@@ -251,23 +251,23 @@ public class ControllerTest {
.region(usCentral.region()) // Two deployments should result in each DNS alias being registered once
.build();
tester.controllerTester().zoneRegistry().setRoutingMethod(List.of(ZoneApiMock.from(usWest), ZoneApiMock.from(usCentral)),
- RoutingMethod.sharedLayer4);
+ RoutingMethod.sharedLayer4);
betaContext.submit(applicationPackage).deploy();
{ // Expected rotation names are passed to beta instance deployments
Collection<Deployment> betaDeployments = betaContext.instance().deployments().values();
assertFalse(betaDeployments.isEmpty());
Set<ContainerEndpoint> containerEndpoints = Set.of(new ContainerEndpoint("foo",
- "global",
- List.of("beta.app1.tenant1.global.vespa.oath.cloud",
- "rotation-id-01"),
- OptionalInt.empty(),
- RoutingMethod.sharedLayer4));
+ "global",
+ List.of("beta.app1.tenant1.global.vespa.oath.cloud",
+ "rotation-id-01"),
+ OptionalInt.empty(),
+ RoutingMethod.sharedLayer4));
for (Deployment deployment : betaDeployments) {
assertEquals(containerEndpoints,
- tester.configServer().containerEndpoints()
- .get(betaContext.deploymentIdIn(deployment.zone())));
+ tester.configServer().containerEndpoints()
+ .get(betaContext.deploymentIdIn(deployment.zone())));
}
betaContext.flushDnsUpdates();
}
@@ -276,20 +276,20 @@ public class ControllerTest {
Collection<Deployment> defaultDeployments = defaultContext.instance().deployments().values();
assertFalse(defaultDeployments.isEmpty());
Set<ContainerEndpoint> containerEndpoints = Set.of(new ContainerEndpoint("foo",
- "global",
- List.of("app1.tenant1.global.vespa.oath.cloud",
- "rotation-id-02"),
- OptionalInt.empty(),
- RoutingMethod.sharedLayer4));
+ "global",
+ List.of("app1.tenant1.global.vespa.oath.cloud",
+ "rotation-id-02"),
+ OptionalInt.empty(),
+ RoutingMethod.sharedLayer4));
for (Deployment deployment : defaultDeployments) {
assertEquals(containerEndpoints,
- tester.configServer().containerEndpoints().get(defaultContext.deploymentIdIn(deployment.zone())));
+ tester.configServer().containerEndpoints().get(defaultContext.deploymentIdIn(deployment.zone())));
}
defaultContext.flushDnsUpdates();
}
Map<String, String> rotationCnames = Map.of("beta.app1.tenant1.global.vespa.oath.cloud", "rotation-fqdn-01.",
- "app1.tenant1.global.vespa.oath.cloud", "rotation-fqdn-02.");
+ "app1.tenant1.global.vespa.oath.cloud", "rotation-fqdn-02.");
rotationCnames.forEach((cname, data) -> {
var record = tester.controllerTester().findCname(cname);
assertTrue(record.isPresent());
@@ -298,20 +298,20 @@ public class ControllerTest {
});
Map<ApplicationId, Set<String>> globalDnsNamesByInstance = Map.of(betaContext.instanceId(), Set.of("beta.app1.tenant1.global.vespa.oath.cloud"),
- defaultContext.instanceId(), Set.of("app1.tenant1.global.vespa.oath.cloud"));
+ defaultContext.instanceId(), Set.of("app1.tenant1.global.vespa.oath.cloud"));
globalDnsNamesByInstance.forEach((instance, dnsNames) -> {
Set<String> actualDnsNames = tester.controller().routing().readDeclaredEndpointsOf(instance)
- .scope(Endpoint.Scope.global)
- .asList().stream()
- .map(Endpoint::dnsName)
- .collect(Collectors.toSet());
- assertEquals("Global DNS names for " + instance, dnsNames, actualDnsNames);
+ .scope(Endpoint.Scope.global)
+ .asList().stream()
+ .map(Endpoint::dnsName)
+ .collect(Collectors.toSet());
+ assertEquals(dnsNames, actualDnsNames, "Global DNS names for " + instance);
});
}
@Test
- public void testDnsUpdatesForGlobalEndpointLegacySyntax() {
+ void testDnsUpdatesForGlobalEndpointLegacySyntax() {
var context = tester.newDeploymentContext("tenant1", "app1", "default");
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.globalServiceId("foo")
@@ -323,10 +323,10 @@ public class ControllerTest {
Collection<Deployment> deployments = context.instance().deployments().values();
assertFalse(deployments.isEmpty());
for (Deployment deployment : deployments) {
- assertEquals("Rotation names are passed to config server in " + deployment.zone(),
- Set.of("rotation-id-01",
+ assertEquals(Set.of("rotation-id-01",
"app1.tenant1.global.vespa.oath.cloud"),
- tester.configServer().containerEndpointNames(context.deploymentIdIn(deployment.zone())));
+ tester.configServer().containerEndpointNames(context.deploymentIdIn(deployment.zone())),
+ "Rotation names are passed to config server in " + deployment.zone());
}
context.flushDnsUpdates();
assertEquals(1, tester.controllerTester().nameService().records().size());
@@ -337,15 +337,15 @@ public class ControllerTest {
assertEquals("rotation-fqdn-01.", record.get().data().asString());
List<String> globalDnsNames = tester.controller().routing().readDeclaredEndpointsOf(context.instanceId())
- .scope(Endpoint.Scope.global)
- .sortedBy(Comparator.comparing(Endpoint::dnsName))
- .mapToList(Endpoint::dnsName);
+ .scope(Endpoint.Scope.global)
+ .sortedBy(Comparator.comparing(Endpoint::dnsName))
+ .mapToList(Endpoint::dnsName);
assertEquals(List.of("app1.tenant1.global.vespa.oath.cloud"),
- globalDnsNames);
+ globalDnsNames);
}
@Test
- public void testDnsUpdatesForMultipleGlobalEndpoints() {
+ void testDnsUpdatesForMultipleGlobalEndpoints() {
var context = tester.newDeploymentContext("tenant1", "app1", "default");
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.endpoint("foobar", "qrs", "us-west-1", "us-central-1") // Rotation 01
@@ -368,9 +368,9 @@ public class ControllerTest {
var west = Sets.union(notWest, Set.of("rotation-id-04", "west.app1.tenant1.global.vespa.oath.cloud"));
for (Deployment deployment : deployments) {
- assertEquals("Rotation names are passed to config server in " + deployment.zone(),
- ZoneId.from("prod.us-west-1").equals(deployment.zone()) ? west : notWest,
- tester.configServer().containerEndpointNames(context.deploymentIdIn(deployment.zone())));
+ assertEquals(ZoneId.from("prod.us-west-1").equals(deployment.zone()) ? west : notWest,
+ tester.configServer().containerEndpointNames(context.deploymentIdIn(deployment.zone())),
+ "Rotation names are passed to config server in " + deployment.zone());
}
context.flushDnsUpdates();
@@ -398,7 +398,7 @@ public class ControllerTest {
}
@Test
- public void testDnsUpdatesForGlobalEndpointChanges() {
+ void testDnsUpdatesForGlobalEndpointChanges() {
var context = tester.newDeploymentContext("tenant1", "app1", "default");
var west = ZoneId.from("prod", "us-west-1");
var central = ZoneId.from("prod", "us-central-1");
@@ -415,10 +415,10 @@ public class ControllerTest {
for (var zone : List.of(west, central)) {
assertEquals(
- "Zone " + zone + " is a member of global endpoint",
Set.of("rotation-id-01", "app1.tenant1.global.vespa.oath.cloud"),
tester.configServer().containerEndpointNames(context.deploymentIdIn(zone))
- );
+ ,
+ "Zone " + zone + " is a member of global endpoint");
}
// Application is deployed with an additional endpoint
@@ -433,16 +433,16 @@ public class ControllerTest {
for (var zone : List.of(west, central)) {
assertEquals(
- "Zone " + zone + " is a member of global endpoint",
Set.of("rotation-id-01", "app1.tenant1.global.vespa.oath.cloud"),
tester.configServer().containerEndpointNames(context.deploymentIdIn(zone))
- );
+ ,
+ "Zone " + zone + " is a member of global endpoint");
}
assertEquals(
- "Zone " + east + " is a member of global endpoint",
Set.of("rotation-id-02", "east.app1.tenant1.global.vespa.oath.cloud"),
tester.configServer().containerEndpointNames(context.deploymentIdIn(east))
- );
+ ,
+ "Zone " + east + " is a member of global endpoint");
// Application is deployed with default endpoint pointing to 3/3 zones
ApplicationPackage applicationPackage3 = new ApplicationPackageBuilder()
@@ -455,13 +455,13 @@ public class ControllerTest {
context.submit(applicationPackage3).deploy();
for (var zone : List.of(west, central, east)) {
assertEquals(
- "Zone " + zone + " is a member of global endpoint",
zone.equals(east)
? Set.of("rotation-id-01", "app1.tenant1.global.vespa.oath.cloud",
- "rotation-id-02", "east.app1.tenant1.global.vespa.oath.cloud")
+ "rotation-id-02", "east.app1.tenant1.global.vespa.oath.cloud")
: Set.of("rotation-id-01", "app1.tenant1.global.vespa.oath.cloud"),
tester.configServer().containerEndpointNames(context.deploymentIdIn(zone))
- );
+ ,
+ "Zone " + zone + " is a member of global endpoint");
}
// Region is removed from an endpoint without override
@@ -477,11 +477,11 @@ public class ControllerTest {
fail("Expected exception");
} catch (IllegalArgumentException e) {
assertEquals("global-endpoint-change: application 'tenant1.app1' has endpoints " +
- "[endpoint 'default' (cluster qrs) -> us-central-1, us-east-3, us-west-1, endpoint 'east' (cluster qrs) -> us-east-3], " +
- "but does not include all of these in deployment.xml. Deploying given deployment.xml " +
- "will remove [endpoint 'default' (cluster qrs) -> us-central-1, us-east-3, us-west-1] " +
- "and add [endpoint 'default' (cluster qrs) -> us-central-1, us-west-1]. " +
- ValidationOverrides.toAllowMessage(ValidationId.globalEndpointChange), e.getMessage());
+ "[endpoint 'default' (cluster qrs) -> us-central-1, us-east-3, us-west-1, endpoint 'east' (cluster qrs) -> us-east-3], " +
+ "but does not include all of these in deployment.xml. Deploying given deployment.xml " +
+ "will remove [endpoint 'default' (cluster qrs) -> us-central-1, us-east-3, us-west-1] " +
+ "and add [endpoint 'default' (cluster qrs) -> us-central-1, us-west-1]. " +
+ ValidationOverrides.toAllowMessage(ValidationId.globalEndpointChange), e.getMessage());
}
// Entire endpoint is removed without override
@@ -496,10 +496,10 @@ public class ControllerTest {
fail("Expected exception");
} catch (IllegalArgumentException e) {
assertEquals("global-endpoint-change: application 'tenant1.app1' has endpoints " +
- "[endpoint 'default' (cluster qrs) -> us-central-1, us-east-3, us-west-1, endpoint 'east' (cluster qrs) -> us-east-3], " +
- "but does not include all of these in deployment.xml. Deploying given deployment.xml " +
- "will remove [endpoint 'default' (cluster qrs) -> us-central-1, us-east-3, us-west-1]. " +
- ValidationOverrides.toAllowMessage(ValidationId.globalEndpointChange), e.getMessage());
+ "[endpoint 'default' (cluster qrs) -> us-central-1, us-east-3, us-west-1, endpoint 'east' (cluster qrs) -> us-east-3], " +
+ "but does not include all of these in deployment.xml. Deploying given deployment.xml " +
+ "will remove [endpoint 'default' (cluster qrs) -> us-central-1, us-east-3, us-west-1]. " +
+ ValidationOverrides.toAllowMessage(ValidationId.globalEndpointChange), e.getMessage());
}
// ... override is added
@@ -514,7 +514,7 @@ public class ControllerTest {
}
@Test
- public void testUnassignRotations() {
+ void testUnassignRotations() {
var context = tester.newDeploymentContext();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.endpoint("default", "qrs", "us-west-1", "us-central-1")
@@ -540,7 +540,7 @@ public class ControllerTest {
}
@Test
- public void testDnsUpdatesWithChangeInRotationAssignment() {
+ void testDnsUpdatesWithChangeInRotationAssignment() {
// Application 1 is deployed and deleted
String dnsName1 = "app1.tenant1.global.vespa.oath.cloud";
{
@@ -567,17 +567,17 @@ public class ControllerTest {
.build();
context.submit(applicationPackage);
tester.applications().deleteApplication(context.application().id(),
- tester.controllerTester().credentialsFor(context.application().id().tenant()));
+ tester.controllerTester().credentialsFor(context.application().id().tenant()));
try (RotationLock lock = tester.controller().routing().rotations().lock()) {
- assertTrue("Rotation is unassigned",
- tester.controller().routing().rotations().availableRotations(lock)
- .containsKey(new RotationId("rotation-id-01")));
+ assertTrue(tester.controller().routing().rotations().availableRotations(lock)
+ .containsKey(new RotationId("rotation-id-01")),
+ "Rotation is unassigned");
}
context.flushDnsUpdates();
// Record is removed
Optional<Record> record = tester.controllerTester().findCname(dnsName1);
- assertTrue(dnsName1 + " is removed", record.isEmpty());
+ assertTrue(record.isEmpty(), dnsName1 + " is removed");
}
// Application 2 is deployed and assigned same rotation as application 1 had before deletion
@@ -624,7 +624,7 @@ public class ControllerTest {
}
@Test
- public void testDnsUpdatesForApplicationEndpoint() {
+ void testDnsUpdatesForApplicationEndpoint() {
ApplicationId beta = ApplicationId.from("tenant1", "app1", "beta");
ApplicationId main = ApplicationId.from("tenant1", "app1", "main");
var context = tester.newDeploymentContext(beta);
@@ -633,14 +633,14 @@ public class ControllerTest {
.region("us-west-1")
.region("us-east-3")
.applicationEndpoint("a", "default", "us-west-1",
- Map.of(beta.instance(), 2,
- main.instance(), 8))
+ Map.of(beta.instance(), 2,
+ main.instance(), 8))
.applicationEndpoint("b", "default", "us-west-1",
- Map.of(beta.instance(), 1,
- main.instance(), 1))
+ Map.of(beta.instance(), 1,
+ main.instance(), 1))
.applicationEndpoint("c", "default", "us-east-3",
- Map.of(beta.instance(), 4,
- main.instance(), 6))
+ Map.of(beta.instance(), 4,
+ main.instance(), 6))
.build();
context.submit(applicationPackage).deploy();
@@ -649,63 +649,63 @@ public class ControllerTest {
// Expected container endpoints are passed to each deployment
Map<DeploymentId, Map<String, Integer>> deploymentEndpoints = Map.of(
new DeploymentId(beta, usWest), Map.of("a.app1.tenant1.us-west-1-r.vespa.oath.cloud", 2,
- "b.app1.tenant1.us-west-1-r.vespa.oath.cloud", 1),
+ "b.app1.tenant1.us-west-1-r.vespa.oath.cloud", 1),
new DeploymentId(main, usWest), Map.of("a.app1.tenant1.us-west-1-r.vespa.oath.cloud", 8,
- "b.app1.tenant1.us-west-1-r.vespa.oath.cloud", 1),
+ "b.app1.tenant1.us-west-1-r.vespa.oath.cloud", 1),
new DeploymentId(beta, usEast), Map.of("c.app1.tenant1.us-east-3-r.vespa.oath.cloud", 4),
new DeploymentId(main, usEast), Map.of("c.app1.tenant1.us-east-3-r.vespa.oath.cloud", 6)
);
deploymentEndpoints.forEach((deployment, endpoints) -> {
Set<ContainerEndpoint> expected = endpoints.entrySet().stream()
- .map(kv -> new ContainerEndpoint("default", "application",
- List.of(kv.getKey()),
- OptionalInt.of(kv.getValue()),
- RoutingMethod.sharedLayer4))
- .collect(Collectors.toSet());
- assertEquals("Endpoint names for " + deployment + " are passed to config server",
- expected,
- tester.configServer().containerEndpoints().get(deployment));
+ .map(kv -> new ContainerEndpoint("default", "application",
+ List.of(kv.getKey()),
+ OptionalInt.of(kv.getValue()),
+ RoutingMethod.sharedLayer4))
+ .collect(Collectors.toSet());
+ assertEquals(expected,
+ tester.configServer().containerEndpoints().get(deployment),
+ "Endpoint names for " + deployment + " are passed to config server");
});
context.flushDnsUpdates();
// DNS records are created for each endpoint
Set<Record> records = tester.controllerTester().nameService().records();
assertEquals(Set.of(new Record(Record.Type.CNAME,
- RecordName.from("a.app1.tenant1.us-west-1-r.vespa.oath.cloud"),
- RecordData.from("vip.prod.us-west-1.")),
- new Record(Record.Type.CNAME,
- RecordName.from("b.app1.tenant1.us-west-1-r.vespa.oath.cloud"),
- RecordData.from("vip.prod.us-west-1.")),
- new Record(Record.Type.CNAME,
- RecordName.from("c.app1.tenant1.us-east-3-r.vespa.oath.cloud"),
- RecordData.from("vip.prod.us-east-3."))),
- records);
+ RecordName.from("a.app1.tenant1.us-west-1-r.vespa.oath.cloud"),
+ RecordData.from("vip.prod.us-west-1.")),
+ new Record(Record.Type.CNAME,
+ RecordName.from("b.app1.tenant1.us-west-1-r.vespa.oath.cloud"),
+ RecordData.from("vip.prod.us-west-1.")),
+ new Record(Record.Type.CNAME,
+ RecordName.from("c.app1.tenant1.us-east-3-r.vespa.oath.cloud"),
+ RecordData.from("vip.prod.us-east-3."))),
+ records);
List<String> endpointDnsNames = tester.controller().routing().declaredEndpointsOf(context.application())
- .scope(Endpoint.Scope.application)
- .mapToList(Endpoint::dnsName);
+ .scope(Endpoint.Scope.application)
+ .mapToList(Endpoint::dnsName);
assertEquals(List.of("a.app1.tenant1.us-west-1-r.vespa.oath.cloud",
- "b.app1.tenant1.us-west-1-r.vespa.oath.cloud",
- "c.app1.tenant1.us-east-3-r.vespa.oath.cloud"),
- endpointDnsNames);
+ "b.app1.tenant1.us-west-1-r.vespa.oath.cloud",
+ "c.app1.tenant1.us-east-3-r.vespa.oath.cloud"),
+ endpointDnsNames);
}
@Test
- public void testDevDeployment() {
+ void testDevDeployment() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder().build();
// Create application
var context = tester.newDeploymentContext();
ZoneId zone = ZoneId.from("dev", "us-east-1");
tester.controllerTester().zoneRegistry()
- .setRoutingMethod(ZoneApiMock.from(zone), RoutingMethod.sharedLayer4);
+ .setRoutingMethod(ZoneApiMock.from(zone), RoutingMethod.sharedLayer4);
// Deploy
context.runJob(zone, applicationPackage);
- assertTrue("Application deployed and activated",
- tester.configServer().application(context.instanceId(), zone).get().activated());
- assertTrue("No job status added",
- context.instanceJobs().isEmpty());
- assertEquals("DeploymentSpec is not stored", DeploymentSpec.empty, context.application().deploymentSpec());
+ assertTrue(tester.configServer().application(context.instanceId(), zone).get().activated(),
+ "Application deployed and activated");
+ assertTrue(context.instanceJobs().isEmpty(),
+ "No job status added");
+ assertEquals(DeploymentSpec.empty, context.application().deploymentSpec(), "DeploymentSpec is not stored");
// Verify zone supports shared layer 4 and shared routing methods
Set<RoutingMethod> routingMethods = tester.controller().routing().readEndpointsOf(context.deploymentIdIn(zone))
@@ -717,20 +717,20 @@ public class ControllerTest {
// Deployment has stored application meta.
assertNotNull(tester.controllerTester().serviceRegistry().applicationStore()
- .getMeta(new DeploymentId(context.instanceId(), zone))
- .get(tester.clock().instant()));
+ .getMeta(new DeploymentId(context.instanceId(), zone))
+ .get(tester.clock().instant()));
// Meta data tombstone placed on delete
tester.clock().advance(Duration.ofSeconds(1));
tester.controller().applications().deactivate(context.instanceId(), zone);
assertArrayEquals(new byte[0],
- tester.controllerTester().serviceRegistry().applicationStore()
- .getMeta(new DeploymentId(context.instanceId(), zone))
- .get(tester.clock().instant()));
+ tester.controllerTester().serviceRegistry().applicationStore()
+ .getMeta(new DeploymentId(context.instanceId(), zone))
+ .get(tester.clock().instant()));
}
@Test
- public void testDevDeploymentWithIncompatibleVersions() {
+ void testDevDeploymentWithIncompatibleVersions() {
Version version1 = new Version("7");
Version version2 = new Version("7.5");
Version version3 = new Version("8");
@@ -778,12 +778,12 @@ public class ControllerTest {
}
@Test
- public void testSuspension() {
+ void testSuspension() {
var context = tester.newDeploymentContext();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
- .region("us-west-1")
- .region("us-east-3")
- .build();
+ .region("us-west-1")
+ .region("us-east-3")
+ .build();
context.submit(applicationPackage).deploy();
DeploymentId deployment1 = context.deploymentIdIn(ZoneId.from(Environment.prod, RegionName.from("us-west-1")));
@@ -798,7 +798,7 @@ public class ControllerTest {
// Application may already have been deleted, or deployment failed without response, test that deleting a
// second time will not fail
@Test
- public void testDeletingApplicationThatHasAlreadyBeenDeleted() {
+ void testDeletingApplicationThatHasAlreadyBeenDeleted() {
var context = tester.newDeploymentContext();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.region("us-west-1")
@@ -811,7 +811,7 @@ public class ControllerTest {
}
@Test
- public void testDeployApplicationWithWarnings() {
+ void testDeployApplicationWithWarnings() {
var context = tester.newDeploymentContext();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.region("us-west-1")
@@ -821,11 +821,11 @@ public class ControllerTest {
tester.configServer().generateWarnings(context.deploymentIdIn(zone), warnings);
context.submit(applicationPackage).deploy();
assertEquals(warnings, context.deployment(zone)
- .metrics().warnings().get(DeploymentMetrics.Warning.all).intValue());
+ .metrics().warnings().get(DeploymentMetrics.Warning.all).intValue());
}
@Test
- public void testDeploySelectivelyProvisionsCertificate() {
+ void testDeploySelectivelyProvisionsCertificate() {
Function<Instance, Optional<EndpointCertificateMetadata>> certificate = (application) -> tester.controller().curator().readEndpointCertificateMetadata(application.id());
// Create app1
@@ -835,22 +835,22 @@ public class ControllerTest {
var testZone = ZoneId.from("test", "us-east-1");
tester.controllerTester().zoneRegistry().exclusiveRoutingIn(ZoneApiMock.from(prodZone));
var applicationPackage = new ApplicationPackageBuilder().athenzIdentity(AthenzDomain.from("domain"), AthenzService.from("service"))
- .region(prodZone.region())
- .build();
+ .region(prodZone.region())
+ .build();
// Deploy app1 in production
context1.submit(applicationPackage).deploy();
var cert = certificate.apply(context1.instance());
- assertTrue("Provisions certificate in " + Environment.prod, cert.isPresent());
+ assertTrue(cert.isPresent(), "Provisions certificate in " + Environment.prod);
assertEquals(Stream.concat(Stream.of("vznqtz7a5ygwjkbhhj7ymxvlrekgt4l6g.vespa.oath.cloud",
- "app1.tenant1.global.vespa.oath.cloud",
- "*.app1.tenant1.global.vespa.oath.cloud"),
- Stream.of(prodZone, testZone, stagingZone)
- .flatMap(zone -> Stream.of("", "*.")
- .map(prefix -> prefix + "app1.tenant1." + zone.region().value() +
- (zone.environment() == Environment.prod ? "" : "." + zone.environment().value()) +
- ".vespa.oath.cloud")))
- .collect(Collectors.toUnmodifiableSet()),
- Set.copyOf(tester.controllerTester().serviceRegistry().endpointCertificateMock().dnsNamesOf(context1.instanceId())));
+ "app1.tenant1.global.vespa.oath.cloud",
+ "*.app1.tenant1.global.vespa.oath.cloud"),
+ Stream.of(prodZone, testZone, stagingZone)
+ .flatMap(zone -> Stream.of("", "*.")
+ .map(prefix -> prefix + "app1.tenant1." + zone.region().value() +
+ (zone.environment() == Environment.prod ? "" : "." + zone.environment().value()) +
+ ".vespa.oath.cloud")))
+ .collect(Collectors.toUnmodifiableSet()),
+ Set.copyOf(tester.controllerTester().serviceRegistry().endpointCertificateMock().dnsNamesOf(context1.instanceId())));
// Next deployment reuses certificate
context1.submit(applicationPackage).deploy();
@@ -862,13 +862,13 @@ public class ControllerTest {
// Deploy app2 in a zone with shared routing
context2.runJob(devZone, applicationPackage);
- assertTrue("Application deployed and activated",
- tester.configServer().application(context2.instanceId(), devZone).get().activated());
- assertTrue("Provisions certificate also in zone with routing layer", certificate.apply(context2.instance()).isPresent());
+ assertTrue(tester.configServer().application(context2.instanceId(), devZone).get().activated(),
+ "Application deployed and activated");
+ assertTrue(certificate.apply(context2.instance()).isPresent(), "Provisions certificate also in zone with routing layer");
}
@Test
- public void testDeployWithGlobalEndpointsInMultipleClouds() {
+ void testDeployWithGlobalEndpointsInMultipleClouds() {
tester.controllerTester().zoneRegistry().setZones(
ZoneApiMock.fromId("test.us-west-1"),
ZoneApiMock.fromId("staging.us-west-1"),
@@ -904,7 +904,7 @@ public class ControllerTest {
}
@Test
- public void testDeployWithoutSourceRevision() {
+ void testDeployWithoutSourceRevision() {
var context = tester.newDeploymentContext();
var applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
@@ -913,12 +913,12 @@ public class ControllerTest {
// Submit without source revision
context.submit(applicationPackage, Optional.empty())
- .deploy();
- assertEquals("Deployed application", 1, context.instance().deployments().size());
+ .deploy();
+ assertEquals(1, context.instance().deployments().size(), "Deployed application");
}
@Test
- public void testDeployWithGlobalEndpointsAndMultipleRoutingMethods() {
+ void testDeployWithGlobalEndpointsAndMultipleRoutingMethods() {
var context = tester.newDeploymentContext();
var zone1 = ZoneId.from("prod", "us-west-1");
var zone2 = ZoneId.from("prod", "us-east-3");
@@ -939,25 +939,25 @@ public class ControllerTest {
var expectedRecords = List.of(
// The weighted record for zone 2's region
new Record(Record.Type.ALIAS,
- RecordName.from("application.tenant.us-east-3-w.vespa.oath.cloud"),
- new WeightedAliasTarget(HostName.of("lb-0--tenant.application.default--prod.us-east-3"),
- "dns-zone-1", ZoneId.from("prod.us-east-3"), 1).pack()),
+ RecordName.from("application.tenant.us-east-3-w.vespa.oath.cloud"),
+ new WeightedAliasTarget(HostName.of("lb-0--tenant.application.default--prod.us-east-3"),
+ "dns-zone-1", ZoneId.from("prod.us-east-3"), 1).pack()),
// The 'east' global endpoint, pointing to the weighted record for zone 2's region
new Record(Record.Type.ALIAS,
- RecordName.from("east.application.tenant.global.vespa.oath.cloud"),
- new LatencyAliasTarget(HostName.of("application.tenant.us-east-3-w.vespa.oath.cloud"),
- "dns-zone-1", ZoneId.from("prod.us-east-3")).pack()),
+ RecordName.from("east.application.tenant.global.vespa.oath.cloud"),
+ new LatencyAliasTarget(HostName.of("application.tenant.us-east-3-w.vespa.oath.cloud"),
+ "dns-zone-1", ZoneId.from("prod.us-east-3")).pack()),
// The zone-scoped endpoint pointing to zone 2 with exclusive routing
new Record(Record.Type.CNAME,
- RecordName.from("application.tenant.us-east-3.vespa.oath.cloud"),
- RecordData.from("lb-0--tenant.application.default--prod.us-east-3.")));
+ RecordName.from("application.tenant.us-east-3.vespa.oath.cloud"),
+ RecordData.from("lb-0--tenant.application.default--prod.us-east-3.")));
assertEquals(expectedRecords, List.copyOf(tester.controllerTester().nameService().records()));
}
@Test
- public void testDeploymentDirectRouting() {
+ void testDeploymentDirectRouting() {
// Rotation-less system
DeploymentTester tester = new DeploymentTester(new ControllerTester(new RotationsConfig.Builder().build(), main));
var context = tester.newDeploymentContext();
@@ -965,7 +965,7 @@ public class ControllerTest {
var zone2 = ZoneId.from("prod", "us-east-3");
var zone3 = ZoneId.from("prod", "eu-west-1");
tester.controllerTester().zoneRegistry()
- .exclusiveRoutingIn(ZoneApiMock.from(zone1), ZoneApiMock.from(zone2), ZoneApiMock.from(zone3));
+ .exclusiveRoutingIn(ZoneApiMock.from(zone1), ZoneApiMock.from(zone2), ZoneApiMock.from(zone3));
var applicationPackageBuilder = new ApplicationPackageBuilder()
.region(zone1.region())
@@ -979,20 +979,20 @@ public class ControllerTest {
// Deployment passes container endpoints to config server
for (var zone : List.of(zone1, zone2)) {
- assertEquals("Expected container endpoints in " + zone,
- Set.of("application.tenant.global.vespa.oath.cloud",
- "foo.application.tenant.global.vespa.oath.cloud",
- "us.application.tenant.global.vespa.oath.cloud"),
- tester.configServer().containerEndpointNames(context.deploymentIdIn(zone)));
+ assertEquals(Set.of("application.tenant.global.vespa.oath.cloud",
+ "foo.application.tenant.global.vespa.oath.cloud",
+ "us.application.tenant.global.vespa.oath.cloud"),
+ tester.configServer().containerEndpointNames(context.deploymentIdIn(zone)),
+ "Expected container endpoints in " + zone);
}
- assertEquals("Expected container endpoints in " + zone3,
- Set.of("application.tenant.global.vespa.oath.cloud",
- "foo.application.tenant.global.vespa.oath.cloud"),
- tester.configServer().containerEndpointNames(context.deploymentIdIn(zone3)));
+ assertEquals(Set.of("application.tenant.global.vespa.oath.cloud",
+ "foo.application.tenant.global.vespa.oath.cloud"),
+ tester.configServer().containerEndpointNames(context.deploymentIdIn(zone3)),
+ "Expected container endpoints in " + zone3);
}
@Test
- public void testChangeEndpointCluster() {
+ void testChangeEndpointCluster() {
var context = tester.newDeploymentContext();
var west = ZoneId.from("prod", "us-west-1");
var east = ZoneId.from("prod", "us-east-3");
@@ -1005,7 +1005,7 @@ public class ControllerTest {
.build();
context.submit(applicationPackage).deploy();
assertEquals(ClusterSpec.Id.from("foo"), tester.applications().requireInstance(context.instanceId())
- .rotations().get(0).clusterId());
+ .rotations().get(0).clusterId());
// Redeploy with endpoint cluster changed needs override
applicationPackage = new ApplicationPackageBuilder()
@@ -1018,12 +1018,12 @@ public class ControllerTest {
fail("Expected exception");
} catch (IllegalArgumentException e) {
assertEquals("global-endpoint-change: application 'tenant.application' has endpoints [endpoint " +
- "'default' (cluster foo) -> us-east-3, us-west-1], but does not include all of these in " +
- "deployment.xml. Deploying given deployment.xml will remove " +
- "[endpoint 'default' (cluster foo) -> us-east-3, us-west-1] and add " +
- "[endpoint 'default' (cluster bar) -> us-east-3, us-west-1]. To allow this add " +
- "<allow until='yyyy-mm-dd'>global-endpoint-change</allow> to validation-overrides.xml, see " +
- "https://docs.vespa.ai/en/reference/validation-overrides.html", e.getMessage());
+ "'default' (cluster foo) -> us-east-3, us-west-1], but does not include all of these in " +
+ "deployment.xml. Deploying given deployment.xml will remove " +
+ "[endpoint 'default' (cluster foo) -> us-east-3, us-west-1] and add " +
+ "[endpoint 'default' (cluster bar) -> us-east-3, us-west-1]. To allow this add " +
+ "<allow until='yyyy-mm-dd'>global-endpoint-change</allow> to validation-overrides.xml, see " +
+ "https://docs.vespa.ai/en/reference/validation-overrides.html", e.getMessage());
}
// Redeploy with override succeeds
@@ -1035,26 +1035,26 @@ public class ControllerTest {
.build();
context.submit(applicationPackage).deploy();
assertEquals(ClusterSpec.Id.from("bar"), tester.applications().requireInstance(context.instanceId())
- .rotations().get(0).clusterId());
+ .rotations().get(0).clusterId());
}
@Test
- public void testReadableApplications() {
+ void testReadableApplications() {
var db = new MockCuratorDb(tester.controller().system());
var tester = new DeploymentTester(new ControllerTester(db));
// Create and deploy two applications
var app1 = tester.newDeploymentContext("t1", "a1", "default")
- .submit()
- .deploy();
+ .submit()
+ .deploy();
var app2 = tester.newDeploymentContext("t2", "a2", "default")
- .submit()
- .deploy();
+ .submit()
+ .deploy();
assertEquals(2, tester.applications().readable().size());
// Write invalid data to one application
db.curator().set(Path.fromString("/controller/v1/applications/" + app2.application().id().serialized()),
- new byte[]{(byte) 0xDE, (byte) 0xAD});
+ new byte[]{(byte) 0xDE, (byte) 0xAD});
// Can read the remaining readable
assertEquals(1, tester.applications().readable().size());
@@ -1071,57 +1071,57 @@ public class ControllerTest {
}
@Test
- public void testClashingEndpointIdAndInstanceName() {
+ void testClashingEndpointIdAndInstanceName() {
String deploymentXml = "<deployment version='1.0' athenz-domain='domain' athenz-service='service'>\n" +
- " <instance id=\"default\">\n" +
- " <prod>\n" +
- " <region active=\"true\">us-west-1</region>\n" +
- " </prod>\n" +
- " <endpoints>\n" +
- " <endpoint id=\"dev\" container-id=\"qrs\"/>\n" +
- " </endpoints>\n" +
- " </instance>\n" +
- " <instance id=\"dev\">\n" +
- " <prod>\n" +
- " <region active=\"true\">us-west-1</region>\n" +
- " </prod>\n" +
- " <endpoints>\n" +
- " <endpoint id=\"default\" container-id=\"qrs\"/>\n" +
- " </endpoints>\n" +
- " </instance>\n" +
- "</deployment>\n";
+ " <instance id=\"default\">\n" +
+ " <prod>\n" +
+ " <region active=\"true\">us-west-1</region>\n" +
+ " </prod>\n" +
+ " <endpoints>\n" +
+ " <endpoint id=\"dev\" container-id=\"qrs\"/>\n" +
+ " </endpoints>\n" +
+ " </instance>\n" +
+ " <instance id=\"dev\">\n" +
+ " <prod>\n" +
+ " <region active=\"true\">us-west-1</region>\n" +
+ " </prod>\n" +
+ " <endpoints>\n" +
+ " <endpoint id=\"default\" container-id=\"qrs\"/>\n" +
+ " </endpoints>\n" +
+ " </instance>\n" +
+ "</deployment>\n";
ApplicationPackage applicationPackage = ApplicationPackageBuilder.fromDeploymentXml(deploymentXml);
try {
tester.newDeploymentContext().submit(applicationPackage);
fail("Expected exception");
} catch (IllegalArgumentException e) {
assertEquals("Endpoint with ID 'default' in instance 'dev' clashes with endpoint 'dev' in instance 'default'",
- e.getMessage());
+ e.getMessage());
}
}
@Test
- public void testTestPackageWarnings() {
+ void testTestPackageWarnings() {
String deploymentXml = "<deployment version='1.0'>\n" +
- " <prod>\n" +
- " <region>us-west-1</region>\n" +
- " </prod>\n" +
- "</deployment>\n";
+ " <prod>\n" +
+ " <region>us-west-1</region>\n" +
+ " </prod>\n" +
+ "</deployment>\n";
ApplicationPackage applicationPackage = ApplicationPackageBuilder.fromDeploymentXml(deploymentXml);
byte[] testPackage = ApplicationPackage.filesZip(Map.of("tests/staging-test/foo.json", new byte[0]));
var app = tester.newDeploymentContext();
tester.jobs().submit(app.application().id(), Submission.basic(applicationPackage, testPackage), 1);
assertEquals(List.of(new Notification(tester.clock().instant(),
- Type.testPackage,
- Level.warning,
- NotificationSource.from(app.application().id()),
- List.of("test package has staging tests, so it should also include staging setup",
- "see https://docs.vespa.ai/en/testing.html for details on how to write system tests for Vespa"))),
- tester.controller().notificationsDb().listNotifications(NotificationSource.from(app.application().id()), true));
+ Type.testPackage,
+ Level.warning,
+ NotificationSource.from(app.application().id()),
+ List.of("test package has staging tests, so it should also include staging setup",
+ "see https://docs.vespa.ai/en/testing.html for details on how to write system tests for Vespa"))),
+ tester.controller().notificationsDb().listNotifications(NotificationSource.from(app.application().id()), true));
}
@Test
- public void testCompileVersion() {
+ void testCompileVersion() {
DeploymentContext context = tester.newDeploymentContext();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder().region("us-west-1").build();
TenantAndApplicationId application = TenantAndApplicationId.from(context.instanceId());
@@ -1186,7 +1186,7 @@ public class ControllerTest {
}
@Test
- public void testCloudAccount() {
+ void testCloudAccount() {
DeploymentContext context = tester.newDeploymentContext();
ZoneId zone = ZoneId.from("prod", "us-west-1");
String cloudAccount = "012345678912";
@@ -1197,7 +1197,8 @@ public class ControllerTest {
try {
context.submit(applicationPackage).deploy();
fail("Expected exception"); // Account invalid for tenant
- } catch (IllegalArgumentException ignored) {}
+ } catch (IllegalArgumentException ignored) {
+ }
tester.controllerTester().flagSource().withListFlag(PermanentFlags.CLOUD_ACCOUNTS.id(), List.of(cloudAccount), String.class);
context.submit(applicationPackage).deploy();
@@ -1205,7 +1206,7 @@ public class ControllerTest {
}
@Test
- public void testSubmitWithElementDeprecatedOnPreviousMajor() {
+ void testSubmitWithElementDeprecatedOnPreviousMajor() {
DeploymentContext context = tester.newDeploymentContext();
var applicationPackage = new ApplicationPackageBuilder()
.compileVersion(Version.fromString("8.1"))
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/ControllerTester.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/ControllerTester.java
index a2eefd47b56..10fd57ce032 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/ControllerTester.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/ControllerTester.java
@@ -74,9 +74,8 @@ import java.util.logging.Handler;
import java.util.logging.Logger;
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.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Convenience methods for controller tests.
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/DeploymentQuotaCalculatorTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/DeploymentQuotaCalculatorTest.java
index 11b3ad0d45a..3163c8b6439 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/DeploymentQuotaCalculatorTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/DeploymentQuotaCalculatorTest.java
@@ -17,7 +17,7 @@ import com.yahoo.vespa.hosted.controller.api.integration.deployment.RevisionId;
import com.yahoo.vespa.hosted.controller.api.integration.noderepository.ApplicationData;
import com.yahoo.vespa.hosted.controller.deployment.RevisionHistory;
import com.yahoo.vespa.hosted.controller.metric.ApplicationMetrics;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.file.Files;
import java.nio.file.Paths;
@@ -29,13 +29,13 @@ import java.util.OptionalInt;
import java.util.OptionalLong;
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 DeploymentQuotaCalculatorTest {
@Test
- public void quota_is_divided_among_prod_instances() {
+ void quota_is_divided_among_prod_instances() {
Quota calculated = DeploymentQuotaCalculator.calculate(Quota.unlimited().withBudget(10), List.of(), ApplicationId.defaultId(), ZoneId.defaultId(),
DeploymentSpec.fromXml(
"<deployment version='1.0'>\n" +
@@ -59,12 +59,12 @@ public class DeploymentQuotaCalculatorTest {
}
@Test
- public void quota_is_divided_among_prod_and_manual_instances() {
+ void quota_is_divided_among_prod_and_manual_instances() {
var existing_dev_deployment = new Application(TenantAndApplicationId.from(ApplicationId.defaultId()), Instant.EPOCH, DeploymentSpec.empty, ValidationOverrides.empty, Optional.empty(),
- Optional.empty(), Optional.empty(), OptionalInt.empty(), new ApplicationMetrics(1, 1), Set.of(), OptionalLong.empty(), RevisionHistory.empty(),
- List.of(new Instance(ApplicationId.defaultId()).withNewDeployment(ZoneId.from(Environment.dev, RegionName.defaultName()),
- RevisionId.forProduction(1), Version.emptyVersion, Instant.EPOCH, Map.of(), QuotaUsage.create(0.53d))));
+ Optional.empty(), Optional.empty(), OptionalInt.empty(), new ApplicationMetrics(1, 1), Set.of(), OptionalLong.empty(), RevisionHistory.empty(),
+ List.of(new Instance(ApplicationId.defaultId()).withNewDeployment(ZoneId.from(Environment.dev, RegionName.defaultName()),
+ RevisionId.forProduction(1), Version.emptyVersion, Instant.EPOCH, Map.of(), QuotaUsage.create(0.53d))));
Quota calculated = DeploymentQuotaCalculator.calculate(Quota.unlimited().withBudget(2), List.of(existing_dev_deployment), ApplicationId.defaultId(), ZoneId.defaultId(),
DeploymentSpec.fromXml(
@@ -84,19 +84,19 @@ public class DeploymentQuotaCalculatorTest {
}
@Test
- public void unlimited_quota_remains_unlimited() {
+ void unlimited_quota_remains_unlimited() {
Quota calculated = DeploymentQuotaCalculator.calculate(Quota.unlimited(), List.of(), ApplicationId.defaultId(), ZoneId.defaultId(), DeploymentSpec.empty);
assertTrue(calculated.isUnlimited());
}
@Test
- public void zero_quota_remains_zero() {
+ void zero_quota_remains_zero() {
Quota calculated = DeploymentQuotaCalculator.calculate(Quota.zero(), List.of(), ApplicationId.defaultId(), ZoneId.defaultId(), DeploymentSpec.empty);
assertEquals(calculated.budget().orElseThrow().doubleValue(), 0, 1e-5);
}
@Test
- public void using_highest_resource_use() throws Exception {
+ void using_highest_resource_use() throws Exception {
var content = new String(Files.readAllBytes(Paths.get("src/test/java/com/yahoo/vespa/hosted/controller/application/response/application.json")));
var mapper = new ObjectMapper();
var application = mapper.readValue(content, ApplicationData.class).toApplication();
@@ -105,7 +105,7 @@ public class DeploymentQuotaCalculatorTest {
}
@Test
- public void tenant_quota_in_pipeline() {
+ void tenant_quota_in_pipeline() {
var tenantQuota = Quota.unlimited().withBudget(42);
var calculated = DeploymentQuotaCalculator.calculate(tenantQuota, List.of(), ApplicationId.defaultId(), ZoneId.from("test", "apac1"), DeploymentSpec.empty);
assertEquals(tenantQuota, calculated);
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/EndpointTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/EndpointTest.java
index 81fc610d1f6..f3324e0c1f3 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/EndpointTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/EndpointTest.java
@@ -8,12 +8,12 @@ import com.yahoo.config.provision.zone.RoutingMethod;
import com.yahoo.config.provision.zone.ZoneId;
import com.yahoo.vespa.hosted.controller.api.identifiers.DeploymentId;
import com.yahoo.vespa.hosted.controller.application.Endpoint.Port;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author mpolden
@@ -26,7 +26,7 @@ public class EndpointTest {
private static final TenantAndApplicationId app2 = TenantAndApplicationId.from(instance2);
@Test
- public void global_endpoints() {
+ void global_endpoints() {
DeploymentId deployment1 = new DeploymentId(instance1, ZoneId.from("prod", "us-north-1"));
DeploymentId deployment2 = new DeploymentId(instance2, ZoneId.from("prod", "us-north-1"));
ClusterSpec.Id cluster = ClusterSpec.Id.from("default");
@@ -72,7 +72,7 @@ public class EndpointTest {
}
@Test
- public void global_endpoints_with_endpoint_id() {
+ void global_endpoints_with_endpoint_id() {
DeploymentId deployment1 = new DeploymentId(instance1, ZoneId.from("prod", "us-north-1"));
DeploymentId deployment2 = new DeploymentId(instance2, ZoneId.from("prod", "us-north-1"));
ClusterSpec.Id cluster = ClusterSpec.Id.from("default");
@@ -114,7 +114,7 @@ public class EndpointTest {
}
@Test
- public void zone_endpoints() {
+ void zone_endpoints() {
var cluster = ClusterSpec.Id.from("default"); // Always default for non-direct routing
var prodZone = new DeploymentId(instance1, ZoneId.from("prod", "us-north-1"));
var prodZone2 = new DeploymentId(instance2, ZoneId.from("prod", "us-north-1"));
@@ -172,7 +172,7 @@ public class EndpointTest {
}
@Test
- public void certificate_endpoints() {
+ void certificate_endpoints() {
var defaultCluster = ClusterSpec.Id.from("default");
var prodZone = new DeploymentId(instance1, ZoneId.from("prod", "us-north-1"));
var testZone = new DeploymentId(instance1, ZoneId.from("test", "us-north-2"));
@@ -237,7 +237,7 @@ public class EndpointTest {
}
@Test
- public void region_endpoints() {
+ void region_endpoints() {
var cluster = ClusterSpec.Id.from("default");
var prodZone = ZoneId.from("prod", "us-north-2");
Map<String, Endpoint> tests = Map.of(
@@ -268,42 +268,42 @@ public class EndpointTest {
);
tests.forEach((expected, endpoint) -> assertEquals(expected, endpoint.url().toString()));
- assertEquals("Availability zone is removed from region",
- "aws-us-north-1",
- tests.get("https://a1.t1.aws-us-north-1.w.vespa-app.cloud/").targets().get(0).deployment().zoneId().region().value());
- assertEquals("Availability zone is removed from region",
- "gcp-us-south1",
- tests.get("https://a1.t1.gcp-us-south1.w.vespa-app.cloud/").targets().get(0).deployment().zoneId().region().value());
+ assertEquals("aws-us-north-1",
+ tests.get("https://a1.t1.aws-us-north-1.w.vespa-app.cloud/").targets().get(0).deployment().zoneId().region().value(),
+ "Availability zone is removed from region");
+ assertEquals("gcp-us-south1",
+ tests.get("https://a1.t1.gcp-us-south1.w.vespa-app.cloud/").targets().get(0).deployment().zoneId().region().value(),
+ "Availability zone is removed from region");
}
@Test
- public void application_endpoints() {
+ void application_endpoints() {
Map<String, Endpoint> tests = Map.of(
"https://weighted.a1.t1.us-west-1.r.vespa-app.cloud/",
Endpoint.of(app1)
.targetApplication(EndpointId.of("weighted"), ClusterSpec.Id.from("qrs"),
- Map.of(new DeploymentId(app1.instance("i1"), ZoneId.from("prod", "us-west-1")), 1))
+ Map.of(new DeploymentId(app1.instance("i1"), ZoneId.from("prod", "us-west-1")), 1))
.routingMethod(RoutingMethod.exclusive)
.on(Port.tls())
.in(SystemName.Public),
"https://weighted.a1.t1.us-west-1.r.cd.vespa-app.cloud/",
Endpoint.of(app1)
.targetApplication(EndpointId.of("weighted"), ClusterSpec.Id.from("qrs"),
- Map.of(new DeploymentId(app1.instance("i1"), ZoneId.from("prod", "us-west-1")), 1))
+ Map.of(new DeploymentId(app1.instance("i1"), ZoneId.from("prod", "us-west-1")), 1))
.routingMethod(RoutingMethod.exclusive)
.on(Port.tls())
.in(SystemName.PublicCd),
"https://a2.t2.us-east-3-r.vespa.oath.cloud/",
Endpoint.of(app2)
.targetApplication(EndpointId.defaultId(), ClusterSpec.Id.from("qrs"),
- Map.of(new DeploymentId(app2.instance("i1"), ZoneId.from("prod", "us-east-3")), 1))
+ Map.of(new DeploymentId(app2.instance("i1"), ZoneId.from("prod", "us-east-3")), 1))
.routingMethod(RoutingMethod.exclusive)
.on(Port.tls())
.in(SystemName.main),
"https://cd.a2.t2.us-east-3-r.vespa.oath.cloud/",
Endpoint.of(app2)
.targetApplication(EndpointId.defaultId(), ClusterSpec.Id.from("qrs"),
- Map.of(new DeploymentId(app2.instance("i1"), ZoneId.from("prod", "us-east-3")), 1))
+ Map.of(new DeploymentId(app2.instance("i1"), ZoneId.from("prod", "us-east-3")), 1))
.routingMethod(RoutingMethod.exclusive)
.on(Port.tls())
.in(SystemName.cd)
@@ -312,7 +312,7 @@ public class EndpointTest {
}
@Test
- public void upstream_name() {
+ void upstream_name() {
var zone = new DeploymentId(instance1, ZoneId.from("prod", "us-north-1"));
var zone2 = new DeploymentId(instance2, ZoneId.from("prod", "us-north-1"));
var tests1 = Map.of(
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/ApplicationPackageDiffTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/ApplicationPackageDiffTest.java
index 977304db3fb..a92c035b502 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/ApplicationPackageDiffTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/ApplicationPackageDiffTest.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.vespa.hosted.controller.application.pkg;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -14,7 +14,7 @@ import java.util.zip.ZipOutputStream;
import static com.yahoo.vespa.hosted.controller.application.pkg.ApplicationPackageDiff.diff;
import static com.yahoo.vespa.hosted.controller.application.pkg.ApplicationPackageDiff.diffAgainstEmpty;
import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author freva
@@ -24,12 +24,12 @@ public class ApplicationPackageDiffTest {
private static final ApplicationPackage app2 = applicationPackage(Map.of("file1", "updated contents\nof the\nfirst file\nafter some changes", "dir/myfile2", "Second file", "dir/binary", "øøøø"));
@Test
- public void no_diff() {
+ void no_diff() {
assertEquals("No diff\n", new String(diff(app1, app1)));
}
@Test
- public void diff_against_empty() {
+ void diff_against_empty() {
assertEquals("--- dir/binary\n" +
"Diff skipped: File is binary (new file -> 8B)\n" +
"\n" +
@@ -45,7 +45,7 @@ public class ApplicationPackageDiffTest {
}
@Test
- public void full_diff() {
+ void full_diff() {
// Even though dir/binary is binary file, we can see they are identical, so it should not print "Diff skipped"
assertEquals("--- dir/myfile\n" +
"@@ -1,1 +1,0 @@\n" +
@@ -66,7 +66,7 @@ public class ApplicationPackageDiffTest {
}
@Test
- public void skips_diff_for_too_large_files() {
+ void skips_diff_for_too_large_files() {
assertEquals("--- dir/myfile\n" +
"@@ -1,1 +1,0 @@\n" +
"- Second file\n" +
@@ -81,7 +81,7 @@ public class ApplicationPackageDiffTest {
}
@Test
- public void skips_diff_if_file_diff_is_too_large() {
+ void skips_diff_if_file_diff_is_too_large() {
assertEquals("--- dir/myfile\n" +
"@@ -1,1 +1,0 @@\n" +
"- Second file\n" +
@@ -96,7 +96,7 @@ public class ApplicationPackageDiffTest {
}
@Test
- public void skips_diff_if_total_diff_is_too_large() {
+ void skips_diff_if_total_diff_is_too_large() {
assertEquals("--- dir/myfile\n" +
"@@ -1,1 +1,0 @@\n" +
"- Second file\n" +
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/ApplicationPackageTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/ApplicationPackageTest.java
index 0458f77fc00..ce7fa5784e8 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/ApplicationPackageTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/ApplicationPackageTest.java
@@ -3,7 +3,7 @@ package com.yahoo.vespa.hosted.controller.application.pkg;
import com.yahoo.config.application.api.DeploymentSpec;
import com.yahoo.config.application.api.ValidationId;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -13,10 +13,10 @@ import java.util.Map;
import java.util.stream.Collectors;
import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-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.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author valerijf
@@ -55,7 +55,7 @@ public class ApplicationPackageTest {
"</nodes>";
@Test
- public void test_createEmptyForDeploymentRemoval() {
+ void test_createEmptyForDeploymentRemoval() {
ApplicationPackage app = ApplicationPackage.deploymentRemoval();
assertEquals(DeploymentSpec.empty, app.deploymentSpec());
assertEquals(List.of(), app.trustedCertificates());
@@ -66,22 +66,22 @@ public class ApplicationPackageTest {
}
@Test
- public void testMetaData() {
+ void testMetaData() {
byte[] zip = ApplicationPackage.filesZip(Map.of("services.xml", servicesXml.getBytes(UTF_8),
- "jdisc.xml", jdiscXml.getBytes(UTF_8),
- "content/content.xml", contentXml.getBytes(UTF_8),
- "content/nodes.xml", nodesXml.getBytes(UTF_8),
- "gurba", "gurba".getBytes(UTF_8)));
+ "jdisc.xml", jdiscXml.getBytes(UTF_8),
+ "content/content.xml", contentXml.getBytes(UTF_8),
+ "content/nodes.xml", nodesXml.getBytes(UTF_8),
+ "gurba", "gurba".getBytes(UTF_8)));
assertEquals(Map.of("services.xml", servicesXml,
- "jdisc.xml", jdiscXml,
- "content/content.xml", contentXml,
- "content/nodes.xml", nodesXml),
- unzip(new ApplicationPackage(zip, false).metaDataZip()));
+ "jdisc.xml", jdiscXml,
+ "content/content.xml", contentXml,
+ "content/nodes.xml", nodesXml),
+ unzip(new ApplicationPackage(zip, false).metaDataZip()));
}
@Test
- public void testMetaDataWithMissingFiles() {
+ void testMetaDataWithMissingFiles() {
byte[] zip = ApplicationPackage.filesZip(Map.of("services.xml", servicesXml.getBytes(UTF_8)));
try {
@@ -94,7 +94,7 @@ public class ApplicationPackageTest {
}
@Test
- public void testAbsoluteInclude() throws Exception {
+ void testAbsoluteInclude() throws Exception {
try {
getApplicationZip("include-absolute.zip");
fail("Should fail on include file outside zip");
@@ -105,7 +105,7 @@ public class ApplicationPackageTest {
}
@Test
- public void testParentInclude() throws Exception {
+ void testParentInclude() throws Exception {
try {
getApplicationZip("include-parent.zip");
fail("Should fail on include file outside zip");
@@ -116,7 +116,7 @@ public class ApplicationPackageTest {
}
@Test
- public void testBundleHashesAreSameWithDifferentDeploymentXml() throws Exception {
+ void testBundleHashesAreSameWithDifferentDeploymentXml() throws Exception {
var originalPackage = getApplicationZip("original.zip");
var changedServices = getApplicationZip("changed-services-xml.zip");
var changedDeploymentXml = getApplicationZip("changed-deployment-xml.zip");
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/LinesComparatorTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/LinesComparatorTest.java
index 92137094f62..8d9f88ca0ca 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/LinesComparatorTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/LinesComparatorTest.java
@@ -1,12 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.application.pkg;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Optional;
import java.util.stream.Collectors;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class LinesComparatorTest {
private static final String text1 = "This part of the\n" +
@@ -64,7 +64,7 @@ public class LinesComparatorTest {
"to this document.";
@Test
- public void diff_test() {
+ void diff_test() {
assertDiff(null, "", "");
assertDiff(null, text1, text1);
assertDiff(text1.lines().map(line -> "- " + line).collect(Collectors.joining("\n", "@@ -1,24 +1,0 @@\n", "\n")), text1, "");
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/TestPackageTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/TestPackageTest.java
index 8588bb9ea16..5bc1c386134 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/TestPackageTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/TestPackageTest.java
@@ -5,7 +5,7 @@ import com.yahoo.config.provision.NodeResources;
import com.yahoo.config.provision.zone.ZoneId;
import com.yahoo.vespa.hosted.controller.application.pkg.TestPackage.TestSummary;
import com.yahoo.vespa.hosted.controller.config.ControllerConfig;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -22,7 +22,7 @@ import static com.yahoo.vespa.hosted.controller.api.integration.deployment.Teste
import static com.yahoo.vespa.hosted.controller.api.integration.deployment.TesterCloud.Suite.system;
import static com.yahoo.vespa.hosted.controller.application.pkg.TestPackage.validateTests;
import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author jonmv
@@ -75,65 +75,65 @@ public class TestPackageTest {
}
@Test
- public void testBundleValidation() throws IOException {
+ void testBundleValidation() throws IOException {
byte[] testZip = ApplicationPackage.filesZip(Map.of("components/foo-tests.jar", testsJar("SystemTest", "StagingSetup", "ProductionTest"),
- "artifacts/key", new byte[0]));
+ "artifacts/key", new byte[0]));
TestSummary summary = validateTests(List.of(system), testZip);
assertEquals(List.of(system, staging_setup, production), summary.suites());
assertEquals(List.of("test package contains 'artifacts/key'; this conflicts with credentials used to run tests in Vespa Cloud",
- "test package has staging setup, so it should also include staging tests",
- "test package has production tests, but no production tests are declared in deployment.xml",
- "see https://docs.vespa.ai/en/testing.html for details on how to write system tests for Vespa"),
- summary.problems());
+ "test package has staging setup, so it should also include staging tests",
+ "test package has production tests, but no production tests are declared in deployment.xml",
+ "see https://docs.vespa.ai/en/testing.html for details on how to write system tests for Vespa"),
+ summary.problems());
}
@Test
- public void testFatTestsValidation() {
+ void testFatTestsValidation() {
byte[] testZip = ApplicationPackage.filesZip(Map.of("artifacts/foo-tests.jar", new byte[0]));
TestSummary summary = validateTests(List.of(staging, production), testZip);
assertEquals(List.of(staging, production), summary.suites());
assertEquals(List.of("test package has staging tests, so it should also include staging setup",
- "see https://docs.vespa.ai/en/testing.html for details on how to write system tests for Vespa"),
- summary.problems());
+ "see https://docs.vespa.ai/en/testing.html for details on how to write system tests for Vespa"),
+ summary.problems());
}
@Test
- public void testBasicTestsValidation() {
+ void testBasicTestsValidation() {
byte[] testZip = ApplicationPackage.filesZip(Map.of("tests/staging-test/foo.json", new byte[0],
- "tests/staging-setup/foo.json", new byte[0]));
+ "tests/staging-setup/foo.json", new byte[0]));
TestSummary summary = validateTests(List.of(system, production), testZip);
assertEquals(List.of(staging_setup, staging), summary.suites());
assertEquals(List.of("test package has no system tests, but <test /> is declared in deployment.xml",
- "test package has no production tests, but production tests are declared in deployment.xml",
- "see https://docs.vespa.ai/en/testing.html for details on how to write system tests for Vespa"),
- summary.problems());
+ "test package has no production tests, but production tests are declared in deployment.xml",
+ "see https://docs.vespa.ai/en/testing.html for details on how to write system tests for Vespa"),
+ summary.problems());
}
@Test
- public void generates_correct_tester_flavor() {
+ void generates_correct_tester_flavor() {
DeploymentSpec spec = DeploymentSpec.fromXml("<deployment version='1.0' athenz-domain='domain' athenz-service='service'>\n" +
- " <instance id='first'>\n" +
- " <test tester-flavor=\"d-6-16-100\" />\n" +
- " <prod>\n" +
- " <region active=\"true\">us-west-1</region>\n" +
- " <test>us-west-1</test>\n" +
- " </prod>\n" +
- " </instance>\n" +
- " <instance id='second'>\n" +
- " <test />\n" +
- " <staging />\n" +
- " <prod tester-flavor=\"d-6-16-100\">\n" +
- " <parallel>\n" +
- " <region active=\"true\">us-east-3</region>\n" +
- " <region active=\"true\">us-central-1</region>\n" +
- " </parallel>\n" +
- " <region active=\"true\">us-west-1</region>\n" +
- " <test>us-west-1</test>\n" +
- " </prod>\n" +
- " </instance>\n" +
- "</deployment>\n");
+ " <instance id='first'>\n" +
+ " <test tester-flavor=\"d-6-16-100\" />\n" +
+ " <prod>\n" +
+ " <region active=\"true\">us-west-1</region>\n" +
+ " <test>us-west-1</test>\n" +
+ " </prod>\n" +
+ " </instance>\n" +
+ " <instance id='second'>\n" +
+ " <test />\n" +
+ " <staging />\n" +
+ " <prod tester-flavor=\"d-6-16-100\">\n" +
+ " <parallel>\n" +
+ " <region active=\"true\">us-east-3</region>\n" +
+ " <region active=\"true\">us-central-1</region>\n" +
+ " </parallel>\n" +
+ " <region active=\"true\">us-west-1</region>\n" +
+ " <test>us-west-1</test>\n" +
+ " </prod>\n" +
+ " </instance>\n" +
+ "</deployment>\n");
NodeResources firstResources = TestPackage.testerResourcesFor(ZoneId.from("prod", "us-west-1"), spec.requireInstance("first"));
assertEquals(TestPackage.DEFAULT_TESTER_RESOURCES, firstResources);
@@ -145,13 +145,13 @@ public class TestPackageTest {
}
@Test
- public void generates_correct_services_xml() throws IOException {
+ void generates_correct_services_xml() throws IOException {
assertEquals(Files.readString(Paths.get("src/test/resources/test_runner_services.xml-cd")),
- new String(TestPackage.servicesXml(true,
- false,
- new NodeResources(2, 12, 75, 1, NodeResources.DiskSpeed.fast, NodeResources.StorageType.local),
- new ControllerConfig.Steprunner.Testerapp.Builder().build()),
- UTF_8));
+ new String(TestPackage.servicesXml(true,
+ false,
+ new NodeResources(2, 12, 75, 1, NodeResources.DiskSpeed.fast, NodeResources.StorageType.local),
+ new ControllerConfig.Steprunner.Testerapp.Builder().build()),
+ UTF_8));
}
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/ZipEntriesTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/ZipEntriesTest.java
index 6908464640b..37062e1002b 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/ZipEntriesTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/application/pkg/ZipEntriesTest.java
@@ -5,7 +5,7 @@ import com.yahoo.security.KeyAlgorithm;
import com.yahoo.security.KeyUtils;
import com.yahoo.security.SignatureAlgorithm;
import com.yahoo.security.X509CertificateBuilder;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.security.auth.x500.X500Principal;
import java.math.BigInteger;
@@ -16,7 +16,7 @@ import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author mpolden
@@ -24,22 +24,22 @@ import static org.junit.Assert.assertEquals;
public class ZipEntriesTest {
@Test
- public void test_replacement() {
+ void test_replacement() {
ApplicationPackage applicationPackage = new ApplicationPackage(new byte[0]);
List<X509Certificate> certificates = IntStream.range(0, 3)
- .mapToObj(i -> {
- KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256);
- X500Principal subject = new X500Principal("CN=subject" + i);
- return X509CertificateBuilder.fromKeypair(keyPair,
- subject,
- Instant.now(),
- Instant.now().plusSeconds(1),
- SignatureAlgorithm.SHA512_WITH_ECDSA,
- BigInteger.valueOf(1))
- .build();
- })
- .collect(Collectors.toUnmodifiableList());
-
+ .mapToObj(i -> {
+ KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256);
+ X500Principal subject = new X500Principal("CN=subject" + i);
+ return X509CertificateBuilder.fromKeypair(keyPair,
+ subject,
+ Instant.now(),
+ Instant.now().plusSeconds(1),
+ SignatureAlgorithm.SHA512_WITH_ECDSA,
+ BigInteger.valueOf(1))
+ .build();
+ })
+ .collect(Collectors.toUnmodifiableList());
+
assertEquals(List.of(), applicationPackage.trustedCertificates());
for (int i = 0; i < certificates.size(); i++) {
applicationPackage = applicationPackage.withTrustedCertificate(certificates.get(i));
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/archive/CuratorArchiveBucketDbTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/archive/CuratorArchiveBucketDbTest.java
index 4c3d76b1b17..081056e5184 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/archive/CuratorArchiveBucketDbTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/archive/CuratorArchiveBucketDbTest.java
@@ -7,7 +7,7 @@ import com.yahoo.config.provision.zone.ZoneId;
import com.yahoo.vespa.hosted.controller.ControllerTester;
import com.yahoo.vespa.hosted.controller.api.integration.archive.ArchiveBucket;
import org.apache.curator.shaded.com.google.common.collect.Streams;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.util.Optional;
@@ -16,12 +16,12 @@ import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class CuratorArchiveBucketDbTest {
@Test
- public void archiveUriFor() {
+ void archiveUriFor() {
ControllerTester tester = new ControllerTester(SystemName.Public);
CuratorArchiveBucketDb bucketDb = new CuratorArchiveBucketDb(tester.controller());
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/auditlog/AuditLoggerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/auditlog/AuditLoggerTest.java
index 7a209b105b3..5c5abea0276 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/auditlog/AuditLoggerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/auditlog/AuditLoggerTest.java
@@ -5,7 +5,7 @@ import com.yahoo.container.jdisc.HttpRequest;
import com.yahoo.jdisc.http.HttpRequest.Method;
import com.yahoo.vespa.hosted.controller.ControllerTester;
import com.yahoo.vespa.hosted.controller.auditlog.AuditLog.Entry;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.net.URI;
@@ -15,8 +15,8 @@ import java.time.Instant;
import java.util.function.Supplier;
import static java.time.temporal.ChronoUnit.MILLIS;
-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 mpolden
@@ -27,11 +27,11 @@ public class AuditLoggerTest {
private final Supplier<AuditLog> log = () -> tester.controller().auditLogger().readLog();
@Test
- public void test_logging() {
+ void test_logging() {
{ // GET request is ignored
HttpRequest request = testRequest(Method.GET, URI.create("http://localhost:8080/os/v1/"), "");
tester.controller().auditLogger().log(request);
- assertTrue("Not logged", log.get().entries().isEmpty());
+ assertTrue(log.get().entries().isEmpty(), "Not logged");
}
{ // PATCH request is logged in audit log
@@ -47,7 +47,7 @@ public class AuditLoggerTest {
{ // Another PATCH request is logged
tester.clock().advance(Duration.ofDays(1));
HttpRequest request = testRequest(Method.PATCH, URI.create("http://localhost:8080/os/v1/"),
- "{\"cloud\":\"cloud9\",\"version\":\"43.0\"}");
+ "{\"cloud\":\"cloud9\",\"version\":\"43.0\"}");
tester.controller().auditLogger().log(request);
assertEntry(Entry.Method.PATCH, 2, "/os/v1/");
}
@@ -55,7 +55,7 @@ public class AuditLoggerTest {
{ // PUT is logged
tester.clock().advance(Duration.ofDays(1));
HttpRequest request = testRequest(Method.PUT, URI.create("http://localhost:8080/zone/v2/prod/us-north-1/nodes/v2/state/dirty/node1/"),
- "");
+ "");
tester.controller().auditLogger().log(request);
assertEntry(Entry.Method.PUT, 3, "/zone/v2/prod/us-north-1/nodes/v2/state/dirty/node1/");
}
@@ -63,7 +63,7 @@ public class AuditLoggerTest {
{ // DELETE is logged
tester.clock().advance(Duration.ofDays(1));
HttpRequest request = testRequest(Method.DELETE, URI.create("http://localhost:8080/zone/v2/prod/us-north-1/nodes/v2/node/node1"),
- "");
+ "");
tester.controller().auditLogger().log(request);
assertEntry(Entry.Method.DELETE, 4, "/zone/v2/prod/us-north-1/nodes/v2/node/node1");
}
@@ -71,7 +71,7 @@ public class AuditLoggerTest {
{ // POST is logged
tester.clock().advance(Duration.ofDays(1));
HttpRequest request = testRequest(Method.POST, URI.create("http://localhost:8080/controller/v1/jobs/upgrader/confidence/6.42"),
- "6.42");
+ "6.42");
tester.controller().auditLogger().log(request);
assertEntry(Entry.Method.POST, 5, "/controller/v1/jobs/upgrader/confidence/6.42");
}
@@ -79,7 +79,7 @@ public class AuditLoggerTest {
{ // 15 days pass and another PATCH request is logged. Older entries are removed due to expiry
tester.clock().advance(Duration.ofDays(15));
HttpRequest request = testRequest(Method.PATCH, URI.create("http://localhost:8080/os/v1/"),
- "{\"cloud\":\"cloud9\",\"version\":\"44.0\"}");
+ "{\"cloud\":\"cloud9\",\"version\":\"44.0\"}");
tester.controller().auditLogger().log(request);
assertEntry(Entry.Method.PATCH, 1, "/os/v1/");
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/certificate/EndpointCertificatesTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/certificate/EndpointCertificatesTest.java
index 4b6d802260e..9a2d9eddba7 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/certificate/EndpointCertificatesTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/certificate/EndpointCertificatesTest.java
@@ -25,8 +25,8 @@ import com.yahoo.vespa.hosted.controller.application.pkg.ApplicationPackage;
import com.yahoo.vespa.hosted.controller.deployment.ApplicationPackageBuilder;
import com.yahoo.vespa.hosted.controller.integration.SecretStoreMock;
import com.yahoo.vespa.hosted.controller.persistence.CuratorDb;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import javax.security.auth.x500.X500Principal;
import java.security.KeyPair;
@@ -39,9 +39,9 @@ import java.util.Map;
import java.util.Optional;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author andreer
@@ -105,7 +105,7 @@ public class EndpointCertificatesTest {
private final String testCertName = "testCertName";
private ZoneId testZone;
- @Before
+ @BeforeEach
public void setUp() {
tester.zoneRegistry().exclusiveRoutingIn(tester.zoneRegistry().zones().all().zones());
testZone = tester.zoneRegistry().zones().all().routingMethod(RoutingMethod.exclusive).in(Environment.prod).zones().stream().findFirst().orElseThrow().getId();
@@ -115,7 +115,7 @@ public class EndpointCertificatesTest {
}
@Test
- public void provisions_new_certificate_in_dev() {
+ void provisions_new_certificate_in_dev() {
ZoneId testZone = tester.zoneRegistry().zones().all().routingMethod(RoutingMethod.exclusive).in(Environment.dev).zones().stream().findFirst().orElseThrow().getId();
Optional<EndpointCertificateMetadata> endpointCertificateMetadata = endpointCertificates.getMetadata(testInstance, testZone, DeploymentSpec.empty);
assertTrue(endpointCertificateMetadata.isPresent());
@@ -126,7 +126,7 @@ public class EndpointCertificatesTest {
}
@Test
- public void provisions_new_certificate_in_prod() {
+ void provisions_new_certificate_in_prod() {
Optional<EndpointCertificateMetadata> endpointCertificateMetadata = endpointCertificates.getMetadata(testInstance, testZone, DeploymentSpec.empty);
assertTrue(endpointCertificateMetadata.isPresent());
assertTrue(endpointCertificateMetadata.get().keyName().matches("vespa.tls.default.default.*-key"));
@@ -136,7 +136,7 @@ public class EndpointCertificatesTest {
}
@Test
- public void provisions_new_certificate_in_public_prod() {
+ void provisions_new_certificate_in_public_prod() {
ControllerTester tester = new ControllerTester(SystemName.Public);
EndpointCertificateValidatorImpl endpointCertificateValidator = new EndpointCertificateValidatorImpl(secretStore, clock);
EndpointCertificates endpointCertificates = new EndpointCertificates(tester.controller(), endpointCertificateMock, endpointCertificateValidator);
@@ -160,7 +160,7 @@ public class EndpointCertificatesTest {
}
@Test
- public void reuses_stored_certificate_metadata() {
+ void reuses_stored_certificate_metadata() {
mockCuratorDb.writeEndpointCertificateMetadata(testInstance.id(), new EndpointCertificateMetadata(testKeyName, testCertName, 7, 0, "request_id", Optional.of("leaf-request-uuid"),
List.of("vt2ktgkqme5zlnp4tj4ttyor7fj3v7q5o.vespa.oath.cloud",
"default.default.global.vespa.oath.cloud",
@@ -178,7 +178,7 @@ public class EndpointCertificatesTest {
}
@Test
- public void reprovisions_certificate_when_necessary() {
+ void reprovisions_certificate_when_necessary() {
mockCuratorDb.writeEndpointCertificateMetadata(testInstance.id(), new EndpointCertificateMetadata(testKeyName, testCertName, -1, 0, "root-request-uuid", Optional.of("leaf-request-uuid"), List.of(), "issuer", Optional.empty(), Optional.empty()));
secretStore.setSecret("vespa.tls.default.default.default-key", KeyUtils.toPem(testKeyPair.getPrivate()), 0);
secretStore.setSecret("vespa.tls.default.default.default-cert", X509CertificateUtils.toPem(testCertificate) + X509CertificateUtils.toPem(testCertificate), 0);
@@ -189,7 +189,7 @@ public class EndpointCertificatesTest {
}
@Test
- public void reprovisions_certificate_with_added_sans_when_deploying_to_new_zone() {
+ void reprovisions_certificate_with_added_sans_when_deploying_to_new_zone() {
ZoneId testZone = tester.zoneRegistry().zones().all().routingMethod(RoutingMethod.exclusive).in(Environment.prod).zones().stream().skip(1).findFirst().orElseThrow().getId();
mockCuratorDb.writeEndpointCertificateMetadata(testInstance.id(), new EndpointCertificateMetadata(testKeyName, testCertName, -1, 0, "original-request-uuid", Optional.of("leaf-request-uuid"), expectedSans, "mockCa", Optional.empty(), Optional.empty()));
@@ -209,7 +209,7 @@ public class EndpointCertificatesTest {
}
@Test
- public void includes_zones_in_deployment_spec_when_deploying_to_staging() {
+ void includes_zones_in_deployment_spec_when_deploying_to_staging() {
DeploymentSpec deploymentSpec = new DeploymentSpecXmlReader(true).read(
"""
<deployment version="1.0">
@@ -233,7 +233,7 @@ public class EndpointCertificatesTest {
}
@Test
- public void includes_application_endpoint_when_declared() {
+ void includes_application_endpoint_when_declared() {
Instance instance = new Instance(ApplicationId.from("t1", "a1", "default"));
ZoneId zone1 = ZoneId.from(Environment.prod, RegionName.from("aws-us-east-1c"));
ZoneId zone2 = ZoneId.from(Environment.prod, RegionName.from("aws-us-west-2a"));
@@ -242,14 +242,14 @@ public class EndpointCertificatesTest {
.region(zone1.region())
.region(zone2.region())
.applicationEndpoint("a", "qrs", zone2.region().value(),
- Map.of(InstanceName.from("beta"), 2,
- InstanceName.from("main"), 8))
+ Map.of(InstanceName.from("beta"), 2,
+ InstanceName.from("main"), 8))
.applicationEndpoint("b", "qrs", zone2.region().value(),
- Map.of(InstanceName.from("beta"), 1,
- InstanceName.from("main"), 1))
+ Map.of(InstanceName.from("beta"), 1,
+ InstanceName.from("main"), 1))
.applicationEndpoint("c", "qrs", zone1.region().value(),
- Map.of(InstanceName.from("beta"), 4,
- InstanceName.from("main"), 6))
+ Map.of(InstanceName.from("beta"), 4,
+ InstanceName.from("main"), 6))
.build();
ControllerTester tester = new ControllerTester(SystemName.Public);
EndpointCertificateValidatorImpl endpointCertificateValidator = new EndpointCertificateValidatorImpl(secretStore, clock);
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/concurrent/OnceTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/concurrent/OnceTest.java
index e9426e96a80..c1a8f77f2e9 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/concurrent/OnceTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/concurrent/OnceTest.java
@@ -1,21 +1,23 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.controller.concurrent;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
import java.time.Duration;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author mpolden
*/
public class OnceTest {
- @Test(timeout = 60_000)
- public void test_run() throws Exception {
+ @Test
+ @Timeout(60_000)
+ void test_run() throws Exception {
CountDownLatch latch = new CountDownLatch(1);
Once.after(Duration.ZERO, latch::countDown);
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentContext.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentContext.java
index ad236fcd4de..934c6b07c29 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentContext.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentContext.java
@@ -59,11 +59,11 @@ import java.util.function.Supplier;
import static com.yahoo.vespa.hosted.controller.deployment.Step.Status.failed;
import static com.yahoo.vespa.hosted.controller.deployment.Step.Status.succeeded;
import static com.yahoo.vespa.hosted.controller.deployment.Step.Status.unfinished;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* A deployment context for an application. This allows fine-grained control of the deployment of an application's
@@ -194,10 +194,10 @@ public class DeploymentContext {
/** Completely deploy the current change */
public DeploymentContext deploy() {
Application application = application();
- assertTrue("Application package submitted", application.revisions().last().isPresent());
- assertFalse("Submission is not already deployed", application.instances().values().stream()
+ assertTrue(application.revisions().last().isPresent(), "Application package submitted");
+ assertFalse(application.instances().values().stream()
.anyMatch(instance -> instance.deployments().values().stream()
- .anyMatch(deployment -> deployment.revision().equals(lastSubmission))));
+ .anyMatch(deployment -> deployment.revision().equals(lastSubmission))), "Submission is not already deployed");
completeRollout(application.deploymentSpec().instances().size() > 1);
for (var instance : application().instances().values()) {
assertFalse(instance.change().hasTargets());
@@ -249,8 +249,8 @@ public class DeploymentContext {
/** Flush all pending DNS updates */
public DeploymentContext flushDnsUpdates() {
flushDnsUpdates(Integer.MAX_VALUE);
- assertTrue("All name service requests dispatched",
- tester.controller().curator().readNameServiceQueue().requests().isEmpty());
+ assertTrue(tester.controller().curator().readNameServiceQueue().requests().isEmpty(),
+ "All name service requests dispatched");
return this;
}
@@ -362,12 +362,12 @@ public class DeploymentContext {
.filter(kv -> kv.getValue() == failed)
.map(Entry::getKey)
.findFirst();
- assertTrue("Found failing step", firstFailing.isPresent());
+ assertTrue(firstFailing.isPresent(), "Found failing step");
Optional<RunLog> details = jobs.details(id);
- assertTrue("Found log entries for run " + id, details.isPresent());
- assertTrue("Found log message containing '" + messagePart.get() + "'",
- details.get().get(firstFailing.get()).stream()
- .anyMatch(entry -> entry.message().contains(messagePart.get())));
+ assertTrue(details.isPresent(), "Found log entries for run " + id);
+ assertTrue(details.get().get(firstFailing.get()).stream()
+ .anyMatch(entry -> entry.message().contains(messagePart.get())),
+ "Found log message containing '" + messagePart.get() + "'");
}
return this;
}
@@ -400,7 +400,7 @@ public class DeploymentContext {
triggerJobs();
}
- assertFalse("Change should have no targets, but was " + instance().change(), instance().change().hasTargets());
+ assertFalse(instance().change().hasTargets(), "Change should have no targets, but was " + instance().change());
return this;
}
@@ -545,13 +545,13 @@ public class DeploymentContext {
}
public void assertRunning(JobType type) {
- assertTrue(jobId(type) + " should be among the active: " + jobs.active(),
- jobs.active().stream().anyMatch(run -> run.id().application().equals(instanceId) && run.id().type().equals(type)));
+ assertTrue(jobs.active().stream().anyMatch(run -> run.id().application().equals(instanceId) && run.id().type().equals(type)),
+ jobId(type) + " should be among the active: " + jobs.active());
}
public void assertNotRunning(JobType type) {
- assertFalse(jobId(type) + " should not be among the active: " + jobs.active(),
- jobs.active().stream().anyMatch(run -> run.id().application().equals(instanceId) && run.id().type().equals(type)));
+ assertFalse(jobs.active().stream().anyMatch(run -> run.id().application().equals(instanceId) && run.id().type().equals(type)),
+ jobId(type) + " should not be among the active: " + jobs.active());
}
/** Deploys tester and real app, and completes tester and initial staging installation first if needed. */
@@ -604,8 +604,8 @@ public class DeploymentContext {
Run run = jobs.last(job)
.filter(r -> r.id().type().equals(job.type()))
.orElseThrow(() -> new AssertionError(job.type() + " is not among the active: " + jobs.active()));
- assertFalse(run.id() + " should not have failed yet: " + run, run.hasFailed());
- assertFalse(run.id() + " should not have ended yet: " + run, run.hasEnded());
+ assertFalse(run.hasFailed(), run.id() + " should not have failed yet: " + run);
+ assertFalse(run.hasEnded(), run.id() + " should not have ended yet: " + run);
return run;
}
@@ -622,7 +622,7 @@ public class DeploymentContext {
assertTrue(jobs.run(id).hasEnded());
return;
}
- assertEquals("Status of " + id, succeeded, jobs.run(id).stepStatuses().get(Step.installReal));
+ assertEquals(succeeded, jobs.run(id).stepStatuses().get(Step.installReal), "Status of " + id);
}
/** Installs tester and starts tests. */
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentTester.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentTester.java
index 2b4a2baa17e..c9553ef5bf1 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentTester.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentTester.java
@@ -27,7 +27,7 @@ import java.time.temporal.TemporalAdjusters;
import java.util.logging.Level;
import java.util.logging.Logger;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author jonmv
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentTriggerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentTriggerTest.java
index 08fc6df37fb..62fafa12993 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentTriggerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentTriggerTest.java
@@ -24,8 +24,7 @@ import com.yahoo.vespa.hosted.controller.application.pkg.ApplicationPackage;
import com.yahoo.vespa.hosted.controller.integration.ZoneApiMock;
import com.yahoo.vespa.hosted.controller.integration.ZoneRegistryMock;
import com.yahoo.vespa.hosted.controller.versions.VespaVersion;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
@@ -61,11 +60,11 @@ import static com.yahoo.vespa.hosted.controller.deployment.DeploymentContext.tes
import static com.yahoo.vespa.hosted.controller.deployment.DeploymentTrigger.ChangesToCancel.ALL;
import static com.yahoo.vespa.hosted.controller.deployment.DeploymentTrigger.ChangesToCancel.PLATFORM;
import static java.util.Collections.emptyList;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertThrows;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Tests a wide variety of deployment scenarios and configurations
@@ -79,7 +78,7 @@ public class DeploymentTriggerTest {
private final DeploymentTester tester = new DeploymentTester();
@Test
- public void testTriggerFailing() {
+ void testTriggerFailing() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
.region("us-west-1")
@@ -96,7 +95,7 @@ public class DeploymentTriggerTest {
// staging-test fails deployment and is retried
app.failDeployment(stagingTest);
tester.triggerJobs();
- assertEquals("Retried dead job", 2, tester.jobs().active().size());
+ assertEquals(2, tester.jobs().active().size(), "Retried dead job");
app.assertRunning(stagingTest);
app.runJob(stagingTest);
@@ -107,7 +106,7 @@ public class DeploymentTriggerTest {
// system-test fails and is retried
app.timeOutUpgrade(systemTest);
tester.triggerJobs();
- assertEquals("Job is retried on failure", 1, tester.jobs().active().size());
+ assertEquals(1, tester.jobs().active().size(), "Job is retried on failure");
app.runJob(systemTest);
tester.triggerJobs();
@@ -118,11 +117,11 @@ public class DeploymentTriggerTest {
tester.applications().store(locked.withProjectId(OptionalLong.empty())));
app.timeOutConvergence(productionUsWest1);
tester.triggerJobs();
- assertEquals("Job is not triggered when no projectId is present", 0, tester.jobs().active().size());
+ assertEquals(0, tester.jobs().active().size(), "Job is not triggered when no projectId is present");
}
@Test
- public void revisionChangeWhenFailingMakesApplicationChangeWaitForPreviousToComplete() {
+ void revisionChangeWhenFailingMakesApplicationChangeWaitForPreviousToComplete() {
DeploymentContext app = tester.newDeploymentContext();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.revisionChange(null) // separate by default, but we override this in test builder
@@ -156,10 +155,10 @@ public class DeploymentTriggerTest {
}
@Test
- public void leadingUpgradeAllowsApplicationChangeWhileUpgrading() {
+ void leadingUpgradeAllowsApplicationChangeWhileUpgrading() {
var applicationPackage = new ApplicationPackageBuilder().region("us-east-3")
- .upgradeRollout("leading")
- .build();
+ .upgradeRollout("leading")
+ .build();
var app = tester.newDeploymentContext();
app.submit(applicationPackage).deploy();
@@ -177,11 +176,11 @@ public class DeploymentTriggerTest {
}
@Test
- public void abortsJobsOnNewApplicationChange() {
+ void abortsJobsOnNewApplicationChange() {
var app = tester.newDeploymentContext();
app.submit()
- .runJob(systemTest)
- .runJob(stagingTest);
+ .runJob(systemTest)
+ .runJob(stagingTest);
tester.triggerJobs();
RunId id = tester.jobs().last(app.instanceId(), productionUsCentral1).get().id();
@@ -221,12 +220,12 @@ public class DeploymentTriggerTest {
tester.triggerJobs();
tester.runner().run();
assertEquals(Set.of(productionUsCentral1), tester.jobs().active().stream()
- .map(run -> run.id().type())
- .collect(Collectors.toCollection(HashSet::new)));
+ .map(run -> run.id().type())
+ .collect(Collectors.toCollection(HashSet::new)));
}
@Test
- public void similarDeploymentSpecsAreNotRolledOut() {
+ void similarDeploymentSpecsAreNotRolledOut() {
ApplicationPackage firstPackage = new ApplicationPackageBuilder()
.region("us-east-3")
.build();
@@ -235,8 +234,8 @@ public class DeploymentTriggerTest {
var version = app.lastSubmission();
assertEquals(version, app.instance().change().revision());
app.runJob(systemTest)
- .runJob(stagingTest)
- .runJob(productionUsEast3);
+ .runJob(stagingTest)
+ .runJob(productionUsEast3);
assertEquals(Change.empty(), app.instance().change());
// A similar application package is submitted. Since a new job is added, the original revision is again a target.
@@ -266,13 +265,13 @@ public class DeploymentTriggerTest {
}
@Test
- public void testOutstandingChangeWithNextRevisionTarget() {
+ void testOutstandingChangeWithNextRevisionTarget() {
ApplicationPackage appPackage = new ApplicationPackageBuilder().revisionTarget("next")
- .revisionChange("when-failing")
- .region("us-east-3")
- .build();
+ .revisionChange("when-failing")
+ .region("us-east-3")
+ .build();
DeploymentContext app = tester.newDeploymentContext()
- .submit(appPackage);
+ .submit(appPackage);
Optional<RevisionId> revision1 = app.lastSubmission();
app.submit(appPackage);
@@ -300,7 +299,7 @@ public class DeploymentTriggerTest {
// The second revision deploys completely, and the third starts rolling out.
app.runJob(systemTest).runJob(stagingTest)
- .runJob(productionUsEast3);
+ .runJob(productionUsEast3);
tester.outstandingChangeDeployer().run();
tester.outstandingChangeDeployer().run();
assertEquals(revision3, app.instance().change().revision());
@@ -315,8 +314,8 @@ public class DeploymentTriggerTest {
// Tests for outstanding change are relevant when current revision completes.
app.runJob(systemTest).runJob(systemTest)
- .jobAborted(stagingTest).runJob(stagingTest).runJob(stagingTest)
- .runJob(productionUsEast3);
+ .jobAborted(stagingTest).runJob(stagingTest).runJob(stagingTest)
+ .runJob(productionUsEast3);
tester.outstandingChangeDeployer().run();
tester.outstandingChangeDeployer().run();
assertEquals(revision5, app.instance().change().revision());
@@ -325,7 +324,7 @@ public class DeploymentTriggerTest {
}
@Test
- public void deploymentSpecWithDelays() {
+ void deploymentSpecWithDelays() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.systemTest()
.delay(Duration.ofSeconds(30))
@@ -363,27 +362,27 @@ public class DeploymentTriggerTest {
// Delayed trigger does nothing as not enough time has passed after us-west-1 completion
tester.triggerJobs();
- assertTrue("No more jobs triggered at this time", tester.jobs().active().isEmpty());
+ assertTrue(tester.jobs().active().isEmpty(), "No more jobs triggered at this time");
// 3 minutes pass, us-central-1 is still not triggered
tester.clock().advance(Duration.ofMinutes(3));
tester.triggerJobs();
- assertTrue("No more jobs triggered at this time", tester.jobs().active().isEmpty());
+ assertTrue(tester.jobs().active().isEmpty(), "No more jobs triggered at this time");
// 4 minutes pass, us-central-1 is triggered
tester.clock().advance(Duration.ofMinutes(1));
tester.triggerJobs();
app.runJob(productionUsCentral1);
- assertTrue("All jobs consumed", tester.jobs().active().isEmpty());
+ assertTrue(tester.jobs().active().isEmpty(), "All jobs consumed");
// Delayed trigger job runs again, with nothing to trigger
tester.clock().advance(Duration.ofMinutes(10));
tester.triggerJobs();
- assertTrue("All jobs consumed", tester.jobs().active().isEmpty());
+ assertTrue(tester.jobs().active().isEmpty(), "All jobs consumed");
}
@Test
- public void deploymentSpecWithParallelDeployments() {
+ void deploymentSpecWithParallelDeployments() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.region("us-central-1")
.parallel("us-west-1", "us-east-3")
@@ -416,11 +415,11 @@ public class DeploymentTriggerTest {
tester.triggerJobs();
assertEquals(1, tester.jobs().active().size());
app.runJob(productionEuWest1);
- assertTrue("All jobs consumed", tester.jobs().active().isEmpty());
+ assertTrue(tester.jobs().active().isEmpty(), "All jobs consumed");
}
@Test
- public void testNoOtherChangesDuringSuspension() {
+ void testNoOtherChangesDuringSuspension() {
// Application is deployed in 3 regions:
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.region("us-central-1")
@@ -433,9 +432,9 @@ public class DeploymentTriggerTest {
// A new change needs to be pushed out, but should not go beyond the suspended zone:
application.submit()
- .runJob(systemTest)
- .runJob(stagingTest)
- .runJob(productionUsCentral1);
+ .runJob(systemTest)
+ .runJob(stagingTest)
+ .runJob(productionUsCentral1);
tester.triggerJobs();
application.assertNotRunning(productionUsEast3);
application.assertNotRunning(productionUsWest1);
@@ -448,7 +447,7 @@ public class DeploymentTriggerTest {
}
@Test
- public void testBlockRevisionChange() {
+ void testBlockRevisionChange() {
// Tuesday, 17:30
tester.at(Instant.parse("2017-09-26T17:30:00.00Z"));
@@ -491,7 +490,7 @@ public class DeploymentTriggerTest {
}
@Test
- public void testCompletionOfPartOfChangeDuringBlockWindow() {
+ void testCompletionOfPartOfChangeDuringBlockWindow() {
// Tuesday, 17:30
tester.at(Instant.parse("2017-09-26T17:30:00.00Z"));
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
@@ -539,7 +538,7 @@ public class DeploymentTriggerTest {
}
@Test
- public void testJobPause() {
+ void testJobPause() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.region("us-west-1")
.region("us-east-3")
@@ -549,9 +548,9 @@ public class DeploymentTriggerTest {
tester.upgrader().maintain();
tester.deploymentTrigger().pauseJob(app.instanceId(), productionUsWest1,
- tester.clock().instant().plus(Duration.ofSeconds(1)));
+ tester.clock().instant().plus(Duration.ofSeconds(1)));
tester.deploymentTrigger().pauseJob(app.instanceId(), productionUsEast3,
- tester.clock().instant().plus(Duration.ofSeconds(3)));
+ tester.clock().instant().plus(Duration.ofSeconds(3)));
// us-west-1 does not trigger when paused.
app.runJob(systemTest).runJob(stagingTest);
@@ -578,11 +577,11 @@ public class DeploymentTriggerTest {
app.assertRunning(productionUsEast3);
assertFalse(app.instance().jobPause(productionUsEast3).isPresent());
assertEquals(app.deployment(productionUsEast3.zone()).version(),
- tester.jobs().last(app.instanceId(), productionUsEast3).get().versions().targetPlatform());
+ tester.jobs().last(app.instanceId(), productionUsEast3).get().versions().targetPlatform());
}
@Test
- public void applicationVersionIsNotDowngraded() {
+ void applicationVersionIsNotDowngraded() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.region("us-central-1")
.region("eu-west-1")
@@ -591,9 +590,9 @@ public class DeploymentTriggerTest {
// productionUsCentral1 fails after deployment, causing a mismatch between deployed and successful state.
app.submit(applicationPackage)
- .runJob(systemTest)
- .runJob(stagingTest)
- .timeOutUpgrade(productionUsCentral1);
+ .runJob(systemTest)
+ .runJob(stagingTest)
+ .timeOutUpgrade(productionUsCentral1);
RevisionId appVersion1 = app.lastSubmission().get();
assertEquals(appVersion1, app.deployment(ZoneId.from("prod.us-central-1")).revision());
@@ -629,7 +628,7 @@ public class DeploymentTriggerTest {
}
@Test
- public void downgradingApplicationVersionWorks() {
+ void downgradingApplicationVersionWorks() {
var app = tester.newDeploymentContext().submit().deploy();
RevisionId appVersion0 = app.lastSubmission().get();
assertEquals(appVersion0, latestDeployed(app.instance()));
@@ -642,16 +641,16 @@ public class DeploymentTriggerTest {
tester.deploymentTrigger().forceChange(app.instanceId(), Change.of(appVersion0));
assertEquals(Change.of(appVersion0), app.instance().change());
app.runJob(stagingTest)
- .runJob(productionUsCentral1)
- .runJob(productionUsEast3)
- .runJob(productionUsWest1);
+ .runJob(productionUsCentral1)
+ .runJob(productionUsEast3)
+ .runJob(productionUsWest1);
assertEquals(Change.empty(), app.instance().change());
assertEquals(appVersion0, app.instance().deployments().get(productionUsEast3.zone()).revision());
assertEquals(appVersion0, latestDeployed(app.instance()));
}
@Test
- public void settingANoOpChangeIsANoOp() {
+ void settingANoOpChangeIsANoOp() {
var app = tester.newDeploymentContext().submit();
app.deploy();
@@ -670,7 +669,7 @@ public class DeploymentTriggerTest {
}
@Test
- public void stepIsCompletePreciselyWhenItShouldBe() {
+ void stepIsCompletePreciselyWhenItShouldBe() {
var app1 = tester.newDeploymentContext("tenant1", "app1", "default");
var app2 = tester.newDeploymentContext("tenant1", "app2", "default");
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
@@ -707,11 +706,11 @@ public class DeploymentTriggerTest {
tester.upgrader().overrideConfidence(version2, VespaVersion.Confidence.broken);
tester.controllerTester().computeVersionStatus();
tester.upgrader().maintain(); // Cancel upgrades to broken version
- assertEquals("Change becomes latest non-broken version", Change.of(version1), app1.instance().change());
+ assertEquals(Change.of(version1), app1.instance().change(), "Change becomes latest non-broken version");
// version1 proceeds 'til the last job, where it fails; us-central-1 is skipped, as current change is strictly dominated by what's deployed there.
app1.runJob(systemTest).runJob(stagingTest)
- .failDeployment(productionEuWest1);
+ .failDeployment(productionEuWest1);
assertEquals(triggered, app1.instanceJobs().get(productionUsCentral1).lastTriggered().get().start());
// Roll out a new application version, which gives a dual change -- this should trigger us-central-1, but only as long as it hasn't yet deployed there.
@@ -719,9 +718,9 @@ public class DeploymentTriggerTest {
app1.submit(applicationPackage);
RevisionId revision2 = app1.lastSubmission().get();
app1.runJob(systemTest) // Tests for new revision on version2
- .runJob(stagingTest)
- .runJob(systemTest) // Tests for new revision on version1
- .runJob(stagingTest);
+ .runJob(stagingTest)
+ .runJob(systemTest) // Tests for new revision on version1
+ .runJob(stagingTest);
assertEquals(Change.of(version1).with(revision2), app1.instance().change());
tester.triggerJobs();
app1.assertRunning(productionUsCentral1);
@@ -742,14 +741,14 @@ public class DeploymentTriggerTest {
// Last job has a different deployment target, so tests need to run again.
app1.runJob(productionEuWest1) // Upgrade completes, and revision is the only change.
- .runJob(productionUsCentral1) // With only revision change, central should run to cover a previous failure.
- .runJob(productionEuWest1); // Finally, west changes revision.
+ .runJob(productionUsCentral1) // With only revision change, central should run to cover a previous failure.
+ .runJob(productionEuWest1); // Finally, west changes revision.
assertEquals(Change.empty(), app1.instance().change());
assertEquals(Optional.of(RunStatus.success), app1.instanceJobs().get(productionUsCentral1).lastStatus());
}
@Test
- public void eachParallelDeployTargetIsTested() {
+ void eachParallelDeployTargetIsTested() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.parallel("eu-west-1", "us-east-3")
.build();
@@ -789,14 +788,14 @@ public class DeploymentTriggerTest {
// Both jobs fail again, and must be re-triggered -- this is ok, as they are both already triggered on their current targets.
app.failDeployment(productionEuWest1).failDeployment(productionUsEast3)
- .runJob(productionEuWest1).runJob(productionUsEast3);
+ .runJob(productionEuWest1).runJob(productionUsEast3);
assertFalse(app.instance().change().hasTargets());
assertEquals(2, app.instanceJobs().get(productionEuWest1).lastSuccess().get().versions().targetRevision().number());
assertEquals(2, app.instanceJobs().get(productionUsEast3).lastSuccess().get().versions().targetRevision().number());
}
@Test
- public void retriesFailingJobs() {
+ void retriesFailingJobs() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.region("us-central-1")
.build();
@@ -841,11 +840,11 @@ public class DeploymentTriggerTest {
// Another application change is deployed and fixes system-test. Change is triggered immediately as target changes
app.submit(applicationPackage).deploy();
- assertTrue("Deployment completed", tester.jobs().active().isEmpty());
+ assertTrue(tester.jobs().active().isEmpty(), "Deployment completed");
}
@Test
- public void testPlatformVersionSelection() {
+ void testPlatformVersionSelection() {
// Setup system
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.region("us-west-1")
@@ -856,7 +855,7 @@ public class DeploymentTriggerTest {
// First deployment: An application change
app1.submit(applicationPackage).deploy();
- assertEquals("First deployment gets system version", version1, app1.application().oldestDeployedPlatform().get());
+ assertEquals(version1, app1.application().oldestDeployedPlatform().get(), "First deployment gets system version");
assertEquals(version1, tester.configServer().lastPrepareVersion().get());
// Application change after a new system version, and a region added
@@ -868,20 +867,19 @@ public class DeploymentTriggerTest {
.region("us-east-3")
.build();
app1.submit(applicationPackage).deploy();
- assertEquals("Application change preserves version, and new region gets oldest version too",
- version1, app1.application().oldestDeployedPlatform().get());
+ assertEquals(version1, app1.application().oldestDeployedPlatform().get(), "Application change preserves version, and new region gets oldest version too");
assertEquals(version1, tester.configServer().lastPrepareVersion().get());
- assertFalse("Change deployed", app1.instance().change().hasTargets());
+ assertFalse(app1.instance().change().hasTargets(), "Change deployed");
tester.upgrader().maintain();
app1.deployPlatform(version2);
- assertEquals("Version upgrade changes version", version2, app1.application().oldestDeployedPlatform().get());
+ assertEquals(version2, app1.application().oldestDeployedPlatform().get(), "Version upgrade changes version");
assertEquals(version2, tester.configServer().lastPrepareVersion().get());
}
@Test
- public void requeueNodeAllocationFailureStagingJob() {
+ void requeueNodeAllocationFailureStagingJob() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.region("us-east-3")
.build();
@@ -980,14 +978,14 @@ public class DeploymentTriggerTest {
}
@Test
- public void testUserInstancesNotInDeploymentSpec() {
+ void testUserInstancesNotInDeploymentSpec() {
var app = tester.newDeploymentContext();
tester.controller().applications().createInstance(app.application().id().instance("user"));
app.submit().deploy();
}
@Test
- public void testMultipleInstancesWithDifferentChanges() {
+ void testMultipleInstancesWithDifferentChanges() {
DeploymentContext i1 = tester.newDeploymentContext("t", "a", "i1");
DeploymentContext i2 = tester.newDeploymentContext("t", "a", "i2");
DeploymentContext i3 = tester.newDeploymentContext("t", "a", "i3");
@@ -1098,7 +1096,7 @@ public class DeploymentTriggerTest {
}
@Test
- public void testMultipleInstancesWithRevisionCatchingUpToUpgrade() {
+ void testMultipleInstancesWithRevisionCatchingUpToUpgrade() {
String spec = """
<deployment>
<instance id='alpha'>
@@ -1161,28 +1159,28 @@ public class DeploymentTriggerTest {
beta.assertNotRunning(testUsEast3);
beta.runJob(productionUsEast3)
- .runJob(testUsEast3);
+ .runJob(testUsEast3);
assertEquals(Change.empty(), beta.instance().change());
}
@Test
- public void testMultipleInstances() {
+ void testMultipleInstances() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1,instance2")
.region("us-east-3")
.build();
var app = tester.newDeploymentContext("tenant1", "application1", "instance1")
- .submit(applicationPackage)
- .completeRollout();
+ .submit(applicationPackage)
+ .completeRollout();
assertEquals(2, app.application().instances().size());
assertEquals(2, app.application().productionDeployments().values().stream()
- .mapToInt(Collection::size)
- .sum());
+ .mapToInt(Collection::size)
+ .sum());
}
@Test
- public void testDeclaredProductionTests() {
+ void testDeclaredProductionTests() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.region("us-east-3")
.delay(Duration.ofMinutes(1))
@@ -1199,8 +1197,8 @@ public class DeploymentTriggerTest {
tester.clock().advance(Duration.ofMinutes(1));
app.runJob(testUsEast3)
- .runJob(productionUsWest1).runJob(productionUsCentral1)
- .runJob(testUsCentral1).runJob(testUsWest1);
+ .runJob(productionUsWest1).runJob(productionUsCentral1)
+ .runJob(testUsCentral1).runJob(testUsWest1);
assertEquals(Change.empty(), app.instance().change());
// Application starts upgrade, but is confidence is broken cancelled after first zone. Tests won't run.
@@ -1250,7 +1248,7 @@ public class DeploymentTriggerTest {
}
@Test
- public void testDeployComplicatedDeploymentSpec() {
+ void testDeployComplicatedDeploymentSpec() {
String complicatedDeploymentSpec =
"""
<deployment version='1.0' athenz-domain='domain' athenz-service='service'>
@@ -1400,14 +1398,14 @@ public class DeploymentTriggerTest {
// Upgrade platform.
app2.runJob(systemTest);
app1.runJob(stagingTest)
- .runJob(productionUsWest1)
- .runJob(productionUsEast3);
+ .runJob(productionUsWest1)
+ .runJob(productionUsEast3);
// Upgrade revision
tester.clock().advance(Duration.ofSeconds(1)); // Ensure we see revision as rolling after upgrade.
app2.runJob(systemTest); // R
app1.runJob(stagingTest) // R
- .runJob(productionUsWest1); // R
- // productionUsEast3 won't change revision before its production test has completed for the upgrade, which is one of the last jobs!
+ .runJob(productionUsWest1); // R
+ // productionUsEast3 won't change revision before its production test has completed for the upgrade, which is one of the last jobs!
tester.clock().advance(Duration.ofHours(2));
app1.runJob(productionEuWest1);
tester.clock().advance(Duration.ofHours(1));
@@ -1443,13 +1441,13 @@ public class DeploymentTriggerTest {
tester.upgrader().maintain();
tester.outstandingChangeDeployer().run();
tester.triggerJobs();
- assertEquals(tester.jobs().active().toString(), 1, tester.jobs().active().size());
+ assertEquals(1, tester.jobs().active().size(), tester.jobs().active().toString());
assertEquals(Change.empty(), app1.instance().change());
assertEquals(Change.of(version), app2.instance().change());
assertEquals(Change.empty(), app3.instance().change());
app2.runJob(productionEuWest1)
- .failDeployment(testEuWest1);
+ .failDeployment(testEuWest1);
// Instance 2 failed the last job, and now exits block window, letting application change roll out with the upgrade.
tester.clock().advance(Duration.ofDays(1)); // Leave block window for revisions.
@@ -1462,7 +1460,7 @@ public class DeploymentTriggerTest {
assertEquals(Change.of(version).with(app1.application().revisions().last().get().id()), app2.instance().change());
app2.runJob(productionEuWest1)
- .runJob(testEuWest1);
+ .runJob(testEuWest1);
assertEquals(Change.empty(), app2.instance().change());
assertEquals(Change.empty(), app3.instance().change());
@@ -1486,12 +1484,12 @@ public class DeploymentTriggerTest {
}
@Test
- public void testRevisionJoinsUpgradeWithSeparateRollout() {
+ void testRevisionJoinsUpgradeWithSeparateRollout() {
var appPackage = new ApplicationPackageBuilder().region("us-central-1")
- .region("us-east-3")
- .region("us-west-1")
- .upgradeRollout("separate")
- .build();
+ .region("us-east-3")
+ .region("us-west-1")
+ .upgradeRollout("separate")
+ .build();
var app = tester.newDeploymentContext().submit(appPackage).deploy();
// Platform rolls through first production zone.
@@ -1512,20 +1510,20 @@ public class DeploymentTriggerTest {
// Upgrade got here first, so attempts to proceed alone, but the upgrade fails.
app.triggerJobs();
assertEquals(new Versions(version1, revision0.get(), Optional.of(version0), revision0),
- tester.jobs().last(app.instanceId(), productionUsEast3).get().versions());
+ tester.jobs().last(app.instanceId(), productionUsEast3).get().versions());
app.timeOutConvergence(productionUsEast3);
// Revision is allowed to join.
app.triggerJobs();
assertEquals(new Versions(version1, revision1.get(), Optional.of(version1), revision0),
- tester.jobs().last(app.instanceId(), productionUsEast3).get().versions());
+ tester.jobs().last(app.instanceId(), productionUsEast3).get().versions());
app.runJob(productionUsEast3);
// Platform and revision now proceed together.
app.runJob(stagingTest);
app.triggerJobs();
assertEquals(new Versions(version1, revision1.get(), Optional.of(version0), revision0),
- tester.jobs().last(app.instanceId(), productionUsWest1).get().versions());
+ tester.jobs().last(app.instanceId(), productionUsWest1).get().versions());
app.runJob(productionUsWest1);
assertEquals(Change.empty(), app.instance().change());
@@ -1539,23 +1537,23 @@ public class DeploymentTriggerTest {
app.submit(appPackage);
app.runJob(systemTest).runJob(stagingTest) // Tests run with combined upgrade.
- .runJob(productionUsCentral1) // Combined upgrade stays together.
- .runJob(productionUsEast3).runJob(productionUsWest1);
+ .runJob(productionUsCentral1) // Combined upgrade stays together.
+ .runJob(productionUsEast3).runJob(productionUsWest1);
assertEquals(Map.of(), app.deploymentStatus().jobsToRun());
assertEquals(Change.empty(), app.instance().change());
}
@Test
- public void testProductionTestBlockingDeploymentWithSeparateRollout() {
+ void testProductionTestBlockingDeploymentWithSeparateRollout() {
var appPackage = new ApplicationPackageBuilder().region("us-east-3")
- .region("us-west-1")
- .delay(Duration.ofHours(1))
- .test("us-east-3")
- .upgradeRollout("separate")
- .build();
+ .region("us-west-1")
+ .delay(Duration.ofHours(1))
+ .test("us-east-3")
+ .upgradeRollout("separate")
+ .build();
var app = tester.newDeploymentContext().submit(appPackage)
- .runJob(systemTest).runJob(stagingTest)
- .runJob(productionUsEast3).runJob(productionUsWest1);
+ .runJob(systemTest).runJob(stagingTest)
+ .runJob(productionUsEast3).runJob(productionUsWest1);
tester.clock().advance(Duration.ofHours(1));
app.runJob(testUsEast3);
assertEquals(Change.empty(), app.instance().change());
@@ -1579,13 +1577,13 @@ public class DeploymentTriggerTest {
// Upgrade got here first, so attempts to proceed alone, but the upgrade fails.
app.triggerJobs();
assertEquals(new Versions(version1, revision0.get(), Optional.of(version0), revision0),
- tester.jobs().last(app.instanceId(), productionUsWest1).get().versions());
+ tester.jobs().last(app.instanceId(), productionUsWest1).get().versions());
app.timeOutConvergence(productionUsWest1).triggerJobs();
// Upgrade now fails between us-east-3 deployment and test, so test is abandoned, and revision unblocked.
app.assertRunning(productionUsEast3);
assertEquals(new Versions(version1, revision1.get(), Optional.of(version1), revision0),
- tester.jobs().last(app.instanceId(), productionUsEast3).get().versions());
+ tester.jobs().last(app.instanceId(), productionUsEast3).get().versions());
app.runJob(productionUsEast3).triggerJobs()
.jobAborted(productionUsWest1).runJob(productionUsWest1);
tester.clock().advance(Duration.ofHours(1));
@@ -1594,15 +1592,15 @@ public class DeploymentTriggerTest {
}
@Test
- public void testProductionTestNotBlockingDeploymentWithSimultaneousRollout() {
+ void testProductionTestNotBlockingDeploymentWithSimultaneousRollout() {
var appPackage = new ApplicationPackageBuilder().region("us-east-3")
- .region("us-central-1")
- .region("us-west-1")
- .delay(Duration.ofHours(1))
- .test("us-east-3")
- .test("us-west-1")
- .upgradeRollout("simultaneous")
- .build();
+ .region("us-central-1")
+ .region("us-west-1")
+ .delay(Duration.ofHours(1))
+ .test("us-east-3")
+ .test("us-west-1")
+ .upgradeRollout("simultaneous")
+ .build();
var app = tester.newDeploymentContext().submit(appPackage)
.runJob(systemTest).runJob(stagingTest)
.runJob(productionUsEast3).runJob(productionUsCentral1).runJob(productionUsWest1);
@@ -1629,7 +1627,7 @@ public class DeploymentTriggerTest {
// Revision deploys to first prod zone.
app.triggerJobs();
assertEquals(new Versions(version1, revision1.get(), Optional.of(version1), revision0),
- tester.jobs().last(app.instanceId(), productionUsEast3).get().versions());
+ tester.jobs().last(app.instanceId(), productionUsEast3).get().versions());
tester.clock().advance(Duration.ofSeconds(1));
app.runJob(productionUsEast3);
@@ -1637,12 +1635,12 @@ public class DeploymentTriggerTest {
app.runJob(systemTest).runJob(stagingTest).runJob(stagingTest).triggerJobs();
app.jobAborted(productionUsCentral1).triggerJobs();
assertEquals(new Versions(version1, revision1.get(), Optional.of(version0), revision0),
- tester.jobs().last(app.instanceId(), productionUsCentral1).get().versions());
+ tester.jobs().last(app.instanceId(), productionUsCentral1).get().versions());
app.runJob(productionUsCentral1).triggerJobs();
// Revision proceeds alone in third prod zone, making test targets different for the two prod tests.
assertEquals(new Versions(version0, revision1.get(), Optional.of(version0), revision0),
- tester.jobs().last(app.instanceId(), productionUsWest1).get().versions());
+ tester.jobs().last(app.instanceId(), productionUsWest1).get().versions());
app.runJob(productionUsWest1);
app.triggerJobs();
app.assertNotRunning(testUsEast3);
@@ -1656,7 +1654,7 @@ public class DeploymentTriggerTest {
}
@Test
- public void testVeryLengthyPipelineRevisions() {
+ void testVeryLengthyPipelineRevisions() {
String lengthyDeploymentSpec =
"""
<deployment version='1.0'>
@@ -1697,7 +1695,7 @@ public class DeploymentTriggerTest {
var revision2 = alpha.lastSubmission();
alpha.runJob(systemTest).runJob(stagingTest)
- .runJob(productionUsEast3).runJob(testUsEast3);
+ .runJob(productionUsEast3).runJob(testUsEast3);
assertEquals(Optional.empty(), alpha.instance().change().revision());
// revision3 is submitted when revision2 is half-way.
@@ -1716,7 +1714,7 @@ public class DeploymentTriggerTest {
// revision3 rolls to beta, then a couple of new revisions are submitted to alpha, and the latter is the new target.
alpha.runJob(systemTest).runJob(stagingTest)
- .runJob(productionUsEast3).runJob(testUsEast3);
+ .runJob(productionUsEast3).runJob(testUsEast3);
tester.outstandingChangeDeployer().run();
assertEquals(Optional.empty(), alpha.instance().change().revision());
assertEquals(revision3, beta.instance().change().revision());
@@ -1725,11 +1723,11 @@ public class DeploymentTriggerTest {
alpha.submit(appPackage, 3);
var revision4 = alpha.lastSubmission();
alpha.runJob(systemTest).runJob(stagingTest)
- .runJob(productionUsEast3);
+ .runJob(productionUsEast3);
alpha.submit(appPackage, 2);
var revision5 = alpha.lastSubmission();
alpha.runJob(systemTest).runJob(stagingTest)
- .runJob(productionUsEast3).runJob(testUsEast3);
+ .runJob(productionUsEast3).runJob(testUsEast3);
tester.outstandingChangeDeployer().run();
assertEquals(Optional.empty(), alpha.instance().change().revision());
assertEquals(revision3, beta.instance().change().revision());
@@ -1738,8 +1736,8 @@ public class DeploymentTriggerTest {
alpha.submit(appPackage, 6);
var revision6 = alpha.lastSubmission();
alpha.runJob(systemTest).runJob(stagingTest)
- .runJob(productionUsEast3)
- .runJob(testUsEast3);
+ .runJob(productionUsEast3)
+ .runJob(testUsEast3);
beta.runJob(productionUsEast3).runJob(testUsEast3);
tester.outstandingChangeDeployer().run();
assertEquals(Optional.empty(), alpha.instance().change().revision());
@@ -1752,7 +1750,7 @@ public class DeploymentTriggerTest {
// revision 2 completes in gamma
gamma.runJob(productionUsEast3)
- .runJob(testUsEast3);
+ .runJob(testUsEast3);
tester.outstandingChangeDeployer().run();
assertEquals(Optional.empty(), alpha.instance().change().revision());
assertEquals(Optional.empty(), gamma.instance().change().revision()); // no other revisions after 3 are ready, so gamma waits
@@ -1770,7 +1768,7 @@ public class DeploymentTriggerTest {
// revision 6 is next, once 3 is done
// revision 3 completes
gamma.runJob(productionUsEast3)
- .runJob(testUsEast3);
+ .runJob(testUsEast3);
tester.outstandingChangeDeployer().run();
assertEquals(revision6, gamma.instance().change().revision());
@@ -1801,7 +1799,7 @@ public class DeploymentTriggerTest {
}
@Test
- public void testVeryLengthyPipelineUpgrade() {
+ void testVeryLengthyPipelineUpgrade() {
String lengthyDeploymentSpec =
"""
<deployment version='1.0'>
@@ -1844,7 +1842,7 @@ public class DeploymentTriggerTest {
tester.upgrader().maintain();
alpha.runJob(systemTest).runJob(stagingTest)
- .runJob(productionUsEast3).runJob(testUsEast3);
+ .runJob(productionUsEast3).runJob(testUsEast3);
assertEquals(Change.empty(), alpha.instance().change());
tester.upgrader().maintain();
@@ -1860,12 +1858,12 @@ public class DeploymentTriggerTest {
}
@Test
- public void testRevisionJoinsUpgradeWithLeadingRollout() {
+ void testRevisionJoinsUpgradeWithLeadingRollout() {
var appPackage = new ApplicationPackageBuilder().region("us-central-1")
- .region("us-east-3")
- .region("us-west-1")
- .upgradeRollout("leading")
- .build();
+ .region("us-east-3")
+ .region("us-west-1")
+ .upgradeRollout("leading")
+ .build();
var app = tester.newDeploymentContext().submit(appPackage).deploy();
// Platform rolls through first production zone.
@@ -1886,7 +1884,7 @@ public class DeploymentTriggerTest {
// Upgrade got here first, and has triggered, but is now obsolete.
app.triggerJobs();
assertEquals(new Versions(version1, revision0.get(), Optional.of(version0), revision0),
- tester.jobs().last(app.instanceId(), productionUsEast3).get().versions());
+ tester.jobs().last(app.instanceId(), productionUsEast3).get().versions());
assertEquals(RunStatus.running, tester.jobs().last(app.instanceId(), productionUsEast3).get().status());
// Once staging tests verify the joint upgrade, the job is replaced with that.
@@ -1894,23 +1892,23 @@ public class DeploymentTriggerTest {
app.triggerJobs();
app.jobAborted(productionUsEast3).runJob(productionUsEast3);
assertEquals(new Versions(version1, revision1.get(), Optional.of(version0), revision0),
- tester.jobs().last(app.instanceId(), productionUsEast3).get().versions());
+ tester.jobs().last(app.instanceId(), productionUsEast3).get().versions());
// Platform and revision now proceed together.
app.triggerJobs();
assertEquals(new Versions(version1, revision1.get(), Optional.of(version0), revision0),
- tester.jobs().last(app.instanceId(), productionUsWest1).get().versions());
+ tester.jobs().last(app.instanceId(), productionUsWest1).get().versions());
app.runJob(productionUsWest1);
assertEquals(Change.empty(), app.instance().change());
}
@Test
- public void testRevisionPassesUpgradeWithSimultaneousRollout() {
+ void testRevisionPassesUpgradeWithSimultaneousRollout() {
var appPackage = new ApplicationPackageBuilder().region("us-central-1")
- .region("us-east-3")
- .region("us-west-1")
- .upgradeRollout("simultaneous")
- .build();
+ .region("us-east-3")
+ .region("us-west-1")
+ .upgradeRollout("simultaneous")
+ .build();
var app = tester.newDeploymentContext().submit(appPackage).deploy();
// Platform rolls through first production zone.
@@ -1932,7 +1930,7 @@ public class DeploymentTriggerTest {
app.triggerJobs();
app.assertRunning(productionUsEast3);
assertEquals(new Versions(version1, revision0.get(), Optional.of(version0), revision0),
- tester.jobs().last(app.instanceId(), productionUsEast3).get().versions());
+ tester.jobs().last(app.instanceId(), productionUsEast3).get().versions());
assertEquals(RunStatus.running, tester.jobs().last(app.instanceId(), productionUsEast3).get().status());
// Once staging tests verify the joint upgrade, the job is replaced with that.
@@ -1940,27 +1938,27 @@ public class DeploymentTriggerTest {
app.triggerJobs();
app.jobAborted(productionUsEast3).runJob(productionUsEast3);
assertEquals(new Versions(version1, revision1.get(), Optional.of(version0), revision0),
- tester.jobs().last(app.instanceId(), productionUsEast3).get().versions());
+ tester.jobs().last(app.instanceId(), productionUsEast3).get().versions());
// Revision now proceeds alone.
app.triggerJobs();
assertEquals(new Versions(version0, revision1.get(), Optional.of(version0), revision0),
- tester.jobs().last(app.instanceId(), productionUsWest1).get().versions());
+ tester.jobs().last(app.instanceId(), productionUsWest1).get().versions());
app.runJob(productionUsWest1);
// Upgrade follows.
app.triggerJobs();
assertEquals(new Versions(version1, revision1.get(), Optional.of(version0), revision1),
- tester.jobs().last(app.instanceId(), productionUsWest1).get().versions());
+ tester.jobs().last(app.instanceId(), productionUsWest1).get().versions());
app.runJob(productionUsWest1);
assertEquals(Change.empty(), app.instance().change());
}
@Test
- public void mixedDirectAndPipelineJobsInProduction() {
+ void mixedDirectAndPipelineJobsInProduction() {
ApplicationPackage cdPackage = new ApplicationPackageBuilder().region("us-east-3")
- .region("aws-us-east-1a")
- .build();
+ .region("aws-us-east-1a")
+ .build();
ControllerTester wrapped = new ControllerTester(cd);
wrapped.upgradeSystem(Version.fromString("6.1"));
wrapped.computeVersionStatus();
@@ -1974,9 +1972,9 @@ public class DeploymentTriggerTest {
// Staging test requires unknown initial version, and is broken.
tester.controller().applications().deploymentTrigger().forceTrigger(app.instanceId(), productionUsEast3, "user", false, true, true);
app.runJob(productionUsEast3)
- .abortJob(stagingTest) // Complete failing run.
- .runJob(stagingTest) // Run staging-test for production zone with no prior deployment.
- .runJob(productionAwsUsEast1a);
+ .abortJob(stagingTest) // Complete failing run.
+ .runJob(stagingTest) // Run staging-test for production zone with no prior deployment.
+ .runJob(productionAwsUsEast1a);
// Manually deploy to east again, then upgrade the system.
app.runJob(productionUsEast3, cdPackage);
@@ -1986,12 +1984,12 @@ public class DeploymentTriggerTest {
// System and staging tests both require unknown versions, and are broken.
tester.controller().applications().deploymentTrigger().forceTrigger(app.instanceId(), productionUsEast3, "user", false, true, true);
app.runJob(productionUsEast3)
- .triggerJobs()
- .jobAborted(systemTest)
- .jobAborted(stagingTest)
- .runJob(systemTest) // Run test for aws zone again.
- .runJob(stagingTest) // Run test for aws zone again.
- .runJob(productionAwsUsEast1a);
+ .triggerJobs()
+ .jobAborted(systemTest)
+ .jobAborted(stagingTest)
+ .runJob(systemTest) // Run test for aws zone again.
+ .runJob(stagingTest) // Run test for aws zone again.
+ .runJob(productionAwsUsEast1a);
// Deploy manually again, then submit new package.
app.runJob(productionUsEast3, cdPackage);
@@ -2000,13 +1998,13 @@ public class DeploymentTriggerTest {
// Staging test requires unknown initial version, and is broken.
tester.controller().applications().deploymentTrigger().forceTrigger(app.instanceId(), productionUsEast3, "user", false, true, true);
app.runJob(productionUsEast3)
- .jobAborted(stagingTest)
- .runJob(stagingTest)
- .runJob(productionAwsUsEast1a);
+ .jobAborted(stagingTest)
+ .runJob(stagingTest)
+ .runJob(productionAwsUsEast1a);
}
@Test
- public void testsInSeparateInstance() {
+ void testsInSeparateInstance() {
String deploymentSpec =
"""
<deployment version='1.0' athenz-domain='domain' athenz-service='service'>
@@ -2029,30 +2027,30 @@ public class DeploymentTriggerTest {
var conservative = tester.newDeploymentContext("t", "a", "default");
canary.runJob(systemTest)
- .runJob(stagingTest);
+ .runJob(stagingTest);
conservative.runJob(productionEuWest1)
- .runJob(testEuWest1);
+ .runJob(testEuWest1);
canary.submit(applicationPackage)
- .runJob(systemTest)
- .runJob(stagingTest);
+ .runJob(systemTest)
+ .runJob(stagingTest);
tester.outstandingChangeDeployer().run();
conservative.runJob(productionEuWest1)
- .runJob(testEuWest1);
+ .runJob(testEuWest1);
tester.controllerTester().upgradeSystem(new Version("7.7.7"));
tester.upgrader().maintain();
canary.runJob(systemTest)
- .runJob(stagingTest);
+ .runJob(stagingTest);
tester.upgrader().maintain();
conservative.runJob(productionEuWest1)
- .runJob(testEuWest1);
+ .runJob(testEuWest1);
}
@Test
- public void testEagerTests() {
+ void testEagerTests() {
var app = tester.newDeploymentContext().submit().deploy();
// Start upgrade, then receive new submission.
@@ -2069,24 +2067,24 @@ public class DeploymentTriggerTest {
tester.triggerJobs();
app.assertRunning(stagingTest);
assertEquals(version1,
- app.instanceJobs().get(stagingTest).lastCompleted().get().versions().targetPlatform());
+ app.instanceJobs().get(stagingTest).lastCompleted().get().versions().targetPlatform());
assertEquals(build1,
- app.instanceJobs().get(stagingTest).lastCompleted().get().versions().targetRevision());
+ app.instanceJobs().get(stagingTest).lastCompleted().get().versions().targetRevision());
assertEquals(version1,
- app.instanceJobs().get(stagingTest).lastTriggered().get().versions().sourcePlatform().get());
+ app.instanceJobs().get(stagingTest).lastTriggered().get().versions().sourcePlatform().get());
assertEquals(build1,
- app.instanceJobs().get(stagingTest).lastTriggered().get().versions().sourceRevision().get());
+ app.instanceJobs().get(stagingTest).lastTriggered().get().versions().sourceRevision().get());
assertEquals(version1,
- app.instanceJobs().get(stagingTest).lastTriggered().get().versions().targetPlatform());
+ app.instanceJobs().get(stagingTest).lastTriggered().get().versions().targetPlatform());
assertEquals(build2,
- app.instanceJobs().get(stagingTest).lastTriggered().get().versions().targetRevision());
+ app.instanceJobs().get(stagingTest).lastTriggered().get().versions().targetRevision());
// App completes upgrade, and outstanding change is triggered. This should let relevant, running jobs finish.
app.runJob(systemTest)
- .runJob(productionUsCentral1)
- .runJob(productionUsEast3)
- .runJob(productionUsWest1);
+ .runJob(productionUsCentral1)
+ .runJob(productionUsEast3)
+ .runJob(productionUsWest1);
tester.outstandingChangeDeployer().run();
assertEquals(RunStatus.running, tester.jobs().last(app.instanceId(), stagingTest).get().status());
@@ -2096,12 +2094,12 @@ public class DeploymentTriggerTest {
}
@Test
- public void testTriggeringOfIdleTestJobsWhenFirstDeploymentIsOnNewerVersionThanChange() {
+ void testTriggeringOfIdleTestJobsWhenFirstDeploymentIsOnNewerVersionThanChange() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder().systemTest()
- .stagingTest()
- .region("us-east-3")
- .region("us-west-1")
- .build();
+ .stagingTest()
+ .region("us-east-3")
+ .region("us-west-1")
+ .build();
var app = tester.newDeploymentContext().submit(applicationPackage).deploy();
var appToAvoidVersionGC = tester.newDeploymentContext("g", "c", "default").submit().deploy();
@@ -2122,9 +2120,9 @@ public class DeploymentTriggerTest {
assertEquals(Optional.of(version2), app.instance().change().platform());
app.runJob(systemTest)
- .runJob(productionUsEast3)
- .runJob(stagingTest)
- .runJob(productionUsWest1);
+ .runJob(productionUsEast3)
+ .runJob(stagingTest)
+ .runJob(productionUsWest1);
assertEquals(version3, app.instanceJobs().get(productionUsEast3).lastSuccess().get().versions().targetPlatform());
assertEquals(version2, app.instanceJobs().get(productionUsWest1).lastSuccess().get().versions().targetPlatform());
@@ -2134,7 +2132,7 @@ public class DeploymentTriggerTest {
}
@Test
- public void testRetriggerQueue() {
+ void testRetriggerQueue() {
var app = tester.newDeploymentContext().submit().deploy();
app.submit();
tester.triggerJobs();
@@ -2144,11 +2142,11 @@ public class DeploymentTriggerTest {
tester.deploymentTrigger().reTriggerOrAddToQueue(app.deploymentIdIn(ZoneId.from("prod", "us-east-3")), null);
List<RetriggerEntry> retriggerEntries = tester.controller().curator().readRetriggerEntries();
- Assert.assertEquals(1, retriggerEntries.size());
+ assertEquals(1, retriggerEntries.size());
}
@Test
- public void testOrchestrationWithIncompatibleVersionPairs() {
+ void testOrchestrationWithIncompatibleVersionPairs() {
Version version1 = new Version("7");
Version version2 = new Version("8");
tester.controllerTester().flagSource().withListFlag(PermanentFlags.INCOMPATIBLE_VERSIONS.id(), List.of("8"), String.class);
@@ -2156,10 +2154,10 @@ public class DeploymentTriggerTest {
// App deploys on version1.
tester.controllerTester().upgradeSystem(version1);
DeploymentContext app = tester.newDeploymentContext()
- .submit(new ApplicationPackageBuilder().region("us-east-3")
- .compileVersion(version1)
- .build())
- .deploy();
+ .submit(new ApplicationPackageBuilder().region("us-east-3")
+ .compileVersion(version1)
+ .build())
+ .deploy();
// System upgrades to version2, but the app is not upgraded.
tester.controllerTester().upgradeSystem(version2);
@@ -2168,8 +2166,8 @@ public class DeploymentTriggerTest {
// App compiles against version2, and upgrades.
app.submit(new ApplicationPackageBuilder().region("us-east-3")
- .compileVersion(version2)
- .build());
+ .compileVersion(version2)
+ .build());
app.deploy();
assertEquals(version2, tester.jobs().last(app.instanceId(), productionUsEast3).get().versions().targetPlatform());
assertEquals(version2, app.application().revisions().get(tester.jobs().last(app.instanceId(), productionUsEast3).get().versions().targetRevision()).compileVersion().get());
@@ -2177,9 +2175,9 @@ public class DeploymentTriggerTest {
// App specifies version1 in deployment spec, compiles against version1, pins to version1, and then downgrades.
app.submit(new ApplicationPackageBuilder().region("us-east-3")
- .majorVersion(7)
- .compileVersion(version1)
- .build());
+ .majorVersion(7)
+ .compileVersion(version1)
+ .build());
tester.deploymentTrigger().forceChange(app.instanceId(), app.instance().change().withPin());
app.deploy();
assertEquals(version1, tester.jobs().last(app.instanceId(), productionUsEast3).get().versions().targetPlatform());
@@ -2187,16 +2185,16 @@ public class DeploymentTriggerTest {
// A new app, compiled against version1, is deployed on version1.
DeploymentContext newApp = tester.newDeploymentContext("new", "app", "default")
- .submit(new ApplicationPackageBuilder().region("us-east-3")
- .compileVersion(version1)
- .build())
- .deploy();
+ .submit(new ApplicationPackageBuilder().region("us-east-3")
+ .compileVersion(version1)
+ .build())
+ .deploy();
assertEquals(version1, tester.jobs().last(newApp.instanceId(), productionUsEast3).get().versions().targetPlatform());
assertEquals(version1, newApp.application().revisions().get(tester.jobs().last(newApp.instanceId(), productionUsEast3).get().versions().targetRevision()).compileVersion().get());
}
@Test
- public void testInstanceWithOnlySystemTestInTwoClouds() {
+ void testInstanceWithOnlySystemTestInTwoClouds() {
String spec = """
<deployment>
<instance id='tests'>
@@ -2272,7 +2270,7 @@ public class DeploymentTriggerTest {
Version version3 = new Version("9");
tester.controllerTester().upgradeSystem(version3);
tests.runJob(systemTest) // Success in default cloud.
- .failDeployment(systemTest); // Failure in centauri cloud.
+ .failDeployment(systemTest); // Failure in centauri cloud.
tester.upgrader().run();
assertEquals(Change.of(version3), tests.instance().change());
@@ -2369,7 +2367,7 @@ public class DeploymentTriggerTest {
}
@Test
- public void testNoTests() {
+ void testNoTests() {
DeploymentContext app = tester.newDeploymentContext();
app.submit(new ApplicationPackageBuilder().systemTest().region("us-east-3").build());
@@ -2381,7 +2379,7 @@ public class DeploymentTriggerTest {
}
@Test
- public void testJobNames() {
+ void testJobNames() {
ZoneRegistryMock zones = new ZoneRegistryMock(SystemName.main);
List<ZoneApi> existing = new ArrayList<>(zones.zones().all().zones());
existing.add(ZoneApiMock.newBuilder().withCloud("pink-clouds").withId("test.zone").build());
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/InternalStepRunnerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/InternalStepRunnerTest.java
index d781b1f1d3f..bf488198126 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/InternalStepRunnerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/InternalStepRunnerTest.java
@@ -25,8 +25,8 @@ import com.yahoo.vespa.hosted.controller.application.SystemApplication;
import com.yahoo.vespa.hosted.controller.application.pkg.ApplicationPackage;
import com.yahoo.vespa.hosted.controller.integration.ZoneApiMock;
import com.yahoo.vespa.hosted.controller.maintenance.JobRunner;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.security.cert.X509Certificate;
import java.time.Duration;
@@ -51,10 +51,10 @@ import static com.yahoo.vespa.hosted.controller.deployment.Step.Status.failed;
import static com.yahoo.vespa.hosted.controller.deployment.Step.Status.succeeded;
import static com.yahoo.vespa.hosted.controller.deployment.Step.Status.unfinished;
import static java.time.temporal.ChronoUnit.SECONDS;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author jonmv
@@ -65,7 +65,7 @@ public class InternalStepRunnerTest {
private DeploymentTester tester;
private DeploymentContext app;
- @Before
+ @BeforeEach
public void setup() {
tester = new DeploymentTester();
app = tester.newDeploymentContext();
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/QuotaUsageTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/QuotaUsageTest.java
index 772d65fa80e..44ca248614b 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/QuotaUsageTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/QuotaUsageTest.java
@@ -2,9 +2,9 @@
package com.yahoo.vespa.hosted.controller.deployment;
import com.yahoo.config.provision.zone.ZoneId;
-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 ogronnesby
@@ -12,7 +12,7 @@ import static org.junit.Assert.assertEquals;
public class QuotaUsageTest {
@Test
- public void testQuotaUsageIsPersisted() {
+ void testQuotaUsageIsPersisted() {
var tester = new DeploymentTester();
var context = tester.newDeploymentContext().submit().deploy();
assertEquals(1.304, context.deployment(ZoneId.from("prod.us-west-1")).quota().rate(), 0.01);
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/TestConfigSerializerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/TestConfigSerializerTest.java
index 67583891765..6493eafcde5 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/TestConfigSerializerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/TestConfigSerializerTest.java
@@ -11,7 +11,7 @@ import com.yahoo.vespa.hosted.controller.api.identifiers.DeploymentId;
import com.yahoo.vespa.hosted.controller.api.integration.deployment.RevisionId;
import com.yahoo.vespa.hosted.controller.application.Endpoint;
import com.yahoo.vespa.hosted.controller.application.EndpointId;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.file.Files;
@@ -21,7 +21,7 @@ import java.util.List;
import java.util.Map;
import static com.yahoo.vespa.hosted.controller.deployment.DeploymentTester.instanceId;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author jonmv
@@ -29,24 +29,24 @@ import static org.junit.Assert.assertEquals;
public class TestConfigSerializerTest {
@Test
- public void testConfig() throws IOException {
+ void testConfig() throws IOException {
ZoneId zone = DeploymentContext.systemTest.zone();
byte[] json = new TestConfigSerializer(SystemName.PublicCd).configJson(instanceId,
- DeploymentContext.systemTest,
- true,
- Version.fromString("1.2.3"),
- RevisionId.forProduction(321),
- Instant.ofEpochMilli(222),
- Map.of(zone, List.of(Endpoint.of(ApplicationId.defaultId())
- .target(EndpointId.of("ai"), ClusterSpec.Id.from("qrs"),
- List.of(new DeploymentId(ApplicationId.defaultId(),
- ZoneId.defaultId())))
- .on(Endpoint.Port.tls())
- .in(SystemName.main))),
- Map.of(zone, List.of("facts")));
+ DeploymentContext.systemTest,
+ true,
+ Version.fromString("1.2.3"),
+ RevisionId.forProduction(321),
+ Instant.ofEpochMilli(222),
+ Map.of(zone, List.of(Endpoint.of(ApplicationId.defaultId())
+ .target(EndpointId.of("ai"), ClusterSpec.Id.from("qrs"),
+ List.of(new DeploymentId(ApplicationId.defaultId(),
+ ZoneId.defaultId())))
+ .on(Endpoint.Port.tls())
+ .in(SystemName.main))),
+ Map.of(zone, List.of("facts")));
byte[] expected = Files.readAllBytes(Paths.get("src/test/resources/testConfig.json"));
assertEquals(new String(SlimeUtils.toJsonBytes(SlimeUtils.jsonToSlime(expected))),
- new String(json));
+ new String(json));
}
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/ZipBuilderTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/ZipBuilderTest.java
index f48658af7e3..8fe48f805df 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/ZipBuilderTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/deployment/ZipBuilderTest.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.vespa.hosted.controller.deployment;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
@@ -13,7 +13,7 @@ import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author freva
@@ -21,7 +21,7 @@ import static org.junit.Assert.assertEquals;
public class ZipBuilderTest {
@Test
- public void test() {
+ void test() {
Map<String, String> expected = new HashMap<>();
expected.put("dir/myfile", "my content");
expected.put("rootfile", "this is root");
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/dns/NameServiceQueueTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/dns/NameServiceQueueTest.java
index b5fd3d750ef..efb04615125 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/dns/NameServiceQueueTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/dns/NameServiceQueueTest.java
@@ -9,13 +9,13 @@ import com.yahoo.vespa.hosted.controller.api.integration.dns.Record;
import com.yahoo.vespa.hosted.controller.api.integration.dns.RecordData;
import com.yahoo.vespa.hosted.controller.api.integration.dns.RecordName;
import com.yahoo.vespa.hosted.controller.dns.NameServiceQueue.Priority;
-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.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author mpolden
@@ -23,18 +23,18 @@ import static org.junit.Assert.assertTrue;
public class NameServiceQueueTest {
@Test
- public void test_queue() {
+ void test_queue() {
var nameService = new MemoryNameService();
var r1 = new Record(Record.Type.CNAME, RecordName.from("cname.vespa.oath.cloud"), RecordData.from("example.com"));
var r2 = new Record(Record.Type.TXT, RecordName.from("txt.example.com"), RecordData.from("text"));
var r3 = List.of(new Record(Record.Type.ALIAS, RecordName.from("alias.example.com"),
- new LatencyAliasTarget(HostName.of("alias1"),
- "dns-zone-01",
- ZoneId.from("prod", "us-north-1")).pack()),
- new Record(Record.Type.ALIAS, RecordName.from("alias.example.com"),
- new LatencyAliasTarget(HostName.of("alias2"),
- "dns-zone-02",
- ZoneId.from("prod", "us-north-2")).pack()));
+ new LatencyAliasTarget(HostName.of("alias1"),
+ "dns-zone-01",
+ ZoneId.from("prod", "us-north-1")).pack()),
+ new Record(Record.Type.ALIAS, RecordName.from("alias.example.com"),
+ new LatencyAliasTarget(HostName.of("alias2"),
+ "dns-zone-02",
+ ZoneId.from("prod", "us-north-2")).pack()));
var req1 = new CreateRecord(r1);
var req2 = new CreateRecords(List.of(r2));
var req3 = new CreateRecords(r3);
@@ -64,17 +64,17 @@ public class NameServiceQueueTest {
// Dispatch removals
queue = queue.with(req4).with(req5).dispatchTo(nameService, 2);
- assertTrue("Removed " + r2, nameService.findRecords(r2.type(), r2.name()).isEmpty());
- assertTrue("Removed " + r3, nameService.findRecords(Record.Type.ALIAS, r3.get(0).name()).isEmpty());
+ assertTrue(nameService.findRecords(r2.type(), r2.name()).isEmpty(), "Removed " + r2);
+ assertTrue(nameService.findRecords(Record.Type.ALIAS, r3.get(0).name()).isEmpty(), "Removed " + r3);
// Dispatch removals by data
queue = queue.with(req6).dispatchTo(nameService, 1);
assertTrue(queue.requests().isEmpty());
- assertTrue("Removed " + r1, nameService.findRecords(Record.Type.CNAME, r1.name()).isEmpty());
+ assertTrue(nameService.findRecords(Record.Type.CNAME, r1.name()).isEmpty(), "Removed " + r1);
// Keep n last requests
queue = queue.with(req1).with(req2).with(req3).with(req4).with(req6)
- .last(2);
+ .last(2);
assertEquals(List.of(req4, req6), List.copyOf(queue.requests()));
assertSame(queue, queue.last(2));
assertSame(queue, queue.last(10));
@@ -82,7 +82,7 @@ public class NameServiceQueueTest {
// Keep n first requests
queue = NameServiceQueue.EMPTY.with(req1).with(req2).with(req3).with(req4).with(req6)
- .first(3);
+ .first(3);
assertEquals(List.of(req1, req2, req3), List.copyOf(queue.requests()));
assertSame(queue, queue.first(3));
assertSame(queue, queue.first(10));
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ApplicationOwnershipConfirmerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ApplicationOwnershipConfirmerTest.java
index 1e258e8febc..b643d3e90d2 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ApplicationOwnershipConfirmerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ApplicationOwnershipConfirmerTest.java
@@ -9,17 +9,17 @@ import com.yahoo.vespa.hosted.controller.api.integration.organization.IssueId;
import com.yahoo.vespa.hosted.controller.api.integration.organization.OwnershipIssues;
import com.yahoo.vespa.hosted.controller.api.integration.organization.User;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.List;
import java.util.Optional;
import static com.yahoo.vespa.hosted.controller.deployment.DeploymentTester.appId;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author jonmv
@@ -30,7 +30,7 @@ public class ApplicationOwnershipConfirmerTest {
private ApplicationOwnershipConfirmer confirmer;
private DeploymentTester tester;
- @Before
+ @BeforeEach
public void setup() {
tester = new DeploymentTester();
issues = new MockOwnershipIssues();
@@ -38,7 +38,7 @@ public class ApplicationOwnershipConfirmerTest {
}
@Test
- public void testConfirmation() {
+ void testConfirmation() {
Optional<Contact> contact = Optional.of(tester.controllerTester().serviceRegistry().contactRetrieverMock().contact());
var app = tester.newDeploymentContext();
tester.controller().tenants().lockOrThrow(appId.tenant(), LockedTenant.Athenz.class, tenant ->
@@ -48,55 +48,55 @@ public class ApplicationOwnershipConfirmerTest {
var appWithoutContact = tester.newDeploymentContext("other", "application", "default");
appWithoutContact.submit().deploy();
- assertFalse("No issue is initially stored for a new application.", app.application().ownershipIssueId().isPresent());
- assertFalse("No issue is initially stored for a new application.", appWithoutContact.application().ownershipIssueId().isPresent());
- assertFalse("No escalation has been attempted for a new application", issues.escalated);
+ assertFalse(app.application().ownershipIssueId().isPresent(), "No issue is initially stored for a new application.");
+ assertFalse(appWithoutContact.application().ownershipIssueId().isPresent(), "No issue is initially stored for a new application.");
+ assertFalse(issues.escalated, "No escalation has been attempted for a new application");
// Set response from the issue mock, which will be obtained by the maintainer on issue filing.
Optional<IssueId> issueId = Optional.of(IssueId.from("1"));
issues.response = issueId;
confirmer.maintain();
- assertFalse("No issue is stored for an application newer than 3 months.", app.application().ownershipIssueId().isPresent());
- assertFalse("No issue is stored for an application newer than 3 months.", appWithoutContact.application().ownershipIssueId().isPresent());
+ assertFalse(app.application().ownershipIssueId().isPresent(), "No issue is stored for an application newer than 3 months.");
+ assertFalse(appWithoutContact.application().ownershipIssueId().isPresent(), "No issue is stored for an application newer than 3 months.");
tester.clock().advance(Duration.ofDays(91));
confirmer.maintain();
- assertEquals("Confirmation issue has been filed for application with contact.", issueId, app.application().ownershipIssueId());
- assertTrue("The confirmation issue response has been ensured.", issues.escalated);
- assertEquals("No confirmation issue has been filed for application without contact.", Optional.empty(), appWithoutContact.application().ownershipIssueId());
+ assertEquals(issueId, app.application().ownershipIssueId(), "Confirmation issue has been filed for application with contact.");
+ assertTrue(issues.escalated, "The confirmation issue response has been ensured.");
+ assertEquals(Optional.empty(), appWithoutContact.application().ownershipIssueId(), "No confirmation issue has been filed for application without contact.");
// No new issue is created, so return empty now.
issues.response = Optional.empty();
confirmer.maintain();
- assertEquals("Confirmation issue reference is not updated when no issue id is returned.", issueId, app.application().ownershipIssueId());
+ assertEquals(issueId, app.application().ownershipIssueId(), "Confirmation issue reference is not updated when no issue id is returned.");
// Time has passed, and a new confirmation issue is in order for the property which is still in production.
Optional<IssueId> issueId2 = Optional.of(IssueId.from("2"));
issues.response = issueId2;
confirmer.maintain();
- assertEquals("A new confirmation issue id is stored when something is returned to the maintainer.", issueId2, app.application().ownershipIssueId());
+ assertEquals(issueId2, app.application().ownershipIssueId(), "A new confirmation issue id is stored when something is returned to the maintainer.");
- assertFalse("No owner is stored for application", app.application().owner().isPresent());
+ assertFalse(app.application().owner().isPresent(), "No owner is stored for application");
issues.owner = Optional.of(User.from("username"));
confirmer.maintain();
- assertEquals("Owner has been added to application", app.application().owner().get().username(), "username");
+ assertEquals(app.application().owner().get().username(), "username", "Owner has been added to application");
// The app deletes all production deployments — see that the issue is forgotten.
- assertEquals("Confirmation issue for application is still open.", issueId2, app.application().ownershipIssueId());
+ assertEquals(issueId2, app.application().ownershipIssueId(), "Confirmation issue for application is still open.");
app.application().productionDeployments().values().stream().flatMap(List::stream)
- .forEach(deployment -> tester.controller().applications().deactivate(app.instanceId(), deployment.zone()));
- assertTrue("No production deployments are listed for user.", app.application().require(InstanceName.defaultName()).productionDeployments().isEmpty());
+ .forEach(deployment -> tester.controller().applications().deactivate(app.instanceId(), deployment.zone()));
+ assertTrue(app.application().require(InstanceName.defaultName()).productionDeployments().isEmpty(), "No production deployments are listed for user.");
confirmer.maintain();
// Time has passed, and a new confirmation issue is in order for the property which is still in production.
issues.response = Optional.of(IssueId.from("3"));
confirmer.maintain();
- assertEquals("Confirmation issue for application without production deployments has not been filed.", issueId2, app.application().ownershipIssueId());
+ assertEquals(issueId2, app.application().ownershipIssueId(), "Confirmation issue for application without production deployments has not been filed.");
}
private static class MockOwnershipIssues implements OwnershipIssues {
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ArchiveAccessMaintainerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ArchiveAccessMaintainerTest.java
index 3535417c586..c10b77d853a 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ArchiveAccessMaintainerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ArchiveAccessMaintainerTest.java
@@ -11,7 +11,7 @@ import com.yahoo.vespa.hosted.controller.api.integration.archive.ArchiveBucket;
import com.yahoo.vespa.hosted.controller.api.integration.archive.MockArchiveService;
import com.yahoo.vespa.hosted.controller.tenant.ArchiveAccess;
import com.yahoo.vespa.hosted.controller.tenant.Tenant;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.Map;
@@ -19,8 +19,7 @@ import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author andreer
@@ -28,7 +27,7 @@ import static org.junit.Assert.assertNull;
public class ArchiveAccessMaintainerTest {
@Test
- public void grantsRoleAccess() {
+ void grantsRoleAccess() {
var tester = new ControllerTester(SystemName.Public);
String tenant1role = "arn:aws:iam::123456789012:role/my-role";
@@ -49,10 +48,10 @@ public class ArchiveAccessMaintainerTest {
assertEquals(new ArchiveAccess().withAWSRole(tenant2role), archiveService.authorizeAccessByTenantName.get(tenant2));
var expected = Map.of("archive.bucketCount",
- tester.controller().zoneRegistry().zonesIncludingSystem().all().ids().stream()
- .collect(Collectors.toMap(
- zone -> Map.of("zone", zone.value(), "cloud", "default"),
- zone -> zone.equals(testZone) ? 1d : 0d)));
+ tester.controller().zoneRegistry().zonesIncludingSystem().all().ids().stream()
+ .collect(Collectors.toMap(
+ zone -> Map.of("zone", zone.value(), "cloud", "default"),
+ zone -> zone.equals(testZone) ? 1d : 0d)));
assertEquals(expected, metric.metrics());
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ArchiveUriUpdaterTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ArchiveUriUpdaterTest.java
index d208657c1c4..cb5a84654d0 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ArchiveUriUpdaterTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ArchiveUriUpdaterTest.java
@@ -13,7 +13,7 @@ import com.yahoo.vespa.hosted.controller.application.SystemApplication;
import com.yahoo.vespa.hosted.controller.application.pkg.ApplicationPackage;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentContext;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.time.Duration;
@@ -21,7 +21,7 @@ import java.util.LinkedHashSet;
import java.util.Map;
import java.util.stream.Collectors;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author freva
@@ -31,7 +31,7 @@ public class ArchiveUriUpdaterTest {
private final DeploymentTester tester = new DeploymentTester(new ControllerTester(SystemName.Public));
@Test
- public void archive_uri_test() {
+ void archive_uri_test() {
var updater = new ArchiveUriUpdater(tester.controller(), Duration.ofDays(1));
var tenant1 = TenantName.from("tenant1");
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ArtifactExpirerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ArtifactExpirerTest.java
index 7703266c9ba..c0f0322d192 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ArtifactExpirerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ArtifactExpirerTest.java
@@ -6,13 +6,13 @@ import com.yahoo.config.provision.CloudName;
import com.yahoo.vespa.hosted.controller.api.integration.artifact.Artifact;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester;
import com.yahoo.vespa.hosted.controller.integration.ArtifactRegistryMock;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author mpolden
@@ -20,7 +20,7 @@ import static org.junit.Assert.assertEquals;
public class ArtifactExpirerTest {
@Test
- public void maintain() {
+ void maintain() {
DeploymentTester tester = new DeploymentTester();
ArtifactExpirer expirer = new ArtifactExpirer(tester.controller(), Duration.ofDays(1));
ArtifactRegistryMock registry = tester.controllerTester().serviceRegistry().artifactRegistry(CloudName.defaultName()).orElseThrow();
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ChangeManagementAssessorTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ChangeManagementAssessorTest.java
index add1a319384..084fd243769 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ChangeManagementAssessorTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ChangeManagementAssessorTest.java
@@ -7,14 +7,14 @@ import com.yahoo.config.provision.NodeType;
import com.yahoo.config.provision.zone.ZoneId;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.Node;
import com.yahoo.vespa.hosted.controller.integration.NodeRepositoryMock;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Collections;
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;
/**
* @author smorgrav
@@ -24,7 +24,7 @@ public class ChangeManagementAssessorTest {
private final ChangeManagementAssessor changeManagementAssessor = new ChangeManagementAssessor(new NodeRepositoryMock());
@Test
- public void empty_input_variations() {
+ void empty_input_variations() {
ZoneId zone = ZoneId.from("prod", "eu-trd");
List<String> hostNames = new ArrayList<>();
List<Node> allNodesInZone = new ArrayList<>();
@@ -36,16 +36,16 @@ public class ChangeManagementAssessorTest {
}
@Test
- public void one_host_one_cluster_no_groups() {
+ void one_host_one_cluster_no_groups() {
ZoneId zone = ZoneId.from("prod", "eu-trd");
List<String> hostNames = Collections.singletonList("host1");
List<Node> allNodesInZone = new ArrayList<>();
- allNodesInZone.add(createNode("node1", "host1", "default", 0 ));
- allNodesInZone.add(createNode("node2", "host1", "default", 0 ));
- allNodesInZone.add(createNode("node3", "host1", "default", 0 ));
+ allNodesInZone.add(createNode("node1", "host1", "default", 0));
+ allNodesInZone.add(createNode("node2", "host1", "default", 0));
+ allNodesInZone.add(createNode("node3", "host1", "default", 0));
// Add an not impacted hosts
- allNodesInZone.add(createNode("node4", "host2", "default", 0 ));
+ allNodesInZone.add(createNode("node4", "host2", "default", 0));
// Add tenant hosts
allNodesInZone.add(createHost("host1", NodeType.host));
@@ -67,27 +67,27 @@ public class ChangeManagementAssessorTest {
}
@Test
- public void one_of_two_groups_in_one_of_two_clusters() {
+ void one_of_two_groups_in_one_of_two_clusters() {
ZoneId zone = ZoneId.from("prod", "eu-trd");
List<String> hostNames = List.of("host1", "host2", "host5");
List<Node> allNodesInZone = new ArrayList<>();
// Two impacted nodes on host1
- allNodesInZone.add(createNode("node1", "host1", "default", 0 ));
- allNodesInZone.add(createNode("node2", "host1", "default", 0 ));
+ allNodesInZone.add(createNode("node1", "host1", "default", 0));
+ allNodesInZone.add(createNode("node2", "host1", "default", 0));
// One impacted nodes on host2
- allNodesInZone.add(createNode("node3", "host2", "default", 0 ));
+ allNodesInZone.add(createNode("node3", "host2", "default", 0));
// Another group on hosts not impacted
- allNodesInZone.add(createNode("node4", "host3", "default", 1 ));
- allNodesInZone.add(createNode("node5", "host3", "default", 1 ));
- allNodesInZone.add(createNode("node6", "host3", "default", 1 ));
+ allNodesInZone.add(createNode("node4", "host3", "default", 1));
+ allNodesInZone.add(createNode("node5", "host3", "default", 1));
+ allNodesInZone.add(createNode("node6", "host3", "default", 1));
// Another cluster on hosts not impacted - this one also with three different groups (should all be ignored here)
- allNodesInZone.add(createNode("node4", "host4", "myman", 4 ));
- allNodesInZone.add(createNode("node5", "host4", "myman", 5 ));
- allNodesInZone.add(createNode("node6", "host4", "myman", 6 ));
+ allNodesInZone.add(createNode("node4", "host4", "myman", 4));
+ allNodesInZone.add(createNode("node5", "host4", "myman", 5));
+ allNodesInZone.add(createNode("node6", "host4", "myman", 6));
// Add tenant hosts
allNodesInZone.add(createHost("host1", NodeType.host));
@@ -114,14 +114,14 @@ public class ChangeManagementAssessorTest {
assertEquals(2, hostAssessments.size());
assertTrue(hostAssessments.stream().anyMatch(hostAssessment ->
hostAssessment.hostName.equals("host1") &&
- hostAssessment.switchName.equals("switch1") &&
- hostAssessment.numberOfChildren == 2 &&
- hostAssessment.numberOfProblematicChildren == 2
+ hostAssessment.switchName.equals("switch1") &&
+ hostAssessment.numberOfChildren == 2 &&
+ hostAssessment.numberOfProblematicChildren == 2
));
}
@Test
- public void two_config_nodes() {
+ void two_config_nodes() {
var zone = ZoneId.from("prod", "eu-trd");
var hostNames = List.of("config1", "config2");
var allNodesInZone = new ArrayList<Node>();
@@ -139,7 +139,7 @@ public class ChangeManagementAssessorTest {
}
@Test
- public void one_of_three_proxy_nodes() {
+ void one_of_three_proxy_nodes() {
var zone = ZoneId.from("prod", "eu-trd");
var hostNames = List.of("routing1");
var allNodesInZone = new ArrayList<Node>();
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ChangeRequestMaintainerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ChangeRequestMaintainerTest.java
index 7607a4f602d..a20a2e26d22 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ChangeRequestMaintainerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ChangeRequestMaintainerTest.java
@@ -8,13 +8,13 @@ import com.yahoo.vespa.hosted.controller.api.integration.vcmr.ChangeRequestSourc
import com.yahoo.vespa.hosted.controller.api.integration.vcmr.ChangeRequestSource.Status;
import com.yahoo.vespa.hosted.controller.api.integration.vcmr.MockChangeRequestClient;
import com.yahoo.vespa.hosted.controller.api.integration.vcmr.VespaChangeRequest;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.ZonedDateTime;
import java.util.List;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author olaa
@@ -26,7 +26,7 @@ public class ChangeRequestMaintainerTest {
private final ChangeRequestMaintainer changeRequestMaintainer = new ChangeRequestMaintainer(tester.controller(), Duration.ofMinutes(1));
@Test
- public void updates_status_time_and_approval() {
+ void updates_status_time_and_approval() {
var time = ZonedDateTime.now();
var persistedChangeRequest = persistedChangeRequest("some-id", time.minusDays(5), Status.WAITING_FOR_APPROVAL);
tester.curator().writeChangeRequest(persistedChangeRequest);
@@ -43,7 +43,7 @@ public class ChangeRequestMaintainerTest {
}
@Test
- public void deletes_old_change_requests() {
+ void deletes_old_change_requests() {
var now = ZonedDateTime.now();
var before = now.minus(Duration.ofDays(8));
var newChangeRequest = persistedChangeRequest("new", now, Status.CLOSED);
@@ -60,7 +60,7 @@ public class ChangeRequestMaintainerTest {
}
@Test
- public void approves_change_request_if_non_prod() {
+ void approves_change_request_if_non_prod() {
var time = ZonedDateTime.now();
var prodChangeRequest = newChangeRequest("id1", ChangeRequest.Approval.REQUESTED, time, Status.WAITING_FOR_APPROVAL);
var nonProdApprovalRequested = newChangeRequest("id2", "unknown-node", ChangeRequest.Approval.REQUESTED, time, Status.WAITING_FOR_APPROVAL);
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/CloudTrialExpirerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/CloudTrialExpirerTest.java
index 187b8f932cf..5ecf28ce7e6 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/CloudTrialExpirerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/CloudTrialExpirerTest.java
@@ -12,13 +12,13 @@ import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester;
import com.yahoo.vespa.hosted.controller.integration.ZoneApiMock;
import com.yahoo.vespa.hosted.controller.tenant.LastLoginInfo;
import com.yahoo.vespa.hosted.controller.tenant.Tenant;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
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;
/**
* @author ogronnesby
@@ -30,35 +30,35 @@ public class CloudTrialExpirerTest {
private final CloudTrialExpirer expirer = new CloudTrialExpirer(tester.controller(), Duration.ofMinutes(5));
@Test
- public void expire_inactive_tenant() {
+ void expire_inactive_tenant() {
registerTenant("trial-tenant", "trial", Duration.ofDays(14).plusMillis(1));
expirer.maintain();
assertPlan("trial-tenant", "none");
}
@Test
- public void tombstone_inactive_none() {
+ void tombstone_inactive_none() {
registerTenant("none-tenant", "none", Duration.ofDays(365).plusMillis(1));
expirer.maintain();
assertEquals(Tenant.Type.deleted, tester.controller().tenants().get(TenantName.from("none-tenant"), true).get().type());
}
@Test
- public void keep_inactive_nontrial_tenants() {
+ void keep_inactive_nontrial_tenants() {
registerTenant("not-a-trial-tenant", "pay-as-you-go", Duration.ofDays(30));
expirer.maintain();
assertPlan("not-a-trial-tenant", "pay-as-you-go");
}
@Test
- public void keep_active_trial_tenants() {
+ void keep_active_trial_tenants() {
registerTenant("active-trial-tenant", "trial", Duration.ofHours(14).minusMillis(1));
expirer.maintain();
assertPlan("active-trial-tenant", "trial");
}
@Test
- public void keep_inactive_exempt_tenants() {
+ void keep_inactive_exempt_tenants() {
registerTenant("exempt-trial-tenant", "trial", Duration.ofDays(40));
((InMemoryFlagSource) tester.controller().flagSource()).withListFlag(PermanentFlags.EXTENDED_TRIAL_TENANTS.id(), List.of("exempt-trial-tenant"), String.class);
expirer.maintain();
@@ -66,7 +66,7 @@ public class CloudTrialExpirerTest {
}
@Test
- public void keep_inactive_trial_tenants_with_deployments() {
+ void keep_inactive_trial_tenants_with_deployments() {
registerTenant("with-deployments", "trial", Duration.ofDays(30));
registerDeployment("with-deployments", "my-app", "default");
expirer.maintain();
@@ -74,7 +74,7 @@ public class CloudTrialExpirerTest {
}
@Test
- public void delete_tenants_with_applications_with_no_deployments() {
+ void delete_tenants_with_applications_with_no_deployments() {
registerTenant("with-apps", "trial", Duration.ofDays(366));
tester.createApplication("with-apps", "app1", "instance1");
expirer.maintain();
@@ -84,7 +84,7 @@ public class CloudTrialExpirerTest {
}
@Test
- public void keep_tenants_without_applications_that_are_idle() {
+ void keep_tenants_without_applications_that_are_idle() {
registerTenant("active", "none", Duration.ofDays(364));
expirer.maintain();
assertPlan("active", "none");
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ContactInformationMaintainerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ContactInformationMaintainerTest.java
index 37b138527fe..f0c11c0ddbd 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ContactInformationMaintainerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ContactInformationMaintainerTest.java
@@ -6,8 +6,8 @@ import com.yahoo.vespa.hosted.controller.ControllerTester;
import com.yahoo.vespa.hosted.controller.api.identifiers.PropertyId;
import com.yahoo.vespa.hosted.controller.api.integration.organization.Contact;
import com.yahoo.vespa.hosted.controller.tenant.AthenzTenant;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.time.Duration;
@@ -16,8 +16,8 @@ import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;
-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 mpolden
@@ -27,30 +27,32 @@ public class ContactInformationMaintainerTest {
private ControllerTester tester;
private ContactInformationMaintainer maintainer;
- @Before
+ @BeforeEach
public void before() {
tester = new ControllerTester();
maintainer = new ContactInformationMaintainer(tester.controller(), Duration.ofDays(1));
}
@Test
- public void updates_contact_information() {
+ void updates_contact_information() {
PropertyId propertyId1 = new PropertyId("1");
PropertyId propertyId2 = new PropertyId("2");
TenantName name1 = tester.createTenant("tenant1", "domain1", 1L);
TenantName name2 = tester.createTenant("zenant1", "domain2", 2L);
Supplier<AthenzTenant> tenant1 = () -> (AthenzTenant) tester.controller().tenants().require(name1);
Supplier<AthenzTenant> tenant2 = () -> (AthenzTenant) tester.controller().tenants().require(name2);
- assertFalse("No contact information initially", tenant1.get().contact().isPresent());
- assertFalse("No contact information initially", tenant2.get().contact().isPresent());
+ assertFalse(tenant1.get().contact().isPresent(), "No contact information initially");
+ assertFalse(tenant2.get().contact().isPresent(), "No contact information initially");
Contact contact = testContact();
- tester.serviceRegistry().contactRetriever().addContact(propertyId1, () -> { throw new RuntimeException("ERROR"); });
+ tester.serviceRegistry().contactRetriever().addContact(propertyId1, () -> {
+ throw new RuntimeException("ERROR");
+ });
tester.serviceRegistry().contactRetriever().addContact(propertyId2, () -> contact);
maintainer.maintain();
- assertEquals("No contact information added due to error", Optional.empty(), tenant1.get().contact());
- assertEquals("Contact information added", Optional.of(contact), tenant2.get().contact());
+ assertEquals(Optional.empty(), tenant1.get().contact(), "No contact information added due to error");
+ assertEquals(Optional.of(contact), tenant2.get().contact(), "Contact information added");
}
private static Contact testContact() {
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ControllerMaintainerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ControllerMaintainerTest.java
index a452d550488..63e2c99cb6e 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ControllerMaintainerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ControllerMaintainerTest.java
@@ -5,14 +5,14 @@ import com.yahoo.config.provision.SystemName;
import com.yahoo.vespa.hosted.controller.Controller;
import com.yahoo.vespa.hosted.controller.ControllerTester;
import com.yahoo.vespa.hosted.controller.integration.MetricsMock;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.EnumSet;
import java.util.concurrent.atomic.AtomicInteger;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author mpolden
@@ -21,13 +21,13 @@ public class ControllerMaintainerTest {
private ControllerTester tester;
- @Before
+ @BeforeEach
public void before() {
tester = new ControllerTester();
}
@Test
- public void only_runs_in_permitted_systems() {
+ void only_runs_in_permitted_systems() {
AtomicInteger executions = new AtomicInteger();
new TestControllerMaintainer(tester.controller(), SystemName.cd, executions).run();
new TestControllerMaintainer(tester.controller(), SystemName.main, executions).run();
@@ -35,7 +35,7 @@ public class ControllerMaintainerTest {
}
@Test
- public void records_metric() {
+ void records_metric() {
TestControllerMaintainer maintainer = new TestControllerMaintainer(tester.controller(), SystemName.main, new AtomicInteger());
maintainer.run();
assertEquals(1.0, successFactorMetric(), 0.0000001);
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/CostReportMaintainerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/CostReportMaintainerTest.java
index 294272041b6..7cfe5dee3de 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/CostReportMaintainerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/CostReportMaintainerTest.java
@@ -7,13 +7,13 @@ import com.yahoo.vespa.hosted.controller.api.identifiers.Property;
import com.yahoo.vespa.hosted.controller.api.integration.resource.CostReportConsumerMock;
import com.yahoo.vespa.hosted.controller.api.integration.resource.ResourceAllocation;
import com.yahoo.vespa.hosted.controller.integration.ZoneApiMock;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author ldalves
@@ -23,7 +23,7 @@ public class CostReportMaintainerTest {
private final ControllerTester tester = new ControllerTester();
@Test
- public void maintain() {
+ void maintain() {
tester.clock().setInstant(Instant.EPOCH);
tester.zoneRegistry().setZones(
ZoneApiMock.newBuilder().withId("prod.us-east-3").withCloud("yahoo").build(),
@@ -35,9 +35,9 @@ public class CostReportMaintainerTest {
CostReportConsumerMock costReportConsumer = new CostReportConsumerMock(
(csv) -> assertEquals(
"Date,Property,Reserved Cpu Cores,Reserved Memory GB,Reserved Disk Space GB,Usage Fraction\n" +
- "1970-01-01,Property1,96.0,96.0,2000.0,0.3055555555555555\n" +
- "1970-01-01,Property3,128.0,96.0,2000.0,0.3333333333333333\n" +
- "1970-01-01,Property2,160.0,96.0,2000.0,0.3611111111111111",
+ "1970-01-01,Property1,96.0,96.0,2000.0,0.3055555555555555\n" +
+ "1970-01-01,Property3,128.0,96.0,2000.0,0.3333333333333333\n" +
+ "1970-01-01,Property2,160.0,96.0,2000.0,0.3611111111111111",
csv),
Map.of(new Property("Property3"), new ResourceAllocation(256, 192, 4000, NodeResources.Architecture.getDefault()))
);
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/DeploymentExpirerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/DeploymentExpirerTest.java
index 10a8bb79c2e..0c238ea7c9d 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/DeploymentExpirerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/DeploymentExpirerTest.java
@@ -12,13 +12,13 @@ import com.yahoo.vespa.hosted.controller.deployment.DeploymentContext;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester;
import com.yahoo.vespa.hosted.controller.deployment.Run;
import com.yahoo.vespa.hosted.controller.deployment.RunStatus;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.Optional;
-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 bratseth
@@ -28,7 +28,7 @@ public class DeploymentExpirerTest {
private final DeploymentTester tester = new DeploymentTester();
@Test
- public void testDeploymentExpiry() {
+ void testDeploymentExpiry() {
ZoneId devZone = ZoneId.from(Environment.dev, RegionName.from("us-east-1"));
tester.controllerTester().zoneRegistry().setDeploymentTimeToLive(devZone, Duration.ofDays(14));
DeploymentExpirer expirer = new DeploymentExpirer(tester.controller(), Duration.ofDays(1));
@@ -59,9 +59,10 @@ public class DeploymentExpirerTest {
Run lastRun = tester.jobs().last(devApp.instanceId(), DeploymentContext.devUsEast1).get();
assertSame(RunStatus.error, lastRun.status());
Deployment deployment = tester.applications().requireInstance(devApp.instanceId())
- .deployments().get(devZone);
- assertEquals("Time of last run is after time of deployment", Duration.ofDays(12),
- Duration.between(deployment.at(), lastRun.end().get()));
+ .deployments().get(devZone);
+ assertEquals(Duration.ofDays(12),
+ Duration.between(deployment.at(), lastRun.end().get()),
+ "Time of last run is after time of deployment");
// Dev application does not expire based on time of successful deployment
tester.clock().advance(Duration.ofDays(2));
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/DeploymentIssueReporterTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/DeploymentIssueReporterTest.java
index 637a8832533..2f84b58dbae 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/DeploymentIssueReporterTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/DeploymentIssueReporterTest.java
@@ -13,8 +13,8 @@ import com.yahoo.vespa.hosted.controller.application.pkg.ApplicationPackage;
import com.yahoo.vespa.hosted.controller.deployment.ApplicationPackageBuilder;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester;
import com.yahoo.vespa.hosted.controller.versions.VespaVersion;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.HashMap;
@@ -27,9 +27,9 @@ import static com.yahoo.vespa.hosted.controller.deployment.DeploymentContext.sys
import static com.yahoo.vespa.hosted.controller.maintenance.DeploymentIssueReporter.maxFailureAge;
import static com.yahoo.vespa.hosted.controller.maintenance.DeploymentIssueReporter.maxInactivity;
import static com.yahoo.vespa.hosted.controller.maintenance.DeploymentIssueReporter.upgradeGracePeriod;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author jonmv
@@ -48,7 +48,7 @@ public class DeploymentIssueReporterTest {
private DeploymentIssueReporter reporter;
private MockDeploymentIssues issues;
- @Before
+ @BeforeEach
public void setup() {
tester = new DeploymentTester();
issues = new MockDeploymentIssues();
@@ -56,7 +56,7 @@ public class DeploymentIssueReporterTest {
}
@Test
- public void nonProductionAppGetsNoIssues() {
+ void nonProductionAppGetsNoIssues() {
tester.controllerTester().upgradeSystem(Version.fromString("6.2"));
var app = tester.newDeploymentContext("application", "tenant", "default");
Contact contact = tester.controllerTester().serviceRegistry().contactRetrieverMock().contact();
@@ -68,11 +68,11 @@ public class DeploymentIssueReporterTest {
// Advance to where deployment issues should be detected.
tester.clock().advance(maxFailureAge.plus(Duration.ofDays(1)));
- assertFalse("No issues are produced for app.", issues.isOpenFor(app.application().id()));
+ assertFalse(issues.isOpenFor(app.application().id()), "No issues are produced for app.");
}
@Test
- public void testDeploymentFailureReporting() {
+ void testDeploymentFailureReporting() {
tester.controllerTester().upgradeSystem(Version.fromString("6.2"));
// Create and deploy one application for each of three tenants.
@@ -102,7 +102,7 @@ public class DeploymentIssueReporterTest {
reporter.maintain();
reporter.maintain();
- assertEquals("No deployments are detected as failing for a long time initially.", 0, issues.size());
+ assertEquals(0, issues.size(), "No deployments are detected as failing for a long time initially.");
// Advance to where deployment issues should be detected.
@@ -110,18 +110,18 @@ public class DeploymentIssueReporterTest {
reporter.maintain();
reporter.maintain();
- assertTrue("One issue is produced for app1.", issues.isOpenFor(app1.application().id()));
- assertFalse("No issues are produced for app2.", issues.isOpenFor(app2.application().id()));
- assertTrue("One issue is produced for app3.", issues.isOpenFor(app3.application().id()));
+ assertTrue(issues.isOpenFor(app1.application().id()), "One issue is produced for app1.");
+ assertFalse(issues.isOpenFor(app2.application().id()), "No issues are produced for app2.");
+ assertTrue(issues.isOpenFor(app3.application().id()), "One issue is produced for app3.");
// app3 closes their issue prematurely; see that it is refiled.
issues.closeFor(app3.application().id());
- assertFalse("No issue is open for app3.", issues.isOpenFor(app3.application().id()));
+ assertFalse(issues.isOpenFor(app3.application().id()), "No issue is open for app3.");
reporter.maintain();
reporter.maintain();
- assertTrue("Issue is re-filed for app3.", issues.isOpenFor(app3.application().id()));
+ assertTrue(issues.isOpenFor(app3.application().id()), "Issue is re-filed for app3.");
// Some time passes; tenant1 leaves her issue unattended, while tenant3 starts work and updates the issue.
tester.clock().advance(maxInactivity.plus(maxFailureAge));
@@ -129,7 +129,7 @@ public class DeploymentIssueReporterTest {
reporter.maintain();
reporter.maintain();
- assertEquals("The issue for app1 is escalated once.", 1, issues.escalationLevelFor(app1.application().id()));
+ assertEquals(1, issues.escalationLevelFor(app1.application().id()), "The issue for app1 is escalated once.");
// app3 fixes their problems, but the ticket for app3 is left open; see the resolved ticket is not escalated when another escalation period has passed.
@@ -138,9 +138,9 @@ public class DeploymentIssueReporterTest {
reporter.maintain();
reporter.maintain();
- assertFalse("We no longer have a platform issue.", issues.platformIssue());
- assertEquals("The issue for app1 is escalated once more.", 2, issues.escalationLevelFor(app1.application().id()));
- assertEquals("The issue for app3 is not escalated.", 0, issues.escalationLevelFor(app3.application().id()));
+ assertFalse(issues.platformIssue(), "We no longer have a platform issue.");
+ assertEquals(2, issues.escalationLevelFor(app1.application().id()), "The issue for app1 is escalated once more.");
+ assertEquals(0, issues.escalationLevelFor(app3.application().id()), "The issue for app3 is not escalated.");
// app3 now has a new failure past max failure age; see that a new issue is filed.
@@ -149,7 +149,7 @@ public class DeploymentIssueReporterTest {
reporter.maintain();
reporter.maintain();
- assertTrue("A new issue is filed for app3.", issues.isOpenFor(app3.application().id()));
+ assertTrue(issues.isOpenFor(app3.application().id()), "A new issue is filed for app3.");
// app2 is changed to be a canary
@@ -167,15 +167,15 @@ public class DeploymentIssueReporterTest {
tester.controllerTester().upgradeSystem(version);
assertEquals(VespaVersion.Confidence.broken, tester.controller().readVersionStatus().systemVersion().get().confidence());
- assertFalse("We have no platform issues initially.", issues.platformIssue());
+ assertFalse(issues.platformIssue(), "We have no platform issues initially.");
reporter.maintain();
reporter.maintain();
- assertFalse("We have no platform issue before the grace period is out for the failing canary.", issues.platformIssue());
+ assertFalse(issues.platformIssue(), "We have no platform issue before the grace period is out for the failing canary.");
tester.clock().advance(upgradeGracePeriod.plus(upgradeGracePeriod));
reporter.maintain();
reporter.maintain();
- assertTrue("We get a platform issue when confidence is broken", issues.platformIssue());
- assertFalse("No deployment issue is filed for app2, which has a version upgrade failure.", issues.isOpenFor(app2.application().id()));
+ assertTrue(issues.platformIssue(), "We get a platform issue when confidence is broken");
+ assertFalse(issues.isOpenFor(app2.application().id()), "No deployment issue is filed for app2, which has a version upgrade failure.");
app2.runJob(systemTest);
tester.controllerTester().upgradeSystem(version);
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/DeploymentMetricsMaintainerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/DeploymentMetricsMaintainerTest.java
index 112519bb717..6ac0509c0f8 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/DeploymentMetricsMaintainerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/DeploymentMetricsMaintainerTest.java
@@ -13,7 +13,7 @@ import com.yahoo.vespa.hosted.controller.application.DeploymentMetrics;
import com.yahoo.vespa.hosted.controller.application.pkg.ApplicationPackage;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentContext;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
@@ -23,8 +23,8 @@ import java.util.Map;
import java.util.function.Supplier;
import static java.time.temporal.ChronoUnit.MILLIS;
-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 smorgrav
@@ -35,7 +35,7 @@ public class DeploymentMetricsMaintainerTest {
private final DeploymentTester tester = new DeploymentTester();
@Test
- public void updates_metrics() {
+ void updates_metrics() {
var application = tester.newDeploymentContext();
application.runJob(DeploymentContext.devUsEast1, new ApplicationPackage(new byte[0]), Version.fromString("7.1"));
@@ -46,17 +46,17 @@ public class DeploymentMetricsMaintainerTest {
// No metrics gathered yet
assertEquals(0, app.get().metrics().queryServiceQuality(), 0);
assertEquals(0, deployment.get().metrics().documentCount(), 0);
- assertFalse("No timestamp set", deployment.get().metrics().instant().isPresent());
- assertFalse("Never received any queries", deployment.get().activity().lastQueried().isPresent());
- assertFalse("Never received any writes", deployment.get().activity().lastWritten().isPresent());
+ assertFalse(deployment.get().metrics().instant().isPresent(), "No timestamp set");
+ assertFalse(deployment.get().activity().lastQueried().isPresent(), "Never received any queries");
+ assertFalse(deployment.get().activity().lastWritten().isPresent(), "Never received any writes");
// Metrics are gathered and saved to application
application.runJob(DeploymentContext.devUsEast1, new ApplicationPackage(new byte[0]), Version.fromString("7.5.5"));
var metrics0 = Map.of(ClusterMetrics.QUERIES_PER_SECOND, 1D,
- ClusterMetrics.FEED_PER_SECOND, 2D,
- ClusterMetrics.DOCUMENT_COUNT, 3D,
- ClusterMetrics.QUERY_LATENCY, 4D,
- ClusterMetrics.FEED_LATENCY, 5D);
+ ClusterMetrics.FEED_PER_SECOND, 2D,
+ ClusterMetrics.DOCUMENT_COUNT, 3D,
+ ClusterMetrics.QUERY_LATENCY, 4D,
+ ClusterMetrics.FEED_LATENCY, 5D);
setMetrics(application.application().id().defaultInstance(), metrics0);
maintainer.maintain();
Instant t1 = tester.clock().instant().truncatedTo(MILLIS);
@@ -107,7 +107,7 @@ public class DeploymentMetricsMaintainerTest {
}
@Test
- public void cluster_metric_aggregation_test() {
+ void cluster_metric_aggregation_test() {
List<ClusterMetrics> clusterMetrics = List.of(
new ClusterMetrics("niceCluster", "container", Map.of("queriesPerSecond", 23.0, "queryLatency", 1337.0), Map.of()),
new ClusterMetrics("alsoNiceCluster", "container", Map.of("queriesPerSecond", 11.0, "queryLatency", 12.0), Map.of()));
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/DeploymentUpgraderTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/DeploymentUpgraderTest.java
index 653ad2bb08a..df0afda838e 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/DeploymentUpgraderTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/DeploymentUpgraderTest.java
@@ -8,7 +8,7 @@ import com.yahoo.config.provision.zone.ZoneId;
import com.yahoo.vespa.hosted.controller.application.pkg.ApplicationPackage;
import com.yahoo.vespa.hosted.controller.deployment.ApplicationPackageBuilder;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
@@ -17,8 +17,8 @@ import static com.yahoo.vespa.hosted.controller.deployment.DeploymentContext.dev
import static com.yahoo.vespa.hosted.controller.deployment.DeploymentContext.productionUsWest1;
import static com.yahoo.vespa.hosted.controller.maintenance.DeploymentUpgrader.mostLikelyWeeHour;
import static java.time.temporal.ChronoUnit.MILLIS;
-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 jonmv
@@ -28,7 +28,7 @@ public class DeploymentUpgraderTest {
private final DeploymentTester tester = new DeploymentTester();
@Test
- public void testDeploymentUpgrading() {
+ void testDeploymentUpgrading() {
ZoneId devZone = ZoneId.from(Environment.dev, RegionName.from("us-east-1"));
DeploymentUpgrader upgrader = new DeploymentUpgrader(tester.controller(), Duration.ofDays(1));
var devApp = tester.newDeploymentContext("tenant1", "app1", "default");
@@ -76,11 +76,11 @@ public class DeploymentUpgraderTest {
}
@Test
- public void testNight() {
- assertEquals(16, mostLikelyWeeHour(new int[]{ 0, 1, 2, 3, 4, 5, 6 }));
- assertEquals(14, mostLikelyWeeHour(new int[]{ 22, 23, 0, 1, 2, 3, 4 }));
- assertEquals(18, mostLikelyWeeHour(new int[]{ 6, 5, 4, 3, 2, 1, 0 }));
- assertEquals(20, mostLikelyWeeHour(new int[]{ 0, 12, 0, 12, 0, 12, 0, 12, 0, 12, 0, 11 }));
+ void testNight() {
+ assertEquals(16, mostLikelyWeeHour(new int[]{0, 1, 2, 3, 4, 5, 6}));
+ assertEquals(14, mostLikelyWeeHour(new int[]{22, 23, 0, 1, 2, 3, 4}));
+ assertEquals(18, mostLikelyWeeHour(new int[]{6, 5, 4, 3, 2, 1, 0}));
+ assertEquals(20, mostLikelyWeeHour(new int[]{0, 12, 0, 12, 0, 12, 0, 12, 0, 12, 0, 11}));
}
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/EndpointCertificateMaintainerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/EndpointCertificateMaintainerTest.java
index 6bcb4284a14..c103894b1a3 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/EndpointCertificateMaintainerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/EndpointCertificateMaintainerTest.java
@@ -9,7 +9,7 @@ import com.yahoo.vespa.hosted.controller.deployment.ApplicationPackageBuilder;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentContext;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester;
import com.yahoo.vespa.hosted.controller.integration.SecretStoreMock;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.List;
@@ -18,9 +18,9 @@ import java.util.Optional;
import static com.yahoo.vespa.hosted.controller.deployment.DeploymentContext.productionUsWest1;
import static com.yahoo.vespa.hosted.controller.deployment.DeploymentContext.stagingTest;
import static com.yahoo.vespa.hosted.controller.deployment.DeploymentContext.systemTest;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author andreer
@@ -33,14 +33,14 @@ public class EndpointCertificateMaintainerTest {
private final EndpointCertificateMetadata exampleMetadata = new EndpointCertificateMetadata("keyName", "certName", 0, 0, "root-request-uuid", Optional.of("leaf-request-uuid"), List.of(), "issuer", Optional.empty(), Optional.empty());
@Test
- public void old_and_unused_cert_is_deleted() {
+ void old_and_unused_cert_is_deleted() {
tester.curator().writeEndpointCertificateMetadata(ApplicationId.defaultId(), exampleMetadata);
assertEquals(1.0, maintainer.maintain(), 0.0000001);
assertTrue(tester.curator().readEndpointCertificateMetadata(ApplicationId.defaultId()).isEmpty());
}
@Test
- public void unused_but_recently_used_cert_is_not_deleted() {
+ void unused_but_recently_used_cert_is_not_deleted() {
EndpointCertificateMetadata recentlyRequestedCert = exampleMetadata.withLastRequested(tester.clock().instant().minusSeconds(3600).getEpochSecond());
tester.curator().writeEndpointCertificateMetadata(ApplicationId.defaultId(), recentlyRequestedCert);
assertEquals(1.0, maintainer.maintain(), 0.0000001);
@@ -48,7 +48,7 @@ public class EndpointCertificateMaintainerTest {
}
@Test
- public void refreshed_certificate_is_updated() {
+ void refreshed_certificate_is_updated() {
EndpointCertificateMetadata recentlyRequestedCert = exampleMetadata.withLastRequested(tester.clock().instant().minusSeconds(3600).getEpochSecond());
tester.curator().writeEndpointCertificateMetadata(ApplicationId.defaultId(), recentlyRequestedCert);
@@ -63,7 +63,7 @@ public class EndpointCertificateMaintainerTest {
}
@Test
- public void certificate_in_use_is_not_deleted() {
+ void certificate_in_use_is_not_deleted() {
var appId = ApplicationId.from("tenant", "application", "default");
DeploymentTester deploymentTester = new DeploymentTester(tester);
@@ -82,7 +82,7 @@ public class EndpointCertificateMaintainerTest {
}
@Test
- public void refreshed_certificate_is_discovered_and_after_four_days_deployed() {
+ void refreshed_certificate_is_discovered_and_after_four_days_deployed() {
var appId = ApplicationId.from("tenant", "application", "default");
DeploymentTester deploymentTester = new DeploymentTester(tester);
@@ -111,7 +111,7 @@ public class EndpointCertificateMaintainerTest {
deploymentContext.assertNotRunning(productionUsWest1);
var updatedMetadata = tester.curator().readEndpointCertificateMetadata(appId).orElseThrow();
assertNotEquals(originalMetadata.leafRequestId().orElseThrow(), updatedMetadata.leafRequestId().orElseThrow());
- assertEquals(updatedMetadata.version(), originalMetadata.version()+1);
+ assertEquals(updatedMetadata.version(), originalMetadata.version() + 1);
// after another 4 days, we should force trigger deployment if it hasn't already happened
tester.clock().advance(Duration.ofDays(4).plusSeconds(1));
@@ -121,7 +121,7 @@ public class EndpointCertificateMaintainerTest {
}
@Test
- public void unmaintained_cert_is_deleted() {
+ void unmaintained_cert_is_deleted() {
EndpointCertificateMock endpointCertificateProvider = (EndpointCertificateMock) tester.controller().serviceRegistry().endpointCertificateProvider();
ApplicationId unknown = ApplicationId.fromSerializedForm("applicationid:is:unknown");
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/HostInfoUpdaterTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/HostInfoUpdaterTest.java
index 890f0b41098..1ef32b8e347 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/HostInfoUpdaterTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/HostInfoUpdaterTest.java
@@ -8,15 +8,15 @@ import com.yahoo.vespa.hosted.controller.ControllerTester;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.Node;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.NodeFilter;
import com.yahoo.vespa.hosted.controller.api.integration.entity.NodeEntity;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.ArrayList;
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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author mpolden
@@ -25,7 +25,7 @@ import static org.junit.Assert.assertTrue;
public class HostInfoUpdaterTest {
@Test
- public void maintain() {
+ void maintain() {
ControllerTester tester = new ControllerTester();
tester.serviceRegistry().configServer().nodeRepository().allowPatching(true);
addNodeEntities(tester);
@@ -36,8 +36,8 @@ public class HostInfoUpdaterTest {
List<Node> nodes = allNodes(tester);
assertFalse(nodes.isEmpty());
for (var node : nodes) {
- assertEquals("Node " + node.hostname().value() + (node.type().isHost() ? " has" : " does not have")
- + " switch hostname", node.type().isHost(), node.switchHostname().isPresent());
+ assertEquals(node.type().isHost(), node.switchHostname().isPresent(), "Node " + node.hostname().value() + (node.type().isHost() ? " has" : " does not have")
+ + " switch hostname");
if (node.type().isHost()) {
assertEquals("tor-" + node.hostname().value(), node.switchHostname().get());
}
@@ -85,18 +85,18 @@ public class HostInfoUpdaterTest {
ZoneId zone = tester.zoneRegistry().zones().controllerUpgraded().all().ids().get(0);
String hostnameSuffix = ".prod." + zone.value();
Node configNode = Node.builder().hostname(HostName.of("cfg3" + hostnameSuffix))
- .type(NodeType.config)
- .build();
+ .type(NodeType.config)
+ .build();
Node configHost = Node.builder().hostname(HostName.of("cfghost3" + hostnameSuffix))
- .type(NodeType.confighost)
- .build();
+ .type(NodeType.confighost)
+ .build();
tester.serviceRegistry().configServer().nodeRepository().putNodes(zone, List.of(configNode, configHost));
String switchHostname = switchHostname(configHost);
NodeEntity configNodeEntity = new NodeEntity("cfg3" + hostnameSuffix, "RD350G", "Lenovo", switchHostname);
tester.serviceRegistry().entityService().addNodeEntity(configNodeEntity);
maintainer.maintain();
assertEquals(switchHostname, getNode(configHost.hostname(), tester).switchHostname().get());
- assertTrue("Switch hostname is not set for non-host", getNode(configNode.hostname(), tester).switchHostname().isEmpty());
+ assertTrue(getNode(configNode.hostname(), tester).switchHostname().isEmpty(), "Switch hostname is not set for non-host");
}
private static Node getNode(HostName hostname, ControllerTester tester) {
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/JobRunnerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/JobRunnerTest.java
index b9ced334e5a..e7e542d2b82 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/JobRunnerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/JobRunnerTest.java
@@ -21,7 +21,7 @@ import com.yahoo.vespa.hosted.controller.deployment.StepRunner;
import com.yahoo.vespa.hosted.controller.deployment.Submission;
import com.yahoo.vespa.hosted.controller.deployment.Versions;
import com.yahoo.vespa.hosted.controller.integration.MetricsMock;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.Collections;
@@ -63,12 +63,12 @@ import static com.yahoo.vespa.hosted.controller.deployment.Step.installReal;
import static com.yahoo.vespa.hosted.controller.deployment.Step.installTester;
import static com.yahoo.vespa.hosted.controller.deployment.Step.report;
import static com.yahoo.vespa.hosted.controller.deployment.Step.startTests;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotSame;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author jonmv
@@ -82,10 +82,10 @@ public class JobRunnerTest {
Optional.empty());
@Test
- public void multiThreadedExecutionFinishes() {
+ void multiThreadedExecutionFinishes() {
DeploymentTester tester = new DeploymentTester();
JobController jobs = tester.controller().jobController();
- StepRunner stepRunner = (step, id) -> id.type().equals(stagingTest) && step.get() == startTests? Optional.of(error) : Optional.of(running);
+ StepRunner stepRunner = (step, id) -> id.type().equals(stagingTest) && step.get() == startTests ? Optional.of(error) : Optional.of(running);
Phaser phaser = new Phaser(1);
JobRunner runner = new JobRunner(tester.controller(), Duration.ofDays(1), phasedExecutor(phaser), stepRunner);
@@ -98,7 +98,8 @@ public class JobRunnerTest {
start(jobs, id, systemTest);
fail("Job is already running, so this should not be allowed!");
}
- catch (IllegalArgumentException ignored) { }
+ catch (IllegalArgumentException ignored) {
+ }
start(jobs, id, stagingTest);
assertTrue(jobs.last(id, systemTest).get().stepStatuses().values().stream().allMatch(unfinished::equals));
@@ -118,7 +119,7 @@ public class JobRunnerTest {
}
@Test
- public void stepLogic() {
+ void stepLogic() {
DeploymentTester tester = new DeploymentTester();
JobController jobs = tester.controller().jobController();
Map<Step, RunStatus> outcomes = new EnumMap<>(Step.class);
@@ -225,7 +226,7 @@ public class JobRunnerTest {
}
@Test
- public void locksAndGarbage() throws InterruptedException, BrokenBarrierException {
+ void locksAndGarbage() throws InterruptedException, BrokenBarrierException {
DeploymentTester tester = new DeploymentTester();
JobController jobs = tester.controller().jobController();
// Hang during tester deployment, until notified.
@@ -242,10 +243,12 @@ public class JobRunnerTest {
runner.maintain();
barrier.await();
try {
- jobs.locked(id, systemTest, deactivateTester, step -> { });
+ jobs.locked(id, systemTest, deactivateTester, step -> {
+ });
fail("deployTester step should still be locked!");
}
- catch (TimeoutException ignored) { }
+ catch (TimeoutException ignored) {
+ }
// Thread is still trying to deploy tester -- delete application, and see all data is garbage collected.
assertEquals(Collections.singletonList(runId), jobs.active().stream().map(run -> run.id()).collect(Collectors.toList()));
@@ -264,7 +267,7 @@ public class JobRunnerTest {
}
@Test
- public void historyPruning() {
+ void historyPruning() {
DeploymentTester tester = new DeploymentTester();
JobController jobs = tester.controller().jobController();
JobRunner runner = new JobRunner(tester.controller(), Duration.ofDays(1), inThreadExecutor(), (id, step) -> Optional.of(running));
@@ -341,7 +344,7 @@ public class JobRunnerTest {
}
@Test
- public void onlySuccessfulRunExpiresThenAnotherFails() {
+ void onlySuccessfulRunExpiresThenAnotherFails() {
DeploymentTester tester = new DeploymentTester();
JobController jobs = tester.controller().jobController();
var app = tester.newDeploymentContext().submit();
@@ -360,7 +363,7 @@ public class JobRunnerTest {
}
@Test
- public void timeout() {
+ void timeout() {
DeploymentTester tester = new DeploymentTester();
JobController jobs = tester.controller().jobController();
Map<Step, RunStatus> outcomes = new EnumMap<>(Step.class);
@@ -378,7 +381,7 @@ public class JobRunnerTest {
}
@Test
- public void jobMetrics() throws TimeoutException {
+ void jobMetrics() throws TimeoutException {
DeploymentTester tester = new DeploymentTester();
JobController jobs = tester.controller().jobController();
Map<Step, RunStatus> outcomes = new EnumMap<>(Step.class);
@@ -401,10 +404,10 @@ public class JobRunnerTest {
}
Map<String, String> context = Map.of("applicationId", "tenant.real.default",
- "tenantName", "tenant",
- "app", "real.default",
- "test", "true",
- "zone", "test.us-east-1");
+ "tenantName", "tenant",
+ "app", "real.default",
+ "test", "true",
+ "zone", "test.us-east-1");
MetricsMock metric = ((MetricsMock) tester.controller().metric());
assertEquals(RunStatus.values().length - 2, metric.getMetric(context::equals, JobMetrics.start).get().intValue());
assertEquals(1, metric.getMetric(context::equals, JobMetrics.abort).get().intValue());
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/MeteringMonitorMaintainerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/MeteringMonitorMaintainerTest.java
index 225b7cb1d5e..65dab67663e 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/MeteringMonitorMaintainerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/MeteringMonitorMaintainerTest.java
@@ -8,15 +8,15 @@ import com.yahoo.vespa.hosted.controller.api.integration.billing.PlanRegistryMoc
import com.yahoo.vespa.hosted.controller.api.integration.resource.ResourceDatabaseClientMock;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester;
import com.yahoo.vespa.hosted.controller.integration.MetricsMock;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
import java.util.Map;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author olaa
@@ -31,7 +31,7 @@ public class MeteringMonitorMaintainerTest {
private final ApplicationId applicationId = ApplicationId.from("foo", "bar", "default");
private final ZoneId zone = ZoneId.from("prod.aws-us-east-1c");
- @Before
+ @BeforeEach
public void setup() {
tester = new ControllerTester(SystemName.Public);
deploymentTester = new DeploymentTester(tester);
@@ -39,8 +39,9 @@ public class MeteringMonitorMaintainerTest {
database = new ResourceDatabaseClientMock(new PlanRegistryMock());
maintainer = new MeteringMonitorMaintainer(tester.controller(), Duration.ofMinutes(5), database, metrics);
}
+
@Test
- public void finds_stale_data() {
+ void finds_stale_data() {
deploymentTester.newDeploymentContext(applicationId).submit().deploy();
maintainer.maintain();
var now = tester.clock().instant().getEpochSecond();
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/MetricsReporterTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/MetricsReporterTest.java
index 215c03030a9..b41c17fcd33 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/MetricsReporterTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/MetricsReporterTest.java
@@ -28,7 +28,7 @@ import com.yahoo.vespa.hosted.controller.integration.MetricsMock;
import com.yahoo.vespa.hosted.controller.integration.ZoneApiMock;
import com.yahoo.vespa.hosted.controller.tenant.Tenant;
import com.yahoo.vespa.hosted.controller.versions.VespaVersion;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
@@ -43,9 +43,9 @@ import java.util.stream.Stream;
import static com.yahoo.vespa.hosted.controller.deployment.DeploymentContext.productionUsWest1;
import static com.yahoo.vespa.hosted.controller.deployment.DeploymentContext.stagingTest;
import static com.yahoo.vespa.hosted.controller.deployment.DeploymentContext.systemTest;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author mortent
@@ -56,7 +56,7 @@ public class MetricsReporterTest {
private final ZmsClientMock zmsClient = new ZmsClientMock(new AthenzDbMock(), AthenzIdentities.from("mock.identity"));
@Test
- public void audit_log_metric() {
+ void audit_log_metric() {
var tester = new ControllerTester();
MetricsReporter metricsReporter = createReporter(tester.controller());
@@ -114,7 +114,7 @@ public class MetricsReporterTest {
}
@Test
- public void deployment_fail_ratio() {
+ void deployment_fail_ratio() {
var tester = new DeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.region("us-west-1")
@@ -147,7 +147,7 @@ public class MetricsReporterTest {
}
@Test
- public void deployment_average_duration() {
+ void deployment_average_duration() {
var tester = new DeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.region("us-west-1")
@@ -156,8 +156,8 @@ public class MetricsReporterTest {
MetricsReporter reporter = createReporter(tester.controller());
var context = tester.newDeploymentContext()
- .submit(applicationPackage)
- .deploy();
+ .submit(applicationPackage)
+ .deploy();
reporter.maintain();
assertEquals(Duration.ZERO, getAverageDeploymentDuration(context.instanceId())); // An exceptionally fast deployment :-)
@@ -180,19 +180,19 @@ public class MetricsReporterTest {
// Another deployment starts and stalls for 12 hours
context.submit(applicationPackage)
- .triggerJobs();
+ .triggerJobs();
tester.clock().advance(Duration.ofHours(12));
reporter.maintain();
assertEquals(Duration.ofHours(12) // hanging system-test
- .plus(Duration.ofHours(12)) // hanging staging-test
- .plus(Duration.ofMinutes(90)) // previous production job
- .dividedBy(3), // Total number of orchestrated jobs
- getAverageDeploymentDuration(context.instanceId()));
+ .plus(Duration.ofHours(12)) // hanging staging-test
+ .plus(Duration.ofMinutes(90)) // previous production job
+ .dividedBy(3), // Total number of orchestrated jobs
+ getAverageDeploymentDuration(context.instanceId()));
}
@Test
- public void deployments_failing_upgrade() {
+ void deployments_failing_upgrade() {
var tester = new DeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.region("us-west-1")
@@ -208,40 +208,40 @@ public class MetricsReporterTest {
// Failing application change is not counted
context.submit(applicationPackage)
- .triggerJobs()
- .failDeployment(systemTest);
+ .triggerJobs()
+ .failDeployment(systemTest);
reporter.maintain();
assertEquals(0, getDeploymentsFailingUpgrade(context.instanceId()));
// Application change completes
context.deploy();
- assertFalse("Change deployed", context.instance().change().hasTargets());
+ assertFalse(context.instance().change().hasTargets(), "Change deployed");
// New versions is released and upgrade fails in test environments
Version version = Version.fromString("7.1");
tester.controllerTester().upgradeSystem(version);
tester.upgrader().maintain();
context.failDeployment(systemTest)
- .failDeployment(stagingTest);
+ .failDeployment(stagingTest);
reporter.maintain();
assertEquals(2, getDeploymentsFailingUpgrade(context.instanceId()));
// Test and staging pass and upgrade fails in production
context.runJob(systemTest)
- .runJob(stagingTest)
- .failDeployment(productionUsWest1);
+ .runJob(stagingTest)
+ .failDeployment(productionUsWest1);
reporter.maintain();
assertEquals(1, getDeploymentsFailingUpgrade(context.instanceId()));
// Upgrade eventually succeeds
context.runJob(productionUsWest1);
- assertFalse("Upgrade deployed", context.instance().change().hasTargets());
+ assertFalse(context.instance().change().hasTargets(), "Upgrade deployed");
reporter.maintain();
assertEquals(0, getDeploymentsFailingUpgrade(context.instanceId()));
}
@Test
- public void deployment_warnings_metric() {
+ void deployment_warnings_metric() {
var tester = new DeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.region("us-west-1")
@@ -257,22 +257,22 @@ public class MetricsReporterTest {
}
@Test
- public void build_time_reporting() {
+ void build_time_reporting() {
var tester = new DeploymentTester();
var applicationPackage = new ApplicationPackageBuilder().region("us-west-1").build();
var context = tester.newDeploymentContext()
- .submit(applicationPackage)
- .deploy();
+ .submit(applicationPackage)
+ .deploy();
assertEquals(1000, context.application().revisions().get(context.lastSubmission().get()).buildTime().get().toEpochMilli());
MetricsReporter reporter = createReporter(tester.controller());
reporter.maintain();
assertEquals(tester.clock().instant().getEpochSecond() - 1,
- getMetric(MetricsReporter.DEPLOYMENT_BUILD_AGE_SECONDS, context.instanceId()));
+ getMetric(MetricsReporter.DEPLOYMENT_BUILD_AGE_SECONDS, context.instanceId()));
}
@Test
- public void name_service_queue_size_metric() {
+ void name_service_queue_size_metric() {
var tester = new DeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.globalServiceId("default")
@@ -281,21 +281,21 @@ public class MetricsReporterTest {
.build();
MetricsReporter reporter = createReporter(tester.controller());
var context = tester.newDeploymentContext()
- .deferDnsUpdates();
+ .deferDnsUpdates();
reporter.maintain();
- assertEquals("Queue is empty initially", 0, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue());
+ assertEquals(0, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue(), "Queue is empty initially");
context.submit(applicationPackage).deploy();
reporter.maintain();
- assertEquals("Deployment queues name services requests", 2, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue());
+ assertEquals(2, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue(), "Deployment queues name services requests");
context.flushDnsUpdates();
reporter.maintain();
- assertEquals("Queue consumed", 0, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue());
+ assertEquals(0, metrics.getMetric(MetricsReporter.NAME_SERVICE_REQUESTS_QUEUED).intValue(), "Queue consumed");
}
@Test
- public void platform_change_duration() {
+ void platform_change_duration() {
var tester = new ControllerTester();
var reporter = createReporter(tester.controller());
var zone = ZoneId.from("prod.eu-west-1");
@@ -326,11 +326,12 @@ public class MetricsReporterTest {
assertPlatformChangeDuration(Duration.ZERO, hosts);
// 1/3 nodes upgrade within timeout
- assertEquals("Wanted version is raised for all nodes", version,
- getNodes(zone, hosts, tester).stream()
- .map(Node::wantedVersion)
- .min(Comparator.naturalOrder())
- .get());
+ assertEquals(version,
+ getNodes(zone, hosts, tester).stream()
+ .map(Node::wantedVersion)
+ .min(Comparator.naturalOrder())
+ .get(),
+ "Wanted version is raised for all nodes");
suspend(hosts, zone, tester);
var firstHost = hosts.get(0);
upgradeTo(version, List.of(firstHost), zone, tester);
@@ -351,7 +352,7 @@ public class MetricsReporterTest {
}
@Test
- public void os_change_duration() {
+ void os_change_duration() {
var tester = new ControllerTester();
var reporter = createReporter(tester.controller());
var zone = ZoneId.from("prod.eu-west-1");
@@ -389,12 +390,13 @@ public class MetricsReporterTest {
assertOsChangeDuration(Duration.ZERO, hosts);
// Nodes are told to upgrade, but do not suspend yet
- assertEquals("Wanted OS version is raised for all nodes", nextVersion,
- tester.configServer().nodeRepository().list(zone, NodeFilter.all().applications(SystemApplication.tenantHost.id())).stream()
- .map(Node::wantedOsVersion).min(Comparator.naturalOrder()).get());
- assertTrue("No nodes are suspended", tester.controller().serviceRegistry().configServer()
- .nodeRepository().list(zone, NodeFilter.all()).stream()
- .noneMatch(node -> node.serviceState() == Node.ServiceState.allowedDown));
+ assertEquals(nextVersion,
+ tester.configServer().nodeRepository().list(zone, NodeFilter.all().applications(SystemApplication.tenantHost.id())).stream()
+ .map(Node::wantedOsVersion).min(Comparator.naturalOrder()).get(),
+ "Wanted OS version is raised for all nodes");
+ assertTrue(tester.controller().serviceRegistry().configServer()
+ .nodeRepository().list(zone, NodeFilter.all()).stream()
+ .noneMatch(node -> node.serviceState() == Node.ServiceState.allowedDown), "No nodes are suspended");
// Another 30 minutes pass
tester.clock().advance(Duration.ofMinutes(30));
@@ -440,19 +442,19 @@ public class MetricsReporterTest {
// Dimensions used for node count metric are only known OS versions
Set<Version> versionDimensions = metrics.getMetrics((dimensions) -> true)
- .entrySet()
- .stream()
- .filter(kv -> kv.getValue().containsKey(MetricsReporter.OS_NODE_COUNT))
- .map(kv -> kv.getKey().getDimensions())
- .map(dimensions -> dimensions.get("currentVersion"))
- .map(Version::fromString)
- .collect(Collectors.toSet());
- assertTrue("Reports only OS versions", allVersions.containsAll(versionDimensions));
+ .entrySet()
+ .stream()
+ .filter(kv -> kv.getValue().containsKey(MetricsReporter.OS_NODE_COUNT))
+ .map(kv -> kv.getKey().getDimensions())
+ .map(dimensions -> dimensions.get("currentVersion"))
+ .map(Version::fromString)
+ .collect(Collectors.toSet());
+ assertTrue(allVersions.containsAll(versionDimensions), "Reports only OS versions");
}
}
@Test
- public void broken_system_version() {
+ void broken_system_version() {
var tester = new DeploymentTester().atMondayMorning();
var ctx = tester.newDeploymentContext();
var applicationPackage = new ApplicationPackageBuilder().upgradePolicy("canary").region("us-west-1").build();
@@ -485,7 +487,7 @@ public class MetricsReporterTest {
}
@Test
- public void tenant_counter() {
+ void tenant_counter() {
var tester = new ControllerTester(SystemName.Public);
tester.createTenant("foo", Tenant.Type.cloud);
tester.createTenant("bar", Tenant.Type.cloud);
@@ -501,17 +503,17 @@ public class MetricsReporterTest {
}
@Test
- public void overdue_upgrade_metric() {
+ void overdue_upgrade_metric() {
ApplicationPackage pkg = new ApplicationPackageBuilder().region("us-west-1")
- // window 1
- .blockChange(false, true, "mon-tue", "2-9", "CET")
- // window 2
- .blockChange(false, true, "mon-tue", "1-8,11-12", "CET")
- // window 3
- .blockChange(false, true, "wed-thu", "0-23", "CET")
- // window 4 (does not apply to upgrade)
- .blockChange(true, false, "mon-sun", "0-7", "CET")
- .build();
+ // window 1
+ .blockChange(false, true, "mon-tue", "2-9", "CET")
+ // window 2
+ .blockChange(false, true, "mon-tue", "1-8,11-12", "CET")
+ // window 3
+ .blockChange(false, true, "wed-thu", "0-23", "CET")
+ // window 4 (does not apply to upgrade)
+ .blockChange(true, false, "mon-sun", "0-7", "CET")
+ .build();
Instant mondayNight = Instant.parse("2021-12-13T23:30:00.00Z");
DeploymentTester tester = new DeploymentTester().at(mondayNight);
@@ -519,8 +521,8 @@ public class MetricsReporterTest {
DeploymentContext context = tester.newDeploymentContext();
Supplier<Duration> metric = () -> {
reporter.maintain();
- return Duration.ofSeconds(metrics.getMetric(context.instanceId(),MetricsReporter.DEPLOYMENT_OVERDUE_UPGRADE)
- .get().longValue());
+ return Duration.ofSeconds(metrics.getMetric(context.instanceId(), MetricsReporter.DEPLOYMENT_OVERDUE_UPGRADE)
+ .get().longValue());
};
// Deploy completely once
@@ -532,33 +534,33 @@ public class MetricsReporterTest {
// Start production job for upgrade, without completing it
context.runJob(systemTest)
- .runJob(stagingTest)
- .triggerJobs()
- .assertRunning(productionUsWest1);
- assertEquals("Upgrade is not overdue yet", Duration.ZERO, metric.get());
+ .runJob(stagingTest)
+ .triggerJobs()
+ .assertRunning(productionUsWest1);
+ assertEquals(Duration.ZERO, metric.get(), "Upgrade is not overdue yet");
// Upgrade continues into block window
tester.clock().advance(Duration.ofHours(1)); // Tuesday at 00:30 (01:30 CET)
- assertEquals("Upgrade is overdue measured relative to window 2", Duration.ofHours(0).plusMinutes(30), metric.get());
+ assertEquals(Duration.ofHours(0).plusMinutes(30), metric.get(), "Upgrade is overdue measured relative to window 2");
tester.clock().advance(Duration.ofHours(1)); // Tuesday at 01:30 (02:30 CET)
- assertEquals("Upgrade is overdue measured relative to window 2", Duration.ofHours(1).plusMinutes(30), metric.get());
+ assertEquals(Duration.ofHours(1).plusMinutes(30), metric.get(), "Upgrade is overdue measured relative to window 2");
tester.clock().advance(Duration.ofHours(1)); // Tuesday at 02:30 (03:30 CET)
- assertEquals("Upgrade is overdue measured relative to window 2", Duration.ofHours(2).plusMinutes(30), metric.get());
+ assertEquals(Duration.ofHours(2).plusMinutes(30), metric.get(), "Upgrade is overdue measured relative to window 2");
tester.clock().advance(Duration.ofHours(6)); // Tuesday at 08:30 (09:30 CET)
- assertEquals("Upgrade is overdue measured relative to window 1", Duration.ofHours(8).plusMinutes(30), metric.get());
+ assertEquals(Duration.ofHours(8).plusMinutes(30), metric.get(), "Upgrade is overdue measured relative to window 1");
tester.clock().advance(Duration.ofHours(1)); // Tuesday at 09:30 (10:30 CET)
- assertEquals("Upgrade is no longer overdue", Duration.ZERO, metric.get());
+ assertEquals(Duration.ZERO, metric.get(), "Upgrade is no longer overdue");
tester.clock().advance(Duration.ofDays(2)); // Thursday at 10:30 (11:30 CET)
- assertEquals("Upgrade is overdue measure relative to window 3", Duration.ofHours(34).plusMinutes(30), metric.get());
+ assertEquals(Duration.ofHours(34).plusMinutes(30), metric.get(), "Upgrade is overdue measure relative to window 3");
}
@Test
- public void zms_quota_metrics() {
+ void zms_quota_metrics() {
var tester = new ControllerTester();
var reporter = createReporter(tester.controller());
reporter.maintain();
@@ -576,7 +578,7 @@ public class MetricsReporterTest {
.map(Number::longValue)
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("Expected to find metric for version " + version));
- assertEquals("Expected number of nodes are on " + version.toFullString(), n, nodeCount);
+ assertEquals(n, nodeCount, "Expected number of nodes are on " + version.toFullString());
}
private void assertPlatformNodeCount(int n, Version version) {
@@ -647,15 +649,13 @@ public class MetricsReporterTest {
private void assertPlatformChangeDuration(Duration duration, List<Node> nodes) {
for (var node : nodes) {
- assertEquals("Platform change duration of " + node.hostname(),
- duration, getChangeDuration(MetricsReporter.PLATFORM_CHANGE_DURATION, node.hostname()));
+ assertEquals(duration, getChangeDuration(MetricsReporter.PLATFORM_CHANGE_DURATION, node.hostname()), "Platform change duration of " + node.hostname());
}
}
private void assertOsChangeDuration(Duration duration, List<Node> nodes) {
for (var node : nodes) {
- assertEquals("OS change duration of " + node.hostname(),
- duration, getChangeDuration(MetricsReporter.OS_CHANGE_DURATION, node.hostname()));
+ assertEquals(duration, getChangeDuration(MetricsReporter.OS_CHANGE_DURATION, node.hostname()), "OS change duration of " + node.hostname());
}
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/OsUpgradeSchedulerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/OsUpgradeSchedulerTest.java
index 621e847c0d3..9268ea5ca1c 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/OsUpgradeSchedulerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/OsUpgradeSchedulerTest.java
@@ -9,7 +9,7 @@ import com.yahoo.vespa.hosted.controller.ControllerTester;
import com.yahoo.vespa.hosted.controller.api.integration.deployment.OsRelease;
import com.yahoo.vespa.hosted.controller.integration.ZoneApiMock;
import com.yahoo.vespa.hosted.controller.versions.OsVersionTarget;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
@@ -18,8 +18,8 @@ import java.time.ZoneOffset;
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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author mpolden
@@ -27,7 +27,7 @@ import static org.junit.Assert.assertTrue;
public class OsUpgradeSchedulerTest {
@Test
- public void schedule_calendar_versioned_release() {
+ void schedule_calendar_versioned_release() {
ControllerTester tester = new ControllerTester();
OsUpgradeScheduler scheduler = new OsUpgradeScheduler(tester.controller(), Duration.ofDays(1));
Instant t0 = Instant.parse("2022-01-16T00:00:00.00Z"); // Outside trigger period
@@ -39,7 +39,7 @@ public class OsUpgradeSchedulerTest {
// Initial run does nothing as the cloud does not have a target
scheduler.maintain();
- assertTrue("No target set", tester.controller().osVersionTarget(cloud).isEmpty());
+ assertTrue(tester.controller().osVersionTarget(cloud).isEmpty(), "No target set");
// Target is set manually
Version version0 = Version.fromString("7.0.0.20220101");
@@ -56,12 +56,14 @@ public class OsUpgradeSchedulerTest {
Version version1 = Version.fromString("7.0.0.20220228");
tester.clock().advance(Duration.ofDays(30));
scheduler.maintain();
- assertEquals("Target is unchanged because we're outside trigger period", version0,
- tester.controller().osVersionTarget(cloud).get().osVersion().version());
+ assertEquals(version0,
+ tester.controller().osVersionTarget(cloud).get().osVersion().version(),
+ "Target is unchanged because we're outside trigger period");
tester.clock().advance(Duration.ofHours(7)); // Put us inside the trigger period
scheduler.maintain();
- assertEquals("New target set", version1,
- tester.controller().osVersionTarget(cloud).get().osVersion().version());
+ assertEquals(version1,
+ tester.controller().osVersionTarget(cloud).get().osVersion().version(),
+ "New target set");
// A few more days pass and target remains unchanged
tester.clock().advance(Duration.ofDays(2));
@@ -70,7 +72,7 @@ public class OsUpgradeSchedulerTest {
}
@Test
- public void schedule_stable_release() {
+ void schedule_stable_release() {
ControllerTester tester = new ControllerTester();
Instant t0 = Instant.parse("2021-06-21T07:00:00.00Z"); // Inside trigger period
tester.clock().setInstant(t0);
@@ -83,7 +85,7 @@ public class OsUpgradeSchedulerTest {
// Stable release is scheduled immediately
Version version1 = Version.fromString("8.1");
tester.serviceRegistry().artifactRepository().addRelease(new OsRelease(version1, OsRelease.Tag.stable,
- tester.clock().instant()));
+ tester.clock().instant()));
scheduleUpgradeAfter(Duration.ZERO, version1, tester);
// A newer version is triggered manually
@@ -95,7 +97,7 @@ public class OsUpgradeSchedulerTest {
}
@Test
- public void schedule_latest_release_in_cd() {
+ void schedule_latest_release_in_cd() {
ControllerTester tester = new ControllerTester(SystemName.cd);
Instant t0 = Instant.parse("2021-06-21T07:00:00.00Z"); // Inside trigger period
tester.clock().setInstant(t0);
@@ -108,7 +110,7 @@ public class OsUpgradeSchedulerTest {
// Latest release is not scheduled immediately
Version version1 = Version.fromString("8.1");
tester.serviceRegistry().artifactRepository().addRelease(new OsRelease(version1, OsRelease.Tag.latest,
- tester.clock().instant()));
+ tester.clock().instant()));
scheduleUpgradeAfter(Duration.ZERO, version0, tester);
// Cooldown period passes and latest release is scheduled
@@ -116,20 +118,20 @@ public class OsUpgradeSchedulerTest {
}
@Test
- public void schedule_of_calender_versioned_releases() {
+ void schedule_of_calender_versioned_releases() {
Map<String, String> tests = Map.of("2022-01-01", "2021-12-27",
- "2022-03-01", "2021-12-27",
- "2022-03-02", "2022-02-28",
- "2022-04-30", "2022-02-28",
- "2022-05-01", "2022-04-25",
- "2022-06-29", "2022-04-25",
- "2022-07-01", "2022-06-27",
- "2022-08-28", "2022-06-27",
- "2022-08-29", "2022-08-29");
+ "2022-03-01", "2021-12-27",
+ "2022-03-02", "2022-02-28",
+ "2022-04-30", "2022-02-28",
+ "2022-05-01", "2022-04-25",
+ "2022-06-29", "2022-04-25",
+ "2022-07-01", "2022-06-27",
+ "2022-08-28", "2022-06-27",
+ "2022-08-29", "2022-08-29");
tests.forEach((now, expectedVersion) -> {
Instant instant = LocalDate.parse(now).atStartOfDay().toInstant(ZoneOffset.UTC);
LocalDate dateOfWantedVersion = OsUpgradeScheduler.CalendarVersionedRelease.dateOfWantedVersion(instant);
- assertEquals("scheduled wanted version at " + now, LocalDate.parse(expectedVersion), dateOfWantedVersion);
+ assertEquals(LocalDate.parse(expectedVersion), dateOfWantedVersion, "scheduled wanted version at " + now);
});
}
@@ -139,8 +141,7 @@ public class OsUpgradeSchedulerTest {
CloudName cloud = tester.controller().clouds().iterator().next();
OsVersionTarget target = tester.controller().osVersionTarget(cloud).get();
assertEquals(version, target.osVersion().version());
- assertEquals("No budget when scheduling a tagged release",
- Duration.ZERO, target.upgradeBudget());
+ assertEquals(Duration.ZERO, target.upgradeBudget(), "No budget when scheduling a tagged release");
}
private static ZoneApi zone(String id, CloudName cloud) {
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/OsUpgraderTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/OsUpgraderTest.java
index 0b987bff6ce..a128bfb897d 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/OsUpgraderTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/OsUpgraderTest.java
@@ -13,7 +13,7 @@ import com.yahoo.vespa.hosted.controller.application.SystemApplication;
import com.yahoo.vespa.hosted.controller.integration.NodeRepositoryMock;
import com.yahoo.vespa.hosted.controller.integration.ZoneApiMock;
import com.yahoo.vespa.hosted.controller.versions.NodeVersion;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.Collection;
@@ -23,8 +23,8 @@ import java.util.function.UnaryOperator;
import java.util.stream.Collectors;
import java.util.stream.Stream;
-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 mpolden
@@ -35,7 +35,7 @@ public class OsUpgraderTest {
private final OsVersionStatusUpdater statusUpdater = new OsVersionStatusUpdater(tester.controller(), Duration.ofDays(1));
@Test
- public void upgrade_os() {
+ void upgrade_os() {
CloudName cloud1 = CloudName.from("c1");
CloudName cloud2 = CloudName.from("c2");
ZoneApi zone0 = zone("prod.us-north-42", "prod.controller", cloud1);
@@ -45,18 +45,18 @@ public class OsUpgraderTest {
ZoneApi zone4 = zone("prod.us-east-3", cloud1);
ZoneApi zone5 = zone("prod.us-north-1", cloud2);
UpgradePolicy upgradePolicy = UpgradePolicy.builder()
- .upgrade(zone0)
- .upgrade(zone1)
- .upgradeInParallel(zone2, zone3)
- .upgrade(zone5) // Belongs to a different cloud and is ignored by this upgrader
- .upgrade(zone4)
- .build();
+ .upgrade(zone0)
+ .upgrade(zone1)
+ .upgradeInParallel(zone2, zone3)
+ .upgrade(zone5) // Belongs to a different cloud and is ignored by this upgrader
+ .upgrade(zone4)
+ .build();
OsUpgrader osUpgrader = osUpgrader(upgradePolicy, cloud1, false);
// Bootstrap system
List<ZoneId> nonControllerZones = Stream.of(zone1, zone2, zone3, zone4, zone5)
- .map(ZoneApi::getVirtualId)
- .collect(Collectors.toList());
+ .map(ZoneApi::getVirtualId)
+ .collect(Collectors.toList());
tester.configServer().bootstrap(nonControllerZones, List.of(SystemApplication.tenantHost));
tester.configServer().addNodes(List.of(zone0.getVirtualId()), List.of(SystemApplication.controllerHost));
@@ -105,10 +105,11 @@ public class OsUpgraderTest {
// zone 2 and 3: completes upgrade
completeUpgrade(version1, SystemApplication.tenantHost, zone2, zone3);
- assertEquals("Current version is unchanged for node deferring OS upgrade", Version.emptyVersion,
- nodeRepository().list(zone2.getVirtualId(), NodeFilter.all().hostnames(nodeDeferringOsUpgrade.hostname()))
- .get(0)
- .currentOsVersion());
+ assertEquals(Version.emptyVersion,
+ nodeRepository().list(zone2.getVirtualId(), NodeFilter.all().hostnames(nodeDeferringOsUpgrade.hostname()))
+ .get(0)
+ .currentOsVersion(),
+ "Current version is unchanged for node deferring OS upgrade");
// zone 4: begins upgrading
osUpgrader.maintain();
@@ -121,14 +122,14 @@ public class OsUpgraderTest {
osUpgrader.maintain();
assertWanted(version1, SystemApplication.tenantHost, zone1, zone2, zone3, zone4);
statusUpdater.maintain();
- assertTrue("All non-deferring nodes are on target version",
- tester.controller().osVersionStatus().nodesIn(cloud1).stream()
- .filter(node -> !node.hostname().equals(nodeDeferringOsUpgrade.hostname()))
- .allMatch(node -> node.currentVersion().equals(version1)));
+ assertTrue(tester.controller().osVersionStatus().nodesIn(cloud1).stream()
+ .filter(node -> !node.hostname().equals(nodeDeferringOsUpgrade.hostname()))
+ .allMatch(node -> node.currentVersion().equals(version1)),
+ "All non-deferring nodes are on target version");
}
@Test
- public void upgrade_os_with_budget() {
+ void upgrade_os_with_budget() {
CloudName cloud = CloudName.from("cloud");
ZoneApi zone0 = zone("prod.us-north-42", "prod.controller", cloud);
ZoneApi zone1 = zone("dev.us-east-1", cloud);
@@ -136,17 +137,17 @@ public class OsUpgraderTest {
ZoneApi zone3 = zone("prod.us-central-1", cloud);
ZoneApi zone4 = zone("prod.eu-west-1", cloud);
UpgradePolicy upgradePolicy = UpgradePolicy.builder()
- .upgrade(zone0)
- .upgrade(zone1)
- .upgradeInParallel(zone2, zone3)
- .upgrade(zone4)
- .build();
+ .upgrade(zone0)
+ .upgrade(zone1)
+ .upgradeInParallel(zone2, zone3)
+ .upgrade(zone4)
+ .build();
OsUpgrader osUpgrader = osUpgrader(upgradePolicy, cloud, true);
// Bootstrap system
List<SystemApplication> nodeTypes = List.of(SystemApplication.configServerHost, SystemApplication.tenantHost);
tester.configServer().bootstrap(List.of(zone1.getId(), zone2.getId(), zone3.getId(), zone4.getId()),
- nodeTypes);
+ nodeTypes);
tester.configServer().addNodes(List.of(zone0.getVirtualId()), List.of(SystemApplication.controllerHost));
// Upgrade with budget
@@ -159,7 +160,7 @@ public class OsUpgraderTest {
// Controllers upgrade first
osUpgrader.maintain();
assertWanted(version, SystemApplication.controllerHost, zone0);
- assertEquals("Controller zone gets a zero budget", Duration.ZERO, upgradeBudget(zone0, SystemApplication.controllerHost, version));
+ assertEquals(Duration.ZERO, upgradeBudget(zone0, SystemApplication.controllerHost, version), "Controller zone gets a zero budget");
completeUpgrade(version, SystemApplication.controllerHost, zone0);
statusUpdater.maintain();
assertEquals(3, nodesOn(version).size());
@@ -175,8 +176,9 @@ public class OsUpgraderTest {
osUpgrader.maintain();
for (var zone : List.of(zone1, zone2, zone3)) {
for (var nodeType : nodeTypes) {
- assertEquals("Parallel prod zones share the budget of a single zone", Duration.ofHours(4),
- upgradeBudget(zone, nodeType, version));
+ assertEquals(Duration.ofHours(4),
+ upgradeBudget(zone, nodeType, version),
+ "Parallel prod zones share the budget of a single zone");
completeUpgrade(version, nodeType, zone);
}
}
@@ -184,31 +186,32 @@ public class OsUpgraderTest {
// Last zone upgrades
osUpgrader.maintain();
for (var nodeType : nodeTypes) {
- assertEquals(nodeType + " in last prod zone gets the budget of a single zone", Duration.ofHours(4),
- upgradeBudget(zone4, nodeType, version));
+ assertEquals(Duration.ofHours(4),
+ upgradeBudget(zone4, nodeType, version),
+ nodeType + " in last prod zone gets the budget of a single zone");
completeUpgrade(version, nodeType, zone4);
}
// All host applications upgraded
statusUpdater.maintain();
- assertTrue("All nodes on target version", tester.controller().osVersionStatus().nodesIn(cloud).stream()
- .allMatch(node -> node.currentVersion().equals(version)));
+ assertTrue(tester.controller().osVersionStatus().nodesIn(cloud).stream()
+ .allMatch(node -> node.currentVersion().equals(version)), "All nodes on target version");
}
@Test
- public void upgrade_os_nodes_choose_newer_version() {
+ void upgrade_os_nodes_choose_newer_version() {
CloudName cloud = CloudName.from("cloud");
ZoneApi zone1 = zone("dev.us-east-1", cloud);
ZoneApi zone2 = zone("prod.us-west-1", cloud);
UpgradePolicy upgradePolicy = UpgradePolicy.builder()
- .upgrade(zone1)
- .upgrade(zone2)
- .build();
+ .upgrade(zone1)
+ .upgrade(zone2)
+ .build();
OsUpgrader osUpgrader = osUpgrader(upgradePolicy, cloud, false);
// Bootstrap system
tester.configServer().bootstrap(List.of(zone1.getId(), zone2.getId()),
- List.of(SystemApplication.tenantHost));
+ List.of(SystemApplication.tenantHost));
// New OS version released
Version version = Version.fromString("7.1");
@@ -234,14 +237,14 @@ public class OsUpgraderTest {
// No more upgrades
osUpgrader.maintain();
assertWanted(version, SystemApplication.tenantHost, zone1, zone2);
- assertTrue("All nodes on target version or newer", tester.controller().osVersionStatus().nodesIn(cloud).stream()
- .noneMatch(node -> node.currentVersion().isBefore(version)));
+ assertTrue(tester.controller().osVersionStatus().nodesIn(cloud).stream()
+ .noneMatch(node -> node.currentVersion().isBefore(version)), "All nodes on target version or newer");
}
private Duration upgradeBudget(ZoneApi zone, SystemApplication application, Version version) {
var upgradeBudget = tester.configServer().nodeRepository().osUpgradeBudget(zone.getVirtualId(), application.nodeType(), version);
- assertTrue("Expected budget for upgrade to " + version + " of " + application.id() + " in " + zone.getVirtualId(),
- upgradeBudget.isPresent());
+ assertTrue(upgradeBudget.isPresent(),
+ "Expected budget for upgrade to " + version + " of " + application.id() + " in " + zone.getVirtualId());
return upgradeBudget.get();
}
@@ -258,9 +261,10 @@ public class OsUpgraderTest {
private void assertWanted(Version version, SystemApplication application, ZoneApi... zones) {
for (var zone : zones) {
- assertEquals("Target version set for " + application + " in " + zone.getVirtualId(), version,
+ assertEquals(version,
nodeRepository().targetVersionsOf(zone.getVirtualId()).osVersion(application.nodeType())
- .orElse(Version.emptyVersion));
+ .orElse(Version.emptyVersion),
+ "Target version set for " + application + " in " + zone.getVirtualId());
}
}
@@ -268,7 +272,7 @@ public class OsUpgraderTest {
ZoneApi... zones) {
for (ZoneApi zone : zones) {
for (Node node : nodesRequiredToUpgrade(zone, application)) {
- assertEquals(application + " version in " + zone, version, versionField.apply(node));
+ assertEquals(version, versionField.apply(node), application + " version in " + zone);
}
}
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/OsVersionStatusUpdaterTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/OsVersionStatusUpdaterTest.java
index f2d738bd2e1..0bd3810e9a4 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/OsVersionStatusUpdaterTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/OsVersionStatusUpdaterTest.java
@@ -8,14 +8,14 @@ import com.yahoo.config.provision.zone.ZoneApi;
import com.yahoo.vespa.hosted.controller.ControllerTester;
import com.yahoo.vespa.hosted.controller.versions.OsVersion;
import com.yahoo.vespa.hosted.controller.versions.OsVersionStatus;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
-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.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author mpolden
@@ -23,7 +23,7 @@ import static org.junit.Assert.assertTrue;
public class OsVersionStatusUpdaterTest {
@Test
- public void test_update() {
+ void test_update() {
ControllerTester tester = new ControllerTester();
OsVersionStatusUpdater statusUpdater = new OsVersionStatusUpdater(tester.controller(), Duration.ofDays(1)
);
@@ -45,8 +45,8 @@ public class OsVersionStatusUpdaterTest {
var osVersions = tester.controller().osVersionStatus().versions();
assertEquals(2, osVersions.size());
- assertFalse("All nodes on unknown version", osVersions.get(new OsVersion(Version.emptyVersion, cloud)).isEmpty());
- assertTrue("No nodes on current target", osVersions.get(new OsVersion(version1, cloud)).isEmpty());
+ assertFalse(osVersions.get(new OsVersion(Version.emptyVersion, cloud)).isEmpty(), "All nodes on unknown version");
+ assertTrue(osVersions.get(new OsVersion(version1, cloud)).isEmpty(), "No nodes on current target");
}
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/OutstandingChangeDeployerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/OutstandingChangeDeployerTest.java
index e989486c595..9b2a1607e76 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/OutstandingChangeDeployerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/OutstandingChangeDeployerTest.java
@@ -8,13 +8,13 @@ import com.yahoo.vespa.hosted.controller.application.Change;
import com.yahoo.vespa.hosted.controller.application.pkg.ApplicationPackage;
import com.yahoo.vespa.hosted.controller.deployment.ApplicationPackageBuilder;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author bratseth
@@ -22,7 +22,7 @@ import static org.junit.Assert.assertTrue;
public class OutstandingChangeDeployerTest {
@Test
- public void testChangeDeployer() {
+ void testChangeDeployer() {
DeploymentTester tester = new DeploymentTester();
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.region("us-west-1")
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ReindexingTriggererTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ReindexingTriggererTest.java
index 53e7dd7ca58..b0601dcd880 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ReindexingTriggererTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ReindexingTriggererTest.java
@@ -6,7 +6,7 @@ import com.yahoo.config.provision.zone.ZoneId;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.ApplicationReindexing;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.ApplicationReindexing.Cluster;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.ApplicationReindexing.Status;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
@@ -22,13 +22,13 @@ import static java.time.DayOfWeek.MONDAY;
import static java.time.DayOfWeek.THURSDAY;
import static java.time.DayOfWeek.TUESDAY;
import static java.time.DayOfWeek.WEDNESDAY;
-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 ReindexingTriggererTest {
@Test
- public void testWindowOfOpportunity() {
+ void testWindowOfOpportunity() {
Duration interval = Duration.ofHours(1);
Instant now = Instant.now();
Instant doom = now.plus(ReindexingTriggerer.reindexingPeriod);
@@ -43,42 +43,42 @@ public class ReindexingTriggererTest {
now = now.plus(interval);
}
// Summer/winter time :'(
- assertTrue("Should be in window of opportunity three to five times each period", 3 <= triggered && triggered <= 5);
+ assertTrue(3 <= triggered && triggered <= 5, "Should be in window of opportunity three to five times each period");
}
@Test
- public void testReindexingIsReady() {
+ void testReindexingIsReady() {
Instant then = Instant.now();
ApplicationReindexing reindexing = new ApplicationReindexing(true,
- Map.of("c", new Cluster(Map.of(), Map.of("d", new Status(then)))));
+ Map.of("c", new Cluster(Map.of(), Map.of("d", new Status(then)))));
Instant now = then;
- assertFalse("Should not be ready less than one half-period after last triggering",
- reindexingIsReady(reindexing, now));
+ assertFalse(reindexingIsReady(reindexing, now),
+ "Should not be ready less than one half-period after last triggering");
now = now.plus(reindexingPeriod.dividedBy(2));
- assertFalse("Should not be ready one half-period after last triggering",
- reindexingIsReady(reindexing, now));
+ assertFalse(reindexingIsReady(reindexing, now),
+ "Should not be ready one half-period after last triggering");
now = now.plusMillis(1);
- assertTrue("Should be ready more than one half-period after last triggering",
- reindexingIsReady(reindexing, now));
+ assertTrue(reindexingIsReady(reindexing, now),
+ "Should be ready more than one half-period after last triggering");
reindexing = new ApplicationReindexing(true,
- Map.of("cluster",
- new Cluster(Map.of(),
- Map.of("type",
- new Status(then, then, null, null, null, null, 1.0)))));
- assertFalse("Should not be ready when reindexing is already running",
- reindexingIsReady(reindexing, now));
+ Map.of("cluster",
+ new Cluster(Map.of(),
+ Map.of("type",
+ new Status(then, then, null, null, null, null, 1.0)))));
+ assertFalse(reindexingIsReady(reindexing, now),
+ "Should not be ready when reindexing is already running");
reindexing = new ApplicationReindexing(true,
- Map.of("cluster",
- new Cluster(Map.of("type", 123L),
- Map.of("type",
- new Status(then, then, now, null, null, null, 1.0)))));
- assertTrue("Should be ready when reindexing is no longer running",
- reindexingIsReady(reindexing, now));
+ Map.of("cluster",
+ new Cluster(Map.of("type", 123L),
+ Map.of("type",
+ new Status(then, then, now, null, null, null, 1.0)))));
+ assertTrue(reindexingIsReady(reindexing, now),
+ "Should be ready when reindexing is no longer running");
}
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ResourceMeterMaintainerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ResourceMeterMaintainerTest.java
index a8d39438654..1f92c7f6e41 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ResourceMeterMaintainerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ResourceMeterMaintainerTest.java
@@ -18,7 +18,7 @@ import com.yahoo.vespa.hosted.controller.deployment.ApplicationPackageBuilder;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester;
import com.yahoo.vespa.hosted.controller.integration.MetricsMock;
import com.yahoo.vespa.hosted.controller.integration.ZoneApiMock;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
@@ -29,9 +29,9 @@ import java.util.function.BiConsumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author olaa
@@ -45,7 +45,7 @@ public class ResourceMeterMaintainerTest {
new ResourceMeterMaintainer(tester.controller(), Duration.ofMinutes(5), metrics, resourceClient);
@Test
- public void updates_deployment_costs() {
+ void updates_deployment_costs() {
ApplicationId app1 = ApplicationId.from("t1", "a1", "default");
ApplicationId app2 = ApplicationId.from("t2", "a1", "default");
ZoneId z1 = ZoneId.from("prod.aws-us-east-1c");
@@ -79,13 +79,13 @@ public class ResourceMeterMaintainerTest {
assertEquals(1.72,
(Double) metrics.getMetric(context ->
z1.value().equals(context.get("zoneId")) &&
- app1.tenant().value().equals(context.get("tenant")),
+ app1.tenant().value().equals(context.get("tenant")),
"metering.cost.hourly").get(),
Double.MIN_VALUE);
}
@Test
- public void testMaintainer() {
+ void testMaintainer() {
setUpZones();
long lastRefreshTime = tester.clock().millis();
tester.curator().writeMeteringRefreshTime(lastRefreshTime);
@@ -105,7 +105,7 @@ public class ResourceMeterMaintainerTest {
assertEquals(24, app2.getMemoryGb(), Double.MIN_VALUE);
assertEquals(500, app2.getDiskGb(), Double.MIN_VALUE);
- assertEquals(tester.clock().millis()/1000, metrics.getMetric("metering_last_reported"));
+ assertEquals(tester.clock().millis() / 1000, metrics.getMetric("metering_last_reported"));
assertEquals(2224.0d, (Double) metrics.getMetric("metering_total_reported"), Double.MIN_VALUE);
assertEquals(24d, (Double) metrics.getMetric(context -> "tenant1".equals(context.get("tenant")), "metering.vcpu").get(), Double.MIN_VALUE);
assertEquals(40d, (Double) metrics.getMetric(context -> "tenant2".equals(context.get("tenant")), "metering.vcpu").get(), Double.MIN_VALUE);
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ResourceTagMaintainerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ResourceTagMaintainerTest.java
index 1a6976034c5..0068f15ed46 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ResourceTagMaintainerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/ResourceTagMaintainerTest.java
@@ -10,14 +10,14 @@ import com.yahoo.vespa.hosted.controller.api.integration.aws.MockResourceTagger;
import com.yahoo.vespa.hosted.controller.api.integration.configserver.Node;
import com.yahoo.vespa.hosted.controller.application.SystemApplication;
import com.yahoo.vespa.hosted.controller.integration.ZoneApiMock;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import static com.yahoo.vespa.hosted.controller.maintenance.ResourceTagMaintainer.SHARED_HOST_APPLICATION;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author olaa
@@ -27,12 +27,12 @@ public class ResourceTagMaintainerTest {
private final ControllerTester tester = new ControllerTester();
@Test
- public void maintain() {
+ void maintain() {
setUpZones();
MockResourceTagger mockResourceTagger = new MockResourceTagger();
ResourceTagMaintainer resourceTagMaintainer = new ResourceTagMaintainer(tester.controller(),
- Duration.ofMinutes(5),
- mockResourceTagger);
+ Duration.ofMinutes(5),
+ mockResourceTagger);
resourceTagMaintainer.maintain();
assertEquals(2, mockResourceTagger.getValues().size());
Map<HostName, ApplicationId> applicationForHost = mockResourceTagger.getValues().get(ZoneId.from("prod.region-2"));
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/RetriggerMaintainerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/RetriggerMaintainerTest.java
index bebecf8b52b..69301ea91ef 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/RetriggerMaintainerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/RetriggerMaintainerTest.java
@@ -9,13 +9,13 @@ import com.yahoo.vespa.hosted.controller.deployment.ApplicationPackageBuilder;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentContext;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester;
import com.yahoo.vespa.hosted.controller.deployment.RetriggerEntry;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.time.Duration;
import java.util.List;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author mortent
@@ -25,7 +25,7 @@ public class RetriggerMaintainerTest {
private final DeploymentTester tester = new DeploymentTester();
@Test
- public void processes_queue() throws IOException {
+ void processes_queue() throws IOException {
RetriggerMaintainer maintainer = new RetriggerMaintainer(tester.controller(), Duration.ofDays(1));
ApplicationId applicationId = ApplicationId.from("tenant", "app", "default");
var devApp = tester.newDeploymentContext(applicationId);
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/SystemUpgraderTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/SystemUpgraderTest.java
index c09d3ec3a92..3ccd7e695c7 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/SystemUpgraderTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/SystemUpgraderTest.java
@@ -11,7 +11,7 @@ import com.yahoo.vespa.hosted.controller.application.SystemApplication;
import com.yahoo.vespa.hosted.controller.integration.NodeRepositoryMock;
import com.yahoo.vespa.hosted.controller.integration.ZoneApiMock;
import com.yahoo.vespa.hosted.controller.versions.VespaVersion;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.List;
@@ -19,9 +19,9 @@ import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author mpolden
@@ -36,19 +36,19 @@ public class SystemUpgraderTest {
private final ControllerTester tester = new ControllerTester();
@Test
- public void upgrade_system() {
+ void upgrade_system() {
SystemUpgrader systemUpgrader = systemUpgrader(
UpgradePolicy.builder()
- .upgrade(zone1)
- .upgradeInParallel(zone2, zone3)
- .upgrade(zone4)
- .build()
+ .upgrade(zone1)
+ .upgradeInParallel(zone2, zone3)
+ .upgrade(zone4)
+ .build()
);
Version version1 = Version.fromString("6.5");
// Bootstrap a system without host applications
tester.configServer().bootstrap(List.of(zone1.getId(), zone2.getId(), zone3.getId(), zone4.getId()),
- SystemApplication.configServer, SystemApplication.proxy);
+ SystemApplication.configServer, SystemApplication.proxy);
// Fail a few nodes. Failed nodes should not affect versions
failNodeIn(zone1, SystemApplication.configServer);
failNodeIn(zone3, SystemApplication.proxy);
@@ -78,8 +78,8 @@ public class SystemUpgraderTest {
systemUpgrader.maintain();
assertWantedVersion(SystemApplication.proxy, version2, zone1);
completeUpgrade(SystemApplication.proxy, version2, zone1);
- assertTrue("Deployed proxy application",
- tester.configServer().application(SystemApplication.proxy.id(), zone1.getId()).isPresent());
+ assertTrue(tester.configServer().application(SystemApplication.proxy.id(), zone1.getId()).isPresent(),
+ "Deployed proxy application");
// zone 2, 3 and 4: still targets old version
assertWantedVersion(SystemApplication.configServer, version1, zone2, zone3, zone4);
@@ -138,12 +138,12 @@ public class SystemUpgraderTest {
}
@Test
- public void upgrade_controller_with_non_converging_application() {
+ void upgrade_controller_with_non_converging_application() {
SystemUpgrader systemUpgrader = systemUpgrader(UpgradePolicy.builder().upgrade(zone1).build());
// Bootstrap system
tester.configServer().bootstrap(List.of(zone1.getId()), SystemApplication.configServer,
- SystemApplication.proxy);
+ SystemApplication.proxy);
Version version1 = Version.fromString("6.5");
tester.upgradeSystem(version1);
@@ -173,13 +173,13 @@ public class SystemUpgraderTest {
}
@Test
- public void upgrade_system_containing_host_applications() {
+ void upgrade_system_containing_host_applications() {
SystemUpgrader systemUpgrader = systemUpgrader(
UpgradePolicy.builder()
- .upgrade(zone1)
- .upgradeInParallel(zone2, zone3)
- .upgrade(zone4)
- .build()
+ .upgrade(zone1)
+ .upgradeInParallel(zone2, zone3)
+ .upgrade(zone4)
+ .build()
);
Version version1 = Version.fromString("6.5");
@@ -196,9 +196,9 @@ public class SystemUpgraderTest {
// System upgrades in zone 1:
systemUpgrader.maintain();
List<SystemApplication> allExceptZone = List.of(SystemApplication.configServerHost,
- SystemApplication.configServer,
- SystemApplication.proxyHost,
- SystemApplication.tenantHost);
+ SystemApplication.configServer,
+ SystemApplication.proxyHost,
+ SystemApplication.tenantHost);
completeUpgrade(allExceptZone, version2, zone1);
systemUpgrader.maintain();
completeUpgrade(SystemApplication.proxy, version2, zone1);
@@ -225,7 +225,7 @@ public class SystemUpgraderTest {
}
@Test
- public void downgrading_controller_never_downgrades_system() {
+ void downgrading_controller_never_downgrades_system() {
SystemUpgrader systemUpgrader = systemUpgrader(UpgradePolicy.builder().upgrade(zone1).build());
Version version = Version.fromString("6.5");
@@ -244,7 +244,7 @@ public class SystemUpgraderTest {
}
@Test
- public void upgrade_halts_on_broken_version() {
+ void upgrade_halts_on_broken_version() {
SystemUpgrader systemUpgrader = systemUpgrader(UpgradePolicy.builder().upgrade(zone1).upgrade(zone2).build());
// Initial system version
@@ -252,11 +252,11 @@ public class SystemUpgraderTest {
tester.upgradeSystem(version1);
systemUpgrader.maintain();
assertCurrentVersion(List.of(SystemApplication.configServerHost, SystemApplication.proxyHost,
- SystemApplication.configServer, SystemApplication.proxy),
- version1, zone1);
+ SystemApplication.configServer, SystemApplication.proxy),
+ version1, zone1);
assertCurrentVersion(List.of(SystemApplication.configServerHost, SystemApplication.proxyHost,
- SystemApplication.configServer, SystemApplication.proxy),
- version1, zone2);
+ SystemApplication.configServer, SystemApplication.proxy),
+ version1, zone2);
// System starts upgrading to next version
Version version2 = Version.fromString("6.6");
@@ -273,13 +273,13 @@ public class SystemUpgraderTest {
overrideConfidence(version2, VespaVersion.Confidence.broken);
systemUpgrader.maintain();
assertWantedVersion(List.of(SystemApplication.configServerHost, SystemApplication.proxyHost,
- SystemApplication.configServer, SystemApplication.proxy), version1, zone2);
+ SystemApplication.configServer, SystemApplication.proxy), version1, zone2);
}
@Test
- public void does_not_deploy_proxy_app_in_zone_without_shared_routing() {
+ void does_not_deploy_proxy_app_in_zone_without_shared_routing() {
var applications = List.of(SystemApplication.configServerHost, SystemApplication.configServer,
- SystemApplication.tenantHost);
+ SystemApplication.tenantHost);
tester.configServer().bootstrap(List.of(zone1.getId()), applications);
tester.configServer().disallowConvergenceCheck(SystemApplication.proxy.id());
tester.zoneRegistry().exclusiveRoutingIn(zone1);
@@ -301,7 +301,7 @@ public class SystemUpgraderTest {
}
@Test
- public void downgrade_from_aborted_version() {
+ void downgrade_from_aborted_version() {
SystemUpgrader systemUpgrader = systemUpgrader(UpgradePolicy.builder().upgrade(zone1).upgrade(zone2).upgrade(zone3).build());
Version version1 = Version.fromString("6.5");
@@ -319,9 +319,9 @@ public class SystemUpgraderTest {
for (var zone : List.of(zone1, zone2)) {
systemUpgrader.maintain();
completeUpgrade(List.of(SystemApplication.tenantHost,
- SystemApplication.proxyHost,
- SystemApplication.configServerHost),
- version2, zone);
+ SystemApplication.proxyHost,
+ SystemApplication.configServerHost),
+ version2, zone);
completeUpgrade(SystemApplication.configServer, version2, zone);
systemUpgrader.maintain();
completeUpgrade(SystemApplication.proxy, version2, zone);
@@ -336,12 +336,12 @@ public class SystemUpgraderTest {
for (var zone : List.of(zone2, zone1)) {
systemUpgrader.maintain();
completeUpgrade(List.of(SystemApplication.tenantHost,
- SystemApplication.configServerHost,
- SystemApplication.proxy),
- version1, zone);
+ SystemApplication.configServerHost,
+ SystemApplication.proxy),
+ version1, zone);
convergeServices(SystemApplication.proxy, zone);
List<SystemApplication> lastToDowngrade = List.of(SystemApplication.configServer,
- SystemApplication.proxyHost);
+ SystemApplication.proxyHost);
assertWantedVersion(lastToDowngrade, version2, zone);
// ... and then configserver and proxyhost
@@ -359,7 +359,8 @@ public class SystemUpgraderTest {
try {
overrideConfidence(version3, VespaVersion.Confidence.aborted);
fail("Expected exception");
- } catch (IllegalArgumentException ignored) {}
+ } catch (IllegalArgumentException ignored) {
+ }
systemUpgrader.maintain();
assertWantedVersion(SystemApplication.notController(), version3, zone1, zone2, zone3);
}
@@ -414,8 +415,9 @@ public class SystemUpgraderTest {
private void assertWantedVersion(SystemApplication application, Version version, ZoneApi first, ZoneApi... rest) {
Stream.concat(Stream.of(first), Stream.of(rest)).forEach(zone -> {
if (!application.hasApplicationPackage()) {
- assertEquals("Target version set for " + application + " in " + zone.getId(), version,
- nodeRepository().targetVersionsOf(zone.getId()).vespaVersion(application.nodeType()).orElse(Version.emptyVersion));
+ assertEquals(version,
+ nodeRepository().targetVersionsOf(zone.getId()).vespaVersion(application.nodeType()).orElse(Version.emptyVersion),
+ "Target version set for " + application + " in " + zone.getId());
}
assertVersion(application, version, Node::wantedVersion, zone);
});
@@ -437,7 +439,7 @@ public class SystemUpgraderTest {
ZoneApi first, ZoneApi... rest) {
Stream.concat(Stream.of(first), Stream.of(rest)).forEach(zone -> {
for (Node node : listNodes(zone, application)) {
- assertEquals("Version of " + application.id() + " in " + zone.getId(), version, versionField.apply(node));
+ assertEquals(version, versionField.apply(node), "Version of " + application.id() + " in " + zone.getId());
}
});
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/TenantRoleMaintainerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/TenantRoleMaintainerTest.java
index 7026d975010..97656583d04 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/TenantRoleMaintainerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/TenantRoleMaintainerTest.java
@@ -9,13 +9,13 @@ import com.yahoo.vespa.hosted.controller.application.pkg.ApplicationPackage;
import com.yahoo.vespa.hosted.controller.deployment.ApplicationPackageBuilder;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentContext;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
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;
/**
* @author mortent
@@ -25,11 +25,11 @@ public class TenantRoleMaintainerTest {
private final DeploymentTester tester = new DeploymentTester();
@Test
- public void maintains_iam_roles_for_tenants_in_production() {
+ void maintains_iam_roles_for_tenants_in_production() {
var devAppTenant1 = tester.newDeploymentContext("tenant1", "app1", "default");
var prodAppTenant2 = tester.newDeploymentContext("tenant2", "app2", "default");
- var devAppTenant2 = tester.newDeploymentContext("tenant2","app3","default");
- var perfAppTenant1 = tester.newDeploymentContext("tenant3","app1","default");
+ var devAppTenant2 = tester.newDeploymentContext("tenant2", "app3", "default");
+ var perfAppTenant1 = tester.newDeploymentContext("tenant3", "app1", "default");
ApplicationPackage appPackage = new ApplicationPackageBuilder()
.region("us-west-1")
.build();
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/TrafficShareUpdaterTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/TrafficShareUpdaterTest.java
index c59155cb162..07ea04b4c84 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/TrafficShareUpdaterTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/TrafficShareUpdaterTest.java
@@ -10,12 +10,12 @@ import com.yahoo.vespa.hosted.controller.application.pkg.ApplicationPackage;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentContext;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester;
import com.yahoo.vespa.hosted.controller.integration.NodeRepositoryMock;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* Tests the traffic fraction updater. This also tests its dependency on DeploymentMetricsMaintainer.
@@ -25,7 +25,7 @@ import static org.junit.Assert.assertEquals;
public class TrafficShareUpdaterTest {
@Test
- public void testTrafficUpdater() {
+ void testTrafficUpdater() {
DeploymentTester tester = new DeploymentTester();
var application = tester.newDeploymentContext();
var deploymentMetricsMaintainer = new DeploymentMetricsMaintainer(tester.controller(), Duration.ofDays(1));
@@ -70,7 +70,7 @@ public class TrafficShareUpdaterTest {
assertTrafficFraction(0.47, 0.50, application.instanceId(), prod2, tester);
assertTrafficFraction(0.00, 0.50, application.instanceId(), prod3, tester);
// - all hot
- setQpsMetric( 50.0, application.application().id().defaultInstance(), prod1, tester);
+ setQpsMetric(50.0, application.application().id().defaultInstance(), prod1, tester);
setQpsMetric(25.0, application.application().id().defaultInstance(), prod2, tester);
setQpsMetric(25.0, application.application().id().defaultInstance(), prod3, tester);
deploymentMetricsMaintainer.maintain();
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/UpgraderTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/UpgraderTest.java
index f053ab7a4a6..b24b6c8e99b 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/UpgraderTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/UpgraderTest.java
@@ -16,7 +16,7 @@ import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTrigger;
import com.yahoo.vespa.hosted.controller.deployment.Run;
import com.yahoo.vespa.hosted.controller.versions.VespaVersion;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
@@ -38,9 +38,9 @@ import static com.yahoo.vespa.hosted.controller.deployment.DeploymentContext.sys
import static com.yahoo.vespa.hosted.controller.deployment.DeploymentTrigger.ChangesToCancel.ALL;
import static com.yahoo.vespa.hosted.controller.deployment.DeploymentTrigger.ChangesToCancel.PIN;
import static com.yahoo.vespa.hosted.controller.deployment.DeploymentTrigger.ChangesToCancel.PLATFORM;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author bratseth
@@ -50,13 +50,13 @@ public class UpgraderTest {
private final DeploymentTester tester = new DeploymentTester().atMondayMorning();
@Test
- public void testUpgrading() {
+ void testUpgrading() {
// --- Setup
Version version0 = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version0);
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("No applications: Nothing to do", 0, tester.jobs().active().size());
+ assertEquals(0, tester.jobs().active().size(), "No applications: Nothing to do");
// Setup applications
var canary0 = createAndDeploy("canary0", "canary");
@@ -68,7 +68,7 @@ public class UpgraderTest {
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("All already on the right version: Nothing to do", 0, tester.jobs().active().size());
+ assertEquals(0, tester.jobs().active().size(), "All already on the right version: Nothing to do");
// --- Next version released - everything goes smoothly
Version version1 = Version.fromString("6.3");
@@ -77,14 +77,14 @@ public class UpgraderTest {
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("New system version: Should upgrade Canaries", 4, tester.jobs().active().size());
+ assertEquals(4, tester.jobs().active().size(), "New system version: Should upgrade Canaries");
canary0.deployPlatform(version1);
assertEquals(version1, tester.configServer().lastPrepareVersion().get());
tester.controllerTester().computeVersionStatus();
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("One canary pending; nothing else", 2, tester.jobs().active().size());
+ assertEquals(2, tester.jobs().active().size(), "One canary pending; nothing else");
canary1.deployPlatform(version1);
@@ -92,7 +92,7 @@ public class UpgraderTest {
assertEquals(VespaVersion.Confidence.normal, tester.controller().readVersionStatus().systemVersion().get().confidence());
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("Canaries done: Should upgrade defaults", 6, tester.jobs().active().size());
+ assertEquals(6, tester.jobs().active().size(), "Canaries done: Should upgrade defaults");
default0.deployPlatform(version1);
default1.deployPlatform(version1);
@@ -102,13 +102,13 @@ public class UpgraderTest {
assertEquals(VespaVersion.Confidence.high, tester.controller().readVersionStatus().systemVersion().get().confidence());
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("Normals done: Should upgrade conservatives", 2, tester.jobs().active().size());
+ assertEquals(2, tester.jobs().active().size(), "Normals done: Should upgrade conservatives");
conservative0.deployPlatform(version1);
tester.controllerTester().computeVersionStatus();
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("Nothing to do", 0, tester.jobs().active().size());
+ assertEquals(0, tester.jobs().active().size(), "Nothing to do");
// --- Next version released - which fails a Canary
Version version2 = Version.fromString("6.4");
@@ -117,7 +117,7 @@ public class UpgraderTest {
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("New system version: Should upgrade Canaries", 4, tester.jobs().active().size());
+ assertEquals(4, tester.jobs().active().size(), "New system version: Should upgrade Canaries");
canary0.runJob(systemTest);
canary0.failDeployment(stagingTest);
@@ -125,7 +125,7 @@ public class UpgraderTest {
assertEquals(VespaVersion.Confidence.broken, tester.controller().readVersionStatus().systemVersion().get().confidence());
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("Version broken, but Canaries should keep trying", 3, tester.jobs().active().size());
+ assertEquals(3, tester.jobs().active().size(), "Version broken, but Canaries should keep trying");
// --- Next version released - which repairs the Canary app and fails a default
Version version3 = Version.fromString("6.5");
@@ -137,14 +137,14 @@ public class UpgraderTest {
canary1.abortJob(stagingTest);
tester.triggerJobs();
- assertEquals("New system version: Should upgrade Canaries", 4, tester.jobs().active().size());
+ assertEquals(4, tester.jobs().active().size(), "New system version: Should upgrade Canaries");
canary0.deployPlatform(version3);
assertEquals(version3, tester.configServer().lastPrepareVersion().get());
tester.controllerTester().computeVersionStatus();
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("One canary pending; nothing else", 2, tester.jobs().active().size());
+ assertEquals(2, tester.jobs().active().size(), "One canary pending; nothing else");
canary1.deployPlatform(version3);
@@ -153,7 +153,7 @@ public class UpgraderTest {
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("Canaries done: Should upgrade defaults", 6, tester.jobs().active().size());
+ assertEquals(6, tester.jobs().active().size(), "Canaries done: Should upgrade defaults");
default0.runJob(systemTest);
default0.failDeployment(stagingTest);
@@ -161,11 +161,10 @@ public class UpgraderTest {
default2.deployPlatform(version3);
tester.controllerTester().computeVersionStatus();
- assertEquals("Not enough evidence to mark this as neither broken nor high",
- VespaVersion.Confidence.normal, tester.controller().readVersionStatus().systemVersion().get().confidence());
+ assertEquals(VespaVersion.Confidence.normal, tester.controller().readVersionStatus().systemVersion().get().confidence(), "Not enough evidence to mark this as neither broken nor high");
tester.triggerJobs();
- assertEquals("Upgrade with error should retry", 1, tester.jobs().active().size());
+ assertEquals(1, tester.jobs().active().size(), "Upgrade with error should retry");
// --- Failing application is repaired by changing the application, causing confidence to move above 'high' threshold
// Deploy application change
@@ -176,13 +175,13 @@ public class UpgraderTest {
assertEquals(VespaVersion.Confidence.high, tester.controller().readVersionStatus().systemVersion().get().confidence());
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("Normals done: Should upgrade conservatives", 2, tester.jobs().active().size());
+ assertEquals(2, tester.jobs().active().size(), "Normals done: Should upgrade conservatives");
conservative0.deployPlatform(version3);
tester.controllerTester().computeVersionStatus();
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("Applications are on " + version3 + " - nothing to do", 0, tester.jobs().active().size());
+ assertEquals(0, tester.jobs().active().size(), "Applications are on " + version3 + " - nothing to do");
// --- Starting upgrading to a new version which breaks, causing upgrades to commence on the previous version
var default3 = createAndDeploy("default3", "default");
@@ -198,7 +197,7 @@ public class UpgraderTest {
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("Upgrade of defaults are scheduled", 10, tester.jobs().active().size());
+ assertEquals(10, tester.jobs().active().size(), "Upgrade of defaults are scheduled");
for (var context : List.of(default0, default1, default2, default3, default4))
assertEquals(version4, context.instance().change().platform().get());
@@ -216,7 +215,7 @@ public class UpgraderTest {
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("Upgrade of defaults are scheduled", 10, tester.jobs().active().size());
+ assertEquals(10, tester.jobs().active().size(), "Upgrade of defaults are scheduled");
assertEquals(version5, default0.instance().change().platform().get());
for (var context : List.of(default1, default2, default3, default4))
assertEquals(version4, context.instance().change().platform().get());
@@ -254,17 +253,17 @@ public class UpgraderTest {
}
@Test
- public void testUpgradingToVersionWhichBreaksSomeNonCanaries() {
+ void testUpgradingToVersionWhichBreaksSomeNonCanaries() {
// --- Setup
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("No system version: Nothing to do", 0, tester.jobs().active().size());
+ assertEquals(0, tester.jobs().active().size(), "No system version: Nothing to do");
Version version = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version);
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("No applications: Nothing to do", 0, tester.jobs().active().size());
+ assertEquals(0, tester.jobs().active().size(), "No applications: Nothing to do");
// Setup applications
var canary0 = createAndDeploy("canary0", "canary");
@@ -282,7 +281,7 @@ public class UpgraderTest {
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("All already on the right version: Nothing to do", 0, tester.jobs().active().size());
+ assertEquals(0, tester.jobs().active().size(), "All already on the right version: Nothing to do");
// --- A new version is released
version = Version.fromString("6.3");
@@ -291,14 +290,14 @@ public class UpgraderTest {
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("New system version: Should upgrade Canaries", 4, tester.jobs().active().size());
+ assertEquals(4, tester.jobs().active().size(), "New system version: Should upgrade Canaries");
canary0.deployPlatform(version);
assertEquals(version, tester.configServer().lastPrepareVersion().get());
tester.controllerTester().computeVersionStatus();
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("One canary pending; nothing else", 2, tester.jobs().active().size());
+ assertEquals(2, tester.jobs().active().size(), "One canary pending; nothing else");
canary1.deployPlatform(version);
@@ -306,7 +305,7 @@ public class UpgraderTest {
assertEquals(VespaVersion.Confidence.normal, tester.controller().readVersionStatus().systemVersion().get().confidence());
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("Canaries done: Should upgrade defaults", 20, tester.jobs().active().size());
+ assertEquals(20, tester.jobs().active().size(), "Canaries done: Should upgrade defaults");
default0.deployPlatform(version);
for (var context : List.of(default1, default2, default3, default4))
@@ -318,7 +317,7 @@ public class UpgraderTest {
tester.abortAll();
tester.triggerJobs();
assertEquals(VespaVersion.Confidence.broken, tester.controller().readVersionStatus().systemVersion().get().confidence());
- assertEquals("Upgrades are cancelled", 0, tester.jobs().active().size());
+ assertEquals(0, tester.jobs().active().size(), "Upgrades are cancelled");
}
// Scenario:
@@ -328,7 +327,7 @@ public class UpgraderTest {
// V2 is marked as broken and upgrade of A to V2 is cancelled.
// Upgrade of A to V1 is scheduled: Should skip the zone on V2 but upgrade the next zone to V1
@Test
- public void testVersionIsBrokenAfterAZoneIsLive() {
+ void testVersionIsBrokenAfterAZoneIsLive() {
Version v0 = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(v0);
@@ -383,8 +382,8 @@ public class UpgraderTest {
// Applications with default policy start upgrading to V2
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("Upgrade scheduled for remaining apps", 10, tester.jobs().active().size());
- assertEquals("default4 is still upgrading to 6.3", v1, default4.instance().change().platform().get());
+ assertEquals(10, tester.jobs().active().size(), "Upgrade scheduled for remaining apps");
+ assertEquals(v1, default4.instance().change().platform().get(), "default4 is still upgrading to 6.3");
// 4/5 applications fail (in the last prod zone) and lowers confidence
default0.runJob(systemTest).runJob(stagingTest).runJob(productionUsWest1).failDeployment(productionUsEast3);
@@ -400,20 +399,19 @@ public class UpgraderTest {
tester.abortAll();
tester.triggerJobs();
- assertEquals("Upgrade to 5.1 scheduled for apps not completely on 5.1 or 5.2", 10, tester.jobs().active().size());
+ assertEquals(10, tester.jobs().active().size(), "Upgrade to 5.1 scheduled for apps not completely on 5.1 or 5.2");
// prod zone on 5.2 (usWest1) is skipped, but we still trigger the next zone from triggerReadyJobs:
default0.runJob(systemTest).runJob(stagingTest).runJob(productionUsEast3);
// Resulting state:
assertEquals(v2, default0.deployment(ZoneId.from("prod.us-west-1")).version());
- assertEquals("Last zone is upgraded to v1",
- v1, default0.deployment(ZoneId.from("prod.us-east-3")).version());
+ assertEquals(v1, default0.deployment(ZoneId.from("prod.us-east-3")).version(), "Last zone is upgraded to v1");
assertFalse(default0.instance().change().hasTargets());
}
@Test
- public void testConfidenceIgnoresFailingApplicationChanges() {
+ void testConfidenceIgnoresFailingApplicationChanges() {
Version version = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version);
@@ -459,7 +457,7 @@ public class UpgraderTest {
}
@Test
- public void testBlockVersionChange() {
+ void testBlockVersionChange() {
// Tuesday, 18:00
tester.at(Instant.parse("2017-09-26T18:00:00.00Z"));
Version version = Version.fromString("6.2");
@@ -481,25 +479,25 @@ public class UpgraderTest {
// Application is not upgraded at this time
tester.upgrader().maintain();
tester.triggerJobs();
- assertTrue("No jobs scheduled", tester.jobs().active().isEmpty());
+ assertTrue(tester.jobs().active().isEmpty(), "No jobs scheduled");
// One hour passes, time is 19:00, still no upgrade
tester.clock().advance(Duration.ofHours(1));
tester.upgrader().maintain();
tester.triggerJobs();
- assertTrue("No jobs scheduled", tester.jobs().active().isEmpty());
+ assertTrue(tester.jobs().active().isEmpty(), "No jobs scheduled");
// Two hours pass in total, time is 20:00 and application upgrades
tester.clock().advance(Duration.ofHours(1));
tester.upgrader().maintain();
tester.triggerJobs();
- assertFalse("Job is scheduled", tester.jobs().active().isEmpty());
+ assertFalse(tester.jobs().active().isEmpty(), "Job is scheduled");
app.deployPlatform(version);
- assertTrue("All jobs consumed", tester.jobs().active().isEmpty());
+ assertTrue(tester.jobs().active().isEmpty(), "All jobs consumed");
}
@Test
- public void testBlockVersionChangeHalfwayThough() {
+ void testBlockVersionChangeHalfwayThough() {
// Tuesday, 17:00
tester.at(Instant.parse("2017-09-26T17:00:00.00Z"));
@@ -532,11 +530,11 @@ public class UpgraderTest {
assertEquals(1, tester.jobs().active().size()); // Next job triggered because upgrade is already rolling out.
app.runJob(productionUsCentral1).runJob(productionUsEast3);
- assertTrue("All jobs consumed", tester.jobs().active().isEmpty());
+ assertTrue(tester.jobs().active().isEmpty(), "All jobs consumed");
}
@Test
- public void testBlockVersionChangeHalfwayThroughThenNewRevision() {
+ void testBlockVersionChangeHalfwayThroughThenNewRevision() {
// Friday, 16:00
tester.at(Instant.parse("2017-09-29T16:00:00.00Z"));
@@ -600,12 +598,12 @@ public class UpgraderTest {
tester.upgrader().maintain();
tester.triggerJobs();
app.runJob(systemTest)
- .runJob(stagingTest)
- .runJob(productionUsWest1)
- .runJob(productionUsCentral1)
- .runJob(stagingTest)
- .runJob(productionUsEast3);
- assertTrue("All jobs consumed", tester.jobs().active().isEmpty());
+ .runJob(stagingTest)
+ .runJob(productionUsWest1)
+ .runJob(productionUsCentral1)
+ .runJob(stagingTest)
+ .runJob(productionUsEast3);
+ assertTrue(tester.jobs().active().isEmpty(), "All jobs consumed");
// App is completely upgraded to the latest version
for (Deployment deployment : app.instance().deployments().values())
@@ -613,7 +611,7 @@ public class UpgraderTest {
}
@Test
- public void testThrottlesUpgrades() {
+ void testThrottlesUpgrades() {
Version version = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version);
@@ -632,7 +630,7 @@ public class UpgraderTest {
// Dev deployment which should be ignored
var dev0 = tester.newDeploymentContext("tenant1", "dev0", "default")
- .runJob(devUsEast1, DeploymentContext.applicationPackage());
+ .runJob(devUsEast1, DeploymentContext.applicationPackage());
// New version is released and canaries upgrade
version = Version.fromString("6.3");
@@ -661,13 +659,13 @@ public class UpgraderTest {
}
@Test
- public void testPinningMajorVersionInDeploymentXml() {
+ void testPinningMajorVersionInDeploymentXml() {
Version version = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version);
ApplicationPackage version6ApplicationPackage = new ApplicationPackageBuilder().majorVersion(6)
- .region("us-west-1")
- .build();
+ .region("us-west-1")
+ .build();
// Setup applications
var canary0 = createAndDeploy("canary0", "canary");
@@ -693,7 +691,7 @@ public class UpgraderTest {
}
@Test
- public void testPinningMajorVersionInApplication() {
+ void testPinningMajorVersionInApplication() {
Version version = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version);
@@ -701,7 +699,7 @@ public class UpgraderTest {
var canary0 = createAndDeploy("canary", "canary");
var default0 = tester.newDeploymentContext().submit().deploy();
tester.applications().lockApplicationOrThrow(default0.application().id(),
- a -> tester.applications().store(a.withMajorVersion(6)));
+ a -> tester.applications().store(a.withMajorVersion(6)));
assertEquals(OptionalInt.of(6), default0.application().majorVersion());
// New major version is released
@@ -724,20 +722,20 @@ public class UpgraderTest {
}
@Test
- public void testPinningMajorVersionInUpgrader() {
+ void testPinningMajorVersionInUpgrader() {
Version version = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version);
ApplicationPackage version7CanaryApplicationPackage = new ApplicationPackageBuilder()
- .majorVersion(7)
- .upgradePolicy("canary")
- .region("us-west-1")
- .build();
+ .majorVersion(7)
+ .upgradePolicy("canary")
+ .region("us-west-1")
+ .build();
ApplicationPackage version7DefaultApplicationPackage = new ApplicationPackageBuilder()
- .majorVersion(7)
- .upgradePolicy("default")
- .region("us-west-1")
- .build();
+ .majorVersion(7)
+ .upgradePolicy("default")
+ .region("us-west-1")
+ .build();
// Setup applications
var canary0 = tester.newDeploymentContext("tenant1", "canary0", "default").submit(version7CanaryApplicationPackage).deploy();
@@ -778,7 +776,7 @@ public class UpgraderTest {
}
@Test
- public void testAllowApplicationChangeDuringFailingUpgrade() {
+ void testAllowApplicationChangeDuringFailingUpgrade() {
Version version = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version);
@@ -797,15 +795,15 @@ public class UpgraderTest {
RevisionId revision = app.lastSubmission().get();
// Application change recorded together with ongoing upgrade
- assertTrue("Change contains both upgrade and application change",
- app.instance().change().platform().get().equals(version) &&
- app.instance().change().revision().get().equals(revision));
+ assertTrue(app.instance().change().platform().get().equals(version) &&
+ app.instance().change().revision().get().equals(revision),
+ "Change contains both upgrade and application change");
// Deployment completes
app.runJob(systemTest).runJob(stagingTest)
- .runJob(productionUsWest1)
- .runJob(productionUsEast3);
- assertEquals("All jobs consumed", List.of(), tester.jobs().active());
+ .runJob(productionUsWest1)
+ .runJob(productionUsEast3);
+ assertEquals(List.of(), tester.jobs().active(), "All jobs consumed");
for (Deployment deployment : app.instance().deployments().values()) {
assertEquals(version, deployment.version());
@@ -814,7 +812,7 @@ public class UpgraderTest {
}
@Test
- public void testBlockRevisionChangeHalfwayThoughThenUpgrade() {
+ void testBlockRevisionChangeHalfwayThoughThenUpgrade() {
// Tuesday, 17:00.
tester.at(Instant.parse("2017-09-26T17:00:00.00Z"));
@@ -852,11 +850,11 @@ public class UpgraderTest {
// Upgrade may start, now that revision is rolled out.
tester.upgrader().maintain();
app.deployPlatform(version);
- assertTrue("All jobs consumed", tester.jobs().active().isEmpty());
+ assertTrue(tester.jobs().active().isEmpty(), "All jobs consumed");
}
@Test
- public void testBlockRevisionChangeHalfwayThoughThenNewRevision() {
+ void testBlockRevisionChangeHalfwayThoughThenNewRevision() {
// Tuesday, 17:00.
tester.at(Instant.parse("2017-09-26T17:00:00.00Z"));
@@ -901,7 +899,7 @@ public class UpgraderTest {
}
@Test
- public void testPinning() {
+ void testPinning() {
Version version0 = Version.fromString("6.2");
tester.controllerTester().upgradeSystem(version0);
@@ -939,7 +937,7 @@ public class UpgraderTest {
// Application fails upgrade after one zone is complete, and is pinned again to the old version.
context.runJob(systemTest).runJob(stagingTest).runJob(productionUsCentral1)
- .timeOutUpgrade(productionUsWest1);
+ .timeOutUpgrade(productionUsWest1);
tester.deploymentTrigger().cancelChange(context.instanceId(), ALL);
tester.deploymentTrigger().forceChange(context.instanceId(), Change.of(version0).withPin());
assertEquals(version0, context.instance().change().platform().get());
@@ -953,7 +951,7 @@ public class UpgraderTest {
}
@Test
- public void upgradesToLatestAllowedMajor() {
+ void upgradesToLatestAllowedMajor() {
Version version0 = Version.fromString("6.1");
tester.controllerTester().upgradeSystem(version0);
@@ -967,7 +965,7 @@ public class UpgraderTest {
// Keep app 1 on current version
tester.controller().applications().lockApplicationIfPresent(app1.application().id(), app ->
tester.controller().applications().store(app.with(app1.instance().name(),
- instance -> instance.withChange(instance.change().withPin()))));
+ instance -> instance.withChange(instance.change().withPin()))));
// New version is released
Version version1 = Version.fromString("6.2");
@@ -989,14 +987,15 @@ public class UpgraderTest {
// App 1 is unpinned and upgrades to latest 6
tester.controller().applications().lockApplicationIfPresent(app1.application().id(), app ->
tester.controller().applications().store(app.with(app1.instance().name(),
- instance -> instance.withChange(instance.change().withoutPin()))));
+ instance -> instance.withChange(instance.change().withoutPin()))));
tester.upgrader().maintain();
- assertEquals("Application upgrades to latest allowed major", version1,
- app1.instance().change().platform().orElseThrow());
+ assertEquals(version1,
+ app1.instance().change().platform().orElseThrow(),
+ "Application upgrades to latest allowed major");
}
@Test
- public void testSettingFailingRevisionAside() {
+ void testSettingFailingRevisionAside() {
DeploymentContext app = tester.newDeploymentContext().submit().deploy();
// New revision fails.
@@ -1050,7 +1049,7 @@ public class UpgraderTest {
}
@Test
- public void testsEachUpgradeCombinationWithFailingDeployments() {
+ void testsEachUpgradeCombinationWithFailingDeployments() {
Version v1 = Version.fromString("6.1");
tester.controllerTester().upgradeSystem(v1);
@@ -1105,11 +1104,11 @@ public class UpgraderTest {
// Upgrade completes
application.runJob(productionUsEast3);
- assertTrue("Upgrade complete", application.instance().change().isEmpty());
+ assertTrue(application.instance().change().isEmpty(), "Upgrade complete");
}
@Test
- public void testUpgradesPerMinute() {
+ void testUpgradesPerMinute() {
assertEquals(0, Upgrader.numberOfApplicationsToUpgrade(10, 0, 0));
for (long now = 0; now < 60_000; now++)
@@ -1130,14 +1129,14 @@ public class UpgraderTest {
}
@Test
- public void testUpgradeShuffling() {
+ void testUpgradeShuffling() {
// Deploy applications on initial version
var default0 = createAndDeploy("default0", "default");
var default1 = createAndDeploy("default1", "default");
var default2 = createAndDeploy("default2", "default");
var applications = Map.of(default0.instanceId(), default0,
- default1.instanceId(), default1,
- default2.instanceId(), default2);
+ default1.instanceId(), default1,
+ default2.instanceId(), default2);
// Throttle upgrades per run
((ManualClock) tester.controller().clock()).setInstant(Instant.ofEpochMilli(1589787107000L)); // Fixed random seed
@@ -1157,10 +1156,10 @@ public class UpgraderTest {
upgrader.maintain();
tester.triggerJobs();
Set<ApplicationId> triggered = tester.jobs().active().stream()
- .map(Run::id)
- .map(RunId::application)
- .collect(Collectors.toSet());
- assertEquals("Expected number of applications is triggered", 1, triggered.size());
+ .map(Run::id)
+ .map(RunId::application)
+ .collect(Collectors.toSet());
+ assertEquals(1, triggered.size(), "Expected number of applications is triggered");
ApplicationId application = triggered.iterator().next();
upgraderOrder.add(application);
applications.get(application).completeRollout();
@@ -1168,7 +1167,7 @@ public class UpgraderTest {
}
upgradeOrders.add(upgraderOrder);
}
- assertEquals("Upgrade orders are distinct", versions.size(), upgradeOrders.size());
+ assertEquals(versions.size(), upgradeOrders.size(), "Upgrade orders are distinct");
}
private static final ApplicationPackage canaryApplicationPackage =
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/UserManagementMaintainerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/UserManagementMaintainerTest.java
index c1a9559ac46..4fe04b25577 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/UserManagementMaintainerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/UserManagementMaintainerTest.java
@@ -3,11 +3,11 @@ package com.yahoo.vespa.hosted.controller.maintenance;
import com.yahoo.config.provision.SystemName;
import com.yahoo.vespa.hosted.controller.ControllerTester;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author olaa
@@ -19,7 +19,7 @@ public class UserManagementMaintainerTest {
private final String APP_NAME = "some-app";
@Test
- public void deletes_tenant_when_not_public() {
+ void deletes_tenant_when_not_public() {
var tester = createTester(SystemName.main);
var maintainer = new UserManagementMaintainer(tester.controller(), Duration.ofMinutes(5), tester.serviceRegistry().roleMaintainer());
maintainer.maintain();
@@ -32,7 +32,7 @@ public class UserManagementMaintainerTest {
}
@Test
- public void no_tenant_deletion_in_public() {
+ void no_tenant_deletion_in_public() {
var tester = createTester(SystemName.Public);
var maintainer = new UserManagementMaintainer(tester.controller(), Duration.ofMinutes(5), tester.serviceRegistry().roleMaintainer());
maintainer.maintain();
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/VcmrMaintainerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/VcmrMaintainerTest.java
index 321ec3ad8ea..52bd8e9c618 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/VcmrMaintainerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/VcmrMaintainerTest.java
@@ -16,8 +16,8 @@ import com.yahoo.vespa.hosted.controller.api.integration.vcmr.VespaChangeRequest
import com.yahoo.vespa.hosted.controller.api.integration.vcmr.VespaChangeRequest.Status;
import com.yahoo.vespa.hosted.controller.integration.MetricsMock;
import com.yahoo.vespa.hosted.controller.integration.NodeRepositoryMock;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.time.DayOfWeek;
import java.time.Duration;
@@ -27,9 +27,9 @@ import java.time.temporal.TemporalAdjusters;
import java.util.List;
import static com.yahoo.vespa.hosted.controller.maintenance.VcmrMaintainer.TRACKED_CMRS_METRIC;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author olaa
@@ -47,7 +47,7 @@ public class VcmrMaintainerTest {
private final HostName host3 = HostName.of("host3");
private final String changeRequestId = "id123";
- @Before
+ @BeforeEach
public void setup() {
tester = new ControllerTester();
metrics = new MetricsMock();
@@ -56,15 +56,15 @@ public class VcmrMaintainerTest {
}
@Test
- public void recycle_hosts_after_completion() {
+ void recycle_hosts_after_completion() {
var vcmrReport = new VcmrReport();
vcmrReport.addVcmr("id123", ZonedDateTime.now(), ZonedDateTime.now());
var parkedNode = createNode(host1, NodeType.host, Node.State.parked, true);
var failedNode = createNode(host2, NodeType.host, Node.State.failed, false);
var reports = vcmrReport.toNodeReports();
parkedNode = Node.builder(parkedNode)
- .reports(reports)
- .build();
+ .reports(reports)
+ .build();
nodeRepo.putNodes(zoneId, List.of(parkedNode, failedNode));
@@ -83,7 +83,7 @@ public class VcmrMaintainerTest {
}
@Test
- public void infrastructure_hosts_require_maunal_intervention() {
+ void infrastructure_hosts_require_maunal_intervention() {
var configNode = createNode(host1, NodeType.config, Node.State.active, false);
var activeNode = createNode(host2, NodeType.host, Node.State.active, false);
nodeRepo.putNodes(zoneId, List.of(configNode, activeNode));
@@ -103,7 +103,7 @@ public class VcmrMaintainerTest {
}
@Test
- public void retires_hosts_when_near_vcmr() {
+ void retires_hosts_when_near_vcmr() {
var activeNode = createNode(host1, NodeType.host, Node.State.active, false);
var failedNode = createNode(host2, NodeType.host, Node.State.failed, false);
nodeRepo.putNodes(zoneId, List.of(activeNode, failedNode));
@@ -125,7 +125,7 @@ public class VcmrMaintainerTest {
}
@Test
- public void no_spare_capacity_requires_operator_action() {
+ void no_spare_capacity_requires_operator_action() {
var activeNode = createNode(host1, NodeType.host, Node.State.active, false);
var failedNode = createNode(host2, NodeType.host, Node.State.failed, false);
nodeRepo.putNodes(zoneId, List.of(activeNode, failedNode));
@@ -147,7 +147,7 @@ public class VcmrMaintainerTest {
}
@Test
- public void updates_status_when_retiring_host_is_parked() {
+ void updates_status_when_retiring_host_is_parked() {
var parkedNode = createNode(host1, NodeType.host, Node.State.parked, true);
nodeRepo.putNodes(zoneId, parkedNode);
nodeRepo.hasSpareCapacity(true);
@@ -162,7 +162,7 @@ public class VcmrMaintainerTest {
}
@Test
- public void pending_retirement_when_vcmr_is_far_ahead() {
+ void pending_retirement_when_vcmr_is_far_ahead() {
var activeNode = createNode(host2, NodeType.host, Node.State.active, false);
nodeRepo.putNodes(zoneId, List.of(activeNode));
nodeRepo.hasSpareCapacity(true);
@@ -181,13 +181,13 @@ public class VcmrMaintainerTest {
activeNode = nodeRepo.list(zoneId, NodeFilter.all().hostnames(host2)).get(0);
var report = VcmrReport.fromReports(activeNode.reports());
var reportAdded = report.getVcmrs().stream()
- .filter(vcmr -> vcmr.getId().equals(changeRequestId))
- .count() == 1;
+ .filter(vcmr -> vcmr.getId().equals(changeRequestId))
+ .count() == 1;
assertTrue(reportAdded);
}
@Test
- public void recycles_nodes_if_vcmr_is_postponed() {
+ void recycles_nodes_if_vcmr_is_postponed() {
var parkedNode = createNode(host1, NodeType.host, Node.State.parked, false);
var retiringNode = createNode(host2, NodeType.host, Node.State.active, true);
nodeRepo.putNodes(zoneId, List.of(parkedNode, retiringNode));
@@ -210,7 +210,7 @@ public class VcmrMaintainerTest {
}
@Test
- public void handle_multizone_vcmr() {
+ void handle_multizone_vcmr() {
var configNode = createNode(host1, NodeType.config, Node.State.active, false);
var tenantNode1 = createNode(host2, NodeType.host, Node.State.active, false);
var tenantNode2 = createNode(host3, NodeType.host, Node.State.active, false);
@@ -234,7 +234,7 @@ public class VcmrMaintainerTest {
}
@Test
- public void out_of_sync_when_manual_reactivation() {
+ void out_of_sync_when_manual_reactivation() {
var nonRetiringNode = createNode(host1, NodeType.host, Node.State.active, false);
nodeRepo.putNodes(zoneId, nonRetiringNode);
@@ -253,7 +253,7 @@ public class VcmrMaintainerTest {
}
@Test
- public void retirement_start_time_ignores_weekends() {
+ void retirement_start_time_ignores_weekends() {
var plannedStartTime = ZonedDateTime.now().with(TemporalAdjusters.nextOrSame(DayOfWeek.WEDNESDAY));
var retirementStartTime = maintainer.getRetirementStartTime(plannedStartTime);
assertEquals(plannedStartTime.minusDays(2), retirementStartTime);
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/VersionStatusUpdaterTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/VersionStatusUpdaterTest.java
index d85ec868d56..e6f46e0630d 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/VersionStatusUpdaterTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/maintenance/VersionStatusUpdaterTest.java
@@ -5,15 +5,15 @@ import com.yahoo.vespa.hosted.controller.ControllerTester;
import com.yahoo.vespa.hosted.controller.api.integration.organization.SystemMonitor;
import com.yahoo.vespa.hosted.controller.versions.VersionStatus;
import com.yahoo.vespa.hosted.controller.versions.VespaVersion;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author bratseth
@@ -23,7 +23,7 @@ public class VersionStatusUpdaterTest {
/** Test that this job updates the status. Test of the content of the update is in
* {@link com.yahoo.vespa.hosted.controller.versions.VersionStatusTest} */
@Test
- public void testVersionUpdating() {
+ void testVersionUpdating() {
ControllerTester tester = new ControllerTester();
tester.controller().updateVersionStatus(new VersionStatus(Collections.emptyList()));
assertFalse(tester.controller().readVersionStatus().systemVersion().isPresent());
@@ -35,7 +35,7 @@ public class VersionStatusUpdaterTest {
}
@Test
- public void testConfidenceConversion() {
+ void testConfidenceConversion() {
List.of(VespaVersion.Confidence.values()).forEach(VersionStatusUpdater::convert);
assertEquals(SystemMonitor.Confidence.broken, VersionStatusUpdater.convert(VespaVersion.Confidence.broken));
assertEquals(SystemMonitor.Confidence.low, VersionStatusUpdater.convert(VespaVersion.Confidence.low));
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/notification/NotificationFormatterTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/notification/NotificationFormatterTest.java
index c643a612f00..164df0a27f5 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/notification/NotificationFormatterTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/notification/NotificationFormatterTest.java
@@ -13,12 +13,12 @@ import com.yahoo.vespa.hosted.controller.api.integration.deployment.JobType;
import com.yahoo.vespa.hosted.controller.api.integration.deployment.RunId;
import com.yahoo.vespa.hosted.controller.application.TenantAndApplicationId;
import com.yahoo.vespa.hosted.controller.integration.ZoneRegistryMock;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.List;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author enygaard
@@ -35,7 +35,7 @@ public class NotificationFormatterTest {
private final NotificationFormatter formatter = new NotificationFormatter(zoneRegistry);
@Test
- public void applicationPackage() {
+ void applicationPackage() {
var notification = new Notification(Instant.now(), Notification.Type.applicationPackage, Notification.Level.warning, NotificationSource.from(applicationId), List.of("1", "2"));
var content = formatter.format(notification);
assertEquals("Application package", content.prettyType());
@@ -44,7 +44,7 @@ public class NotificationFormatterTest {
}
@Test
- public void deployment() {
+ void deployment() {
var runId = new RunId(applicationId, JobType.prod(RegionName.defaultName()), 1001);
var notification = new Notification(Instant.now(), Notification.Type.deployment, Notification.Level.warning, NotificationSource.from(runId), List.of("1"));
var content = formatter.format(notification);
@@ -54,7 +54,7 @@ public class NotificationFormatterTest {
}
@Test
- public void deploymentError() {
+ void deploymentError() {
var runId = new RunId(applicationId, JobType.prod(RegionName.defaultName()), 1001);
var notification = new Notification(Instant.now(), Notification.Type.deployment, Notification.Level.error, NotificationSource.from(runId), List.of("1"));
var content = formatter.format(notification);
@@ -64,7 +64,7 @@ public class NotificationFormatterTest {
}
@Test
- public void testPackage() {
+ void testPackage() {
var notification = new Notification(Instant.now(), Notification.Type.testPackage, Notification.Level.warning, NotificationSource.from(TenantAndApplicationId.from(applicationId)), List.of("1"));
var content = formatter.format(notification);
assertEquals("Test package", content.prettyType());
@@ -73,7 +73,7 @@ public class NotificationFormatterTest {
}
@Test
- public void reindex() {
+ void reindex() {
var notification = new Notification(Instant.now(), Notification.Type.reindex, Notification.Level.info, NotificationSource.from(deploymentId, cluster), List.of("1"));
var content = formatter.format(notification);
assertEquals("Reindex", content.prettyType());
@@ -82,7 +82,7 @@ public class NotificationFormatterTest {
}
@Test
- public void feedBlock() {
+ void feedBlock() {
var notification = new Notification(Instant.now(), Notification.Type.feedBlock, Notification.Level.warning, NotificationSource.from(deploymentId, cluster), List.of("1"));
var content = formatter.format(notification);
assertEquals("Nearly feed blocked", content.prettyType());
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/notification/NotificationsDbTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/notification/NotificationsDbTest.java
index 5666f8bafd8..1a171341ee0 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/notification/NotificationsDbTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/notification/NotificationsDbTest.java
@@ -25,8 +25,8 @@ import com.yahoo.vespa.hosted.controller.tenant.CloudTenant;
import com.yahoo.vespa.hosted.controller.tenant.LastLoginInfo;
import com.yahoo.vespa.hosted.controller.tenant.TenantContacts;
import com.yahoo.vespa.hosted.controller.tenant.TenantInfo;
-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.ArrayList;
@@ -39,9 +39,9 @@ import java.util.stream.Collectors;
import static com.yahoo.vespa.hosted.controller.notification.Notification.Level;
import static com.yahoo.vespa.hosted.controller.notification.Notification.Type;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author freva
@@ -77,7 +77,7 @@ public class NotificationsDbTest {
private final NotificationsDb notificationsDb = new NotificationsDb(clock, curatorDb, new Notifier(curatorDb, new ZoneRegistryMock(SystemName.cd), mailer, flagSource));
@Test
- public void list_test() {
+ void list_test() {
assertEquals(notifications, notificationsDb.listNotifications(NotificationSource.from(tenant), false));
assertEquals(notificationIndices(0, 1, 2, 3), notificationsDb.listNotifications(NotificationSource.from(tenant), true));
assertEquals(notificationIndices(2, 3), notificationsDb.listNotifications(NotificationSource.from(TenantAndApplicationId.from(tenant.value(), "app2")), false));
@@ -87,7 +87,7 @@ public class NotificationsDbTest {
}
@Test
- public void add_test() {
+ void add_test() {
Notification notification1 = notification(12345, Type.deployment, Level.warning, NotificationSource.from(ApplicationId.from(tenant.value(), "app2", "instance2")), "instance msg #2");
Notification notification2 = notification(12345, Type.deployment, Level.error, NotificationSource.from(ApplicationId.from(tenant.value(), "app3", "instance2")), "instance msg #3");
@@ -103,11 +103,11 @@ public class NotificationsDbTest {
}
@Test
- public void notifier_test() {
+ void notifier_test() {
Notification notification1 = notification(12345, Type.deployment, Level.warning, NotificationSource.from(ApplicationId.from(tenant.value(), "app2", "instance2")), "instance msg #2");
Notification notification2 = notification(12345, Type.applicationPackage, Level.error, NotificationSource.from(ApplicationId.from(tenant.value(), "app3", "instance2")), "instance msg #3");
Notification notification3 = notification(12345, Type.reindex, Level.warning, NotificationSource.from(new DeploymentId(ApplicationId.from(tenant.value(), "app2", "instance2"), ZoneId.defaultId()), new ClusterSpec.Id("content")), "instance msg #2");
-;
+ ;
var a = notifications.get(0);
notificationsDb.setNotification(a.source(), a.type(), a.level(), a.messages());
assertEquals(0, mailer.inbox(email).size());
@@ -126,7 +126,7 @@ public class NotificationsDbTest {
}
@Test
- public void remove_single_test() {
+ void remove_single_test() {
// Remove the 3rd notification
notificationsDb.removeNotification(NotificationSource.from(ApplicationId.from(tenant.value(), "app2", "instance2")), Type.deployment);
@@ -137,7 +137,7 @@ public class NotificationsDbTest {
}
@Test
- public void remove_multiple_test() {
+ void remove_multiple_test() {
// Remove the 3rd notification
notificationsDb.removeNotifications(NotificationSource.from(ApplicationId.from(tenant.value(), "app1", "instance1")));
assertEquals(notificationIndices(0, 1, 2, 3), curatorDb.readNotifications(tenant));
@@ -149,7 +149,7 @@ public class NotificationsDbTest {
}
@Test
- public void deployment_metrics_notify_test() {
+ void deployment_metrics_notify_test() {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenant.value(), "app1", "instance1"), ZoneId.from("prod", "us-south-3"));
NotificationSource sourceCluster1 = NotificationSource.from(deploymentId, ClusterSpec.Id.from("cluster1"));
List<Notification> expected = new ArrayList<>(notifications);
@@ -172,7 +172,7 @@ public class NotificationsDbTest {
}
@Test
- public void feed_blocked_single_cluster_test() {
+ void feed_blocked_single_cluster_test() {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenant.value(), "app1", "instance1"), ZoneId.from("prod", "us-south-3"));
NotificationSource sourceCluster1 = NotificationSource.from(deploymentId, ClusterSpec.Id.from("cluster1"));
List<Notification> expected = new ArrayList<>(notifications);
@@ -207,7 +207,7 @@ public class NotificationsDbTest {
}
@Test
- public void deployment_metrics_multiple_cluster_test() {
+ void deployment_metrics_multiple_cluster_test() {
DeploymentId deploymentId = new DeploymentId(ApplicationId.from(tenant.value(), "app1", "instance1"), ZoneId.from("prod", "us-south-3"));
NotificationSource sourceCluster1 = NotificationSource.from(deploymentId, ClusterSpec.Id.from("cluster1"));
NotificationSource sourceCluster2 = NotificationSource.from(deploymentId, ClusterSpec.Id.from("cluster2"));
@@ -231,7 +231,7 @@ public class NotificationsDbTest {
assertEquals(expected, curatorDb.readNotifications(tenant));
}
- @Before
+ @BeforeEach
public void init() {
curatorDb.writeNotifications(tenant, notifications);
curatorDb.writeTenant(cloudTenant);
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/notification/NotifierTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/notification/NotifierTest.java
index 4132db74140..00d8c100ced 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/notification/NotifierTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/notification/NotifierTest.java
@@ -16,17 +16,15 @@ import com.yahoo.vespa.hosted.controller.tenant.CloudTenant;
import com.yahoo.vespa.hosted.controller.tenant.LastLoginInfo;
import com.yahoo.vespa.hosted.controller.tenant.TenantContacts;
import com.yahoo.vespa.hosted.controller.tenant.TenantInfo;
-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.List;
import java.util.Map;
import java.util.Optional;
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class NotifierTest {
private static final TenantName tenant = TenantName.from("tenant1");
@@ -48,13 +46,13 @@ public class NotifierTest {
MockCuratorDb curatorDb = new MockCuratorDb(SystemName.Public);
- @Before
+ @BeforeEach
public void init() {
curatorDb.writeTenant(cloudTenant);
}
@Test
- public void dispatch() {
+ void dispatch() {
var mailer = new MockMailer();
var flagSource = new InMemoryFlagSource().withBooleanFlag(Flags.NOTIFICATION_DISPATCH_FLAG.id(), true);
var notifier = new Notifier(curatorDb, new ZoneRegistryMock(SystemName.cd), mailer, flagSource);
@@ -86,7 +84,7 @@ public class NotifierTest {
}
@Test
- public void linkify() {
+ void linkify() {
var data = Map.of(
"Hello. https://example.com/foo/bar.html is a nice place.", "Hello. <a href=\"https://example.com/foo/bar.html\">https://example.com/foo/bar.html</a> is a nice place.",
"No url.", "No url.");
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ApplicationSerializerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ApplicationSerializerTest.java
index e60325a140a..88da698b3f2 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ApplicationSerializerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ApplicationSerializerTest.java
@@ -30,7 +30,7 @@ import com.yahoo.vespa.hosted.controller.metric.ApplicationMetrics;
import com.yahoo.vespa.hosted.controller.routing.rotation.RotationId;
import com.yahoo.vespa.hosted.controller.routing.rotation.RotationState;
import com.yahoo.vespa.hosted.controller.routing.rotation.RotationStatus;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.file.Files;
import java.nio.file.Path;
@@ -47,7 +47,7 @@ import java.util.OptionalInt;
import java.util.OptionalLong;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bratseth
@@ -70,18 +70,18 @@ public class ApplicationSerializerTest {
@Test
- public void testSerialization() throws Exception {
+ void testSerialization() throws Exception {
DeploymentSpec deploymentSpec = DeploymentSpec.fromXml("<deployment version='1.0'>\n" +
- " <staging/>\n" +
- " <instance id=\"i1\">\n" +
- " <prod global-service-id=\"default\">\n" +
- " <region active=\"true\">us-west-1</region>\n" +
- " </prod>\n" +
- " </instance>\n" +
- "</deployment>");
+ " <staging/>\n" +
+ " <instance id=\"i1\">\n" +
+ " <prod global-service-id=\"default\">\n" +
+ " <region active=\"true\">us-west-1</region>\n" +
+ " </prod>\n" +
+ " </instance>\n" +
+ "</deployment>");
ValidationOverrides validationOverrides = ValidationOverrides.fromXml("<validation-overrides version='1.0'>" +
- " <allow until='2017-06-15'>deployment-removal</allow>" +
- "</validation-overrides>");
+ " <allow until='2017-06-15'>deployment-removal</allow>" +
+ "</validation-overrides>");
OptionalLong projectId = OptionalLong.of(123L);
@@ -89,69 +89,69 @@ public class ApplicationSerializerTest {
ApplicationId id3 = ApplicationId.from("t1", "a1", "i3");
List<Deployment> deployments = new ArrayList<>();
ApplicationVersion applicationVersion1 = new ApplicationVersion(RevisionId.forProduction(31),
- Optional.of(new SourceRevision("git@github:org/repo.git", "branch1", "commit1")),
- Optional.of("william@shakespeare"),
- Optional.of(Version.fromString("1.2.3")),
- Optional.of(Instant.ofEpochMilli(666)),
- Optional.empty(),
- Optional.of("best commit"),
- Optional.of("hash1"),
- true,
- false,
- Optional.of("~(˘▾˘)~"),
- 3);
+ Optional.of(new SourceRevision("git@github:org/repo.git", "branch1", "commit1")),
+ Optional.of("william@shakespeare"),
+ Optional.of(Version.fromString("1.2.3")),
+ Optional.of(Instant.ofEpochMilli(666)),
+ Optional.empty(),
+ Optional.of("best commit"),
+ Optional.of("hash1"),
+ true,
+ false,
+ Optional.of("~(˘▾˘)~"),
+ 3);
assertEquals("https://github/org/repo/tree/commit1", applicationVersion1.sourceUrl().get());
ApplicationVersion applicationVersion2 = ApplicationVersion.from(RevisionId.forDevelopment(31, new JobId(id1, DeploymentContext.productionUsEast3)),
- new SourceRevision("repo1", "branch1", "commit1"), "a@b",
- Version.fromString("6.3.1"),
- Instant.ofEpochMilli(496));
+ new SourceRevision("repo1", "branch1", "commit1"), "a@b",
+ Version.fromString("6.3.1"),
+ Instant.ofEpochMilli(496));
Instant activityAt = Instant.parse("2018-06-01T10:15:30.00Z");
deployments.add(new Deployment(zone1, applicationVersion1.id(), Version.fromString("1.2.3"), Instant.ofEpochMilli(3),
- DeploymentMetrics.none, DeploymentActivity.none, QuotaUsage.none, OptionalDouble.empty()));
+ DeploymentMetrics.none, DeploymentActivity.none, QuotaUsage.none, OptionalDouble.empty()));
deployments.add(new Deployment(zone2, applicationVersion2.id(), Version.fromString("1.2.3"), Instant.ofEpochMilli(5),
- new DeploymentMetrics(2, 3, 4, 5, 6,
- Optional.of(Instant.now().truncatedTo(ChronoUnit.MILLIS)),
- Map.of(DeploymentMetrics.Warning.all, 3)),
- DeploymentActivity.create(Optional.of(activityAt), Optional.of(activityAt),
- OptionalDouble.of(200), OptionalDouble.of(10)),
- QuotaUsage.create(OptionalDouble.of(23.5)),
- OptionalDouble.of(12.3)));
+ new DeploymentMetrics(2, 3, 4, 5, 6,
+ Optional.of(Instant.now().truncatedTo(ChronoUnit.MILLIS)),
+ Map.of(DeploymentMetrics.Warning.all, 3)),
+ DeploymentActivity.create(Optional.of(activityAt), Optional.of(activityAt),
+ OptionalDouble.of(200), OptionalDouble.of(10)),
+ QuotaUsage.create(OptionalDouble.of(23.5)),
+ OptionalDouble.of(12.3)));
var rotationStatus = RotationStatus.from(Map.of(new RotationId("my-rotation"),
- new RotationStatus.Targets(
- Map.of(ZoneId.from("prod", "us-west-1"), RotationState.in,
- ZoneId.from("prod", "us-east-3"), RotationState.out),
- Instant.ofEpochMilli(42))));
+ new RotationStatus.Targets(
+ Map.of(ZoneId.from("prod", "us-west-1"), RotationState.in,
+ ZoneId.from("prod", "us-east-3"), RotationState.out),
+ Instant.ofEpochMilli(42))));
RevisionHistory revisions = RevisionHistory.ofRevisions(List.of(applicationVersion1),
- Map.of(new JobId(id1, DeploymentContext.productionUsEast3), List.of(applicationVersion2)));
+ Map.of(new JobId(id1, DeploymentContext.productionUsEast3), List.of(applicationVersion2)));
List<Instance> instances = List.of(new Instance(id1,
- deployments,
- Map.of(DeploymentContext.systemTest, Instant.ofEpochMilli(333)),
- List.of(AssignedRotation.fromStrings("foo", "default", "my-rotation", Set.of("us-west-1"))),
- rotationStatus,
- Change.of(new Version("6.1"))),
- new Instance(id3,
- List.of(),
- Map.of(),
- List.of(),
- RotationStatus.EMPTY,
- Change.of(Version.fromString("6.7")).withPin()));
+ deployments,
+ Map.of(DeploymentContext.systemTest, Instant.ofEpochMilli(333)),
+ List.of(AssignedRotation.fromStrings("foo", "default", "my-rotation", Set.of("us-west-1"))),
+ rotationStatus,
+ Change.of(new Version("6.1"))),
+ new Instance(id3,
+ List.of(),
+ Map.of(),
+ List.of(),
+ RotationStatus.EMPTY,
+ Change.of(Version.fromString("6.7")).withPin()));
Application original = new Application(TenantAndApplicationId.from(id1),
- Instant.now().truncatedTo(ChronoUnit.MILLIS),
- deploymentSpec,
- validationOverrides,
- Optional.of(IssueId.from("4321")),
- Optional.of(IssueId.from("1234")),
- Optional.of(User.from("by-username")),
- OptionalInt.of(7),
- new ApplicationMetrics(0.5, 0.9),
- Set.of(publicKey, otherPublicKey),
- projectId,
- revisions,
- instances
+ Instant.now().truncatedTo(ChronoUnit.MILLIS),
+ deploymentSpec,
+ validationOverrides,
+ Optional.of(IssueId.from("4321")),
+ Optional.of(IssueId.from("1234")),
+ Optional.of(User.from("by-username")),
+ OptionalInt.of(7),
+ new ApplicationMetrics(0.5, 0.9),
+ Set.of(publicKey, otherPublicKey),
+ projectId,
+ revisions,
+ instances
);
Application serialized = APPLICATION_SERIALIZER.fromSlime(SlimeUtils.toJsonBytes(APPLICATION_SERIALIZER.toSlime(original)));
@@ -189,9 +189,9 @@ public class ApplicationSerializerTest {
assertEquals(original.require(id1.instance()).deployments().get(zone2), serialized.require(id1.instance()).deployments().get(zone2));
assertEquals(original.require(id1.instance()).jobPause(DeploymentContext.systemTest),
- serialized.require(id1.instance()).jobPause(DeploymentContext.systemTest));
+ serialized.require(id1.instance()).jobPause(DeploymentContext.systemTest));
assertEquals(original.require(id1.instance()).jobPause(DeploymentContext.stagingTest),
- serialized.require(id1.instance()).jobPause(DeploymentContext.stagingTest));
+ serialized.require(id1.instance()).jobPause(DeploymentContext.stagingTest));
assertEquals(original.ownershipIssueId(), serialized.ownershipIssueId());
assertEquals(original.owner(), serialized.owner());
@@ -220,7 +220,7 @@ public class ApplicationSerializerTest {
}
@Test
- public void testCompleteApplicationDeserialization() throws Exception {
+ void testCompleteApplicationDeserialization() throws Exception {
byte[] applicationJson = Files.readAllBytes(testData.resolve("complete-application.json"));
APPLICATION_SERIALIZER.fromSlime(applicationJson);
// ok if no error
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ArchiveBucketsSerializerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ArchiveBucketsSerializerTest.java
index a3e4f6e6f89..82c5a6fc0c1 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ArchiveBucketsSerializerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ArchiveBucketsSerializerTest.java
@@ -3,16 +3,16 @@ package com.yahoo.vespa.hosted.controller.persistence;
import com.yahoo.config.provision.TenantName;
import com.yahoo.vespa.hosted.controller.api.integration.archive.ArchiveBucket;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.LinkedHashSet;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class ArchiveBucketsSerializerTest {
@Test
- public void serdes() {
+ void serdes() {
var testTenants = new LinkedHashSet<TenantName>();
testTenants.add(TenantName.from("tenant1"));
testTenants.add(TenantName.from("tenant2"));
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/AuditLogSerializerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/AuditLogSerializerTest.java
index c047f31e171..4508372738f 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/AuditLogSerializerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/AuditLogSerializerTest.java
@@ -2,7 +2,7 @@
package com.yahoo.vespa.hosted.controller.persistence;
import com.yahoo.vespa.hosted.controller.auditlog.AuditLog;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
@@ -10,8 +10,8 @@ import java.time.Instant;
import java.util.List;
import static java.time.temporal.ChronoUnit.MILLIS;
-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 mpolden
@@ -19,7 +19,7 @@ import static org.junit.Assert.assertTrue;
public class AuditLogSerializerTest {
@Test
- public void test_serialization() {
+ void test_serialization() {
Instant i1 = Instant.now();
Instant i2 = i1.minus(Duration.ofHours(1));
Instant i3 = i1.minus(Duration.ofHours(2));
@@ -27,20 +27,20 @@ public class AuditLogSerializerTest {
AuditLog log = new AuditLog(List.of(
new AuditLog.Entry(i1, "bar", AuditLog.Entry.Method.POST,
- "/bar/baz/",
- "0".repeat(2048).getBytes(StandardCharsets.UTF_8)),
+ "/bar/baz/",
+ "0".repeat(2048).getBytes(StandardCharsets.UTF_8)),
new AuditLog.Entry(i2, "foo", AuditLog.Entry.Method.POST,
- "/foo/bar/",
- "{\"foo\":\"bar\"}".getBytes(StandardCharsets.UTF_8)),
+ "/foo/bar/",
+ "{\"foo\":\"bar\"}".getBytes(StandardCharsets.UTF_8)),
new AuditLog.Entry(i3, "baz", AuditLog.Entry.Method.POST,
- "/foo/baz/",
- new byte[0]),
+ "/foo/baz/",
+ new byte[0]),
new AuditLog.Entry(i4, "baz", AuditLog.Entry.Method.POST,
- "/foo/baz/",
- "000\ufdff\ufeff\uffff000".getBytes(StandardCharsets.UTF_8)), // non-ascii
+ "/foo/baz/",
+ "000\ufdff\ufeff\uffff000".getBytes(StandardCharsets.UTF_8)), // non-ascii
new AuditLog.Entry(i4, "quux", AuditLog.Entry.Method.POST,
- "/foo/quux/",
- new byte[]{(byte) 0xDE, (byte) 0xAD, (byte) 0xBE, (byte) 0xEF}) // garbage
+ "/foo/quux/",
+ new byte[]{(byte) 0xDE, (byte) 0xAD, (byte) 0xBE, (byte) 0xEF}) // garbage
));
AuditLogSerializer serializer = new AuditLogSerializer();
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/BufferedLogStoreTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/BufferedLogStoreTest.java
index 87280c0c1a3..eb5422f5cff 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/BufferedLogStoreTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/BufferedLogStoreTest.java
@@ -10,7 +10,7 @@ import com.yahoo.vespa.hosted.controller.api.integration.stubs.MockRunDataStore;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentContext;
import com.yahoo.vespa.hosted.controller.deployment.RunLog;
import com.yahoo.vespa.hosted.controller.deployment.Step;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.ArrayList;
@@ -20,21 +20,21 @@ import java.util.Optional;
import java.util.stream.IntStream;
import static java.util.stream.Collectors.toUnmodifiableList;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class BufferedLogStoreTest {
@Test
- public void chunkingAndFlush() {
+ void chunkingAndFlush() {
int chunkSize = 1 << 10;
int maxChunks = 1 << 5;
CuratorDb buffer = new MockCuratorDb(SystemName.main);
RunDataStore store = new MockRunDataStore();
BufferedLogStore logs = new BufferedLogStore(chunkSize, chunkSize * maxChunks, buffer, store);
RunId id = new RunId(ApplicationId.from("tenant", "application", "instance"),
- DeploymentContext.productionUsWest1,
- 123);
+ DeploymentContext.productionUsWest1,
+ 123);
byte[] manyBytes = new byte[chunkSize / 2 + 1]; // One fits, and two (over-)fills.
Arrays.fill(manyBytes, (byte) 'O');
@@ -52,27 +52,27 @@ public class BufferedLogStoreTest {
logs.append(id.application(), id.type(), Step.deployReal, List.of(entry), false);
assertEquals(List.of(entry0),
- logs.readActive(id.application(), id.type(), -1).get(Step.deployReal));
+ logs.readActive(id.application(), id.type(), -1).get(Step.deployReal));
assertEquals(RunLog.empty(), logs.readActive(id.application(), id.type(), 0));
logs.append(id.application(), id.type(), Step.deployReal, List.of(entry), false);
assertEquals(List.of(entry0, entry1),
- logs.readActive(id.application(), id.type(), -1).get(Step.deployReal));
+ logs.readActive(id.application(), id.type(), -1).get(Step.deployReal));
assertEquals(List.of(entry1),
- logs.readActive(id.application(), id.type(), 0).get(Step.deployReal));
+ logs.readActive(id.application(), id.type(), 0).get(Step.deployReal));
assertEquals(RunLog.empty(), logs.readActive(id.application(), id.type(), 1));
logs.append(id.application(), id.type(), Step.deployReal, List.of(entry, entry, entry), false);
assertEquals(List.of(entry0, entry1, entry2, entry3, entry4),
- logs.readActive(id.application(), id.type(), -1).get(Step.deployReal));
+ logs.readActive(id.application(), id.type(), -1).get(Step.deployReal));
assertEquals(List.of(entry1, entry2, entry3, entry4),
- logs.readActive(id.application(), id.type(), 0).get(Step.deployReal));
+ logs.readActive(id.application(), id.type(), 0).get(Step.deployReal));
assertEquals(List.of(entry2, entry3, entry4),
- logs.readActive(id.application(), id.type(), 1).get(Step.deployReal));
+ logs.readActive(id.application(), id.type(), 1).get(Step.deployReal));
assertEquals(List.of(entry3, entry4),
- logs.readActive(id.application(), id.type(), 2).get(Step.deployReal));
+ logs.readActive(id.application(), id.type(), 2).get(Step.deployReal));
assertEquals(List.of(entry4),
- logs.readActive(id.application(), id.type(), 3).get(Step.deployReal));
+ logs.readActive(id.application(), id.type(), 3).get(Step.deployReal));
assertEquals(RunLog.empty(), logs.readActive(id.application(), id.type(), 4));
// We should now have three chunks, with two, two, and one entries.
@@ -86,21 +86,21 @@ public class BufferedLogStoreTest {
assertEquals(RunLog.empty(), logs.readActive(id.application(), id.type(), -1));
assertEquals(List.of(entry0, entry1, entry2, entry3, entry4),
- logs.readFinished(id, -1).get().get(Step.deployReal));
+ logs.readFinished(id, -1).get().get(Step.deployReal));
assertEquals(List.of(entry1, entry2, entry3, entry4),
- logs.readFinished(id, 0).get().get(Step.deployReal));
+ logs.readFinished(id, 0).get().get(Step.deployReal));
assertEquals(List.of(entry2, entry3, entry4),
- logs.readFinished(id, 1).get().get(Step.deployReal));
+ logs.readFinished(id, 1).get().get(Step.deployReal));
assertEquals(List.of(entry3, entry4),
- logs.readFinished(id, 2).get().get(Step.deployReal));
+ logs.readFinished(id, 2).get().get(Step.deployReal));
assertEquals(List.of(entry4),
- logs.readFinished(id, 3).get().get(Step.deployReal));
+ logs.readFinished(id, 3).get().get(Step.deployReal));
assertEquals(List.of(), logs.readFinished(id, 4).get().get(Step.deployReal));
// Logging a large entry enough times to reach the maximum size causes no further entries to be stored.
List<LogEntry> monsterLog = IntStream.range(0, 2 * maxChunks + 3)
- .mapToObj(i -> new LogEntry(i, entry.at(), entry.type(), entry.message()))
- .collect(toUnmodifiableList());
+ .mapToObj(i -> new LogEntry(i, entry.at(), entry.type(), entry.message()))
+ .collect(toUnmodifiableList());
List<LogEntry> logged = new ArrayList<>(monsterLog);
logged.remove(logged.size() - 1);
logged.remove(logged.size() - 1);
@@ -109,18 +109,18 @@ public class BufferedLogStoreTest {
logs.append(id.application(), id.type(), Step.deployReal, monsterLog, false);
assertEquals(logged.size(),
- logs.readActive(id.application(), id.type(), -1).get(Step.deployReal).size());
+ logs.readActive(id.application(), id.type(), -1).get(Step.deployReal).size());
assertEquals(logged,
- logs.readActive(id.application(), id.type(), -1).get(Step.deployReal));
+ logs.readActive(id.application(), id.type(), -1).get(Step.deployReal));
// An additional, forced entry is appended.
LogEntry forced = new LogEntry(logged.size(), entry.at(), entry.type(), entry.message());
logs.append(id.application(), id.type(), Step.deployReal, List.of(forced), true);
logged.add(forced);
assertEquals(logged.size(),
- logs.readActive(id.application(), id.type(), -1).get(Step.deployReal).size());
+ logs.readActive(id.application(), id.type(), -1).get(Step.deployReal).size());
assertEquals(logged,
- logs.readActive(id.application(), id.type(), -1).get(Step.deployReal));
+ logs.readActive(id.application(), id.type(), -1).get(Step.deployReal));
logged.remove(logged.size() - 1);
// Flushing the buffer clears it again, and makes it ready for reuse.
@@ -128,9 +128,9 @@ public class BufferedLogStoreTest {
for (int i = 0; i < 2 * maxChunks + 3; i++)
logs.append(id.application(), id.type(), Step.deployReal, List.of(entry), false);
assertEquals(logged.size(),
- logs.readActive(id.application(), id.type(), -1).get(Step.deployReal).size());
+ logs.readActive(id.application(), id.type(), -1).get(Step.deployReal).size());
assertEquals(logged,
- logs.readActive(id.application(), id.type(), -1).get(Step.deployReal));
+ logs.readActive(id.application(), id.type(), -1).get(Step.deployReal));
}
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ChangeRequestSerializerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ChangeRequestSerializerTest.java
index a52a6b81eb9..77686467336 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ChangeRequestSerializerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ChangeRequestSerializerTest.java
@@ -6,13 +6,13 @@ import com.yahoo.vespa.hosted.controller.api.integration.vcmr.ChangeRequest;
import com.yahoo.vespa.hosted.controller.api.integration.vcmr.ChangeRequestSource;
import com.yahoo.vespa.hosted.controller.api.integration.vcmr.HostAction;
import com.yahoo.vespa.hosted.controller.api.integration.vcmr.VespaChangeRequest;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.time.ZonedDateTime;
import java.util.List;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author olaa
@@ -20,7 +20,7 @@ import static org.junit.Assert.assertEquals;
public class ChangeRequestSerializerTest {
@Test
- public void reserialization_equality() {
+ void reserialization_equality() {
var source = new ChangeRequestSource("aws", "id321", "url", ChangeRequestSource.Status.STARTED, ZonedDateTime.now(), ZonedDateTime.now());
var actionPlan = List.of(
new HostAction("host1", HostAction.State.RETIRING, Instant.now()),
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ControllerVersionSerializerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ControllerVersionSerializerTest.java
index 20cc82f0143..a7188cfa93e 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ControllerVersionSerializerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ControllerVersionSerializerTest.java
@@ -3,11 +3,11 @@ package com.yahoo.vespa.hosted.controller.persistence;
import com.yahoo.component.Version;
import com.yahoo.vespa.hosted.controller.api.identifiers.ControllerVersion;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Instant;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author mpolden
@@ -17,7 +17,7 @@ public class ControllerVersionSerializerTest {
private final ControllerVersionSerializer serializer = new ControllerVersionSerializer();
@Test
- public void serialization() {
+ void serialization() {
var version = new ControllerVersion(Version.fromString("7.42.1"), "badc0ffee", Instant.ofEpochSecond(1565876112));
var serialized = serializer.fromSlime(serializer.toSlime(version));
assertEquals(version.version(), serialized.version());
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/EndpointCertificateMetadataSerializerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/EndpointCertificateMetadataSerializerTest.java
index c4aa2b5a18b..819d9282618 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/EndpointCertificateMetadataSerializerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/EndpointCertificateMetadataSerializerTest.java
@@ -2,12 +2,12 @@
package com.yahoo.vespa.hosted.controller.persistence;
import com.yahoo.vespa.hosted.controller.api.integration.certificates.EndpointCertificateMetadata;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Optional;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class EndpointCertificateMetadataSerializerTest {
@@ -18,21 +18,21 @@ public class EndpointCertificateMetadataSerializerTest {
new EndpointCertificateMetadata("keyName", "certName", 1, 0, "rootRequestId", Optional.empty(), List.of("SAN1", "SAN2"), "issuer", Optional.empty(), Optional.empty());
@Test
- public void serialize_with_optional_fields() {
+ void serialize_with_optional_fields() {
assertEquals(
"{\"keyName\":\"keyName\",\"certName\":\"certName\",\"version\":1,\"lastRequested\":0,\"requestId\":\"rootRequestId\",\"leafRequestId\":\"leafRequestId\",\"requestedDnsSans\":[\"SAN1\",\"SAN2\"],\"issuer\":\"issuer\",\"expiry\":1628000000,\"lastRefreshed\":1612000000}",
EndpointCertificateMetadataSerializer.toSlime(sampleWithOptionalFieldsSet).toString());
}
@Test
- public void serialize_without_optional_fields() {
+ void serialize_without_optional_fields() {
assertEquals(
"{\"keyName\":\"keyName\",\"certName\":\"certName\",\"version\":1,\"lastRequested\":0,\"requestId\":\"rootRequestId\",\"requestedDnsSans\":[\"SAN1\",\"SAN2\"],\"issuer\":\"issuer\"}",
EndpointCertificateMetadataSerializer.toSlime(sampleWithoutOptionalFieldsSet).toString());
}
@Test
- public void deserialize_from_json_with_optional_fields() {
+ void deserialize_from_json_with_optional_fields() {
assertEquals(
sampleWithOptionalFieldsSet,
EndpointCertificateMetadataSerializer.fromJsonString(
@@ -40,7 +40,7 @@ public class EndpointCertificateMetadataSerializerTest {
}
@Test
- public void deserialize_from_json_without_optional_fields() {
+ void deserialize_from_json_without_optional_fields() {
assertEquals(
sampleWithoutOptionalFieldsSet,
EndpointCertificateMetadataSerializer.fromJsonString(
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/LogSerializerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/LogSerializerTest.java
index 1e63b87e7c6..d03a17edde2 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/LogSerializerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/LogSerializerTest.java
@@ -3,7 +3,7 @@ package com.yahoo.vespa.hosted.controller.persistence;
import com.yahoo.vespa.hosted.controller.api.integration.LogEntry;
import com.yahoo.vespa.hosted.controller.deployment.Step;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.file.Files;
@@ -17,7 +17,7 @@ import java.util.Map;
import static com.yahoo.vespa.hosted.controller.deployment.Step.deployReal;
import static com.yahoo.vespa.hosted.controller.deployment.Step.deployTester;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author jonmv
@@ -28,7 +28,7 @@ public class LogSerializerTest {
private static final Path logsFile = Paths.get("src/test/java/com/yahoo/vespa/hosted/controller/persistence/testdata/logs.json");
@Test
- public void testSerialization() throws IOException {
+ void testSerialization() throws IOException {
for (LogEntry.Type type : LogEntry.Type.values())
assertEquals(type, LogSerializer.typeOf(LogSerializer.valueOf(type)));
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/NameServiceQueueSerializerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/NameServiceQueueSerializerTest.java
index 5ecc22ffc5e..6f0a36690ed 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/NameServiceQueueSerializerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/NameServiceQueueSerializerTest.java
@@ -11,11 +11,11 @@ import com.yahoo.vespa.hosted.controller.dns.CreateRecord;
import com.yahoo.vespa.hosted.controller.dns.CreateRecords;
import com.yahoo.vespa.hosted.controller.dns.NameServiceQueue;
import com.yahoo.vespa.hosted.controller.dns.RemoveRecords;
-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 mpolden
@@ -25,20 +25,20 @@ public class NameServiceQueueSerializerTest {
private final NameServiceQueueSerializer serializer = new NameServiceQueueSerializer();
@Test
- public void test_serialization() {
+ void test_serialization() {
var record1 = new Record(Record.Type.CNAME, RecordName.from("cname.example.com"), RecordData.from("example.com"));
var record2 = new Record(Record.Type.TXT, RecordName.from("txt.example.com"), RecordData.from("text"));
var requests = List.of(
new CreateRecord(record1),
new CreateRecords(List.of(record2)),
new CreateRecords(List.of(new Record(Record.Type.ALIAS, RecordName.from("alias.example.com"),
- new LatencyAliasTarget(HostName.of("alias1"),
- "dns-zone-01",
- ZoneId.from("prod", "us-north-1")).pack()),
- new Record(Record.Type.ALIAS, RecordName.from("alias.example.com"),
- new LatencyAliasTarget(HostName.of("alias2"),
- "dns-zone-02",
- ZoneId.from("prod", "us-north-2")).pack()))
+ new LatencyAliasTarget(HostName.of("alias1"),
+ "dns-zone-01",
+ ZoneId.from("prod", "us-north-1")).pack()),
+ new Record(Record.Type.ALIAS, RecordName.from("alias.example.com"),
+ new LatencyAliasTarget(HostName.of("alias2"),
+ "dns-zone-02",
+ ZoneId.from("prod", "us-north-2")).pack()))
),
new RemoveRecords(record1.type(), record1.name()),
new RemoveRecords(record2.type(), record2.data())
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/NotificationsSerializerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/NotificationsSerializerTest.java
index 370b1cbe02c..c9755672232 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/NotificationsSerializerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/NotificationsSerializerTest.java
@@ -10,13 +10,13 @@ import com.yahoo.vespa.hosted.controller.application.TenantAndApplicationId;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentContext;
import com.yahoo.vespa.hosted.controller.notification.Notification;
import com.yahoo.vespa.hosted.controller.notification.NotificationSource;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.time.Instant;
import java.util.List;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author freva
@@ -24,7 +24,7 @@ import static org.junit.Assert.assertEquals;
public class NotificationsSerializerTest {
@Test
- public void serialization_test() throws IOException {
+ void serialization_test() throws IOException {
NotificationsSerializer serializer = new NotificationsSerializer();
TenantName tenantName = TenantName.from("tenant1");
List<Notification> notifications = List.of(
@@ -42,20 +42,20 @@ public class NotificationsSerializerTest {
Slime serialized = serializer.toSlime(notifications);
assertEquals("{\"notifications\":[" +
"{" +
- "\"at\":1234000," +
- "\"type\":\"applicationPackage\"," +
- "\"level\":\"warning\"," +
- "\"messages\":[\"Something something deprecated...\"]," +
- "\"application\":\"app1\"" +
+ "\"at\":1234000," +
+ "\"type\":\"applicationPackage\"," +
+ "\"level\":\"warning\"," +
+ "\"messages\":[\"Something something deprecated...\"]," +
+ "\"application\":\"app1\"" +
"},{" +
- "\"at\":2345000," +
- "\"type\":\"deployment\"," +
- "\"level\":\"error\"," +
- "\"messages\":[\"Failed to deploy: Node allocation failure\"]," +
- "\"application\":\"app1\"," +
- "\"instance\":\"instance1\"," +
- "\"jobId\":\"test.us-east-1\"," +
- "\"runNumber\":12" +
+ "\"at\":2345000," +
+ "\"type\":\"deployment\"," +
+ "\"level\":\"error\"," +
+ "\"messages\":[\"Failed to deploy: Node allocation failure\"]," +
+ "\"application\":\"app1\"," +
+ "\"instance\":\"instance1\"," +
+ "\"jobId\":\"test.us-east-1\"," +
+ "\"runNumber\":12" +
"}]}", new String(SlimeUtils.toJsonBytes(serialized)));
List<Notification> deserialized = serializer.fromSlime(tenantName, serialized);
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/OsVersionSerializerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/OsVersionSerializerTest.java
index c722b3bbb96..568b17817a1 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/OsVersionSerializerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/OsVersionSerializerTest.java
@@ -5,11 +5,11 @@ import com.google.common.collect.ImmutableSet;
import com.yahoo.component.Version;
import com.yahoo.config.provision.CloudName;
import com.yahoo.vespa.hosted.controller.versions.OsVersion;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author mpolden
@@ -17,7 +17,7 @@ import static org.junit.Assert.assertEquals;
public class OsVersionSerializerTest {
@Test
- public void test_serialization() {
+ void test_serialization() {
OsVersionSerializer serializer = new OsVersionSerializer();
Set<OsVersion> osVersions = ImmutableSet.of(
new OsVersion(Version.fromString("7.1"), CloudName.defaultName()),
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/OsVersionStatusSerializerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/OsVersionStatusSerializerTest.java
index d50c071d98e..7461bf6516c 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/OsVersionStatusSerializerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/OsVersionStatusSerializerTest.java
@@ -8,7 +8,7 @@ import com.yahoo.config.provision.zone.ZoneId;
import com.yahoo.vespa.hosted.controller.versions.NodeVersion;
import com.yahoo.vespa.hosted.controller.versions.OsVersion;
import com.yahoo.vespa.hosted.controller.versions.OsVersionStatus;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.LinkedHashMap;
@@ -16,7 +16,7 @@ import java.util.List;
import java.util.Map;
import java.util.Optional;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author mpolden
@@ -24,7 +24,7 @@ import static org.junit.Assert.assertEquals;
public class OsVersionStatusSerializerTest {
@Test
- public void serialization() {
+ void serialization() {
Version version1 = Version.fromString("7.1");
Version version2 = Version.fromString("7.2");
Map<OsVersion, List<NodeVersion>> versions = new LinkedHashMap<>();
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/OsVersionTargetSerializerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/OsVersionTargetSerializerTest.java
index 1af4465528d..654703b36c0 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/OsVersionTargetSerializerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/OsVersionTargetSerializerTest.java
@@ -6,13 +6,13 @@ import com.yahoo.component.Version;
import com.yahoo.config.provision.CloudName;
import com.yahoo.vespa.hosted.controller.versions.OsVersion;
import com.yahoo.vespa.hosted.controller.versions.OsVersionTarget;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author mpolden
@@ -20,7 +20,7 @@ import static org.junit.Assert.assertEquals;
public class OsVersionTargetSerializerTest {
@Test
- public void serialization() {
+ void serialization() {
OsVersionTargetSerializer serializer = new OsVersionTargetSerializer(new OsVersionSerializer());
Set<OsVersionTarget> targets = ImmutableSet.of(
new OsVersionTarget(new OsVersion(Version.fromString("7.1"), CloudName.defaultName()), Duration.ZERO, Instant.ofEpochMilli(123)),
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/RoutingPolicySerializerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/RoutingPolicySerializerTest.java
index 2e8ba84d4ff..3df459513d7 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/RoutingPolicySerializerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/RoutingPolicySerializerTest.java
@@ -9,7 +9,7 @@ import com.yahoo.vespa.hosted.controller.application.EndpointId;
import com.yahoo.vespa.hosted.controller.routing.RoutingPolicy;
import com.yahoo.vespa.hosted.controller.routing.RoutingPolicyId;
import com.yahoo.vespa.hosted.controller.routing.RoutingStatus;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.Iterator;
@@ -17,7 +17,7 @@ import java.util.List;
import java.util.Optional;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author mortent
@@ -27,34 +27,34 @@ public class RoutingPolicySerializerTest {
private final RoutingPolicySerializer serializer = new RoutingPolicySerializer();
@Test
- public void serialization() {
+ void serialization() {
var owner = ApplicationId.defaultId();
var instanceEndpoints = Set.of(EndpointId.of("r1"), EndpointId.of("r2"));
var applicationEndpoints = Set.of(EndpointId.of("a1"));
var id1 = new RoutingPolicyId(owner,
- ClusterSpec.Id.from("my-cluster1"),
- ZoneId.from("prod", "us-north-1"));
+ ClusterSpec.Id.from("my-cluster1"),
+ ZoneId.from("prod", "us-north-1"));
var id2 = new RoutingPolicyId(owner,
- ClusterSpec.Id.from("my-cluster2"),
- ZoneId.from("prod", "us-north-2"));
+ ClusterSpec.Id.from("my-cluster2"),
+ ZoneId.from("prod", "us-north-2"));
var policies = List.of(new RoutingPolicy(id1,
- HostName.of("long-and-ugly-name"),
- Optional.of("zone1"),
- instanceEndpoints,
- applicationEndpoints,
- new RoutingPolicy.Status(true, RoutingStatus.DEFAULT)),
- new RoutingPolicy(id2,
- HostName.of("long-and-ugly-name-2"),
- Optional.empty(),
- instanceEndpoints,
- Set.of(),
- new RoutingPolicy.Status(false,
- new RoutingStatus(RoutingStatus.Value.out,
- RoutingStatus.Agent.tenant,
- Instant.ofEpochSecond(123)))));
+ HostName.of("long-and-ugly-name"),
+ Optional.of("zone1"),
+ instanceEndpoints,
+ applicationEndpoints,
+ new RoutingPolicy.Status(true, RoutingStatus.DEFAULT)),
+ new RoutingPolicy(id2,
+ HostName.of("long-and-ugly-name-2"),
+ Optional.empty(),
+ instanceEndpoints,
+ Set.of(),
+ new RoutingPolicy.Status(false,
+ new RoutingStatus(RoutingStatus.Value.out,
+ RoutingStatus.Agent.tenant,
+ Instant.ofEpochSecond(123)))));
var serialized = serializer.fromSlime(owner, serializer.toSlime(policies));
assertEquals(policies.size(), serialized.size());
- for (Iterator<RoutingPolicy> it1 = policies.iterator(), it2 = serialized.iterator(); it1.hasNext();) {
+ for (Iterator<RoutingPolicy> it1 = policies.iterator(), it2 = serialized.iterator(); it1.hasNext(); ) {
var expected = it1.next();
var actual = it2.next();
assertEquals(expected.id(), actual.id());
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/RunSerializerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/RunSerializerTest.java
index 6a01a70eb98..644f26e888a 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/RunSerializerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/RunSerializerTest.java
@@ -15,7 +15,7 @@ import com.yahoo.vespa.hosted.controller.deployment.Run;
import com.yahoo.vespa.hosted.controller.deployment.RunStatus;
import com.yahoo.vespa.hosted.controller.deployment.Step;
import com.yahoo.vespa.hosted.controller.deployment.StepInfo;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.file.Files;
@@ -46,9 +46,9 @@ import static com.yahoo.vespa.hosted.controller.deployment.Step.startStagingSetu
import static com.yahoo.vespa.hosted.controller.deployment.Step.startTests;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.time.temporal.ChronoUnit.MILLIS;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
public class RunSerializerTest {
@@ -60,7 +60,7 @@ public class RunSerializerTest {
private static final Instant start = Instant.parse("2007-12-03T10:15:30.00Z");
@Test
- public void testSerialization() throws IOException {
+ void testSerialization() throws IOException {
for (Step step : Step.values())
assertEquals(step, RunSerializer.stepOf(RunSerializer.valueOf(step)));
@@ -89,16 +89,16 @@ public class RunSerializerTest {
assertEquals(new Version(1, 2, 2), run.versions().sourcePlatform().get());
assertEquals(revision2, run.versions().sourceRevision().get());
assertEquals(Optional.of(new ConvergenceSummary(1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233)),
- run.convergenceSummary());
+ run.convergenceSummary());
assertEquals(X509CertificateUtils.fromPem("-----BEGIN CERTIFICATE-----\n" +
- "MIIBEzCBu6ADAgECAgEBMAoGCCqGSM49BAMEMBQxEjAQBgNVBAMTCW15c2Vydmlj\n" +
- "ZTAeFw0xOTA5MDYwNzM3MDZaFw0xOTA5MDcwNzM3MDZaMBQxEjAQBgNVBAMTCW15\n" +
- "c2VydmljZTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABM0JhD8fV2DlAkjQOGX3\n" +
- "Y50ryMBr3g2+v/uFiRoxJ1muuSOWYrW7HCQIGuzc04fa0QwtaX/voAZKCV51t6jF\n" +
- "0fwwCgYIKoZIzj0EAwQDRwAwRAIgVbQ3Co1H4X0gmRrtXSyTU0HgBQu9PXHMmX20\n" +
- "5MyyPSoCIBltOcmaPfdN03L3zqbqZ6PgUBWsvAHgiBzL3hrtJ+iy\n" +
- "-----END CERTIFICATE-----"),
- run.testerCertificate().get());
+ "MIIBEzCBu6ADAgECAgEBMAoGCCqGSM49BAMEMBQxEjAQBgNVBAMTCW15c2Vydmlj\n" +
+ "ZTAeFw0xOTA5MDYwNzM3MDZaFw0xOTA5MDcwNzM3MDZaMBQxEjAQBgNVBAMTCW15\n" +
+ "c2VydmljZTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABM0JhD8fV2DlAkjQOGX3\n" +
+ "Y50ryMBr3g2+v/uFiRoxJ1muuSOWYrW7HCQIGuzc04fa0QwtaX/voAZKCV51t6jF\n" +
+ "0fwwCgYIKoZIzj0EAwQDRwAwRAIgVbQ3Co1H4X0gmRrtXSyTU0HgBQu9PXHMmX20\n" +
+ "5MyyPSoCIBltOcmaPfdN03L3zqbqZ6PgUBWsvAHgiBzL3hrtJ+iy\n" +
+ "-----END CERTIFICATE-----"),
+ run.testerCertificate().get());
assertEquals(ImmutableMap.<Step, StepInfo>builder()
.put(deployInitialReal, new StepInfo(deployInitialReal, unfinished, Optional.empty()))
.put(installInitialReal, new StepInfo(installInitialReal, failed, Optional.of(Instant.ofEpochMilli(1196676940000L))))
@@ -118,10 +118,10 @@ public class RunSerializerTest {
run.steps());
run = run.with(1L << 50)
- .with(Instant.now().truncatedTo(MILLIS))
- .noNodesDownSince(Instant.now().truncatedTo(MILLIS))
- .aborted()
- .finished(Instant.now().truncatedTo(MILLIS));
+ .with(Instant.now().truncatedTo(MILLIS))
+ .noNodesDownSince(Instant.now().truncatedTo(MILLIS))
+ .aborted()
+ .finished(Instant.now().truncatedTo(MILLIS));
assertEquals(aborted, run.status());
assertTrue(run.hasEnded());
@@ -140,7 +140,7 @@ public class RunSerializerTest {
assertEquals(run.reason(), phoenix.reason());
assertEquals(new String(SlimeUtils.toJsonBytes(serializer.toSlime(run).get(), false), UTF_8),
- new String(SlimeUtils.toJsonBytes(serializer.toSlime(phoenix).get(), false), UTF_8));
+ new String(SlimeUtils.toJsonBytes(serializer.toSlime(phoenix).get(), false), UTF_8));
Run initial = Run.initial(id, run.versions(), run.isRedeployment(), run.start(), JobProfile.production, Optional.empty());
assertEquals(initial, serializer.runFromSlime(serializer.toSlime(initial)));
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/SupportAccessSerializerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/SupportAccessSerializerTest.java
index 8b2c291f751..8aa53fb5cd4 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/SupportAccessSerializerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/SupportAccessSerializerTest.java
@@ -11,7 +11,7 @@ import com.yahoo.slime.Slime;
import com.yahoo.vespa.hosted.controller.support.access.SupportAccess;
import com.yahoo.vespa.hosted.controller.support.access.SupportAccessGrant;
import org.intellij.lang.annotations.Language;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.security.auth.x500.X500Principal;
import java.io.ByteArrayOutputStream;
@@ -22,7 +22,7 @@ import java.security.cert.X509Certificate;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class SupportAccessSerializerTest {
@@ -78,70 +78,70 @@ public class SupportAccessSerializerTest {
}
@Test
- public void serialize_default() {
+ void serialize_default() {
var slime = SupportAccessSerializer.serializeCurrentState(SupportAccess.DISALLOWED_NO_HISTORY, Instant.EPOCH);
assertSerialized(slime, "{\n" +
- " \"state\": {\n" +
- " \"supportAccess\": \"NOT_ALLOWED\"\n" +
- " },\n" +
- " \"history\": [ ],\n" +
- " \"grants\": [ ]\n" +
- "}\n");
+ " \"state\": {\n" +
+ " \"supportAccess\": \"NOT_ALLOWED\"\n" +
+ " },\n" +
+ " \"history\": [ ],\n" +
+ " \"grants\": [ ]\n" +
+ "}\n");
}
@Test
- public void serialize_with_certificates() {
+ void serialize_with_certificates() {
var slime = SupportAccessSerializer.toSlime(supportAccessExample);
assertSerialized(slime, expectedWithCertificates);
}
@Test
- public void serialize_with_status() {
+ void serialize_with_status() {
var slime = SupportAccessSerializer.serializeCurrentState(supportAccessExample, hour(12));
assertSerialized(slime,
- "{\n"
- + " \"state\": {\n"
- + " \"supportAccess\": \"ALLOWED\",\n"
- + " \"until\": \"1970-01-02T12:00:00Z\",\n"
- + " \"by\": \"andreer\"\n"
- + " },\n"
- + " \"history\": [\n"
- + " {\n"
- + " \"state\": \"allowed\",\n"
- + " \"at\": \"1970-01-02T06:00:00Z\",\n"
- + " \"until\": \"1970-01-02T12:00:00Z\",\n"
- + " \"by\": \"andreer\"\n"
- + " },\n"
- + " {\n"
- + " \"state\": \"disallowed\",\n"
- + " \"at\": \"1970-01-01T22:00:00Z\",\n"
- + " \"by\": \"andreer\"\n"
- + " },\n"
- + " {\n"
- + " \"state\": \"allowed\",\n"
- + " \"at\": \"1970-01-01T02:00:00Z\",\n"
- + " \"until\": \"1970-01-02T00:00:00Z\",\n"
- + " \"by\": \"andreer\"\n"
- + " },\n"
- + " {\n"
- + " \"state\": \"grant\",\n"
- + " \"at\": \"1970-01-01T03:00:00Z\",\n"
- + " \"until\": \"1970-01-01T04:00:00Z\",\n"
- + " \"by\": \"mortent\"\n"
- + " }\n"
- + " ],\n"
- + " \"grants\": [\n"
- + " {\n"
- + " \"requestor\": \"mortent\",\n"
- + " \"notBefore\": \"1970-01-01T07:00:00Z\",\n"
- + " \"notAfter\": \"1970-01-01T19:00:00Z\"\n"
- + " }\n"
- + " ]\n"
- + "}\n");
+ "{\n"
+ + " \"state\": {\n"
+ + " \"supportAccess\": \"ALLOWED\",\n"
+ + " \"until\": \"1970-01-02T12:00:00Z\",\n"
+ + " \"by\": \"andreer\"\n"
+ + " },\n"
+ + " \"history\": [\n"
+ + " {\n"
+ + " \"state\": \"allowed\",\n"
+ + " \"at\": \"1970-01-02T06:00:00Z\",\n"
+ + " \"until\": \"1970-01-02T12:00:00Z\",\n"
+ + " \"by\": \"andreer\"\n"
+ + " },\n"
+ + " {\n"
+ + " \"state\": \"disallowed\",\n"
+ + " \"at\": \"1970-01-01T22:00:00Z\",\n"
+ + " \"by\": \"andreer\"\n"
+ + " },\n"
+ + " {\n"
+ + " \"state\": \"allowed\",\n"
+ + " \"at\": \"1970-01-01T02:00:00Z\",\n"
+ + " \"until\": \"1970-01-02T00:00:00Z\",\n"
+ + " \"by\": \"andreer\"\n"
+ + " },\n"
+ + " {\n"
+ + " \"state\": \"grant\",\n"
+ + " \"at\": \"1970-01-01T03:00:00Z\",\n"
+ + " \"until\": \"1970-01-01T04:00:00Z\",\n"
+ + " \"by\": \"mortent\"\n"
+ + " }\n"
+ + " ],\n"
+ + " \"grants\": [\n"
+ + " {\n"
+ + " \"requestor\": \"mortent\",\n"
+ + " \"notBefore\": \"1970-01-01T07:00:00Z\",\n"
+ + " \"notAfter\": \"1970-01-01T19:00:00Z\"\n"
+ + " }\n"
+ + " ]\n"
+ + "}\n");
}
@Test
- public void deserialize() {
+ void deserialize() {
var slime = SupportAccessSerializer.toSlime(supportAccessExample);
assertSerialized(slime, expectedWithCertificates);
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/TenantSerializerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/TenantSerializerTest.java
index a9e633a78d6..e29d4afabff 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/TenantSerializerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/TenantSerializerTest.java
@@ -23,7 +23,7 @@ import com.yahoo.vespa.hosted.controller.tenant.TenantBilling;
import com.yahoo.vespa.hosted.controller.tenant.TenantContact;
import com.yahoo.vespa.hosted.controller.tenant.TenantContacts;
import com.yahoo.vespa.hosted.controller.tenant.TenantInfo;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.security.PublicKey;
@@ -33,9 +33,9 @@ import java.util.List;
import java.util.Map;
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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author mpolden
@@ -53,12 +53,12 @@ public class TenantSerializerTest {
"-----END PUBLIC KEY-----\n");
@Test
- public void athenz_tenant() {
+ void athenz_tenant() {
AthenzTenant tenant = AthenzTenant.create(TenantName.from("athenz-tenant"),
- new AthenzDomain("domain1"),
- new Property("property1"),
- Optional.of(new PropertyId("1")),
- Instant.ofEpochMilli(1234L));
+ new AthenzDomain("domain1"),
+ new Property("property1"),
+ Optional.of(new PropertyId("1")),
+ Instant.ofEpochMilli(1234L));
AthenzTenant serialized = (AthenzTenant) serializer.tenantFrom(serializer.toSlime(tenant));
assertEquals(tenant.name(), serialized.name());
assertEquals(tenant.domain(), serialized.domain());
@@ -69,41 +69,41 @@ public class TenantSerializerTest {
}
@Test
- public void athenz_tenant_without_property_id() {
+ void athenz_tenant_without_property_id() {
AthenzTenant tenant = AthenzTenant.create(TenantName.from("athenz-tenant"),
- new AthenzDomain("domain1"),
- new Property("property1"),
- Optional.empty(),
- Instant.EPOCH);
+ new AthenzDomain("domain1"),
+ new Property("property1"),
+ Optional.empty(),
+ Instant.EPOCH);
AthenzTenant serialized = (AthenzTenant) serializer.tenantFrom(serializer.toSlime(tenant));
assertFalse(serialized.propertyId().isPresent());
assertEquals(tenant.propertyId(), serialized.propertyId());
}
@Test
- public void athenz_tenant_with_contact() {
+ void athenz_tenant_with_contact() {
AthenzTenant tenant = new AthenzTenant(TenantName.from("athenz-tenant"),
- new AthenzDomain("domain1"),
- new Property("property1"),
- Optional.of(new PropertyId("1")),
- Optional.of(contact()),
- Instant.EPOCH,
- lastLoginInfo(321L, 654L, 987L));
+ new AthenzDomain("domain1"),
+ new Property("property1"),
+ Optional.of(new PropertyId("1")),
+ Optional.of(contact()),
+ Instant.EPOCH,
+ lastLoginInfo(321L, 654L, 987L));
AthenzTenant serialized = (AthenzTenant) serializer.tenantFrom(serializer.toSlime(tenant));
assertEquals(tenant.contact(), serialized.contact());
}
@Test
- public void cloud_tenant() {
+ void cloud_tenant() {
CloudTenant tenant = new CloudTenant(TenantName.from("elderly-lady"),
- Instant.ofEpochMilli(1234L),
- lastLoginInfo(123L, 456L, null),
- Optional.of(new SimplePrincipal("foobar-user")),
- ImmutableBiMap.of(publicKey, new SimplePrincipal("joe"),
- otherPublicKey, new SimplePrincipal("jane")),
- TenantInfo.empty(),
- List.of(),
- new ArchiveAccess()
+ Instant.ofEpochMilli(1234L),
+ lastLoginInfo(123L, 456L, null),
+ Optional.of(new SimplePrincipal("foobar-user")),
+ ImmutableBiMap.of(publicKey, new SimplePrincipal("joe"),
+ otherPublicKey, new SimplePrincipal("jane")),
+ TenantInfo.empty(),
+ List.of(),
+ new ArchiveAccess()
);
CloudTenant serialized = (CloudTenant) serializer.tenantFrom(serializer.toSlime(tenant));
assertEquals(tenant.name(), serialized.name());
@@ -113,7 +113,7 @@ public class TenantSerializerTest {
}
@Test
- public void cloud_tenant_with_info() {
+ void cloud_tenant_with_info() {
CloudTenant tenant = new CloudTenant(TenantName.from("elderly-lady"),
Instant.EPOCH,
lastLoginInfo(null, 789L, 654L),
@@ -133,7 +133,7 @@ public class TenantSerializerTest {
}
@Test
- public void cloud_tenant_with_old_archive_access_serialization() {
+ void cloud_tenant_with_old_archive_access_serialization() {
var json = "{\n" +
" \"name\": \"elderly-lady\",\n" +
" \"type\": \"cloud\",\n" +
@@ -165,7 +165,7 @@ public class TenantSerializerTest {
}
@Test
- public void cloud_tenant_with_archive_access() {
+ void cloud_tenant_with_archive_access() {
CloudTenant tenant = new CloudTenant(TenantName.from("elderly-lady"),
Instant.ofEpochMilli(1234L),
lastLoginInfo(123L, 456L, null),
@@ -182,7 +182,7 @@ public class TenantSerializerTest {
}
@Test
- public void cloud_tenant_with_tenant_info_partial() {
+ void cloud_tenant_with_tenant_info_partial() {
TenantInfo partialInfo = TenantInfo.empty()
.withAddress(TenantAddress.empty().withCity("Hønefoss"));
@@ -193,7 +193,7 @@ public class TenantSerializerTest {
}
@Test
- public void cloud_tenant_with_tenant_info_full() {
+ void cloud_tenant_with_tenant_info_full() {
TenantInfo fullInfo = TenantInfo.empty()
.withName("My Company")
.withEmail("email@mycomp.any")
@@ -222,7 +222,7 @@ public class TenantSerializerTest {
}
@Test
- public void cloud_tenant_with_tenant_info_contacts() {
+ void cloud_tenant_with_tenant_info_contacts() {
TenantInfo tenantInfo = TenantInfo.empty()
.withContacts(new TenantContacts(List.of(
new TenantContacts.EmailContact(List.of(TenantContacts.Audience.TENANT), "email1@email.com"),
@@ -235,7 +235,7 @@ public class TenantSerializerTest {
}
@Test
- public void deleted_tenant() {
+ void deleted_tenant() {
DeletedTenant tenant = new DeletedTenant(
TenantName.from("tenant1"), Instant.ofEpochMilli(1234L), Instant.ofEpochMilli(2345L));
DeletedTenant serialized = (DeletedTenant) serializer.tenantFrom(serializer.toSlime(tenant));
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/VersionStatusSerializerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/VersionStatusSerializerTest.java
index 73cfc6ad2f3..618c33835bd 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/VersionStatusSerializerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/VersionStatusSerializerTest.java
@@ -7,7 +7,7 @@ import com.yahoo.config.provision.zone.ZoneId;
import com.yahoo.vespa.hosted.controller.versions.NodeVersion;
import com.yahoo.vespa.hosted.controller.versions.VersionStatus;
import com.yahoo.vespa.hosted.controller.versions.VespaVersion;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.ArrayList;
@@ -15,7 +15,7 @@ import java.util.List;
import java.util.Optional;
import static java.time.temporal.ChronoUnit.MILLIS;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author mpolden
@@ -23,15 +23,15 @@ import static org.junit.Assert.assertEquals;
public class VersionStatusSerializerTest {
@Test
- public void testSerialization() {
+ void testSerialization() {
List<VespaVersion> vespaVersions = new ArrayList<>();
Version version = Version.fromString("5.0");
vespaVersions.add(new VespaVersion(version, "dead", Instant.now(), false, false,
- true, nodeVersions(Version.fromString("5.0"), Version.fromString("5.1"),
- "cfg1", "cfg2", "cfg3"), VespaVersion.Confidence.normal));
+ true, nodeVersions(Version.fromString("5.0"), Version.fromString("5.1"),
+ "cfg1", "cfg2", "cfg3"), VespaVersion.Confidence.normal));
vespaVersions.add(new VespaVersion(version, "cafe", Instant.now(), true, true,
- false, nodeVersions(Version.fromString("5.0"), Version.fromString("5.1"),
- "cfg1", "cfg2", "cfg3"), VespaVersion.Confidence.normal));
+ false, nodeVersions(Version.fromString("5.0"), Version.fromString("5.1"),
+ "cfg1", "cfg2", "cfg3"), VespaVersion.Confidence.normal));
VersionStatus status = new VersionStatus(vespaVersions);
VersionStatusSerializer serializer = new VersionStatusSerializer(new NodeVersionSerializer());
VersionStatus deserialized = serializer.fromSlime(serializer.toSlime(status));
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ZoneRoutingPolicySerializerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ZoneRoutingPolicySerializerTest.java
index 234de233571..f524f4a2d4f 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ZoneRoutingPolicySerializerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/persistence/ZoneRoutingPolicySerializerTest.java
@@ -4,11 +4,11 @@ package com.yahoo.vespa.hosted.controller.persistence;
import com.yahoo.config.provision.zone.ZoneId;
import com.yahoo.vespa.hosted.controller.routing.RoutingStatus;
import com.yahoo.vespa.hosted.controller.routing.ZoneRoutingPolicy;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Instant;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author mpolden
@@ -16,12 +16,12 @@ import static org.junit.Assert.assertEquals;
public class ZoneRoutingPolicySerializerTest {
@Test
- public void serialization() {
+ void serialization() {
var serializer = new ZoneRoutingPolicySerializer(new RoutingPolicySerializer());
var zone = ZoneId.from("prod", "us-north-1");
var policy = new ZoneRoutingPolicy(zone,
- RoutingStatus.create(RoutingStatus.Value.out, RoutingStatus.Agent.operator,
- Instant.ofEpochMilli(123)));
+ RoutingStatus.create(RoutingStatus.Value.out, RoutingStatus.Agent.operator,
+ Instant.ofEpochMilli(123)));
var serialized = serializer.fromSlime(zone, serializer.toSlime(policy));
assertEquals(policy, serialized);
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/proxy/ConfigServerRestExecutorImplTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/proxy/ConfigServerRestExecutorImplTest.java
index f5926e799af..5214ded0904 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/proxy/ConfigServerRestExecutorImplTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/proxy/ConfigServerRestExecutorImplTest.java
@@ -2,7 +2,7 @@
package com.yahoo.vespa.hosted.controller.proxy;
import ai.vespa.http.HttpURL.Path;
-import com.github.tomakehurst.wiremock.junit.WireMockRule;
+import com.github.tomakehurst.wiremock.junit5.WireMockExtension;
import com.github.tomakehurst.wiremock.stubbing.Scenario;
import com.yahoo.container.jdisc.HttpRequest;
import com.yahoo.container.jdisc.HttpResponse;
@@ -10,8 +10,8 @@ import com.yahoo.yolean.concurrent.Sleeper;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpCoreContext;
-import org.junit.Rule;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
import javax.net.ssl.SSLContext;
import java.io.ByteArrayOutputStream;
@@ -25,21 +25,21 @@ import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author mpolden
*/
public class ConfigServerRestExecutorImplTest {
- @Rule
- public final WireMockRule wireMock = new WireMockRule(options().dynamicPort(), true);
+ @RegisterExtension
+ public final WireMockExtension wireMock = WireMockExtension.newInstance().options(options().dynamicPort()).failOnUnmatchedRequests(true).build();
@Test
- public void proxy_with_retries() throws Exception {
+ void proxy_with_retries() throws Exception {
var connectionReuseStrategy = new CountingConnectionReuseStrategy(Set.of("127.0.0.1"));
var proxy = new ConfigServerRestExecutorImpl(new SSLConnectionSocketFactory(SSLContext.getDefault()),
- Sleeper.NOOP, connectionReuseStrategy);
+ Sleeper.NOOP, connectionReuseStrategy);
URI url = url();
String path = url.getPath();
@@ -61,10 +61,10 @@ public class ConfigServerRestExecutorImplTest {
}
@Test
- public void proxy_without_connection_reuse() throws Exception {
+ void proxy_without_connection_reuse() throws Exception {
var connectionReuseStrategy = new CountingConnectionReuseStrategy(Set.of());
var proxy = new ConfigServerRestExecutorImpl(new SSLConnectionSocketFactory(SSLContext.getDefault()),
- Sleeper.NOOP, connectionReuseStrategy);
+ Sleeper.NOOP, connectionReuseStrategy);
URI url = url();
String path = url.getPath();
@@ -79,7 +79,7 @@ public class ConfigServerRestExecutorImplTest {
}
private URI url() {
- return URI.create("http://127.0.0.1:" + wireMock.port() + "/");
+ return URI.create("http://127.0.0.1:" + wireMock.getPort() + "/");
}
private void stubRequests(String path) {
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/proxy/ProxyRequestTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/proxy/ProxyRequestTest.java
index e6de60c859b..d851eb56890 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/proxy/ProxyRequestTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/proxy/ProxyRequestTest.java
@@ -3,14 +3,14 @@ package com.yahoo.vespa.hosted.controller.proxy;
import ai.vespa.http.HttpURL.Path;
import com.yahoo.jdisc.http.HttpRequest;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.util.List;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* @author Haakon Dybdahl
@@ -18,14 +18,14 @@ import static org.junit.Assert.assertThrows;
public class ProxyRequestTest {
@Test
- public void testBadUri() {
+ void testBadUri() {
assertEquals("Request path '/path' does not end with proxy path '/zone/v2/'",
- assertThrows(IllegalArgumentException.class,
- () -> testRequest("http://domain.tld/path", "/zone/v2/")).getMessage());
+ assertThrows(IllegalArgumentException.class,
+ () -> testRequest("http://domain.tld/path", "/zone/v2/")).getMessage());
}
@Test
- public void testUris() {
+ void testUris() {
{
// Root request
ProxyRequest request = testRequest("http://controller.domain.tld/my/path", "");
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/proxy/ProxyResponseTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/proxy/ProxyResponseTest.java
index 845d007c154..08164de6a8e 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/proxy/ProxyResponseTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/proxy/ProxyResponseTest.java
@@ -3,7 +3,7 @@ package com.yahoo.vespa.hosted.controller.proxy;
import ai.vespa.http.HttpURL.Path;
import com.yahoo.jdisc.http.HttpRequest;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.net.URI;
@@ -11,7 +11,7 @@ import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Haakon Dybdahl
@@ -19,7 +19,7 @@ import static org.junit.Assert.assertEquals;
public class ProxyResponseTest {
@Test
- public void testRewriteUrl() throws Exception {
+ void testRewriteUrl() throws Exception {
ProxyRequest request = new ProxyRequest(HttpRequest.Method.GET, URI.create("http://domain.tld/zone/v2/dev/us-north-1/configserver"),
Map.of(), null, List.of(URI.create("http://example.com")), Path.parse("configserver"));
ProxyResponse proxyResponse = new ProxyResponse(
@@ -37,9 +37,9 @@ public class ProxyResponseTest {
}
@Test
- public void testRewriteSecureUrl() throws Exception {
+ void testRewriteSecureUrl() throws Exception {
ProxyRequest request = new ProxyRequest(HttpRequest.Method.GET, URI.create("https://domain.tld/zone/v2/prod/eu-south-3/configserver"),
- Map.of(), null, List.of(URI.create("http://example.com")), Path.parse("configserver"));
+ Map.of(), null, List.of(URI.create("http://example.com")), Path.parse("configserver"));
ProxyResponse proxyResponse = new ProxyResponse(
request,
"response link is http://configserver:4443/bla/bla/",
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/ContainerTester.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/ContainerTester.java
index 07f00e8c989..539d6cff06d 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/ContainerTester.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/ContainerTester.java
@@ -28,8 +28,8 @@ import java.util.Optional;
import java.util.function.Supplier;
import static java.nio.charset.StandardCharsets.UTF_8;
-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;
/**
* Provides testing of JSON container responses
@@ -123,7 +123,7 @@ public class ContainerTester {
catch (IOException e) {
fail("failed writing JSON: " + e);
}
- assertEquals("Status code", expectedStatusCode, response.getStatus());
+ assertEquals(expectedStatusCode, response.getStatus(), "Status code");
}
public void assertResponse(Supplier<Request> request, String expectedResponse) {
@@ -154,7 +154,7 @@ public class ContainerTester {
} catch (Exception e) {
throw new RuntimeException(e);
}
- assertEquals("Status code", expectedStatusCode, response.getStatus());
+ assertEquals(expectedStatusCode, response.getStatus(), "Status code");
}
// Hack to run request filters as part of the request processing chain.
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/ControllerContainerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/ControllerContainerTest.java
index 87fe8dd17fe..404dcca87c0 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/ControllerContainerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/ControllerContainerTest.java
@@ -9,8 +9,8 @@ import com.yahoo.vespa.athenz.api.AthenzIdentity;
import com.yahoo.vespa.athenz.api.AthenzUser;
import com.yahoo.vespa.athenz.api.OAuthCredentials;
import com.yahoo.vespa.hosted.controller.api.integration.athenz.AthenzClientFactoryMock;
-import org.junit.After;
-import org.junit.Before;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
import static com.yahoo.vespa.hosted.controller.integration.AthenzFilterMock.IDENTITY_HEADER_NAME;
import static com.yahoo.vespa.hosted.controller.integration.AthenzFilterMock.OKTA_ACCESS_TOKEN_HEADER_NAME;
@@ -33,7 +33,7 @@ public class ControllerContainerTest {
protected JDisc container;
- @Before
+ @BeforeEach
public void startContainer() {
container = JDisc.fromServicesXml(controllerServicesXml(), networking());
addUserToHostedOperatorRole(hostedOperator);
@@ -41,7 +41,7 @@ public class ControllerContainerTest {
protected Networking networking() { return Networking.disable; }
- @After
+ @AfterEach
public void stopContainer() { container.close(); }
private String controllerServicesXml() {
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/ApplicationApiCloudTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/ApplicationApiCloudTest.java
index 26dd6335ab8..674424fbdd9 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/ApplicationApiCloudTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/ApplicationApiCloudTest.java
@@ -27,8 +27,8 @@ import com.yahoo.vespa.hosted.controller.security.Auth0Credentials;
import com.yahoo.vespa.hosted.controller.security.CloudTenantSpec;
import com.yahoo.vespa.hosted.controller.security.Credentials;
import com.yahoo.vespa.hosted.controller.tenant.CloudTenant;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.util.Collections;
@@ -40,10 +40,10 @@ import static com.yahoo.application.container.handler.Request.Method.GET;
import static com.yahoo.application.container.handler.Request.Method.POST;
import static com.yahoo.application.container.handler.Request.Method.PUT;
import static com.yahoo.vespa.hosted.controller.restapi.application.ApplicationApiTest.createApplicationSubmissionData;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author oyving
@@ -57,7 +57,7 @@ public class ApplicationApiCloudTest extends ControllerContainerCloudTest {
private static final TenantName tenantName = TenantName.from("scoober");
private static final ApplicationName applicationName = ApplicationName.from("albums");
- @Before
+ @BeforeEach
public void before() {
tester = new ContainerTester(container, responseFiles);
((InMemoryFlagSource) tester.controller().flagSource())
@@ -66,7 +66,7 @@ public class ApplicationApiCloudTest extends ControllerContainerCloudTest {
}
@Test
- public void test_missing_security_clients_pem() {
+ void test_missing_security_clients_pem() {
var application = prodBuilder().build();
var deployRequest = request("/application/v4/tenant/scoober/application/albums/submit", POST)
@@ -80,7 +80,7 @@ public class ApplicationApiCloudTest extends ControllerContainerCloudTest {
}
@Test
- public void tenant_info_profile() {
+ void tenant_info_profile() {
var request = request("/application/v4/tenant/scoober/info/profile", GET)
.roles(Set.of(Role.reader(tenantName)));
tester.assertResponse(request, "{}", 200);
@@ -94,7 +94,7 @@ public class ApplicationApiCloudTest extends ControllerContainerCloudTest {
}
@Test
- public void tenant_info_billing() {
+ void tenant_info_billing() {
var request = request("/application/v4/tenant/scoober/info/billing", GET)
.roles(Set.of(Role.reader(tenantName)));
tester.assertResponse(request, "{}", 200);
@@ -111,7 +111,7 @@ public class ApplicationApiCloudTest extends ControllerContainerCloudTest {
}
@Test
- public void tenant_info_contacts() {
+ void tenant_info_contacts() {
var request = request("/application/v4/tenant/scoober/info/contacts", GET)
.roles(Set.of(Role.reader(tenantName)));
tester.assertResponse(request, "{\"contacts\":[]}", 200);
@@ -126,10 +126,10 @@ public class ApplicationApiCloudTest extends ControllerContainerCloudTest {
}
@Test
- public void tenant_info_workflow() {
+ void tenant_info_workflow() {
var infoRequest =
request("/application/v4/tenant/scoober/info", GET)
- .roles(Set.of(Role.reader(tenantName)));
+ .roles(Set.of(Role.reader(tenantName)));
tester.assertResponse(infoRequest, "{}", 200);
String partialInfo = "{\"contactName\":\"newName\", \"contactEmail\": \"foo@example.com\", \"billingContact\":{\"name\":\"billingName\"}}";
@@ -166,7 +166,7 @@ public class ApplicationApiCloudTest extends ControllerContainerCloudTest {
}
@Test
- public void tenant_info_missing_fields() {
+ void tenant_info_missing_fields() {
// tenants can be created with empty tenant info - they're not part of the POST to v4/tenant
var infoRequest =
request("/application/v4/tenant/scoober/info", GET)
@@ -255,7 +255,7 @@ public class ApplicationApiCloudTest extends ControllerContainerCloudTest {
}
@Test
- public void trial_tenant_limit_reached() {
+ void trial_tenant_limit_reached() {
((InMemoryFlagSource) tester.controller().flagSource()).withIntFlag(PermanentFlags.MAX_TRIAL_TENANTS.id(), 1);
tester.controller().serviceRegistry().billingController().setPlan(tenantName, PlanId.from("pay-as-you-go"), false, false);
@@ -273,7 +273,7 @@ public class ApplicationApiCloudTest extends ControllerContainerCloudTest {
}
@Test
- public void test_secret_store_configuration() {
+ void test_secret_store_configuration() {
var secretStoreRequest =
request("/application/v4/tenant/scoober/secret-store/some-name", PUT)
.data("{" +
@@ -303,7 +303,7 @@ public class ApplicationApiCloudTest extends ControllerContainerCloudTest {
}
@Test
- public void validate_secret_store() {
+ void validate_secret_store() {
deployApplication();
var secretStoreRequest =
request("/application/v4/tenant/scoober/secret-store/secret-foo/validate?aws-region=us-west-1&parameter-name=foo&application-id=scoober.albums.default&zone=prod.aws-us-east-1c", GET)
@@ -326,7 +326,7 @@ public class ApplicationApiCloudTest extends ControllerContainerCloudTest {
}
@Test
- public void delete_secret_store() {
+ void delete_secret_store() {
var deleteRequest =
request("/application/v4/tenant/scoober/secret-store/secret-foo", DELETE)
.roles(Set.of(Role.developer(tenantName)));
@@ -347,18 +347,18 @@ public class ApplicationApiCloudTest extends ControllerContainerCloudTest {
}
@Test
- public void archive_uri_test() {
+ void archive_uri_test() {
ControllerTester wrapped = new ControllerTester(tester);
wrapped.upgradeSystem(Version.fromString("7.1"));
new DeploymentTester(wrapped).newDeploymentContext(ApplicationId.from(tenantName, applicationName, InstanceName.defaultName()))
- .submit()
- .deploy();
+ .submit()
+ .deploy();
tester.assertResponse(request("/application/v4/tenant/scoober", GET).roles(Role.reader(tenantName)),
(response) -> assertFalse(response.getBodyAsString().contains("archiveAccessRole")),
200);
tester.assertResponse(request("/application/v4/tenant/scoober/archive-access", PUT)
- .data("{\"role\":\"dummy\"}").roles(Role.administrator(tenantName)),
+ .data("{\"role\":\"dummy\"}").roles(Role.administrator(tenantName)),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"Invalid archive access role 'dummy': Must match expected pattern: 'arn:aws:iam::\\\\d{12}:.+'\"}", 400);
tester.assertResponse(request("/application/v4/tenant/scoober/archive-access/aws", PUT)
@@ -411,7 +411,7 @@ public class ApplicationApiCloudTest extends ControllerContainerCloudTest {
}
@Test
- public void create_application_on_deploy() {
+ void create_application_on_deploy() {
var application = ApplicationName.from("unique");
var applicationPackage = new ApplicationPackageBuilder().withoutAthenzIdentity().build();
@@ -420,15 +420,15 @@ public class ApplicationApiCloudTest extends ControllerContainerCloudTest {
tester.assertResponse(
request("/application/v4/tenant/scoober/application/unique/instance/default/deploy/dev-aws-us-east-1c", POST)
- .data(createApplicationDeployData(Optional.of(applicationPackage), Optional.empty(), true))
- .roles(Set.of(Role.developer(tenantName))),
+ .data(createApplicationDeployData(Optional.of(applicationPackage), Optional.empty(), true))
+ .roles(Set.of(Role.developer(tenantName))),
"{\"message\":\"Deployment started in run 1 of dev-aws-us-east-1c for scoober.unique. This may take about 15 minutes the first time.\",\"run\":1}");
assertTrue(tester.controller().applications().getApplication(TenantAndApplicationId.from(tenantName, application)).isPresent());
}
@Test
- public void create_application_on_submit() {
+ void create_application_on_submit() {
var application = ApplicationName.from("unique");
var applicationPackage = new ApplicationPackageBuilder()
.trustDefaultCertificate()
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/ApplicationApiTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/ApplicationApiTest.java
index 2435bb2efb8..e3292700432 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/ApplicationApiTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/ApplicationApiTest.java
@@ -70,8 +70,8 @@ import com.yahoo.vespa.hosted.controller.tenant.AthenzTenant;
import com.yahoo.vespa.hosted.controller.tenant.LastLoginInfo;
import com.yahoo.vespa.hosted.controller.versions.VespaVersion;
import com.yahoo.yolean.Exceptions;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import javax.security.auth.x500.X500Principal;
import java.io.File;
@@ -100,9 +100,9 @@ import static com.yahoo.application.container.handler.Request.Method.PUT;
import static java.net.URLEncoder.encode;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.stream.Collectors.joining;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author bratseth
@@ -153,7 +153,7 @@ public class ApplicationApiTest extends ControllerContainerTest {
private ContainerTester tester;
private DeploymentTester deploymentTester;
- @Before
+ @BeforeEach
public void before() {
tester = new ContainerTester(container, responseFiles);
deploymentTester = new DeploymentTester(new ControllerTester(tester));
@@ -161,24 +161,24 @@ public class ApplicationApiTest extends ControllerContainerTest {
}
@Test
- public void testApplicationApi() {
+ void testApplicationApi() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID); // (Necessary but not provided in this API)
// GET API root
tester.assertResponse(request("/application/v4/", GET).userIdentity(USER_ID),
- new File("root.json"));
+ new File("root.json"));
// POST (add) a tenant without property ID
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
- .userIdentity(USER_ID)
- .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
- .oAuthCredentials(OKTA_CREDENTIALS),
- new File("tenant-without-applications.json"));
+ .userIdentity(USER_ID)
+ .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ new File("tenant-without-applications.json"));
// PUT (modify) a tenant
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
- .userIdentity(USER_ID)
- .oAuthCredentials(OKTA_CREDENTIALS)
- .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
- new File("tenant-without-applications.json"));
+ .userIdentity(USER_ID)
+ .oAuthCredentials(OKTA_CREDENTIALS)
+ .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
+ new File("tenant-without-applications.json"));
// Add another Athens domain, so we can try to create more tenants
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN_2, USER_ID); // New domain to test tenant w/property ID
@@ -187,59 +187,59 @@ public class ApplicationApiTest extends ControllerContainerTest {
// POST (add) a tenant with property ID
tester.assertResponse(request("/application/v4/tenant/tenant2", POST)
- .userIdentity(USER_ID)
- .oAuthCredentials(OKTA_CREDENTIALS)
- .data("{\"athensDomain\":\"domain2\", \"property\":\"property2\", \"propertyId\":\"1234\"}"),
- new File("tenant-without-applications-with-id.json"));
+ .userIdentity(USER_ID)
+ .oAuthCredentials(OKTA_CREDENTIALS)
+ .data("{\"athensDomain\":\"domain2\", \"property\":\"property2\", \"propertyId\":\"1234\"}"),
+ new File("tenant-without-applications-with-id.json"));
// PUT (modify) a tenant with property ID
tester.assertResponse(request("/application/v4/tenant/tenant2", PUT)
- .userIdentity(USER_ID)
- .oAuthCredentials(OKTA_CREDENTIALS)
- .data("{\"athensDomain\":\"domain2\", \"property\":\"property2\", \"propertyId\":\"1234\"}"),
- new File("tenant-without-applications-with-id.json"));
+ .userIdentity(USER_ID)
+ .oAuthCredentials(OKTA_CREDENTIALS)
+ .data("{\"athensDomain\":\"domain2\", \"property\":\"property2\", \"propertyId\":\"1234\"}"),
+ new File("tenant-without-applications-with-id.json"));
// GET a tenant with property ID and contact information
updateContactInformation();
tester.controller().tenants().updateLastLogin(TenantName.from("tenant2"),
List.of(LastLoginInfo.UserLevel.user, LastLoginInfo.UserLevel.administrator), Instant.ofEpochMilli(1234));
tester.assertResponse(request("/application/v4/tenant/tenant2", GET).userIdentity(USER_ID),
- new File("tenant2.json"));
+ new File("tenant2.json"));
// POST (create) an application
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
- .userIdentity(USER_ID)
- .oAuthCredentials(OKTA_CREDENTIALS),
- new File("instance-reference.json"));
+ .userIdentity(USER_ID)
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ new File("instance-reference.json"));
// GET a tenant
tester.assertResponse(request("/application/v4/tenant/tenant1", GET).userIdentity(USER_ID),
- new File("tenant-with-application.json"));
+ new File("tenant-with-application.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1", GET)
- .userIdentity(USER_ID)
- .properties(Map.of("activeInstances", "true")),
- new File("tenant-without-applications.json"));
+ .userIdentity(USER_ID)
+ .properties(Map.of("activeInstances", "true")),
+ new File("tenant-without-applications.json"));
// GET tenant applications
tester.assertResponse(request("/application/v4/tenant/tenant1/application/", GET).userIdentity(USER_ID),
- new File("application-list.json"));
+ new File("application-list.json"));
// GET tenant application instances for application that does not exist
tester.assertResponse(request("/application/v4/tenant/tenant1/application/fake-app/instance/", GET).userIdentity(USER_ID),
"{\"error-code\":\"NOT_FOUND\",\"message\":\"Application 'fake-app' does not exist\"}", 404);
// GET tenant applications (instances of "application1" only)
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/", GET).userIdentity(USER_ID),
- new File("application-list.json"));
+ new File("application-list.json"));
// GET at a tenant, with "&recursive=true&production=true", recurses over no instances yet, as they are not in deployment spec.
tester.assertResponse(request("/application/v4/tenant/tenant1/", GET)
- .userIdentity(USER_ID)
- .properties(Map.of("recursive", "true",
- "production", "true")),
- new File("tenant-with-empty-application.json"));
+ .userIdentity(USER_ID)
+ .properties(Map.of("recursive", "true",
+ "production", "true")),
+ new File("tenant-with-empty-application.json"));
// GET at an application, with "&recursive=true&production=true", recurses over no instances yet, as they are not in deployment spec.
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", GET)
- .userIdentity(USER_ID)
- .properties(Map.of("recursive", "true",
- "production", "true")),
- new File("application-without-instances.json"));
+ .userIdentity(USER_ID)
+ .properties(Map.of("recursive", "true",
+ "production", "true")),
+ new File("application-without-instances.json"));
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
@@ -249,87 +249,87 @@ public class ApplicationApiTest extends ControllerContainerTest {
// POST (deploy) an application to start a manual deployment in prod is not allowed
MultiPartStreamer entity = createApplicationDeployData(applicationPackageInstance1);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploy/production-us-east-3/", POST)
- .data(entity)
- .userIdentity(USER_ID),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Direct deployments are only allowed to manually deployed environments.\"}", 400);
+ .data(entity)
+ .userIdentity(USER_ID),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Direct deployments are only allowed to manually deployed environments.\"}", 400);
// POST (deploy) an application to start a manual deployment in prod is allowed for operators
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploy/production-us-east-3/", POST)
- .data(entity)
- .userIdentity(HOSTED_VESPA_OPERATOR),
- "{\"message\":\"Deployment started in run 1 of production-us-east-3 for tenant1.application1.instance1. This may take about 15 minutes the first time.\",\"run\":1}");
+ .data(entity)
+ .userIdentity(HOSTED_VESPA_OPERATOR),
+ "{\"message\":\"Deployment started in run 1 of production-us-east-3 for tenant1.application1.instance1. This may take about 15 minutes the first time.\",\"run\":1}");
app1.runJob(DeploymentContext.productionUsEast3);
tester.controller().applications().deactivate(app1.instanceId(), ZoneId.from("prod", "us-east-3"));
// POST (deploy) an application to start a manual deployment to dev
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploy/dev-us-east-1/", POST)
- .data(entity)
- .userIdentity(USER_ID),
- "{\"message\":\"Deployment started in run 1 of dev-us-east-1 for tenant1.application1.instance1. This may take about 15 minutes the first time.\",\"run\":1}");
+ .data(entity)
+ .userIdentity(USER_ID),
+ "{\"message\":\"Deployment started in run 1 of dev-us-east-1 for tenant1.application1.instance1. This may take about 15 minutes the first time.\",\"run\":1}");
app1.runJob(DeploymentContext.devUsEast1);
// POST (deploy) a job to restart a manual deployment to dev
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/dev-us-east-1", POST)
- .userIdentity(USER_ID),
- "{\"message\":\"Triggered dev-us-east-1 for tenant1.application1.instance1\"}");
+ .userIdentity(USER_ID),
+ "{\"message\":\"Triggered dev-us-east-1 for tenant1.application1.instance1\"}");
app1.runJob(DeploymentContext.devUsEast1);
// GET dev application package
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/dev-us-east-1/package", GET)
- .userIdentity(USER_ID),
- (response) -> {
- assertEquals("attachment; filename=\"tenant1.application1.instance1.dev.us-east-1.zip\"", response.getHeaders().getFirst("Content-Disposition"));
- assertArrayEquals(applicationPackageInstance1.zippedContent(), response.getBody());
- },
- 200);
+ .userIdentity(USER_ID),
+ (response) -> {
+ assertEquals("attachment; filename=\"tenant1.application1.instance1.dev.us-east-1.zip\"", response.getHeaders().getFirst("Content-Disposition"));
+ assertArrayEquals(applicationPackageInstance1.zippedContent(), response.getBody());
+ },
+ 200);
// POST an application package is not generally allowed under user instance
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser/deploy/dev-us-east-1", POST)
- .userIdentity(OTHER_USER_ID)
- .data(createApplicationDeployData(applicationPackageInstance1)),
- accessDenied,
- 403);
+ .userIdentity(OTHER_USER_ID)
+ .data(createApplicationDeployData(applicationPackageInstance1)),
+ accessDenied,
+ 403);
// DELETE a dev deployment is not generally allowed under user instance
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/otheruser/environment/dev/region/us-east-1", DELETE)
- .userIdentity(OTHER_USER_ID),
- accessDenied,
- 403);
+ .userIdentity(OTHER_USER_ID),
+ accessDenied,
+ 403);
// When the user is a tenant admin, user instances are allowed.
// POST an application package is not allowed under user instance for tenant admins
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/myuser/deploy/dev-us-east-1", POST)
- .userIdentity(USER_ID)
- .data(createApplicationDeployData(applicationPackageInstance1)),
- new File("deployment-job-accepted-2.json"));
+ .userIdentity(USER_ID)
+ .data(createApplicationDeployData(applicationPackageInstance1)),
+ new File("deployment-job-accepted-2.json"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/myuser/job/dev-us-east-1/diff/1", GET).userIdentity(HOSTED_VESPA_OPERATOR),
- (response) -> assertTrue(response.getBodyAsString(),
- response.getBodyAsString().contains("--- schemas/test.sd\n" +
+ (response) -> assertTrue(response.getBodyAsString().contains("--- schemas/test.sd\n" +
"@@ -1,0 +1,1 @@\n" +
- "+ search test { }\n")),
+ "+ search test { }\n"),
+ response.getBodyAsString()),
200);
// DELETE a dev deployment is allowed under user instance for tenant admins
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/myuser/environment/dev/region/us-east-1", DELETE)
- .userIdentity(USER_ID),
- "{\"message\":\"Deactivated tenant1.application1.myuser in dev.us-east-1\"}");
+ .userIdentity(USER_ID),
+ "{\"message\":\"Deactivated tenant1.application1.myuser in dev.us-east-1\"}");
// DELETE a user instance
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/myuser", DELETE)
- .userIdentity(USER_ID)
- .oAuthCredentials(OKTA_CREDENTIALS),
- "{\"message\":\"Deleted instance tenant1.application1.myuser\"}");
+ .userIdentity(USER_ID)
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ "{\"message\":\"Deleted instance tenant1.application1.myuser\"}");
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
- ATHENZ_TENANT_DOMAIN,
- id.application());
+ ATHENZ_TENANT_DOMAIN,
+ id.application());
// POST an application package and a test jar, submitting a new application for production deployment.
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit", POST)
- .screwdriverIdentity(SCREWDRIVER_ID)
- .data(createApplicationSubmissionData(applicationPackageInstance1, 123)),
- "{\"message\":\"application build 1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
+ .screwdriverIdentity(SCREWDRIVER_ID)
+ .data(createApplicationSubmissionData(applicationPackageInstance1, 123)),
+ "{\"message\":\"application build 1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
app1.runJob(DeploymentContext.systemTest).runJob(DeploymentContext.stagingTest).runJob(DeploymentContext.productionUsCentral1);
@@ -344,102 +344,102 @@ public class ApplicationApiTest extends ControllerContainerTest {
// POST (create) another application
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/default", POST)
- .userIdentity(USER_ID)
- .oAuthCredentials(OKTA_CREDENTIALS),
- new File("instance-reference-2.json"));
+ .userIdentity(USER_ID)
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ new File("instance-reference-2.json"));
ApplicationId id2 = ApplicationId.from("tenant2", "application2", "instance1");
var app2 = deploymentTester.newDeploymentContext(id2);
addScrewdriverUserToDeployRole(SCREWDRIVER_ID,
- ATHENZ_TENANT_DOMAIN_2,
- id2.application());
+ ATHENZ_TENANT_DOMAIN_2,
+ id2.application());
// POST an application package and a test jar, submitting a new application for production deployment.
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/submit", POST)
- .screwdriverIdentity(SCREWDRIVER_ID)
- .data(createApplicationSubmissionData(applicationPackage, 1000)),
- "{\"message\":\"application build 1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
+ .screwdriverIdentity(SCREWDRIVER_ID)
+ .data(createApplicationSubmissionData(applicationPackage, 1000)),
+ "{\"message\":\"application build 1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
deploymentTester.triggerJobs();
// POST a triggering to force a production job to start without successful tests
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/instance1/job/production-us-west-1", POST)
- .data("{ \"skipTests\": true, \"skipRevision\": true, \"skipUpgrade\": true }")
- .userIdentity(USER_ID),
- "{\"message\":\"Triggered production-us-west-1 for tenant2.application2.instance1, without revision and platform upgrade\"}");
+ .data("{ \"skipTests\": true, \"skipRevision\": true, \"skipUpgrade\": true }")
+ .userIdentity(USER_ID),
+ "{\"message\":\"Triggered production-us-west-1 for tenant2.application2.instance1, without revision and platform upgrade\"}");
app2.runJob(DeploymentContext.productionUsWest1);
// POST a re-triggering to force a production job to start with previous parameters
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/instance1/job/production-us-west-1", POST)
- .data("{\"reTrigger\":true}")
- .userIdentity(USER_ID),
- "{\"message\":\"Triggered production-us-west-1 for tenant2.application2.instance1\"}");
+ .data("{\"reTrigger\":true}")
+ .userIdentity(USER_ID),
+ "{\"message\":\"Triggered production-us-west-1 for tenant2.application2.instance1\"}");
// DELETE manually deployed prod deployment again
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/instance1/environment/prod/region/us-west-1", DELETE)
- .userIdentity(HOSTED_VESPA_OPERATOR),
- "{\"message\":\"Deactivated tenant2.application2.instance1 in prod.us-west-1\"}");
+ .userIdentity(HOSTED_VESPA_OPERATOR),
+ "{\"message\":\"Deactivated tenant2.application2.instance1 in prod.us-west-1\"}");
// GET application having both change and outstanding change
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", GET)
- .screwdriverIdentity(SCREWDRIVER_ID),
- new File("application2.json"));
+ .screwdriverIdentity(SCREWDRIVER_ID),
+ new File("application2.json"));
// PATCH in a major version override
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", PATCH)
- .userIdentity(USER_ID)
- .data("{\"majorVersion\":7}"),
- "{\"message\":\"Set major version to 7\"}");
+ .userIdentity(USER_ID)
+ .data("{\"majorVersion\":7}"),
+ "{\"message\":\"Set major version to 7\"}");
// POST a pem deploy key
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/key", POST)
- .userIdentity(USER_ID)
- .data("{\"key\":\"" + pemPublicKey + "\"}"),
- "{\"keys\":[\"-----BEGIN PUBLIC KEY-----\\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEuKVFA8dXk43kVfYKzkUqhEY2rDT9\\nz/4jKSTHwbYR8wdsOSrJGVEUPbS2nguIJ64OJH7gFnxM6sxUVj+Nm2HlXw==\\n-----END PUBLIC KEY-----\\n\"]}");
+ .userIdentity(USER_ID)
+ .data("{\"key\":\"" + pemPublicKey + "\"}"),
+ "{\"keys\":[\"-----BEGIN PUBLIC KEY-----\\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEuKVFA8dXk43kVfYKzkUqhEY2rDT9\\nz/4jKSTHwbYR8wdsOSrJGVEUPbS2nguIJ64OJH7gFnxM6sxUVj+Nm2HlXw==\\n-----END PUBLIC KEY-----\\n\"]}");
// PATCH in a pem deploy key at deprecated path
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/default", PATCH)
- .userIdentity(USER_ID)
- .data("{\"pemDeployKey\":\"" + pemPublicKey + "\"}"),
- "{\"message\":\"Added deploy key " + quotedPemPublicKey + "\"}");
+ .userIdentity(USER_ID)
+ .data("{\"pemDeployKey\":\"" + pemPublicKey + "\"}"),
+ "{\"message\":\"Added deploy key " + quotedPemPublicKey + "\"}");
// GET an application with a major version override
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", GET)
- .userIdentity(USER_ID),
- new File("application2-with-patches.json"));
+ .userIdentity(USER_ID),
+ new File("application2-with-patches.json"));
// PATCH in removal of the application major version override removal
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", PATCH)
- .userIdentity(USER_ID)
- .data("{\"majorVersion\":null}"),
- "{\"message\":\"Set major version to empty\"}");
+ .userIdentity(USER_ID)
+ .data("{\"majorVersion\":null}"),
+ "{\"message\":\"Set major version to empty\"}");
// GET compile version for an application
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/compile-version", GET)
- .userIdentity(USER_ID),
- "{\"compileVersion\":\"6.1.0\"}");
+ .userIdentity(USER_ID),
+ "{\"compileVersion\":\"6.1.0\"}");
// DELETE the pem deploy key
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/key", DELETE)
- .userIdentity(USER_ID)
- .data("{\"key\":\"" + pemPublicKey + "\"}"),
- "{\"keys\":[]}");
+ .userIdentity(USER_ID)
+ .data("{\"key\":\"" + pemPublicKey + "\"}"),
+ "{\"keys\":[]}");
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", GET)
- .userIdentity(USER_ID),
- new File("application2.json"));
+ .userIdentity(USER_ID),
+ new File("application2.json"));
// DELETE instance 1 of 2
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/instance/default", DELETE)
- .userIdentity(USER_ID)
- .oAuthCredentials(OKTA_CREDENTIALS),
- "{\"message\":\"Deleted instance tenant2.application2.default\"}");
+ .userIdentity(USER_ID)
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ "{\"message\":\"Deleted instance tenant2.application2.default\"}");
// DELETE application with only one instance left
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2", DELETE)
- .userIdentity(USER_ID)
- .oAuthCredentials(OKTA_CREDENTIALS),
- "{\"message\":\"Deleted application tenant2.application2\"}");
+ .userIdentity(USER_ID)
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ "{\"message\":\"Deleted application tenant2.application2\"}");
// Set version 6.1 to broken to change compile version for.
deploymentTester.upgrader().overrideConfidence(Version.fromString("6.1"), VespaVersion.Confidence.broken);
@@ -448,44 +448,44 @@ public class ApplicationApiTest extends ControllerContainerTest {
// GET tenant application deployments
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
- .userIdentity(USER_ID),
- new File("instance.json"));
+ .userIdentity(USER_ID),
+ new File("instance.json"));
// GET an application deployment
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", GET)
- .userIdentity(USER_ID),
- new File("deployment.json"));
+ .userIdentity(USER_ID),
+ new File("deployment.json"));
addIssues(deploymentTester, TenantAndApplicationId.from("tenant1", "application1"));
// GET at root, with "&recursive=deployment", returns info about all tenants, their applications and their deployments
tester.assertResponse(request("/application/v4/", GET)
- .userIdentity(USER_ID)
- .recursive("deployment"),
- new File("recursive-root.json"));
+ .userIdentity(USER_ID)
+ .recursive("deployment"),
+ new File("recursive-root.json"));
// GET at root, with "&recursive=tenant", returns info about all tenants, with limited info about their applications.
tester.assertResponse(request("/application/v4/", GET)
- .userIdentity(USER_ID)
- .recursive("tenant"),
- new File("recursive-until-tenant-root.json"));
+ .userIdentity(USER_ID)
+ .recursive("tenant"),
+ new File("recursive-until-tenant-root.json"));
// GET at a tenant, with "&recursive=true", returns full info about their applications and their deployments
tester.assertResponse(request("/application/v4/tenant/tenant1/", GET)
- .userIdentity(USER_ID)
- .recursive("true"),
- new File("tenant1-recursive.json"));
+ .userIdentity(USER_ID)
+ .recursive("true"),
+ new File("tenant1-recursive.json"));
// GET at an application, with "&recursive=true", returns full info about its deployments
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
- .userIdentity(USER_ID)
- .recursive("true"),
- new File("instance1-recursive.json"));
+ .userIdentity(USER_ID)
+ .recursive("true"),
+ new File("instance1-recursive.json"));
// GET nodes
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/nodes", GET)
- .userIdentity(USER_ID),
- new File("application-nodes.json"));
+ .userIdentity(USER_ID),
+ new File("application-nodes.json"));
// GET clusters
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/clusters", GET)
- .userIdentity(USER_ID),
- new File("application-clusters.json"));
+ .userIdentity(USER_ID),
+ new File("application-clusters.json"));
// GET logs
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application1/environment/dev/region/us-east-1/instance/default/logs?from=1233&to=3214", GET)
@@ -494,12 +494,12 @@ public class ApplicationApiTest extends ControllerContainerTest {
// GET controller logs
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application1/environment/prod/region/controller/instance/default/logs?from=1233&to=3214", GET)
- .userIdentity(USER_ID),
- "INFO - All good");
+ .userIdentity(USER_ID),
+ "INFO - All good");
// Get content/../foo
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application1/instance/default/environment/dev/region/us-east-1/content/%2E%2E%2Ffoo", GET).userIdentity(USER_ID),
- accessDenied, 403);
+ accessDenied, 403);
// Get content - root
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application1/instance/default/environment/dev/region/us-east-1/content/", GET).userIdentity(USER_ID),
"{\"path\":\"/\"}");
@@ -513,121 +513,121 @@ public class ApplicationApiTest extends ControllerContainerTest {
// GET metrics
tester.assertJsonResponse(request("/application/v4/tenant/tenant2/application/application1/environment/dev/region/us-east-1/instance/default/metrics", GET)
.userIdentity(USER_ID),
- new File("proton-metrics.json"));
+ new File("proton-metrics.json"));
// POST a roll-out of the latest application
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/application", POST)
- .userIdentity(USER_ID),
- "{\"message\":\"Triggered revision change to build 1 for tenant1.application1.instance1\"}");
+ .userIdentity(USER_ID),
+ "{\"message\":\"Triggered revision change to build 1 for tenant1.application1.instance1\"}");
// POST a roll-out of a given revision
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/application", POST)
- .data("{ \"build\": 1 }")
- .userIdentity(USER_ID),
- "{\"message\":\"Triggered revision change to build 1 for tenant1.application1.instance1\"}");
+ .data("{ \"build\": 1 }")
+ .userIdentity(USER_ID),
+ "{\"message\":\"Triggered revision change to build 1 for tenant1.application1.instance1\"}");
// DELETE (cancel) ongoing change
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", DELETE)
- .userIdentity(HOSTED_VESPA_OPERATOR),
- "{\"message\":\"Changed deployment from 'revision change to build 1' to 'no change' for tenant1.application1.instance1\"}");
+ .userIdentity(HOSTED_VESPA_OPERATOR),
+ "{\"message\":\"Changed deployment from 'revision change to build 1' to 'no change' for tenant1.application1.instance1\"}");
// DELETE (cancel) again is a no-op
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", DELETE)
- .userIdentity(USER_ID)
- .data("{\"cancel\":\"all\"}"),
- "{\"message\":\"No deployment in progress for tenant1.application1.instance1 at this time\"}");
+ .userIdentity(USER_ID)
+ .data("{\"cancel\":\"all\"}"),
+ "{\"message\":\"No deployment in progress for tenant1.application1.instance1 at this time\"}");
// POST pinning to a given version to an application
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/pin", POST)
- .userIdentity(USER_ID)
- .data("6.1.0"),
- "{\"message\":\"Triggered pin to 6.1 for tenant1.application1.instance1\"}");
- assertTrue("Action is logged to audit log",
- tester.controller().auditLogger().readLog().entries().stream()
- .anyMatch(entry -> entry.resource().equals("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/pin?")));
+ .userIdentity(USER_ID)
+ .data("6.1.0"),
+ "{\"message\":\"Triggered pin to 6.1 for tenant1.application1.instance1\"}");
+ assertTrue(tester.controller().auditLogger().readLog().entries().stream()
+ .anyMatch(entry -> entry.resource().equals("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/pin?")),
+ "Action is logged to audit log");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", GET)
- .userIdentity(USER_ID), "{\"platform\":\"6.1\",\"pinned\":true}");
+ .userIdentity(USER_ID), "{\"platform\":\"6.1\",\"pinned\":true}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/pin", GET)
- .userIdentity(USER_ID), "{\"platform\":\"6.1\",\"pinned\":true}");
+ .userIdentity(USER_ID), "{\"platform\":\"6.1\",\"pinned\":true}");
// DELETE only the pin to a given version
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/pin", DELETE)
- .userIdentity(USER_ID),
- "{\"message\":\"Changed deployment from 'pin to 6.1' to 'upgrade to 6.1' for tenant1.application1.instance1\"}");
+ .userIdentity(USER_ID),
+ "{\"message\":\"Changed deployment from 'pin to 6.1' to 'upgrade to 6.1' for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", GET)
- .userIdentity(USER_ID), "{\"platform\":\"6.1\",\"pinned\":false}");
+ .userIdentity(USER_ID), "{\"platform\":\"6.1\",\"pinned\":false}");
// POST pinning again
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/pin", POST)
- .userIdentity(USER_ID)
- .data("6.1"),
- "{\"message\":\"Triggered pin to 6.1 for tenant1.application1.instance1\"}");
+ .userIdentity(USER_ID)
+ .data("6.1"),
+ "{\"message\":\"Triggered pin to 6.1 for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", GET)
- .userIdentity(USER_ID), "{\"platform\":\"6.1\",\"pinned\":true}");
+ .userIdentity(USER_ID), "{\"platform\":\"6.1\",\"pinned\":true}");
// DELETE only the version, but leave the pin
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/platform", DELETE)
- .userIdentity(USER_ID),
- "{\"message\":\"Changed deployment from 'pin to 6.1' to 'pin to current platform' for tenant1.application1.instance1\"}");
+ .userIdentity(USER_ID),
+ "{\"message\":\"Changed deployment from 'pin to 6.1' to 'pin to current platform' for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", GET)
- .userIdentity(USER_ID), "{\"pinned\":true}");
+ .userIdentity(USER_ID), "{\"pinned\":true}");
// DELETE also the pin to a given version
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying/pin", DELETE)
- .userIdentity(USER_ID),
- "{\"message\":\"Changed deployment from 'pin to current platform' to 'no change' for tenant1.application1.instance1\"}");
+ .userIdentity(USER_ID),
+ "{\"message\":\"Changed deployment from 'pin to current platform' to 'no change' for tenant1.application1.instance1\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploying", GET)
- .userIdentity(USER_ID), "{}");
+ .userIdentity(USER_ID), "{}");
// POST a pause to a production job
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/production-us-west-1/pause", POST)
- .userIdentity(USER_ID),
- "{\"message\":\"production-us-west-1 for tenant1.application1.instance1 paused for " + DeploymentTrigger.maxPause + "\"}");
+ .userIdentity(USER_ID),
+ "{\"message\":\"production-us-west-1 for tenant1.application1.instance1 paused for " + DeploymentTrigger.maxPause + "\"}");
// DELETE a pause of a production job
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/production-us-west-1/pause", DELETE)
- .userIdentity(USER_ID),
- "{\"message\":\"production-us-west-1 for tenant1.application1.instance1 resumed\"}");
+ .userIdentity(USER_ID),
+ "{\"message\":\"production-us-west-1 for tenant1.application1.instance1 resumed\"}");
// POST a triggering to the same production job
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/production-us-west-1", POST)
- .userIdentity(USER_ID),
- "{\"message\":\"Triggered production-us-west-1 for tenant1.application1.instance1\"}");
+ .userIdentity(USER_ID),
+ "{\"message\":\"Triggered production-us-west-1 for tenant1.application1.instance1\"}");
// POST a 'reindex application' command
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-central-1/reindex", POST)
- .properties(Map.of("indexedOnly", "true",
- "speed", "10"))
- .userIdentity(USER_ID),
- "{\"message\":\"Requested reindexing of tenant1.application1.instance1 in prod.us-central-1, for indexed types, with speed 10.0\"}");
+ .properties(Map.of("indexedOnly", "true",
+ "speed", "10"))
+ .userIdentity(USER_ID),
+ "{\"message\":\"Requested reindexing of tenant1.application1.instance1 in prod.us-central-1, for indexed types, with speed 10.0\"}");
// POST a 'reindex application' command with cluster filter
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-central-1/reindex", POST)
- .properties(Map.of("clusterId", "boo,moo"))
- .userIdentity(USER_ID),
- "{\"message\":\"Requested reindexing of tenant1.application1.instance1 in prod.us-central-1, on clusters boo, moo\"}");
+ .properties(Map.of("clusterId", "boo,moo"))
+ .userIdentity(USER_ID),
+ "{\"message\":\"Requested reindexing of tenant1.application1.instance1 in prod.us-central-1, on clusters boo, moo\"}");
// POST a 'reindex application' command with cluster and document type filters
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-central-1/reindex", POST)
- .properties(Map.of("clusterId", "boo,moo",
- "documentType", "foo,boo"))
- .userIdentity(USER_ID),
- "{\"message\":\"Requested reindexing of tenant1.application1.instance1 in prod.us-central-1, on clusters boo, moo, for types foo, boo\"}");
+ .properties(Map.of("clusterId", "boo,moo",
+ "documentType", "foo,boo"))
+ .userIdentity(USER_ID),
+ "{\"message\":\"Requested reindexing of tenant1.application1.instance1 in prod.us-central-1, on clusters boo, moo, for types foo, boo\"}");
// POST to enable reindexing
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-central-1/reindexing", POST)
- .userIdentity(USER_ID),
- "{\"message\":\"Enabled reindexing of tenant1.application1.instance1 in prod.us-central-1\"}");
+ .userIdentity(USER_ID),
+ "{\"message\":\"Enabled reindexing of tenant1.application1.instance1 in prod.us-central-1\"}");
// DELETE to disable reindexing
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-central-1/reindexing", DELETE)
- .userIdentity(USER_ID),
- "{\"message\":\"Disabled reindexing of tenant1.application1.instance1 in prod.us-central-1\"}");
+ .userIdentity(USER_ID),
+ "{\"message\":\"Disabled reindexing of tenant1.application1.instance1 in prod.us-central-1\"}");
// GET to get reindexing status
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-central-1/reindexing", GET)
- .userIdentity(USER_ID),
- "{\"enabled\":true,\"clusters\":[{\"name\":\"cluster\",\"pending\":[{\"type\":\"type\",\"requiredGeneration\":100}],\"ready\":[{\"type\":\"type\",\"readyAtMillis\":345,\"startedAtMillis\":456,\"endedAtMillis\":567,\"state\":\"failed\",\"message\":\"(#`д´)ノ\",\"progress\":0.1,\"speed\":1.0}]}]}");
+ .userIdentity(USER_ID),
+ "{\"enabled\":true,\"clusters\":[{\"name\":\"cluster\",\"pending\":[{\"type\":\"type\",\"requiredGeneration\":100}],\"ready\":[{\"type\":\"type\",\"readyAtMillis\":345,\"startedAtMillis\":456,\"endedAtMillis\":567,\"state\":\"failed\",\"message\":\"(#`д´)ノ\",\"progress\":0.1,\"speed\":1.0}]}]}");
// POST to request a service dump
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-central-1/node/host-tenant1.application1.instance1-prod.us-central-1/service-dump", POST)
@@ -643,122 +643,122 @@ public class ApplicationApiTest extends ControllerContainerTest {
// POST a 'restart application' command
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/restart", POST)
- .userIdentity(USER_ID),
- "{\"message\":\"Requested restart of tenant1.application1.instance1 in prod.us-central-1\"}");
+ .userIdentity(USER_ID),
+ "{\"message\":\"Requested restart of tenant1.application1.instance1 in prod.us-central-1\"}");
// POST a 'restart application' command
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/restart", POST)
- .userIdentity(HOSTED_VESPA_OPERATOR),
- "{\"message\":\"Requested restart of tenant1.application1.instance1 in prod.us-central-1\"}");
+ .userIdentity(HOSTED_VESPA_OPERATOR),
+ "{\"message\":\"Requested restart of tenant1.application1.instance1 in prod.us-central-1\"}");
addUserToHostedOperatorRole(HostedAthenzIdentities.from(SCREWDRIVER_ID));
// POST a 'restart application' in staging environment
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/staging/region/us-east-3/instance/instance1/restart", POST)
- .screwdriverIdentity(SCREWDRIVER_ID),
- "{\"message\":\"Requested restart of tenant1.application1.instance1 in staging.us-east-3\"}");
+ .screwdriverIdentity(SCREWDRIVER_ID),
+ "{\"message\":\"Requested restart of tenant1.application1.instance1 in staging.us-east-3\"}");
// POST a 'restart application' in test environment
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/test/region/us-east-1/instance/instance1/restart", POST)
- .screwdriverIdentity(SCREWDRIVER_ID),
- "{\"message\":\"Requested restart of tenant1.application1.instance1 in test.us-east-1\"}");
+ .screwdriverIdentity(SCREWDRIVER_ID),
+ "{\"message\":\"Requested restart of tenant1.application1.instance1 in test.us-east-1\"}");
// POST a 'restart application' in dev environment
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-east-1/instance/instance1/restart", POST)
- .userIdentity(USER_ID),
- "{\"message\":\"Requested restart of tenant1.application1.instance1 in dev.us-east-1\"}");
+ .userIdentity(USER_ID),
+ "{\"message\":\"Requested restart of tenant1.application1.instance1 in dev.us-east-1\"}");
// POST a 'restart application' command with a host filter (other filters not supported yet)
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/restart", POST)
- .properties(Map.of("hostname", "node-1-tenant-host-prod.us-central-1"))
- .screwdriverIdentity(SCREWDRIVER_ID),
- "{\"message\":\"Requested restart of tenant1.application1.instance1 in prod.us-central-1\"}", 200);
+ .properties(Map.of("hostname", "node-1-tenant-host-prod.us-central-1"))
+ .screwdriverIdentity(SCREWDRIVER_ID),
+ "{\"message\":\"Requested restart of tenant1.application1.instance1 in prod.us-central-1\"}", 200);
// POST a 'suspend application' in dev environment
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/dev/region/us-east-1/suspend", POST)
- .userIdentity(USER_ID),
- "{\"message\":\"Suspended orchestration of tenant1.application1.instance1 in dev.us-east-1\"}");
+ .userIdentity(USER_ID),
+ "{\"message\":\"Suspended orchestration of tenant1.application1.instance1 in dev.us-east-1\"}");
// POST a 'resume application' in dev environment
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/dev/region/us-east-1/suspend", DELETE)
- .userIdentity(USER_ID),
- "{\"message\":\"Resumed orchestration of tenant1.application1.instance1 in dev.us-east-1\"}");
+ .userIdentity(USER_ID),
+ "{\"message\":\"Resumed orchestration of tenant1.application1.instance1 in dev.us-east-1\"}");
// POST a 'suspend application' in prod environment fails
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-east-3/suspend", POST)
- .userIdentity(USER_ID),
- accessDenied, 403);
+ .userIdentity(USER_ID),
+ accessDenied, 403);
// GET suspended
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1/suspended", GET)
- .userIdentity(USER_ID),
- new File("suspended.json"));
+ .userIdentity(USER_ID),
+ new File("suspended.json"));
// GET service/state/v1
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-central-1/service/storagenode/host.com/state/v1/?foo=bar", GET)
- .userIdentity(USER_ID),
- new File("service"));
+ .userIdentity(USER_ID),
+ new File("service"));
// GET orchestrator
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-central-1/orchestrator", GET)
- .userIdentity(USER_ID),
- "{\"json\":\"thank you very much\"}");
+ .userIdentity(USER_ID),
+ "{\"json\":\"thank you very much\"}");
// GET application package which has been deployed to production
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET)
- .properties(Map.of("build", "latestDeployed"))
- .userIdentity(HOSTED_VESPA_OPERATOR),
- (response) -> {
- assertEquals("attachment; filename=\"tenant1.application1-build1.zip\"", response.getHeaders().getFirst("Content-Disposition"));
- assertArrayEquals(applicationPackageInstance1.zippedContent(), response.getBody());
- },
- 200);
+ .properties(Map.of("build", "latestDeployed"))
+ .userIdentity(HOSTED_VESPA_OPERATOR),
+ (response) -> {
+ assertEquals("attachment; filename=\"tenant1.application1-build1.zip\"", response.getHeaders().getFirst("Content-Disposition"));
+ assertArrayEquals(applicationPackageInstance1.zippedContent(), response.getBody());
+ },
+ 200);
// DELETE application with active deployments fails
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
- .userIdentity(USER_ID)
- .oAuthCredentials(OKTA_CREDENTIALS),
- new File("delete-with-active-deployments.json"), 400);
+ .userIdentity(USER_ID)
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ new File("delete-with-active-deployments.json"), 400);
// DELETE (deactivate) a deployment - dev
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-east-1/instance/instance1", DELETE)
- .userIdentity(USER_ID),
- "{\"message\":\"Deactivated tenant1.application1.instance1 in dev.us-east-1\"}");
+ .userIdentity(USER_ID),
+ "{\"message\":\"Deactivated tenant1.application1.instance1 in dev.us-east-1\"}");
// DELETE (deactivate) a deployment - prod
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", DELETE)
- .screwdriverIdentity(SCREWDRIVER_ID),
- "{\"message\":\"Deactivated tenant1.application1.instance1 in prod.us-central-1\"}");
+ .screwdriverIdentity(SCREWDRIVER_ID),
+ "{\"message\":\"Deactivated tenant1.application1.instance1 in prod.us-central-1\"}");
// DELETE (deactivate) a deployment is idempotent
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-central-1/instance/instance1", DELETE)
- .screwdriverIdentity(SCREWDRIVER_ID),
- "{\"message\":\"Deactivated tenant1.application1.instance1 in prod.us-central-1\"}");
+ .screwdriverIdentity(SCREWDRIVER_ID),
+ "{\"message\":\"Deactivated tenant1.application1.instance1 in prod.us-central-1\"}");
// Setup for test config tests
tester.controller().jobController().deploy(ApplicationId.from("tenant1", "application1", "default"),
- DeploymentContext.productionUsCentral1,
- Optional.empty(),
- applicationPackageDefault);
+ DeploymentContext.productionUsCentral1,
+ Optional.empty(),
+ applicationPackageDefault);
tester.controller().jobController().deploy(ApplicationId.from("tenant1", "application1", "my-user"),
- DeploymentContext.devUsEast1,
- Optional.empty(),
- applicationPackageDefault);
+ DeploymentContext.devUsEast1,
+ Optional.empty(),
+ applicationPackageDefault);
// GET test-config for local tests against a dev deployment
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user/job/dev-us-east-1/test-config", GET)
- .userIdentity(USER_ID),
- new File("test-config-dev.json"));
+ .userIdentity(USER_ID),
+ new File("test-config-dev.json"));
// GET test-config for local tests against a prod deployment
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/my-user/job/production-us-central-1/test-config", GET)
- .userIdentity(USER_ID),
- new File("test-config.json"));
+ .userIdentity(USER_ID),
+ new File("test-config.json"));
tester.controller().applications().deactivate(ApplicationId.from("tenant1", "application1", "default"),
- ZoneId.from("prod", "us-central-1"));
+ ZoneId.from("prod", "us-central-1"));
tester.controller().applications().deactivate(ApplicationId.from("tenant1", "application1", "my-user"),
- ZoneId.from("dev", "us-east-1"));
+ ZoneId.from("dev", "us-east-1"));
// teardown for test config tests
// Second attempt has a service under a different domain than the tenant of the application, and fails.
@@ -769,9 +769,9 @@ public class ApplicationApiTest extends ControllerContainerTest {
.build();
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN_2, "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
- .screwdriverIdentity(SCREWDRIVER_ID)
- .data(createApplicationSubmissionData(packageWithServiceForWrongDomain, 123)),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz domain in deployment.xml: [domain2] must match tenant domain: [domain1]\"}", 400);
+ .screwdriverIdentity(SCREWDRIVER_ID)
+ .data(createApplicationSubmissionData(packageWithServiceForWrongDomain, 123)),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz domain in deployment.xml: [domain2] must match tenant domain: [domain1]\"}", 400);
// Third attempt has a service under the domain of the tenant, and also succeeds.
ApplicationPackage packageWithService = new ApplicationPackageBuilder()
@@ -783,54 +783,54 @@ public class ApplicationApiTest extends ControllerContainerTest {
.build();
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
- .screwdriverIdentity(SCREWDRIVER_ID)
- .data(createApplicationSubmissionData(packageWithService, 123)),
- "{\"message\":\"application build 2, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
+ .screwdriverIdentity(SCREWDRIVER_ID)
+ .data(createApplicationSubmissionData(packageWithService, 123)),
+ "{\"message\":\"application build 2, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/diff/2", GET).userIdentity(HOSTED_VESPA_OPERATOR),
- (response) -> assertTrue(response.getBodyAsString(),
- response.getBodyAsString().contains("+ <deployment version='1.0' athenz-domain='domain1' athenz-service='service'>\n" +
- "- <deployment version='1.0' >\n")),
- 200);
+ (response) -> assertTrue(response.getBodyAsString().contains("+ <deployment version='1.0' athenz-domain='domain1' athenz-service='service'>\n" +
+ "- <deployment version='1.0' >\n"),
+ response.getBodyAsString()),
+ 200);
// GET last submitted application package
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET).userIdentity(HOSTED_VESPA_OPERATOR),
- (response) -> {
- assertEquals("attachment; filename=\"tenant1.application1-build2.zip\"", response.getHeaders().getFirst("Content-Disposition"));
- assertArrayEquals(packageWithService.zippedContent(), response.getBody());
- },
- 200);
+ (response) -> {
+ assertEquals("attachment; filename=\"tenant1.application1-build2.zip\"", response.getHeaders().getFirst("Content-Disposition"));
+ assertArrayEquals(packageWithService.zippedContent(), response.getBody());
+ },
+ 200);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET).userIdentity(HOSTED_VESPA_OPERATOR).properties(Map.of("tests", "true")),
- (response) -> {
- assertEquals("attachment; filename=\"tenant1.application1-tests2.zip\"", response.getHeaders().getFirst("Content-Disposition"));
- assertArrayEquals("content".getBytes(UTF_8), response.getBody());
- },
- 200);
+ (response) -> {
+ assertEquals("attachment; filename=\"tenant1.application1-tests2.zip\"", response.getHeaders().getFirst("Content-Disposition"));
+ assertArrayEquals("content".getBytes(UTF_8), response.getBody());
+ },
+ 200);
// GET application package for specific build
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET)
- .properties(Map.of("build", "2"))
- .userIdentity(HOSTED_VESPA_OPERATOR),
- (response) -> {
- assertEquals("attachment; filename=\"tenant1.application1-build2.zip\"", response.getHeaders().getFirst("Content-Disposition"));
- assertArrayEquals(packageWithService.zippedContent(), response.getBody());
- },
- 200);
+ .properties(Map.of("build", "2"))
+ .userIdentity(HOSTED_VESPA_OPERATOR),
+ (response) -> {
+ assertEquals("attachment; filename=\"tenant1.application1-build2.zip\"", response.getHeaders().getFirst("Content-Disposition"));
+ assertArrayEquals(packageWithService.zippedContent(), response.getBody());
+ },
+ 200);
// Fourth attempt has a wrong content hash in a header, and fails.
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
- .screwdriverIdentity(SCREWDRIVER_ID)
- .header("X-Content-Hash", "not/the/right/hash")
- .data(createApplicationSubmissionData(packageWithService, 123)),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Value of X-Content-Hash header does not match computed content hash\"}", 400);
+ .screwdriverIdentity(SCREWDRIVER_ID)
+ .header("X-Content-Hash", "not/the/right/hash")
+ .data(createApplicationSubmissionData(packageWithService, 123)),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Value of X-Content-Hash header does not match computed content hash\"}", 400);
// Fifth attempt has the right content hash in a header, and succeeds.
MultiPartStreamer streamer = createApplicationSubmissionData(packageWithService, 123);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
- .screwdriverIdentity(SCREWDRIVER_ID)
- .header("X-Content-Hash", Base64.getEncoder().encodeToString(Signatures.sha256Digest(streamer::data)))
- .data(streamer),
- "{\"message\":\"application build 3, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
+ .screwdriverIdentity(SCREWDRIVER_ID)
+ .header("X-Content-Hash", Base64.getEncoder().encodeToString(Signatures.sha256Digest(streamer::data)))
+ .data(streamer),
+ "{\"message\":\"application build 3, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
// Sixth attempt has a multi-instance deployment spec, and is accepted.
ApplicationPackage multiInstanceSpec = new ApplicationPackageBuilder()
@@ -841,53 +841,53 @@ public class ApplicationApiTest extends ControllerContainerTest {
.endpoint("default", "foo", "us-central-1", "us-west-1", "us-east-3")
.build();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/submit", POST)
- .screwdriverIdentity(SCREWDRIVER_ID)
- .data(createApplicationSubmissionData(multiInstanceSpec, 123)),
- "{\"message\":\"application build 4, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
+ .screwdriverIdentity(SCREWDRIVER_ID)
+ .data(createApplicationSubmissionData(multiInstanceSpec, 123)),
+ "{\"message\":\"application build 4, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
// DELETE submitted build, to mark it as non-deployable
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit/2", DELETE)
- .userIdentity(USER_ID),
- "{\"message\":\"Marked build '2' as non-deployable\"}");
+ .userIdentity(USER_ID),
+ "{\"message\":\"Marked build '2' as non-deployable\"}");
// GET deployment job overview, after triggering system and staging test jobs.
assertEquals(2, tester.controller().applications().deploymentTrigger().triggerReadyJobs().triggered());
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job", GET)
- .userIdentity(USER_ID),
- new File("jobs.json"));
+ .userIdentity(USER_ID),
+ new File("jobs.json"));
// GET deployment job overview for whole application.
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/deployment", GET)
- .userIdentity(USER_ID),
- new File("deployment-overview.json"));
+ .userIdentity(USER_ID),
+ new File("deployment-overview.json"));
// GET system test job overview.
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/system-test", GET)
- .userIdentity(USER_ID),
- new File("system-test-job.json"));
+ .userIdentity(USER_ID),
+ new File("system-test-job.json"));
// GET system test run 1 details.
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/system-test/run/1", GET)
- .userIdentity(USER_ID),
- new File("system-test-details.json"));
+ .userIdentity(USER_ID),
+ new File("system-test-details.json"));
// DELETE a running job to have it aborted.
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/job/staging-test", DELETE)
- .userIdentity(USER_ID),
- "{\"message\":\"Aborting run 2 of staging-test for tenant1.application1.instance1\"}");
+ .userIdentity(USER_ID),
+ "{\"message\":\"Aborting run 2 of staging-test for tenant1.application1.instance1\"}");
// GET compile version for specific major
deploymentTester.controllerTester().upgradeSystem(Version.fromString("7.0"));
deploymentTester.controllerTester().flagSource().withListFlag(PermanentFlags.INCOMPATIBLE_VERSIONS.id(), List.of("*"), String.class);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/compile-version", GET)
- .userIdentity(USER_ID).properties(Map.of("allowMajor", "7")),
- "{\"compileVersion\":\"7.0.0\"}");
+ .userIdentity(USER_ID).properties(Map.of("allowMajor", "7")),
+ "{\"compileVersion\":\"7.0.0\"}");
// OPTIONS return 200 OK
tester.assertResponse(request("/application/v4/", Request.Method.OPTIONS)
- .userIdentity(USER_ID),
- "");
+ .userIdentity(USER_ID),
+ "");
addNotifications(TenantName.from("tenant1"));
addNotifications(TenantName.from("tenant2"));
@@ -902,14 +902,14 @@ public class ApplicationApiTest extends ControllerContainerTest {
// DELETE the application which no longer has any deployments
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
- .userIdentity(USER_ID)
- .oAuthCredentials(OKTA_CREDENTIALS),
- "{\"message\":\"Deleted application tenant1.application1\"}");
+ .userIdentity(USER_ID)
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ "{\"message\":\"Deleted application tenant1.application1\"}");
// DELETE an empty tenant
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE).userIdentity(USER_ID)
- .oAuthCredentials(OKTA_CREDENTIALS),
- "{\"message\":\"Deleted tenant tenant1\"}");
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ "{\"message\":\"Deleted tenant tenant1\"}");
// The tenant is not found
tester.assertResponse(request("/application/v4/tenant/tenant1", GET).userIdentity(USER_ID)
@@ -947,7 +947,7 @@ public class ApplicationApiTest extends ControllerContainerTest {
}
@Test
- public void testRotationOverride() {
+ void testRotationOverride() {
// Setup
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
var westZone = ZoneId.from("prod", "us-west-1");
@@ -965,60 +965,60 @@ public class ApplicationApiTest extends ControllerContainerTest {
// Invalid application fails
tester.assertResponse(request("/application/v4/tenant/tenant2/application/application2/environment/prod/region/us-west-1/instance/default/global-rotation", GET)
- .userIdentity(USER_ID),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"tenant2.application2 not found\"}",
- 400);
+ .userIdentity(USER_ID),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"tenant2.application2 not found\"}",
+ 400);
// Invalid deployment fails
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-central-1/global-rotation", GET)
- .userIdentity(USER_ID),
- "{\"error-code\":\"NOT_FOUND\",\"message\":\"application 'tenant1.application1.instance1' has no deployment in prod.us-central-1\"}",
- 404);
+ .userIdentity(USER_ID),
+ "{\"error-code\":\"NOT_FOUND\",\"message\":\"application 'tenant1.application1.instance1' has no deployment in prod.us-central-1\"}",
+ 404);
// Change status of non-existing deployment fails
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-central-1/global-rotation/override", PUT)
- .userIdentity(USER_ID)
- .data("{\"reason\":\"unit-test\"}"),
- "{\"error-code\":\"NOT_FOUND\",\"message\":\"application 'tenant1.application1.instance1' has no deployment in prod.us-central-1\"}",
- 404);
+ .userIdentity(USER_ID)
+ .data("{\"reason\":\"unit-test\"}"),
+ "{\"error-code\":\"NOT_FOUND\",\"message\":\"application 'tenant1.application1.instance1' has no deployment in prod.us-central-1\"}",
+ 404);
// GET global rotation status
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation", GET)
- .userIdentity(USER_ID),
- new File("global-rotation.json"));
+ .userIdentity(USER_ID),
+ new File("global-rotation.json"));
// GET global rotation override status
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation/override", GET)
- .userIdentity(USER_ID),
- new File("global-rotation-get.json"));
+ .userIdentity(USER_ID),
+ new File("global-rotation-get.json"));
// SET global rotation override status
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation/override", PUT)
- .userIdentity(USER_ID)
- .data("{\"reason\":\"unit-test\"}"),
- new File("global-rotation-put.json"));
+ .userIdentity(USER_ID)
+ .data("{\"reason\":\"unit-test\"}"),
+ new File("global-rotation-put.json"));
// Status of routing policy is changed
assertGlobalRouting(app.deploymentIdIn(westZone), RoutingStatus.Value.out, RoutingStatus.Agent.tenant);
// DELETE global rotation override status
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation/override", DELETE)
- .userIdentity(USER_ID)
- .data("{\"reason\":\"unit-test\"}"),
- new File("global-rotation-delete.json"));
+ .userIdentity(USER_ID)
+ .data("{\"reason\":\"unit-test\"}"),
+ new File("global-rotation-delete.json"));
assertGlobalRouting(app.deploymentIdIn(westZone), RoutingStatus.Value.in, RoutingStatus.Agent.tenant);
// SET global rotation override status by operator
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation/override", PUT)
- .userIdentity(HOSTED_VESPA_OPERATOR)
- .data("{\"reason\":\"unit-test\"}"),
- new File("global-rotation-put.json"));
+ .userIdentity(HOSTED_VESPA_OPERATOR)
+ .data("{\"reason\":\"unit-test\"}"),
+ new File("global-rotation-put.json"));
assertGlobalRouting(app.deploymentIdIn(westZone), RoutingStatus.Value.out, RoutingStatus.Agent.operator);
}
@Test
- public void multiple_endpoints() {
+ void multiple_endpoints() {
// Setup
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
@@ -1036,34 +1036,34 @@ public class ApplicationApiTest extends ControllerContainerTest {
// GET global rotation status without specifying endpointId fails
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation", GET)
- .userIdentity(USER_ID),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"application 'tenant1.application1.instance1' has multiple rotations. Query parameter 'endpointId' must be given\"}",
- 400);
+ .userIdentity(USER_ID),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"application 'tenant1.application1.instance1' has multiple rotations. Query parameter 'endpointId' must be given\"}",
+ 400);
// GET global rotation status for us-west-1 in default endpoint
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation", GET)
- .properties(Map.of("endpointId", "default"))
- .userIdentity(USER_ID),
- "{\"bcpStatus\":{\"rotationStatus\":\"UNKNOWN\"}}",
- 200);
+ .properties(Map.of("endpointId", "default"))
+ .userIdentity(USER_ID),
+ "{\"bcpStatus\":{\"rotationStatus\":\"UNKNOWN\"}}",
+ 200);
// GET global rotation status for us-west-1 in eu endpoint
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/global-rotation", GET)
- .properties(Map.of("endpointId", "eu"))
- .userIdentity(USER_ID),
- "{\"bcpStatus\":{\"rotationStatus\":\"UNKNOWN\"}}",
- 200);
+ .properties(Map.of("endpointId", "eu"))
+ .userIdentity(USER_ID),
+ "{\"bcpStatus\":{\"rotationStatus\":\"UNKNOWN\"}}",
+ 200);
// GET global rotation status for eu-west-1 in eu endpoint
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/eu-west-1/global-rotation", GET)
- .properties(Map.of("endpointId", "eu"))
- .userIdentity(USER_ID),
- "{\"bcpStatus\":{\"rotationStatus\":\"UNKNOWN\"}}",
- 200);
+ .properties(Map.of("endpointId", "eu"))
+ .userIdentity(USER_ID),
+ "{\"bcpStatus\":{\"rotationStatus\":\"UNKNOWN\"}}",
+ 200);
}
@Test
- public void testDeployWithApplicationPackage() {
+ void testDeployWithApplicationPackage() {
// Setup
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
deploymentTester.controllerTester().upgradeController(new Version("6.2"));
@@ -1071,22 +1071,22 @@ public class ApplicationApiTest extends ControllerContainerTest {
// POST (deploy) a system application with an application package
MultiPartStreamer noAppEntity = createApplicationDeployData(Optional.empty());
tester.assertResponse(request("/application/v4/tenant/hosted-vespa/application/routing/environment/prod/region/us-central-1/instance/default/deploy", POST)
- .data(noAppEntity)
- .userIdentity(HOSTED_VESPA_OPERATOR),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Deployment of system applications during a system upgrade is not allowed\"}",
- 400);
+ .data(noAppEntity)
+ .userIdentity(HOSTED_VESPA_OPERATOR),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Deployment of system applications during a system upgrade is not allowed\"}",
+ 400);
deploymentTester.controllerTester()
- .upgradeSystem(deploymentTester.controller().readVersionStatus().controllerVersion().get()
- .versionNumber());
+ .upgradeSystem(deploymentTester.controller().readVersionStatus().controllerVersion().get()
+ .versionNumber());
tester.assertResponse(request("/application/v4/tenant/hosted-vespa/application/routing/environment/prod/region/us-central-1/instance/default/deploy", POST)
- .data(noAppEntity)
- .userIdentity(HOSTED_VESPA_OPERATOR),
- new File("deploy-result.json"));
+ .data(noAppEntity)
+ .userIdentity(HOSTED_VESPA_OPERATOR),
+ new File("deploy-result.json"));
}
@Test
- public void testRemovingAllDeployments() {
+ void testRemovingAllDeployments() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1")
@@ -1116,100 +1116,100 @@ public class ApplicationApiTest extends ControllerContainerTest {
}
@Test
- public void testErrorResponses() {
+ void testErrorResponses() {
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
// PUT (update) non-existing tenant returns 403 as tenant access cannot be determined when the tenant does not exist
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
- .userIdentity(USER_ID)
- .oAuthCredentials(OKTA_CREDENTIALS)
- .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
- accessDenied,
- 403);
+ .userIdentity(USER_ID)
+ .oAuthCredentials(OKTA_CREDENTIALS)
+ .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
+ accessDenied,
+ 403);
// GET non-existing tenant
tester.assertResponse(request("/application/v4/tenant/tenant1", GET)
- .userIdentity(USER_ID),
- "{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'tenant1' does not exist\"}",
- 404);
+ .userIdentity(USER_ID),
+ "{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'tenant1' does not exist\"}",
+ 404);
// GET non-existing tenant's applications
tester.assertResponse(request("/application/v4/tenant/tenant1/application", GET)
- .userIdentity(USER_ID),
- "{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'tenant1' does not exist\"}",
- 404);
+ .userIdentity(USER_ID),
+ "{\"error-code\":\"NOT_FOUND\",\"message\":\"Tenant 'tenant1' does not exist\"}",
+ 404);
// GET non-existing application
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", GET)
- .userIdentity(USER_ID),
- "{\"error-code\":\"NOT_FOUND\",\"message\":\"tenant1.application1 not found\"}",
- 404);
+ .userIdentity(USER_ID),
+ "{\"error-code\":\"NOT_FOUND\",\"message\":\"tenant1.application1 not found\"}",
+ 404);
// GET non-existing deployment
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-east/instance/default", GET)
- .userIdentity(USER_ID),
- "{\"error-code\":\"NOT_FOUND\",\"message\":\"tenant1.application1 not found\"}",
- 404);
+ .userIdentity(USER_ID),
+ "{\"error-code\":\"NOT_FOUND\",\"message\":\"tenant1.application1 not found\"}",
+ 404);
// POST (add) a tenant
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
- .userIdentity(USER_ID)
- .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
- .oAuthCredentials(OKTA_CREDENTIALS),
- new File("tenant-without-applications.json"));
+ .userIdentity(USER_ID)
+ .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ new File("tenant-without-applications.json"));
// POST (add) another tenant under the same domain
tester.assertResponse(request("/application/v4/tenant/tenant2", POST)
- .userIdentity(USER_ID)
- .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
- .oAuthCredentials(OKTA_CREDENTIALS),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create tenant 'tenant2': The Athens domain 'domain1' is already connected to tenant 'tenant1'\"}",
- 400);
+ .userIdentity(USER_ID)
+ .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create tenant 'tenant2': The Athens domain 'domain1' is already connected to tenant 'tenant1'\"}",
+ 400);
// Add the same tenant again
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
- .userIdentity(USER_ID)
- .oAuthCredentials(OKTA_CREDENTIALS)
- .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'tenant1' already exists\"}",
- 400);
+ .userIdentity(USER_ID)
+ .oAuthCredentials(OKTA_CREDENTIALS)
+ .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'tenant1' already exists\"}",
+ 400);
// POST (add) an Athenz tenant with underscore in name
tester.assertResponse(request("/application/v4/tenant/my_tenant_2", POST)
- .userIdentity(USER_ID)
- .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
- .oAuthCredentials(OKTA_CREDENTIALS),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"New tenant or application names must start with a letter, may contain no more than 20 characters, and may only contain lowercase letters, digits or dashes, but no double-dashes.\"}",
- 400);
+ .userIdentity(USER_ID)
+ .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"New tenant or application names must start with a letter, may contain no more than 20 characters, and may only contain lowercase letters, digits or dashes, but no double-dashes.\"}",
+ 400);
// POST (add) an Athenz tenant with a reserved name
tester.assertResponse(request("/application/v4/tenant/hosted-vespa", POST)
- .userIdentity(USER_ID)
- .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
- .oAuthCredentials(OKTA_CREDENTIALS),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'hosted-vespa' already exists\"}",
- 400);
+ .userIdentity(USER_ID)
+ .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'hosted-vespa' already exists\"}",
+ 400);
// POST (create) an (empty) application
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
- .userIdentity(USER_ID)
- .oAuthCredentials(OKTA_CREDENTIALS),
- new File("instance-reference.json"));
+ .userIdentity(USER_ID)
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ new File("instance-reference.json"));
// Create the same application again
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
- .oAuthCredentials(OKTA_CREDENTIALS)
- .userIdentity(USER_ID),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create 'tenant1.application1.instance1': Instance already exists\"}",
- 400);
+ .oAuthCredentials(OKTA_CREDENTIALS)
+ .userIdentity(USER_ID),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not create 'tenant1.application1.instance1': Instance already exists\"}",
+ 400);
ConfigServerMock configServer = tester.serviceRegistry().configServerMock();
configServer.throwOnNextPrepare(new ConfigServerException(ConfigServerException.ErrorCode.INVALID_APPLICATION_PACKAGE, "Failed to prepare application", "Invalid application package"));
// GET non-existent application package
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET).userIdentity(HOSTED_VESPA_OPERATOR),
- "{\"error-code\":\"NOT_FOUND\",\"message\":\"no application package has been submitted for tenant1.application1\"}",
- 404);
+ "{\"error-code\":\"NOT_FOUND\",\"message\":\"no application package has been submitted for tenant1.application1\"}",
+ 404);
// GET non-existent application package of specific build
addScrewdriverUserToDeployRole(SCREWDRIVER_ID, ATHENZ_TENANT_DOMAIN, ApplicationName.from("application1"));
@@ -1218,63 +1218,63 @@ public class ApplicationApiTest extends ControllerContainerTest {
.data(createApplicationSubmissionData(applicationPackageInstance1, 1000)),
"{\"message\":\"application build 1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET)
- .properties(Map.of("build", "42"))
- .userIdentity(HOSTED_VESPA_OPERATOR),
- "{\"error-code\":\"NOT_FOUND\",\"message\":\"No build 42 found for tenant1.application1\"}",
- 404);
+ .properties(Map.of("build", "42"))
+ .userIdentity(HOSTED_VESPA_OPERATOR),
+ "{\"error-code\":\"NOT_FOUND\",\"message\":\"No build 42 found for tenant1.application1\"}",
+ 404);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/deployment", DELETE).userIdentity(USER_ID).oAuthCredentials(OKTA_CREDENTIALS),
"{\"message\":\"All deployments removed\"}");
// GET non-existent application package of invalid build
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/package", GET)
- .properties(Map.of("build", "foobar"))
- .userIdentity(HOSTED_VESPA_OPERATOR),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"invalid value for request parameter 'build': For input string: \\\"foobar\\\"\"}",
- 400);
-
+ .properties(Map.of("build", "foobar"))
+ .userIdentity(HOSTED_VESPA_OPERATOR),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"invalid value for request parameter 'build': For input string: \\\"foobar\\\"\"}",
+ 400);
+
// POST (deploy) an application to legacy deploy path
MultiPartStreamer entity = createApplicationDeployData(applicationPackageInstance1);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/dev/region/us-east-1/instance/instance1/deploy", POST)
- .data(entity)
- .userIdentity(USER_ID),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Deployment of tenant1.application1.instance1 is not supported through this API\"}", 400);
+ .data(entity)
+ .userIdentity(USER_ID),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Deployment of tenant1.application1.instance1 is not supported through this API\"}", 400);
// DELETE tenant which has an application
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
- .userIdentity(USER_ID)
- .oAuthCredentials(OKTA_CREDENTIALS),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not delete tenant 'tenant1': This tenant has active applications\"}",
- 400);
+ .userIdentity(USER_ID)
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Could not delete tenant 'tenant1': This tenant has active applications\"}",
+ 400);
// DELETE application
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
- .userIdentity(USER_ID)
- .oAuthCredentials(OKTA_CREDENTIALS),
- "{\"message\":\"Deleted instance tenant1.application1.instance1\"}");
+ .userIdentity(USER_ID)
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ "{\"message\":\"Deleted instance tenant1.application1.instance1\"}");
// DELETE application again - should produce 404
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", DELETE)
- .oAuthCredentials(OKTA_CREDENTIALS)
- .userIdentity(USER_ID),
- "{\"error-code\":\"NOT_FOUND\",\"message\":\"Could not delete instance 'tenant1.application1.instance1': Instance not found\"}",
- 404);
+ .oAuthCredentials(OKTA_CREDENTIALS)
+ .userIdentity(USER_ID),
+ "{\"error-code\":\"NOT_FOUND\",\"message\":\"Could not delete instance 'tenant1.application1.instance1': Instance not found\"}",
+ 404);
// DELETE and forget an application as non-operator
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE).properties(Map.of("forget", "true"))
- .userIdentity(USER_ID)
- .oAuthCredentials(OKTA_CREDENTIALS),
- "{\"error-code\":\"FORBIDDEN\",\"message\":\"Only operators can forget a tenant\"}",
- 403);
+ .userIdentity(USER_ID)
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ "{\"error-code\":\"FORBIDDEN\",\"message\":\"Only operators can forget a tenant\"}",
+ 403);
// DELETE tenant
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
- .userIdentity(USER_ID)
- .oAuthCredentials(OKTA_CREDENTIALS),
- "{\"message\":\"Deleted tenant tenant1\"}");
+ .userIdentity(USER_ID)
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ "{\"message\":\"Deleted tenant tenant1\"}");
// DELETE tenant again returns 403 as tenant access cannot be determined when the tenant does not exist
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
- .userIdentity(USER_ID),
- accessDenied,
- 403);
+ .userIdentity(USER_ID),
+ accessDenied,
+ 403);
// Create legacy tenant name containing underscores
tester.controller().curator().writeTenant(new AthenzTenant(TenantName.from("my_tenant"), ATHENZ_TENANT_DOMAIN,
@@ -1282,116 +1282,116 @@ public class ApplicationApiTest extends ControllerContainerTest {
// POST (add) a Athenz tenant with dashes duplicates existing one with underscores
tester.assertResponse(request("/application/v4/tenant/my-tenant", POST)
- .userIdentity(USER_ID)
- .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
- .oAuthCredentials(OKTA_CREDENTIALS),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'my-tenant' already exists\"}",
- 400);
+ .userIdentity(USER_ID)
+ .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Tenant 'my-tenant' already exists\"}",
+ 400);
}
@Test
- public void testAuthorization() {
+ void testAuthorization() {
UserId authorizedUser = USER_ID;
UserId unauthorizedUser = new UserId("othertenant");
-
+
// Mutation without an user is disallowed
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
- .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
- "{\n \"message\" : \"Not authenticated\"\n}",
- 401);
+ .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
+ "{\n \"message\" : \"Not authenticated\"\n}",
+ 401);
// ... but read methods are allowed for authenticated user
tester.assertResponse(request("/application/v4/tenant/", GET)
- .userIdentity(USER_ID)
- .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
- "[]",
- 200);
+ .userIdentity(USER_ID)
+ .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}"),
+ "[]",
+ 200);
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
// Creating a tenant for an Athens domain the user is not admin for is disallowed
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
- .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
- .oAuthCredentials(OKTA_CREDENTIALS)
- .userIdentity(unauthorizedUser),
- "{\"error-code\":\"FORBIDDEN\",\"message\":\"The user 'user.othertenant' is not admin in Athenz domain 'domain1'\"}",
- 403);
+ .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
+ .oAuthCredentials(OKTA_CREDENTIALS)
+ .userIdentity(unauthorizedUser),
+ "{\"error-code\":\"FORBIDDEN\",\"message\":\"The user 'user.othertenant' is not admin in Athenz domain 'domain1'\"}",
+ 403);
// (Create it with the right tenant id)
tester.assertResponse(request("/application/v4/tenant/tenant1", POST)
- .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
- .userIdentity(authorizedUser)
- .oAuthCredentials(OKTA_CREDENTIALS),
- new File("tenant-without-applications.json"),
- 200);
+ .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
+ .userIdentity(authorizedUser)
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ new File("tenant-without-applications.json"),
+ 200);
// Creating an application for an Athens domain the user is not admin for is disallowed
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
- .userIdentity(unauthorizedUser)
- .oAuthCredentials(OKTA_CREDENTIALS),
- accessDenied,
- 403);
+ .userIdentity(unauthorizedUser)
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ accessDenied,
+ 403);
// (Create it with the right tenant id)
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", POST)
- .userIdentity(authorizedUser)
- .oAuthCredentials(OKTA_CREDENTIALS),
- new File("instance-reference.json"),
- 200);
+ .userIdentity(authorizedUser)
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ new File("instance-reference.json"),
+ 200);
// Deploy to an authorized zone by a user tenant is disallowed
MultiPartStreamer entity = createApplicationDeployData(applicationPackageDefault);
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-west-1/instance/default/deploy", POST)
- .data(entity)
- .userIdentity(USER_ID),
- accessDenied,
- 403);
+ .data(entity)
+ .userIdentity(USER_ID),
+ accessDenied,
+ 403);
// Deleting an application for an Athens domain the user is not admin for is disallowed
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
- .userIdentity(unauthorizedUser),
- accessDenied,
- 403);
+ .userIdentity(unauthorizedUser),
+ accessDenied,
+ 403);
// Create another instance under the application
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/default", POST)
- .userIdentity(authorizedUser)
- .oAuthCredentials(OKTA_CREDENTIALS),
- new File("instance-reference-default.json"),
- 200);
+ .userIdentity(authorizedUser)
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ new File("instance-reference-default.json"),
+ 200);
// (Deleting the application with the right tenant id)
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1", DELETE)
- .userIdentity(authorizedUser)
- .oAuthCredentials(OKTA_CREDENTIALS),
- "{\"message\":\"Deleted application tenant1.application1\"}",
- 200);
+ .userIdentity(authorizedUser)
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ "{\"message\":\"Deleted application tenant1.application1\"}",
+ 200);
// Updating a tenant for an Athens domain the user is not admin for is disallowed
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
- .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
- .userIdentity(unauthorizedUser),
- accessDenied,
- 403);
-
+ .data("{\"athensDomain\":\"domain1\", \"property\":\"property1\"}")
+ .userIdentity(unauthorizedUser),
+ accessDenied,
+ 403);
+
// Change Athens domain
createAthenzDomainWithAdmin(new AthenzDomain("domain2"), USER_ID);
tester.assertResponse(request("/application/v4/tenant/tenant1", PUT)
- .data("{\"athensDomain\":\"domain2\", \"property\":\"property1\"}")
- .userIdentity(authorizedUser)
- .oAuthCredentials(OKTA_CREDENTIALS),
- new File("tenant1.json"),
- 200);
+ .data("{\"athensDomain\":\"domain2\", \"property\":\"property1\"}")
+ .userIdentity(authorizedUser)
+ .oAuthCredentials(OKTA_CREDENTIALS),
+ new File("tenant1.json"),
+ 200);
// Deleting a tenant for an Athens domain the user is not admin for is disallowed
tester.assertResponse(request("/application/v4/tenant/tenant1", DELETE)
- .userIdentity(unauthorizedUser),
- accessDenied,
- 403);
+ .userIdentity(unauthorizedUser),
+ accessDenied,
+ 403);
}
@Test
- public void athenz_service_must_be_allowed_to_launch_and_be_under_tenant_domain() {
+ void athenz_service_must_be_allowed_to_launch_and_be_under_tenant_domain() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.upgradePolicy("default")
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("another.domain"), com.yahoo.config.provision.AthenzService.from("service"))
@@ -1407,10 +1407,10 @@ public class ApplicationApiTest extends ControllerContainerTest {
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(new AthenzDomain("another.domain"), "service"));
// Submit a package with a service under a different Athenz domain from that of the tenant
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit/", POST)
- .data(createApplicationSubmissionData(applicationPackage, 123))
- .screwdriverIdentity(screwdriverId),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz domain in deployment.xml: [another.domain] must match tenant domain: [domain1]\"}",
- 400);
+ .data(createApplicationSubmissionData(applicationPackage, 123))
+ .screwdriverIdentity(screwdriverId),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Athenz domain in deployment.xml: [another.domain] must match tenant domain: [domain1]\"}",
+ 400);
// Set the correct domain in the application package, but do not yet allow Vespa to launch the service.
applicationPackage = new ApplicationPackageBuilder()
@@ -1420,22 +1420,22 @@ public class ApplicationApiTest extends ControllerContainerTest {
.build();
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit", POST)
- .data(createApplicationSubmissionData(applicationPackage, 123))
- .screwdriverIdentity(screwdriverId),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Not allowed to launch Athenz service domain1.service\"}",
- 400);
+ .data(createApplicationSubmissionData(applicationPackage, 123))
+ .screwdriverIdentity(screwdriverId),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Not allowed to launch Athenz service domain1.service\"}",
+ 400);
// Allow Vespa to launch the Athenz service.
allowLaunchOfService(new com.yahoo.vespa.athenz.api.AthenzService(ATHENZ_TENANT_DOMAIN, "service"));
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/submit/", POST)
- .data(createApplicationSubmissionData(applicationPackage, 123))
- .screwdriverIdentity(screwdriverId),
- "{\"message\":\"application build 1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
+ .data(createApplicationSubmissionData(applicationPackage, 123))
+ .screwdriverIdentity(screwdriverId),
+ "{\"message\":\"application build 1, source revision of repository 'repository1', branch 'master' with commit 'commit1', by a@b, built against 6.1 at 1970-01-01T00:00:01Z\"}");
}
@Test
- public void personal_deployment_with_athenz_service_requires_user_is_admin() {
+ void personal_deployment_with_athenz_service_requires_user_is_admin() {
// Setup
UserId tenantAdmin = new UserId("tenant-admin");
UserId userId = new UserId("new-user");
@@ -1450,26 +1450,26 @@ public class ApplicationApiTest extends ControllerContainerTest {
MultiPartStreamer entity = createApplicationDeployData(applicationPackage);
// POST (deploy) an application to dev through a deployment job, with user instance and a proper tenant
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/new-user/deploy/dev-us-east-1", POST)
- .data(entity)
- .userIdentity(userId),
- accessDenied,
- 403);
+ .data(entity)
+ .userIdentity(userId),
+ accessDenied,
+ 403);
// Add "new-user" to the admin role, to allow service launches.
tester.athenzClientFactory().getSetup()
.domains.get(ATHENZ_TENANT_DOMAIN)
- .admin(HostedAthenzIdentities.from(userId));
+ .admin(HostedAthenzIdentities.from(userId));
// POST (deploy) an application to dev through a deployment job
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/new-user/deploy/dev-us-east-1", POST)
- .data(entity)
- .userIdentity(userId),
- "{\"message\":\"Deployment started in run 1 of dev-us-east-1 for tenant1.application1.new-user. This may take about 15 minutes the first time.\",\"run\":1}");
+ .data(entity)
+ .userIdentity(userId),
+ "{\"message\":\"Deployment started in run 1 of dev-us-east-1 for tenant1.application1.new-user. This may take about 15 minutes the first time.\",\"run\":1}");
}
- @Test
// Deploy to sandbox tenant launching a service from another domain.
- public void developers_can_deploy_when_privileged() {
+ @Test
+ void developers_can_deploy_when_privileged() {
// Create an athenz domain where the developer is not yet authorized
UserId tenantAdmin = new UserId("tenant-admin");
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, tenantAdmin);
@@ -1503,7 +1503,7 @@ public class ApplicationApiTest extends ControllerContainerTest {
// Allow developer launch privilege to domain1.service. Deployment now completes.
AthenzDbMock.Domain domainMock = tester.athenzClientFactory().getSetup().getOrCreateDomain(ATHENZ_TENANT_DOMAIN);
- domainMock.withPolicy("launch-" +developer.id(), "user." + developer.id(), "launch", "service.service");
+ domainMock.withPolicy("launch-" + developer.id(), "user." + developer.id(), "launch", "service.service");
tester.assertResponse(request("/application/v4/tenant/sandbox/application/myapp/instance/default/deploy/dev-us-east-1", POST)
@@ -1526,25 +1526,25 @@ public class ApplicationApiTest extends ControllerContainerTest {
// POST (deploy) an application package as content type application/zip — not multipart
tester.assertResponse(request("/application/v4/tenant/sandbox/application/myapp/instance/default/deploy/dev-us-east-1", POST)
- .data(applicationPackageInstance1.zippedContent())
- .contentType("application/zip")
- .userIdentity(developer2),
- "{\"message\":\"Deployment started in run 3 of dev-us-east-1 for sandbox.myapp. This may take about 15 minutes the first time.\",\"run\":3}");
+ .data(applicationPackageInstance1.zippedContent())
+ .contentType("application/zip")
+ .userIdentity(developer2),
+ "{\"message\":\"Deployment started in run 3 of dev-us-east-1 for sandbox.myapp. This may take about 15 minutes the first time.\",\"run\":3}");
// POST (deploy) an application package not as content type application/zip — not multipart — is disallowed
tester.assertResponse(request("/application/v4/tenant/sandbox/application/myapp/instance/default/deploy/dev-us-east-1", POST)
- .data(applicationPackageInstance1.zippedContent())
- .contentType("application/gzip")
- .userIdentity(developer2),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Expected a multipart or application/zip message, but got Content-Type: application/gzip\"}", 400);
+ .data(applicationPackageInstance1.zippedContent())
+ .contentType("application/gzip")
+ .userIdentity(developer2),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Expected a multipart or application/zip message, but got Content-Type: application/gzip\"}", 400);
}
@Test
- public void applicationWithRoutingPolicy() {
+ void applicationWithRoutingPolicy() {
var app = deploymentTester.newDeploymentContext(createTenantAndApplication());
var zone = ZoneId.from(Environment.prod, RegionName.from("us-west-1"));
deploymentTester.controllerTester().zoneRegistry().setRoutingMethod(ZoneApiMock.from(zone),
- RoutingMethod.exclusive);
+ RoutingMethod.exclusive);
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.athenzIdentity(com.yahoo.config.provision.AthenzDomain.from("domain"), AthenzService.from("service"))
.instances("instance1")
@@ -1555,22 +1555,22 @@ public class ApplicationApiTest extends ControllerContainerTest {
// GET application
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1", GET)
- .userIdentity(USER_ID),
- new File("instance-with-routing-policy.json"));
+ .userIdentity(USER_ID),
+ new File("instance-with-routing-policy.json"));
// GET deployment
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-west-1/instance/instance1", GET)
- .userIdentity(USER_ID),
- new File("deployment-with-routing-policy.json"));
+ .userIdentity(USER_ID),
+ new File("deployment-with-routing-policy.json"));
// GET deployment
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/environment/prod/region/us-west-1/instance/instance1", GET)
- .userIdentity(USER_ID),
- new File("deployment-without-shared-endpoints.json"));
+ .userIdentity(USER_ID),
+ new File("deployment-without-shared-endpoints.json"));
}
@Test
- public void support_access() {
+ void support_access() {
var app = deploymentTester.newDeploymentContext(createTenantAndApplication());
var zone = ZoneId.from(Environment.prod, RegionName.from("us-west-1"));
deploymentTester.controllerTester().zoneRegistry().setRoutingMethod(ZoneApiMock.from(zone), RoutingMethod.exclusive);
@@ -1601,15 +1601,15 @@ public class ApplicationApiTest extends ControllerContainerTest {
// Grant access to support user
X509Certificate support_cert = grantCertificate(now, now.plusSeconds(3600));
- String grantPayload= "{\n" +
- " \"applicationId\": \"tenant1:application1:instance1\",\n" +
- " \"zone\": \"prod.us-west-1\",\n" +
- " \"certificate\":\""+X509CertificateUtils.toPem(support_cert)+ "\"\n" +
- "}";
- tester.assertResponse(request("/controller/v1/access/grants/"+HOSTED_VESPA_OPERATOR.id(), POST)
- .data(grantPayload)
- .userIdentity(HOSTED_VESPA_OPERATOR),
- "{\"message\":\"Operator user.johnoperator granted access and job production-us-west-1 triggered\"}");
+ String grantPayload = "{\n" +
+ " \"applicationId\": \"tenant1:application1:instance1\",\n" +
+ " \"zone\": \"prod.us-west-1\",\n" +
+ " \"certificate\":\"" + X509CertificateUtils.toPem(support_cert) + "\"\n" +
+ "}";
+ tester.assertResponse(request("/controller/v1/access/grants/" + HOSTED_VESPA_OPERATOR.id(), POST)
+ .data(grantPayload)
+ .userIdentity(HOSTED_VESPA_OPERATOR),
+ "{\"message\":\"Operator user.johnoperator granted access and job production-us-west-1 triggered\"}");
// GET shows grant
String grantResponse = allowedResponse.replaceAll("\"grants\":\\[]",
@@ -1631,7 +1631,7 @@ public class ApplicationApiTest extends ControllerContainerTest {
// DELETE removes access
String disallowedResponse = grantResponse
.replaceAll("ALLOWED\".*?}", "NOT_ALLOWED\"}")
- .replace("history\":[", "history\":[{\"state\":\"disallowed\",\"at\":\""+ serializeInstant(now) +"\",\"by\":\"user.myuser\"},");
+ .replace("history\":[", "history\":[{\"state\":\"disallowed\",\"at\":\"" + serializeInstant(now) + "\",\"by\":\"user.myuser\"},");
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/environment/prod/region/us-west-1/access/support", DELETE)
.userIdentity(USER_ID),
disallowedResponse, 200
@@ -1646,7 +1646,7 @@ public class ApplicationApiTest extends ControllerContainerTest {
}
@Test
- public void create_application_on_deploy() {
+ void create_application_on_deploy() {
// Setup
createAthenzDomainWithAdmin(ATHENZ_TENANT_DOMAIN, USER_ID);
addUserToHostedOperatorRole(HostedAthenzIdentities.from(HOSTED_VESPA_OPERATOR));
@@ -1668,7 +1668,7 @@ public class ApplicationApiTest extends ControllerContainerTest {
tester.assertResponse(request("/application/v4/tenant/tenant1/application/application1/instance/instance1/deploy/dev-us-east-1/", POST)
.data(entity)
.oAuthCredentials(OKTA_CREDENTIALS)
-
+
.userIdentity(USER_ID),
"{\"message\":\"Deployment started in run 1 of dev-us-east-1 for tenant1.application1.instance1. This may take about 15 minutes the first time.\",\"run\":1}");
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/CliApiHandlerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/CliApiHandlerTest.java
index 5a4d47e0db5..4166ce8b81e 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/CliApiHandlerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/CliApiHandlerTest.java
@@ -3,8 +3,8 @@ package com.yahoo.vespa.hosted.controller.restapi.application;
import com.yahoo.vespa.hosted.controller.restapi.ContainerTester;
import com.yahoo.vespa.hosted.controller.restapi.ControllerContainerTest;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
/**
* @author mpolden
@@ -13,13 +13,13 @@ public class CliApiHandlerTest extends ControllerContainerTest {
private ContainerTester tester;
- @Before
+ @BeforeEach
public void before() {
tester = new ContainerTester(container, "src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/responses/");
}
@Test
- public void root() {
+ void root() {
tester.assertResponse(authenticatedRequest("http://localhost:8080/cli/v1/"), "{\"minVersion\":\"7.547.18\"}");
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/JobControllerApiHandlerHelperTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/JobControllerApiHandlerHelperTest.java
index d2698afdc48..233b460333e 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/JobControllerApiHandlerHelperTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/JobControllerApiHandlerHelperTest.java
@@ -15,7 +15,7 @@ import com.yahoo.vespa.hosted.controller.deployment.DeploymentContext;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester;
import com.yahoo.vespa.hosted.controller.notification.Notification.Type;
import com.yahoo.vespa.hosted.controller.notification.NotificationSource;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.net.URI;
@@ -40,7 +40,7 @@ import static com.yahoo.vespa.hosted.controller.deployment.RunStatus.deploymentF
import static com.yahoo.vespa.hosted.controller.deployment.RunStatus.installationFailed;
import static com.yahoo.vespa.hosted.controller.deployment.RunStatus.running;
import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author jonmv
@@ -49,7 +49,7 @@ import static org.junit.Assert.assertEquals;
public class JobControllerApiHandlerHelperTest {
@Test
- public void testResponses() {
+ void testResponses() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.stagingTest()
.blockChange(true, true, "mon,tue", "7-13", "UTC")
@@ -100,7 +100,7 @@ public class JobControllerApiHandlerHelperTest {
// Revision 3 starts.
app.submit(applicationPackage)
- .runJob(systemTest).runJob(stagingTest);
+ .runJob(systemTest).runJob(stagingTest);
tester.triggerJobs(); // Starts runs for us-central-1 and a new staging test run.
tester.runner().run();
assertEquals(running, tester.jobs().last(app.instanceId(), productionUsCentral1).get().status());
@@ -147,7 +147,7 @@ public class JobControllerApiHandlerHelperTest {
}
@Test
- public void testDevResponses() {
+ void testDevResponses() {
DeploymentTester tester = new DeploymentTester();
var app = tester.newDeploymentContext();
tester.clock().setInstant(Instant.EPOCH);
@@ -167,7 +167,7 @@ public class JobControllerApiHandlerHelperTest {
}
@Test
- public void testResponsesWithDirectDeployment() {
+ void testResponsesWithDirectDeployment() {
var tester = new DeploymentTester();
var app = tester.newDeploymentContext();
tester.clock().setInstant(Instant.EPOCH);
@@ -176,11 +176,11 @@ public class JobControllerApiHandlerHelperTest {
// Deploy directly to production zone, like integration tests.
tester.controller().jobController().deploy(tester.instance().id(), productionUsWest1, Optional.empty(), applicationPackage);
assertResponse(JobControllerApiHandlerHelper.jobTypeResponse(tester.controller(), app.instanceId(), URI.create("https://some.url:43/root/")),
- "jobs-direct-deployment.json");
+ "jobs-direct-deployment.json");
}
@Test
- public void testResponsesWithDryRunDeployment() {
+ void testResponsesWithDryRunDeployment() {
var tester = new DeploymentTester();
var app = tester.newDeploymentContext();
tester.clock().setInstant(Instant.EPOCH);
@@ -189,7 +189,7 @@ public class JobControllerApiHandlerHelperTest {
// Deploy directly to production zone, like integration tests, with dryRun.
tester.controller().jobController().deploy(tester.instance().id(), productionUsWest1, Optional.empty(), applicationPackage, true);
assertResponse(JobControllerApiHandlerHelper.jobTypeResponse(tester.controller(), app.instanceId(), URI.create("https://some.url:43/root/")),
- "jobs-direct-deployment.json");
+ "jobs-direct-deployment.json");
}
private void assertResponse(HttpResponse response, String fileName) {
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/MultipartParserTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/MultipartParserTest.java
index 12a0a00713c..37f4c19e27a 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/MultipartParserTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/application/MultipartParserTest.java
@@ -7,16 +7,16 @@ import com.yahoo.jdisc.Request;
import com.yahoo.jdisc.ResourceReference;
import com.yahoo.jdisc.handler.RequestHandler;
import com.yahoo.jdisc.service.CurrentContainer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Map;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author bratseth
@@ -24,25 +24,25 @@ import static org.junit.Assert.fail;
public class MultipartParserTest {
@Test
- public void parser() {
+ void parser() {
String data =
"Content-Type: multipart/form-data; boundary=AaB03x\r\n" +
- "\r\n" +
- "--AaB03x\r\n" +
- "Content-Disposition: form-data; name=\"submit-name\"\r\n" +
- "\r\n" +
- "Larry\r\n" +
- "--AaB03x\r\n" +
- "Content-Disposition: form-data; name=\"submit-address\"\r\n" +
- "Content-Type: text/plain\r\n" +
- "\r\n" +
- "House 1\r\n" +
- "--AaB03x\r\n" +
- "Content-Disposition: form-data; name=\"files\"; filename=\"file1.txt\"\r\n" +
- "Content-Type: text/plain\r\n" +
- "\r\n" +
- "... contents of file1.txt ...\r\n" +
- "--AaB03x--\r\n";
+ "\r\n" +
+ "--AaB03x\r\n" +
+ "Content-Disposition: form-data; name=\"submit-name\"\r\n" +
+ "\r\n" +
+ "Larry\r\n" +
+ "--AaB03x\r\n" +
+ "Content-Disposition: form-data; name=\"submit-address\"\r\n" +
+ "Content-Type: text/plain\r\n" +
+ "\r\n" +
+ "House 1\r\n" +
+ "--AaB03x\r\n" +
+ "Content-Disposition: form-data; name=\"files\"; filename=\"file1.txt\"\r\n" +
+ "Content-Type: text/plain\r\n" +
+ "\r\n" +
+ "... contents of file1.txt ...\r\n" +
+ "--AaB03x--\r\n";
Map<String, byte[]> parts = parse(data, Long.MAX_VALUE);
assertEquals(3, parts.size());
assertTrue(parts.containsKey("submit-name"));
@@ -53,22 +53,22 @@ public class MultipartParserTest {
}
@Test
- public void max_length() {
+ void max_length() {
String part1 = "Larry";
String part2 = "House 1";
String data =
"Content-Type: multipart/form-data; boundary=AaB03x\r\n" +
- "\r\n" +
- "--AaB03x\r\n" +
- "Content-Disposition: form-data; name=\"submit-name\"\r\n" +
- "\r\n" +
- part1 + "\r\n" +
- "--AaB03x\r\n" +
- "Content-Disposition: form-data; name=\"submit-address\"\r\n" +
- "Content-Type: text/plain\r\n" +
- "\r\n" +
- part2 + "\r\n" +
- "--AaB03x--\r\n";
+ "\r\n" +
+ "--AaB03x\r\n" +
+ "Content-Disposition: form-data; name=\"submit-name\"\r\n" +
+ "\r\n" +
+ part1 + "\r\n" +
+ "--AaB03x\r\n" +
+ "Content-Disposition: form-data; name=\"submit-address\"\r\n" +
+ "Content-Type: text/plain\r\n" +
+ "\r\n" +
+ part2 + "\r\n" +
+ "--AaB03x--\r\n";
parse(data, part1.length() + part2.length());
try {
parse(data, part1.length() + part2.length() - 1);
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/athenz/AthenzApiTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/athenz/AthenzApiTest.java
index de3968727d6..3a539987443 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/athenz/AthenzApiTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/athenz/AthenzApiTest.java
@@ -7,7 +7,7 @@ import com.yahoo.vespa.athenz.api.AthenzDomain;
import com.yahoo.vespa.hosted.controller.ControllerTester;
import com.yahoo.vespa.hosted.controller.restapi.ContainerTester;
import com.yahoo.vespa.hosted.controller.restapi.ControllerContainerTest;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.File;
@@ -19,7 +19,7 @@ public class AthenzApiTest extends ControllerContainerTest {
private static final String responseFiles = "src/test/java/com/yahoo/vespa/hosted/controller/restapi/athenz/responses/";
@Test
- public void testAthenzApi() {
+ void testAthenzApi() {
ContainerTester tester = new ContainerTester(container, responseFiles);
ControllerTester controllerTester = new ControllerTester(tester);
@@ -38,19 +38,19 @@ public class AthenzApiTest extends ControllerContainerTest {
// GET root
tester.assertResponse(authenticatedRequest("http://localhost:8080/athenz/v1/"),
- new File("root.json"));
+ new File("root.json"));
// GET Athenz domains
tester.assertResponse(authenticatedRequest("http://localhost:8080/athenz/v1/domains"),
- new File("athensDomain-list.json"));
+ new File("athensDomain-list.json"));
// GET properties
tester.assertResponse(authenticatedRequest("http://localhost:8080/athenz/v1/properties/"),
- new File("property-list.json"));
+ new File("property-list.json"));
// POST user signup
tester.assertResponse(authenticatedRequest("http://localhost:8080/athenz/v1/user", "", Request.Method.POST),
- "{\"message\":\"User 'bob' added to admin role of 'vespa.vespa.tenants.sandbox'\"}");
+ "{\"message\":\"User 'bob' added to admin role of 'vespa.vespa.tenants.sandbox'\"}");
}
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/billing/BillingApiHandlerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/billing/BillingApiHandlerTest.java
index 38ebe030e8e..aa9cb57f541 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/billing/BillingApiHandlerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/billing/BillingApiHandlerTest.java
@@ -12,9 +12,8 @@ import com.yahoo.vespa.hosted.controller.restapi.ContainerTester;
import com.yahoo.vespa.hosted.controller.restapi.ControllerContainerCloudTest;
import com.yahoo.vespa.hosted.controller.security.Auth0Credentials;
import com.yahoo.vespa.hosted.controller.security.CloudTenantSpec;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.math.BigDecimal;
@@ -30,8 +29,8 @@ import static com.yahoo.application.container.handler.Request.Method.DELETE;
import static com.yahoo.application.container.handler.Request.Method.GET;
import static com.yahoo.application.container.handler.Request.Method.PATCH;
import static com.yahoo.application.container.handler.Request.Method.POST;
-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 olaa
@@ -47,7 +46,7 @@ public class BillingApiHandlerTest extends ControllerContainerCloudTest {
private ContainerTester tester;
- @Before
+ @BeforeEach
public void setup() {
tester = new ContainerTester(container, responseFiles);
billingController = (MockBillingController) tester.serviceRegistry().billingController();
@@ -79,32 +78,32 @@ public class BillingApiHandlerTest extends ControllerContainerCloudTest {
}
@Test
- public void list_plans() {
+ void list_plans() {
var listPlansRequest = request("/billing/v1/plans", GET)
.roles(Role.hostedAccountant());
tester.assertResponse(listPlansRequest, "{\"plans\":[{\"id\":\"trial\",\"name\":\"Free Trial - for testing purposes\"},{\"id\":\"paid\",\"name\":\"Paid Plan - for testing purposes\"},{\"id\":\"none\",\"name\":\"None Plan - for testing purposes\"}]}");
}
@Test
- public void setting_and_deleting_instrument() {
+ void setting_and_deleting_instrument() {
assertTrue(billingController.getDefaultInstrument(tenant).isEmpty());
var instrumentRequest = request("/billing/v1/tenant/tenant1/instrument", PATCH)
.data("{\"active\": \"id-1\"}")
.roles(tenantRole);
- tester.assertResponse(instrumentRequest,"OK");
+ tester.assertResponse(instrumentRequest, "OK");
assertEquals("id-1", billingController.getDefaultInstrument(tenant).get().getId());
var deleteInstrumentRequest = request("/billing/v1/tenant/tenant1/instrument/id-1", DELETE)
.roles(tenantRole);
- tester.assertResponse(deleteInstrumentRequest,"OK");
+ tester.assertResponse(deleteInstrumentRequest, "OK");
assertTrue(billingController.getDefaultInstrument(tenant).isEmpty());
}
@Test
- public void response_list_bills() {
+ void response_list_bills() {
var bill = createBill();
billingController.addBill(tenant, bill, true);
@@ -117,7 +116,7 @@ public class BillingApiHandlerTest extends ControllerContainerCloudTest {
}
@Test
- public void test_bill_creation() {
+ void test_bill_creation() {
var bills = billingController.getBillsForTenant(tenant);
assertEquals(0, bills.size());
@@ -141,7 +140,7 @@ public class BillingApiHandlerTest extends ControllerContainerCloudTest {
}
@Test
- public void adding_and_listing_line_item() {
+ void adding_and_listing_line_item() {
var requestBody = "{" +
"\"description\":\"some description\"," +
@@ -155,7 +154,7 @@ public class BillingApiHandlerTest extends ControllerContainerCloudTest {
tester.assertResponse(request, "{\"message\":\"Added line item for tenant tenant1\"}");
var lineItems = billingController.getUnusedLineItems(tenant);
- Assert.assertEquals(1, lineItems.size());
+ assertEquals(1, lineItems.size());
Bill.LineItem lineItem = lineItems.get(0);
assertEquals("some description", lineItem.description());
assertEquals(new BigDecimal("123.45"), lineItem.amount());
@@ -167,7 +166,7 @@ public class BillingApiHandlerTest extends ControllerContainerCloudTest {
}
@Test
- public void adding_new_status() {
+ void adding_new_status() {
billingController.addBill(tenant, createBill(), true);
var requestBody = "{\"status\":\"DONE\"}";
@@ -181,7 +180,7 @@ public class BillingApiHandlerTest extends ControllerContainerCloudTest {
}
@Test
- public void list_all_unbilled_items() {
+ void list_all_unbilled_items() {
tester.controller().tenants().create(new CloudTenantSpec(tenant, ""), new Auth0Credentials(() -> "foo", Set.of(Role.hostedOperator())));
tester.controller().tenants().create(new CloudTenantSpec(tenant2, ""), new Auth0Credentials(() -> "foo", Set.of(Role.hostedOperator())));
@@ -198,7 +197,7 @@ public class BillingApiHandlerTest extends ControllerContainerCloudTest {
}
@Test
- public void setting_plans() {
+ void setting_plans() {
var planRequest = request("/billing/v1/tenant/tenant1/plan", PATCH)
.data("{\"plan\": \"new-plan\"}")
.roles(tenantRole);
@@ -207,7 +206,7 @@ public class BillingApiHandlerTest extends ControllerContainerCloudTest {
}
@Test
- public void csv_export() {
+ void csv_export() {
var bill = createBill();
billingController.addBill(tenant, bill, true);
var csvRequest = request("/billing/v1/invoice/export", GET).roles(financeAdmin);
@@ -215,7 +214,7 @@ public class BillingApiHandlerTest extends ControllerContainerCloudTest {
}
@Test
- public void patch_collection_method() {
+ void patch_collection_method() {
test_patch_collection_with_field_name("collectionMethod");
test_patch_collection_with_field_name("collection");
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/billing/BillingApiHandlerV2Test.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/billing/BillingApiHandlerV2Test.java
index 58701732515..7c3f0e51b92 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/billing/BillingApiHandlerV2Test.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/billing/BillingApiHandlerV2Test.java
@@ -10,8 +10,8 @@ import com.yahoo.vespa.hosted.controller.restapi.ContainerTester;
import com.yahoo.vespa.hosted.controller.restapi.ControllerContainerCloudTest;
import com.yahoo.vespa.hosted.controller.security.Auth0Credentials;
import com.yahoo.vespa.hosted.controller.security.CloudTenantSpec;
-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.Set;
@@ -37,7 +37,7 @@ public class BillingApiHandlerV2Test extends ControllerContainerCloudTest {
private MockBillingController billingController;
private ContainerTester tester;
- @Before
+ @BeforeEach
public void before() {
tester = new ContainerTester(container, responseFiles);
tester.controller().tenants().create(new CloudTenantSpec(tenant, ""), new Auth0Credentials(() -> "foo", Set.of(Role.hostedOperator())));
@@ -68,13 +68,13 @@ public class BillingApiHandlerV2Test extends ControllerContainerCloudTest {
}
@Test
- public void require_tenant_info() {
+ void require_tenant_info() {
var request = request("/billing/v2/tenant/" + tenant.value()).roles(tenantReader);
tester.assertResponse(request, "{\"tenant\":\"tenant1\",\"plan\":{\"id\":\"trial\",\"name\":\"Free Trial - for testing purposes\"},\"collection\":\"AUTO\"}");
}
@Test
- public void require_admin_for_update_plan() {
+ void require_admin_for_update_plan() {
var request = request("/billing/v2/tenant/" + tenant.value(), Request.Method.PATCH)
.data("{\"plan\": \"paid\"}");
@@ -86,7 +86,7 @@ public class BillingApiHandlerV2Test extends ControllerContainerCloudTest {
}
@Test
- public void require_accountant_for_update_collection() {
+ void require_accountant_for_update_collection() {
var request = request("/billing/v2/tenant/" + tenant.value(), Request.Method.PATCH)
.data("{\"collection\": \"INVOICE\"}");
@@ -99,13 +99,13 @@ public class BillingApiHandlerV2Test extends ControllerContainerCloudTest {
}
@Test
- public void require_tenant_usage() {
+ void require_tenant_usage() {
var request = request("/billing/v2/tenant/" + tenant + "/usage").roles(tenantReader);
tester.assertResponse(request, "{\"from\":\"2021-04-13\",\"to\":\"2021-04-13\",\"total\":\"0.00\",\"items\":[]}");
}
@Test
- public void require_tenant_invoice() {
+ void require_tenant_invoice() {
var listRequest = request("/billing/v2/tenant/" + tenant + "/bill").roles(tenantReader);
tester.assertResponse(listRequest, "{\"invoices\":[{\"id\":\"id-1\",\"from\":\"2020-05-23\",\"to\":\"2020-05-28\",\"total\":\"123.00\",\"status\":\"OPEN\"}]}");
@@ -115,7 +115,7 @@ public class BillingApiHandlerV2Test extends ControllerContainerCloudTest {
}
@Test
- public void require_accountant_summary() {
+ void require_accountant_summary() {
var tenantRequest = request("/billing/v2/accountant").roles(tenantReader);
tester.assertResponse(tenantRequest, "{\n" +
" \"code\" : 403,\n" +
@@ -128,13 +128,13 @@ public class BillingApiHandlerV2Test extends ControllerContainerCloudTest {
}
@Test
- public void require_accountant_tenant_preview() {
+ void require_accountant_tenant_preview() {
var accountantRequest = request("/billing/v2/accountant/preview/tenant/tenant1").roles(Role.hostedAccountant());
tester.assertResponse(accountantRequest, "{\"id\":\"empty\",\"from\":\"2021-04-13\",\"to\":\"2021-04-12\",\"total\":\"0.00\",\"status\":\"OPEN\",\"statusHistory\":[{\"at\":\"2021-04-13T00:00:00Z\",\"status\":\"OPEN\"}],\"items\":[]}");
}
@Test
- public void require_accountant_tenant_bill() {
+ void require_accountant_tenant_bill() {
var accountantRequest = request("/billing/v2/accountant/preview/tenant/tenant1", Request.Method.POST)
.roles(Role.hostedAccountant())
.data("{\"from\": \"2020-05-01\",\"to\": \"2020-06-01\"}");
@@ -142,7 +142,7 @@ public class BillingApiHandlerV2Test extends ControllerContainerCloudTest {
}
@Test
- public void require_list_of_all_plans() {
+ void require_list_of_all_plans() {
var accountantRequest = request("/billing/v2/accountant/plans")
.roles(Role.hostedAccountant());
tester.assertResponse(accountantRequest, "{\"plans\":[{\"id\":\"trial\",\"name\":\"Free Trial - for testing purposes\"},{\"id\":\"paid\",\"name\":\"Paid Plan - for testing purposes\"},{\"id\":\"none\",\"name\":\"None Plan - for testing purposes\"}]}");
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/changemanagement/ChangeManagementApiHandlerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/changemanagement/ChangeManagementApiHandlerTest.java
index ea2c303d3f6..de2bf70997a 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/changemanagement/ChangeManagementApiHandlerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/changemanagement/ChangeManagementApiHandlerTest.java
@@ -13,8 +13,8 @@ import com.yahoo.vespa.hosted.controller.api.integration.vcmr.HostAction;
import com.yahoo.vespa.hosted.controller.api.integration.vcmr.VespaChangeRequest;
import com.yahoo.vespa.hosted.controller.restapi.ContainerTester;
import com.yahoo.vespa.hosted.controller.restapi.ControllerContainerTest;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.time.Instant;
@@ -22,7 +22,7 @@ import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.List;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class ChangeManagementApiHandlerTest extends ControllerContainerTest {
@@ -32,7 +32,7 @@ public class ChangeManagementApiHandlerTest extends ControllerContainerTest {
private ContainerTester tester;
- @Before
+ @BeforeEach
public void before() {
tester = new ContainerTester(container, responses);
addUserToHostedOperatorRole(operator);
@@ -42,26 +42,26 @@ public class ChangeManagementApiHandlerTest extends ControllerContainerTest {
}
@Test
- public void test_api() {
+ void test_api() {
assertFile(new Request("http://localhost:8080/changemanagement/v1/assessment", "{\"zone\":\"prod.us-east-3\", \"hosts\": [\"host1\"]}", Request.Method.POST), "initial.json");
assertFile(new Request("http://localhost:8080/changemanagement/v1/assessment", "{\"zone\":\"prod.us-east-3\", \"switches\": [\"switch1\"]}", Request.Method.POST), "initial.json");
assertFile(new Request("http://localhost:8080/changemanagement/v1/vcmr"), "vcmrs.json");
}
@Test
- public void deletes_vcmr() {
+ void deletes_vcmr() {
assertEquals(1, tester.controller().curator().readChangeRequests().size());
assertFile(new Request("http://localhost:8080/changemanagement/v1/vcmr/" + changeRequestId, "", Request.Method.DELETE), "vcmr.json");
assertEquals(0, tester.controller().curator().readChangeRequests().size());
}
@Test
- public void get_vcmr() {
+ void get_vcmr() {
assertFile(new Request("http://localhost:8080/changemanagement/v1/vcmr/" + changeRequestId, "", Request.Method.GET), "vcmr.json");
}
@Test
- public void patch_vcmr() {
+ void patch_vcmr() {
var payload = "{" +
"\"approval\": \"REJECTED\"," +
"\"status\": \"COMPLETED\"," +
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/configserver/ConfigServerApiHandlerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/configserver/ConfigServerApiHandlerTest.java
index ce6f713a13d..8bda8ba0d59 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/configserver/ConfigServerApiHandlerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/configserver/ConfigServerApiHandlerTest.java
@@ -10,15 +10,15 @@ import com.yahoo.vespa.hosted.controller.integration.ZoneApiMock;
import com.yahoo.vespa.hosted.controller.proxy.ProxyRequest;
import com.yahoo.vespa.hosted.controller.restapi.ContainerTester;
import com.yahoo.vespa.hosted.controller.restapi.ControllerContainerTest;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.net.URI;
import java.util.List;
-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 freva
@@ -35,7 +35,7 @@ public class ConfigServerApiHandlerTest extends ControllerContainerTest {
private ContainerTester tester;
private ConfigServerProxyMock proxy;
- @Before
+ @BeforeEach
public void before() {
tester = new ContainerTester(container, responseFiles);
tester.serviceRegistry().zoneRegistry()
@@ -45,14 +45,14 @@ public class ConfigServerApiHandlerTest extends ControllerContainerTest {
}
@Test
- public void test_requests() {
+ void test_requests() {
// GET /configserver/v1
tester.assertResponse(operatorRequest("http://localhost:8080/configserver/v1"),
new File("root.json"));
// GET /configserver/v1/nodes/v2
tester.assertResponse(operatorRequest("http://localhost:8080/configserver/v1/prod/us-north-1/nodes/v2"),
- "ok");
+ "ok");
assertLastRequest("https://cfg.prod.us-north-1.test.vip:4443/", "GET");
// GET /configserver/v1/nodes/v2/node/?recursive=true
@@ -82,11 +82,11 @@ public class ConfigServerApiHandlerTest extends ControllerContainerTest {
assertLastRequest("https://cfg.dev.aws-us-north-2.test.vip:4443/", "PATCH");
assertEquals("{\"currentRestartGeneration\": 1}", proxy.lastRequestBody().get());
- assertFalse("Actions are logged to audit log", tester.controller().auditLogger().readLog().entries().isEmpty());
+ assertFalse(tester.controller().auditLogger().readLog().entries().isEmpty(), "Actions are logged to audit log");
}
@Test
- public void test_allowed_apis() {
+ void test_allowed_apis() {
// GET /configserver/v1/prod/us-north-1
tester.assertResponse(() -> operatorRequest("http://localhost:8080/configserver/v1/prod/us-north-1/"),
"{\"error-code\":\"FORBIDDEN\",\"message\":\"Cannot access path '/' through /configserver/v1, following APIs are permitted: /flags/v1/, /nodes/v2/, /orchestrator/v1/\"}",
@@ -98,33 +98,33 @@ public class ConfigServerApiHandlerTest extends ControllerContainerTest {
}
@Test
- public void test_invalid_requests() {
+ void test_invalid_requests() {
// POST /configserver/v1/prod/us-north-34/nodes/v2
tester.assertResponse(() -> operatorRequest("http://localhost:8080/configserver/v1/prod/us-north-42/nodes/v2",
- "", Request.Method.POST),
+ "", Request.Method.POST),
"{\"error-code\":\"BAD_REQUEST\",\"message\":\"No such zone: prod.us-north-42\"}", 400);
assertFalse(proxy.lastReceived().isPresent());
}
@Test
- public void non_operators_are_forbidden() {
+ void non_operators_are_forbidden() {
// Read request
tester.assertResponse(() -> authenticatedRequest("http://localhost:8080/configserver/v1/prod/us-north-1/nodes/v2/node"),
"{\n" +
- " \"code\" : 403,\n" +
- " \"message\" : \"Access denied\"\n" +
- "}", 403);
+ " \"code\" : 403,\n" +
+ " \"message\" : \"Access denied\"\n" +
+ "}", 403);
// Write request
tester.assertResponse(() -> authenticatedRequest("http://localhost:8080/configserver/v1/prod/us-north-1/nodes/v2/node", "", Request.Method.POST),
"{\n" +
- " \"code\" : 403,\n" +
- " \"message\" : \"Access denied\"\n" +
- "}", 403);
+ " \"code\" : 403,\n" +
+ " \"message\" : \"Access denied\"\n" +
+ "}", 403);
}
@Test
- public void unauthenticated_request_are_unauthorized() {
+ void unauthenticated_request_are_unauthorized() {
{
// Read request
Request request = new Request("http://localhost:8080/configserver/v1/prod/us-north-1/nodes/v2/node", "", Request.Method.GET);
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/controller/ControllerApiTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/controller/ControllerApiTest.java
index 5936c135af9..fa652af18f3 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/controller/ControllerApiTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/controller/ControllerApiTest.java
@@ -17,8 +17,8 @@ import com.yahoo.vespa.hosted.controller.auditlog.AuditLogger;
import com.yahoo.vespa.hosted.controller.integration.NodeRepositoryMock;
import com.yahoo.vespa.hosted.controller.restapi.ContainerTester;
import com.yahoo.vespa.hosted.controller.restapi.ControllerContainerTest;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.File;
@@ -27,7 +27,7 @@ import java.time.Duration;
import java.time.Instant;
import java.util.List;
-import static org.junit.Assert.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertFalse;
/**
* @author bratseth
@@ -38,42 +38,42 @@ public class ControllerApiTest extends ControllerContainerTest {
private ContainerTester tester;
- @Before
+ @BeforeEach
public void before() {
tester = new ContainerTester(container, responseFiles);
}
@Test
- public void testControllerApi() {
+ void testControllerApi() {
tester.assertResponse(authenticatedRequest("http://localhost:8080/controller/v1/", "", Request.Method.GET), new File("root.json"));
((InMemoryFlagSource) tester.controller().flagSource()).withListFlag(PermanentFlags.INACTIVE_MAINTENANCE_JOBS.id(), List.of("DeploymentExpirer"), String.class);
// GET a list of all maintenance jobs
tester.assertResponse(authenticatedRequest("http://localhost:8080/controller/v1/maintenance/", "", Request.Method.GET),
- new File("maintenance.json"));
+ new File("maintenance.json"));
}
@Test
- public void testStats() {
- var mock = (NodeRepositoryMock)tester.controller().serviceRegistry().configServer().nodeRepository();
+ void testStats() {
+ var mock = (NodeRepositoryMock) tester.controller().serviceRegistry().configServer().nodeRepository();
mock.putApplication(ZoneId.from("prod", "us-west-1"),
- new Application(ApplicationId.fromFullString("t1.a1.i1"), List.of()));
+ new Application(ApplicationId.fromFullString("t1.a1.i1"), List.of()));
mock.putApplication(ZoneId.from("prod", "us-west-1"),
- new Application(ApplicationId.fromFullString("t2.a2.i2"), List.of()));
+ new Application(ApplicationId.fromFullString("t2.a2.i2"), List.of()));
mock.putApplication(ZoneId.from("prod", "us-east-3"),
- new Application(ApplicationId.fromFullString("t1.a1.i1"), List.of()));
+ new Application(ApplicationId.fromFullString("t1.a1.i1"), List.of()));
tester.assertResponse(authenticatedRequest("http://localhost:8080/controller/v1/stats", "", Request.Method.GET),
- new File("stats.json"));
+ new File("stats.json"));
}
@Test
- public void testUpgraderApi() {
+ void testUpgraderApi() {
// Get current configuration
tester.assertResponse(authenticatedRequest("http://localhost:8080/controller/v1/jobs/upgrader", "", Request.Method.GET),
- "{\"upgradesPerMinute\":0.125,\"confidenceOverrides\":[]}",
- 200);
+ "{\"upgradesPerMinute\":0.125,\"confidenceOverrides\":[]}",
+ 200);
// Set invalid configuration
tester.assertResponse(
@@ -123,11 +123,11 @@ public class ControllerApiTest extends ControllerContainerTest {
"{\"upgradesPerMinute\":42.0,\"confidenceOverrides\":[{\"6.43\":\"broken\"}]}",
200);
- assertFalse("Actions are logged to audit log", tester.controller().auditLogger().readLog().entries().isEmpty());
+ assertFalse(tester.controller().auditLogger().readLog().entries().isEmpty(), "Actions are logged to audit log");
}
@Test
- public void testAuditLogApi() {
+ void testAuditLogApi() {
ManualClock clock = new ManualClock(Instant.parse("2019-03-01T12:13:14.00Z"));
AuditLogger logger = new AuditLogger(tester.controller().curator(), clock);
@@ -153,13 +153,13 @@ public class ControllerApiTest extends ControllerContainerTest {
}
@Test
- public void testMeteringApi() {
+ void testMeteringApi() {
ApplicationId applicationId = ApplicationId.from("tenant", "app", "instance");
Instant timestamp = Instant.ofEpochMilli(123456789);
ZoneId zoneId = ZoneId.defaultId();
List<ResourceSnapshot> snapshots = List.of(
- new ResourceSnapshot(applicationId, 12,48,1200, NodeResources.Architecture.arm64, timestamp, zoneId),
- new ResourceSnapshot(applicationId, 24, 96,2400, NodeResources.Architecture.x86_64, timestamp, zoneId)
+ new ResourceSnapshot(applicationId, 12, 48, 1200, NodeResources.Architecture.arm64, timestamp, zoneId),
+ new ResourceSnapshot(applicationId, 24, 96, 2400, NodeResources.Architecture.x86_64, timestamp, zoneId)
);
tester.controller().serviceRegistry().resourceDatabase().writeResourceSnapshots(snapshots);
tester.assertResponse(
@@ -169,24 +169,24 @@ public class ControllerApiTest extends ControllerContainerTest {
}
@Test
- public void testApproveMembership() {
+ void testApproveMembership() {
ApplicationId applicationId = ApplicationId.from("tenant", "app", "instance");
DeploymentId deployment = new DeploymentId(applicationId, ZoneId.defaultId());
String requestBody = "{\n" +
- " \"applicationId\": \"" + deployment.applicationId().serializedForm() + "\",\n" +
- " \"zone\": \"" + deployment.zoneId().value() + "\"\n" +
- "}";
+ " \"applicationId\": \"" + deployment.applicationId().serializedForm() + "\",\n" +
+ " \"zone\": \"" + deployment.zoneId().value() + "\"\n" +
+ "}";
MockAccessControlService accessControlService = (MockAccessControlService) tester.serviceRegistry().accessControlService();
- tester.assertResponse(operatorRequest("http://localhost:8080/controller/v1/access/requests/"+hostedOperator.getName(), requestBody, Request.Method.POST),
- "{\"message\":\"Unable to approve membership request\"}", 400);
+ tester.assertResponse(operatorRequest("http://localhost:8080/controller/v1/access/requests/" + hostedOperator.getName(), requestBody, Request.Method.POST),
+ "{\"message\":\"Unable to approve membership request\"}", 400);
accessControlService.addPendingMember(hostedOperator);
- tester.assertResponse(operatorRequest("http://localhost:8080/controller/v1/access/requests/"+hostedOperator.getName(), requestBody, Request.Method.POST),
- "{\"message\":\"Unable to approve membership request\"}", 400);
+ tester.assertResponse(operatorRequest("http://localhost:8080/controller/v1/access/requests/" + hostedOperator.getName(), requestBody, Request.Method.POST),
+ "{\"message\":\"Unable to approve membership request\"}", 400);
tester.controller().supportAccess().allow(deployment, tester.controller().clock().instant().plus(Duration.ofHours(1)), "tenantx");
- tester.assertResponse(operatorRequest("http://localhost:8080/controller/v1/access/requests/"+hostedOperator.getName(), requestBody, Request.Method.POST),
- "{\"members\":[\"user.alice\"]}");
+ tester.assertResponse(operatorRequest("http://localhost:8080/controller/v1/access/requests/" + hostedOperator.getName(), requestBody, Request.Method.POST),
+ "{\"members\":[\"user.alice\"]}");
}
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/deployment/BadgeApiTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/deployment/BadgeApiTest.java
index d99239e8f23..5dd57b09af4 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/deployment/BadgeApiTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/deployment/BadgeApiTest.java
@@ -9,7 +9,7 @@ import com.yahoo.vespa.hosted.controller.deployment.DeploymentContext;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester;
import com.yahoo.vespa.hosted.controller.restapi.ContainerTester;
import com.yahoo.vespa.hosted.controller.restapi.ControllerContainerTest;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.file.Files;
@@ -24,30 +24,30 @@ public class BadgeApiTest extends ControllerContainerTest {
private static final String responseFiles = "src/test/java/com/yahoo/vespa/hosted/controller/restapi/deployment/responses/";
@Test
- public void testBadgeApi() throws IOException {
+ void testBadgeApi() throws IOException {
ContainerTester tester = new ContainerTester(container, responseFiles);
DeploymentTester deploymentTester = new DeploymentTester(new ControllerTester(tester));
deploymentTester.controllerTester().upgradeSystem(Version.fromString("6.1"));
var application = deploymentTester.newDeploymentContext("tenant", "application", "default");
ApplicationPackage applicationPackage = new ApplicationPackageBuilder().parallel("us-west-1", "aws-us-east-1a")
- .test("us-west-1")
- .region("ap-southeast-1")
- .test("ap-southeast-1")
- .region("eu-west-1")
- .test("eu-west-1")
- .build();
+ .test("us-west-1")
+ .region("ap-southeast-1")
+ .test("ap-southeast-1")
+ .region("eu-west-1")
+ .test("eu-west-1")
+ .build();
application.submit(applicationPackage).deploy();
application.submit(applicationPackage)
- .runJob(DeploymentContext.systemTest)
- .runJob(DeploymentContext.stagingTest)
- .runJob(DeploymentContext.productionUsWest1)
- .runJob(DeploymentContext.productionAwsUsEast1a)
- .runJob(DeploymentContext.testUsWest1)
- .runJob(DeploymentContext.productionApSoutheast1)
- .failDeployment(DeploymentContext.testApSoutheast1);
+ .runJob(DeploymentContext.systemTest)
+ .runJob(DeploymentContext.stagingTest)
+ .runJob(DeploymentContext.productionUsWest1)
+ .runJob(DeploymentContext.productionAwsUsEast1a)
+ .runJob(DeploymentContext.testUsWest1)
+ .runJob(DeploymentContext.productionApSoutheast1)
+ .failDeployment(DeploymentContext.testApSoutheast1);
application.submit(applicationPackage)
- .failTests(DeploymentContext.systemTest, true)
- .runJob(DeploymentContext.stagingTest);
+ .failTests(DeploymentContext.systemTest, true)
+ .runJob(DeploymentContext.stagingTest);
for (int i = 0; i < 31; i++)
if ((i & 1) == 0)
application.failDeployment(DeploymentContext.productionUsWest1);
@@ -58,27 +58,27 @@ public class BadgeApiTest extends ControllerContainerTest {
tester.controller().applications().deploymentTrigger().reTrigger(application.instanceId(), DeploymentContext.testEuWest1, "reason");
tester.assertResponse(authenticatedRequest("http://localhost:8080/badge/v1/tenant/application/default"),
- Files.readString(Paths.get(responseFiles + "overview.svg")), 200);
+ Files.readString(Paths.get(responseFiles + "overview.svg")), 200);
tester.assertResponse(authenticatedRequest("http://localhost:8080/badge/v1/tenant/application/default/production-us-west-1?historyLength=0"),
- Files.readString(Paths.get(responseFiles + "single-running.svg")), 200);
+ Files.readString(Paths.get(responseFiles + "single-running.svg")), 200);
tester.assertResponse(authenticatedRequest("http://localhost:8080/badge/v1/tenant/application/default/system-test"),
- Files.readString(Paths.get(responseFiles + "running-test.svg")), 200);
+ Files.readString(Paths.get(responseFiles + "running-test.svg")), 200);
tester.assertResponse(authenticatedRequest("http://localhost:8080/badge/v1/tenant/application/default/production-us-west-1?historyLength=32"),
- Files.readString(Paths.get(responseFiles + "history.svg")), 200);
+ Files.readString(Paths.get(responseFiles + "history.svg")), 200);
// New change not reflected before cache entry expires.
tester.serviceRegistry().clock().advance(Duration.ofSeconds(59));
application.runJob(DeploymentContext.productionUsWest1);
tester.assertResponse(authenticatedRequest("http://localhost:8080/badge/v1/tenant/application/default/production-us-west-1?historyLength=32"),
- Files.readString(Paths.get(responseFiles + "history.svg")), 200);
+ Files.readString(Paths.get(responseFiles + "history.svg")), 200);
// Cached entry refreshed after a minute.
tester.serviceRegistry().clock().advance(Duration.ofSeconds(1));
tester.assertResponse(authenticatedRequest("http://localhost:8080/badge/v1/tenant/application/default/production-us-west-1?historyLength=32"),
- Files.readString(Paths.get(responseFiles + "history2.svg")), 200);
+ Files.readString(Paths.get(responseFiles + "history2.svg")), 200);
tester.assertResponse(authenticatedRequest("http://localhost:8080/badge/v1/tenant/application/default/production-us-west-1?historyLength=0"),
- Files.readString(Paths.get(responseFiles + "single-done.svg")), 200);
+ Files.readString(Paths.get(responseFiles + "single-done.svg")), 200);
}
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/deployment/DeploymentApiTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/deployment/DeploymentApiTest.java
index d837b9e8264..7ee5f6db9b9 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/deployment/DeploymentApiTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/deployment/DeploymentApiTest.java
@@ -15,7 +15,7 @@ import com.yahoo.vespa.hosted.controller.restapi.ControllerContainerTest;
import com.yahoo.vespa.hosted.controller.versions.NodeVersion;
import com.yahoo.vespa.hosted.controller.versions.VersionStatus;
import com.yahoo.vespa.hosted.controller.versions.VespaVersion;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.util.ArrayList;
@@ -30,7 +30,7 @@ public class DeploymentApiTest extends ControllerContainerTest {
private final static String responseFiles = "src/test/java/com/yahoo/vespa/hosted/controller/restapi/deployment/responses/";
@Test
- public void testDeploymentApi() {
+ void testDeploymentApi() {
ContainerTester tester = new ContainerTester(container, responseFiles);
DeploymentTester deploymentTester = new DeploymentTester(new ControllerTester(tester));
Version version = Version.fromString("4.9");
@@ -43,8 +43,8 @@ public class DeploymentApiTest extends ControllerContainerTest {
.region("us-west-1")
.build();
ApplicationPackage emptyPackage = new ApplicationPackageBuilder().instances("default")
- .allow(ValidationId.deploymentRemoval)
- .build();
+ .allow(ValidationId.deploymentRemoval)
+ .build();
// Deploy application without any declared jobs on the oldest version.
var oldAppWithoutDeployment = deploymentTester.newDeploymentContext("tenant4", "application4", "default");
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/filter/AthenzRoleFilterTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/filter/AthenzRoleFilterTest.java
index 577aab0ade6..877ca4a99d2 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/filter/AthenzRoleFilterTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/filter/AthenzRoleFilterTest.java
@@ -15,13 +15,13 @@ import com.yahoo.vespa.hosted.controller.api.integration.athenz.AthenzClientFact
import com.yahoo.vespa.hosted.controller.api.integration.athenz.AthenzDbMock;
import com.yahoo.vespa.hosted.controller.api.role.Role;
import com.yahoo.vespa.hosted.controller.athenz.HostedAthenzIdentities;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.util.Set;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author jonmv
@@ -48,7 +48,7 @@ public class AthenzRoleFilterTest {
private AthenzRoleFilter filter;
- @Before
+ @BeforeEach
public void setup() {
ControllerTester tester = new ControllerTester();
filter = new AthenzRoleFilter(new AthenzClientFactoryMock(tester.athenzDb()),
@@ -67,70 +67,70 @@ public class AthenzRoleFilterTest {
}
@Test
- public void testTranslations() throws Exception {
+ void testTranslations() throws Exception {
// Hosted operators are always members of the hostedOperator role.
assertEquals(Set.of(Role.hostedOperator(), Role.systemFlagsDeployer(), Role.systemFlagsDryrunner(), Role.paymentProcessor(), Role.hostedAccountant(), Role.hostedSupporter()),
- filter.roles(HOSTED_OPERATOR, NO_CONTEXT_PATH));
+ filter.roles(HOSTED_OPERATOR, NO_CONTEXT_PATH));
assertEquals(Set.of(Role.hostedOperator(), Role.systemFlagsDeployer(), Role.systemFlagsDryrunner(), Role.paymentProcessor(), Role.hostedAccountant(), Role.hostedSupporter()),
- filter.roles(HOSTED_OPERATOR, TENANT_CONTEXT_PATH));
+ filter.roles(HOSTED_OPERATOR, TENANT_CONTEXT_PATH));
assertEquals(Set.of(Role.hostedOperator(), Role.systemFlagsDeployer(), Role.systemFlagsDryrunner(), Role.paymentProcessor(), Role.hostedAccountant(), Role.hostedSupporter()),
- filter.roles(HOSTED_OPERATOR, APPLICATION_CONTEXT_PATH));
+ filter.roles(HOSTED_OPERATOR, APPLICATION_CONTEXT_PATH));
// Tenant admins are members of the athenzTenantAdmin role within their tenant subtree.
assertEquals(Set.of(Role.everyone()),
- filter.roles(TENANT_PIPELINE, NO_CONTEXT_PATH));
+ filter.roles(TENANT_PIPELINE, NO_CONTEXT_PATH));
assertEquals(Set.of(Role.athenzTenantAdmin(TENANT)),
- filter.roles(TENANT_ADMIN, TENANT_CONTEXT_PATH));
+ filter.roles(TENANT_ADMIN, TENANT_CONTEXT_PATH));
assertEquals(Set.of(Role.athenzTenantAdmin(TENANT)),
- filter.roles(TENANT_ADMIN, APPLICATION_CONTEXT_PATH));
+ filter.roles(TENANT_ADMIN, APPLICATION_CONTEXT_PATH));
assertEquals(Set.of(Role.athenzTenantAdmin(TENANT)),
- filter.roles(TENANT_ADMIN, TENANT2_CONTEXT_PATH));
+ filter.roles(TENANT_ADMIN, TENANT2_CONTEXT_PATH));
assertEquals(Set.of(Role.athenzTenantAdmin(TENANT)),
- filter.roles(TENANT_ADMIN, APPLICATION2_CONTEXT_PATH));
+ filter.roles(TENANT_ADMIN, APPLICATION2_CONTEXT_PATH));
// Build services are members of the buildService role within their application subtree.
assertEquals(Set.of(Role.everyone()),
- filter.roles(TENANT_PIPELINE, NO_CONTEXT_PATH));
+ filter.roles(TENANT_PIPELINE, NO_CONTEXT_PATH));
assertEquals(Set.of(Role.everyone()),
- filter.roles(TENANT_PIPELINE, TENANT_CONTEXT_PATH));
+ filter.roles(TENANT_PIPELINE, TENANT_CONTEXT_PATH));
assertEquals(Set.of(Role.buildService(TENANT, APPLICATION)),
- filter.roles(TENANT_PIPELINE, APPLICATION_CONTEXT_PATH));
+ filter.roles(TENANT_PIPELINE, APPLICATION_CONTEXT_PATH));
assertEquals(Set.of(Role.everyone()),
- filter.roles(TENANT_PIPELINE, APPLICATION2_CONTEXT_PATH));
+ filter.roles(TENANT_PIPELINE, APPLICATION2_CONTEXT_PATH));
// Principals member of both tenantPipeline and tenantAdmin roles get correct roles
assertEquals(Set.of(Role.athenzTenantAdmin(TENANT)),
- filter.roles(TENANT_ADMIN_AND_PIPELINE, TENANT_CONTEXT_PATH));
+ filter.roles(TENANT_ADMIN_AND_PIPELINE, TENANT_CONTEXT_PATH));
assertEquals(Set.of(Role.athenzTenantAdmin(TENANT), Role.buildService(TENANT, APPLICATION)),
- filter.roles(TENANT_ADMIN_AND_PIPELINE, APPLICATION_CONTEXT_PATH));
+ filter.roles(TENANT_ADMIN_AND_PIPELINE, APPLICATION_CONTEXT_PATH));
// Users have nothing special under their instance
assertEquals(Set.of(Role.everyone()),
- filter.roles(USER, INSTANCE_CONTEXT_PATH));
+ filter.roles(USER, INSTANCE_CONTEXT_PATH));
// Unprivileged users are just members of the everyone role.
assertEquals(Set.of(Role.everyone()),
- filter.roles(USER, NO_CONTEXT_PATH));
+ filter.roles(USER, NO_CONTEXT_PATH));
assertEquals(Set.of(Role.everyone()),
- filter.roles(USER, TENANT_CONTEXT_PATH));
+ filter.roles(USER, TENANT_CONTEXT_PATH));
assertEquals(Set.of(Role.everyone()),
- filter.roles(USER, APPLICATION_CONTEXT_PATH));
+ filter.roles(USER, APPLICATION_CONTEXT_PATH));
assertEquals(Set.of(Role.everyone()),
- filter.roles(USER, INSTANCE2_CONTEXT_PATH));
+ filter.roles(USER, INSTANCE2_CONTEXT_PATH));
}
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/filter/ControllerAuthorizationFilterTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/filter/ControllerAuthorizationFilterTest.java
index be3a50c38b0..64dce08e735 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/filter/ControllerAuthorizationFilterTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/filter/ControllerAuthorizationFilterTest.java
@@ -11,7 +11,7 @@ import com.yahoo.vespa.hosted.controller.ControllerTester;
import com.yahoo.vespa.hosted.controller.api.role.Role;
import com.yahoo.vespa.hosted.controller.api.role.SecurityContext;
import com.yahoo.vespa.hosted.controller.restapi.ApplicationRequestToDiscFilterRequestWrapper;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.UncheckedIOException;
@@ -20,9 +20,9 @@ import java.util.Set;
import static com.yahoo.container.jdisc.RequestHandlerTestDriver.MockResponseHandler;
import static com.yahoo.jdisc.http.HttpResponse.Status.FORBIDDEN;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author bjorncs
@@ -33,7 +33,7 @@ public class ControllerAuthorizationFilterTest {
private static final ObjectMapper mapper = new ObjectMapper();
@Test
- public void operator() {
+ void operator() {
ControllerTester tester = new ControllerTester();
SecurityContext securityContext = new SecurityContext(() -> "operator", Set.of(Role.hostedOperator()));
ControllerAuthorizationFilter filter = createFilter(tester);
@@ -44,7 +44,7 @@ public class ControllerAuthorizationFilterTest {
}
@Test
- public void supporter() {
+ void supporter() {
ControllerTester tester = new ControllerTester();
SecurityContext securityContext = new SecurityContext(() -> "operator", Set.of(Role.hostedSupporter()));
ControllerAuthorizationFilter filter = createFilter(tester);
@@ -54,7 +54,7 @@ public class ControllerAuthorizationFilterTest {
}
@Test
- public void unprivileged() {
+ void unprivileged() {
ControllerTester tester = new ControllerTester();
SecurityContext securityContext = new SecurityContext(() -> "user", Set.of(Role.everyone()));
ControllerAuthorizationFilter filter = createFilter(tester);
@@ -65,7 +65,7 @@ public class ControllerAuthorizationFilterTest {
}
@Test
- public void unprivilegedInPublic() {
+ void unprivilegedInPublic() {
ControllerTester tester = new ControllerTester(SystemName.Public);
SecurityContext securityContext = new SecurityContext(() -> "user", Set.of(Role.everyone()));
@@ -76,7 +76,7 @@ public class ControllerAuthorizationFilterTest {
}
@Test
- public void hostedDeveloper() {
+ void hostedDeveloper() {
ControllerTester tester = new ControllerTester();
TenantName tenantName = TenantName.defaultName();
SecurityContext securityContext = new SecurityContext(() -> "user", Set.of(Role.hostedDeveloper(tenantName)));
@@ -88,14 +88,14 @@ public class ControllerAuthorizationFilterTest {
}
private static void assertIsAllowed(Optional<AuthorizationResponse> response) {
- assertFalse("Expected no response from filter, but got \"" +
- response.map(r -> r.message + "\" (" + r.statusCode + ")").orElse(""),
- response.isPresent());
+ assertFalse(response.isPresent(),
+ "Expected no response from filter, but got \"" +
+ response.map(r -> r.message + "\" (" + r.statusCode + ")").orElse(""));
}
private static void assertIsForbidden(Optional<AuthorizationResponse> response) {
- assertTrue("Expected a response from filter", response.isPresent());
- assertEquals("Invalid status code", FORBIDDEN, response.get().statusCode);
+ assertTrue(response.isPresent(), "Expected a response from filter");
+ assertEquals(FORBIDDEN, response.get().statusCode, "Invalid status code");
}
private static ControllerAuthorizationFilter createFilter(ControllerTester tester) {
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/filter/LastLoginUpdateFilterTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/filter/LastLoginUpdateFilterTest.java
index c7071cfb68c..b85c93a5d90 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/filter/LastLoginUpdateFilterTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/filter/LastLoginUpdateFilterTest.java
@@ -8,7 +8,7 @@ import com.yahoo.vespa.hosted.controller.api.role.Role;
import com.yahoo.vespa.hosted.controller.api.role.SecurityContext;
import com.yahoo.vespa.hosted.controller.restapi.ApplicationRequestToDiscFilterRequestWrapper;
import com.yahoo.vespa.hosted.controller.tenant.LastLoginInfo;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.Set;
@@ -16,7 +16,7 @@ import java.util.Set;
import static com.yahoo.vespa.hosted.controller.tenant.LastLoginInfo.UserLevel.administrator;
import static com.yahoo.vespa.hosted.controller.tenant.LastLoginInfo.UserLevel.developer;
import static com.yahoo.vespa.hosted.controller.tenant.LastLoginInfo.UserLevel.user;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class LastLoginUpdateFilterTest {
@@ -27,7 +27,7 @@ public class LastLoginUpdateFilterTest {
private final LastLoginUpdateFilter filter = new LastLoginUpdateFilter(tester.controller());
@Test
- public void updateLastLoginTimeTest() {
+ void updateLastLoginTimeTest() {
tester.createTenant(tenant1.value());
tester.createTenant(tenant2.value());
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/filter/SignatureFilterTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/filter/SignatureFilterTest.java
index 9024d7c8e7e..9ff79213983 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/filter/SignatureFilterTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/filter/SignatureFilterTest.java
@@ -20,8 +20,8 @@ import com.yahoo.vespa.hosted.controller.tenant.ArchiveAccess;
import com.yahoo.vespa.hosted.controller.tenant.CloudTenant;
import com.yahoo.vespa.hosted.controller.tenant.LastLoginInfo;
import com.yahoo.vespa.hosted.controller.tenant.TenantInfo;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
@@ -34,8 +34,8 @@ import java.util.List;
import java.util.Optional;
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 SignatureFilterTest {
@@ -63,7 +63,7 @@ public class SignatureFilterTest {
private SignatureFilter filter;
private RequestSigner signer;
- @Before
+ @BeforeEach
public void setup() {
tester = new ControllerTester();
applications = tester.controller().applications();
@@ -82,12 +82,12 @@ public class SignatureFilterTest {
}
@Test
- public void testFilter() {
+ void testFilter() {
// Unsigned request gets no role.
HttpRequest.Builder request = HttpRequest.newBuilder(URI.create("https://host:123/path/./..//..%2F?query=empty&%3F=%26"));
byte[] emptyBody = new byte[0];
verifySecurityContext(requestOf(request.copy().method("GET", HttpRequest.BodyPublishers.ofByteArray(emptyBody)).build(), emptyBody),
- null);
+ null);
// Signed request gets no role when no key is stored for the application.
verifySecurityContext(requestOf(signer.signed(request.copy(), Method.GET, InputStream::nullInputStream), emptyBody),
@@ -97,42 +97,42 @@ public class SignatureFilterTest {
applications.lockApplicationOrThrow(appId, application -> applications.store(application.withDeployKey(otherPublicKey)));
// Signed request gets no role when no key is stored for the application.
verifySecurityContext(requestOf(signer.signed(request.copy(), Method.GET, InputStream::nullInputStream), emptyBody),
- null);
+ null);
// Signed request gets a headless role when a matching key is stored for the application.
applications.lockApplicationOrThrow(appId, application -> applications.store(application.withDeployKey(publicKey)));
verifySecurityContext(requestOf(signer.signed(request.copy(), Method.GET, InputStream::nullInputStream), emptyBody),
- new SecurityContext(new SimplePrincipal("headless@my-tenant.my-app"),
- Set.of(Role.reader(id.tenant()),
- Role.headless(id.tenant(), id.application())),
- tester.clock().instant()));
+ new SecurityContext(new SimplePrincipal("headless@my-tenant.my-app"),
+ Set.of(Role.reader(id.tenant()),
+ Role.headless(id.tenant(), id.application())),
+ tester.clock().instant()));
// Signed POST request with X-Key header gets a headless role.
byte[] hiBytes = new byte[]{0x48, 0x69};
verifySecurityContext(requestOf(signer.signed(request.copy(), Method.POST, () -> new ByteArrayInputStream(hiBytes)), hiBytes),
- new SecurityContext(new SimplePrincipal("headless@my-tenant.my-app"),
- Set.of(Role.reader(id.tenant()),
- Role.headless(id.tenant(), id.application())),
- tester.clock().instant()));
+ new SecurityContext(new SimplePrincipal("headless@my-tenant.my-app"),
+ Set.of(Role.reader(id.tenant()),
+ Role.headless(id.tenant(), id.application())),
+ tester.clock().instant()));
// Signed request gets a developer role when a matching developer key is stored for the tenant.
tester.curator().writeTenant(new CloudTenant(appId.tenant(),
- Instant.EPOCH,
- LastLoginInfo.EMPTY,
- Optional.empty(),
- ImmutableBiMap.of(publicKey, () -> "user"),
- TenantInfo.empty(),
- List.of(),
- new ArchiveAccess()));
+ Instant.EPOCH,
+ LastLoginInfo.EMPTY,
+ Optional.empty(),
+ ImmutableBiMap.of(publicKey, () -> "user"),
+ TenantInfo.empty(),
+ List.of(),
+ new ArchiveAccess()));
verifySecurityContext(requestOf(signer.signed(request.copy(), Method.POST, () -> new ByteArrayInputStream(hiBytes)), hiBytes),
- new SecurityContext(new SimplePrincipal("user"),
- Set.of(Role.reader(id.tenant()),
- Role.developer(id.tenant())),
- tester.clock().instant()));
+ new SecurityContext(new SimplePrincipal("user"),
+ Set.of(Role.reader(id.tenant()),
+ Role.developer(id.tenant())),
+ tester.clock().instant()));
// Unsigned requests still get no roles.
verifySecurityContext(requestOf(request.copy().method("GET", HttpRequest.BodyPublishers.ofByteArray(emptyBody)).build(), emptyBody),
- null);
+ null);
}
private void verifySecurityContext(DiscFilterRequest request, SecurityContext securityContext) {
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/flags/AuditedFlagsApiTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/flags/AuditedFlagsApiTest.java
index 6d8826f6e48..ee89f506f17 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/flags/AuditedFlagsApiTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/flags/AuditedFlagsApiTest.java
@@ -7,10 +7,10 @@ import com.yahoo.vespa.athenz.api.AthenzUser;
import com.yahoo.vespa.hosted.controller.auditlog.AuditLog;
import com.yahoo.vespa.hosted.controller.restapi.ContainerTester;
import com.yahoo.vespa.hosted.controller.restapi.ControllerContainerTest;
-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 mpolden
@@ -22,24 +22,24 @@ public class AuditedFlagsApiTest extends ControllerContainerTest {
private ContainerTester tester;
- @Before
+ @BeforeEach
public void before() {
addUserToHostedOperatorRole(operator);
tester = new ContainerTester(container, responses);
}
@Test
- public void test_audit_logging() {
+ void test_audit_logging() {
var body = "{\n" +
- " \"id\": \"id1\",\n" +
- " \"rules\": [\n" +
- " {\n" +
- " \"value\": true\n" +
- " }\n" +
- " ]\n" +
- "}";
+ " \"id\": \"id1\",\n" +
+ " \"rules\": [\n" +
+ " {\n" +
+ " \"value\": true\n" +
+ " }\n" +
+ " ]\n" +
+ "}";
assertResponse(new Request("http://localhost:8080/flags/v1/data/id1?force=true", body, Request.Method.PUT),
- "", 200);
+ "", 200);
var log = tester.controller().auditLogger().readLog();
assertEquals(1, log.entries().size());
var entry = log.entries().get(0);
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/horizon/HorizonApiTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/horizon/HorizonApiTest.java
index 96b08006790..fabae508057 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/horizon/HorizonApiTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/horizon/HorizonApiTest.java
@@ -8,7 +8,7 @@ import com.yahoo.vespa.flags.InMemoryFlagSource;
import com.yahoo.vespa.hosted.controller.api.role.Role;
import com.yahoo.vespa.hosted.controller.restapi.ContainerTester;
import com.yahoo.vespa.hosted.controller.restapi.ControllerContainerCloudTest;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Set;
@@ -18,7 +18,7 @@ import java.util.Set;
public class HorizonApiTest extends ControllerContainerCloudTest {
@Test
- public void only_operators_and_flag_enabled_tenants_allowed() {
+ void only_operators_and_flag_enabled_tenants_allowed() {
ContainerTester tester = new ContainerTester(container, "");
TenantName tenantName = TenantName.defaultName();
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/horizon/TsdbQueryRewriterTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/horizon/TsdbQueryRewriterTest.java
index 62ec8f4222c..d0d169720d0 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/horizon/TsdbQueryRewriterTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/horizon/TsdbQueryRewriterTest.java
@@ -5,7 +5,7 @@ import com.yahoo.config.provision.SystemName;
import com.yahoo.config.provision.TenantName;
import com.yahoo.slime.JsonFormat;
import com.yahoo.slime.SlimeUtils;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@@ -16,7 +16,7 @@ import java.util.Set;
import static com.yahoo.slime.SlimeUtils.jsonToSlimeOrThrow;
import static com.yahoo.slime.SlimeUtils.toJsonBytes;
import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author valerijf
@@ -24,7 +24,7 @@ import static org.junit.Assert.assertEquals;
public class TsdbQueryRewriterTest {
@Test
- public void rewrites_query() throws IOException {
+ void rewrites_query() throws IOException {
assertRewrite("filters-complex.json", "filters-complex.expected.json", Set.of(TenantName.from("tenant2")), false);
assertRewrite("filter-in-execution-graph.json",
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/os/OsApiTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/os/OsApiTest.java
index 15e7a804143..6ddc58feaea 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/os/OsApiTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/os/OsApiTest.java
@@ -21,15 +21,15 @@ import com.yahoo.vespa.hosted.controller.restapi.ContainerTester;
import com.yahoo.vespa.hosted.controller.restapi.ControllerContainerTest;
import com.yahoo.vespa.hosted.controller.versions.OsVersionStatus;
import org.intellij.lang.annotations.Language;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.time.Duration;
import java.time.Instant;
import java.util.List;
-import static org.junit.Assert.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertFalse;
/**
* @author mpolden
@@ -52,7 +52,7 @@ public class OsApiTest extends ControllerContainerTest {
return SystemName.cd;
}
- @Before
+ @BeforeEach
public void before() {
tester = new ContainerTester(container, responses);
tester.serviceRegistry().clock().setInstant(Instant.ofEpochMilli(1234));
@@ -69,7 +69,7 @@ public class OsApiTest extends ControllerContainerTest {
}
@Test
- public void test_api() {
+ void test_api() {
// No versions available yet
assertResponse(new Request("http://localhost:8080/os/v1/"), "{\"versions\":[]}", 200);
@@ -77,9 +77,9 @@ public class OsApiTest extends ControllerContainerTest {
upgradeAndUpdateStatus();
// Upgrade OS to a different version in each cloud
assertResponse(new Request("http://localhost:8080/os/v1/", "{\"version\": \"7.5.2\", \"cloud\": \"cloud1\", \"upgradeBudget\": \"PT0S\"}", Request.Method.PATCH),
- "{\"message\":\"Set target OS version for cloud 'cloud1' to 7.5.2 with upgrade budget PT0S\"}", 200);
+ "{\"message\":\"Set target OS version for cloud 'cloud1' to 7.5.2 with upgrade budget PT0S\"}", 200);
assertResponse(new Request("http://localhost:8080/os/v1/", "{\"version\": \"8.2.1\", \"cloud\": \"cloud2\", \"upgradeBudget\": \"PT24H\"}", Request.Method.PATCH),
- "{\"message\":\"Set target OS version for cloud 'cloud2' to 8.2.1 with upgrade budget PT24H\"}", 200);
+ "{\"message\":\"Set target OS version for cloud 'cloud2' to 8.2.1 with upgrade budget PT24H\"}", 200);
// Status is updated after some zones are upgraded
upgradeAndUpdateStatus();
@@ -93,49 +93,49 @@ public class OsApiTest extends ControllerContainerTest {
// Downgrade with force is permitted
assertResponse(new Request("http://localhost:8080/os/v1/", "{\"version\": \"7.5.1\", \"cloud\": \"cloud1\", \"force\": true, \"upgradeBudget\": \"PT0S\"}", Request.Method.PATCH),
- "{\"message\":\"Set target OS version for cloud 'cloud1' to 7.5.1 with upgrade budget PT0S\"}", 200);
+ "{\"message\":\"Set target OS version for cloud 'cloud1' to 7.5.1 with upgrade budget PT0S\"}", 200);
// Clear target for a given cloud
assertResponse(new Request("http://localhost:8080/os/v1/", "{\"version\": null, \"cloud\": \"cloud2\"}", Request.Method.PATCH),
- "{\"message\":\"Cleared target OS version for cloud 'cloud2'\"}", 200);
+ "{\"message\":\"Cleared target OS version for cloud 'cloud2'\"}", 200);
// Error: Missing fields
assertResponse(new Request("http://localhost:8080/os/v1/", "{\"version\": \"7.6\"}", Request.Method.PATCH),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Field 'cloud' is required\"}", 400);
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Field 'cloud' is required\"}", 400);
assertResponse(new Request("http://localhost:8080/os/v1/", "{\"cloud\": \"cloud1\"}", Request.Method.PATCH),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Field 'version' is required\"}", 400);
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Field 'version' is required\"}", 400);
// Error: Invalid versions
assertResponse(new Request("http://localhost:8080/os/v1/", "{\"version\": \"0.0.0\", \"cloud\": \"cloud1\", \"upgradeBudget\": \"PT0S\"}", Request.Method.PATCH),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Invalid version '0.0.0'\"}", 400);
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Invalid version '0.0.0'\"}", 400);
assertResponse(new Request("http://localhost:8080/os/v1/", "{\"version\": \"foo\", \"cloud\": \"cloud1\", \"upgradeBudget\": \"PT0S\"}", Request.Method.PATCH),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Invalid version 'foo': For input string: \\\"foo\\\"\"}", 400);
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Invalid version 'foo': For input string: \\\"foo\\\"\"}", 400);
// Error: Invalid cloud
assertResponse(new Request("http://localhost:8080/os/v1/", "{\"version\": \"7.6\", \"cloud\": \"foo\", \"upgradeBudget\": \"PT0S\"}", Request.Method.PATCH),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cloud 'foo' does not exist in this system\"}", 400);
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cloud 'foo' does not exist in this system\"}", 400);
// Error: Downgrade OS
assertResponse(new Request("http://localhost:8080/os/v1/", "{\"version\": \"7.4.1\", \"cloud\": \"cloud1\", \"upgradeBudget\": \"PT0S\"}", Request.Method.PATCH),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot downgrade cloud 'cloud1' to version 7.4.1\"}", 400);
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Cannot downgrade cloud 'cloud1' to version 7.4.1\"}", 400);
// Request firmware checks in all zones.
assertResponse(new Request("http://localhost:8080/os/v1/firmware/", "", Request.Method.POST),
- "{\"message\":\"Requested firmware checks in prod.us-east-3, prod.us-west-1, prod.eu-west-1.\"}", 200);
+ "{\"message\":\"Requested firmware checks in prod.us-east-3, prod.us-west-1, prod.eu-west-1.\"}", 200);
// Cancel firmware checks in all prod zones.
assertResponse(new Request("http://localhost:8080/os/v1/firmware/prod/", "", Request.Method.DELETE),
- "{\"message\":\"Cancelled firmware checks in prod.us-east-3, prod.us-west-1, prod.eu-west-1.\"}", 200);
+ "{\"message\":\"Cancelled firmware checks in prod.us-east-3, prod.us-west-1, prod.eu-west-1.\"}", 200);
// Request firmware checks in prod.us-east-3.
assertResponse(new Request("http://localhost:8080/os/v1/firmware/prod/us-east-3", "", Request.Method.POST),
- "{\"message\":\"Requested firmware checks in prod.us-east-3.\"}", 200);
+ "{\"message\":\"Requested firmware checks in prod.us-east-3.\"}", 200);
// Error: Cancel firmware checks in an empty set of zones.
assertResponse(new Request("http://localhost:8080/os/v1/firmware/dev/", "", Request.Method.DELETE),
- "{\"error-code\":\"NOT_FOUND\",\"message\":\"No zones at path '/os/v1/firmware/dev/'\"}", 404);
+ "{\"error-code\":\"NOT_FOUND\",\"message\":\"No zones at path '/os/v1/firmware/dev/'\"}", 404);
- assertFalse("Actions are logged to audit log", tester.controller().auditLogger().readLog().entries().isEmpty());
+ assertFalse(tester.controller().auditLogger().readLog().entries().isEmpty(), "Actions are logged to audit log");
}
private void upgradeAndUpdateStatus() {
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/routing/RoutingApiTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/routing/RoutingApiTest.java
index ea7ec7c1589..cb402d700e2 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/routing/RoutingApiTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/routing/RoutingApiTest.java
@@ -14,13 +14,13 @@ import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester;
import com.yahoo.vespa.hosted.controller.integration.ZoneApiMock;
import com.yahoo.vespa.hosted.controller.restapi.ContainerTester;
import com.yahoo.vespa.hosted.controller.restapi.ControllerContainerTest;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.util.List;
-import static org.junit.Assert.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
/**
* @author mpolden
@@ -32,7 +32,7 @@ public class RoutingApiTest extends ControllerContainerTest {
private ContainerTester tester;
private DeploymentTester deploymentTester;
- @Before
+ @BeforeEach
public void before() {
tester = new ContainerTester(container, responseFiles);
deploymentTester = new DeploymentTester(new ControllerTester(tester));
@@ -40,7 +40,7 @@ public class RoutingApiTest extends ControllerContainerTest {
}
@Test
- public void discovery() {
+ void discovery() {
// Deploy
var context = deploymentTester.newDeploymentContext("t1", "a1", "default");
var westZone = ZoneId.from("prod", "us-west-1");
@@ -54,34 +54,34 @@ public class RoutingApiTest extends ControllerContainerTest {
// GET root
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/", "",
- Request.Method.GET),
- new File("discovery/root.json"));
+ Request.Method.GET),
+ new File("discovery/root.json"));
// GET tenant
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/tenant/t1", "",
- Request.Method.GET),
- new File("discovery/tenant.json"));
+ Request.Method.GET),
+ new File("discovery/tenant.json"));
// GET application
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/tenant/t1/application/a1/",
- "",
- Request.Method.GET),
- new File("discovery/application.json"));
+ "",
+ Request.Method.GET),
+ new File("discovery/application.json"));
// GET instance
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/tenant/t1/application/a1/instance/default/",
- "",
- Request.Method.GET),
- new File("discovery/instance.json"));
+ "",
+ Request.Method.GET),
+ new File("discovery/instance.json"));
// GET environment
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/environment/", "",
- Request.Method.GET),
- new File("discovery/environment.json"));
+ Request.Method.GET),
+ new File("discovery/environment.json"));
}
@Test
- public void recursion() {
+ void recursion() {
var context1 = deploymentTester.newDeploymentContext("t1", "a1", "default");
var westZone = ZoneId.from("prod", "us-west-1");
var eastZone = ZoneId.from("prod", "us-east-3");
@@ -102,33 +102,33 @@ public class RoutingApiTest extends ControllerContainerTest {
// GET tenant recursively
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/tenant/t1?recursive=true", "",
- Request.Method.GET),
- new File("recursion/tenant.json"));
+ Request.Method.GET),
+ new File("recursion/tenant.json"));
// GET application recursively
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/tenant/t1/application/a1?recursive=true", "",
- Request.Method.GET),
- new File("recursion/application.json"));
+ Request.Method.GET),
+ new File("recursion/application.json"));
// GET instance recursively
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/tenant/t1/application/a1/instance/default?recursive=true", "",
- Request.Method.GET),
- new File("recursion/application.json"));
+ Request.Method.GET),
+ new File("recursion/application.json"));
// GET environment recursively
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/environment?recursive=true", "",
- Request.Method.GET),
- new File("recursion/environment.json"));
+ Request.Method.GET),
+ new File("recursion/environment.json"));
}
@Test
- public void exclusive_routing() {
+ void exclusive_routing() {
var context = deploymentTester.newDeploymentContext();
// Zones support direct routing
var westZone = ZoneId.from("prod", "us-west-1");
var eastZone = ZoneId.from("prod", "us-east-3");
deploymentTester.controllerTester().zoneRegistry().exclusiveRoutingIn(ZoneApiMock.from(westZone),
- ZoneApiMock.from(eastZone));
+ ZoneApiMock.from(eastZone));
// Deploy application
var applicationPackage = new ApplicationPackageBuilder()
.athenzIdentity(AthenzDomain.from("domain"), AthenzService.from("service"))
@@ -140,45 +140,45 @@ public class RoutingApiTest extends ControllerContainerTest {
// GET initial deployment status
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/tenant/tenant/application/application/instance/default/environment/prod/region/us-west-1",
- "", Request.Method.GET),
- new File("policy/deployment-status-initial.json"));
+ "", Request.Method.GET),
+ new File("policy/deployment-status-initial.json"));
// POST sets deployment out
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/inactive/tenant/tenant/application/application/instance/default/environment/prod/region/us-west-1",
- "", Request.Method.POST),
- "{\"message\":\"Set global routing status for tenant.application in prod.us-west-1 to OUT\"}");
+ "", Request.Method.POST),
+ "{\"message\":\"Set global routing status for tenant.application in prod.us-west-1 to OUT\"}");
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/tenant/tenant/application/application/instance/default/environment/prod/region/us-west-1",
- "", Request.Method.GET),
- new File("policy/deployment-status-out.json"));
+ "", Request.Method.GET),
+ new File("policy/deployment-status-out.json"));
// DELETE sets deployment in
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/inactive/tenant/tenant/application/application/instance/default/environment/prod/region/us-west-1",
- "", Request.Method.DELETE),
- "{\"message\":\"Set global routing status for tenant.application in prod.us-west-1 to IN\"}");
+ "", Request.Method.DELETE),
+ "{\"message\":\"Set global routing status for tenant.application in prod.us-west-1 to IN\"}");
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/tenant/tenant/application/application/instance/default/environment/prod/region/us-west-1",
- "", Request.Method.GET),
- new File("policy/deployment-status-in.json"));
+ "", Request.Method.GET),
+ new File("policy/deployment-status-in.json"));
// GET initial zone status
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/environment/prod/region/us-west-1",
- "", Request.Method.GET),
- new File("policy/zone-status-initial.json"));
+ "", Request.Method.GET),
+ new File("policy/zone-status-initial.json"));
// POST sets zone out
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/inactive/environment/prod/region/us-west-1",
- "", Request.Method.POST),
- "{\"message\":\"Set global routing status for deployments in prod.us-west-1 to OUT\"}");
+ "", Request.Method.POST),
+ "{\"message\":\"Set global routing status for deployments in prod.us-west-1 to OUT\"}");
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/environment/prod/region/us-west-1",
- "", Request.Method.GET),
- new File("policy/zone-status-out.json"));
+ "", Request.Method.GET),
+ new File("policy/zone-status-out.json"));
// DELETE sets zone in
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/inactive/environment/prod/region/us-west-1",
- "", Request.Method.DELETE),
- "{\"message\":\"Set global routing status for deployments in prod.us-west-1 to IN\"}");
+ "", Request.Method.DELETE),
+ "{\"message\":\"Set global routing status for deployments in prod.us-west-1 to IN\"}");
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/environment/prod/region/us-west-1",
- "", Request.Method.GET),
- new File("policy/zone-status-in.json"));
+ "", Request.Method.GET),
+ new File("policy/zone-status-in.json"));
// Endpoint is removed
applicationPackage = new ApplicationPackageBuilder()
@@ -191,12 +191,12 @@ public class RoutingApiTest extends ControllerContainerTest {
// GET deployment status. Now empty as no routing policies have global endpoints
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/tenant/tenant/application/application/instance/default/environment/prod/region/us-west-1",
- "", Request.Method.GET),
- "{\"deployments\":[]}");
+ "", Request.Method.GET),
+ "{\"deployments\":[]}");
}
@Test
- public void shared_routing() {
+ void shared_routing() {
// Deploy application
var context = deploymentTester.newDeploymentContext();
var westZone = ZoneId.from("prod", "us-west-1");
@@ -208,61 +208,61 @@ public class RoutingApiTest extends ControllerContainerTest {
.build();
context.submit(applicationPackage).deploy();
- assertNotEquals("Rotation is assigned", List.of(), context.instance().rotations());
+ assertNotEquals(List.of(), context.instance().rotations(), "Rotation is assigned");
// GET initial deployment status
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/tenant/tenant/application/application/instance/default/environment/prod/region/us-west-1",
- "", Request.Method.GET),
- new File("rotation/deployment-status-initial.json"));
+ "", Request.Method.GET),
+ new File("rotation/deployment-status-initial.json"));
// POST sets deployment out
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/inactive/tenant/tenant/application/application/instance/default/environment/prod/region/us-west-1",
- "", Request.Method.POST),
- "{\"message\":\"Set global routing status for tenant.application in prod.us-west-1 to OUT\"}");
+ "", Request.Method.POST),
+ "{\"message\":\"Set global routing status for tenant.application in prod.us-west-1 to OUT\"}");
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/tenant/tenant/application/application/instance/default/environment/prod/region/us-west-1",
- "", Request.Method.GET),
- new File("rotation/deployment-status-out.json"));
+ "", Request.Method.GET),
+ new File("rotation/deployment-status-out.json"));
// DELETE sets deployment in
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/inactive/tenant/tenant/application/application/instance/default/environment/prod/region/us-west-1",
- "", Request.Method.DELETE),
- "{\"message\":\"Set global routing status for tenant.application in prod.us-west-1 to IN\"}");
+ "", Request.Method.DELETE),
+ "{\"message\":\"Set global routing status for tenant.application in prod.us-west-1 to IN\"}");
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/tenant/tenant/application/application/instance/default/environment/prod/region/us-west-1",
- "", Request.Method.GET),
- new File("rotation/deployment-status-in.json"));
+ "", Request.Method.GET),
+ new File("rotation/deployment-status-in.json"));
// GET initial zone status
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/environment/prod/region/us-west-1",
- "", Request.Method.GET),
- new File("rotation/zone-status-initial.json"));
+ "", Request.Method.GET),
+ new File("rotation/zone-status-initial.json"));
// POST sets zone out
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/inactive/environment/prod/region/us-west-1",
- "", Request.Method.POST),
- "{\"message\":\"Set global routing status for deployments in prod.us-west-1 to OUT\"}");
+ "", Request.Method.POST),
+ "{\"message\":\"Set global routing status for deployments in prod.us-west-1 to OUT\"}");
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/environment/prod/region/us-west-1",
- "", Request.Method.GET),
- new File("rotation/zone-status-out.json"));
+ "", Request.Method.GET),
+ new File("rotation/zone-status-out.json"));
// DELETE sets zone in
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/inactive/environment/prod/region/us-west-1",
- "", Request.Method.DELETE),
- "{\"message\":\"Set global routing status for deployments in prod.us-west-1 to IN\"}");
+ "", Request.Method.DELETE),
+ "{\"message\":\"Set global routing status for deployments in prod.us-west-1 to IN\"}");
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/environment/prod/region/us-west-1",
- "", Request.Method.GET),
- new File("rotation/zone-status-in.json"));
+ "", Request.Method.GET),
+ new File("rotation/zone-status-in.json"));
}
@Test
- public void mixed_routing_multiple_zones() {
+ void mixed_routing_multiple_zones() {
var westZone = ZoneId.from("prod", "us-west-1");
var eastZone = ZoneId.from("prod", "us-east-3");
// One shared and one exclusive zone
deploymentTester.controllerTester().zoneRegistry().setRoutingMethod(ZoneApiMock.from(westZone),
- RoutingMethod.sharedLayer4);
+ RoutingMethod.sharedLayer4);
deploymentTester.controllerTester().zoneRegistry().setRoutingMethod(ZoneApiMock.from(eastZone),
- RoutingMethod.exclusive);
+ RoutingMethod.exclusive);
// Deploy application
var context = deploymentTester.newDeploymentContext();
@@ -277,23 +277,23 @@ public class RoutingApiTest extends ControllerContainerTest {
// GET status for zone using sharedLayer4 routing
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/tenant/tenant/application/application/instance/default/environment/prod/region/us-west-1",
- "", Request.Method.GET),
- new File("rotation/deployment-status-initial.json"));
+ "", Request.Method.GET),
+ new File("rotation/deployment-status-initial.json"));
// GET status for zone using exclusive routing
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/tenant/tenant/application/application/instance/default/environment/prod/region/us-east-3",
- "", Request.Method.GET),
- "{\"deployments\":[{\"routingMethod\":\"exclusive\",\"instance\":\"tenant:application:default\"," +
- "\"environment\":\"prod\",\"region\":\"us-east-3\",\"status\":\"in\",\"agent\":\"system\",\"changedAt\":0}]}");
+ "", Request.Method.GET),
+ "{\"deployments\":[{\"routingMethod\":\"exclusive\",\"instance\":\"tenant:application:default\"," +
+ "\"environment\":\"prod\",\"region\":\"us-east-3\",\"status\":\"in\",\"agent\":\"system\",\"changedAt\":0}]}");
}
@Test
- public void invalid_requests() {
+ void invalid_requests() {
// GET non-existent application
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/tenant/t1/application/a1/instance/default/environment/prod/region/us-west-1",
- "", Request.Method.GET),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"t1.a1 not found\"}",
- 400);
+ "", Request.Method.GET),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"t1.a1 not found\"}",
+ 400);
// GET, DELETE non-existent deployment
var context = deploymentTester.newDeploymentContext();
@@ -303,23 +303,23 @@ public class RoutingApiTest extends ControllerContainerTest {
.build();
context.submit(applicationPackage).deploy();
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/tenant/tenant/application/application/instance/default/environment/prod/region/us-west-1",
- "", Request.Method.GET),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"No such deployment: tenant.application in prod.us-west-1\"}",
- 400);
+ "", Request.Method.GET),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"No such deployment: tenant.application in prod.us-west-1\"}",
+ 400);
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/inactive/tenant/tenant/application/application/instance/default/environment/prod/region/us-west-1",
- "", Request.Method.DELETE),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"No such deployment: tenant.application in prod.us-west-1\"}",
- 400);
+ "", Request.Method.DELETE),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"No such deployment: tenant.application in prod.us-west-1\"}",
+ 400);
// GET non-existent zone
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/environment/prod/region/us-north-1",
- "", Request.Method.GET),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"No such zone: prod.us-north-1\"}",
- 400);
+ "", Request.Method.GET),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"No such zone: prod.us-north-1\"}",
+ 400);
}
@Test
- public void endpoints_list() {
+ void endpoints_list() {
var context = deploymentTester.newDeploymentContext("t1", "a1", "default");
var westZone = ZoneId.from("prod", "us-west-1");
var eastZone = ZoneId.from("prod", "us-east-3");
@@ -331,7 +331,7 @@ public class RoutingApiTest extends ControllerContainerTest {
context.submit(applicationPackage).deploy();
tester.assertResponse(operatorRequest("http://localhost:8080/routing/v1/status/tenant/t1/application/a1/instance/default/endpoint", "", Request.Method.GET),
- new File("endpoint/endpoints.json"));
+ new File("endpoint/endpoints.json"));
}
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/systemflags/SystemFlagsDeployResultTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/systemflags/SystemFlagsDeployResultTest.java
index c157cb3516f..36679e0dd91 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/systemflags/SystemFlagsDeployResultTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/systemflags/SystemFlagsDeployResultTest.java
@@ -7,7 +7,7 @@ import com.yahoo.vespa.hosted.controller.api.systemflags.v1.FlagsTarget;
import com.yahoo.vespa.hosted.controller.api.systemflags.v1.wire.WireSystemFlagsDeployResult;
import com.yahoo.vespa.hosted.controller.integration.ZoneApiMock;
import com.yahoo.vespa.hosted.controller.integration.ZoneRegistryMock;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
@@ -21,7 +21,7 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
public class SystemFlagsDeployResultTest {
@Test
- public void changes_and_errors_are_present_in_wire_format() {
+ void changes_and_errors_are_present_in_wire_format() {
FlagsTarget controllerTarget = FlagsTarget.forController(SystemName.cd);
FlagId flagOne = new FlagId("flagone");
FlagId flagTwo = new FlagId("flagtwo");
@@ -40,7 +40,7 @@ public class SystemFlagsDeployResultTest {
}
@Test
- public void identical_errors_and_changes_from_multiple_targets_are_merged() {
+ void identical_errors_and_changes_from_multiple_targets_are_merged() {
ZoneApiMock prodUsWest1Zone = ZoneApiMock.fromId("prod.us-west-1");
ZoneRegistryMock registry = new ZoneRegistryMock(SystemName.cd).setZones(prodUsWest1Zone);
FlagsTarget prodUsWest1Target = FlagsTarget.forConfigServer(registry, prodUsWest1Zone.getId());
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/systemflags/SystemFlagsDeployerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/systemflags/SystemFlagsDeployerTest.java
index d92b0be0eb9..50354639f6f 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/systemflags/SystemFlagsDeployerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/systemflags/SystemFlagsDeployerTest.java
@@ -8,7 +8,7 @@ import com.yahoo.vespa.hosted.controller.api.systemflags.v1.FlagsTarget;
import com.yahoo.vespa.hosted.controller.api.systemflags.v1.SystemFlagsDataArchive;
import com.yahoo.vespa.hosted.controller.integration.ZoneApiMock;
import com.yahoo.vespa.hosted.controller.integration.ZoneRegistryMock;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.UncheckedIOException;
@@ -43,7 +43,7 @@ public class SystemFlagsDeployerTest {
private final FlagsTarget prodUsEast3Target = FlagsTarget.forConfigServer(registry, prodUsEast3Zone.getId());
@Test
- public void deploys_flag_data_to_targets() throws IOException {
+ void deploys_flag_data_to_targets() throws IOException {
FlagsClient flagsClient = mock(FlagsClient.class);
when(flagsClient.listFlagData(controllerTarget)).thenReturn(List.of());
when(flagsClient.listFlagData(prodUsWest1Target)).thenReturn(List.of(flagData("existing-prod.us-west-1.json")));
@@ -74,7 +74,7 @@ public class SystemFlagsDeployerTest {
}
@Test
- public void dryrun_should_not_change_flags() throws IOException {
+ void dryrun_should_not_change_flags() throws IOException {
FlagsClient flagsClient = mock(FlagsClient.class);
when(flagsClient.listFlagData(controllerTarget)).thenReturn(List.of());
when(flagsClient.listDefinedFlags(controllerTarget)).thenReturn(List.of(new FlagId("my-flag")));
@@ -97,7 +97,7 @@ public class SystemFlagsDeployerTest {
}
@Test
- public void creates_error_entries_in_result_if_flag_data_operations_fail() throws IOException {
+ void creates_error_entries_in_result_if_flag_data_operations_fail() throws IOException {
FlagsClient flagsClient = mock(FlagsClient.class);
UncheckedIOException exception = new UncheckedIOException(new IOException("I/O error message"));
when(flagsClient.listFlagData(prodUsWest1Target)).thenThrow(exception);
@@ -120,7 +120,7 @@ public class SystemFlagsDeployerTest {
}
@Test
- public void creates_error_entry_for_invalid_flag_archive() throws IOException {
+ void creates_error_entry_for_invalid_flag_archive() throws IOException {
FlagsClient flagsClient = mock(FlagsClient.class);
FlagData defaultData = flagData("flags/my-flag/main.json");
SystemFlagsDataArchive archive = new SystemFlagsDataArchive.Builder()
@@ -135,7 +135,7 @@ public class SystemFlagsDeployerTest {
}
@Test
- public void creates_error_entry_for_flag_data_of_undefined_flag() throws IOException {
+ void creates_error_entry_for_flag_data_of_undefined_flag() throws IOException {
FlagData prodUsEast3Data = flagData("flags/my-flag/main.prod.us-east-3.json");
FlagsClient flagsClient = mock(FlagsClient.class);
when(flagsClient.listFlagData(prodUsEast3Target))
@@ -154,7 +154,7 @@ public class SystemFlagsDeployerTest {
}
@Test
- public void creates_warning_entry_for_existing_flag_data_for_undefined_flag() throws IOException {
+ void creates_warning_entry_for_existing_flag_data_for_undefined_flag() throws IOException {
FlagData prodUsEast3Data = flagData("flags/my-flag/main.prod.us-east-3.json");
FlagsClient flagsClient = mock(FlagsClient.class);
when(flagsClient.listFlagData(prodUsEast3Target))
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/UserApiOnPremTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/UserApiOnPremTest.java
index 1cd4b5e5541..f7e270b3c68 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/UserApiOnPremTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/UserApiOnPremTest.java
@@ -11,7 +11,7 @@ import com.yahoo.vespa.hosted.controller.ControllerTester;
import com.yahoo.jdisc.http.filter.security.misc.User;
import com.yahoo.vespa.hosted.controller.restapi.ContainerTester;
import com.yahoo.vespa.hosted.controller.restapi.ControllerContainerTest;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.util.HashMap;
@@ -26,7 +26,7 @@ public class UserApiOnPremTest extends ControllerContainerTest {
private static final String responseFiles = "src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/responses/";
@Test
- public void userMetadataOnPremTest() {
+ void userMetadataOnPremTest() {
try (Flags.Replacer ignored = Flags.clearFlagsForTesting(PermanentFlags.MAX_TRIAL_TENANTS.id(), PermanentFlags.ENABLE_PUBLIC_SIGNUP_FLOW.id())) {
ContainerTester tester = new ContainerTester(container, responseFiles);
ControllerTester controller = new ControllerTester(tester);
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/UserApiTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/UserApiTest.java
index 1bb409b9906..3e9f6256134 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/UserApiTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/UserApiTest.java
@@ -14,7 +14,7 @@ import com.yahoo.vespa.hosted.controller.api.role.Role;
import com.yahoo.vespa.hosted.controller.restapi.ContainerTester;
import com.yahoo.vespa.hosted.controller.restapi.ControllerContainerCloudTest;
import com.yahoo.vespa.hosted.controller.tenant.Tenant;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.util.Set;
@@ -22,7 +22,7 @@ import java.util.Set;
import static com.yahoo.application.container.handler.Request.Method.DELETE;
import static com.yahoo.application.container.handler.Request.Method.POST;
import static com.yahoo.application.container.handler.Request.Method.PUT;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author jonmv
@@ -42,7 +42,7 @@ public class UserApiTest extends ControllerContainerCloudTest {
@Test
- public void testUserManagement() {
+ void testUserManagement() {
ContainerTester tester = new ContainerTester(container, responseFiles);
assertEquals(SystemName.Public, tester.controller().system());
Set<Role> operator = Set.of(Role.hostedOperator());
@@ -51,25 +51,25 @@ public class UserApiTest extends ControllerContainerCloudTest {
// GET at application/v4 root fails as it's not public read.
tester.assertResponse(request("/application/v4/"),
- accessDenied, 403);
+ accessDenied, 403);
// GET at application/v4/tenant succeeds for operators.
tester.assertResponse(request("/application/v4/tenant")
- .roles(operator),
- "[]");
+ .roles(operator),
+ "[]");
// POST a tenant is not available to everyone.
tester.assertResponse(request("/application/v4/tenant/my-tenant", POST)
- .data("{\"token\":\"hello\"}"),
- "{\"error-code\":\"FORBIDDEN\",\"message\":\"You are not currently permitted to create tenants. Please contact the Vespa team to request access.\"}", 403);
+ .data("{\"token\":\"hello\"}"),
+ "{\"error-code\":\"FORBIDDEN\",\"message\":\"You are not currently permitted to create tenants. Please contact the Vespa team to request access.\"}", 403);
// POST a tenant is available to operators.
tester.assertResponse(request("/application/v4/tenant/my-tenant", POST)
- .roles(operator)
- .principal("administrator@tenant")
- .user(new User("administrator@tenant", "administrator", "admin", "picture"))
- .data("{\"token\":\"hello\"}"),
- new File("tenant-without-applications.json"));
+ .roles(operator)
+ .principal("administrator@tenant")
+ .user(new User("administrator@tenant", "administrator", "admin", "picture"))
+ .data("{\"token\":\"hello\"}"),
+ new File("tenant-without-applications.json"));
// GET at tenant/info with contact information.
tester.assertResponse(request("/application/v4/tenant/my-tenant/info")
@@ -79,97 +79,97 @@ public class UserApiTest extends ControllerContainerCloudTest {
// GET at user/v1 root fails as no access control is defined there.
tester.assertResponse(request("/user/v1/"),
- accessDenied, 403);
+ accessDenied, 403);
// POST a hosted operator role is not allowed.
tester.assertResponse(request("/user/v1/tenant/my-tenant", POST)
- .roles(Set.of(Role.administrator(id.tenant())))
- .data("{\"user\":\"evil@evil\",\"roleName\":\"hostedOperator\"}"),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Malformed or illegal role name 'hostedOperator'.\"}", 400);
+ .roles(Set.of(Role.administrator(id.tenant())))
+ .data("{\"user\":\"evil@evil\",\"roleName\":\"hostedOperator\"}"),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Malformed or illegal role name 'hostedOperator'.\"}", 400);
// POST a tenant developer is available to the tenant owner.
tester.assertResponse(request("/user/v1/tenant/my-tenant", POST)
- .roles(Set.of(Role.administrator(id.tenant())))
- .data("{\"user\":\"developer@tenant\",\"roles\":[\"developer\",\"reader\"]}"),
- "{\"message\":\"user 'developer@tenant' is now a member of role 'developer' of 'my-tenant', role 'reader' of 'my-tenant'\"}");
+ .roles(Set.of(Role.administrator(id.tenant())))
+ .data("{\"user\":\"developer@tenant\",\"roles\":[\"developer\",\"reader\"]}"),
+ "{\"message\":\"user 'developer@tenant' is now a member of role 'developer' of 'my-tenant', role 'reader' of 'my-tenant'\"}");
// POST a tenant admin is not available to a tenant developer.
tester.assertResponse(request("/user/v1/tenant/my-tenant", POST)
- .roles(Set.of(Role.developer(id.tenant())))
- .data("{\"user\":\"developer@tenant\",\"roleName\":\"administrator\"}"),
- accessDenied, 403);
+ .roles(Set.of(Role.developer(id.tenant())))
+ .data("{\"user\":\"developer@tenant\",\"roleName\":\"administrator\"}"),
+ accessDenied, 403);
// POST a headless for a non-existent application fails.
tester.assertResponse(request("/user/v1/tenant/my-tenant/application/my-app", POST)
- .roles(Set.of(Role.administrator(TenantName.from("my-tenant"))))
- .data("{\"user\":\"headless@app\",\"roleName\":\"headless\"}"),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"role 'headless' of 'my-app' owned by 'my-tenant' not found\"}", 400);
+ .roles(Set.of(Role.administrator(TenantName.from("my-tenant"))))
+ .data("{\"user\":\"headless@app\",\"roleName\":\"headless\"}"),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"role 'headless' of 'my-app' owned by 'my-tenant' not found\"}", 400);
// POST an application is allowed for a tenant developer.
tester.assertResponse(request("/application/v4/tenant/my-tenant/application/my-app", POST)
- .principal("developer@tenant")
- .roles(Set.of(Role.developer(id.tenant()))),
- new File("application-created.json"));
+ .principal("developer@tenant")
+ .roles(Set.of(Role.developer(id.tenant()))),
+ new File("application-created.json"));
// POST an application is not allowed under a different tenant.
tester.assertResponse(request("/application/v4/tenant/other-tenant/application/my-app", POST)
- .roles(Set.of(Role.administrator(id.tenant()))),
- accessDenied, 403);
+ .roles(Set.of(Role.administrator(id.tenant()))),
+ accessDenied, 403);
// POST a tenant role is not allowed to an application.
tester.assertResponse(request("/user/v1/tenant/my-tenant/application/my-app", POST)
- .roles(Set.of(Role.hostedOperator()))
- .data("{\"user\":\"developer@app\",\"roleName\":\"developer\"}"),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Malformed or illegal role name 'developer'.\"}", 400);
+ .roles(Set.of(Role.hostedOperator()))
+ .data("{\"user\":\"developer@app\",\"roleName\":\"developer\"}"),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Malformed or illegal role name 'developer'.\"}", 400);
// GET tenant role information is available to readers.
tester.assertResponse(request("/user/v1/tenant/my-tenant")
- .roles(Set.of(Role.reader(id.tenant()))),
- new File("tenant-roles.json"));
+ .roles(Set.of(Role.reader(id.tenant()))),
+ new File("tenant-roles.json"));
// GET application role information is available to tenant administrators.
tester.assertResponse(request("/user/v1/tenant/my-tenant/application/my-app")
- .roles(Set.of(Role.administrator(id.tenant()))),
- new File("application-roles.json"));
+ .roles(Set.of(Role.administrator(id.tenant()))),
+ new File("application-roles.json"));
// POST a pem deploy key
tester.assertResponse(request("/application/v4/tenant/my-tenant/application/my-app/key", POST)
- .roles(Set.of(Role.developer(id.tenant())))
- .data("{\"key\":\"" + pemPublicKey + "\"}"),
- new File("first-deploy-key.json"));
+ .roles(Set.of(Role.developer(id.tenant())))
+ .data("{\"key\":\"" + pemPublicKey + "\"}"),
+ new File("first-deploy-key.json"));
// POST a pem developer key
tester.assertResponse(request("/application/v4/tenant/my-tenant/key", POST)
- .principal("joe@dev")
- .roles(Set.of(Role.developer(id.tenant())))
- .data("{\"key\":\"" + pemPublicKey + "\"}"),
- new File("first-developer-key.json"));
+ .principal("joe@dev")
+ .roles(Set.of(Role.developer(id.tenant())))
+ .data("{\"key\":\"" + pemPublicKey + "\"}"),
+ new File("first-developer-key.json"));
// POST the same pem developer key for a different user is forbidden
tester.assertResponse(request("/application/v4/tenant/my-tenant/key", POST)
- .principal("operator@tenant")
- .roles(Set.of(Role.developer(id.tenant())))
- .data("{\"key\":\"" + pemPublicKey + "\"}"),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Key "+ quotedPemPublicKey + " is already owned by joe@dev\"}",
- 400);
+ .principal("operator@tenant")
+ .roles(Set.of(Role.developer(id.tenant())))
+ .data("{\"key\":\"" + pemPublicKey + "\"}"),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Key " + quotedPemPublicKey + " is already owned by joe@dev\"}",
+ 400);
// POST in a different pem developer key
tester.assertResponse(request("/application/v4/tenant/my-tenant/key", POST)
- .principal("developer@tenant")
- .roles(Set.of(Role.developer(id.tenant())))
- .data("{\"key\":\"" + otherPemPublicKey + "\"}"),
- new File("both-developer-keys.json"));
+ .principal("developer@tenant")
+ .roles(Set.of(Role.developer(id.tenant())))
+ .data("{\"key\":\"" + otherPemPublicKey + "\"}"),
+ new File("both-developer-keys.json"));
// GET tenant information with keys
tester.assertResponse(request("/application/v4/tenant/my-tenant/")
- .roles(Set.of(Role.reader(id.tenant()))),
- new File("tenant-with-keys.json"));
+ .roles(Set.of(Role.reader(id.tenant()))),
+ new File("tenant-with-keys.json"));
// DELETE a pem developer key
tester.assertResponse(request("/application/v4/tenant/my-tenant/key", DELETE)
- .roles(Set.of(Role.developer(id.tenant())))
- .data("{\"key\":\"" + pemPublicKey + "\"}"),
- new File("second-developer-key.json"));
+ .roles(Set.of(Role.developer(id.tenant())))
+ .data("{\"key\":\"" + pemPublicKey + "\"}"),
+ new File("second-developer-key.json"));
// PUT in a new secret store for the tenant
tester.assertResponse(request("/application/v4/tenant/my-tenant/secret-store/secret-foo", PUT)
@@ -187,33 +187,33 @@ public class UserApiTest extends ControllerContainerCloudTest {
// DELETE an application is available to developers.
tester.assertResponse(request("/application/v4/tenant/my-tenant/application/my-app", DELETE)
- .roles(Set.of(Role.developer(id.tenant()))),
- "{\"message\":\"Deleted application my-tenant.my-app\"}");
+ .roles(Set.of(Role.developer(id.tenant()))),
+ "{\"message\":\"Deleted application my-tenant.my-app\"}");
// DELETE a tenant role is available to tenant admins.
// DELETE the developer role clears any developer key.
tester.assertResponse(request("/user/v1/tenant/my-tenant", DELETE)
- .roles(Set.of(Role.administrator(id.tenant())))
- .data("{\"user\":\"developer@tenant\",\"roles\":[\"developer\",\"reader\"]}"),
- "{\"message\":\"user 'developer@tenant' is no longer a member of role 'developer' of 'my-tenant', role 'reader' of 'my-tenant'\"}");
+ .roles(Set.of(Role.administrator(id.tenant())))
+ .data("{\"user\":\"developer@tenant\",\"roles\":[\"developer\",\"reader\"]}"),
+ "{\"message\":\"user 'developer@tenant' is no longer a member of role 'developer' of 'my-tenant', role 'reader' of 'my-tenant'\"}");
// DELETE the last tenant owner is not allowed.
tester.assertResponse(request("/user/v1/tenant/my-tenant", DELETE)
- .roles(operator)
- .data("{\"user\":\"administrator@tenant\",\"roleName\":\"administrator\"}"),
- "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Can't remove the last administrator of a tenant.\"}", 400);
+ .roles(operator)
+ .data("{\"user\":\"administrator@tenant\",\"roleName\":\"administrator\"}"),
+ "{\"error-code\":\"BAD_REQUEST\",\"message\":\"Can't remove the last administrator of a tenant.\"}", 400);
// DELETE the tenant is not allowed
tester.assertResponse(request("/application/v4/tenant/my-tenant", DELETE)
- .roles(Set.of(Role.developer(id.tenant()))),
- "{\n" +
- " \"code\" : 403,\n" +
- " \"message\" : \"Access denied\"\n" +
- "}", 403);
+ .roles(Set.of(Role.developer(id.tenant()))),
+ "{\n" +
+ " \"code\" : 403,\n" +
+ " \"message\" : \"Access denied\"\n" +
+ "}", 403);
}
@Test
- public void userMetadataTest() {
+ void userMetadataTest() {
try (Flags.Replacer ignored = Flags.clearFlagsForTesting(PermanentFlags.MAX_TRIAL_TENANTS.id(), PermanentFlags.ENABLE_PUBLIC_SIGNUP_FLOW.id())) {
ContainerTester tester = new ContainerTester(container, responseFiles);
((InMemoryFlagSource) tester.controller().flagSource())
@@ -262,7 +262,7 @@ public class UserApiTest extends ControllerContainerCloudTest {
}
@Test
- public void maxTrialTenants() {
+ void maxTrialTenants() {
try (Flags.Replacer ignored = Flags.clearFlagsForTesting(PermanentFlags.MAX_TRIAL_TENANTS.id(), PermanentFlags.ENABLE_PUBLIC_SIGNUP_FLOW.id())) {
ContainerTester tester = new ContainerTester(container, responseFiles);
((InMemoryFlagSource) tester.controller().flagSource())
@@ -280,7 +280,7 @@ public class UserApiTest extends ControllerContainerCloudTest {
}
@Test
- public void supportTenant() {
+ void supportTenant() {
try (Flags.Replacer ignored = Flags.clearFlagsForTesting(PermanentFlags.MAX_TRIAL_TENANTS.id(), PermanentFlags.ENABLE_PUBLIC_SIGNUP_FLOW.id())) {
ContainerTester tester = new ContainerTester(container, responseFiles);
((InMemoryFlagSource) tester.controller().flagSource())
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/UserFlagsSerializerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/UserFlagsSerializerTest.java
index 8625628b74e..ed7d02d0047 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/UserFlagsSerializerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/user/UserFlagsSerializerTest.java
@@ -14,7 +14,7 @@ import com.yahoo.vespa.flags.JsonNodeRawFlag;
import com.yahoo.vespa.flags.json.Condition;
import com.yahoo.vespa.flags.json.FlagData;
import com.yahoo.vespa.flags.json.Rule;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@@ -36,7 +36,7 @@ import static com.yahoo.vespa.flags.FetchVector.Dimension.TENANT_ID;
public class UserFlagsSerializerTest {
@Test
- public void user_flag_test() throws IOException {
+ void user_flag_test() throws IOException {
String email1 = "alice@domain.tld";
String email2 = "bob@domain.tld";
@@ -56,33 +56,33 @@ public class UserFlagsSerializerTest {
rule("[\"value2\"]", condition(CONSOLE_USER_EMAIL, Condition.Type.WHITELIST, email2)),
rule("[\"value1\",\"value3\"]", condition(APPLICATION_ID, Condition.Type.BLACKLIST, "tenant1:video:default", "tenant1:video:default", "tenant2:music:default"))),
flagData("jackson-id", rule("{\"integer\":456,\"string\":\"xyz\"}", condition(CONSOLE_USER_EMAIL, Condition.Type.WHITELIST, email1), condition(TENANT_ID, Condition.Type.WHITELIST, "tenant1", "tenant3")))
- ).collect(Collectors.toMap(FlagData::id, fd -> fd));
+ ).collect(Collectors.toMap(FlagData::id, fd -> fd));
// double-id is not here as it does not have CONSOLE_USER_EMAIL dimension
assertUserFlags("{\"flags\":[" +
- "{\"id\":\"int-id\",\"rules\":[{\"value\":456}]}," + // Default from DB
- "{\"id\":\"jackson-id\",\"rules\":[{\"conditions\":[{\"type\":\"whitelist\",\"dimension\":\"tenant\"}],\"value\":{\"integer\":456,\"string\":\"xyz\"}},{\"value\":{\"integer\":123,\"string\":\"abc\"}}]}," + // Resolved for email
- // Resolved for email, but conditions are empty since this user is not authorized for any tenants
- "{\"id\":\"list-id\",\"rules\":[{\"conditions\":[{\"type\":\"blacklist\",\"dimension\":\"application\"}],\"value\":[\"value1\"]},{\"conditions\":[{\"type\":\"blacklist\",\"dimension\":\"application\"}],\"value\":[\"value1\",\"value3\"]},{\"value\":[\"a\"]}]}," +
- "{\"id\":\"string-id\",\"rules\":[{\"value\":\"value1\"}]}]}", // resolved for email
+ "{\"id\":\"int-id\",\"rules\":[{\"value\":456}]}," + // Default from DB
+ "{\"id\":\"jackson-id\",\"rules\":[{\"conditions\":[{\"type\":\"whitelist\",\"dimension\":\"tenant\"}],\"value\":{\"integer\":456,\"string\":\"xyz\"}},{\"value\":{\"integer\":123,\"string\":\"abc\"}}]}," + // Resolved for email
+ // Resolved for email, but conditions are empty since this user is not authorized for any tenants
+ "{\"id\":\"list-id\",\"rules\":[{\"conditions\":[{\"type\":\"blacklist\",\"dimension\":\"application\"}],\"value\":[\"value1\"]},{\"conditions\":[{\"type\":\"blacklist\",\"dimension\":\"application\"}],\"value\":[\"value1\",\"value3\"]},{\"value\":[\"a\"]}]}," +
+ "{\"id\":\"string-id\",\"rules\":[{\"value\":\"value1\"}]}]}", // resolved for email
flagData, Set.of(), false, email1);
// Same as the first one, but user is authorized for tenant1
assertUserFlags("{\"flags\":[" +
- "{\"id\":\"int-id\",\"rules\":[{\"value\":456}]}," + // Default from DB
- "{\"id\":\"jackson-id\",\"rules\":[{\"conditions\":[{\"type\":\"whitelist\",\"dimension\":\"tenant\",\"values\":[\"tenant1\"]}],\"value\":{\"integer\":456,\"string\":\"xyz\"}},{\"value\":{\"integer\":123,\"string\":\"abc\"}}]}," + // Resolved for email
- // Resolved for email, but conditions have filtered out tenant2
- "{\"id\":\"list-id\",\"rules\":[{\"conditions\":[{\"type\":\"blacklist\",\"dimension\":\"application\",\"values\":[\"tenant1:video:default\",\"tenant1:video:default\"]}],\"value\":[\"value1\"]},{\"conditions\":[{\"type\":\"blacklist\",\"dimension\":\"application\",\"values\":[\"tenant1:video:default\",\"tenant1:video:default\"]}],\"value\":[\"value1\",\"value3\"]},{\"value\":[\"a\"]}]}," +
- "{\"id\":\"string-id\",\"rules\":[{\"value\":\"value1\"}]}]}", // resolved for email
+ "{\"id\":\"int-id\",\"rules\":[{\"value\":456}]}," + // Default from DB
+ "{\"id\":\"jackson-id\",\"rules\":[{\"conditions\":[{\"type\":\"whitelist\",\"dimension\":\"tenant\",\"values\":[\"tenant1\"]}],\"value\":{\"integer\":456,\"string\":\"xyz\"}},{\"value\":{\"integer\":123,\"string\":\"abc\"}}]}," + // Resolved for email
+ // Resolved for email, but conditions have filtered out tenant2
+ "{\"id\":\"list-id\",\"rules\":[{\"conditions\":[{\"type\":\"blacklist\",\"dimension\":\"application\",\"values\":[\"tenant1:video:default\",\"tenant1:video:default\"]}],\"value\":[\"value1\"]},{\"conditions\":[{\"type\":\"blacklist\",\"dimension\":\"application\",\"values\":[\"tenant1:video:default\",\"tenant1:video:default\"]}],\"value\":[\"value1\",\"value3\"]},{\"value\":[\"a\"]}]}," +
+ "{\"id\":\"string-id\",\"rules\":[{\"value\":\"value1\"}]}]}", // resolved for email
flagData, Set.of("tenant1"), false, email1);
// As operator no conditions are filtered, but the email precondition is applied
assertUserFlags("{\"flags\":[" +
- "{\"id\":\"int-id\",\"rules\":[{\"value\":456}]}," + // Default from DB
- "{\"id\":\"jackson-id\",\"rules\":[{\"value\":{\"integer\":123,\"string\":\"abc\"}}]}," + // Default from code, no DB values match
- // Includes last value from DB which is not conditioned on email and the default from code
- "{\"id\":\"list-id\",\"rules\":[{\"conditions\":[{\"type\":\"blacklist\",\"dimension\":\"application\",\"values\":[\"tenant1:video:default\",\"tenant1:video:default\",\"tenant2:music:default\"]}],\"value\":[\"value1\",\"value3\"]},{\"value\":[\"a\"]}]}," +
- "{\"id\":\"string-id\",\"rules\":[{\"value\":\"default value\"}]}]}", // Default from code
+ "{\"id\":\"int-id\",\"rules\":[{\"value\":456}]}," + // Default from DB
+ "{\"id\":\"jackson-id\",\"rules\":[{\"value\":{\"integer\":123,\"string\":\"abc\"}}]}," + // Default from code, no DB values match
+ // Includes last value from DB which is not conditioned on email and the default from code
+ "{\"id\":\"list-id\",\"rules\":[{\"conditions\":[{\"type\":\"blacklist\",\"dimension\":\"application\",\"values\":[\"tenant1:video:default\",\"tenant1:video:default\",\"tenant2:music:default\"]}],\"value\":[\"value1\",\"value3\"]},{\"value\":[\"a\"]}]}," +
+ "{\"id\":\"string-id\",\"rules\":[{\"value\":\"default value\"}]}]}", // Default from code
flagData, Set.of(), true, "operator@domain.tld");
}
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/zone/v1/ZoneApiTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/zone/v1/ZoneApiTest.java
index fcf8402d23c..5d5e310503d 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/zone/v1/ZoneApiTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/zone/v1/ZoneApiTest.java
@@ -8,8 +8,8 @@ import com.yahoo.vespa.hosted.controller.api.role.Role;
import com.yahoo.vespa.hosted.controller.integration.ZoneApiMock;
import com.yahoo.vespa.hosted.controller.restapi.ContainerTester;
import com.yahoo.vespa.hosted.controller.restapi.ControllerContainerCloudTest;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.util.List;
@@ -31,7 +31,7 @@ public class ZoneApiTest extends ControllerContainerCloudTest {
private ContainerTester tester;
- @Before
+ @BeforeEach
public void before() {
tester = new ContainerTester(container, responseFiles);
tester.serviceRegistry().zoneRegistry()
@@ -40,30 +40,30 @@ public class ZoneApiTest extends ControllerContainerCloudTest {
}
@Test
- public void test_requests() {
+ void test_requests() {
// GET /zone/v1
tester.assertResponse(request("/zone/v1")
- .roles(everyone),
- new File("root.json"));
+ .roles(everyone),
+ new File("root.json"));
// GET /zone/v1/environment/prod
tester.assertResponse(request("/zone/v1/environment/prod")
- .roles(everyone),
- new File("prod.json"));
+ .roles(everyone),
+ new File("prod.json"));
// GET /zone/v1/environment/dev/default
tester.assertResponse(request("/zone/v1/environment/dev/default")
- .roles(everyone),
- new File("default-for-region.json"));
+ .roles(everyone),
+ new File("default-for-region.json"));
}
@Test
- public void test_invalid_requests() {
+ void test_invalid_requests() {
// GET /zone/v1/environment/prod/default: No default region
tester.assertResponse(request("/zone/v1/environment/prod/default")
- .roles(everyone),
- new File("no-default-region.json"),
- 400);
+ .roles(everyone),
+ new File("no-default-region.json"),
+ 400);
}
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/zone/v2/ZoneApiTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/zone/v2/ZoneApiTest.java
index fd39c13707b..81484f05d1e 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/zone/v2/ZoneApiTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/restapi/zone/v2/ZoneApiTest.java
@@ -11,15 +11,15 @@ import com.yahoo.vespa.hosted.controller.integration.ZoneApiMock;
import com.yahoo.vespa.hosted.controller.proxy.ProxyRequest;
import com.yahoo.vespa.hosted.controller.restapi.ContainerTester;
import com.yahoo.vespa.hosted.controller.restapi.ControllerContainerTest;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+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.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author mpolden
@@ -36,7 +36,7 @@ public class ZoneApiTest extends ControllerContainerTest {
private ContainerTester tester;
private ConfigServerProxyMock proxy;
- @Before
+ @BeforeEach
public void before() {
tester = new ContainerTester(container, responseFiles);
tester.serviceRegistry().zoneRegistry()
@@ -46,53 +46,53 @@ public class ZoneApiTest extends ControllerContainerTest {
}
@Test
- public void test_requests() {
+ void test_requests() {
// GET /zone/v2
tester.assertResponse(authenticatedRequest("http://localhost:8080/zone/v2"),
- new File("root.json"));
+ new File("root.json"));
// GET /zone/v2/prod/us-north-1
tester.assertResponse(authenticatedRequest("http://localhost:8080/zone/v2/prod/us-north-1"),
- "ok");
+ "ok");
assertLastRequest(ZoneId.from("prod", "us-north-1"), 1, "GET");
// GET /zone/v2/nodes/v2/node/?recursive=true
tester.assertResponse(authenticatedRequest("http://localhost:8080/zone/v2/prod/us-north-1/nodes/v2/node/?recursive=true"),
- "ok");
+ "ok");
assertLastRequest(ZoneId.from("prod", "us-north-1"), 1, "GET");
// POST /zone/v2/dev/us-north-2/nodes/v2/command/restart?hostname=node1
tester.assertResponse(operatorRequest("http://localhost:8080/zone/v2/dev/aws-us-north-2/nodes/v2/command/restart?hostname=node1",
- "", Method.POST),
- "ok");
+ "", Method.POST),
+ "ok");
// PUT /zone/v2/prod/us-north-1/nodes/v2/state/dirty/node1
tester.assertResponse(operatorRequest("http://localhost:8080/zone/v2/prod/us-north-1/nodes/v2/state/dirty/node1",
- "", Method.PUT), "ok");
+ "", Method.PUT), "ok");
assertLastRequest(ZoneId.from("prod", "us-north-1"), 1, "PUT");
// DELETE /zone/v2/prod/us-north-1/nodes/v2/node/node1
tester.assertResponse(operatorRequest("http://localhost:8080/zone/v2/prod/us-north-1/nodes/v2/node/node1",
- "", Method.DELETE), "ok");
+ "", Method.DELETE), "ok");
assertLastRequest(ZoneId.from("prod", "us-north-1"), 1, "DELETE");
// PATCH /zone/v2/prod/us-north-1/nodes/v2/node/node1
tester.assertResponse(operatorRequest("http://localhost:8080/zone/v2/dev/aws-us-north-2/nodes/v2/node/node1",
- "{\"currentRestartGeneration\": 1}",
- Method.PATCH), "ok");
+ "{\"currentRestartGeneration\": 1}",
+ Method.PATCH), "ok");
assertLastRequest(ZoneId.from("dev", "aws-us-north-2"), 1, "PATCH");
assertEquals("{\"currentRestartGeneration\": 1}", proxy.lastRequestBody().get());
- assertFalse("Actions are logged to audit log", tester.controller().auditLogger().readLog().entries().isEmpty());
+ assertFalse(tester.controller().auditLogger().readLog().entries().isEmpty(), "Actions are logged to audit log");
}
@Test
- public void test_invalid_requests() {
+ void test_invalid_requests() {
// POST /zone/v2/prod/us-north-34/nodes/v2
tester.assertResponse(operatorRequest("http://localhost:8080/zone/v2/prod/us-north-42/nodes/v2",
- "", Method.POST),
- new File("unknown-zone.json"), 400);
+ "", Method.POST),
+ new File("unknown-zone.json"), 400);
assertFalse(proxy.lastReceived().isPresent());
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/routing/RoutingPoliciesTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/routing/RoutingPoliciesTest.java
index c0fb9b3d8c7..c5d74e0b01d 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/routing/RoutingPoliciesTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/routing/RoutingPoliciesTest.java
@@ -32,7 +32,7 @@ import com.yahoo.vespa.hosted.controller.deployment.DeploymentContext;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester;
import com.yahoo.vespa.hosted.controller.integration.ZoneApiMock;
import com.yahoo.vespa.hosted.rotation.config.RotationsConfig;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
@@ -47,9 +47,9 @@ import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author mortent
@@ -67,7 +67,7 @@ public class RoutingPoliciesTest {
.build();
@Test
- public void global_routing_policies() {
+ void global_routing_policies() {
var tester = new RoutingPoliciesTester();
var context1 = tester.newDeploymentContext("tenant1", "app1", "default");
var context2 = tester.newDeploymentContext("tenant1", "app2", "default");
@@ -87,9 +87,9 @@ public class RoutingPoliciesTest {
tester.assertTargets(context1.instanceId(), EndpointId.of("r0"), 0, zone1, zone2);
tester.assertTargets(context1.instanceId(), EndpointId.of("r1"), 0, zone1);
tester.assertTargets(context1.instanceId(), EndpointId.of("r2"), 1, zone1, zone2);
- assertEquals("Routing policy count is equal to cluster count",
- numberOfDeployments * clustersPerZone,
- tester.policiesOf(context1.instance().id()).size());
+ assertEquals(numberOfDeployments * clustersPerZone,
+ tester.policiesOf(context1.instance().id()).size(),
+ "Routing policy count is equal to cluster count");
// Applications gains a new deployment
ApplicationPackage applicationPackage2 = applicationPackageBuilder()
@@ -144,13 +144,13 @@ public class RoutingPoliciesTest {
tester.assertTargets(context1.instanceId(), EndpointId.of("r2"), 0);
var policies = tester.policiesOf(context1.instanceId());
assertEquals(clustersPerZone * numberOfDeployments, policies.size());
- assertTrue("Rotation membership is removed from all policies",
- policies.asList().stream().allMatch(policy -> policy.instanceEndpoints().isEmpty()));
- assertEquals("Rotations for " + context2.application() + " are not removed", 1, tester.aliasDataOf(endpoint4).size());
+ assertTrue(policies.asList().stream().allMatch(policy -> policy.instanceEndpoints().isEmpty()),
+ "Rotation membership is removed from all policies");
+ assertEquals(1, tester.aliasDataOf(endpoint4).size(), "Rotations for " + context2.application() + " are not removed");
}
@Test
- public void global_routing_policies_with_duplicate_region() {
+ void global_routing_policies_with_duplicate_region() {
var tester = new RoutingPoliciesTester();
var context = tester.newDeploymentContext("tenant1", "app1", "default");
int clustersPerZone = 2;
@@ -168,40 +168,40 @@ public class RoutingPoliciesTest {
context.submit(applicationPackage).deferLoadBalancerProvisioningIn(Environment.prod).deploy();
tester.assertTargets(context.instanceId(), EndpointId.of("r0"), 0, zone1, zone3, zone4);
tester.assertTargets(context.instanceId(), EndpointId.of("r1"), 1, zone1, zone3, zone4);
- assertEquals("Routing policy count is equal to cluster count",
- numberOfDeployments * clustersPerZone,
- tester.policiesOf(context.instance().id()).size());
+ assertEquals(numberOfDeployments * clustersPerZone,
+ tester.policiesOf(context.instance().id()).size(),
+ "Routing policy count is equal to cluster count");
// A zone in shared region is set out
tester.routingPolicies().setRoutingStatus(context.deploymentIdIn(zone4), RoutingStatus.Value.out,
- RoutingStatus.Agent.tenant);
+ RoutingStatus.Agent.tenant);
context.flushDnsUpdates();
// Weight of inactive zone is set to zero
tester.assertTargets(context.instanceId(), EndpointId.of("r0"), 0, ImmutableMap.of(zone1, 1L,
- zone3, 1L,
- zone4, 0L));
+ zone3, 1L,
+ zone4, 0L));
// Other zone in shared region is set out. Entire record group for the region is removed as all zones in the
// region are out (weight sum = 0)
tester.routingPolicies().setRoutingStatus(context.deploymentIdIn(zone3), RoutingStatus.Value.out,
- RoutingStatus.Agent.tenant);
+ RoutingStatus.Agent.tenant);
context.flushDnsUpdates();
tester.assertTargets(context.instanceId(), EndpointId.of("r0"), 0, ImmutableMap.of(zone1, 1L));
// Everything is set back in
tester.routingPolicies().setRoutingStatus(context.deploymentIdIn(zone3), RoutingStatus.Value.in,
- RoutingStatus.Agent.tenant);
+ RoutingStatus.Agent.tenant);
tester.routingPolicies().setRoutingStatus(context.deploymentIdIn(zone4), RoutingStatus.Value.in,
- RoutingStatus.Agent.tenant);
+ RoutingStatus.Agent.tenant);
context.flushDnsUpdates();
tester.assertTargets(context.instanceId(), EndpointId.of("r0"), 0, ImmutableMap.of(zone1, 1L,
- zone3, 1L,
- zone4, 1L));
+ zone3, 1L,
+ zone4, 1L));
}
@Test
- public void global_routing_policies_legacy_global_service_id() {
+ void global_routing_policies_legacy_global_service_id() {
var tester = new RoutingPoliciesTester();
var context = tester.newDeploymentContext("tenant1", "app1", "default");
int clustersPerZone = 2;
@@ -216,13 +216,13 @@ public class RoutingPoliciesTest {
// Creates alias records
context.submit(applicationPackage).deferLoadBalancerProvisioningIn(Environment.prod).deploy();
tester.assertTargets(context.instanceId(), EndpointId.defaultId(), 0, zone1, zone2);
- assertEquals("Routing policy count is equal to cluster count",
- numberOfDeployments * clustersPerZone,
- tester.policiesOf(context.instance().id()).size());
+ assertEquals(numberOfDeployments * clustersPerZone,
+ tester.policiesOf(context.instance().id()).size(),
+ "Routing policy count is equal to cluster count");
}
@Test
- public void zone_routing_policies() {
+ void zone_routing_policies() {
zone_routing_policies(false);
zone_routing_policies(true);
}
@@ -313,12 +313,12 @@ public class RoutingPoliciesTest {
"c1.app1.tenant1.us-central-1.vespa.oath.cloud"
);
assertEquals(expectedRecords, tester.recordNames());
- assertTrue("Removes stale routing policies " + context2.application(), tester.routingPolicies().read(context2.instanceId()).isEmpty());
- assertEquals("Keeps routing policies for " + context1.application(), 4, tester.routingPolicies().read(context1.instanceId()).size());
+ assertTrue(tester.routingPolicies().read(context2.instanceId()).isEmpty(), "Removes stale routing policies " + context2.application());
+ assertEquals(4, tester.routingPolicies().read(context1.instanceId()).size(), "Keeps routing policies for " + context1.application());
}
@Test
- public void zone_routing_policies_without_dns_update() {
+ void zone_routing_policies_without_dns_update() {
var tester = new RoutingPoliciesTester(new DeploymentTester(), false);
var context = tester.newDeploymentContext("tenant1", "app1", "default");
tester.provisionLoadBalancers(1, context.instanceId(), true, zone1, zone2);
@@ -329,7 +329,7 @@ public class RoutingPoliciesTest {
}
@Test
- public void global_routing_policies_in_rotationless_system() {
+ void global_routing_policies_in_rotationless_system() {
var tester = new RoutingPoliciesTester(SystemName.Public);
var context = tester.newDeploymentContext("tenant1", "app1", "default");
List<ZoneId> prodZones = tester.controllerTester().controller().zoneRegistry().zones().all().in(Environment.prod).ids();
@@ -345,13 +345,13 @@ public class RoutingPoliciesTest {
context.submit(applicationPackage).deferLoadBalancerProvisioningIn(Environment.prod).deploy();
tester.assertTargets(context.instanceId(), EndpointId.of("r0"), 0, zone1);
- assertTrue("No rotations assigned", context.application().instances().values().stream()
- .map(Instance::rotations)
- .allMatch(List::isEmpty));
+ assertTrue(context.application().instances().values().stream()
+ .map(Instance::rotations)
+ .allMatch(List::isEmpty), "No rotations assigned");
}
@Test
- public void global_routing_policies_in_public() {
+ void global_routing_policies_in_public() {
var tester = new RoutingPoliciesTester(SystemName.Public);
var context = tester.newDeploymentContext("tenant1", "app1", "default");
List<ZoneId> prodZones = tester.controllerTester().controller().zoneRegistry().zones().all().in(Environment.prod).ids();
@@ -367,19 +367,19 @@ public class RoutingPoliciesTest {
context.submit(applicationPackage).deploy();
tester.assertTargets(context.instanceId(), EndpointId.defaultId(),
- ClusterSpec.Id.from("default"), 0,
- Map.of(zone1, 1L, zone2, 1L));
- assertEquals("Registers expected DNS names",
- Set.of("app1.tenant1.aws-eu-west-1.w.vespa-app.cloud",
- "app1.tenant1.aws-eu-west-1a.z.vespa-app.cloud",
- "app1.tenant1.aws-us-east-1.w.vespa-app.cloud",
- "app1.tenant1.aws-us-east-1c.z.vespa-app.cloud",
- "app1.tenant1.g.vespa-app.cloud"),
- tester.recordNames());
+ ClusterSpec.Id.from("default"), 0,
+ Map.of(zone1, 1L, zone2, 1L));
+ assertEquals(Set.of("app1.tenant1.aws-eu-west-1.w.vespa-app.cloud",
+ "app1.tenant1.aws-eu-west-1a.z.vespa-app.cloud",
+ "app1.tenant1.aws-us-east-1.w.vespa-app.cloud",
+ "app1.tenant1.aws-us-east-1c.z.vespa-app.cloud",
+ "app1.tenant1.g.vespa-app.cloud"),
+ tester.recordNames(),
+ "Registers expected DNS names");
}
@Test
- public void manual_deployment_creates_routing_policy() {
+ void manual_deployment_creates_routing_policy() {
// Empty application package is valid in manually deployed environments
var tester = new RoutingPoliciesTester();
var context = tester.newDeploymentContext("tenant1", "app1", "default");
@@ -387,12 +387,12 @@ public class RoutingPoliciesTest {
var zone = ZoneId.from("dev", "us-east-1");
var zoneApi = ZoneApiMock.from(zone.environment(), zone.region());
tester.controllerTester().serviceRegistry().zoneRegistry()
- .setZones(zoneApi)
- .exclusiveRoutingIn(zoneApi);
+ .setZones(zoneApi)
+ .exclusiveRoutingIn(zoneApi);
// Deploy to dev
context.runJob(zone, emptyApplicationPackage);
- assertEquals("DeploymentSpec is not persisted", DeploymentSpec.empty, context.application().deploymentSpec());
+ assertEquals(DeploymentSpec.empty, context.application().deploymentSpec(), "DeploymentSpec is not persisted");
context.flushDnsUpdates();
// Routing policy is created and DNS is updated
@@ -401,7 +401,7 @@ public class RoutingPoliciesTest {
}
@Test
- public void manual_deployment_creates_routing_policy_with_non_empty_spec() {
+ void manual_deployment_creates_routing_policy_with_non_empty_spec() {
// Initial deployment
var tester = new RoutingPoliciesTester();
var context = tester.newDeploymentContext("tenant1", "app1", "default");
@@ -415,7 +415,7 @@ public class RoutingPoliciesTest {
var devContext = tester.newDeploymentContext(context.application().id().instance("user"));
devContext.runJob(zone, applicationPackage);
- assertEquals("DeploymentSpec is persisted", applicationPackage.deploymentSpec(), context.application().deploymentSpec());
+ assertEquals(applicationPackage.deploymentSpec(), context.application().deploymentSpec(), "DeploymentSpec is persisted");
context.flushDnsUpdates();
// Routing policy is created and DNS is updated
@@ -424,7 +424,7 @@ public class RoutingPoliciesTest {
}
@Test
- public void reprovisioning_load_balancer_preserves_cname_record() {
+ void reprovisioning_load_balancer_preserves_cname_record() {
var tester = new RoutingPoliciesTester();
var context = tester.newDeploymentContext("tenant1", "app1", "default");
@@ -449,23 +449,24 @@ public class RoutingPoliciesTest {
// Load balancer for the same application is provisioned again, but with a different hostname
var newHostname = HostName.of("new-hostname");
var loadBalancer = new LoadBalancer("LB-0-Z-" + zone1.value(),
- context.instanceId(),
- ClusterSpec.Id.from("c0"),
- Optional.of(newHostname),
- LoadBalancer.State.active,
- Optional.of("dns-zone-1"));
+ context.instanceId(),
+ ClusterSpec.Id.from("c0"),
+ Optional.of(newHostname),
+ LoadBalancer.State.active,
+ Optional.of("dns-zone-1"));
tester.controllerTester().configServer().putLoadBalancers(zone1, List.of(loadBalancer));
// Application redeployment preserves DNS record
context.submit(applicationPackage).deferLoadBalancerProvisioningIn(Environment.prod).deploy();
assertEquals(expectedRecords, tester.recordNames());
assertEquals(1, tester.policiesOf(context.instanceId()).size());
- assertEquals("CNAME points to current load blancer", newHostname.value() + ".",
- tester.cnameDataOf(expectedRecords.iterator().next()).get(0));
+ assertEquals(newHostname.value() + ".",
+ tester.cnameDataOf(expectedRecords.iterator().next()).get(0),
+ "CNAME points to current load blancer");
}
@Test
- public void set_global_endpoint_status() {
+ void set_global_endpoint_status() {
var tester = new RoutingPoliciesTester();
var context = tester.newDeploymentContext("tenant1", "app1", "default");
@@ -486,7 +487,7 @@ public class RoutingPoliciesTest {
// Global routing status is overridden in one zone
var changedAt = tester.controllerTester().clock().instant();
tester.routingPolicies().setRoutingStatus(context.deploymentIdIn(zone1), RoutingStatus.Value.out,
- RoutingStatus.Agent.tenant);
+ RoutingStatus.Agent.tenant);
context.flushDnsUpdates();
// Inactive zone is removed from global DNS record
@@ -548,7 +549,7 @@ public class RoutingPoliciesTest {
}
@Test
- public void set_zone_global_endpoint_status() {
+ void set_zone_global_endpoint_status() {
var tester = new RoutingPoliciesTester();
var context1 = tester.newDeploymentContext("tenant1", "app1", "default");
var context2 = tester.newDeploymentContext("tenant2", "app2", "default");
@@ -573,12 +574,12 @@ public class RoutingPoliciesTest {
tester.assertTargets(context2.instanceId(), EndpointId.defaultId(), 0, zone1);
for (var context : contexts) {
var policies = tester.routingPolicies().read(context.instanceId());
- assertTrue("Global routing status for policy remains " + RoutingStatus.Value.in,
- policies.asList().stream()
- .map(RoutingPolicy::status)
- .map(RoutingPolicy.Status::routingStatus)
- .map(RoutingStatus::value)
- .allMatch(status -> status == RoutingStatus.Value.in));
+ assertTrue(policies.asList().stream()
+ .map(RoutingPolicy::status)
+ .map(RoutingPolicy.Status::routingStatus)
+ .map(RoutingStatus::value)
+ .allMatch(status -> status == RoutingStatus.Value.in),
+ "Global routing status for policy remains " + RoutingStatus.Value.in);
}
var changedAt = tester.controllerTester().clock().instant();
var zonePolicy = tester.controllerTester().controller().curator().readZoneRoutingPolicy(zone2);
@@ -604,7 +605,7 @@ public class RoutingPoliciesTest {
}
@Test
- public void non_production_deployment_is_not_registered_in_global_endpoint() {
+ void non_production_deployment_is_not_registered_in_global_endpoint() {
var tester = new RoutingPoliciesTester(SystemName.Public);
// Configure the system to use the same region for test, staging and prod
@@ -634,7 +635,7 @@ public class RoutingPoliciesTest {
}
@Test
- public void changing_global_routing_status_never_removes_all_members() {
+ void changing_global_routing_status_never_removes_all_members() {
var tester = new RoutingPoliciesTester();
var context = tester.newDeploymentContext("tenant1", "app1", "default");
@@ -652,20 +653,20 @@ public class RoutingPoliciesTest {
// Global routing status is overridden for one deployment
tester.routingPolicies().setRoutingStatus(context.deploymentIdIn(zone1), RoutingStatus.Value.out,
- RoutingStatus.Agent.tenant);
+ RoutingStatus.Agent.tenant);
context.flushDnsUpdates();
tester.assertTargets(context.instanceId(), EndpointId.of("r0"), 0, zone2);
// Setting other deployment out implicitly sets all deployments in. Weight is set to zero, but that has no
// impact on routing decisions when the weight sum is zero
tester.routingPolicies().setRoutingStatus(context.deploymentIdIn(zone2), RoutingStatus.Value.out,
- RoutingStatus.Agent.tenant);
+ RoutingStatus.Agent.tenant);
context.flushDnsUpdates();
tester.assertTargets(context.instanceId(), EndpointId.of("r0"), 0, ImmutableMap.of(zone1, 0L, zone2, 0L));
// One inactive deployment is put back in. Global DNS record now points to the only active deployment
tester.routingPolicies().setRoutingStatus(context.deploymentIdIn(zone1), RoutingStatus.Value.in,
- RoutingStatus.Agent.tenant);
+ RoutingStatus.Agent.tenant);
context.flushDnsUpdates();
tester.assertTargets(context.instanceId(), EndpointId.of("r0"), 0, zone1);
@@ -682,7 +683,7 @@ public class RoutingPoliciesTest {
// Inactive deployment is set in
tester.routingPolicies().setRoutingStatus(context.deploymentIdIn(zone2), RoutingStatus.Value.in,
- RoutingStatus.Agent.tenant);
+ RoutingStatus.Agent.tenant);
context.flushDnsUpdates();
for (var policy : tester.routingPolicies().read(context.instanceId())) {
assertSame(RoutingStatus.Value.in, policy.status().routingStatus().value());
@@ -691,7 +692,7 @@ public class RoutingPoliciesTest {
}
@Test
- public void application_endpoint_routing_policy() {
+ void application_endpoint_routing_policy() {
RoutingPoliciesTester tester = new RoutingPoliciesTester();
TenantAndApplicationId application = TenantAndApplicationId.from("tenant1", "app1");
ApplicationId betaInstance = application.instance("beta");
@@ -704,11 +705,11 @@ public class RoutingPoliciesTest {
.region(zone1.region())
.region(zone2.region())
.applicationEndpoint("a0", "c0", "us-west-1",
- Map.of(betaInstance.instance(), 2,
- mainInstance.instance(), 8))
+ Map.of(betaInstance.instance(), 2,
+ mainInstance.instance(), 8))
.applicationEndpoint("a1", "c1", "us-central-1",
- Map.of(betaInstance.instance(), 4,
- mainInstance.instance(), 6))
+ Map.of(betaInstance.instance(), 4,
+ mainInstance.instance(), 6))
.build();
for (var zone : List.of(zone1, zone2)) {
tester.provisionLoadBalancers(2, betaInstance, zone);
@@ -724,11 +725,11 @@ public class RoutingPoliciesTest {
DeploymentId betaZone2 = betaContext.deploymentIdIn(zone2);
DeploymentId mainZone2 = mainContext.deploymentIdIn(zone2);
tester.assertTargets(application, EndpointId.of("a0"), ClusterSpec.Id.from("c0"), 0,
- Map.of(betaZone1, 2,
- mainZone1, 8));
+ Map.of(betaZone1, 2,
+ mainZone1, 8));
tester.assertTargets(application, EndpointId.of("a1"), ClusterSpec.Id.from("c1"), 1,
- Map.of(betaZone2, 4,
- mainZone2, 6));
+ Map.of(betaZone2, 4,
+ mainZone2, 6));
// Weights are updated
applicationPackage = applicationPackageBuilder()
@@ -736,19 +737,19 @@ public class RoutingPoliciesTest {
.region(zone1.region())
.region(zone2.region())
.applicationEndpoint("a0", "c0", "us-west-1",
- Map.of(betaInstance.instance(), 3,
- mainInstance.instance(), 7))
+ Map.of(betaInstance.instance(), 3,
+ mainInstance.instance(), 7))
.applicationEndpoint("a1", "c1", "us-central-1",
- Map.of(betaInstance.instance(), 1,
- mainInstance.instance(), 9))
+ Map.of(betaInstance.instance(), 1,
+ mainInstance.instance(), 9))
.build();
betaContext.submit(applicationPackage).deploy();
tester.assertTargets(application, EndpointId.of("a0"), ClusterSpec.Id.from("c0"), 0,
- Map.of(betaZone1, 3,
- mainZone1, 7));
+ Map.of(betaZone1, 3,
+ mainZone1, 7));
tester.assertTargets(application, EndpointId.of("a1"), ClusterSpec.Id.from("c1"), 1,
- Map.of(betaZone2, 1,
- mainZone2, 9));
+ Map.of(betaZone2, 1,
+ mainZone2, 9));
// An endpoint is removed
applicationPackage = applicationPackageBuilder()
@@ -756,21 +757,21 @@ public class RoutingPoliciesTest {
.region(zone1.region())
.region(zone2.region())
.applicationEndpoint("a0", "c0", "us-west-1",
- Map.of(betaInstance.instance(), 1))
+ Map.of(betaInstance.instance(), 1))
.build();
betaContext.submit(applicationPackage).deploy();
// Application endpoints now point to a single instance
tester.assertTargets(application, EndpointId.of("a0"), ClusterSpec.Id.from("c0"), 0,
- Map.of(betaZone1, 1));
- assertTrue("Endpoint removed",
- tester.controllerTester().controller().routing()
- .readDeclaredEndpointsOf(application)
- .named(EndpointId.of("a1")).isEmpty());
+ Map.of(betaZone1, 1));
+ assertTrue(tester.controllerTester().controller().routing()
+ .readDeclaredEndpointsOf(application)
+ .named(EndpointId.of("a1")).isEmpty(),
+ "Endpoint removed");
}
@Test
- public void application_endpoint_routing_status() {
+ void application_endpoint_routing_status() {
RoutingPoliciesTester tester = new RoutingPoliciesTester();
TenantAndApplicationId application = TenantAndApplicationId.from("tenant1", "app1");
ApplicationId betaInstance = application.instance("beta");
@@ -782,8 +783,8 @@ public class RoutingPoliciesTest {
.instances("beta,main")
.region(zone1.region())
.applicationEndpoint("a0", "c0", "us-west-1",
- Map.of(betaInstance.instance(), 2,
- mainInstance.instance(), 8))
+ Map.of(betaInstance.instance(), 2,
+ mainInstance.instance(), 8))
.build();
tester.provisionLoadBalancers(1, betaInstance, zone1);
tester.provisionLoadBalancers(1, mainInstance, zone1);
@@ -795,35 +796,35 @@ public class RoutingPoliciesTest {
DeploymentId betaZone1 = betaContext.deploymentIdIn(zone1);
DeploymentId mainZone1 = mainContext.deploymentIdIn(zone1);
tester.assertTargets(application, EndpointId.of("a0"), ClusterSpec.Id.from("c0"), 0,
- Map.of(betaZone1, 2,
- mainZone1, 8));
+ Map.of(betaZone1, 2,
+ mainZone1, 8));
// Changing routing status removes deployment from DNS
tester.routingPolicies().setRoutingStatus(mainZone1, RoutingStatus.Value.out, RoutingStatus.Agent.tenant);
betaContext.flushDnsUpdates();
tester.assertTargets(application, EndpointId.of("a0"), ClusterSpec.Id.from("c0"), 0,
- Map.of(betaZone1, 2));
+ Map.of(betaZone1, 2));
// Changing routing status for remaining deployment adds back all deployments, because removing all deployments
// puts all IN
tester.routingPolicies().setRoutingStatus(betaZone1, RoutingStatus.Value.out, RoutingStatus.Agent.tenant);
betaContext.flushDnsUpdates();
tester.assertTargets(application, EndpointId.of("a0"), ClusterSpec.Id.from("c0"), 0,
- Map.of(betaZone1, 2,
- mainZone1, 8));
+ Map.of(betaZone1, 2,
+ mainZone1, 8));
// Activating main deployment allows us to deactivate the beta deployment
tester.routingPolicies().setRoutingStatus(mainZone1, RoutingStatus.Value.in, RoutingStatus.Agent.tenant);
betaContext.flushDnsUpdates();
tester.assertTargets(application, EndpointId.of("a0"), ClusterSpec.Id.from("c0"), 0,
- Map.of(mainZone1, 8));
+ Map.of(mainZone1, 8));
// Activate all deployments again
tester.routingPolicies().setRoutingStatus(betaZone1, RoutingStatus.Value.in, RoutingStatus.Agent.tenant);
betaContext.flushDnsUpdates();
tester.assertTargets(application, EndpointId.of("a0"), ClusterSpec.Id.from("c0"), 0,
- Map.of(betaZone1, 2,
- mainZone1, 8));
+ Map.of(betaZone1, 2,
+ mainZone1, 8));
}
/** Returns an application package builder that satisfies requirements for a directly routed endpoint */
@@ -951,20 +952,21 @@ public class RoutingPoliciesTest {
.named(endpointId)
.targets(deployment)
.cluster(cluster);
- assertEquals("Expected a single endpoint with ID '" + endpointId + "'", 1,
- applicationEndpoints.size());
+ assertEquals(1,
+ applicationEndpoints.size(),
+ "Expected a single endpoint with ID '" + endpointId + "'");
String dnsName = applicationEndpoints.asList().get(0).dnsName();
deploymentsByDnsName.computeIfAbsent(dnsName, (k) -> new ArrayList<>())
.add(deployment);
}
- assertEquals("Found " + endpointId + " for " + application, 1, deploymentsByDnsName.size());
+ assertEquals(1, deploymentsByDnsName.size(), "Found " + endpointId + " for " + application);
deploymentsByDnsName.forEach((dnsName, deployments) -> {
Set<String> weightedTargets = deployments.stream()
.map(d -> "weighted/lb-" + loadBalancerId + "--" +
d.applicationId().toFullString() + "--" + d.zoneId().value() +
"/dns-zone-1/" + d.zoneId().value() + "/" + deploymentWeights.get(d))
.collect(Collectors.toSet());
- assertEquals(dnsName + " has expected targets", weightedTargets, aliasDataOf(dnsName));
+ assertEquals(weightedTargets, aliasDataOf(dnsName), dnsName + " has expected targets");
});
}
@@ -988,9 +990,9 @@ public class RoutingPoliciesTest {
instance.toFullString() + "--" + z.value() +
"/dns-zone-1/" + z.value() + "/" + zoneWeights.get(z))
.collect(Collectors.toSet());
- assertEquals("Region endpoint " + regionEndpoint + " points to load balancer",
- weightedTargets,
- aliasDataOf(regionEndpoint));
+ assertEquals(weightedTargets,
+ aliasDataOf(regionEndpoint),
+ "Region endpoint " + regionEndpoint + " points to load balancer");
ZoneId zone = zonesInRegion.get(0);
String latencyTarget = "latency/" + regionEndpoint + "/dns-zone-1/" + zone.value();
latencyTargets.add(latencyTarget);
@@ -1002,8 +1004,7 @@ public class RoutingPoliciesTest {
.primary()
.map(Endpoint::dnsName)
.orElse("<none>");
- assertEquals("Global endpoint " + globalEndpoint + " points to expected latency targets",
- latencyTargets, Set.copyOf(aliasDataOf(globalEndpoint)));
+ assertEquals(latencyTargets, Set.copyOf(aliasDataOf(globalEndpoint)), "Global endpoint " + globalEndpoint + " points to expected latency targets");
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/routing/rotation/RotationRepositoryTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/routing/rotation/RotationRepositoryTest.java
index 277c8e1ef85..7477b94e3f4 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/routing/rotation/RotationRepositoryTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/routing/rotation/RotationRepositoryTest.java
@@ -13,7 +13,7 @@ import com.yahoo.vespa.hosted.controller.deployment.DeploymentContext;
import com.yahoo.vespa.hosted.controller.deployment.DeploymentTester;
import com.yahoo.vespa.hosted.controller.integration.ZoneApiMock;
import com.yahoo.vespa.hosted.rotation.config.RotationsConfig;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.util.List;
@@ -21,8 +21,8 @@ import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
-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 Oyvind Gronnesby
@@ -53,21 +53,21 @@ public class RotationRepositoryTest {
private final DeploymentContext application = tester.newDeploymentContext("tenant1", "app1", "default");
@Test
- public void assigns_and_reuses_rotation() {
+ void assigns_and_reuses_rotation() {
// Deploying assigns a rotation
application.submit(applicationPackage).deploy();
Rotation expected = new Rotation(new RotationId("foo-1"), "foo-1.com");
assertEquals(List.of(expected.id()), rotationIds(application.instance().rotations()));
assertEquals(URI.create("https://app1.tenant1.global.vespa.oath.cloud/"),
- tester.controller().routing().readDeclaredEndpointsOf(application.instanceId()).direct().first().get().url());
+ tester.controller().routing().readDeclaredEndpointsOf(application.instanceId()).direct().first().get().url());
try (RotationLock lock = repository.lock()) {
List<AssignedRotation> rotations = repository.getOrAssignRotations(application.application().deploymentSpec(),
- application.instance(),
- lock);
+ application.instance(),
+ lock);
assertSingleRotation(expected, rotations, repository);
assertEquals(Set.of(RegionName.from("us-west-1"), RegionName.from("us-east-3")),
- application.instance().rotations().get(0).regions());
+ application.instance().rotations().get(0).regions());
}
// Submitting once more assigns same rotation
@@ -83,12 +83,12 @@ public class RotationRepositoryTest {
.build();
application.submit(applicationPackage).deploy();
assertEquals(Set.of(RegionName.from("us-west-1"), RegionName.from("us-east-3"),
- RegionName.from("us-central-1")),
- application.instance().rotations().get(0).regions());
+ RegionName.from("us-central-1")),
+ application.instance().rotations().get(0).regions());
}
-
+
@Test
- public void strips_whitespace_in_rotation_fqdn() {
+ void strips_whitespace_in_rotation_fqdn() {
var tester = new DeploymentTester(new ControllerTester(rotationsConfigWhitespaces, SystemName.main));
RotationRepository repository = tester.controller().routing().rotations();
var application2 = tester.newDeploymentContext("tenant1", "app2", "default");
@@ -103,7 +103,7 @@ public class RotationRepositoryTest {
}
@Test
- public void out_of_rotations() {
+ void out_of_rotations() {
// Assigns 1 rotation
application.submit(applicationPackage).deploy();
@@ -114,11 +114,11 @@ public class RotationRepositoryTest {
// We're now out of rotations and next deployment fails
var application3 = tester.newDeploymentContext("tenant3", "app3", "default");
application3.submit(applicationPackage)
- .runJobExpectingFailure(DeploymentContext.systemTest, Optional.of("out of rotations"));
+ .runJobExpectingFailure(DeploymentContext.systemTest, Optional.of("out of rotations"));
}
@Test
- public void too_few_zones() {
+ void too_few_zones() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.globalServiceId("foo")
.region("us-east-3")
@@ -127,7 +127,7 @@ public class RotationRepositoryTest {
}
@Test
- public void no_rotation_assigned_for_application_without_service_id() {
+ void no_rotation_assigned_for_application_without_service_id() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.region("us-east-3")
.region("us-west-1")
@@ -137,7 +137,7 @@ public class RotationRepositoryTest {
}
@Test
- public void prefixes_system_when_not_main() {
+ void prefixes_system_when_not_main() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.globalServiceId("foo")
.region("cd-us-east-1")
@@ -150,18 +150,18 @@ public class RotationRepositoryTest {
ZoneApiMock.fromId("prod.cd-us-west-1"));
DeploymentTester tester = new DeploymentTester(new ControllerTester(rotationsConfig, SystemName.cd));
tester.controllerTester().zoneRegistry()
- .setZones(zones)
- .setRoutingMethod(zones, RoutingMethod.sharedLayer4);
+ .setZones(zones)
+ .setRoutingMethod(zones, RoutingMethod.sharedLayer4);
tester.configServer().bootstrap(tester.controllerTester().zoneRegistry().zones().all().ids(), SystemApplication.notController());
var application2 = tester.newDeploymentContext("tenant2", "app2", "default");
application2.submit(applicationPackage).deploy();
assertEquals(List.of(new RotationId("foo-1")), rotationIds(application2.instance().rotations()));
assertEquals("https://cd.app2.tenant2.global.vespa.oath.cloud/",
- tester.controller().routing().readDeclaredEndpointsOf(application2.instanceId()).primary().get().url().toString());
+ tester.controller().routing().readDeclaredEndpointsOf(application2.instanceId()).primary().get().url().toString());
}
@Test
- public void multiple_instances_with_similar_global_service_id() {
+ void multiple_instances_with_similar_global_service_id() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1,instance2")
.region("us-central-1")
@@ -169,19 +169,19 @@ public class RotationRepositoryTest {
.globalServiceId("global")
.build();
var instance1 = tester.newDeploymentContext("tenant1", "application1", "instance1")
- .submit(applicationPackage)
- .deploy();
+ .submit(applicationPackage)
+ .deploy();
var instance2 = tester.newDeploymentContext("tenant1", "application1", "instance2");
assertEquals(List.of(new RotationId("foo-1")), rotationIds(instance1.instance().rotations()));
assertEquals(List.of(new RotationId("foo-2")), rotationIds(instance2.instance().rotations()));
assertEquals(URI.create("https://instance1.application1.tenant1.global.vespa.oath.cloud/"),
- tester.controller().routing().readDeclaredEndpointsOf(instance1.instanceId()).direct().first().get().url());
+ tester.controller().routing().readDeclaredEndpointsOf(instance1.instanceId()).direct().first().get().url());
assertEquals(URI.create("https://instance2.application1.tenant1.global.vespa.oath.cloud/"),
- tester.controller().routing().readDeclaredEndpointsOf(instance2.instanceId()).direct().first().get().url());
+ tester.controller().routing().readDeclaredEndpointsOf(instance2.instanceId()).direct().first().get().url());
}
@Test
- public void multiple_instances_with_similar_endpoints() {
+ void multiple_instances_with_similar_endpoints() {
ApplicationPackage applicationPackage = new ApplicationPackageBuilder()
.instances("instance1,instance2")
.region("us-central-1")
@@ -189,17 +189,17 @@ public class RotationRepositoryTest {
.endpoint("default", "foo", "us-central-1", "us-west-1")
.build();
var instance1 = tester.newDeploymentContext("tenant1", "application1", "instance1")
- .submit(applicationPackage)
- .deploy();
+ .submit(applicationPackage)
+ .deploy();
var instance2 = tester.newDeploymentContext("tenant1", "application1", "instance2");
assertEquals(List.of(new RotationId("foo-1")), rotationIds(instance1.instance().rotations()));
assertEquals(List.of(new RotationId("foo-2")), rotationIds(instance2.instance().rotations()));
assertEquals(URI.create("https://instance1.application1.tenant1.global.vespa.oath.cloud/"),
- tester.controller().routing().readDeclaredEndpointsOf(instance1.instanceId()).direct().first().get().url());
+ tester.controller().routing().readDeclaredEndpointsOf(instance1.instanceId()).direct().first().get().url());
assertEquals(URI.create("https://instance2.application1.tenant1.global.vespa.oath.cloud/"),
- tester.controller().routing().readDeclaredEndpointsOf(instance2.instanceId()).direct().first().get().url());
+ tester.controller().routing().readDeclaredEndpointsOf(instance2.instanceId()).direct().first().get().url());
}
private void assertSingleRotation(Rotation expected, List<AssignedRotation> assignedRotations, RotationRepository repository) {
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/tls/SecureContainerTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/tls/SecureContainerTest.java
index de268f34093..05a0aedb18b 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/tls/SecureContainerTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/tls/SecureContainerTest.java
@@ -9,19 +9,19 @@ import com.yahoo.component.ComponentId;
import com.yahoo.security.KeyStoreBuilder;
import com.yahoo.security.KeyStoreType;
import com.yahoo.security.KeyStoreUtils;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+import java.io.File;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Path;
import java.security.KeyStore;
-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 mpolden
@@ -30,28 +30,28 @@ public class SecureContainerTest {
private JDisc container;
- @Rule
- public TemporaryFolder folder = new TemporaryFolder();
+ @TempDir
+ public File folder;
- @Before
+ @BeforeEach
public void startContainer() {
container = JDisc.fromServicesXml(servicesXml(writeKeyStore()), Networking.enable);
}
- @After
+ @AfterEach
public void stopContainer() {
container.close();
}
@Test
- public void test_https_request() {
- assertNotNull("SslContextFactoryProvider is created", sslContextFactoryProvider());
+ void test_https_request() {
+ assertNotNull(sslContextFactoryProvider(), "SslContextFactoryProvider is created");
assertResponse(Request.Method.GET, "/", 200);
}
private void assertResponse(Request.Method method, String path, int expectedStatusCode) {
Response response = container.handleRequest(new Request("https://localhost:9999" + path, new byte[0], method));
- assertEquals("Status code", expectedStatusCode, response.getStatus());
+ assertEquals(expectedStatusCode, response.getStatus(), "Status code");
}
private ControllerSslContextFactoryProvider sslContextFactoryProvider() {
@@ -83,7 +83,7 @@ public class SecureContainerTest {
Keys.keyPair.getPrivate(), new char[0], Keys.certificate)
.build();
try {
- Path path = folder.newFile().toPath();
+ Path path = File.createTempFile("junit", null, folder).toPath();
KeyStoreUtils.writeKeyStoreToFile(keyStore, path);
return path;
} catch (IOException e) {
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/versions/MavenRepositoryClientTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/versions/MavenRepositoryClientTest.java
index 25dd72ae622..33b1792accb 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/versions/MavenRepositoryClientTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/versions/MavenRepositoryClientTest.java
@@ -2,11 +2,11 @@
package com.yahoo.vespa.hosted.controller.versions;
import com.yahoo.vespa.hosted.controller.api.integration.maven.ArtifactId;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author jonmv
@@ -14,10 +14,10 @@ import static org.junit.Assert.assertEquals;
public class MavenRepositoryClientTest {
@Test
- public void testUri() {
+ void testUri() {
assertEquals(URI.create("https://domain:123/base/group/id/artifact-id/maven-metadata.xml"),
- MavenRepositoryClient.withArtifactPath(URI.create("https://domain:123/base/"),
- new ArtifactId("group.id", "artifact-id")));
+ MavenRepositoryClient.withArtifactPath(URI.create("https://domain:123/base/"),
+ new ArtifactId("group.id", "artifact-id")));
}
}
diff --git a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/versions/VersionStatusTest.java b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/versions/VersionStatusTest.java
index 7b045e508a9..18776be2dce 100644
--- a/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/versions/VersionStatusTest.java
+++ b/controller-server/src/test/java/com/yahoo/vespa/hosted/controller/versions/VersionStatusTest.java
@@ -22,7 +22,7 @@ import com.yahoo.vespa.hosted.controller.deployment.Run;
import com.yahoo.vespa.hosted.controller.persistence.CuratorDb;
import com.yahoo.vespa.hosted.controller.persistence.MockCuratorDb;
import com.yahoo.vespa.hosted.controller.versions.VespaVersion.Confidence;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
@@ -37,11 +37,11 @@ import static com.yahoo.vespa.hosted.controller.deployment.DeploymentContext.pro
import static com.yahoo.vespa.hosted.controller.deployment.DeploymentContext.stagingTest;
import static com.yahoo.vespa.hosted.controller.deployment.DeploymentContext.systemTest;
import static java.util.stream.Collectors.toSet;
-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.Assert.assertTrue;
+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.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Test computing of version status
@@ -100,8 +100,8 @@ public class VersionStatusTest {
writeControllerVersion(controller3, Version.fromString("6.2"), db);
VersionStatus versionStatus = VersionStatus.compute(tester.controller());
- assertEquals("Controller version is oldest version", Version.fromString("6.1"),
- versionStatus.controllerVersion().get().versionNumber());
+ assertEquals(Version.fromString("6.1"),
+ versionStatus.controllerVersion().get().versionNumber(), "Controller version is oldest version");
// Last controller upgrades
writeControllerVersion(controller2, Version.fromString("6.2"), db);
@@ -162,7 +162,7 @@ public class VersionStatusTest {
tester.triggerJobs();
tester.controllerTester().computeVersionStatus();
List<VespaVersion> versions = tester.controller().readVersionStatus().versions();
- assertEquals("The two versions above exist", 2, versions.size());
+ assertEquals(2, versions.size(), "The two versions above exist");
VespaVersion v1 = versions.get(0);
assertEquals(version1, v1.versionNumber());
@@ -178,9 +178,9 @@ public class VersionStatusTest {
context2.instanceId(), List.of(productionUsEast3),
context3.instanceId(), List.of(productionUsWest1, productionUsEast3)),
statistics1.productionSuccesses());
- assertEquals("No applications have active deployment jobs on version1.",
+ assertEquals(
List.of(),
- statistics1.runningUpgrade());
+ statistics1.runningUpgrade(), "No applications have active deployment jobs on version1.");
VespaVersion v2 = versions.get(1);
assertEquals(version2, v2.versionNumber());
@@ -203,13 +203,13 @@ public class VersionStatusTest {
}
private static void assertJobsRun(String assertion, Map<ApplicationId, List<JobType>> jobs, List<Run> runs) {
- assertEquals(assertion,
- jobs.entrySet().stream()
+ assertEquals(jobs.entrySet().stream()
.flatMap(entry -> entry.getValue().stream().map(type -> new JobId(entry.getKey(), type)))
.collect(toSet()),
runs.stream()
.map(run -> run.id().job())
- .collect(toSet()));
+ .collect(toSet()),
+ assertion);
}
@Test
@@ -273,8 +273,8 @@ public class VersionStatusTest {
// Application without deployment
var ignored0 = tester.newDeploymentContext("tenant1", "ignored0", "default");
- assertEquals("All applications running on this version: High",
- Confidence.high, confidence(tester.controller(), version0));
+ assertEquals(
+ Confidence.high, confidence(tester.controller(), version0), "All applications running on this version: High");
// New version is released
Version version1 = new Version("6.3");
@@ -288,25 +288,25 @@ public class VersionStatusTest {
.runJob(stagingTest)
.failDeployment(productionUsWest1);
tester.controllerTester().computeVersionStatus();
- assertEquals("One canary failed: Broken",
- Confidence.broken, confidence(tester.controller(), version1));
+ assertEquals(
+ Confidence.broken, confidence(tester.controller(), version1), "One canary failed: Broken");
// New version is released
Version version2 = new Version("6.4");
tester.controllerTester().upgradeSystem(version2);
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("Confidence defaults to low for version with no applications",
- Confidence.low, confidence(tester.controller(), version2));
+ assertEquals(
+ Confidence.low, confidence(tester.controller(), version2), "Confidence defaults to low for version with no applications");
// All canaries upgrade successfully
canary0.deployPlatform(version2);
canary1.deployPlatform(version2);
- assertEquals("Confidence for remains unchanged for version1: Broken",
- Confidence.broken, confidence(tester.controller(), version1));
- assertEquals("Nothing has failed but not all canaries have upgraded: Low",
- Confidence.low, confidence(tester.controller(), version2));
+ assertEquals(
+ Confidence.broken, confidence(tester.controller(), version1), "Confidence for remains unchanged for version1: Broken");
+ assertEquals(
+ Confidence.low, confidence(tester.controller(), version2), "Nothing has failed but not all canaries have upgraded: Low");
// Remaining canary upgrades to version2 which raises confidence to normal and more apps upgrade
canary2.triggerJobs().jobAborted(systemTest).jobAborted(stagingTest);
@@ -315,8 +315,8 @@ public class VersionStatusTest {
tester.controllerTester().computeVersionStatus();
tester.upgrader().maintain();
tester.triggerJobs();
- assertEquals("Canaries have upgraded: Normal",
- Confidence.normal, confidence(tester.controller(), version2));
+ assertEquals(
+ Confidence.normal, confidence(tester.controller(), version2), "Canaries have upgraded: Normal");
default0.deployPlatform(version2);
default1.deployPlatform(version2);
default2.deployPlatform(version2);
@@ -330,23 +330,23 @@ public class VersionStatusTest {
// Remember confidence across restart
tester.controllerTester().createNewController();
- assertEquals("Confidence remains unchanged for version0: High",
- Confidence.high, confidence(tester.controller(), version0));
- assertEquals("All canaries deployed + < 90% of defaults: Normal",
- Confidence.normal, confidence(tester.controller(), version2));
- assertTrue("Status for version without applications is removed",
- tester.controller().readVersionStatus().versions().stream()
- .noneMatch(vespaVersion -> vespaVersion.versionNumber().equals(version1)));
+ assertEquals(
+ Confidence.high, confidence(tester.controller(), version0), "Confidence remains unchanged for version0: High");
+ assertEquals(
+ Confidence.normal, confidence(tester.controller(), version2), "All canaries deployed + < 90% of defaults: Normal");
+ assertTrue(tester.controller().readVersionStatus().versions().stream()
+ .noneMatch(vespaVersion -> vespaVersion.versionNumber().equals(version1)),
+ "Status for version without applications is removed");
// Another default application upgrades, raising confidence to high
default8.deployPlatform(version2);
default9.deployPlatform(version2);
tester.controllerTester().computeVersionStatus();
- assertEquals("Confidence remains unchanged for version0: High",
- Confidence.high, confidence(tester.controller(), version0));
- assertEquals("90% of defaults deployed successfully: High",
- VespaVersion.Confidence.high, confidence(tester.controller(), version2));
+ assertEquals(
+ Confidence.high, confidence(tester.controller(), version0), "Confidence remains unchanged for version0: High");
+ assertEquals(
+ VespaVersion.Confidence.high, confidence(tester.controller(), version2), "90% of defaults deployed successfully: High");
// A new version is released, all canaries upgrade successfully, but enough "default" apps fail to mark version
// as broken
@@ -366,12 +366,12 @@ public class VersionStatusTest {
default3.failDeployment(stagingTest);
tester.controllerTester().computeVersionStatus();
- assertEquals("Confidence remains unchanged for version0: High",
- Confidence.high, confidence(tester.controller(), version0));
- assertEquals("Confidence remains unchanged for version2: High",
- Confidence.high, confidence(tester.controller(), version2));
- assertEquals("40% of defaults failed: Broken",
- VespaVersion.Confidence.broken, confidence(tester.controller(), version3));
+ assertEquals(
+ Confidence.high, confidence(tester.controller(), version0), "Confidence remains unchanged for version0: High");
+ assertEquals(
+ Confidence.high, confidence(tester.controller(), version2), "Confidence remains unchanged for version2: High");
+ assertEquals(
+ VespaVersion.Confidence.broken, confidence(tester.controller(), version3), "40% of defaults failed: Broken");
// Test version order
List<VespaVersion> versions = tester.controller().readVersionStatus().versions();
@@ -417,8 +417,8 @@ public class VersionStatusTest {
.submit(appPackage)
.deploy();
- assertEquals("All applications running on this version: High",
- Confidence.high, confidence(tester.controller(), version0));
+ assertEquals(
+ Confidence.high, confidence(tester.controller(), version0), "All applications running on this version: High");
// New version is released
Version version1 = new Version("6.3");
@@ -430,59 +430,61 @@ public class VersionStatusTest {
canary0.failDeployment(systemTest);
canary0.abortJob(stagingTest);
tester.controllerTester().computeVersionStatus();
- assertEquals("One canary failed: Broken",
- Confidence.broken, confidence(tester.controller(), version1));
+ assertEquals(
+ Confidence.broken, confidence(tester.controller(), version1), "One canary failed: Broken");
// New version is released
Version version2 = new Version("6.4");
tester.controllerTester().upgradeSystem(version2);
tester.upgrader().maintain();
- assertEquals("Confidence remains unchanged for version1 until app overrides old tests: Broken",
- Confidence.broken, confidence(tester.controller(), version1));
- assertEquals("Confidence defaults to low for version with no applications",
- Confidence.low, confidence(tester.controller(), version2));
+ assertEquals(
+ Confidence.broken, confidence(tester.controller(), version1), "Confidence remains unchanged for version1 until app overrides old tests: Broken");
+ assertEquals(
+ Confidence.low, confidence(tester.controller(), version2), "Confidence defaults to low for version with no applications");
assertEquals(version2, canary0.instance().change().platform().orElseThrow());
canary0.failDeployment(systemTest);
canary0.abortJob(stagingTest);
tester.controllerTester().computeVersionStatus();
- assertFalse("Previous version should be forgotten, as canary only had test jobs run on it",
- tester.controller().readVersionStatus().versions().stream().anyMatch(version -> version.versionNumber().equals(version1)));
+ assertFalse(
+ tester.controller().readVersionStatus().versions().stream().anyMatch(version -> version.versionNumber().equals(version1)),
+ "Previous version should be forgotten, as canary only had test jobs run on it");
// App succeeds with tests, but fails production deployment
canary0.runJob(systemTest)
.runJob(stagingTest)
.failDeployment(productionUsWest1);
- assertEquals("One canary failed: Broken",
- Confidence.broken, confidence(tester.controller(), version2));
+ assertEquals(
+ Confidence.broken, confidence(tester.controller(), version2), "One canary failed: Broken");
// A new version is released, and the app again fails production deployment.
Version version3 = new Version("6.5");
tester.controllerTester().upgradeSystem(version3);
tester.upgrader().maintain();
- assertEquals("Confidence remains unchanged for version2: Broken",
- Confidence.broken, confidence(tester.controller(), version2));
- assertEquals("Confidence defaults to low for version with no applications",
- Confidence.low, confidence(tester.controller(), version3));
+ assertEquals(
+ Confidence.broken, confidence(tester.controller(), version2), "Confidence remains unchanged for version2: Broken");
+ assertEquals(
+ Confidence.low, confidence(tester.controller(), version3), "Confidence defaults to low for version with no applications");
assertEquals(version3, canary0.instance().change().platform().orElseThrow());
canary0.runJob(systemTest)
.runJob(stagingTest)
.failDeployment(productionUsWest1);
tester.controllerTester().computeVersionStatus();
- assertEquals("Confidence remains unchanged for version2: Broken",
- Confidence.broken, confidence(tester.controller(), version2));
- assertEquals("Canary broken, so confidence for version3: Broken",
- Confidence.broken, confidence(tester.controller(), version3));
+ assertEquals(
+ Confidence.broken, confidence(tester.controller(), version2), "Confidence remains unchanged for version2: Broken");
+ assertEquals(
+ Confidence.broken, confidence(tester.controller(), version3), "Canary broken, so confidence for version3: Broken");
// App succeeds production deployment, clearing failure on version2
canary0.runJob(productionUsWest1);
tester.controllerTester().computeVersionStatus();
- assertFalse("Previous version should be forgotten, as canary only had test jobs run on it",
- tester.controller().readVersionStatus().versions().stream().anyMatch(version -> version.versionNumber().equals(version2)));
- assertEquals("Canary OK, but not done upgrading, so confidence for version3: Low",
- Confidence.low, confidence(tester.controller(), version3));
+ assertFalse(
+ tester.controller().readVersionStatus().versions().stream().anyMatch(version -> version.versionNumber().equals(version2)),
+ "Previous version should be forgotten, as canary only had test jobs run on it");
+ assertEquals(
+ Confidence.low, confidence(tester.controller(), version3), "Canary OK, but not done upgrading, so confidence for version3: Low");
}
@Test
@@ -512,8 +514,9 @@ public class VersionStatusTest {
assertEquals(Confidence.high, confidence(tester.controller(), version1));
// Stale override was removed
- assertFalse("Stale override removed", tester.controller().curator().readConfidenceOverrides()
- .containsKey(version0));
+ assertFalse( tester.controller().curator().readConfidenceOverrides()
+ .containsKey(version0),
+ "Stale override removed");
}
@Test
@@ -692,11 +695,11 @@ public class VersionStatusTest {
private void assertOnVersion(Version version, ApplicationId instance, DeploymentTester tester) {
var vespaVersion = tester.controller().readVersionStatus().version(version);
- assertNotNull("Statistics for version " + version + " exist", vespaVersion);
+ assertNotNull(vespaVersion, "Statistics for version " + version + " exist");
var statistics = DeploymentStatistics.compute(List.of(version), tester.deploymentStatuses()).get(0);
- assertTrue("Application is on version " + version,
+ assertTrue(
Stream.of(statistics.productionSuccesses(), statistics.failingUpgrades(), statistics.runningUpgrade())
- .anyMatch(runs -> runs.stream().anyMatch(run -> run.id().application().equals(instance))));
+ .anyMatch(runs -> runs.stream().anyMatch(run -> run.id().application().equals(instance))), "Application is on version " + version);
}
private static void writeControllerVersion(HostName hostname, Version version, CuratorDb db) {
diff --git a/flags/pom.xml b/flags/pom.xml
index 21206b160a6..0c268fbd644 100644
--- a/flags/pom.xml
+++ b/flags/pom.xml
@@ -56,19 +56,13 @@
</dependency>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
- <artifactId>hamcrest-junit</artifactId>
- <version>2.0.0.0</version>
+ <artifactId>hamcrest-library</artifactId>
<scope>test</scope>
</dependency>
<dependency>
@@ -76,17 +70,26 @@
<artifactId>testutil</artifactId>
<version>${project.version}</version>
<scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-core</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-library</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
- <dependency>
- <groupId>org.junit.vintage</groupId>
- <artifactId>junit-vintage-engine</artifactId>
- <scope>test</scope>
- </dependency>
</dependencies>
<build>
<plugins>
diff --git a/flags/src/main/java/com/yahoo/vespa/flags/Flags.java b/flags/src/main/java/com/yahoo/vespa/flags/Flags.java
index c6238149be1..7d10d643ec1 100644
--- a/flags/src/main/java/com/yahoo/vespa/flags/Flags.java
+++ b/flags/src/main/java/com/yahoo/vespa/flags/Flags.java
@@ -70,7 +70,7 @@ public class Flags {
public static final UnboundBooleanFlag KEEP_STORAGE_NODE_UP = defineFeatureFlag(
"keep-storage-node-up", true,
- List.of("hakonhall"), "2022-07-07", "2022-08-07",
+ List.of("hakonhall"), "2022-07-07", "2022-09-07",
"Whether to leave the storage node (with wanted state) UP while the node is permanently down.",
"Takes effect immediately for nodes transitioning to permanently down.",
ZONE_ID, APPLICATION_ID);
diff --git a/flags/src/test/java/com/yahoo/vespa/flags/FlagsTest.java b/flags/src/test/java/com/yahoo/vespa/flags/FlagsTest.java
index 3c022c1ddd2..3edde140de8 100644
--- a/flags/src/test/java/com/yahoo/vespa/flags/FlagsTest.java
+++ b/flags/src/test/java/com/yahoo/vespa/flags/FlagsTest.java
@@ -4,7 +4,7 @@ package com.yahoo.vespa.flags;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.node.BooleanNode;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.List;
@@ -12,11 +12,10 @@ import java.util.Objects;
import java.util.Optional;
import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.emptyOrNullString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
-import static org.hamcrest.Matchers.not;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
@@ -29,7 +28,7 @@ import static org.mockito.Mockito.when;
*/
public class FlagsTest {
@Test
- public void testBoolean() {
+ void testBoolean() {
final boolean defaultValue = false;
FlagSource source = mock(FlagSource.class);
BooleanFlag booleanFlag = Flags.defineFeatureFlag("id", defaultValue, List.of("owner"), "1970-01-01", "2100-01-01", "description",
@@ -45,8 +44,9 @@ public class FlagsTest {
ArgumentCaptor<FetchVector> vector = ArgumentCaptor.forClass(FetchVector.class);
verify(source).fetch(any(), vector.capture());
// hostname is set by default
- assertThat(vector.getValue().getValue(FetchVector.Dimension.HOSTNAME).isPresent(), is(true));
- assertThat(vector.getValue().getValue(FetchVector.Dimension.HOSTNAME).get(), is(not(emptyOrNullString())));
+ Optional<String> hostname = vector.getValue().getValue(FetchVector.Dimension.HOSTNAME);
+ assertTrue(hostname.isPresent());
+ assertFalse(hostname.get().isEmpty());
// zone is set because it was set on the unbound flag above
assertThat(vector.getValue().getValue(FetchVector.Dimension.ZONE_ID), is(Optional.of("a-zone")));
// application and node type are not set
@@ -66,41 +66,41 @@ public class FlagsTest {
}
@Test
- public void testString() {
+ void testString() {
testGeneric(Flags.defineStringFlag("string-id", "default value", List.of("owner"), "1970-01-01", "2100-01-01", "description",
- "modification effect", FetchVector.Dimension.ZONE_ID, FetchVector.Dimension.HOSTNAME),
- "other value");
+ "modification effect", FetchVector.Dimension.ZONE_ID, FetchVector.Dimension.HOSTNAME),
+ "other value");
}
@Test
- public void testInt() {
+ void testInt() {
testGeneric(Flags.defineIntFlag("int-id", 2, List.of("owner"), "1970-01-01", "2100-01-01", "desc", "mod"), 3);
}
@Test
- public void testLong() {
+ void testLong() {
testGeneric(Flags.defineLongFlag("long-id", 1L, List.of("owner"), "1970-01-01", "2100-01-01", "desc", "mod"), 2L);
}
@Test
- public void testDouble() {
+ void testDouble() {
testGeneric(Flags.defineDoubleFlag("double-id", 3.142, List.of("owner"), "1970-01-01", "2100-01-01", "desc", "mod"), 2.718);
}
@Test
- public void testList() {
+ void testList() {
testGeneric(Flags.defineListFlag("list-id", List.of("a"), String.class, List.of("owner"), "1970-01-01", "2100-01-01", "desc", "mod"), List.of("a", "b", "c"));
}
@Test
- public void testJacksonClass() {
+ void testJacksonClass() {
ExampleJacksonClass defaultInstance = new ExampleJacksonClass();
ExampleJacksonClass instance = new ExampleJacksonClass();
instance.integer = -2;
instance.string = "foo";
testGeneric(Flags.defineJacksonFlag("jackson-id", defaultInstance, ExampleJacksonClass.class,
- List.of("owner"), "1970-01-01", "2100-01-01", "description", "modification effect", FetchVector.Dimension.HOSTNAME),
+ List.of("owner"), "1970-01-01", "2100-01-01", "description", "modification effect", FetchVector.Dimension.HOSTNAME),
instance);
testGeneric(Flags.defineListFlag("jackson-list-id", List.of(defaultInstance), ExampleJacksonClass.class, List.of("owner"), "1970-01-01", "2100-01-01", "desc", "mod"),
diff --git a/flags/src/test/java/com/yahoo/vespa/flags/OrderedFlagSourceTest.java b/flags/src/test/java/com/yahoo/vespa/flags/OrderedFlagSourceTest.java
index dfd676b6472..6da994386a3 100644
--- a/flags/src/test/java/com/yahoo/vespa/flags/OrderedFlagSourceTest.java
+++ b/flags/src/test/java/com/yahoo/vespa/flags/OrderedFlagSourceTest.java
@@ -1,12 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.flags;
-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.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
@@ -18,7 +18,7 @@ import static org.mockito.Mockito.when;
*/
public class OrderedFlagSourceTest {
@Test
- public void test() {
+ void test() {
FlagSource source1 = mock(FlagSource.class);
FlagSource source2 = mock(FlagSource.class);
OrderedFlagSource orderedSource = new OrderedFlagSource(source1, source2);
diff --git a/flags/src/test/java/com/yahoo/vespa/flags/custom/ClusterCapacityTest.java b/flags/src/test/java/com/yahoo/vespa/flags/custom/ClusterCapacityTest.java
index 066955ee369..189e3fd79c9 100644
--- a/flags/src/test/java/com/yahoo/vespa/flags/custom/ClusterCapacityTest.java
+++ b/flags/src/test/java/com/yahoo/vespa/flags/custom/ClusterCapacityTest.java
@@ -2,15 +2,15 @@
package com.yahoo.vespa.flags.custom;
import com.fasterxml.jackson.databind.ObjectMapper;
-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;
public class ClusterCapacityTest {
@Test
- public void serialization() throws IOException {
+ void serialization() throws IOException {
ClusterCapacity clusterCapacity = new ClusterCapacity(7, 1.2, 3.4, 5.6, null);
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(clusterCapacity);
@@ -25,7 +25,7 @@ public class ClusterCapacityTest {
}
@Test
- public void serialization2() throws IOException {
+ void serialization2() throws IOException {
ClusterCapacity clusterCapacity = new ClusterCapacity(7, 1.2, 3.4, 5.6, 2.3);
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(clusterCapacity);
diff --git a/flags/src/test/java/com/yahoo/vespa/flags/custom/SharedHostTest.java b/flags/src/test/java/com/yahoo/vespa/flags/custom/SharedHostTest.java
index 852e1f9b7b1..1c8fbc41d35 100644
--- a/flags/src/test/java/com/yahoo/vespa/flags/custom/SharedHostTest.java
+++ b/flags/src/test/java/com/yahoo/vespa/flags/custom/SharedHostTest.java
@@ -2,22 +2,22 @@
package com.yahoo.vespa.flags.custom;
import com.fasterxml.jackson.databind.ObjectMapper;
-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.jupiter.api.Assertions.assertEquals;
public class SharedHostTest {
@Test
- public void serialization() throws IOException {
+ void serialization() throws IOException {
verifySerialization(new SharedHost(List.of(
new HostResources(1.0, 2.0, 3.0, 4.0, "fast", "remote",
- "container", 5, "x86_64")), 6));
+ "container", 5, "x86_64")), 6));
verifySerialization(new SharedHost(List.of(
new HostResources(1.0, 2.0, 3.0, 4.0, "fast", "remote",
- "admin", 5, "arm64")), null));
+ "admin", 5, "arm64")), null));
}
private void verifySerialization(SharedHost sharedHost) throws IOException {
diff --git a/flags/src/test/java/com/yahoo/vespa/flags/file/FlagDbFileTest.java b/flags/src/test/java/com/yahoo/vespa/flags/file/FlagDbFileTest.java
index f2d389188f9..884d44e12b6 100644
--- a/flags/src/test/java/com/yahoo/vespa/flags/file/FlagDbFileTest.java
+++ b/flags/src/test/java/com/yahoo/vespa/flags/file/FlagDbFileTest.java
@@ -6,8 +6,7 @@ import com.yahoo.vespa.flags.FlagId;
import com.yahoo.vespa.flags.json.FlagData;
import com.yahoo.vespa.test.file.TestFileSystem;
import org.hamcrest.collection.IsMapContaining;
-import org.hamcrest.collection.IsMapWithSize;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystem;
@@ -19,6 +18,8 @@ import java.util.Map;
import static com.yahoo.yolean.Exceptions.uncheck;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author hakonhall
@@ -28,7 +29,7 @@ public class FlagDbFileTest {
private final FlagDbFile flagDb = new FlagDbFile(fileSystem);
@Test
- public void test() {
+ void test() {
Map<FlagId, FlagData> dataMap = new HashMap<>();
FlagId id1 = new FlagId("id1");
FlagData data1 = new FlagData(id1, new FetchVector());
@@ -38,12 +39,12 @@ public class FlagDbFileTest {
dataMap.put(id2, data2);
// Non-existing directory => empty map
- assertThat(flagDb.read(), IsMapWithSize.anEmptyMap());
+ assertTrue(flagDb.read().isEmpty());
// sync() will create directory with map content
assertThat(flagDb.sync(dataMap), equalTo(true));
Map<FlagId, FlagData> readDataMap = flagDb.read();
- assertThat(readDataMap, IsMapWithSize.aMapWithSize(2));
+ assertEquals(2, readDataMap.size());
assertThat(readDataMap, IsMapContaining.hasKey(id1));
assertThat(readDataMap, IsMapContaining.hasKey(id2));
@@ -61,7 +62,7 @@ public class FlagDbFileTest {
dataMap.put(id3, data3);
assertThat(flagDb.sync(dataMap), equalTo(true));
Map<FlagId, FlagData> anotherReadDataMap = flagDb.read();
- assertThat(anotherReadDataMap, IsMapWithSize.aMapWithSize(2));
+ assertEquals(2, anotherReadDataMap.size());
assertThat(anotherReadDataMap, IsMapContaining.hasKey(id1));
assertThat(anotherReadDataMap, IsMapContaining.hasKey(id3));
assertThat(anotherReadDataMap.get(id1).serializeToJson(), equalTo("{\"id\":\"id1\",\"attributes\":{\"hostname\":\"h1\"}}"));
diff --git a/flags/src/test/java/com/yahoo/vespa/flags/json/ConditionTest.java b/flags/src/test/java/com/yahoo/vespa/flags/json/ConditionTest.java
index 677efd0fe1c..4da66bd5cc1 100644
--- a/flags/src/test/java/com/yahoo/vespa/flags/json/ConditionTest.java
+++ b/flags/src/test/java/com/yahoo/vespa/flags/json/ConditionTest.java
@@ -2,18 +2,18 @@
package com.yahoo.vespa.flags.json;
import com.yahoo.vespa.flags.FetchVector;
-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.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author hakonhall
*/
public class ConditionTest {
@Test
- public void testWhitelist() {
+ void testWhitelist() {
String hostname1 = "host1";
var params = new Condition.CreateParams(FetchVector.Dimension.HOSTNAME).withValues(hostname1);
Condition condition = WhitelistCondition.create(params);
@@ -24,7 +24,7 @@ public class ConditionTest {
}
@Test
- public void testBlacklist() {
+ void testBlacklist() {
String hostname1 = "host1";
var params = new Condition.CreateParams(FetchVector.Dimension.HOSTNAME).withValues(hostname1);
Condition condition = BlacklistCondition.create(params);
@@ -35,7 +35,7 @@ public class ConditionTest {
}
@Test
- public void testRelational() {
+ void testRelational() {
verifyVespaVersionFor("<", true, false, false);
verifyVespaVersionFor("<=", true, true, false);
verifyVespaVersionFor(">", false, false, true);
diff --git a/flags/src/test/java/com/yahoo/vespa/flags/json/FlagDataTest.java b/flags/src/test/java/com/yahoo/vespa/flags/json/FlagDataTest.java
index 5856cf99558..c89b5883fd1 100644
--- a/flags/src/test/java/com/yahoo/vespa/flags/json/FlagDataTest.java
+++ b/flags/src/test/java/com/yahoo/vespa/flags/json/FlagDataTest.java
@@ -3,13 +3,13 @@ package com.yahoo.vespa.flags.json;
import com.yahoo.vespa.flags.FetchVector;
import com.yahoo.vespa.flags.RawFlag;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author hakonhall
@@ -52,7 +52,7 @@ public class FlagDataTest {
private final FetchVector vector = new FetchVector();
@Test
- public void test() {
+ void test() {
// Second rule matches with the default zone matching
verify(Optional.of("false"), vector);
diff --git a/flags/src/test/java/com/yahoo/vespa/flags/json/SerializationTest.java b/flags/src/test/java/com/yahoo/vespa/flags/json/SerializationTest.java
index 35478768924..2cc19917793 100644
--- a/flags/src/test/java/com/yahoo/vespa/flags/json/SerializationTest.java
+++ b/flags/src/test/java/com/yahoo/vespa/flags/json/SerializationTest.java
@@ -5,23 +5,23 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.JsonNodeType;
import com.yahoo.vespa.flags.json.wire.WireCondition;
import com.yahoo.vespa.flags.json.wire.WireFlagData;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.Matchers.anEmptyMap;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author hakonhall
*/
public class SerializationTest {
@Test
- public void emptyJson() throws IOException {
+ void emptyJson() throws IOException {
String json = "{\"id\":\"id1\"}";
WireFlagData wireData = WireFlagData.deserialize(json);
assertThat(wireData.id, equalTo("id1"));
@@ -33,7 +33,7 @@ public class SerializationTest {
}
@Test
- public void deserialization() throws IOException {
+ void deserialization() throws IOException {
String json = "{\n" +
" \"id\": \"id2\",\n" +
" \"rules\": [\n" +
@@ -107,7 +107,7 @@ public class SerializationTest {
}
@Test
- public void jsonWithStrayFields() {
+ void jsonWithStrayFields() {
String json = "{\n" +
" \"id\": \"id3\",\n" +
" \"foo\": true,\n" +
@@ -136,7 +136,7 @@ public class SerializationTest {
assertThat(whitelistCondition.dimension, equalTo("zone"));
assertThat(whitelistCondition.values, nullValue());
assertThat(wireData.rules.get(0).value, nullValue());
- assertThat(wireData.defaultFetchVector, anEmptyMap());
+ assertTrue(wireData.defaultFetchVector.isEmpty());
assertThat(wireData.serializeToJson(), equalTo("{\"id\":\"id3\",\"rules\":[{\"conditions\":[{\"type\":\"whitelist\",\"dimension\":\"zone\"}]}],\"attributes\":{}}"));
diff --git a/hosted-zone-api/pom.xml b/hosted-zone-api/pom.xml
index 87012df8479..4227d457c4d 100644
--- a/hosted-zone-api/pom.xml
+++ b/hosted-zone-api/pom.xml
@@ -25,14 +25,25 @@
<artifactId>jdisc_core</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
-
- <!-- test -->
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
+ </dependency>
+
+ <!-- test -->
</dependencies>
<build>
<plugins>
diff --git a/hosted-zone-api/src/test/java/ai/vespa/cloud/SystemInfoTest.java b/hosted-zone-api/src/test/java/ai/vespa/cloud/SystemInfoTest.java
index 80b22a185bb..2bae9f0c9e2 100644
--- a/hosted-zone-api/src/test/java/ai/vespa/cloud/SystemInfoTest.java
+++ b/hosted-zone-api/src/test/java/ai/vespa/cloud/SystemInfoTest.java
@@ -1,12 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package ai.vespa.cloud;
-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;
/**
* @author bratseth
@@ -14,7 +14,7 @@ import static org.junit.Assert.fail;
public class SystemInfoTest {
@Test
- public void testSystemInfo() {
+ void testSystemInfo() {
ApplicationId application = new ApplicationId("tenant1", "application1", "instance1");
Zone zone = new Zone(Environment.dev, "us-west-1");
Cloud cloud = new Cloud("aws");
@@ -30,7 +30,7 @@ public class SystemInfoTest {
}
@Test
- public void testZone() {
+ void testZone() {
Zone zone = Zone.from("dev.us-west-1");
zone = Zone.from(zone.toString());
assertEquals(Environment.dev, zone.environment());
@@ -58,7 +58,7 @@ public class SystemInfoTest {
}
@Test
- public void testCluster() {
+ void testCluster() {
int size = 1;
var indices = List.of(1);
Cluster cluster = new Cluster(size, indices);
@@ -67,7 +67,7 @@ public class SystemInfoTest {
}
@Test
- public void testNode() {
+ void testNode() {
int index = 0;
Node node = new Node(index);
assertEquals(index, node.index());
diff --git a/http-utils/pom.xml b/http-utils/pom.xml
index 5b26235b62e..6cb6cd018c8 100644
--- a/http-utils/pom.xml
+++ b/http-utils/pom.xml
@@ -50,8 +50,13 @@
<!-- test scope -->
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
diff --git a/http-utils/src/test/java/ai/vespa/util/http/hc4/VespaHttpClientBuilderTest.java b/http-utils/src/test/java/ai/vespa/util/http/hc4/VespaHttpClientBuilderTest.java
index cf80375611f..27819ff0117 100644
--- a/http-utils/src/test/java/ai/vespa/util/http/hc4/VespaHttpClientBuilderTest.java
+++ b/http-utils/src/test/java/ai/vespa/util/http/hc4/VespaHttpClientBuilderTest.java
@@ -7,9 +7,9 @@ import org.apache.http.HttpRequest;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.conn.routing.HttpRoutePlanner;
-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.mockito.Mockito.mock;
/**
@@ -18,17 +18,17 @@ import static org.mockito.Mockito.mock;
public class VespaHttpClientBuilderTest {
@Test
- public void route_planner_modifies_scheme_of_requests() throws HttpException {
+ void route_planner_modifies_scheme_of_requests() throws HttpException {
verifyProcessedUriMatchesExpectedOutput("http://dummyhostname:8080", "https://dummyhostname:8080");
}
@Test
- public void route_planer_handles_implicit_http_port() throws HttpException {
+ void route_planer_handles_implicit_http_port() throws HttpException {
verifyProcessedUriMatchesExpectedOutput("http://dummyhostname", "https://dummyhostname:80");
}
@Test
- public void route_planer_handles_https_port() throws HttpException {
+ void route_planer_handles_https_port() throws HttpException {
verifyProcessedUriMatchesExpectedOutput("http://dummyhostname:443", "https://dummyhostname:443");
}
diff --git a/http-utils/src/test/java/ai/vespa/util/http/hc4/retry/DelayedConnectionLevelRetryHandlerTest.java b/http-utils/src/test/java/ai/vespa/util/http/hc4/retry/DelayedConnectionLevelRetryHandlerTest.java
index bd034ab9ef2..0b83227d538 100644
--- a/http-utils/src/test/java/ai/vespa/util/http/hc4/retry/DelayedConnectionLevelRetryHandlerTest.java
+++ b/http-utils/src/test/java/ai/vespa/util/http/hc4/retry/DelayedConnectionLevelRetryHandlerTest.java
@@ -2,7 +2,7 @@
package ai.vespa.util.http.hc4.retry;
import org.apache.http.client.protocol.HttpClientContext;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.net.ssl.SSLException;
import java.io.IOException;
@@ -10,8 +10,8 @@ import java.net.ConnectException;
import java.time.Duration;
import java.util.Arrays;
-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;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -23,7 +23,7 @@ public class DelayedConnectionLevelRetryHandlerTest {
@SuppressWarnings("unchecked")
@Test
- public void retry_consumers_are_invoked() {
+ void retry_consumers_are_invoked() {
RetryConsumer<IOException> retryConsumer = (RetryConsumer<IOException>) mock(RetryConsumer.class);
RetryFailedConsumer<IOException> retryFailedConsumer = (RetryFailedConsumer<IOException>) mock(RetryFailedConsumer.class);
@@ -51,7 +51,7 @@ public class DelayedConnectionLevelRetryHandlerTest {
}
@Test
- public void retry_with_fixed_delay_sleeps_for_expected_duration() {
+ void retry_with_fixed_delay_sleeps_for_expected_duration() {
Sleeper sleeper = mock(Sleeper.class);
Duration delay = Duration.ofSeconds(2);
@@ -73,7 +73,7 @@ public class DelayedConnectionLevelRetryHandlerTest {
}
@Test
- public void retry_with_fixed_backoff_sleeps_for_expected_durations() {
+ void retry_with_fixed_backoff_sleeps_for_expected_durations() {
Sleeper sleeper = mock(Sleeper.class);
Duration startDelay = Duration.ofMillis(500);
@@ -100,7 +100,7 @@ public class DelayedConnectionLevelRetryHandlerTest {
}
@Test
- public void retries_for_listed_exceptions_until_max_retries_exceeded() {
+ void retries_for_listed_exceptions_until_max_retries_exceeded() {
int maxRetries = 2;
DelayedConnectionLevelRetryHandler handler = DelayedConnectionLevelRetryHandler.Builder
@@ -119,7 +119,7 @@ public class DelayedConnectionLevelRetryHandlerTest {
}
@Test
- public void does_not_retry_for_non_listed_exception() {
+ void does_not_retry_for_non_listed_exception() {
DelayedConnectionLevelRetryHandler handler = DelayedConnectionLevelRetryHandler.Builder
.withFixedDelay(Duration.ofSeconds(2), 2)
.retryForExceptions(Arrays.asList(SSLException.class, ConnectException.class))
diff --git a/http-utils/src/test/java/ai/vespa/util/http/hc4/retry/DelayedResponseLevelRetryHandlerTest.java b/http-utils/src/test/java/ai/vespa/util/http/hc4/retry/DelayedResponseLevelRetryHandlerTest.java
index adbc445de1a..374dee63019 100644
--- a/http-utils/src/test/java/ai/vespa/util/http/hc4/retry/DelayedResponseLevelRetryHandlerTest.java
+++ b/http-utils/src/test/java/ai/vespa/util/http/hc4/retry/DelayedResponseLevelRetryHandlerTest.java
@@ -7,15 +7,15 @@ import org.apache.http.HttpVersion;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.message.BasicStatusLine;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.Arrays;
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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@@ -26,7 +26,7 @@ public class DelayedResponseLevelRetryHandlerTest {
@Test
@SuppressWarnings("unchecked")
- public void retry_consumers_are_invoked() {
+ void retry_consumers_are_invoked() {
RetryConsumer<HttpResponse> retryConsumer = mock(RetryConsumer.class);
RetryFailedConsumer<HttpResponse> retryFailedConsumer = mock(RetryFailedConsumer.class);
@@ -53,7 +53,7 @@ public class DelayedResponseLevelRetryHandlerTest {
}
@Test
- public void retry_with_fixed_delay_sleeps_for_expected_duration() {
+ void retry_with_fixed_delay_sleeps_for_expected_duration() {
Duration delay = Duration.ofSeconds(2);
int maxRetries = 2;
@@ -71,7 +71,7 @@ public class DelayedResponseLevelRetryHandlerTest {
}
@Test
- public void retry_with_fixed_backoff_sleeps_for_expected_durations() {
+ void retry_with_fixed_backoff_sleeps_for_expected_durations() {
Duration startDelay = Duration.ofMillis(500);
Duration maxDelay = Duration.ofSeconds(5);
int maxRetries = 10;
@@ -90,12 +90,12 @@ public class DelayedResponseLevelRetryHandlerTest {
Duration.ofSeconds(5), Duration.ofSeconds(5), Duration.ofSeconds(5));
for (int i = 1; i <= lastExecutionCount; i++) {
handler.retryRequest(response, i, ctx);
- assertEquals(expectedIntervals.get(i-1).toMillis(), handler.getRetryInterval());
+ assertEquals(expectedIntervals.get(i - 1).toMillis(), handler.getRetryInterval());
}
}
@Test
- public void retries_for_listed_exceptions_until_max_retries_exceeded() {
+ void retries_for_listed_exceptions_until_max_retries_exceeded() {
int maxRetries = 2;
DelayedResponseLevelRetryHandler handler = DelayedResponseLevelRetryHandler.Builder
@@ -113,7 +113,7 @@ public class DelayedResponseLevelRetryHandlerTest {
}
@Test
- public void does_not_retry_for_non_listed_exception() {
+ void does_not_retry_for_non_listed_exception() {
DelayedResponseLevelRetryHandler handler = DelayedResponseLevelRetryHandler.Builder
.withFixedDelay(Duration.ofSeconds(2), 2)
.retryForStatusCodes(Arrays.asList(HttpStatus.SC_SERVICE_UNAVAILABLE, HttpStatus.SC_BAD_GATEWAY))
diff --git a/http-utils/src/test/java/ai/vespa/util/http/hc5/HttpToHttpsRoutePlannerTest.java b/http-utils/src/test/java/ai/vespa/util/http/hc5/HttpToHttpsRoutePlannerTest.java
index 78c413fba56..b20d801e39c 100644
--- a/http-utils/src/test/java/ai/vespa/util/http/hc5/HttpToHttpsRoutePlannerTest.java
+++ b/http-utils/src/test/java/ai/vespa/util/http/hc5/HttpToHttpsRoutePlannerTest.java
@@ -6,9 +6,9 @@ import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.protocol.HttpClientContext;
import org.apache.hc.core5.http.HttpException;
import org.apache.hc.core5.http.HttpHost;
-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 jonmv
@@ -18,7 +18,7 @@ public class HttpToHttpsRoutePlannerTest {
final HttpToHttpsRoutePlanner planner = new HttpToHttpsRoutePlanner();
@Test
- public void verifySchemeMustBeHttp() throws HttpException {
+ void verifySchemeMustBeHttp() throws HttpException {
try {
planner.determineRoute(new HttpHost("https", "host", 1), new HttpClientContext());
}
@@ -28,7 +28,7 @@ public class HttpToHttpsRoutePlannerTest {
}
@Test
- public void verifyPortMustBeSet() throws HttpException {
+ void verifyPortMustBeSet() throws HttpException {
try {
planner.determineRoute(new HttpHost("http", "host", -1), new HttpClientContext());
}
@@ -39,7 +39,7 @@ public class HttpToHttpsRoutePlannerTest {
@Test
- public void verifyProxyIsDisallowed() throws HttpException {
+ void verifyProxyIsDisallowed() throws HttpException {
HttpClientContext context = new HttpClientContext();
context.setRequestConfig(RequestConfig.custom().setProxy(new HttpHost("proxy")).build());
try {
@@ -51,9 +51,9 @@ public class HttpToHttpsRoutePlannerTest {
}
@Test
- public void verifySchemeIsRewritten() throws HttpException {
+ void verifySchemeIsRewritten() throws HttpException {
assertEquals(new HttpRoute(new HttpHost("https", "host", 1)),
- planner.determineRoute(new HttpHost("http", "host", 1), new HttpClientContext()));
+ planner.determineRoute(new HttpHost("http", "host", 1), new HttpClientContext()));
}
}
diff --git a/jdisc-security-filters/pom.xml b/jdisc-security-filters/pom.xml
index 475a8b7e3e9..a452327f6ff 100644
--- a/jdisc-security-filters/pom.xml
+++ b/jdisc-security-filters/pom.xml
@@ -19,9 +19,21 @@
<!-- provided -->
<dependency>
<groupId>com.yahoo.vespa</groupId>
+ <artifactId>configdefinitions</artifactId>
+ <version>${project.version}</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.yahoo.vespa</groupId>
<artifactId>container-dev</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>com.yahoo.vespa</groupId>
@@ -32,11 +44,6 @@
<!-- test -->
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
@@ -46,17 +53,6 @@
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
- <dependency>
- <groupId>org.junit.vintage</groupId>
- <artifactId>junit-vintage-engine</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>com.yahoo.vespa</groupId>
- <artifactId>testutil</artifactId>
- <version>${project.version}</version>
- <scope>test</scope>
- </dependency>
</dependencies>
<build>
diff --git a/jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filter/security/misc/SecurityHeadersResponseFilter.java b/jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filter/security/misc/SecurityHeadersResponseFilter.java
index 24cd9245b61..520e22de136 100644
--- a/jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filter/security/misc/SecurityHeadersResponseFilter.java
+++ b/jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filter/security/misc/SecurityHeadersResponseFilter.java
@@ -19,5 +19,6 @@ public class SecurityHeadersResponseFilter implements SecurityResponseFilter {
response.setHeader("Strict-Transport-Security", "max-age=31536000; includeSubDomains");
response.setHeader("X-Content-Type-Options", "nosniff");
response.setHeader("X-Frame-Options", "DENY");
+ response.setHeader("Referrer-Policy", "strict-origin-when-cross-origin");
}
}
diff --git a/jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filter/security/rule/RuleBasedRequestFilter.java b/jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filter/security/rule/RuleBasedRequestFilter.java
index dac4d3ee4d6..9fb709126bf 100644
--- a/jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filter/security/rule/RuleBasedRequestFilter.java
+++ b/jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filter/security/rule/RuleBasedRequestFilter.java
@@ -6,7 +6,8 @@ import com.yahoo.jdisc.Metric;
import com.yahoo.jdisc.Response;
import com.yahoo.jdisc.http.filter.DiscFilterRequest;
import com.yahoo.jdisc.http.filter.security.base.JsonSecurityRequestFilterBase;
-import com.yahoo.jdisc.http.filter.security.rule.RuleBasedFilterConfig.Rule.Action;
+import com.yahoo.vespa.config.jdisc.http.filter.RuleBasedFilterConfig;
+import com.yahoo.vespa.config.jdisc.http.filter.RuleBasedFilterConfig.Rule.Action;
import com.yahoo.restapi.Path;
import java.net.URI;
diff --git a/jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filter/security/rule/package-info.java b/jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filter/security/rule/package-info.java
deleted file mode 100644
index 73313c2c86d..00000000000
--- a/jdisc-security-filters/src/main/java/com/yahoo/jdisc/http/filter/security/rule/package-info.java
+++ /dev/null
@@ -1,8 +0,0 @@
-// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
-/**
- * @author bjorncs
- */
-@ExportPackage
-package com.yahoo.jdisc.http.filter.security.rule;
-
-import com.yahoo.osgi.annotation.ExportPackage; \ No newline at end of file
diff --git a/jdisc-security-filters/src/main/resources/configdefinitions/jdisc.http.filter.security.rule.rule-based-filter.def b/jdisc-security-filters/src/main/resources/configdefinitions/jdisc.http.filter.security.rule.rule-based-filter.def
index 1d0dcddfc31..d619f5ff735 100644
--- a/jdisc-security-filters/src/main/resources/configdefinitions/jdisc.http.filter.security.rule.rule-based-filter.def
+++ b/jdisc-security-filters/src/main/resources/configdefinitions/jdisc.http.filter.security.rule.rule-based-filter.def
@@ -1,4 +1,6 @@
# Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+# TODO: remove this def when oldest hosted model no longer uses it.
+
namespace=jdisc.http.filter.security.rule
dryrun bool default=false
diff --git a/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/athenz/AthenzAuthorizationFilterTest.java b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/athenz/AthenzAuthorizationFilterTest.java
index d74075831f1..752f1026f3d 100644
--- a/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/athenz/AthenzAuthorizationFilterTest.java
+++ b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/athenz/AthenzAuthorizationFilterTest.java
@@ -21,7 +21,7 @@ import com.yahoo.vespa.athenz.api.ZToken;
import com.yahoo.vespa.athenz.utils.AthenzIdentities;
import com.yahoo.vespa.athenz.zpe.AuthorizationResult;
import com.yahoo.vespa.athenz.zpe.Zpe;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.security.auth.x500.X500Principal;
import java.math.BigInteger;
@@ -39,10 +39,10 @@ import static com.yahoo.jdisc.http.filter.security.athenz.AthenzAuthorizationFil
import static com.yahoo.security.SignatureAlgorithm.SHA256_WITH_ECDSA;
import static com.yahoo.security.SubjectAlternativeName.Type.EMAIL;
import static com.yahoo.vespa.athenz.zpe.AuthorizationResult.Type;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
@@ -72,7 +72,7 @@ public class AthenzAuthorizationFilterTest {
private static final String REJECTED_METRIC_NAME = "jdisc.http.filter.athenz.rejected_requests";
@Test
- public void accepts_request_with_access_token() {
+ void accepts_request_with_access_token() {
AthenzAuthorizationFilter filter = createFilter(new AllowingZpe(), List.of());
MockResponseHandler responseHandler = new MockResponseHandler();
@@ -86,7 +86,7 @@ public class AthenzAuthorizationFilterTest {
}
@Test
- public void accepts_request_with_role_certificate() {
+ void accepts_request_with_role_certificate() {
AthenzAuthorizationFilter filter = createFilter(new AllowingZpe(), List.of());
MockResponseHandler responseHandler = new MockResponseHandler();
@@ -100,7 +100,7 @@ public class AthenzAuthorizationFilterTest {
}
@Test
- public void accepts_request_with_role_token() {
+ void accepts_request_with_role_token() {
AthenzAuthorizationFilter filter = createFilter(new AllowingZpe(), List.of());
MockResponseHandler responseHandler = new MockResponseHandler();
@@ -114,7 +114,7 @@ public class AthenzAuthorizationFilterTest {
}
@Test
- public void accepts_request_with_proxied_access_token() {
+ void accepts_request_with_proxied_access_token() {
Zpe zpe = mock(Zpe.class);
when(zpe.checkAccessAllowed(any(), any(), any(), any())).thenReturn(new AuthorizationResult(Type.ALLOW, ROLE));
when(zpe.checkAccessAllowed((AthenzAccessToken) any(), any(), any())).thenReturn(new AuthorizationResult(Type.ALLOW, ROLE));
@@ -135,7 +135,7 @@ public class AthenzAuthorizationFilterTest {
}
@Test
- public void accepts_request_with_access_token_and_matching_identity_certificate_with_proxy_support_enabled() {
+ void accepts_request_with_access_token_and_matching_identity_certificate_with_proxy_support_enabled() {
Zpe zpe = mock(Zpe.class);
when(zpe.checkAccessAllowed(any(), any(), any(), any())).thenReturn(new AuthorizationResult(Type.ALLOW, ROLE));
when(zpe.checkAccessAllowed((AthenzAccessToken) any(), any(), any())).thenReturn(new AuthorizationResult(Type.ALLOW, ROLE));
@@ -156,7 +156,7 @@ public class AthenzAuthorizationFilterTest {
}
@Test
- public void returns_forbidden_when_identity_certificate_has_unknown_proxy_identity() {
+ void returns_forbidden_when_identity_certificate_has_unknown_proxy_identity() {
Zpe zpe = mock(Zpe.class);
when(zpe.checkAccessAllowed(any(), any(), any(), any())).thenReturn(new AuthorizationResult(Type.DENY, ROLE));
when(zpe.checkAccessAllowed((AthenzAccessToken) any(), any(), any())).thenReturn(new AuthorizationResult(Type.DENY, ROLE));
@@ -174,7 +174,7 @@ public class AthenzAuthorizationFilterTest {
}
@Test
- public void returns_unauthorized_for_request_with_disabled_credential_type() {
+ void returns_unauthorized_for_request_with_disabled_credential_type() {
AthenzAuthorizationFilter filter =
createFilter(new AllowingZpe(), List.of(EnabledCredentials.ROLE_CERTIFICATE, EnabledCredentials.ACCESS_TOKEN));
@@ -188,7 +188,7 @@ public class AthenzAuthorizationFilterTest {
}
@Test
- public void returns_forbidden_for_credentials_rejected_by_zpe() {
+ void returns_forbidden_for_credentials_rejected_by_zpe() {
AthenzAuthorizationFilter filter = createFilter(new DenyingZpe(), List.of());
MockResponseHandler responseHandler = new MockResponseHandler();
@@ -200,7 +200,7 @@ public class AthenzAuthorizationFilterTest {
}
@Test
- public void reports_metrics_for_rejected_requests() {
+ void reports_metrics_for_rejected_requests() {
MetricMock metric = new MetricMock();
AthenzAuthorizationFilter filter = createFilter(new DenyingZpe(), List.of(), metric, null);
MockResponseHandler responseHandler = new MockResponseHandler();
@@ -211,7 +211,7 @@ public class AthenzAuthorizationFilterTest {
}
@Test
- public void reports_metrics_for_accepted_requests() {
+ void reports_metrics_for_accepted_requests() {
MetricMock metric = new MetricMock();
AthenzAuthorizationFilter filter = createFilter(new AllowingZpe(), List.of(EnabledCredentials.ACCESS_TOKEN), metric, null);
MockResponseHandler responseHandler = new MockResponseHandler();
@@ -222,7 +222,7 @@ public class AthenzAuthorizationFilterTest {
}
@Test
- public void ignores_access_token_if_client_has_role_certificate() {
+ void ignores_access_token_if_client_has_role_certificate() {
AthenzAuthorizationFilter filter = createFilter(new AllowingZpe(), List.of());
MockResponseHandler responseHandler = new MockResponseHandler();
@@ -238,7 +238,7 @@ public class AthenzAuthorizationFilterTest {
private void assertMetrics(MetricMock metric, String metricName, Map<String, String> dimensions) {
assertTrue(metric.addInvocations.keySet().contains(metricName));
SimpleMetricContext metricContext = metric.addInvocations.get(metricName);
- assertNotNull("Metric not found " + metricName, metricName);
+ assertNotNull(metricName, "Metric not found " + metricName);
for (Map.Entry<String, String> entry : dimensions.entrySet()) {
String dimensionName = entry.getKey();
String expected = entry.getValue();
diff --git a/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/athenz/AthenzPrincipalFilterTest.java b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/athenz/AthenzPrincipalFilterTest.java
index d670c969e5c..0b04993a723 100644
--- a/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/athenz/AthenzPrincipalFilterTest.java
+++ b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/athenz/AthenzPrincipalFilterTest.java
@@ -12,7 +12,7 @@ import com.yahoo.security.X509CertificateBuilder;
import com.yahoo.vespa.athenz.api.AthenzIdentity;
import com.yahoo.vespa.athenz.api.AthenzPrincipal;
import com.yahoo.vespa.athenz.api.AthenzUser;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.security.auth.x500.X500Principal;
import java.io.BufferedReader;
@@ -31,10 +31,10 @@ import static com.yahoo.security.SignatureAlgorithm.SHA256_WITH_ECDSA;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.joining;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -48,7 +48,7 @@ public class AthenzPrincipalFilterTest {
private static final X509Certificate CERTIFICATE = createSelfSignedCertificate(IDENTITY);
@Test
- public void missing_certificate_is_unauthorized() {
+ void missing_certificate_is_unauthorized() {
DiscFilterRequest request = createRequestMock();
when(request.getClientCertificateChain()).thenReturn(emptyList());
@@ -61,7 +61,7 @@ public class AthenzPrincipalFilterTest {
}
@Test
- public void certificate_is_accepted() {
+ void certificate_is_accepted() {
DiscFilterRequest request = createRequestMock();
when(request.getClientCertificateChain()).thenReturn(singletonList(CERTIFICATE));
@@ -81,7 +81,7 @@ public class AthenzPrincipalFilterTest {
@Test
- public void no_response_produced_when_passthrough_mode_is_enabled() {
+ void no_response_produced_when_passthrough_mode_is_enabled() {
DiscFilterRequest request = createRequestMock();
when(request.getClientCertificateChain()).thenReturn(emptyList());
diff --git a/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/base/JsonSecurityRequestFilterBaseTest.java b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/base/JsonSecurityRequestFilterBaseTest.java
index 0f5512a6ec5..34db051aa28 100644
--- a/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/base/JsonSecurityRequestFilterBaseTest.java
+++ b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/base/JsonSecurityRequestFilterBaseTest.java
@@ -6,13 +6,13 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import com.yahoo.container.jdisc.RequestHandlerTestDriver;
import com.yahoo.jdisc.Response;
import com.yahoo.jdisc.http.filter.DiscFilterRequest;
-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.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.Mockito.mock;
/**
@@ -23,7 +23,7 @@ public class JsonSecurityRequestFilterBaseTest {
private final ObjectMapper mapper = new ObjectMapper();
@Test
- public void filter_renders_errors_as_json() throws IOException {
+ void filter_renders_errors_as_json() throws IOException {
int statusCode = 403;
String message = "Forbidden";
DiscFilterRequest request = mock(DiscFilterRequest.class);
diff --git a/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/cors/CorsPreflightRequestFilterTest.java b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/cors/CorsPreflightRequestFilterTest.java
index ead816afdfd..b5b94d5a2c2 100644
--- a/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/cors/CorsPreflightRequestFilterTest.java
+++ b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/cors/CorsPreflightRequestFilterTest.java
@@ -8,16 +8,16 @@ import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.http.filter.DiscFilterRequest;
import com.yahoo.jdisc.http.filter.SecurityRequestFilter;
import com.yahoo.jdisc.http.filter.security.cors.CorsFilterConfig.Builder;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import static com.yahoo.jdisc.http.HttpRequest.Method.OPTIONS;
import static com.yahoo.jdisc.http.filter.security.cors.CorsLogic.ACCESS_CONTROL_HEADERS;
import static com.yahoo.jdisc.http.filter.security.cors.CorsLogic.ALLOW_ORIGIN_HEADER;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -29,28 +29,28 @@ import static org.mockito.Mockito.when;
public class CorsPreflightRequestFilterTest {
@Test
- public void any_options_request_yields_access_control_headers_in_response() {
+ void any_options_request_yields_access_control_headers_in_response() {
HeaderFields headers = doFilterRequest(newRequestFilter(), "http://any.origin");
ACCESS_CONTROL_HEADERS.keySet().forEach(
- header -> assertFalse("Empty header: " + header, headers.getFirst(header).isEmpty()));
+ header -> assertFalse(headers.getFirst(header).isEmpty(), "Empty header: " + header));
}
@Test
- public void allowed_request_origin_yields_allow_origin_header_in_response() {
+ void allowed_request_origin_yields_allow_origin_header_in_response() {
final String ALLOWED_ORIGIN = "http://allowed.origin";
HeaderFields headers = doFilterRequest(newRequestFilter(ALLOWED_ORIGIN), ALLOWED_ORIGIN);
assertEquals(ALLOWED_ORIGIN, headers.getFirst(ALLOW_ORIGIN_HEADER));
}
@Test
- public void allowed_wildcard_origin_yields_origin_header_in_response() {
+ void allowed_wildcard_origin_yields_origin_header_in_response() {
final String ALLOWED_ORIGIN = "http://allowed.origin";
HeaderFields headers = doFilterRequest(newRequestFilter("*"), ALLOWED_ORIGIN);
assertEquals(ALLOWED_ORIGIN, headers.getFirst(ALLOW_ORIGIN_HEADER));
}
@Test
- public void disallowed_request_origin_does_not_yield_allow_origin_header_in_response() {
+ void disallowed_request_origin_does_not_yield_allow_origin_header_in_response() {
HeaderFields headers = doFilterRequest(newRequestFilter("http://allowed.origin"), "http://disallowed.origin");
assertNull(headers.getFirst(ALLOW_ORIGIN_HEADER));
}
diff --git a/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/cors/CorsResponseFilterTest.java b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/cors/CorsResponseFilterTest.java
index e3a3568700c..7762fde1a72 100644
--- a/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/cors/CorsResponseFilterTest.java
+++ b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/cors/CorsResponseFilterTest.java
@@ -6,7 +6,7 @@ import com.yahoo.jdisc.http.filter.DiscFilterResponse;
import com.yahoo.jdisc.http.filter.RequestView;
import com.yahoo.jdisc.http.filter.SecurityResponseFilter;
import com.yahoo.jdisc.http.filter.security.cors.CorsFilterConfig.Builder;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
@@ -16,9 +16,9 @@ import java.util.Optional;
import static com.yahoo.jdisc.http.filter.security.cors.CorsLogic.ACCESS_CONTROL_HEADERS;
import static com.yahoo.jdisc.http.filter.security.cors.CorsLogic.ALLOW_ORIGIN_HEADER;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -29,27 +29,27 @@ import static org.mockito.Mockito.when;
public class CorsResponseFilterTest {
@Test
- public void any_request_yields_access_control_headers_in_response() {
+ void any_request_yields_access_control_headers_in_response() {
Map<String, String> headers = doFilterRequest(newResponseFilter(), "http://any.origin");
ACCESS_CONTROL_HEADERS.keySet().forEach(
- header -> assertFalse("Empty header: " + header, headers.get(header).isEmpty()));
+ header -> assertFalse(headers.get(header).isEmpty(), "Empty header: " + header));
}
@Test
- public void allowed_request_origin_yields_allow_origin_header_in_response() {
+ void allowed_request_origin_yields_allow_origin_header_in_response() {
final String ALLOWED_ORIGIN = "http://allowed.origin";
Map<String, String> headers = doFilterRequest(newResponseFilter(ALLOWED_ORIGIN), ALLOWED_ORIGIN);
assertEquals(ALLOWED_ORIGIN, headers.get(ALLOW_ORIGIN_HEADER));
}
@Test
- public void disallowed_request_origin_does_not_yield_allow_origin_header_in_response() {
+ void disallowed_request_origin_does_not_yield_allow_origin_header_in_response() {
Map<String, String> headers = doFilterRequest(newResponseFilter("http://allowed.origin"), "http://disallowed.origin");
assertNull(headers.get(ALLOW_ORIGIN_HEADER));
}
@Test
- public void any_request_origin_yields_allow_origin_header_in_response_when_wildcard_is_allowed() {
+ void any_request_origin_yields_allow_origin_header_in_response_when_wildcard_is_allowed() {
Map<String, String> headers = doFilterRequest(newResponseFilter("*"), "http://any.origin");
assertEquals("http://any.origin", headers.get(ALLOW_ORIGIN_HEADER));
}
diff --git a/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/misc/LocalhostFilterTest.java b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/misc/LocalhostFilterTest.java
index 676c3e23ad7..aaf6ebf1aee 100644
--- a/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/misc/LocalhostFilterTest.java
+++ b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/misc/LocalhostFilterTest.java
@@ -4,13 +4,13 @@ package com.yahoo.jdisc.http.filter.security.misc;
import com.yahoo.container.jdisc.RequestHandlerTestDriver;
import com.yahoo.jdisc.Response;
import com.yahoo.jdisc.http.filter.DiscFilterRequest;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.net.URI;
-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;
import static org.mockito.Mockito.when;
/**
@@ -20,7 +20,7 @@ import static org.mockito.Mockito.when;
public class LocalhostFilterTest {
@Test
- public void filter() {
+ void filter() {
// Reject from non-loopback
assertUnauthorized(createRequest("1.2.3.4", null));
diff --git a/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/misc/VespaTlsFilterTest.java b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/misc/VespaTlsFilterTest.java
index d1d74d30572..95bc1f92572 100644
--- a/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/misc/VespaTlsFilterTest.java
+++ b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/misc/VespaTlsFilterTest.java
@@ -9,7 +9,7 @@ import com.yahoo.security.KeyAlgorithm;
import com.yahoo.security.KeyUtils;
import com.yahoo.security.SignatureAlgorithm;
import com.yahoo.security.X509CertificateBuilder;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import javax.security.auth.x500.X500Principal;
@@ -21,14 +21,14 @@ import java.time.temporal.ChronoUnit;
import java.util.Collections;
import java.util.List;
-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;
import static org.mockito.Mockito.when;
public class VespaTlsFilterTest {
@Test
- public void testFilter() {
+ void testFilter() {
assertSuccess(createRequest(List.of(createCertificate())));
assertForbidden(createRequest(Collections.emptyList()));
}
diff --git a/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/rule/RuleBasedRequestFilterTest.java b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/rule/RuleBasedRequestFilterTest.java
index cfd0e80968f..4ad593efe82 100644
--- a/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/rule/RuleBasedRequestFilterTest.java
+++ b/jdisc-security-filters/src/test/java/com/yahoo/jdisc/http/filter/security/rule/RuleBasedRequestFilterTest.java
@@ -8,9 +8,9 @@ import com.yahoo.container.jdisc.RequestHandlerTestDriver.MockResponseHandler;
import com.yahoo.jdisc.Metric;
import com.yahoo.jdisc.Response;
import com.yahoo.jdisc.http.filter.DiscFilterRequest;
-import com.yahoo.jdisc.http.filter.security.rule.RuleBasedFilterConfig.DefaultRule;
-import com.yahoo.jdisc.http.filter.security.rule.RuleBasedFilterConfig.Rule;
-import com.yahoo.test.json.JsonTestHelper;
+import com.yahoo.vespa.config.jdisc.http.filter.RuleBasedFilterConfig;
+import com.yahoo.vespa.config.jdisc.http.filter.RuleBasedFilterConfig.DefaultRule;
+import com.yahoo.vespa.config.jdisc.http.filter.RuleBasedFilterConfig.Rule;
import org.junit.jupiter.api.Test;
import java.io.IOException;
@@ -237,7 +237,7 @@ class RuleBasedRequestFilterTest {
ObjectNode expectedJson = jsonMapper.createObjectNode();
expectedJson.put("message", expectedMessage).put("code", expectedCode);
JsonNode actualJson = jsonMapper.readTree(handler.readAll().getBytes());
- JsonTestHelper.assertJsonEquals(expectedJson, actualJson);
+ assertEquals(expectedJson, actualJson);
}
} \ No newline at end of file
diff --git a/jdisc_core/pom.xml b/jdisc_core/pom.xml
index 0ed5e17b2ba..0e261f9dbef 100644
--- a/jdisc_core/pom.xml
+++ b/jdisc_core/pom.xml
@@ -51,6 +51,30 @@
<artifactId>testutil</artifactId>
<version>${project.version}</version>
<scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-core</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-library</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
</dependency>
<dependency>
<groupId>aopalliance</groupId>
diff --git a/jdisc_core/src/main/java/com/yahoo/jdisc/core/ApplicationLoader.java b/jdisc_core/src/main/java/com/yahoo/jdisc/core/ApplicationLoader.java
index dc6ee180321..cdde43bb3c2 100644
--- a/jdisc_core/src/main/java/com/yahoo/jdisc/core/ApplicationLoader.java
+++ b/jdisc_core/src/main/java/com/yahoo/jdisc/core/ApplicationLoader.java
@@ -127,6 +127,7 @@ public class ApplicationLoader implements BootstrapLoader, ContainerActivator, C
@Override
public void start() throws Exception {
log.finer("Initializing application.");
+ watchdog.start();
Injector injector = guiceModules.activate();
Application app;
if (!appBundles.isEmpty()) {
diff --git a/jdisc_core/src/main/java/com/yahoo/jdisc/core/ContainerWatchdog.java b/jdisc_core/src/main/java/com/yahoo/jdisc/core/ContainerWatchdog.java
index c010eac02b5..f28d5ea2b26 100644
--- a/jdisc_core/src/main/java/com/yahoo/jdisc/core/ContainerWatchdog.java
+++ b/jdisc_core/src/main/java/com/yahoo/jdisc/core/ContainerWatchdog.java
@@ -1,18 +1,29 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.core;
+import com.yahoo.concurrent.Threads;
import com.yahoo.jdisc.Metric;
import com.yahoo.jdisc.statistics.ContainerWatchdogMetrics;
+import com.yahoo.lang.MutableInteger;
+import org.apache.felix.framework.BundleWiringImpl;
+import org.osgi.framework.Bundle;
+import java.lang.reflect.Field;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
+import java.util.Optional;
import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
+import java.util.logging.Level;
import java.util.logging.Logger;
/**
@@ -24,7 +35,7 @@ class ContainerWatchdog implements ContainerWatchdogMetrics, AutoCloseable {
static final Duration GRACE_PERIOD = Duration.ofMinutes(5);
static final Duration UPDATE_PERIOD = Duration.ofMinutes(5);
- static final Duration CHECK_PERIOD = Duration.ofSeconds(1);
+ static final Duration CONTAINER_CHECK_PERIOD = Duration.ofSeconds(1);
private static final Logger log = Logger.getLogger(ContainerWatchdog.class.getName());
@@ -37,6 +48,9 @@ class ContainerWatchdog implements ContainerWatchdogMetrics, AutoCloseable {
private Instant currentContainerActivationTime;
private int numStaleContainers;
private Instant lastLogTime;
+ private ScheduledFuture<?> threadMonitoringTask;
+ private ScheduledFuture<?> containerMontoringTask;
+
ContainerWatchdog() {
this(new ScheduledThreadPoolExecutor(
@@ -53,7 +67,11 @@ class ContainerWatchdog implements ContainerWatchdogMetrics, AutoCloseable {
this.scheduler = scheduler;
this.clock = clock;
this.lastLogTime = clock.instant();
- scheduler.scheduleAtFixedRate(this::monitorDeactivatedContainers, CHECK_PERIOD.getSeconds(), CHECK_PERIOD.getSeconds(), TimeUnit.SECONDS);
+ }
+
+ void start() {
+ this.containerMontoringTask = scheduler.scheduleAtFixedRate(this::monitorDeactivatedContainers,
+ CONTAINER_CHECK_PERIOD.getSeconds(), CONTAINER_CHECK_PERIOD.getSeconds(), TimeUnit.SECONDS);
}
@Override
@@ -67,8 +85,8 @@ class ContainerWatchdog implements ContainerWatchdogMetrics, AutoCloseable {
@Override
public void close() throws InterruptedException {
- scheduler.shutdownNow();
- scheduler.awaitTermination(1, TimeUnit.MINUTES);
+ if (containerMontoringTask != null) containerMontoringTask.cancel(false);
+ if (threadMonitoringTask != null) threadMonitoringTask.cancel(false);
synchronized (monitor) {
deactivatedContainers.clear();
currentContainer = null;
@@ -83,6 +101,8 @@ class ContainerWatchdog implements ContainerWatchdogMetrics, AutoCloseable {
}
currentContainer = nextContainer;
currentContainerActivationTime = clock.instant();
+ if (threadMonitoringTask != null) threadMonitoringTask.cancel(false);
+ threadMonitoringTask = scheduler.schedule(this::monitorThreads, 1, TimeUnit.MINUTES);
}
}
@@ -126,6 +146,68 @@ class ContainerWatchdog implements ContainerWatchdogMetrics, AutoCloseable {
return clock.instant().isAfter(container.timeDeactivated.plus(GRACE_PERIOD));
}
+ private void monitorThreads() {
+ Collection<Thread> threads = Threads.getAllThreads();
+ warnOnThreadsHavingClassloaderFromUninstalledBundles(threads);
+ }
+
+ /**
+ * Detect and warn on threads leaked by defunct application components.
+ * These are threads launched by components of application bundles and not stopped after subsequent component deconstruction.
+ * The below algorithm is a heuristic and will not detect all leaked threads.
+ */
+ private void warnOnThreadsHavingClassloaderFromUninstalledBundles(Collection<Thread> threads) {
+ record ThreadDetails(Thread thread, Bundle bundle) {}
+ List<ThreadDetails> staleThreads = new ArrayList<>();
+ for (Thread t : threads) {
+ // Find threads which are sub-classes of java.lang.Thread from an uninstalled bundle
+ Bundle b = hasClassloaderForUninstalledBundle(t).orElse(null);
+ if (b != null) {
+ staleThreads.add(new ThreadDetails(t, b));
+ continue;
+ }
+ // Find threads which Runnable is a class from an uninstalled bundle
+ // This may create false positives
+ b = getTargetFieldOfThread(t).flatMap(ContainerWatchdog::hasClassloaderForUninstalledBundle).orElse(null);
+ if (b != null) {
+ staleThreads.add(new ThreadDetails(t, b));
+ }
+ // Note: no reliable mechanism for detecting threads owned by leaked executors (e.g. ScheduledThreadPoolExecutor)
+ }
+ if (!staleThreads.isEmpty()) {
+ StringBuilder msg = new StringBuilder(
+ ("Found %d stale threads that should have been stopped during previous reconfiguration(s). " +
+ "These threads have a classloader for a bundle that has been uninstalled: \n")
+ .formatted(staleThreads.size()));
+ MutableInteger i = new MutableInteger(1);
+ Comparator<ThreadDetails> outputOrdering =
+ Comparator.<ThreadDetails, Long>comparing(td -> td.bundle().getBundleId())
+ .thenComparing(td -> td.thread().getName()).thenComparing(td -> td.thread().getId());
+ staleThreads.stream().sorted(outputOrdering).forEach(t ->
+ msg.append("%d) Thread '%s' using bundle '%s'. \n"
+ .formatted(i.next(), t.thread().getName(), t.bundle().toString())));
+ log.log(Level.INFO, msg::toString); // Level 'info' until deemed reliable enough as 'warning'
+ }
+ }
+
+ private static Optional<Runnable> getTargetFieldOfThread(Thread t) {
+ try {
+ Field f = Thread.class.getDeclaredField("target");
+ f.setAccessible(true);
+ return Optional.ofNullable((Runnable)f.get(t));
+ } catch (ReflectiveOperationException e) {
+ return Optional.empty();
+ }
+ }
+
+ private static Optional<Bundle> hasClassloaderForUninstalledBundle(Object o) {
+ if (o.getClass().getClassLoader() instanceof BundleWiringImpl.BundleClassLoader cl) {
+ Bundle b = cl.getBundle();
+ if (b.getState() == Bundle.UNINSTALLED) return Optional.of(b);
+ }
+ return Optional.empty();
+ }
+
private static class DeactivatedContainer {
final ActiveContainer instance;
final Instant timeActivated;
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/AbstractResourceTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/AbstractResourceTestCase.java
index edde64c5e58..0de164ed693 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/AbstractResourceTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/AbstractResourceTestCase.java
@@ -1,12 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -14,7 +14,7 @@ import static org.junit.Assert.fail;
public class AbstractResourceTestCase {
@Test
- public void requireThatDestroyIsCalledWhenReleased() {
+ void requireThatDestroyIsCalledWhenReleased() {
MyResource res = new MyResource();
assertFalse(res.destroyed);
res.release();
@@ -22,7 +22,7 @@ public class AbstractResourceTestCase {
}
@Test
- public void requireThatDestroyIsCalledWhenRetainCountReachesZero() {
+ void requireThatDestroyIsCalledWhenRetainCountReachesZero() {
MyResource res = new MyResource();
assertEquals(1, res.retainCount());
assertFalse(res.destroyed);
@@ -37,7 +37,7 @@ public class AbstractResourceTestCase {
}
@Test
- public void requireThatDestroyIsCalledWhenRetainCountReachesZeroOppositeOrder() {
+ void requireThatDestroyIsCalledWhenRetainCountReachesZeroOppositeOrder() {
MyResource res = new MyResource();
assertEquals(1, res.retainCount());
assertFalse(res.destroyed);
@@ -52,7 +52,7 @@ public class AbstractResourceTestCase {
}
@Test
- public void requireThatReleaseCanOnlyBeCalledOnceEvenWhenReferenceCountIsPositive() {
+ void requireThatReleaseCanOnlyBeCalledOnceEvenWhenReferenceCountIsPositive() {
MyResource res = new MyResource();
final ResourceReference secondReference = res.refer();
res.release();
@@ -66,7 +66,7 @@ public class AbstractResourceTestCase {
}
@Test
- public void requireThatSecondaryReferenceCanOnlyBeClosedOnceEvenWhenReferenceCountIsPositive() {
+ void requireThatSecondaryReferenceCanOnlyBeClosedOnceEvenWhenReferenceCountIsPositive() {
MyResource res = new MyResource();
final ResourceReference secondReference = res.refer();
secondReference.close();
@@ -80,7 +80,7 @@ public class AbstractResourceTestCase {
}
@Test
- public void requireThatReleaseAfterDestroyThrows() {
+ void requireThatReleaseAfterDestroyThrows() {
MyResource res = new MyResource();
res.release();
assertTrue(res.destroyed);
@@ -101,7 +101,7 @@ public class AbstractResourceTestCase {
}
@Test
- public void requireThatReferAfterDestroyThrows() {
+ void requireThatReferAfterDestroyThrows() {
MyResource res = new MyResource();
res.release();
assertTrue(res.destroyed);
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/ContainerTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/ContainerTestCase.java
index 184f7b4d77d..2a4360be0d7 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/ContainerTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/ContainerTestCase.java
@@ -4,12 +4,12 @@ package com.yahoo.jdisc;
import com.google.inject.AbstractModule;
import com.yahoo.jdisc.service.BindingSetNotFoundException;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertSame;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
/**
@@ -18,7 +18,7 @@ import static org.junit.Assert.assertSame;
public class ContainerTestCase {
@Test
- public void requireThatNewRequestsReferenceSameSnapshot() throws Exception {
+ void requireThatNewRequestsReferenceSameSnapshot() throws Exception {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
driver.activateContainer(driver.newContainerBuilder());
Request foo = new Request(driver, URI.create("http://foo"));
@@ -31,7 +31,7 @@ public class ContainerTestCase {
}
@Test
- public void requireThatInjectionWorks() throws BindingSetNotFoundException {
+ void requireThatInjectionWorks() throws BindingSetNotFoundException {
final Object foo = new Object();
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi(new AbstractModule() {
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/HeaderFieldsTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/HeaderFieldsTestCase.java
index 2fa5700f87b..70de99b191b 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/HeaderFieldsTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/HeaderFieldsTestCase.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.jdisc;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collection;
@@ -11,12 +11,13 @@ import java.util.List;
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.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.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -25,7 +26,7 @@ import static org.junit.Assert.fail;
public class HeaderFieldsTestCase {
@Test
- public void requireThatSizeWorksAsExpected() {
+ void requireThatSizeWorksAsExpected() {
HeaderFields headers = new HeaderFields();
assertEquals(0, headers.size());
headers.add("foo", "bar");
@@ -41,7 +42,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatIsEmptyWorksAsExpected() {
+ void requireThatIsEmptyWorksAsExpected() {
HeaderFields headers = new HeaderFields();
assertTrue(headers.isEmpty());
headers.add("foo", "bar");
@@ -51,7 +52,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatContainsKeyWorksAsExpected() {
+ void requireThatContainsKeyWorksAsExpected() {
HeaderFields headers = new HeaderFields();
assertFalse(headers.containsKey("foo"));
assertFalse(headers.containsKey("FOO"));
@@ -61,7 +62,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatContainsValueWorksAsExpected() {
+ void requireThatContainsValueWorksAsExpected() {
HeaderFields headers = new HeaderFields();
assertFalse(headers.containsValue(Arrays.asList("bar")));
headers.add("foo", "bar");
@@ -69,7 +70,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatContainsWorksAsExpected() {
+ void requireThatContainsWorksAsExpected() {
HeaderFields headers = new HeaderFields();
assertFalse(headers.contains("foo", "bar"));
assertFalse(headers.contains("FOO", "bar"));
@@ -83,7 +84,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatContainsIgnoreCaseWorksAsExpected() {
+ void requireThatContainsIgnoreCaseWorksAsExpected() {
HeaderFields headers = new HeaderFields();
assertFalse(headers.containsIgnoreCase("foo", "bar"));
assertFalse(headers.containsIgnoreCase("FOO", "bar"));
@@ -97,7 +98,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatAddStringWorksAsExpected() {
+ void requireThatAddStringWorksAsExpected() {
HeaderFields headers = new HeaderFields();
assertNull(headers.get("foo"));
headers.add("foo", "bar");
@@ -107,7 +108,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatAddListWorksAsExpected() {
+ void requireThatAddListWorksAsExpected() {
HeaderFields headers = new HeaderFields();
assertNull(headers.get("foo"));
headers.add("foo", Arrays.asList("bar"));
@@ -117,7 +118,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatAddAllWorksAsExpected() {
+ void requireThatAddAllWorksAsExpected() {
HeaderFields headers = new HeaderFields();
headers.add("foo", "bar");
headers.add("bar", "baz");
@@ -134,7 +135,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatPutStringWorksAsExpected() {
+ void requireThatPutStringWorksAsExpected() {
HeaderFields headers = new HeaderFields();
assertNull(headers.get("foo"));
headers.put("foo", "bar");
@@ -144,7 +145,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatPutListWorksAsExpected() {
+ void requireThatPutListWorksAsExpected() {
HeaderFields headers = new HeaderFields();
assertNull(headers.get("foo"));
headers.put("foo", Arrays.asList("bar"));
@@ -154,7 +155,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatPutAllWorksAsExpected() {
+ void requireThatPutAllWorksAsExpected() {
HeaderFields headers = new HeaderFields();
headers.add("foo", "bar");
headers.add("bar", "baz");
@@ -171,7 +172,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatRemoveWorksAsExpected() {
+ void requireThatRemoveWorksAsExpected() {
HeaderFields headers = new HeaderFields();
headers.put("foo", Arrays.asList("bar", "baz"));
assertEquals(Arrays.asList("bar", "baz"), headers.get("foo"));
@@ -181,7 +182,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatRemoveStringWorksAsExpected() {
+ void requireThatRemoveStringWorksAsExpected() {
HeaderFields headers = new HeaderFields();
headers.put("foo", Arrays.asList("bar", "baz"));
assertEquals(Arrays.asList("bar", "baz"), headers.get("foo"));
@@ -194,7 +195,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatClearWorksAsExpected() {
+ void requireThatClearWorksAsExpected() {
HeaderFields headers = new HeaderFields();
headers.add("foo", "bar");
headers.add("bar", "baz");
@@ -206,7 +207,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatGetWorksAsExpected() {
+ void requireThatGetWorksAsExpected() {
HeaderFields headers = new HeaderFields();
assertNull(headers.get("foo"));
headers.add("foo", "bar");
@@ -214,7 +215,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatGetFirstWorksAsExpected() {
+ void requireThatGetFirstWorksAsExpected() {
HeaderFields headers = new HeaderFields();
assertNull(headers.getFirst("foo"));
headers.add("foo", Arrays.asList("bar", "baz"));
@@ -222,7 +223,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatIsTrueWorksAsExpected() {
+ void requireThatIsTrueWorksAsExpected() {
HeaderFields headers = new HeaderFields();
assertFalse(headers.isTrue("foo"));
headers.put("foo", Arrays.asList("true"));
@@ -240,7 +241,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatKeySetWorksAsExpected() {
+ void requireThatKeySetWorksAsExpected() {
HeaderFields headers = new HeaderFields();
assertTrue(headers.keySet().isEmpty());
headers.add("foo", "bar");
@@ -250,7 +251,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatValuesWorksAsExpected() {
+ void requireThatValuesWorksAsExpected() {
HeaderFields headers = new HeaderFields();
assertTrue(headers.values().isEmpty());
headers.add("foo", "bar");
@@ -266,7 +267,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatEntrySetWorksAsExpected() {
+ void requireThatEntrySetWorksAsExpected() {
HeaderFields headers = new HeaderFields();
assertTrue(headers.entrySet().isEmpty());
headers.put("foo", Arrays.asList("bar", "baz"));
@@ -280,7 +281,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatEntriesWorksAsExpected() {
+ void requireThatEntriesWorksAsExpected() {
HeaderFields headers = new HeaderFields();
assertTrue(headers.entries().isEmpty());
headers.put("foo", Arrays.asList("bar", "baz"));
@@ -299,7 +300,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatEntryIsUnmodifiable() {
+ void requireThatEntryIsUnmodifiable() {
HeaderFields headers = new HeaderFields();
headers.put("foo", "bar");
Map.Entry<String, String> entry = headers.entries().get(0);
@@ -312,7 +313,7 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatEntriesAreUnmodifiable() {
+ void requireThatEntriesAreUnmodifiable() {
HeaderFields headers = new HeaderFields();
headers.put("foo", "bar");
List<Map.Entry<String, String>> entries = headers.entries();
@@ -331,25 +332,25 @@ public class HeaderFieldsTestCase {
}
@Test
- public void requireThatEqualsWorksAsExpected() {
+ void requireThatEqualsWorksAsExpected() {
HeaderFields lhs = new HeaderFields();
HeaderFields rhs = new HeaderFields();
- assertTrue(lhs.equals(rhs));
+ assertEquals(lhs, rhs);
lhs.add("foo", "bar");
- assertFalse(lhs.equals(rhs));
+ assertNotEquals(lhs, rhs);
rhs.add("foo", "bar");
- assertTrue(lhs.equals(rhs));
+ assertEquals(lhs, rhs);
}
@Test
- public void requireThatHashCodeWorksAsExpected() {
+ void requireThatHashCodeWorksAsExpected() {
HeaderFields lhs = new HeaderFields();
HeaderFields rhs = new HeaderFields();
- assertTrue(lhs.hashCode() == rhs.hashCode());
+ assertEquals(lhs.hashCode(), rhs.hashCode());
lhs.add("foo", "bar");
assertTrue(lhs.hashCode() != rhs.hashCode());
rhs.add("foo", "bar");
- assertTrue(lhs.hashCode() == rhs.hashCode());
+ assertEquals(lhs.hashCode(), rhs.hashCode());
}
private static class MyEntry implements Map.Entry<String, String> {
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/ProxyRequestHandlerTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/ProxyRequestHandlerTestCase.java
index 017db9d39da..c6b959e1c37 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/ProxyRequestHandlerTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/ProxyRequestHandlerTestCase.java
@@ -7,7 +7,7 @@ import com.yahoo.jdisc.handler.ContentChannel;
import com.yahoo.jdisc.handler.RequestHandler;
import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.nio.ByteBuffer;
@@ -16,13 +16,13 @@ import java.util.logging.Handler;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
-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.assertSame;
-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.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -31,7 +31,7 @@ import static org.junit.Assert.fail;
public class ProxyRequestHandlerTestCase {
@Test
- public void requireThatRequestHandlerIsProxied() {
+ void requireThatRequestHandlerIsProxied() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
MyRequestHandler requestHandler = MyRequestHandler.newEagerCompletion();
Request request = newRequest(driver, requestHandler);
@@ -54,7 +54,7 @@ public class ProxyRequestHandlerTestCase {
}
@Test
- public void requireThatRequestContentCompletedIsProxied() {
+ void requireThatRequestContentCompletedIsProxied() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
MyRequestHandler requestHandler = MyRequestHandler.newInstance();
Request request = newRequest(driver, requestHandler);
@@ -90,7 +90,7 @@ public class ProxyRequestHandlerTestCase {
}
@Test
- public void requireThatRequestContentFailedIsProxied() {
+ void requireThatRequestContentFailedIsProxied() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
MyRequestHandler requestHandler = MyRequestHandler.newInstance();
Request request = newRequest(driver, requestHandler);
@@ -128,7 +128,7 @@ public class ProxyRequestHandlerTestCase {
}
@Test
- public void requireThatNullRequestContentIsProxied() {
+ void requireThatNullRequestContentIsProxied() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
MyRequestHandler requestHandler = MyRequestHandler.newNullContent();
Request request = newRequest(driver, requestHandler);
@@ -140,7 +140,7 @@ public class ProxyRequestHandlerTestCase {
}
@Test
- public void requireThatRequestWriteCompletionCanOnlyBeCalledOnce() {
+ void requireThatRequestWriteCompletionCanOnlyBeCalledOnce() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
MyRequestHandler requestHandler = MyRequestHandler.newInstance();
Request request = newRequest(driver, requestHandler);
@@ -178,7 +178,7 @@ public class ProxyRequestHandlerTestCase {
}
@Test
- public void requireThatRequestCloseCompletionCanOnlyBeCalledOnce() {
+ void requireThatRequestCloseCompletionCanOnlyBeCalledOnce() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
MyRequestHandler requestHandler = MyRequestHandler.newInstance();
Request request = newRequest(driver, requestHandler);
@@ -214,7 +214,7 @@ public class ProxyRequestHandlerTestCase {
}
@Test
- public void requireThatResponseContentCompletedIsProxied() {
+ void requireThatResponseContentCompletedIsProxied() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
MyRequestHandler requestHandler = MyRequestHandler.newEagerCompletion();
Request request = newRequest(driver, requestHandler);
@@ -251,7 +251,7 @@ public class ProxyRequestHandlerTestCase {
}
@Test
- public void requireThatResponseContentFailedIsProxied() {
+ void requireThatResponseContentFailedIsProxied() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
MyRequestHandler requestHandler = MyRequestHandler.newEagerCompletion();
Request request = newRequest(driver, requestHandler);
@@ -290,7 +290,7 @@ public class ProxyRequestHandlerTestCase {
}
@Test
- public void requireThatNullResponseContentIsProxied() {
+ void requireThatNullResponseContentIsProxied() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
MyRequestHandler requestHandler = MyRequestHandler.newEagerCompletion();
Request request = newRequest(driver, requestHandler);
@@ -308,7 +308,7 @@ public class ProxyRequestHandlerTestCase {
}
@Test
- public void requireThatResponseWriteCompletionCanOnlyBeCalledOnce() {
+ void requireThatResponseWriteCompletionCanOnlyBeCalledOnce() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
MyRequestHandler requestHandler = MyRequestHandler.newEagerCompletion();
MyResponseHandler responseHandler = MyResponseHandler.newInstance();
@@ -347,7 +347,7 @@ public class ProxyRequestHandlerTestCase {
}
@Test
- public void requireThatResponseCloseCompletionCanOnlyBeCalledOnce() {
+ void requireThatResponseCloseCompletionCanOnlyBeCalledOnce() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
MyRequestHandler requestHandler = MyRequestHandler.newEagerCompletion();
MyResponseHandler responseHandler = MyResponseHandler.newInstance();
@@ -383,7 +383,7 @@ public class ProxyRequestHandlerTestCase {
}
@Test
- public void requireThatUncaughtCompletionFailureIsLogged() {
+ void requireThatUncaughtCompletionFailureIsLogged() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
MyRequestHandler requestHandler = MyRequestHandler.newInstance();
Request request = newRequest(driver, requestHandler);
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/ReferencedResourceTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/ReferencedResourceTestCase.java
index 9b42ea19c81..42fc772f28b 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/ReferencedResourceTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/ReferencedResourceTestCase.java
@@ -1,9 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertSame;
+import static org.junit.jupiter.api.Assertions.assertSame;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -13,7 +13,7 @@ import static org.mockito.Mockito.verify;
*/
public class ReferencedResourceTestCase {
@Test
- public void requireThatGettersMatchConstructor() {
+ void requireThatGettersMatchConstructor() {
final SharedResource resource = mock(SharedResource.class);
final ResourceReference reference = mock(ResourceReference.class);
final ReferencedResource<SharedResource> referencedResource = new ReferencedResource<>(resource, reference);
@@ -22,7 +22,7 @@ public class ReferencedResourceTestCase {
}
@Test
- public void requireThatCloseCallsReferenceClose() {
+ void requireThatCloseCallsReferenceClose() {
final SharedResource resource = mock(SharedResource.class);
final ResourceReference reference = mock(ResourceReference.class);
final ReferencedResource<SharedResource> referencedResource = new ReferencedResource<>(resource, reference);
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/ReferencesTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/ReferencesTestCase.java
index 7a561e7fc89..efe48e1e528 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/ReferencesTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/ReferencesTestCase.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.jdisc;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
@@ -12,7 +12,7 @@ import static org.mockito.Mockito.verify;
*/
public class ReferencesTestCase {
@Test
- public void requireThatFromResourceCallsReleaseOnResource() {
+ void requireThatFromResourceCallsReleaseOnResource() {
final SharedResource resource = mock(SharedResource.class);
final ResourceReference reference = References.fromResource(resource);
reference.close();
@@ -20,7 +20,7 @@ public class ReferencesTestCase {
}
@Test
- public void requireThatNoopReferenceCanBeCalledMultipleTimes() {
+ void requireThatNoopReferenceCanBeCalledMultipleTimes() {
References.NOOP_REFERENCE.close();
References.NOOP_REFERENCE.close();
}
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/RequestTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/RequestTestCase.java
index 0d665e297da..4b2bb327442 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/RequestTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/RequestTestCase.java
@@ -12,19 +12,19 @@ import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.service.BindingSetNotFoundException;
import com.yahoo.jdisc.service.CurrentContainer;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.concurrent.TimeUnit;
-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.assertSame;
-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.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -33,7 +33,7 @@ import static org.junit.Assert.fail;
public class RequestTestCase {
@Test
- public void requireThatAccessorsWork() throws BindingSetNotFoundException {
+ void requireThatAccessorsWork() throws BindingSetNotFoundException {
MyTimer timer = new MyTimer();
timer.currentTime = 69;
@@ -58,7 +58,7 @@ public class RequestTestCase {
}
@Test
- public void requireThatCancelWorks() {
+ void requireThatCancelWorks() {
MyTimer timer = new MyTimer();
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi(timer);
Request request = newRequest(driver);
@@ -70,7 +70,7 @@ public class RequestTestCase {
}
@Test
- public void requireThatDefaultTimeoutIsInfinite() {
+ void requireThatDefaultTimeoutIsInfinite() {
MyTimer timer = new MyTimer();
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi(timer);
Request request = newRequest(driver);
@@ -84,7 +84,7 @@ public class RequestTestCase {
}
@Test
- public void requireThatTimeRemainingUsesTimer() {
+ void requireThatTimeRemainingUsesTimer() {
MyTimer timer = new MyTimer();
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi(timer);
Request request = newRequest(driver);
@@ -93,14 +93,14 @@ public class RequestTestCase {
++timer.currentTime)
{
assertEquals(request.getTimeout(TimeUnit.MILLISECONDS) - timer.currentTime,
- request.timeRemaining(TimeUnit.MILLISECONDS).longValue());
+ request.timeRemaining(TimeUnit.MILLISECONDS).longValue());
}
request.release();
assertTrue(driver.close());
}
@Test
- public void requireThatTimeoutCausesCancel() {
+ void requireThatTimeoutCausesCancel() {
MyTimer timer = new MyTimer();
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi(timer);
Request request = newRequest(driver);
@@ -113,7 +113,7 @@ public class RequestTestCase {
}
@Test
- public void requireThatCancelIsTrueIfParentIsCancelled() {
+ void requireThatCancelIsTrueIfParentIsCancelled() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
Request parent = newRequest(driver);
Request child = new Request(parent, URI.create("http://localhost/"));
@@ -125,7 +125,7 @@ public class RequestTestCase {
}
@Test
- public void requireThatDestroyReleasesContainer() {
+ void requireThatDestroyReleasesContainer() {
final MyContainer container = new MyContainer();
Request request = new Request(new CurrentContainer() {
@@ -140,7 +140,7 @@ public class RequestTestCase {
}
@Test
- public void requireThatServerConnectResolvesToServerBinding() {
+ void requireThatServerConnectResolvesToServerBinding() {
MyContainer container = new MyContainer();
Request request = new Request(container, URI.create("http://localhost/"));
request.connect(new MyResponseHandler());
@@ -149,7 +149,7 @@ public class RequestTestCase {
}
@Test
- public void requireThatClientConnectResolvesToClientBinding() {
+ void requireThatClientConnectResolvesToClientBinding() {
MyContainer container = new MyContainer();
Request serverReq = new Request(container, URI.create("http://localhost/"));
Request clientReq = new Request(serverReq, URI.create("http://localhost/"));
@@ -159,7 +159,7 @@ public class RequestTestCase {
}
@Test
- public void requireThatNullTimeoutManagerThrowsException() {
+ void requireThatNullTimeoutManagerThrowsException() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
Request request = newRequest(driver);
@@ -175,7 +175,7 @@ public class RequestTestCase {
}
@Test
- public void requireThatTimeoutManagerCanNotBeReplaced() {
+ void requireThatTimeoutManagerCanNotBeReplaced() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
Request request = newRequest(driver);
@@ -193,7 +193,7 @@ public class RequestTestCase {
}
@Test
- public void requireThatSetTimeoutCallsTimeoutManager() {
+ void requireThatSetTimeoutCallsTimeoutManager() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
Request request = newRequest(driver);
@@ -207,7 +207,7 @@ public class RequestTestCase {
}
@Test
- public void requireThatSetTimeoutManagerPropagatesCurrentTimeout() {
+ void requireThatSetTimeoutManagerPropagatesCurrentTimeout() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
Request request = newRequest(driver);
@@ -221,7 +221,7 @@ public class RequestTestCase {
}
@Test
- public void requireThatUriIsNormalized() {
+ void requireThatUriIsNormalized() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
driver.activateContainer(driver.newContainerBuilder());
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/ResponseTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/ResponseTestCase.java
index b3fbbceb06a..ec5079a31ab 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/ResponseTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/ResponseTestCase.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.jdisc;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -14,7 +14,7 @@ import static org.junit.Assert.assertTrue;
public class ResponseTestCase {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
Response response = new Response(69);
assertEquals(69, response.getStatus());
response.setStatus(96);
@@ -27,7 +27,7 @@ public class ResponseTestCase {
}
@Test
- public void requireThatStatusCodesDoNotChange() {
+ void requireThatStatusCodesDoNotChange() {
assertEquals(100, Response.Status.CONTINUE);
assertEquals(101, Response.Status.SWITCHING_PROTOCOLS);
assertEquals(102, Response.Status.PROCESSING);
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/application/AbstractApplicationTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/application/AbstractApplicationTestCase.java
index 3a6aa03ad45..03d5728679f 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/application/AbstractApplicationTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/application/AbstractApplicationTestCase.java
@@ -4,15 +4,15 @@ package com.yahoo.jdisc.application;
import com.google.inject.Inject;
import com.yahoo.jdisc.service.CurrentContainer;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
-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.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -21,27 +21,27 @@ import static org.junit.Assert.assertTrue;
public class AbstractApplicationTestCase {
@Test
- public void requireThatContainerApiIsAvailable() {
+ void requireThatContainerApiIsAvailable() {
TestDriver driver = TestDriver.newInjectedApplicationInstance(MyApplication.class);
- MyApplication app = (MyApplication)driver.application();
+ MyApplication app = (MyApplication) driver.application();
app.activateContainer(app.newContainerBuilder());
assertNotNull(app.container());
assertTrue(driver.close());
}
@Test
- public void requireThatDestroySignalsTermination() {
+ void requireThatDestroySignalsTermination() {
TestDriver driver = TestDriver.newInjectedApplicationInstance(MyApplication.class);
- MyApplication app = (MyApplication)driver.application();
+ MyApplication app = (MyApplication) driver.application();
assertFalse(app.isTerminated());
assertTrue(driver.close());
assertTrue(app.isTerminated());
}
@Test
- public void requireThatTerminationCanBeWaitedForWithTimeout() throws InterruptedException {
+ void requireThatTerminationCanBeWaitedForWithTimeout() throws InterruptedException {
TestDriver driver = TestDriver.newInjectedApplicationInstance(MyApplication.class);
- final MyApplication app = (MyApplication)driver.application();
+ final MyApplication app = (MyApplication) driver.application();
final CountDownLatch latch = new CountDownLatch(1);
Executors.newSingleThreadExecutor().execute(new Runnable() {
@@ -61,9 +61,9 @@ public class AbstractApplicationTestCase {
}
@Test
- public void requireThatTerminationCanBeWaitedForWithoutTimeout() throws InterruptedException {
+ void requireThatTerminationCanBeWaitedForWithoutTimeout() throws InterruptedException {
TestDriver driver = TestDriver.newInjectedApplicationInstance(MyApplication.class);
- final MyApplication app = (MyApplication)driver.application();
+ final MyApplication app = (MyApplication) driver.application();
final CountDownLatch latch = new CountDownLatch(1);
Executors.newSingleThreadExecutor().execute(new Runnable() {
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/application/ApplicationNotReadyTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/application/ApplicationNotReadyTestCase.java
index 63331d2014d..1ac091fcc68 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/application/ApplicationNotReadyTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/application/ApplicationNotReadyTestCase.java
@@ -4,11 +4,11 @@ package com.yahoo.jdisc.application;
import com.google.inject.Inject;
import com.google.inject.ProvisionException;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-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.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -17,7 +17,7 @@ import static org.junit.Assert.fail;
public class ApplicationNotReadyTestCase {
@Test
- public void requireThatExceptionIsThrown() {
+ void requireThatExceptionIsThrown() {
try {
TestDriver.newInjectedApplicationInstanceWithoutOsgi(MyApplication.class);
fail();
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/application/BindingMatchTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/application/BindingMatchTestCase.java
index 5c0942fbf37..7ea8e84228d 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/application/BindingMatchTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/application/BindingMatchTestCase.java
@@ -1,13 +1,13 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.application;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -16,7 +16,7 @@ import static org.junit.Assert.fail;
public class BindingMatchTestCase {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
Object obj = new Object();
UriPattern pattern = new UriPattern("http://*/*");
BindingMatch<Object> match = new BindingMatch<>(
@@ -31,7 +31,7 @@ public class BindingMatchTestCase {
}
@Test
- public void requireThatConstructorArgumentsCanNotBeNull() {
+ void requireThatConstructorArgumentsCanNotBeNull() {
try {
new BindingMatch<>(null, null, null);
fail();
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/application/BindingRepositoryTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/application/BindingRepositoryTestCase.java
index 95ba6cde595..92a85cfdc4a 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/application/BindingRepositoryTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/application/BindingRepositoryTestCase.java
@@ -7,19 +7,19 @@ import com.yahoo.jdisc.handler.ContentChannel;
import com.yahoo.jdisc.handler.RequestHandler;
import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.test.NonWorkingRequestHandler;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
-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.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.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -27,7 +27,7 @@ import static org.junit.Assert.fail;
public class BindingRepositoryTestCase {
@Test
- public void requireThatRepositoryCanBeActivated() {
+ void requireThatRepositoryCanBeActivated() {
BindingRepository<Object> bindings = new BindingRepository<>();
bindings.bind("http://host/path", new Object());
@@ -41,7 +41,7 @@ public class BindingRepositoryTestCase {
}
@Test
- public void requireThatActivationIsSnapshotOfRepository() {
+ void requireThatActivationIsSnapshotOfRepository() {
BindingRepository<Object> bindings = new BindingRepository<>();
bindings.bind("http://host/path", new Object());
@@ -57,7 +57,7 @@ public class BindingRepositoryTestCase {
}
@Test
- public void requireThatObjectsCanBeBound() {
+ void requireThatObjectsCanBeBound() {
BindingRepository<Object> bindings = new BindingRepository<>();
Object foo = new Object();
Object bar = new Object();
@@ -79,7 +79,7 @@ public class BindingRepositoryTestCase {
}
@Test
- public void requireThatPatternCannotBeStolen() {
+ void requireThatPatternCannotBeStolen() {
final String pattern = "http://host/path";
final RequestHandler originallyBoundHandler = new NonWorkingRequestHandler();
@@ -92,7 +92,7 @@ public class BindingRepositoryTestCase {
}
@Test
- public void requireThatBindAllMethodWorks() {
+ void requireThatBindAllMethodWorks() {
Object foo = new Object();
Object bar = new Object();
Object baz = new Object();
@@ -122,7 +122,7 @@ public class BindingRepositoryTestCase {
}
@Test
- public void requireThatPutAllMethodWorks() {
+ void requireThatPutAllMethodWorks() {
Object foo = new Object();
Object bar = new Object();
Object baz = new Object();
@@ -153,7 +153,7 @@ public class BindingRepositoryTestCase {
}
@Test
- public void requireThatPutNullThrowsException() {
+ void requireThatPutNullThrowsException() {
try {
new BindingRepository<>().put(null, new Object());
fail();
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/application/BindingSetTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/application/BindingSetTestCase.java
index 3b7d8aafcab..504810dc2ed 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/application/BindingSetTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/application/BindingSetTestCase.java
@@ -4,7 +4,7 @@ package com.yahoo.jdisc.application;
import com.yahoo.jdisc.handler.RequestHandler;
import com.yahoo.jdisc.test.NonWorkingRequestHandler;
import static com.yahoo.vespa.defaults.Defaults.getDefaults;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.util.ArrayList;
@@ -14,12 +14,12 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
-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.assertSame;
-import static org.junit.Assert.assertTrue;
+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.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -28,7 +28,7 @@ import static org.junit.Assert.assertTrue;
public class BindingSetTestCase {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
Map<UriPattern, RequestHandler> handlers = new LinkedHashMap<>();
RequestHandler foo = new NonWorkingRequestHandler();
handlers.put(new UriPattern("http://host/foo"), foo);
@@ -51,7 +51,7 @@ public class BindingSetTestCase {
}
@Test
- public void requireThatSimpleResolutionWorks() {
+ void requireThatSimpleResolutionWorks() {
Map<UriPattern, RequestHandler> handlers = new LinkedHashMap<>();
RequestHandler foo = new NonWorkingRequestHandler();
handlers.put(new UriPattern("http://host/foo"), foo);
@@ -72,7 +72,7 @@ public class BindingSetTestCase {
}
@Test
- public void requireThatPatternResolutionWorks() {
+ void requireThatPatternResolutionWorks() {
Map<UriPattern, RequestHandler> handlers = new LinkedHashMap<>();
RequestHandler foo = new NonWorkingRequestHandler();
handlers.put(new UriPattern("http://host/*"), foo);
@@ -94,7 +94,7 @@ public class BindingSetTestCase {
}
@Test
- public void requireThatPatternResolutionWorksForWildCards() {
+ void requireThatPatternResolutionWorksForWildCards() {
Map<UriPattern, RequestHandler> handlers = new LinkedHashMap<>();
RequestHandler foo = new NonWorkingRequestHandler();
handlers.put(new UriPattern("http://host:*/bar"), foo);
@@ -125,7 +125,7 @@ public class BindingSetTestCase {
}
@Test
- public void requireThatPatternResolutionWorksForFilters() {
+ void requireThatPatternResolutionWorksForFilters() {
Map<UriPattern, RequestHandler> handlers = new LinkedHashMap<>();
RequestHandler foo = new NonWorkingRequestHandler();
handlers.put(new UriPattern("http://*/filtered/*"), foo);
@@ -139,7 +139,7 @@ public class BindingSetTestCase {
}
@Test
- public void requireThatTreeSplitCanBeBoundForSchemes() {
+ void requireThatTreeSplitCanBeBoundForSchemes() {
Map<UriPattern, RequestHandler> handlers = new LinkedHashMap<>();
RequestHandler httpfoo = new NonWorkingRequestHandler();
RequestHandler httpsfoo = new NonWorkingRequestHandler();
@@ -152,7 +152,7 @@ public class BindingSetTestCase {
}
@Test
- public void requireThatTreeSplitCanBeBoundForHosts() {
+ void requireThatTreeSplitCanBeBoundForHosts() {
Map<UriPattern, RequestHandler> handlers = new LinkedHashMap<>();
RequestHandler foo = new NonWorkingRequestHandler();
RequestHandler foobar = new NonWorkingRequestHandler();
@@ -165,7 +165,7 @@ public class BindingSetTestCase {
}
@Test
- public void requireThatTreeSplitCanBeBoundForPorts() {
+ void requireThatTreeSplitCanBeBoundForPorts() {
Map<UriPattern, RequestHandler> handlers = new LinkedHashMap<>();
RequestHandler foo8080 = new NonWorkingRequestHandler();
RequestHandler foo80 = new NonWorkingRequestHandler();
@@ -181,7 +181,7 @@ public class BindingSetTestCase {
}
@Test
- public void requireThatTreeSplitCanBeBoundForPaths() {
+ void requireThatTreeSplitCanBeBoundForPaths() {
Map<UriPattern, RequestHandler> handlers = new LinkedHashMap<>();
RequestHandler foo = new NonWorkingRequestHandler();
RequestHandler foobar = new NonWorkingRequestHandler();
@@ -194,7 +194,7 @@ public class BindingSetTestCase {
}
@Test
- public void requireThatTreeSplitCanBeBoundForWildcards() {
+ void requireThatTreeSplitCanBeBoundForWildcards() {
Map<UriPattern, RequestHandler> handlers = new LinkedHashMap<>();
RequestHandler foo8080 = new NonWorkingRequestHandler();
RequestHandler foo80 = new NonWorkingRequestHandler();
@@ -213,7 +213,7 @@ public class BindingSetTestCase {
}
@Test
- public void requireThatTreeWorksForURIWithQueryOrFragments() {
+ void requireThatTreeWorksForURIWithQueryOrFragments() {
Map<UriPattern, RequestHandler> handlers = new LinkedHashMap<>();
RequestHandler foo = new NonWorkingRequestHandler();
handlers.put(new UriPattern("http://*/application/v1/session"), foo);
@@ -226,7 +226,7 @@ public class BindingSetTestCase {
}
@Test
- public void requireThatTreeWorksForURIWithPathWildCards() {
+ void requireThatTreeWorksForURIWithPathWildCards() {
Map<UriPattern, RequestHandler> handlers = new LinkedHashMap<>();
RequestHandler foo = new NonWorkingRequestHandler();
RequestHandler foo1 = new NonWorkingRequestHandler();
@@ -303,7 +303,7 @@ public class BindingSetTestCase {
}
@Test
- public void requireThatPathOverPortWorks() {
+ void requireThatPathOverPortWorks() {
Map<UriPattern, RequestHandler> handlers = new LinkedHashMap<>();
RequestHandler applicationStatus = new NonWorkingRequestHandler();
RequestHandler search = new NonWorkingRequestHandler();
@@ -327,7 +327,7 @@ public class BindingSetTestCase {
}
@Test
- public void requireThatPathOverPortsDoNotWorkOverStricterPatterns() {
+ void requireThatPathOverPortsDoNotWorkOverStricterPatterns() {
Map<UriPattern, RequestHandler> handlers = new LinkedHashMap<>();
RequestHandler foo = new NonWorkingRequestHandler();
RequestHandler bar = new NonWorkingRequestHandler();
@@ -339,7 +339,7 @@ public class BindingSetTestCase {
}
@Test
- public void requireThatSchemeOrderOverHost() {
+ void requireThatSchemeOrderOverHost() {
Map<UriPattern, RequestHandler> handlers = new LinkedHashMap<>();
RequestHandler foo = new NonWorkingRequestHandler();
RequestHandler bar = new NonWorkingRequestHandler();
@@ -352,7 +352,7 @@ public class BindingSetTestCase {
}
@Test
- public void requireThatPortsAreOrdered() {
+ void requireThatPortsAreOrdered() {
Map<UriPattern, RequestHandler> handlers = new LinkedHashMap<>();
RequestHandler foo = new NonWorkingRequestHandler();
RequestHandler bar = new NonWorkingRequestHandler();
@@ -370,7 +370,7 @@ public class BindingSetTestCase {
}
@Test
- public void requireThatPathsAreOrdered() {
+ void requireThatPathsAreOrdered() {
Map<UriPattern, RequestHandler> handlers = new LinkedHashMap<>();
RequestHandler foo = new NonWorkingRequestHandler();
RequestHandler bar = new NonWorkingRequestHandler();
@@ -388,7 +388,7 @@ public class BindingSetTestCase {
}
@Test
- public void requireThatStrictPatternsOrderBeforeWildcards() {
+ void requireThatStrictPatternsOrderBeforeWildcards() {
Map<UriPattern, RequestHandler> handlers = new LinkedHashMap<>();
RequestHandler fooScheme = new NonWorkingRequestHandler();
@@ -436,7 +436,7 @@ public class BindingSetTestCase {
}
@Test
- public void requireThatToStringMethodWorks() {
+ void requireThatToStringMethodWorks() {
Map<UriPattern, RequestHandler> handlers = new LinkedHashMap<>();
RequestHandler foo = new NonWorkingRequestHandler();
RequestHandler bar = new NonWorkingRequestHandler();
@@ -449,7 +449,7 @@ public class BindingSetTestCase {
@Test
- public void requireThatPatternsAreOrderedMoreSpecificToLess() {
+ void requireThatPatternsAreOrderedMoreSpecificToLess() {
assertOrder("3://host/path", "2://host/path", "1://host/path");
assertOrder("http://3/path", "http://2/path", "http://1/path");
assertOrder("http://host:3/path", "http://host:2/path", "http://host:1/path");
@@ -459,19 +459,19 @@ public class BindingSetTestCase {
assertOrder("http://host:*/3", "http://host:2/2", "http://host:1/1");
assertOrder("http://host/*/3/2/", "http://host/*/1/2", "http://host/*/2/*");
assertOrder("http://host:69/path",
- "http://host/*",
- "http://*:69/path",
- "http://*/path",
- "http://*:69/*",
- "http://*/*",
- "*://host/path",
- "*://*/path",
- "*://*/*");
+ "http://host/*",
+ "http://*:69/path",
+ "http://*/path",
+ "http://*:69/*",
+ "http://*/*",
+ "*://host/path",
+ "*://*/path",
+ "*://*/*");
assertOrder("http://*/HelloWorld",
- "http://*:4080/state/v1/*",
- "http://*:4083/*",
- "http://*:4081/*",
- "http://*:4080/*");
+ "http://*:4080/state/v1/*",
+ "http://*:4083/*",
+ "http://*:4081/*",
+ "http://*:4080/*");
}
private static void assertOrder(String... expected) {
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/application/BundleInstallationExceptionTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/application/BundleInstallationExceptionTestCase.java
index 681ca4dea98..d16f13814c1 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/application/BundleInstallationExceptionTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/application/BundleInstallationExceptionTestCase.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.jdisc.application;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.osgi.framework.Bundle;
@@ -9,9 +9,9 @@ import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -20,7 +20,7 @@ import static org.junit.Assert.fail;
public class BundleInstallationExceptionTestCase {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
Throwable t = new Throwable("foo");
Collection<Bundle> bundles = new LinkedList<>();
bundles.add(Mockito.mock(Bundle.class));
@@ -31,7 +31,7 @@ public class BundleInstallationExceptionTestCase {
}
@Test
- public void requireThatBundlesCollectionIsDefensivelyCopied() {
+ void requireThatBundlesCollectionIsDefensivelyCopied() {
Collection<Bundle> bundles = new LinkedList<>();
bundles.add(Mockito.mock(Bundle.class));
BundleInstallationException e = new BundleInstallationException(bundles, new Throwable());
@@ -40,9 +40,9 @@ public class BundleInstallationExceptionTestCase {
}
@Test
- public void requireThatBundlesCollectionIsUnmodifiable() {
+ void requireThatBundlesCollectionIsUnmodifiable() {
BundleInstallationException e = new BundleInstallationException(Arrays.asList(Mockito.mock(Bundle.class)),
- new Throwable());
+ new Throwable());
try {
e.installedBundles().add(Mockito.mock(Bundle.class));
fail();
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/application/ContainerBuilderTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/application/ContainerBuilderTestCase.java
index 288b46c995f..a31c72584a5 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/application/ContainerBuilderTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/application/ContainerBuilderTestCase.java
@@ -5,18 +5,18 @@ import com.google.inject.AbstractModule;
import com.google.inject.Key;
import com.google.inject.name.Names;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -25,7 +25,7 @@ import static org.junit.Assert.fail;
public class ContainerBuilderTestCase {
@Test
- public void requireThatAccessorsWork() throws URISyntaxException {
+ void requireThatAccessorsWork() throws URISyntaxException {
final Object obj = new Object();
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi(new AbstractModule() {
@@ -47,7 +47,7 @@ public class ContainerBuilderTestCase {
}
@Test
- public void requireThatContainerThreadFactoryIsBound() {
+ void requireThatContainerThreadFactoryIsBound() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
assertSame(ContainerThread.Factory.class, builder.getInstance(ThreadFactory.class).getClass());
@@ -55,7 +55,7 @@ public class ContainerBuilderTestCase {
}
@Test
- public void requireThatThreadFactoryCanBeReconfigured() {
+ void requireThatThreadFactoryCanBeReconfigured() {
final ThreadFactory factory = Executors.defaultThreadFactory();
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
@@ -71,7 +71,7 @@ public class ContainerBuilderTestCase {
}
@Test
- public void requireThatBindingSetsAreCreatedOnDemand() {
+ void requireThatBindingSetsAreCreatedOnDemand() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
BindingRepository<?> repo = builder.serverBindings("foo");
@@ -87,12 +87,12 @@ public class ContainerBuilderTestCase {
}
@Test
- public void requireThatSafeClassCastWorks() {
+ void requireThatSafeClassCastWorks() {
ContainerBuilder.safeClassCast(Integer.class, Integer.class);
}
@Test
- public void requireThatSafeClassCastThrowsIllegalArgument() {
+ void requireThatSafeClassCastThrowsIllegalArgument() {
try {
ContainerBuilder.safeClassCast(Integer.class, Double.class);
fail();
@@ -102,7 +102,7 @@ public class ContainerBuilderTestCase {
}
@Test
- public void requireThatSafeStringSplitWorks() {
+ void requireThatSafeStringSplitWorks() {
assertTrue(ContainerBuilder.safeStringSplit(new Object(), ",").isEmpty());
assertTrue(ContainerBuilder.safeStringSplit("", ",").isEmpty());
assertTrue(ContainerBuilder.safeStringSplit(" \f\n\r\t", ",").isEmpty());
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/application/ContainerThreadTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/application/ContainerThreadTestCase.java
index c7780808bf6..4d17b285926 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/application/ContainerThreadTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/application/ContainerThreadTestCase.java
@@ -2,13 +2,13 @@
package com.yahoo.jdisc.application;
import com.yahoo.jdisc.Metric;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-import static org.junit.Assert.assertSame;
+import static org.junit.jupiter.api.Assertions.assertSame;
/**
@@ -17,14 +17,14 @@ import static org.junit.Assert.assertSame;
public class ContainerThreadTestCase {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
MetricConsumer consumer = new MyConsumer();
ContainerThread thread = new ContainerThread(new MyTask(), consumer);
assertSame(consumer, thread.consumer());
}
@Test
- public void requireThatTaskIsRun() throws InterruptedException {
+ void requireThatTaskIsRun() throws InterruptedException {
MyTask task = new MyTask();
ContainerThread thread = new ContainerThread(task, null);
thread.start();
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/application/GlobPatternTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/application/GlobPatternTestCase.java
index abe47662970..8a01406940f 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/application/GlobPatternTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/application/GlobPatternTestCase.java
@@ -1,18 +1,18 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.application;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
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.assertNotNull;
-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.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Simon Thoresen Hult
@@ -20,7 +20,7 @@ import static org.junit.Assert.assertTrue;
public class GlobPatternTestCase {
@Test
- public void requireThatCompileCreatesExpectedParts() {
+ void requireThatCompileCreatesExpectedParts() {
assertToString("foo");
assertToString("*foo");
assertToString("*oo");
@@ -38,7 +38,7 @@ public class GlobPatternTestCase {
}
@Test
- public void requireThatGlobMatcherWorks() {
+ void requireThatGlobMatcherWorks() {
assertMatch("foo", "foo", Collections.<String>emptyList());
assertNotMatch("foo", "bar");
@@ -81,7 +81,7 @@ public class GlobPatternTestCase {
}
@Test
- public void requireThatGlobPatternOrdersMoreSpecificFirst() {
+ void requireThatGlobPatternOrdersMoreSpecificFirst() {
assertCompareEq("foo", "foo");
assertCompareLt("foo", "foo*");
assertCompareLt("foo", "*foo");
@@ -112,15 +112,15 @@ public class GlobPatternTestCase {
}
@Test
- public void requireThatEqualsIsImplemented() {
- assertTrue(GlobPattern.compile("foo").equals(GlobPattern.compile("foo")));
- assertFalse(GlobPattern.compile("foo").equals(GlobPattern.compile("bar")));
+ void requireThatEqualsIsImplemented() {
+ assertEquals(GlobPattern.compile("foo"), GlobPattern.compile("foo"));
+ assertNotEquals(GlobPattern.compile("foo"), GlobPattern.compile("bar"));
}
@Test
- public void requireThatHashCodeIsImplemented() {
- assertTrue(GlobPattern.compile("foo").hashCode() == GlobPattern.compile("foo").hashCode());
- assertFalse(GlobPattern.compile("foo").hashCode() == GlobPattern.compile("bar").hashCode());
+ void requireThatHashCodeIsImplemented() {
+ assertEquals(GlobPattern.compile("foo").hashCode(), GlobPattern.compile("foo").hashCode());
+ assertNotNull(GlobPattern.compile("bar").hashCode());
}
private static void assertCompareLt(String lhs, String rhs) {
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/application/GuiceRepositoryTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/application/GuiceRepositoryTestCase.java
index 11857163970..9e100e3346a 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/application/GuiceRepositoryTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/application/GuiceRepositoryTestCase.java
@@ -10,18 +10,18 @@ import com.google.inject.Module;
import com.google.inject.PrivateModule;
import com.google.inject.name.Named;
import com.google.inject.name.Names;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Iterator;
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.Assert.assertSame;
-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.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -30,7 +30,7 @@ import static org.junit.Assert.fail;
public class GuiceRepositoryTestCase {
@Test
- public void requireThatInstallWorks() {
+ void requireThatInstallWorks() {
GuiceRepository guice = new GuiceRepository();
StringBinding module = new StringBinding("fooKey", "fooVal");
guice.install(module);
@@ -43,7 +43,7 @@ public class GuiceRepositoryTestCase {
}
@Test
- public void requireThatInstallAllWorks() {
+ void requireThatInstallAllWorks() {
GuiceRepository guice = new GuiceRepository();
StringBinding foo = new StringBinding("fooKey", "fooVal");
StringBinding bar = new StringBinding("barKey", "barVal");
@@ -60,7 +60,7 @@ public class GuiceRepositoryTestCase {
}
@Test
- public void requireThatUninstallWorks() {
+ void requireThatUninstallWorks() {
GuiceRepository guice = new GuiceRepository();
StringBinding module = new StringBinding("fooKey", "fooVal");
guice.install(module);
@@ -72,7 +72,7 @@ public class GuiceRepositoryTestCase {
}
@Test
- public void requireThatUninstallAllWorks() {
+ void requireThatUninstallAllWorks() {
GuiceRepository guice = new GuiceRepository();
StringBinding foo = new StringBinding("fooKey", "fooVal");
StringBinding bar = new StringBinding("barKey", "barVal");
@@ -95,7 +95,7 @@ public class GuiceRepositoryTestCase {
}
@Test
- public void requireThatBindingsCanBeOverridden() {
+ void requireThatBindingsCanBeOverridden() {
GuiceRepository guice = new GuiceRepository();
guice.install(new StringBinding("fooKey", "fooVal1"));
assertBinding(guice, "fooKey", "fooVal1");
@@ -104,7 +104,7 @@ public class GuiceRepositoryTestCase {
}
@Test
- public void requireThatModulesAreOnlyEvaluatedOnce() {
+ void requireThatModulesAreOnlyEvaluatedOnce() {
GuiceRepository guice = new GuiceRepository();
EvalCounter foo = new EvalCounter();
EvalCounter bar = new EvalCounter();
@@ -119,18 +119,18 @@ public class GuiceRepositoryTestCase {
}
@Test
- public void requireThatPrivateModulesWorks() {
+ void requireThatPrivateModulesWorks() {
GuiceRepository guice = new GuiceRepository();
List<Named> names = Arrays.asList(Names.named("A"), Names.named("B"));
- for (Named name: names) {
+ for (Named name : names) {
guice.install(createPrivateInjectNameModule(name));
}
Injector injector = guice.getInjector();
- for (Named name: names) {
+ for (Named name : names) {
NameHolder nameHolder = injector.getInstance(Key.get(NameHolder.class, name));
assertEquals(name, nameHolder.name);
}
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/application/MetricImplTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/application/MetricImplTestCase.java
index 29c51760347..33897d8eacc 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/application/MetricImplTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/application/MetricImplTestCase.java
@@ -5,7 +5,7 @@ import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.yahoo.jdisc.Metric;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@@ -14,8 +14,8 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
-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;
/**
@@ -24,13 +24,13 @@ import static org.junit.Assert.assertTrue;
public class MetricImplTestCase {
@Test
- public void requireThatClassIsInjectedByDefault() {
+ void requireThatClassIsInjectedByDefault() {
Metric metric = Guice.createInjector().getInstance(Metric.class);
assertTrue(metric instanceof MetricImpl);
}
@Test
- public void requireThatConsumerIsOptional() {
+ void requireThatConsumerIsOptional() {
Injector injector = Guice.createInjector();
Metric metric = injector.getInstance(Metric.class);
metric.set("foo", 6, null);
@@ -38,7 +38,7 @@ public class MetricImplTestCase {
}
@Test
- public void requireThatConsumerIsCalled() throws InterruptedException {
+ void requireThatConsumerIsCalled() throws InterruptedException {
final MyConsumer consumer = new MyConsumer();
Injector injector = Guice.createInjector(new AbstractModule() {
@@ -57,7 +57,7 @@ public class MetricImplTestCase {
}
@Test
- public void requireThatWorkerMetricHasPrecedence() throws InterruptedException {
+ void requireThatWorkerMetricHasPrecedence() throws InterruptedException {
final MyConsumer globalConsumer = new MyConsumer();
Injector injector = Guice.createInjector(new AbstractModule() {
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/application/OsgiHeaderTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/application/OsgiHeaderTestCase.java
index da1ab024ede..111ae868e05 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/application/OsgiHeaderTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/application/OsgiHeaderTestCase.java
@@ -1,9 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.application;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
@@ -12,7 +12,7 @@ import static org.junit.Assert.assertEquals;
public class OsgiHeaderTestCase {
@Test
- public void requireThatOsgiHeadersDoNotChange() {
+ void requireThatOsgiHeadersDoNotChange() {
assertEquals("X-JDisc-Application", OsgiHeader.APPLICATION);
assertEquals("X-JDisc-Preinstall-Bundle", OsgiHeader.PREINSTALL_BUNDLE);
assertEquals("X-JDisc-Privileged-Activator", OsgiHeader.PRIVILEGED_ACTIVATOR);
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/application/OsgiRepositoryTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/application/OsgiRepositoryTestCase.java
index b57fc5ae31f..49d76172c39 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/application/OsgiRepositoryTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/application/OsgiRepositoryTestCase.java
@@ -1,9 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.application;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -12,7 +12,7 @@ import static org.junit.Assert.assertTrue;
public class OsgiRepositoryTestCase {
@Test
- public void requireNothingSinceIntegrationModuleTestsThis() {
+ void requireNothingSinceIntegrationModuleTestsThis() {
assertTrue(true);
}
}
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/application/ResourcePoolTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/application/ResourcePoolTestCase.java
index b94ff063fc7..d422a6c45e5 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/application/ResourcePoolTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/application/ResourcePoolTestCase.java
@@ -6,12 +6,12 @@ import com.google.inject.Key;
import com.yahoo.jdisc.AbstractResource;
import com.yahoo.jdisc.ResourceReference;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -20,7 +20,7 @@ import static org.junit.Assert.fail;
public class ResourcePoolTestCase {
@Test
- public void requireThatAddReturnsArgument() {
+ void requireThatAddReturnsArgument() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
MyResource foo = new MyResource();
assertSame(foo, new ResourcePool(driver.newContainerBuilder()).add(foo));
@@ -28,7 +28,7 @@ public class ResourcePoolTestCase {
}
@Test
- public void requireThatAddDoesNotRetainArgument() {
+ void requireThatAddDoesNotRetainArgument() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
MyResource foo = new MyResource();
assertEquals(1, foo.retainCount());
@@ -38,12 +38,12 @@ public class ResourcePoolTestCase {
}
@Test
- public void requireThatAddCanBeUsedWithoutContainerBuilder() {
+ void requireThatAddCanBeUsedWithoutContainerBuilder() {
new ResourcePool().add(new MyResource());
}
@Test
- public void requireThatRetainReturnsArgument() {
+ void requireThatRetainReturnsArgument() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
MyResource foo = new MyResource();
assertSame(foo, new ResourcePool(driver.newContainerBuilder()).retain(foo));
@@ -51,7 +51,7 @@ public class ResourcePoolTestCase {
}
@Test
- public void requireThatRetainRetainsArgument() {
+ void requireThatRetainRetainsArgument() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
MyResource foo = new MyResource();
assertEquals(1, foo.retainCount());
@@ -61,12 +61,12 @@ public class ResourcePoolTestCase {
}
@Test
- public void requireThatRetainCanBeUsedWithoutContainerBuilder() {
+ void requireThatRetainCanBeUsedWithoutContainerBuilder() {
new ResourcePool().retain(new MyResource());
}
@Test
- public void requireThatGetReturnsBoundInstance() {
+ void requireThatGetReturnsBoundInstance() {
final MyResource foo = new MyResource();
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi(new AbstractModule() {
@@ -82,7 +82,7 @@ public class ResourcePoolTestCase {
}
@Test
- public void requireThatGetDoesNotRetainArgument() {
+ void requireThatGetDoesNotRetainArgument() {
final MyResource foo = new MyResource();
assertEquals(1, foo.retainCount());
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi(new AbstractModule() {
@@ -101,7 +101,7 @@ public class ResourcePoolTestCase {
}
@Test
- public void requireThatGetCanNotBeUsedWithoutContainerBuilder() {
+ void requireThatGetCanNotBeUsedWithoutContainerBuilder() {
ResourcePool pool = new ResourcePool();
try {
pool.get(MyResource.class);
@@ -118,7 +118,7 @@ public class ResourcePoolTestCase {
}
@Test
- public void requireThatResourcesAreReleasedOnDestroy() {
+ void requireThatResourcesAreReleasedOnDestroy() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ResourcePool pool = new ResourcePool(driver.newContainerBuilder());
@@ -152,7 +152,7 @@ public class ResourcePoolTestCase {
}
@Test
- public void requireThatAutoCloseCallsRelease() throws Exception {
+ void requireThatAutoCloseCallsRelease() throws Exception {
MyResource foo = new MyResource();
assertEquals(1, foo.retainCount());
try (ResourcePool pool = new ResourcePool()) {
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/application/ServerRepositoryTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/application/ServerRepositoryTestCase.java
index a5d7184e31a..cb3a81277f3 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/application/ServerRepositoryTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/application/ServerRepositoryTestCase.java
@@ -3,15 +3,15 @@ package com.yahoo.jdisc.application;
import com.yahoo.jdisc.NoopSharedResource;
import com.yahoo.jdisc.service.ServerProvider;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Iterator;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Simon Thoresen Hult
@@ -19,7 +19,7 @@ import static org.junit.Assert.assertTrue;
public class ServerRepositoryTestCase {
@Test
- public void requireThatInstallWorks() {
+ void requireThatInstallWorks() {
ServerRepository servers = newServerRepository();
MyServer server = new MyServer();
servers.install(server);
@@ -31,7 +31,7 @@ public class ServerRepositoryTestCase {
}
@Test
- public void requireThatInstallAllWorks() {
+ void requireThatInstallAllWorks() {
ServerRepository servers = newServerRepository();
ServerProvider foo = new MyServer();
ServerProvider bar = new MyServer();
@@ -46,7 +46,7 @@ public class ServerRepositoryTestCase {
}
@Test
- public void requireThatUninstallWorks() {
+ void requireThatUninstallWorks() {
ServerRepository servers = newServerRepository();
ServerProvider server = new MyServer();
servers.install(server);
@@ -55,7 +55,7 @@ public class ServerRepositoryTestCase {
}
@Test
- public void requireThatUninstallAllWorks() {
+ void requireThatUninstallAllWorks() {
ServerRepository servers = newServerRepository();
ServerProvider foo = new MyServer();
ServerProvider bar = new MyServer();
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/application/UriPatternTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/application/UriPatternTestCase.java
index 32327ace4f4..7a67aeda5f8 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/application/UriPatternTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/application/UriPatternTestCase.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.jdisc.application;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.util.ArrayList;
@@ -9,11 +9,11 @@ import java.util.Arrays;
import java.util.Collections;
import java.util.List;
-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.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -23,7 +23,7 @@ public class UriPatternTestCase {
private static final List<String> NO_GROUPS = Collections.emptyList();
@Test
- public void requireThatIllegalPatternsAreDetected() {
+ void requireThatIllegalPatternsAreDetected() {
assertIllegalPattern("scheme");
assertIllegalPattern("scheme://");
assertIllegalPattern("scheme://host");
@@ -36,13 +36,13 @@ public class UriPatternTestCase {
}
@Test
- public void requireThatNoPortImpliesWildcard() {
+ void requireThatNoPortImpliesWildcard() {
assertEquals(new UriPattern("scheme://host/path"),
- new UriPattern("scheme://host:*/path"));
+ new UriPattern("scheme://host:*/path"));
}
@Test
- public void requireThatPatternMatches() {
+ void requireThatPatternMatches() {
// scheme matching
UriPattern pattern = new UriPattern("bar://host:69/path");
assertNotMatch(pattern, "foobar://host:69/path");
@@ -124,7 +124,7 @@ public class UriPatternTestCase {
}
@Test
- public void requireThatUriWithoutPathDoesNotThrowException() {
+ void requireThatUriWithoutPathDoesNotThrowException() {
UriPattern pattern = new UriPattern("scheme://host/path");
assertNotMatch(pattern, "scheme://host");
@@ -133,123 +133,123 @@ public class UriPatternTestCase {
}
@Test
- public void requireThatOnlySchemeHostPortAndPathIsMatched() {
+ void requireThatOnlySchemeHostPortAndPathIsMatched() {
UriPattern pattern = new UriPattern("scheme://host:69/path");
assertMatch(pattern, "scheme://host:69/path?foo", NO_GROUPS);
assertMatch(pattern, "scheme://host:69/path?foo#bar", NO_GROUPS);
}
@Test
- public void requireThatHostSupportsWildcard() {
+ void requireThatHostSupportsWildcard() {
UriPattern pattern = new UriPattern("scheme://*.host/path");
assertMatch(pattern, "scheme://a.host/path", Arrays.asList("a"));
assertMatch(pattern, "scheme://a.b.host/path", Arrays.asList("a.b"));
}
@Test
- public void requireThatSchemesAreOrdered() {
+ void requireThatSchemesAreOrdered() {
assertCompareLt("b://host:69/path",
- "a://host:69/path");
+ "a://host:69/path");
}
@Test
- public void requireThatSchemeOrdersBeforeHost() {
+ void requireThatSchemeOrdersBeforeHost() {
assertCompareLt("b://*:69/path",
- "a://host:69/path");
+ "a://host:69/path");
}
@Test
- public void requireThatHostsAreOrdered() {
+ void requireThatHostsAreOrdered() {
assertCompareLt("scheme://b:69/path",
- "scheme://a:69/path");
+ "scheme://a:69/path");
}
@Test
- public void requireThatHostOrdersBeforePath() {
+ void requireThatHostOrdersBeforePath() {
assertCompareLt("scheme://b:69/*",
- "scheme://a:69/path");
+ "scheme://a:69/path");
}
@Test
- public void requireThatPortsAreOrdered() {
+ void requireThatPortsAreOrdered() {
for (int i = 1; i < 69; ++i) {
assertCompareEq("scheme://host:" + i + "/path",
- "scheme://host:" + i + "/path");
+ "scheme://host:" + i + "/path");
assertCompareLt("scheme://host:" + (i + 1) + "/path",
- "scheme://host:" + i + "/path");
+ "scheme://host:" + i + "/path");
assertCompareLt("scheme://host:" + i + "/path",
- "scheme://host:*/path");
+ "scheme://host:*/path");
}
}
@Test
- public void requireThatPathsAreOrdered() {
+ void requireThatPathsAreOrdered() {
assertCompareLt("scheme://host:69/b",
- "scheme://host:69/a");
+ "scheme://host:69/a");
}
@Test
- public void requireThatPathOrdersBeforePort() {
+ void requireThatPathOrdersBeforePort() {
assertCompareLt("scheme://host:*/b",
- "scheme://host:69/a");
+ "scheme://host:69/a");
}
@Test
- public void requireThatEqualPatternsOrderEqual() {
+ void requireThatEqualPatternsOrderEqual() {
assertCompareEq("scheme://host:69/path",
- "scheme://host:69/path");
+ "scheme://host:69/path");
assertCompareEq("*://host:69/path",
- "*://host:69/path");
+ "*://host:69/path");
assertCompareEq("scheme://*:69/path",
- "scheme://*:69/path");
+ "scheme://*:69/path");
assertCompareEq("scheme://host:*/path",
- "scheme://host:*/path");
+ "scheme://host:*/path");
assertCompareEq("scheme://host:69/*",
- "scheme://host:69/*");
+ "scheme://host:69/*");
}
@Test
- public void requireThatStrictPatternsOrderBeforeWildcards() {
+ void requireThatStrictPatternsOrderBeforeWildcards() {
assertCompareLt("scheme://host:69/path",
- "*://host:69/path");
+ "*://host:69/path");
assertCompareLt("scheme://a:69/path",
- "scheme://*:69/path");
+ "scheme://*:69/path");
assertCompareLt("scheme://a:69/path",
- "scheme://*a:69/path");
+ "scheme://*a:69/path");
assertCompareLt("scheme://*aa:69/path",
- "scheme://*a:69/path");
+ "scheme://*a:69/path");
assertCompareLt("scheme://host:69/path",
- "scheme://host:*/path");
+ "scheme://host:*/path");
assertCompareLt("scheme://host:69/a",
- "scheme://host:69/*");
+ "scheme://host:69/*");
assertCompareLt("scheme://host:69/a",
- "scheme://host:69/a*");
+ "scheme://host:69/a*");
assertCompareLt("scheme://host:69/aa*",
- "scheme://host:69/a*");
+ "scheme://host:69/a*");
assertCompareLt("scheme://*:69/path",
- "*://host:69/path");
+ "*://host:69/path");
assertCompareLt("scheme://host:*/path",
- "scheme://*:69/path");
+ "scheme://*:69/path");
assertCompareLt("scheme://host:*/path",
- "scheme://host:69/*");
+ "scheme://host:69/*");
assertCompareLt("scheme://host:69/foo",
- "scheme://host:69/*");
+ "scheme://host:69/*");
assertCompareLt("scheme://host:69/foo/bar",
- "scheme://host:69/foo/*");
+ "scheme://host:69/foo/*");
assertCompareLt("scheme://host:69/foo/bar/baz",
- "scheme://host:69/foo/bar/*");
+ "scheme://host:69/foo/bar/*");
}
@Test
- public void requireThatLongPatternsOrderBeforeShort() {
+ void requireThatLongPatternsOrderBeforeShort() {
assertCompareLt("scheme://host:69/foo/bar",
- "scheme://host:69/foo");
+ "scheme://host:69/foo");
assertCompareLt("scheme://host:69/foo/bar/baz",
- "scheme://host:69/foo/bar");
+ "scheme://host:69/foo/bar");
}
@Test
- public void requireThatHttpsSchemeIsHandledAsHttp() {
+ void requireThatHttpsSchemeIsHandledAsHttp() {
UriPattern httpPattern = new UriPattern("http://host:80/path");
assertMatch(httpPattern, "https://host:80/path", NO_GROUPS);
@@ -258,7 +258,7 @@ public class UriPatternTestCase {
}
@Test
- public void requireThatUrlEncodingIsNotDoneForPath() {
+ void requireThatUrlEncodingIsNotDoneForPath() {
UriPattern encodedSlashPattern = new UriPattern("http://host:80/one%2Fpath");
assertMatch(encodedSlashPattern, "http://host:80/one%2Fpath", NO_GROUPS);
assertNotMatch(encodedSlashPattern, "http://host:80/one/path");
@@ -304,7 +304,7 @@ public class UriPatternTestCase {
assertTrue(rhsCmp < 0);
return 1;
}
- assertTrue(rhsCmp == 0);
+ assertEquals(rhsCmp, 0);
return 0;
}
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/BindingMatchingTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/BindingMatchingTestCase.java
index d6f49c6a038..9dfe0ece0be 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/BindingMatchingTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/BindingMatchingTestCase.java
@@ -4,7 +4,7 @@ package com.yahoo.jdisc.benchmark;
import com.yahoo.jdisc.application.BindingRepository;
import com.yahoo.jdisc.application.BindingSet;
import com.yahoo.jdisc.application.UriPattern;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.util.ArrayList;
@@ -33,7 +33,7 @@ public class BindingMatchingTestCase {
private static final ExecutorService executor = Executors.newFixedThreadPool(MAX_THREADS);
@Test
- public void runThroughtputMeasurements() throws Exception {
+ void runThroughtputMeasurements() throws Exception {
System.err.format("%15s%15s%15s%15s%15s%15s%15s%15s\n",
"No. of Bindings", "1 thread", "2 thread", "4 thread", "8 thread", "16 thread", "32 thread", "64 thread");
for (int numBindings : Arrays.asList(1, 10, 25, 50, 100, 250)) {
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/LatencyTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/LatencyTestCase.java
index 0ac453d2502..131b4187c2a 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/LatencyTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/LatencyTestCase.java
@@ -10,14 +10,14 @@ import com.yahoo.jdisc.handler.ContentChannel;
import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.service.CurrentContainer;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.Random;
import java.util.concurrent.TimeUnit;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Simon Thoresen Hult
@@ -27,7 +27,7 @@ public class LatencyTestCase {
private static final int NUM_REQUESTS = 100;
@Test
- public void runLatencyMeasurements() {
+ void runLatencyMeasurements() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
MyRequestHandler foo = new MyRequestHandler("foo");
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/ThroughputTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/ThroughputTestCase.java
index 23d94114a38..8e369b0aba6 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/ThroughputTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/ThroughputTestCase.java
@@ -13,7 +13,7 @@ import com.yahoo.jdisc.handler.ResponseDispatch;
import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.service.CurrentContainer;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.util.Iterator;
@@ -26,7 +26,7 @@ import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Simon Thoresen Hult
@@ -45,7 +45,7 @@ public class ThroughputTestCase {
private static long preventOptimization = 0;
@Test
- public void runUnthreadedMeasurementsWithWorkload() throws Exception {
+ void runUnthreadedMeasurementsWithWorkload() throws Exception {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
runMeasurements(driver, new UnthreadedHandler(MAX_LOOPS)); // warmup
@@ -75,7 +75,7 @@ public class ThroughputTestCase {
}
@Test
- public void runThreadedMeasurements() throws Exception {
+ void runThreadedMeasurements() throws Exception {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
runMeasurements(driver, new ThreadedHandler()); // warmup
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/UriMatchingTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/UriMatchingTestCase.java
index e822bd20536..e20d2b6ff5e 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/UriMatchingTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/benchmark/UriMatchingTestCase.java
@@ -2,7 +2,7 @@
package com.yahoo.jdisc.benchmark;
import com.yahoo.jdisc.application.UriPattern;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.util.ArrayList;
@@ -19,7 +19,7 @@ public class UriMatchingTestCase {
private static long preventOptimization = 0;
@Test
- public void requireThatUriPatternMatchingIsFast() {
+ void requireThatUriPatternMatchingIsFast() {
List<String> inputs = Arrays.asList(
"other://host/",
"scheme://other/",
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/client/AbstractClientApplicationTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/client/AbstractClientApplicationTestCase.java
index 5534a97a10c..3362726ddc7 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/client/AbstractClientApplicationTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/client/AbstractClientApplicationTestCase.java
@@ -6,7 +6,7 @@ import com.google.inject.Inject;
import com.yahoo.jdisc.application.BundleInstaller;
import com.yahoo.jdisc.application.ContainerActivator;
import com.yahoo.jdisc.service.CurrentContainer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
@@ -16,8 +16,8 @@ import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
-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 Simon Thoresen Hult
@@ -25,7 +25,7 @@ import static org.junit.Assert.assertTrue;
public class AbstractClientApplicationTestCase {
@Test
- public void requireThatApplicationCanBeShutdown() throws Exception {
+ void requireThatApplicationCanBeShutdown() throws Exception {
MyDriver driver = newDriver();
assertFalse(driver.awaitDone(100, TimeUnit.MILLISECONDS));
assertTrue(driver.awaitApp(600, TimeUnit.SECONDS));
@@ -35,7 +35,7 @@ public class AbstractClientApplicationTestCase {
}
@Test
- public void requireThatShutdownCanBeWaitedForWithTimeout() throws Exception {
+ void requireThatShutdownCanBeWaitedForWithTimeout() throws Exception {
final MyDriver driver = newDriver();
assertFalse(driver.awaitDone(100, TimeUnit.MILLISECONDS));
assertTrue(driver.awaitApp(600, TimeUnit.SECONDS));
@@ -57,7 +57,7 @@ public class AbstractClientApplicationTestCase {
}
@Test
- public void requireThatShutdownCanBeWaitedForWithoutTimeout() throws Exception {
+ void requireThatShutdownCanBeWaitedForWithoutTimeout() throws Exception {
final MyDriver driver = newDriver();
assertFalse(driver.awaitDone(100, TimeUnit.MILLISECONDS));
assertTrue(driver.awaitApp(600, TimeUnit.SECONDS));
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/client/ClientDriverTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/client/ClientDriverTestCase.java
index cd7d5552287..159d8ef8f44 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/client/ClientDriverTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/client/ClientDriverTestCase.java
@@ -3,9 +3,9 @@ package com.yahoo.jdisc.client;
import com.google.inject.AbstractModule;
import com.google.inject.Inject;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
@@ -14,14 +14,14 @@ import static org.junit.Assert.assertEquals;
public class ClientDriverTestCase {
@Test
- public void requireThatApplicationInstanceInjectionWorks() throws Exception {
+ void requireThatApplicationInstanceInjectionWorks() throws Exception {
MyModule module = new MyModule();
ClientDriver.runApplication(new MyApplication(module));
assertEquals(5, module.state);
}
@Test
- public void requireThatApplicationClassInjectionWorks() throws Exception {
+ void requireThatApplicationClassInjectionWorks() throws Exception {
MyModule module = new MyModule();
ClientDriver.runApplication(MyApplication.class, module);
assertEquals(5, module.state);
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ActiveContainerTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ActiveContainerTestCase.java
index cf1fa62b102..4232b6ed087 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ActiveContainerTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ActiveContainerTestCase.java
@@ -14,12 +14,13 @@ import com.yahoo.jdisc.test.TestDriver;
import java.util.Iterator;
import java.util.Map;
-import org.junit.Test;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertSame;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* @author Simon Thoresen Hult
@@ -27,7 +28,7 @@ import static org.junit.Assert.assertSame;
public class ActiveContainerTestCase {
@Test
- public void requireThatGuiceAccessorWorks() {
+ void requireThatGuiceAccessorWorks() {
final Object obj = new Object();
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi(new AbstractModule() {
@@ -42,7 +43,7 @@ public class ActiveContainerTestCase {
}
@Test
- public void requireThatServerAccessorWorks() {
+ void requireThatServerAccessorWorks() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
ServerProvider foo = new NonWorkingServerProvider();
@@ -61,7 +62,7 @@ public class ActiveContainerTestCase {
}
@Test
- public void requireThatServerBindingAccessorWorks() {
+ void requireThatServerBindingAccessorWorks() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
RequestHandler foo = new NonWorkingRequestHandler();
@@ -103,7 +104,7 @@ public class ActiveContainerTestCase {
}
@Test
- public void requireThatClientBindingAccessorWorks() {
+ void requireThatClientBindingAccessorWorks() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
RequestHandler foo = new NonWorkingRequestHandler();
@@ -145,7 +146,7 @@ public class ActiveContainerTestCase {
}
@Test
- public void requireThatDefaultBindingsAreAlwaysCreated() {
+ void requireThatDefaultBindingsAreAlwaysCreated() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
ActiveContainer container = new ActiveContainer(builder);
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationConfigModuleTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationConfigModuleTestCase.java
index d17c5b183d8..8a1d155df2c 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationConfigModuleTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationConfigModuleTestCase.java
@@ -15,9 +15,10 @@ import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
-import org.junit.Test;
-import static org.junit.Assert.fail;
-import static org.junit.Assert.assertEquals;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -25,7 +26,7 @@ import static org.junit.Assert.assertEquals;
public class ApplicationConfigModuleTestCase {
@Test
- public void requireThatEntriesAreBoundWithLowerCaseKeys() {
+ void requireThatEntriesAreBoundWithLowerCaseKeys() {
Map<String, String> config = new HashMap<>();
config.put("foo_key", "foo");
config.put("BAR_key", "bar");
@@ -38,7 +39,7 @@ public class ApplicationConfigModuleTestCase {
}
@Test
- public void requireThatEntriesAreBoundWithUnmodifiedValue() {
+ void requireThatEntriesAreBoundWithUnmodifiedValue() {
Map<String, String> config = new HashMap<>();
config.put("foo", "foo_val");
config.put("bar", "BAR_val");
@@ -51,7 +52,7 @@ public class ApplicationConfigModuleTestCase {
}
@Test
- public void requireThatUpperCaseKeysPrecedeLowerCaseKeys() {
+ void requireThatUpperCaseKeysPrecedeLowerCaseKeys() {
Map<String, String> config = new HashMap<>();
config.put("foo", "lower-case");
assertBinding(config, "foo", "lower-case");
@@ -67,7 +68,7 @@ public class ApplicationConfigModuleTestCase {
}
@Test
- public void requireThatNullFileNameThrowsException() throws IOException {
+ void requireThatNullFileNameThrowsException() throws IOException {
try {
ApplicationConfigModule.newInstanceFromFile(null);
fail();
@@ -77,7 +78,7 @@ public class ApplicationConfigModuleTestCase {
}
@Test
- public void requireThatFileNotFoundThrowsException() throws IOException {
+ void requireThatFileNotFoundThrowsException() throws IOException {
try {
ApplicationConfigModule.newInstanceFromFile("/file/not/found");
fail();
@@ -87,7 +88,7 @@ public class ApplicationConfigModuleTestCase {
}
@Test
- public void requireThatPropertieFilesCanBeRead() throws IOException {
+ void requireThatPropertieFilesCanBeRead() throws IOException {
Properties props = new Properties();
props.put("foo_key", "foo_val");
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationEnvironmentModuleTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationEnvironmentModuleTestCase.java
index 3bd60832ca3..87a0d4d0e18 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationEnvironmentModuleTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationEnvironmentModuleTestCase.java
@@ -10,7 +10,7 @@ import com.yahoo.jdisc.application.ContainerBuilder;
import com.yahoo.jdisc.application.OsgiFramework;
import com.yahoo.jdisc.service.CurrentContainer;
import com.yahoo.jdisc.test.NonWorkingOsgiFramework;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.LinkedList;
import java.util.List;
@@ -18,8 +18,8 @@ import java.util.Map;
import java.util.concurrent.ThreadFactory;
import static java.util.Collections.emptyList;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Simon Thoresen Hult
@@ -27,7 +27,7 @@ import static org.junit.Assert.assertTrue;
public class ApplicationEnvironmentModuleTestCase {
@Test
- public void requireThatBindingsExist() {
+ void requireThatBindingsExist() {
List<Class<?>> expected = new LinkedList<>();
expected.add(ContainerActivator.class);
expected.add(ContainerBuilder.class);
@@ -49,10 +49,10 @@ public class ApplicationEnvironmentModuleTestCase {
}
@Test
- public void requireThatContainerBuilderCanBeInjected() {
+ void requireThatContainerBuilderCanBeInjected() {
ApplicationLoader loader = new ApplicationLoader(new NonWorkingOsgiFramework(), emptyList());
assertNotNull(new ApplicationEnvironmentModule(loader).containerBuilder());
assertNotNull(Guice.createInjector(new ApplicationEnvironmentModule(loader))
- .getInstance(ContainerBuilder.class));
+ .getInstance(ContainerBuilder.class));
}
}
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationLoaderTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationLoaderTestCase.java
index e5d335beb38..301f0fc571e 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationLoaderTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationLoaderTestCase.java
@@ -16,7 +16,7 @@ import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.service.CurrentContainer;
import com.yahoo.jdisc.test.NonWorkingOsgiFramework;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.osgi.framework.BundleContext;
import java.nio.ByteBuffer;
@@ -27,12 +27,12 @@ import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-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.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -41,9 +41,9 @@ import static org.junit.Assert.fail;
public class ApplicationLoaderTestCase {
@Test
- public void requireThatStartFailsWithoutApplication() throws Exception {
+ void requireThatStartFailsWithoutApplication() throws Exception {
ApplicationLoader loader = new ApplicationLoader(new NonWorkingOsgiFramework(),
- Collections.<Module>emptyList());
+ Collections.<Module>emptyList());
try {
loader.init(null, false);
loader.start();
@@ -54,25 +54,25 @@ public class ApplicationLoaderTestCase {
}
@Test
- public void requireThatStopDoesNotFailWithoutStart() throws Exception {
+ void requireThatStopDoesNotFailWithoutStart() throws Exception {
ApplicationLoader loader = new ApplicationLoader(new NonWorkingOsgiFramework(),
- Collections.<Module>emptyList());
+ Collections.<Module>emptyList());
loader.stop();
loader.destroy();
}
@Test
- public void requireThatDestroyDoesNotFailWithActiveContainer() throws Exception {
+ void requireThatDestroyDoesNotFailWithActiveContainer() throws Exception {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
assertNull(driver.activateContainer(driver.newContainerBuilder()));
assertTrue(driver.close());
}
@Test
- public void requireThatApplicationStartExceptionUnsetsAndDestroysApplication() throws Exception {
+ void requireThatApplicationStartExceptionUnsetsAndDestroysApplication() throws Exception {
MyApplication app = MyApplication.newStartException();
ApplicationLoader loader = new ApplicationLoader(new NonWorkingOsgiFramework(),
- Arrays.asList(new MyApplicationModule(app)));
+ Arrays.asList(new MyApplicationModule(app)));
loader.init(null, false);
try {
loader.start();
@@ -94,10 +94,10 @@ public class ApplicationLoaderTestCase {
}
@Test
- public void requireThatApplicationStopExceptionDestroysApplication() throws Exception {
+ void requireThatApplicationStopExceptionDestroysApplication() throws Exception {
MyApplication app = MyApplication.newStopException();
ApplicationLoader loader = new ApplicationLoader(new NonWorkingOsgiFramework(),
- Arrays.asList(new MyApplicationModule(app)));
+ Arrays.asList(new MyApplicationModule(app)));
loader.init(null, false);
loader.start();
try {
@@ -110,7 +110,7 @@ public class ApplicationLoaderTestCase {
}
@Test
- public void requireThatApplicationDestroyIsCalledAfterContainerTermination() throws InterruptedException {
+ void requireThatApplicationDestroyIsCalledAfterContainerTermination() throws InterruptedException {
MyApplication app = MyApplication.newInstance();
TestDriver driver = TestDriver.newInjectedApplicationInstance(app);
ContainerBuilder builder = driver.newContainerBuilder();
@@ -125,7 +125,7 @@ public class ApplicationLoaderTestCase {
}
@Test
- public void requireThatContainerActivatorReturnsPrev() throws Exception {
+ void requireThatContainerActivatorReturnsPrev() throws Exception {
TestDriver driver = TestDriver.newInjectedApplicationInstance(MyApplication.newInstance());
assertNull(driver.activateContainer(driver.newContainerBuilder()));
assertNotNull(driver.activateContainer(null));
@@ -133,7 +133,7 @@ public class ApplicationLoaderTestCase {
}
@Test
- public void requireThatOsgiServicesAreRegistered() {
+ void requireThatOsgiServicesAreRegistered() {
TestDriver driver = TestDriver.newSimpleApplicationInstance();
BundleContext ctx = driver.osgiFramework().bundleContext();
Object service = ctx.getService(ctx.getServiceReference(CurrentContainer.class.getName()));
@@ -142,7 +142,7 @@ public class ApplicationLoaderTestCase {
}
@Test
- public void requireThatThreadFactoryCanBeBound() {
+ void requireThatThreadFactoryCanBeBound() {
final ThreadFactory factory = Executors.defaultThreadFactory();
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi(new AbstractModule() {
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationRestartTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationRestartTestCase.java
index 941067ff27d..cf283fa3ae3 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationRestartTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationRestartTestCase.java
@@ -11,7 +11,7 @@ import com.yahoo.jdisc.handler.CompletionHandler;
import com.yahoo.jdisc.handler.ContentChannel;
import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.test.NonWorkingOsgiFramework;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.nio.ByteBuffer;
@@ -19,8 +19,8 @@ import java.util.Arrays;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-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;
/**
@@ -29,7 +29,7 @@ import static org.junit.Assert.assertTrue;
public class ApplicationRestartTestCase {
@Test
- public void requireThatStopStartDoesNotBreakShutdown() throws Exception {
+ void requireThatStopStartDoesNotBreakShutdown() throws Exception {
ApplicationLoader loader = newApplicationLoader();
loader.init(null, false);
loader.start();
@@ -40,7 +40,7 @@ public class ApplicationRestartTestCase {
}
@Test
- public void requireThatDestroyInitDoesNotBreakShutdown() throws Exception {
+ void requireThatDestroyInitDoesNotBreakShutdown() throws Exception {
ApplicationLoader loader = newApplicationLoader();
loader.init(null, false);
loader.start();
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationShutdownTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationShutdownTestCase.java
index 3f906263867..fb88f5567e7 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationShutdownTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ApplicationShutdownTestCase.java
@@ -10,14 +10,14 @@ import com.yahoo.jdisc.handler.ContentChannel;
import com.yahoo.jdisc.handler.RequestHandler;
import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.concurrent.TimeUnit;
-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 Simon Thoresen Hult
@@ -25,7 +25,7 @@ import static org.junit.Assert.assertTrue;
public class ApplicationShutdownTestCase {
@Test
- public void requireThatStopWaitsForPreviousContainer() throws Exception {
+ void requireThatStopWaitsForPreviousContainer() throws Exception {
Context ctx = new Context();
MyRequestHandler requestHandler = new MyRequestHandler();
ctx.activateContainer(requestHandler);
@@ -38,7 +38,7 @@ public class ApplicationShutdownTestCase {
}
@Test
- public void requireThatStopWaitsForAllPreviousContainers() {
+ void requireThatStopWaitsForAllPreviousContainers() {
Context ctx = new Context();
MyRequestHandler requestHandlerA = new MyRequestHandler();
ctx.activateContainer(requestHandlerA);
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/BundleLocationResolverTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/BundleLocationResolverTestCase.java
index 86f7f5875a7..f65fb849836 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/BundleLocationResolverTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/BundleLocationResolverTestCase.java
@@ -1,12 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.core;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Simon Thoresen Hult
@@ -14,13 +14,13 @@ import static org.junit.Assert.assertEquals;
public class BundleLocationResolverTestCase {
@Test
- public void requireThatDollarsAreIncludedInLocation() {
+ void requireThatDollarsAreIncludedInLocation() {
assertLocation("scheme:$foo", "scheme:$foo");
assertLocation("scheme:foo$bar", "scheme:foo$bar");
}
@Test
- public void requireThatCurlyBracesAreIncludedInLocation() {
+ void requireThatCurlyBracesAreIncludedInLocation() {
assertLocation("scheme:{foo", "scheme:{foo");
assertLocation("scheme:foo{", "scheme:foo{");
assertLocation("scheme:foo{bar", "scheme:foo{bar");
@@ -32,14 +32,14 @@ public class BundleLocationResolverTestCase {
}
@Test
- public void requireThatUnterminatedPropertiesAreIncludedInLocation() {
+ void requireThatUnterminatedPropertiesAreIncludedInLocation() {
assertLocation("scheme:${foo", "scheme:${foo");
assertLocation("scheme:foo${", "scheme:foo${");
assertLocation("scheme:foo${bar", "scheme:foo${bar");
}
@Test
- public void requireThatAllSystemPropertiesAreExpanded() throws IOException {
+ void requireThatAllSystemPropertiesAreExpanded() throws IOException {
assertCanonicalPath("", "${foo}");
assertCanonicalPath("barcox", "${foo}bar${baz}cox");
assertCanonicalPath("foobaz", "foo${bar}baz${cox}");
@@ -50,18 +50,18 @@ public class BundleLocationResolverTestCase {
System.setProperty("requireThatAllSystemPropertiesAreExpanded.cox", "COX");
assertCanonicalPath("FOO", "${requireThatAllSystemPropertiesAreExpanded.foo}");
assertCanonicalPath("FOObarBAZcox", "${requireThatAllSystemPropertiesAreExpanded.foo}bar" +
- "${requireThatAllSystemPropertiesAreExpanded.baz}cox");
+ "${requireThatAllSystemPropertiesAreExpanded.baz}cox");
assertCanonicalPath("fooBARbazCOX", "foo${requireThatAllSystemPropertiesAreExpanded.bar}" +
- "baz${requireThatAllSystemPropertiesAreExpanded.cox}");
+ "baz${requireThatAllSystemPropertiesAreExpanded.cox}");
}
@Test
- public void requireThatUnschemedLocationsAreExpandedToBundleLocationProperty() throws IOException {
+ void requireThatUnschemedLocationsAreExpandedToBundleLocationProperty() throws IOException {
assertCanonicalPath(BundleLocationResolver.BUNDLE_PATH + "foo", "foo");
}
@Test
- public void requireThatFileSchemedLocationsAreCanonicalized() throws IOException {
+ void requireThatFileSchemedLocationsAreCanonicalized() throws IOException {
assertCanonicalPath("", "file:");
assertCanonicalPath("foo", "file:foo");
assertCanonicalPath("foo", "file:./foo");
@@ -71,7 +71,7 @@ public class BundleLocationResolverTestCase {
}
@Test
- public void requireThatOtherSchemedLocationsAreUntouched() {
+ void requireThatOtherSchemedLocationsAreUntouched() {
assertLocation("foo:", "foo:");
assertLocation("foo:bar", "foo:bar");
assertLocation("foo:bar/baz", "foo:bar/baz");
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ConsoleLogFormatterTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ConsoleLogFormatterTestCase.java
index f8a982d02cf..64130ddc125 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ConsoleLogFormatterTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ConsoleLogFormatterTestCase.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.jdisc.core;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.osgi.framework.Bundle;
import org.osgi.framework.ServiceReference;
@@ -13,7 +13,7 @@ import java.io.StringWriter;
import java.io.Writer;
import java.time.Instant;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
@@ -27,178 +27,178 @@ public class ConsoleLogFormatterTestCase {
// TODO: Should (at least) use ConsoleLogFormatter.ABSENCE_REPLACEMENT instead of literal '-'. See ticket 7128315.
@Test
- public void requireThatMillisecondsArePadded() {
+ void requireThatMillisecondsArePadded() {
for (int i = 0; i < 10000; ++i) {
LogEntry entry = new MyEntry(i, 0, null);
Instant instant = Instant.ofEpochMilli(i);
assertEquals(String.format("%d.%06d\t-\t-\t-\t-\tunknown\t", instant.getEpochSecond(), instant.getNano() / 1000),
- SIMPLE_FORMATTER.formatEntry(entry));
+ SIMPLE_FORMATTER.formatEntry(entry));
}
}
@Test
- public void requireThatHostNameIsIncluded() {
+ void requireThatHostNameIsIncluded() {
assertEquals("0.000000\thostName\t-\t-\t-\tunknown\t",
- new ConsoleLogFormatter("hostName", null, null).formatEntry(SIMPLE_ENTRY));
+ new ConsoleLogFormatter("hostName", null, null).formatEntry(SIMPLE_ENTRY));
}
@Test
- public void requireThatHostNameIsOptional() {
+ void requireThatHostNameIsOptional() {
assertEquals("0.000000\t-\t-\t-\t-\tunknown\t",
- new ConsoleLogFormatter(null, null, null).formatEntry(SIMPLE_ENTRY));
+ new ConsoleLogFormatter(null, null, null).formatEntry(SIMPLE_ENTRY));
assertEquals("0.000000\t-\t-\t-\t-\tunknown\t",
- new ConsoleLogFormatter("", null, null).formatEntry(SIMPLE_ENTRY));
+ new ConsoleLogFormatter("", null, null).formatEntry(SIMPLE_ENTRY));
assertEquals("0.000000\t-\t-\t-\t-\tunknown\t",
- new ConsoleLogFormatter(" ", null, null).formatEntry(SIMPLE_ENTRY));
+ new ConsoleLogFormatter(" ", null, null).formatEntry(SIMPLE_ENTRY));
}
@Test
- public void requireThatProcessIdIsIncluded() {
+ void requireThatProcessIdIsIncluded() {
assertEquals("0.000000\t-\tprocessId\t-\t-\tunknown\t",
- new ConsoleLogFormatter(null, "processId", null).formatEntry(SIMPLE_ENTRY));
+ new ConsoleLogFormatter(null, "processId", null).formatEntry(SIMPLE_ENTRY));
}
@Test
- public void requireThatProcessIdIsOptional() {
+ void requireThatProcessIdIsOptional() {
assertEquals("0.000000\t-\t-\t-\t-\tunknown\t",
- new ConsoleLogFormatter(null, null, null).formatEntry(SIMPLE_ENTRY));
+ new ConsoleLogFormatter(null, null, null).formatEntry(SIMPLE_ENTRY));
assertEquals("0.000000\t-\t-\t-\t-\tunknown\t",
- new ConsoleLogFormatter(null, "", null).formatEntry(SIMPLE_ENTRY));
+ new ConsoleLogFormatter(null, "", null).formatEntry(SIMPLE_ENTRY));
assertEquals("0.000000\t-\t-\t-\t-\tunknown\t",
- new ConsoleLogFormatter(null, " ", null).formatEntry(SIMPLE_ENTRY));
+ new ConsoleLogFormatter(null, " ", null).formatEntry(SIMPLE_ENTRY));
}
@Test
- public void requireThatProcessIdIncludesThreadIdWhenAvailable() {
+ void requireThatProcessIdIncludesThreadIdWhenAvailable() {
LogEntry entry = new MyEntry(0, 0, null).putProperty("THREAD_ID", "threadId");
assertEquals("0.000000\t-\tprocessId/threadId\t-\t-\tunknown\t",
- new ConsoleLogFormatter(null, "processId", null).formatEntry(entry));
+ new ConsoleLogFormatter(null, "processId", null).formatEntry(entry));
}
@Test
- public void requireThatServiceNameIsIncluded() {
+ void requireThatServiceNameIsIncluded() {
assertEquals("0.000000\t-\t-\tserviceName\t-\tunknown\t",
- new ConsoleLogFormatter(null, null, "serviceName").formatEntry(SIMPLE_ENTRY));
+ new ConsoleLogFormatter(null, null, "serviceName").formatEntry(SIMPLE_ENTRY));
}
@Test
- public void requireThatServiceNameIsOptional() {
+ void requireThatServiceNameIsOptional() {
assertEquals("0.000000\t-\t-\t-\t-\tunknown\t",
- new ConsoleLogFormatter(null, null, null).formatEntry(SIMPLE_ENTRY));
+ new ConsoleLogFormatter(null, null, null).formatEntry(SIMPLE_ENTRY));
assertEquals("0.000000\t-\t-\t-\t-\tunknown\t",
- new ConsoleLogFormatter(null, null, "").formatEntry(SIMPLE_ENTRY));
+ new ConsoleLogFormatter(null, null, "").formatEntry(SIMPLE_ENTRY));
assertEquals("0.000000\t-\t-\t-\t-\tunknown\t",
- new ConsoleLogFormatter(null, null, " ").formatEntry(SIMPLE_ENTRY));
+ new ConsoleLogFormatter(null, null, " ").formatEntry(SIMPLE_ENTRY));
}
@Test
- public void requireThatBundleNameIsIncluded() {
+ void requireThatBundleNameIsIncluded() {
LogEntry entry = new MyEntry(0, 0, null).setBundleSymbolicName("bundleName");
assertEquals("0.000000\t-\t-\t-\tbundleName\tunknown\t",
- SIMPLE_FORMATTER.formatEntry(entry));
+ SIMPLE_FORMATTER.formatEntry(entry));
}
@Test
- public void requireThatBundleNameIsOptional() {
+ void requireThatBundleNameIsOptional() {
assertEquals("0.000000\t-\t-\t-\t-\tunknown\t",
- SIMPLE_FORMATTER.formatEntry(SIMPLE_ENTRY));
+ SIMPLE_FORMATTER.formatEntry(SIMPLE_ENTRY));
}
@Test
- public void requireThatLoggerNameIsIncluded() {
+ void requireThatLoggerNameIsIncluded() {
LogEntry entry = new MyEntry(0, 0, null).putProperty("LOGGER_NAME", "loggerName");
assertEquals("0.000000\t-\t-\t-\t/loggerName\tunknown\t",
- SIMPLE_FORMATTER.formatEntry(entry));
+ SIMPLE_FORMATTER.formatEntry(entry));
}
@Test
- public void requireThatLoggerNameIsOptional() {
+ void requireThatLoggerNameIsOptional() {
assertEquals("0.000000\t-\t-\t-\t-\tunknown\t",
- SIMPLE_FORMATTER.formatEntry(SIMPLE_ENTRY));
+ SIMPLE_FORMATTER.formatEntry(SIMPLE_ENTRY));
}
@Test
- public void requireThatBundleAndLoggerNameIsCombined() {
+ void requireThatBundleAndLoggerNameIsCombined() {
LogEntry entry = new MyEntry(0, 0, null).setBundleSymbolicName("bundleName")
- .putProperty("LOGGER_NAME", "loggerName");
+ .putProperty("LOGGER_NAME", "loggerName");
assertEquals("0.000000\t-\t-\t-\tbundleName/loggerName\tunknown\t",
- SIMPLE_FORMATTER.formatEntry(entry));
+ SIMPLE_FORMATTER.formatEntry(entry));
}
@Test
- public void requireThatLevelNameIsIncluded() {
+ void requireThatLevelNameIsIncluded() {
ConsoleLogFormatter formatter = SIMPLE_FORMATTER;
assertEquals("0.000000\t-\t-\t-\t-\terror\t",
- formatter.formatEntry(new MyEntry(0, LogService.LOG_ERROR, null)));
+ formatter.formatEntry(new MyEntry(0, LogService.LOG_ERROR, null)));
assertEquals("0.000000\t-\t-\t-\t-\twarning\t",
- formatter.formatEntry(new MyEntry(0, LogService.LOG_WARNING, null)));
+ formatter.formatEntry(new MyEntry(0, LogService.LOG_WARNING, null)));
assertEquals("0.000000\t-\t-\t-\t-\tinfo\t",
- formatter.formatEntry(new MyEntry(0, LogService.LOG_INFO, null)));
+ formatter.formatEntry(new MyEntry(0, LogService.LOG_INFO, null)));
assertEquals("0.000000\t-\t-\t-\t-\tdebug\t",
- formatter.formatEntry(new MyEntry(0, LogService.LOG_DEBUG, null)));
+ formatter.formatEntry(new MyEntry(0, LogService.LOG_DEBUG, null)));
assertEquals("0.000000\t-\t-\t-\t-\tunknown\t",
- formatter.formatEntry(new MyEntry(0, 69, null)));
+ formatter.formatEntry(new MyEntry(0, 69, null)));
}
@Test
- public void requireThatMessageIsIncluded() {
+ void requireThatMessageIsIncluded() {
LogEntry entry = new MyEntry(0, 0, "message");
assertEquals("0.000000\t-\t-\t-\t-\tunknown\tmessage",
- SIMPLE_FORMATTER.formatEntry(entry));
+ SIMPLE_FORMATTER.formatEntry(entry));
}
@Test
- public void requireThatMessageIsOptional() {
+ void requireThatMessageIsOptional() {
LogEntry entry = new MyEntry(0, 0, null);
assertEquals("0.000000\t-\t-\t-\t-\tunknown\t",
- SIMPLE_FORMATTER.formatEntry(entry));
+ SIMPLE_FORMATTER.formatEntry(entry));
}
@Test
- public void requireThatMessageIsEscaped() {
+ void requireThatMessageIsEscaped() {
LogEntry entry = new MyEntry(0, 0, "\\\n\r\t");
assertEquals("0.000000\t-\t-\t-\t-\tunknown\t\\\\\\n\\r\\t",
- SIMPLE_FORMATTER.formatEntry(entry));
+ SIMPLE_FORMATTER.formatEntry(entry));
}
@Test
- public void requireThatExceptionIsIncluded() {
+ void requireThatExceptionIsIncluded() {
Throwable t = new Throwable();
LogEntry entry = new MyEntry(0, 0, null).setException(t);
assertEquals("0.000000\t-\t-\t-\t-\tunknown\t\\n" + formatThrowable(t),
- SIMPLE_FORMATTER.formatEntry(entry));
+ SIMPLE_FORMATTER.formatEntry(entry));
}
@Test
- public void requireThatExceptionIsEscaped() {
+ void requireThatExceptionIsEscaped() {
Throwable t = new Throwable("\\\n\r\t");
LogEntry entry = new MyEntry(0, 0, null).setException(t);
assertEquals("0.000000\t-\t-\t-\t-\tunknown\t\\n" + formatThrowable(t),
- SIMPLE_FORMATTER.formatEntry(entry));
+ SIMPLE_FORMATTER.formatEntry(entry));
}
@Test
- public void requireThatExceptionIsSimplifiedForInfoEntries() {
+ void requireThatExceptionIsSimplifiedForInfoEntries() {
Throwable t = new Throwable("exception");
LogEntry entry = new MyEntry(0, LogService.LOG_INFO, "entry").setException(t);
assertEquals("0.000000\t-\t-\t-\t-\tinfo\tentry: exception",
- SIMPLE_FORMATTER.formatEntry(entry));
+ SIMPLE_FORMATTER.formatEntry(entry));
}
@Test
- public void requireThatSimplifiedExceptionIsEscaped() {
+ void requireThatSimplifiedExceptionIsEscaped() {
Throwable t = new Throwable("\\\n\r\t");
LogEntry entry = new MyEntry(0, LogService.LOG_INFO, "entry").setException(t);
assertEquals("0.000000\t-\t-\t-\t-\tinfo\tentry: \\\\\\n\\r\\t",
- SIMPLE_FORMATTER.formatEntry(entry));
+ SIMPLE_FORMATTER.formatEntry(entry));
}
@Test
- public void requireThatSimplifiedExceptionMessageIsOptional() {
+ void requireThatSimplifiedExceptionMessageIsOptional() {
Throwable t = new Throwable();
LogEntry entry = new MyEntry(0, LogService.LOG_INFO, "entry").setException(t);
assertEquals("0.000000\t-\t-\t-\t-\tinfo\tentry: java.lang.Throwable",
- SIMPLE_FORMATTER.formatEntry(entry));
+ SIMPLE_FORMATTER.formatEntry(entry));
}
private static String formatThrowable(Throwable t) {
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ConsoleLogListenerTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ConsoleLogListenerTestCase.java
index 5f7f7e733fa..0efefc21a2f 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ConsoleLogListenerTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ConsoleLogListenerTestCase.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.jdisc.core;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.ServiceReference;
import org.osgi.service.log.LogEntry;
@@ -11,7 +11,7 @@ import org.osgi.service.log.LogService;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Vikas Panwar
@@ -22,7 +22,7 @@ public class ConsoleLogListenerTestCase {
private static final String PROCESS_ID = ConsoleLogListener.getProcessId();
@Test
- public void requireThatLogLevelParserKnowsOsgiLogLevels() {
+ void requireThatLogLevelParserKnowsOsgiLogLevels() {
assertEquals(LogService.LOG_ERROR, ConsoleLogListener.parseLogLevel("ERROR"));
assertEquals(LogService.LOG_WARNING, ConsoleLogListener.parseLogLevel("WARNING"));
assertEquals(LogService.LOG_INFO, ConsoleLogListener.parseLogLevel("INFO"));
@@ -30,31 +30,31 @@ public class ConsoleLogListenerTestCase {
}
@Test
- public void requireThatLogLevelParserKnowsOff() {
+ void requireThatLogLevelParserKnowsOff() {
assertEquals(Integer.MIN_VALUE, ConsoleLogListener.parseLogLevel("OFF"));
}
@Test
- public void requireThatLogLevelParserKnowsAll() {
+ void requireThatLogLevelParserKnowsAll() {
assertEquals(Integer.MAX_VALUE, ConsoleLogListener.parseLogLevel("ALL"));
}
@Test
- public void requireThatLogLevelParserKnowsIntegers() {
+ void requireThatLogLevelParserKnowsIntegers() {
for (int i = -69; i < 69; ++i) {
assertEquals(i, ConsoleLogListener.parseLogLevel(String.valueOf(i)));
}
}
@Test
- public void requireThatLogLevelParserErrorsReturnDefault() {
+ void requireThatLogLevelParserErrorsReturnDefault() {
assertEquals(ConsoleLogListener.DEFAULT_LOG_LEVEL, ConsoleLogListener.parseLogLevel(null));
assertEquals(ConsoleLogListener.DEFAULT_LOG_LEVEL, ConsoleLogListener.parseLogLevel(""));
assertEquals(ConsoleLogListener.DEFAULT_LOG_LEVEL, ConsoleLogListener.parseLogLevel("foo"));
}
@Test
- public void requireThatLogEntryWithLevelAboveThresholdIsNotOutput() {
+ void requireThatLogEntryWithLevelAboveThresholdIsNotOutput() {
ByteArrayOutputStream out = new ByteArrayOutputStream();
LogListener listener = new ConsoleLogListener(new PrintStream(out), null, "5");
for (int i = 0; i < 10; ++i) {
@@ -62,12 +62,12 @@ public class ConsoleLogListenerTestCase {
}
// TODO: Should use ConsoleLogFormatter.ABSENCE_REPLACEMENT instead of literal '-'. See ticket 7128315.
assertEquals("0.000000\t" + HOSTNAME + "\t" + PROCESS_ID + "\t-\t-\tunknown\tmessage\n" +
- "0.000000\t" + HOSTNAME + "\t" + PROCESS_ID + "\t-\t-\terror\tmessage\n" +
- "0.000000\t" + HOSTNAME + "\t" + PROCESS_ID + "\t-\t-\twarning\tmessage\n" +
- "0.000000\t" + HOSTNAME + "\t" + PROCESS_ID + "\t-\t-\tinfo\tmessage\n" +
- "0.000000\t" + HOSTNAME + "\t" + PROCESS_ID + "\t-\t-\tdebug\tmessage\n" +
- "0.000000\t" + HOSTNAME + "\t" + PROCESS_ID + "\t-\t-\tunknown\tmessage\n",
- out.toString());
+ "0.000000\t" + HOSTNAME + "\t" + PROCESS_ID + "\t-\t-\terror\tmessage\n" +
+ "0.000000\t" + HOSTNAME + "\t" + PROCESS_ID + "\t-\t-\twarning\tmessage\n" +
+ "0.000000\t" + HOSTNAME + "\t" + PROCESS_ID + "\t-\t-\tinfo\tmessage\n" +
+ "0.000000\t" + HOSTNAME + "\t" + PROCESS_ID + "\t-\t-\tdebug\tmessage\n" +
+ "0.000000\t" + HOSTNAME + "\t" + PROCESS_ID + "\t-\t-\tunknown\tmessage\n",
+ out.toString());
}
private static class MyEntry implements LogEntry {
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ConsoleLogManagerTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ConsoleLogManagerTestCase.java
index 4172d6d907a..fb5ee147bd8 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ConsoleLogManagerTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ConsoleLogManagerTestCase.java
@@ -2,17 +2,17 @@
package com.yahoo.jdisc.core;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.service.log.LogListener;
import org.osgi.service.log.LogReaderService;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -21,7 +21,7 @@ import static org.junit.Assert.fail;
public class ConsoleLogManagerTestCase {
@Test
- public void requireThatManagerCanNotBeInstalledTwice() throws BundleException {
+ void requireThatManagerCanNotBeInstalledTwice() throws BundleException {
FelixFramework felix = TestDriver.newOsgiFramework();
felix.start();
@@ -38,7 +38,7 @@ public class ConsoleLogManagerTestCase {
}
@Test
- public void requireThatManagerCanBeUninstalledTwice() throws BundleException {
+ void requireThatManagerCanBeUninstalledTwice() throws BundleException {
FelixFramework felix = TestDriver.newOsgiFramework();
felix.start();
@@ -52,7 +52,7 @@ public class ConsoleLogManagerTestCase {
}
@Test
- public void requireThatLogReaderServicesAreTracked() throws BundleException {
+ void requireThatLogReaderServicesAreTracked() throws BundleException {
FelixFramework felix = TestDriver.newOsgiFramework();
felix.start();
BundleContext ctx = felix.bundleContext();
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerResourceTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerResourceTestCase.java
index a1610c81331..ca78bea85b4 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerResourceTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerResourceTestCase.java
@@ -10,13 +10,13 @@ import com.yahoo.jdisc.handler.RequestHandler;
import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.service.ServerProvider;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.util.concurrent.atomic.AtomicInteger;
-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;
/**
@@ -25,7 +25,7 @@ import static org.junit.Assert.assertTrue;
public class ContainerResourceTestCase {
@Test
- public void requireThatBoundRequestHandlersAreRetainedOnActivate() {
+ void requireThatBoundRequestHandlersAreRetainedOnActivate() {
MyRequestHandler foo = new MyRequestHandler();
MyRequestHandler bar = new MyRequestHandler();
@@ -43,7 +43,7 @@ public class ContainerResourceTestCase {
}
@Test
- public void requireThatBoundRequestHandlersAreReleasedOnTermination() {
+ void requireThatBoundRequestHandlersAreReleasedOnTermination() {
MyRequestHandler handler = new MyRequestHandler();
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
@@ -62,7 +62,7 @@ public class ContainerResourceTestCase {
}
@Test
- public void requireThatServerProvidersAreRetainedOnActivate() {
+ void requireThatServerProvidersAreRetainedOnActivate() {
MyServerProvider foo = new MyServerProvider();
MyServerProvider bar = new MyServerProvider();
@@ -80,7 +80,7 @@ public class ContainerResourceTestCase {
}
@Test
- public void requireThatServerProvidersAreReleasedOnTermination() {
+ void requireThatServerProvidersAreReleasedOnTermination() {
MyServerProvider server = new MyServerProvider();
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerShutdownTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerShutdownTestCase.java
index cf247040c41..458ce3200fc 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerShutdownTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerShutdownTestCase.java
@@ -11,14 +11,14 @@ import com.yahoo.jdisc.handler.ContentChannel;
import com.yahoo.jdisc.handler.RequestHandler;
import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.nio.ByteBuffer;
-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.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -26,7 +26,7 @@ import static org.junit.Assert.fail;
public class ContainerShutdownTestCase {
@Test
- public void requireThatContainerBlocksTermination() {
+ void requireThatContainerBlocksTermination() {
Context ctx = Context.newInstance();
Container container = ctx.driver.newReference(URI.create("http://host/path"));
assertFalse(ctx.shutdown());
@@ -36,7 +36,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatNewRequestBlocksTermination() {
+ void requireThatNewRequestBlocksTermination() {
Context ctx = Context.newPendingRequest(MyRequestHandler.newInstance());
assertFalse(ctx.shutdown());
ctx.request.release();
@@ -45,7 +45,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatOpenRequestBlocksTermination() {
+ void requireThatOpenRequestBlocksTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerCompletion();
Context ctx = Context.newPendingRequest(requestHandler);
ContentChannel requestContent = ctx.request.connect(MyResponseHandler.newEagerCompletion());
@@ -58,7 +58,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatResponsePendingBlocksTermination() {
+ void requireThatResponsePendingBlocksTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerCompletion();
Context ctx = Context.newPendingRequest(requestHandler);
ctx.request.connect(MyResponseHandler.newEagerCompletion()).close(null);
@@ -70,7 +70,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatOpenResponseBlocksTermination() {
+ void requireThatOpenResponseBlocksTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerCompletion();
Context ctx = Context.newPendingRequest(requestHandler);
ctx.request.connect(MyResponseHandler.newEagerCompletion()).close(null);
@@ -83,7 +83,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatRequestExceptionDoesNotBlockTermination() {
+ void requireThatRequestExceptionDoesNotBlockTermination() {
Context ctx = Context.newPendingRequest(MyRequestHandler.newRequestException());
try {
ctx.request.connect(MyResponseHandler.newEagerCompletion());
@@ -97,7 +97,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatRequestExceptionWithEagerHandleResponseBlocksTermination() {
+ void requireThatRequestExceptionWithEagerHandleResponseBlocksTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newRequestExceptionWithEagerHandleResponse();
Context ctx = Context.newPendingRequest(requestHandler);
try {
@@ -114,7 +114,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatRequestExceptionWithEagerCloseResponseDoesNotBlockTermination() {
+ void requireThatRequestExceptionWithEagerCloseResponseDoesNotBlockTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newRequestExceptionWithEagerCloseResponse();
Context ctx = Context.newPendingRequest(requestHandler);
try {
@@ -129,7 +129,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatNullRequestContentBlocksTermination() {
+ void requireThatNullRequestContentBlocksTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newNullContent();
Context ctx = Context.newPendingRequest(requestHandler);
ctx.request.connect(MyResponseHandler.newEagerCompletion()).close(null);
@@ -142,7 +142,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatNullRequestContentWithEagerHandleResponseBlocksTermination() {
+ void requireThatNullRequestContentWithEagerHandleResponseBlocksTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newNullContentWithEagerHandleResponse();
Context ctx = Context.newPendingRequest(requestHandler);
ctx.request.connect(MyResponseHandler.newEagerCompletion()).close(null);
@@ -154,7 +154,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatNullRequestContentWithEagerCloseResponseBlocksTermination() {
+ void requireThatNullRequestContentWithEagerCloseResponseBlocksTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newNulContentWithEagerCloseResponse();
Context ctx = Context.newPendingRequest(requestHandler);
ContentChannel requestContent = ctx.request.connect(MyResponseHandler.newEagerCompletion());
@@ -166,7 +166,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatRequestContentWriteFailedDoesNotBlockTermination() {
+ void requireThatRequestContentWriteFailedDoesNotBlockTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerFail();
Context ctx = Context.newPendingRequest(requestHandler);
ContentChannel requestContent = ctx.request.connect(MyResponseHandler.newEagerCompletion());
@@ -179,7 +179,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatRequestContentWriteExceptionDoesNotBlockTermination() {
+ void requireThatRequestContentWriteExceptionDoesNotBlockTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newContentWriteExceptionWithEagerCompletion();
Context ctx = Context.newPendingRequest(requestHandler);
ContentChannel requestContent = ctx.request.connect(MyResponseHandler.newEagerCompletion());
@@ -197,7 +197,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatRequestContentWriteExceptionDoesNotForceTermination() {
+ void requireThatRequestContentWriteExceptionDoesNotForceTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newContentWriteExceptionWithEagerCompletion();
Context ctx = Context.newPendingRequest(requestHandler);
ContentChannel requestContent = ctx.request.connect(MyResponseHandler.newEagerCompletion());
@@ -216,7 +216,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatRequestContentWriteExceptionWithCompletionDoesNotBlockTermination() {
+ void requireThatRequestContentWriteExceptionWithCompletionDoesNotBlockTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newContentWriteExceptionWithEagerCompletion();
Context ctx = Context.newPendingRequest(requestHandler);
ContentChannel requestContent = ctx.request.connect(MyResponseHandler.newEagerCompletion());
@@ -234,7 +234,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatRequestContentCloseFailedDoesNotBlockTermination() {
+ void requireThatRequestContentCloseFailedDoesNotBlockTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerFail();
Context ctx = Context.newPendingRequest(requestHandler);
ContentChannel requestContent = ctx.request.connect(MyResponseHandler.newEagerCompletion());
@@ -246,7 +246,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatRequestContentCloseExceptionDoesNotBlockTermination() {
+ void requireThatRequestContentCloseExceptionDoesNotBlockTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newContentCloseException();
Context ctx = Context.newPendingRequest(requestHandler);
ContentChannel requestContent = ctx.request.connect(MyResponseHandler.newEagerCompletion());
@@ -263,7 +263,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatRequestContentCloseExceptionWithCompletionDoesNotBlockTermination() {
+ void requireThatRequestContentCloseExceptionWithCompletionDoesNotBlockTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newContentCloseException();
Context ctx = Context.newPendingRequest(requestHandler);
ContentChannel requestContent = ctx.request.connect(MyResponseHandler.newEagerCompletion());
@@ -280,7 +280,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatRequestWriteCompletionBlocksTermination() {
+ void requireThatRequestWriteCompletionBlocksTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerCloseResponse();
Context ctx = Context.newPendingRequest(requestHandler);
ContentChannel requestContent = ctx.request.connect(MyResponseHandler.newEagerCompletion());
@@ -295,7 +295,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatRequestWriteCompletionExceptionDoesNotBlockTermination() {
+ void requireThatRequestWriteCompletionExceptionDoesNotBlockTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerCloseResponse();
Context ctx = Context.newPendingRequest(requestHandler);
ContentChannel requestContent = ctx.request.connect(MyResponseHandler.newEagerCompletion());
@@ -315,7 +315,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatRequestCloseCompletionBlocksTermination() {
+ void requireThatRequestCloseCompletionBlocksTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerCloseResponse();
Context ctx = Context.newPendingRequest(requestHandler);
ContentChannel requestContent = ctx.request.connect(MyResponseHandler.newEagerCompletion());
@@ -328,7 +328,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatRequestCloseCompletionExceptionDoesNotBlockTermination() {
+ void requireThatRequestCloseCompletionExceptionDoesNotBlockTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerCloseResponse();
Context ctx = Context.newPendingRequest(requestHandler);
ContentChannel requestContent = ctx.request.connect(MyResponseHandler.newEagerCompletion());
@@ -346,7 +346,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatNullResponseContentBlocksTermination() {
+ void requireThatNullResponseContentBlocksTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerRespondWithEagerCompletion();
Context ctx = Context.newPendingRequest(requestHandler);
MyResponseHandler responseHandler = MyResponseHandler.newNullContent();
@@ -360,7 +360,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatResponseExceptionDoesNotBlockTermination() {
+ void requireThatResponseExceptionDoesNotBlockTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerCompletion();
Context ctx = Context.newPendingRequest(requestHandler);
ctx.request.connect(MyResponseHandler.newResponseException()).close(null);
@@ -376,7 +376,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatResponseContentWriteFailedDoesNotBlockTermination() {
+ void requireThatResponseContentWriteFailedDoesNotBlockTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerCompletion();
Context ctx = Context.newPendingRequest(requestHandler);
MyResponseHandler responseHandler = MyResponseHandler.newEagerFail();
@@ -390,7 +390,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatResponseContentCloseFailedDoesNotBlockTermination() {
+ void requireThatResponseContentCloseFailedDoesNotBlockTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerCompletion();
Context ctx = Context.newPendingRequest(requestHandler);
MyResponseHandler responseHandler = MyResponseHandler.newEagerFail();
@@ -403,7 +403,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatResponseContentWriteExceptionDoesNotBlockTermination() {
+ void requireThatResponseContentWriteExceptionDoesNotBlockTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerCompletion();
Context ctx = Context.newPendingRequest(requestHandler);
MyResponseHandler responseHandler = MyResponseHandler.newContentWriteException();
@@ -423,7 +423,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatResponseContentWriteExceptionDoesNotForceTermination() {
+ void requireThatResponseContentWriteExceptionDoesNotForceTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerCompletion();
Context ctx = Context.newPendingRequest(requestHandler);
MyResponseHandler responseHandler = MyResponseHandler.newContentWriteException();
@@ -444,7 +444,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatResponseContentWriteExceptionWithCompletionDoesNotBlockTermination() {
+ void requireThatResponseContentWriteExceptionWithCompletionDoesNotBlockTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerCompletion();
Context ctx = Context.newPendingRequest(requestHandler);
MyResponseHandler responseHandler = MyResponseHandler.newContentWriteException();
@@ -464,7 +464,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatResponseContentCloseExceptionDoesNotBlockTermination() {
+ void requireThatResponseContentCloseExceptionDoesNotBlockTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerCompletion();
Context ctx = Context.newPendingRequest(requestHandler);
ctx.request.connect(MyResponseHandler.newContentCloseException()).close(null);
@@ -480,7 +480,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatResponseContentCloseExceptionWithCompletionDoesNotBlockTermination() {
+ void requireThatResponseContentCloseExceptionWithCompletionDoesNotBlockTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerCompletion();
Context ctx = Context.newPendingRequest(requestHandler);
ctx.request.connect(MyResponseHandler.newContentCloseException()).close(null);
@@ -496,7 +496,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatResponseWriteCompletionBlocksTermination() {
+ void requireThatResponseWriteCompletionBlocksTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerRespondWithEagerCompletion();
Context ctx = Context.newPendingRequest(requestHandler);
MyResponseHandler responseHandler = MyResponseHandler.newInstance();
@@ -513,7 +513,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatResponseWriteCompletionExceptionDoesNotBlockTermination() {
+ void requireThatResponseWriteCompletionExceptionDoesNotBlockTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerRespondWithEagerCompletion();
Context ctx = Context.newPendingRequest(requestHandler);
MyResponseHandler responseHandler = MyResponseHandler.newInstance();
@@ -535,7 +535,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatResponseCloseCompletionBlocksTermination() {
+ void requireThatResponseCloseCompletionBlocksTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerRespondWithEagerCompletion();
Context ctx = Context.newPendingRequest(requestHandler);
MyResponseHandler responseHandler = MyResponseHandler.newInstance();
@@ -550,7 +550,7 @@ public class ContainerShutdownTestCase {
}
@Test
- public void requireThatResponseCloseCompletionExceptionDoesNotBlockTermination() {
+ void requireThatResponseCloseCompletionExceptionDoesNotBlockTermination() {
MyRequestHandler requestHandler = MyRequestHandler.newEagerRespondWithEagerCompletion();
Context ctx = Context.newPendingRequest(requestHandler);
MyResponseHandler responseHandler = MyResponseHandler.newInstance();
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerSnapshotTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerSnapshotTestCase.java
index dc1f3c7609e..2f93832b503 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerSnapshotTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerSnapshotTestCase.java
@@ -11,16 +11,16 @@ import com.yahoo.jdisc.handler.ContentChannel;
import com.yahoo.jdisc.handler.RequestHandler;
import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.nio.ByteBuffer;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -29,7 +29,7 @@ import static org.junit.Assert.assertTrue;
public class ContainerSnapshotTestCase {
@Test
- public void requireThatServerHandlerCanBeResolved() {
+ void requireThatServerHandlerCanBeResolved() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
builder.serverBindings().bind("http://foo/*", MyRequestHandler.newInstance());
@@ -59,7 +59,7 @@ public class ContainerSnapshotTestCase {
}
@Test
- public void requireThatClientHandlerCanBeResolved() {
+ void requireThatClientHandlerCanBeResolved() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
builder.clientBindings().bind("http://foo/*", MyRequestHandler.newInstance());
@@ -89,7 +89,7 @@ public class ContainerSnapshotTestCase {
}
@Test
- public void requireThatClientBindingsAreUsed() {
+ void requireThatClientBindingsAreUsed() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
builder.clientBindings().bind("http://host/path", MyRequestHandler.newInstance());
@@ -101,7 +101,7 @@ public class ContainerSnapshotTestCase {
}
@Test
- public void requireThatBindingMatchIsSetByResolveHandler() {
+ void requireThatBindingMatchIsSetByResolveHandler() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
builder.serverBindings().bind("http://*/*", MyRequestHandler.newInstance());
@@ -121,7 +121,7 @@ public class ContainerSnapshotTestCase {
}
@Test
- public void requireThatNewRequestHasSameSnapshot() {
+ void requireThatNewRequestHasSameSnapshot() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
driver.activateContainer(driver.newContainerBuilder());
Request foo = new Request(driver, URI.create("http://host/foo"));
@@ -133,7 +133,7 @@ public class ContainerSnapshotTestCase {
}
@Test
- public void requireThatActiveInjectorIsUsed() {
+ void requireThatActiveInjectorIsUsed() {
final Object obj = new Object();
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi(new AbstractModule() {
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerTerminationTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerTerminationTestCase.java
index de22a49895f..110ea9745b6 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerTerminationTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerTerminationTestCase.java
@@ -4,11 +4,11 @@ package com.yahoo.jdisc.core;
import com.yahoo.jdisc.application.ContainerBuilder;
import com.yahoo.jdisc.application.DeactivatedContainer;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Simon Thoresen Hult
@@ -16,14 +16,14 @@ import static org.junit.Assert.assertTrue;
public class ContainerTerminationTestCase {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
Object obj = new Object();
ContainerTermination termination = new ContainerTermination(obj);
assertSame(obj, termination.appContext());
}
@Test
- public void requireThatAppContextIsFromBuilder() {
+ void requireThatAppContextIsFromBuilder() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
Object obj = new Object();
@@ -35,7 +35,7 @@ public class ContainerTerminationTestCase {
}
@Test
- public void requireThatEarlyTerminationIsNotified() {
+ void requireThatEarlyTerminationIsNotified() {
ContainerTermination termination = new ContainerTermination(null);
termination.run();
MyTask task = new MyTask();
@@ -44,7 +44,7 @@ public class ContainerTerminationTestCase {
}
@Test
- public void requireThatLaterTerminationIsNotified() {
+ void requireThatLaterTerminationIsNotified() {
ContainerTermination termination = new ContainerTermination(null);
MyTask task = new MyTask();
termination.notifyTermination(task);
@@ -54,7 +54,7 @@ public class ContainerTerminationTestCase {
}
@Test
- public void requireThatNotifyCanOnlyBeCalledOnce() {
+ void requireThatNotifyCanOnlyBeCalledOnce() {
ContainerTermination termination = new ContainerTermination(null);
termination.notifyTermination(new MyTask());
try {
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerWatchdogTest.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerWatchdogTest.java
index e72b01d8b8f..d669961e728 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerWatchdogTest.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ContainerWatchdogTest.java
@@ -4,14 +4,14 @@ package com.yahoo.jdisc.core;
import com.yahoo.jdisc.Metric;
import com.yahoo.jdisc.test.TestDriver;
import com.yahoo.test.ManualClock;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
/**
@@ -20,7 +20,7 @@ import static org.mockito.Mockito.mock;
public class ContainerWatchdogTest {
@Test
- public void watchdog_counts_stale_container() {
+ void watchdog_counts_stale_container() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ManualClock clock = new ManualClock(Instant.EPOCH);
DummyMetric metric = new DummyMetric();
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/DefaultBindingSelectorTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/DefaultBindingSelectorTestCase.java
index 66c92aa138a..50db994c4d3 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/DefaultBindingSelectorTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/DefaultBindingSelectorTestCase.java
@@ -4,12 +4,12 @@ package com.yahoo.jdisc.core;
import com.google.inject.Guice;
import com.yahoo.jdisc.application.BindingSet;
import com.yahoo.jdisc.application.BindingSetSelector;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
-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;
/**
@@ -18,13 +18,13 @@ import static org.junit.Assert.assertTrue;
public class DefaultBindingSelectorTestCase {
@Test
- public void requireThatClassIsInjectedByDefault() {
+ void requireThatClassIsInjectedByDefault() {
BindingSetSelector selector = Guice.createInjector().getInstance(BindingSetSelector.class);
assertTrue(selector instanceof DefaultBindingSelector);
}
@Test
- public void requireThatDefaultSetIsAlwaysSelected() {
+ void requireThatDefaultSetIsAlwaysSelected() {
DefaultBindingSelector selector = new DefaultBindingSelector();
assertEquals(BindingSet.DEFAULT, selector.select(null));
for (int i = 0; i < 69; ++i) {
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ExportPackagesIT.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ExportPackagesIT.java
index 1cd8db67476..e9aba0893f9 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ExportPackagesIT.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ExportPackagesIT.java
@@ -1,12 +1,12 @@
package com.yahoo.jdisc.core;
-import org.junit.ClassRule;
-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.FileReader;
import java.io.IOException;
+import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
@@ -15,8 +15,8 @@ import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* Integration tests for {@link ExportPackages}.
@@ -49,22 +49,22 @@ public class ExportPackagesIT {
"javax.activation.jar"
).map(f -> JAR_PATH + f).toList();
- @ClassRule
- public static TemporaryFolder tempFolder = new TemporaryFolder();
+ @TempDir
+ public static File tempFolder;
@Test
- public void exported_packages_are_not_changed_unintentionally() throws Exception {
+ void exported_packages_are_not_changed_unintentionally() throws Exception {
Properties actualProperties = getPropertiesFromFile(createPropertiesFile());
String actualValue = actualProperties.getProperty(ExportPackages.EXPORT_PACKAGES);
- assertNotNull("Missing exportPackages property in file.", actualValue);
+ assertNotNull(actualValue, "Missing exportPackages property in file.");
Properties expectedProperties = getPropertiesFromFile(expectedExportPackages);
String expectedValue = expectedProperties.getProperty(ExportPackages.EXPORT_PACKAGES);
- assertNotNull("Missing exportPackages property in file.", expectedValue);
+ assertNotNull(expectedValue, "Missing exportPackages property in file.");
Set<String> actualPackages = getPackages(actualValue);
Set<String> expectedPackages = getPackages(expectedValue);
- if (! actualPackages.equals(expectedPackages)) {
+ if (!actualPackages.equals(expectedPackages)) {
StringBuilder message = getDiff(actualPackages, expectedPackages);
message.append("\n\nIf this test fails due to an intentional change in exported packages, run the following command:\n")
.append("$ cp jdisc_core/target/classes/exportPackages.properties jdisc_core/src/test/resources/")
@@ -116,7 +116,7 @@ public class ExportPackagesIT {
}
private static File createPropertiesFile() throws IOException {
- File file = tempFolder.newFile(ExportPackages.PROPERTIES_FILE);
+ File file = Paths.get(tempFolder.toString(), ExportPackages.PROPERTIES_FILE).toFile();
String[] args = Stream.concat(Stream.of(file.getAbsolutePath()),
RE_EXPORTED_BUNDLES.stream()).toArray(String[]::new);
ExportPackages.main(args);
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/FelixFrameworkTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/FelixFrameworkTestCase.java
index fb663afa23f..d1cb59dbc30 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/FelixFrameworkTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/FelixFrameworkTestCase.java
@@ -2,10 +2,10 @@
package com.yahoo.jdisc.core;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.osgi.framework.BundleException;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -14,20 +14,20 @@ import static org.junit.Assert.fail;
public class FelixFrameworkTestCase {
@Test
- public void requireThatLifecycleWorks() throws BundleException {
+ void requireThatLifecycleWorks() throws BundleException {
FelixFramework felix = TestDriver.newOsgiFramework();
felix.start();
felix.stop();
}
@Test
- public void requireThatStopWithoutStartDoesNotThrowException() throws BundleException {
+ void requireThatStopWithoutStartDoesNotThrowException() throws BundleException {
FelixFramework felix = TestDriver.newOsgiFramework();
felix.stop();
}
@Test
- public void requireThatInstallCanThrowException() throws BundleException {
+ void requireThatInstallCanThrowException() throws BundleException {
FelixFramework felix = TestDriver.newOsgiFramework();
felix.start();
try {
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/FelixParamsTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/FelixParamsTestCase.java
index 490470b4fdf..6c488f8b735 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/FelixParamsTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/FelixParamsTestCase.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.jdisc.core;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.osgi.framework.Constants;
import java.util.Arrays;
@@ -9,9 +9,9 @@ import java.util.LinkedList;
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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Simon Thoresen Hult
@@ -19,7 +19,7 @@ import static org.junit.Assert.assertTrue;
public class FelixParamsTestCase {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
FelixParams params = new FelixParams();
params.setCachePath("foo");
assertEquals("foo", params.getCachePath());
@@ -28,7 +28,7 @@ public class FelixParamsTestCase {
}
@Test
- public void requireThatSystemPackagesAreNotReplaced() {
+ void requireThatSystemPackagesAreNotReplaced() {
String systemPackages = ExportPackages.getSystemPackages();
FelixParams params = new FelixParams(systemPackages);
@@ -46,7 +46,7 @@ public class FelixParamsTestCase {
}
@Test
- public void requireThatExportsAreIncludedInConfig() {
+ void requireThatExportsAreIncludedInConfig() {
FelixParams params = new FelixParams();
Map<String, String> config = params.toConfig();
assertNotNull(config);
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/OsgiLogHandlerTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/OsgiLogHandlerTestCase.java
index 7c07623814e..626cae67c41 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/OsgiLogHandlerTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/OsgiLogHandlerTestCase.java
@@ -1,12 +1,11 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.core;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.osgi.framework.ServiceReference;
import org.osgi.service.log.LogService;
import java.time.Instant;
-import java.util.Arrays;
import java.util.Enumeration;
import java.util.ResourceBundle;
import java.util.logging.Handler;
@@ -14,11 +13,11 @@ 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.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
/**
* @author Simon Thoresen Hult
@@ -26,7 +25,7 @@ import static org.junit.Assert.assertTrue;
public class OsgiLogHandlerTestCase {
@Test
- public void requireThatLogRecordsArePublishedToLogService() {
+ void requireThatLogRecordsArePublishedToLogService() {
MyLogService logService = new MyLogService();
Logger log = newLogger(logService);
@@ -43,7 +42,7 @@ public class OsgiLogHandlerTestCase {
}
@Test
- public void requireThatStadardLogLevelsAreConverted() {
+ void requireThatStadardLogLevelsAreConverted() {
assertLogLevel(LogService.LOG_ERROR, Level.SEVERE);
assertLogLevel(LogService.LOG_WARNING, Level.WARNING);
assertLogLevel(LogService.LOG_INFO, Level.INFO);
@@ -54,7 +53,7 @@ public class OsgiLogHandlerTestCase {
}
@Test
- public void requireThatCustomLogLevelsAreConverted() {
+ void requireThatCustomLogLevelsAreConverted() {
for (int i = Level.ALL.intValue() - 69; i < Level.OFF.intValue() + 69; ++i) {
int expectedLevel;
if (i >= Level.SEVERE.intValue()) {
@@ -71,7 +70,7 @@ public class OsgiLogHandlerTestCase {
}
@Test
- public void requireThatJdk14PropertiesAreAvailableThroughServiceReference() {
+ void requireThatJdk14PropertiesAreAvailableThroughServiceReference() {
MyLogService logService = new MyLogService();
Logger log = newLogger(logService);
@@ -93,19 +92,19 @@ public class OsgiLogHandlerTestCase {
ServiceReference<?> ref = logService.lastServiceReference;
assertNotNull(ref);
- assertTrue(Arrays.equals(new String[] { "LEVEL",
- "LOGGER_NAME",
- "MESSAGE",
- "MILLIS",
- "PARAMETERS",
- "RESOURCE_BUNDLE",
- "RESOURCE_BUNDLE_NAME",
- "SEQUENCE_NUMBER",
- "SOURCE_CLASS_NAME",
- "SOURCE_METHOD_NAME",
- "THREAD_ID",
- "THROWN" },
- ref.getPropertyKeys()));
+ assertArrayEquals(new String[]{"LEVEL",
+ "LOGGER_NAME",
+ "MESSAGE",
+ "MILLIS",
+ "PARAMETERS",
+ "RESOURCE_BUNDLE",
+ "RESOURCE_BUNDLE_NAME",
+ "SEQUENCE_NUMBER",
+ "SOURCE_CLASS_NAME",
+ "SOURCE_METHOD_NAME",
+ "THREAD_ID",
+ "THROWN"},
+ ref.getPropertyKeys());
assertEquals(Level.INFO, ref.getProperty("LEVEL"));
assertEquals("loggerName", ref.getProperty("LOGGER_NAME"));
assertEquals("message", ref.getProperty("MESSAGE"));
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/OsgiLogManagerTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/OsgiLogManagerTestCase.java
index be4c0ada514..7b5af97ca13 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/OsgiLogManagerTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/OsgiLogManagerTestCase.java
@@ -2,7 +2,7 @@
package com.yahoo.jdisc.core;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
@@ -13,9 +13,9 @@ import org.osgi.service.log.LogService;
import java.util.logging.Level;
import java.util.logging.Logger;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
/**
@@ -24,7 +24,7 @@ import static org.junit.Assert.assertSame;
public class OsgiLogManagerTestCase {
@Test
- public void requireThatAllLogMethodsAreImplemented() throws BundleException {
+ void requireThatAllLogMethodsAreImplemented() throws BundleException {
FelixFramework felix = TestDriver.newOsgiFramework();
felix.start();
@@ -55,7 +55,7 @@ public class OsgiLogManagerTestCase {
}
@Test
- public void requireThatLogManagerWritesToAllRegisteredLogServices() throws BundleException {
+ void requireThatLogManagerWritesToAllRegisteredLogServices() throws BundleException {
FelixFramework felix = TestDriver.newOsgiFramework();
felix.start();
@@ -122,7 +122,7 @@ public class OsgiLogManagerTestCase {
}
@Test
- public void requireThatRootLoggerModificationCanBeDisabled() throws BundleException {
+ void requireThatRootLoggerModificationCanBeDisabled() throws BundleException {
Logger logger = Logger.getLogger("");
logger.setLevel(Level.WARNING);
@@ -134,7 +134,7 @@ public class OsgiLogManagerTestCase {
}
@Test
- public void requireThatRootLoggerLevelIsModifiedIfNoLoggerConfigIsGiven() {
+ void requireThatRootLoggerLevelIsModifiedIfNoLoggerConfigIsGiven() {
Logger logger = Logger.getLogger("");
logger.setLevel(Level.WARNING);
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/OsgiLogServiceTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/OsgiLogServiceTestCase.java
index 15377d7ae37..bfdaad9450f 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/OsgiLogServiceTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/OsgiLogServiceTestCase.java
@@ -3,15 +3,15 @@ package com.yahoo.jdisc.core;
import com.yahoo.jdisc.application.OsgiFramework;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.service.log.LogReaderService;
import org.osgi.service.log.LogService;
import org.osgi.util.tracker.ServiceTracker;
-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;
/**
@@ -20,12 +20,12 @@ import static org.junit.Assert.fail;
public class OsgiLogServiceTestCase {
@Test
- public void requireThatLogServiceIsRegistered() throws BundleException, InterruptedException {
+ void requireThatLogServiceIsRegistered() throws BundleException, InterruptedException {
OsgiFramework osgi = TestDriver.newOsgiFramework();
osgi.start();
- ServiceTracker<?,?> logs = newTracker(osgi, LogService.class);
- ServiceTracker<?,?> logReaders = newTracker(osgi, LogReaderService.class);
+ ServiceTracker<?, ?> logs = newTracker(osgi, LogService.class);
+ ServiceTracker<?, ?> logReaders = newTracker(osgi, LogReaderService.class);
assertEquals(1, logs.getTrackingCount());
assertEquals(1, logReaders.getTrackingCount());
@@ -38,7 +38,7 @@ public class OsgiLogServiceTestCase {
}
@Test
- public void requireThatLogServiceCanNotBeStartedTwice() throws BundleException {
+ void requireThatLogServiceCanNotBeStartedTwice() throws BundleException {
OsgiFramework osgi = TestDriver.newOsgiFramework();
osgi.start();
@@ -57,7 +57,7 @@ public class OsgiLogServiceTestCase {
}
@Test
- public void requireThatLogServiceCanNotBeStoppedTwice() throws BundleException {
+ void requireThatLogServiceCanNotBeStoppedTwice() throws BundleException {
OsgiFramework osgi = TestDriver.newOsgiFramework();
osgi.start();
@@ -77,7 +77,7 @@ public class OsgiLogServiceTestCase {
}
@Test
- public void requireThatUnstartedLogServiceCanNotBeStopped() throws BundleException {
+ void requireThatUnstartedLogServiceCanNotBeStopped() throws BundleException {
try {
new OsgiLogService().stop();
fail();
@@ -87,7 +87,7 @@ public class OsgiLogServiceTestCase {
}
@Test
- public void requireThatLogServiceCanNotStartWithoutBundleContext() throws BundleException {
+ void requireThatLogServiceCanNotStartWithoutBundleContext() throws BundleException {
try {
new OsgiLogService().start(null);
fail();
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ScheduledQueueTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ScheduledQueueTestCase.java
index 163111c641d..cd963caa8d2 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/ScheduledQueueTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/ScheduledQueueTestCase.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.jdisc.core;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.LinkedList;
@@ -11,9 +11,9 @@ import java.util.Queue;
import static com.yahoo.jdisc.core.ScheduledQueue.MILLIS_PER_SLOT;
import static com.yahoo.jdisc.core.ScheduledQueue.NUM_SLOTS;
import static com.yahoo.jdisc.core.ScheduledQueue.NUM_SLOTS_UNDILATED;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -21,21 +21,21 @@ import static org.junit.Assert.fail;
public class ScheduledQueueTestCase {
@Test
- public void requireThatSlotMaskPreventsOverflow() {
+ void requireThatSlotMaskPreventsOverflow() {
for (int slot = 0; slot < NUM_SLOTS * 2; ++slot) {
assertTrue((slot & ScheduledQueue.SLOT_MASK) < NUM_SLOTS);
}
}
@Test
- public void requireThatIterShiftDiscardsSlotBits() {
+ void requireThatIterShiftDiscardsSlotBits() {
for (int slot = 0; slot < NUM_SLOTS * 2; ++slot) {
assertEquals(slot / NUM_SLOTS, slot >> ScheduledQueue.ITER_SHIFT);
}
}
@Test
- public void requireThatNewEntryDoesNotAcceptNull() {
+ void requireThatNewEntryDoesNotAcceptNull() {
ScheduledQueue queue = new ScheduledQueue(0);
try {
queue.newEntry(null);
@@ -46,7 +46,7 @@ public class ScheduledQueueTestCase {
}
@Test
- public void requireThatEntriesCanBeScheduled() {
+ void requireThatEntriesCanBeScheduled() {
ScheduledQueue queue = new ScheduledQueue(0);
Object foo = new Object();
ScheduledQueue.Entry entry = queue.newEntry(foo);
@@ -57,7 +57,7 @@ public class ScheduledQueueTestCase {
}
@Test
- public void requireThatEntriesCanBeRescheduled() {
+ void requireThatEntriesCanBeRescheduled() {
ScheduledQueue queue = new ScheduledQueue(0);
Object foo = new Object();
ScheduledQueue.Entry entry = queue.newEntry(foo);
@@ -69,7 +69,7 @@ public class ScheduledQueueTestCase {
}
@Test
- public void requireThatEntriesCanBeUnscheduled() {
+ void requireThatEntriesCanBeUnscheduled() {
ScheduledQueue queue = new ScheduledQueue(0);
Object foo = new Object();
ScheduledQueue.Entry entry = queue.newEntry(foo);
@@ -80,7 +80,7 @@ public class ScheduledQueueTestCase {
}
@Test
- public void requireThatDrainToOnlyDrainsExpiredEntries() {
+ void requireThatDrainToOnlyDrainsExpiredEntries() {
ScheduledQueue queue = new ScheduledQueue(0);
Object foo = scheduleAt(queue, 100);
Object bar = scheduleAt(queue, 300);
@@ -93,7 +93,7 @@ public class ScheduledQueueTestCase {
}
@Test
- public void requireThatEntriesDoNotExpireMoreThanOnce() {
+ void requireThatEntriesDoNotExpireMoreThanOnce() {
ScheduledQueue queue = new ScheduledQueue(0);
Object foo = scheduleAt(queue, NUM_SLOTS * MILLIS_PER_SLOT + 50);
@@ -108,7 +108,7 @@ public class ScheduledQueueTestCase {
}
@Test
- public void requireThatNegativeScheduleTranslatesToNow() {
+ void requireThatNegativeScheduleTranslatesToNow() {
ScheduledQueue queue = new ScheduledQueue(0);
Object foo = scheduleAt(queue, -100);
@@ -116,7 +116,7 @@ public class ScheduledQueueTestCase {
}
@Test
- public void requireThatDrainToPerformsTimeDilationWhenOverloaded() {
+ void requireThatDrainToPerformsTimeDilationWhenOverloaded() {
ScheduledQueue queue = new ScheduledQueue(0);
List<Object> payloads = new LinkedList<>();
for (int i = 1; i <= NUM_SLOTS_UNDILATED + 1; ++i) {
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/SystemTimerTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/SystemTimerTestCase.java
index 52e25877402..dc6d3b30cb2 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/SystemTimerTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/SystemTimerTestCase.java
@@ -3,9 +3,9 @@ package com.yahoo.jdisc.core;
import com.google.inject.Guice;
import com.yahoo.jdisc.Timer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -14,13 +14,13 @@ import static org.junit.Assert.assertTrue;
public class SystemTimerTestCase {
@Test
- public void requireThatClassIsInjectedByDefault() {
+ void requireThatClassIsInjectedByDefault() {
Timer timer = Guice.createInjector().getInstance(Timer.class);
assertTrue(timer instanceof SystemTimer);
}
@Test
- public void requireThatSystemTimerIsSane() {
+ void requireThatSystemTimerIsSane() {
long before = System.currentTimeMillis();
long millis = new SystemTimer().currentTimeMillis();
long after = System.currentTimeMillis();
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/core/TimeoutManagerImplTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/core/TimeoutManagerImplTestCase.java
index 75ebad12158..0308abebd8a 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/core/TimeoutManagerImplTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/core/TimeoutManagerImplTestCase.java
@@ -19,7 +19,7 @@ import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.service.CurrentContainer;
import com.yahoo.jdisc.test.NonWorkingRequest;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.nio.ByteBuffer;
@@ -28,13 +28,13 @@ import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
-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.assertSame;
-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.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -44,35 +44,35 @@ public class TimeoutManagerImplTestCase {
private static final String REQUEST_URI = "http://host/path";
@Test
- public void requireThatDefaultIsNoTimeout() {
+ void requireThatDefaultIsNoTimeout() {
Context ctx = new Context(MyRequestHandler.newEagerResponse());
assertNull(ctx.dispatchRequest(null, MyResponseHandler.newInstance()));
assertTrue(ctx.close());
}
@Test
- public void requireThatTimeoutCanBeSetByServerProvider() {
+ void requireThatTimeoutCanBeSetByServerProvider() {
Context ctx = new Context(MyRequestHandler.newEagerResponse());
assertEquals(Long.valueOf(69), ctx.dispatchRequest(69L, MyResponseHandler.newInstance()));
assertTrue(ctx.close());
}
@Test
- public void requireThatTimeoutCanBeSetByRequestHandler() {
+ void requireThatTimeoutCanBeSetByRequestHandler() {
Context ctx = new Context(MyRequestHandler.newTimeoutWithEagerResponse(69));
assertEquals(Long.valueOf(69), ctx.dispatchRequest(null, MyResponseHandler.newInstance()));
assertTrue(ctx.close());
}
@Test
- public void requireThatTimeoutRequestHandlerTimeoutHasPrecedence() {
+ void requireThatTimeoutRequestHandlerTimeoutHasPrecedence() {
Context ctx = new Context(MyRequestHandler.newTimeoutWithEagerResponse(6));
assertEquals(Long.valueOf(6), ctx.dispatchRequest(9L, MyResponseHandler.newInstance()));
assertTrue(ctx.close());
}
@Test
- public void requireThatResponseCancelsTimeout() throws InterruptedException {
+ void requireThatResponseCancelsTimeout() throws InterruptedException {
Context ctx = new Context(MyRequestHandler.newEagerResponse());
assertEquals(Response.Status.OK, ctx.awaitResponse(69L, MyResponseHandler.newInstance()));
assertEquals(Response.Status.OK, ctx.awaitResponse(69L, MyResponseHandler.newInstance()));
@@ -80,7 +80,7 @@ public class TimeoutManagerImplTestCase {
}
@Test
- public void requireThatNullRequestContentCanTimeout() throws InterruptedException {
+ void requireThatNullRequestContentCanTimeout() throws InterruptedException {
Context ctx = new Context(MyRequestHandler.newNullContent());
assertEquals(Response.Status.GATEWAY_TIMEOUT, ctx.awaitResponse(69L, MyResponseHandler.newInstance()));
assertEquals(Response.Status.GATEWAY_TIMEOUT, ctx.awaitResponse(69L, MyResponseHandler.newInstance()));
@@ -88,7 +88,7 @@ public class TimeoutManagerImplTestCase {
}
@Test
- public void requireThatTimeoutWorksAfterRequestDenied() throws InterruptedException {
+ void requireThatTimeoutWorksAfterRequestDenied() throws InterruptedException {
Context ctx = new Context(MyRequestHandler.newFirstRequestDenied());
try {
ctx.dispatchRequest(null, MyResponseHandler.newInstance());
@@ -101,7 +101,7 @@ public class TimeoutManagerImplTestCase {
}
@Test
- public void requireThatTimeoutWorksAfterResponseDenied() throws InterruptedException {
+ void requireThatTimeoutWorksAfterResponseDenied() throws InterruptedException {
Context ctx = new Context(MyRequestHandler.newInstance());
assertEquals(Response.Status.GATEWAY_TIMEOUT, ctx.awaitResponse(69L, MyResponseHandler.newResponseDenied()));
assertEquals(Response.Status.GATEWAY_TIMEOUT, ctx.awaitResponse(69L, MyResponseHandler.newInstance()));
@@ -109,7 +109,7 @@ public class TimeoutManagerImplTestCase {
}
@Test
- public void requireThatTimeoutWorksAfterResponseThrowsException() throws InterruptedException {
+ void requireThatTimeoutWorksAfterResponseThrowsException() throws InterruptedException {
Context ctx = new Context(MyRequestHandler.newInstance());
assertEquals(Response.Status.GATEWAY_TIMEOUT, ctx.awaitResponse(69L, MyResponseHandler.newThrowException()));
assertEquals(Response.Status.GATEWAY_TIMEOUT, ctx.awaitResponse(69L, MyResponseHandler.newInstance()));
@@ -117,7 +117,7 @@ public class TimeoutManagerImplTestCase {
}
@Test
- public void requireThatTimeoutWorksAfterResponseInterruptsThread() throws InterruptedException {
+ void requireThatTimeoutWorksAfterResponseInterruptsThread() throws InterruptedException {
Context ctx = new Context(MyRequestHandler.newInstance());
assertEquals(Response.Status.GATEWAY_TIMEOUT, ctx.awaitResponse(69L, MyResponseHandler.newInterruptThread()));
assertEquals(Response.Status.GATEWAY_TIMEOUT, ctx.awaitResponse(69L, MyResponseHandler.newInstance()));
@@ -125,7 +125,7 @@ public class TimeoutManagerImplTestCase {
}
@Test
- public void requireThatTimeoutOccursInOrder() throws InterruptedException {
+ void requireThatTimeoutOccursInOrder() throws InterruptedException {
Context ctx = new Context(MyRequestHandler.newInstance());
MyResponseHandler foo = MyResponseHandler.newInstance();
ctx.dispatchRequest(300L, foo);
@@ -152,7 +152,7 @@ public class TimeoutManagerImplTestCase {
}
@Test
- public void requireThatResponseHandlerIsWellBehavedAfterTimeout() throws InterruptedException {
+ void requireThatResponseHandlerIsWellBehavedAfterTimeout() throws InterruptedException {
Context ctx = new Context(MyRequestHandler.newInstance());
assertEquals(Response.Status.GATEWAY_TIMEOUT, ctx.awaitResponse(69L, MyResponseHandler.newInstance()));
@@ -172,11 +172,11 @@ public class TimeoutManagerImplTestCase {
}
@Test
- public void requireThatManagedHandlerForwardsAllCalls() throws InterruptedException {
+ void requireThatManagedHandlerForwardsAllCalls() throws InterruptedException {
Request request = NonWorkingRequest.newInstance(REQUEST_URI);
MyRequestHandler requestHandler = MyRequestHandler.newInstance();
TimeoutManagerImpl timeoutManager = new TimeoutManagerImpl(Executors.defaultThreadFactory(),
- new SystemTimer());
+ new SystemTimer());
RequestHandler managedHandler = timeoutManager.manageHandler(requestHandler);
MyResponseHandler responseHandler = MyResponseHandler.newInstance();
@@ -219,7 +219,7 @@ public class TimeoutManagerImplTestCase {
}
@Test
- public void requireThatTimeoutOccursAtExpectedTime() throws InterruptedException {
+ void requireThatTimeoutOccursAtExpectedTime() throws InterruptedException {
final Context ctx = new Context(MyRequestHandler.newInstance());
final MyResponseHandler responseHandler = MyResponseHandler.newInstance();
@@ -251,7 +251,7 @@ public class TimeoutManagerImplTestCase {
}
@Test
- public void requireThatQueueEntryIsRemovedWhenResponseHandlerIsCalledBeforeTimeout() {
+ void requireThatQueueEntryIsRemovedWhenResponseHandlerIsCalledBeforeTimeout() {
Context ctx = new Context(MyRequestHandler.newInstance());
ctx.dispatchRequest(69L, MyResponseHandler.newInstance());
assertTrue(ctx.awaitQueueSize(1, 600, TimeUnit.SECONDS));
@@ -261,7 +261,7 @@ public class TimeoutManagerImplTestCase {
}
@Test
- public void requireThatNoEntryIsMadeIfTimeoutIsNull() {
+ void requireThatNoEntryIsMadeIfTimeoutIsNull() {
Context ctx = new Context(MyRequestHandler.newInstance());
ctx.dispatchRequest(null, MyResponseHandler.newInstance());
assertFalse(ctx.awaitQueueSize(1, 100, TimeUnit.MILLISECONDS));
@@ -271,7 +271,7 @@ public class TimeoutManagerImplTestCase {
}
@Test
- public void requireThatNoEntryIsMadeIfHandleRequestCallsHandleResponse() {
+ void requireThatNoEntryIsMadeIfHandleRequestCallsHandleResponse() {
Context ctx = new Context(MyRequestHandler.newEagerResponse());
ctx.dispatchRequest(69L, MyResponseHandler.newInstance());
assertFalse(ctx.awaitQueueSize(1, 100, TimeUnit.MILLISECONDS));
@@ -280,7 +280,7 @@ public class TimeoutManagerImplTestCase {
}
@Test
- public void requireThatNoEntryIsMadeIfTimeoutHandlerHasBeenSet() {
+ void requireThatNoEntryIsMadeIfTimeoutHandlerHasBeenSet() {
final Context ctx = new Context(MyRequestHandler.newInstance());
new RequestDispatch() {
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/AbstractContentOutputStreamTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/AbstractContentOutputStreamTestCase.java
index 4951ff72ffd..7578e3213dd 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/AbstractContentOutputStreamTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/AbstractContentOutputStreamTestCase.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.jdisc.handler;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@@ -11,8 +11,8 @@ import java.nio.ByteBuffer;
import java.util.ArrayList;
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;
/**
@@ -21,15 +21,15 @@ import static org.junit.Assert.assertTrue;
public class AbstractContentOutputStreamTestCase {
@Test
- public void requireThatStreamCanBeWrittenTo() throws IOException {
+ void requireThatStreamCanBeWrittenTo() throws IOException {
MyOutputStream out = new MyOutputStream();
int len = 2 * AbstractContentOutputStream.BUFFERSIZE;
for (int i = 0; i < len; ++i) {
out.write(69);
- out.write(new byte[] { });
- out.write(new byte[] { 6, 9 });
- out.write(new byte[] { 6, 69, 9 }, 1, 0); // zero length
- out.write(new byte[] { 6, 69, 9 }, 1, 1);
+ out.write(new byte[]{});
+ out.write(new byte[]{6, 9});
+ out.write(new byte[]{6, 69, 9}, 1, 0); // zero length
+ out.write(new byte[]{6, 69, 9}, 1, 1);
}
out.close();
@@ -45,7 +45,7 @@ public class AbstractContentOutputStreamTestCase {
}
@Test
- public void requireThatBigBuffersAreWrittenInOrder() throws IOException {
+ void requireThatBigBuffersAreWrittenInOrder() throws IOException {
MyOutputStream out = new MyOutputStream();
out.write(6);
out.write(new byte[2 * AbstractContentOutputStream.BUFFERSIZE]);
@@ -62,7 +62,7 @@ public class AbstractContentOutputStreamTestCase {
}
@Test
- public void requireThatEmptyBuffersAreNotFlushed() throws Exception {
+ void requireThatEmptyBuffersAreNotFlushed() throws Exception {
MyOutputStream out = new MyOutputStream();
out.close();
assertTrue(out.writes.isEmpty());
@@ -70,9 +70,9 @@ public class AbstractContentOutputStreamTestCase {
}
@Test
- public void requireThatNoExcessiveBytesAreWritten() throws Exception {
+ void requireThatNoExcessiveBytesAreWritten() throws Exception {
MyOutputStream out = new MyOutputStream();
- out.write(new byte[] { 6, 9 });
+ out.write(new byte[]{6, 9});
out.close();
InputStream in = out.toInputStream();
@@ -85,7 +85,7 @@ public class AbstractContentOutputStreamTestCase {
}
@Test
- public void requireThatWrittenArraysAreCopied() throws Exception {
+ void requireThatWrittenArraysAreCopied() throws Exception {
MyOutputStream out = new MyOutputStream();
byte[] buf = new byte[1];
for (byte b = 0; b < 127; ++b) {
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/AbstractRequestHandlerTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/AbstractRequestHandlerTestCase.java
index 6b5382b8bba..14ff6d87555 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/AbstractRequestHandlerTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/AbstractRequestHandlerTestCase.java
@@ -6,18 +6,18 @@ import com.yahoo.jdisc.Response;
import com.yahoo.jdisc.application.ContainerBuilder;
import com.yahoo.jdisc.test.NonWorkingRequest;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.nio.ByteBuffer;
import java.util.concurrent.TimeUnit;
import static java.nio.charset.StandardCharsets.UTF_8;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -28,7 +28,7 @@ public class AbstractRequestHandlerTestCase {
private static final int NUM_REQUESTS = 666;
@Test
- public void requireThatHandleTimeoutIsImplemented() throws Exception {
+ void requireThatHandleTimeoutIsImplemented() throws Exception {
FutureResponse handler = new FutureResponse();
new AbstractRequestHandler() {
@@ -43,7 +43,7 @@ public class AbstractRequestHandlerTestCase {
}
@Test
- public void requireThatHelloWorldWorks() throws InterruptedException {
+ void requireThatHelloWorldWorks() throws InterruptedException {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
builder.serverBindings().bind("http://localhost/", new HelloWorldHandler());
@@ -62,7 +62,7 @@ public class AbstractRequestHandlerTestCase {
}
@Test
- public void requireThatEchoWorks() throws InterruptedException {
+ void requireThatEchoWorks() throws InterruptedException {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
builder.serverBindings().bind("http://localhost/", new EchoHandler());
@@ -83,7 +83,7 @@ public class AbstractRequestHandlerTestCase {
}
@Test
- public void requireThatForwardWorks() throws InterruptedException {
+ void requireThatForwardWorks() throws InterruptedException {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
builder.serverBindings().bind("http://localhost/", new ForwardHandler());
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/BindingNotFoundTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/BindingNotFoundTestCase.java
index 7d76e9de7e2..03fd4368be9 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/BindingNotFoundTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/BindingNotFoundTestCase.java
@@ -4,12 +4,12 @@ package com.yahoo.jdisc.handler;
import com.yahoo.jdisc.Request;
import com.yahoo.jdisc.Response;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
-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;
/**
@@ -18,14 +18,14 @@ import static org.junit.Assert.fail;
public class BindingNotFoundTestCase {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
URI uri = URI.create("http://host/path");
BindingNotFoundException e = new BindingNotFoundException(uri);
assertEquals(uri, e.uri());
}
@Test
- public void requireThatBindingNotFoundIsThrown() {
+ void requireThatBindingNotFoundIsThrown() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
driver.activateContainer(driver.newContainerBuilder());
Request request = new Request(driver, URI.create("http://host/path"));
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/BlockingContentWriterTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/BlockingContentWriterTestCase.java
index 651c24648a1..96c6edbdcf5 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/BlockingContentWriterTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/BlockingContentWriterTestCase.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.jdisc.handler;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
import java.util.concurrent.*;
-import static org.junit.Assert.fail;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -17,7 +17,7 @@ import static org.junit.Assert.assertTrue;
public class BlockingContentWriterTestCase {
@Test
- public void requireThatContentChannelIsNotNull() {
+ void requireThatContentChannelIsNotNull() {
try {
new BlockingContentWriter(null);
fail();
@@ -27,7 +27,7 @@ public class BlockingContentWriterTestCase {
}
@Test
- public void requireThatWriteDeliversBuffer() throws InterruptedException {
+ void requireThatWriteDeliversBuffer() throws InterruptedException {
MyContent content = MyContent.newNonBlockingContent();
BlockingContentWriter writer = new BlockingContentWriter(content);
ByteBuffer buf = ByteBuffer.allocate(69);
@@ -36,7 +36,7 @@ public class BlockingContentWriterTestCase {
}
@Test
- public void requireThatWriteIsBlocking() throws Exception {
+ void requireThatWriteIsBlocking() throws Exception {
MyContent content = MyContent.newBlockingContent();
BlockingContentWriter writer = new BlockingContentWriter(content);
FutureTask<Boolean> task = new FutureTask<>(new WriteTask(writer, ByteBuffer.allocate(69)));
@@ -53,7 +53,7 @@ public class BlockingContentWriterTestCase {
}
@Test
- public void requireThatWriteExceptionIsThrown() throws Exception {
+ void requireThatWriteExceptionIsThrown() throws Exception {
Throwable throwMe = new RuntimeException();
try {
new BlockingContentWriter(MyContent.newFailedContent(throwMe)).write(ByteBuffer.allocate(69));
@@ -76,7 +76,7 @@ public class BlockingContentWriterTestCase {
}
@Test
- public void requireThatCloseIsBlocking() throws Exception {
+ void requireThatCloseIsBlocking() throws Exception {
MyContent content = MyContent.newBlockingContent();
BlockingContentWriter writer = new BlockingContentWriter(content);
FutureTask<Boolean> task = new FutureTask<>(new CloseTask(writer));
@@ -93,7 +93,7 @@ public class BlockingContentWriterTestCase {
}
@Test
- public void requireThatCloseExceptionIsThrown() throws Exception {
+ void requireThatCloseExceptionIsThrown() throws Exception {
Throwable throwMe = new RuntimeException();
try {
new BlockingContentWriter(MyContent.newFailedContent(throwMe)).close();
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/BufferedContentChannelTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/BufferedContentChannelTestCase.java
index 705d6d008b0..3824c0eb928 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/BufferedContentChannelTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/BufferedContentChannelTestCase.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.jdisc.handler;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
import java.util.LinkedList;
@@ -9,11 +9,11 @@ import java.util.List;
import java.util.Random;
import java.util.concurrent.*;
-import static org.junit.Assert.fail;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -21,7 +21,7 @@ import static org.junit.Assert.assertEquals;
public class BufferedContentChannelTestCase {
@Test
- public void requireThatIsConnectedWorks() {
+ void requireThatIsConnectedWorks() {
MyContent target = new MyContent();
BufferedContentChannel content = new BufferedContentChannel();
assertFalse(content.isConnected());
@@ -30,7 +30,7 @@ public class BufferedContentChannelTestCase {
}
@Test
- public void requireThatConnectToNullThrowsException() {
+ void requireThatConnectToNullThrowsException() {
BufferedContentChannel content = new BufferedContentChannel();
try {
content.connectTo(null);
@@ -41,7 +41,7 @@ public class BufferedContentChannelTestCase {
}
@Test
- public void requireThatWriteAfterCloseThrowsException() {
+ void requireThatWriteAfterCloseThrowsException() {
BufferedContentChannel content = new BufferedContentChannel();
content.close(null);
try {
@@ -53,7 +53,7 @@ public class BufferedContentChannelTestCase {
}
@Test
- public void requireThatCloseAfterCloseThrowsException() {
+ void requireThatCloseAfterCloseThrowsException() {
BufferedContentChannel content = new BufferedContentChannel();
content.close(null);
try {
@@ -65,7 +65,7 @@ public class BufferedContentChannelTestCase {
}
@Test
- public void requireThatConnecToAfterConnecToThrowsException() {
+ void requireThatConnecToAfterConnecToThrowsException() {
BufferedContentChannel content = new BufferedContentChannel();
content.connectTo(new MyContent());
try {
@@ -77,7 +77,7 @@ public class BufferedContentChannelTestCase {
}
@Test
- public void requireThatWriteBeforeConnectToWritesToTarget() {
+ void requireThatWriteBeforeConnectToWritesToTarget() {
BufferedContentChannel content = new BufferedContentChannel();
ByteBuffer buf = ByteBuffer.allocate(69);
MyCompletion completion = new MyCompletion();
@@ -89,7 +89,7 @@ public class BufferedContentChannelTestCase {
}
@Test
- public void requireThatWriteAfterConnectToWritesToTarget() {
+ void requireThatWriteAfterConnectToWritesToTarget() {
MyContent target = new MyContent();
BufferedContentChannel content = new BufferedContentChannel();
content.connectTo(target);
@@ -101,7 +101,7 @@ public class BufferedContentChannelTestCase {
}
@Test
- public void requireThatCloseBeforeConnectToClosesTarget() {
+ void requireThatCloseBeforeConnectToClosesTarget() {
BufferedContentChannel content = new BufferedContentChannel();
MyCompletion completion = new MyCompletion();
content.close(completion);
@@ -112,7 +112,7 @@ public class BufferedContentChannelTestCase {
}
@Test
- public void requireThatCloseAfterConnectToClosesTarget() {
+ void requireThatCloseAfterConnectToClosesTarget() {
MyContent target = new MyContent();
BufferedContentChannel content = new BufferedContentChannel();
content.connectTo(target);
@@ -123,7 +123,7 @@ public class BufferedContentChannelTestCase {
}
@Test
- public void requireThatIsConnectedIsTrueWhenConnectedBeforeClose() {
+ void requireThatIsConnectedIsTrueWhenConnectedBeforeClose() {
BufferedContentChannel content = new BufferedContentChannel();
assertFalse(content.isConnected());
content.connectTo(new MyContent());
@@ -133,7 +133,7 @@ public class BufferedContentChannelTestCase {
}
@Test
- public void requireThatIsConnectedIsTrueWhenClosedBeforeConnected() {
+ void requireThatIsConnectedIsTrueWhenClosedBeforeConnected() {
BufferedContentChannel content = new BufferedContentChannel();
assertFalse(content.isConnected());
content.close(null);
@@ -143,7 +143,7 @@ public class BufferedContentChannelTestCase {
}
@Test
- public void requireThatContentIsThreadSafe() throws Exception {
+ void requireThatContentIsThreadSafe() throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(101);
for (int run = 0; run < 69; ++run) {
List<ByteBuffer> bufs = new LinkedList<>();
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/CallableRequestDispatchTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/CallableRequestDispatchTestCase.java
index b11afacb518..6e5ad50f447 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/CallableRequestDispatchTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/CallableRequestDispatchTestCase.java
@@ -5,12 +5,12 @@ import com.yahoo.jdisc.Request;
import com.yahoo.jdisc.Response;
import com.yahoo.jdisc.application.ContainerBuilder;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Simon Thoresen Hult
@@ -18,7 +18,7 @@ import static org.junit.Assert.assertTrue;
public class CallableRequestDispatchTestCase {
@Test
- public void requireThatDispatchIsCalled() throws Exception {
+ void requireThatDispatchIsCalled() throws Exception {
final TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
Response response = new Response(Response.Status.OK);
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/CallableResponseDispatchTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/CallableResponseDispatchTestCase.java
index bb17bb9bc41..ff953fe0384 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/CallableResponseDispatchTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/CallableResponseDispatchTestCase.java
@@ -2,11 +2,11 @@
package com.yahoo.jdisc.handler;
import com.yahoo.jdisc.Response;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.TimeUnit;
-import static org.junit.Assert.assertSame;
+import static org.junit.jupiter.api.Assertions.assertSame;
/**
@@ -15,7 +15,7 @@ import static org.junit.Assert.assertSame;
public class CallableResponseDispatchTestCase {
@Test
- public void requireThatDispatchIsCalled() throws Exception {
+ void requireThatDispatchIsCalled() throws Exception {
final Response response = new Response(Response.Status.OK);
FutureResponse handler = new FutureResponse();
new CallableResponseDispatch(handler) {
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/ContentInputStreamTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/ContentInputStreamTestCase.java
index f90251bc16e..30169699077 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/ContentInputStreamTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/ContentInputStreamTestCase.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.jdisc.handler;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.Future;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -14,13 +14,13 @@ import static org.junit.Assert.assertTrue;
public class ContentInputStreamTestCase {
@Test
- public void requireThatContentInputStreamExtendsUnsafeContentInputStream() {
+ void requireThatContentInputStreamExtendsUnsafeContentInputStream() {
assertTrue(UnsafeContentInputStream.class.isAssignableFrom(ContentInputStream.class));
}
@Test
@SuppressWarnings("FinalizeCalledExplicitly")
- public void requireThatFinalizerClosesStream() throws Throwable {
+ void requireThatFinalizerClosesStream() throws Throwable {
BufferedContentChannel channel = new BufferedContentChannel();
FastContentWriter writer = new FastContentWriter(channel);
writer.write("foo");
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/FastContentOutputStreamTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/FastContentOutputStreamTestCase.java
index 2cdc0e1256f..3f97fe014e6 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/FastContentOutputStreamTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/FastContentOutputStreamTestCase.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.jdisc.handler;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.nio.ByteBuffer;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
-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;
/**
@@ -18,15 +18,15 @@ import static org.junit.Assert.fail;
public class FastContentOutputStreamTestCase {
@Test
- public void requireThatNullConstructorArgumentThrows() {
+ void requireThatNullConstructorArgumentThrows() {
try {
- new FastContentOutputStream((ContentChannel)null);
+ new FastContentOutputStream((ContentChannel) null);
fail();
} catch (NullPointerException e) {
assertEquals("out", e.getMessage());
}
try {
- new FastContentOutputStream((FastContentWriter)null);
+ new FastContentOutputStream((FastContentWriter) null);
fail();
} catch (NullPointerException e) {
assertEquals("out", e.getMessage());
@@ -34,11 +34,11 @@ public class FastContentOutputStreamTestCase {
}
@Test
- public void requireThatAllMethodsDelegateToWriter() throws Exception {
+ void requireThatAllMethodsDelegateToWriter() throws Exception {
FastContentWriter writer = Mockito.mock(FastContentWriter.class);
FastContentOutputStream out = new FastContentOutputStream(writer);
- out.write(new byte[] { 6, 9 });
+ out.write(new byte[]{6, 9});
out.flush();
Mockito.verify(writer).write(Mockito.any(ByteBuffer.class));
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/FastContentWriterTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/FastContentWriterTestCase.java
index 45bc230896f..4e0b989db74 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/FastContentWriterTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/FastContentWriterTestCase.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.jdisc.handler;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.nio.ByteBuffer;
@@ -15,14 +15,14 @@ import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
-import static org.junit.Assert.fail;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+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.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -30,7 +30,7 @@ import static org.junit.Assert.assertArrayEquals;
public class FastContentWriterTestCase {
@Test
- public void requireThatContentCanBeWritten() throws ExecutionException, InterruptedException {
+ void requireThatContentCanBeWritten() throws ExecutionException, InterruptedException {
ReadableContentChannel content = new ReadableContentChannel();
FastContentWriter out = new FastContentWriter(content);
@@ -50,7 +50,7 @@ public class FastContentWriterTestCase {
}
@Test
- public void requireThatStringsAreUtf8Encoded() {
+ void requireThatStringsAreUtf8Encoded() {
ReadableContentChannel content = new ReadableContentChannel();
FastContentWriter out = new FastContentWriter(content);
@@ -65,7 +65,7 @@ public class FastContentWriterTestCase {
}
@Test
- public void requireThatCancelThrowsUnsupportedOperation() {
+ void requireThatCancelThrowsUnsupportedOperation() {
try {
new FastContentWriter(Mockito.mock(ContentChannel.class)).cancel(true);
fail();
@@ -75,7 +75,7 @@ public class FastContentWriterTestCase {
}
@Test
- public void requireThatCancelIsAlwaysFalse() {
+ void requireThatCancelIsAlwaysFalse() {
FastContentWriter writer = new FastContentWriter(Mockito.mock(ContentChannel.class));
assertFalse(writer.isCancelled());
try {
@@ -88,11 +88,11 @@ public class FastContentWriterTestCase {
}
@Test
- public void requireThatGetThrowsTimeoutUntilCloseCompletionHandlerIsCalled() throws Exception {
+ void requireThatGetThrowsTimeoutUntilCloseCompletionHandlerIsCalled() throws Exception {
ReadableContentChannel buf = new ReadableContentChannel();
FastContentWriter out = new FastContentWriter(buf);
- out.write(new byte[] { 6, 9 });
+ out.write(new byte[]{6, 9});
assertFalse(out.isDone());
try {
out.get(100, TimeUnit.MILLISECONDS);
@@ -126,11 +126,11 @@ public class FastContentWriterTestCase {
}
@Test
- public void requireThatSyncWriteExceptionFailsFuture() throws InterruptedException {
+ void requireThatSyncWriteExceptionFailsFuture() throws InterruptedException {
IllegalStateException expected = new IllegalStateException();
ContentChannel content = Mockito.mock(ContentChannel.class);
Mockito.doThrow(expected)
- .when(content).write(Mockito.any(ByteBuffer.class), Mockito.any(CompletionHandler.class));
+ .when(content).write(Mockito.any(ByteBuffer.class), Mockito.any(CompletionHandler.class));
FastContentWriter out = new FastContentWriter(content);
try {
out.write("foo");
@@ -147,11 +147,11 @@ public class FastContentWriterTestCase {
}
@Test
- public void requireThatSyncCloseExceptionFailsFuture() throws InterruptedException {
+ void requireThatSyncCloseExceptionFailsFuture() throws InterruptedException {
IllegalStateException expected = new IllegalStateException();
ContentChannel content = Mockito.mock(ContentChannel.class);
Mockito.doThrow(expected)
- .when(content).close(Mockito.any(CompletionHandler.class));
+ .when(content).close(Mockito.any(CompletionHandler.class));
FastContentWriter out = new FastContentWriter(content);
try {
out.close();
@@ -168,7 +168,7 @@ public class FastContentWriterTestCase {
}
@Test
- public void requireThatAsyncExceptionFailsFuture() throws InterruptedException {
+ void requireThatAsyncExceptionFailsFuture() throws InterruptedException {
IllegalStateException expected = new IllegalStateException();
ReadableContentChannel content = new ReadableContentChannel();
FastContentWriter out = new FastContentWriter(content);
@@ -183,13 +183,13 @@ public class FastContentWriterTestCase {
}
@Test
- public void requireThatWriterCanBeListenedTo() throws InterruptedException {
+ void requireThatWriterCanBeListenedTo() throws InterruptedException {
ReadableContentChannel buf = new ReadableContentChannel();
FastContentWriter out = new FastContentWriter(buf);
RunnableLatch listener = new RunnableLatch();
out.addListener(listener, Runnable::run);
- out.write(new byte[] { 6, 9 });
+ out.write(new byte[]{6, 9});
assertFalse(listener.await(100, TimeUnit.MILLISECONDS));
assertNotNull(buf.read());
assertFalse(listener.await(100, TimeUnit.MILLISECONDS));
@@ -200,7 +200,7 @@ public class FastContentWriterTestCase {
}
@Test
- public void requireThatWriterIsThreadSafe() throws Exception {
+ void requireThatWriterIsThreadSafe() throws Exception {
final CountDownLatch latch = new CountDownLatch(2);
final ReadableContentChannel content = new ReadableContentChannel();
Future<Integer> read = Executors.newSingleThreadExecutor().submit(new Callable<Integer>() {
@@ -235,6 +235,6 @@ public class FastContentWriterTestCase {
}
});
assertEquals(read.get(600, TimeUnit.SECONDS),
- write.get(600, TimeUnit.SECONDS));
+ write.get(600, TimeUnit.SECONDS));
}
}
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/FutureCompletionTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/FutureCompletionTestCase.java
index ef63b200b5f..fe4b329ba9d 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/FutureCompletionTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/FutureCompletionTestCase.java
@@ -1,16 +1,16 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.handler;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
-import static org.junit.Assert.fail;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertSame;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -18,7 +18,7 @@ import static org.junit.Assert.assertSame;
public class FutureCompletionTestCase {
@Test
- public void requireThatCancelIsUnsupported() {
+ void requireThatCancelIsUnsupported() {
FutureCompletion future = new FutureCompletion();
assertFalse(future.isCancelled());
try {
@@ -38,7 +38,7 @@ public class FutureCompletionTestCase {
}
@Test
- public void requireThatCompletedReturnsTrue() throws Exception {
+ void requireThatCompletedReturnsTrue() throws Exception {
FutureCompletion future = new FutureCompletion();
try {
future.get(0, TimeUnit.MILLISECONDS);
@@ -52,7 +52,7 @@ public class FutureCompletionTestCase {
}
@Test
- public void requireThatCompletionIsDoneWhenCompleted() {
+ void requireThatCompletionIsDoneWhenCompleted() {
FutureCompletion future = new FutureCompletion();
assertFalse(future.isDone());
future.completed();
@@ -60,7 +60,7 @@ public class FutureCompletionTestCase {
}
@Test
- public void requireThatCompletionIsDoneWhenFailed() {
+ void requireThatCompletionIsDoneWhenFailed() {
FutureCompletion future = new FutureCompletion();
assertFalse(future.isDone());
future.failed(new Throwable());
@@ -68,7 +68,7 @@ public class FutureCompletionTestCase {
}
@Test
- public void requireThatFailedCauseIsRethrown() throws Exception {
+ void requireThatFailedCauseIsRethrown() throws Exception {
FutureCompletion future = new FutureCompletion();
Throwable t = new Throwable();
future.failed(t);
@@ -87,7 +87,7 @@ public class FutureCompletionTestCase {
}
@Test
- public void requireThatCompletionCanBeListenedTo() throws InterruptedException {
+ void requireThatCompletionCanBeListenedTo() throws InterruptedException {
FutureCompletion completion = new FutureCompletion();
RunnableLatch listener = new RunnableLatch();
completion.addListener(listener, Runnable::run);
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/FutureConjunctionTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/FutureConjunctionTestCase.java
index 1aa78a16dfc..16c6b394426 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/FutureConjunctionTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/FutureConjunctionTestCase.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.jdisc.handler;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
@@ -10,10 +10,10 @@ import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -23,13 +23,17 @@ public class FutureConjunctionTestCase {
private final ExecutorService executor = Executors.newCachedThreadPool();
@Test
- public void requireThatAllFuturesAreWaitedFor() throws Exception {
+ void requireThatAllFuturesAreWaitedFor() throws Exception {
final CountDownLatch latch = new CountDownLatch(1);
FutureConjunction future = new FutureConjunction();
CompletableFuture<Boolean> cf = new CompletableFuture<>();
cf.completeAsync(() -> {
- try { return latch.await(600, TimeUnit.SECONDS); }
- catch (InterruptedException e) { return false; }
+ try {
+ return latch.await(600, TimeUnit.SECONDS);
+ }
+ catch (InterruptedException e) {
+ return false;
+ }
}, executor);
future.addOperand(cf);
try {
@@ -43,7 +47,7 @@ public class FutureConjunctionTestCase {
}
@Test
- public void requireThatGetReturnValueIsAConjunction() throws Exception {
+ void requireThatGetReturnValueIsAConjunction() throws Exception {
assertTrue(tryGet(true));
assertTrue(tryGet(true, true));
assertTrue(tryGet(true, true, true));
@@ -60,7 +64,7 @@ public class FutureConjunctionTestCase {
}
@Test
- public void requireThatIsDoneReturnValueIsAConjunction() {
+ void requireThatIsDoneReturnValueIsAConjunction() {
assertTrue(tryIsDone(true));
assertTrue(tryIsDone(true, true));
assertTrue(tryIsDone(true, true, true));
@@ -77,7 +81,7 @@ public class FutureConjunctionTestCase {
}
@Test
- public void requireThatCancelReturnValueIsAConjuction() {
+ void requireThatCancelReturnValueIsAConjuction() {
assertTrue(tryCancel(true));
assertTrue(tryCancel(true, true));
assertTrue(tryCancel(true, true, true));
@@ -94,7 +98,7 @@ public class FutureConjunctionTestCase {
}
@Test
- public void requireThatIsCancelledReturnValueIsAConjuction() {
+ void requireThatIsCancelledReturnValueIsAConjuction() {
assertTrue(tryIsCancelled(true));
assertTrue(tryIsCancelled(true, true));
assertTrue(tryIsCancelled(true, true, true));
@@ -111,7 +115,7 @@ public class FutureConjunctionTestCase {
}
@Test
- public void requireThatConjunctionCanBeListenedTo() throws InterruptedException {
+ void requireThatConjunctionCanBeListenedTo() throws InterruptedException {
FutureConjunction conjunction = new FutureConjunction();
RunnableLatch listener = new RunnableLatch();
conjunction.addListener(listener, Runnable::run);
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/FutureResponseTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/FutureResponseTestCase.java
index 398f288e307..09f6db882fb 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/FutureResponseTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/FutureResponseTestCase.java
@@ -3,15 +3,15 @@ package com.yahoo.jdisc.handler;
import com.yahoo.jdisc.Response;
import com.yahoo.jdisc.test.NonWorkingContentChannel;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
-import static org.junit.Assert.fail;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertSame;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -19,7 +19,7 @@ import static org.junit.Assert.assertSame;
public class FutureResponseTestCase {
@Test
- public void requireThatCancelIsUnsupported() {
+ void requireThatCancelIsUnsupported() {
FutureResponse future = new FutureResponse();
assertFalse(future.isCancelled());
try {
@@ -39,7 +39,7 @@ public class FutureResponseTestCase {
}
@Test
- public void requireThatCompletionIsDoneWhenHandlerIsCalled() {
+ void requireThatCompletionIsDoneWhenHandlerIsCalled() {
FutureResponse future = new FutureResponse();
assertFalse(future.isDone());
future.handleResponse(new Response(69));
@@ -47,7 +47,7 @@ public class FutureResponseTestCase {
}
@Test
- public void requireThatResponseBecomesAvailable() throws Exception {
+ void requireThatResponseBecomesAvailable() throws Exception {
FutureResponse future = new FutureResponse();
try {
future.get(0, TimeUnit.MILLISECONDS);
@@ -61,7 +61,7 @@ public class FutureResponseTestCase {
}
@Test
- public void requireThatResponseContentIsReturnedToCaller() throws Exception {
+ void requireThatResponseContentIsReturnedToCaller() throws Exception {
ContentChannel content = new NonWorkingContentChannel();
FutureResponse future = new FutureResponse(content);
Response response = new Response(Response.Status.OK);
@@ -69,7 +69,7 @@ public class FutureResponseTestCase {
}
@Test
- public void requireThatResponseCanBeListenedTo() throws InterruptedException {
+ void requireThatResponseCanBeListenedTo() throws InterruptedException {
FutureResponse response = new FutureResponse();
RunnableLatch listener = new RunnableLatch();
response.addListener(listener, Runnable::run);
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/NullContentTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/NullContentTestCase.java
index 598d21b94ea..8e18ab01ae3 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/NullContentTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/NullContentTestCase.java
@@ -1,12 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.jdisc.handler;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.nio.ByteBuffer;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -14,7 +14,7 @@ import static org.junit.Assert.fail;
public class NullContentTestCase {
@Test
- public void requireThatWriteThrowsException() {
+ void requireThatWriteThrowsException() {
CompletionHandler completion = Mockito.mock(CompletionHandler.class);
try {
NullContent.INSTANCE.write(ByteBuffer.allocate(69), completion);
@@ -26,7 +26,7 @@ public class NullContentTestCase {
}
@Test
- public void requireThatWriteEmptyDoesNotThrowException() {
+ void requireThatWriteEmptyDoesNotThrowException() {
CompletionHandler completion = Mockito.mock(CompletionHandler.class);
NullContent.INSTANCE.write(ByteBuffer.allocate(0), completion);
Mockito.verify(completion).completed();
@@ -34,7 +34,7 @@ public class NullContentTestCase {
}
@Test
- public void requireThatCloseCallsCompletion() {
+ void requireThatCloseCallsCompletion() {
CompletionHandler completion = Mockito.mock(CompletionHandler.class);
NullContent.INSTANCE.close(completion);
Mockito.verify(completion).completed();
@@ -42,7 +42,7 @@ public class NullContentTestCase {
}
@Test
- public void requireThatCloseWithoutCompletionDoesNotThrow() {
+ void requireThatCloseWithoutCompletionDoesNotThrow() {
NullContent.INSTANCE.close(null);
}
}
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/ReadableContentChannelTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/ReadableContentChannelTestCase.java
index 385cd4015b9..77da00bfa89 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/ReadableContentChannelTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/ReadableContentChannelTestCase.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.jdisc.handler;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
import java.util.Iterator;
@@ -10,12 +10,12 @@ import java.util.List;
import java.util.NoSuchElementException;
import java.util.concurrent.*;
-import static org.junit.Assert.fail;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+import static org.junit.jupiter.api.Assertions.assertFalse;
/**
* @author Simon Thoresen Hult
@@ -23,7 +23,7 @@ import static org.junit.Assert.assertSame;
public class ReadableContentChannelTestCase {
@Test
- public void requireThatWriteNullThrowsException() {
+ void requireThatWriteNullThrowsException() {
ReadableContentChannel content = new ReadableContentChannel();
try {
content.write(null, new MyCompletion());
@@ -34,7 +34,7 @@ public class ReadableContentChannelTestCase {
}
@Test
- public void requireThatWriteAfterCloseThrowsException() {
+ void requireThatWriteAfterCloseThrowsException() {
ReadableContentChannel content = new ReadableContentChannel();
content.close(null);
try {
@@ -46,7 +46,7 @@ public class ReadableContentChannelTestCase {
}
@Test
- public void requireThatWriteAfterFailedThrowsException() {
+ void requireThatWriteAfterFailedThrowsException() {
ReadableContentChannel content = new ReadableContentChannel();
content.failed(new RuntimeException());
try {
@@ -58,7 +58,7 @@ public class ReadableContentChannelTestCase {
}
@Test
- public void requireThatCloseAfterCloseThrowsException() {
+ void requireThatCloseAfterCloseThrowsException() {
ReadableContentChannel content = new ReadableContentChannel();
content.close(null);
try {
@@ -70,7 +70,7 @@ public class ReadableContentChannelTestCase {
}
@Test
- public void requireThatCloseAfterFailedThrowsException() {
+ void requireThatCloseAfterFailedThrowsException() {
ReadableContentChannel content = new ReadableContentChannel();
content.failed(new RuntimeException());
try {
@@ -82,7 +82,7 @@ public class ReadableContentChannelTestCase {
}
@Test
- public void requireThatFailedAfterFailedThrowsException() {
+ void requireThatFailedAfterFailedThrowsException() {
ReadableContentChannel content = new ReadableContentChannel();
content.failed(new RuntimeException());
try {
@@ -94,7 +94,7 @@ public class ReadableContentChannelTestCase {
}
@Test
- public void requireThatIteratorDoesNotSupportRemove() {
+ void requireThatIteratorDoesNotSupportRemove() {
try {
new ReadableContentChannel().iterator().remove();
fail();
@@ -104,7 +104,7 @@ public class ReadableContentChannelTestCase {
}
@Test
- public void requireThatWrittenBufferCanBeRead() {
+ void requireThatWrittenBufferCanBeRead() {
ReadableContentChannel content = new ReadableContentChannel();
ByteBuffer buf = ByteBuffer.allocate(69);
content.write(buf, null);
@@ -112,7 +112,7 @@ public class ReadableContentChannelTestCase {
}
@Test
- public void requireThatWrittenBuffersAreReadInOrder() {
+ void requireThatWrittenBuffersAreReadInOrder() {
ReadableContentChannel content = new ReadableContentChannel();
ByteBuffer foo = ByteBuffer.allocate(69);
content.write(foo, null);
@@ -124,7 +124,7 @@ public class ReadableContentChannelTestCase {
}
@Test
- public void requireThatReadAfterCloseIsNull() {
+ void requireThatReadAfterCloseIsNull() {
ReadableContentChannel content = new ReadableContentChannel();
content.close(null);
assertNull(content.read());
@@ -132,7 +132,7 @@ public class ReadableContentChannelTestCase {
}
@Test
- public void requireThatWrittenBufferCanBeReadByIterator() {
+ void requireThatWrittenBufferCanBeReadByIterator() {
ReadableContentChannel content = new ReadableContentChannel();
ByteBuffer foo = ByteBuffer.allocate(69);
content.write(foo, null);
@@ -155,7 +155,7 @@ public class ReadableContentChannelTestCase {
}
@Test
- public void requireThatReadAfterFailedIsNull() {
+ void requireThatReadAfterFailedIsNull() {
ReadableContentChannel content = new ReadableContentChannel();
content.failed(new RuntimeException());
assertNull(content.read());
@@ -163,7 +163,7 @@ public class ReadableContentChannelTestCase {
}
@Test
- public void requireThatReadCallsCompletion() {
+ void requireThatReadCallsCompletion() {
ReadableContentChannel content = new ReadableContentChannel();
ByteBuffer buf = ByteBuffer.allocate(69);
MyCompletion completion = new MyCompletion();
@@ -180,7 +180,7 @@ public class ReadableContentChannelTestCase {
}
@Test
- public void requireThatReadWaitsForWrite() throws Exception {
+ void requireThatReadWaitsForWrite() throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
ReadableContentChannel content = new ReadableContentChannel();
Future<ByteBuffer> readBuf = executor.submit(new ReadTask(content));
@@ -196,7 +196,7 @@ public class ReadableContentChannelTestCase {
}
@Test
- public void requireThatCloseNotifiesRead() throws Exception {
+ void requireThatCloseNotifiesRead() throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
ReadableContentChannel content = new ReadableContentChannel();
Future<ByteBuffer> buf = executor.submit(new ReadTask(content));
@@ -211,7 +211,7 @@ public class ReadableContentChannelTestCase {
}
@Test
- public void requireThatFailedNotifiesRead() throws Exception {
+ void requireThatFailedNotifiesRead() throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
ReadableContentChannel content = new ReadableContentChannel();
Future<ByteBuffer> buf = executor.submit(new ReadTask(content));
@@ -226,7 +226,7 @@ public class ReadableContentChannelTestCase {
}
@Test
- public void requireThatFailedCallsPendingCompletions() {
+ void requireThatFailedCallsPendingCompletions() {
MyCompletion foo = new MyCompletion();
MyCompletion bar = new MyCompletion();
ReadableContentChannel content = new ReadableContentChannel();
@@ -239,10 +239,10 @@ public class ReadableContentChannelTestCase {
}
@Test
- public void requireThatAvailableIsNotBlocking() {
+ void requireThatAvailableIsNotBlocking() {
ReadableContentChannel content = new ReadableContentChannel();
assertEquals(0, content.available());
- ByteBuffer buf = ByteBuffer.wrap(new byte[] { 6, 9 });
+ ByteBuffer buf = ByteBuffer.wrap(new byte[]{6, 9});
content.write(buf, null);
assertTrue(content.available() > 0);
assertSame(buf, content.read());
@@ -253,7 +253,7 @@ public class ReadableContentChannelTestCase {
}
@Test
- public void requireThatContentIsThreadSafe() {
+ void requireThatContentIsThreadSafe() {
ExecutorService executor = Executors.newFixedThreadPool(100);
for (int run = 0; run < 69; ++run) {
List<ByteBuffer> bufs = new LinkedList<>();
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/RequestDeniedTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/RequestDeniedTestCase.java
index 01634498bf3..724125e9c5e 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/RequestDeniedTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/RequestDeniedTestCase.java
@@ -6,12 +6,12 @@ import com.yahoo.jdisc.Request;
import com.yahoo.jdisc.Response;
import com.yahoo.jdisc.application.ContainerBuilder;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
-import static org.junit.Assert.fail;
-import static org.junit.Assert.assertSame;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -19,7 +19,7 @@ import static org.junit.Assert.assertSame;
public class RequestDeniedTestCase {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
driver.activateContainer(driver.newContainerBuilder());
Request request = new Request(driver, URI.create("http://host/path"));
@@ -30,7 +30,7 @@ public class RequestDeniedTestCase {
}
@Test
- public void requireThatRequestDeniedIsThrown() {
+ void requireThatRequestDeniedIsThrown() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
RequestHandler requestHandler = new MyRequestHandler();
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/RequestDispatchTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/RequestDispatchTestCase.java
index 6ec78f01733..fdae7e8e701 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/RequestDispatchTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/RequestDispatchTestCase.java
@@ -5,7 +5,7 @@ import com.yahoo.jdisc.Request;
import com.yahoo.jdisc.Response;
import com.yahoo.jdisc.application.ContainerBuilder;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.InputStream;
@@ -16,12 +16,12 @@ import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -29,7 +29,7 @@ import static org.junit.Assert.fail;
public class RequestDispatchTestCase {
@Test
- public void requireThatRequestCanBeDispatched() throws Exception {
+ void requireThatRequestCanBeDispatched() throws Exception {
final TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
final List<ByteBuffer> writtenContent = Arrays.asList(ByteBuffer.allocate(6), ByteBuffer.allocate(9));
ReadableContentChannel receivedContent = new ReadableContentChannel();
@@ -62,7 +62,7 @@ public class RequestDispatchTestCase {
}
@Test
- public void requireThatStreamCanBeConnected() throws IOException {
+ void requireThatStreamCanBeConnected() throws IOException {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
ReadableContentChannel content = new ReadableContentChannel();
@@ -84,7 +84,7 @@ public class RequestDispatchTestCase {
}
@Test
- public void requireThatCancelIsUnsupported() {
+ void requireThatCancelIsUnsupported() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
RequestDispatch dispatch = driver.newRequestDispatch("http://localhost/", new FutureResponse());
assertFalse(dispatch.isCancelled());
@@ -106,7 +106,7 @@ public class RequestDispatchTestCase {
}
@Test
- public void requireThatDispatchHandlesConnectException() {
+ void requireThatDispatchHandlesConnectException() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
builder.serverBindings().bind("http://localhost/", new AbstractRequestHandler() {
@@ -127,7 +127,7 @@ public class RequestDispatchTestCase {
}
@Test
- public void requireThatDispatchHandlesWriteException() {
+ void requireThatDispatchHandlesWriteException() {
final TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
Response response = new Response(Response.Status.OK);
@@ -165,7 +165,7 @@ public class RequestDispatchTestCase {
}
@Test
- public void requireThatDispatchHandlesCloseException() {
+ void requireThatDispatchHandlesCloseException() {
final TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
Response response = new Response(Response.Status.OK);
@@ -203,7 +203,7 @@ public class RequestDispatchTestCase {
}
@Test
- public void requireThatDispatchCanBeListenedTo() throws InterruptedException {
+ void requireThatDispatchCanBeListenedTo() throws InterruptedException {
final TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
ReadableContentChannel requestContent = new ReadableContentChannel();
@@ -220,7 +220,7 @@ public class RequestDispatchTestCase {
}.dispatch().whenComplete((__, ___) -> listener.run());
assertFalse(listener.await(100, TimeUnit.MILLISECONDS));
ContentChannel responseContent = ResponseDispatch.newInstance(Response.Status.OK)
- .connect(requestHandler.responseHandler);
+ .connect(requestHandler.responseHandler);
assertFalse(listener.await(100, TimeUnit.MILLISECONDS));
assertNull(requestContent.read());
assertTrue(listener.await(600, TimeUnit.SECONDS));
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/ResponseDispatchTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/ResponseDispatchTestCase.java
index 4006ab072cb..2c00689c3f4 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/ResponseDispatchTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/ResponseDispatchTestCase.java
@@ -2,7 +2,7 @@
package com.yahoo.jdisc.handler;
import com.yahoo.jdisc.Response;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.InputStream;
@@ -13,13 +13,13 @@ import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
-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.assertSame;
-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.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -27,7 +27,7 @@ import static org.junit.Assert.fail;
public class ResponseDispatchTestCase {
@Test
- public void requireThatFactoryMethodsWork() throws Exception {
+ void requireThatFactoryMethodsWork() throws Exception {
{
FutureResponse handler = new FutureResponse();
ResponseDispatch.newInstance(69).dispatch(handler);
@@ -78,7 +78,7 @@ public class ResponseDispatchTestCase {
}
@Test
- public void requireThatResponseCanBeDispatched() throws Exception {
+ void requireThatResponseCanBeDispatched() throws Exception {
final Response response = new Response(Response.Status.OK);
final List<ByteBuffer> writtenContent = Arrays.asList(ByteBuffer.allocate(6), ByteBuffer.allocate(9));
ResponseDispatch dispatch = new ResponseDispatch() {
@@ -109,7 +109,7 @@ public class ResponseDispatchTestCase {
}
@Test
- public void requireThatStreamCanBeConnected() throws IOException {
+ void requireThatStreamCanBeConnected() throws IOException {
ReadableContentChannel responseContent = new ReadableContentChannel();
OutputStream out = new FastContentOutputStream(new ResponseDispatch() {
@@ -129,7 +129,7 @@ public class ResponseDispatchTestCase {
}
@Test
- public void requireThatCancelIsUnsupported() {
+ void requireThatCancelIsUnsupported() {
ResponseDispatch dispatch = ResponseDispatch.newInstance(69);
assertFalse(dispatch.isCancelled());
try {
@@ -149,7 +149,7 @@ public class ResponseDispatchTestCase {
}
@Test
- public void requireThatDispatchClosesContentIfWriteThrowsException() {
+ void requireThatDispatchClosesContentIfWriteThrowsException() {
final AtomicBoolean closed = new AtomicBoolean(false);
try {
ResponseDispatch.newInstance(6, ByteBuffer.allocate(9)).dispatch(
@@ -173,12 +173,12 @@ public class ResponseDispatchTestCase {
}
@Test
- public void requireThatDispatchCanBeListenedTo() throws InterruptedException {
+ void requireThatDispatchCanBeListenedTo() throws InterruptedException {
RunnableLatch listener = new RunnableLatch();
ReadableContentChannel responseContent = new ReadableContentChannel();
ResponseDispatch.newInstance(6, ByteBuffer.allocate(9))
- .dispatch(new MyResponseHandler(responseContent))
- .whenComplete((__, ___) -> listener.run());
+ .dispatch(new MyResponseHandler(responseContent))
+ .whenComplete((__, ___) -> listener.run());
assertFalse(listener.await(100, TimeUnit.MILLISECONDS));
assertNotNull(responseContent.read());
assertFalse(listener.await(100, TimeUnit.MILLISECONDS));
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/ThreadedRequestHandlerTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/ThreadedRequestHandlerTestCase.java
index f639877b87b..63a6d310208 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/ThreadedRequestHandlerTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/ThreadedRequestHandlerTestCase.java
@@ -6,7 +6,7 @@ import com.yahoo.jdisc.Response;
import com.yahoo.jdisc.application.ContainerBuilder;
import com.yahoo.jdisc.service.CurrentContainer;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.nio.ByteBuffer;
@@ -18,12 +18,12 @@ import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -31,7 +31,7 @@ import static org.junit.Assert.fail;
public class ThreadedRequestHandlerTestCase {
@Test
- public void requireThatNullExecutorThrowsException() {
+ void requireThatNullExecutorThrowsException() {
try {
new ThreadedRequestHandler(null) {
@@ -47,7 +47,7 @@ public class ThreadedRequestHandlerTestCase {
}
@Test
- public void requireThatAccessorWork() {
+ void requireThatAccessorWork() {
MyRequestHandler requestHandler = new MyRequestHandler(newExecutor());
requestHandler.setTimeout(1000, TimeUnit.MILLISECONDS);
assertEquals(1000, requestHandler.getTimeout(TimeUnit.MILLISECONDS));
@@ -55,7 +55,7 @@ public class ThreadedRequestHandlerTestCase {
}
@Test
- public void requireThatHandlerSetsRequestTimeout() throws InterruptedException {
+ void requireThatHandlerSetsRequestTimeout() throws InterruptedException {
MyRequestHandler requestHandler = new MyRequestHandler(newExecutor());
requestHandler.setTimeout(600, TimeUnit.SECONDS);
TestDriver driver = newTestDriver("http://localhost/", requestHandler);
@@ -74,7 +74,7 @@ public class ThreadedRequestHandlerTestCase {
}
@Test
- public void requireThatRequestAndResponseReachHandlers() throws InterruptedException {
+ void requireThatRequestAndResponseReachHandlers() throws InterruptedException {
MyRequestHandler requestHandler = new MyRequestHandler(newExecutor());
TestDriver driver = newTestDriver("http://localhost/", requestHandler);
@@ -99,18 +99,18 @@ public class ThreadedRequestHandlerTestCase {
}
@Test
- public void requireThatNotImplementedHandlerDoesNotPreventShutdown() throws Exception {
+ void requireThatNotImplementedHandlerDoesNotPreventShutdown() throws Exception {
TestDriver driver = newTestDriver("http://localhost/", new ThreadedRequestHandler(newExecutor()) {
});
assertEquals(Response.Status.NOT_IMPLEMENTED,
- dispatchRequest(driver, "http://localhost/", ByteBuffer.wrap(new byte[] { 69 }))
- .get(600, TimeUnit.SECONDS).getStatus());
+ dispatchRequest(driver, "http://localhost/", ByteBuffer.wrap(new byte[]{69}))
+ .get(600, TimeUnit.SECONDS).getStatus());
assertTrue(driver.close());
}
@Test
- public void requireThatThreadedRequestHandlerRetainsTheRequestUntilHandlerIsRun() throws Exception {
+ void requireThatThreadedRequestHandlerRetainsTheRequestUntilHandlerIsRun() throws Exception {
final TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
final AtomicInteger baseRetainCount = new AtomicInteger();
@@ -130,7 +130,7 @@ public class ThreadedRequestHandlerTestCase {
@Override
public void handleRequest(Request request, ReadableContentChannel requestContent,
- ResponseHandler responseHandler) {
+ ResponseHandler responseHandler) {
try {
entryLatch.await(600, TimeUnit.SECONDS);
} catch (InterruptedException e) {
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/UnsafeContentInputStreamTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/UnsafeContentInputStreamTestCase.java
index 0c3670dd56e..50d695dbb27 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/handler/UnsafeContentInputStreamTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/handler/UnsafeContentInputStreamTestCase.java
@@ -2,7 +2,7 @@
package com.yahoo.jdisc.handler;
import com.yahoo.text.Utf8;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.BufferedReader;
import java.io.IOException;
@@ -10,11 +10,11 @@ import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-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.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
* @author Simon Thoresen Hult
@@ -22,7 +22,7 @@ import static org.junit.Assert.fail;
public class UnsafeContentInputStreamTestCase {
@Test
- public void requireThatBytesCanBeRead() throws IOException {
+ void requireThatBytesCanBeRead() throws IOException {
BufferedContentChannel channel = new BufferedContentChannel();
FastContentWriter writer = new FastContentWriter(channel);
writer.write("Hello ");
@@ -35,7 +35,7 @@ public class UnsafeContentInputStreamTestCase {
}
@Test
- public void testMark() throws IOException {
+ void testMark() throws IOException {
BufferedContentChannel channel = new BufferedContentChannel();
FastContentWriter writer = new FastContentWriter(channel);
writer.write("Hello ");
@@ -71,13 +71,13 @@ public class UnsafeContentInputStreamTestCase {
}
@Test
- public void requireThatReadAfterResetIncludesDataAfterMark() throws IOException {
+ void requireThatReadAfterResetIncludesDataAfterMark() throws IOException {
ReadableContentChannel content = new ReadableContentChannel();
UnsafeContentInputStream in = new UnsafeContentInputStream(content);
- byte[] outBuf = new byte[] {1, 2, 3};
+ byte[] outBuf = new byte[]{1, 2, 3};
content.write(ByteBuffer.wrap(outBuf), null);
in.mark(4);
- assertEquals(3, in.read(new byte[] {101, 102, 103, 104}));
+ assertEquals(3, in.read(new byte[]{101, 102, 103, 104}));
in.reset();
byte[] inBuf = new byte[4];
int read = in.read(inBuf);
@@ -86,7 +86,7 @@ public class UnsafeContentInputStreamTestCase {
}
@Test
- public void requireThatCompletionsAreCalledWithDeprecatedContentWriter() throws IOException {
+ void requireThatCompletionsAreCalledWithDeprecatedContentWriter() throws IOException {
BufferedContentChannel channel = new BufferedContentChannel();
FastContentWriter writer = new FastContentWriter(channel);
writer.write("foo");
@@ -101,7 +101,7 @@ public class UnsafeContentInputStreamTestCase {
}
@Test
- public void requireThatCompletionsAreCalled() throws IOException {
+ void requireThatCompletionsAreCalled() throws IOException {
BufferedContentChannel channel = new BufferedContentChannel();
FastContentWriter writer = new FastContentWriter(channel);
writer.write("foo");
@@ -116,7 +116,7 @@ public class UnsafeContentInputStreamTestCase {
}
@Test
- public void requireThatCloseDrainsStreamWithDeprecatedContentWriter() {
+ void requireThatCloseDrainsStreamWithDeprecatedContentWriter() {
BufferedContentChannel channel = new BufferedContentChannel();
FastContentWriter writer = new FastContentWriter(channel);
writer.write("foo");
@@ -127,7 +127,7 @@ public class UnsafeContentInputStreamTestCase {
}
@Test
- public void requireThatCloseDrainsStream() {
+ void requireThatCloseDrainsStream() {
BufferedContentChannel channel = new BufferedContentChannel();
FastContentWriter writer = new FastContentWriter(channel);
writer.write("foo");
@@ -138,11 +138,11 @@ public class UnsafeContentInputStreamTestCase {
}
@Test
- public void requireThatAvailableIsNotBlocking() throws IOException {
+ void requireThatAvailableIsNotBlocking() throws IOException {
BufferedContentChannel channel = new BufferedContentChannel();
InputStream stream = asInputStream(channel);
assertEquals(0, stream.available());
- channel.write(ByteBuffer.wrap(new byte[] { 6, 9 }), null);
+ channel.write(ByteBuffer.wrap(new byte[]{6, 9}), null);
assertTrue(stream.available() > 0);
assertEquals(6, stream.read());
assertTrue(stream.available() > 0);
@@ -154,11 +154,11 @@ public class UnsafeContentInputStreamTestCase {
}
@Test
- public void requireThatReadLargeArrayIsNotBlocking() throws IOException {
+ void requireThatReadLargeArrayIsNotBlocking() throws IOException {
BufferedContentChannel channel = new BufferedContentChannel();
InputStream stream = asInputStream(channel);
assertEquals(0, stream.available());
- channel.write(ByteBuffer.wrap(new byte[] { 6, 9 }), null);
+ channel.write(ByteBuffer.wrap(new byte[]{6, 9}), null);
assertTrue(stream.available() > 0);
byte[] buf = new byte[69];
assertEquals(2, stream.read(buf));
@@ -171,12 +171,12 @@ public class UnsafeContentInputStreamTestCase {
}
@Test
- public void requireThatAllByteValuesCanBeRead() throws IOException {
+ void requireThatAllByteValuesCanBeRead() throws IOException {
ReadableContentChannel content = new ReadableContentChannel();
InputStream in = new UnsafeContentInputStream(content);
for (int i = Byte.MIN_VALUE; i <= Byte.MAX_VALUE; ++i) {
- content.write(ByteBuffer.wrap(new byte[] { (byte)i }), null);
- assertEquals(i, (byte)in.read());
+ content.write(ByteBuffer.wrap(new byte[]{(byte) i}), null);
+ assertEquals(i, (byte) in.read());
}
}
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/service/AbstractClientProviderTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/service/AbstractClientProviderTestCase.java
index bd205fd777e..9fe0b91cb39 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/service/AbstractClientProviderTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/service/AbstractClientProviderTestCase.java
@@ -4,9 +4,9 @@ package com.yahoo.jdisc.service;
import com.yahoo.jdisc.Request;
import com.yahoo.jdisc.handler.ContentChannel;
import com.yahoo.jdisc.handler.ResponseHandler;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -15,12 +15,12 @@ import static org.junit.Assert.assertTrue;
public class AbstractClientProviderTestCase {
@Test
- public void requireThatAbstractClassIsAClientProvider() {
+ void requireThatAbstractClassIsAClientProvider() {
assertTrue(ClientProvider.class.isInstance(new MyClientProvider()));
}
@Test
- public void requireThatStartDoesNotThrowAnException() {
+ void requireThatStartDoesNotThrowAnException() {
new MyClientProvider().start();
}
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/service/AbstractServerProviderTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/service/AbstractServerProviderTestCase.java
index 7f4d9f72980..d46c5067dd9 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/service/AbstractServerProviderTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/service/AbstractServerProviderTestCase.java
@@ -4,10 +4,10 @@ package com.yahoo.jdisc.service;
import com.google.inject.Inject;
import com.yahoo.jdisc.application.ContainerBuilder;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -16,14 +16,14 @@ import static org.junit.Assert.assertTrue;
public class AbstractServerProviderTestCase {
@Test
- public void requireThatAbstractClassIsAServerProvider() {
+ void requireThatAbstractClassIsAServerProvider() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
assertTrue(ServerProvider.class.isInstance(new MyServerProvider(driver)));
assertTrue(driver.close());
}
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
MyServerProvider server = builder.getInstance(MyServerProvider.class);
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/service/BindingSetNotFoundTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/service/BindingSetNotFoundTestCase.java
index 880641fe0f0..ad09c9d745e 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/service/BindingSetNotFoundTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/service/BindingSetNotFoundTestCase.java
@@ -4,12 +4,12 @@ package com.yahoo.jdisc.service;
import com.google.inject.AbstractModule;
import com.yahoo.jdisc.application.BindingSetSelector;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
-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;
/**
@@ -18,13 +18,13 @@ import static org.junit.Assert.fail;
public class BindingSetNotFoundTestCase {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
BindingSetNotFoundException e = new BindingSetNotFoundException("foo");
assertEquals("foo", e.bindingSet());
}
@Test
- public void requireThatBindingSetNotFoundIsThrown() {
+ void requireThatBindingSetNotFoundIsThrown() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi(new AbstractModule() {
@Override
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/service/ConnectToHandlerTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/service/ConnectToHandlerTestCase.java
index 7182379dc85..3de43874129 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/service/ConnectToHandlerTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/service/ConnectToHandlerTestCase.java
@@ -9,14 +9,14 @@ import com.yahoo.jdisc.handler.CompletionHandler;
import com.yahoo.jdisc.handler.ContentChannel;
import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.nio.ByteBuffer;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -25,7 +25,7 @@ import static org.junit.Assert.fail;
public class ConnectToHandlerTestCase {
@Test
- public void requireThatNullResponseHandlerThrowsException() {
+ void requireThatNullResponseHandlerThrowsException() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
driver.activateContainer(driver.newContainerBuilder());
Request request = new Request(driver, URI.create("http://host/path"));
@@ -40,7 +40,7 @@ public class ConnectToHandlerTestCase {
}
@Test
- public void requireThatConnectToHandlerWorks() {
+ void requireThatConnectToHandlerWorks() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
MyRequestHandler requestHandler = new MyRequestHandler(new MyContent());
ContainerBuilder builder = driver.newContainerBuilder();
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/service/ContainerNotReadyTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/service/ContainerNotReadyTestCase.java
index 6fcc7601339..70a0b55f75a 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/service/ContainerNotReadyTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/service/ContainerNotReadyTestCase.java
@@ -2,11 +2,11 @@
package com.yahoo.jdisc.service;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -15,7 +15,7 @@ import static org.junit.Assert.fail;
public class ContainerNotReadyTestCase {
@Test
- public void requireThatExceptionIsThrown() throws BindingSetNotFoundException {
+ void requireThatExceptionIsThrown() throws BindingSetNotFoundException {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
try {
driver.newReference(URI.create("http://host"));
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/service/CurrentContainerTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/service/CurrentContainerTestCase.java
index 6aa8b891480..99622f2f3d2 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/service/CurrentContainerTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/service/CurrentContainerTestCase.java
@@ -3,11 +3,11 @@ package com.yahoo.jdisc.service;
import com.yahoo.jdisc.Request;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
@@ -16,7 +16,7 @@ import static org.junit.Assert.assertNotNull;
public class CurrentContainerTestCase {
@Test
- public void requireThatNewRequestsCreateSnapshot() throws Exception {
+ void requireThatNewRequestsCreateSnapshot() throws Exception {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
driver.activateContainer(driver.newContainerBuilder());
Request request = new Request(driver, URI.create("http://host/path"));
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/service/NoBindingSetSelectedTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/service/NoBindingSetSelectedTestCase.java
index cd59f676d62..68733b35adb 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/service/NoBindingSetSelectedTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/service/NoBindingSetSelectedTestCase.java
@@ -4,12 +4,12 @@ package com.yahoo.jdisc.service;
import com.google.inject.AbstractModule;
import com.yahoo.jdisc.application.BindingSetSelector;
import com.yahoo.jdisc.test.TestDriver;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
-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;
/**
@@ -18,14 +18,14 @@ import static org.junit.Assert.fail;
public class NoBindingSetSelectedTestCase {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
URI uri = URI.create("http://host/path");
NoBindingSetSelectedException e = new NoBindingSetSelectedException(uri);
assertEquals(uri, e.uri());
}
@Test
- public void requireThatNoBindingSetSelectedIsThrown() {
+ void requireThatNoBindingSetSelectedIsThrown() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi(new AbstractModule() {
@Override
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingClientTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingClientTestCase.java
index 82cf4953010..862acfa1ce4 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingClientTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingClientTestCase.java
@@ -2,9 +2,9 @@
package com.yahoo.jdisc.test;
import com.yahoo.jdisc.service.ClientProvider;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -13,7 +13,7 @@ import static org.junit.Assert.fail;
public class NonWorkingClientTestCase {
@Test
- public void requireThatHandleRequestThrowsException() {
+ void requireThatHandleRequestThrowsException() {
ClientProvider client = new NonWorkingClientProvider();
try {
client.handleRequest(null, null);
@@ -24,7 +24,7 @@ public class NonWorkingClientTestCase {
}
@Test
- public void requireThatHandleTimeoutThrowsException() {
+ void requireThatHandleTimeoutThrowsException() {
ClientProvider client = new NonWorkingClientProvider();
try {
client.handleTimeout(null, null);
@@ -35,19 +35,19 @@ public class NonWorkingClientTestCase {
}
@Test
- public void requireThatStartDoesNotThrow() {
+ void requireThatStartDoesNotThrow() {
ClientProvider client = new NonWorkingClientProvider();
client.start();
}
@Test
- public void requireThatRetainDoesNotThrow() {
+ void requireThatRetainDoesNotThrow() {
ClientProvider client = new NonWorkingClientProvider();
client.release();
}
@Test
- public void requireThatReleaseDoesNotThrow() {
+ void requireThatReleaseDoesNotThrow() {
ClientProvider client = new NonWorkingClientProvider();
client.release();
}
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingCompletionHandlerTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingCompletionHandlerTestCase.java
index 7aff45e195f..edd4447cbe6 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingCompletionHandlerTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingCompletionHandlerTestCase.java
@@ -2,9 +2,9 @@
package com.yahoo.jdisc.test;
import com.yahoo.jdisc.handler.CompletionHandler;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -13,7 +13,7 @@ import static org.junit.Assert.fail;
public class NonWorkingCompletionHandlerTestCase {
@Test
- public void requireThatCompletedThrowsException() {
+ void requireThatCompletedThrowsException() {
CompletionHandler completion = new NonWorkingCompletionHandler();
try {
completion.completed();
@@ -24,7 +24,7 @@ public class NonWorkingCompletionHandlerTestCase {
}
@Test
- public void requireThatFailedThrowsException() {
+ void requireThatFailedThrowsException() {
CompletionHandler completion = new NonWorkingCompletionHandler();
try {
completion.failed(null);
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingContentChannelTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingContentChannelTestCase.java
index 4b26a53442d..46bbbad95ca 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingContentChannelTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingContentChannelTestCase.java
@@ -3,11 +3,11 @@ package com.yahoo.jdisc.test;
import com.yahoo.jdisc.handler.CompletionHandler;
import com.yahoo.jdisc.handler.ContentChannel;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -16,7 +16,7 @@ import static org.junit.Assert.fail;
public class NonWorkingContentChannelTestCase {
@Test
- public void requireThatWriteThrowsException() {
+ void requireThatWriteThrowsException() {
ContentChannel content = new NonWorkingContentChannel();
try {
content.write(null, null);
@@ -48,7 +48,7 @@ public class NonWorkingContentChannelTestCase {
}
@Test
- public void requireThatCloseThrowsException() {
+ void requireThatCloseThrowsException() {
ContentChannel content = new NonWorkingContentChannel();
try {
content.close(null);
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingOsgiFrameworkTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingOsgiFrameworkTestCase.java
index 64d670b3efe..96c4e66987d 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingOsgiFrameworkTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingOsgiFrameworkTestCase.java
@@ -2,15 +2,15 @@
package com.yahoo.jdisc.test;
import com.yahoo.jdisc.application.OsgiFramework;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleException;
import java.util.Collections;
-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.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -19,26 +19,26 @@ import static org.junit.Assert.fail;
public class NonWorkingOsgiFrameworkTestCase {
@Test
- public void requireThatFrameworkCanStartAndStop() throws BundleException {
+ void requireThatFrameworkCanStartAndStop() throws BundleException {
OsgiFramework osgi = new NonWorkingOsgiFramework();
osgi.start();
osgi.stop();
}
@Test
- public void requireThatFrameworkHasNoBundles() throws BundleException {
+ void requireThatFrameworkHasNoBundles() throws BundleException {
OsgiFramework osgi = new NonWorkingOsgiFramework();
assertTrue(osgi.bundles().isEmpty());
}
@Test
- public void requireThatFrameworkHasNoBundleContext() {
+ void requireThatFrameworkHasNoBundleContext() {
OsgiFramework osgi = new NonWorkingOsgiFramework();
assertNull(osgi.bundleContext());
}
@Test
- public void requireThatFrameworkThrowsOnInstallBundle() throws BundleException {
+ void requireThatFrameworkThrowsOnInstallBundle() throws BundleException {
OsgiFramework osgi = new NonWorkingOsgiFramework();
try {
osgi.installBundle("file:bundle.jar");
@@ -49,7 +49,7 @@ public class NonWorkingOsgiFrameworkTestCase {
}
@Test
- public void requireThatFrameworkThrowsOnStartBundles() throws BundleException {
+ void requireThatFrameworkThrowsOnStartBundles() throws BundleException {
OsgiFramework osgi = new NonWorkingOsgiFramework();
try {
osgi.startBundles(Collections.<Bundle>emptyList(), false);
@@ -60,7 +60,7 @@ public class NonWorkingOsgiFrameworkTestCase {
}
@Test
- public void requireThatFrameworkThrowsOnRefreshPackages() throws BundleException, InterruptedException {
+ void requireThatFrameworkThrowsOnRefreshPackages() throws BundleException, InterruptedException {
OsgiFramework osgi = new NonWorkingOsgiFramework();
try {
osgi.refreshPackages();
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingRequestHandlerTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingRequestHandlerTestCase.java
index 4d7e911907f..26713d78ca2 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingRequestHandlerTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingRequestHandlerTestCase.java
@@ -2,9 +2,9 @@
package com.yahoo.jdisc.test;
import com.yahoo.jdisc.handler.RequestHandler;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -13,7 +13,7 @@ import static org.junit.Assert.fail;
public class NonWorkingRequestHandlerTestCase {
@Test
- public void requireThatHandleRequestThrowsException() {
+ void requireThatHandleRequestThrowsException() {
RequestHandler requestHandler = new NonWorkingRequestHandler();
try {
requestHandler.handleRequest(null, null);
@@ -24,7 +24,7 @@ public class NonWorkingRequestHandlerTestCase {
}
@Test
- public void requireThatHandleTimeoutThrowsException() {
+ void requireThatHandleTimeoutThrowsException() {
RequestHandler requestHandler = new NonWorkingRequestHandler();
try {
requestHandler.handleTimeout(null, null);
@@ -35,7 +35,7 @@ public class NonWorkingRequestHandlerTestCase {
}
@Test
- public void requireThatDestroyDoesNotThrow() {
+ void requireThatDestroyDoesNotThrow() {
RequestHandler requestHandler = new NonWorkingRequestHandler();
requestHandler.release();
}
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingRequestTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingRequestTestCase.java
index b0d67102a12..31c08057c87 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingRequestTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingRequestTestCase.java
@@ -3,10 +3,10 @@ package com.yahoo.jdisc.test;
import com.google.inject.AbstractModule;
import com.yahoo.jdisc.Request;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertSame;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertSame;
/**
@@ -15,12 +15,12 @@ import static org.junit.Assert.assertSame;
public class NonWorkingRequestTestCase {
@Test
- public void requireThatFactoryMethodWorks() {
+ void requireThatFactoryMethodWorks() {
assertNotNull(NonWorkingRequest.newInstance("scheme://host/path"));
}
@Test
- public void requireThatGuiceModulesAreInjected() {
+ void requireThatGuiceModulesAreInjected() {
Object obj = new Object();
Request request = NonWorkingRequest.newInstance("scheme://host/path", new AbstractModule() {
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingResponseHandlerTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingResponseHandlerTestCase.java
index 6b7af12c763..08b0a58b75c 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingResponseHandlerTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingResponseHandlerTestCase.java
@@ -2,9 +2,9 @@
package com.yahoo.jdisc.test;
import com.yahoo.jdisc.Response;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -13,7 +13,7 @@ import static org.junit.Assert.fail;
public class NonWorkingResponseHandlerTestCase {
@Test
- public void requireThatHandleResponseThrowsException() {
+ void requireThatHandleResponseThrowsException() {
NonWorkingResponseHandler handler = new NonWorkingResponseHandler();
try {
handler.handleResponse(new Response(Response.Status.OK));
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingServerTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingServerTestCase.java
index 1666f737459..54fbb29afec 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingServerTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/test/NonWorkingServerTestCase.java
@@ -2,7 +2,7 @@
package com.yahoo.jdisc.test;
import com.yahoo.jdisc.service.ServerProvider;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
/**
* @author Simon Thoresen Hult
@@ -10,25 +10,25 @@ import org.junit.Test;
public class NonWorkingServerTestCase {
@Test
- public void requireThatStartDoesNotThrow() {
+ void requireThatStartDoesNotThrow() {
ServerProvider server = new NonWorkingServerProvider();
server.start();
}
@Test
- public void requireThatCloseDoesNotThrow() {
+ void requireThatCloseDoesNotThrow() {
ServerProvider server = new NonWorkingServerProvider();
server.close();
}
@Test
- public void requireThatReferDoesNotThrow() {
+ void requireThatReferDoesNotThrow() {
ServerProvider server = new NonWorkingServerProvider();
server.refer();
}
@Test
- public void requireThatReleaseDoesNotThrow() {
+ void requireThatReleaseDoesNotThrow() {
ServerProvider server = new NonWorkingServerProvider();
server.release();
}
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/test/ServerProviderConformanceTestTest.java b/jdisc_core/src/test/java/com/yahoo/jdisc/test/ServerProviderConformanceTestTest.java
index c9c7ec1db48..89befa40367 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/test/ServerProviderConformanceTestTest.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/test/ServerProviderConformanceTestTest.java
@@ -12,7 +12,7 @@ import com.yahoo.jdisc.handler.ContentChannel;
import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.service.CurrentContainer;
import com.yahoo.jdisc.service.ServerProvider;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.net.URI;
diff --git a/jdisc_core/src/test/java/com/yahoo/jdisc/test/TestDriverTestCase.java b/jdisc_core/src/test/java/com/yahoo/jdisc/test/TestDriverTestCase.java
index 70ee85861e6..961e2998d8f 100644
--- a/jdisc_core/src/test/java/com/yahoo/jdisc/test/TestDriverTestCase.java
+++ b/jdisc_core/src/test/java/com/yahoo/jdisc/test/TestDriverTestCase.java
@@ -11,13 +11,13 @@ import com.yahoo.jdisc.handler.ContentChannel;
import com.yahoo.jdisc.handler.RequestDeniedException;
import com.yahoo.jdisc.handler.ResponseHandler;
import com.yahoo.jdisc.service.ContainerNotReadyException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.ByteBuffer;
-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.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
/**
@@ -26,7 +26,7 @@ import static org.junit.Assert.fail;
public class TestDriverTestCase {
@Test
- public void requireThatFactoryMethodsWork() {
+ void requireThatFactoryMethodsWork() {
TestDriver.newInjectedApplicationInstance(MyApplication.class).close();
TestDriver.newInjectedApplicationInstanceWithoutOsgi(MyApplication.class).close();
TestDriver.newInjectedApplicationInstance(new MyApplication()).close();
@@ -36,14 +36,14 @@ public class TestDriverTestCase {
}
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
assertNotNull(driver.bootstrapLoader());
assertTrue(driver.close());
}
@Test
- public void requireThatConnectRequestWorks() {
+ void requireThatConnectRequestWorks() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
MyRequestHandler requestHandler = new MyRequestHandler(new MyContentChannel());
ContainerBuilder builder = driver.newContainerBuilder();
@@ -58,7 +58,7 @@ public class TestDriverTestCase {
}
@Test
- public void requireThatDispatchRequestWorks() {
+ void requireThatDispatchRequestWorks() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
MyRequestHandler requestHandler = new MyRequestHandler(new MyContentChannel());
ContainerBuilder builder = driver.newContainerBuilder();
@@ -72,7 +72,7 @@ public class TestDriverTestCase {
}
@Test
- public void requireThatFailedRequestCreateDoesNotBlockClose() {
+ void requireThatFailedRequestCreateDoesNotBlockClose() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
try {
driver.connectRequest("scheme://host/path", new MyResponseHandler());
@@ -84,7 +84,7 @@ public class TestDriverTestCase {
}
@Test
- public void requireThatFailedRequestConnectDoesNotBlockClose() {
+ void requireThatFailedRequestConnectDoesNotBlockClose() {
TestDriver driver = TestDriver.newSimpleApplicationInstanceWithoutOsgi();
ContainerBuilder builder = driver.newContainerBuilder();
builder.serverBindings().bind("scheme://host/path", new MyRequestHandler(null));
diff --git a/messagebus/pom.xml b/messagebus/pom.xml
index 512c001e3ff..10ce87a429b 100644
--- a/messagebus/pom.xml
+++ b/messagebus/pom.xml
@@ -15,11 +15,6 @@
<packaging>jar</packaging>
<dependencies>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>com.yahoo.vespa</groupId>
<artifactId>vespajlib</artifactId>
<version>${project.version}</version>
@@ -37,6 +32,16 @@
<scope>provided</scope>
</dependency>
<dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
<groupId>com.yahoo.vespa</groupId>
<artifactId>config</artifactId>
<version>${project.version}</version>
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/ChokeTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/ChokeTestCase.java
index 6d50fc769be..a8a1fc33284 100755
--- a/messagebus/src/test/java/com/yahoo/messagebus/ChokeTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/ChokeTestCase.java
@@ -10,16 +10,13 @@ import com.yahoo.messagebus.routing.Route;
import com.yahoo.messagebus.test.Receptor;
import com.yahoo.messagebus.test.SimpleMessage;
import com.yahoo.messagebus.test.SimpleProtocol;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+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.assertTrue;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertFalse;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -31,7 +28,7 @@ public class ChokeTestCase {
SourceSession srcSession;
DestinationSession dstSession;
- @Before
+ @BeforeEach
public void setUp() throws ListenFailedException {
slobrok = new Slobrok();
dstServer = new TestServer(new MessageBusParams().addProtocol(new SimpleProtocol()),
@@ -44,7 +41,7 @@ public class ChokeTestCase {
assertTrue(srcServer.waitSlobrok("dst/session", 1));
}
- @After
+ @AfterEach
public void tearDown() {
slobrok.stop();
dstSession.destroy();
@@ -55,7 +52,7 @@ public class ChokeTestCase {
@Test
@SuppressWarnings("deprecation")
- public void testMaxCount() {
+ void testMaxCount() {
int max = 10;
dstServer.mb.setMaxPendingCount(max);
List<Message> lst = new ArrayList<>();
@@ -67,11 +64,11 @@ public class ChokeTestCase {
}
assertTrue(srcSession.send(createMessage("msg"), Route.parse("dst/session")).isAccepted());
if (i < max) {
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
lst.add(msg);
} else {
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
assertEquals(1, reply.getNumErrors());
assertEquals(ErrorCode.SESSION_BUSY, reply.getError(0).getCode());
@@ -81,13 +78,13 @@ public class ChokeTestCase {
Message msg = lst.remove(0);
dstSession.acknowledge(msg);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
assertFalse(reply.hasErrors());
assertNotNull(msg = reply.getMessage());
assertTrue(srcSession.send(msg, Route.parse("dst/session")).isAccepted());
- assertNotNull(msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60));
lst.add(msg);
}
while (!lst.isEmpty()) {
@@ -95,7 +92,7 @@ public class ChokeTestCase {
Message msg = lst.remove(0);
dstSession.acknowledge(msg);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
assertFalse(reply.hasErrors());
}
@@ -104,7 +101,7 @@ public class ChokeTestCase {
@Test
@SuppressWarnings("deprecation")
- public void testMaxSize() {
+ void testMaxSize() {
int size = createMessage("msg").getApproxSize();
int max = size * 10;
dstServer.mb.setMaxPendingSize(max);
@@ -117,11 +114,11 @@ public class ChokeTestCase {
}
assertTrue(srcSession.send(createMessage("msg"), Route.parse("dst/session")).isAccepted());
if (i < max) {
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
lst.add(msg);
} else {
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
assertEquals(1, reply.getNumErrors());
assertEquals(ErrorCode.SESSION_BUSY, reply.getError(0).getCode());
@@ -131,13 +128,13 @@ public class ChokeTestCase {
Message msg = lst.remove(0);
dstSession.acknowledge(msg);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
assertFalse(reply.hasErrors());
assertNotNull(msg = reply.getMessage());
assertTrue(srcSession.send(msg, Route.parse("dst/session")).isAccepted());
- assertNotNull(msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60));
lst.add(msg);
}
while (!lst.isEmpty()) {
@@ -145,7 +142,7 @@ public class ChokeTestCase {
Message msg = lst.remove(0);
dstSession.acknowledge(msg);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
assertFalse(reply.hasErrors());
}
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/ConfigAgentTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/ConfigAgentTestCase.java
index a32175ff414..ad8e8a7c94e 100755
--- a/messagebus/src/test/java/com/yahoo/messagebus/ConfigAgentTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/ConfigAgentTestCase.java
@@ -4,26 +4,24 @@ package com.yahoo.messagebus;
import com.yahoo.config.subscription.ConfigSet;
import com.yahoo.config.subscription.ConfigURI;
import com.yahoo.messagebus.routing.RoutingSpec;
-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.util.concurrent.TimeUnit;
-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
*/
public class ConfigAgentTestCase {
- @Rule
- public TemporaryFolder tmpFolder = new TemporaryFolder();
+ @TempDir
+ public File tmpFolder;
@Test
- public void testRoutingConfig() throws InterruptedException {
+ void testRoutingConfig() throws InterruptedException {
LocalHandler handler = new LocalHandler();
assertFalse(testHalf(handler.spec));
assertFalse(testFull(handler.spec));
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/DynamicThrottlePolicyTest.java b/messagebus/src/test/java/com/yahoo/messagebus/DynamicThrottlePolicyTest.java
index 9307396ceab..8f9ed2323d7 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/DynamicThrottlePolicyTest.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/DynamicThrottlePolicyTest.java
@@ -3,7 +3,7 @@ package com.yahoo.messagebus;
import com.yahoo.messagebus.test.SimpleMessage;
import com.yahoo.messagebus.test.SimpleReply;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayDeque;
import java.util.Collections;
@@ -16,7 +16,7 @@ import java.util.stream.IntStream;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Collectors.toUnmodifiableList;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* These tests are based on a simulated server, the {@link MockServer} below.
@@ -37,7 +37,7 @@ public class DynamicThrottlePolicyTest {
}
@Test
- public void singlePolicyWithSmallWindows() {
+ void singlePolicyWithSmallWindows() {
long operations = 1_000_000;
int numberOfWorkers = 1;
int maximumTasksPerWorker = 16;
@@ -48,8 +48,8 @@ public class DynamicThrottlePolicyTest {
CustomTimer timer = new CustomTimer();
DynamicThrottlePolicy policy = new DynamicThrottlePolicy(timer).setMinWindowSize(1)
- .setWindowSizeIncrement(0.1)
- .setResizeRate(100);
+ .setWindowSizeIncrement(0.1)
+ .setResizeRate(100);
Summary summary = run(operations, workPerSuccess, numberOfWorkers, maximumTasksPerWorker, workerParallelism, timer, policy);
double minMaxPending = numberOfWorkers * workerParallelism;
@@ -66,8 +66,8 @@ public class DynamicThrottlePolicyTest {
CustomTimer timer = new CustomTimer();
DynamicThrottlePolicy policy = new DynamicThrottlePolicy(timer).setMinWindowSize(1)
- .setWindowSizeIncrement(0.1)
- .setResizeRate(100);
+ .setWindowSizeIncrement(0.1)
+ .setResizeRate(100);
Summary summary = run(operations, workPerSuccess, numberOfWorkers, maximumTasksPerWorker, workerParallelism, timer, policy);
double maxMaxPending = numberOfWorkers * maximumTasksPerWorker;
@@ -82,8 +82,8 @@ public class DynamicThrottlePolicyTest {
CustomTimer timer = new CustomTimer();
DynamicThrottlePolicy policy = new DynamicThrottlePolicy(timer).setMinWindowSize(1)
- .setWindowSizeIncrement(0.1)
- .setResizeRate(100);
+ .setWindowSizeIncrement(0.1)
+ .setResizeRate(100);
Summary summary = run(operations, workPerSuccess, numberOfWorkers, maximumTasksPerWorker, workerParallelism, timer, policy);
double minMaxPending = numberOfWorkers * workerParallelism;
@@ -96,7 +96,7 @@ public class DynamicThrottlePolicyTest {
/** Sort of a dummy test, as the conditions are perfect. In a more realistic scenario, below, the algorithm needs luck to climb this high. */
@Test
- public void singlePolicySingleWorkerWithIncreasingParallelism() {
+ void singlePolicySingleWorkerWithIncreasingParallelism() {
for (int exponent = 0; exponent < 4; exponent++) {
CustomTimer timer = new CustomTimer();
DynamicThrottlePolicy policy = new DynamicThrottlePolicy(timer);
@@ -119,7 +119,7 @@ public class DynamicThrottlePolicyTest {
/** A more realistic test, where throughput gradually flattens with increasing window size, and with more variance in throughput. */
@Test
- public void singlePolicyIncreasingWorkersWithNoParallelism() {
+ void singlePolicyIncreasingWorkersWithNoParallelism() {
for (int exponent = 0; exponent < 4; exponent++) {
CustomTimer timer = new CustomTimer();
DynamicThrottlePolicy policy = new DynamicThrottlePolicy(timer);
@@ -149,7 +149,7 @@ public class DynamicThrottlePolicyTest {
}
@Test
- public void twoWeightedPoliciesWithUnboundedTaskQueue() {
+ void twoWeightedPoliciesWithUnboundedTaskQueue() {
for (int repeat = 0; repeat < 3; repeat++) {
long operations = 1_000_000;
int workPerSuccess = 6 + (int) (30 * Math.random());
@@ -173,7 +173,7 @@ public class DynamicThrottlePolicyTest {
}
@Test
- public void tenPoliciesVeryParallelServerWithShortTaskQueue() {
+ void tenPoliciesVeryParallelServerWithShortTaskQueue() {
for (int repeat = 0; repeat < 2; repeat++) {
long operations = 1_000_000;
int workPerSuccess = 6;
@@ -183,11 +183,11 @@ public class DynamicThrottlePolicyTest {
CustomTimer timer = new CustomTimer();
int p = 10;
DynamicThrottlePolicy[] policies = IntStream.range(0, p)
- .mapToObj(j -> new DynamicThrottlePolicy(timer)
- .setWeight((j + 1.0) / p)
- .setWindowSizeIncrement(5)
- .setMinWindowSize(1))
- .toArray(DynamicThrottlePolicy[]::new);
+ .mapToObj(j -> new DynamicThrottlePolicy(timer)
+ .setWeight((j + 1.0) / p)
+ .setWindowSizeIncrement(5)
+ .setMinWindowSize(1))
+ .toArray(DynamicThrottlePolicy[]::new);
Summary summary = run(operations, workPerSuccess, numberOfWorkers, maximumTasksPerWorker, workerParallelism, timer, policies);
double minMaxPending = numberOfWorkers * workerParallelism;
@@ -198,8 +198,8 @@ public class DynamicThrottlePolicyTest {
double imperfectionFactor = 1.6;
// Actual shares are not distributed perfectly proportionally to weights, but close enough.
assertInRange(minMaxPending * expectedShare / imperfectionFactor,
- summary.averageWindows[j],
- maxMaxPending * expectedShare * imperfectionFactor);
+ summary.averageWindows[j],
+ maxMaxPending * expectedShare * imperfectionFactor);
}
assertInRange(1.0, summary.inefficiency, 1.05);
assertInRange(0, summary.waste, 0.1);
@@ -208,8 +208,8 @@ public class DynamicThrottlePolicyTest {
static void assertInRange(double lower, double actual, double upper) {
System.err.printf("%10.4f <= %10.4f <= %10.4f\n", lower, actual, upper);
- assertTrue(actual + " should be not be smaller than " + lower, lower <= actual);
- assertTrue(actual + " should be not be greater than " + upper, upper >= actual);
+ assertTrue(lower <= actual, actual + " should be not be smaller than " + lower);
+ assertTrue(upper >= actual, actual + " should be not be greater than " + upper);
}
private Summary run(long operations, int workPerSuccess, int numberOfWorkers, int maximumTasksPerWorker,
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/ErrorTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/ErrorTestCase.java
index 82696d839d9..26e3661a137 100755
--- a/messagebus/src/test/java/com/yahoo/messagebus/ErrorTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/ErrorTestCase.java
@@ -7,11 +7,11 @@ import com.yahoo.messagebus.routing.RoutingTableSpec;
import com.yahoo.messagebus.test.Receptor;
import com.yahoo.messagebus.test.SimpleMessage;
import com.yahoo.messagebus.test.SimpleProtocol;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -19,7 +19,7 @@ import static org.junit.Assert.*;
public class ErrorTestCase {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
Error err = new Error(69, "foo");
assertEquals(69, err.getCode());
assertEquals("foo", err.getMessage());
@@ -31,7 +31,7 @@ public class ErrorTestCase {
}
@Test
- public void requireThatErrorIsPropagated() throws Exception {
+ void requireThatErrorIsPropagated() throws Exception {
RoutingTableSpec table = new RoutingTableSpec(SimpleProtocol.NAME);
table.addHop("itr", "test/itr/session", Arrays.asList("test/itr/session"));
table.addHop("dst", "test/dst/session", Arrays.asList("test/dst/session"));
@@ -89,8 +89,9 @@ public class ErrorTestCase {
src.destroy();
slobrok.stop();
}
+
@Test
- public void testErrorCodeCategorization() {
+ void testErrorCodeCategorization() {
assertTrue(ErrorCode.isFatal(ErrorCode.FATAL_ERROR));
assertFalse(ErrorCode.isTransient(ErrorCode.FATAL_ERROR));
assertTrue(ErrorCode.isMBusError(ErrorCode.FATAL_ERROR));
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/MessageBusTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/MessageBusTestCase.java
index 69a5401a27e..314d8558735 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/MessageBusTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/MessageBusTestCase.java
@@ -14,24 +14,24 @@ import com.yahoo.messagebus.routing.test.CustomPolicyFactory;
import com.yahoo.messagebus.test.Receptor;
import com.yahoo.messagebus.test.SimpleMessage;
import com.yahoo.messagebus.test.SimpleProtocol;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
public class MessageBusTestCase {
@Test
- public void requireThatBucketSequencingWithResenderEnabledCausesError() throws ListenFailedException {
+ void requireThatBucketSequencingWithResenderEnabledCausesError() throws ListenFailedException {
Slobrok slobrok = new Slobrok();
TestServer server = new TestServer(new MessageBusParams()
- .addProtocol(new SimpleProtocol())
- .setRetryPolicy(new RetryTransientErrorsPolicy()),
- new RPCNetworkParams()
- .setSlobrokConfigId(slobrok.configId()));
+ .addProtocol(new SimpleProtocol())
+ .setRetryPolicy(new RetryTransientErrorsPolicy()),
+ new RPCNetworkParams()
+ .setSlobrokConfigId(slobrok.configId()));
Receptor receptor = new Receptor();
SourceSession session = server.mb.createSourceSession(
new SourceSessionParams().setTimeout(600.0).setReplyHandler(receptor));
@@ -51,7 +51,7 @@ public class MessageBusTestCase {
}
@Test
- public void testConnectionSpec() throws ListenFailedException, UnknownHostException {
+ void testConnectionSpec() throws ListenFailedException, UnknownHostException {
// Setup servers and sessions.
Slobrok slobrok = new Slobrok();
List<TestServer> servers = new ArrayList<>();
@@ -84,28 +84,28 @@ public class MessageBusTestCase {
assertTrue(src.send(msg, Route.parse(route.toString())).isAccepted());
for (IntermediateSession itr : sessions) {
// Received using session name.
- assertNotNull(msg = ((Receptor)itr.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) itr.getMessageHandler()).getMessage(60));
itr.forward(msg);
// Received using connection spec.
- assertNotNull(msg = ((Receptor)itr.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) itr.getMessageHandler()).getMessage(60));
itr.forward(msg);
}
- assertNotNull(msg = ((Receptor)dst.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) dst.getMessageHandler()).getMessage(60));
dst.acknowledge(msg);
- for (int i = sessions.size(); --i >= 0;) {
+ for (int i = sessions.size(); --i >= 0; ) {
IntermediateSession itr = sessions.get(i);
// Received for connection spec.
- Reply reply = ((Receptor)itr.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) itr.getReplyHandler()).getReply(60);
assertNotNull(reply);
itr.forward(reply);
// Received for session name.
- assertNotNull(reply = ((Receptor)itr.getReplyHandler()).getReply(60));
+ assertNotNull(reply = ((Receptor) itr.getReplyHandler()).getReply(60));
itr.forward(reply);
}
- assertNotNull(((Receptor)src.getReplyHandler()).getReply(60));
+ assertNotNull(((Receptor) src.getReplyHandler()).getReply(60));
// Cleanup.
for (IntermediateSession session : sessions) {
@@ -118,13 +118,13 @@ public class MessageBusTestCase {
}
@Test
- public void testRoutingPolicyCache() throws ListenFailedException, UnknownHostException {
+ void testRoutingPolicyCache() throws ListenFailedException, UnknownHostException {
Slobrok slobrok = new Slobrok();
String config = "slobrok[1]\nslobrok[0].connectionspec \"" + new Spec("localhost", slobrok.port()).toString() + "\"\n";
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", new CustomPolicyFactory());
MessageBus bus = new MessageBus(new RPCNetwork(new RPCNetworkParams().setSlobrokConfigId("raw:" + config)),
- new MessageBusParams().addProtocol(protocol));
+ new MessageBusParams().addProtocol(protocol));
RoutingPolicy all = bus.getRoutingPolicy(SimpleProtocol.NAME, "Custom", null);
assertNotNull(all);
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/MessengerTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/MessengerTestCase.java
index 5bfb36f194b..cacbd08ab1c 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/MessengerTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/MessengerTestCase.java
@@ -1,12 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.messagebus;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Simon Thoresen Hult
@@ -14,7 +14,7 @@ import static org.junit.Assert.assertTrue;
public class MessengerTestCase {
@Test
- public void requireThatSyncWithSelfDoesNotCauseDeadLock() throws InterruptedException {
+ void requireThatSyncWithSelfDoesNotCauseDeadLock() throws InterruptedException {
final Messenger msn = new Messenger();
msn.start();
@@ -35,14 +35,14 @@ public class MessengerTestCase {
}
@Test
- public void requireThatTaskIsExecuted() throws InterruptedException {
+ void requireThatTaskIsExecuted() throws InterruptedException {
Messenger msn = new Messenger();
msn.start();
assertTrue(tryMessenger(msn));
}
@Test
- public void requireThatRunExceptionIsCaught() throws InterruptedException {
+ void requireThatRunExceptionIsCaught() throws InterruptedException {
Messenger msn = new Messenger();
msn.start();
msn.enqueue(new Messenger.Task() {
@@ -60,7 +60,7 @@ public class MessengerTestCase {
}
@Test
- public void requireThatDestroyExceptionIsCaught() throws InterruptedException {
+ void requireThatDestroyExceptionIsCaught() throws InterruptedException {
Messenger msn = new Messenger();
msn.start();
msn.enqueue(new Messenger.Task() {
@@ -78,7 +78,7 @@ public class MessengerTestCase {
}
@Test
- public void requireThatRunAndDestroyExceptionsAreCaught() throws InterruptedException {
+ void requireThatRunAndDestroyExceptionsAreCaught() throws InterruptedException {
Messenger msn = new Messenger();
msn.start();
msn.enqueue(new Messenger.Task() {
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/ProtocolRepositoryTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/ProtocolRepositoryTestCase.java
index af2b4148a3c..c587550a2f5 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/ProtocolRepositoryTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/ProtocolRepositoryTestCase.java
@@ -4,9 +4,9 @@ package com.yahoo.messagebus;
import com.yahoo.messagebus.routing.RoutingContext;
import com.yahoo.messagebus.routing.RoutingPolicy;
import com.yahoo.messagebus.test.SimpleProtocol;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -14,7 +14,7 @@ import static org.junit.Assert.*;
public class ProtocolRepositoryTestCase {
@Test
- public void requireThatPolicyCanBeNull() {
+ void requireThatPolicyCanBeNull() {
ProtocolRepository repo = new ProtocolRepository();
SimpleProtocol protocol = new SimpleProtocol();
repo.putProtocol(protocol);
@@ -22,7 +22,7 @@ public class ProtocolRepositoryTestCase {
}
@Test
- public void requireThatPolicyCanBeCreated() {
+ void requireThatPolicyCanBeCreated() {
ProtocolRepository repo = new ProtocolRepository();
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", new MyFactory());
@@ -31,7 +31,7 @@ public class ProtocolRepositoryTestCase {
}
@Test
- public void requireThatPolicyIsCached() {
+ void requireThatPolicyIsCached() {
ProtocolRepository repo = new ProtocolRepository();
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", new MyFactory());
@@ -46,7 +46,7 @@ public class ProtocolRepositoryTestCase {
}
@Test
- public void requireThatPolicyParamIsPartOfCacheKey() {
+ void requireThatPolicyParamIsPartOfCacheKey() {
ProtocolRepository repo = new ProtocolRepository();
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", new MyFactory());
@@ -61,7 +61,7 @@ public class ProtocolRepositoryTestCase {
}
@Test
- public void requireThatCreatePolicyExceptionIsCaught() {
+ void requireThatCreatePolicyExceptionIsCaught() {
ProtocolRepository repo = new ProtocolRepository();
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", new SimpleProtocol.PolicyFactory() {
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/RateThrottlingTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/RateThrottlingTestCase.java
index f52cb1df2fe..5e579f5d622 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/RateThrottlingTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/RateThrottlingTestCase.java
@@ -2,15 +2,15 @@
package com.yahoo.messagebus;
import com.yahoo.messagebus.test.SimpleMessage;
-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;
public class RateThrottlingTestCase {
@Test
- public void testPending() {
+ void testPending() {
CustomTimer timer = new CustomTimer();
RateThrottlingPolicy policy = new RateThrottlingPolicy(5.0, timer);
policy.setMaxPendingCount(200);
@@ -35,7 +35,7 @@ public class RateThrottlingTestCase {
}
@Test
- public void testRates() {
+ void testRates() {
assertEquals(10, getActualRate(0.1), 1);
assertEquals(1000, getActualRate(10), 100);
assertEquals(500, getActualRate(5), 50);
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/RoutableTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/RoutableTestCase.java
index ca60bb8024c..9802a7099d8 100755
--- a/messagebus/src/test/java/com/yahoo/messagebus/RoutableTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/RoutableTestCase.java
@@ -8,22 +8,18 @@ import com.yahoo.messagebus.routing.Route;
import com.yahoo.messagebus.test.Receptor;
import com.yahoo.messagebus.test.SimpleMessage;
import com.yahoo.messagebus.test.SimpleReply;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.UnknownHostException;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
public class RoutableTestCase {
private final double delta = 0.00000001;
@Test
- public void testMessageContext() throws ListenFailedException {
+ void testMessageContext() throws ListenFailedException {
Slobrok slobrok = new Slobrok();
TestServer srcServer = new TestServer("src", null, slobrok, null);
TestServer dstServer = new TestServer("dst", null, slobrok, null);
@@ -39,10 +35,10 @@ public class RoutableTestCase {
msg.setContext(context);
assertTrue(srcSession.send(msg, "dst/session", true).isAccepted());
- assertNotNull(msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60));
dstSession.acknowledge(msg);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
assertSame(reply.getContext(), context);
@@ -54,7 +50,7 @@ public class RoutableTestCase {
}
@Test
- public void testMessageSwapState() {
+ void testMessageSwapState() {
Message foo = new SimpleMessage("foo");
Route fooRoute = Route.parse("foo");
foo.setRoute(fooRoute);
@@ -80,7 +76,7 @@ public class RoutableTestCase {
}
@Test
- public void testReplySwapState() {
+ void testReplySwapState() {
Reply foo = new SimpleReply("foo");
Message fooMsg = new SimpleMessage("foo");
foo.setMessage(fooMsg);
@@ -104,7 +100,7 @@ public class RoutableTestCase {
}
@Test
- public void testMessageDiscard() {
+ void testMessageDiscard() {
Receptor handler = new Receptor();
Message msg = new SimpleMessage("foo");
msg.pushHandler(handler);
@@ -114,7 +110,7 @@ public class RoutableTestCase {
}
@Test
- public void testReplyDiscard() {
+ void testReplyDiscard() {
Receptor handler = new Receptor();
Message msg = new SimpleMessage("foo");
msg.pushHandler(handler);
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/SendProxyTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/SendProxyTestCase.java
index b51fc2da3de..2cce53c51e1 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/SendProxyTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/SendProxyTestCase.java
@@ -13,18 +13,15 @@ import com.yahoo.messagebus.test.Receptor;
import com.yahoo.messagebus.test.SimpleMessage;
import com.yahoo.messagebus.test.SimpleProtocol;
import com.yahoo.messagebus.test.SimpleReply;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.util.logging.Handler;
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.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -36,7 +33,7 @@ public class SendProxyTestCase {
SourceSession srcSession;
DestinationSession dstSession;
- @Before
+ @BeforeEach
public void setUp() throws ListenFailedException {
slobrok = new Slobrok();
dstServer = new TestServer(new MessageBusParams().addProtocol(new SimpleProtocol()),
@@ -49,7 +46,7 @@ public class SendProxyTestCase {
assertTrue(srcServer.waitSlobrok("dst/session", 1));
}
- @After
+ @AfterEach
public void tearDown() {
slobrok.stop();
dstSession.destroy();
@@ -59,7 +56,7 @@ public class SendProxyTestCase {
}
@Test
- public void testTraceByLogLevel() {
+ void testTraceByLogLevel() {
Logger log = Logger.getLogger(SendProxy.class.getName());
LogHandler logHandler = new LogHandler();
log.addHandler(logHandler);
@@ -77,17 +74,17 @@ public class SendProxyTestCase {
sendMessage(0, new Error(ErrorCode.FATAL_ERROR, "err"));
assertEquals("Trace for reply with error(s):\n" +
- "<trace>\n" +
- " <trace>\n" +
- " Sending message (version ${VERSION}) from client to 'dst/session' with x seconds timeout.\n" +
- " <trace>\n" +
- " Message (type 1) received at 'dst' for session 'session'.\n" +
- " [FATAL_ERROR @ localhost]: err\n" +
- " Sending reply (version ${VERSION}) from 'dst'.\n" +
- " </trace>\n" +
- " Reply (type 2) received at client.\n" +
- " </trace>\n" +
- "</trace>\n", logHandler.trace);
+ "<trace>\n" +
+ " <trace>\n" +
+ " Sending message (version ${VERSION}) from client to 'dst/session' with x seconds timeout.\n" +
+ " <trace>\n" +
+ " Message (type 1) received at 'dst' for session 'session'.\n" +
+ " [FATAL_ERROR @ localhost]: err\n" +
+ " Sending reply (version ${VERSION}) from 'dst'.\n" +
+ " </trace>\n" +
+ " Reply (type 2) received at client.\n" +
+ " </trace>\n" +
+ "</trace>\n", logHandler.trace);
logHandler.trace = null;
log.setLevel(Level.FINEST);
@@ -96,16 +93,16 @@ public class SendProxyTestCase {
sendMessage(0, null);
assertEquals("Trace for reply:\n" +
- "<trace>\n" +
- " <trace>\n" +
- " Sending message (version ${VERSION}) from client to 'dst/session' with x seconds timeout.\n" +
- " <trace>\n" +
- " Message (type 1) received at 'dst' for session 'session'.\n" +
- " Sending reply (version ${VERSION}) from 'dst'.\n" +
- " </trace>\n" +
- " Reply (type 0) received at client.\n" +
- " </trace>\n" +
- "</trace>\n", logHandler.trace);
+ "<trace>\n" +
+ " <trace>\n" +
+ " Sending message (version ${VERSION}) from client to 'dst/session' with x seconds timeout.\n" +
+ " <trace>\n" +
+ " Message (type 1) received at 'dst' for session 'session'.\n" +
+ " Sending reply (version ${VERSION}) from 'dst'.\n" +
+ " </trace>\n" +
+ " Reply (type 0) received at client.\n" +
+ " </trace>\n" +
+ "</trace>\n", logHandler.trace);
logHandler.trace = null;
sendMessage(1, new Error(ErrorCode.FATAL_ERROR, "err"));
@@ -113,17 +110,17 @@ public class SendProxyTestCase {
sendMessage(0, new Error(ErrorCode.FATAL_ERROR, "err"));
assertEquals("Trace for reply with error(s):\n" +
- "<trace>\n" +
- " <trace>\n" +
- " Sending message (version ${VERSION}) from client to 'dst/session' with x seconds timeout.\n" +
- " <trace>\n" +
- " Message (type 1) received at 'dst' for session 'session'.\n" +
- " [FATAL_ERROR @ localhost]: err\n" +
- " Sending reply (version ${VERSION}) from 'dst'.\n" +
- " </trace>\n" +
- " Reply (type 2) received at client.\n" +
- " </trace>\n" +
- "</trace>\n", logHandler.trace);
+ "<trace>\n" +
+ " <trace>\n" +
+ " Sending message (version ${VERSION}) from client to 'dst/session' with x seconds timeout.\n" +
+ " <trace>\n" +
+ " Message (type 1) received at 'dst' for session 'session'.\n" +
+ " [FATAL_ERROR @ localhost]: err\n" +
+ " Sending reply (version ${VERSION}) from 'dst'.\n" +
+ " </trace>\n" +
+ " Reply (type 2) received at client.\n" +
+ " </trace>\n" +
+ "</trace>\n", logHandler.trace);
logHandler.trace = null;
}
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/SequencerTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/SequencerTestCase.java
index 07de8f238bc..c3166a578b5 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/SequencerTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/SequencerTestCase.java
@@ -2,14 +2,12 @@
package com.yahoo.messagebus;
import com.yahoo.messagebus.test.SimpleMessage;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.LinkedList;
import java.util.Queue;
-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
@@ -17,7 +15,7 @@ import static org.junit.Assert.assertTrue;
public class SequencerTestCase {
@Test
- public void testSyncNone() {
+ void testSyncNone() {
TestQueue src = new TestQueue();
TestQueue dst = new TestQueue();
QueueSender sender = new QueueSender(dst);
@@ -49,7 +47,7 @@ public class SequencerTestCase {
}
@Test
- public void testSyncId() {
+ void testSyncId() {
TestQueue src = new TestQueue();
TestQueue dst = new TestQueue();
QueueSender sender = new QueueSender(dst);
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/SimpleTripTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/SimpleTripTestCase.java
index f13749ae213..0f930c51152 100755
--- a/messagebus/src/test/java/com/yahoo/messagebus/SimpleTripTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/SimpleTripTestCase.java
@@ -11,11 +11,9 @@ import com.yahoo.messagebus.test.Receptor;
import com.yahoo.messagebus.test.SimpleMessage;
import com.yahoo.messagebus.test.SimpleProtocol;
import com.yahoo.messagebus.test.SimpleReply;
-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.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -23,32 +21,32 @@ import static org.junit.Assert.assertTrue;
public class SimpleTripTestCase {
@Test
- public void testSimpleTrip() throws ListenFailedException {
+ void testSimpleTrip() throws ListenFailedException {
Slobrok slobrok = new Slobrok();
TestServer server = new TestServer(new MessageBusParams().addProtocol(new SimpleProtocol()),
- new RPCNetworkParams()
- .setIdentity(new Identity("srv"))
- .setSlobrokConfigId(TestServer.getSlobrokConfig(slobrok)));
+ new RPCNetworkParams()
+ .setIdentity(new Identity("srv"))
+ .setSlobrokConfigId(TestServer.getSlobrokConfig(slobrok)));
DestinationSession dst = server.mb.createDestinationSession(new DestinationSessionParams().setName("session").setMessageHandler(new Receptor()));
SourceSession src = server.mb.createSourceSession(
new SourceSessionParams().setTimeout(600.0).setReplyHandler(new Receptor()));
assertTrue(server.waitSlobrok("srv/session", 1));
assertTrue(src.send(new SimpleMessage("msg"), Route.parse("srv/session")).isAccepted());
- Message msg = ((Receptor)dst.getMessageHandler()).getMessage(60);
+ Message msg = ((Receptor) dst.getMessageHandler()).getMessage(60);
assertNotNull(msg);
assertEquals(SimpleProtocol.NAME, msg.getProtocol());
assertEquals(SimpleProtocol.MESSAGE, msg.getType());
- assertEquals("msg", ((SimpleMessage)msg).getValue());
+ assertEquals("msg", ((SimpleMessage) msg).getValue());
Reply reply = new SimpleReply("reply");
reply.swapState(msg);
dst.reply(reply);
- assertNotNull(reply = ((Receptor)src.getReplyHandler()).getReply(60));
+ assertNotNull(reply = ((Receptor) src.getReplyHandler()).getReply(60));
assertEquals(SimpleProtocol.NAME, reply.getProtocol());
assertEquals(SimpleProtocol.REPLY, reply.getType());
- assertEquals("reply", ((SimpleReply)reply).getValue());
+ assertEquals("reply", ((SimpleReply) reply).getValue());
src.destroy();
dst.destroy();
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/ThrottlerTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/ThrottlerTestCase.java
index c308380dbb2..045dc1177db 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/ThrottlerTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/ThrottlerTestCase.java
@@ -10,16 +10,13 @@ import com.yahoo.messagebus.test.Receptor;
import com.yahoo.messagebus.test.SimpleMessage;
import com.yahoo.messagebus.test.SimpleProtocol;
import com.yahoo.messagebus.test.SimpleReply;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
-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 Simon Thoresen Hult
@@ -29,7 +26,7 @@ public class ThrottlerTestCase {
Slobrok slobrok;
TestServer src, dst;
- @Before
+ @BeforeEach
public void setUp() throws ListenFailedException {
RoutingTableSpec table = new RoutingTableSpec(SimpleProtocol.NAME);
table.addHop("dst", "test/dst/session", Arrays.asList("test/dst/session"));
@@ -39,7 +36,7 @@ public class ThrottlerTestCase {
dst = new TestServer("test/dst", table, slobrok, null);
}
- @After
+ @AfterEach
public void tearDown() {
dst.destroy();
src.destroy();
@@ -47,7 +44,7 @@ public class ThrottlerTestCase {
}
@Test
- public void testMaxCount() {
+ void testMaxCount() {
// Prepare a source session with throttle enabled.
SourceSessionParams params = new SourceSessionParams().setTimeout(600.0);
StaticThrottlePolicy policy = new StaticThrottlePolicy();
@@ -71,7 +68,7 @@ public class ThrottlerTestCase {
// Acknowledge one message at a time, then attempt to send two more.
for (int i = 0; i < 10; i++) {
assertTrue(dst_q.waitSize(policy.getMaxPendingCount(), 60));
- dst_s.acknowledge((Message)dst_q.dequeue());
+ dst_s.acknowledge((Message) dst_q.dequeue());
assertNotNull(src_rr.getReply(60));
assertTrue(src_s.send(new SimpleMessage("msg"), "test").isAccepted());
@@ -80,7 +77,7 @@ public class ThrottlerTestCase {
assertTrue(dst_q.waitSize(policy.getMaxPendingCount(), 60));
while (!dst_q.isEmpty()) {
- dst_s.acknowledge((Message)dst_q.dequeue());
+ dst_s.acknowledge((Message) dst_q.dequeue());
}
src_s.close();
@@ -88,7 +85,7 @@ public class ThrottlerTestCase {
}
@Test
- public void testMaxSize() {
+ void testMaxSize() {
// Prepare a source session with throttle enabled.
SourceSessionParams params = new SourceSessionParams().setTimeout(600.0);
StaticThrottlePolicy policy = new StaticThrottlePolicy();
@@ -110,17 +107,17 @@ public class ThrottlerTestCase {
assertTrue(dst_q.waitSize(2, 60));
assertFalse(src_s.send(new SimpleMessage("1"), "test").isAccepted());
- dst_s.acknowledge((Message)dst_q.dequeue());
+ dst_s.acknowledge((Message) dst_q.dequeue());
assertNotNull(src_rr.getReply(60));
assertFalse(src_s.send(new SimpleMessage("1"), "test").isAccepted());
- dst_s.acknowledge((Message)dst_q.dequeue());
+ dst_s.acknowledge((Message) dst_q.dequeue());
assertNotNull(src_rr.getReply(60));
assertTrue(src_s.send(new SimpleMessage("12"), "test").isAccepted());
assertTrue(dst_q.waitSize(1, 60));
assertFalse(src_s.send(new SimpleMessage("1"), "test").isAccepted());
- dst_s.acknowledge((Message)dst_q.dequeue());
+ dst_s.acknowledge((Message) dst_q.dequeue());
assertNotNull(src_rr.getReply(60));
// Close sessions.
@@ -129,12 +126,12 @@ public class ThrottlerTestCase {
}
@Test
- public void testDynamicWindowSize() {
+ void testDynamicWindowSize() {
CustomTimer timer = new CustomTimer();
DynamicThrottlePolicy policy = new DynamicThrottlePolicy(timer);
policy.setWindowSizeIncrement(5)
- .setResizeRate(1);
+ .setResizeRate(1);
double windowSize = getWindowSize(policy, timer, 100);
assertTrue(windowSize >= 90 && windowSize <= 105);
@@ -153,13 +150,13 @@ public class ThrottlerTestCase {
}
@Test
- public void testIdleTimePeriod() {
+ void testIdleTimePeriod() {
CustomTimer timer = new CustomTimer();
DynamicThrottlePolicy policy = new DynamicThrottlePolicy(timer);
policy.setWindowSizeIncrement(5)
- .setMinWindowSize(1)
- .setResizeRate(1);
+ .setMinWindowSize(1)
+ .setResizeRate(1);
double windowSize = getWindowSize(policy, timer, 100);
assertTrue(windowSize >= 90 && windowSize <= 110);
@@ -180,20 +177,20 @@ public class ThrottlerTestCase {
}
@Test
- public void testMinWindowSize() {
+ void testMinWindowSize() {
CustomTimer timer = new CustomTimer();
DynamicThrottlePolicy policy = new DynamicThrottlePolicy(timer);
policy.setWindowSizeIncrement(5)
- .setResizeRate(1)
- .setMinWindowSize(150);
+ .setResizeRate(1)
+ .setMinWindowSize(150);
double windowSize = getWindowSize(policy, timer, 200);
assertTrue(windowSize >= 150 && windowSize <= 210);
}
@Test
- public void testMaxWindowSize() {
+ void testMaxWindowSize() {
CustomTimer timer = new CustomTimer();
DynamicThrottlePolicy policy = new DynamicThrottlePolicy(timer);
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/TimeoutTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/TimeoutTestCase.java
index a834b27156a..3957b7de985 100755
--- a/messagebus/src/test/java/com/yahoo/messagebus/TimeoutTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/TimeoutTestCase.java
@@ -10,14 +10,14 @@ import com.yahoo.messagebus.routing.Route;
import com.yahoo.messagebus.test.Receptor;
import com.yahoo.messagebus.test.SimpleMessage;
import com.yahoo.messagebus.test.SimpleProtocol;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.net.UnknownHostException;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Simon Thoresen Hult
@@ -43,12 +43,12 @@ public class TimeoutTestCase {
new SourceSessionParams().setTimeout(600.0).setReplyHandler(new Receptor()));
}
- @Before
+ @BeforeEach
public void waitForSlobrokRegistration() {
assertTrue(srcServer.waitSlobrok("dst/session", 1));
}
- @After
+ @AfterEach
public void destroyResources() {
slobrok.stop();
dstSession.destroy();
@@ -63,17 +63,17 @@ public class TimeoutTestCase {
}
@Test
- public void requireThatMessageCanTimeout() throws ListenFailedException, UnknownHostException {
+ void requireThatMessageCanTimeout() throws ListenFailedException, UnknownHostException {
srcSession.setTimeout(1);
assertSend(srcSession, newMessage(), "dst/session");
- assertTimeout(((Receptor)srcSession.getReplyHandler()).getReply(60));
+ assertTimeout(((Receptor) srcSession.getReplyHandler()).getReply(60));
}
@Test
- public void requireThatZeroTimeoutMeansImmediateTimeout() throws ListenFailedException, UnknownHostException {
+ void requireThatZeroTimeoutMeansImmediateTimeout() throws ListenFailedException, UnknownHostException {
srcSession.setTimeout(0);
assertSend(srcSession, newMessage(), "dst/session");
- assertTimeout(((Receptor)srcSession.getReplyHandler()).getReply(60));
+ assertTimeout(((Receptor) srcSession.getReplyHandler()).getReply(60));
}
private static void assertSend(SourceSession session, Message msg, String route) {
@@ -82,7 +82,7 @@ public class TimeoutTestCase {
private static void assertTimeout(Reply reply) {
assertNotNull(reply);
- assertTrue(reply.getTrace().toString(), hasError(reply, ErrorCode.TIMEOUT));
+ assertTrue(hasError(reply, ErrorCode.TIMEOUT), reply.getTrace().toString());
}
private static Message newMessage() {
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/TraceTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/TraceTestCase.java
index 7408079b7ac..2a6534a9445 100755
--- a/messagebus/src/test/java/com/yahoo/messagebus/TraceTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/TraceTestCase.java
@@ -1,10 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.messagebus;
-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.*;
/**
* @author Simon Thoresen Hult
@@ -12,7 +11,7 @@ import static org.junit.Assert.assertTrue;
public class TraceTestCase {
@Test
- public void testEncodeDecode() {
+ void testEncodeDecode() {
assertEquals("()", TraceNode.decode("").encode());
assertEquals("()", TraceNode.decode("[xyz").encode());
assertEquals("([xyz][])", TraceNode.decode("[xyz][]").encode());
@@ -25,12 +24,12 @@ public class TraceTestCase {
assertEquals("([])", TraceNode.decode("([])").encode());
assertTrue(TraceNode.decode("").isEmpty());
- assertTrue(!TraceNode.decode("([note])").isEmpty());
+ assertFalse(TraceNode.decode("([note])").isEmpty());
String str =
"([[17/Jun/2009:09:02:30 +0200\\] Message (type 1) received at 'dst' for session 'session'.]" +
- "[[17/Jun/2009:09:02:30 +0200\\] [APP_TRANSIENT_ERROR @ localhost\\]: err1]" +
- "[[17/Jun/2009:09:02:30 +0200\\] Sending reply (version 4.2) from 'dst'.])";
+ "[[17/Jun/2009:09:02:30 +0200\\] [APP_TRANSIENT_ERROR @ localhost\\]: err1]" +
+ "[[17/Jun/2009:09:02:30 +0200\\] Sending reply (version 4.2) from 'dst'.])";
System.out.println(TraceNode.decode(str).toString());
assertEquals(str, TraceNode.decode(str).encode());
@@ -40,7 +39,7 @@ public class TraceTestCase {
assertTrue(t.isRoot());
assertTrue(t.isStrict());
- assertTrue(!t.isLeaf());
+ assertFalse(t.isLeaf());
assertEquals(4, t.getNumChildren());
{
@@ -55,8 +54,8 @@ public class TraceTestCase {
}
{
TraceNode c = t.getChild(2);
- assertTrue(!c.isLeaf());
- assertTrue(!c.isStrict());
+ assertFalse(c.isLeaf());
+ assertFalse(c.isStrict());
assertEquals(1, c.getNumChildren());
{
TraceNode d = c.getChild(0);
@@ -66,12 +65,12 @@ public class TraceTestCase {
}
{
TraceNode c = t.getChild(3);
- assertTrue(!c.isStrict());
+ assertFalse(c.isStrict());
assertEquals(2, c.getNumChildren());
{
TraceNode d = c.getChild(0);
assertTrue(d.isStrict());
- assertTrue(!d.isLeaf());
+ assertFalse(d.isLeaf());
assertEquals(1, d.getNumChildren());
{
TraceNode e = d.getChild(0);
@@ -85,7 +84,7 @@ public class TraceTestCase {
assertEquals(1, d.getNumChildren());
{
TraceNode e = d.getChild(0);
- assertTrue(!e.isStrict());
+ assertFalse(e.isStrict());
assertEquals(1, e.getNumChildren());
{
TraceNode f = e.getChild(0);
@@ -98,7 +97,7 @@ public class TraceTestCase {
}
@Test
- public void testReservedChars() {
+ void testReservedChars() {
TraceNode t = new TraceNode();
t.addChild("abc(){}[]\\xyz");
assertEquals("abc(){}[]\\xyz", t.getChild(0).getNote());
@@ -108,7 +107,7 @@ public class TraceTestCase {
TraceNode t2 = new TraceNode();
assertTrue(t2.isEmpty());
t2.swap(t);
- assertTrue(!t2.isEmpty());
+ assertFalse(t2.isEmpty());
assertEquals("abc(){}[]\\xyz", t2.getChild(0).getNote());
assertEquals("([abc(){}[\\]\\\\xyz])", t2.encode());
t2.clear();
@@ -117,7 +116,7 @@ public class TraceTestCase {
}
@Test
- public void testAdd() {
+ void testAdd() {
TraceNode t1 = TraceNode.decode("([x])");
TraceNode t2 = TraceNode.decode("([y])");
TraceNode t3 = TraceNode.decode("([z])");
@@ -137,14 +136,14 @@ public class TraceTestCase {
}
@Test
- public void testStrict() {
+ void testStrict() {
assertEquals("{}", TraceNode.decode("()").setStrict(false).encode());
assertEquals("{[x]}", TraceNode.decode("([x])").setStrict(false).encode());
assertEquals("{[x][y]}", TraceNode.decode("([x][y])").setStrict(false).encode());
}
@Test
- public void testTraceLevel() {
+ void testTraceLevel() {
Trace t = new Trace();
t.setLevel(4);
assertEquals(4, t.getLevel());
@@ -171,7 +170,7 @@ public class TraceTestCase {
}
@Test
- public void testCompact() {
+ void testCompact() {
assertEquals("()", TraceNode.decode("()").compact().encode());
assertEquals("()", TraceNode.decode("(())").compact().encode());
assertEquals("()", TraceNode.decode("(()())").compact().encode());
@@ -201,7 +200,7 @@ public class TraceTestCase {
}
@Test
- public void testSort() {
+ void testSort() {
assertEquals("([b][a][c])", TraceNode.decode("([b][a][c])").sort().encode());
assertEquals("({[a][b][c]})", TraceNode.decode("({[b][a][c]})").sort().encode());
assertEquals("(([c][a])([b]))", TraceNode.decode("(([c][a])([b]))").sort().encode());
@@ -211,7 +210,7 @@ public class TraceTestCase {
}
@Test
- public void testNormalize() {
+ void testNormalize() {
TraceNode t1 = TraceNode.decode("({([a][b]{[x][y]([p][q])})([c][d])([e][f])})");
TraceNode t2 = TraceNode.decode("({([a][b]{[y][x]([p][q])})([c][d])([e][f])})");
TraceNode t3 = TraceNode.decode("({([a][b]{[y]([p][q])[x]})([c][d])([e][f])})");
@@ -224,13 +223,13 @@ public class TraceTestCase {
assertEquals("({([a][b]{[x][y]([p][q])})([c][d])([e][f])})", t1.compact().encode());
- assertTrue(!t1.compact().encode().equals(t2.compact().encode()));
- assertTrue(!t1.compact().encode().equals(t3.compact().encode()));
- assertTrue(!t1.compact().encode().equals(t4.compact().encode()));
- assertTrue(!t1.compact().encode().equals(t5.compact().encode()));
- assertTrue(!t1.compact().encode().equals(tx.compact().encode()));
- assertTrue(!t1.compact().encode().equals(ty.compact().encode()));
- assertTrue(!t1.compact().encode().equals(tz.compact().encode()));
+ assertNotEquals(t1.compact().encode(), t2.compact().encode());
+ assertNotEquals(t1.compact().encode(), t3.compact().encode());
+ assertNotEquals(t1.compact().encode(), t4.compact().encode());
+ assertNotEquals(t1.compact().encode(), t5.compact().encode());
+ assertNotEquals(t1.compact().encode(), tx.compact().encode());
+ assertNotEquals(t1.compact().encode(), ty.compact().encode());
+ assertNotEquals(t1.compact().encode(), tz.compact().encode());
System.out.println("1: " + t1.normalize().encode());
System.out.println("2: " + t2.normalize().encode());
@@ -240,19 +239,19 @@ public class TraceTestCase {
System.out.println("x: " + tx.normalize().encode());
System.out.println("y: " + ty.normalize().encode());
System.out.println("z: " + tz.normalize().encode());
- assertTrue(t1.normalize().encode().equals(t2.normalize().encode()));
- assertTrue(t1.normalize().encode().equals(t3.normalize().encode()));
- assertTrue(t1.normalize().encode().equals(t4.normalize().encode()));
- assertTrue(t1.normalize().encode().equals(t5.normalize().encode()));
- assertTrue(!t1.normalize().encode().equals(tx.normalize().encode()));
- assertTrue(!t1.normalize().encode().equals(ty.normalize().encode()));
- assertTrue(!t1.normalize().encode().equals(tz.normalize().encode()));
+ assertEquals(t1.normalize().encode(), t2.normalize().encode());
+ assertEquals(t1.normalize().encode(), t3.normalize().encode());
+ assertEquals(t1.normalize().encode(), t4.normalize().encode());
+ assertEquals(t1.normalize().encode(), t5.normalize().encode());
+ assertNotEquals(t1.normalize().encode(), tx.normalize().encode());
+ assertNotEquals(t1.normalize().encode(), ty.normalize().encode());
+ assertNotEquals(t1.normalize().encode(), tz.normalize().encode());
assertEquals("({([c][d])([e][f])([a][b]{[x][y]([p][q])})})", t1.normalize().encode());
}
@Test
- public void testTraceDump() {
+ void testTraceDump() {
{
Trace big = new Trace();
TraceNode b1 = new TraceNode();
@@ -283,17 +282,17 @@ public class TraceTestCase {
assertEquals("...\n", s1.toString(0));
assertEquals("<trace>\n...\n", s1.toString(1));
assertEquals("<trace>\n" + // 8 8
- " <trace>\n" + // 12 20
- " test\n" + // 13 33
- "...\n", s1.toString(33));
+ " <trace>\n" + // 12 20
+ " test\n" + // 13 33
+ "...\n", s1.toString(33));
assertEquals("<trace>\n" + // 8 8
- " test\n" + // 9 17
- " test\n" + // 9 26
- "...\n", s2.toString(26));
+ " test\n" + // 9 17
+ " test\n" + // 9 26
+ "...\n", s2.toString(26));
assertEquals("<trace>\n" + // 8 8
- " test\n" + // 9 17
- " test\n" + // 9 26
- "</trace>\n", s2.toString(27));
+ " test\n" + // 9 17
+ " test\n" + // 9 26
+ "</trace>\n", s2.toString(27));
assertEquals(s2.toString(27), s2.toString());
}
}
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/TraceTripTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/TraceTripTestCase.java
index cc3e689e33e..e8d2fd72a47 100755
--- a/messagebus/src/test/java/com/yahoo/messagebus/TraceTripTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/TraceTripTestCase.java
@@ -8,14 +8,15 @@ import com.yahoo.messagebus.routing.RoutingTableSpec;
import com.yahoo.messagebus.test.Receptor;
import com.yahoo.messagebus.test.SimpleMessage;
import com.yahoo.messagebus.test.SimpleProtocol;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.net.UnknownHostException;
import java.util.Arrays;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Simon Thoresen Hult
@@ -27,7 +28,7 @@ public class TraceTripTestCase {
TestServer pxy;
TestServer dst;
- @Before
+ @BeforeEach
public void setUp() throws ListenFailedException {
RoutingTableSpec table = new RoutingTableSpec(SimpleProtocol.NAME)
.addHop("pxy", "test/pxy/session", Arrays.asList("test/pxy/session"))
@@ -40,7 +41,7 @@ public class TraceTripTestCase {
dst = new TestServer("test/dst", table, slobrok, null);
}
- @After
+ @AfterEach
public void tearDown() {
dst.destroy();
pxy.destroy();
@@ -49,7 +50,7 @@ public class TraceTripTestCase {
}
@Test
- public void testTrip() {
+ void testTrip() {
Receptor src_rr = new Receptor();
SourceSession src_s = src.mb.createSourceSession(src_rr);
@@ -66,18 +67,18 @@ public class TraceTripTestCase {
src_s.send(msg, "test");
Reply reply = src_rr.getReply(60);
reply.getTrace().trace(1, "Client reply", false);
- assertTrue(reply.getNumErrors() == 0);
+ assertEquals(reply.getNumErrors(), 0);
TraceNode t = new TraceNode()
- .addChild("Client message")
- .addChild("Proxy message")
- .addChild("Server message")
- .addChild("Server reply")
- .addChild("Proxy reply")
- .addChild("Client reply");
+ .addChild("Client message")
+ .addChild("Proxy message")
+ .addChild("Server message")
+ .addChild("Server reply")
+ .addChild("Proxy reply")
+ .addChild("Client reply");
System.out.println("reply: " + reply.getTrace().getRoot().encode());
System.out.println("want : " + t.encode());
- assertTrue(reply.getTrace().getRoot().encode().equals(t.encode()));
+ assertEquals(reply.getTrace().getRoot().encode(), t.encode());
}
private static class Proxy implements MessageHandler, ReplyHandler {
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/network/IdentityTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/network/IdentityTestCase.java
index 4309d17a407..5d2ca40df1a 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/network/IdentityTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/network/IdentityTestCase.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.messagebus.network;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* @author Simon Thoresen Hult
@@ -12,14 +12,14 @@ import static org.junit.Assert.assertNotNull;
public class IdentityTestCase {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
Identity id = new Identity("foo");
assertNotNull(id.getHostname());
assertEquals("foo", id.getServicePrefix());
}
@Test
- public void requireThatCopyConstructorWorks() {
+ void requireThatCopyConstructorWorks() {
Identity lhs = new Identity("foo");
Identity rhs = new Identity(lhs);
assertEquals(lhs.getHostname(), rhs.getHostname());
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/network/NetworkMultiplexerTest.java b/messagebus/src/test/java/com/yahoo/messagebus/network/NetworkMultiplexerTest.java
index 58145bb4f25..60da1b49d90 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/network/NetworkMultiplexerTest.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/network/NetworkMultiplexerTest.java
@@ -9,7 +9,7 @@ import com.yahoo.messagebus.test.SimpleMessage;
import com.yahoo.messagebus.test.SimpleProtocol;
import com.yahoo.text.Utf8Array;
import com.yahoo.text.Utf8String;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.HashMap;
@@ -19,10 +19,7 @@ import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
-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 jonmv
@@ -30,7 +27,7 @@ import static org.junit.Assert.fail;
public class NetworkMultiplexerTest {
@Test
- public void testShared() {
+ void testShared() {
MockNetwork net = new MockNetwork();
MockOwner owner1 = new MockOwner();
MockOwner owner2 = new MockOwner();
@@ -95,7 +92,7 @@ public class NetworkMultiplexerTest {
}
@Test
- public void testDedicated() {
+ void testDedicated() {
MockNetwork net = new MockNetwork();
MockOwner owner = new MockOwner();
NetworkMultiplexer dedicated = NetworkMultiplexer.dedicated(net);
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/network/local/LocalNetworkTest.java b/messagebus/src/test/java/com/yahoo/messagebus/network/local/LocalNetworkTest.java
index b3fec784d38..60618744c83 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/network/local/LocalNetworkTest.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/network/local/LocalNetworkTest.java
@@ -24,15 +24,13 @@ import com.yahoo.messagebus.routing.Route;
import com.yahoo.messagebus.test.SimpleMessage;
import com.yahoo.messagebus.test.SimpleProtocol;
import com.yahoo.messagebus.test.SimpleReply;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;
-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
@@ -40,7 +38,7 @@ import static org.junit.Assert.assertTrue;
public class LocalNetworkTest {
@Test
- public void requireThatLocalNetworkCanSendAndReceive() throws InterruptedException {
+ void requireThatLocalNetworkCanSendAndReceive() throws InterruptedException {
final LocalWire wire = new LocalWire();
final Server serverA = new Server(wire);
@@ -54,29 +52,29 @@ public class LocalNetworkTest {
Message msg = new SimpleMessage("foo");
msg.setRoute(new Route().addHop(Hop.parse(intermediate.getConnectionSpec()))
- .addHop(Hop.parse(destination.getConnectionSpec())));
+ .addHop(Hop.parse(destination.getConnectionSpec())));
assertTrue(source.send(msg).isAccepted());
msg = serverB.messages.poll(60, TimeUnit.SECONDS);
assertTrue(msg instanceof SimpleMessage);
- assertEquals("foo", ((SimpleMessage)msg).getValue());
+ assertEquals("foo", ((SimpleMessage) msg).getValue());
intermediate.forward(msg);
msg = serverC.messages.poll(60, TimeUnit.SECONDS);
assertTrue(msg instanceof SimpleMessage);
- assertEquals("foo", ((SimpleMessage)msg).getValue());
+ assertEquals("foo", ((SimpleMessage) msg).getValue());
Reply reply = new SimpleReply("bar");
reply.swapState(msg);
destination.reply(reply);
reply = serverB.replies.poll(60, TimeUnit.SECONDS);
assertTrue(reply instanceof SimpleReply);
- assertEquals("bar", ((SimpleReply)reply).getValue());
+ assertEquals("bar", ((SimpleReply) reply).getValue());
intermediate.forward(reply);
reply = serverA.replies.poll(60, TimeUnit.SECONDS);
assertTrue(reply instanceof SimpleReply);
- assertEquals("bar", ((SimpleReply)reply).getValue());
+ assertEquals("bar", ((SimpleReply) reply).getValue());
serverA.mbus.destroy();
serverB.mbus.destroy();
@@ -84,7 +82,7 @@ public class LocalNetworkTest {
}
@Test
- public void requireThatUnknownServiceRepliesWithNoAddressForService() throws InterruptedException {
+ void requireThatUnknownServiceRepliesWithNoAddressForService() throws InterruptedException {
final Server server = new Server(new LocalWire());
final SourceSession source = server.newSourceSession();
@@ -97,7 +95,7 @@ public class LocalNetworkTest {
}
@Test
- public void requireThatBlockingSendTimeOutInSendQ() throws InterruptedException {
+ void requireThatBlockingSendTimeOutInSendQ() throws InterruptedException {
final LocalWire wire = new LocalWire();
final Server serverA = new Server(wire);
@@ -124,24 +122,24 @@ public class LocalNetworkTest {
assertEquals(ErrorCode.TIMEOUT, res.getError().getCode());
assertTrue(res.getError().getMessage().endsWith("Timed out in sendQ"));
long end = SystemTimer.INSTANCE.milliTime();
- assertTrue(end >= start+TIMEOUT);
- assertTrue(end < start+5*TIMEOUT);
+ assertTrue(end >= start + TIMEOUT);
+ assertTrue(end < start + 5 * TIMEOUT);
msg = serverB.messages.poll(60, TimeUnit.SECONDS);
assertTrue(msg instanceof SimpleMessage);
- assertEquals("foo", ((SimpleMessage)msg).getValue());
+ assertEquals("foo", ((SimpleMessage) msg).getValue());
intermediate.forward(msg);
msg = serverC.messages.poll(60, TimeUnit.SECONDS);
assertTrue(msg instanceof SimpleMessage);
- assertEquals("foo", ((SimpleMessage)msg).getValue());
+ assertEquals("foo", ((SimpleMessage) msg).getValue());
Reply reply = new SimpleReply("bar");
reply.swapState(msg);
destination.reply(reply);
reply = serverB.replies.poll(60, TimeUnit.SECONDS);
assertTrue(reply instanceof SimpleReply);
- assertEquals("bar", ((SimpleReply)reply).getValue());
+ assertEquals("bar", ((SimpleReply) reply).getValue());
intermediate.forward(reply);
reply = serverA.replies.poll(60, TimeUnit.SECONDS);
@@ -150,7 +148,7 @@ public class LocalNetworkTest {
reply = serverA.replies.poll(60, TimeUnit.SECONDS);
assertTrue(reply instanceof SimpleReply);
- assertEquals("bar", ((SimpleReply)reply).getValue());
+ assertEquals("bar", ((SimpleReply) reply).getValue());
serverA.mbus.destroy();
serverB.mbus.destroy();
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/BasicNetworkTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/BasicNetworkTestCase.java
index 4134e352757..ffe15a7da29 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/BasicNetworkTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/BasicNetworkTestCase.java
@@ -13,16 +13,14 @@ import com.yahoo.messagebus.test.Receptor;
import com.yahoo.messagebus.test.SimpleMessage;
import com.yahoo.messagebus.test.SimpleProtocol;
import com.yahoo.messagebus.test.SimpleReply;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.net.UnknownHostException;
import java.util.Arrays;
-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.*;
/**
@@ -35,7 +33,7 @@ public class BasicNetworkTestCase {
TestServer pxy;
TestServer dst;
- @Before
+ @BeforeEach
public void setUp() throws ListenFailedException {
RoutingTableSpec table = new RoutingTableSpec(SimpleProtocol.NAME);
table.addHop("pxy", "test/pxy/session", Arrays.asList("test/pxy/session"));
@@ -47,7 +45,7 @@ public class BasicNetworkTestCase {
dst = new TestServer("test/dst", table, slobrok, null);
}
- @After
+ @AfterEach
public void tearDown() {
dst.destroy();
pxy.destroy();
@@ -56,7 +54,7 @@ public class BasicNetworkTestCase {
}
@Test
- public void testNetwork() {
+ void testNetwork() {
// set up receptors
Receptor src_rr = new Receptor();
Receptor pxy_mr = new Receptor();
@@ -126,7 +124,7 @@ public class BasicNetworkTestCase {
}
@Test
- public void testTimeoutsFollowMessage() {
+ void testTimeoutsFollowMessage() {
SourceSessionParams params = new SourceSessionParams().setTimeout(600.0);
SourceSession ss = src.mb.createSourceSession(new Receptor(), params);
DestinationSession ds = dst.mb.createDestinationSession("session", true, new Receptor());
@@ -138,24 +136,24 @@ public class BasicNetworkTestCase {
long now = SystemTimer.INSTANCE.milliTime();
assertTrue(ss.send(msg, Route.parse("dst")).isAccepted());
- assertNotNull(msg = ((Receptor)ds.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) ds.getMessageHandler()).getMessage(60));
assertTrue(msg.getTimeReceived() >= now);
assertTrue(params.getTimeout() * 1000 >= msg.getTimeRemaining());
ds.acknowledge(msg);
- assertNotNull(((Receptor)ss.getReplyHandler()).getReply(60));
+ assertNotNull(((Receptor) ss.getReplyHandler()).getReply(60));
// Test default timeouts being overwritten.
msg = new SimpleMessage("msg");
msg.getTrace().setLevel(9);
- msg.setTimeRemaining(2 * (long)(params.getTimeout() * 1000));
+ msg.setTimeRemaining(2 * (long) (params.getTimeout() * 1000));
assertTrue(ss.send(msg, Route.parse("dst")).isAccepted());
- assertNotNull(msg = ((Receptor)ds.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) ds.getMessageHandler()).getMessage(60));
assertTrue(params.getTimeout() * 1000 < msg.getTimeRemaining());
ds.acknowledge(msg);
- assertNotNull(((Receptor)ss.getReplyHandler()).getReply(60));
+ assertNotNull(((Receptor) ss.getReplyHandler()).getReply(60));
ss.destroy();
ds.destroy();
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/LoadBalanceTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/LoadBalanceTestCase.java
index 8ade06335f5..0856fb09318 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/LoadBalanceTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/LoadBalanceTestCase.java
@@ -9,12 +9,12 @@ import com.yahoo.messagebus.network.rpc.test.TestServer;
import com.yahoo.messagebus.routing.Route;
import com.yahoo.messagebus.test.QueueAdapter;
import com.yahoo.messagebus.test.SimpleMessage;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.UnknownHostException;
-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 havardpe
@@ -22,7 +22,7 @@ import static org.junit.Assert.assertTrue;
public class LoadBalanceTestCase {
@Test
- public void testLoadBalance() throws ListenFailedException {
+ void testLoadBalance() throws ListenFailedException {
Slobrok slobrok = new Slobrok();
TestServer src = new TestServer("src", null, slobrok, null);
TestServer dst1 = new TestServer("dst/1", null, slobrok, null);
@@ -32,14 +32,14 @@ public class LoadBalanceTestCase {
// set up handlers
final QueueAdapter sq = new QueueAdapter();
SourceSession ss = src.mb.createSourceSession(new SourceSessionParams().setTimeout(600.0).setThrottlePolicy(null)
- .setReplyHandler(new ReplyHandler() {
- @Override
- public void handleReply(Reply reply) {
- System.out.println(Thread.currentThread().getName() + ": Reply '" +
- ((SimpleMessage)reply.getMessage()).getValue() + "' received at source.");
- sq.handleReply(reply);
- }
- }));
+ .setReplyHandler(new ReplyHandler() {
+ @Override
+ public void handleReply(Reply reply) {
+ System.out.println(Thread.currentThread().getName() + ": Reply '" +
+ ((SimpleMessage) reply.getMessage()).getValue() + "' received at source.");
+ sq.handleReply(reply);
+ }
+ }));
SimpleDestination h1 = new SimpleDestination(dst1.mb, dst1.net.getIdentity());
SimpleDestination h2 = new SimpleDestination(dst2.mb, dst2.net.getIdentity());
SimpleDestination h3 = new SimpleDestination(dst3.mb, dst3.net.getIdentity());
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/RPCNetworkTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/RPCNetworkTestCase.java
index 0c42c592624..e8ea5f60715 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/RPCNetworkTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/RPCNetworkTestCase.java
@@ -17,12 +17,12 @@ import com.yahoo.messagebus.routing.Route;
import com.yahoo.messagebus.routing.RoutingPolicy;
import com.yahoo.messagebus.test.Receptor;
import com.yahoo.text.Utf8String;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.PrintWriter;
import java.io.StringWriter;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -30,12 +30,12 @@ import static org.junit.Assert.*;
public class RPCNetworkTestCase {
@Test
- public void requireThatProtocolEncodeExceptionIsCaught() throws Exception {
+ void requireThatProtocolEncodeExceptionIsCaught() throws Exception {
RuntimeException e = new RuntimeException();
Slobrok slobrok = new Slobrok();
TestServer server = new TestServer(new MessageBusParams().addProtocol(MyProtocol.newEncodeException(e)),
- new RPCNetworkParams().setSlobrokConfigId(slobrok.configId()));
+ new RPCNetworkParams().setSlobrokConfigId(slobrok.configId()));
Receptor receptor = new Receptor();
SourceSession src = server.mb.createSourceSession(
new SourceSessionParams().setTimeout(600.0).setReplyHandler(receptor));
@@ -50,7 +50,7 @@ public class RPCNetworkTestCase {
e.printStackTrace(new PrintWriter(expected));
String actual = reply.getError(0).toString();
- assertTrue(actual, actual.contains(expected.toString()));
+ assertTrue(actual.contains(expected.toString()), actual);
}
private static class MyMessage extends Message {
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/SendAdapterTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/SendAdapterTestCase.java
index 437be44ea25..c4cbf8ce6fb 100755
--- a/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/SendAdapterTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/SendAdapterTestCase.java
@@ -21,18 +21,15 @@ import com.yahoo.messagebus.test.Receptor;
import com.yahoo.messagebus.test.SimpleMessage;
import com.yahoo.messagebus.test.SimpleProtocol;
import com.yahoo.messagebus.test.SimpleReply;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.List;
-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.*;
/**
@@ -53,7 +50,7 @@ public class SendAdapterTestCase {
DestinationSession dstSession;
TestProtocol srcProtocol, itrProtocol, dstProtocol;
- @Before
+ @BeforeEach
public void setUp() throws ListenFailedException, UnknownHostException {
slobrok = new Slobrok();
dstServer = new TestServer(
@@ -74,7 +71,7 @@ public class SendAdapterTestCase {
assertTrue(srcServer.waitSlobrok("*/session", 2));
}
- @After
+ @AfterEach
public void tearDown() {
slobrok.stop();
dstSession.destroy();
@@ -92,16 +89,16 @@ public class SendAdapterTestCase {
////////////////////////////////////////////////////////////////////////////////
@Test
- public void requireCorrectVersionSelection() {
- assertNull(srcServer.net.getSendAdapter(new Version(4,999)));
- assertNull(srcServer.net.getSendAdapter(new Version(5,0)));
- assertNull(srcServer.net.getSendAdapter(new Version(6,148)));
- assertTrue(srcServer.net.getSendAdapter(new Version(6,149)) instanceof RPCSendV2);
- assertTrue(srcServer.net.getSendAdapter(new Version(9,9999)) instanceof RPCSendV2);
+ void requireCorrectVersionSelection() {
+ assertNull(srcServer.net.getSendAdapter(new Version(4, 999)));
+ assertNull(srcServer.net.getSendAdapter(new Version(5, 0)));
+ assertNull(srcServer.net.getSendAdapter(new Version(6, 148)));
+ assertTrue(srcServer.net.getSendAdapter(new Version(6, 149)) instanceof RPCSendV2);
+ assertTrue(srcServer.net.getSendAdapter(new Version(9, 9999)) instanceof RPCSendV2);
}
@Test
- public void requireThatMessagesCanBeSentAcrossAllSupportedVersions() {
+ void requireThatMessagesCanBeSentAcrossAllSupportedVersions() {
List<Version> versions = Arrays.asList(
new Version(6, 149),
new Version(9, 999)
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/ServiceAddressTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/ServiceAddressTestCase.java
index bbf1b827c87..af039dc46cb 100755
--- a/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/ServiceAddressTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/ServiceAddressTestCase.java
@@ -6,17 +6,14 @@ import com.yahoo.jrt.Spec;
import com.yahoo.jrt.slobrok.api.Mirror;
import com.yahoo.jrt.slobrok.server.Slobrok;
import com.yahoo.messagebus.network.Identity;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.net.UnknownHostException;
import java.util.List;
-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 Simon Thoresen Hult
@@ -26,7 +23,7 @@ public class ServiceAddressTestCase {
private Slobrok slobrok;
private RPCNetwork network;
- @Before
+ @BeforeEach
public void setUp() throws ListenFailedException, UnknownHostException {
slobrok = new Slobrok();
network = new RPCNetwork(new RPCNetworkParams()
@@ -35,14 +32,14 @@ public class ServiceAddressTestCase {
new Spec("localhost", slobrok.port()).toString() + "\"\n"));
}
- @After
+ @AfterEach
public void tearDown() {
network.shutdown();
slobrok.stop();
}
@Test
- public void testAddrServiceAddress() {
+ void testAddrServiceAddress() {
assertNullAddress("tcp");
assertNullAddress("tcp/");
assertNullAddress("tcp/localhost");
@@ -56,7 +53,7 @@ public class ServiceAddressTestCase {
}
@Test
- public void testNameServiceAddress() {
+ void testNameServiceAddress() {
network.unregisterSession("session");
assertTrue(waitSlobrok("foo/session", 0));
assertNullAddress("foo/session");
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/ServicePoolTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/ServicePoolTestCase.java
index 4bb39e99a48..ed085c73b54 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/ServicePoolTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/ServicePoolTestCase.java
@@ -4,10 +4,9 @@ package com.yahoo.messagebus.network.rpc;
import com.yahoo.jrt.ListenFailedException;
import com.yahoo.jrt.slobrok.server.Slobrok;
import com.yahoo.messagebus.network.rpc.test.TestServer;
-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.*;
/**
* @author Simon Thoresen Hult
@@ -15,7 +14,7 @@ import static org.junit.Assert.assertTrue;
public class ServicePoolTestCase {
@Test
- public void testMaxSize() throws ListenFailedException {
+ void testMaxSize() throws ListenFailedException {
Slobrok slobrok = new Slobrok();
RPCNetwork net = new RPCNetwork(new RPCNetworkParams().setSlobrokConfigId(TestServer.getSlobrokConfig(slobrok)));
RPCServicePool pool = new RPCServicePool(net, 2);
@@ -23,30 +22,30 @@ public class ServicePoolTestCase {
pool.resolve("foo");
assertEquals(1, pool.getSize());
assertTrue(pool.hasService("foo"));
- assertTrue(!pool.hasService("bar"));
- assertTrue(!pool.hasService("baz"));
+ assertFalse(pool.hasService("bar"));
+ assertFalse(pool.hasService("baz"));
pool.resolve("foo");
assertEquals(1, pool.getSize());
assertTrue(pool.hasService("foo"));
- assertTrue(!pool.hasService("bar"));
- assertTrue(!pool.hasService("baz"));
+ assertFalse(pool.hasService("bar"));
+ assertFalse(pool.hasService("baz"));
pool.resolve("bar");
assertEquals(2, pool.getSize());
assertTrue(pool.hasService("foo"));
assertTrue(pool.hasService("bar"));
- assertTrue(!pool.hasService("baz"));
+ assertFalse(pool.hasService("baz"));
pool.resolve("baz");
assertEquals(2, pool.getSize());
- assertTrue(!pool.hasService("foo"));
+ assertFalse(pool.hasService("foo"));
assertTrue(pool.hasService("bar"));
assertTrue(pool.hasService("baz"));
pool.resolve("bar");
assertEquals(2, pool.getSize());
- assertTrue(!pool.hasService("foo"));
+ assertFalse(pool.hasService("foo"));
assertTrue(pool.hasService("bar"));
assertTrue(pool.hasService("baz"));
@@ -54,7 +53,7 @@ public class ServicePoolTestCase {
assertEquals(2, pool.getSize());
assertTrue(pool.hasService("foo"));
assertTrue(pool.hasService("bar"));
- assertTrue(!pool.hasService("baz"));
+ assertFalse(pool.hasService("baz"));
slobrok.stop();
}
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/SlobrokTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/SlobrokTestCase.java
index 931fed596e5..35dad077809 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/SlobrokTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/SlobrokTestCase.java
@@ -7,15 +7,15 @@ import com.yahoo.jrt.Spec;
import com.yahoo.jrt.slobrok.api.Mirror;
import com.yahoo.jrt.slobrok.server.Slobrok;
import com.yahoo.messagebus.network.Identity;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -81,7 +81,7 @@ public class SlobrokTestCase {
assertTrue(false);
}
- @Before
+ @BeforeEach
public void setUp() throws ListenFailedException {
slobrok = new Slobrok();
String slobrokCfgId = "raw:slobrok[1]\nslobrok[0].connectionspec \"" + new Spec("localhost", slobrok.port()).toString() + "\"\n";
@@ -93,7 +93,7 @@ public class SlobrokTestCase {
port3 = net3.getPort();
}
- @After
+ @AfterEach
public void tearDown() {
net3.shutdown();
net2.shutdown();
@@ -102,7 +102,7 @@ public class SlobrokTestCase {
}
@Test
- public void testSlobrok() {
+ void testSlobrok() {
net1.registerSession("foo");
net2.registerSession("foo");
net2.registerSession("bar");
@@ -111,43 +111,43 @@ public class SlobrokTestCase {
net3.registerSession("baz");
check(net1, "*/*/*", new Res()
- .add("net/a/foo", net1.getConnectionSpec())
- .add("net/b/foo", net2.getConnectionSpec())
- .add("net/b/bar", net2.getConnectionSpec())
- .add("net/c/foo", net3.getConnectionSpec())
- .add("net/c/bar", net3.getConnectionSpec())
- .add("net/c/baz", net3.getConnectionSpec()).toArray());
+ .add("net/a/foo", net1.getConnectionSpec())
+ .add("net/b/foo", net2.getConnectionSpec())
+ .add("net/b/bar", net2.getConnectionSpec())
+ .add("net/c/foo", net3.getConnectionSpec())
+ .add("net/c/bar", net3.getConnectionSpec())
+ .add("net/c/baz", net3.getConnectionSpec()).toArray());
check(net2, "*/*/*", new Res()
- .add("net/a/foo", net1.getConnectionSpec())
- .add("net/b/foo", net2.getConnectionSpec())
- .add("net/b/bar", net2.getConnectionSpec())
- .add("net/c/foo", net3.getConnectionSpec())
- .add("net/c/bar", net3.getConnectionSpec())
- .add("net/c/baz", net3.getConnectionSpec()).toArray());
+ .add("net/a/foo", net1.getConnectionSpec())
+ .add("net/b/foo", net2.getConnectionSpec())
+ .add("net/b/bar", net2.getConnectionSpec())
+ .add("net/c/foo", net3.getConnectionSpec())
+ .add("net/c/bar", net3.getConnectionSpec())
+ .add("net/c/baz", net3.getConnectionSpec()).toArray());
check(net3, "*/*/*", new Res()
- .add("net/a/foo", net1.getConnectionSpec())
- .add("net/b/foo", net2.getConnectionSpec())
- .add("net/b/bar", net2.getConnectionSpec())
- .add("net/c/foo", net3.getConnectionSpec())
- .add("net/c/bar", net3.getConnectionSpec())
- .add("net/c/baz", net3.getConnectionSpec()).toArray());
+ .add("net/a/foo", net1.getConnectionSpec())
+ .add("net/b/foo", net2.getConnectionSpec())
+ .add("net/b/bar", net2.getConnectionSpec())
+ .add("net/c/foo", net3.getConnectionSpec())
+ .add("net/c/bar", net3.getConnectionSpec())
+ .add("net/c/baz", net3.getConnectionSpec()).toArray());
net2.unregisterSession("bar");
net3.unregisterSession("bar");
net3.unregisterSession("baz");
check(net1, "*/*/*", new Res()
- .add("net/a/foo", net1.getConnectionSpec())
- .add("net/b/foo", net2.getConnectionSpec())
- .add("net/c/foo", net3.getConnectionSpec()).toArray());
+ .add("net/a/foo", net1.getConnectionSpec())
+ .add("net/b/foo", net2.getConnectionSpec())
+ .add("net/c/foo", net3.getConnectionSpec()).toArray());
check(net2, "*/*/*", new Res()
- .add("net/a/foo", net1.getConnectionSpec())
- .add("net/b/foo", net2.getConnectionSpec())
- .add("net/c/foo", net3.getConnectionSpec()).toArray());
+ .add("net/a/foo", net1.getConnectionSpec())
+ .add("net/b/foo", net2.getConnectionSpec())
+ .add("net/c/foo", net3.getConnectionSpec()).toArray());
check(net3, "*/*/*", new Res()
- .add("net/a/foo", net1.getConnectionSpec())
- .add("net/b/foo", net2.getConnectionSpec())
- .add("net/c/foo", net3.getConnectionSpec()).toArray());
+ .add("net/a/foo", net1.getConnectionSpec())
+ .add("net/b/foo", net2.getConnectionSpec())
+ .add("net/c/foo", net3.getConnectionSpec()).toArray());
}
}
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/TargetPoolTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/TargetPoolTestCase.java
index 4dde73ad8c5..afeaa1304a1 100755
--- a/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/TargetPoolTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/network/rpc/TargetPoolTestCase.java
@@ -7,17 +7,14 @@ import com.yahoo.jrt.Transport;
import com.yahoo.jrt.slobrok.server.Slobrok;
import com.yahoo.concurrent.Timer;
import com.yahoo.messagebus.network.rpc.test.TestServer;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+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.assertNotSame;
-import static org.junit.Assert.assertSame;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -28,14 +25,14 @@ public class TargetPoolTestCase {
private List<TestServer> servers;
private Supervisor orb;
- @Before
+ @BeforeEach
public void setUp() throws ListenFailedException {
slobrok = new Slobrok();
servers = new ArrayList<>();
orb = new Supervisor(new Transport());
}
- @After
+ @AfterEach
public void tearDown() {
slobrok.stop();
for (TestServer server : servers) {
@@ -45,7 +42,7 @@ public class TargetPoolTestCase {
}
@Test
- public void testConnectionCycling() {
+ void testConnectionCycling() {
// Necessary setup to be able to resolve targets.
RPCServiceAddress adr1 = registerServer();
@@ -75,8 +72,9 @@ public class TargetPoolTestCase {
target3.subRef();
target4.subRef();
}
+
@Test
- public void testConnectionExpire() {
+ void testConnectionExpire() {
// Necessary setup to be able to resolve targets.
RPCServiceAddress adr1 = registerServer();
RPCServiceAddress adr2 = registerServer();
@@ -87,9 +85,12 @@ public class TargetPoolTestCase {
// Assert that all connections expire.
RPCTarget target;
- assertNotNull(target = pool.getTarget(orb, adr1)); target.subRef();
- assertNotNull(target = pool.getTarget(orb, adr2)); target.subRef();
- assertNotNull(target = pool.getTarget(orb, adr3)); target.subRef();
+ assertNotNull(target = pool.getTarget(orb, adr1));
+ target.subRef();
+ assertNotNull(target = pool.getTarget(orb, adr2));
+ target.subRef();
+ assertNotNull(target = pool.getTarget(orb, adr3));
+ target.subRef();
assertEquals(3, pool.size());
for (int i = 0; i < 10; ++i) {
pool.flushTargets(false);
@@ -100,20 +101,26 @@ public class TargetPoolTestCase {
assertEquals(0, pool.size());
// Assert that only idle connections expire.
- assertNotNull(target = pool.getTarget(orb, adr1)); target.subRef();
- assertNotNull(target = pool.getTarget(orb, adr2)); target.subRef();
- assertNotNull(target = pool.getTarget(orb, adr3)); target.subRef();
+ assertNotNull(target = pool.getTarget(orb, adr1));
+ target.subRef();
+ assertNotNull(target = pool.getTarget(orb, adr2));
+ target.subRef();
+ assertNotNull(target = pool.getTarget(orb, adr3));
+ target.subRef();
assertEquals(3, pool.size());
timer.millis += 444;
pool.flushTargets(false);
assertEquals(3, pool.size());
- assertNotNull(target = pool.getTarget(orb, adr2)); target.subRef();
- assertNotNull(target = pool.getTarget(orb, adr3)); target.subRef();
+ assertNotNull(target = pool.getTarget(orb, adr2));
+ target.subRef();
+ assertNotNull(target = pool.getTarget(orb, adr3));
+ target.subRef();
assertEquals(3, pool.size());
timer.millis += 444;
pool.flushTargets(false);
assertEquals(2, pool.size());
- assertNotNull(target = pool.getTarget(orb, adr3)); target.subRef();
+ assertNotNull(target = pool.getTarget(orb, adr3));
+ target.subRef();
timer.millis += 444;
pool.flushTargets(false);
assertEquals(1, pool.size());
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/routing/AdvancedRoutingTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/routing/AdvancedRoutingTestCase.java
index 3e6f345fb93..37024456878 100755
--- a/messagebus/src/test/java/com/yahoo/messagebus/routing/AdvancedRoutingTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/routing/AdvancedRoutingTestCase.java
@@ -20,16 +20,13 @@ import com.yahoo.messagebus.routing.test.CustomPolicyFactory;
import com.yahoo.messagebus.test.Receptor;
import com.yahoo.messagebus.test.SimpleMessage;
import com.yahoo.messagebus.test.SimpleProtocol;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.net.UnknownHostException;
-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 Simon Thoresen Hult
@@ -41,7 +38,7 @@ public class AdvancedRoutingTestCase {
SourceSession srcSession;
DestinationSession dstFoo, dstBar, dstBaz;
- @Before
+ @BeforeEach
public void setUp() throws ListenFailedException {
slobrok = new Slobrok();
dstServer = new TestServer(new MessageBusParams().addProtocol(new SimpleProtocol()),
@@ -56,7 +53,7 @@ public class AdvancedRoutingTestCase {
assertTrue(srcServer.waitSlobrok("dst/*", 3));
}
- @After
+ @AfterEach
public void tearDown() {
slobrok.stop();
dstFoo.destroy();
@@ -68,53 +65,53 @@ public class AdvancedRoutingTestCase {
}
@Test
- public void testAdvanced() {
+ void testAdvanced() {
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", new CustomPolicyFactory(false, ErrorCode.NO_ADDRESS_FOR_SERVICE));
srcServer.mb.putProtocol(protocol);
srcServer.setupRouting(new RoutingTableSpec(SimpleProtocol.NAME)
- .addHop(new HopSpec("bar", "dst/bar"))
- .addHop(new HopSpec("baz", "dst/baz"))
- .addRoute(new RouteSpec("baz").addHop("baz")));
+ .addHop(new HopSpec("bar", "dst/bar"))
+ .addHop(new HopSpec("baz", "dst/baz"))
+ .addRoute(new RouteSpec("baz").addHop("baz")));
Message msg = new SimpleMessage("msg");
msg.getTrace().setLevel(9);
assertTrue(srcSession.send(msg, Route.parse("[Custom:" + dstFoo.getConnectionSpec() + ",bar,route:baz,dst/cox,?dst/unknown]")).isAccepted());
// Initial send.
- assertNotNull(msg = ((Receptor)dstFoo.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) dstFoo.getMessageHandler()).getMessage(60));
dstFoo.acknowledge(msg);
- assertNotNull(msg = ((Receptor)dstBar.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) dstBar.getMessageHandler()).getMessage(60));
Reply reply = new EmptyReply();
reply.swapState(msg);
reply.addError(new Error(ErrorCode.TRANSIENT_ERROR, "bar"));
dstBar.reply(reply);
- assertNotNull(msg = ((Receptor)dstBaz.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) dstBaz.getMessageHandler()).getMessage(60));
reply = new EmptyReply();
reply.swapState(msg);
reply.addError(new Error(ErrorCode.TRANSIENT_ERROR, "baz1"));
dstBaz.reply(reply);
// First retry.
- assertNull(((Receptor)dstFoo.getMessageHandler()).getMessage(0));
- assertNotNull(msg = ((Receptor)dstBar.getMessageHandler()).getMessage(60));
+ assertNull(((Receptor) dstFoo.getMessageHandler()).getMessage(0));
+ assertNotNull(msg = ((Receptor) dstBar.getMessageHandler()).getMessage(60));
dstBar.acknowledge(msg);
- assertNotNull(msg = ((Receptor)dstBaz.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) dstBaz.getMessageHandler()).getMessage(60));
reply = new EmptyReply();
reply.swapState(msg);
reply.addError(new Error(ErrorCode.TRANSIENT_ERROR, "baz2"));
dstBaz.reply(reply);
// Second retry.
- assertNull(((Receptor)dstFoo.getMessageHandler()).getMessage(0));
- assertNull(((Receptor)dstBar.getMessageHandler()).getMessage(0));
- assertNotNull(msg = ((Receptor)dstBaz.getMessageHandler()).getMessage(60));
+ assertNull(((Receptor) dstFoo.getMessageHandler()).getMessage(0));
+ assertNull(((Receptor) dstBar.getMessageHandler()).getMessage(0));
+ assertNotNull(msg = ((Receptor) dstBaz.getMessageHandler()).getMessage(60));
reply = new EmptyReply();
reply.swapState(msg);
reply.addError(new Error(ErrorCode.FATAL_ERROR, "baz3"));
dstBaz.reply(reply);
// Done.
- reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertEquals(2, reply.getNumErrors());
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/routing/ResenderTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/routing/ResenderTestCase.java
index 375b247d286..3bc607f169b 100755
--- a/messagebus/src/test/java/com/yahoo/messagebus/routing/ResenderTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/routing/ResenderTestCase.java
@@ -19,15 +19,11 @@ import com.yahoo.messagebus.network.rpc.test.TestServer;
import com.yahoo.messagebus.test.Receptor;
import com.yahoo.messagebus.test.SimpleMessage;
import com.yahoo.messagebus.test.SimpleProtocol;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+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.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -40,7 +36,7 @@ public class ResenderTestCase {
DestinationSession dstSession;
RetryTransientErrorsPolicy retryPolicy;
- @Before
+ @BeforeEach
public void setUp() throws ListenFailedException {
slobrok = new Slobrok();
dstServer = new TestServer(new MessageBusParams().addProtocol(new SimpleProtocol()),
@@ -55,7 +51,7 @@ public class ResenderTestCase {
assertTrue(srcServer.waitSlobrok("dst/session", 1));
}
- @After
+ @AfterEach
public void tearDown() {
slobrok.stop();
dstSession.destroy();
@@ -65,94 +61,94 @@ public class ResenderTestCase {
}
@Test
- public void testRetryTag() {
+ void testRetryTag() {
assertTrue(srcSession.send(createMessage("msg"), Route.parse("dst/session")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
for (int i = 0; i < 5; ++i) {
assertEquals(i, msg.getRetry());
assertEquals(true, msg.getRetryEnabled());
replyFromDestination(msg, ErrorCode.APP_TRANSIENT_ERROR, 0);
- assertNotNull(msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60));
}
dstSession.acknowledge(msg);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
assertFalse(reply.hasErrors());
- assertNull(((Receptor)dstSession.getMessageHandler()).getMessage(0));
+ assertNull(((Receptor) dstSession.getMessageHandler()).getMessage(0));
System.out.println(reply.getTrace());
}
@Test
- public void testRetryEnabledTag() {
+ void testRetryEnabledTag() {
Message msg = createMessage("msg");
msg.setRetryEnabled(false);
assertTrue(srcSession.send(msg, Route.parse("dst/session")).isAccepted());
- assertNotNull(msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60));
assertEquals(false, msg.getRetryEnabled());
replyFromDestination(msg, ErrorCode.APP_TRANSIENT_ERROR, 0);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
assertTrue(reply.hasErrors());
- assertNull(((Receptor)dstSession.getMessageHandler()).getMessage(0));
+ assertNull(((Receptor) dstSession.getMessageHandler()).getMessage(0));
System.out.println(reply.getTrace());
}
@Test
- public void testTransientError() {
+ void testTransientError() {
assertTrue(srcSession.send(createMessage("msg"), Route.parse("dst/session")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
replyFromDestination(msg, ErrorCode.APP_TRANSIENT_ERROR, 0);
- assertNotNull(msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60));
replyFromDestination(msg, ErrorCode.APP_FATAL_ERROR, 0);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
assertTrue(reply.hasFatalErrors());
- assertNull(((Receptor)dstSession.getMessageHandler()).getMessage(0));
+ assertNull(((Receptor) dstSession.getMessageHandler()).getMessage(0));
}
@Test
- public void testFatalError() {
+ void testFatalError() {
assertTrue(srcSession.send(createMessage("msg"), Route.parse("dst/session")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
replyFromDestination(msg, ErrorCode.APP_FATAL_ERROR, 0);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
assertTrue(reply.hasFatalErrors());
- assertNull(((Receptor)dstSession.getMessageHandler()).getMessage(0));
+ assertNull(((Receptor) dstSession.getMessageHandler()).getMessage(0));
}
@Test
- public void testDisableRetry() {
+ void testDisableRetry() {
retryPolicy.setEnabled(false);
assertTrue(srcSession.send(createMessage("msg"), Route.parse("dst/session")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
replyFromDestination(msg, ErrorCode.APP_TRANSIENT_ERROR, 0);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
assertTrue(reply.hasErrors());
- assertTrue(!reply.hasFatalErrors());
- assertNull(((Receptor)dstSession.getMessageHandler()).getMessage(0));
+ assertFalse(reply.hasFatalErrors());
+ assertNull(((Receptor) dstSession.getMessageHandler()).getMessage(0));
}
@Test
- public void testRetryDelay() {
+ void testRetryDelay() {
retryPolicy.setBaseDelay(0.01);
assertTrue(srcSession.send(createMessage("msg"), Route.parse("dst/session")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
for (int i = 0; i < 5; ++i) {
replyFromDestination(msg, ErrorCode.APP_TRANSIENT_ERROR, -1);
- assertNotNull(msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60));
}
replyFromDestination(msg, ErrorCode.APP_FATAL_ERROR, 0);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
assertTrue(reply.hasFatalErrors());
- assertNull(((Receptor)dstSession.getMessageHandler()).getMessage(0));
+ assertNull(((Receptor) dstSession.getMessageHandler()).getMessage(0));
String trace = reply.getTrace().toString();
assertTrue(trace.contains("retry 1 in 0.0"));
@@ -163,19 +159,19 @@ public class ResenderTestCase {
}
@Test
- public void testRequestRetryDelay() {
+ void testRequestRetryDelay() {
assertTrue(srcSession.send(createMessage("msg"), Route.parse("dst/session")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
for (int i = 0; i < 5; ++i) {
replyFromDestination(msg, ErrorCode.APP_TRANSIENT_ERROR, i / 50.0);
- assertNotNull(msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60));
}
replyFromDestination(msg, ErrorCode.APP_FATAL_ERROR, 0);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
assertTrue(reply.hasFatalErrors());
- assertNull(((Receptor)dstSession.getMessageHandler()).getMessage(0));
+ assertNull(((Receptor) dstSession.getMessageHandler()).getMessage(0));
String trace = reply.getTrace().toString();
System.out.println(trace);
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/routing/RetryPolicyTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/routing/RetryPolicyTestCase.java
index 5095de0b2e7..6d3790e1407 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/routing/RetryPolicyTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/routing/RetryPolicyTestCase.java
@@ -2,11 +2,9 @@
package com.yahoo.messagebus.routing;
import com.yahoo.messagebus.ErrorCode;
-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.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -15,12 +13,12 @@ public class RetryPolicyTestCase {
private static final double SMALL = 0.00000000000000000001;
@Test
- public void testSimpleRetryPolicy() {
+ void testSimpleRetryPolicy() {
RetryTransientErrorsPolicy policy = new RetryTransientErrorsPolicy();
assertEquals(0.0, policy.getRetryDelay(0), SMALL);
assertEquals(0.0, policy.getRetryDelay(1), SMALL);
for (int i = 2; i < 15; i++) {
- assertEquals(0.001*(1 << (i-1)), policy.getRetryDelay(i), SMALL);
+ assertEquals(0.001 * (1 << (i - 1)), policy.getRetryDelay(i), SMALL);
}
assertEquals(10.0, policy.getRetryDelay(15), SMALL);
assertEquals(10.0, policy.getRetryDelay(20), SMALL);
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/routing/RouteParserTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/routing/RouteParserTestCase.java
index 20fc66825d7..aef61a05263 100755
--- a/messagebus/src/test/java/com/yahoo/messagebus/routing/RouteParserTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/routing/RouteParserTestCase.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.messagebus.routing;
-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.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -13,7 +11,7 @@ import static org.junit.Assert.assertTrue;
public class RouteParserTestCase {
@Test
- public void testHopParser() {
+ void testHopParser() {
Hop hop = Hop.parse("foo");
assertNotNull(hop);
assertEquals(1, hop.getNumDirectives());
@@ -34,45 +32,45 @@ public class RouteParserTestCase {
assertNotNull(hop = Hop.parse("[Extern:tcp/localhost:3619;foo/bar]"));
assertEquals(1, hop.getNumDirectives());
- assertPolicyDirective(hop.getDirective(0), "Extern","tcp/localhost:3619;foo/bar");
+ assertPolicyDirective(hop.getDirective(0), "Extern", "tcp/localhost:3619;foo/bar");
assertNotNull(hop = Hop.parse("[AND:foo bar]"));
assertEquals(1, hop.getNumDirectives());
- assertPolicyDirective(hop.getDirective(0), "AND","foo bar");
+ assertPolicyDirective(hop.getDirective(0), "AND", "foo bar");
assertNotNull(hop = Hop.parse("[DocumentRouteSelector:raw:route[2]\n" +
- "route[0].name \"foo\"\n" +
- "route[0].selector \"testdoc\"\n" +
- "route[0].feed \"myfeed\"\n" +
- "route[1].name \"bar\"\n" +
- "route[1].selector \"other\"\n" +
- "route[1].feed \"myfeed\"\n" +
- "]"));
+ "route[0].name \"foo\"\n" +
+ "route[0].selector \"testdoc\"\n" +
+ "route[0].feed \"myfeed\"\n" +
+ "route[1].name \"bar\"\n" +
+ "route[1].selector \"other\"\n" +
+ "route[1].feed \"myfeed\"\n" +
+ "]"));
assertEquals(1, hop.getNumDirectives());
assertPolicyDirective(hop.getDirective(0), "DocumentRouteSelector",
- "raw:route[2]\n" +
- "route[0].name \"foo\"\n" +
- "route[0].selector \"testdoc\"\n" +
- "route[0].feed \"myfeed\"\n" +
- "route[1].name \"bar\"\n" +
- "route[1].selector \"other\"\n" +
- "route[1].feed \"myfeed\"");
+ "raw:route[2]\n" +
+ "route[0].name \"foo\"\n" +
+ "route[0].selector \"testdoc\"\n" +
+ "route[0].feed \"myfeed\"\n" +
+ "route[1].name \"bar\"\n" +
+ "route[1].selector \"other\"\n" +
+ "route[1].feed \"myfeed\"");
assertNotNull(hop = Hop.parse("[DocumentRouteSelector:raw:route[1]\n" +
- "route[0].name \"docproc/cluster.foo\"\n" +
- "route[0].selector \"testdoc\"\n" +
- "route[0].feed \"myfeed\"" +
- "]"));
+ "route[0].name \"docproc/cluster.foo\"\n" +
+ "route[0].selector \"testdoc\"\n" +
+ "route[0].feed \"myfeed\"" +
+ "]"));
assertEquals(1, hop.getNumDirectives());
assertPolicyDirective(hop.getDirective(0), "DocumentRouteSelector",
- "raw:route[1]\n" +
- "route[0].name \"docproc/cluster.foo\"\n" +
- "route[0].selector \"testdoc\"\n" +
- "route[0].feed \"myfeed\"");
+ "raw:route[1]\n" +
+ "route[0].name \"docproc/cluster.foo\"\n" +
+ "route[0].selector \"testdoc\"\n" +
+ "route[0].feed \"myfeed\"");
}
@Test
- public void testHopParserErrors() {
+ void testHopParserErrors() {
assertError(Hop.parse(""), "Failed to parse empty string.");
assertError(Hop.parse("[foo"), "Unterminated '[' in '[foo'");
assertError(Hop.parse("foo/[bar]]"), "Unexpected token ']' in 'foo/[bar]]'");
@@ -80,7 +78,7 @@ public class RouteParserTestCase {
}
@Test
- public void testShortRoute() {
+ void testShortRoute() {
Route shortRoute = Route.parse("c");
assertNotNull(shortRoute);
assertEquals(1, shortRoute.getNumHops());
@@ -91,7 +89,7 @@ public class RouteParserTestCase {
}
@Test
- public void testShortHops() {
+ void testShortHops() {
Route shortRoute = Route.parse("a b c");
assertNotNull(shortRoute);
assertEquals(3, shortRoute.getNumHops());
@@ -102,7 +100,7 @@ public class RouteParserTestCase {
}
@Test
- public void testRouteParser() {
+ void testRouteParser() {
Route route = Route.parse("foo bar/baz");
assertNotNull(route);
assertEquals(2, route.getNumHops());
@@ -126,7 +124,7 @@ public class RouteParserTestCase {
}
@Test
- public void testRouteParserErrors() {
+ void testRouteParserErrors() {
assertError(Route.parse(""), "Failed to parse empty string.");
assertError(Route.parse("foo [bar"), "Unterminated '[' in '[bar'");
assertError(Route.parse("foo bar/[baz]]"), "Unexpected token ']' in 'bar/[baz]]'");
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/routing/RoutingContextTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/routing/RoutingContextTestCase.java
index 2efbc0724d7..42a6b244508 100755
--- a/messagebus/src/test/java/com/yahoo/messagebus/routing/RoutingContextTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/routing/RoutingContextTestCase.java
@@ -11,17 +11,17 @@ import com.yahoo.messagebus.network.rpc.test.TestServer;
import com.yahoo.messagebus.test.Receptor;
import com.yahoo.messagebus.test.SimpleMessage;
import com.yahoo.messagebus.test.SimpleProtocol;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
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.Assert.assertTrue;
+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.assertTrue;
/**
* @author Simon Thoresen Hult
@@ -35,7 +35,7 @@ public class RoutingContextTestCase {
SourceSession srcSession;
DestinationSession dstSession;
- @Before
+ @BeforeEach
public void setUp() throws ListenFailedException {
slobrok = new Slobrok();
dstServer = new TestServer(new MessageBusParams().addProtocol(new SimpleProtocol()),
@@ -48,7 +48,7 @@ public class RoutingContextTestCase {
assertTrue(srcServer.waitSlobrok("dst/session", 1));
}
- @After
+ @AfterEach
public void tearDown() {
slobrok.stop();
dstSession.destroy();
@@ -58,7 +58,7 @@ public class RoutingContextTestCase {
}
@Test
- public void testSingleDirective() {
+ void testSingleDirective() {
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", new CustomPolicyFactory(
false,
@@ -68,10 +68,10 @@ public class RoutingContextTestCase {
srcServer.setupRouting(new RoutingTableSpec(SimpleProtocol.NAME)
.addRoute(new RouteSpec("myroute").addHop("myhop"))
.addHop(new HopSpec("myhop", "[Custom]")
- .addRecipient("foo").addRecipient("bar").addRecipient("baz/cox")));
+ .addRecipient("foo").addRecipient("bar").addRecipient("baz/cox")));
for (int i = 0; i < 2; ++i) {
assertTrue(srcSession.send(createMessage("msg"), "myroute").isAccepted());
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(TIMEOUT_SECS);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(TIMEOUT_SECS);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertFalse(reply.hasErrors());
@@ -79,7 +79,7 @@ public class RoutingContextTestCase {
}
@Test
- public void testMoreDirectives() {
+ void testMoreDirectives() {
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", new CustomPolicyFactory(
false,
@@ -89,12 +89,12 @@ public class RoutingContextTestCase {
srcServer.setupRouting(new RoutingTableSpec(SimpleProtocol.NAME)
.addRoute(new RouteSpec("myroute").addHop("myhop"))
.addHop(new HopSpec("myhop", "foo/[Custom]/baz")
- .addRecipient("foo").addRecipient("foo/bar")
- .addRecipient("foo/bar0/baz").addRecipient("foo/bar1/baz")
- .addRecipient("foo/bar/baz/cox")));
+ .addRecipient("foo").addRecipient("foo/bar")
+ .addRecipient("foo/bar0/baz").addRecipient("foo/bar1/baz")
+ .addRecipient("foo/bar/baz/cox")));
for (int i = 0; i < 2; ++i) {
assertTrue(srcSession.send(createMessage("msg"), "myroute").isAccepted());
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(TIMEOUT_SECS);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(TIMEOUT_SECS);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertFalse(reply.hasErrors());
@@ -102,7 +102,7 @@ public class RoutingContextTestCase {
}
@Test
- public void testRecipientsRemain() {
+ void testRecipientsRemain() {
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("First", new CustomPolicyFactory(true, Arrays.asList("foo/bar"), Arrays.asList("foo/[Second]")));
protocol.addPolicyFactory("Second", new CustomPolicyFactory(false, Arrays.asList("foo/bar"), Arrays.asList("foo/bar")));
@@ -110,10 +110,10 @@ public class RoutingContextTestCase {
srcServer.setupRouting(new RoutingTableSpec(SimpleProtocol.NAME)
.addRoute(new RouteSpec("myroute").addHop("myhop"))
.addHop(new HopSpec("myhop", "[First]/[Second]")
- .addRecipient("foo/bar")));
+ .addRecipient("foo/bar")));
for (int i = 0; i < 2; ++i) {
assertTrue(srcSession.send(createMessage("msg"), "myroute").isAccepted());
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(TIMEOUT_SECS);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(TIMEOUT_SECS);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertFalse(reply.hasErrors());
@@ -121,15 +121,15 @@ public class RoutingContextTestCase {
}
@Test
- public void testToString() {
+ void testToString() {
assertEquals("node : null, directive: 1, errors: [], selectOnRetry: true context: null", new RoutingContext(null, 1).toString());
}
@Test
- public void testConstRoute() {
+ void testConstRoute() {
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("DocumentRouteSelector",
- new CustomPolicyFactory(true, Arrays.asList("dst"), Arrays.asList("dst")));
+ new CustomPolicyFactory(true, Arrays.asList("dst"), Arrays.asList("dst")));
srcServer.mb.putProtocol(protocol);
srcServer.setupRouting(new RoutingTableSpec(SimpleProtocol.NAME)
.addRoute(new RouteSpec("default").addHop("indexing"))
@@ -137,10 +137,10 @@ public class RoutingContextTestCase {
.addHop(new HopSpec("dst", "dst/session")));
for (int i = 0; i < 2; ++i) {
assertTrue(srcSession.send(createMessage("msg"), Route.parse("route:default")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(TIMEOUT_SECS);
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(TIMEOUT_SECS);
assertNotNull(msg);
dstSession.acknowledge(msg);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(TIMEOUT_SECS);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(TIMEOUT_SECS);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertFalse(reply.hasErrors());
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/routing/RoutingSpecTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/routing/RoutingSpecTestCase.java
index 0f492e65421..28dcadf1896 100755
--- a/messagebus/src/test/java/com/yahoo/messagebus/routing/RoutingSpecTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/routing/RoutingSpecTestCase.java
@@ -3,16 +3,14 @@ package com.yahoo.messagebus.routing;
import com.yahoo.messagebus.ConfigAgent;
import com.yahoo.messagebus.ConfigHandler;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
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 Simon Thoresen Hult
@@ -20,7 +18,7 @@ import static org.junit.Assert.assertTrue;
public class RoutingSpecTestCase {
@Test
- public void testConfig() {
+ void testConfig() {
assertConfig(new RoutingSpec());
assertConfig(new RoutingSpec().addTable(new RoutingTableSpec("mytable1")));
assertConfig(new RoutingSpec().addTable(new RoutingTableSpec("mytable1")
@@ -42,239 +40,239 @@ public class RoutingSpecTestCase {
.addRoute(new RouteSpec("myroute12").addHop("myhop1").addHop("myhop2")))
.addTable(new RoutingTableSpec("mytable2")));
assertEquals("routingtable[2]\n" +
- "routingtable[0].protocol \"mytable1\"\n" +
- "routingtable[1].protocol \"mytable2\"\n" +
- "routingtable[1].hop[3]\n" +
- "routingtable[1].hop[0].name \"myhop1\"\n" +
- "routingtable[1].hop[0].selector \"myselector1\"\n" +
- "routingtable[1].hop[1].name \"myhop2\"\n" +
- "routingtable[1].hop[1].selector \"myselector2\"\n" +
- "routingtable[1].hop[1].ignoreresult true\n" +
- "routingtable[1].hop[2].name \"myhop1\"\n" +
- "routingtable[1].hop[2].selector \"myselector3\"\n" +
- "routingtable[1].hop[2].recipient[2]\n" +
- "routingtable[1].hop[2].recipient[0] \"myrecipient1\"\n" +
- "routingtable[1].hop[2].recipient[1] \"myrecipient2\"\n" +
- "routingtable[1].route[1]\n" +
- "routingtable[1].route[0].name \"myroute1\"\n" +
- "routingtable[1].route[0].hop[1]\n" +
- "routingtable[1].route[0].hop[0] \"myhop1\"\n",
- new RoutingSpec()
- .addTable(new RoutingTableSpec("mytable1"))
- .addTable(new RoutingTableSpec("mytable2")
- .addHop(new HopSpec("myhop1", "myselector1"))
- .addHop(new HopSpec("myhop2", "myselector2").setIgnoreResult(true))
- .addHop(new HopSpec("myhop1", "myselector3")
- .addRecipient("myrecipient1")
- .addRecipient("myrecipient2"))
- .addRoute(new RouteSpec("myroute1").addHop("myhop1"))).toString());
+ "routingtable[0].protocol \"mytable1\"\n" +
+ "routingtable[1].protocol \"mytable2\"\n" +
+ "routingtable[1].hop[3]\n" +
+ "routingtable[1].hop[0].name \"myhop1\"\n" +
+ "routingtable[1].hop[0].selector \"myselector1\"\n" +
+ "routingtable[1].hop[1].name \"myhop2\"\n" +
+ "routingtable[1].hop[1].selector \"myselector2\"\n" +
+ "routingtable[1].hop[1].ignoreresult true\n" +
+ "routingtable[1].hop[2].name \"myhop1\"\n" +
+ "routingtable[1].hop[2].selector \"myselector3\"\n" +
+ "routingtable[1].hop[2].recipient[2]\n" +
+ "routingtable[1].hop[2].recipient[0] \"myrecipient1\"\n" +
+ "routingtable[1].hop[2].recipient[1] \"myrecipient2\"\n" +
+ "routingtable[1].route[1]\n" +
+ "routingtable[1].route[0].name \"myroute1\"\n" +
+ "routingtable[1].route[0].hop[1]\n" +
+ "routingtable[1].route[0].hop[0] \"myhop1\"\n",
+ new RoutingSpec()
+ .addTable(new RoutingTableSpec("mytable1"))
+ .addTable(new RoutingTableSpec("mytable2")
+ .addHop(new HopSpec("myhop1", "myselector1"))
+ .addHop(new HopSpec("myhop2", "myselector2").setIgnoreResult(true))
+ .addHop(new HopSpec("myhop1", "myselector3")
+ .addRecipient("myrecipient1")
+ .addRecipient("myrecipient2"))
+ .addRoute(new RouteSpec("myroute1").addHop("myhop1"))).toString());
}
@Test
- public void testApplicationSpec() {
+ void testApplicationSpec() {
assertApplicationSpec(Arrays.asList("foo"),
- Arrays.asList("foo",
- "*"));
+ Arrays.asList("foo",
+ "*"));
assertApplicationSpec(Arrays.asList("foo/bar"),
- Arrays.asList("foo/bar",
- "foo/*",
- "*/bar",
- "*/*"));
+ Arrays.asList("foo/bar",
+ "foo/*",
+ "*/bar",
+ "*/*"));
assertApplicationSpec(Arrays.asList("foo/0/baz",
- "foo/1/baz",
- "foo/2/baz"),
- Arrays.asList("foo/0/baz",
- "foo/1/baz",
- "foo/2/baz",
- "foo/0/*",
- "foo/1/*",
- "foo/2/*",
- "foo/*/baz",
- "*/0/baz",
- "*/1/baz",
- "*/2/baz",
- "foo/*/*",
- "*/0/*",
- "*/1/*",
- "*/2/*",
- "*/*/baz",
- "*/*/*"));
+ "foo/1/baz",
+ "foo/2/baz"),
+ Arrays.asList("foo/0/baz",
+ "foo/1/baz",
+ "foo/2/baz",
+ "foo/0/*",
+ "foo/1/*",
+ "foo/2/*",
+ "foo/*/baz",
+ "*/0/baz",
+ "*/1/baz",
+ "*/2/baz",
+ "foo/*/*",
+ "*/0/*",
+ "*/1/*",
+ "*/2/*",
+ "*/*/baz",
+ "*/*/*"));
}
@Test
- public void testVeriyfOk() {
+ void testVeriyfOk() {
assertVerifyOk(new RoutingSpec().addTable(new RoutingTableSpec("mytable")
.addHop(new HopSpec("hop1", "myservice1"))),
- new ApplicationSpec().addService("mytable", "myservice1"));
+ new ApplicationSpec().addService("mytable", "myservice1"));
assertVerifyOk(new RoutingSpec().addTable(new RoutingTableSpec("mytable")
.addRoute(new RouteSpec("route1").addHop("myservice1"))),
- new ApplicationSpec().addService("mytable", "myservice1"));
+ new ApplicationSpec().addService("mytable", "myservice1"));
assertVerifyOk(new RoutingSpec().addTable(new RoutingTableSpec("mytable")
.addHop(new HopSpec("hop1", "myservice1"))
.addRoute(new RouteSpec("route1").addHop("hop1"))),
- new ApplicationSpec().addService("mytable", "myservice1"));
+ new ApplicationSpec().addService("mytable", "myservice1"));
assertVerifyOk(new RoutingSpec().addTable(new RoutingTableSpec("mytable")
.addHop(new HopSpec("hop1", "route:route2"))
.addHop(new HopSpec("hop2", "myservice1"))
.addRoute(new RouteSpec("route1").addHop("hop1"))
.addRoute(new RouteSpec("route2").addHop("hop2"))),
- new ApplicationSpec().addService("mytable", "myservice1"));
+ new ApplicationSpec().addService("mytable", "myservice1"));
assertVerifyOk(new RoutingSpec().addTable(new RoutingTableSpec("mytable")
.addHop(new HopSpec("myhop1", "foo/[bar]/baz").addRecipient("foo/0/baz").addRecipient("foo/1/baz"))),
- new ApplicationSpec()
- .addService("mytable", "foo/0/baz")
- .addService("mytable", "foo/1/baz"));
+ new ApplicationSpec()
+ .addService("mytable", "foo/0/baz")
+ .addService("mytable", "foo/1/baz"));
}
@Test
- public void testVerifyToggle() {
+ void testVerifyToggle() {
assertVerifyOk(new RoutingSpec(false)
- .addTable(new RoutingTableSpec("mytable"))
- .addTable(new RoutingTableSpec("mytable")),
- new ApplicationSpec());
+ .addTable(new RoutingTableSpec("mytable"))
+ .addTable(new RoutingTableSpec("mytable")),
+ new ApplicationSpec());
assertVerifyOk(new RoutingSpec().addTable(new RoutingTableSpec("mytable", false)
.addHop(new HopSpec("foo", "bar"))
.addHop(new HopSpec("foo", "baz"))),
- new ApplicationSpec());
+ new ApplicationSpec());
assertVerifyOk(new RoutingSpec().addTable(new RoutingTableSpec("mytable")
.addHop(new HopSpec("foo", "", false))),
- new ApplicationSpec());
+ new ApplicationSpec());
assertVerifyOk(new RoutingSpec().addTable(new RoutingTableSpec("mytable")
.addRoute(new RouteSpec("foo", false))),
- new ApplicationSpec());
+ new ApplicationSpec());
}
@Test
- public void testVerifyFail() {
+ void testVerifyFail() {
// Duplicate table.
assertVerifyFail(new RoutingSpec()
- .addTable(new RoutingTableSpec("mytable"))
- .addTable(new RoutingTableSpec("mytable")),
- new ApplicationSpec(),
- Arrays.asList("Routing table 'mytable' is defined 2 times."));
+ .addTable(new RoutingTableSpec("mytable"))
+ .addTable(new RoutingTableSpec("mytable")),
+ new ApplicationSpec(),
+ Arrays.asList("Routing table 'mytable' is defined 2 times."));
// Duplicate hop.
assertVerifyFail(new RoutingSpec().addTable(new RoutingTableSpec("mytable")
.addHop(new HopSpec("foo", "bar"))
.addHop(new HopSpec("foo", "baz"))),
- new ApplicationSpec()
- .addService("mytable", "bar")
- .addService("mytable", "baz"),
- Arrays.asList("Hop 'foo' in routing table 'mytable' is defined 2 times."));
+ new ApplicationSpec()
+ .addService("mytable", "bar")
+ .addService("mytable", "baz"),
+ Arrays.asList("Hop 'foo' in routing table 'mytable' is defined 2 times."));
// Duplicate route.
assertVerifyFail(new RoutingSpec().addTable(new RoutingTableSpec("mytable")
.addRoute(new RouteSpec("foo").addHop("bar"))
.addRoute(new RouteSpec("foo").addHop("baz"))),
- new ApplicationSpec()
- .addService("mytable", "bar")
- .addService("mytable", "baz"),
- Arrays.asList("Route 'foo' in routing table 'mytable' is defined 2 times."));
+ new ApplicationSpec()
+ .addService("mytable", "bar")
+ .addService("mytable", "baz"),
+ Arrays.asList("Route 'foo' in routing table 'mytable' is defined 2 times."));
// Empty hop.
assertVerifyFail(new RoutingSpec().addTable(new RoutingTableSpec("mytable")
.addHop(new HopSpec("foo", ""))),
- new ApplicationSpec(),
- Arrays.asList("For hop 'foo' in routing table 'mytable'; Failed to parse empty string."));
+ new ApplicationSpec(),
+ Arrays.asList("For hop 'foo' in routing table 'mytable'; Failed to parse empty string."));
// Empty route.
assertVerifyFail(new RoutingSpec().addTable(new RoutingTableSpec("mytable")
.addRoute(new RouteSpec("foo"))),
- new ApplicationSpec(),
- Arrays.asList("Route 'foo' in routing table 'mytable' has no hops."));
+ new ApplicationSpec(),
+ Arrays.asList("Route 'foo' in routing table 'mytable' has no hops."));
// Hop error.
assertVerifyFail(new RoutingSpec().addTable(new RoutingTableSpec("mytable")
.addHop(new HopSpec("foo", "bar/baz cox"))),
- new ApplicationSpec(),
- Arrays.asList("For hop 'foo' in routing table 'mytable'; Failed to completely parse 'bar/baz cox'."));
+ new ApplicationSpec(),
+ Arrays.asList("For hop 'foo' in routing table 'mytable'; Failed to completely parse 'bar/baz cox'."));
// Hop error in recipient.
assertVerifyFail(new RoutingSpec().addTable(new RoutingTableSpec("mytable")
.addHop(new HopSpec("foo", "[bar]").addRecipient("bar/baz cox"))),
- new ApplicationSpec(),
- Arrays.asList("For recipient 'bar/baz cox' in hop 'foo' in routing table 'mytable'; Failed to completely parse 'bar/baz cox'."));
+ new ApplicationSpec(),
+ Arrays.asList("For recipient 'bar/baz cox' in hop 'foo' in routing table 'mytable'; Failed to completely parse 'bar/baz cox'."));
// Hop error in route.
assertVerifyFail(new RoutingSpec().addTable(new RoutingTableSpec("mytable")
.addRoute(new RouteSpec("foo").addHop("bar/baz cox"))),
- new ApplicationSpec(),
- Arrays.asList("For hop 1 in route 'foo' in routing table 'mytable'; Failed to completely parse 'bar/baz cox'."));
+ new ApplicationSpec(),
+ Arrays.asList("For hop 1 in route 'foo' in routing table 'mytable'; Failed to completely parse 'bar/baz cox'."));
// Hop not found.
assertVerifyFail(new RoutingSpec().addTable(new RoutingTableSpec("mytable")
.addRoute(new RouteSpec("foo").addHop("bar"))),
- new ApplicationSpec(),
- Arrays.asList("Hop 1 in route 'foo' in routing table 'mytable' references 'bar' which is neither a service, a route nor another hop."));
+ new ApplicationSpec(),
+ Arrays.asList("Hop 1 in route 'foo' in routing table 'mytable' references 'bar' which is neither a service, a route nor another hop."));
// Mismatched recipient.
assertVerifyFail(new RoutingSpec().addTable(new RoutingTableSpec("mytable")
.addHop(new HopSpec("foo", "bar/[baz]/cox").addRecipient("cox/0/bar"))),
- new ApplicationSpec(),
- Arrays.asList("Selector 'bar/[baz]/cox' does not match recipient 'cox/0/bar' in hop 'foo' in routing table 'mytable'."));
+ new ApplicationSpec(),
+ Arrays.asList("Selector 'bar/[baz]/cox' does not match recipient 'cox/0/bar' in hop 'foo' in routing table 'mytable'."));
// Route not found.
assertVerifyFail(new RoutingSpec().addTable(new RoutingTableSpec("mytable")
.addHop(new HopSpec("foo", "route:bar"))),
- new ApplicationSpec(),
- Arrays.asList("Hop 'foo' in routing table 'mytable' references route 'bar' which does not exist."));
+ new ApplicationSpec(),
+ Arrays.asList("Hop 'foo' in routing table 'mytable' references route 'bar' which does not exist."));
// Route not found in route.
assertVerifyFail(new RoutingSpec().addTable(new RoutingTableSpec("mytable")
.addRoute(new RouteSpec("foo").addHop("route:bar"))),
- new ApplicationSpec(),
- Arrays.asList("Hop 1 in route 'foo' in routing table 'mytable' references route 'bar' which does not exist."));
+ new ApplicationSpec(),
+ Arrays.asList("Hop 1 in route 'foo' in routing table 'mytable' references route 'bar' which does not exist."));
// Service not found.
assertVerifyFail(new RoutingSpec().addTable(new RoutingTableSpec("mytable")
.addHop(new HopSpec("foo", "bar/baz"))),
- new ApplicationSpec(),
- Arrays.asList("Hop 'foo' in routing table 'mytable' references 'bar/baz' which is neither a service, a route nor another hop."));
+ new ApplicationSpec(),
+ Arrays.asList("Hop 'foo' in routing table 'mytable' references 'bar/baz' which is neither a service, a route nor another hop."));
// Unexpected recipient.
assertVerifyFail(new RoutingSpec().addTable(new RoutingTableSpec("mytable")
.addHop(new HopSpec("foo", "bar").addRecipient("baz"))),
- new ApplicationSpec()
- .addService("mytable", "bar")
- .addService("mytable", "baz"),
- Arrays.asList("Hop 'foo' in routing table 'mytable' has recipients but no policy directive."));
+ new ApplicationSpec()
+ .addService("mytable", "bar")
+ .addService("mytable", "baz"),
+ Arrays.asList("Hop 'foo' in routing table 'mytable' has recipients but no policy directive."));
// Multiple errors.
assertVerifyFail(new RoutingSpec()
- .addTable(new RoutingTableSpec("mytable"))
- .addTable(new RoutingTableSpec("mytable")
- .addHop(new HopSpec("hop1", "bar"))
- .addHop(new HopSpec("hop1", "baz"))
- .addHop(new HopSpec("hop2", ""))
- .addHop(new HopSpec("hop3", "bar/baz cox"))
- .addHop(new HopSpec("hop4", "[bar]").addRecipient("bar/baz cox"))
- .addHop(new HopSpec("hop5", "bar/[baz]/cox").addRecipient("cox/0/bar"))
- .addHop(new HopSpec("hop6", "route:route69"))
- .addHop(new HopSpec("hop7", "bar/baz"))
- .addHop(new HopSpec("hop8", "bar").addRecipient("baz"))
- .addRoute(new RouteSpec("route1").addHop("bar"))
- .addRoute(new RouteSpec("route1").addHop("baz"))
- .addRoute(new RouteSpec("route2").addHop(""))
- .addRoute(new RouteSpec("route3").addHop("bar/baz cox"))
- .addRoute(new RouteSpec("route4").addHop("hop69"))
- .addRoute(new RouteSpec("route5").addHop("route:route69"))),
- new ApplicationSpec()
- .addService("mytable", "bar")
- .addService("mytable", "baz"),
- Arrays.asList("Routing table 'mytable' is defined 2 times.",
- "For hop 'hop2' in routing table 'mytable'; Failed to parse empty string.",
- "For hop 'hop3' in routing table 'mytable'; Failed to completely parse 'bar/baz cox'.",
- "For hop 1 in route 'route2' in routing table 'mytable'; Failed to parse empty string.",
- "For hop 1 in route 'route3' in routing table 'mytable'; Failed to completely parse 'bar/baz cox'.",
- "For recipient 'bar/baz cox' in hop 'hop4' in routing table 'mytable'; Failed to completely parse 'bar/baz cox'.",
- "Hop 'hop1' in routing table 'mytable' is defined 2 times.",
- "Hop 'hop6' in routing table 'mytable' references route 'route69' which does not exist.",
- "Hop 'hop7' in routing table 'mytable' references 'bar/baz' which is neither a service, a route nor another hop.",
- "Hop 'hop8' in routing table 'mytable' has recipients but no policy directive.",
- "Hop 1 in route 'route4' in routing table 'mytable' references 'hop69' which is neither a service, a route nor another hop.",
- "Hop 1 in route 'route5' in routing table 'mytable' references route 'route69' which does not exist.",
- "Route 'route1' in routing table 'mytable' is defined 2 times.",
- "Selector 'bar/[baz]/cox' does not match recipient 'cox/0/bar' in hop 'hop5' in routing table 'mytable'."));
+ .addTable(new RoutingTableSpec("mytable"))
+ .addTable(new RoutingTableSpec("mytable")
+ .addHop(new HopSpec("hop1", "bar"))
+ .addHop(new HopSpec("hop1", "baz"))
+ .addHop(new HopSpec("hop2", ""))
+ .addHop(new HopSpec("hop3", "bar/baz cox"))
+ .addHop(new HopSpec("hop4", "[bar]").addRecipient("bar/baz cox"))
+ .addHop(new HopSpec("hop5", "bar/[baz]/cox").addRecipient("cox/0/bar"))
+ .addHop(new HopSpec("hop6", "route:route69"))
+ .addHop(new HopSpec("hop7", "bar/baz"))
+ .addHop(new HopSpec("hop8", "bar").addRecipient("baz"))
+ .addRoute(new RouteSpec("route1").addHop("bar"))
+ .addRoute(new RouteSpec("route1").addHop("baz"))
+ .addRoute(new RouteSpec("route2").addHop(""))
+ .addRoute(new RouteSpec("route3").addHop("bar/baz cox"))
+ .addRoute(new RouteSpec("route4").addHop("hop69"))
+ .addRoute(new RouteSpec("route5").addHop("route:route69"))),
+ new ApplicationSpec()
+ .addService("mytable", "bar")
+ .addService("mytable", "baz"),
+ Arrays.asList("Routing table 'mytable' is defined 2 times.",
+ "For hop 'hop2' in routing table 'mytable'; Failed to parse empty string.",
+ "For hop 'hop3' in routing table 'mytable'; Failed to completely parse 'bar/baz cox'.",
+ "For hop 1 in route 'route2' in routing table 'mytable'; Failed to parse empty string.",
+ "For hop 1 in route 'route3' in routing table 'mytable'; Failed to completely parse 'bar/baz cox'.",
+ "For recipient 'bar/baz cox' in hop 'hop4' in routing table 'mytable'; Failed to completely parse 'bar/baz cox'.",
+ "Hop 'hop1' in routing table 'mytable' is defined 2 times.",
+ "Hop 'hop6' in routing table 'mytable' references route 'route69' which does not exist.",
+ "Hop 'hop7' in routing table 'mytable' references 'bar/baz' which is neither a service, a route nor another hop.",
+ "Hop 'hop8' in routing table 'mytable' has recipients but no policy directive.",
+ "Hop 1 in route 'route4' in routing table 'mytable' references 'hop69' which is neither a service, a route nor another hop.",
+ "Hop 1 in route 'route5' in routing table 'mytable' references route 'route69' which does not exist.",
+ "Route 'route1' in routing table 'mytable' is defined 2 times.",
+ "Selector 'bar/[baz]/cox' does not match recipient 'cox/0/bar' in hop 'hop5' in routing table 'mytable'."));
}
private static void assertVerifyOk(RoutingSpec routing, ApplicationSpec app) {
@@ -297,7 +295,7 @@ public class RoutingSpecTestCase {
ConfigStore store = new ConfigStore();
ConfigAgent subscriber = new ConfigAgent("raw:" + routing.toString(), store);
subscriber.subscribe();
- assertTrue(store.routing.equals(routing));
+ assertEquals(store.routing, routing);
}
private static void assertApplicationSpec(List<String> services, List<String> patterns) {
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/routing/RoutingTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/routing/RoutingTestCase.java
index 2640fbc8db3..db5dce04af0 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/routing/RoutingTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/routing/RoutingTestCase.java
@@ -23,11 +23,11 @@ import com.yahoo.messagebus.routing.test.CustomPolicyFactory;
import com.yahoo.messagebus.test.Receptor;
import com.yahoo.messagebus.test.SimpleMessage;
import com.yahoo.messagebus.test.SimpleProtocol;
-import org.junit.After;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.net.UnknownHostException;
import java.util.ArrayList;
@@ -36,11 +36,7 @@ import java.util.List;
import java.util.logging.Logger;
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.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author havardpe
@@ -60,7 +56,7 @@ public class RoutingTestCase {
String sessName = "session";
String dstSessName = "dst/session";
- @BeforeClass
+ @BeforeAll
public static void commonSetup() throws ListenFailedException {
slobrok = new Slobrok();
dstServer = new TestServer("dst", null, slobrok, new SimpleProtocol());
@@ -70,7 +66,7 @@ public class RoutingTestCase {
slobrok);
}
- @AfterClass
+ @AfterAll
public static void commonTeardown() {
dstServer.destroy();
srcServer.destroy();
@@ -80,7 +76,7 @@ public class RoutingTestCase {
slobrok = null;
}
- @Before
+ @BeforeEach
public void setUp() throws ListenFailedException, UnknownHostException {
// reset some params:
retryPolicy.setEnabled(true);
@@ -99,7 +95,7 @@ public class RoutingTestCase {
assertTrue(srcServer.waitSlobrok(dstSessName, 1));
}
- @After
+ @AfterEach
public void tearDown() {
dstSession.destroy();
srcSession.destroy();
@@ -108,10 +104,10 @@ public class RoutingTestCase {
}
@Test
- public void requireThatNullRouteIsCaught() {
+ void requireThatNullRouteIsCaught() {
log.log(Level.INFO, "Starting: requireThatNullRouteIsCaught");
assertTrue(srcSession.send(createMessage("msg")).isAccepted());
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertEquals(1, reply.getNumErrors());
@@ -120,10 +116,10 @@ public class RoutingTestCase {
}
@Test
- public void requireThatEmptyRouteIsCaught() {
+ void requireThatEmptyRouteIsCaught() {
log.log(Level.INFO, "Starting: requireThatEmptyRouteIsCaught");
assertTrue(srcSession.send(createMessage("msg"), new Route()).isAccepted());
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertEquals(1, reply.getNumErrors());
@@ -132,15 +128,15 @@ public class RoutingTestCase {
}
@Test
- public void requireThatHopNameIsExpanded() {
+ void requireThatHopNameIsExpanded() {
log.log(Level.INFO, "Starting: requireThatHopNameIsExpanded");
srcServer.setupRouting(new RoutingTableSpec(SimpleProtocol.NAME)
- .addHop(new HopSpec("dst", dstSessName)));
+ .addHop(new HopSpec("dst", dstSessName)));
assertTrue(srcSession.send(createMessage("msg"), Route.parse("dst")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
dstSession.acknowledge(msg);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertFalse(reply.hasErrors());
@@ -148,16 +144,16 @@ public class RoutingTestCase {
}
@Test
- public void requireThatRouteDirectiveWorks() {
+ void requireThatRouteDirectiveWorks() {
log.log(Level.INFO, "Starting: requireThatRouteDirectiveWorks");
srcServer.setupRouting(new RoutingTableSpec(SimpleProtocol.NAME)
- .addRoute(new RouteSpec("dst").addHop(dstSessName))
- .addHop(new HopSpec("dir", "route:dst")));
+ .addRoute(new RouteSpec("dst").addHop(dstSessName))
+ .addHop(new HopSpec("dir", "route:dst")));
assertTrue(srcSession.send(createMessage("msg"), Route.parse("dir")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
dstSession.acknowledge(msg);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertFalse(reply.hasErrors());
@@ -165,15 +161,15 @@ public class RoutingTestCase {
}
@Test
- public void requireThatRouteNameIsExpanded() {
+ void requireThatRouteNameIsExpanded() {
log.log(Level.INFO, "Starting: requireThatRouteNameIsExpanded");
srcServer.setupRouting(new RoutingTableSpec(SimpleProtocol.NAME)
- .addRoute(new RouteSpec("dst").addHop(dstSessName)));
+ .addRoute(new RouteSpec("dst").addHop(dstSessName)));
assertTrue(srcSession.send(createMessage("msg"), Route.parse("dst")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
dstSession.acknowledge(msg);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertFalse(reply.hasErrors());
@@ -181,13 +177,13 @@ public class RoutingTestCase {
}
@Test
- public void requireThatHopResolutionOverflowIsCaught() {
+ void requireThatHopResolutionOverflowIsCaught() {
log.log(Level.INFO, "Starting: requireThatHopResolutionOverflowIsCaught");
srcServer.setupRouting(new RoutingTableSpec(SimpleProtocol.NAME)
- .addHop(new HopSpec("foo", "bar"))
- .addHop(new HopSpec("bar", "foo")));
+ .addHop(new HopSpec("foo", "bar"))
+ .addHop(new HopSpec("bar", "foo")));
assertTrue(srcSession.send(createMessage("msg"), Route.parse("foo")).isAccepted());
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertEquals(1, reply.getNumErrors());
@@ -196,12 +192,12 @@ public class RoutingTestCase {
}
@Test
- public void requireThatRouteResolutionOverflowIsCaught() {
+ void requireThatRouteResolutionOverflowIsCaught() {
log.log(Level.INFO, "Starting: requireThatRouteResolutionOverflowIsCaught");
srcServer.setupRouting(new RoutingTableSpec(SimpleProtocol.NAME)
- .addRoute(new RouteSpec("foo").addHop("route:foo")));
+ .addRoute(new RouteSpec("foo").addHop("route:foo")));
assertTrue(srcSession.send(createMessage("msg"), "foo").isAccepted());
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertEquals(1, reply.getNumErrors());
@@ -210,18 +206,18 @@ public class RoutingTestCase {
}
@Test
- public void requireThatRouteExpansionOnlyReplacesFirstHop() {
+ void requireThatRouteExpansionOnlyReplacesFirstHop() {
log.log(Level.INFO, "Starting: requireThatRouteExpansionOnlyReplacesFirstHop");
srcServer.setupRouting(new RoutingTableSpec(SimpleProtocol.NAME)
- .addRoute(new RouteSpec("foo").addHop(dstSessName).addHop("bar")));
+ .addRoute(new RouteSpec("foo").addHop(dstSessName).addHop("bar")));
assertTrue(srcSession.send(createMessage("msg"), Route.parse("route:foo baz")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
assertEquals(2, msg.getRoute().getNumHops());
assertEquals("bar", msg.getRoute().getHop(0).toString());
assertEquals("baz", msg.getRoute().getHop(1).toString());
dstSession.acknowledge(msg);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertFalse(reply.hasErrors());
@@ -229,12 +225,12 @@ public class RoutingTestCase {
}
@Test
- public void requireThatErrorDirectiveWorks() {
+ void requireThatErrorDirectiveWorks() {
log.log(Level.INFO, "Starting: requireThatErrorDirectiveWorks");
Route route = Route.parse("foo/bar/baz");
route.getHop(0).setDirective(1, new ErrorDirective("err"));
assertTrue(srcSession.send(createMessage("msg"), route).isAccepted());
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertEquals(1, reply.getNumErrors());
@@ -244,7 +240,7 @@ public class RoutingTestCase {
}
@Test
- public void requireThatIllegalSelectIsCaught() {
+ void requireThatIllegalSelectIsCaught() {
log.log(Level.INFO, "Starting: requireThatIllegalSelectIsCaught");
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", new CustomPolicyFactory());
@@ -252,7 +248,7 @@ public class RoutingTestCase {
Route route = Route.parse("[Custom: ]");
assertNotNull(route);
assertTrue(srcSession.send(createMessage("msg"), route).isAccepted());
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertEquals(1, reply.getNumErrors());
@@ -261,13 +257,13 @@ public class RoutingTestCase {
}
@Test
- public void requireThatEmptySelectIsCaught() {
+ void requireThatEmptySelectIsCaught() {
log.log(Level.INFO, "Starting: requireThatEmptySelectIsCaught");
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", new CustomPolicyFactory());
srcServer.mb.putProtocol(protocol);
assertTrue(srcSession.send(createMessage("msg"), Route.parse("[Custom]")).isAccepted());
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertEquals(1, reply.getNumErrors());
@@ -276,16 +272,16 @@ public class RoutingTestCase {
}
@Test
- public void requireThatPolicySelectWorks() {
+ void requireThatPolicySelectWorks() {
log.log(Level.INFO, "Starting: requireThatPolicySelectWorks");
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", new CustomPolicyFactory());
srcServer.mb.putProtocol(protocol);
- assertTrue(srcSession.send(createMessage("msg"), Route.parse("[Custom:"+dstSessName+"]")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ assertTrue(srcSession.send(createMessage("msg"), Route.parse("[Custom:" + dstSessName + "]")).isAccepted());
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
dstSession.acknowledge(msg);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertFalse(reply.hasErrors());
@@ -293,110 +289,110 @@ public class RoutingTestCase {
}
@Test
- public void requireThatTransientErrorsAreRetried() {
+ void requireThatTransientErrorsAreRetried() {
log.log(Level.INFO, "Starting: requireThatTransientErrorsAreRetried");
assertTrue(srcSession.send(createMessage("msg"), Route.parse(dstSessName)).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
Reply reply = new EmptyReply();
reply.swapState(msg);
reply.addError(new Error(ErrorCode.APP_TRANSIENT_ERROR, "err1"));
dstSession.reply(reply);
- assertNotNull(msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60));
reply = new EmptyReply();
reply.swapState(msg);
reply.addError(new Error(ErrorCode.APP_TRANSIENT_ERROR, "err2"));
dstSession.reply(reply);
- assertNotNull(msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60));
dstSession.acknowledge(msg);
- assertNotNull(reply = ((Receptor)srcSession.getReplyHandler()).getReply(60));
+ assertNotNull(reply = ((Receptor) srcSession.getReplyHandler()).getReply(60));
System.out.println(reply.getTrace());
assertFalse(reply.hasErrors());
assertTrace(Arrays.asList("[APP_TRANSIENT_ERROR @ localhost]: err1",
- "-[APP_TRANSIENT_ERROR @ localhost]: err1",
- "[APP_TRANSIENT_ERROR @ localhost]: err2",
- "-[APP_TRANSIENT_ERROR @ localhost]: err2"),
- reply.getTrace());
+ "-[APP_TRANSIENT_ERROR @ localhost]: err1",
+ "[APP_TRANSIENT_ERROR @ localhost]: err2",
+ "-[APP_TRANSIENT_ERROR @ localhost]: err2"),
+ reply.getTrace());
log.log(Level.INFO, "Finished: requireThatTransientErrorsAreRetried");
}
@Test
- public void requireThatTransientErrorsAreRetriedWithPolicy() {
+ void requireThatTransientErrorsAreRetriedWithPolicy() {
log.log(Level.INFO, "Starting: requireThatTransientErrorsAreRetriedWithPolicy");
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", new CustomPolicyFactory());
srcServer.mb.putProtocol(protocol);
- assertTrue(srcSession.send(createMessage("msg"), Route.parse("[Custom:"+dstSessName+"]")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ assertTrue(srcSession.send(createMessage("msg"), Route.parse("[Custom:" + dstSessName + "]")).isAccepted());
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
Reply reply = new EmptyReply();
reply.swapState(msg);
reply.addError(new Error(ErrorCode.APP_TRANSIENT_ERROR, "err1"));
dstSession.reply(reply);
- assertNotNull(msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60));
reply = new EmptyReply();
reply.swapState(msg);
reply.addError(new Error(ErrorCode.APP_TRANSIENT_ERROR, "err2"));
dstSession.reply(reply);
- assertNotNull(msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60));
dstSession.acknowledge(msg);
- assertNotNull(reply = ((Receptor)srcSession.getReplyHandler()).getReply(60));
+ assertNotNull(reply = ((Receptor) srcSession.getReplyHandler()).getReply(60));
System.out.println(reply.getTrace());
assertFalse(reply.hasErrors());
assertTrace(Arrays.asList("Source session accepted a 3 byte message. 1 message(s) now pending.",
- "Running routing policy 'Custom'.",
- "Selecting ["+dstSessName+"].",
- "Component '"+dstSessName+"' selected by policy 'Custom'.",
- "Resolving '"+dstSessName+"'.",
- "Sending message (version ${VERSION}) from client to '"+dstSessName+"'",
- "Message (type 1) received at 'dst' for session '"+sessName+"'.",
- "[APP_TRANSIENT_ERROR @ localhost]: err1",
- "Sending reply (version ${VERSION}) from 'dst'.",
- "Reply (type 0) received at client.",
- "Routing policy 'Custom' merging replies.",
- "Merged ["+dstSessName+"].",
- "Message scheduled for retry 1 in 0.0 seconds.",
- "Resender resending message.",
- "Running routing policy 'Custom'.",
- "Selecting ["+dstSessName+"].",
- "Component '"+dstSessName+"' selected by policy 'Custom'.",
- "Resolving '"+dstSessName+"'.",
- "Sending message (version ${VERSION}) from client to '"+dstSessName+"'",
- "Message (type 1) received at 'dst' for session '"+sessName+"'.",
- "[APP_TRANSIENT_ERROR @ localhost]: err2",
- "Sending reply (version ${VERSION}) from 'dst'.",
- "Reply (type 0) received at client.",
- "Routing policy 'Custom' merging replies.",
- "Merged ["+dstSessName+"].",
- "Message scheduled for retry 2 in 0.0 seconds.",
- "Resender resending message.",
- "Running routing policy 'Custom'.",
- "Selecting ["+dstSessName+"].",
- "Component '"+dstSessName+"' selected by policy 'Custom'.",
- "Resolving '"+dstSessName+"'.",
- "Sending message (version ${VERSION}) from client to '"+dstSessName+"'",
- "Message (type 1) received at 'dst' for session '"+sessName+"'.",
- "Sending reply (version ${VERSION}) from 'dst'.",
- "Reply (type 0) received at client.",
- "Routing policy 'Custom' merging replies.",
- "Merged ["+dstSessName+"].",
- "Source session received reply. 0 message(s) now pending."),
- reply.getTrace());
+ "Running routing policy 'Custom'.",
+ "Selecting [" + dstSessName + "].",
+ "Component '" + dstSessName + "' selected by policy 'Custom'.",
+ "Resolving '" + dstSessName + "'.",
+ "Sending message (version ${VERSION}) from client to '" + dstSessName + "'",
+ "Message (type 1) received at 'dst' for session '" + sessName + "'.",
+ "[APP_TRANSIENT_ERROR @ localhost]: err1",
+ "Sending reply (version ${VERSION}) from 'dst'.",
+ "Reply (type 0) received at client.",
+ "Routing policy 'Custom' merging replies.",
+ "Merged [" + dstSessName + "].",
+ "Message scheduled for retry 1 in 0.0 seconds.",
+ "Resender resending message.",
+ "Running routing policy 'Custom'.",
+ "Selecting [" + dstSessName + "].",
+ "Component '" + dstSessName + "' selected by policy 'Custom'.",
+ "Resolving '" + dstSessName + "'.",
+ "Sending message (version ${VERSION}) from client to '" + dstSessName + "'",
+ "Message (type 1) received at 'dst' for session '" + sessName + "'.",
+ "[APP_TRANSIENT_ERROR @ localhost]: err2",
+ "Sending reply (version ${VERSION}) from 'dst'.",
+ "Reply (type 0) received at client.",
+ "Routing policy 'Custom' merging replies.",
+ "Merged [" + dstSessName + "].",
+ "Message scheduled for retry 2 in 0.0 seconds.",
+ "Resender resending message.",
+ "Running routing policy 'Custom'.",
+ "Selecting [" + dstSessName + "].",
+ "Component '" + dstSessName + "' selected by policy 'Custom'.",
+ "Resolving '" + dstSessName + "'.",
+ "Sending message (version ${VERSION}) from client to '" + dstSessName + "'",
+ "Message (type 1) received at 'dst' for session '" + sessName + "'.",
+ "Sending reply (version ${VERSION}) from 'dst'.",
+ "Reply (type 0) received at client.",
+ "Routing policy 'Custom' merging replies.",
+ "Merged [" + dstSessName + "].",
+ "Source session received reply. 0 message(s) now pending."),
+ reply.getTrace());
log.log(Level.INFO, "Finished: requireThatTransientErrorsAreRetriedWithPolicy");
}
@Test
- public void requireThatRetryCanBeDisabled() {
+ void requireThatRetryCanBeDisabled() {
log.log(Level.INFO, "Starting: requireThatRetryCanBeDisabled");
retryPolicy.setEnabled(false);
assertTrue(srcSession.send(createMessage("msg"), Route.parse(dstSessName)).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
Reply reply = new EmptyReply();
reply.swapState(msg);
reply.addError(new Error(ErrorCode.APP_TRANSIENT_ERROR, "err"));
dstSession.reply(reply);
- reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertEquals(1, reply.getNumErrors());
@@ -405,120 +401,120 @@ public class RoutingTestCase {
}
@Test
- public void requireThatRetryCallsSelect() {
+ void requireThatRetryCallsSelect() {
log.log(Level.INFO, "Starting: requireThatRetryCallsSelect");
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", new CustomPolicyFactory());
srcServer.mb.putProtocol(protocol);
- assertTrue(srcSession.send(createMessage("msg"), Route.parse("[Custom:"+dstSessName+"]")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ assertTrue(srcSession.send(createMessage("msg"), Route.parse("[Custom:" + dstSessName + "]")).isAccepted());
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
Reply reply = new EmptyReply();
reply.swapState(msg);
reply.addError(new Error(ErrorCode.APP_TRANSIENT_ERROR, "err"));
dstSession.reply(reply);
- assertNotNull(msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60));
dstSession.acknowledge(msg);
- assertNotNull(reply = ((Receptor)srcSession.getReplyHandler()).getReply(60));
+ assertNotNull(reply = ((Receptor) srcSession.getReplyHandler()).getReply(60));
System.out.println(reply.getTrace());
assertFalse(reply.hasErrors());
- assertTrace(Arrays.asList("Selecting ["+dstSessName+"].",
- "[APP_TRANSIENT_ERROR @ localhost]",
- "-[APP_TRANSIENT_ERROR @ localhost]",
- "Merged ["+dstSessName+"].",
- "Selecting ["+dstSessName+"].",
- "Sending reply",
- "Merged ["+dstSessName+"]."),
- reply.getTrace());
+ assertTrace(Arrays.asList("Selecting [" + dstSessName + "].",
+ "[APP_TRANSIENT_ERROR @ localhost]",
+ "-[APP_TRANSIENT_ERROR @ localhost]",
+ "Merged [" + dstSessName + "].",
+ "Selecting [" + dstSessName + "].",
+ "Sending reply",
+ "Merged [" + dstSessName + "]."),
+ reply.getTrace());
log.log(Level.INFO, "Finished: requireThatRetryCallsSelect");
}
@Test
- public void requireThatPolicyCanDisableReselectOnRetry() {
+ void requireThatPolicyCanDisableReselectOnRetry() {
log.log(Level.INFO, "Starting: requireThatPolicyCanDisableReselectOnRetry");
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", new CustomPolicyFactory(false));
srcServer.mb.putProtocol(protocol);
- assertTrue(srcSession.send(createMessage("msg"), Route.parse("[Custom:"+dstSessName+"]")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ assertTrue(srcSession.send(createMessage("msg"), Route.parse("[Custom:" + dstSessName + "]")).isAccepted());
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
Reply reply = new EmptyReply();
reply.swapState(msg);
reply.addError(new Error(ErrorCode.APP_TRANSIENT_ERROR, "err"));
dstSession.reply(reply);
- assertNotNull(msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60));
dstSession.acknowledge(msg);
- assertNotNull(reply = ((Receptor)srcSession.getReplyHandler()).getReply(60));
+ assertNotNull(reply = ((Receptor) srcSession.getReplyHandler()).getReply(60));
System.out.println(reply.getTrace());
assertFalse(reply.hasErrors());
- assertTrace(Arrays.asList("Selecting ["+dstSessName+"].",
- "[APP_TRANSIENT_ERROR @ localhost]",
- "-[APP_TRANSIENT_ERROR @ localhost]",
- "Merged ["+dstSessName+"].",
- "-Selecting ["+dstSessName+"].",
- "Sending reply",
- "Merged ["+dstSessName+"]."),
- reply.getTrace());
+ assertTrace(Arrays.asList("Selecting [" + dstSessName + "].",
+ "[APP_TRANSIENT_ERROR @ localhost]",
+ "-[APP_TRANSIENT_ERROR @ localhost]",
+ "Merged [" + dstSessName + "].",
+ "-Selecting [" + dstSessName + "].",
+ "Sending reply",
+ "Merged [" + dstSessName + "]."),
+ reply.getTrace());
log.log(Level.INFO, "Finished: requireThatPolicyCanDisableReselectOnRetry");
}
@Test
- public void requireThatPolicyCanConsumeErrors() {
+ void requireThatPolicyCanConsumeErrors() {
log.log(Level.INFO, "Starting: requireThatPolicyCanConsumeErrors");
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", new CustomPolicyFactory(true, ErrorCode.NO_ADDRESS_FOR_SERVICE));
srcServer.mb.putProtocol(protocol);
retryPolicy.setEnabled(false);
- assertTrue(srcSession.send(createMessage("msg"), Route.parse("[Custom:"+dstSessName+",dst/unknown]")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ assertTrue(srcSession.send(createMessage("msg"), Route.parse("[Custom:" + dstSessName + ",dst/unknown]")).isAccepted());
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
dstSession.acknowledge(msg);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertEquals(1, reply.getNumErrors());
assertEquals(ErrorCode.NO_ADDRESS_FOR_SERVICE, reply.getError(0).getCode());
- assertTrace(Arrays.asList("Selecting ["+dstSessName+", dst/unknown].",
- "[NO_ADDRESS_FOR_SERVICE @ localhost]",
- "Sending reply",
- "Merged ["+dstSessName+", dst/unknown]."),
- reply.getTrace());
+ assertTrace(Arrays.asList("Selecting [" + dstSessName + ", dst/unknown].",
+ "[NO_ADDRESS_FOR_SERVICE @ localhost]",
+ "Sending reply",
+ "Merged [" + dstSessName + ", dst/unknown]."),
+ reply.getTrace());
log.log(Level.INFO, "Finished: requireThatPolicyCanConsumeErrors");
}
@Test
- public void requireThatPolicyOnlyConsumesDeclaredErrors() {
+ void requireThatPolicyOnlyConsumesDeclaredErrors() {
log.log(Level.INFO, "Starting: requireThatPolicyOnlyConsumesDeclaredErrors");
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", new CustomPolicyFactory());
srcServer.mb.putProtocol(protocol);
retryPolicy.setEnabled(false);
assertTrue(srcSession.send(createMessage("msg"), Route.parse("[Custom:dst/unknown]")).isAccepted());
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertEquals(1, reply.getNumErrors());
assertEquals(ErrorCode.NO_ADDRESS_FOR_SERVICE, reply.getError(0).getCode());
assertTrace(Arrays.asList("Selecting [dst/unknown].",
- "[NO_ADDRESS_FOR_SERVICE @ localhost]",
- "Merged [dst/unknown]."),
- reply.getTrace());
+ "[NO_ADDRESS_FOR_SERVICE @ localhost]",
+ "Merged [dst/unknown]."),
+ reply.getTrace());
log.log(Level.INFO, "Finished: requireThatPolicyOnlyConsumesDeclaredErrors");
}
@Test
- public void requireThatPolicyCanExpandToPolicy() {
+ void requireThatPolicyCanExpandToPolicy() {
log.log(Level.INFO, "Starting: requireThatPolicyCanExpandToPolicy");
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", new CustomPolicyFactory(true, ErrorCode.NO_ADDRESS_FOR_SERVICE));
srcServer.mb.putProtocol(protocol);
retryPolicy.setEnabled(false);
assertTrue(srcSession.send(createMessage("msg"),
- Route.parse("[Custom:[Custom:"+dstSessName+"],[Custom:dst/unknown]]")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ Route.parse("[Custom:[Custom:" + dstSessName + "],[Custom:dst/unknown]]")).isAccepted());
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
dstSession.acknowledge(msg);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertEquals(1, reply.getNumErrors());
@@ -527,7 +523,7 @@ public class RoutingTestCase {
}
@Test
- public void requireThatReplyCanBeRemovedFromChildNodes() {
+ void requireThatReplyCanBeRemovedFromChildNodes() {
log.log(Level.INFO, "Starting: requireThatReplyCanBeRemovedFromChildNodes");
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", new SimpleProtocol.PolicyFactory() {
@@ -535,32 +531,32 @@ public class RoutingTestCase {
@Override
public RoutingPolicy create(String param) {
return new RemoveReplyPolicy(true,
- Arrays.asList(ErrorCode.NO_ADDRESS_FOR_SERVICE),
- CustomPolicyFactory.parseRoutes(param),
- 0);
+ Arrays.asList(ErrorCode.NO_ADDRESS_FOR_SERVICE),
+ CustomPolicyFactory.parseRoutes(param),
+ 0);
}
});
srcServer.mb.putProtocol(protocol);
retryPolicy.setEnabled(false);
assertTrue(srcSession.send(createMessage("msg"),
- Route.parse("[Custom:[Custom:"+dstSessName+"],[Custom:dst/unknown]]")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ Route.parse("[Custom:[Custom:" + dstSessName + "],[Custom:dst/unknown]]")).isAccepted());
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
dstSession.acknowledge(msg);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertFalse(reply.hasErrors());
assertTrace(Arrays.asList("[NO_ADDRESS_FOR_SERVICE @ localhost]",
- "-[NO_ADDRESS_FOR_SERVICE @ localhost]",
- "Sending message",
- "-Sending message"),
- reply.getTrace());
+ "-[NO_ADDRESS_FOR_SERVICE @ localhost]",
+ "Sending message",
+ "-Sending message"),
+ reply.getTrace());
log.log(Level.INFO, "Finished: requireThatReplyCanBeRemovedFromChildNodes");
}
@Test
- public void requireThatSetReplyWorks() {
+ void requireThatSetReplyWorks() {
log.log(Level.INFO, "Starting: requireThatSetReplyWorks");
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Select", new CustomPolicyFactory(true, ErrorCode.APP_FATAL_ERROR));
@@ -574,11 +570,11 @@ public class RoutingTestCase {
srcServer.mb.putProtocol(protocol);
retryPolicy.setEnabled(false);
assertTrue(
- srcSession.send(createMessage("msg"), Route.parse("[Select:[SetReply:foo],"+dstSessName+"]")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ srcSession.send(createMessage("msg"), Route.parse("[Select:[SetReply:foo]," + dstSessName + "]")).isAccepted());
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
dstSession.acknowledge(msg);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertEquals(1, reply.getNumErrors());
@@ -588,7 +584,7 @@ public class RoutingTestCase {
}
@Test
- public void requireThatReplyCanBeReusedOnRetry() {
+ void requireThatReplyCanBeReusedOnRetry() {
log.log(Level.INFO, "Starting: requireThatReplyCanBeReusedOnRetry");
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("ReuseReply", new SimpleProtocol.PolicyFactory() {
@@ -596,8 +592,8 @@ public class RoutingTestCase {
@Override
public RoutingPolicy create(String param) {
return new ReuseReplyPolicy(false,
- Arrays.asList(ErrorCode.APP_FATAL_ERROR),
- CustomPolicyFactory.parseRoutes(param));
+ Arrays.asList(ErrorCode.APP_FATAL_ERROR),
+ CustomPolicyFactory.parseRoutes(param));
}
});
protocol.addPolicyFactory("SetReply", new SimpleProtocol.PolicyFactory() {
@@ -605,29 +601,29 @@ public class RoutingTestCase {
@Override
public RoutingPolicy create(String param) {
return new SetReplyPolicy(false,
- Arrays.asList(ErrorCode.APP_FATAL_ERROR),
- param);
+ Arrays.asList(ErrorCode.APP_FATAL_ERROR),
+ param);
}
});
srcServer.mb.putProtocol(protocol);
assertTrue(srcSession.send(createMessage("msg"),
- Route.parse("[ReuseReply:[SetReply:foo],"+dstSessName+"]")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ Route.parse("[ReuseReply:[SetReply:foo]," + dstSessName + "]")).isAccepted());
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
Reply reply = new EmptyReply();
reply.swapState(msg);
reply.addError(new Error(ErrorCode.APP_TRANSIENT_ERROR, "dst"));
dstSession.reply(reply);
- assertNotNull(msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60));
+ assertNotNull(msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60));
dstSession.acknowledge(msg);
- assertNotNull(reply = ((Receptor)srcSession.getReplyHandler()).getReply(60));
+ assertNotNull(reply = ((Receptor) srcSession.getReplyHandler()).getReply(60));
System.out.println(reply.getTrace());
assertFalse(reply.hasErrors());
log.log(Level.INFO, "Finished: requireThatReplyCanBeReusedOnRetry");
}
@Test
- public void requireThatReplyCanBeRemovedAndRetried() {
+ void requireThatReplyCanBeRemovedAndRetried() {
log.log(Level.INFO, "Starting: requireThatReplyCanBeRemovedAndRetried");
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("RemoveReply", new SimpleProtocol.PolicyFactory() {
@@ -635,9 +631,9 @@ public class RoutingTestCase {
@Override
public RoutingPolicy create(String param) {
return new RemoveReplyPolicy(false,
- Arrays.asList(ErrorCode.APP_TRANSIENT_ERROR),
- CustomPolicyFactory.parseRoutes(param),
- 0);
+ Arrays.asList(ErrorCode.APP_TRANSIENT_ERROR),
+ CustomPolicyFactory.parseRoutes(param),
+ 0);
}
});
protocol.addPolicyFactory("SetReply", new SimpleProtocol.PolicyFactory() {
@@ -645,71 +641,71 @@ public class RoutingTestCase {
@Override
public RoutingPolicy create(String param) {
return new SetReplyPolicy(false,
- Arrays.asList(ErrorCode.APP_TRANSIENT_ERROR, ErrorCode.APP_FATAL_ERROR),
- param);
+ Arrays.asList(ErrorCode.APP_TRANSIENT_ERROR, ErrorCode.APP_FATAL_ERROR),
+ param);
}
});
srcServer.mb.putProtocol(protocol);
assertTrue(srcSession
- .send(createMessage("msg"), Route.parse("[RemoveReply:[SetReply:foo],"+dstSessName+"]")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ .send(createMessage("msg"), Route.parse("[RemoveReply:[SetReply:foo]," + dstSessName + "]")).isAccepted());
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
dstSession.acknowledge(msg);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertEquals(1, reply.getNumErrors());
assertEquals(ErrorCode.APP_FATAL_ERROR, reply.getError(0).getCode());
assertEquals("foo", reply.getError(0).getMessage());
assertTrace(Arrays.asList("Resolving '[SetReply:foo]'.",
- "Resolving '"+dstSessName+"'.",
- "Resender resending message.",
- "Resolving '"+dstSessName+"'.",
- "Resolving '[SetReply:foo]'."),
- reply.getTrace());
+ "Resolving '" + dstSessName + "'.",
+ "Resender resending message.",
+ "Resolving '" + dstSessName + "'.",
+ "Resolving '[SetReply:foo]'."),
+ reply.getTrace());
log.log(Level.INFO, "Finished: requireThatReplyCanBeRemovedAndRetried");
}
@Test
- public void requireThatIgnoreResultWorks() {
+ void requireThatIgnoreResultWorks() {
log.log(Level.INFO, "Starting: requireThatIgnoreResultWorks");
- assertTrue(srcSession.send(createMessage("msg"), Route.parse("?"+dstSessName)).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ assertTrue(srcSession.send(createMessage("msg"), Route.parse("?" + dstSessName)).isAccepted());
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
Reply reply = new EmptyReply();
reply.swapState(msg);
reply.addError(new Error(ErrorCode.APP_FATAL_ERROR, "dst"));
dstSession.reply(reply);
- assertNotNull(reply = ((Receptor)srcSession.getReplyHandler()).getReply(60));
+ assertNotNull(reply = ((Receptor) srcSession.getReplyHandler()).getReply(60));
System.out.println(reply.getTrace());
assertFalse(reply.hasErrors());
- assertTrace(Arrays.asList("Not waiting for a reply from '"+dstSessName+"'."),
- reply.getTrace());
+ assertTrace(Arrays.asList("Not waiting for a reply from '" + dstSessName + "'."),
+ reply.getTrace());
log.log(Level.INFO, "Finished: requireThatIgnoreResultWorks");
}
@Test
- public void requireThatIgnoreResultCanBeSetInHopBlueprint() {
+ void requireThatIgnoreResultCanBeSetInHopBlueprint() {
log.log(Level.INFO, "Starting: requireThatIgnoreResultCanBeSetInHopBlueprint");
srcServer.setupRouting(new RoutingTableSpec(SimpleProtocol.NAME)
- .addHop(new HopSpec("foo", dstSessName).setIgnoreResult(true)));
+ .addHop(new HopSpec("foo", dstSessName).setIgnoreResult(true)));
assertTrue(srcSession.send(createMessage("msg"), Route.parse("foo")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
Reply reply = new EmptyReply();
reply.swapState(msg);
reply.addError(new Error(ErrorCode.APP_FATAL_ERROR, "dst"));
dstSession.reply(reply);
- assertNotNull(reply = ((Receptor)srcSession.getReplyHandler()).getReply(60));
+ assertNotNull(reply = ((Receptor) srcSession.getReplyHandler()).getReply(60));
System.out.println(reply.getTrace());
assertFalse(reply.hasErrors());
- assertTrace(Arrays.asList("Not waiting for a reply from '"+dstSessName+"'."),
- reply.getTrace());
+ assertTrace(Arrays.asList("Not waiting for a reply from '" + dstSessName + "'."),
+ reply.getTrace());
log.log(Level.INFO, "Finished: requireThatIgnoreResultCanBeSetInHopBlueprint");
}
@Test
- public void requireThatIgnoreFlagPersistsThroughHopLookup() {
+ void requireThatIgnoreFlagPersistsThroughHopLookup() {
log.log(Level.INFO, "Starting: requireThatIgnoreFlagPersistsThroughHopLookup");
setupRouting(new RoutingTableSpec(SimpleProtocol.NAME).addHop(new HopSpec("foo", "dst/unknown")));
assertSend("?foo");
@@ -718,7 +714,7 @@ public class RoutingTestCase {
}
@Test
- public void requireThatIgnoreFlagPersistsThroughRouteLookup() {
+ void requireThatIgnoreFlagPersistsThroughRouteLookup() {
log.log(Level.INFO, "Starting: requireThatIgnoreFlagPersistsThroughRouteLookup");
setupRouting(new RoutingTableSpec(SimpleProtocol.NAME).addRoute(new RouteSpec("foo").addHop("dst/unknown")));
assertSend("?foo");
@@ -727,7 +723,7 @@ public class RoutingTestCase {
}
@Test
- public void requireThatIgnoreFlagPersistsThroughPolicySelect() {
+ void requireThatIgnoreFlagPersistsThroughPolicySelect() {
log.log(Level.INFO, "Starting: requireThatIgnoreFlagPersistsThroughPolicySelect");
setupPolicy("Custom", MyPolicy.newSelectAndMerge("dst/unknown"));
assertSend("?[Custom]");
@@ -736,10 +732,10 @@ public class RoutingTestCase {
}
@Test
- public void requireThatIgnoreFlagIsSerializedWithMessage() {
+ void requireThatIgnoreFlagIsSerializedWithMessage() {
log.log(Level.INFO, "Starting: requireThatIgnoreFlagIsSerializedWithMessage");
- assertSend(dstSessName+" foo ?bar");
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ assertSend(dstSessName + " foo ?bar");
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
Route route = msg.getRoute();
assertEquals(2, route.getNumHops());
@@ -755,7 +751,7 @@ public class RoutingTestCase {
}
@Test
- public void requireThatIgnoreFlagDoesNotInterfere() {
+ void requireThatIgnoreFlagDoesNotInterfere() {
log.log(Level.INFO, "Starting: requireThatIgnoreFlagDoesNotInterfere");
setupPolicy("Custom", MyPolicy.newSelectAndMerge(dstSessName));
assertSend("?[Custom]");
@@ -764,7 +760,7 @@ public class RoutingTestCase {
}
@Test
- public void requireThatEmptySelectionCanBeIgnored() {
+ void requireThatEmptySelectionCanBeIgnored() {
log.log(Level.INFO, "Starting: requireThatEmptySelectionCanBeIgnored");
setupPolicy("Custom", MyPolicy.newEmptySelection());
assertSend("?[Custom]");
@@ -773,7 +769,7 @@ public class RoutingTestCase {
}
@Test
- public void requireThatSelectErrorCanBeIgnored() {
+ void requireThatSelectErrorCanBeIgnored() {
log.log(Level.INFO, "Starting: requireThatSelectErrorCanBeIgnored");
setupPolicy("Custom", MyPolicy.newSelectError(ErrorCode.APP_FATAL_ERROR, "foo"));
assertSend("?[Custom]");
@@ -782,7 +778,7 @@ public class RoutingTestCase {
}
@Test
- public void requireThatSelectExceptionCanBeIgnored() {
+ void requireThatSelectExceptionCanBeIgnored() {
log.log(Level.INFO, "Starting: requireThatSelectExceptionCanBeIgnored");
setupPolicy("Custom", MyPolicy.newSelectException(new RuntimeException()));
assertSend("?[Custom]");
@@ -791,7 +787,7 @@ public class RoutingTestCase {
}
@Test
- public void requireThatSelectAndThrowCanBeIgnored() {
+ void requireThatSelectAndThrowCanBeIgnored() {
log.log(Level.INFO, "Starting: requireThatSelectAndThrowCanBeIgnored");
setupPolicy("Custom", MyPolicy.newSelectAndThrow(dstSessName, new RuntimeException()));
assertSend("?[Custom]");
@@ -800,7 +796,7 @@ public class RoutingTestCase {
}
@Test
- public void requireThatEmptyMergeCanBeIgnored() {
+ void requireThatEmptyMergeCanBeIgnored() {
log.log(Level.INFO, "Starting: requireThatEmptyMergeCanBeIgnored");
setupPolicy("Custom", MyPolicy.newEmptyMerge(dstSessName));
assertSend("?[Custom]");
@@ -810,7 +806,7 @@ public class RoutingTestCase {
}
@Test
- public void requireThatMergeErrorCanBeIgnored() {
+ void requireThatMergeErrorCanBeIgnored() {
log.log(Level.INFO, "Starting: requireThatMergeErrorCanBeIgnored");
setupPolicy("Custom", MyPolicy.newMergeError(dstSessName, ErrorCode.APP_FATAL_ERROR, "foo"));
assertSend("?[Custom]");
@@ -820,7 +816,7 @@ public class RoutingTestCase {
}
@Test
- public void requireThatMergeExceptionCanBeIgnored() {
+ void requireThatMergeExceptionCanBeIgnored() {
log.log(Level.INFO, "Starting: requireThatMergeExceptionCanBeIgnored");
setupPolicy("Custom", MyPolicy.newMergeException(dstSessName, new RuntimeException()));
assertSend("?[Custom]");
@@ -830,7 +826,7 @@ public class RoutingTestCase {
}
@Test
- public void requireThatMergeAndThrowCanBeIgnored() {
+ void requireThatMergeAndThrowCanBeIgnored() {
log.log(Level.INFO, "Starting: requireThatMergeAndThrowCanBeIgnored");
setupPolicy("Custom", MyPolicy.newMergeAndThrow(dstSessName, new RuntimeException()));
assertSend("?[Custom]");
@@ -840,7 +836,7 @@ public class RoutingTestCase {
}
@Test
- public void requireThatAllocServiceAddressCanBeIgnored() {
+ void requireThatAllocServiceAddressCanBeIgnored() {
log.log(Level.INFO, "Starting: requireThatAllocServiceAddressCanBeIgnored");
assertSend("?dst/unknown");
assertTrace("Ignoring errors in reply.");
@@ -848,7 +844,7 @@ public class RoutingTestCase {
}
@Test
- public void requireThatDepthLimitCanBeIgnored() {
+ void requireThatDepthLimitCanBeIgnored() {
log.log(Level.INFO, "Starting: requireThatDepthLimitCanBeIgnored");
setupPolicy("Custom", MyPolicy.newSelectAndMerge("[Custom]"));
assertSend("?[Custom]");
@@ -857,21 +853,21 @@ public class RoutingTestCase {
}
@Test
- public void requireThatRouteCanBeEmptyInDestination() {
+ void requireThatRouteCanBeEmptyInDestination() {
log.log(Level.INFO, "Starting: requireThatRouteCanBeEmptyInDestination");
assertTrue(srcSession.send(createMessage("msg"), Route.parse(dstSessName)).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
assertNull(msg.getRoute());
dstSession.acknowledge(msg);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
log.log(Level.INFO, "Finished: requireThatRouteCanBeEmptyInDestination");
}
@Test
- public void requireThatOnlyActiveNodesAreAborted() {
+ void requireThatOnlyActiveNodesAreAborted() {
log.log(Level.INFO, "Starting: requireThatOnlyActiveNodesAreAborted");
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", new CustomPolicyFactory(false));
@@ -880,16 +876,16 @@ public class RoutingTestCase {
@Override
public RoutingPolicy create(String param) {
return new SetReplyPolicy(false,
- Arrays.asList(ErrorCode.APP_TRANSIENT_ERROR,
- ErrorCode.APP_TRANSIENT_ERROR,
- ErrorCode.APP_FATAL_ERROR),
- param);
+ Arrays.asList(ErrorCode.APP_TRANSIENT_ERROR,
+ ErrorCode.APP_TRANSIENT_ERROR,
+ ErrorCode.APP_FATAL_ERROR),
+ param);
}
});
srcServer.mb.putProtocol(protocol);
assertTrue(srcSession.send(createMessage("msg"),
- Route.parse("[Custom:[SetReply:foo],?bar,"+dstSessName+"]")).isAccepted());
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Route.parse("[Custom:[SetReply:foo],?bar," + dstSessName + "]")).isAccepted());
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertEquals(2, reply.getNumErrors());
@@ -899,12 +895,12 @@ public class RoutingTestCase {
}
@Test
- public void requireThatTimeoutWorks() {
+ void requireThatTimeoutWorks() {
log.log(Level.INFO, "Starting: requireThatTimeoutWorks");
retryPolicy.setBaseDelay(0.01);
srcSession.setTimeout(0.5);
assertTrue(srcSession.send(createMessage("msg"), Route.parse("dst/unknown")).isAccepted());
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertEquals(2, reply.getNumErrors());
@@ -914,10 +910,10 @@ public class RoutingTestCase {
}
@Test
- public void requireThatUnknownPolicyIsCaught() {
+ void requireThatUnknownPolicyIsCaught() {
log.log(Level.INFO, "Starting: requireThatUnknownPolicyIsCaught");
assertTrue(srcSession.send(createMessage("msg"), Route.parse("[Unknown]")).isAccepted());
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertEquals(1, reply.getNumErrors());
@@ -950,13 +946,13 @@ public class RoutingTestCase {
}
@Test
- public void requireThatSelectExceptionIsCaught() {
+ void requireThatSelectExceptionIsCaught() {
log.log(Level.INFO, "Starting: requireThatSelectExceptionIsCaught");
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", exceptionOnSelectThrowingMockFactory());
srcServer.mb.putProtocol(protocol);
assertTrue(srcSession.send(createMessage("msg"), Route.parse("[Custom]")).isAccepted());
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertEquals(1, reply.getNumErrors());
@@ -966,12 +962,12 @@ public class RoutingTestCase {
}
@Test
- public void selectExceptionIncludesStackTraceInMessage() {
+ void selectExceptionIncludesStackTraceInMessage() {
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", exceptionOnSelectThrowingMockFactory());
srcServer.mb.putProtocol(protocol);
assertTrue(srcSession.send(createMessage("msg"), Route.parse("[Custom]")).isAccepted());
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertEquals(ErrorCode.POLICY_ERROR, reply.getError(0).getCode());
// Attempting any sort of full matching of the stack trace is brittle, so
// simplify by assuming any message which mentions the source file of the
@@ -980,7 +976,7 @@ public class RoutingTestCase {
}
@Test
- public void requireThatMergeExceptionIsCaught() {
+ void requireThatMergeExceptionIsCaught() {
log.log(Level.INFO, "Starting: requireThatMergeExceptionIsCaught");
SimpleProtocol protocol = new SimpleProtocol();
protocol.addPolicyFactory("Custom", new SimpleProtocol.PolicyFactory() {
@@ -1008,10 +1004,10 @@ public class RoutingTestCase {
});
srcServer.mb.putProtocol(protocol);
assertTrue(srcSession.send(createMessage("msg"), Route.parse("[Custom]")).isAccepted());
- Message msg = ((Receptor)dstSession.getMessageHandler()).getMessage(60);
+ Message msg = ((Receptor) dstSession.getMessageHandler()).getMessage(60);
assertNotNull(msg);
dstSession.acknowledge(msg);
- Reply reply = ((Receptor)srcSession.getReplyHandler()).getReply(60);
+ Reply reply = ((Receptor) srcSession.getReplyHandler()).getReply(60);
assertNotNull(reply);
System.out.println(reply.getTrace());
assertEquals(1, reply.getNumErrors());
@@ -1066,11 +1062,11 @@ public class RoutingTestCase {
String line = expected.get(i).replaceFirst("\\$\\{VERSION\\}", Vtag.currentVersion.toString());
if (line.charAt(0) == '-') {
String str = line.substring(1);
- assertTrue("Line " + i + " '" + str + "' not expected.",
- actual.indexOf(str, pos + 1) < 0);
+ assertTrue(actual.indexOf(str, pos + 1) < 0,
+ "Line " + i + " '" + str + "' not expected.");
} else {
pos = actual.indexOf(line, pos + 1);
- assertTrue("Line " + i + " '" + line + "' missing.", pos >= 0);
+ assertTrue(pos >= 0, "Line " + i + " '" + line + "' missing.");
}
}
}
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/test/QueueAdapterTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/test/QueueAdapterTestCase.java
index 3147587aa96..f23a4325d79 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/test/QueueAdapterTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/test/QueueAdapterTestCase.java
@@ -4,11 +4,11 @@ package com.yahoo.messagebus.test;
import com.yahoo.messagebus.Message;
import com.yahoo.messagebus.Reply;
import com.yahoo.text.Utf8String;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.atomic.AtomicReference;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -19,7 +19,7 @@ public class QueueAdapterTestCase {
private static final int WAIT_FOREVER = 60;
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
QueueAdapter queue = new QueueAdapter();
assertTrue(queue.isEmpty());
assertEquals(0, queue.size());
@@ -39,7 +39,7 @@ public class QueueAdapterTestCase {
}
@Test
- public void requireThatSizeCanBeWaitedFor() {
+ void requireThatSizeCanBeWaitedFor() {
final QueueAdapter queue = new QueueAdapter();
assertTrue(queue.waitSize(0, NO_WAIT));
assertFalse(queue.waitSize(1, NO_WAIT));
@@ -64,7 +64,7 @@ public class QueueAdapterTestCase {
}
@Test
- public void requireThatWaitCanBeInterrupted() throws InterruptedException {
+ void requireThatWaitCanBeInterrupted() throws InterruptedException {
final QueueAdapter queue = new QueueAdapter();
final AtomicReference<Boolean> result = new AtomicReference<>();
Thread thread = new Thread() {
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/test/ReceptorTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/test/ReceptorTestCase.java
index 2e60f68eb43..59a93df17ed 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/test/ReceptorTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/test/ReceptorTestCase.java
@@ -4,12 +4,12 @@ package com.yahoo.messagebus.test;
import com.yahoo.messagebus.Message;
import com.yahoo.messagebus.Reply;
import com.yahoo.text.Utf8String;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -17,7 +17,7 @@ import static org.junit.Assert.*;
public class ReceptorTestCase {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
Receptor receptor = new Receptor();
assertNull(receptor.getMessage(0));
Message msg = new MyMessage();
@@ -30,7 +30,7 @@ public class ReceptorTestCase {
}
@Test
- public void requireThatMessagesAndRepliesAreTrackedIndividually() {
+ void requireThatMessagesAndRepliesAreTrackedIndividually() {
Receptor receptor = new Receptor();
receptor.handleMessage(new MyMessage());
receptor.handleReply(new MyReply());
@@ -44,7 +44,7 @@ public class ReceptorTestCase {
}
@Test
- public void requireThatMessagesCanBeWaitedFor() {
+ void requireThatMessagesCanBeWaitedFor() {
final Receptor receptor = new Receptor();
Thread thread = new Thread() {
@@ -63,7 +63,7 @@ public class ReceptorTestCase {
}
@Test
- public void requireThatMessageWaitCanBeInterrupted() throws InterruptedException {
+ void requireThatMessageWaitCanBeInterrupted() throws InterruptedException {
final Receptor receptor = new Receptor();
final CountDownLatch latch = new CountDownLatch(1);
Thread thread = new Thread() {
@@ -80,7 +80,7 @@ public class ReceptorTestCase {
}
@Test
- public void requireThatRepliesCanBeWaitedFor() {
+ void requireThatRepliesCanBeWaitedFor() {
final Receptor receptor = new Receptor();
Thread thread = new Thread() {
@@ -99,7 +99,7 @@ public class ReceptorTestCase {
}
@Test
- public void requireThatReplyWaitCanBeInterrupted() throws InterruptedException {
+ void requireThatReplyWaitCanBeInterrupted() throws InterruptedException {
final Receptor receptor = new Receptor();
final CountDownLatch latch = new CountDownLatch(1);
Thread thread = new Thread() {
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/test/SimpleMessageTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/test/SimpleMessageTestCase.java
index 217f5347f40..7e3d9e926b9 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/test/SimpleMessageTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/test/SimpleMessageTestCase.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.messagebus.test;
-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.jupiter.api.Assertions.assertEquals;
/**
* @author Simon Thoresen Hult
@@ -13,7 +11,7 @@ import static org.junit.Assert.assertTrue;
public class SimpleMessageTestCase {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
SimpleMessage msg = new SimpleMessage("foo");
assertEquals(SimpleProtocol.MESSAGE, msg.getType());
assertEquals(SimpleProtocol.NAME, msg.getProtocol());
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/test/SimpleProtocolTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/test/SimpleProtocolTestCase.java
index 76d6a1ee778..a8406cd5d1f 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/test/SimpleProtocolTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/test/SimpleProtocolTestCase.java
@@ -4,11 +4,9 @@ package com.yahoo.messagebus.test;
import com.yahoo.component.Version;
import com.yahoo.messagebus.EmptyReply;
import com.yahoo.messagebus.Routable;
-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.Assert.assertNull;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -19,45 +17,45 @@ public class SimpleProtocolTestCase {
private static final SimpleProtocol PROTOCOL = new SimpleProtocol();
@Test
- public void requireThatNameIsSet() {
+ void requireThatNameIsSet() {
assertEquals(SimpleProtocol.NAME, PROTOCOL.getName());
}
@Test
- public void requireThatMessageCanBeEncodedAndDecoded() {
+ void requireThatMessageCanBeEncodedAndDecoded() {
SimpleMessage msg = new SimpleMessage("foo");
byte[] buf = PROTOCOL.encode(Version.emptyVersion, msg);
Routable routable = PROTOCOL.decode(Version.emptyVersion, buf);
assertNotNull(routable);
assertEquals(SimpleMessage.class, routable.getClass());
- msg = (SimpleMessage)routable;
+ msg = (SimpleMessage) routable;
assertEquals("foo", msg.getValue());
}
@Test
- public void requireThatReplyCanBeDecoded() {
+ void requireThatReplyCanBeDecoded() {
SimpleReply reply = new SimpleReply("foo");
byte[] buf = PROTOCOL.encode(Version.emptyVersion, reply);
Routable routable = PROTOCOL.decode(Version.emptyVersion, buf);
assertNotNull(routable);
assertEquals(SimpleReply.class, routable.getClass());
- reply = (SimpleReply)routable;
+ reply = (SimpleReply) routable;
assertEquals("foo", reply.getValue());
}
@Test
- public void requireThatUnknownRoutablesAreNotEncoded() {
+ void requireThatUnknownRoutablesAreNotEncoded() {
assertNull(PROTOCOL.encode(VERSION, new EmptyReply()));
}
@Test
- public void requireThatEmptyBufferIsNotDecoded() {
+ void requireThatEmptyBufferIsNotDecoded() {
assertNull(PROTOCOL.decode(VERSION, new byte[0]));
}
@Test
- public void requireThatUnknownBufferIsNotDecoded() {
- assertNull(PROTOCOL.decode(VERSION, new byte[] { 'U' }));
+ void requireThatUnknownBufferIsNotDecoded() {
+ assertNull(PROTOCOL.decode(VERSION, new byte[]{'U'}));
}
}
diff --git a/messagebus/src/test/java/com/yahoo/messagebus/test/SimpleReplyTestCase.java b/messagebus/src/test/java/com/yahoo/messagebus/test/SimpleReplyTestCase.java
index 0d3f67bcb3c..bbb72a6b637 100644
--- a/messagebus/src/test/java/com/yahoo/messagebus/test/SimpleReplyTestCase.java
+++ b/messagebus/src/test/java/com/yahoo/messagebus/test/SimpleReplyTestCase.java
@@ -1,9 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.messagebus.test;
-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 Simon Thoresen Hult
@@ -11,7 +11,7 @@ import static org.junit.Assert.assertEquals;
public class SimpleReplyTestCase {
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
SimpleReply reply = new SimpleReply("foo");
assertEquals(SimpleProtocol.REPLY, reply.getType());
assertEquals(SimpleProtocol.NAME, reply.getProtocol());
diff --git a/node-admin/pom.xml b/node-admin/pom.xml
index ae7e6ac2bce..8ef8e934cd8 100644
--- a/node-admin/pom.xml
+++ b/node-admin/pom.xml
@@ -87,21 +87,11 @@
<scope>test</scope>
</dependency>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
- <groupId>org.junit.vintage</groupId>
- <artifactId>junit-vintage-engine</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>com.yahoo.vespa</groupId>
<artifactId>application</artifactId>
<version>${project.version}</version>
@@ -136,6 +126,20 @@
<artifactId>testutil</artifactId>
<version>${project.version}</version>
<scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-core</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-library</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<!-- Needed for node repo mock -->
<dependency>
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/ConfigServerApiImplTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/ConfigServerApiImplTest.java
index 866b7d2877a..9014875d780 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/ConfigServerApiImplTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/ConfigServerApiImplTest.java
@@ -9,8 +9,8 @@ import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.message.BasicStatusLine;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
@@ -21,10 +21,7 @@ import java.nio.charset.StandardCharsets;
import java.time.Duration;
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.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -55,7 +52,7 @@ public class ConfigServerApiImplTest {
private ConfigServerApiImpl configServerApi;
private int mockReturnCode = 200;
- @Before
+ @BeforeEach
public void initExecutor() throws IOException {
CloseableHttpClient httpMock = mock(CloseableHttpClient.class);
when(httpMock.execute(any())).thenAnswer(invocationOnMock -> {
@@ -83,24 +80,26 @@ public class ConfigServerApiImplTest {
}
@Test
- public void testBasicParsingSingleServer() {
+ void testBasicParsingSingleServer() {
TestPojo answer = configServerApi.get("/path", TestPojo.class);
assertEquals(answer.foo, "bar");
assertLogStringContainsGETForAHost();
}
- @Test(expected = HttpException.class)
- public void testBasicFailure() {
- // Server is returning 400, no retries.
- mockReturnCode = 400;
-
- TestPojo testPojo = configServerApi.get("/path", TestPojo.class);
- assertEquals(testPojo.errorCode.intValue(), mockReturnCode);
- assertLogStringContainsGETForAHost();
+ @Test
+ void testBasicFailure() {
+ assertThrows(HttpException.class, () -> {
+ // Server is returning 400, no retries.
+ mockReturnCode = 400;
+
+ TestPojo testPojo = configServerApi.get("/path", TestPojo.class);
+ assertEquals(testPojo.errorCode.intValue(), mockReturnCode);
+ assertLogStringContainsGETForAHost();
+ });
}
@Test
- public void testBasicSuccessWithNoRetries() {
+ void testBasicSuccessWithNoRetries() {
// Server is returning 201, no retries.
mockReturnCode = 201;
@@ -110,7 +109,7 @@ public class ConfigServerApiImplTest {
}
@Test
- public void testBasicSuccessWithCustomTimeouts() {
+ void testBasicSuccessWithCustomTimeouts() {
mockReturnCode = TIMEOUT_RETURN_CODE;
var params = new ConfigServerApi.Params<TestPojo>();
@@ -126,7 +125,7 @@ public class ConfigServerApiImplTest {
}
@Test
- public void testRetries() {
+ void testRetries() {
// Client is throwing exception, should be retries.
mockReturnCode = FAIL_RETURN_CODE;
try {
@@ -141,7 +140,7 @@ public class ConfigServerApiImplTest {
}
@Test
- public void testNoRetriesOnBadHttpResponseCode() {
+ void testNoRetriesOnBadHttpResponseCode() {
// Client is throwing exception, should be retries.
mockReturnCode = 503;
try {
@@ -155,7 +154,7 @@ public class ConfigServerApiImplTest {
}
@Test
- public void testForbidden() {
+ void testForbidden() {
mockReturnCode = 403;
try {
configServerApi.get("/path", TestPojo.class);
@@ -167,7 +166,7 @@ public class ConfigServerApiImplTest {
}
@Test
- public void testNotFound() {
+ void testNotFound() {
// Server is returning 404, special exception is thrown.
mockReturnCode = 404;
try {
@@ -180,7 +179,7 @@ public class ConfigServerApiImplTest {
}
@Test
- public void testConflict() {
+ void testConflict() {
// Server is returning 409, no exception is thrown.
mockReturnCode = 409;
configServerApi.get("/path", TestPojo.class);
@@ -189,7 +188,7 @@ public class ConfigServerApiImplTest {
private void assertLogStringContainsGETForAHost() {
String logString = mockLog.toString();
- assertTrue("log does not contain expected entries:" + logString,
- (logString.equals("GET http://host1:666/path ") || logString.equals("GET http://host2:666/path ")));
+ assertTrue((logString.equals("GET http://host1:666/path ") || logString.equals("GET http://host2:666/path ")),
+ "log does not contain expected entries:" + logString);
}
}
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/flags/RealFlagRepositoryTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/flags/RealFlagRepositoryTest.java
index 8c914530122..74bb644ea9d 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/flags/RealFlagRepositoryTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/flags/RealFlagRepositoryTest.java
@@ -6,13 +6,13 @@ import com.yahoo.vespa.flags.json.FlagData;
import com.yahoo.vespa.flags.json.wire.WireFlagData;
import com.yahoo.vespa.flags.json.wire.WireFlagDataList;
import com.yahoo.vespa.hosted.node.admin.configserver.ConfigServerApi;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Map;
-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;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
@@ -26,7 +26,7 @@ public class RealFlagRepositoryTest {
private final RealFlagRepository repository = new RealFlagRepository(configServerApi);
@Test
- public void test() {
+ void test() {
WireFlagDataList list = new WireFlagDataList();
list.flags = new ArrayList<>();
list.flags.add(new WireFlagData());
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/AclTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/AclTest.java
index 87f3d71ec7a..78971dc30c7 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/AclTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/AclTest.java
@@ -2,13 +2,13 @@
package com.yahoo.vespa.hosted.node.admin.configserver.noderepository;
import com.yahoo.vespa.hosted.node.admin.task.util.network.IPVersion;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
*
@@ -27,7 +27,7 @@ public class AclTest {
Set.of());
@Test
- public void no_trusted_ports() {
+ void no_trusted_ports() {
String listRulesIpv4 = String.join("\n", aclWithoutPorts.toRules(IPVersion.IPv4));
assertEquals(
"-P INPUT ACCEPT\n" +
@@ -42,7 +42,7 @@ public class AclTest {
}
@Test
- public void ipv4_rules() {
+ void ipv4_rules() {
String listRulesIpv4 = String.join("\n", aclCommon.toRules(IPVersion.IPv4));
assertEquals(
"-P INPUT ACCEPT\n" +
@@ -58,7 +58,7 @@ public class AclTest {
}
@Test
- public void ipv6_rules() {
+ void ipv6_rules() {
String listRulesIpv6 = String.join("\n", aclCommon.toRules(IPVersion.IPv6));
assertEquals(
"-P INPUT ACCEPT\n" +
@@ -75,43 +75,43 @@ public class AclTest {
}
@Test
- public void ipv6_rules_stable_order() {
+ void ipv6_rules_stable_order() {
Acl aclCommonDifferentOrder = new Acl(
Set.of(453, 1234),
testNodes("fe80::2", "192.1.2.2", "fb00::1", "fe80::3"),
Set.of());
- for (IPVersion ipVersion: IPVersion.values()) {
+ for (IPVersion ipVersion : IPVersion.values()) {
assertEquals(aclCommon.toRules(ipVersion), aclCommonDifferentOrder.toRules(ipVersion));
}
}
@Test
- public void trusted_networks() {
+ void trusted_networks() {
Acl acl = new Acl(Set.of(4080), testNodes("127.0.0.1"), Set.of("10.0.0.0/24", "2001:db8::/32"));
assertEquals("-P INPUT ACCEPT\n" +
- "-P FORWARD ACCEPT\n" +
- "-P OUTPUT ACCEPT\n" +
- "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT\n" +
- "-A INPUT -i lo -j ACCEPT\n" +
- "-A INPUT -p icmp -j ACCEPT\n" +
- "-A INPUT -p tcp -m multiport --dports 4080 -j ACCEPT\n" +
- "-A INPUT -s 127.0.0.1/32 -j ACCEPT\n" +
- "-A INPUT -s 10.0.0.0/24 -j ACCEPT\n" +
- "-A INPUT -j REJECT --reject-with icmp-port-unreachable",
- String.join("\n", acl.toRules(IPVersion.IPv4)));
+ "-P FORWARD ACCEPT\n" +
+ "-P OUTPUT ACCEPT\n" +
+ "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT\n" +
+ "-A INPUT -i lo -j ACCEPT\n" +
+ "-A INPUT -p icmp -j ACCEPT\n" +
+ "-A INPUT -p tcp -m multiport --dports 4080 -j ACCEPT\n" +
+ "-A INPUT -s 127.0.0.1/32 -j ACCEPT\n" +
+ "-A INPUT -s 10.0.0.0/24 -j ACCEPT\n" +
+ "-A INPUT -j REJECT --reject-with icmp-port-unreachable",
+ String.join("\n", acl.toRules(IPVersion.IPv4)));
assertEquals("-P INPUT ACCEPT\n" +
- "-P FORWARD ACCEPT\n" +
- "-P OUTPUT ACCEPT\n" +
- "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT\n" +
- "-A INPUT -i lo -j ACCEPT\n" +
- "-A INPUT -p ipv6-icmp -j ACCEPT\n" +
- "-A INPUT -p tcp -m multiport --dports 4080 -j ACCEPT\n" +
- "-A INPUT -s 2001:db8::/32 -j ACCEPT\n" +
- "-A INPUT -j REJECT --reject-with icmp6-port-unreachable",
- String.join("\n", acl.toRules(IPVersion.IPv6)));
+ "-P FORWARD ACCEPT\n" +
+ "-P OUTPUT ACCEPT\n" +
+ "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT\n" +
+ "-A INPUT -i lo -j ACCEPT\n" +
+ "-A INPUT -p ipv6-icmp -j ACCEPT\n" +
+ "-A INPUT -p tcp -m multiport --dports 4080 -j ACCEPT\n" +
+ "-A INPUT -s 2001:db8::/32 -j ACCEPT\n" +
+ "-A INPUT -j REJECT --reject-with icmp6-port-unreachable",
+ String.join("\n", acl.toRules(IPVersion.IPv6)));
}
private static Set<Acl.Node> testNodes(String... address) {
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/NodeStateTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/NodeStateTest.java
index e1cd7b45b86..ad909bd2583 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/NodeStateTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/NodeStateTest.java
@@ -2,13 +2,13 @@
package com.yahoo.vespa.hosted.node.admin.configserver.noderepository;
import com.yahoo.vespa.hosted.provision.Node;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author freva
@@ -16,7 +16,7 @@ import static org.junit.Assert.assertEquals;
public class NodeStateTest {
@Test
- public void is_equal_to_node_repository_states() {
+ void is_equal_to_node_repository_states() {
Set<String> nodeRepositoryStates = Stream.of(Node.State.values()).map(Enum::name).collect(Collectors.toSet());
Set<String> nodeAdminStates = Stream.of(NodeState.values()).map(Enum::name).collect(Collectors.toSet());
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/RealNodeRepositoryTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/RealNodeRepositoryTest.java
index 98a85085b4a..1ad8a4326e7 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/RealNodeRepositoryTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/RealNodeRepositoryTest.java
@@ -11,9 +11,9 @@ import com.yahoo.vespa.hosted.node.admin.configserver.ConfigServerApi;
import com.yahoo.vespa.hosted.node.admin.configserver.ConfigServerApiImpl;
import com.yahoo.vespa.hosted.provision.restapi.NodesV2ApiHandler;
import com.yahoo.vespa.hosted.provision.testutils.ContainerConfig;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.ServerSocket;
@@ -23,10 +23,7 @@ import java.util.List;
import java.util.Optional;
import java.util.Set;
-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.*;
/**
* Tests the NodeRepository class used for talking to the node repository. It uses a mock from the node repository
@@ -54,7 +51,7 @@ public class RealNodeRepositoryTest {
* {@link NodesV2ApiHandler}
* These classes define some test data that is used in these tests.
*/
- @Before
+ @BeforeEach
public void startContainer() throws Exception {
Exception lastException = null;
@@ -89,7 +86,7 @@ public class RealNodeRepositoryTest {
throw new RuntimeException("Could not get answer from container.");
}
- @After
+ @AfterEach
public void stopContainer() {
if (container != null) {
container.close();
@@ -97,7 +94,7 @@ public class RealNodeRepositoryTest {
}
@Test
- public void testGetContainersToRunApi() {
+ void testGetContainersToRunApi() {
String dockerHostHostname = "dockerhost1.yahoo.com";
List<NodeSpec> containersToRun = nodeRepositoryApi.getNodes(dockerHostHostname);
@@ -114,7 +111,7 @@ public class RealNodeRepositoryTest {
}
@Test
- public void testGetContainer() {
+ void testGetContainer() {
String hostname = "host4.yahoo.com";
Optional<NodeSpec> node = nodeRepositoryApi.getOptionalNode(hostname);
assertTrue(node.isPresent());
@@ -122,14 +119,14 @@ public class RealNodeRepositoryTest {
}
@Test
- public void testGetContainerForNonExistingNode() {
+ void testGetContainerForNonExistingNode() {
String hostname = "host-that-does-not-exist";
Optional<NodeSpec> node = nodeRepositoryApi.getOptionalNode(hostname);
assertFalse(node.isPresent());
}
@Test
- public void testUpdateNodeAttributes() {
+ void testUpdateNodeAttributes() {
String hostname = "host4.yahoo.com";
nodeRepositoryApi.updateNodeAttributes(
hostname,
@@ -139,7 +136,7 @@ public class RealNodeRepositoryTest {
}
@Test
- public void testMarkAsReady() {
+ void testMarkAsReady() {
nodeRepositoryApi.setNodeState("host5.yahoo.com", NodeState.dirty);
nodeRepositoryApi.setNodeState("host5.yahoo.com", NodeState.ready);
@@ -159,13 +156,13 @@ public class RealNodeRepositoryTest {
}
@Test
- public void testAddNodes() {
+ void testAddNodes() {
AddNode host = AddNode.forHost("host123.domain.tld",
- "id1",
- "default",
- Optional.of(FlavorOverrides.ofDisk(123)),
- NodeType.confighost,
- Set.of("::1"), Set.of("::2", "::3"));
+ "id1",
+ "default",
+ Optional.of(FlavorOverrides.ofDisk(123)),
+ NodeType.confighost,
+ Set.of("::1"), Set.of("::2", "::3"));
NodeResources nodeResources = new NodeResources(1, 2, 3, 4, NodeResources.DiskSpeed.slow, NodeResources.StorageType.local);
AddNode node = AddNode.forNode("host123-1.domain.tld", "id1", "host123.domain.tld", nodeResources, NodeType.config, Set.of("::2", "::3"));
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/bindings/NodeRepositoryNodeTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/bindings/NodeRepositoryNodeTest.java
index 055bdb5c1f5..92d0cfc8483 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/bindings/NodeRepositoryNodeTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/bindings/NodeRepositoryNodeTest.java
@@ -9,12 +9,12 @@ import com.yahoo.test.json.JsonTestHelper;
import com.yahoo.vespa.hosted.node.admin.configserver.noderepository.NodeAttributes;
import com.yahoo.vespa.hosted.node.admin.configserver.noderepository.RealNodeRepository;
import com.yahoo.vespa.hosted.node.admin.configserver.noderepository.reports.BaseReport;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.HashMap;
import static com.yahoo.yolean.Exceptions.uncheck;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author hakonhall
@@ -31,7 +31,7 @@ public class NodeRepositoryNodeTest {
* NodeAttributes -> NodeRepositoryNode -> JSON.
*/
@Test
- public void testReportsSerialization() {
+ void testReportsSerialization() {
// Make sure we don't accidentally patch with "reports": null, as that actually means removing all reports.
assertEquals(JsonInclude.Include.NON_NULL, NodeRepositoryNode.class.getAnnotation(JsonInclude.class).value());
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/reports/BaseReportTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/reports/BaseReportTest.java
index 72a42911426..6d51c6fb53c 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/reports/BaseReportTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/noderepository/reports/BaseReportTest.java
@@ -2,13 +2,11 @@
package com.yahoo.vespa.hosted.node.admin.configserver.noderepository.reports;
import com.yahoo.test.json.JsonTestHelper;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static com.yahoo.vespa.hosted.node.admin.configserver.noderepository.reports.BaseReport.Type.SOFT_FAIL;
import static com.yahoo.vespa.hosted.node.admin.configserver.noderepository.reports.BaseReport.Type.UNSPECIFIED;
-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 hakonhall
@@ -18,7 +16,7 @@ public class BaseReportTest {
private static final String JSON_2 = "{\"createdMillis\": 1, \"description\": \"desc\", \"type\": \"SOFT_FAIL\"}";
@Test
- public void testSerialization1() {
+ void testSerialization1() {
JsonTestHelper.assertJsonEquals(new BaseReport(1L, "desc", SOFT_FAIL).toJsonNode(),
JSON_2);
JsonTestHelper.assertJsonEquals(new BaseReport(null, "desc", SOFT_FAIL).toJsonNode(),
@@ -39,7 +37,7 @@ public class BaseReportTest {
}
@Test
- public void testShouldUpdate() {
+ void testShouldUpdate() {
BaseReport report = new BaseReport(1L, "desc", SOFT_FAIL);
assertFalse(report.updates(report));
@@ -58,7 +56,7 @@ public class BaseReportTest {
}
@Test
- public void testJsonSerialization() {
+ void testJsonSerialization() {
BaseReport report = BaseReport.fromJson(JSON_2);
assertEquals(1L, (long) report.getCreatedMillisOrNull());
assertEquals("desc", report.getDescriptionOrNull());
@@ -67,9 +65,9 @@ public class BaseReportTest {
}
@Test
- public void testUnspecifiedType() {
+ void testUnspecifiedType() {
BaseReport report = new BaseReport(1L, "desc", null);
- assertEquals(null, report.getTypeOrNull());
+ assertNull(report.getTypeOrNull());
assertEquals(UNSPECIFIED, report.getType());
}
} \ No newline at end of file
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/orchestrator/OrchestratorImplTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/orchestrator/OrchestratorImplTest.java
index 7f2c584303b..2bc6561dbf9 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/orchestrator/OrchestratorImplTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/orchestrator/OrchestratorImplTest.java
@@ -6,11 +6,12 @@ import com.yahoo.vespa.hosted.node.admin.configserver.HttpException;
import com.yahoo.vespa.orchestrator.restapi.wire.BatchOperationResult;
import com.yahoo.vespa.orchestrator.restapi.wire.HostStateChangeDenialReason;
import com.yahoo.vespa.orchestrator.restapi.wire.UpdateHostResponse;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Optional;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.mock;
@@ -27,9 +28,9 @@ public class OrchestratorImplTest {
private final OrchestratorImpl orchestrator = new OrchestratorImpl(configServerApi);
@Test
- public void testSuspendCall() {
+ void testSuspendCall() {
when(configServerApi.put(
- eq(OrchestratorImpl.ORCHESTRATOR_PATH_PREFIX_HOST_API + "/" + hostName+ "/suspended"),
+ eq(OrchestratorImpl.ORCHESTRATOR_PATH_PREFIX_HOST_API + "/" + hostName + "/suspended"),
eq(Optional.empty()),
eq(UpdateHostResponse.class),
any()
@@ -38,75 +39,87 @@ public class OrchestratorImplTest {
orchestrator.suspend(hostName);
}
- @Test(expected=OrchestratorException.class)
- public void testSuspendCallWithFailureReason() {
- when(configServerApi.put(
- eq(OrchestratorImpl.ORCHESTRATOR_PATH_PREFIX_HOST_API + "/" + hostName+ "/suspended"),
- eq(Optional.empty()),
- eq(UpdateHostResponse.class),
- any()
- )).thenReturn(new UpdateHostResponse(hostName, new HostStateChangeDenialReason("hostname", "fail")));
-
- orchestrator.suspend(hostName);
+ @Test
+ void testSuspendCallWithFailureReason() {
+ assertThrows(OrchestratorException.class, () -> {
+ when(configServerApi.put(
+ eq(OrchestratorImpl.ORCHESTRATOR_PATH_PREFIX_HOST_API + "/" + hostName + "/suspended"),
+ eq(Optional.empty()),
+ eq(UpdateHostResponse.class),
+ any()
+ )).thenReturn(new UpdateHostResponse(hostName, new HostStateChangeDenialReason("hostname", "fail")));
+
+ orchestrator.suspend(hostName);
+ });
}
- @Test(expected=OrchestratorNotFoundException.class)
- public void testSuspendCallWithNotFound() {
- when(configServerApi.put(any(String.class), any(), any(), any()))
- .thenThrow(new HttpException.NotFoundException("Not Found"));
+ @Test
+ void testSuspendCallWithNotFound() {
+ assertThrows(OrchestratorNotFoundException.class, () -> {
+ when(configServerApi.put(any(String.class), any(), any(), any()))
+ .thenThrow(new HttpException.NotFoundException("Not Found"));
- orchestrator.suspend(hostName);
+ orchestrator.suspend(hostName);
+ });
}
- @Test(expected=RuntimeException.class)
- public void testSuspendCallWithSomeOtherException() {
- when(configServerApi.put(any(String.class), any(), any(), any()))
- .thenThrow(new RuntimeException("Some parameter was wrong"));
+ @Test
+ void testSuspendCallWithSomeOtherException() {
+ assertThrows(RuntimeException.class, () -> {
+ when(configServerApi.put(any(String.class), any(), any(), any()))
+ .thenThrow(new RuntimeException("Some parameter was wrong"));
- orchestrator.suspend(hostName);
+ orchestrator.suspend(hostName);
+ });
}
@Test
- public void testResumeCall() {
+ void testResumeCall() {
when(configServerApi.delete(
- OrchestratorImpl.ORCHESTRATOR_PATH_PREFIX_HOST_API + "/" + hostName+ "/suspended",
+ OrchestratorImpl.ORCHESTRATOR_PATH_PREFIX_HOST_API + "/" + hostName + "/suspended",
UpdateHostResponse.class
)).thenReturn(new UpdateHostResponse(hostName, null));
orchestrator.resume(hostName);
}
- @Test(expected=OrchestratorException.class)
- public void testResumeCallWithFailureReason() {
- when(configServerApi.delete(
- OrchestratorImpl.ORCHESTRATOR_PATH_PREFIX_HOST_API + "/" + hostName+ "/suspended",
- UpdateHostResponse.class
- )).thenReturn(new UpdateHostResponse(hostName, new HostStateChangeDenialReason("hostname", "fail")));
-
- orchestrator.resume(hostName);
+ @Test
+ void testResumeCallWithFailureReason() {
+ assertThrows(OrchestratorException.class, () -> {
+ when(configServerApi.delete(
+ OrchestratorImpl.ORCHESTRATOR_PATH_PREFIX_HOST_API + "/" + hostName + "/suspended",
+ UpdateHostResponse.class
+ )).thenReturn(new UpdateHostResponse(hostName, new HostStateChangeDenialReason("hostname", "fail")));
+
+ orchestrator.resume(hostName);
+ });
}
- @Test(expected=OrchestratorNotFoundException.class)
- public void testResumeCallWithNotFound() {
- when(configServerApi.delete(
- any(String.class),
- any()
- )).thenThrow(new HttpException.NotFoundException("Not Found"));
-
- orchestrator.resume(hostName);
+ @Test
+ void testResumeCallWithNotFound() {
+ assertThrows(OrchestratorNotFoundException.class, () -> {
+ when(configServerApi.delete(
+ any(String.class),
+ any()
+ )).thenThrow(new HttpException.NotFoundException("Not Found"));
+
+ orchestrator.resume(hostName);
+ });
}
- @Test(expected=RuntimeException.class)
- public void testResumeCallWithSomeOtherException() {
- when(configServerApi.put(any(String.class), any(), any(), any()))
- .thenThrow(new RuntimeException("Some parameter was wrong"));
+ @Test
+ void testResumeCallWithSomeOtherException() {
+ assertThrows(RuntimeException.class, () -> {
+ when(configServerApi.put(any(String.class), any(), any(), any()))
+ .thenThrow(new RuntimeException("Some parameter was wrong"));
- orchestrator.suspend(hostName);
+ orchestrator.suspend(hostName);
+ });
}
@Test
- public void testBatchSuspendCall() {
+ void testBatchSuspendCall() {
String parentHostName = "host1.test.yahoo.com";
List<String> hostNames = List.of("a1.host1.test.yahoo.com", "a2.host1.test.yahoo.com");
@@ -120,36 +133,40 @@ public class OrchestratorImplTest {
orchestrator.suspend(parentHostName, hostNames);
}
- @Test(expected=OrchestratorException.class)
- public void testBatchSuspendCallWithFailureReason() {
- String parentHostName = "host1.test.yahoo.com";
- List<String> hostNames = List.of("a1.host1.test.yahoo.com", "a2.host1.test.yahoo.com");
- String failureReason = "Failed to suspend";
-
- when(configServerApi.put(
- eq("/orchestrator/v1/suspensions/hosts/host1.test.yahoo.com?hostname=a1.host1.test.yahoo.com&hostname=a2.host1.test.yahoo.com"),
- eq(Optional.empty()),
- eq(BatchOperationResult.class),
- any()
- )).thenReturn(new BatchOperationResult(failureReason));
-
- orchestrator.suspend(parentHostName, hostNames);
+ @Test
+ void testBatchSuspendCallWithFailureReason() {
+ assertThrows(OrchestratorException.class, () -> {
+ String parentHostName = "host1.test.yahoo.com";
+ List<String> hostNames = List.of("a1.host1.test.yahoo.com", "a2.host1.test.yahoo.com");
+ String failureReason = "Failed to suspend";
+
+ when(configServerApi.put(
+ eq("/orchestrator/v1/suspensions/hosts/host1.test.yahoo.com?hostname=a1.host1.test.yahoo.com&hostname=a2.host1.test.yahoo.com"),
+ eq(Optional.empty()),
+ eq(BatchOperationResult.class),
+ any()
+ )).thenReturn(new BatchOperationResult(failureReason));
+
+ orchestrator.suspend(parentHostName, hostNames);
+ });
}
- @Test(expected=RuntimeException.class)
- public void testBatchSuspendCallWithSomeException() {
- String parentHostName = "host1.test.yahoo.com";
- List<String> hostNames = List.of("a1.host1.test.yahoo.com", "a2.host1.test.yahoo.com");
- String exceptionMessage = "Exception: Something crashed!";
-
- when(configServerApi.put(
- eq("/orchestrator/v1/suspensions/hosts/host1.test.yahoo.com?hostname=a1.host1.test.yahoo.com&hostname=a2.host1.test.yahoo.com"),
- eq(Optional.empty()),
- eq(BatchOperationResult.class),
- any()
- )).thenThrow(new RuntimeException(exceptionMessage));
-
- orchestrator.suspend(parentHostName, hostNames);
+ @Test
+ void testBatchSuspendCallWithSomeException() {
+ assertThrows(RuntimeException.class, () -> {
+ String parentHostName = "host1.test.yahoo.com";
+ List<String> hostNames = List.of("a1.host1.test.yahoo.com", "a2.host1.test.yahoo.com");
+ String exceptionMessage = "Exception: Something crashed!";
+
+ when(configServerApi.put(
+ eq("/orchestrator/v1/suspensions/hosts/host1.test.yahoo.com?hostname=a1.host1.test.yahoo.com&hostname=a2.host1.test.yahoo.com"),
+ eq(Optional.empty()),
+ eq(BatchOperationResult.class),
+ any()
+ )).thenThrow(new RuntimeException(exceptionMessage));
+
+ orchestrator.suspend(parentHostName, hostNames);
+ });
}
}
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/state/HealthResponseTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/state/HealthResponseTest.java
index 18feee9cb63..4f213f0acf9 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/state/HealthResponseTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/state/HealthResponseTest.java
@@ -3,13 +3,13 @@ package com.yahoo.vespa.hosted.node.admin.configserver.state;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yahoo.vespa.hosted.node.admin.configserver.state.bindings.HealthResponse;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class HealthResponseTest {
@Test
- public void deserializationOfNormalResponse() throws Exception {
+ void deserializationOfNormalResponse() throws Exception {
String jsonResponse = "{\n" +
" \"metrics\": {\n" +
" \"snapshot\": {\n" +
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/state/StateImplTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/state/StateImplTest.java
index 3184f36b75e..190e4f772be 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/state/StateImplTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/configserver/state/StateImplTest.java
@@ -4,11 +4,11 @@ package com.yahoo.vespa.hosted.node.admin.configserver.state;
import com.yahoo.vespa.hosted.node.admin.configserver.ConfigServerApi;
import com.yahoo.vespa.hosted.node.admin.configserver.ConnectionException;
import com.yahoo.vespa.hosted.node.admin.configserver.state.bindings.HealthResponse;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.ConnectException;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -18,7 +18,7 @@ public class StateImplTest {
private final StateImpl state = new StateImpl(api);
@Test
- public void testWhenUp() {
+ void testWhenUp() {
HealthResponse response = new HealthResponse();
response.status.code = "up";
when(api.get(any(), any())).thenReturn(response);
@@ -28,7 +28,7 @@ public class StateImplTest {
}
@Test
- public void connectException() {
+ void connectException() {
RuntimeException exception =
ConnectionException.handleException("Error: ", new ConnectException("connection refused"));
when(api.get(any(), any())).thenThrow(exception);
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/ContainerNameTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/ContainerNameTest.java
index bff3fb34663..aec559d7d76 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/ContainerNameTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/ContainerNameTest.java
@@ -1,45 +1,52 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.admin.container;
-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;
/**
* @author freva
*/
public class ContainerNameTest {
@Test
- public void testAlphanumericalContainerName() {
+ void testAlphanumericalContainerName() {
String name = "container123";
ContainerName containerName = new ContainerName(name);
assertEquals(containerName.asString(), name);
}
@Test
- public void testAlphanumericalWithDashContainerName() {
+ void testAlphanumericalWithDashContainerName() {
String name = "container-123";
ContainerName containerName = new ContainerName(name);
assertEquals(containerName.asString(), name);
}
@Test
- public void testContainerNameFromHostname() {
+ void testContainerNameFromHostname() {
assertEquals(new ContainerName("container-123"), ContainerName.fromHostname("container-123.sub.domain.tld"));
}
- @Test(expected=IllegalArgumentException.class)
- public void testAlphanumericalWithSlashContainerName() {
- new ContainerName("container/123");
+ @Test
+ void testAlphanumericalWithSlashContainerName() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new ContainerName("container/123");
+ });
}
- @Test(expected=IllegalArgumentException.class)
- public void testEmptyContainerName() {
- new ContainerName("");
+ @Test
+ void testEmptyContainerName() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new ContainerName("");
+ });
}
- @Test(expected=NullPointerException.class)
- public void testNullContainerName() {
- new ContainerName(null);
+ @Test
+ void testNullContainerName() {
+ assertThrows(NullPointerException.class, () -> {
+ new ContainerName(null);
+ });
}
}
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/ContainerOperationsTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/ContainerOperationsTest.java
index d0c54dd4e04..9a5ca8c805e 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/ContainerOperationsTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/ContainerOperationsTest.java
@@ -4,7 +4,7 @@ package com.yahoo.vespa.hosted.node.admin.container;
import com.yahoo.config.provision.DockerImage;
import com.yahoo.vespa.hosted.node.admin.component.TestTaskContext;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.file.FileSystem;
import java.time.Instant;
@@ -13,9 +13,7 @@ import java.util.Map;
import java.util.Set;
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 mpolden
@@ -28,7 +26,7 @@ public class ContainerOperationsTest {
private final ContainerOperations containerOperations = new ContainerOperations(containerEngine, new CGroupV2(fileSystem), fileSystem);
@Test
- public void no_managed_containers_running() {
+ void no_managed_containers_running() {
Container c1 = createContainer("c1", true);
Container c2 = createContainer("c2", false);
@@ -43,7 +41,7 @@ public class ContainerOperationsTest {
}
@Test
- public void retain_managed_containers() {
+ void retain_managed_containers() {
Container c1 = createContainer("c1", true);
Container c2 = createContainer("c2", true);
Container c3 = createContainer("c3", false);
@@ -53,9 +51,9 @@ public class ContainerOperationsTest {
containerOperations.retainManagedContainers(context, Set.of(c1.name()));
assertEquals(List.of(c1.name(), c3.name()), containerEngine.listContainers(context).stream()
- .map(PartialContainer::name)
- .sorted()
- .collect(Collectors.toList()));
+ .map(PartialContainer::name)
+ .sorted()
+ .collect(Collectors.toList()));
}
private Container createContainer(String name, boolean managed) {
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/ContainerResourcesTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/ContainerResourcesTest.java
index 12f928f0d44..e7a3b4ec9b1 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/ContainerResourcesTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/ContainerResourcesTest.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.hosted.node.admin.container;
-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
@@ -12,14 +12,14 @@ import static org.junit.Assert.fail;
public class ContainerResourcesTest {
@Test
- public void verify_unlimited() {
+ void verify_unlimited() {
assertEquals(-1, ContainerResources.UNLIMITED.cpuQuota());
assertEquals(100_000, ContainerResources.UNLIMITED.cpuPeriod());
assertEquals(0, ContainerResources.UNLIMITED.cpuShares());
}
@Test
- public void validate_shares() {
+ void validate_shares() {
new ContainerResources(0, 0, 0);
new ContainerResources(0, 2, 0);
new ContainerResources(0, 2048, 0);
@@ -31,7 +31,7 @@ public class ContainerResourcesTest {
}
@Test
- public void cpu_shares_scaling() {
+ void cpu_shares_scaling() {
ContainerResources resources = ContainerResources.from(5.3, 2.5, 0);
assertEquals(530_000, resources.cpuQuota());
assertEquals(100_000, resources.cpuPeriod());
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/ContainerStatsCollectorTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/ContainerStatsCollectorTest.java
index 7df5309961f..79c7558ea9e 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/ContainerStatsCollectorTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/ContainerStatsCollectorTest.java
@@ -3,7 +3,7 @@ package com.yahoo.vespa.hosted.node.admin.container;
import com.yahoo.vespa.hosted.node.admin.task.util.file.UnixPath;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.file.FileSystem;
@@ -16,8 +16,8 @@ import static com.yahoo.vespa.hosted.node.admin.container.CGroup.CpuStatField.TH
import static com.yahoo.vespa.hosted.node.admin.container.CGroup.CpuStatField.TOTAL_PERIODS;
import static com.yahoo.vespa.hosted.node.admin.container.CGroup.CpuStatField.TOTAL_USAGE_USEC;
import static com.yahoo.vespa.hosted.node.admin.container.CGroup.CpuStatField.USER_USAGE_USEC;
-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;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -31,11 +31,11 @@ public class ContainerStatsCollectorTest {
private final CGroup cgroup = mock(CGroup.class);
@Test
- public void collect() throws IOException {
+ void collect() throws IOException {
ContainerStatsCollector collector = new ContainerStatsCollector(cgroup, fileSystem, 24);
ContainerId containerId = new ContainerId("id1");
int containerPid = 42;
- assertTrue("No stats found", collector.collect(containerId, containerPid, "eth0").isEmpty());
+ assertTrue(collector.collect(containerId, containerPid, "eth0").isEmpty(), "No stats found");
mockMemoryStats(containerId);
mockCpuStats(containerId);
@@ -44,13 +44,13 @@ public class ContainerStatsCollectorTest {
Optional<ContainerStats> stats = collector.collect(containerId, containerPid, "eth0");
assertTrue(stats.isPresent());
assertEquals(new ContainerStats.CpuStats(24, 6049374780000L, 691675615472L,
- 262190000000L, 3L, 1L, 2L),
- stats.get().getCpuStats());
+ 262190000000L, 3L, 1L, 2L),
+ stats.get().getCpuStats());
assertEquals(new ContainerStats.MemoryStats(470790144L, 1228017664L, 2147483648L),
- stats.get().getMemoryStats());
+ stats.get().getMemoryStats());
assertEquals(Map.of("eth0", new ContainerStats.NetworkStats(22280813L, 4L, 3L,
- 19859383L, 6L, 5L)),
- stats.get().getNetworks());
+ 19859383L, 6L, 5L)),
+ stats.get().getNetworks());
}
private void mockNetworkStats(int pid) {
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/image/ContainerImageDownloaderTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/image/ContainerImageDownloaderTest.java
index 7db8cb79949..9fd14e7e665 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/image/ContainerImageDownloaderTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/image/ContainerImageDownloaderTest.java
@@ -6,29 +6,31 @@ import com.yahoo.vespa.hosted.node.admin.component.TaskContext;
import com.yahoo.vespa.hosted.node.admin.component.TestTaskContext;
import com.yahoo.vespa.hosted.node.admin.container.ContainerEngineMock;
import com.yahoo.vespa.hosted.node.admin.container.RegistryCredentials;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
-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 mpolden
*/
public class ContainerImageDownloaderTest {
- @Test(timeout = 5_000)
- public void test_download() {
+ @Test
+ @Timeout(5_000)
+ void test_download() {
ContainerEngineMock podman = new ContainerEngineMock().asyncImageDownload(true);
ContainerImageDownloader downloader = new ContainerImageDownloader(podman);
TaskContext context = new TestTaskContext();
DockerImage image = DockerImage.fromString("registry.example.com/repo/vespa:7.42");
- assertFalse("Download started", downloader.get(context, image, RegistryCredentials.none));
- assertFalse("Download pending", downloader.get(context, image, RegistryCredentials.none));
+ assertFalse(downloader.get(context, image, RegistryCredentials.none), "Download started");
+ assertFalse(downloader.get(context, image, RegistryCredentials.none), "Download pending");
podman.completeDownloadOf(image);
boolean downloadCompleted;
- while (!(downloadCompleted = downloader.get(context, image, RegistryCredentials.none)));
- assertTrue("Download completed", downloadCompleted);
+ while (!(downloadCompleted = downloader.get(context, image, RegistryCredentials.none))) ;
+ assertTrue(downloadCompleted, "Download completed");
}
}
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/image/ContainerImagePrunerTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/image/ContainerImagePrunerTest.java
index a7307b5d1de..2ef6780dff6 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/image/ContainerImagePrunerTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/image/ContainerImagePrunerTest.java
@@ -10,7 +10,7 @@ import com.yahoo.vespa.hosted.node.admin.container.ContainerEngineMock;
import com.yahoo.vespa.hosted.node.admin.container.ContainerId;
import com.yahoo.vespa.hosted.node.admin.container.ContainerName;
import com.yahoo.vespa.hosted.node.admin.container.ContainerResources;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.Instant;
@@ -18,7 +18,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author freva
@@ -29,90 +29,90 @@ public class ContainerImagePrunerTest {
private final Tester tester = new Tester();
@Test
- public void noImagesMeansNoUnusedImages() {
+ void noImagesMeansNoUnusedImages() {
tester.withExistingImages()
- .expectDeletedImages();
+ .expectDeletedImages();
}
@Test
- public void singleImageWithoutContainersIsUnused() {
+ void singleImageWithoutContainersIsUnused() {
tester.withExistingImages(image("image-1"))
- // Even though nothing is using the image, we will keep it for at least 1h
- .expectDeletedImagesAfterMinutes(0)
- .expectDeletedImagesAfterMinutes(30)
- .expectDeletedImagesAfterMinutes(30, "image-1");
+ // Even though nothing is using the image, we will keep it for at least 1h
+ .expectDeletedImagesAfterMinutes(0)
+ .expectDeletedImagesAfterMinutes(30)
+ .expectDeletedImagesAfterMinutes(30, "image-1");
}
@Test
- public void singleImageWithContainerIsUsed() {
+ void singleImageWithContainerIsUsed() {
tester.withExistingImages(image("image-1"))
- .withExistingContainers(container("container-1", "image-1"))
- .expectDeletedImages();
+ .withExistingContainers(container("container-1", "image-1"))
+ .expectDeletedImages();
}
@Test
- public void multipleUnusedImagesAreIdentified() {
+ void multipleUnusedImagesAreIdentified() {
tester.withExistingImages(image("image-1"), image("image-2"))
- .expectDeletedImages("image-1", "image-2");
+ .expectDeletedImages("image-1", "image-2");
}
@Test
- public void unusedImagesWithMultipleTags() {
+ void unusedImagesWithMultipleTags() {
tester.withExistingImages(image("image-1", "vespa-6", "vespa-6.28", "vespa:latest"))
- .expectDeletedImages("vespa-6", "vespa-6.28", "vespa:latest");
+ .expectDeletedImages("vespa-6", "vespa-6.28", "vespa:latest");
}
@Test
- public void unusedImagesWithMultipleUntagged() {
+ void unusedImagesWithMultipleUntagged() {
tester.withExistingImages(image("image1", "<none>:<none>"),
- image("image2", "<none>:<none>"))
- .expectDeletedImages("image1", "image2");
+ image("image2", "<none>:<none>"))
+ .expectDeletedImages("image1", "image2");
}
@Test
- public void taggedImageWithNoContainersIsUnused() {
+ void taggedImageWithNoContainersIsUnused() {
tester.withExistingImages(image("image-1", "vespa-6"))
- .expectDeletedImages("vespa-6");
+ .expectDeletedImages("vespa-6");
}
@Test
- public void reDownloadingImageIsNotImmediatelyDeleted() {
+ void reDownloadingImageIsNotImmediatelyDeleted() {
tester.withExistingImages(image("image"))
- .expectDeletedImages("image") // After 1h we delete image
- .expectDeletedImagesAfterMinutes(0) // image is immediately re-downloaded, but is not deleted
- .expectDeletedImagesAfterMinutes(10)
- .expectDeletedImages("image"); // 1h after re-download it is deleted again
+ .expectDeletedImages("image") // After 1h we delete image
+ .expectDeletedImagesAfterMinutes(0) // image is immediately re-downloaded, but is not deleted
+ .expectDeletedImagesAfterMinutes(10)
+ .expectDeletedImages("image"); // 1h after re-download it is deleted again
}
@Test
- public void reDownloadingImageIsNotImmediatelyDeletedWhenDeletingByTag() {
+ void reDownloadingImageIsNotImmediatelyDeletedWhenDeletingByTag() {
tester.withExistingImages(image("image", "my-tag"))
- .expectDeletedImages("my-tag") // After 1h we delete image
- .expectDeletedImagesAfterMinutes(0) // image is immediately re-downloaded, but is not deleted
- .expectDeletedImagesAfterMinutes(10)
- .expectDeletedImages("my-tag"); // 1h after re-download it is deleted again
+ .expectDeletedImages("my-tag") // After 1h we delete image
+ .expectDeletedImagesAfterMinutes(0) // image is immediately re-downloaded, but is not deleted
+ .expectDeletedImagesAfterMinutes(10)
+ .expectDeletedImages("my-tag"); // 1h after re-download it is deleted again
}
/** Same scenario as in {@link #multipleUnusedImagesAreIdentified()} */
@Test
- public void doesNotDeleteExcludedByIdImages() {
+ void doesNotDeleteExcludedByIdImages() {
tester.withExistingImages(image("image-1"), image("image-2"))
- // Normally, image-1 should also be deleted, but because we exclude image-1 only image-2 is deleted
- .expectDeletedImages(List.of("image-1"), "image-2");
+ // Normally, image-1 should also be deleted, but because we exclude image-1 only image-2 is deleted
+ .expectDeletedImages(List.of("image-1"), "image-2");
}
/** Same as in {@link #doesNotDeleteExcludedByIdImages()} but with tags */
@Test
- public void doesNotDeleteExcludedByTagImages() {
+ void doesNotDeleteExcludedByTagImages() {
tester.withExistingImages(image("image-1", "vespa:6.288.16"), image("image-2", "vespa:6.289.94"))
- .expectDeletedImages(List.of("vespa:6.288.16"), "vespa:6.289.94");
+ .expectDeletedImages(List.of("vespa:6.288.16"), "vespa:6.289.94");
}
@Test
- public void excludingNotDownloadedImageIsNoop() {
+ void excludingNotDownloadedImageIsNoop() {
tester.withExistingImages(image("image-1", "vespa:6.288.16"),
- image("image-2", "vespa:6.289.94"))
- .expectDeletedImages(List.of("vespa:6.300.1"), "vespa:6.288.16", "vespa:6.289.94", "rhel-6");
+ image("image-2", "vespa:6.289.94"))
+ .expectDeletedImages(List.of("vespa:6.300.1"), "vespa:6.288.16", "vespa:6.289.94", "rhel-6");
}
private static Image image(String id, String... tags) {
@@ -174,8 +174,8 @@ public class ContainerImagePrunerTest {
int newValue = removalCountByImageId.getOrDefault(imageId, 0) + 1;
removalCountByImageId.put(imageId, newValue);
- assertTrue("Image " + imageId + " removed",
- containerEngine.listImages(context).stream().noneMatch(image -> image.id().equals(imageId)));
+ assertTrue(containerEngine.listImages(context).stream().noneMatch(image -> image.id().equals(imageId)),
+ "Image " + imageId + " removed");
});
return this;
}
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/metrics/MetricsTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/metrics/MetricsTest.java
index c7f7058d4f5..3de3c1a3d32 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/metrics/MetricsTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/container/metrics/MetricsTest.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.hosted.node.admin.container.metrics;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Map;
import java.util.stream.Collectors;
import static com.yahoo.vespa.hosted.node.admin.container.metrics.Metrics.APPLICATION_HOST;
import static com.yahoo.vespa.hosted.node.admin.container.metrics.Metrics.DimensionType.DEFAULT;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author freva
@@ -18,38 +18,38 @@ public class MetricsTest {
private final Metrics metrics = new Metrics();
@Test
- public void testDefaultValue() {
+ void testDefaultValue() {
metrics.declareCounter("some.name", hostDimension);
assertEquals(getMetricsForDimension(hostDimension).get("some.name"), 0L);
}
@Test
- public void testSimpleIncrementMetric() {
+ void testSimpleIncrementMetric() {
Counter counter = metrics.declareCounter("a_counter.value", hostDimension);
counter.add(5);
counter.add(8);
Map<String, Number> latestMetrics = getMetricsForDimension(hostDimension);
- assertEquals("Expected only 1 metric value to be set", 1, latestMetrics.size());
+ assertEquals(1, latestMetrics.size(), "Expected only 1 metric value to be set");
assertEquals(latestMetrics.get("a_counter.value"), 13L); // 5 + 8
}
@Test
- public void testSimpleGauge() {
+ void testSimpleGauge() {
Gauge gauge = metrics.declareGauge("test.gauge", hostDimension);
gauge.sample(42);
gauge.sample(-342.23);
Map<String, Number> latestMetrics = getMetricsForDimension(hostDimension);
- assertEquals("Expected only 1 metric value to be set", 1, latestMetrics.size());
+ assertEquals(1, latestMetrics.size(), "Expected only 1 metric value to be set");
assertEquals(latestMetrics.get("test.gauge"), -342.23);
}
@Test
- public void testRedeclaringSameGauge() {
+ void testRedeclaringSameGauge() {
Gauge gauge = metrics.declareGauge("test.gauge", hostDimension);
gauge.sample(42);
@@ -62,7 +62,7 @@ public class MetricsTest {
}
@Test
- public void testSameMetricNameButDifferentDimensions() {
+ void testSameMetricNameButDifferentDimensions() {
Gauge gauge = metrics.declareGauge("test.gauge", hostDimension);
gauge.sample(42);
@@ -76,7 +76,7 @@ public class MetricsTest {
}
@Test
- public void testDeletingMetric() {
+ void testDeletingMetric() {
metrics.declareGauge("test.gauge", hostDimension);
Dimensions differentDimension = new Dimensions.Builder().add("host", "abcd.yahoo.com").build();
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/ContainerFailTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/ContainerFailTest.java
index c22f2b0ab50..0edc03cc33e 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/ContainerFailTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/ContainerFailTest.java
@@ -7,7 +7,7 @@ import com.yahoo.vespa.hosted.node.admin.container.ContainerName;
import com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentContext;
import com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentContextImpl;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
@@ -22,7 +22,7 @@ import static org.mockito.Mockito.verify;
public class ContainerFailTest {
@Test
- public void test() {
+ void test() {
DockerImage dockerImage = DockerImage.fromString("registry.example.com/repo/image");
try (ContainerTester tester = new ContainerTester(List.of(dockerImage))) {
ContainerName containerName = new ContainerName("host1");
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/MultiContainerTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/MultiContainerTest.java
index eab320733ee..8a5c4faeddc 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/MultiContainerTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/MultiContainerTest.java
@@ -6,7 +6,7 @@ import com.yahoo.vespa.hosted.node.admin.configserver.noderepository.NodeSpec;
import com.yahoo.vespa.hosted.node.admin.configserver.noderepository.NodeState;
import com.yahoo.vespa.hosted.node.admin.container.ContainerName;
import com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentContext;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
@@ -20,7 +20,7 @@ import static org.mockito.ArgumentMatchers.eq;
public class MultiContainerTest {
@Test
- public void test() {
+ void test() {
DockerImage image1 = DockerImage.fromString("registry.example.com/repo/image1");
DockerImage image2 = DockerImage.fromString("registry.example.com/repo/image2");
try (ContainerTester tester = new ContainerTester(List.of(image1, image2))) {
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/RebootTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/RebootTest.java
index 8498fa57084..0a405cd38b2 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/RebootTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/RebootTest.java
@@ -5,13 +5,13 @@ import com.yahoo.config.provision.DockerImage;
import com.yahoo.vespa.hosted.node.admin.configserver.noderepository.NodeSpec;
import com.yahoo.vespa.hosted.node.admin.container.ContainerName;
import com.yahoo.vespa.hosted.node.admin.nodeadmin.NodeAdminStateUpdater;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import static com.yahoo.vespa.hosted.node.admin.integration.ContainerTester.HOST_HOSTNAME;
import static com.yahoo.vespa.hosted.node.admin.integration.ContainerTester.containerMatcher;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
@@ -26,7 +26,7 @@ public class RebootTest {
private final DockerImage dockerImage = DockerImage.fromString("registry.example.com/repo/image");
@Test
- public void test() {
+ void test() {
try (ContainerTester tester = new ContainerTester(List.of(dockerImage))) {
tester.addChildNodeRepositoryNode(NodeSpec.Builder.testSpec(hostname).wantedDockerImage(dockerImage).build());
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/RestartTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/RestartTest.java
index 9a481959c63..62bde5ff1a8 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/RestartTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/integration/RestartTest.java
@@ -5,7 +5,7 @@ import com.yahoo.config.provision.DockerImage;
import com.yahoo.vespa.hosted.node.admin.configserver.noderepository.NodeAttributes;
import com.yahoo.vespa.hosted.node.admin.configserver.noderepository.NodeSpec;
import com.yahoo.vespa.hosted.node.admin.container.ContainerName;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
@@ -21,7 +21,7 @@ import static org.mockito.ArgumentMatchers.eq;
public class RestartTest {
@Test
- public void test() {
+ void test() {
DockerImage dockerImage = DockerImage.fromString("registry.example.com/repo/image:1.2.3");
try (ContainerTester tester = new ContainerTester(List.of(dockerImage))) {
String hostname = "host1.test.yahoo.com";
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/StorageMaintainerTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/StorageMaintainerTest.java
index 42661bdfdd0..d98ca5d84f2 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/StorageMaintainerTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/StorageMaintainerTest.java
@@ -14,8 +14,8 @@ import com.yahoo.vespa.hosted.node.admin.task.util.file.FileFinder;
import com.yahoo.vespa.hosted.node.admin.task.util.fs.ContainerPath;
import com.yahoo.vespa.hosted.node.admin.task.util.process.TestTerminal;
import com.yahoo.vespa.test.file.TestFileSystem;
-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.nio.file.FileSystem;
@@ -29,7 +29,7 @@ import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
@@ -51,7 +51,7 @@ public class StorageMaintainerTest {
fileSystem.getPath("/data/vespa/storage/container-archive"));
@Test
- public void testDiskUsed() {
+ void testDiskUsed() {
NodeAgentContext context = NodeAgentContextImpl.builder("host-1.domain.tld").fileSystem(fileSystem).build();
terminal.expectCommand("du -xsk /data/vespa/storage/host-1 2>&1", 0, "321\t/data/vespa/storage/host-1/");
@@ -62,13 +62,13 @@ public class StorageMaintainerTest {
}
@Test
- public void testNonExistingDiskUsed() {
+ void testNonExistingDiskUsed() {
DiskSize size = storageMaintainer.getDiskUsed(null, Paths.get("/fake/path"));
assertEquals(DiskSize.ZERO, size);
}
@Test
- public void archive_container_data_test() throws IOException {
+ void archive_container_data_test() throws IOException {
// Create some files in containers
NodeAgentContext context1 = createNodeAgentContextAndContainerStorage(fileSystem, "container-1");
createNodeAgentContextAndContainerStorage(fileSystem, "container-2");
@@ -141,7 +141,7 @@ public class StorageMaintainerTest {
}
@Test
- public void not_run_if_not_enough_used() throws IOException {
+ void not_run_if_not_enough_used() throws IOException {
NodeAgentContext context = NodeAgentContextImpl.builder(
NodeSpec.Builder.testSpec("h123a.domain.tld").realResources(new NodeResources(1, 1, 1, 1)).build())
.fileSystem(fileSystem).build();
@@ -152,7 +152,7 @@ public class StorageMaintainerTest {
}
@Test
- public void deletes_correct_amount() throws IOException {
+ void deletes_correct_amount() throws IOException {
NodeAgentContext context = NodeAgentContextImpl.builder(
NodeSpec.Builder.testSpec("h123a.domain.tld").realResources(new NodeResources(1, 1, 1, 1)).build())
.fileSystem(fileSystem).build();
@@ -164,7 +164,7 @@ public class StorageMaintainerTest {
verify(diskCleanup).cleanup(eq(context), any(), eq(272_800_000L));
}
- @After
+ @AfterEach
public void after() {
terminal.verifyAllCommandsExecuted();
}
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/acl/AclMaintainerTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/acl/AclMaintainerTest.java
index 80fde82a89f..6b2ac98ad0b 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/acl/AclMaintainerTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/acl/AclMaintainerTest.java
@@ -10,15 +10,15 @@ import com.yahoo.vespa.hosted.node.admin.task.util.network.IPAddressesMock;
import com.yahoo.vespa.hosted.node.admin.task.util.network.IPVersion;
import com.yahoo.vespa.hosted.node.admin.task.util.process.CommandResult;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.nio.file.FileSystem;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.endsWith;
import static org.mockito.ArgumentMatchers.eq;
@@ -45,7 +45,7 @@ public class AclMaintainerTest {
private final List<String> writtenFileContents = new ArrayList<>();
@Test
- public void configures_full_container_acl_from_empty() {
+ void configures_full_container_acl_from_empty() {
Acl acl = new Acl.Builder().withTrustedPorts(22, 4443)
.withTrustedNode("hostname1", "3001::abcd")
.withTrustedNode("hostname2", "3001::1234")
@@ -71,54 +71,54 @@ public class AclMaintainerTest {
List<String> expected = List.of(
// IPv4 filter table restore
"*filter\n" +
- "-P INPUT ACCEPT\n" +
- "-P FORWARD ACCEPT\n" +
- "-P OUTPUT ACCEPT\n" +
- "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT\n" +
- "-A INPUT -i lo -j ACCEPT\n" +
- "-A INPUT -p icmp -j ACCEPT\n" +
- "-A INPUT -p tcp -m multiport --dports 22,4443 -j ACCEPT\n" +
- "-A INPUT -s 172.16.5.234/32 -j ACCEPT\n" +
- "-A INPUT -s 192.168.0.5/32 -j ACCEPT\n" +
- "-A INPUT -j REJECT --reject-with icmp-port-unreachable\n" +
- "COMMIT\n",
+ "-P INPUT ACCEPT\n" +
+ "-P FORWARD ACCEPT\n" +
+ "-P OUTPUT ACCEPT\n" +
+ "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT\n" +
+ "-A INPUT -i lo -j ACCEPT\n" +
+ "-A INPUT -p icmp -j ACCEPT\n" +
+ "-A INPUT -p tcp -m multiport --dports 22,4443 -j ACCEPT\n" +
+ "-A INPUT -s 172.16.5.234/32 -j ACCEPT\n" +
+ "-A INPUT -s 192.168.0.5/32 -j ACCEPT\n" +
+ "-A INPUT -j REJECT --reject-with icmp-port-unreachable\n" +
+ "COMMIT\n",
// IPv6 filter table restore
"*filter\n" +
- "-P INPUT ACCEPT\n" +
- "-P FORWARD ACCEPT\n" +
- "-P OUTPUT ACCEPT\n" +
- "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT\n" +
- "-A INPUT -i lo -j ACCEPT\n" +
- "-A INPUT -p ipv6-icmp -j ACCEPT\n" +
- "-A INPUT -p tcp -m multiport --dports 22,4443 -j ACCEPT\n" +
- "-A INPUT -s 3001::1234/128 -j ACCEPT\n" +
- "-A INPUT -s 3001::abcd/128 -j ACCEPT\n" +
- "-A INPUT -j REJECT --reject-with icmp6-port-unreachable\n" +
- "COMMIT\n",
+ "-P INPUT ACCEPT\n" +
+ "-P FORWARD ACCEPT\n" +
+ "-P OUTPUT ACCEPT\n" +
+ "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT\n" +
+ "-A INPUT -i lo -j ACCEPT\n" +
+ "-A INPUT -p ipv6-icmp -j ACCEPT\n" +
+ "-A INPUT -p tcp -m multiport --dports 22,4443 -j ACCEPT\n" +
+ "-A INPUT -s 3001::1234/128 -j ACCEPT\n" +
+ "-A INPUT -s 3001::abcd/128 -j ACCEPT\n" +
+ "-A INPUT -j REJECT --reject-with icmp6-port-unreachable\n" +
+ "COMMIT\n",
// IPv4 nat table restore
"*nat\n" +
- "-P PREROUTING ACCEPT\n" +
- "-P INPUT ACCEPT\n" +
- "-P OUTPUT ACCEPT\n" +
- "-P POSTROUTING ACCEPT\n" +
- "-A OUTPUT -d 10.0.0.1/32 -j REDIRECT\n" +
- "COMMIT\n",
+ "-P PREROUTING ACCEPT\n" +
+ "-P INPUT ACCEPT\n" +
+ "-P OUTPUT ACCEPT\n" +
+ "-P POSTROUTING ACCEPT\n" +
+ "-A OUTPUT -d 10.0.0.1/32 -j REDIRECT\n" +
+ "COMMIT\n",
// IPv6 nat table restore
"*nat\n" +
- "-P PREROUTING ACCEPT\n" +
- "-P INPUT ACCEPT\n" +
- "-P OUTPUT ACCEPT\n" +
- "-P POSTROUTING ACCEPT\n" +
- "-A OUTPUT -d 2001::1/128 -j REDIRECT\n" +
- "COMMIT\n");
+ "-P PREROUTING ACCEPT\n" +
+ "-P INPUT ACCEPT\n" +
+ "-P OUTPUT ACCEPT\n" +
+ "-P POSTROUTING ACCEPT\n" +
+ "-A OUTPUT -d 2001::1/128 -j REDIRECT\n" +
+ "COMMIT\n");
assertEquals(expected, writtenFileContents);
}
@Test
- public void configures_minimal_container_acl_from_empty() {
+ void configures_minimal_container_acl_from_empty() {
// The ACL spec is empty and our this node's addresses do not resolve
Acl acl = new Acl.Builder().withTrustedPorts().build();
NodeAgentContext context = contextGenerator.apply(acl);
@@ -138,30 +138,30 @@ public class AclMaintainerTest {
List<String> expected = List.of(
// IPv4 filter table restore
"*filter\n" +
- "-P INPUT ACCEPT\n" +
- "-P FORWARD ACCEPT\n" +
- "-P OUTPUT ACCEPT\n" +
- "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT\n" +
- "-A INPUT -i lo -j ACCEPT\n" +
- "-A INPUT -p icmp -j ACCEPT\n" +
- "-A INPUT -j REJECT --reject-with icmp-port-unreachable\n" +
- "COMMIT\n",
+ "-P INPUT ACCEPT\n" +
+ "-P FORWARD ACCEPT\n" +
+ "-P OUTPUT ACCEPT\n" +
+ "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT\n" +
+ "-A INPUT -i lo -j ACCEPT\n" +
+ "-A INPUT -p icmp -j ACCEPT\n" +
+ "-A INPUT -j REJECT --reject-with icmp-port-unreachable\n" +
+ "COMMIT\n",
// IPv6 filter table restore
"*filter\n" +
- "-P INPUT ACCEPT\n" +
- "-P FORWARD ACCEPT\n" +
- "-P OUTPUT ACCEPT\n" +
- "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT\n" +
- "-A INPUT -i lo -j ACCEPT\n" +
- "-A INPUT -p ipv6-icmp -j ACCEPT\n" +
- "-A INPUT -j REJECT --reject-with icmp6-port-unreachable\n" +
- "COMMIT\n");
+ "-P INPUT ACCEPT\n" +
+ "-P FORWARD ACCEPT\n" +
+ "-P OUTPUT ACCEPT\n" +
+ "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT\n" +
+ "-A INPUT -i lo -j ACCEPT\n" +
+ "-A INPUT -p ipv6-icmp -j ACCEPT\n" +
+ "-A INPUT -j REJECT --reject-with icmp6-port-unreachable\n" +
+ "COMMIT\n");
assertEquals(expected, writtenFileContents);
}
@Test
- public void only_configure_iptables_for_ipversion_that_differs() {
+ void only_configure_iptables_for_ipversion_that_differs() {
Acl acl = new Acl.Builder().withTrustedPorts(22, 4443).withTrustedNode("hostname1", "3001::abcd").build();
NodeAgentContext context = contextGenerator.apply(acl);
@@ -170,20 +170,20 @@ public class AclMaintainerTest {
whenListRules(context, "filter", IPVersion.IPv4, EMPTY_FILTER_TABLE);
whenListRules(context, "filter", IPVersion.IPv6,
"-P INPUT ACCEPT\n" +
- "-P FORWARD ACCEPT\n" +
- "-P OUTPUT ACCEPT\n" +
- "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT\n" +
- "-A INPUT -i lo -j ACCEPT\n" +
- "-A INPUT -p ipv6-icmp -j ACCEPT\n" +
- "-A INPUT -p tcp -m multiport --dports 22,4443 -j ACCEPT\n" +
- "-A INPUT -s 3001::abcd/128 -j ACCEPT\n" +
- "-A INPUT -j REJECT --reject-with icmp6-port-unreachable\n");
+ "-P FORWARD ACCEPT\n" +
+ "-P OUTPUT ACCEPT\n" +
+ "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT\n" +
+ "-A INPUT -i lo -j ACCEPT\n" +
+ "-A INPUT -p ipv6-icmp -j ACCEPT\n" +
+ "-A INPUT -p tcp -m multiport --dports 22,4443 -j ACCEPT\n" +
+ "-A INPUT -s 3001::abcd/128 -j ACCEPT\n" +
+ "-A INPUT -j REJECT --reject-with icmp6-port-unreachable\n");
whenListRules(context, "nat", IPVersion.IPv6,
"-P PREROUTING ACCEPT\n" +
- "-P INPUT ACCEPT\n" +
- "-P OUTPUT ACCEPT\n" +
- "-P POSTROUTING ACCEPT\n" +
- "-A OUTPUT -d 2001::1/128 -j REDIRECT\n");
+ "-P INPUT ACCEPT\n" +
+ "-P OUTPUT ACCEPT\n" +
+ "-P POSTROUTING ACCEPT\n" +
+ "-A OUTPUT -d 2001::1/128 -j REDIRECT\n");
aclMaintainer.converge(context);
@@ -194,20 +194,20 @@ public class AclMaintainerTest {
List<String> expected = List.of(
"*filter\n" +
- "-P INPUT ACCEPT\n" +
- "-P FORWARD ACCEPT\n" +
- "-P OUTPUT ACCEPT\n" +
- "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT\n" +
- "-A INPUT -i lo -j ACCEPT\n" +
- "-A INPUT -p icmp -j ACCEPT\n" +
- "-A INPUT -p tcp -m multiport --dports 22,4443 -j ACCEPT\n" +
- "-A INPUT -j REJECT --reject-with icmp-port-unreachable\n" +
- "COMMIT\n");
+ "-P INPUT ACCEPT\n" +
+ "-P FORWARD ACCEPT\n" +
+ "-P OUTPUT ACCEPT\n" +
+ "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT\n" +
+ "-A INPUT -i lo -j ACCEPT\n" +
+ "-A INPUT -p icmp -j ACCEPT\n" +
+ "-A INPUT -p tcp -m multiport --dports 22,4443 -j ACCEPT\n" +
+ "-A INPUT -j REJECT --reject-with icmp-port-unreachable\n" +
+ "COMMIT\n");
assertEquals(expected, writtenFileContents);
}
@Test
- public void rollback_is_attempted_when_applying_acl_fail() {
+ void rollback_is_attempted_when_applying_acl_fail() {
Acl acl = new Acl.Builder().withTrustedPorts(22, 4443).withTrustedNode("hostname1", "3001::abcd").build();
NodeAgentContext context = contextGenerator.apply(acl);
@@ -216,20 +216,20 @@ public class AclMaintainerTest {
whenListRules(context, "filter", IPVersion.IPv4, EMPTY_FILTER_TABLE);
whenListRules(context, "filter", IPVersion.IPv6,
"-P INPUT ACCEPT\n" +
- "-P FORWARD ACCEPT\n" +
- "-P OUTPUT ACCEPT\n" +
- "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT\n" +
- "-A INPUT -i lo -j ACCEPT\n" +
- "-A INPUT -p ipv6-icmp -j ACCEPT\n" +
- "-A INPUT -p tcp -m multiport --dports 22,4443 -j ACCEPT\n" +
- "-A INPUT -s 3001::abcd/128 -j ACCEPT\n" +
- "-A INPUT -j REJECT --reject-with icmp6-port-unreachable\n");
+ "-P FORWARD ACCEPT\n" +
+ "-P OUTPUT ACCEPT\n" +
+ "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT\n" +
+ "-A INPUT -i lo -j ACCEPT\n" +
+ "-A INPUT -p ipv6-icmp -j ACCEPT\n" +
+ "-A INPUT -p tcp -m multiport --dports 22,4443 -j ACCEPT\n" +
+ "-A INPUT -s 3001::abcd/128 -j ACCEPT\n" +
+ "-A INPUT -j REJECT --reject-with icmp6-port-unreachable\n");
whenListRules(context, "nat", IPVersion.IPv6,
"-P PREROUTING ACCEPT\n" +
- "-P INPUT ACCEPT\n" +
- "-P OUTPUT ACCEPT\n" +
- "-P POSTROUTING ACCEPT\n" +
- "-A OUTPUT -d 2001::1/128 -j REDIRECT\n");
+ "-P INPUT ACCEPT\n" +
+ "-P OUTPUT ACCEPT\n" +
+ "-P POSTROUTING ACCEPT\n" +
+ "-A OUTPUT -d 2001::1/128 -j REDIRECT\n");
when(containerOperations.executeCommandInNetworkNamespace(eq(context), eq("iptables-restore"), any()))
.thenThrow(new RuntimeException("iptables restore failed"));
@@ -244,7 +244,7 @@ public class AclMaintainerTest {
aclMaintainer.converge(context);
}
- @Before
+ @BeforeEach
public void setup() {
doAnswer(invoc -> {
String path = invoc.getArgument(2);
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/acl/FilterTableLineEditorTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/acl/FilterTableLineEditorTest.java
index 6aa3a0420ff..6cd4038975b 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/acl/FilterTableLineEditorTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/acl/FilterTableLineEditorTest.java
@@ -4,12 +4,12 @@ package com.yahoo.vespa.hosted.node.admin.maintenance.acl;
import com.yahoo.vespa.hosted.node.admin.configserver.noderepository.Acl;
import com.yahoo.vespa.hosted.node.admin.task.util.file.Editor;
import com.yahoo.vespa.hosted.node.admin.task.util.network.IPVersion;
-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.jupiter.api.Assertions.assertEquals;
/**
* @author freva
@@ -17,44 +17,44 @@ import static org.junit.Assert.assertEquals;
public class FilterTableLineEditorTest {
@Test
- public void filter_set_wanted_rules() {
+ void filter_set_wanted_rules() {
Acl acl = new Acl.Builder().withTrustedPorts(22).withTrustedNode("hostname", "3001::1").build();
assertFilterTableLineEditorResult(
acl, IPVersion.IPv6,
"-P INPUT ACCEPT\n" +
- "-P FORWARD ACCEPT\n" +
- "-P OUTPUT ACCEPT\n",
+ "-P FORWARD ACCEPT\n" +
+ "-P OUTPUT ACCEPT\n",
"-P INPUT ACCEPT\n" +
- "-P FORWARD ACCEPT\n" +
- "-P OUTPUT ACCEPT\n" +
- "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT\n" +
- "-A INPUT -i lo -j ACCEPT\n" +
- "-A INPUT -p ipv6-icmp -j ACCEPT\n" +
- "-A INPUT -p tcp -m multiport --dports 22 -j ACCEPT\n" +
- "-A INPUT -s 3001::1/128 -j ACCEPT\n" +
- "-A INPUT -j REJECT --reject-with icmp6-port-unreachable");
+ "-P FORWARD ACCEPT\n" +
+ "-P OUTPUT ACCEPT\n" +
+ "-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT\n" +
+ "-A INPUT -i lo -j ACCEPT\n" +
+ "-A INPUT -p ipv6-icmp -j ACCEPT\n" +
+ "-A INPUT -p tcp -m multiport --dports 22 -j ACCEPT\n" +
+ "-A INPUT -s 3001::1/128 -j ACCEPT\n" +
+ "-A INPUT -j REJECT --reject-with icmp6-port-unreachable");
}
@Test
- public void produces_minimal_diff_simple() {
+ void produces_minimal_diff_simple() {
assertFilterTableDiff(List.of(2, 5, 3, 6, 1, 4), List.of(2, 5, 6, 1, 4),
"Patching file table:\n" +
- "--A INPUT -s 2001::3/128 -j ACCEPT\n");
+ "--A INPUT -s 2001::3/128 -j ACCEPT\n");
}
@Test
- public void produces_minimal_diff_complex() {
+ void produces_minimal_diff_complex() {
assertFilterTableDiff(List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), List.of(5, 11, 6, 3, 10, 4, 8, 12),
"Patching file table:\n" +
- "--A INPUT -s 2001::1/128 -j ACCEPT\n" +
- "--A INPUT -s 2001::2/128 -j ACCEPT\n" +
- "+-A INPUT -s 2001::11/128 -j ACCEPT\n" +
- "+-A INPUT -s 2001::12/128 -j ACCEPT\n" +
- "--A INPUT -s 2001::7/128 -j ACCEPT\n" +
- "--A INPUT -s 2001::9/128 -j ACCEPT\n");
+ "--A INPUT -s 2001::1/128 -j ACCEPT\n" +
+ "--A INPUT -s 2001::2/128 -j ACCEPT\n" +
+ "+-A INPUT -s 2001::11/128 -j ACCEPT\n" +
+ "+-A INPUT -s 2001::12/128 -j ACCEPT\n" +
+ "--A INPUT -s 2001::7/128 -j ACCEPT\n" +
+ "--A INPUT -s 2001::9/128 -j ACCEPT\n");
}
private static void assertFilterTableLineEditorResult(
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/acl/NatTableLineEditorTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/acl/NatTableLineEditorTest.java
index 015181c7ca4..999b7bda9bb 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/acl/NatTableLineEditorTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/acl/NatTableLineEditorTest.java
@@ -2,11 +2,11 @@
package com.yahoo.vespa.hosted.node.admin.maintenance.acl;
import com.yahoo.vespa.hosted.node.admin.task.util.file.Editor;
-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 freva
@@ -14,74 +14,74 @@ import static org.junit.Assert.assertEquals;
public class NatTableLineEditorTest {
@Test
- public void nat_set_redirect_rule_without_touching_docker_rules() {
+ void nat_set_redirect_rule_without_touching_docker_rules() {
assertNatTableLineEditorResult(
"-A OUTPUT -d 3001::1/128 -j REDIRECT",
"-P PREROUTING ACCEPT\n" +
- "-P INPUT ACCEPT\n" +
- "-P OUTPUT ACCEPT\n" +
- "-P POSTROUTING ACCEPT\n" +
- "-N DOCKER_OUTPUT\n" +
- "-N DOCKER_POSTROUTING\n" +
- "-A OUTPUT -d 127.0.0.11/32 -j DOCKER_OUTPUT\n" +
- "-A POSTROUTING -d 127.0.0.11/32 -j DOCKER_POSTROUTING\n" +
- "-A DOCKER_OUTPUT -d 127.0.0.11/32 -p tcp -m tcp --dport 53 -j DNAT --to-destination 127.0.0.11:43500\n" +
- "-A DOCKER_OUTPUT -d 127.0.0.11/32 -p udp -m udp --dport 53 -j DNAT --to-destination 127.0.0.11:57392\n" +
- "-A DOCKER_POSTROUTING -s 127.0.0.11/32 -p tcp -m tcp --sport 43500 -j SNAT --to-source :53\n" +
- "-A DOCKER_POSTROUTING -s 127.0.0.11/32 -p udp -m udp --sport 57392 -j SNAT --to-source :53\n",
+ "-P INPUT ACCEPT\n" +
+ "-P OUTPUT ACCEPT\n" +
+ "-P POSTROUTING ACCEPT\n" +
+ "-N DOCKER_OUTPUT\n" +
+ "-N DOCKER_POSTROUTING\n" +
+ "-A OUTPUT -d 127.0.0.11/32 -j DOCKER_OUTPUT\n" +
+ "-A POSTROUTING -d 127.0.0.11/32 -j DOCKER_POSTROUTING\n" +
+ "-A DOCKER_OUTPUT -d 127.0.0.11/32 -p tcp -m tcp --dport 53 -j DNAT --to-destination 127.0.0.11:43500\n" +
+ "-A DOCKER_OUTPUT -d 127.0.0.11/32 -p udp -m udp --dport 53 -j DNAT --to-destination 127.0.0.11:57392\n" +
+ "-A DOCKER_POSTROUTING -s 127.0.0.11/32 -p tcp -m tcp --sport 43500 -j SNAT --to-source :53\n" +
+ "-A DOCKER_POSTROUTING -s 127.0.0.11/32 -p udp -m udp --sport 57392 -j SNAT --to-source :53\n",
"-P PREROUTING ACCEPT\n" +
- "-P INPUT ACCEPT\n" +
- "-P OUTPUT ACCEPT\n" +
- "-P POSTROUTING ACCEPT\n" +
- "-N DOCKER_OUTPUT\n" +
- "-N DOCKER_POSTROUTING\n" +
- "-A OUTPUT -d 127.0.0.11/32 -j DOCKER_OUTPUT\n" +
- "-A POSTROUTING -d 127.0.0.11/32 -j DOCKER_POSTROUTING\n" +
- "-A DOCKER_OUTPUT -d 127.0.0.11/32 -p tcp -m tcp --dport 53 -j DNAT --to-destination 127.0.0.11:43500\n" +
- "-A DOCKER_OUTPUT -d 127.0.0.11/32 -p udp -m udp --dport 53 -j DNAT --to-destination 127.0.0.11:57392\n" +
- "-A DOCKER_POSTROUTING -s 127.0.0.11/32 -p tcp -m tcp --sport 43500 -j SNAT --to-source :53\n" +
- "-A DOCKER_POSTROUTING -s 127.0.0.11/32 -p udp -m udp --sport 57392 -j SNAT --to-source :53\n" +
- "-A OUTPUT -d 3001::1/128 -j REDIRECT");
+ "-P INPUT ACCEPT\n" +
+ "-P OUTPUT ACCEPT\n" +
+ "-P POSTROUTING ACCEPT\n" +
+ "-N DOCKER_OUTPUT\n" +
+ "-N DOCKER_POSTROUTING\n" +
+ "-A OUTPUT -d 127.0.0.11/32 -j DOCKER_OUTPUT\n" +
+ "-A POSTROUTING -d 127.0.0.11/32 -j DOCKER_POSTROUTING\n" +
+ "-A DOCKER_OUTPUT -d 127.0.0.11/32 -p tcp -m tcp --dport 53 -j DNAT --to-destination 127.0.0.11:43500\n" +
+ "-A DOCKER_OUTPUT -d 127.0.0.11/32 -p udp -m udp --dport 53 -j DNAT --to-destination 127.0.0.11:57392\n" +
+ "-A DOCKER_POSTROUTING -s 127.0.0.11/32 -p tcp -m tcp --sport 43500 -j SNAT --to-source :53\n" +
+ "-A DOCKER_POSTROUTING -s 127.0.0.11/32 -p udp -m udp --sport 57392 -j SNAT --to-source :53\n" +
+ "-A OUTPUT -d 3001::1/128 -j REDIRECT");
}
@Test
- public void nat_cleanup_wrong_redirect_rules() {
+ void nat_cleanup_wrong_redirect_rules() {
assertNatTableLineEditorResult(
"-A OUTPUT -d 3001::1/128 -j REDIRECT",
"-P PREROUTING ACCEPT\n" +
- "-P INPUT ACCEPT\n" +
- "-P OUTPUT ACCEPT\n" +
- "-P POSTROUTING ACCEPT\n" +
- "-A OUTPUT -d 3001::2/128 -j REDIRECT\n",
+ "-P INPUT ACCEPT\n" +
+ "-P OUTPUT ACCEPT\n" +
+ "-P POSTROUTING ACCEPT\n" +
+ "-A OUTPUT -d 3001::2/128 -j REDIRECT\n",
"-P PREROUTING ACCEPT\n" +
- "-P INPUT ACCEPT\n" +
- "-P OUTPUT ACCEPT\n" +
- "-P POSTROUTING ACCEPT\n" +
- "-A OUTPUT -d 3001::1/128 -j REDIRECT");
+ "-P INPUT ACCEPT\n" +
+ "-P OUTPUT ACCEPT\n" +
+ "-P POSTROUTING ACCEPT\n" +
+ "-A OUTPUT -d 3001::1/128 -j REDIRECT");
}
@Test
- public void nat_delete_duplicate_rules() {
+ void nat_delete_duplicate_rules() {
assertNatTableLineEditorResult(
"-A OUTPUT -d 3001::1/128 -j REDIRECT",
"-P PREROUTING ACCEPT\n" +
- "-P INPUT ACCEPT\n" +
- "-P OUTPUT ACCEPT\n" +
- "-P POSTROUTING ACCEPT\n" +
- "-A OUTPUT -d 3001::2/128 -j REDIRECT\n" +
- "-A OUTPUT -d 3001::1/128 -j REDIRECT\n" +
- "-A OUTPUT -d 3001::4/128 -j REDIRECT\n",
+ "-P INPUT ACCEPT\n" +
+ "-P OUTPUT ACCEPT\n" +
+ "-P POSTROUTING ACCEPT\n" +
+ "-A OUTPUT -d 3001::2/128 -j REDIRECT\n" +
+ "-A OUTPUT -d 3001::1/128 -j REDIRECT\n" +
+ "-A OUTPUT -d 3001::4/128 -j REDIRECT\n",
"-P PREROUTING ACCEPT\n" +
- "-P INPUT ACCEPT\n" +
- "-P OUTPUT ACCEPT\n" +
- "-P POSTROUTING ACCEPT\n" +
- "-A OUTPUT -d 3001::1/128 -j REDIRECT");
+ "-P INPUT ACCEPT\n" +
+ "-P OUTPUT ACCEPT\n" +
+ "-P POSTROUTING ACCEPT\n" +
+ "-A OUTPUT -d 3001::1/128 -j REDIRECT");
}
private static void assertNatTableLineEditorResult(String redirectRule, String currentNatTable, String expectedNatTable) {
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/coredump/CoreCollectorTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/coredump/CoreCollectorTest.java
index 5c334837040..c0bf6ebbeb3 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/coredump/CoreCollectorTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/coredump/CoreCollectorTest.java
@@ -7,15 +7,15 @@ import com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentContextImpl;
import com.yahoo.vespa.hosted.node.admin.task.util.fs.ContainerPath;
import com.yahoo.vespa.hosted.node.admin.task.util.process.CommandResult;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static com.yahoo.vespa.hosted.node.admin.maintenance.coredump.CoreCollector.GDB_PATH_RHEL8;
import static com.yahoo.vespa.hosted.node.admin.maintenance.coredump.CoreCollector.JAVA_HEAP_DUMP_METADATA;
-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;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -37,7 +37,7 @@ public class CoreCollectorTest {
"#0 0x00000000004004d8 in main (argv=...) at main.c:4");
@Test
- public void extractsBinaryPathTest() {
+ void extractsBinaryPathTest() {
final String[] cmd = {"file", TEST_CORE_PATH.pathInContainer()};
mockExec(cmd,
@@ -73,7 +73,7 @@ public class CoreCollectorTest {
}
@Test
- public void extractsBinaryPathUsingGdbTest() {
+ void extractsBinaryPathUsingGdbTest() {
final String[] cmd = new String[]{"/bin/sh", "-c",
GDB_PATH_RHEL8 + " -n -batch -core /tmp/core.1234 | grep '^Core was generated by'"};
@@ -91,14 +91,14 @@ public class CoreCollectorTest {
}
@Test
- public void extractsBacktraceUsingGdb() {
+ void extractsBacktraceUsingGdb() {
mockExec(new String[]{GDB_PATH_RHEL8, "-n", "-ex", "set print frame-arguments none",
- "-ex", "bt", "-batch", "/usr/bin/program", "/tmp/core.1234"},
+ "-ex", "bt", "-batch", "/usr/bin/program", "/tmp/core.1234"},
String.join("\n", GDB_BACKTRACE));
assertEquals(GDB_BACKTRACE, coreCollector.readBacktrace(context, TEST_CORE_PATH, TEST_BIN_PATH, false));
mockExec(new String[]{GDB_PATH_RHEL8, "-n", "-ex", "set print frame-arguments none",
- "-ex", "bt", "-batch", "/usr/bin/program", "/tmp/core.1234"},
+ "-ex", "bt", "-batch", "/usr/bin/program", "/tmp/core.1234"},
"", "Failure");
try {
coreCollector.readBacktrace(context, TEST_CORE_PATH, TEST_BIN_PATH, false);
@@ -111,7 +111,7 @@ public class CoreCollectorTest {
}
@Test
- public void extractsBacktraceFromAllThreadsUsingGdb() {
+ void extractsBacktraceFromAllThreadsUsingGdb() {
mockExec(new String[]{GDB_PATH_RHEL8, "-n",
"-ex", "set print frame-arguments none",
"-ex", "thread apply all bt", "-batch",
@@ -121,15 +121,15 @@ public class CoreCollectorTest {
}
@Test
- public void collectsDataTest() {
+ void collectsDataTest() {
mockExec(new String[]{"file", TEST_CORE_PATH.pathInContainer()},
"/tmp/core.1234: ELF 64-bit LSB core file x86-64, version 1 (SYSV), SVR4-style, from " +
"'/usr/bin/program'");
mockExec(new String[]{GDB_PATH_RHEL8, "-n", "-ex", "set print frame-arguments none",
- "-ex", "bt", "-batch", "/usr/bin/program", "/tmp/core.1234"},
+ "-ex", "bt", "-batch", "/usr/bin/program", "/tmp/core.1234"},
String.join("\n", GDB_BACKTRACE));
mockExec(new String[]{GDB_PATH_RHEL8, "-n", "-ex", "set print frame-arguments none",
- "-ex", "thread apply all bt", "-batch",
+ "-ex", "thread apply all bt", "-batch",
"/usr/bin/program", "/tmp/core.1234"},
String.join("\n", GDB_BACKTRACE));
@@ -141,7 +141,7 @@ public class CoreCollectorTest {
}
@Test
- public void collectsPartialIfBacktraceFailsTest() {
+ void collectsPartialIfBacktraceFailsTest() {
mockExec(new String[]{"file", TEST_CORE_PATH.pathInContainer()},
"/tmp/core.1234: ELF 64-bit LSB core file x86-64, version 1 (SYSV), SVR4-style, from " +
"'/usr/bin/program'");
@@ -153,7 +153,7 @@ public class CoreCollectorTest {
}
@Test
- public void reportsJstackInsteadOfGdbForJdkCores() {
+ void reportsJstackInsteadOfGdbForJdkCores() {
mockExec(new String[]{"file", TEST_CORE_PATH.pathInContainer()},
"dump.core.5954: ELF 64-bit LSB core file x86-64, version 1 (SYSV), too many program header sections (33172)");
@@ -171,7 +171,7 @@ public class CoreCollectorTest {
}
@Test
- public void metadata_for_java_heap_dump() {
+ void metadata_for_java_heap_dump() {
assertEquals(JAVA_HEAP_DUMP_METADATA, coreCollector.collect(context, context.paths().of("/dump_java_pid123.hprof")));
}
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/coredump/CoredumpHandlerTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/coredump/CoredumpHandlerTest.java
index 5c681ddc129..31579fb7c9b 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/coredump/CoredumpHandlerTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/coredump/CoredumpHandlerTest.java
@@ -9,8 +9,8 @@ import com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentContextImpl;
import com.yahoo.vespa.hosted.node.admin.task.util.file.UnixPath;
import com.yahoo.vespa.hosted.node.admin.task.util.fs.ContainerPath;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.file.FileSystem;
@@ -28,8 +28,7 @@ import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.yahoo.yolean.Exceptions.uncheck;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
@@ -59,7 +58,7 @@ public class CoredumpHandlerTest {
@Test
- public void coredump_enqueue_test() throws IOException {
+ void coredump_enqueue_test() throws IOException {
ContainerPath crashPath = context.paths().of("/some/crash/path");
ContainerPath processingDir = context.paths().of("/some/other/processing");
@@ -93,7 +92,7 @@ public class CoredumpHandlerTest {
}
@Test
- public void enqueue_with_hs_err_files() throws IOException {
+ void enqueue_with_hs_err_files() throws IOException {
ContainerPath crashPath = context.paths().of("/some/crash/path");
ContainerPath processingDir = context.paths().of("/some/other/processing");
Files.createDirectories(crashPath);
@@ -114,7 +113,7 @@ public class CoredumpHandlerTest {
}
@Test
- public void coredump_to_process_test() throws IOException {
+ void coredump_to_process_test() throws IOException {
ContainerPath processingDir = context.paths().of("/some/other/processing");
// Initially there are no core dumps
@@ -138,7 +137,7 @@ public class CoredumpHandlerTest {
}
@Test
- public void get_metadata_test() throws IOException {
+ void get_metadata_test() throws IOException {
Map<String, Object> metadata = new HashMap<>();
metadata.put("bin_path", "/bin/bash");
metadata.put("backtrace", List.of("call 1", "function 2", "something something"));
@@ -174,21 +173,25 @@ public class CoredumpHandlerTest {
verify(coreCollector, times(1)).collect(any(), any());
}
- @Test(expected = IllegalStateException.class)
- public void cant_get_metadata_if_no_core_file() throws IOException {
- coredumpHandler.getMetadata(context, context.paths().of("/fake/path"), Map::of);
+ @Test
+ void cant_get_metadata_if_no_core_file() throws IOException {
+ assertThrows(IllegalStateException.class, () -> {
+ coredumpHandler.getMetadata(context, context.paths().of("/fake/path"), Map::of);
+ });
}
- @Test(expected = IllegalStateException.class)
- public void fails_to_get_core_file_if_only_compressed() throws IOException {
- ContainerPath coredumpDirectory = context.paths().of("/path/to/coredump/proccessing/id-123");
- Files.createDirectories(coredumpDirectory);
- Files.createFile(coredumpDirectory.resolve("dump_bash.core.431.zstd"));
- coredumpHandler.findCoredumpFileInProcessingDirectory(coredumpDirectory);
+ @Test
+ void fails_to_get_core_file_if_only_compressed() throws IOException {
+ assertThrows(IllegalStateException.class, () -> {
+ ContainerPath coredumpDirectory = context.paths().of("/path/to/coredump/proccessing/id-123");
+ Files.createDirectories(coredumpDirectory);
+ Files.createFile(coredumpDirectory.resolve("dump_bash.core.431.zstd"));
+ coredumpHandler.findCoredumpFileInProcessingDirectory(coredumpDirectory);
+ });
}
@Test
- public void process_single_coredump_test() throws IOException {
+ void process_single_coredump_test() throws IOException {
ContainerPath coredumpDirectory = context.paths().of("/path/to/coredump/proccessing/id-123");
Files.createDirectories(coredumpDirectory);
Files.write(coredumpDirectory.resolve("metadata.json"), "metadata".getBytes());
@@ -204,7 +207,7 @@ public class CoredumpHandlerTest {
}
@Test
- public void report_enqueued_and_processed_metrics() throws IOException {
+ void report_enqueued_and_processed_metrics() throws IOException {
Path processingPath = containerCrashPath.resolve("processing");
Files.createFile(containerCrashPath.resolve("dump-1"));
Files.createFile(containerCrashPath.resolve("dump-2"));
@@ -225,7 +228,7 @@ public class CoredumpHandlerTest {
assertEquals(1, values.get("coredumps.processed").intValue());
}
- @Before
+ @BeforeEach
public void setup() throws IOException {
Files.createDirectories(containerCrashPath.pathOnHost());
}
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/disk/CoredumpCleanupRuleTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/disk/CoredumpCleanupRuleTest.java
index 272fdba7e9a..9bd746e3ddf 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/disk/CoredumpCleanupRuleTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/disk/CoredumpCleanupRuleTest.java
@@ -2,7 +2,7 @@
package com.yahoo.vespa.hosted.node.admin.maintenance.disk;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.file.FileSystem;
@@ -16,7 +16,7 @@ import java.util.stream.Collectors;
import static com.yahoo.vespa.hosted.node.admin.maintenance.disk.DiskCleanupRule.PrioritizedFileAttributes;
import static com.yahoo.vespa.hosted.node.admin.maintenance.disk.DiskCleanupRule.Priority;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author freva
@@ -26,7 +26,7 @@ public class CoredumpCleanupRuleTest {
private final FileSystem fileSystem = TestFileSystem.create();
@Test
- public void for_container_test() throws IOException {
+ void for_container_test() throws IOException {
Path path = fileSystem.getPath("/test/path");
DiskCleanupRule rule = CoredumpCleanupRule.forContainer(path);
@@ -56,7 +56,7 @@ public class CoredumpCleanupRuleTest {
}
@Test
- public void for_host_test() throws IOException {
+ void for_host_test() throws IOException {
Path path = fileSystem.getPath("/test/path");
DiskCleanupRule rule = CoredumpCleanupRule.forHost(path);
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/disk/DiskCleanupTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/disk/DiskCleanupTest.java
index 1386177d17a..44367f37dd9 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/disk/DiskCleanupTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/disk/DiskCleanupTest.java
@@ -4,7 +4,7 @@ package com.yahoo.vespa.hosted.node.admin.maintenance.disk;
import com.yahoo.vespa.hosted.node.admin.component.TestTaskContext;
import com.yahoo.vespa.hosted.node.admin.task.util.file.FileFinder;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.file.FileSystem;
@@ -21,10 +21,10 @@ import java.util.Set;
import java.util.stream.Collectors;
import static com.yahoo.vespa.hosted.node.admin.task.util.file.FileFinder.FileAttributes;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static com.yahoo.vespa.hosted.node.admin.maintenance.disk.DiskCleanupRule.Priority;
-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.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author freva
@@ -36,7 +36,7 @@ public class DiskCleanupTest {
private final DiskCleanup diskCleanup = new DiskCleanup();
@Test
- public void nothing_deleted() throws IOException {
+ void nothing_deleted() throws IOException {
assertFalse(diskCleanup.cleanup(context, List.of(), 0));
assertFalse(diskCleanup.cleanup(context, List.of(), 10));
@@ -56,7 +56,7 @@ public class DiskCleanupTest {
}
@Test
- public void delete_test() throws IOException {
+ void delete_test() throws IOException {
tester.createFile("/opt/vespa/var/db/do-not-delete-1.db", 1);
tester.createFile("/opt/vespa/var/db/do-not-delete-2.db", 1);
tester.createFile("/opt/vespa/var/zookeeper/do-not-delete-3", 1);
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/disk/LinearCleanupRuleTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/disk/LinearCleanupRuleTest.java
index 55a379054d4..1ef876d7e04 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/disk/LinearCleanupRuleTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/disk/LinearCleanupRuleTest.java
@@ -1,16 +1,17 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.admin.maintenance.disk;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static com.yahoo.vespa.hosted.node.admin.task.util.file.FileFinder.FileAttributes;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static com.yahoo.vespa.hosted.node.admin.maintenance.disk.DiskCleanupRule.PrioritizedFileAttributes;
import static com.yahoo.vespa.hosted.node.admin.maintenance.disk.DiskCleanupRule.Priority;
-import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
/**
@@ -19,27 +20,29 @@ import static org.mockito.Mockito.mock;
public class LinearCleanupRuleTest {
@Test
- public void basic() {
+ void basic() {
assertRule(Map.of(), Priority.LOWEST, Priority.HIGHEST);
assertRule(Map.of(0.0, Priority.LOW, 0.5, Priority.LOW, 1.0, Priority.LOW), Priority.LOW, Priority.LOW);
assertRule(Map.of(0.0, Priority.LOW, 0.5, Priority.MEDIUM, 1.0, Priority.MEDIUM), Priority.LOW, Priority.MEDIUM);
assertRule(Map.of(
- -5.0, Priority.LOW,
- 0.0, Priority.LOW,
- 0.2, Priority.LOW,
- 0.35, Priority.MEDIUM,
- 0.65, Priority.MEDIUM,
- 0.8, Priority.HIGH,
- 1.0, Priority.HIGH,
- 5.0, Priority.HIGH),
+ -5.0, Priority.LOW,
+ 0.0, Priority.LOW,
+ 0.2, Priority.LOW,
+ 0.35, Priority.MEDIUM,
+ 0.65, Priority.MEDIUM,
+ 0.8, Priority.HIGH,
+ 1.0, Priority.HIGH,
+ 5.0, Priority.HIGH),
Priority.LOW, Priority.HIGH);
}
- @Test(expected = IllegalArgumentException.class)
- public void fail_if_high_priority_lower_than_low() {
- assertRule(Map.of(), Priority.HIGHEST, Priority.LOWEST);
+ @Test
+ void fail_if_high_priority_lower_than_low() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ assertRule(Map.of(), Priority.HIGHEST, Priority.LOWEST);
+ });
}
private static void assertRule(Map<Double, Priority> expectedPriorities, Priority low, Priority high) {
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/ArtifactProducersTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/ArtifactProducersTest.java
index 4e34d936d85..fd7d0d8c1c0 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/ArtifactProducersTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/servicedump/ArtifactProducersTest.java
@@ -6,7 +6,8 @@ import org.junit.jupiter.api.Test;
import java.util.List;
-import static org.junit.jupiter.api.Assertions.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* @author bjorncs
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/sync/SyncFileInfoTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/sync/SyncFileInfoTest.java
index 94c2ce6d106..8be1ef23bb2 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/sync/SyncFileInfoTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/sync/SyncFileInfoTest.java
@@ -4,7 +4,7 @@ package com.yahoo.vespa.hosted.node.admin.maintenance.sync;
import com.yahoo.config.provision.ApplicationId;
import com.yahoo.vespa.hosted.node.admin.task.util.file.UnixPath;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.URI;
import java.nio.file.FileSystem;
@@ -15,7 +15,7 @@ import java.util.Optional;
import static com.yahoo.vespa.hosted.node.admin.maintenance.sync.SyncFileInfo.Compression.NONE;
import static com.yahoo.vespa.hosted.node.admin.maintenance.sync.SyncFileInfo.Compression.ZSTD;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author freva
@@ -37,7 +37,7 @@ public class SyncFileInfoTest {
private static final Path zkLogPath1 = fileSystem.getPath("/opt/vespa/logs/zookeeper.configserver.1.log");
@Test
- public void access_logs() {
+ void access_logs() {
assertForLogFile(accessLogPath1, null, null, true);
assertForLogFile(accessLogPath1, "s3://vespa-data-bucket/vespa/music/main/h432a/logs/access/access.log.20210211.zst", ZSTD, false);
@@ -52,7 +52,7 @@ public class SyncFileInfoTest {
}
@Test
- public void connection_logs() {
+ void connection_logs() {
assertForLogFile(connectionLogPath1, null, null, true);
assertForLogFile(connectionLogPath1, "s3://vespa-data-bucket/vespa/music/main/h432a/logs/connection/ConnectionLog.20210210.zst", ZSTD, false);
@@ -61,7 +61,7 @@ public class SyncFileInfoTest {
}
@Test
- public void vespa_logs() {
+ void vespa_logs() {
assertForLogFile(vespaLogPath1, "s3://vespa-data-bucket/vespa/music/main/h432a/logs/vespa/vespa.log.zst", ZSTD, Duration.ofHours(1), true);
assertForLogFile(vespaLogPath1, "s3://vespa-data-bucket/vespa/music/main/h432a/logs/vespa/vespa.log.zst", ZSTD, Duration.ZERO, false);
@@ -70,7 +70,7 @@ public class SyncFileInfoTest {
}
@Test
- public void zookeeper_logs() {
+ void zookeeper_logs() {
assertForLogFile(zkLogPath0, "s3://vespa-data-bucket/vespa/music/main/h432a/logs/zookeeper/zookeeper.log.zst", ZSTD, Duration.ofHours(1), true);
assertForLogFile(zkLogPath0, "s3://vespa-data-bucket/vespa/music/main/h432a/logs/zookeeper/zookeeper.log.zst", ZSTD, Duration.ZERO, false);
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/sync/ZstdCompressingInputStreamTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/sync/ZstdCompressingInputStreamTest.java
index ab43c3fd5fc..e6963175977 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/sync/ZstdCompressingInputStreamTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/maintenance/sync/ZstdCompressingInputStreamTest.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.vespa.hosted.node.admin.maintenance.sync;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@@ -10,8 +10,8 @@ import java.io.UncheckedIOException;
import java.util.Random;
import static com.yahoo.vespa.hosted.node.admin.maintenance.sync.ZstdCompressingInputStream.compressor;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author freva
@@ -19,7 +19,7 @@ import static org.junit.Assert.assertEquals;
public class ZstdCompressingInputStreamTest {
@Test
- public void compression_test() throws Exception {
+ void compression_test() throws Exception {
Random rnd = new Random();
byte[] data = new byte[(int) (100_000 * (10 + rnd.nextDouble()))];
rnd.nextBytes(data);
@@ -27,9 +27,9 @@ public class ZstdCompressingInputStreamTest {
}
@Test
- public void compress_empty_file_test() {
+ void compress_empty_file_test() {
byte[] compressedData = compress(new byte[0], 1 << 10);
- assertEquals("zstd compressing an empty file results in a 13 bytes file", 13, compressedData.length);
+ assertEquals(13, compressedData.length, "zstd compressing an empty file results in a 13 bytes file");
}
private static void assertCompression(byte[] data, int bufferSize) {
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/NodeAdminImplTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/NodeAdminImplTest.java
index f8dc05b5eda..8504a724417 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/NodeAdminImplTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/NodeAdminImplTest.java
@@ -6,7 +6,7 @@ import com.yahoo.vespa.hosted.node.admin.container.metrics.Metrics;
import com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentContext;
import com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentContextImpl;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
import java.time.Duration;
@@ -17,9 +17,7 @@ import java.util.Set;
import static com.yahoo.vespa.hosted.node.admin.nodeadmin.NodeAdminImpl.NodeAgentWithScheduler;
import static com.yahoo.vespa.hosted.node.admin.nodeadmin.NodeAdminImpl.NodeAgentWithSchedulerFactory;
-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.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.eq;
@@ -42,7 +40,7 @@ public class NodeAdminImplTest {
new Metrics(), clock, Duration.ZERO, Duration.ZERO);
@Test
- public void nodeAgentsAreProperlyLifeCycleManaged() {
+ void nodeAgentsAreProperlyLifeCycleManaged() {
final NodeAgentContext context1 = createNodeAgentContext("host1.test.yahoo.com");
final NodeAgentContext context2 = createNodeAgentContext("host2.test.yahoo.com");
final NodeAgentWithScheduler nodeAgent1 = mockNodeAgentWithSchedulerFactory(context1);
@@ -80,7 +78,7 @@ public class NodeAdminImplTest {
}
@Test
- public void testSetFrozen() {
+ void testSetFrozen() {
Set<NodeAgentContext> contexts = new HashSet<>();
List<NodeAgentWithScheduler> nodeAgents = new ArrayList<>();
for (int i = 0; i < 3; i++) {
@@ -127,7 +125,7 @@ public class NodeAdminImplTest {
}
@Test
- public void testSubsystemFreezeDuration() {
+ void testSubsystemFreezeDuration() {
// Initially everything is frozen to force convergence
assertTrue(nodeAdmin.isFrozen());
assertTrue(nodeAdmin.subsystemFreezeDuration().isZero());
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/NodeAdminStateUpdaterTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/NodeAdminStateUpdaterTest.java
index 995712c6dda..1197fd1469b 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/NodeAdminStateUpdaterTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeadmin/NodeAdminStateUpdaterTest.java
@@ -10,7 +10,7 @@ import com.yahoo.vespa.hosted.node.admin.configserver.noderepository.Orchestrato
import com.yahoo.vespa.hosted.node.admin.configserver.orchestrator.Orchestrator;
import com.yahoo.vespa.hosted.node.admin.integration.NodeRepoMock;
import com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentContextFactory;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.ArrayList;
@@ -23,8 +23,8 @@ import java.util.stream.IntStream;
import static com.yahoo.vespa.hosted.node.admin.nodeadmin.NodeAdminStateUpdater.State.RESUMED;
import static com.yahoo.vespa.hosted.node.admin.nodeadmin.NodeAdminStateUpdater.State.SUSPENDED;
import static com.yahoo.vespa.hosted.node.admin.nodeadmin.NodeAdminStateUpdater.State.SUSPENDED_NODE_ADMIN;
-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;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.argThat;
@@ -54,7 +54,7 @@ public class NodeAdminStateUpdaterTest {
@Test
- public void state_convergence() {
+ void state_convergence() {
mockNodeRepo(NodeState.active, 4);
List<String> activeHostnames = nodeRepository.getNodes(hostHostname.value()).stream()
.map(NodeSpec::hostname)
@@ -132,7 +132,7 @@ public class NodeAdminStateUpdaterTest {
}
@Test
- public void half_transition_revert() {
+ void half_transition_revert() {
final String exceptionMsg = "Cannot allow to suspend because some reason";
mockNodeRepo(NodeState.active, 3);
@@ -174,7 +174,7 @@ public class NodeAdminStateUpdaterTest {
}
@Test
- public void do_not_orchestrate_host_when_not_active() {
+ void do_not_orchestrate_host_when_not_active() {
when(nodeAdmin.subsystemFreezeDuration()).thenReturn(Duration.ofHours(1));
when(nodeAdmin.setFrozen(anyBoolean())).thenReturn(true);
mockNodeRepo(NodeState.ready, 3);
@@ -196,7 +196,7 @@ public class NodeAdminStateUpdaterTest {
}
@Test
- public void node_spec_and_acl_aligned() {
+ void node_spec_and_acl_aligned() {
Acl acl = new Acl.Builder().withTrustedPorts(22).build();
mockNodeRepo(NodeState.active, 3);
mockAcl(acl, 1, 2, 3);
@@ -213,7 +213,7 @@ public class NodeAdminStateUpdaterTest {
}
@Test
- public void node_spec_and_acl_mismatch_missing_one_acl() {
+ void node_spec_and_acl_mismatch_missing_one_acl() {
Acl acl = new Acl.Builder().withTrustedPorts(22).build();
mockNodeRepo(NodeState.active, 3);
mockAcl(acl, 1, 2); // Acl for 3 is missing
@@ -231,7 +231,7 @@ public class NodeAdminStateUpdaterTest {
}
@Test
- public void node_spec_and_acl_mismatch_additional_acl() {
+ void node_spec_and_acl_mismatch_additional_acl() {
Acl acl = new Acl.Builder().withTrustedPorts(22).build();
mockNodeRepo(NodeState.active, 2);
mockAcl(acl, 1, 2, 3); // Acl for 3 is extra
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentContextImplTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentContextImplTest.java
index 9a6a358d9f0..061cd6e264b 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentContextImplTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentContextImplTest.java
@@ -4,15 +4,13 @@ package com.yahoo.vespa.hosted.node.admin.nodeagent;
import com.yahoo.vespa.flags.InMemoryFlagSource;
import com.yahoo.vespa.flags.PermanentFlags;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.file.FileSystem;
import java.nio.file.Path;
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 freva
@@ -23,7 +21,7 @@ public class NodeAgentContextImplTest {
.fileSystem(fileSystem).build();
@Test
- public void path_on_host_from_path_in_node_test() {
+ void path_on_host_from_path_in_node_test() {
assertEquals(
"/data/vespa/storage/container-1",
context.paths().of("/").pathOnHost().toString());
@@ -33,35 +31,43 @@ public class NodeAgentContextImplTest {
context.paths().of("/dev/null").pathOnHost().toString());
}
- @Test(expected=IllegalArgumentException.class)
- public void path_in_container_must_be_absolute() {
- context.paths().of("some/relative/path");
+ @Test
+ void path_in_container_must_be_absolute() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ context.paths().of("some/relative/path");
+ });
}
@Test
- public void path_in_node_from_path_on_host_test() {
+ void path_in_node_from_path_on_host_test() {
assertEquals(
"/dev/null",
context.paths().fromPathOnHost(fileSystem.getPath("/data/vespa/storage/container-1/dev/null")).pathInContainer());
}
- @Test(expected=IllegalArgumentException.class)
- public void path_on_host_must_be_absolute() {
- context.paths().fromPathOnHost(Path.of("some/relative/path"));
+ @Test
+ void path_on_host_must_be_absolute() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ context.paths().fromPathOnHost(Path.of("some/relative/path"));
+ });
}
- @Test(expected=IllegalArgumentException.class)
- public void path_on_host_must_be_inside_container_storage_of_context() {
- context.paths().fromPathOnHost(fileSystem.getPath("/data/vespa/storage/container-2/dev/null"));
+ @Test
+ void path_on_host_must_be_inside_container_storage_of_context() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ context.paths().fromPathOnHost(fileSystem.getPath("/data/vespa/storage/container-2/dev/null"));
+ });
}
- @Test(expected=IllegalArgumentException.class)
- public void path_on_host_must_be_inside_container_storage() {
- context.paths().fromPathOnHost(fileSystem.getPath("/home"));
+ @Test
+ void path_on_host_must_be_inside_container_storage() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ context.paths().fromPathOnHost(fileSystem.getPath("/home"));
+ });
}
@Test
- public void path_under_vespa_host_in_container_test() {
+ void path_under_vespa_host_in_container_test() {
assertEquals(
"/opt/vespa",
context.paths().underVespaHome("").pathInContainer());
@@ -71,13 +77,15 @@ public class NodeAgentContextImplTest {
context.paths().underVespaHome("logs/vespa/vespa.log").pathInContainer());
}
- @Test(expected=IllegalArgumentException.class)
- public void path_under_vespa_home_must_be_relative() {
- context.paths().underVespaHome("/home");
+ @Test
+ void path_under_vespa_home_must_be_relative() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ context.paths().underVespaHome("/home");
+ });
}
@Test
- public void disabledTasksTest() {
+ void disabledTasksTest() {
NodeAgentContext context1 = createContextWithDisabledTasks();
assertFalse(context1.isDisabled(NodeAgentTask.DiskCleanup));
assertFalse(context1.isDisabled(NodeAgentTask.CoreDumps));
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentContextManagerTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentContextManagerTest.java
index 9502fc48911..82c3f79f39f 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentContextManagerTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentContextManagerTest.java
@@ -2,7 +2,8 @@
package com.yahoo.vespa.hosted.node.admin.nodeagent;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
import java.time.Clock;
import java.time.Duration;
@@ -12,10 +13,7 @@ import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import static com.yahoo.vespa.hosted.node.admin.nodeagent.NodeAgentContextSupplier.ContextSupplierInterruptedException;
-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.jupiter.api.Assertions.*;
/**
* @author freva
@@ -28,8 +26,9 @@ public class NodeAgentContextManagerTest {
private final NodeAgentContext initialContext = generateContext();
private final NodeAgentContextManager manager = new NodeAgentContextManager(clock, initialContext);
- @Test(timeout = TIMEOUT)
- public void context_is_ignored_unless_scheduled_while_waiting() {
+ @Test
+ @Timeout(TIMEOUT)
+ void context_is_ignored_unless_scheduled_while_waiting() {
NodeAgentContext context1 = generateContext();
manager.scheduleTickWith(context1, clock.instant());
assertSame(initialContext, manager.currentContext());
@@ -45,8 +44,9 @@ public class NodeAgentContextManagerTest {
assertSame(context2, manager.currentContext());
}
- @Test(timeout = TIMEOUT)
- public void returns_no_earlier_than_at_given_time() {
+ @Test
+ @Timeout(TIMEOUT)
+ void returns_no_earlier_than_at_given_time() {
AsyncExecutor<NodeAgentContext> async = new AsyncExecutor<>(manager::nextContext);
manager.waitUntilWaitingForNextContext();
@@ -60,8 +60,9 @@ public class NodeAgentContextManagerTest {
assertFalse(clock.instant().plusMillis(1).isBefore(returnAt));
}
- @Test(timeout = TIMEOUT)
- public void blocks_in_nextContext_until_one_is_scheduled() {
+ @Test
+ @Timeout(TIMEOUT)
+ void blocks_in_nextContext_until_one_is_scheduled() {
AsyncExecutor<NodeAgentContext> async = new AsyncExecutor<>(manager::nextContext);
manager.waitUntilWaitingForNextContext();
assertFalse(async.isCompleted());
@@ -74,8 +75,9 @@ public class NodeAgentContextManagerTest {
assertFalse(async.exception.isPresent());
}
- @Test(timeout = TIMEOUT)
- public void blocks_in_nextContext_until_interrupt() {
+ @Test
+ @Timeout(TIMEOUT)
+ void blocks_in_nextContext_until_interrupt() {
AsyncExecutor<NodeAgentContext> async = new AsyncExecutor<>(manager::nextContext);
manager.waitUntilWaitingForNextContext();
assertFalse(async.isCompleted());
@@ -87,8 +89,9 @@ public class NodeAgentContextManagerTest {
assertFalse(async.response.isPresent());
}
- @Test(timeout = TIMEOUT)
- public void setFrozen_does_not_block_with_no_timeout() {
+ @Test
+ @Timeout(TIMEOUT)
+ void setFrozen_does_not_block_with_no_timeout() {
assertFalse(manager.setFrozen(false, Duration.ZERO));
// Generate new context and get it from the supplier, this completes the unfreeze
@@ -101,8 +104,9 @@ public class NodeAgentContextManagerTest {
assertTrue(manager.setFrozen(false, Duration.ZERO));
}
- @Test(timeout = TIMEOUT)
- public void setFrozen_blocks_at_least_for_duration_of_timeout() {
+ @Test
+ @Timeout(TIMEOUT)
+ void setFrozen_blocks_at_least_for_duration_of_timeout() {
long wantedDurationMillis = 100;
long start = clock.millis();
assertFalse(manager.setFrozen(false, Duration.ofMillis(wantedDurationMillis)));
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentImplTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentImplTest.java
index d31c341532f..b13a3a184e5 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentImplTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/nodeagent/NodeAgentImplTest.java
@@ -28,8 +28,8 @@ import com.yahoo.vespa.hosted.node.admin.maintenance.identity.CredentialsMaintai
import com.yahoo.vespa.hosted.node.admin.maintenance.servicedump.VespaServiceDumper;
import com.yahoo.vespa.hosted.node.admin.nodeadmin.ConvergenceException;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
import java.nio.file.FileSystem;
@@ -39,8 +39,8 @@ import java.util.List;
import java.util.Map;
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;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
@@ -76,7 +76,7 @@ public class NodeAgentImplTest {
private final ManualClock clock = new ManualClock(Instant.now());
private final FileSystem fileSystem = TestFileSystem.create();
- @Before
+ @BeforeEach
public void setUp() {
when(containerOperations.suspendNode(any())).thenReturn("");
when(containerOperations.resumeNode(any())).thenReturn("");
@@ -86,7 +86,7 @@ public class NodeAgentImplTest {
}
@Test
- public void upToDateContainerIsUntouched() {
+ void upToDateContainerIsUntouched() {
final NodeSpec node = nodeBuilder(NodeState.active)
.wantedDockerImage(dockerImage).currentDockerImage(dockerImage)
.wantedVespaVersion(vespaVersion).currentVespaVersion(vespaVersion)
@@ -111,7 +111,7 @@ public class NodeAgentImplTest {
}
@Test
- public void verifyRemoveOldFilesIfDiskFull() {
+ void verifyRemoveOldFilesIfDiskFull() {
final NodeSpec node = nodeBuilder(NodeState.active)
.wantedDockerImage(dockerImage).currentDockerImage(dockerImage)
.wantedVespaVersion(vespaVersion).currentVespaVersion(vespaVersion)
@@ -127,7 +127,7 @@ public class NodeAgentImplTest {
}
@Test
- public void startsAfterStoppingServices() {
+ void startsAfterStoppingServices() {
final InOrder inOrder = inOrder(containerOperations);
final NodeSpec node = nodeBuilder(NodeState.active)
.wantedDockerImage(dockerImage).currentDockerImage(dockerImage)
@@ -161,7 +161,7 @@ public class NodeAgentImplTest {
}
@Test
- public void absentContainerCausesStart() {
+ void absentContainerCausesStart() {
final NodeSpec node = nodeBuilder(NodeState.active)
.wantedDockerImage(dockerImage)
.wantedVespaVersion(vespaVersion)
@@ -192,7 +192,7 @@ public class NodeAgentImplTest {
}
@Test
- public void containerIsNotStoppedIfNewImageMustBePulled() {
+ void containerIsNotStoppedIfNewImageMustBePulled() {
final DockerImage newDockerImage = DockerImage.fromString("registry.example.com/repo/new-image");
final NodeSpec node = nodeBuilder(NodeState.active)
.wantedDockerImage(newDockerImage).currentDockerImage(dockerImage)
@@ -216,7 +216,7 @@ public class NodeAgentImplTest {
}
@Test
- public void containerIsUpdatedIfCpuChanged() {
+ void containerIsUpdatedIfCpuChanged() {
NodeSpec.Builder specBuilder = nodeBuilder(NodeState.active)
.wantedDockerImage(dockerImage).currentDockerImage(dockerImage)
.wantedVespaVersion(vespaVersion).currentVespaVersion(vespaVersion)
@@ -263,7 +263,7 @@ public class NodeAgentImplTest {
}
@Test
- public void containerIsRecreatedIfMemoryChanged() {
+ void containerIsRecreatedIfMemoryChanged() {
NodeSpec.Builder specBuilder = nodeBuilder(NodeState.active)
.wantedDockerImage(dockerImage).currentDockerImage(dockerImage)
.wantedVespaVersion(vespaVersion).currentVespaVersion(vespaVersion)
@@ -294,7 +294,7 @@ public class NodeAgentImplTest {
}
@Test
- public void noRestartIfOrchestratorSuspendFails() {
+ void noRestartIfOrchestratorSuspendFails() {
final NodeSpec node = nodeBuilder(NodeState.active)
.wantedDockerImage(dockerImage).currentDockerImage(dockerImage)
.wantedVespaVersion(vespaVersion).currentVespaVersion(vespaVersion)
@@ -308,7 +308,8 @@ public class NodeAgentImplTest {
try {
nodeAgent.doConverge(context);
fail("Expected to throw an exception");
- } catch (OrchestratorException ignored) { }
+ } catch (OrchestratorException ignored) {
+ }
verify(containerOperations, never()).createContainer(eq(context), any());
verify(containerOperations, never()).startContainer(eq(context));
@@ -320,7 +321,7 @@ public class NodeAgentImplTest {
}
@Test
- public void recreatesContainerIfRebootWanted() {
+ void recreatesContainerIfRebootWanted() {
final long wantedRebootGeneration = 2;
final NodeSpec node = nodeBuilder(NodeState.active)
.wantedDockerImage(dockerImage).currentDockerImage(dockerImage)
@@ -338,7 +339,8 @@ public class NodeAgentImplTest {
try {
nodeAgent.doConverge(context);
- } catch (ConvergenceException ignored) {}
+ } catch (ConvergenceException ignored) {
+ }
// First time we fail to resume because health verification fails
verify(orchestrator, times(1)).suspend(eq(hostName));
@@ -359,7 +361,7 @@ public class NodeAgentImplTest {
}
@Test
- public void failedNodeRunningContainerShouldStillBeRunning() {
+ void failedNodeRunningContainerShouldStillBeRunning() {
final NodeSpec node = nodeBuilder(NodeState.failed)
.wantedDockerImage(dockerImage).currentDockerImage(dockerImage)
.wantedVespaVersion(vespaVersion).currentVespaVersion(vespaVersion)
@@ -378,11 +380,11 @@ public class NodeAgentImplTest {
}
@Test
- public void readyNodeLeadsToNoAction() {
+ void readyNodeLeadsToNoAction() {
final NodeSpec node = nodeBuilder(NodeState.ready).build();
NodeAgentContext context = createContext(node);
- NodeAgentImpl nodeAgent = makeNodeAgent(null,false);
+ NodeAgentImpl nodeAgent = makeNodeAgent(null, false);
when(nodeRepository.getOptionalNode(hostName)).thenReturn(Optional.of(node));
@@ -400,7 +402,7 @@ public class NodeAgentImplTest {
}
@Test
- public void inactiveNodeRunningContainerShouldStillBeRunning() {
+ void inactiveNodeRunningContainerShouldStillBeRunning() {
final NodeSpec node = nodeBuilder(NodeState.inactive)
.wantedDockerImage(dockerImage).currentDockerImage(dockerImage)
.wantedVespaVersion(vespaVersion).currentVespaVersion(vespaVersion)
@@ -421,7 +423,7 @@ public class NodeAgentImplTest {
}
@Test
- public void reservedNodeDoesNotUpdateNodeRepoWithVersion() {
+ void reservedNodeDoesNotUpdateNodeRepoWithVersion() {
final NodeSpec node = nodeBuilder(NodeState.reserved)
.wantedDockerImage(dockerImage)
.wantedVespaVersion(vespaVersion)
@@ -470,17 +472,17 @@ public class NodeAgentImplTest {
}
@Test
- public void dirtyNodeRunningContainerIsTakenDownAndCleanedAndRecycled() {
+ void dirtyNodeRunningContainerIsTakenDownAndCleanedAndRecycled() {
nodeRunningContainerIsTakenDownAndCleanedAndRecycled(NodeState.dirty, Optional.of(1L));
}
@Test
- public void dirtyNodeRunningContainerIsTakenDownAndCleanedAndRecycledNoRestartGeneration() {
+ void dirtyNodeRunningContainerIsTakenDownAndCleanedAndRecycledNoRestartGeneration() {
nodeRunningContainerIsTakenDownAndCleanedAndRecycled(NodeState.dirty, Optional.empty());
}
@Test
- public void provisionedNodeIsMarkedAsReady() {
+ void provisionedNodeIsMarkedAsReady() {
final NodeSpec node = nodeBuilder(NodeState.provisioned)
.wantedDockerImage(dockerImage)
.build();
@@ -494,7 +496,7 @@ public class NodeAgentImplTest {
}
@Test
- public void testRestartDeadContainerAfterNodeAdminRestart() {
+ void testRestartDeadContainerAfterNodeAdminRestart() {
final NodeSpec node = nodeBuilder(NodeState.active)
.currentDockerImage(dockerImage).wantedDockerImage(dockerImage)
.currentVespaVersion(vespaVersion)
@@ -513,7 +515,7 @@ public class NodeAgentImplTest {
}
@Test
- public void resumeProgramRunsUntilSuccess() {
+ void resumeProgramRunsUntilSuccess() {
final NodeSpec node = nodeBuilder(NodeState.active)
.wantedDockerImage(dockerImage).currentDockerImage(dockerImage)
.currentVespaVersion(vespaVersion)
@@ -535,7 +537,8 @@ public class NodeAgentImplTest {
try {
nodeAgent.doConverge(context);
fail("Expected to throw an exception");
- } catch (RuntimeException ignored) { }
+ } catch (RuntimeException ignored) {
+ }
inOrder.verify(containerOperations, times(1)).resumeNode(any());
inOrder.verifyNoMoreInteractions();
@@ -549,7 +552,7 @@ public class NodeAgentImplTest {
}
@Test
- public void start_container_subtask_failure_leads_to_container_restart() {
+ void start_container_subtask_failure_leads_to_container_restart() {
final NodeSpec node = nodeBuilder(NodeState.active)
.wantedDockerImage(dockerImage)
.wantedVespaVersion(vespaVersion)
@@ -565,7 +568,8 @@ public class NodeAgentImplTest {
try {
nodeAgent.doConverge(context);
fail("Expected to get RuntimeException");
- } catch (RuntimeException ignored) { }
+ } catch (RuntimeException ignored) {
+ }
verify(containerOperations, never()).removeContainer(eq(context), any());
verify(containerOperations, times(1)).createContainer(eq(context), any());
@@ -584,7 +588,7 @@ public class NodeAgentImplTest {
}
@Test
- public void testRunningConfigServer() {
+ void testRunningConfigServer() {
final NodeSpec node = nodeBuilder(NodeState.active)
.type(NodeType.config)
.wantedDockerImage(dockerImage)
@@ -617,7 +621,7 @@ public class NodeAgentImplTest {
// Tests that only containers without owners are stopped
@Test
- public void testThatStopContainerDependsOnOwnerPresent() {
+ void testThatStopContainerDependsOnOwnerPresent() {
verifyThatContainerIsStopped(NodeState.parked, Optional.empty());
verifyThatContainerIsStopped(NodeState.parked, Optional.of(ApplicationId.defaultId()));
verifyThatContainerIsStopped(NodeState.failed, Optional.empty());
@@ -626,7 +630,7 @@ public class NodeAgentImplTest {
}
@Test
- public void initial_cpu_cap_test() {
+ void initial_cpu_cap_test() {
NodeSpec.Builder specBuilder = nodeBuilder(NodeState.active)
.wantedDockerImage(dockerImage).currentDockerImage(dockerImage)
.wantedVespaVersion(vespaVersion).currentVespaVersion(vespaVersion);
@@ -678,7 +682,7 @@ public class NodeAgentImplTest {
}
@Test
- public void resumes_normally_if_container_is_already_capped_on_start() {
+ void resumes_normally_if_container_is_already_capped_on_start() {
NodeSpec.Builder specBuilder = nodeBuilder(NodeState.active)
.wantedDockerImage(dockerImage).currentDockerImage(dockerImage)
.wantedVespaVersion(vespaVersion).currentVespaVersion(vespaVersion)
@@ -700,7 +704,7 @@ public class NodeAgentImplTest {
}
@Test
- public void uncaps_and_caps_cpu_for_services_restart() {
+ void uncaps_and_caps_cpu_for_services_restart() {
NodeSpec.Builder specBuilder = nodeBuilder(NodeState.active)
.wantedDockerImage(dockerImage).currentDockerImage(dockerImage)
.wantedVespaVersion(vespaVersion).currentVespaVersion(vespaVersion)
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/provider/DebugHandlerHelperTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/provider/DebugHandlerHelperTest.java
index fd16b974e18..b7099a5f2bd 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/provider/DebugHandlerHelperTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/provider/DebugHandlerHelperTest.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.hosted.node.admin.provider;
-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;
public class DebugHandlerHelperTest {
@Test
- public void trivial() {
+ void trivial() {
DebugHandlerHelper helper = new DebugHandlerHelper();
helper.addConstant("constant-key", "constant-value");
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/DefaultEnvWriterTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/DefaultEnvWriterTest.java
index 3869ec26d02..bc461af0eb3 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/DefaultEnvWriterTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/DefaultEnvWriterTest.java
@@ -2,10 +2,10 @@
package com.yahoo.vespa.hosted.node.admin.task.util;
import com.yahoo.vespa.hosted.node.admin.component.TaskContext;
-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;
@@ -13,9 +13,7 @@ import java.nio.file.Paths;
import java.util.logging.Logger;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
-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.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
@@ -26,8 +24,8 @@ import static org.mockito.Mockito.verify;
*/
public class DefaultEnvWriterTest {
- @Rule
- public TemporaryFolder temporaryFolder = new TemporaryFolder();
+ @TempDir
+ public File temporaryFolder;
private static final Path EXAMPLE_FILE = Paths.get("src/test/resources/default-env-example.txt");
private static final Path EXPECTED_RESULT_FILE = Paths.get("src/test/resources/default-env-rewritten.txt");
@@ -35,8 +33,8 @@ public class DefaultEnvWriterTest {
private final TaskContext context = mock(TaskContext.class);
@Test
- public void default_env_is_correctly_rewritten() throws IOException {
- Path tempFile = temporaryFolder.newFile().toPath();
+ void default_env_is_correctly_rewritten() throws IOException {
+ Path tempFile = File.createTempFile("junit", null, temporaryFolder).toPath();
Files.copy(EXAMPLE_FILE, tempFile, REPLACE_EXISTING);
DefaultEnvWriter writer = new DefaultEnvWriter();
@@ -57,7 +55,7 @@ public class DefaultEnvWriterTest {
}
@Test
- public void generates_default_env_content() throws IOException {
+ void generates_default_env_content() throws IOException {
DefaultEnvWriter writer = new DefaultEnvWriter();
writer.addOverride("VESPA_HOSTNAME", "my-new-hostname");
writer.addFallback("VESPA_CONFIGSERVER", "new-fallback-configserver");
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/editor/StringEditorTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/editor/StringEditorTest.java
index a66d77edbfa..4f8e28cf53c 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/editor/StringEditorTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/editor/StringEditorTest.java
@@ -2,22 +2,19 @@
package com.yahoo.vespa.hosted.node.admin.task.util.editor;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Optional;
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.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
public class StringEditorTest {
private final StringEditor editor = new StringEditor();
private final Cursor cursor = editor.cursor();
@Test
- public void testBasics() {
+ void testBasics() {
assertCursor(0, 0, "");
cursor.write("hello");
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/editor/TextBufferImplTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/editor/TextBufferImplTest.java
index 584b7c2c906..ca95fada774 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/editor/TextBufferImplTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/editor/TextBufferImplTest.java
@@ -2,15 +2,15 @@
package com.yahoo.vespa.hosted.node.admin.task.util.editor;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class TextBufferImplTest {
private final TextBufferImpl textBuffer = new TextBufferImpl();
@Test
- public void testWrite() {
+ void testWrite() {
assertEquals("", textBuffer.getString());
assertWrite(2, 0, "foo\nbar\n",
0, 0, "foo\nbar\n");
@@ -25,7 +25,7 @@ public class TextBufferImplTest {
}
@Test
- public void testDelete() {
+ void testDelete() {
write(0, 0, "foo\nbar\nzoo\n");
delete(0, 2, 2, 1);
assertEquals("fooo\n", textBuffer.getString());
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/DiskSizeTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/DiskSizeTest.java
index 9c7bad3b130..8d8f9437495 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/DiskSizeTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/DiskSizeTest.java
@@ -1,9 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.admin.task.util.file;
-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 freva
@@ -11,7 +11,7 @@ import static org.junit.Assert.assertEquals;
public class DiskSizeTest {
@Test
- public void bytes_to_display_count_test() {
+ void bytes_to_display_count_test() {
assertEquals("-1 bytes", DiskSize.of(-1).asString());
assertEquals("123 bytes", DiskSize.of(123).asString());
assertEquals("1 kB", DiskSize.of(1_000).asString());
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/EditorTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/EditorTest.java
index 59bc7864ef5..25c1063c92f 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/EditorTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/EditorTest.java
@@ -3,15 +3,13 @@ package com.yahoo.vespa.hosted.node.admin.task.util.file;
import com.yahoo.vespa.hosted.node.admin.component.TaskContext;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.nio.file.FileSystem;
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.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
@@ -23,7 +21,7 @@ public class EditorTest {
private final UnixPath path = new UnixPath(fileSystem.getPath("/file"));
@Test
- public void testEdit() {
+ void testEdit() {
path.writeUtf8File(joinLines("first", "second", "third"));
LineEditor lineEditor = mock(LineEditor.class);
@@ -51,7 +49,7 @@ public class EditorTest {
}
@Test
- public void testInsert() {
+ void testInsert() {
path.writeUtf8File(joinLines("second", "eight", "fifth", "seventh"));
LineEditor lineEditor = mock(LineEditor.class);
@@ -86,7 +84,7 @@ public class EditorTest {
}
@Test
- public void noop() {
+ void noop() {
path.writeUtf8File("line\n");
LineEditor lineEditor = mock(LineEditor.class);
@@ -107,7 +105,7 @@ public class EditorTest {
}
@Test
- public void testMissingFile() {
+ void testMissingFile() {
LineEditor lineEditor = mock(LineEditor.class);
when(lineEditor.onComplete()).thenReturn(List.of("line"));
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileAttributesCacheTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileAttributesCacheTest.java
index 9a2ada2bebe..8c9188a9409 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileAttributesCacheTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileAttributesCacheTest.java
@@ -1,13 +1,11 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.admin.task.util.file;
-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.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -16,7 +14,7 @@ import static org.mockito.Mockito.when;
public class FileAttributesCacheTest {
@Test
- public void exists() {
+ void exists() {
UnixPath unixPath = mock(UnixPath.class);
FileAttributesCache cache = new FileAttributesCache(unixPath);
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileContentCacheTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileContentCacheTest.java
index 32eb7708f68..9184ac2daa0 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileContentCacheTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileContentCacheTest.java
@@ -2,12 +2,12 @@
package com.yahoo.vespa.hosted.node.admin.task.util.file;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
-import static org.junit.Assert.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -22,7 +22,7 @@ public class FileContentCacheTest {
private final byte[] newContent = "new-content".getBytes(StandardCharsets.UTF_8);
@Test
- public void get() {
+ void get() {
when(unixPath.readBytes()).thenReturn(content);
assertArrayEquals(content, cache.get(Instant.ofEpochMilli(0)));
verify(unixPath, times(1)).readBytes();
@@ -49,7 +49,7 @@ public class FileContentCacheTest {
}
@Test
- public void updateWith() {
+ void updateWith() {
cache.updateWith(content, Instant.ofEpochMilli(2));
assertArrayEquals(content, cache.get(Instant.ofEpochMilli(2)));
verifyNoMoreInteractions(unixPath);
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileDeleterTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileDeleterTest.java
index 5cf7f950c4f..360ffacca8d 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileDeleterTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileDeleterTest.java
@@ -3,12 +3,12 @@ package com.yahoo.vespa.hosted.node.admin.task.util.file;
import com.yahoo.vespa.hosted.node.admin.component.TaskContext;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.file.FileSystem;
-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;
import static org.mockito.Mockito.mock;
public class FileDeleterTest {
@@ -18,7 +18,7 @@ public class FileDeleterTest {
private final TaskContext context = mock(TaskContext.class);
@Test
- public void deleteExisting() {
+ void deleteExisting() {
assertFalse(deleter.converge(context));
path.createParents().writeUtf8File("bar");
assertTrue(deleter.converge(context));
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileFinderTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileFinderTest.java
index 0bb820bbfdc..ce193059fb2 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileFinderTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileFinderTest.java
@@ -3,10 +3,9 @@ package com.yahoo.vespa.hosted.node.admin.task.util.file;
import com.yahoo.vespa.hosted.node.admin.component.TaskContext;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.experimental.runners.Enclosed;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Nested;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.UncheckedIOException;
@@ -27,24 +26,24 @@ import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.Set.of;
-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.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
+
/**
* @author freva
*/
-@RunWith(Enclosed.class)
+
public class FileFinderTest {
- public static class GeneralLogicTests {
+ @Nested
+ public class GeneralLogicTests {
private final FileSystem fileSystem = TestFileSystem.create();
@Test
- public void all_files_non_recursive() {
+ void all_files_non_recursive() {
assertFileHelper(FileFinder.files(testRoot())
.maxDepth(1),
@@ -53,7 +52,7 @@ public class FileFinderTest {
}
@Test
- public void all_files_recursive() {
+ void all_files_recursive() {
assertFileHelper(FileFinder.files(testRoot()),
of("file-1.json", "test.json", "test.txt", "test/file.txt", "test/data.json", "test/subdir-1/test"),
@@ -61,7 +60,7 @@ public class FileFinderTest {
}
@Test
- public void all_files_recursive_with_prune_relative() {
+ void all_files_recursive_with_prune_relative() {
assertFileHelper(FileFinder.files(testRoot()).prune(fileSystem.getPath("test")),
of("file-1.json", "test.json", "test.txt"),
@@ -69,20 +68,22 @@ public class FileFinderTest {
}
@Test
- public void all_files_recursive_with_prune_absolute() {
+ void all_files_recursive_with_prune_absolute() {
assertFileHelper(FileFinder.files(testRoot()).prune(testRoot().resolve("test/subdir-1")),
of("file-1.json", "test.json", "test.txt", "test/file.txt", "test/data.json"),
of("test", "test/subdir-1", "test/subdir-1/test", "test/subdir-2"));
}
- @Test(expected = IllegalArgumentException.class)
- public void throws_if_prune_path_not_under_base_path() {
- FileFinder.files(Paths.get("/some/path")).prune(Paths.get("/other/path"));
+ @Test
+ void throws_if_prune_path_not_under_base_path() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ FileFinder.files(Paths.get("/some/path")).prune(Paths.get("/other/path"));
+ });
}
@Test
- public void with_file_filter_recursive() {
+ void with_file_filter_recursive() {
assertFileHelper(FileFinder.files(testRoot())
.match(FileFinder.nameEndsWith(".json")),
@@ -91,7 +92,7 @@ public class FileFinderTest {
}
@Test
- public void all_files_limited_depth() {
+ void all_files_limited_depth() {
assertFileHelper(FileFinder.files(testRoot())
.maxDepth(2),
@@ -100,7 +101,7 @@ public class FileFinderTest {
}
@Test
- public void directory_with_filter() {
+ void directory_with_filter() {
assertFileHelper(FileFinder.directories(testRoot())
.match(FileFinder.nameStartsWith("subdir"))
.maxDepth(2),
@@ -110,7 +111,7 @@ public class FileFinderTest {
}
@Test
- public void match_file_and_directory_with_same_name() {
+ void match_file_and_directory_with_same_name() {
assertFileHelper(FileFinder.from(testRoot())
.match(FileFinder.nameEndsWith("test")),
@@ -119,7 +120,7 @@ public class FileFinderTest {
}
@Test
- public void all_contents() {
+ void all_contents() {
assertFileHelper(FileFinder.from(testRoot())
.maxDepth(1),
@@ -129,7 +130,7 @@ public class FileFinderTest {
assertTrue(Files.exists(testRoot()));
}
- @Before
+ @BeforeEach
public void setup() throws IOException {
Path root = testRoot();
Files.createDirectories(root);
@@ -185,12 +186,13 @@ public class FileFinderTest {
}
}
- public static class FilterUnitTests {
+ @Nested
+ public class FilterUnitTests {
private final BasicFileAttributes attributes = mock(BasicFileAttributes.class);
@Test
- public void age_filter_test() {
+ void age_filter_test() {
Path path = Paths.get("/my/fake/path");
when(attributes.lastModifiedTime()).thenReturn(FileTime.from(Instant.now().minus(Duration.ofHours(1))));
FileFinder.FileAttributes fileAttributes = new FileFinder.FileAttributes(path, attributes);
@@ -203,7 +205,7 @@ public class FileFinderTest {
}
@Test
- public void size_filters() {
+ void size_filters() {
Path path = Paths.get("/my/fake/path");
when(attributes.size()).thenReturn(100L);
FileFinder.FileAttributes fileAttributes = new FileFinder.FileAttributes(path, attributes);
@@ -216,7 +218,7 @@ public class FileFinderTest {
}
@Test
- public void filename_filters() {
+ void filename_filters() {
Path path = Paths.get("/my/fake/path/some-12352-file.json");
FileFinder.FileAttributes fileAttributes = new FileFinder.FileAttributes(path, attributes);
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileSnapshotTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileSnapshotTest.java
index 54291188397..8e09ac64e26 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileSnapshotTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileSnapshotTest.java
@@ -2,14 +2,11 @@
package com.yahoo.vespa.hosted.node.admin.task.util.file;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.file.FileSystem;
-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.jupiter.api.Assertions.*;
/**
* @author hakonhall
@@ -21,7 +18,7 @@ public class FileSnapshotTest {
private FileSnapshot fileSnapshot = FileSnapshot.forPath(path.toPath());
@Test
- public void fileDoesNotExist() {
+ void fileDoesNotExist() {
assertFalse(fileSnapshot.exists());
assertFalse(fileSnapshot.attributes().isPresent());
assertFalse(fileSnapshot.content().isPresent());
@@ -29,7 +26,7 @@ public class FileSnapshotTest {
}
@Test
- public void directory() {
+ void directory() {
path.createParents().createDirectory();
fileSnapshot = fileSnapshot.snapshot();
assertTrue(fileSnapshot.exists());
@@ -38,7 +35,7 @@ public class FileSnapshotTest {
}
@Test
- public void regularFile() {
+ void regularFile() {
path.createParents().writeUtf8File("file content");
fileSnapshot = fileSnapshot.snapshot();
assertTrue(fileSnapshot.exists());
@@ -52,7 +49,7 @@ public class FileSnapshotTest {
}
@Test
- public void fileRemoval() {
+ void fileRemoval() {
path.createParents().writeUtf8File("file content");
fileSnapshot = fileSnapshot.snapshot();
assertTrue(fileSnapshot.exists());
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileSyncTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileSyncTest.java
index 2355f047b00..5c7becdb9f1 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileSyncTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileSyncTest.java
@@ -3,7 +3,7 @@ package com.yahoo.vespa.hosted.node.admin.task.util.file;
import com.yahoo.vespa.hosted.node.admin.component.TestTaskContext;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.file.FileSystem;
import java.nio.file.Files;
@@ -12,10 +12,7 @@ import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
-import static org.junit.Assert.assertArrayEquals;
-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.*;
public class FileSyncTest {
private final TestTaskContext taskContext = new TestTaskContext();
@@ -31,7 +28,7 @@ public class FileSyncTest {
private String permissions = "rw-r-xr--";
@Test
- public void trivial() {
+ void trivial() {
assertConvergence("Creating file /dir/file.txt",
"Changing user ID of /dir/file.txt from 1 to 123",
"Changing group ID of /dir/file.txt from 2 to 456",
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileWriterTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileWriterTest.java
index 0f11a4c9a7a..03f91c5d48a 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileWriterTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/FileWriterTest.java
@@ -4,15 +4,13 @@ package com.yahoo.vespa.hosted.node.admin.task.util.file;
import com.yahoo.vespa.test.file.TestFileSystem;
import com.yahoo.vespa.hosted.node.admin.component.TaskContext;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.file.FileSystem;
import java.nio.file.Path;
import java.time.Instant;
-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.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
@@ -24,7 +22,7 @@ public class FileWriterTest {
private final TaskContext context = mock(TaskContext.class);
@Test
- public void testWrite() {
+ void testWrite() {
final String content = "content";
final String permissions = "rwxr-xr-x";
final int owner = 123;
@@ -52,7 +50,7 @@ public class FileWriterTest {
}
@Test
- public void testAtomicWrite() {
+ void testAtomicWrite() {
FileWriter writer = new FileWriter(fileSystem.getPath("/foo/bar"))
.atomicWrite(true);
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/MakeDirectoryTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/MakeDirectoryTest.java
index b2c02690443..bcd65fd45dd 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/MakeDirectoryTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/MakeDirectoryTest.java
@@ -3,7 +3,7 @@ package com.yahoo.vespa.hosted.node.admin.task.util.file;
import com.yahoo.vespa.hosted.node.admin.component.TestTaskContext;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.UncheckedIOException;
import java.nio.file.FileSystem;
@@ -11,10 +11,7 @@ import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
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.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author hakonhall
@@ -29,7 +26,7 @@ public class MakeDirectoryTest {
private int groupId = 456;
@Test
- public void newDirectory() {
+ void newDirectory() {
verifySystemModifications(
"Creating directory " + path,
"Changing user ID of /parent/dir from 1 to 123",
@@ -62,7 +59,7 @@ public class MakeDirectoryTest {
}
@Test
- public void exceptionIfMissingParent() {
+ void exceptionIfMissingParent() {
String path = "/parent/dir";
MakeDirectory makeDirectory = new MakeDirectory(fileSystem.getPath(path));
@@ -78,7 +75,7 @@ public class MakeDirectoryTest {
}
@Test
- public void okIfParentExists() {
+ void okIfParentExists() {
String path = "/dir";
MakeDirectory makeDirectory = new MakeDirectory(fileSystem.getPath(path));
assertTrue(makeDirectory.converge(context));
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/StoredBooleanTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/StoredBooleanTest.java
index a34f4b93a4d..67b3bf815d9 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/StoredBooleanTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/StoredBooleanTest.java
@@ -3,15 +3,15 @@ package com.yahoo.vespa.hosted.node.admin.task.util.file;
import com.yahoo.vespa.hosted.node.admin.component.TaskContext;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
-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;
import static org.mockito.Mockito.mock;
/**
@@ -24,7 +24,7 @@ public class StoredBooleanTest {
private final StoredBoolean storedBoolean = new StoredBoolean(path);
@Test
- public void storedBoolean() {
+ void storedBoolean() {
assertFalse(storedBoolean.value());
storedBoolean.set(context);
assertTrue(storedBoolean.value());
@@ -33,7 +33,7 @@ public class StoredBooleanTest {
}
@Test
- public void testCompatibility() throws IOException {
+ void testCompatibility() throws IOException {
StoredInteger storedInteger = new StoredInteger(path);
assertFalse(storedBoolean.value());
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/TemplateTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/TemplateTest.java
index d82bd517cae..50a18cc83b3 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/TemplateTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/TemplateTest.java
@@ -4,19 +4,19 @@ package com.yahoo.vespa.hosted.node.admin.task.util.file;
import com.yahoo.vespa.hosted.node.admin.component.TaskContext;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.nio.file.FileSystem;
import java.nio.file.Path;
-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;
import static org.mockito.Mockito.mock;
public class TemplateTest {
@Test
- public void basic() {
+ void basic() {
FileSystem fileSystem = TestFileSystem.create();
Path templatePath = fileSystem.getPath("/example.vm");
String templateContent = "a $x, $y b";
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/UnixPathTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/UnixPathTest.java
index 01c7e9265ac..ad8c6ea3a35 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/UnixPathTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/file/UnixPathTest.java
@@ -3,19 +3,15 @@
package com.yahoo.vespa.hosted.node.admin.task.util.file;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.ComparisonFailure;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
+import org.opentest4j.AssertionFailedError;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
-import static org.junit.Assert.assertArrayEquals;
-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 hakonhall
@@ -25,7 +21,7 @@ public class UnixPathTest {
private final FileSystem fs = TestFileSystem.create();
@Test
- public void createParents() {
+ void createParents() {
Path parentDirectory = fs.getPath("/a/b/c");
Path filePath = parentDirectory.resolve("bar");
UnixPath path = new UnixPath(filePath);
@@ -36,7 +32,7 @@ public class UnixPathTest {
}
@Test
- public void utf8File() {
+ void utf8File() {
String original = "foo\nbar\n";
UnixPath path = new UnixPath(fs.getPath("example.txt"));
path.writeUtf8File(original);
@@ -45,7 +41,7 @@ public class UnixPathTest {
}
@Test
- public void permissions() {
+ void permissions() {
String expectedPermissions = "rwxr-x---";
UnixPath path = new UnixPath(fs.getPath("file.txt"));
path.writeUtf8File("foo");
@@ -53,13 +49,15 @@ public class UnixPathTest {
assertEquals(expectedPermissions, path.getPermissions());
}
- @Test(expected = IllegalArgumentException.class)
- public void badPermissionsString() {
- new UnixPath(fs.getPath("file.txt")).setPermissions("abcdefghi");
+ @Test
+ void badPermissionsString() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new UnixPath(fs.getPath("file.txt")).setPermissions("abcdefghi");
+ });
}
@Test
- public void owner() {
+ void owner() {
Path path = fs.getPath("file.txt");
UnixPath unixPath = new UnixPath(path);
unixPath.writeUtf8File("foo");
@@ -72,7 +70,7 @@ public class UnixPathTest {
}
@Test
- public void createDirectoryWithPermissions() {
+ void createDirectoryWithPermissions() {
Path path = fs.getPath("dir");
UnixPath unixPath = new UnixPath(path);
String permissions = "rwxr-xr--";
@@ -82,7 +80,7 @@ public class UnixPathTest {
}
@Test
- public void createSymbolicLink() {
+ void createSymbolicLink() {
String original = "foo\nbar\n";
UnixPath path = new UnixPath(fs.getPath("example.txt"));
path.writeUtf8File(original);
@@ -94,7 +92,7 @@ public class UnixPathTest {
}
@Test
- public void readBytesIfExists() {
+ void readBytesIfExists() {
UnixPath path = new UnixPath(fs.getPath("example.txt"));
assertFalse(path.readBytesIfExists().isPresent());
path.writeBytes(new byte[]{42});
@@ -102,7 +100,7 @@ public class UnixPathTest {
}
@Test
- public void deleteRecursively() throws Exception {
+ void deleteRecursively() throws Exception {
// Create the following file tree:
//
// /dir1
@@ -118,17 +116,17 @@ public class UnixPathTest {
var link1 = Files.createSymbolicLink(fs.getPath("/link1"), dir2);
new UnixPath(link1).deleteRecursively();
- assertTrue("Deleting " + link1 + " recursively does not remove " + dir2, Files.exists(dir2));
- assertTrue("Deleting " + link1 + " recursively does not remove " + file1, Files.exists(file1));
+ assertTrue(Files.exists(dir2), "Deleting " + link1 + " recursively does not remove " + dir2);
+ assertTrue(Files.exists(file1), "Deleting " + link1 + " recursively does not remove " + file1);
new UnixPath(dir1).deleteRecursively();
- assertFalse(dir1 + " deleted recursively", Files.exists(file1));
- assertFalse(dir1 + " deleted recursively", Files.exists(dir2));
- assertFalse(dir1 + " deleted recursively", Files.exists(dir1));
+ assertFalse(Files.exists(file1), dir1 + " deleted recursively");
+ assertFalse(Files.exists(dir2), dir1 + " deleted recursively");
+ assertFalse(Files.exists(dir1), dir1 + " deleted recursively");
}
@Test
- public void isEmptyDirectory() {
+ void isEmptyDirectory() {
var path = new UnixPath((fs.getPath("/foo")));
assertFalse(path.isEmptyDirectory());
@@ -144,7 +142,7 @@ public class UnixPathTest {
}
@Test
- public void atomicWrite() {
+ void atomicWrite() {
var path = new UnixPath(fs.getPath("/dir/foo"));
path.createParents();
path.writeUtf8File("bar");
@@ -153,7 +151,7 @@ public class UnixPathTest {
}
@Test
- public void testParentAndFilename() {
+ void testParentAndFilename() {
var absolutePath = new UnixPath("/foo/bar");
assertEquals("/foo", absolutePath.getParent().toString());
assertEquals("bar", absolutePath.getFilename());
@@ -176,7 +174,7 @@ public class UnixPathTest {
fail("No exception was thrown");
} catch (RuntimeException e) {
if (!baseClass.isInstance(e)) {
- throw new ComparisonFailure("Exception class mismatch", baseClass.getName(), e.getClass().getName());
+ throw new AssertionFailedError("Exception class mismatch", baseClass.getName(), e.getClass().getName());
}
assertEquals(message, e.getMessage());
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/network/IPAddressesTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/network/IPAddressesTest.java
index 703b81af9ae..ed2fad3e979 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/network/IPAddressesTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/network/IPAddressesTest.java
@@ -2,12 +2,13 @@
package com.yahoo.vespa.hosted.node.admin.task.util.network;
import com.google.common.net.InetAddresses;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.net.Inet6Address;
import java.net.InetAddress;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* @author smorgrav
@@ -17,7 +18,7 @@ public class IPAddressesTest {
private final IPAddressesMock mock = new IPAddressesMock();
@Test
- public void choose_sitelocal_ipv4_over_public() {
+ void choose_sitelocal_ipv4_over_public() {
mock.addAddress("localhost", "38.3.4.2")
.addAddress("localhost", "10.0.2.2")
.addAddress("localhost", "fe80::1")
@@ -27,7 +28,7 @@ public class IPAddressesTest {
}
@Test
- public void choose_ipv6_public_over_local() {
+ void choose_ipv6_public_over_local() {
mock.addAddress("localhost", "38.3.4.2")
.addAddress("localhost", "10.0.2.2")
.addAddress("localhost", "fe80::1")
@@ -36,23 +37,27 @@ public class IPAddressesTest {
assertEquals(InetAddresses.forString("2001::1"), mock.getIPv6Address("localhost").get());
}
- @Test(expected = RuntimeException.class)
- public void throws_when_multiple_ipv6_addresses() {
- mock.addAddress("localhost", "2001::1")
- .addAddress("localhost", "2001::2");
- mock.getIPv6Address("localhost");
+ @Test
+ void throws_when_multiple_ipv6_addresses() {
+ assertThrows(RuntimeException.class, () -> {
+ mock.addAddress("localhost", "2001::1")
+ .addAddress("localhost", "2001::2");
+ mock.getIPv6Address("localhost");
+ });
}
- @Test(expected = RuntimeException.class)
- public void throws_when_multiple_private_ipv4_addresses() {
- mock.addAddress("localhost", "38.3.4.2")
- .addAddress("localhost", "10.0.2.2")
- .addAddress("localhost", "10.0.2.3");
- mock.getIPv4Address("localhost");
+ @Test
+ void throws_when_multiple_private_ipv4_addresses() {
+ assertThrows(RuntimeException.class, () -> {
+ mock.addAddress("localhost", "38.3.4.2")
+ .addAddress("localhost", "10.0.2.2")
+ .addAddress("localhost", "10.0.2.3");
+ mock.getIPv4Address("localhost");
+ });
}
@Test
- public void translator_with_valid_parameters() {
+ void translator_with_valid_parameters() {
// Test simplest possible address
Inet6Address original = (Inet6Address) InetAddresses.forString("2001:db8::1");
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/process/ChildProcess2ImplTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/process/ChildProcess2ImplTest.java
index a4220956272..f209290cb14 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/process/ChildProcess2ImplTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/process/ChildProcess2ImplTest.java
@@ -3,8 +3,8 @@ package com.yahoo.vespa.hosted.node.admin.task.util.process;
import com.yahoo.jdisc.Timer;
import com.yahoo.vespa.test.file.TestFileSystem;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@@ -14,8 +14,8 @@ import java.nio.file.Path;
import java.time.Duration;
import java.time.Instant;
-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;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.Mockito.mock;
@@ -31,13 +31,13 @@ public class ChildProcess2ImplTest {
private final ProcessApi2 processApi = mock(ProcessApi2.class);
private Path temporaryFile;
- @Before
+ @BeforeEach
public void setUp() throws IOException {
temporaryFile = Files.createTempFile(fileSystem.getPath("/"), "", "");
}
@Test
- public void testSuccess() throws Exception {
+ void testSuccess() throws Exception {
when(commandLine.getTimeout()).thenReturn(Duration.ofHours(1));
when(commandLine.getMaxOutputBytes()).thenReturn(10L);
when(commandLine.getOutputEncoding()).thenReturn(StandardCharsets.UTF_8);
@@ -52,13 +52,13 @@ public class ChildProcess2ImplTest {
when(processApi.waitFor(anyLong(), any())).thenReturn(true);
try (ChildProcess2Impl child =
- new ChildProcess2Impl(commandLine, processApi, temporaryFile, timer)) {
+ new ChildProcess2Impl(commandLine, processApi, temporaryFile, timer)) {
child.waitForTermination();
}
}
@Test
- public void testTimeout() throws Exception {
+ void testTimeout() throws Exception {
when(commandLine.getTimeout()).thenReturn(Duration.ofSeconds(1));
when(commandLine.getMaxOutputBytes()).thenReturn(10L);
when(commandLine.getOutputEncoding()).thenReturn(StandardCharsets.UTF_8);
@@ -73,7 +73,7 @@ public class ChildProcess2ImplTest {
when(processApi.waitFor(anyLong(), any())).thenReturn(true);
try (ChildProcess2Impl child =
- new ChildProcess2Impl(commandLine, processApi, temporaryFile, timer)) {
+ new ChildProcess2Impl(commandLine, processApi, temporaryFile, timer)) {
try {
child.waitForTermination();
fail();
@@ -86,7 +86,7 @@ public class ChildProcess2ImplTest {
}
@Test
- public void testMaxOutputBytes() throws Exception {
+ void testMaxOutputBytes() throws Exception {
when(commandLine.getTimeout()).thenReturn(Duration.ofSeconds(1));
when(commandLine.getMaxOutputBytes()).thenReturn(10L);
when(commandLine.getOutputEncoding()).thenReturn(StandardCharsets.UTF_8);
@@ -103,7 +103,7 @@ public class ChildProcess2ImplTest {
Files.write(temporaryFile, "1234567890123".getBytes(StandardCharsets.UTF_8));
try (ChildProcess2Impl child =
- new ChildProcess2Impl(commandLine, processApi, temporaryFile, timer)) {
+ new ChildProcess2Impl(commandLine, processApi, temporaryFile, timer)) {
try {
child.waitForTermination();
fail();
@@ -116,7 +116,7 @@ public class ChildProcess2ImplTest {
}
@Test
- public void testUnkillable() throws Exception {
+ void testUnkillable() throws Exception {
when(commandLine.getTimeout()).thenReturn(Duration.ofSeconds(1));
when(commandLine.getMaxOutputBytes()).thenReturn(10L);
when(commandLine.getOutputEncoding()).thenReturn(StandardCharsets.UTF_8);
@@ -133,7 +133,7 @@ public class ChildProcess2ImplTest {
Files.write(temporaryFile, "1234567890123".getBytes(StandardCharsets.UTF_8));
try (ChildProcess2Impl child =
- new ChildProcess2Impl(commandLine, processApi, temporaryFile, timer)) {
+ new ChildProcess2Impl(commandLine, processApi, temporaryFile, timer)) {
try {
child.waitForTermination();
fail();
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/process/CommandLineTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/process/CommandLineTest.java
index e434274aacc..872a730c342 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/process/CommandLineTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/process/CommandLineTest.java
@@ -2,31 +2,28 @@
package com.yahoo.vespa.hosted.node.admin.task.util.process;
import com.yahoo.vespa.hosted.node.admin.component.TestTaskContext;
-import org.junit.After;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;
-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 CommandLineTest {
private final TestTerminal terminal = new TestTerminal();
private final TestTaskContext context = new TestTaskContext();
private final CommandLine commandLine = terminal.newCommandLine(context);
- @After
+ @AfterEach
public void tearDown() {
terminal.verifyAllCommandsExecuted();
}
@Test
- public void testStrings() {
+ void testStrings() {
terminal.expectCommand(
"/bin/bash \"with space\" \"speci&l\" \"\" \"double\\\"quote\" 2>&1",
0,
@@ -36,7 +33,7 @@ public class CommandLineTest {
}
@Test
- public void testBasicExecute() {
+ void testBasicExecute() {
terminal.expectCommand("foo bar 2>&1", 0, "line1\nline2\n\n");
CommandResult result = commandLine.add("foo", "bar").execute();
assertEquals(0, result.getExitCode());
@@ -48,14 +45,14 @@ public class CommandLineTest {
List<CommandLine> commandLines = terminal.getTestProcessFactory().getMutableCommandLines();
assertEquals(1, commandLines.size());
- assertTrue(commandLine == commandLines.get(0));
+ assertEquals(commandLine, commandLines.get(0));
int lines = result.map(r -> r.getOutputLines().size());
assertEquals(2, lines);
}
@Test
- public void verifyDefaults() {
+ void verifyDefaults() {
assertEquals(CommandLine.DEFAULT_TIMEOUT, commandLine.getTimeout());
assertEquals(CommandLine.DEFAULT_MAX_OUTPUT_BYTES, commandLine.getMaxOutputBytes());
assertEquals(CommandLine.DEFAULT_SIGTERM_GRACE_PERIOD, commandLine.getSigTermGracePeriod());
@@ -70,7 +67,7 @@ public class CommandLineTest {
}
@Test
- public void executeSilently() {
+ void executeSilently() {
terminal.ignoreCommand("");
commandLine.add("foo", "bar").executeSilently();
assertEquals(0, context.getSystemModificationLog().size());
@@ -79,16 +76,20 @@ public class CommandLineTest {
assertEquals("Executed command: foo bar 2>&1", context.getSystemModificationLog().get(0));
}
- @Test(expected = NegativeArraySizeException.class)
- public void processFactorySpawnFails() {
- terminal.interceptCommand(
- commandLine.toString(),
- command -> { throw new NegativeArraySizeException(); });
- commandLine.add("foo").execute();
+ @Test
+ void processFactorySpawnFails() {
+ assertThrows(NegativeArraySizeException.class, () -> {
+ terminal.interceptCommand(
+ commandLine.toString(),
+ command -> {
+ throw new NegativeArraySizeException();
+ });
+ commandLine.add("foo").execute();
+ });
}
@Test
- public void waitingForTerminationExceptionStillClosesChild() {
+ void waitingForTerminationExceptionStillClosesChild() {
TestChildProcess2 child = new TestChildProcess2(0, "");
child.throwInWaitForTermination(new NegativeArraySizeException());
terminal.interceptCommand(commandLine.toString(), command -> child);
@@ -104,7 +105,7 @@ public class CommandLineTest {
}
@Test
- public void programFails() {
+ void programFails() {
terminal.expectCommand("foo 2>&1", 1, "");
try {
commandLine.add("foo").execute();
@@ -117,22 +118,24 @@ public class CommandLineTest {
}
@Test
- public void mapException() {
+ void mapException() {
terminal.ignoreCommand("output");
CommandResult result = terminal.newCommandLine(context).add("program").execute();
IllegalArgumentException exception = new IllegalArgumentException("foo");
try {
- result.mapOutput(output -> { throw exception; });
+ result.mapOutput(output -> {
+ throw exception;
+ });
fail();
} catch (UnexpectedOutputException e) {
assertEquals("Command 'program 2>&1' output was not of the expected format: " +
"Failed to map output: stdout/stderr: 'output'", e.getMessage());
- assertTrue(e.getCause() == exception);
+ assertEquals(e.getCause(), exception);
}
}
@Test
- public void testMapEachLine() {
+ void testMapEachLine() {
assertEquals(
1 + 2 + 3,
terminal.ignoreCommand("1\n2\n3\n")
@@ -146,7 +149,7 @@ public class CommandLineTest {
}
@Test
- public void addTokensWithMultipleWhiteSpaces() {
+ void addTokensWithMultipleWhiteSpaces() {
terminal.expectCommand("iptables -L 2>&1");
commandLine.addTokens("iptables -L").execute();
@@ -154,7 +157,7 @@ public class CommandLineTest {
}
@Test
- public void addTokensWithSpecialCharacters() {
+ void addTokensWithSpecialCharacters() {
terminal.expectCommand("find . ! -name hei 2>&1");
commandLine.addTokens("find . ! -name hei").execute();
@@ -162,7 +165,7 @@ public class CommandLineTest {
}
@Test
- public void testEnvironment() {
+ void testEnvironment() {
terminal.expectCommand("env k1=v1 -u k2 \"key 3=value 3\" programname 2>&1");
commandLine.add("programname")
.setEnvironmentVariable("key 3", "value 3")
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/process/ProcessFactoryImplTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/process/ProcessFactoryImplTest.java
index 722abe1f7bd..ebf5f45f51e 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/process/ProcessFactoryImplTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/process/ProcessFactoryImplTest.java
@@ -3,7 +3,7 @@ package com.yahoo.vespa.hosted.node.admin.task.util.process;
import com.yahoo.vespa.hosted.node.admin.task.util.file.UnixPath;
import com.yahoo.jdisc.test.TestTimer;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.nio.file.Files;
@@ -16,9 +16,7 @@ import java.util.Optional;
import java.util.Set;
import static com.yahoo.yolean.Exceptions.uncheck;
-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.*;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -29,7 +27,7 @@ public class ProcessFactoryImplTest {
private final ProcessFactoryImpl processFactory = new ProcessFactoryImpl(starter, timer);
@Test
- public void testSpawn() {
+ void testSpawn() {
CommandLine commandLine = mock(CommandLine.class);
when(commandLine.getArguments()).thenReturn(List.of("program"));
when(commandLine.getRedirectStderrToStdoutInsteadOfDiscard()).thenReturn(true);
@@ -53,17 +51,22 @@ public class ProcessFactoryImplTest {
}
@Test
- public void testSpawnWithPersistentOutputFile() {
+ void testSpawnWithPersistentOutputFile() {
class TemporaryFile implements AutoCloseable {
private final Path path;
+
private TemporaryFile() {
String outputFileName = ProcessFactoryImplTest.class.getSimpleName() + "-temporary-test-file.out";
FileAttribute<Set<PosixFilePermission>> fileAttribute = PosixFilePermissions.asFileAttribute(
PosixFilePermissions.fromString("rw-------"));
path = uncheck(() -> Files.createTempFile(outputFileName, ".out", fileAttribute));
}
- @Override public void close() { uncheck(() -> Files.deleteIfExists(path)); }
+
+ @Override
+ public void close() {
+ uncheck(() -> Files.deleteIfExists(path));
+ }
}
try (TemporaryFile outputPath = new TemporaryFile()) {
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/systemd/SystemCtlTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/systemd/SystemCtlTest.java
index eea6c744bab..8eb1fca9210 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/systemd/SystemCtlTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/systemd/SystemCtlTest.java
@@ -4,11 +4,9 @@ package com.yahoo.vespa.hosted.node.admin.task.util.systemd;
import com.yahoo.vespa.hosted.node.admin.component.TaskContext;
import com.yahoo.vespa.hosted.node.admin.task.util.process.ChildProcessFailureException;
import com.yahoo.vespa.hosted.node.admin.task.util.process.TestTerminal;
-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.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.mock;
/**
@@ -20,18 +18,18 @@ public class SystemCtlTest {
private final TestTerminal terminal = new TestTerminal();
@Test
- public void enable() {
+ void enable() {
terminal.expectCommand("systemctl --quiet is-enabled docker 2>&1", 1, "")
.expectCommand("systemctl enable docker 2>&1")
.expectCommand("systemctl --quiet is-enabled docker 2>&1");
SystemCtl.SystemCtlEnable enableDockerService = new SystemCtl(terminal).enable("docker");
assertTrue(enableDockerService.converge(taskContext));
- assertFalse("Already converged", enableDockerService.converge(taskContext));
+ assertFalse(enableDockerService.converge(taskContext), "Already converged");
}
@Test
- public void enableCommandFailure() {
+ void enableCommandFailure() {
terminal.expectCommand("systemctl --quiet is-enabled docker 2>&1", 1, "")
.expectCommand("systemctl enable docker 2>&1", 1, "error enabling service");
SystemCtl.SystemCtlEnable enableDockerService = new SystemCtl(terminal).enable("docker");
@@ -45,13 +43,13 @@ public class SystemCtlTest {
@Test
- public void start() {
+ void start() {
terminal.expectCommand(
- "systemctl show docker 2>&1",
- 0,
- "a=b\n" +
- "ActiveState=failed\n" +
- "bar=zoo\n")
+ "systemctl show docker 2>&1",
+ 0,
+ "a=b\n" +
+ "ActiveState=failed\n" +
+ "bar=zoo\n")
.expectCommand("systemctl start docker 2>&1", 0, "");
SystemCtl.SystemCtlStart startDockerService = new SystemCtl(terminal).start("docker");
@@ -59,13 +57,13 @@ public class SystemCtlTest {
}
@Test
- public void startIsNoop() {
+ void startIsNoop() {
terminal.expectCommand(
- "systemctl show docker 2>&1",
- 0,
- "a=b\n" +
- "ActiveState=active\n" +
- "bar=zoo\n")
+ "systemctl show docker 2>&1",
+ 0,
+ "a=b\n" +
+ "ActiveState=active\n" +
+ "bar=zoo\n")
.expectCommand("systemctl start docker 2>&1", 0, "");
SystemCtl.SystemCtlStart startDockerService = new SystemCtl(terminal).start("docker");
@@ -74,7 +72,7 @@ public class SystemCtlTest {
@Test
- public void startCommandFailre() {
+ void startCommandFailre() {
terminal.expectCommand("systemctl show docker 2>&1", 1, "error");
SystemCtl.SystemCtlStart startDockerService = new SystemCtl(terminal).start("docker");
try {
@@ -87,36 +85,36 @@ public class SystemCtlTest {
@Test
- public void disable() {
+ void disable() {
terminal.expectCommand("systemctl --quiet is-enabled docker 2>&1")
.expectCommand("systemctl disable docker 2>&1")
.expectCommand("systemctl --quiet is-enabled docker 2>&1", 1, "");
assertTrue(new SystemCtl(terminal).disable("docker").converge(taskContext));
- assertFalse("Already converged", new SystemCtl(terminal).disable("docker").converge(taskContext));
+ assertFalse(new SystemCtl(terminal).disable("docker").converge(taskContext), "Already converged");
}
@Test
- public void stop() {
+ void stop() {
terminal.expectCommand(
- "systemctl show docker 2>&1",
- 0,
- "a=b\n" +
- "ActiveState=active\n" +
- "bar=zoo\n")
+ "systemctl show docker 2>&1",
+ 0,
+ "a=b\n" +
+ "ActiveState=active\n" +
+ "bar=zoo\n")
.expectCommand("systemctl stop docker 2>&1", 0, "");
assertTrue(new SystemCtl(terminal).stop("docker").converge(taskContext));
}
@Test
- public void restart() {
+ void restart() {
terminal.expectCommand("systemctl restart docker 2>&1", 0, "");
assertTrue(new SystemCtl(terminal).restart("docker").converge(taskContext));
}
@Test
- public void testUnitExists() {
+ void testUnitExists() {
SystemCtl systemCtl = new SystemCtl(terminal);
terminal.expectCommand("systemctl list-unit-files foo.service 2>&1", 0,
@@ -142,7 +140,7 @@ public class SystemCtlTest {
}
@Test
- public void withSudo() {
+ void withSudo() {
SystemCtl systemCtl = new SystemCtl(terminal).withSudo();
terminal.expectCommand("sudo systemctl restart docker 2>&1", 0, "");
assertTrue(systemCtl.restart("docker").converge(taskContext));
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/systemd/SystemCtlTesterTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/systemd/SystemCtlTesterTest.java
index 7b18f741941..bbdb707c294 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/systemd/SystemCtlTesterTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/systemd/SystemCtlTesterTest.java
@@ -3,12 +3,12 @@ package com.yahoo.vespa.hosted.node.admin.task.util.systemd;
import com.yahoo.vespa.hosted.node.admin.component.TestTaskContext;
import com.yahoo.vespa.hosted.node.admin.task.util.process.TestTerminal;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.function.Function;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author freva
@@ -21,7 +21,7 @@ public class SystemCtlTesterTest {
private final TestTaskContext context = new TestTaskContext();
@Test
- public void return_expectations() {
+ void return_expectations() {
assertSystemCtlMethod(sct -> sct.expectEnable(unit), sc -> sc.enable(unit).converge(context));
assertSystemCtlMethod(sct -> sct.expectDisable(unit), sc -> sc.disable(unit).converge(context));
assertSystemCtlMethod(sct -> sct.expectStart(unit), sc -> sc.start(unit).converge(context));
@@ -31,7 +31,7 @@ public class SystemCtlTesterTest {
}
@Test
- public void void_tests() {
+ void void_tests() {
systemCtl.expectRestart(unit);
systemCtl.restart(unit).converge(context);
terminal.verifyAllCommandsExecuted();
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/yum/YumPackageNameTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/yum/YumPackageNameTest.java
index 0ff98e2b5fe..d32447d9052 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/yum/YumPackageNameTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/yum/YumPackageNameTest.java
@@ -1,14 +1,11 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.hosted.node.admin.task.util.yum;
-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.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author hakonhall
@@ -16,7 +13,7 @@ import static org.junit.Assert.fail;
public class YumPackageNameTest {
@Test
- public void testBuilder() {
+ void testBuilder() {
YumPackageName yumPackage = new YumPackageName.Builder("docker")
.setEpoch("2")
.setVersion("1.12.6")
@@ -27,7 +24,7 @@ public class YumPackageNameTest {
}
@Test
- public void testAllValidFormats() {
+ void testAllValidFormats() {
// name
verifyPackageName(
"docker-engine-selinux",
@@ -63,13 +60,13 @@ public class YumPackageNameTest {
// name-ver
verifyPackageName("docker-engine-selinux-1.12.6",
- null,
- "docker-engine-selinux",
- "1.12.6",
- null,
- null,
- "docker-engine-selinux-0:1.12.6",
- null);
+ null,
+ "docker-engine-selinux",
+ "1.12.6",
+ null,
+ null,
+ "docker-engine-selinux-0:1.12.6",
+ null);
// name-ver-rel
verifyPackageName("docker-engine-selinux-1.12.6-1.el7",
@@ -135,9 +132,9 @@ public class YumPackageNameTest {
yumPackageName.toVersionLockName();
fail();
} catch (IllegalStateException e) {
- assertTrue("Exception message contains expected substring: " + e.getMessage(),
- e.getMessage().contains("Version is missing ") ||
- e.getMessage().contains("Release is missing "));
+ assertTrue(e.getMessage().contains("Version is missing ") ||
+ e.getMessage().contains("Release is missing "),
+ "Exception message contains expected substring: " + e.getMessage());
}
} else {
assertEquals(toVersionName, yumPackageName.toVersionLockName());
@@ -146,28 +143,28 @@ public class YumPackageNameTest {
private void assertPackageField(String field, String expected, Optional<String> actual) {
if (expected == null) {
- assertFalse(field + " is not present", actual.isPresent());
+ assertFalse(actual.isPresent(), field + " is not present");
} else {
- assertEquals(field + " has expected value", expected, actual.get());
+ assertEquals(expected, actual.get(), field + " has expected value");
}
}
@Test
- public void testArchitectures() {
+ void testArchitectures() {
assertEquals("x86_64", YumPackageName.fromString("docker.x86_64").getArchitecture().get());
assertEquals("i686", YumPackageName.fromString("docker.i686").getArchitecture().get());
assertEquals("noarch", YumPackageName.fromString("docker.noarch").getArchitecture().get());
}
@Test
- public void unrecognizedArchitectureGetsGobbledUp() {
+ void unrecognizedArchitectureGetsGobbledUp() {
YumPackageName packageName = YumPackageName.fromString("docker-engine-selinux-1.12.6-1.el7.i486");
// This is not a great feature - please use YumPackageName.Builder instead.
assertEquals("1.el7.i486", packageName.getRelease().get());
}
@Test
- public void failParsingOfPackageNameWithEpochAndArchitecture() {
+ void failParsingOfPackageNameWithEpochAndArchitecture() {
try {
YumPackageName.fromString("epoch:docker-engine-selinux-1.12.6-1.el7.x86_64");
fail();
@@ -177,7 +174,7 @@ public class YumPackageNameTest {
}
@Test
- public void testSubset() {
+ void testSubset() {
YumPackageName yumPackage = new YumPackageName.Builder("docker")
.setVersion("1.12.6")
.build();
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/yum/YumTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/yum/YumTest.java
index 3376ba70500..8c9e36abb32 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/yum/YumTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/yum/YumTest.java
@@ -4,16 +4,12 @@ package com.yahoo.vespa.hosted.node.admin.task.util.yum;
import com.yahoo.vespa.hosted.node.admin.component.TaskContext;
import com.yahoo.vespa.hosted.node.admin.task.util.process.ChildProcessFailureException;
import com.yahoo.vespa.hosted.node.admin.task.util.process.TestTerminal;
-import org.junit.After;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+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.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.mock;
/**
@@ -25,13 +21,13 @@ public class YumTest {
private final TestTerminal terminal = new TestTerminal();
private final Yum yum = new Yum(terminal);
- @After
+ @AfterEach
public void after() {
terminal.verifyAllCommandsExecuted();
}
@Test
- public void testQueryInstalled() {
+ void testQueryInstalled() {
terminal.expectCommand(
"rpm -q docker --queryformat \"%{NAME}\\\\n%{EPOCH}\\\\n%{VERSION}\\\\n%{RELEASE}\\\\n%{ARCH}\" 2>&1",
0,
@@ -48,7 +44,7 @@ public class YumTest {
}
@Test
- public void testQueryInstalledPartial() {
+ void testQueryInstalledPartial() {
terminal.expectCommand(
"rpm -q vespa-node-admin --queryformat \"%{NAME}\\\\n%{EPOCH}\\\\n%{VERSION}\\\\n%{RELEASE}\\\\n%{ARCH}\" 2>&1",
0,
@@ -65,7 +61,7 @@ public class YumTest {
}
@Test
- public void testQueryNotInstalled() {
+ void testQueryNotInstalled() {
terminal.expectCommand(
"rpm -q fake-package --queryformat \"%{NAME}\\\\n%{EPOCH}\\\\n%{VERSION}\\\\n%{RELEASE}\\\\n%{ARCH}\" 2>&1",
1,
@@ -77,20 +73,20 @@ public class YumTest {
}
@Test
- public void testQueryInstalledMultiplePackages() {
+ void testQueryInstalledMultiplePackages() {
terminal.expectCommand(
"rpm -q kernel-devel --queryformat \"%{NAME}\\\\n%{EPOCH}\\\\n%{VERSION}\\\\n%{RELEASE}\\\\n%{ARCH}\" 2>&1",
0,
"kernel-devel\n" +
- "(none)\n" +
- "4.18.0\n" +
- "305.7.1.el8_4\n" +
- "x86_64\n" +
- "kernel-devel\n" +
- "(none)\n" +
- "4.18.0\n" +
- "240.15.1.el8_3\n" +
- "x86_64\n");
+ "(none)\n" +
+ "4.18.0\n" +
+ "305.7.1.el8_4\n" +
+ "x86_64\n" +
+ "kernel-devel\n" +
+ "(none)\n" +
+ "4.18.0\n" +
+ "240.15.1.el8_3\n" +
+ "x86_64\n");
try {
yum.queryInstalled(taskContext, "kernel-devel");
fail("Expected exception");
@@ -100,30 +96,30 @@ public class YumTest {
}
@Test
- public void testAlreadyInstalled() {
+ void testAlreadyInstalled() {
mockRpmQuery("package-1", null);
terminal.expectCommand(
"yum install --assumeyes --enablerepo=repo1 --enablerepo=repo2 --setopt skip_missing_names_on_install=False package-1 package-2 2>&1",
0,
"foobar\nNothing to do.\n"); // Note trailing dot
assertFalse(yum.install("package-1", "package-2")
- .enableRepo("repo1", "repo2")
- .converge(taskContext));
+ .enableRepo("repo1", "repo2")
+ .converge(taskContext));
}
@Test
- public void testAlreadyUpgraded() {
+ void testAlreadyUpgraded() {
terminal.expectCommand(
"yum upgrade --assumeyes --setopt skip_missing_names_on_update=False package-1 package-2 2>&1",
0,
"foobar\nNothing to do.\n"); // Same message as yum install no-op
assertFalse(yum.upgrade("package-1", "package-2")
- .converge(taskContext));
+ .converge(taskContext));
}
@Test
- public void testAlreadyRemoved() {
+ void testAlreadyRemoved() {
mockRpmQuery("package-1", YumPackageName.fromString("package-1-1.2.3-1"));
terminal.expectCommand(
"yum remove --assumeyes package-1 package-2 2>&1",
@@ -131,18 +127,18 @@ public class YumTest {
"foobar\nNo packages marked for removal.\n"); // Different output
assertFalse(yum.remove("package-1", "package-2")
- .converge(taskContext));
+ .converge(taskContext));
}
@Test
- public void skipsYumRemoveNotInRpm() {
+ void skipsYumRemoveNotInRpm() {
mockRpmQuery("package-1", null);
mockRpmQuery("package-2", null);
assertFalse(yum.remove("package-1", "package-2").converge(taskContext));
}
@Test
- public void testInstall() {
+ void testInstall() {
mockRpmQuery("package-1", null);
terminal.expectCommand(
"yum install --assumeyes --setopt skip_missing_names_on_install=False package-1 package-2 2>&1",
@@ -155,14 +151,14 @@ public class YumTest {
}
@Test
- public void skipsYumInstallIfInRpm() {
+ void skipsYumInstallIfInRpm() {
mockRpmQuery("package-1-0:1.2.3-1", YumPackageName.fromString("package-1-1.2.3-1"));
mockRpmQuery("package-2", YumPackageName.fromString("1:package-2-1.2.3-1.el7.x86_64"));
assertFalse(yum.install("package-1-1.2.3-1", "package-2").converge(taskContext));
}
@Test
- public void testInstallWithEnablerepo() {
+ void testInstallWithEnablerepo() {
mockRpmQuery("package-1", null);
terminal.expectCommand(
"yum install --assumeyes --enablerepo=repo-name --setopt skip_missing_names_on_install=False package-1 package-2 2>&1",
@@ -176,10 +172,10 @@ public class YumTest {
}
@Test
- public void testWithVersionLock() {
+ void testWithVersionLock() {
terminal.expectCommand("yum versionlock list 2>&1",
- 0,
- "Last metadata expiration check: 0:51:26 ago on Thu 14 Jan 2021 09:39:24 AM UTC.\n");
+ 0,
+ "Last metadata expiration check: 0:51:26 ago on Thu 14 Jan 2021 09:39:24 AM UTC.\n");
terminal.expectCommand("yum versionlock add --assumeyes \"openssh-0:8.0p1-4.el8_1.*\" 2>&1");
terminal.expectCommand(
"yum install --assumeyes openssh-0:8.0p1-4.el8_1.x86_64 2>&1",
@@ -196,7 +192,7 @@ public class YumTest {
}
@Test
- public void testWithDifferentVersionLock() {
+ void testWithDifferentVersionLock() {
terminal.expectCommand("yum versionlock list 2>&1",
0,
"Repository chef_rpms-release is listed more than once in the configuration\n" +
@@ -220,7 +216,7 @@ public class YumTest {
}
@Test
- public void testWithExistingVersionLock() {
+ void testWithExistingVersionLock() {
terminal.expectCommand("yum versionlock list 2>&1",
0,
"Repository chef_rpms-release is listed more than once in the configuration\n" +
@@ -235,7 +231,7 @@ public class YumTest {
}
@Test
- public void testWithDowngrade() {
+ void testWithDowngrade() {
terminal.expectCommand("yum versionlock list 2>&1",
0,
"Repository chef_rpms-release is listed more than once in the configuration\n" +
@@ -253,23 +249,25 @@ public class YumTest {
assertTrue(yum.installFixedVersion(YumPackageName.fromString("package-0:0.10-654.el7")).converge(taskContext));
}
- @Test(expected = ChildProcessFailureException.class)
- public void testFailedInstall() {
- mockRpmQuery("package-1", null);
- terminal.expectCommand(
- "yum install --assumeyes --enablerepo=repo-name --setopt skip_missing_names_on_install=False package-1 package-2 2>&1",
- 1,
- "error");
-
- yum
- .install("package-1", "package-2")
- .enableRepo("repo-name")
- .converge(taskContext);
- fail();
+ @Test
+ void testFailedInstall() {
+ assertThrows(ChildProcessFailureException.class, () -> {
+ mockRpmQuery("package-1", null);
+ terminal.expectCommand(
+ "yum install --assumeyes --enablerepo=repo-name --setopt skip_missing_names_on_install=False package-1 package-2 2>&1",
+ 1,
+ "error");
+
+ yum
+ .install("package-1", "package-2")
+ .enableRepo("repo-name")
+ .converge(taskContext);
+ fail();
+ });
}
@Test
- public void testUnknownPackages() {
+ void testUnknownPackages() {
mockRpmQuery("package-1", null);
terminal.expectCommand(
"yum install --assumeyes --setopt skip_missing_names_on_install=False package-1 package-2 package-3 2>&1",
@@ -290,19 +288,21 @@ public class YumTest {
}
}
- @Test(expected = IllegalArgumentException.class)
- public void throwIfNoPackagesSpecified() {
- yum.install();
+ @Test
+ void throwIfNoPackagesSpecified() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ yum.install();
+ });
}
@Test
- public void allowToCallUpgradeWithNoPackages() {
+ void allowToCallUpgradeWithNoPackages() {
terminal.expectCommand("yum upgrade --assumeyes 2>&1", 0, "OK");
yum.upgrade().converge(taskContext);
}
@Test
- public void testDeleteVersionLock() {
+ void testDeleteVersionLock() {
terminal.expectCommand("yum versionlock delete openssh-0:8.0p1-4.el8_1.x86_64 2>&1");
YumPackageName pkg = new YumPackageName
diff --git a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/yum/YumTesterTest.java b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/yum/YumTesterTest.java
index f5cb188d07a..59c138b51df 100644
--- a/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/yum/YumTesterTest.java
+++ b/node-admin/src/test/java/com/yahoo/vespa/hosted/node/admin/task/util/yum/YumTesterTest.java
@@ -3,13 +3,13 @@ package com.yahoo.vespa.hosted.node.admin.task.util.yum;
import com.yahoo.vespa.hosted.node.admin.component.TestTaskContext;
import com.yahoo.vespa.hosted.node.admin.task.util.process.TestTerminal;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author freva
@@ -26,7 +26,7 @@ public class YumTesterTest {
private final TestTaskContext context = new TestTaskContext();
@Test
- public void generic_yum_methods() {
+ void generic_yum_methods() {
assertYumMethod(yum -> yum.expectInstall(packages).withEnableRepo(repos),
yum -> yum.install(List.of(packages)).enableRepo(repos).converge(context));
@@ -41,12 +41,12 @@ public class YumTesterTest {
// versionlock always returns success
assertYumMethodAlwaysSuccess(yum -> yum.expectDeleteVersionLock(minimalPackage.toName()),
- yum -> yum.deleteVersionLock(minimalPackage).converge(context));
+ yum -> yum.deleteVersionLock(minimalPackage).converge(context));
}
@Test
- public void expect_query_installed() {
+ void expect_query_installed() {
yum.expectQueryInstalled(packages[0]).andReturn(fullPackage);
assertEquals(Optional.of(fullPackage), yum.queryInstalled(context, packages[0]));
terminal.verifyAllCommandsExecuted();
diff --git a/parent/pom.xml b/parent/pom.xml
index 05060c57ec9..ddca2a36696 100644
--- a/parent/pom.xml
+++ b/parent/pom.xml
@@ -301,6 +301,27 @@
</execution>
</executions>
</plugin>
+ <plugin>
+ <!--
+ Configure rewrite-maven-plugin to facilitate Junit4 to Junit5 conversion.
+ Run "mvn rewrite:run" to perform automated rewrite to Junit5.
+ -->
+ <groupId>org.openrewrite.maven</groupId>
+ <artifactId>rewrite-maven-plugin</artifactId>
+ <version>4.27.0</version>
+ <configuration>
+ <activeRecipes>
+ <recipe>org.openrewrite.java.testing.junit5.JUnit5BestPractices</recipe>
+ </activeRecipes>
+ </configuration>
+ <dependencies>
+ <dependency>
+ <groupId>org.openrewrite.recipe</groupId>
+ <artifactId>rewrite-testing-frameworks</artifactId>
+ <version>1.24.0</version>
+ </dependency>
+ </dependencies>
+ </plugin>
</plugins>
</pluginManagement>
</build>
@@ -422,7 +443,6 @@
</profiles>
<dependencyManagement>
<dependencies>
-
<!-- Please keep this list lexically sorted by groupId, then artifactId.-->
<dependency>
@@ -474,6 +494,11 @@
<version>2.6.0</version>
</dependency>
<dependency>
+ <groupId>com.github.tomakehurst</groupId>
+ <artifactId>wiremock-jre8-standalone</artifactId>
+ <version>2.33.2</version>
+ </dependency>
+ <dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>${findbugs.version}</version>
@@ -919,6 +944,15 @@
<scope>test</scope> <!-- TODO: remove scope from parent pom -->
</dependency>
<dependency>
+ <!-- Facilitates automated Junit4 to Junit5 conversion.
+ See pluginManagement of rewrite-maven-plugin for more details -->
+ <groupId>org.openrewrite.recipe</groupId>
+ <artifactId>rewrite-recipe-bom</artifactId>
+ <version>1.5.0</version>
+ <type>pom</type>
+ <scope>import</scope>
+ </dependency>
+ <dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>${asm.version}</version>
@@ -1033,6 +1067,7 @@
<maven-source-plugin.version>3.2.1</maven-source-plugin.version>
<mockito.version>4.0.0</mockito.version>
<onnxruntime.version>1.11.0</onnxruntime.version> <!-- WARNING: sync cloud-tenant-base-dependencies-enforcer/pom.xml -->
+ <org.json.version>20220320</org.json.version>
<org.lz4.version>1.8.0</org.lz4.version>
<prometheus.client.version>0.6.0</prometheus.client.version>
<protobuf.version>3.19.2</protobuf.version>
diff --git a/predicate-search-core/pom.xml b/predicate-search-core/pom.xml
index 4951b3d40f1..0862d76c5a1 100644
--- a/predicate-search-core/pom.xml
+++ b/predicate-search-core/pom.xml
@@ -15,13 +15,14 @@
<name>${project.artifactId}</name>
<dependencies>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>org.antlr</groupId>
<artifactId>antlr-runtime</artifactId>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>com.yahoo.vespa</groupId>
@@ -35,6 +36,16 @@
<scope>provided</scope>
</dependency>
<dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<scope>provided</scope>
diff --git a/predicate-search-core/src/test/java/com/yahoo/document/predicate/BinaryFormatTest.java b/predicate-search-core/src/test/java/com/yahoo/document/predicate/BinaryFormatTest.java
index c37d6b246a5..0f15fcd656a 100644
--- a/predicate-search-core/src/test/java/com/yahoo/document/predicate/BinaryFormatTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/document/predicate/BinaryFormatTest.java
@@ -3,10 +3,10 @@ package com.yahoo.document.predicate;
import com.yahoo.slime.Inspector;
import com.yahoo.slime.Slime;
-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
@@ -14,7 +14,7 @@ import static org.junit.Assert.fail;
public class BinaryFormatTest {
@Test
- public void requireThatEncodeNullThrows() {
+ void requireThatEncodeNullThrows() {
try {
BinaryFormat.encode(null);
fail();
@@ -24,7 +24,7 @@ public class BinaryFormatTest {
}
@Test
- public void requireThatDecodeNullThrows() {
+ void requireThatDecodeNullThrows() {
try {
BinaryFormat.decode(null);
fail();
@@ -34,7 +34,7 @@ public class BinaryFormatTest {
}
@Test
- public void requireThatDecodeEmptyThrows() {
+ void requireThatDecodeEmptyThrows() {
try {
BinaryFormat.decode(new byte[0]);
fail();
@@ -44,17 +44,17 @@ public class BinaryFormatTest {
}
@Test
- public void requireThatConjunctionCanBeSerialized() {
+ void requireThatConjunctionCanBeSerialized() {
assertSerialize(new Conjunction(new FeatureSet("foo", "bar"), new FeatureSet("baz", "cox")));
}
@Test
- public void requireThatDisjunctionCanBeSerialized() {
+ void requireThatDisjunctionCanBeSerialized() {
assertSerialize(new Disjunction(new FeatureSet("foo", "bar"), new FeatureSet("baz", "cox")));
}
@Test
- public void requireThatFeatureRangeCanBeSerialized() {
+ void requireThatFeatureRangeCanBeSerialized() {
assertSerialize(new FeatureRange("foo", null, null));
assertSerialize(new FeatureRange("foo", null, 9L));
assertSerialize(new FeatureRange("foo", 6L, null));
@@ -62,7 +62,7 @@ public class BinaryFormatTest {
}
@Test
- public void requireThatPartitionedFeatureRangeCanBeSerialized() {
+ void requireThatPartitionedFeatureRangeCanBeSerialized() {
FeatureRange expected = new FeatureRange("foo", 8L, 20L);
FeatureRange f = new FeatureRange("foo", 8L, 20L);
f.addPartition(new RangeEdgePartition("foo=0", 0, 8, -1));
@@ -87,25 +87,25 @@ public class BinaryFormatTest {
}
@Test
- public void requireThatFeatureSetCanBeSerialized() {
+ void requireThatFeatureSetCanBeSerialized() {
assertSerialize(new FeatureSet("foo"));
assertSerialize(new FeatureSet("foo", "bar"));
assertSerialize(new FeatureSet("foo", "bar", "baz"));
}
@Test
- public void requireThatNegationCanBeSerialized() {
+ void requireThatNegationCanBeSerialized() {
assertSerialize(new Negation(new FeatureSet("foo", "bar")));
}
@Test
- public void requireThatBooleanCanBeSerialized() {
+ void requireThatBooleanCanBeSerialized() {
assertSerialize(new BooleanPredicate(true));
assertSerialize(new BooleanPredicate(false));
}
@Test
- public void requireThatUnknownNodeThrows() {
+ void requireThatUnknownNodeThrows() {
try {
BinaryFormat.encode(SimplePredicates.newString("foo"));
fail();
diff --git a/predicate-search-core/src/test/java/com/yahoo/document/predicate/BooleanPredicateTest.java b/predicate-search-core/src/test/java/com/yahoo/document/predicate/BooleanPredicateTest.java
index 92c45520504..0dbfdb2559d 100644
--- a/predicate-search-core/src/test/java/com/yahoo/document/predicate/BooleanPredicateTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/document/predicate/BooleanPredicateTest.java
@@ -1,12 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.document.predicate;
-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.assertNotSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -14,12 +11,12 @@ import static org.junit.Assert.assertTrue;
public class BooleanPredicateTest {
@Test
- public void requireThatFalseIsAValue() {
+ void requireThatFalseIsAValue() {
assertTrue(PredicateValue.class.isAssignableFrom(BooleanPredicate.class));
}
@Test
- public void requireThatCloneIsImplemented() throws CloneNotSupportedException {
+ void requireThatCloneIsImplemented() throws CloneNotSupportedException {
BooleanPredicate node1 = new BooleanPredicate(true);
BooleanPredicate node2 = node1.clone();
assertEquals(node1, node2);
@@ -27,21 +24,21 @@ public class BooleanPredicateTest {
}
@Test
- public void requireThatHashCodeIsImplemented() {
+ void requireThatHashCodeIsImplemented() {
assertEquals(new BooleanPredicate(true).hashCode(), new BooleanPredicate(true).hashCode());
assertEquals(new BooleanPredicate(false).hashCode(), new BooleanPredicate(false).hashCode());
}
@Test
- public void requireThatEqualsIsImplemented() {
+ void requireThatEqualsIsImplemented() {
BooleanPredicate lhs = new BooleanPredicate(true);
- assertTrue(lhs.equals(lhs));
- assertFalse(lhs.equals(new Object()));
+ assertEquals(lhs, lhs);
+ assertNotEquals(lhs, new Object());
BooleanPredicate rhs = new BooleanPredicate(false);
- assertFalse(lhs.equals(rhs));
+ assertNotEquals(lhs, rhs);
rhs.setValue(true);
- assertTrue(lhs.equals(rhs));
+ assertEquals(lhs, rhs);
}
}
diff --git a/predicate-search-core/src/test/java/com/yahoo/document/predicate/ConjunctionTest.java b/predicate-search-core/src/test/java/com/yahoo/document/predicate/ConjunctionTest.java
index cbcab2917e5..fa4872715f6 100644
--- a/predicate-search-core/src/test/java/com/yahoo/document/predicate/ConjunctionTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/document/predicate/ConjunctionTest.java
@@ -1,14 +1,11 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.document.predicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -16,12 +13,12 @@ import static org.junit.Assert.assertTrue;
public class ConjunctionTest {
@Test
- public void requireThatConjunctionIsAnOperator() {
+ void requireThatConjunctionIsAnOperator() {
assertTrue(PredicateOperator.class.isAssignableFrom(Conjunction.class));
}
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
Conjunction node = new Conjunction();
Predicate a = SimplePredicates.newString("a");
node.addOperand(a);
@@ -40,7 +37,7 @@ public class ConjunctionTest {
}
@Test
- public void requireThatConstructorsWork() {
+ void requireThatConstructorsWork() {
Predicate foo = SimplePredicates.newString("foo");
Predicate bar = SimplePredicates.newString("bar");
Conjunction node = new Conjunction(foo, bar);
@@ -51,7 +48,7 @@ public class ConjunctionTest {
}
@Test
- public void requireThatCloneIsImplemented() throws CloneNotSupportedException {
+ void requireThatCloneIsImplemented() throws CloneNotSupportedException {
Conjunction node1 = new Conjunction(SimplePredicates.newString("a"), SimplePredicates.newString("b"));
Conjunction node2 = node1.clone();
assertEquals(node1, node2);
@@ -60,27 +57,27 @@ public class ConjunctionTest {
}
@Test
- public void requireThatHashCodeIsImplemented() {
+ void requireThatHashCodeIsImplemented() {
assertEquals(new Conjunction().hashCode(), new Conjunction().hashCode());
}
@Test
- public void requireThatEqualsIsImplemented() {
+ void requireThatEqualsIsImplemented() {
Conjunction lhs = new Conjunction(SimplePredicates.newString("foo"),
- SimplePredicates.newString("bar"));
- assertTrue(lhs.equals(lhs));
- assertFalse(lhs.equals(new Object()));
+ SimplePredicates.newString("bar"));
+ assertEquals(lhs, lhs);
+ assertNotEquals(lhs, new Object());
Conjunction rhs = new Conjunction();
- assertFalse(lhs.equals(rhs));
+ assertNotEquals(lhs, rhs);
rhs.addOperand(SimplePredicates.newString("foo"));
- assertFalse(lhs.equals(rhs));
+ assertNotEquals(lhs, rhs);
rhs.addOperand(SimplePredicates.newString("bar"));
- assertTrue(lhs.equals(rhs));
+ assertEquals(lhs, rhs);
}
@Test
- public void requireThatNodeDelimiterIsAND() {
+ void requireThatNodeDelimiterIsAND() {
assertEquals("", newConjunction().toString());
assertEquals("foo", newConjunction("foo").toString());
assertEquals("foo and bar", newConjunction("foo", "bar").toString());
@@ -88,22 +85,22 @@ public class ConjunctionTest {
}
@Test
- public void requireThatSimpleConjunctionsArePrettyPrinted() {
+ void requireThatSimpleConjunctionsArePrettyPrinted() {
assertEquals("foo and bar",
- new Conjunction(SimplePredicates.newString("foo"),
- SimplePredicates.newString("bar")).toString());
+ new Conjunction(SimplePredicates.newString("foo"),
+ SimplePredicates.newString("bar")).toString());
}
@Test
- public void requireThatComplexConjunctionsArePrintedAsGroup() {
+ void requireThatComplexConjunctionsArePrintedAsGroup() {
assertEquals("foo and bar and baz",
- new Conjunction(SimplePredicates.newString("foo"),
- new Conjunction(SimplePredicates.newString("bar"),
- SimplePredicates.newString("baz"))).toString());
+ new Conjunction(SimplePredicates.newString("foo"),
+ new Conjunction(SimplePredicates.newString("bar"),
+ SimplePredicates.newString("baz"))).toString());
assertEquals("foo and (bar or baz)",
- new Conjunction(SimplePredicates.newString("foo"),
- new Disjunction(SimplePredicates.newString("bar"),
- SimplePredicates.newString("baz"))).toString());
+ new Conjunction(SimplePredicates.newString("foo"),
+ new Disjunction(SimplePredicates.newString("bar"),
+ SimplePredicates.newString("baz"))).toString());
}
private static Conjunction newConjunction(String... operands) {
diff --git a/predicate-search-core/src/test/java/com/yahoo/document/predicate/DisjunctionTest.java b/predicate-search-core/src/test/java/com/yahoo/document/predicate/DisjunctionTest.java
index 1dab0dd80a2..d5640c7f0a2 100644
--- a/predicate-search-core/src/test/java/com/yahoo/document/predicate/DisjunctionTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/document/predicate/DisjunctionTest.java
@@ -1,14 +1,11 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.document.predicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -16,12 +13,12 @@ import static org.junit.Assert.assertTrue;
public class DisjunctionTest {
@Test
- public void requireThatDisjunctionIsAnOperator() {
+ void requireThatDisjunctionIsAnOperator() {
assertTrue(PredicateOperator.class.isAssignableFrom(Disjunction.class));
}
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
Disjunction node = new Disjunction();
Predicate a = SimplePredicates.newString("a");
node.addOperand(a);
@@ -40,7 +37,7 @@ public class DisjunctionTest {
}
@Test
- public void requireThatConstructorsWork() {
+ void requireThatConstructorsWork() {
Predicate foo = SimplePredicates.newString("foo");
Predicate bar = SimplePredicates.newString("bar");
Disjunction node = new Disjunction(foo, bar);
@@ -51,7 +48,7 @@ public class DisjunctionTest {
}
@Test
- public void requireThatCloneIsImplemented() throws CloneNotSupportedException {
+ void requireThatCloneIsImplemented() throws CloneNotSupportedException {
Disjunction node1 = new Disjunction(SimplePredicates.newString("a"), SimplePredicates.newString("b"));
Disjunction node2 = node1.clone();
assertEquals(node1, node2);
@@ -60,27 +57,27 @@ public class DisjunctionTest {
}
@Test
- public void requireThatHashCodeIsImplemented() {
+ void requireThatHashCodeIsImplemented() {
assertEquals(new Disjunction().hashCode(), new Disjunction().hashCode());
}
@Test
- public void requireThatEqualsIsImplemented() {
+ void requireThatEqualsIsImplemented() {
Disjunction lhs = new Disjunction(SimplePredicates.newString("foo"),
- SimplePredicates.newString("bar"));
- assertTrue(lhs.equals(lhs));
- assertFalse(lhs.equals(new Object()));
+ SimplePredicates.newString("bar"));
+ assertEquals(lhs, lhs);
+ assertNotEquals(lhs, new Object());
Disjunction rhs = new Disjunction();
- assertFalse(lhs.equals(rhs));
+ assertNotEquals(lhs, rhs);
rhs.addOperand(SimplePredicates.newString("foo"));
- assertFalse(lhs.equals(rhs));
+ assertNotEquals(lhs, rhs);
rhs.addOperand(SimplePredicates.newString("bar"));
- assertTrue(lhs.equals(rhs));
+ assertEquals(lhs, rhs);
}
@Test
- public void requireThatNodeDelimiterIsOR() {
+ void requireThatNodeDelimiterIsOR() {
assertEquals("", newDisjunction().toString());
assertEquals("foo", newDisjunction("foo").toString());
assertEquals("foo or bar", newDisjunction("foo", "bar").toString());
@@ -88,22 +85,22 @@ public class DisjunctionTest {
}
@Test
- public void requireThatSimpleDisjunctionsArePrettyPrinted() {
+ void requireThatSimpleDisjunctionsArePrettyPrinted() {
assertEquals("foo or bar",
- new Disjunction(SimplePredicates.newString("foo"),
- SimplePredicates.newString("bar")).toString());
+ new Disjunction(SimplePredicates.newString("foo"),
+ SimplePredicates.newString("bar")).toString());
}
@Test
- public void requireThatComplexDisjunctionsArePrintedAsGroup() {
+ void requireThatComplexDisjunctionsArePrintedAsGroup() {
assertEquals("foo or bar or baz",
- new Disjunction(SimplePredicates.newString("foo"),
- new Disjunction(SimplePredicates.newString("bar"),
- SimplePredicates.newString("baz"))).toString());
+ new Disjunction(SimplePredicates.newString("foo"),
+ new Disjunction(SimplePredicates.newString("bar"),
+ SimplePredicates.newString("baz"))).toString());
assertEquals("foo or (bar and baz)",
- new Disjunction(SimplePredicates.newString("foo"),
- new Conjunction(SimplePredicates.newString("bar"),
- SimplePredicates.newString("baz"))).toString());
+ new Disjunction(SimplePredicates.newString("foo"),
+ new Conjunction(SimplePredicates.newString("bar"),
+ SimplePredicates.newString("baz"))).toString());
}
private static Disjunction newDisjunction(String... operands) {
diff --git a/predicate-search-core/src/test/java/com/yahoo/document/predicate/FeatureConjunctionTest.java b/predicate-search-core/src/test/java/com/yahoo/document/predicate/FeatureConjunctionTest.java
index 059022f87e8..e44fd0e0a78 100644
--- a/predicate-search-core/src/test/java/com/yahoo/document/predicate/FeatureConjunctionTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/document/predicate/FeatureConjunctionTest.java
@@ -1,13 +1,14 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.document.predicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
import static com.yahoo.document.predicate.Predicates.feature;
import static com.yahoo.document.predicate.Predicates.not;
+import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* @author bjorncs
@@ -15,38 +16,48 @@ import static com.yahoo.document.predicate.Predicates.not;
public class FeatureConjunctionTest {
@Test
- public void require_that_featureconjunction_with_valid_operands_can_be_constructed() {
+ void require_that_featureconjunction_with_valid_operands_can_be_constructed() {
new FeatureConjunction(Arrays.asList(
not(feature("a").inSet("1")),
feature("b").inSet("1")));
}
- @Test(expected = IllegalArgumentException.class)
- public void require_that_constructor_throws_exception_if_all_operands_are_not_featuresets() {
- new FeatureConjunction(Arrays.asList(
- not(feature("a").inSet("1")),
- feature("b").inRange(1, 2)));
+ @Test
+ void require_that_constructor_throws_exception_if_all_operands_are_not_featuresets() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new FeatureConjunction(Arrays.asList(
+ not(feature("a").inSet("1")),
+ feature("b").inRange(1, 2)));
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void require_that_constructor_throws_exception_if_single_operand() {
- new FeatureConjunction(Arrays.asList(feature("a").inSet("1")));
+ @Test
+ void require_that_constructor_throws_exception_if_single_operand() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new FeatureConjunction(Arrays.asList(feature("a").inSet("1")));
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void require_that_constructor_throws_exception_if_no_operands() {
- new FeatureConjunction(Collections.emptyList());
+ @Test
+ void require_that_constructor_throws_exception_if_no_operands() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new FeatureConjunction(Collections.emptyList());
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void require_that_contructor_throws_exception_if_featuresets_contain_multiple_values() {
- new FeatureConjunction(Arrays.asList(feature("a").inSet("1"), feature("b").inSet("2", "3")));
+ @Test
+ void require_that_contructor_throws_exception_if_featuresets_contain_multiple_values() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new FeatureConjunction(Arrays.asList(feature("a").inSet("1"), feature("b").inSet("2", "3")));
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void require_that_constructor_throws_exception_if_featureset_keys_are_not_unique() {
- new FeatureConjunction(Arrays.asList(
- not(feature("a").inSet("1")),
- feature("a").inSet("2")));
+ @Test
+ void require_that_constructor_throws_exception_if_featureset_keys_are_not_unique() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ new FeatureConjunction(Arrays.asList(
+ not(feature("a").inSet("1")),
+ feature("a").inSet("2")));
+ });
}
}
diff --git a/predicate-search-core/src/test/java/com/yahoo/document/predicate/FeatureRangeTest.java b/predicate-search-core/src/test/java/com/yahoo/document/predicate/FeatureRangeTest.java
index 0951ae3bbc6..8d31765cf1b 100644
--- a/predicate-search-core/src/test/java/com/yahoo/document/predicate/FeatureRangeTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/document/predicate/FeatureRangeTest.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.document.predicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -13,12 +13,12 @@ import static org.junit.Assert.*;
public class FeatureRangeTest {
@Test
- public void requireThatFeatureRangeIsAValue() {
+ void requireThatFeatureRangeIsAValue() {
assertTrue(PredicateValue.class.isAssignableFrom(FeatureRange.class));
}
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
FeatureRange node = new FeatureRange("foo");
assertEquals("foo", node.getKey());
node.setKey("bar");
@@ -36,7 +36,7 @@ public class FeatureRangeTest {
}
@Test
- public void requireThatConstructorsWork() {
+ void requireThatConstructorsWork() {
FeatureRange node = new FeatureRange("foo");
assertEquals("foo", node.getKey());
assertNull(node.getFromInclusive());
@@ -64,7 +64,7 @@ public class FeatureRangeTest {
}
@Test
- public void requireThatCloneIsImplemented() throws CloneNotSupportedException {
+ void requireThatCloneIsImplemented() throws CloneNotSupportedException {
FeatureRange node1 = new FeatureRange("foo", 6L, 9L);
FeatureRange node2 = node1.clone();
assertEquals(node1, node2);
@@ -72,36 +72,36 @@ public class FeatureRangeTest {
}
@Test
- public void requireThatHashCodeIsImplemented() {
+ void requireThatHashCodeIsImplemented() {
assertEquals(new FeatureRange("key").hashCode(), new FeatureRange("key").hashCode());
}
@Test
- public void requireThatEqualsIsImplemented() {
+ void requireThatEqualsIsImplemented() {
FeatureRange lhs = new FeatureRange("foo", 6L, 9L);
- assertTrue(lhs.equals(lhs));
- assertFalse(lhs.equals(new Object()));
+ assertEquals(lhs, lhs);
+ assertNotEquals(lhs, new Object());
FeatureRange rhs = new FeatureRange("bar");
- assertFalse(lhs.equals(rhs));
+ assertNotEquals(lhs, rhs);
rhs.setKey("foo");
- assertFalse(lhs.equals(rhs));
+ assertNotEquals(lhs, rhs);
rhs.setFromInclusive(6L);
- assertFalse(lhs.equals(rhs));
+ assertNotEquals(lhs, rhs);
rhs.setToInclusive(9L);
- assertTrue(lhs.equals(rhs));
+ assertEquals(lhs, rhs);
rhs.addPartition(new RangePartition("foo"));
- assertFalse(lhs.equals(rhs));
+ assertNotEquals(lhs, rhs);
lhs.addPartition(new RangePartition("foo"));
- assertTrue(lhs.equals(rhs));
+ assertEquals(lhs, rhs);
rhs.addPartition(new RangeEdgePartition("foo", 10, 0, 2));
- assertFalse(lhs.equals(rhs));
+ assertNotEquals(lhs, rhs);
lhs.addPartition(new RangeEdgePartition("foo", 10, 0, 2));
- assertTrue(lhs.equals(rhs));
+ assertEquals(lhs, rhs);
}
@Test
- public void requireThatFeatureKeyIsMandatoryInConstructor() {
+ void requireThatFeatureKeyIsMandatoryInConstructor() {
try {
new FeatureRange(null);
fail();
@@ -111,7 +111,7 @@ public class FeatureRangeTest {
}
@Test
- public void requireThatFeatureKeyIsMandatoryInSetter() {
+ void requireThatFeatureKeyIsMandatoryInSetter() {
FeatureRange node = new FeatureRange("foo");
try {
node.setKey(null);
@@ -123,7 +123,7 @@ public class FeatureRangeTest {
}
@Test
- public void requireThatRangeCanBeSingleValue() {
+ void requireThatRangeCanBeSingleValue() {
FeatureRange node = new FeatureRange("key", 6L, 6L);
assertEquals(6, node.getFromInclusive().intValue());
assertEquals(6, node.getToInclusive().intValue());
@@ -134,7 +134,7 @@ public class FeatureRangeTest {
}
@Test
- public void requireThatFromCanNotBeConstructedGreaterThanTo() {
+ void requireThatFromCanNotBeConstructedGreaterThanTo() {
try {
new FeatureRange("key", 9L, 6L);
fail();
@@ -144,7 +144,7 @@ public class FeatureRangeTest {
}
@Test
- public void requireThatFromCanNotBeSetGreaterThanTo() {
+ void requireThatFromCanNotBeSetGreaterThanTo() {
FeatureRange node = new FeatureRange("key", null, 6L);
try {
node.setFromInclusive(9L);
@@ -165,7 +165,7 @@ public class FeatureRangeTest {
}
@Test
- public void requireThatToCanNotBeSetLessThanFrom() {
+ void requireThatToCanNotBeSetLessThanFrom() {
FeatureRange node = new FeatureRange("key", 9L, null);
try {
node.setToInclusive(6L);
@@ -186,49 +186,49 @@ public class FeatureRangeTest {
}
@Test
- public void requireThatKeyIsEscapedInToString() {
+ void requireThatKeyIsEscapedInToString() {
assertEquals("foo in [6..9]",
- new FeatureRange("foo", 6L, 9L).toString());
+ new FeatureRange("foo", 6L, 9L).toString());
assertEquals("'\\foo' in [6..9]",
- new FeatureRange("\foo", 6L, 9L).toString());
+ new FeatureRange("\foo", 6L, 9L).toString());
assertEquals("'\\x27foo\\x27' in [6..9]",
- new FeatureRange("'foo'", 6L, 9L).toString());
+ new FeatureRange("'foo'", 6L, 9L).toString());
}
@Test
- public void requireThatToStringIncludesLimits() {
+ void requireThatToStringIncludesLimits() {
assertEquals("foo in [6..9]", new FeatureRange("foo", 6L, 9L).toString());
}
@Test
- public void requireThatToStringAllowsNullLimits() {
+ void requireThatToStringAllowsNullLimits() {
assertEquals("foo in [..]", new FeatureRange("foo").toString());
}
@Test
- public void requireThatToStringAllowsNullFromLimit() {
+ void requireThatToStringAllowsNullFromLimit() {
assertEquals("foo in [..69]", new FeatureRange("foo", null, 69L).toString());
}
@Test
- public void requireThatToStringAllowsNullToLimit() {
+ void requireThatToStringAllowsNullToLimit() {
assertEquals("foo in [69..]", new FeatureRange("foo", 69L, null).toString());
}
@Test
- public void requireThatSimpleStringsArePrettyPrinted() {
+ void requireThatSimpleStringsArePrettyPrinted() {
assertEquals("foo in [6..9]",
- new FeatureRange("foo", 6L, 9L).toString());
+ new FeatureRange("foo", 6L, 9L).toString());
}
@Test
- public void requireThatComplexStringsAreEscaped() {
+ void requireThatComplexStringsAreEscaped() {
assertEquals("'\\foo' in [6..9]",
- new FeatureRange("\foo", 6L, 9L).toString());
+ new FeatureRange("\foo", 6L, 9L).toString());
}
@Test
- public void requireThatRangePartitionsCanBeAdded() {
+ void requireThatRangePartitionsCanBeAdded() {
FeatureRange range = new FeatureRange("foo", 10L, 22L);
range.addPartition(new RangePartition("foo=10-19"));
range.addPartition(new RangePartition("foo", 0, 0x8000000000000000L, true));
@@ -237,7 +237,7 @@ public class FeatureRangeTest {
}
@Test
- public void requireThatRangePartitionsCanBeCleared() {
+ void requireThatRangePartitionsCanBeCleared() {
FeatureRange range = new FeatureRange("foo", 10L, 22L);
range.addPartition(new RangePartition("foo=10-19"));
range.addPartition(new RangeEdgePartition("foo=20", 20, 0, 2));
@@ -247,7 +247,7 @@ public class FeatureRangeTest {
}
@Test
- public void requireThatFeatureRangeCanBeBuiltFromMixedInNode() {
+ void requireThatFeatureRangeCanBeBuiltFromMixedInNode() {
assertEquals(new FeatureRange("foo", 10L, 19L),
FeatureRange.buildFromMixedIn("foo", Arrays.asList("foo=10-19"), 10));
assertEquals(new FeatureRange("foo", -19L, -10L),
diff --git a/predicate-search-core/src/test/java/com/yahoo/document/predicate/FeatureSetTest.java b/predicate-search-core/src/test/java/com/yahoo/document/predicate/FeatureSetTest.java
index e0ed8da13c8..7068538a1e0 100644
--- a/predicate-search-core/src/test/java/com/yahoo/document/predicate/FeatureSetTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/document/predicate/FeatureSetTest.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.document.predicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
@@ -9,12 +9,7 @@ import java.util.Collection;
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.assertNotNull;
-import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author Simon Thoresen Hult
@@ -22,12 +17,12 @@ import static org.junit.Assert.fail;
public class FeatureSetTest {
@Test
- public void requireThatFeatureSetIsAValue() {
+ void requireThatFeatureSetIsAValue() {
assertTrue(PredicateValue.class.isAssignableFrom(FeatureSet.class));
}
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
FeatureSet node = new FeatureSet("key", "valueA", "valueB");
assertEquals("key", node.getKey());
assertValues(Arrays.asList("valueA", "valueB"), node);
@@ -40,7 +35,7 @@ public class FeatureSetTest {
}
@Test
- public void requireThatValueSetIsMutable() {
+ void requireThatValueSetIsMutable() {
FeatureSet node = new FeatureSet("key");
node.getValues().add("valueA");
assertValues(Arrays.asList("valueA"), node);
@@ -51,7 +46,7 @@ public class FeatureSetTest {
}
@Test
- public void requireThatConstructorsWork() {
+ void requireThatConstructorsWork() {
FeatureSet node = new FeatureSet("key", "valueA", "valueB");
assertEquals("key", node.getKey());
assertValues(Arrays.asList("valueA", "valueB"), node);
@@ -62,7 +57,7 @@ public class FeatureSetTest {
}
@Test
- public void requireThatCloneIsImplemented() throws CloneNotSupportedException {
+ void requireThatCloneIsImplemented() throws CloneNotSupportedException {
FeatureSet node1 = new FeatureSet("key", "valueA", "valueB");
FeatureSet node2 = node1.clone();
assertEquals(node1, node2);
@@ -71,28 +66,28 @@ public class FeatureSetTest {
}
@Test
- public void requireThatHashCodeIsImplemented() {
+ void requireThatHashCodeIsImplemented() {
assertEquals(new FeatureSet("key").hashCode(), new FeatureSet("key").hashCode());
}
@Test
- public void requireThatEqualsIsImplemented() {
+ void requireThatEqualsIsImplemented() {
FeatureSet lhs = new FeatureSet("keyA", "valueA", "valueB");
- assertTrue(lhs.equals(lhs));
- assertFalse(lhs.equals(new Object()));
+ assertEquals(lhs, lhs);
+ assertNotEquals(lhs, new Object());
FeatureSet rhs = new FeatureSet("keyB");
- assertFalse(lhs.equals(rhs));
+ assertNotEquals(lhs, rhs);
rhs.setKey("keyA");
- assertFalse(lhs.equals(rhs));
+ assertNotEquals(lhs, rhs);
rhs.addValue("valueA");
- assertFalse(lhs.equals(rhs));
+ assertNotEquals(lhs, rhs);
rhs.addValue("valueB");
- assertTrue(lhs.equals(rhs));
+ assertEquals(lhs, rhs);
}
@Test
- public void requireThatkeyIsMandatoryInConstructor() {
+ void requireThatkeyIsMandatoryInConstructor() {
try {
new FeatureSet(null);
fail();
@@ -108,7 +103,7 @@ public class FeatureSetTest {
}
@Test
- public void requireThatkeyIsMandatoryInSetter() {
+ void requireThatkeyIsMandatoryInSetter() {
FeatureSet node = new FeatureSet("foo");
try {
node.setKey(null);
@@ -120,7 +115,7 @@ public class FeatureSetTest {
}
@Test
- public void requireThatValueIsMandatoryInSetter() {
+ void requireThatValueIsMandatoryInSetter() {
FeatureSet node = new FeatureSet("foo", "bar");
try {
node.addValue(null);
@@ -132,49 +127,49 @@ public class FeatureSetTest {
}
@Test
- public void requireThatKeyIsEscapedInToString() {
+ void requireThatKeyIsEscapedInToString() {
assertEquals("foo in [val]",
- new FeatureSet("foo", "val").toString());
+ new FeatureSet("foo", "val").toString());
assertEquals("'\\foo' in [val]",
- new FeatureSet("\foo", "val").toString());
+ new FeatureSet("\foo", "val").toString());
assertEquals("'\\x27foo\\x27' in [val]",
- new FeatureSet("'foo'", "val").toString());
+ new FeatureSet("'foo'", "val").toString());
}
@Test
- public void requireThatValuesAreEscapedInToString() {
+ void requireThatValuesAreEscapedInToString() {
assertEquals("key in [bar, foo]",
- new FeatureSet("key", "foo", "bar").toString());
+ new FeatureSet("key", "foo", "bar").toString());
assertEquals("key in ['\\foo', 'ba\\r']",
- new FeatureSet("key", "\foo", "ba\r").toString());
+ new FeatureSet("key", "\foo", "ba\r").toString());
assertEquals("key in ['\\x27bar\\x27', '\\x27foo\\x27']",
- new FeatureSet("key", "'foo'", "'bar'").toString());
+ new FeatureSet("key", "'foo'", "'bar'").toString());
}
@Test
- public void requireThatSimpleStringsArePrettyPrinted() {
+ void requireThatSimpleStringsArePrettyPrinted() {
assertEquals("foo in [bar]",
- new FeatureSet("foo", "bar").toString());
+ new FeatureSet("foo", "bar").toString());
}
@Test
- public void requireThatComplexStringsAreEscaped() {
+ void requireThatComplexStringsAreEscaped() {
assertEquals("'\\foo' in ['ba\\r']",
- new FeatureSet("\foo", "ba\r").toString());
+ new FeatureSet("\foo", "ba\r").toString());
}
@Test
- public void requireThatNegatedFeatureSetsArePrettyPrinted() {
+ void requireThatNegatedFeatureSetsArePrettyPrinted() {
assertEquals("country not in [no, se]",
- new Negation(new FeatureSet("country", "no", "se")).toString());
+ new Negation(new FeatureSet("country", "no", "se")).toString());
}
private static void assertValues(Collection<String> expected, FeatureSet actual) {
List<String> tmp = new ArrayList<>(expected);
for (String value : actual.getValues()) {
- assertNotNull(value, tmp.remove(value));
+ assertNotNull(tmp.remove(value), value);
}
- assertTrue(tmp.toString(), tmp.isEmpty());
+ assertTrue(tmp.isEmpty(), tmp.toString());
}
}
diff --git a/predicate-search-core/src/test/java/com/yahoo/document/predicate/NegationTest.java b/predicate-search-core/src/test/java/com/yahoo/document/predicate/NegationTest.java
index 904dce795c3..2a86727c81a 100644
--- a/predicate-search-core/src/test/java/com/yahoo/document/predicate/NegationTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/document/predicate/NegationTest.java
@@ -1,14 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.document.predicate;
-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.assertNotSame;
-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.*;
/**
* @author Simon Thoresen Hult
@@ -16,12 +11,12 @@ import static org.junit.Assert.fail;
public class NegationTest {
@Test
- public void requireThatNegationIsAnOperator() {
+ void requireThatNegationIsAnOperator() {
assertTrue(PredicateOperator.class.isAssignableFrom(Negation.class));
}
@Test
- public void requireThatAccessorsWork() {
+ void requireThatAccessorsWork() {
Predicate foo = SimplePredicates.newString("foo");
Negation node = new Negation(foo);
assertSame(foo, node.getOperand());
@@ -32,7 +27,7 @@ public class NegationTest {
}
@Test
- public void requireThatCloneIsImplemented() throws CloneNotSupportedException {
+ void requireThatCloneIsImplemented() throws CloneNotSupportedException {
Negation node1 = new Negation(SimplePredicates.newString("a"));
Negation node2 = node1.clone();
assertEquals(node1, node2);
@@ -41,25 +36,25 @@ public class NegationTest {
}
@Test
- public void requireThatHashCodeIsImplemented() {
+ void requireThatHashCodeIsImplemented() {
Predicate predicate = SimplePredicates.newPredicate();
assertEquals(new Negation(predicate).hashCode(), new Negation(predicate).hashCode());
}
@Test
- public void requireThatEqualsIsImplemented() {
+ void requireThatEqualsIsImplemented() {
Negation lhs = new Negation(SimplePredicates.newString("foo"));
- assertTrue(lhs.equals(lhs));
- assertFalse(lhs.equals(new Object()));
+ assertEquals(lhs, lhs);
+ assertNotEquals(lhs, new Object());
Negation rhs = new Negation(SimplePredicates.newString("bar"));
- assertFalse(lhs.equals(rhs));
+ assertNotEquals(lhs, rhs);
rhs.setOperand(SimplePredicates.newString("foo"));
- assertTrue(lhs.equals(rhs));
+ assertEquals(lhs, rhs);
}
@Test
- public void requireThatChildIsMandatoryInConstructor() {
+ void requireThatChildIsMandatoryInConstructor() {
try {
new Negation(null);
fail();
@@ -69,7 +64,7 @@ public class NegationTest {
}
@Test
- public void requireThatChildIsMandatoryInSetter() {
+ void requireThatChildIsMandatoryInSetter() {
Predicate operand = SimplePredicates.newPredicate();
Negation negation = new Negation(operand);
try {
@@ -82,7 +77,7 @@ public class NegationTest {
}
@Test
- public void requireThatChildIsIncludedInToString() {
+ void requireThatChildIsIncludedInToString() {
assertEquals("not (foo)", new Negation(SimplePredicates.newString("foo")).toString());
}
diff --git a/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateHashTest.java b/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateHashTest.java
index 7b1b6886aa0..2db73aff6fe 100644
--- a/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateHashTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateHashTest.java
@@ -1,16 +1,16 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.document.predicate;
-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 <a href="mailto:magnarn@yahoo-inc.com">Magnar Nedland</a>
*/
public class PredicateHashTest{
@Test
- public void requireThatShortStringsGetsHashes() {
+ void requireThatShortStringsGetsHashes() {
assertHashesTo(0x82af3d1de65ec252L, "abcdefg");
assertHashesTo(0xdc50d922fb0e91d6L, "雅虎");
assertHashesTo(0x709bd6ff1a84dc14L, "country=日本");
@@ -44,7 +44,7 @@ public class PredicateHashTest{
}
@Test
- public void requireThatLongStringsGetsHashes() {
+ void requireThatLongStringsGetsHashes() {
assertHashesTo(0x79fac97d13f4cc84L, "abcdefghijklmn1234567890");
assertHashesTo(0xd7af1798f1d5de44L, "abcdefghijklmn1234567890a");
assertHashesTo(0x5a259ad887478cccL, "abcdefghijklmn1234567890ab");
diff --git a/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateOperatorTest.java b/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateOperatorTest.java
index 2bcc62b76e0..d1e36c2b117 100644
--- a/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateOperatorTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateOperatorTest.java
@@ -1,9 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.document.predicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Simon Thoresen Hult
@@ -11,7 +11,7 @@ import static org.junit.Assert.assertTrue;
public class PredicateOperatorTest {
@Test
- public void requireThatOperatorIsAPredicate() {
+ void requireThatOperatorIsAPredicate() {
assertTrue(Predicate.class.isAssignableFrom(PredicateOperator.class));
}
}
diff --git a/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateParserTest.java b/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateParserTest.java
index b4b45ab198e..96c774fe8ed 100644
--- a/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateParserTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateParserTest.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.document.predicate;
-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.*;
/**
* @author <a href="mailto:magnarn@yahoo-inc.com">Magnar Nedland</a>
@@ -14,7 +12,7 @@ import static org.junit.Assert.fail;
public class PredicateParserTest {
@Test
- public void requireThatParseErrorThrowsException() {
+ void requireThatParseErrorThrowsException() {
try {
Predicate.fromString("a in b");
fail("Expected an exception");
@@ -24,7 +22,7 @@ public class PredicateParserTest {
}
@Test
- public void requireThatLexerErrorThrowsException() {
+ void requireThatLexerErrorThrowsException() {
try {
Predicate.fromString("a-b in [b]");
fail("Expected an exception");
@@ -34,7 +32,7 @@ public class PredicateParserTest {
}
@Test
- public void requireThatSingleValueLeafNodesParse() {
+ void requireThatSingleValueLeafNodesParse() {
assertParsesTo("a in [b]", "a in [b]");
assertParsesTo("0 in [1]", "0 in [1]");
assertParsesTo("in in [in]", "in in [in]");
@@ -44,17 +42,17 @@ public class PredicateParserTest {
assertParsesTo("string in ['!@#$%^&*()[]']", "'string' in ['!@#$%^&*()[]']");
assertParsesTo("a in [b]", "a in [b]");
assertParsesTo("string in ['foo\\\\_\"\\t\\n\\f\\rbar']",
- "string in ['foo\\\\_\\x22\\t\\n\\f\\rbar']");
+ "string in ['foo\\\\_\\x22\\t\\n\\f\\rbar']");
assertParsesTo("'\\xC3\\xB8' in [b]", "'ø' in [b]");
assertParsesTo("'\\xEF\\xBF\\xBD' in [b]", "'\\xf8' in [b]");
assertParsesTo("'\\xEF\\xBF\\xBD' in [b]", "'\\xef\\xbf\\xbd' in ['b']");
assertParsesTo("'\\xE4\\xB8\\x9C\\xE8\\xA5\\xBF' in ['\\xE8\\x87\\xAA\\xE8\\xA1\\x8C\\xE8\\xBD\\xA6']",
- "'东西' in ['自行车']");
+ "'东西' in ['自行车']");
assertParsesTo("true in [false]", "true in [false]");
}
@Test
- public void requireThatMultiValueLeafNodesParse() {
+ void requireThatMultiValueLeafNodesParse() {
assertParsesTo("a in [b]", "a in [b]");
assertParsesTo("0 in [1]", "0 in [1]");
assertParsesTo("in in [and, in]", "in in [in, and]");
@@ -62,7 +60,7 @@ public class PredicateParserTest {
}
@Test
- public void requireThatBothSingleAndDoubleQuotesWork() {
+ void requireThatBothSingleAndDoubleQuotesWork() {
assertParsesTo("a in [b]", "'a' in ['b']");
assertParsesTo("a in [b]", "\"a\" in [\"b\"]");
assertParsesTo("'a\\x27' in [b]", "'a\\'' in ['b']");
@@ -70,7 +68,7 @@ public class PredicateParserTest {
}
@Test
- public void requireThatRangeLeafNodesParse() {
+ void requireThatRangeLeafNodesParse() {
assertParsesTo("a in [0..100]", "a in [0..100]");
assertParsesTo("0 in [..100]", "0 in [..100]");
assertParsesTo("0 in [0..]", "0 in [0..]");
@@ -81,7 +79,7 @@ public class PredicateParserTest {
}
@Test
- public void requireThatRangePartitionsAreIgnored() {
+ void requireThatRangePartitionsAreIgnored() {
assertParsesTo("a in [0..100]", "a in [0..100 (a=0-99,a=100+[..0])]");
assertParsesTo("a in [-100..0]", "a in [-100..0 (a=-0-99,a=-100+[..0])]");
assertParsesTo("a in [-9223372036854775808..0]", "a in [-9223372036854775808..0 (a=-0-9223372036854775808)]");
@@ -91,57 +89,57 @@ public class PredicateParserTest {
}
@Test
- public void requireThatNotInSetWorks() {
+ void requireThatNotInSetWorks() {
assertParsesTo("a not in [b]", "a not in [b]");
}
@Test
- public void requireThatConjunctionWorks() {
+ void requireThatConjunctionWorks() {
assertParsesTo("a in [b] and c in [d]", "a in [b] and c in [d]");
assertParsesTo("a in [b] and c in [d] and e in [f]", "a in [b] and c in [d] and e in [f]");
}
@Test
- public void requireThatDisjunctionWorks() {
+ void requireThatDisjunctionWorks() {
assertParsesTo("a in [b] or c in [d]", "a in [b] or c in [d]");
assertParsesTo("a in [b] or c in [d] or e in [f]", "a in [b] or c in [d] or e in [f]");
}
@Test
- public void requireThatParenthesesWorks() {
+ void requireThatParenthesesWorks() {
assertParsesTo("a in [b] or c in [d]",
- "(a in [b]) or (c in [d])");
+ "(a in [b]) or (c in [d])");
assertParsesTo("a in [b] or c in [d] or e in [f]",
- "(((a in [b]) or c in [d]) or e in [f])");
+ "(((a in [b]) or c in [d]) or e in [f])");
assertParsesTo("(a in [b] and c in [d]) or e in [f]",
- "a in [b] and c in [d] or e in [f]");
+ "a in [b] and c in [d] or e in [f]");
assertParsesTo("a in [b] and (c in [d] or e in [f])",
- "a in [b] and (c in [d] or e in [f])");
+ "a in [b] and (c in [d] or e in [f])");
assertParsesTo("a in [b] and (c in [d] or e in [f]) and g in [h]",
- "a in [b] and (c in [d] or e in [f]) and g in [h]");
+ "a in [b] and (c in [d] or e in [f]) and g in [h]");
}
@Test
- public void requireThatNotOutsideParenthesesWorks() {
+ void requireThatNotOutsideParenthesesWorks() {
assertParsesTo("a not in [b]", "not (a in [b])");
}
@Test
- public void requireThatConjunctionsCanGetMoreThanTwoChildren() {
+ void requireThatConjunctionsCanGetMoreThanTwoChildren() {
Predicate p = Predicate.fromString("a in [b] and c in [d] and e in [f] and g in [h]");
assertTrue(p instanceof Conjunction);
- assertEquals(4, ((Conjunction)p).getOperands().size());
+ assertEquals(4, ((Conjunction) p).getOperands().size());
}
@Test
- public void requireThatDisjunctionsCanGetMoreThanTwoChildren() {
+ void requireThatDisjunctionsCanGetMoreThanTwoChildren() {
Predicate p = Predicate.fromString("a in [b] or c in [d] or e in [f] or g in [h]");
assertTrue(p instanceof Disjunction);
- assertEquals(4, ((Disjunction)p).getOperands().size());
+ assertEquals(4, ((Disjunction) p).getOperands().size());
}
@Test
- public void requireThatBooleanCanBeParsed() {
+ void requireThatBooleanCanBeParsed() {
assertParsesTo("true", "true");
assertParsesTo("false", "false");
assertParsesTo("true or false", "true or false");
diff --git a/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateTest.java b/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateTest.java
index 10de465f342..544403f6c9f 100644
--- a/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateTest.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.document.predicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static com.yahoo.document.predicate.Predicates.and;
import static com.yahoo.document.predicate.Predicates.feature;
import static com.yahoo.document.predicate.Predicates.not;
import static com.yahoo.document.predicate.Predicates.or;
-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 Simon Thoresen Hult
@@ -16,12 +16,12 @@ import static org.junit.Assert.assertTrue;
public class PredicateTest {
@Test
- public void requireThatPredicateIsCloneable() {
+ void requireThatPredicateIsCloneable() {
assertTrue(Cloneable.class.isAssignableFrom(Predicate.class));
}
@Test
- public void requireThatANDConstructsAConjunction() {
+ void requireThatANDConstructsAConjunction() {
Predicate foo = SimplePredicates.newString("foo");
Predicate bar = SimplePredicates.newString("bar");
Predicate predicate = and(foo, bar);
@@ -30,7 +30,7 @@ public class PredicateTest {
}
@Test
- public void requireThatORConstructsADisjunction() {
+ void requireThatORConstructsADisjunction() {
Predicate foo = SimplePredicates.newString("foo");
Predicate bar = SimplePredicates.newString("bar");
Predicate predicate = or(foo, bar);
@@ -39,7 +39,7 @@ public class PredicateTest {
}
@Test
- public void requireThatNOTConstructsANegation() {
+ void requireThatNOTConstructsANegation() {
Predicate foo = SimplePredicates.newString("foo");
Predicate predicate = not(foo);
assertEquals(Negation.class, predicate.getClass());
@@ -47,52 +47,52 @@ public class PredicateTest {
}
@Test
- public void requireThatFeatureBuilderCanConstructFeatureRange() {
+ void requireThatFeatureBuilderCanConstructFeatureRange() {
assertEquals(new FeatureRange("key", 6L, 9L),
- feature("key").inRange(6, 9));
+ feature("key").inRange(6, 9));
assertEquals(new Negation(new FeatureRange("key", 6L, 9L)),
- feature("key").notInRange(6, 9));
+ feature("key").notInRange(6, 9));
assertEquals(new FeatureRange("key", 7L, null),
- feature("key").greaterThan(6));
+ feature("key").greaterThan(6));
assertEquals(new FeatureRange("key", 6L, null),
- feature("key").greaterThanOrEqualTo(6));
+ feature("key").greaterThanOrEqualTo(6));
assertEquals(new FeatureRange("key", null, 5L),
- feature("key").lessThan(6));
+ feature("key").lessThan(6));
assertEquals(new FeatureRange("key", null, 9L),
- feature("key").lessThanOrEqualTo(9));
+ feature("key").lessThanOrEqualTo(9));
}
@Test
- public void requireThatFeatureBuilderCanConstructFeatureSet() {
+ void requireThatFeatureBuilderCanConstructFeatureSet() {
assertEquals(new FeatureSet("key", "valueA", "valueB"),
- feature("key").inSet("valueA", "valueB"));
+ feature("key").inSet("valueA", "valueB"));
assertEquals(new Negation(new FeatureSet("key", "valueA", "valueB")),
- feature("key").notInSet("valueA", "valueB"));
+ feature("key").notInSet("valueA", "valueB"));
}
@Test
- public void requireThatPredicatesCanBeConstructedUsingConstructors() {
+ void requireThatPredicatesCanBeConstructedUsingConstructors() {
assertEquals("country in [no, se] and age in [20..30]",
- new Conjunction(new FeatureSet("country", "no", "se"),
- new FeatureRange("age", 20L, 30L)).toString());
+ new Conjunction(new FeatureSet("country", "no", "se"),
+ new FeatureRange("age", 20L, 30L)).toString());
assertEquals("country not in [no, se] or age in [20..] or height in [..160]",
- new Disjunction(new Negation(new FeatureSet("country", "no", "se")),
- new FeatureRange("age", 20L, null),
- new FeatureRange("height", null, 160L)).toString());
+ new Disjunction(new Negation(new FeatureSet("country", "no", "se")),
+ new FeatureRange("age", 20L, null),
+ new FeatureRange("height", null, 160L)).toString());
}
@Test
- public void requireThatPredicatesCanBeBuiltUsingChainedMethodCalls() {
+ void requireThatPredicatesCanBeBuiltUsingChainedMethodCalls() {
assertEquals("country not in [no, se] or age in [20..] or height in [..160]",
- new Disjunction()
- .addOperand(new Negation(new FeatureSet("country").addValue("no").addValue("se")))
- .addOperand(new FeatureRange("age").setFromInclusive(20L))
- .addOperand(new FeatureRange("height").setToInclusive(160L))
- .toString());
+ new Disjunction()
+ .addOperand(new Negation(new FeatureSet("country").addValue("no").addValue("se")))
+ .addOperand(new FeatureRange("age").setFromInclusive(20L))
+ .addOperand(new FeatureRange("height").setToInclusive(160L))
+ .toString());
}
@Test
- public void requireThatPredicatesCanBeBuiltUsingSeparateMethodCalls() {
+ void requireThatPredicatesCanBeBuiltUsingSeparateMethodCalls() {
Conjunction conjunction = new Conjunction();
FeatureSet countrySet = new FeatureSet("country");
countrySet.addValue("no");
@@ -105,6 +105,6 @@ public class PredicateTest {
heightRange.setToInclusive(160L);
conjunction.addOperand(heightRange);
assertEquals("country in [no, se] and age in [20..] and height in [..160]",
- conjunction.toString());
+ conjunction.toString());
}
}
diff --git a/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateValueTest.java b/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateValueTest.java
index fe5f6db1cfa..c32a36f153b 100644
--- a/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateValueTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicateValueTest.java
@@ -1,9 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.document.predicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author Simon Thoresen Hult
@@ -11,7 +11,7 @@ import static org.junit.Assert.assertTrue;
public class PredicateValueTest {
@Test
- public void requireThatValueIsAPredicate() {
+ void requireThatValueIsAPredicate() {
assertTrue(Predicate.class.isAssignableFrom(PredicateValue.class));
}
}
diff --git a/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicatesTest.java b/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicatesTest.java
index c8cd3f776c8..a40e577fae5 100644
--- a/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicatesTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/document/predicate/PredicatesTest.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.document.predicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static com.yahoo.document.predicate.Predicates.and;
import static com.yahoo.document.predicate.Predicates.feature;
import static com.yahoo.document.predicate.Predicates.not;
import static com.yahoo.document.predicate.Predicates.or;
import static com.yahoo.document.predicate.Predicates.value;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author Simon Thoresen Hult
@@ -16,21 +16,21 @@ import static org.junit.Assert.assertEquals;
public class PredicatesTest {
@Test
- public void requireThatApiIsUsable() {
+ void requireThatApiIsUsable() {
assertEquals(
new Disjunction(
new Conjunction(new FeatureSet("country", "de", "no"),
- new Negation(new FeatureSet("gender", "female")),
- new FeatureRange("age", 6L, 9L)),
+ new Negation(new FeatureSet("gender", "female")),
+ new FeatureRange("age", 6L, 9L)),
new Conjunction(new Negation(new FeatureSet("country", "se")),
- new FeatureSet("gender", "female"),
- new FeatureRange("age", 69L, null))),
+ new FeatureSet("gender", "female"),
+ new FeatureRange("age", 69L, null))),
or(and(feature("country").inSet("de", "no"),
- feature("gender").notInSet("female"),
- feature("age").inRange(6, 9)),
- and(not(feature("country").inSet("se")),
- feature("gender").inSet("female"),
- feature("age").greaterThanOrEqualTo(69))));
+ feature("gender").notInSet("female"),
+ feature("age").inRange(6, 9)),
+ and(not(feature("country").inSet("se")),
+ feature("gender").inSet("female"),
+ feature("age").greaterThanOrEqualTo(69))));
assertEquals(new BooleanPredicate(true), value(true));
assertEquals(new BooleanPredicate(false), value(false));
diff --git a/predicate-search-core/src/test/java/com/yahoo/document/predicate/RangeEdgePartitionTest.java b/predicate-search-core/src/test/java/com/yahoo/document/predicate/RangeEdgePartitionTest.java
index be01b1cd842..00a25e4dc49 100644
--- a/predicate-search-core/src/test/java/com/yahoo/document/predicate/RangeEdgePartitionTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/document/predicate/RangeEdgePartitionTest.java
@@ -1,10 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.document.predicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.*;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author <a href="mailto:magnarn@yahoo-inc.com">Magnar Nedland</a>
@@ -12,12 +11,12 @@ import static org.junit.Assert.assertEquals;
public class RangeEdgePartitionTest {
@Test
- public void requireThatRangeEdgePartitionIsAValue() {
+ void requireThatRangeEdgePartitionIsAValue() {
assertTrue(PredicateValue.class.isAssignableFrom(RangeEdgePartition.class));
}
@Test
- public void requireThatConstructorsWork() {
+ void requireThatConstructorsWork() {
RangeEdgePartition part = new RangeEdgePartition("foo=10", 10, 0, -1);
assertEquals("foo=10", part.getLabel());
assertEquals(0, part.getLowerBound());
@@ -25,7 +24,7 @@ public class RangeEdgePartitionTest {
}
@Test
- public void requireThatCloneIsImplemented() throws CloneNotSupportedException {
+ void requireThatCloneIsImplemented() throws CloneNotSupportedException {
RangeEdgePartition node1 = new RangeEdgePartition("foo=10", 10, 0, 0);
RangeEdgePartition node2 = node1.clone();
assertEquals(node1, node2);
@@ -33,29 +32,29 @@ public class RangeEdgePartitionTest {
}
@Test
- public void requireThatHashCodeIsImplemented() {
+ void requireThatHashCodeIsImplemented() {
assertEquals(new RangeEdgePartition("foo=-10", 10, 2, 3).hashCode(),
new RangeEdgePartition("foo=-10", 10, 2, 3).hashCode());
}
@Test
- public void requireThatEqualsIsImplemented() {
+ void requireThatEqualsIsImplemented() {
RangeEdgePartition lhs = new RangeEdgePartition("foo=10", 10, 5, 10);
- assertTrue(lhs.equals(lhs));
- assertFalse(lhs.equals(new Object()));
+ assertEquals(lhs, lhs);
+ assertNotEquals(lhs, new Object());
RangeEdgePartition rhs = new RangeEdgePartition("foo=20", 20, 0, 0);
- assertFalse(lhs.equals(rhs));
+ assertNotEquals(lhs, rhs);
rhs = new RangeEdgePartition("foo=10", 10, 5, 10);
- assertTrue(lhs.equals(rhs));
- assertFalse(lhs.equals(new RangeEdgePartition("foo=10", 10, 5, 11)));
- assertFalse(lhs.equals(new RangeEdgePartition("foo=10", 10, 6, 10)));
- assertFalse(lhs.equals(new RangeEdgePartition("foo=10", 11, 5, 10)));
- assertFalse(lhs.equals(new RangeEdgePartition("foo=11", 10, 5, 10)));
+ assertEquals(lhs, rhs);
+ assertNotEquals(lhs, new RangeEdgePartition("foo=10", 10, 5, 11));
+ assertNotEquals(lhs, new RangeEdgePartition("foo=10", 10, 6, 10));
+ assertNotEquals(lhs, new RangeEdgePartition("foo=10", 11, 5, 10));
+ assertNotEquals(lhs, new RangeEdgePartition("foo=11", 10, 5, 10));
}
@Test
- public void requireThatKeyIsEscapedInToString() {
+ void requireThatKeyIsEscapedInToString() {
assertEquals("foo=10+[2..3]", new RangeEdgePartition("foo=10", 10, 2, 3).toString());
assertEquals("'\\foo=10'+[2..3]", new RangeEdgePartition("\foo=10", 10, 2, 3).toString());
assertEquals("'\\x27foo\\x27=10'+[2..3]", new RangeEdgePartition("'foo'=10", 10, 2, 3).toString());
diff --git a/predicate-search-core/src/test/java/com/yahoo/document/predicate/RangePartitionTest.java b/predicate-search-core/src/test/java/com/yahoo/document/predicate/RangePartitionTest.java
index c11a7fb433f..ea191c705a5 100644
--- a/predicate-search-core/src/test/java/com/yahoo/document/predicate/RangePartitionTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/document/predicate/RangePartitionTest.java
@@ -1,10 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.document.predicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.*;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author <a href="mailto:magnarn@yahoo-inc.com">Magnar Nedland</a>
@@ -12,12 +11,12 @@ import static org.junit.Assert.assertEquals;
public class RangePartitionTest {
@Test
- public void requireThatRangePartitionIsAValue() {
+ void requireThatRangePartitionIsAValue() {
assertTrue(PredicateValue.class.isAssignableFrom(RangePartition.class));
}
@Test
- public void requireThatConstructorsWork() {
+ void requireThatConstructorsWork() {
RangePartition part = new RangePartition("foo=10-19");
assertEquals("foo=10-19", part.getLabel());
part = new RangePartition("foo", 10, 19, false);
@@ -27,7 +26,7 @@ public class RangePartitionTest {
}
@Test
- public void requireThatCloneIsImplemented() throws CloneNotSupportedException {
+ void requireThatCloneIsImplemented() throws CloneNotSupportedException {
RangePartition node1 = new RangePartition("foo=300-399");
RangePartition node2 = node1.clone();
assertEquals(node1, node2);
@@ -35,24 +34,24 @@ public class RangePartitionTest {
}
@Test
- public void requireThatHashCodeIsImplemented() {
+ void requireThatHashCodeIsImplemented() {
assertEquals(new RangePartition("foo=0-9").hashCode(), new RangePartition("foo=0-9").hashCode());
}
@Test
- public void requireThatEqualsIsImplemented() {
+ void requireThatEqualsIsImplemented() {
RangePartition lhs = new RangePartition("foo=10-19");
- assertTrue(lhs.equals(lhs));
- assertFalse(lhs.equals(new Object()));
+ assertEquals(lhs, lhs);
+ assertNotEquals(lhs, new Object());
RangePartition rhs = new RangePartition("bar=1000-1999");
- assertFalse(lhs.equals(rhs));
+ assertNotEquals(lhs, rhs);
rhs = new RangePartition("foo=10-19");
- assertTrue(lhs.equals(rhs));
+ assertEquals(lhs, rhs);
}
@Test
- public void requireThatKeyIsEscapedInToString() {
+ void requireThatKeyIsEscapedInToString() {
assertEquals("foo=10-19", new RangePartition("foo=10-19").toString());
assertEquals("'\\foo=10-19'", new RangePartition("\foo=10-19").toString());
assertEquals("'\\x27foo\\x27=10-19'", new RangePartition("'foo'=10-19").toString());
diff --git a/predicate-search-core/src/test/java/com/yahoo/search/predicate/PredicateQueryParserTest.java b/predicate-search-core/src/test/java/com/yahoo/search/predicate/PredicateQueryParserTest.java
index bd580ac232e..8e8a4f45562 100644
--- a/predicate-search-core/src/test/java/com/yahoo/search/predicate/PredicateQueryParserTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/search/predicate/PredicateQueryParserTest.java
@@ -1,13 +1,13 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.predicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bjorncs
@@ -15,17 +15,17 @@ import static org.junit.Assert.assertEquals;
public class PredicateQueryParserTest {
@Test
- public void require_that_json_is_correctly_parsed() {
+ void require_that_json_is_correctly_parsed() {
String json =
"{" +
- " \"features\":[" +
- " {\"k\":\"k1\",\"v\":\"value1\",\"s\":\"0x1\"}," +
- " {\"k\":\"k2\",\"v\":\"value2\",\"s\":\"0x3\"}" +
- " ],\"rangeFeatures\":[" +
- " {\"k\":\"range1\",\"v\":123456789123,\"s\":\"0xffff\"}," +
- " {\"k\":\"range2\",\"v\":0,\"s\":\"0xffffffffffffffff\"}" +
- " ]" +
- "}";
+ " \"features\":[" +
+ " {\"k\":\"k1\",\"v\":\"value1\",\"s\":\"0x1\"}," +
+ " {\"k\":\"k2\",\"v\":\"value2\",\"s\":\"0x3\"}" +
+ " ],\"rangeFeatures\":[" +
+ " {\"k\":\"range1\",\"v\":123456789123,\"s\":\"0xffff\"}," +
+ " {\"k\":\"range2\",\"v\":0,\"s\":\"0xffffffffffffffff\"}" +
+ " ]" +
+ "}";
PredicateQueryParser parser = new PredicateQueryParser();
List<String> result = new ArrayList<>();
diff --git a/predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/AndOrSimplifierTest.java b/predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/AndOrSimplifierTest.java
index 2725132e68a..497c490b844 100644
--- a/predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/AndOrSimplifierTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/AndOrSimplifierTest.java
@@ -2,13 +2,13 @@
package com.yahoo.search.predicate.optimization;
import com.yahoo.document.predicate.Predicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static com.yahoo.document.predicate.Predicates.and;
import static com.yahoo.document.predicate.Predicates.feature;
import static com.yahoo.document.predicate.Predicates.not;
import static com.yahoo.document.predicate.Predicates.or;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author <a href="mailto:magnarn@yahoo-inc.com">Magnar Nedland</a>
@@ -16,93 +16,93 @@ import static org.junit.Assert.assertEquals;
public class AndOrSimplifierTest {
@Test
- public void requireThatNestedConjunctionsAreCollapsed() {
+ void requireThatNestedConjunctionsAreCollapsed() {
assertSimplified(and(feature("a").inSet("b"),
- feature("c").inSet("d")),
- and(and(feature("a").inSet("b"),
- feature("c").inSet("d"))));
+ feature("c").inSet("d")),
+ and(and(feature("a").inSet("b"),
+ feature("c").inSet("d"))));
}
@Test
- public void requireThatNestedConjuctionsAreCollapsedInPlace() {
+ void requireThatNestedConjuctionsAreCollapsedInPlace() {
assertSimplified(and(feature("a").inSet("b"),
- feature("c").inSet("d"),
- feature("e").inSet("f")),
- and(feature("a").inSet("b"),
- and(feature("c").inSet("d")),
- feature("e").inSet("f")));
+ feature("c").inSet("d"),
+ feature("e").inSet("f")),
+ and(feature("a").inSet("b"),
+ and(feature("c").inSet("d")),
+ feature("e").inSet("f")));
}
@Test
- public void requireThatDeeplyNestedConjunctionsAreCollapsed() {
+ void requireThatDeeplyNestedConjunctionsAreCollapsed() {
assertSimplified(and(feature("a").inSet("b"),
- feature("c").inSet("d"),
- feature("e").inSet("f"),
- feature("g").inSet("h"),
- feature("i").inSet("j")),
- and(feature("a").inSet("b"),
- and(feature("c").inSet("d")),
- feature("e").inSet("f"),
- and(and(feature("g").inSet("h"),
- feature("i").inSet("j")))));
+ feature("c").inSet("d"),
+ feature("e").inSet("f"),
+ feature("g").inSet("h"),
+ feature("i").inSet("j")),
+ and(feature("a").inSet("b"),
+ and(feature("c").inSet("d")),
+ feature("e").inSet("f"),
+ and(and(feature("g").inSet("h"),
+ feature("i").inSet("j")))));
}
@Test
- public void requireThatNestedDisjunctionsAreCollapsed() {
+ void requireThatNestedDisjunctionsAreCollapsed() {
assertSimplified(or(feature("a").inSet("b"),
- feature("c").inSet("d")),
- or(or(feature("a").inSet("b"),
- feature("c").inSet("d"))));
+ feature("c").inSet("d")),
+ or(or(feature("a").inSet("b"),
+ feature("c").inSet("d"))));
}
@Test
- public void requireThatNestedDisjuctionsAreCollapsedInPlace() {
+ void requireThatNestedDisjuctionsAreCollapsedInPlace() {
assertSimplified(or(feature("a").inSet("b"),
- feature("c").inSet("d"),
- feature("e").inSet("f")),
- or(feature("a").inSet("b"),
- or(feature("c").inSet("d")),
- feature("e").inSet("f")));
+ feature("c").inSet("d"),
+ feature("e").inSet("f")),
+ or(feature("a").inSet("b"),
+ or(feature("c").inSet("d")),
+ feature("e").inSet("f")));
}
@Test
- public void requireThatDeeplyNestedDisjunctionsAreCollapsed() {
+ void requireThatDeeplyNestedDisjunctionsAreCollapsed() {
assertSimplified(or(feature("a").inSet("b"),
- feature("c").inSet("d"),
- feature("e").inSet("f"),
- feature("g").inSet("h"),
- feature("i").inSet("j")),
- or(feature("a").inSet("b"),
- or(feature("c").inSet("d")),
- feature("e").inSet("f"),
- or(or(feature("g").inSet("h"),
- feature("i").inSet("j")))));
+ feature("c").inSet("d"),
+ feature("e").inSet("f"),
+ feature("g").inSet("h"),
+ feature("i").inSet("j")),
+ or(feature("a").inSet("b"),
+ or(feature("c").inSet("d")),
+ feature("e").inSet("f"),
+ or(or(feature("g").inSet("h"),
+ feature("i").inSet("j")))));
}
@Test
- public void requireThatConjunctionsAndDisjunctionsAreNotCollapsed() {
+ void requireThatConjunctionsAndDisjunctionsAreNotCollapsed() {
assertSimplified(and(or(feature("a").inSet("b"),
- feature("c").inSet("d"))),
- and(or(feature("a").inSet("b"),
- feature("c").inSet("d"))));
+ feature("c").inSet("d"))),
+ and(or(feature("a").inSet("b"),
+ feature("c").inSet("d"))));
}
@Test
- public void requireThatNotOrIsTranslatedToAndNot() {
+ void requireThatNotOrIsTranslatedToAndNot() {
assertSimplified(
and(feature("a").notInSet("b"), feature("c").inSet("d")),
not(or(feature("a").inSet("b"), feature("c").notInSet("d"))));
}
@Test
- public void requireThatNotAndIsTranslatedToOrNot() {
+ void requireThatNotAndIsTranslatedToOrNot() {
assertSimplified(
or(feature("a").notInSet("b"), feature("c").inSet("d")),
not(and(feature("a").inSet("b"), feature("c").notInSet("d"))));
}
@Test
- public void requireThatTreeWithoutNotIsNotAffected() {
+ void requireThatTreeWithoutNotIsNotAffected() {
assertSimplified(
and(feature("a").inSet("b"), feature("c").notInSet("d")),
and(feature("a").inSet("b"), feature("c").notInSet("d")));
@@ -113,14 +113,14 @@ public class AndOrSimplifierTest {
}
@Test
- public void requireThatNotOfNotIsRemoved() {
+ void requireThatNotOfNotIsRemoved() {
assertSimplified(feature("a").inSet("b"), not(not(feature("a").inSet("b"))));
assertSimplified(feature("a").inSet("b"), not(feature("a").notInSet("b")));
assertSimplified(feature("a").notInSet("b"), not(not(feature("a").notInSet("b"))));
}
@Test
- public void requireThatNotBeneathAndIsTranslated() {
+ void requireThatNotBeneathAndIsTranslated() {
assertSimplified(
and(feature("a").notInSet("b"), feature("c").inSet("d"), feature("b").inSet("c")),
and(not(or(feature("a").inSet("b"), feature("c").notInSet("d"))), feature("b").inSet("c")));
diff --git a/predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/BooleanSimplifierTest.java b/predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/BooleanSimplifierTest.java
index 54031d36b47..e03a01d3996 100644
--- a/predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/BooleanSimplifierTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/BooleanSimplifierTest.java
@@ -2,10 +2,10 @@
package com.yahoo.search.predicate.optimization;
import com.yahoo.document.predicate.Predicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static com.yahoo.document.predicate.Predicates.*;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author <a href="mailto:magnarn@yahoo-inc.com">Magnar Nedland</a>
@@ -13,32 +13,32 @@ import static org.junit.Assert.assertEquals;
public class BooleanSimplifierTest {
@Test
- public void requireThatOrOfTrueIsTrue() {
+ void requireThatOrOfTrueIsTrue() {
assertSimplifiedTo(value(true), or(feature("a").inSet("b"), value(true)));
}
@Test
- public void requireThatFalseChildrenOfOrAreRemoved() {
+ void requireThatFalseChildrenOfOrAreRemoved() {
assertSimplifiedTo(feature("a").inSet("b"), or(feature("a").inSet("b"), value(false)));
}
@Test
- public void requireThatAndOfFalseIsFalse() {
+ void requireThatAndOfFalseIsFalse() {
assertSimplifiedTo(value(false), and(feature("a").inSet("b"), value(false)));
}
@Test
- public void requireThatTrueChildrenOfAndAreRemoved() {
+ void requireThatTrueChildrenOfAndAreRemoved() {
assertSimplifiedTo(feature("a").inSet("b"), and(feature("a").inSet("b"), value(true)));
}
@Test
- public void requireThatSingleChildAndOrAreRemoved() {
+ void requireThatSingleChildAndOrAreRemoved() {
assertSimplifiedTo(feature("a").inSet("b"), and(or(and(feature("a").inSet("b")))));
}
@Test
- public void requireThatValueChildrenOfNotAreInverted() {
+ void requireThatValueChildrenOfNotAreInverted() {
assertSimplifiedTo(value(true), not(value(false)));
assertSimplifiedTo(value(false), not(value(true)));
assertSimplifiedTo(value(true), not(not(not(value(false)))));
@@ -46,7 +46,7 @@ public class BooleanSimplifierTest {
}
@Test
- public void requireThatComplexExpressionIsSimplified() {
+ void requireThatComplexExpressionIsSimplified() {
assertSimplifiedTo(
Predicate.fromString("'pub_entity' not in [301951]"),
Predicate.fromString("true and true and true and true and true and 'pub_entity' not in [301951] and ((true and true and true and true) or (true and true and true and true) or (true and true and true and true and 'pub_entity' in [86271]))"));
diff --git a/predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/ComplexNodeTransformerTest.java b/predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/ComplexNodeTransformerTest.java
index ac491d57ecd..596b28e8395 100644
--- a/predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/ComplexNodeTransformerTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/ComplexNodeTransformerTest.java
@@ -4,9 +4,9 @@ package com.yahoo.search.predicate.optimization;
import com.yahoo.document.predicate.FeatureRange;
import com.yahoo.document.predicate.Predicate;
import com.yahoo.document.predicate.RangePartition;
-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 <a href="mailto:magnarn@yahoo-inc.com">Magnar Nedland</a>
@@ -29,7 +29,7 @@ public class ComplexNodeTransformerTest {
}
@Test
- public void requireThatSingleValueRangesAreConverted() {
+ void requireThatSingleValueRangesAreConverted() {
testConvert("foo in [0..0]", "foo in [0..0 (foo=0+[..0])]");
testConvert("foo in [5..5]", "foo in [5..5 (foo=0+[5..5])]");
testConvert("foo in [9..9]", "foo in [9..9 (foo=0+[9..])]");
@@ -40,7 +40,7 @@ public class ComplexNodeTransformerTest {
}
@Test
- public void requireThatVeryShortRangesAreConverted() {
+ void requireThatVeryShortRangesAreConverted() {
testConvert("foo in [10..17]", "foo in [10..17 (foo=10+[..7])]");
testConvert("foo in [12..19]", "foo in [12..19 (foo=10+[2..])]");
testConvert("foo in [11..18]", "foo in [11..18 (foo=10+[1..8])]");
@@ -53,7 +53,7 @@ public class ComplexNodeTransformerTest {
}
@Test
- public void requireThatShortRangeIsConverted() {
+ void requireThatShortRangeIsConverted() {
testConvert("foo in [9..19]", "foo in [9..19 (foo=0+[9..],foo=10-19)]");
testConvert("foo in [10..19]", "foo in [10..19 (foo=10-19)]");
testConvert("foo in [10..20]", "foo in [10..20 (foo=20+[..0],foo=10-19)]");
@@ -67,7 +67,7 @@ public class ComplexNodeTransformerTest {
}
@Test
- public void requireThatMediumRangeIsConverted() {
+ void requireThatMediumRangeIsConverted() {
testConvert("foo in [10..39]", "foo in [10..39 (foo=10-19,foo=20-29,foo=30-39)]");
testConvert("foo in [10..38]", "foo in [10..38 (foo=30+[..8],foo=10-19,foo=20-29)]");
testConvert("foo in [18..39]", "foo in [18..39 (foo=10+[8..],foo=20-29,foo=30-39)]");
@@ -80,7 +80,7 @@ public class ComplexNodeTransformerTest {
}
@Test
- public void requireThatLargeRangeIsConverted() {
+ void requireThatLargeRangeIsConverted() {
testConvert("foo in [10..199]", "foo in [10..199 (foo=10-19,foo=20-29,foo=30-39,foo=40-49,foo=50-59,foo=60-69,foo=70-79,foo=80-89,foo=90-99,foo=100-199)]");
testConvert("foo in [8..207]", "foo in [8..207 (foo=0+[8..],foo=200+[..7],foo=10-19,foo=20-29,foo=30-39,foo=40-49,foo=50-59,foo=60-69,foo=70-79,foo=80-89,foo=90-99,foo=100-199)]");
testConvert("foo in [999..2001]", "foo in [999..2001 (foo=990+[9..],foo=2000+[..1],foo=1000-1999)]");
@@ -94,7 +94,7 @@ public class ComplexNodeTransformerTest {
}
@Test
- public void requireThatLongMaxIsConverted() {
+ void requireThatLongMaxIsConverted() {
testConvert("foo in [0..9223372036854775807]",
"foo in [0..9223372036854775807 (" +
"foo=9223372036854775800+[..7]," +
@@ -184,7 +184,7 @@ public class ComplexNodeTransformerTest {
}
@Test
- public void requireThatLongMinIsConverted() {
+ void requireThatLongMinIsConverted() {
testConvert("foo in [-9223372036854775808..-1]",
"foo in [-9223372036854775808..-1 (" +
"foo=-9223372036854775800+[..8]," +
@@ -273,7 +273,7 @@ public class ComplexNodeTransformerTest {
}
@Test
- public void requireThatLowAritiesWork() {
+ void requireThatLowAritiesWork() {
testConvert("foo in [10..39]", "foo in [10..39 (foo=10-11,foo=12-15,foo=32-39,foo=16-31)]", 2);
testConvert("foo in [2..32]", "foo in [2..32 (foo=32+[..0],foo=2-3,foo=4-7,foo=8-15,foo=16-31)]", 2);
testConvert("foo in [-31..63]", "foo in [-31..63 (foo=-31-0,foo=0-63)]", 2);
@@ -327,7 +327,7 @@ public class ComplexNodeTransformerTest {
}
@Test
- public void requireThatHighAritiesWork() {
+ void requireThatHighAritiesWork() {
testConvert("foo in [10..39]", "foo in [10..39 (foo=0+[10..39])]", 1000);
testConvert("foo in [9000..11000]", "foo in [9000..11000 (foo=0+[9000..],foo=10000+[..1000])]", 10000);
testConvert("foo in [10..39]", "foo in [10..39 (foo=0+[10..39])]", 16384);
@@ -338,13 +338,13 @@ public class ComplexNodeTransformerTest {
}
@Test
- public void requireThatOpenRangesWork() {
+ void requireThatOpenRangesWork() {
testConvert("foo in [-7..]", "foo in [-7.. (foo=-7-0,foo=0-9223372036854775807)]", 2);
testConvert("foo in [..7]", "foo in [..7 (foo=-9223372036854775808+[..0],foo=-9223372036854775807-0,foo=0-7)]", 2);
}
@Test
- public void requireThatUpperAndLowerBoundsWork() {
+ void requireThatUpperAndLowerBoundsWork() {
lowerBound = -999;
upperBound = 999;
testConvert("foo in [-9..]", "foo in [-9.. (foo=-9-0,foo=0-999)]", 10);
@@ -353,7 +353,7 @@ public class ComplexNodeTransformerTest {
}
@Test
- public void requireThatUpperAndLowerBoundsPruneClosedRanges() {
+ void requireThatUpperAndLowerBoundsPruneClosedRanges() {
lowerBound = -999;
upperBound = 999;
testConvert("foo in [0..10000]", "foo in [0..10000 (foo=0-999)]", 10);
@@ -364,7 +364,7 @@ public class ComplexNodeTransformerTest {
}
@Test
- public void requireThatRangesOutsideBoundsAreSimplifiedToOneImpossibleRange() {
+ void requireThatRangesOutsideBoundsAreSimplifiedToOneImpossibleRange() {
lowerBound = 900;
upperBound = 999;
testConvert("foo in [0..100]", "foo in [0..100 (foo=-9223372036854775799-9223372036854775790)]", 10);
@@ -380,7 +380,7 @@ public class ComplexNodeTransformerTest {
}
@Test
- public void requireThatUpperAndLowerBoundsAreAdjustedWithArity() {
+ void requireThatUpperAndLowerBoundsAreAdjustedWithArity() {
lowerBound = -999;
upperBound = 999;
testConvert("foo in [0..10000]", "foo in [0..10000 (foo=0-999)]", 10);
@@ -592,10 +592,10 @@ public class ComplexNodeTransformerTest {
}
@Test
- public void requireThatExistingPartitionsAreCleared() {
+ void requireThatExistingPartitionsAreCleared() {
testConvert("foo in [10..19]", "foo in [10..19 (foo=10-19)]");
Predicate p = Predicate.fromString("foo in [10..19]");
- ((FeatureRange)p).addPartition(new RangePartition("foo", 10000L, 20000L, false));
+ ((FeatureRange) p).addPartition(new RangePartition("foo", 10000L, 20000L, false));
ComplexNodeTransformer tranformer = new ComplexNodeTransformer();
Predicate converted = tranformer.process(p, new PredicateOptions(10, lowerBound, upperBound));
assertEquals("foo in [10..19 (foo=10-19)]", converted.toString());
diff --git a/predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/NotNodeReordererTest.java b/predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/NotNodeReordererTest.java
index b1a0be796ab..665b88d3af5 100644
--- a/predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/NotNodeReordererTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/NotNodeReordererTest.java
@@ -2,19 +2,19 @@
package com.yahoo.search.predicate.optimization;
import com.yahoo.document.predicate.Predicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static com.yahoo.document.predicate.Predicates.and;
import static com.yahoo.document.predicate.Predicates.feature;
import static com.yahoo.document.predicate.Predicates.or;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author <a href="mailto:magnarn@yahoo-inc.com">Magnar Nedland</a>
*/
public class NotNodeReordererTest {
@Test
- public void requireThatNotChildrenAreMovedAwayFromLastAndChild() {
+ void requireThatNotChildrenAreMovedAwayFromLastAndChild() {
checkReorder(
and(feature("a").inSet("b"), feature("c").notInSet("d")),
and(feature("c").notInSet("d"), feature("a").inSet("b")));
@@ -25,7 +25,7 @@ public class NotNodeReordererTest {
}
@Test
- public void requireThatNotChildrenAreMovedToLastOrChild() {
+ void requireThatNotChildrenAreMovedToLastOrChild() {
checkReorder(
or(feature("c").notInSet("d"), feature("a").inSet("b")),
or(feature("a").inSet("b"), feature("c").notInSet("d")));
@@ -36,15 +36,15 @@ public class NotNodeReordererTest {
}
@Test
- public void requireThatComplexReorderingWork() {
+ void requireThatComplexReorderingWork() {
checkReorder(and(feature("g").inSet("h"),
- or(and(feature("a").notInSet("b"),
- feature("c").notInSet("d")),
- feature("e").inSet("f"))),
+ or(and(feature("a").notInSet("b"),
+ feature("c").notInSet("d")),
+ feature("e").inSet("f"))),
and(or(feature("e").inSet("f"),
- and(feature("a").notInSet("b"),
- feature("c").notInSet("d"))),
- feature("g").inSet("h")));
+ and(feature("a").notInSet("b"),
+ feature("c").notInSet("d"))),
+ feature("g").inSet("h")));
}
private static void checkReorder(Predicate input, Predicate expected) {
diff --git a/predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/OrSimplifierTest.java b/predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/OrSimplifierTest.java
index 90487b761db..e51e3d29ac2 100644
--- a/predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/OrSimplifierTest.java
+++ b/predicate-search-core/src/test/java/com/yahoo/search/predicate/optimization/OrSimplifierTest.java
@@ -2,18 +2,18 @@
package com.yahoo.search.predicate.optimization;
import com.yahoo.document.predicate.Predicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static com.yahoo.document.predicate.Predicates.and;
import static com.yahoo.document.predicate.Predicates.feature;
import static com.yahoo.document.predicate.Predicates.not;
import static com.yahoo.document.predicate.Predicates.or;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class OrSimplifierTest {
@Test
- public void require_that_or_with_feature_sets_of_same_key_is_simplified_to_single_feature_set() {
+ void require_that_or_with_feature_sets_of_same_key_is_simplified_to_single_feature_set() {
Predicate p =
or(
feature("key1").inSet("value1", "value4"),
@@ -24,7 +24,7 @@ public class OrSimplifierTest {
}
@Test
- public void require_that_or_with_feature_sets_of_different_keys_is_simplified() {
+ void require_that_or_with_feature_sets_of_different_keys_is_simplified() {
Predicate p =
or(
feature("key1").inSet("value1", "value3"),
@@ -39,7 +39,7 @@ public class OrSimplifierTest {
}
@Test
- public void require_that_conversion_is_recursive_and_cascades() {
+ void require_that_conversion_is_recursive_and_cascades() {
Predicate p =
or(
feature("key1").inSet("value1", "value4"),
@@ -52,7 +52,7 @@ public class OrSimplifierTest {
}
@Test
- public void require_that_or_below_and_is_converted() {
+ void require_that_or_below_and_is_converted() {
Predicate p =
and(
or(
@@ -67,7 +67,7 @@ public class OrSimplifierTest {
}
@Test
- public void require_that_or_below_not_is_converted() {
+ void require_that_or_below_not_is_converted() {
Predicate p =
not(
or(
@@ -78,7 +78,7 @@ public class OrSimplifierTest {
}
@Test
- public void require_that_non_feature_set_nodes_are_left_untouched() {
+ void require_that_non_feature_set_nodes_are_left_untouched() {
Predicate p =
or(
feature("key1").inSet("value1"),
diff --git a/predicate-search/pom.xml b/predicate-search/pom.xml
index 75c9350707c..a41c72b0211 100644
--- a/predicate-search/pom.xml
+++ b/predicate-search/pom.xml
@@ -15,11 +15,6 @@
<name>${project.artifactId}</name>
<dependencies>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
@@ -36,6 +31,16 @@
<scope>provided</scope>
</dependency>
<dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/PredicateIndexBuilderTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/PredicateIndexBuilderTest.java
index bed1228c8b8..b6e4de3a6b8 100644
--- a/predicate-search/src/test/java/com/yahoo/search/predicate/PredicateIndexBuilderTest.java
+++ b/predicate-search/src/test/java/com/yahoo/search/predicate/PredicateIndexBuilderTest.java
@@ -3,24 +3,27 @@ package com.yahoo.search.predicate;
import com.yahoo.document.predicate.BooleanPredicate;
import com.yahoo.document.predicate.Predicate;
-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;
/**
* @author bjorncs
*/
public class PredicateIndexBuilderTest {
- @Test(expected = IllegalArgumentException.class)
- public void requireThatIndexingMultiDocumentsWithSameIdThrowsException() {
- PredicateIndexBuilder builder = new PredicateIndexBuilder(2);
- builder.indexDocument(1, Predicate.fromString("a in ['b']"));
- builder.indexDocument(1, Predicate.fromString("c in ['d']"));
+ @Test
+ void requireThatIndexingMultiDocumentsWithSameIdThrowsException() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ PredicateIndexBuilder builder = new PredicateIndexBuilder(2);
+ builder.indexDocument(1, Predicate.fromString("a in ['b']"));
+ builder.indexDocument(1, Predicate.fromString("c in ['d']"));
+ });
}
@Test
- public void requireThatEmptyDocumentsCanBeIndexed() {
+ void requireThatEmptyDocumentsCanBeIndexed() {
PredicateIndexBuilder builder = new PredicateIndexBuilder(10);
assertEquals(0, builder.getZeroConstraintDocCount());
builder.indexDocument(2, new BooleanPredicate(true));
@@ -29,7 +32,7 @@ public class PredicateIndexBuilderTest {
}
@Test
- public void requireThatMultipleDocumentsCanBeIndexed() {
+ void requireThatMultipleDocumentsCanBeIndexed() {
PredicateIndexBuilder builder = new PredicateIndexBuilder(10);
builder.indexDocument(1, Predicate.fromString("a in ['b']"));
builder.indexDocument(2, Predicate.fromString("a in ['b']"));
diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/PredicateIndexTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/PredicateIndexTest.java
index 5ed04418664..a8aef273f3c 100644
--- a/predicate-search/src/test/java/com/yahoo/search/predicate/PredicateIndexTest.java
+++ b/predicate-search/src/test/java/com/yahoo/search/predicate/PredicateIndexTest.java
@@ -2,13 +2,13 @@
package com.yahoo.search.predicate;
import com.yahoo.document.predicate.Predicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import static com.yahoo.search.predicate.serialization.SerializationTestHelper.assertSerializationDeserializationMatches;
import static java.util.stream.Collectors.toList;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author <a href="mailto:magnarn@yahoo-inc.com">Magnar Nedland</a>
@@ -19,7 +19,7 @@ public class PredicateIndexTest {
private static final int DOC_ID = 42;
@Test
- public void requireThatPredicateIndexCanSearch() {
+ void requireThatPredicateIndexCanSearch() {
PredicateIndexBuilder builder = new PredicateIndexBuilder(10);
builder.indexDocument(1, Predicate.fromString("country in ['no', 'se'] and gender in ['male']"));
builder.indexDocument(0x3fffffe, Predicate.fromString("country in ['no'] and gender in ['female']"));
@@ -34,7 +34,7 @@ public class PredicateIndexTest {
}
@Test
- public void requireThatPredicateIndexCanSearchWithNotExpression() {
+ void requireThatPredicateIndexCanSearchWithNotExpression() {
{
PredicateIndexBuilder builder = new PredicateIndexBuilder(10);
builder.indexDocument(1, Predicate.fromString("country in ['no'] and gender not in ['male']"));
@@ -77,7 +77,7 @@ public class PredicateIndexTest {
}
@Test
- public void requireThatSearchesCanUseSubqueries() {
+ void requireThatSearchesCanUseSubqueries() {
PredicateIndexBuilder builder = new PredicateIndexBuilder(10);
builder.indexDocument(DOC_ID, Predicate.fromString("country in [no] and gender in [male]"));
PredicateIndex index = builder.build();
@@ -91,7 +91,7 @@ public class PredicateIndexTest {
}
@Test
- public void requireThatPredicateIndexCanSearchWithRange() {
+ void requireThatPredicateIndexCanSearchWithRange() {
PredicateIndexBuilder builder = new PredicateIndexBuilder(10);
builder.indexDocument(1, Predicate.fromString("gender in ['male'] and age in [20..40]"));
builder.indexDocument(2, Predicate.fromString("gender in ['female'] and age in [20..40]"));
@@ -106,7 +106,7 @@ public class PredicateIndexTest {
}
@Test
- public void requireThatPredicateIndexCanSearchWithEmptyDocuments() {
+ void requireThatPredicateIndexCanSearchWithEmptyDocuments() {
PredicateIndexBuilder builder = new PredicateIndexBuilder(10);
builder.indexDocument(1, Predicate.fromString("true"));
builder.indexDocument(2, Predicate.fromString("false"));
@@ -117,7 +117,7 @@ public class PredicateIndexTest {
}
@Test
- public void requireThatPredicatesHavingMultipleIdenticalConjunctionsAreSupported() {
+ void requireThatPredicatesHavingMultipleIdenticalConjunctionsAreSupported() {
PredicateIndexBuilder builder = new PredicateIndexBuilder(10);
builder.indexDocument(DOC_ID, Predicate.fromString(
"((a in ['b'] and c in ['d']) or x in ['y']) and ((a in ['b'] and c in ['d']) or z in ['w'])"));
@@ -130,7 +130,7 @@ public class PredicateIndexTest {
}
@Test
- public void require_that_serialization_and_deserialization_retain_data() throws IOException {
+ void require_that_serialization_and_deserialization_retain_data() throws IOException {
PredicateIndexBuilder builder = new PredicateIndexBuilder(10);
builder.indexDocument(1, Predicate.fromString("country in ['no', 'se'] and gender in ['male']"));
builder.indexDocument(0x3fffffe, Predicate.fromString("country in ['no'] and gender in ['female']"));
diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/annotator/PredicateTreeAnalyzerTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/annotator/PredicateTreeAnalyzerTest.java
index 789a8e0a7f4..bde9891895b 100644
--- a/predicate-search/src/test/java/com/yahoo/search/predicate/annotator/PredicateTreeAnalyzerTest.java
+++ b/predicate-search/src/test/java/com/yahoo/search/predicate/annotator/PredicateTreeAnalyzerTest.java
@@ -4,7 +4,7 @@ package com.yahoo.search.predicate.annotator;
import com.yahoo.document.predicate.FeatureConjunction;
import com.yahoo.document.predicate.Predicate;
import com.yahoo.document.predicate.PredicateOperator;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
@@ -12,14 +12,12 @@ import static com.yahoo.document.predicate.Predicates.and;
import static com.yahoo.document.predicate.Predicates.feature;
import static com.yahoo.document.predicate.Predicates.not;
import static com.yahoo.document.predicate.Predicates.or;
-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.*;
public class PredicateTreeAnalyzerTest {
@Test
- public void require_that_minfeature_is_1_for_simple_term() {
+ void require_that_minfeature_is_1_for_simple_term() {
Predicate p = feature("foo").inSet("bar");
PredicateTreeAnalyzerResult r = PredicateTreeAnalyzer.analyzePredicateTree(p);
assertEquals(1, r.minFeature);
@@ -28,14 +26,14 @@ public class PredicateTreeAnalyzerTest {
}
@Test
- public void require_that_minfeature_is_1_for_simple_negative_term() {
+ void require_that_minfeature_is_1_for_simple_negative_term() {
Predicate p = not(feature("foo").inSet("bar"));
PredicateTreeAnalyzerResult r = PredicateTreeAnalyzer.analyzePredicateTree(p);
assertEquals(1, r.minFeature);
}
@Test
- public void require_that_minfeature_is_sum_for_and() {
+ void require_that_minfeature_is_sum_for_and() {
Predicate p =
and(
feature("foo").inSet("bar"),
@@ -51,7 +49,7 @@ public class PredicateTreeAnalyzerTest {
}
@Test
- public void require_that_minfeature_is_min_for_or() {
+ void require_that_minfeature_is_min_for_or() {
Predicate p =
or(
and(
@@ -73,7 +71,7 @@ public class PredicateTreeAnalyzerTest {
}
@Test
- public void require_that_minfeature_rounds_up() {
+ void require_that_minfeature_rounds_up() {
Predicate p =
or(
feature("foo").inSet("bar"),
@@ -85,7 +83,7 @@ public class PredicateTreeAnalyzerTest {
}
@Test
- public void require_that_minvalue_feature_set_considers_all_values() {
+ void require_that_minvalue_feature_set_considers_all_values() {
{
Predicate p =
and(
@@ -107,7 +105,7 @@ public class PredicateTreeAnalyzerTest {
}
@Test
- public void require_that_not_features_dont_count_towards_minfeature_calculation() {
+ void require_that_not_features_dont_count_towards_minfeature_calculation() {
Predicate p =
and(
feature("foo").inSet("A"),
@@ -120,7 +118,7 @@ public class PredicateTreeAnalyzerTest {
}
@Test
- public void require_that_multilevel_and_stores_size() {
+ void require_that_multilevel_and_stores_size() {
Predicate p =
and(
and(
@@ -144,7 +142,7 @@ public class PredicateTreeAnalyzerTest {
}
@Test
- public void require_that_not_ranges_dont_count_towards_minfeature_calculation() {
+ void require_that_not_ranges_dont_count_towards_minfeature_calculation() {
Predicate p =
and(
feature("foo").inRange(0, 10),
@@ -157,7 +155,7 @@ public class PredicateTreeAnalyzerTest {
}
@Test
- public void require_that_featureconjunctions_contribute_as_one_feature() {
+ void require_that_featureconjunctions_contribute_as_one_feature() {
Predicate p =
conj(
feature("foo").inSet("bar"),
@@ -168,7 +166,7 @@ public class PredicateTreeAnalyzerTest {
}
@Test
- public void require_that_featureconjunctions_count_as_leaf_in_subtree_calculation() {
+ void require_that_featureconjunctions_count_as_leaf_in_subtree_calculation() {
Predicate p =
and(
and(
@@ -189,7 +187,7 @@ public class PredicateTreeAnalyzerTest {
}
@Test
- public void require_that_multiple_indentical_feature_conjunctions_does_not_contribute_more_than_one() {
+ void require_that_multiple_indentical_feature_conjunctions_does_not_contribute_more_than_one() {
Predicate p =
and(
or(
diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/annotator/PredicateTreeAnnotatorTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/annotator/PredicateTreeAnnotatorTest.java
index 6414104f996..2ab5ec6505b 100644
--- a/predicate-search/src/test/java/com/yahoo/search/predicate/annotator/PredicateTreeAnnotatorTest.java
+++ b/predicate-search/src/test/java/com/yahoo/search/predicate/annotator/PredicateTreeAnnotatorTest.java
@@ -11,7 +11,7 @@ import com.yahoo.document.predicate.RangePartition;
import com.yahoo.search.predicate.index.Feature;
import com.yahoo.search.predicate.index.IntervalWithBounds;
import com.yahoo.search.predicate.index.conjunction.IndexableFeatureConjunction;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
@@ -21,14 +21,12 @@ import static com.yahoo.document.predicate.Predicates.and;
import static com.yahoo.document.predicate.Predicates.feature;
import static com.yahoo.document.predicate.Predicates.not;
import static com.yahoo.document.predicate.Predicates.or;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.*;
public class PredicateTreeAnnotatorTest {
@Test
- public void require_that_or_intervals_are_the_same() {
+ void require_that_or_intervals_are_the_same() {
Predicate p =
or(
feature("key1").inSet("value1"),
@@ -42,7 +40,7 @@ public class PredicateTreeAnnotatorTest {
}
@Test
- public void require_that_ands_below_ors_get_different_intervals() {
+ void require_that_ands_below_ors_get_different_intervals() {
Predicate p =
or(
and(
@@ -62,7 +60,7 @@ public class PredicateTreeAnnotatorTest {
}
@Test
- public void require_that_nots_get_correct_intervals() {
+ void require_that_nots_get_correct_intervals() {
Predicate p =
and(
feature("key").inSet("value"),
@@ -78,7 +76,7 @@ public class PredicateTreeAnnotatorTest {
}
@Test
- public void require_that_final_first_not_interval_is_extended() {
+ void require_that_final_first_not_interval_is_extended() {
Predicate p = not(feature("key").inSet("A"));
PredicateTreeAnnotations r = PredicateTreeAnnotator.createPredicateTreeAnnotations(p);
assertEquals(1, r.minFeature);
@@ -89,7 +87,7 @@ public class PredicateTreeAnnotatorTest {
}
@Test
- public void show_different_types_of_not_intervals() {
+ void show_different_types_of_not_intervals() {
{
Predicate p =
and(
@@ -151,7 +149,7 @@ public class PredicateTreeAnnotatorTest {
}
@Test
- public void require_that_hashed_ranges_get_correct_intervals() {
+ void require_that_hashed_ranges_get_correct_intervals() {
Predicate p =
and(
range("key",
@@ -183,7 +181,7 @@ public class PredicateTreeAnnotatorTest {
}
@Test
- public void require_that_extreme_ranges_works() {
+ void require_that_extreme_ranges_works() {
Predicate p =
and(
range("max range", partition("max range=9223372036854775806-9223372036854775807")),
@@ -202,7 +200,7 @@ public class PredicateTreeAnnotatorTest {
}
@Test
- public void require_that_featureconjunctions_are_registered_and_given_an_interval() {
+ void require_that_featureconjunctions_are_registered_and_given_an_interval() {
Predicate p =
and(
or(
diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/index/BoundsPostingListTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/index/BoundsPostingListTest.java
index ad9f5b8cdd1..2bde0401c51 100644
--- a/predicate-search/src/test/java/com/yahoo/search/predicate/index/BoundsPostingListTest.java
+++ b/predicate-search/src/test/java/com/yahoo/search/predicate/index/BoundsPostingListTest.java
@@ -2,15 +2,13 @@
package com.yahoo.search.predicate.index;
import com.google.common.primitives.Ints;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static java.util.stream.Collectors.toList;
-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.*;
/**
* This test lies in com.yahoo.search.predicate to get access to some methods of PredicateIndex.
@@ -20,7 +18,7 @@ import static org.junit.Assert.assertTrue;
public class BoundsPostingListTest {
@Test
- public void requireThatPostingListChecksBounds() {
+ void requireThatPostingListChecksBounds() {
PredicateIntervalStore.Builder builder = new PredicateIntervalStore.Builder();
List<Integer> docIds = new ArrayList<>();
List<Integer> dataRefs = new ArrayList<>();
@@ -72,13 +70,13 @@ public class BoundsPostingListTest {
}
private void checkNext(BoundsPostingList postingList, int movePast, int docId, int intervalCount) {
- assertTrue("Unable to move past " + movePast, postingList.nextDocument(movePast));
+ assertTrue(postingList.nextDocument(movePast), "Unable to move past " + movePast);
assertEquals(intervalCount > 0, postingList.prepareIntervals());
assertEquals(docId, postingList.getDocId());
for (int i = 0; i < intervalCount - 1; ++i) {
- assertTrue("Too few intervals, expected " + intervalCount, postingList.nextInterval());
+ assertTrue(postingList.nextInterval(), "Too few intervals, expected " + intervalCount);
}
- assertFalse("Too many intervals, expected " + intervalCount, postingList.nextInterval());
+ assertFalse(postingList.nextInterval(), "Too many intervals, expected " + intervalCount);
}
}
diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/index/CachedPostingListCounterTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/index/CachedPostingListCounterTest.java
index 21691a47f3e..71cbff6ab3f 100644
--- a/predicate-search/src/test/java/com/yahoo/search/predicate/index/CachedPostingListCounterTest.java
+++ b/predicate-search/src/test/java/com/yahoo/search/predicate/index/CachedPostingListCounterTest.java
@@ -3,14 +3,14 @@ package com.yahoo.search.predicate.index;
import com.google.common.primitives.Ints;
import org.eclipse.collections.impl.map.mutable.primitive.ObjectIntHashMap;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -20,7 +20,7 @@ import static org.mockito.Mockito.when;
public class CachedPostingListCounterTest {
@Test
- public void require_that_docids_are_counted_correctly() {
+ void require_that_docids_are_counted_correctly() {
int nDocuments = 4;
byte[] nPostingListsPerDocument = new byte[nDocuments];
CachedPostingListCounter c = new CachedPostingListCounter(nDocuments);
@@ -35,7 +35,7 @@ public class CachedPostingListCounterTest {
}
@Test
- public void require_that_most_costly_posting_lists_are_first_in_bit_vector() {
+ void require_that_most_costly_posting_lists_are_first_in_bit_vector() {
int nDocuments = 5;
CachedPostingListCounter c = new CachedPostingListCounter(nDocuments);
List<PostingList> list = new ArrayList<>();
@@ -43,7 +43,10 @@ public class CachedPostingListCounterTest {
PostingList p2 = postingList(0, 1, 2, 3, 4);
PostingList p3 = postingList(1, 2, 3, 4);
PostingList p4 = postingList(3, 4);
- list.add(p1); list.add(p2); list.add(p3); list.add(p4);
+ list.add(p1);
+ list.add(p2);
+ list.add(p3);
+ list.add(p4);
for (int i = 0; i < 100; i++) {
list.add(postingList(0));
}
@@ -64,7 +67,7 @@ public class CachedPostingListCounterTest {
}
@Test
- public void require_that_cached_docids_are_counted_correctly() {
+ void require_that_cached_docids_are_counted_correctly() {
int nDocuments = 4;
byte[] nPostingListsPerDocument = new byte[nDocuments];
CachedPostingListCounter c = new CachedPostingListCounter(nDocuments);
@@ -82,7 +85,7 @@ public class CachedPostingListCounterTest {
}
@Test
- public void require_that_cache_rebuilding_behaves_correctly_for_large_amount_of_posting_lists() {
+ void require_that_cache_rebuilding_behaves_correctly_for_large_amount_of_posting_lists() {
int nDocuments = 4;
byte[] nPostingListsPerDocument = new byte[nDocuments];
CachedPostingListCounter c = new CachedPostingListCounter(nDocuments);
diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/index/IntervalPostingListTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/index/IntervalPostingListTest.java
index 6cf8821c5f4..755cf39afff 100644
--- a/predicate-search/src/test/java/com/yahoo/search/predicate/index/IntervalPostingListTest.java
+++ b/predicate-search/src/test/java/com/yahoo/search/predicate/index/IntervalPostingListTest.java
@@ -2,24 +2,22 @@
package com.yahoo.search.predicate.index;
import com.yahoo.search.predicate.SubqueryBitmap;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
-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.*;
public class IntervalPostingListTest {
@Test
- public void requireThatPostingListCanIterate() {
+ void requireThatPostingListCanIterate() {
PredicateIntervalStore.Builder builder = new PredicateIntervalStore.Builder();
int ref1 = builder.insert(Arrays.asList(0x1ffff));
int ref2 = builder.insert(Arrays.asList(0x1ffff));
int ref3 = builder.insert(Arrays.asList(0x10001, 0x2ffff));
IntervalPostingList postingList = new IntervalPostingList(
- builder.build(), new int[]{2, 4, 6}, new int[] {ref1, ref2, ref3}, SubqueryBitmap.ALL_SUBQUERIES);
+ builder.build(), new int[]{2, 4, 6}, new int[]{ref1, ref2, ref3}, SubqueryBitmap.ALL_SUBQUERIES);
assertEquals(-1, postingList.getDocId());
assertEquals(0, postingList.getInterval());
assertEquals(0xffffffffffffffffL, postingList.getSubquery());
diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/index/PredicateIntervalStoreTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/index/PredicateIntervalStoreTest.java
index c12817fbcf6..95ce3116fdf 100644
--- a/predicate-search/src/test/java/com/yahoo/search/predicate/index/PredicateIntervalStoreTest.java
+++ b/predicate-search/src/test/java/com/yahoo/search/predicate/index/PredicateIntervalStoreTest.java
@@ -2,7 +2,7 @@
package com.yahoo.search.predicate.index;
import com.google.common.primitives.Ints;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.ArrayList;
@@ -10,44 +10,44 @@ import java.util.Arrays;
import java.util.List;
import static com.yahoo.search.predicate.serialization.SerializationTestHelper.assertSerializationDeserializationMatches;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author bjorncs
*/
public class PredicateIntervalStoreTest {
- @Test(expected = IllegalArgumentException.class)
- public void requireThatEmptyIntervalListThrows() {
- PredicateIntervalStore.Builder builder = new PredicateIntervalStore.Builder();
- builder.insert(new ArrayList<>());
+ @Test
+ void requireThatEmptyIntervalListThrows() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ PredicateIntervalStore.Builder builder = new PredicateIntervalStore.Builder();
+ builder.insert(new ArrayList<>());
+ });
}
@Test
- public void requireThatSingleIntervalCanBeInserted() {
+ void requireThatSingleIntervalCanBeInserted() {
testInsertAndRetrieve(0x0001ffff);
}
@Test
- public void requireThatMultiIntervalEntriesCanBeInserted() {
+ void requireThatMultiIntervalEntriesCanBeInserted() {
testInsertAndRetrieve(0x00010001, 0x00020002, 0x0003ffff);
testInsertAndRetrieve(0x00010001, 0x00020002, 0x00030003, 0x00040004, 0x00050005, 0x00060006,
0x00070007, 0x00080008, 0x00090009, 0x000a000a);
}
@Test
- public void requireThatDifferentSizeIntervalArraysCanBeInserted() {
+ void requireThatDifferentSizeIntervalArraysCanBeInserted() {
PredicateIntervalStore.Builder builder = new PredicateIntervalStore.Builder();
- int intervals1[] = new int[] {0x00010001, 0x00020002};
- int intervals2[] = new int[] {0x00010001, 0x00020002, 0x00030003};
+ int intervals1[] = new int[]{0x00010001, 0x00020002};
+ int intervals2[] = new int[]{0x00010001, 0x00020002, 0x00030003};
assertEquals(0, builder.insert(Ints.asList(intervals1)));
assertEquals(1, builder.insert(Ints.asList(intervals2)));
}
@Test
- public void requireThatSerializationAndDeserializationRetainIntervals() throws IOException {
+ void requireThatSerializationAndDeserializationRetainIntervals() throws IOException {
PredicateIntervalStore.Builder builder = new PredicateIntervalStore.Builder();
builder.insert(Arrays.asList(0x00010001, 0x00020002));
builder.insert(Arrays.asList(0x00010001, 0x00020002, 0x00030003));
@@ -58,7 +58,7 @@ public class PredicateIntervalStoreTest {
}
@Test
- public void requireThatEqualIntervalListsReturnsSameReference() {
+ void requireThatEqualIntervalListsReturnsSameReference() {
PredicateIntervalStore.Builder builder = new PredicateIntervalStore.Builder();
List<Integer> intervals1 = Arrays.asList(0x00010001, 0x00020002);
List<Integer> intervals2 = Arrays.asList(0x00010001, 0x00020002);
@@ -67,7 +67,7 @@ public class PredicateIntervalStoreTest {
PredicateIntervalStore store = builder.build();
int[] a1 = store.get(ref1);
int[] a2 = store.get(ref2);
- assertTrue(a1 == a2);
+ assertEquals(a1, a2);
}
private static void testInsertAndRetrieve(int... intervals) {
diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/index/PredicateRangeTermExpanderTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/index/PredicateRangeTermExpanderTest.java
index 90db2aea89b..9d43893864d 100644
--- a/predicate-search/src/test/java/com/yahoo/search/predicate/index/PredicateRangeTermExpanderTest.java
+++ b/predicate-search/src/test/java/com/yahoo/search/predicate/index/PredicateRangeTermExpanderTest.java
@@ -2,21 +2,19 @@
package com.yahoo.search.predicate.index;
import com.yahoo.document.predicate.PredicateHash;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Iterator;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.*;
/**
* @author <a href="mailto:magnarn@yahoo-inc.com">Magnar Nedland</a>
*/
public class PredicateRangeTermExpanderTest {
@Test
- public void requireThatSmallRangeIsExpanded() {
+ void requireThatSmallRangeIsExpanded() {
PredicateRangeTermExpander expander = new PredicateRangeTermExpander(10);
Iterator<String> expectedLabels = Arrays.asList(
"key=40-49",
@@ -38,12 +36,15 @@ public class PredicateRangeTermExpanderTest {
"key=0-99999999999999999",
"key=0-999999999999999999").iterator();
expander.expand("key", 42, range -> assertEquals(PredicateHash.hash64(expectedLabels.next()), range),
- (edge, value) -> { assertEquals(PredicateHash.hash64("key=40"), edge); assertEquals(2, value); });
+ (edge, value) -> {
+ assertEquals(PredicateHash.hash64("key=40"), edge);
+ assertEquals(2, value);
+ });
assertFalse(expectedLabels.hasNext());
}
@Test
- public void requireThatLargeRangeIsExpanded() {
+ void requireThatLargeRangeIsExpanded() {
PredicateRangeTermExpander expander = new PredicateRangeTermExpander(10);
Iterator<String> expectedLabels = Arrays.asList(
"key=123456789012345670-123456789012345679",
@@ -65,12 +66,15 @@ public class PredicateRangeTermExpanderTest {
"key=100000000000000000-199999999999999999",
"key=0-999999999999999999").iterator();
expander.expand("key", 123456789012345678L, range -> assertEquals(PredicateHash.hash64(expectedLabels.next()), range),
- (edge, value) -> { assertEquals(PredicateHash.hash64("key=123456789012345670"), edge); assertEquals(8, value); });
+ (edge, value) -> {
+ assertEquals(PredicateHash.hash64("key=123456789012345670"), edge);
+ assertEquals(8, value);
+ });
assertFalse(expectedLabels.hasNext());
}
@Test
- public void requireThatMaxRangeIsExpanded() {
+ void requireThatMaxRangeIsExpanded() {
PredicateRangeTermExpander expander = new PredicateRangeTermExpander(10);
expander.expand("key", 9223372036854775807L, range -> fail(),
(edge, value) -> {
@@ -80,7 +84,7 @@ public class PredicateRangeTermExpanderTest {
}
@Test
- public void requireThatSmallNegativeRangeIsExpanded() {
+ void requireThatSmallNegativeRangeIsExpanded() {
PredicateRangeTermExpander expander = new PredicateRangeTermExpander(10);
Iterator<String> expectedLabels = Arrays.asList(
"key=-49-40",
@@ -102,12 +106,15 @@ public class PredicateRangeTermExpanderTest {
"key=-99999999999999999-0",
"key=-999999999999999999-0").iterator();
expander.expand("key", -42, range -> assertEquals(PredicateHash.hash64(expectedLabels.next()), range),
- (edge, value) -> { assertEquals(PredicateHash.hash64("key=-40"), edge); assertEquals(2, value); });
+ (edge, value) -> {
+ assertEquals(PredicateHash.hash64("key=-40"), edge);
+ assertEquals(2, value);
+ });
assertFalse(expectedLabels.hasNext());
}
@Test
- public void requireThatMinRangeIsExpanded() {
+ void requireThatMinRangeIsExpanded() {
PredicateRangeTermExpander expander = new PredicateRangeTermExpander(10);
expander.expand("key", -9223372036854775808L, range -> fail(),
(edge, value) -> {
@@ -117,18 +124,21 @@ public class PredicateRangeTermExpanderTest {
}
@Test
- public void requireThatMinRangeMinus9IsExpanded() {
+ void requireThatMinRangeMinus9IsExpanded() {
PredicateRangeTermExpander expander = new PredicateRangeTermExpander(10);
Iterator<String> expectedLabels = Arrays.asList(
"key=-9223372036854775799-9223372036854775790",
"key=-9223372036854775799-9223372036854775700").iterator();
expander.expand("key", -9223372036854775799L, range -> assertEquals(PredicateHash.hash64(expectedLabels.next()), range),
- (edge, value) -> { assertEquals(PredicateHash.hash64("key=-9223372036854775790"), edge); assertEquals(9, value); });
+ (edge, value) -> {
+ assertEquals(PredicateHash.hash64("key=-9223372036854775790"), edge);
+ assertEquals(9, value);
+ });
assertFalse(expectedLabels.hasNext());
}
@Test
- public void requireThatMinRangeIsExpandedWithArity8() {
+ void requireThatMinRangeIsExpandedWithArity8() {
PredicateRangeTermExpander expander = new PredicateRangeTermExpander(8);
expander.expand("key", -9223372036854775808L, range -> fail(),
(edge, value) -> {
@@ -138,7 +148,7 @@ public class PredicateRangeTermExpanderTest {
}
@Test
- public void requireThatSmallRangeIsExpandedInArity2() {
+ void requireThatSmallRangeIsExpandedInArity2() {
PredicateRangeTermExpander expander = new PredicateRangeTermExpander(2);
Iterator<String> expectedLabels = Arrays.asList(
"key=42-43",
@@ -205,12 +215,15 @@ public class PredicateRangeTermExpanderTest {
"key=0-4611686018427387903",
"key=0-9223372036854775807").iterator();
expander.expand("key", 42, range -> assertEquals(PredicateHash.hash64(expectedLabels.next()), range),
- (edge, value) -> { assertEquals(PredicateHash.hash64("key=42"), edge); assertEquals(0, value); });
+ (edge, value) -> {
+ assertEquals(PredicateHash.hash64("key=42"), edge);
+ assertEquals(0, value);
+ });
assertFalse(expectedLabels.hasNext());
}
@Test
- public void requireThatSmallNegativeRangeIsExpandedInArity2() {
+ void requireThatSmallNegativeRangeIsExpandedInArity2() {
PredicateRangeTermExpander expander = new PredicateRangeTermExpander(2);
Iterator<String> expectedLabels = Arrays.asList(
"key=-43-42",
@@ -277,12 +290,15 @@ public class PredicateRangeTermExpanderTest {
"key=-4611686018427387903-0",
"key=-9223372036854775807-0").iterator();
expander.expand("key", -42, range -> assertEquals(PredicateHash.hash64(expectedLabels.next()), range),
- (edge, value) -> { assertEquals(PredicateHash.hash64("key=-42"), edge); assertEquals(0, value); });
+ (edge, value) -> {
+ assertEquals(PredicateHash.hash64("key=-42"), edge);
+ assertEquals(0, value);
+ });
assertFalse(expectedLabels.hasNext());
}
@Test
- public void requireThatUpperBoundIsUsed() {
+ void requireThatUpperBoundIsUsed() {
PredicateRangeTermExpander expander = new PredicateRangeTermExpander(10, -99, 9999);
Iterator<String> expectedLabels = Arrays.asList(
"key=40-49",
@@ -290,12 +306,15 @@ public class PredicateRangeTermExpanderTest {
"key=0-999",
"key=0-9999").iterator();
expander.expand("key", 42, range -> assertEquals(PredicateHash.hash64(expectedLabels.next()), range),
- (edge, value) -> { assertEquals(PredicateHash.hash64("key=40"), edge); assertEquals(2, value); });
+ (edge, value) -> {
+ assertEquals(PredicateHash.hash64("key=40"), edge);
+ assertEquals(2, value);
+ });
assertFalse(expectedLabels.hasNext());
}
@Test
- public void requireThatLowerBoundIsUsed() {
+ void requireThatLowerBoundIsUsed() {
PredicateRangeTermExpander expander = new PredicateRangeTermExpander(10, -9999, 99);
Iterator<String> expectedLabels = Arrays.asList(
"key=-49-40",
@@ -303,19 +322,22 @@ public class PredicateRangeTermExpanderTest {
"key=-999-0",
"key=-9999-0").iterator();
expander.expand("key", -42, range -> assertEquals(PredicateHash.hash64(expectedLabels.next()), range),
- (edge, value) -> { assertEquals(PredicateHash.hash64("key=-40"), edge); assertEquals(2, value); });
+ (edge, value) -> {
+ assertEquals(PredicateHash.hash64("key=-40"), edge);
+ assertEquals(2, value);
+ });
assertFalse(expectedLabels.hasNext());
}
@Test
- public void requireThatSearchesOutsideBoundsGenerateNoLabels() {
+ void requireThatSearchesOutsideBoundsGenerateNoLabels() {
PredicateRangeTermExpander expander = new PredicateRangeTermExpander(10, 0, 200);
- expander.expand("key", -10, x -> fail(), (x,y) -> fail());
+ expander.expand("key", -10, x -> fail(), (x, y) -> fail());
expander.expand("key", 210, x -> fail(), (x, y) -> fail());
}
@Test
- public void requireThatUpperAndLowerBoundGreaterThan0Works() {
+ void requireThatUpperAndLowerBoundGreaterThan0Works() {
PredicateRangeTermExpander expander = new PredicateRangeTermExpander(10, 100, 9999);
Iterator<String> expectedLabels = Arrays.asList(
"key=140-149",
@@ -323,12 +345,15 @@ public class PredicateRangeTermExpanderTest {
"key=0-999",
"key=0-9999").iterator();
expander.expand("key", 142, range -> assertEquals(PredicateHash.hash64(expectedLabels.next()), range),
- (edge, value) -> { assertEquals(PredicateHash.hash64("key=140"), edge); assertEquals(2, value); });
+ (edge, value) -> {
+ assertEquals(PredicateHash.hash64("key=140"), edge);
+ assertEquals(2, value);
+ });
assertFalse(expectedLabels.hasNext());
}
@Test
- public void requireThatSearchCloseToUnevenUpperBoundIsSensible() {
+ void requireThatSearchCloseToUnevenUpperBoundIsSensible() {
PredicateRangeTermExpander expander = new PredicateRangeTermExpander(10, -99, 1234);
Iterator<String> expectedLabels = Arrays.asList(
"key=40-49",
@@ -336,19 +361,25 @@ public class PredicateRangeTermExpanderTest {
"key=0-999",
"key=0-9999").iterator();
expander.expand("key", 42, range -> assertEquals(PredicateHash.hash64(expectedLabels.next()), range),
- (edge, value) -> { assertEquals(PredicateHash.hash64("key=40"), edge); assertEquals(2, value); });
+ (edge, value) -> {
+ assertEquals(PredicateHash.hash64("key=40"), edge);
+ assertEquals(2, value);
+ });
assertFalse(expectedLabels.hasNext());
}
@Test
- public void requireThatSearchCloseToMaxUnevenUpperBoundIsSensible() {
+ void requireThatSearchCloseToMaxUnevenUpperBoundIsSensible() {
PredicateRangeTermExpander expander = new PredicateRangeTermExpander(10, 0, 9223372036854771234L);
Iterator<String> expectedLabels = Arrays.asList(
"key=9223372036854770000-9223372036854770009",
"key=9223372036854770000-9223372036854770099",
"key=9223372036854770000-9223372036854770999").iterator();
expander.expand("key", 9223372036854770000L, range -> assertEquals(PredicateHash.hash64(expectedLabels.next()), range),
- (edge, value) -> { assertEquals(PredicateHash.hash64("key=9223372036854770000"), edge); assertEquals(0, value); });
+ (edge, value) -> {
+ assertEquals(PredicateHash.hash64("key=9223372036854770000"), edge);
+ assertEquals(0, value);
+ });
assertFalse(expectedLabels.hasNext());
}
}
diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/index/PredicateSearchTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/index/PredicateSearchTest.java
index 654b944fb3f..433d69e88a2 100644
--- a/predicate-search/src/test/java/com/yahoo/search/predicate/index/PredicateSearchTest.java
+++ b/predicate-search/src/test/java/com/yahoo/search/predicate/index/PredicateSearchTest.java
@@ -3,14 +3,14 @@ package com.yahoo.search.predicate.index;
import com.yahoo.search.predicate.Hit;
import com.yahoo.search.predicate.SubqueryBitmap;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static java.util.stream.Collectors.toList;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author <a href="mailto:magnarn@yahoo-inc.com">Magnar Nedland</a>
@@ -19,13 +19,13 @@ import static org.junit.Assert.assertEquals;
public class PredicateSearchTest {
@Test
- public void requireThatNoStreamsReturnNoResults() {
+ void requireThatNoStreamsReturnNoResults() {
PredicateSearch search = new PredicateSearch(new ArrayList<>(), new byte[0], new byte[0], new short[0], 1);
assertEquals(0, search.stream().count());
}
@Test
- public void requireThatSingleStreamFiltersOnConstructedCompleteIntervals() {
+ void requireThatSingleStreamFiltersOnConstructedCompleteIntervals() {
PredicateSearch search = createPredicateSearch(
new byte[]{1, 1, 1},
postingList(
@@ -37,7 +37,7 @@ public class PredicateSearchTest {
}
@Test
- public void requireThatMinFeatureIsUsedToPruneResults() {
+ void requireThatMinFeatureIsUsedToPruneResults() {
PredicateSearch search = createPredicateSearch(
new byte[]{3, 1},
postingList(
@@ -48,7 +48,7 @@ public class PredicateSearchTest {
}
@Test
- public void requireThatAHighKCanYieldResults() {
+ void requireThatAHighKCanYieldResults() {
PredicateSearch search = createPredicateSearch(
new byte[]{2},
postingList(SubqueryBitmap.ALL_SUBQUERIES,
@@ -59,9 +59,9 @@ public class PredicateSearchTest {
}
@Test
- public void requireThatPostingListsAreSortedAfterAdvancing() {
+ void requireThatPostingListsAreSortedAfterAdvancing() {
PredicateSearch search = createPredicateSearch(
- new byte[] {2, 1, 1, 1},
+ new byte[]{2, 1, 1, 1},
postingList(SubqueryBitmap.ALL_SUBQUERIES,
entry(0, 0x000100ff),
entry(3, 0x000100ff)),
@@ -72,7 +72,7 @@ public class PredicateSearchTest {
}
@Test
- public void requireThatEmptyPostingListsWork() {
+ void requireThatEmptyPostingListsWork() {
PredicateSearch search = createPredicateSearch(
new byte[0],
postingList(SubqueryBitmap.ALL_SUBQUERIES));
@@ -80,7 +80,7 @@ public class PredicateSearchTest {
}
@Test
- public void requireThatShorterPostingListEndingIsOk() {
+ void requireThatShorterPostingListEndingIsOk() {
PredicateSearch search = createPredicateSearch(
new byte[]{1, 1, 1},
postingList(SubqueryBitmap.ALL_SUBQUERIES,
@@ -92,7 +92,7 @@ public class PredicateSearchTest {
}
@Test
- public void requireThatSortingWorksForManyPostingLists() {
+ void requireThatSortingWorksForManyPostingLists() {
PredicateSearch search = createPredicateSearch(
new byte[]{1, 5, 2, 2},
postingList(SubqueryBitmap.ALL_SUBQUERIES,
@@ -116,7 +116,7 @@ public class PredicateSearchTest {
}
@Test
- public void requireThatInsufficientIntervalCoveragePreventsMatch() {
+ void requireThatInsufficientIntervalCoveragePreventsMatch() {
PredicateSearch search = createPredicateSearch(
new byte[]{1, 1},
postingList(SubqueryBitmap.ALL_SUBQUERIES,
@@ -126,7 +126,7 @@ public class PredicateSearchTest {
}
@Test
- public void requireThatIntervalsAreSorted() {
+ void requireThatIntervalsAreSorted() {
PredicateSearch search = createPredicateSearch(
new byte[]{1},
postingList(SubqueryBitmap.ALL_SUBQUERIES,
@@ -139,7 +139,7 @@ public class PredicateSearchTest {
}
@Test
- public void requireThatThereCanBeManyIntervals() {
+ void requireThatThereCanBeManyIntervals() {
PredicateSearch search = createPredicateSearch(
new byte[]{1},
postingList(SubqueryBitmap.ALL_SUBQUERIES,
@@ -148,7 +148,7 @@ public class PredicateSearchTest {
}
@Test
- public void requireThatNotIsSupported_NoMatch() {
+ void requireThatNotIsSupported_NoMatch() {
PredicateSearch search = createPredicateSearch(
new byte[]{1},
postingList(SubqueryBitmap.ALL_SUBQUERIES,
@@ -159,7 +159,7 @@ public class PredicateSearchTest {
}
@Test
- public void requireThatNotIsSupported_Match() {
+ void requireThatNotIsSupported_Match() {
PredicateSearch search = createPredicateSearch(
new byte[]{1},
postingList(SubqueryBitmap.ALL_SUBQUERIES,
@@ -168,7 +168,7 @@ public class PredicateSearchTest {
}
@Test
- public void requireThatNotIsSupported_NoMatchBecauseOfPreviousTerm() {
+ void requireThatNotIsSupported_NoMatchBecauseOfPreviousTerm() {
PredicateSearch search = createPredicateSearch(
new byte[]{1},
postingList(SubqueryBitmap.ALL_SUBQUERIES,
@@ -177,7 +177,7 @@ public class PredicateSearchTest {
}
@Test
- public void requireThatIntervalSortingWorksAsUnsigned() {
+ void requireThatIntervalSortingWorksAsUnsigned() {
PredicateSearch search = createPredicateSearch(
new byte[]{1},
postingList(SubqueryBitmap.ALL_SUBQUERIES,
@@ -188,7 +188,7 @@ public class PredicateSearchTest {
}
@Test
- public void requireThatMatchCanRequireMultiplePostingLists() {
+ void requireThatMatchCanRequireMultiplePostingLists() {
PredicateSearch search = createPredicateSearch(
new byte[]{6},
postingList(SubqueryBitmap.ALL_SUBQUERIES,
diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/index/SimpleIndexTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/index/SimpleIndexTest.java
index b0ff62e33fb..6d416eade9f 100644
--- a/predicate-search/src/test/java/com/yahoo/search/predicate/index/SimpleIndexTest.java
+++ b/predicate-search/src/test/java/com/yahoo/search/predicate/index/SimpleIndexTest.java
@@ -1,13 +1,13 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.predicate.index;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import static com.yahoo.search.predicate.serialization.SerializationTestHelper.assertSerializationDeserializationMatches;
-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 <a href="mailto:magnarn@yahoo-inc.com">Magnar Nedland</a>
@@ -19,7 +19,7 @@ public class SimpleIndexTest {
private static final int DOC_ID = 42;
@Test
- public void requireThatValuesCanBeInserted() {
+ void requireThatValuesCanBeInserted() {
SimpleIndex.Builder builder = new SimpleIndex.Builder();
builder.insert(KEY, new Posting(DOC_ID, 10));
SimpleIndex index = builder.build();
@@ -38,7 +38,7 @@ public class SimpleIndexTest {
}
@Test
- public void requireThatEntriesAreSortedOnId() {
+ void requireThatEntriesAreSortedOnId() {
SimpleIndex.Builder builder = new SimpleIndex.Builder();
builder.insert(KEY, new Posting(DOC_ID, 10));
builder.insert(KEY, new Posting(DOC_ID - 1, 20)); // Out of order
@@ -52,7 +52,7 @@ public class SimpleIndexTest {
}
@Test
- public void requireThatSerializationAndDeserializationRetainDictionary() throws IOException {
+ void requireThatSerializationAndDeserializationRetainDictionary() throws IOException {
SimpleIndex.Builder builder = new SimpleIndex.Builder();
builder.insert(KEY, new Posting(DOC_ID, 10));
builder.insert(KEY, new Posting(DOC_ID + 1, 20));
diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/index/ZeroConstraintPostingListTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/index/ZeroConstraintPostingListTest.java
index bade49aaeca..c218e9e5474 100644
--- a/predicate-search/src/test/java/com/yahoo/search/predicate/index/ZeroConstraintPostingListTest.java
+++ b/predicate-search/src/test/java/com/yahoo/search/predicate/index/ZeroConstraintPostingListTest.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.search.predicate.index;
-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.jupiter.api.Assertions.*;
/**
* @author <a href="mailto:magnarn@yahoo-inc.com">Magnar Nedland</a>
@@ -13,9 +11,9 @@ import static org.junit.Assert.assertTrue;
public class ZeroConstraintPostingListTest {
@Test
- public void requireThatPostingListCanIterate() {
+ void requireThatPostingListCanIterate() {
ZeroConstraintPostingList postingList =
- new ZeroConstraintPostingList(new int[] {2, 4, 6, 8});
+ new ZeroConstraintPostingList(new int[]{2, 4, 6, 8});
assertEquals(-1, postingList.getDocId());
assertEquals(Interval.fromBoundaries(1, Interval.ZERO_CONSTRAINT_RANGE), postingList.getInterval());
assertEquals(0xffffffffffffffffL, postingList.getSubquery());
diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/index/ZstarCompressedPostingListTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/index/ZstarCompressedPostingListTest.java
index e0378bdb7e9..f1d7d0b308a 100644
--- a/predicate-search/src/test/java/com/yahoo/search/predicate/index/ZstarCompressedPostingListTest.java
+++ b/predicate-search/src/test/java/com/yahoo/search/predicate/index/ZstarCompressedPostingListTest.java
@@ -1,20 +1,18 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.predicate.index;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
-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 <a href="mailto:magnarn@yahoo-inc.com">Magnar Nedland</a>
*/
public class ZstarCompressedPostingListTest {
@Test
- public void requireThatPostingListCanIterate() {
+ void requireThatPostingListCanIterate() {
PredicateIntervalStore.Builder builder = new PredicateIntervalStore.Builder();
int ref1 = builder.insert(Arrays.asList(0x10000));
int ref2 = builder.insert(Arrays.asList(0x10000, 0x0ffff));
diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/index/conjunction/ConjunctionIdIteratorTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/index/conjunction/ConjunctionIdIteratorTest.java
index 56c6721fe76..23068097f83 100644
--- a/predicate-search/src/test/java/com/yahoo/search/predicate/index/conjunction/ConjunctionIdIteratorTest.java
+++ b/predicate-search/src/test/java/com/yahoo/search/predicate/index/conjunction/ConjunctionIdIteratorTest.java
@@ -2,11 +2,9 @@
package com.yahoo.search.predicate.index.conjunction;
import com.yahoo.search.predicate.SubqueryBitmap;
-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.jupiter.api.Assertions.*;
/**
* @author bjorncs
@@ -15,7 +13,7 @@ public class ConjunctionIdIteratorTest {
@SuppressWarnings("PointlessBitwiseExpression")
@Test
- public void require_that_next_returns_skips_to_correct_value() {
+ void require_that_next_returns_skips_to_correct_value() {
// NOTE: LST bit represents the conjunction sign: 0 => negative, 1 => positive.
int[] conjunctionIds = new int[]{
0 | 1,
@@ -49,7 +47,7 @@ public class ConjunctionIdIteratorTest {
}
@Test
- public void require_that_subquery_is_correct() {
+ void require_that_subquery_is_correct() {
ConjunctionIdIterator iterator = new ConjunctionIdIterator(0b1111, new int[]{1});
assertEquals(0b1111, iterator.getSubqueryBitmap());
}
diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/index/conjunction/ConjunctionIndexTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/index/conjunction/ConjunctionIndexTest.java
index 07bcf83776a..9f040553a83 100644
--- a/predicate-search/src/test/java/com/yahoo/search/predicate/index/conjunction/ConjunctionIndexTest.java
+++ b/predicate-search/src/test/java/com/yahoo/search/predicate/index/conjunction/ConjunctionIndexTest.java
@@ -4,7 +4,7 @@ package com.yahoo.search.predicate.index.conjunction;
import com.yahoo.document.predicate.FeatureConjunction;
import com.yahoo.document.predicate.Predicate;
import com.yahoo.search.predicate.PredicateQuery;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.Arrays;
@@ -14,14 +14,12 @@ import java.util.List;
import static com.yahoo.document.predicate.Predicates.feature;
import static com.yahoo.document.predicate.Predicates.not;
import static com.yahoo.search.predicate.serialization.SerializationTestHelper.assertSerializationDeserializationMatches;
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
public class ConjunctionIndexTest {
@Test
- public void require_that_single_conjunction_can_be_indexed() {
+ void require_that_single_conjunction_can_be_indexed() {
ConjunctionIndexBuilder builder = new ConjunctionIndexBuilder();
builder.indexConjunction(indexableConj(conj(feature("a").inSet("1"), feature("b").inSet("2"))));
assertEquals(2, builder.calculateFeatureCount());
@@ -29,7 +27,7 @@ public class ConjunctionIndexTest {
}
@Test
- public void require_that_large_conjunction_can_be_indexed() {
+ void require_that_large_conjunction_can_be_indexed() {
ConjunctionIndexBuilder builder = new ConjunctionIndexBuilder();
builder.indexConjunction(indexableConj(
conj(
@@ -41,7 +39,7 @@ public class ConjunctionIndexTest {
}
@Test
- public void require_that_multiple_conjunctions_can_be_indexed() {
+ void require_that_multiple_conjunctions_can_be_indexed() {
ConjunctionIndexBuilder builder = new ConjunctionIndexBuilder();
builder.indexConjunction(indexableConj(
conj(
@@ -70,7 +68,7 @@ public class ConjunctionIndexTest {
}
@Test
- public void require_that_search_for_simple_conjunctions_work() {
+ void require_that_search_for_simple_conjunctions_work() {
ConjunctionIndexBuilder builder = new ConjunctionIndexBuilder();
IndexableFeatureConjunction c1 = indexableConj(
@@ -105,7 +103,7 @@ public class ConjunctionIndexTest {
@Test
- public void require_that_conjunction_with_not_is_indexed() {
+ void require_that_conjunction_with_not_is_indexed() {
ConjunctionIndexBuilder builder = new ConjunctionIndexBuilder();
builder.indexConjunction(indexableConj(
conj(
@@ -121,7 +119,7 @@ public class ConjunctionIndexTest {
}
@Test
- public void require_that_not_works_when_k_is_0() {
+ void require_that_not_works_when_k_is_0() {
ConjunctionIndexBuilder builder = new ConjunctionIndexBuilder();
IndexableFeatureConjunction c1 = indexableConj(
conj(
@@ -161,7 +159,7 @@ public class ConjunctionIndexTest {
}
@Test
- public void require_that_not_works_when_k_is_1() {
+ void require_that_not_works_when_k_is_1() {
ConjunctionIndexBuilder builder = new ConjunctionIndexBuilder();
IndexableFeatureConjunction c1 = indexableConj(
conj(
@@ -197,7 +195,7 @@ public class ConjunctionIndexTest {
}
@Test
- public void require_that_not_works_when_k_is_2() {
+ void require_that_not_works_when_k_is_2() {
ConjunctionIndexBuilder builder = new ConjunctionIndexBuilder();
IndexableFeatureConjunction c1 = indexableConj(
conj(
@@ -236,7 +234,7 @@ public class ConjunctionIndexTest {
}
@Test
- public void require_that_multi_term_queries_are_supported() {
+ void require_that_multi_term_queries_are_supported() {
ConjunctionIndexBuilder builder = new ConjunctionIndexBuilder();
IndexableFeatureConjunction c1 = indexableConj(
conj(
@@ -255,7 +253,7 @@ public class ConjunctionIndexTest {
}
@Test
- public void require_that_subqueries_are_supported() {
+ void require_that_subqueries_are_supported() {
ConjunctionIndexBuilder builder = new ConjunctionIndexBuilder();
IndexableFeatureConjunction c1 = indexableConj(
conj(
@@ -328,7 +326,7 @@ public class ConjunctionIndexTest {
}
@Test
- public void require_that_serialization_and_deserialization_retain_data() throws IOException {
+ void require_that_serialization_and_deserialization_retain_data() throws IOException {
ConjunctionIndexBuilder builder = new ConjunctionIndexBuilder();
builder.indexConjunction(indexableConj(
conj(
diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/optimization/FeatureConjunctionTransformerTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/optimization/FeatureConjunctionTransformerTest.java
index 88b8bf005a4..6bdb3d1e415 100644
--- a/predicate-search/src/test/java/com/yahoo/search/predicate/optimization/FeatureConjunctionTransformerTest.java
+++ b/predicate-search/src/test/java/com/yahoo/search/predicate/optimization/FeatureConjunctionTransformerTest.java
@@ -5,14 +5,14 @@ import com.yahoo.document.predicate.FeatureConjunction;
import com.yahoo.document.predicate.FeatureRange;
import com.yahoo.document.predicate.FeatureSet;
import com.yahoo.document.predicate.Predicate;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import static com.yahoo.document.predicate.Predicates.and;
import static com.yahoo.document.predicate.Predicates.not;
import static com.yahoo.document.predicate.Predicates.or;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bjorncs
@@ -21,7 +21,7 @@ public class FeatureConjunctionTransformerTest {
private static final FeatureConjunctionTransformer transformer = new FeatureConjunctionTransformer(true);
@Test
- public void require_that_simple_ands_are_converted() {
+ void require_that_simple_ands_are_converted() {
assertConvertedPredicateEquals(
conj(not(featureSet(1)), featureSet(2)),
and(not(featureSet(1)), featureSet(2))
@@ -29,7 +29,7 @@ public class FeatureConjunctionTransformerTest {
}
@Test
- public void require_that_featureranges_are_split_into_separate_and() {
+ void require_that_featureranges_are_split_into_separate_and() {
assertConvertedPredicateEquals(
and(featureRange(2), conj(not(featureSet(1)), featureSet(3))),
and(not(featureSet(1)), featureRange(2), featureSet(3))
@@ -37,7 +37,7 @@ public class FeatureConjunctionTransformerTest {
}
@Test
- public void require_that_ors_are_split_into_separate_and() {
+ void require_that_ors_are_split_into_separate_and() {
assertConvertedPredicateEquals(
and(or(featureSet(1), featureSet(2)), conj(featureSet(3), featureSet(4))),
and(or(featureSet(1), featureSet(2)), featureSet(3), featureSet(4))
@@ -45,7 +45,7 @@ public class FeatureConjunctionTransformerTest {
}
@Test
- public void require_that_ands_must_have_more_than_one_featureset_to_be_converted() {
+ void require_that_ands_must_have_more_than_one_featureset_to_be_converted() {
assertConvertedPredicateEquals(
and(featureSet(1), featureRange(2)),
and(featureSet(1), featureRange(2))
@@ -53,7 +53,7 @@ public class FeatureConjunctionTransformerTest {
}
@Test
- public void require_that_ordering_of_and_operands_are_preserved() {
+ void require_that_ordering_of_and_operands_are_preserved() {
assertConvertedPredicateEquals(
and(not(featureRange(1)), featureRange(4), conj(not(featureSet(2)), featureSet(3))),
and(not(featureRange(1)), not(featureSet(2)), featureSet(3), featureRange(4))
@@ -61,7 +61,7 @@ public class FeatureConjunctionTransformerTest {
}
@Test
- public void require_that_nested_ands_are_converted() {
+ void require_that_nested_ands_are_converted() {
assertConvertedPredicateEquals(
and(conj(featureSet(1), featureSet(2)), conj(featureSet(3), featureSet(4))),
and(and(featureSet(1), featureSet(2)), and(featureSet(3), featureSet(4)))
@@ -69,7 +69,7 @@ public class FeatureConjunctionTransformerTest {
}
@Test
- public void require_that_featureset_with_common_key_is_not_converted() {
+ void require_that_featureset_with_common_key_is_not_converted() {
assertConvertedPredicateEquals(
and(not(featureSet(1)), featureSet(1)),
and(not(featureSet(1)), featureSet(1))
@@ -77,7 +77,7 @@ public class FeatureConjunctionTransformerTest {
}
@Test
- public void require_that_nonunique_featureset_are_split_into_separate_conjunctions() {
+ void require_that_nonunique_featureset_are_split_into_separate_conjunctions() {
assertConvertedPredicateEquals(
and(conj(not(featureSet(1)), featureSet(2)), featureSet(1)),
and(not(featureSet(1)), featureSet(1), featureSet(2))
@@ -93,7 +93,7 @@ public class FeatureConjunctionTransformerTest {
}
@Test
- public void require_that_featuresets_in_conjunction_may_only_have_a_single_value() {
+ void require_that_featuresets_in_conjunction_may_only_have_a_single_value() {
assertConvertedPredicateEquals(
and(featureSet(1, "a", "b"), featureSet(4, "c", "d"), conj(featureSet(2), featureSet(3))),
and(featureSet(1, "a", "b"), featureSet(2), featureSet(3), featureSet(4, "c", "d"))
diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/serialization/PredicateQuerySerializerTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/serialization/PredicateQuerySerializerTest.java
index 0bd9a1cda01..f6a44caf130 100644
--- a/predicate-search/src/test/java/com/yahoo/search/predicate/serialization/PredicateQuerySerializerTest.java
+++ b/predicate-search/src/test/java/com/yahoo/search/predicate/serialization/PredicateQuerySerializerTest.java
@@ -3,11 +3,11 @@ package com.yahoo.search.predicate.serialization;
import com.yahoo.search.predicate.PredicateQuery;
import com.yahoo.search.predicate.SubqueryBitmap;
-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 bjorncs
@@ -15,15 +15,15 @@ import static org.junit.Assert.assertEquals;
public class PredicateQuerySerializerTest {
@Test
- public void require_that_query_is_correctly_parsed_and_written_back_to_json() throws Exception {
+ void require_that_query_is_correctly_parsed_and_written_back_to_json() throws Exception {
String json =
"{\"features\":[" +
- "{\"k\":\"k1\",\"v\":\"value1\",\"s\":\"0x1\"}," +
- "{\"k\":\"k2\",\"v\":\"value2\",\"s\":\"0x3\"}" +
- "],\"rangeFeatures\":[" +
- "{\"k\":\"range1\",\"v\":123456789123,\"s\":\"0xffff\"}," +
- "{\"k\":\"range2\",\"v\":0}" +
- "]}";
+ "{\"k\":\"k1\",\"v\":\"value1\",\"s\":\"0x1\"}," +
+ "{\"k\":\"k2\",\"v\":\"value2\",\"s\":\"0x3\"}" +
+ "],\"rangeFeatures\":[" +
+ "{\"k\":\"range1\",\"v\":123456789123,\"s\":\"0xffff\"}," +
+ "{\"k\":\"range2\",\"v\":0}" +
+ "]}";
PredicateQuerySerializer serializer = new PredicateQuerySerializer();
PredicateQuery query = serializer.fromJSON(json);
List<PredicateQuery.Feature> features = query.getFeatures();
diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/serialization/SerializationHelperTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/serialization/SerializationHelperTest.java
index fa8fbb1e77d..1a2df01b248 100644
--- a/predicate-search/src/test/java/com/yahoo/search/predicate/serialization/SerializationHelperTest.java
+++ b/predicate-search/src/test/java/com/yahoo/search/predicate/serialization/SerializationHelperTest.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.search.predicate.serialization;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
@@ -13,28 +13,28 @@ import static com.yahoo.search.predicate.serialization.SerializationTestHelper.*
public class SerializationHelperTest {
@Test
- public void require_that_long_serialization_works() throws IOException {
+ void require_that_long_serialization_works() throws IOException {
long[] longs = {1, 2, 3, 4};
assertSerializationDeserializationMatches(
longs, SerializationHelper::writeLongArray, SerializationHelper::readLongArray);
}
@Test
- public void require_that_int_serialization_works() throws IOException {
+ void require_that_int_serialization_works() throws IOException {
int[] ints = {1, 2, 3, 4};
assertSerializationDeserializationMatches(
ints, SerializationHelper::writeIntArray, SerializationHelper::readIntArray);
}
@Test
- public void require_that_byte_serialization_works() throws IOException {
+ void require_that_byte_serialization_works() throws IOException {
byte[] bytes = {1, 2, 3, 4};
assertSerializationDeserializationMatches(
bytes, SerializationHelper::writeByteArray, SerializationHelper::readByteArray);
}
@Test
- public void require_that_short_serialization_works() throws IOException {
+ void require_that_short_serialization_works() throws IOException {
short[] shorts = {1, 2, 3, 4};
assertSerializationDeserializationMatches(
shorts, SerializationHelper::writeShortArray, SerializationHelper::readShortArray);
diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/serialization/SerializationTestHelper.java b/predicate-search/src/test/java/com/yahoo/search/predicate/serialization/SerializationTestHelper.java
index 42cfa861f34..608ed0b1a52 100644
--- a/predicate-search/src/test/java/com/yahoo/search/predicate/serialization/SerializationTestHelper.java
+++ b/predicate-search/src/test/java/com/yahoo/search/predicate/serialization/SerializationTestHelper.java
@@ -7,7 +7,7 @@ import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
-import static org.junit.Assert.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
/**
* @author bjorncs
diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/utils/PostingListSearchTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/utils/PostingListSearchTest.java
index a1bb225fb9f..2b452ad6536 100644
--- a/predicate-search/src/test/java/com/yahoo/search/predicate/utils/PostingListSearchTest.java
+++ b/predicate-search/src/test/java/com/yahoo/search/predicate/utils/PostingListSearchTest.java
@@ -1,9 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.predicate.utils;
-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 bjorncs
@@ -11,7 +11,7 @@ import static org.junit.Assert.assertEquals;
public class PostingListSearchTest {
@Test
- public void require_that_search_find_index_of_first_element_higher() {
+ void require_that_search_find_index_of_first_element_higher() {
int[] values = {2, 8, 4000, 4001, 4100, 10000, 10000000};
int length = values.length;
assertEquals(0, PostingListSearch.interpolationSearch(values, 0, length, 1));
@@ -24,7 +24,7 @@ public class PostingListSearchTest {
}
@Test
- public void require_that_search_is_correct_for_one_size_arrays() {
+ void require_that_search_is_correct_for_one_size_arrays() {
int[] values = {100};
assertEquals(0, PostingListSearch.interpolationSearch(values, 0, 1, 0));
assertEquals(0, PostingListSearch.interpolationSearch(values, 0, 1, 99));
@@ -34,7 +34,7 @@ public class PostingListSearchTest {
}
@Test
- public void require_that_search_is_correct_for_sub_arrays() {
+ void require_that_search_is_correct_for_sub_arrays() {
int[] values = {0, 2, 8, 4000, 4001, 4100};
assertEquals(1, PostingListSearch.interpolationSearch(values, 1, 2, 1));
assertEquals(2, PostingListSearch.interpolationSearch(values, 1, 2, 2));
@@ -45,7 +45,7 @@ public class PostingListSearchTest {
}
@Test
- public void require_that_search_is_correct_for_large_arrays() {
+ void require_that_search_is_correct_for_large_arrays() {
int length = 10000;
int[] values = new int[length];
for (int i = 0; i < length; i++) {
diff --git a/predicate-search/src/test/java/com/yahoo/search/predicate/utils/PrimitiveArraySorterTest.java b/predicate-search/src/test/java/com/yahoo/search/predicate/utils/PrimitiveArraySorterTest.java
index eb641b6fa05..692fb9ab696 100644
--- a/predicate-search/src/test/java/com/yahoo/search/predicate/utils/PrimitiveArraySorterTest.java
+++ b/predicate-search/src/test/java/com/yahoo/search/predicate/utils/PrimitiveArraySorterTest.java
@@ -1,33 +1,30 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.predicate.utils;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Random;
-import static org.junit.Assert.assertArrayEquals;
-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.*;
public class PrimitiveArraySorterTest {
@Test
- public void sorting_empty_array_should_not_throw_exception() {
+ void sorting_empty_array_should_not_throw_exception() {
short[] array = {};
PrimitiveArraySorter.sort(array, Short::compare);
}
@Test
- public void test_sorting_single_item_array() {
+ void test_sorting_single_item_array() {
short[] array = {42};
PrimitiveArraySorter.sort(array, Short::compare);
assertEquals(42, array[0]);
}
@Test
- public void test_sorting_custom_comparator() {
+ void test_sorting_custom_comparator() {
short[] array = {4, 2, 5};
PrimitiveArraySorter.sort(array, (a, b) -> Short.compare(b, a)); // Sort using inverse ordering.
short[] expected = {5, 4, 2};
@@ -35,7 +32,7 @@ public class PrimitiveArraySorterTest {
}
@Test
- public void test_complicated_array() {
+ void test_complicated_array() {
short[] array = {20381, -28785, -19398, 17307, -12612, 11459, -30164, -16597, -4267, 30838, 8918, 9014, -26444,
-1232, -14620, 12636, -12389, -4931, 32108, 19854, -12681, 14933, 319, 27348, -4907, 19196, 14209,
-32694, 2579, 9771, -1157, -13717, 28506, -8016, 21423, 23697, 23755, 29650, 25644, -14660, -18952,
@@ -48,7 +45,7 @@ public class PrimitiveArraySorterTest {
}
@Test
- public void sorting_random_arrays_should_produce_identical_result_as_java_sort() {
+ void sorting_random_arrays_should_produce_identical_result_as_java_sort() {
Random r = new Random(4234);
for (int i = 0; i < 10000; i++) {
short[] original = makeRandomArray(r);
@@ -57,12 +54,12 @@ public class PrimitiveArraySorterTest {
PrimitiveArraySorter.sort(customSorted, Short::compare);
Arrays.sort(javaSorted);
String errorMsg = String.format("%s != %s (before sorting: %s)", Arrays.toString(customSorted), Arrays.toString(javaSorted), Arrays.toString(original));
- assertArrayEquals(errorMsg, customSorted, javaSorted);
+ assertArrayEquals(customSorted, javaSorted, errorMsg);
}
}
@Test
- public void test_merging_simple_array() {
+ void test_merging_simple_array() {
short[] array = {-20, -12, 2, -22, -11, 33, 44};
short[] expected = {-22, -20, -12, -11, 2, 33, 44};
short[] result = new short[array.length];
@@ -71,7 +68,7 @@ public class PrimitiveArraySorterTest {
}
@Test
- public void test_merging_of_random_generated_arrays() {
+ void test_merging_of_random_generated_arrays() {
Random r = new Random(4234);
for (int i = 0; i < 10000; i++) {
short[] array = makeRandomArray(r);
@@ -89,7 +86,7 @@ public class PrimitiveArraySorterTest {
}
@Test
- public void test_sortandmerge_returns_false_when_sort_is_in_place() {
+ void test_sortandmerge_returns_false_when_sort_is_in_place() {
short[] array = {3, 2, 1, 0, 4, 5, 6};
short[] mergeArray = new short[array.length];
assertFalse(PrimitiveArraySorter.sortAndMerge(array, mergeArray, 4, 7, Short::compare));
diff --git a/security-tools/pom.xml b/security-tools/pom.xml
index 7f248c185a2..2af6e09a84d 100644
--- a/security-tools/pom.xml
+++ b/security-tools/pom.xml
@@ -27,13 +27,18 @@
<!-- test scope -->
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
+ <groupId>org.assertj</groupId>
+ <artifactId>assertj-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
- <groupId>org.assertj</groupId>
- <artifactId>assertj-core</artifactId>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
diff --git a/security-tools/src/test/java/com/yahoo/vespa/security/tool/securityenv/MainTest.java b/security-tools/src/test/java/com/yahoo/vespa/security/tool/securityenv/MainTest.java
index 4b8f4bf0156..b1d263a1a82 100644
--- a/security-tools/src/test/java/com/yahoo/vespa/security/tool/securityenv/MainTest.java
+++ b/security-tools/src/test/java/com/yahoo/vespa/security/tool/securityenv/MainTest.java
@@ -4,11 +4,11 @@ package com.yahoo.vespa.security.tool.securityenv;
import com.yahoo.security.tls.MixedMode;
import com.yahoo.security.tls.TransportSecurityOptions;
import com.yahoo.security.tls.TransportSecurityUtils;
-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.ByteArrayOutputStream;
+import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
@@ -30,18 +30,18 @@ public class MainTest {
private final PrintStream stdOut = new PrintStream(stdOutBytes);
private final PrintStream stdError = new PrintStream(stdErrBytes);
- @Rule
- public TemporaryFolder tmpFolder = new TemporaryFolder();
+ @TempDir
+ public File tmpFolder;
@Test
- public void prints_help_page_on_help_option() throws IOException {
+ void prints_help_page_on_help_option() throws IOException {
int exitCode = runMain(List.of("--help"), Map.of());
assertThat(exitCode).isEqualTo(0);
assertThat(stdOut()).isEqualTo(readTestResource("expected-help-output.txt"));
}
@Test
- public void unsets_all_variables_when_no_security_config() throws IOException {
+ void unsets_all_variables_when_no_security_config() throws IOException {
int exitCode = runMain(List.of(), Map.of());
assertThat(exitCode).isEqualTo(0);
assertThat(stdErr()).isEmpty();
@@ -49,7 +49,7 @@ public class MainTest {
}
@Test
- public void prints_security_variables_with_specified_shell() throws IOException {
+ void prints_security_variables_with_specified_shell() throws IOException {
Path configFile = generateConfigFile();
Map<String, String> env = Map.of(TransportSecurityUtils.CONFIG_FILE_ENVIRONMENT_VARIABLE, configFile.toString());
int exitCode = runMain(List.of(), env);
@@ -58,7 +58,7 @@ public class MainTest {
}
@Test
- public void prints_security_variables_with_auto_detected_shell() throws IOException {
+ void prints_security_variables_with_auto_detected_shell() throws IOException {
Path configFile = generateConfigFile();
Map<String, String> env = Map.of(
TransportSecurityUtils.CONFIG_FILE_ENVIRONMENT_VARIABLE, configFile.toString(),
@@ -71,14 +71,14 @@ public class MainTest {
@Test
- public void prints_error_message_on_unknown_shell_name() {
+ void prints_error_message_on_unknown_shell_name() {
int exitCode = runMain(List.of("--shell", "invalid-shell-name"), Map.of());
assertThat(exitCode).isEqualTo(1);
assertThat(stdErr()).isEqualTo("Invalid command line arguments: Unknown shell: invalid-shell-name\n");
}
@Test
- public void prints_error_message_on_unknown_command_line_parameter() {
+ void prints_error_message_on_unknown_command_line_parameter() {
int exitCode = runMain(List.of("--unknown-parameter"), Map.of());
assertThat(exitCode).isEqualTo(1);
assertThat(stdErr()).isEqualTo("Failed to parse command line arguments: Unrecognized option: --unknown-parameter\n");
@@ -108,7 +108,7 @@ public class MainTest {
.withCaCertificates(Paths.get("/path/to/cacerts"))
.withHostnameValidationDisabled(true)
.build();
- Path configFile = tmpFolder.newFile().toPath();
+ Path configFile = File.createTempFile("junit", null, tmpFolder).toPath();
options.toJsonFile(configFile);
return configFile;
}
diff --git a/security-utils/pom.xml b/security-utils/pom.xml
index 0a2e1251d6a..71920327fbb 100644
--- a/security-utils/pom.xml
+++ b/security-utils/pom.xml
@@ -35,17 +35,6 @@
<!-- test scope -->
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>com.yahoo.vespa</groupId>
- <artifactId>testutil</artifactId>
- <version>${project.version}</version>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<scope>test</scope>
@@ -60,11 +49,6 @@
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
- <dependency>
- <groupId>org.junit.vintage</groupId>
- <artifactId>junit-vintage-engine</artifactId>
- <scope>test</scope>
- </dependency>
</dependencies>
<build>
<plugins>
diff --git a/security-utils/src/test/java/com/yahoo/security/AutoReloadingX509KeyManagerTest.java b/security-utils/src/test/java/com/yahoo/security/AutoReloadingX509KeyManagerTest.java
index 5bde63598c0..c335acc12be 100644
--- a/security-utils/src/test/java/com/yahoo/security/AutoReloadingX509KeyManagerTest.java
+++ b/security-utils/src/test/java/com/yahoo/security/AutoReloadingX509KeyManagerTest.java
@@ -7,13 +7,14 @@ import com.yahoo.security.KeyUtils;
import com.yahoo.security.SignatureAlgorithm;
import com.yahoo.security.X509CertificateBuilder;
import com.yahoo.security.X509CertificateUtils;
-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.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import javax.security.auth.x500.X500Principal;
+
+import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Files;
@@ -36,16 +37,16 @@ import static org.mockito.Mockito.verify;
public class AutoReloadingX509KeyManagerTest {
private static final X500Principal SUBJECT = new X500Principal("CN=dummy");
- @Rule
- public TemporaryFolder tempDirectory = new TemporaryFolder();
+ @TempDir
+ public File tempDirectory;
@Test
- public void crypto_material_is_reloaded_when_scheduler_task_is_executed() throws IOException {
+ void crypto_material_is_reloaded_when_scheduler_task_is_executed() throws IOException {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.EC);
- Path privateKeyFile = tempDirectory.newFile().toPath();
+ Path privateKeyFile = File.createTempFile("junit", null, tempDirectory).toPath();
Files.write(privateKeyFile, KeyUtils.toPem(keyPair.getPrivate()).getBytes());
- Path certificateFile = tempDirectory.newFile().toPath();
+ Path certificateFile = File.createTempFile("junit", null, tempDirectory).toPath();
BigInteger serialNumberInitialCertificate = BigInteger.ONE;
X509Certificate initialCertificate = generateCertificate(keyPair, serialNumberInitialCertificate);
Files.write(certificateFile, X509CertificateUtils.toPem(initialCertificate).getBytes());
diff --git a/security-utils/src/test/java/com/yahoo/security/KeyStoreBuilderTest.java b/security-utils/src/test/java/com/yahoo/security/KeyStoreBuilderTest.java
index 0d3924063f3..d9ca9731065 100644
--- a/security-utils/src/test/java/com/yahoo/security/KeyStoreBuilderTest.java
+++ b/security-utils/src/test/java/com/yahoo/security/KeyStoreBuilderTest.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.security;
-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.nio.file.Path;
import java.security.KeyPair;
import java.security.cert.X509Certificate;
@@ -20,11 +20,11 @@ public class KeyStoreBuilderTest {
private static final char[] PASSWORD = new char[0];
- @Rule
- public TemporaryFolder tempDirectory = new TemporaryFolder();
+ @TempDir
+ public File tempDirectory;
@Test
- public void can_create_jks_keystore_from_privatekey_and_certificate() throws Exception {
+ void can_create_jks_keystore_from_privatekey_and_certificate() throws Exception {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256);
X509Certificate certificate = createCertificate(keyPair);
KeyStoreBuilder.withType(KeyStoreType.JKS)
@@ -33,8 +33,8 @@ public class KeyStoreBuilderTest {
}
@Test
- public void can_build_jks_keystore_from_file() throws Exception {
- Path keystoreFile = tempDirectory.newFile().toPath();
+ void can_build_jks_keystore_from_file() throws Exception {
+ Path keystoreFile = File.createTempFile("junit", null, tempDirectory).toPath();
createKeystoreFile(keystoreFile, KeyStoreType.JKS, PASSWORD);
KeyStoreBuilder.withType(KeyStoreType.JKS)
@@ -43,8 +43,8 @@ public class KeyStoreBuilderTest {
}
@Test
- public void can_build_pcks12_keystore_from_file() throws Exception {
- Path keystoreFile = tempDirectory.newFile().toPath();
+ void can_build_pcks12_keystore_from_file() throws Exception {
+ Path keystoreFile = File.createTempFile("junit", null, tempDirectory).toPath();
createKeystoreFile(keystoreFile, KeyStoreType.PKCS12, PASSWORD);
KeyStoreBuilder.withType(KeyStoreType.PKCS12)
diff --git a/security-utils/src/test/java/com/yahoo/security/KeyUtilsTest.java b/security-utils/src/test/java/com/yahoo/security/KeyUtilsTest.java
index f6f48d8b1b8..afaa25ce606 100644
--- a/security-utils/src/test/java/com/yahoo/security/KeyUtilsTest.java
+++ b/security-utils/src/test/java/com/yahoo/security/KeyUtilsTest.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.security;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author bjorncs
@@ -17,41 +17,41 @@ import static org.junit.Assert.assertTrue;
public class KeyUtilsTest {
@Test
- public void can_extract_public_key_from_rsa_private() {
+ void can_extract_public_key_from_rsa_private() {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.RSA);
PublicKey publicKey = KeyUtils.extractPublicKey(keyPair.getPrivate());
assertNotNull(publicKey);
}
@Test
- public void can_extract_public_key_from_ecdsa_private() {
+ void can_extract_public_key_from_ecdsa_private() {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.EC);
PublicKey publicKey = KeyUtils.extractPublicKey(keyPair.getPrivate());
assertNotNull(publicKey);
}
@Test
- public void can_serialize_and_deserialize_rsa_privatekey_using_pkcs1_pem_format() {
+ void can_serialize_and_deserialize_rsa_privatekey_using_pkcs1_pem_format() {
testPrivateKeySerialization(KeyAlgorithm.RSA, KeyFormat.PKCS1, "RSA PRIVATE KEY");
}
@Test
- public void can_serialize_and_deserialize_rsa_privatekey_using_pkcs8_pem_format() {
+ void can_serialize_and_deserialize_rsa_privatekey_using_pkcs8_pem_format() {
testPrivateKeySerialization(KeyAlgorithm.RSA, KeyFormat.PKCS8, "PRIVATE KEY");
}
@Test
- public void can_serialize_and_deserialize_ec_privatekey_using_pkcs1_pem_format() {
+ void can_serialize_and_deserialize_ec_privatekey_using_pkcs1_pem_format() {
testPrivateKeySerialization(KeyAlgorithm.EC, KeyFormat.PKCS1, "EC PRIVATE KEY");
}
@Test
- public void can_serialize_and_deserialize_ec_privatekey_using_pkcs8_pem_format() {
+ void can_serialize_and_deserialize_ec_privatekey_using_pkcs8_pem_format() {
testPrivateKeySerialization(KeyAlgorithm.EC, KeyFormat.PKCS8, "PRIVATE KEY");
}
@Test
- public void can_serialize_and_deserialize_rsa_publickey_using_pem_format() {
+ void can_serialize_and_deserialize_rsa_publickey_using_pem_format() {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.RSA);
String pem = KeyUtils.toPem(keyPair.getPublic());
assertTrue(pem.contains("BEGIN PUBLIC KEY"));
@@ -62,7 +62,7 @@ public class KeyUtilsTest {
}
@Test
- public void can_serialize_and_deserialize_ec_publickey_using_pem_format() {
+ void can_serialize_and_deserialize_ec_publickey_using_pem_format() {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.EC);
String pem = KeyUtils.toPem(keyPair.getPublic());
assertTrue(pem.contains("BEGIN PUBLIC KEY"));
diff --git a/security-utils/src/test/java/com/yahoo/security/MutableX509KeyManagerTest.java b/security-utils/src/test/java/com/yahoo/security/MutableX509KeyManagerTest.java
index 871b0937f18..ddceb762d2a 100644
--- a/security-utils/src/test/java/com/yahoo/security/MutableX509KeyManagerTest.java
+++ b/security-utils/src/test/java/com/yahoo/security/MutableX509KeyManagerTest.java
@@ -8,7 +8,7 @@ import com.yahoo.security.KeyUtils;
import com.yahoo.security.MutableX509KeyManager;
import com.yahoo.security.SignatureAlgorithm;
import com.yahoo.security.X509CertificateBuilder;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.security.auth.x500.X500Principal;
import java.math.BigInteger;
@@ -29,7 +29,7 @@ public class MutableX509KeyManagerTest {
private static final X500Principal SUBJECT = new X500Principal("CN=dummy");
@Test
- public void key_manager_can_be_updated_with_new_certificate() {
+ void key_manager_can_be_updated_with_new_certificate() {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.EC);
BigInteger serialNumberInitialCertificate = BigInteger.ONE;
diff --git a/security-utils/src/test/java/com/yahoo/security/MutableX509TrustManagerTest.java b/security-utils/src/test/java/com/yahoo/security/MutableX509TrustManagerTest.java
index 489aa7eb4da..ea9f9a4a68a 100644
--- a/security-utils/src/test/java/com/yahoo/security/MutableX509TrustManagerTest.java
+++ b/security-utils/src/test/java/com/yahoo/security/MutableX509TrustManagerTest.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.security;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.security.auth.x500.X500Principal;
import java.math.BigInteger;
@@ -19,7 +19,7 @@ import static org.assertj.core.api.Assertions.assertThat;
public class MutableX509TrustManagerTest {
@Test
- public void key_manager_can_be_updated_with_new_certificate() {
+ void key_manager_can_be_updated_with_new_certificate() {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.EC);
X509Certificate initialCertificate = generateCertificate(new X500Principal("CN=issuer1"), keyPair);
diff --git a/security-utils/src/test/java/com/yahoo/security/Pkcs10CsrBuilderTest.java b/security-utils/src/test/java/com/yahoo/security/Pkcs10CsrBuilderTest.java
index 5ad49bbc599..ca8fb280ec7 100644
--- a/security-utils/src/test/java/com/yahoo/security/Pkcs10CsrBuilderTest.java
+++ b/security-utils/src/test/java/com/yahoo/security/Pkcs10CsrBuilderTest.java
@@ -1,12 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.security;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.security.auth.x500.X500Principal;
import java.security.KeyPair;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bjorncs
@@ -14,7 +14,7 @@ import static org.junit.Assert.assertEquals;
public class Pkcs10CsrBuilderTest {
@Test
- public void can_build_csr_with_sans() {
+ void can_build_csr_with_sans() {
X500Principal subject = new X500Principal("CN=subject");
KeyPair keypair = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256);
Pkcs10Csr csr = Pkcs10CsrBuilder.fromKeypair(subject, keypair, SignatureAlgorithm.SHA512_WITH_ECDSA)
diff --git a/security-utils/src/test/java/com/yahoo/security/Pkcs10CsrTest.java b/security-utils/src/test/java/com/yahoo/security/Pkcs10CsrTest.java
index d03c52027bf..3fe36dc6a7c 100644
--- a/security-utils/src/test/java/com/yahoo/security/Pkcs10CsrTest.java
+++ b/security-utils/src/test/java/com/yahoo/security/Pkcs10CsrTest.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.security;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.security.auth.x500.X500Principal;
import java.security.KeyPair;
@@ -9,8 +9,8 @@ import java.util.Arrays;
import java.util.List;
import static com.yahoo.security.SubjectAlternativeName.Type.DNS;
-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 bjorncs
@@ -18,7 +18,7 @@ import static org.junit.Assert.assertTrue;
public class Pkcs10CsrTest {
@Test
- public void can_read_subject_alternative_names() {
+ void can_read_subject_alternative_names() {
X500Principal subject = new X500Principal("CN=subject");
KeyPair keypair = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256);
SubjectAlternativeName san1 = new SubjectAlternativeName(DNS, "san1.com");
@@ -31,7 +31,7 @@ public class Pkcs10CsrTest {
}
@Test
- public void can_read_basic_constraints() {
+ void can_read_basic_constraints() {
X500Principal subject = new X500Principal("CN=subject");
KeyPair keypair = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256);
Pkcs10Csr csr = Pkcs10CsrBuilder.fromKeypair(subject, keypair, SignatureAlgorithm.SHA512_WITH_ECDSA)
@@ -42,7 +42,7 @@ public class Pkcs10CsrTest {
}
@Test
- public void can_read_extensions() {
+ void can_read_extensions() {
X500Principal subject = new X500Principal("CN=subject");
KeyPair keypair = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256);
Pkcs10Csr csr = Pkcs10CsrBuilder.fromKeypair(subject, keypair, SignatureAlgorithm.SHA512_WITH_ECDSA)
diff --git a/security-utils/src/test/java/com/yahoo/security/Pkcs10CsrUtilsTest.java b/security-utils/src/test/java/com/yahoo/security/Pkcs10CsrUtilsTest.java
index 32b8dfc5bcd..48ff3e9a6fd 100644
--- a/security-utils/src/test/java/com/yahoo/security/Pkcs10CsrUtilsTest.java
+++ b/security-utils/src/test/java/com/yahoo/security/Pkcs10CsrUtilsTest.java
@@ -1,13 +1,13 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.security;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.security.auth.x500.X500Principal;
import java.security.KeyPair;
-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 bjorncs
@@ -15,7 +15,7 @@ import static org.junit.Assert.assertTrue;
public class Pkcs10CsrUtilsTest {
@Test
- public void can_deserialize_serialized_pem_csr() {
+ void can_deserialize_serialized_pem_csr() {
X500Principal subject = new X500Principal("CN=subject");
KeyPair keypair = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256);
Pkcs10Csr csr = Pkcs10CsrBuilder.fromKeypair(subject, keypair, SignatureAlgorithm.SHA512_WITH_ECDSA).build();
diff --git a/security-utils/src/test/java/com/yahoo/security/SslContextBuilderTest.java b/security-utils/src/test/java/com/yahoo/security/SslContextBuilderTest.java
index 3c40cb89e6c..b08494bb8da 100644
--- a/security-utils/src/test/java/com/yahoo/security/SslContextBuilderTest.java
+++ b/security-utils/src/test/java/com/yahoo/security/SslContextBuilderTest.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.security;
-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.nio.file.Path;
import java.security.KeyPair;
import java.security.cert.X509Certificate;
@@ -20,25 +20,25 @@ public class SslContextBuilderTest {
private static final char[] PASSWORD = new char[0];
- @Rule
- public TemporaryFolder tempDirectory = new TemporaryFolder();
+ @TempDir
+ public File tempDirectory;
@Test
- public void can_build_sslcontext_with_truststore_only() throws Exception {
+ void can_build_sslcontext_with_truststore_only() throws Exception {
new SslContextBuilder()
.withTrustStore(createKeystore(KeyStoreType.JKS, PASSWORD))
.build();
}
@Test
- public void can_build_sslcontext_with_keystore_only() throws Exception {
+ void can_build_sslcontext_with_keystore_only() throws Exception {
new SslContextBuilder()
.withKeyStore(createKeystore(KeyStoreType.JKS, PASSWORD), PASSWORD)
.build();
}
@Test
- public void can_build_sslcontext_with_truststore_and_keystore() throws Exception {
+ void can_build_sslcontext_with_truststore_and_keystore() throws Exception {
new SslContextBuilder()
.withKeyStore(createKeystore(KeyStoreType.JKS, PASSWORD), PASSWORD)
.withTrustStore(createKeystore(KeyStoreType.JKS, PASSWORD))
@@ -46,7 +46,7 @@ public class SslContextBuilderTest {
}
@Test
- public void can_build_sslcontext_with_keystore_from_private_key_and_certificate() throws Exception {
+ void can_build_sslcontext_with_keystore_from_private_key_and_certificate() throws Exception {
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256);
X509Certificate certificate = createCertificate(keyPair);
new SslContextBuilder()
@@ -55,8 +55,8 @@ public class SslContextBuilderTest {
}
@Test
- public void can_build_sslcontext_with_jks_keystore_from_file() throws Exception {
- Path keystoreFile = tempDirectory.newFile().toPath();
+ void can_build_sslcontext_with_jks_keystore_from_file() throws Exception {
+ Path keystoreFile = File.createTempFile("junit", null, tempDirectory).toPath();
createKeystoreFile(keystoreFile, KeyStoreType.JKS, PASSWORD);
new SslContextBuilder()
@@ -65,8 +65,8 @@ public class SslContextBuilderTest {
}
@Test
- public void can_build_sslcontext_with_pcks12_keystore_from_file() throws Exception {
- Path keystoreFile = tempDirectory.newFile().toPath();
+ void can_build_sslcontext_with_pcks12_keystore_from_file() throws Exception {
+ Path keystoreFile = File.createTempFile("junit", null, tempDirectory).toPath();
createKeystoreFile(keystoreFile, KeyStoreType.PKCS12, PASSWORD);
new SslContextBuilder()
diff --git a/security-utils/src/test/java/com/yahoo/security/X509CertificateBuilderTest.java b/security-utils/src/test/java/com/yahoo/security/X509CertificateBuilderTest.java
index eb6fe4286d8..1a9c4999146 100644
--- a/security-utils/src/test/java/com/yahoo/security/X509CertificateBuilderTest.java
+++ b/security-utils/src/test/java/com/yahoo/security/X509CertificateBuilderTest.java
@@ -1,9 +1,8 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.security;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
import javax.security.auth.x500.X500Principal;
import java.math.BigInteger;
@@ -14,35 +13,35 @@ import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Collection;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bjorncs
*/
-@RunWith(Parameterized.class)
public class X509CertificateBuilderTest {
- @Parameterized.Parameters(name = "{0}")
public static Collection<Object[]> data() {
- return Arrays.asList(new Object[][] {
+ return Arrays.asList(new Object[][]{
{KeyAlgorithm.RSA, 2048, SignatureAlgorithm.SHA512_WITH_RSA},
{KeyAlgorithm.EC, 256, SignatureAlgorithm.SHA512_WITH_ECDSA}});
}
- private final KeyAlgorithm keyAlgorithm;
- private final int keySize;
- private final SignatureAlgorithm signatureAlgorithm;
+ private KeyAlgorithm keyAlgorithm;
+ private int keySize;
+ private SignatureAlgorithm signatureAlgorithm;
- public X509CertificateBuilderTest(KeyAlgorithm keyAlgorithm,
- int keySize,
- SignatureAlgorithm signatureAlgorithm) {
+ public void initX509CertificateBuilderTest(KeyAlgorithm keyAlgorithm,
+ int keySize,
+ SignatureAlgorithm signatureAlgorithm) {
this.keyAlgorithm = keyAlgorithm;
this.keySize = keySize;
this.signatureAlgorithm = signatureAlgorithm;
}
- @Test
- public void can_build_self_signed_certificate() {
+ @MethodSource("data")
+ @ParameterizedTest(name = "{0}")
+ void can_build_self_signed_certificate(KeyAlgorithm keyAlgorithm, int keySize, SignatureAlgorithm signatureAlgorithm) {
+ initX509CertificateBuilderTest(keyAlgorithm, keySize, signatureAlgorithm);
KeyPair keyPair = KeyUtils.generateKeypair(keyAlgorithm, keySize);
X500Principal subject = new X500Principal("CN=myservice");
X509Certificate cert =
@@ -53,13 +52,15 @@ public class X509CertificateBuilderTest {
Instant.now().plus(1, ChronoUnit.DAYS),
signatureAlgorithm,
BigInteger.valueOf(1))
- .setBasicConstraints(true, true)
- .build();
+ .setBasicConstraints(true, true)
+ .build();
assertEquals(subject, cert.getSubjectX500Principal());
}
- @Test
- public void can_build_certificate_from_csr() {
+ @MethodSource("data")
+ @ParameterizedTest(name = "{0}")
+ void can_build_certificate_from_csr(KeyAlgorithm keyAlgorithm, int keySize, SignatureAlgorithm signatureAlgorithm) {
+ initX509CertificateBuilderTest(keyAlgorithm, keySize, signatureAlgorithm);
X500Principal subject = new X500Principal("CN=subject");
X500Principal issuer = new X500Principal("CN=issuer");
KeyPair csrKeypair = KeyUtils.generateKeypair(keyAlgorithm, keySize);
diff --git a/security-utils/src/test/java/com/yahoo/security/X509CertificateUtilsTest.java b/security-utils/src/test/java/com/yahoo/security/X509CertificateUtilsTest.java
index 6bb87554de3..c0560627661 100644
--- a/security-utils/src/test/java/com/yahoo/security/X509CertificateUtilsTest.java
+++ b/security-utils/src/test/java/com/yahoo/security/X509CertificateUtilsTest.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.security;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.security.auth.x500.X500Principal;
import java.math.BigInteger;
@@ -14,16 +14,16 @@ import java.util.List;
import static com.yahoo.security.SubjectAlternativeName.Type.DNS;
-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.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author bjorncs
*/
public class X509CertificateUtilsTest {
@Test
- public void can_deserialize_serialized_pem_certificate() {
+ void can_deserialize_serialized_pem_certificate() {
KeyPair keypair = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256);
X500Principal subject = new X500Principal("CN=myservice");
X509Certificate cert = TestUtils.createCertificate(keypair, subject);
@@ -36,7 +36,7 @@ public class X509CertificateUtilsTest {
}
@Test
- public void can_deserialize_serialized_pem_certificate_list() {
+ void can_deserialize_serialized_pem_certificate_list() {
KeyPair keypair = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256);
X500Principal subject1 = new X500Principal("CN=myservice1");
X509Certificate cert1 = TestUtils.createCertificate(keypair, subject1);
@@ -51,7 +51,7 @@ public class X509CertificateUtilsTest {
}
@Test
- public void can_list_subject_alternative_names() {
+ void can_list_subject_alternative_names() {
KeyPair keypair = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256);
X500Principal subject = new X500Principal("CN=myservice");
SubjectAlternativeName san = new SubjectAlternativeName(DNS, "dns-san");
@@ -72,7 +72,7 @@ public class X509CertificateUtilsTest {
}
@Test
- public void verifies_matching_cert_and_key() {
+ void verifies_matching_cert_and_key() {
KeyPair ecKeypairA = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256);
KeyPair ecKeypairB = KeyUtils.generateKeypair(KeyAlgorithm.EC, 256);
KeyPair rsaKeypairA = KeyUtils.generateKeypair(KeyAlgorithm.RSA, 1024);
diff --git a/security-utils/src/test/java/com/yahoo/security/tls/AuthorizedPeersTest.java b/security-utils/src/test/java/com/yahoo/security/tls/AuthorizedPeersTest.java
index e4c530dbb0b..2a7149ba2e3 100644
--- a/security-utils/src/test/java/com/yahoo/security/tls/AuthorizedPeersTest.java
+++ b/security-utils/src/test/java/com/yahoo/security/tls/AuthorizedPeersTest.java
@@ -1,26 +1,27 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.security.tls;
-import com.yahoo.security.tls.PeerPolicy;
-import com.yahoo.security.tls.RequiredPeerCredential;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.HashSet;
import static com.yahoo.security.tls.RequiredPeerCredential.Field.CN;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
+import static org.junit.jupiter.api.Assertions.assertThrows;
/**
* @author bjorncs
*/
public class AuthorizedPeersTest {
- @Test(expected = IllegalArgumentException.class)
- public void throws_exception_on_peer_policies_with_duplicate_names() {
- PeerPolicy peerPolicy1 = new PeerPolicy("duplicate-name", singletonList(RequiredPeerCredential.of(CN, "mycfgserver")));
- PeerPolicy peerPolicy2 = new PeerPolicy("duplicate-name", singletonList(RequiredPeerCredential.of(CN, "myclient")));
- new AuthorizedPeers(new HashSet<>(asList(peerPolicy1, peerPolicy2)));
+ @Test
+ void throws_exception_on_peer_policies_with_duplicate_names() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ PeerPolicy peerPolicy1 = new PeerPolicy("duplicate-name", singletonList(RequiredPeerCredential.of(CN, "mycfgserver")));
+ PeerPolicy peerPolicy2 = new PeerPolicy("duplicate-name", singletonList(RequiredPeerCredential.of(CN, "myclient")));
+ new AuthorizedPeers(new HashSet<>(asList(peerPolicy1, peerPolicy2)));
+ });
}
}
diff --git a/security-utils/src/test/java/com/yahoo/security/tls/ConfigFileBasedTlsContextTest.java b/security-utils/src/test/java/com/yahoo/security/tls/ConfigFileBasedTlsContextTest.java
index 0af6d231701..7b70c842a4c 100644
--- a/security-utils/src/test/java/com/yahoo/security/tls/ConfigFileBasedTlsContextTest.java
+++ b/security-utils/src/test/java/com/yahoo/security/tls/ConfigFileBasedTlsContextTest.java
@@ -4,12 +4,13 @@ package com.yahoo.security.tls;
import com.yahoo.security.KeyUtils;
import com.yahoo.security.X509CertificateBuilder;
import com.yahoo.security.X509CertificateUtils;
-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 javax.net.ssl.SSLEngine;
import javax.security.auth.x500.X500Principal;
+
+import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Files;
@@ -28,23 +29,23 @@ import static org.assertj.core.api.Assertions.assertThat;
*/
public class ConfigFileBasedTlsContextTest {
- @Rule
- public TemporaryFolder tempDirectory = new TemporaryFolder();
+ @TempDir
+ public File tempDirectory;
@Test
- public void can_create_sslcontext_from_credentials() throws IOException, InterruptedException {
+ void can_create_sslcontext_from_credentials() throws IOException, InterruptedException {
KeyPair keyPair = KeyUtils.generateKeypair(EC);
- Path privateKeyFile = tempDirectory.newFile().toPath();
+ Path privateKeyFile = File.createTempFile("junit", null, tempDirectory).toPath();
Files.write(privateKeyFile, KeyUtils.toPem(keyPair.getPrivate()).getBytes());
X509Certificate certificate = X509CertificateBuilder
.fromKeypair(keyPair, new X500Principal("CN=dummy"), EPOCH, EPOCH.plus(1, DAYS), SHA256_WITH_ECDSA, BigInteger.ONE)
.build();
- Path certificateChainFile = tempDirectory.newFile().toPath();
+ Path certificateChainFile = File.createTempFile("junit", null, tempDirectory).toPath();
String certificatePem = X509CertificateUtils.toPem(certificate);
Files.write(certificateChainFile, certificatePem.getBytes());
- Path caCertificatesFile = tempDirectory.newFile().toPath();
+ Path caCertificatesFile = File.createTempFile("junit", null, tempDirectory).toPath();
Files.write(caCertificatesFile, certificatePem.getBytes());
TransportSecurityOptions options = new TransportSecurityOptions.Builder()
@@ -52,7 +53,7 @@ public class ConfigFileBasedTlsContextTest {
.withCaCertificates(caCertificatesFile)
.build();
- Path optionsFile = tempDirectory.newFile().toPath();
+ Path optionsFile = File.createTempFile("junit", null, tempDirectory).toPath();
options.toJsonFile(optionsFile);
try (TlsContext tlsContext = new ConfigFileBasedTlsContext(optionsFile, AuthorizationMode.ENFORCE)) {
diff --git a/security-utils/src/test/java/com/yahoo/security/tls/DefaultTlsContextTest.java b/security-utils/src/test/java/com/yahoo/security/tls/DefaultTlsContextTest.java
index b6c40a0c2e1..bf4a618d9ce 100644
--- a/security-utils/src/test/java/com/yahoo/security/tls/DefaultTlsContextTest.java
+++ b/security-utils/src/test/java/com/yahoo/security/tls/DefaultTlsContextTest.java
@@ -3,7 +3,7 @@ package com.yahoo.security.tls;
import com.yahoo.security.KeyUtils;
import com.yahoo.security.X509CertificateBuilder;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.net.ssl.SSLEngine;
import javax.security.auth.x500.X500Principal;
@@ -26,7 +26,7 @@ import static org.assertj.core.api.Assertions.assertThat;
public class DefaultTlsContextTest {
@Test
- public void can_create_sslcontext_from_credentials() {
+ void can_create_sslcontext_from_credentials() {
KeyPair keyPair = KeyUtils.generateKeypair(EC);
X509Certificate certificate = X509CertificateBuilder
diff --git a/security-utils/src/test/java/com/yahoo/security/tls/HostGlobPatternTest.java b/security-utils/src/test/java/com/yahoo/security/tls/HostGlobPatternTest.java
index a5628a637f8..b63b1dfeaa0 100644
--- a/security-utils/src/test/java/com/yahoo/security/tls/HostGlobPatternTest.java
+++ b/security-utils/src/test/java/com/yahoo/security/tls/HostGlobPatternTest.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.security.tls;
-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;
/**
@@ -13,28 +13,28 @@ import static org.junit.Assert.assertTrue;
public class HostGlobPatternTest {
@Test
- public void glob_without_wildcards_matches_entire_string() {
+ void glob_without_wildcards_matches_entire_string() {
assertTrue(globMatches("foo", "foo"));
assertFalse(globMatches("foo", "fooo"));
assertFalse(globMatches("foo", "ffoo"));
}
@Test
- public void wildcard_glob_can_match_prefix() {
+ void wildcard_glob_can_match_prefix() {
assertTrue(globMatches("foo*", "foo"));
assertTrue(globMatches("foo*", "foobar"));
assertFalse(globMatches("foo*", "ffoo"));
}
@Test
- public void wildcard_glob_can_match_suffix() {
+ void wildcard_glob_can_match_suffix() {
assertTrue(globMatches("*foo", "foo"));
assertTrue(globMatches("*foo", "ffoo"));
assertFalse(globMatches("*foo", "fooo"));
}
@Test
- public void wildcard_glob_can_match_substring() {
+ void wildcard_glob_can_match_substring() {
assertTrue(globMatches("f*o", "fo"));
assertTrue(globMatches("f*o", "foo"));
assertTrue(globMatches("f*o", "ffoo"));
@@ -42,7 +42,7 @@ public class HostGlobPatternTest {
}
@Test
- public void wildcard_glob_does_not_cross_multiple_dot_delimiter_boundaries() {
+ void wildcard_glob_does_not_cross_multiple_dot_delimiter_boundaries() {
assertTrue(globMatches("*.bar.baz", "foo.bar.baz"));
assertTrue(globMatches("*.bar.baz", ".bar.baz"));
assertFalse(globMatches("*.bar.baz", "zoid.foo.bar.baz"));
@@ -51,7 +51,7 @@ public class HostGlobPatternTest {
}
@Test
- public void single_char_glob_matches_non_dot_characters() {
+ void single_char_glob_matches_non_dot_characters() {
assertTrue(globMatches("f?o", "foo"));
assertFalse(globMatches("f?o", "fooo"));
assertFalse(globMatches("f?o", "ffoo"));
@@ -59,7 +59,7 @@ public class HostGlobPatternTest {
}
@Test
- public void other_regex_meta_characters_are_matched_as_literal_characters() {
+ void other_regex_meta_characters_are_matched_as_literal_characters() {
assertTrue(globMatches("<([{\\^-=$!|]})+.>", "<([{\\^-=$!|]})+.>"));
}
diff --git a/security-utils/src/test/java/com/yahoo/security/tls/PeerAuthorizerTest.java b/security-utils/src/test/java/com/yahoo/security/tls/PeerAuthorizerTest.java
index 94b0dc4f83e..bea5c6108f2 100644
--- a/security-utils/src/test/java/com/yahoo/security/tls/PeerAuthorizerTest.java
+++ b/security-utils/src/test/java/com/yahoo/security/tls/PeerAuthorizerTest.java
@@ -6,7 +6,7 @@ import com.yahoo.security.KeyUtils;
import com.yahoo.security.SubjectAlternativeName.Type;
import com.yahoo.security.X509CertificateBuilder;
import com.yahoo.security.tls.RequiredPeerCredential.Field;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.security.auth.x500.X500Principal;
import java.math.BigInteger;
@@ -28,8 +28,8 @@ import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static java.util.stream.Collectors.toSet;
import static org.assertj.core.api.Assertions.assertThat;
-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
@@ -40,7 +40,7 @@ public class PeerAuthorizerTest {
private static final String POLICY_1 = "policy-1", POLICY_2 = "policy-2";
@Test
- public void certificate_must_match_both_san_and_cn_pattern() {
+ void certificate_must_match_both_san_and_cn_pattern() {
RequiredPeerCredential cnRequirement = createRequiredCredential(CN, "*.matching.cn");
RequiredPeerCredential sanRequirement = createRequiredCredential(SAN_DNS, "*.matching.san");
PeerAuthorizer authorizer = createPeerAuthorizer(createPolicy(POLICY_1, cnRequirement, sanRequirement));
@@ -50,12 +50,12 @@ public class PeerAuthorizerTest {
assertThat(result.matchedPolicies()).containsOnly(POLICY_1);
assertUnauthorized(authorizer.authorizePeer(createCertificate("foo.invalid.cn", singletonList("foo.matching.san"), emptyList())));
- assertUnauthorized(authorizer.authorizePeer(createCertificate("foo.invalid.cn", asList("foo.matching.san", "foo.invalid.san"),emptyList())));
+ assertUnauthorized(authorizer.authorizePeer(createCertificate("foo.invalid.cn", asList("foo.matching.san", "foo.invalid.san"), emptyList())));
assertUnauthorized(authorizer.authorizePeer(createCertificate("foo.matching.cn", singletonList("foo.invalid.san"), emptyList())));
}
@Test
- public void can_match_multiple_policies() {
+ void can_match_multiple_policies() {
RequiredPeerCredential cnRequirement = createRequiredCredential(CN, "*.matching.cn");
RequiredPeerCredential sanRequirement = createRequiredCredential(SAN_DNS, "*.matching.san");
@@ -70,7 +70,7 @@ public class PeerAuthorizerTest {
}
@Test
- public void can_match_subset_of_policies() {
+ void can_match_subset_of_policies() {
PeerAuthorizer peerAuthorizer = createPeerAuthorizer(
createPolicy(POLICY_1, createRequiredCredential(CN, "*.matching.cn")),
createPolicy(POLICY_2, createRequiredCredential(SAN_DNS, "*.matching.san")));
@@ -81,7 +81,7 @@ public class PeerAuthorizerTest {
}
@Test
- public void must_match_all_cn_and_san_patterns() {
+ void must_match_all_cn_and_san_patterns() {
RequiredPeerCredential cnSuffixRequirement = createRequiredCredential(CN, "*.*.matching.suffix.cn");
RequiredPeerCredential cnPrefixRequirement = createRequiredCredential(CN, "matching.prefix.*.*.*");
RequiredPeerCredential sanPrefixRequirement = createRequiredCredential(SAN_DNS, "*.*.matching.suffix.san");
@@ -95,7 +95,7 @@ public class PeerAuthorizerTest {
}
@Test
- public void can_match_policy_with_san_uri_pattern() {
+ void can_match_policy_with_san_uri_pattern() {
RequiredPeerCredential cnRequirement = createRequiredCredential(CN, "*.matching.cn");
RequiredPeerCredential sanUriRequirement = createRequiredCredential(SAN_URI, "myscheme://my/*/uri");
PeerAuthorizer authorizer = createPeerAuthorizer(createPolicy(POLICY_1, cnRequirement, sanUriRequirement));
@@ -108,7 +108,7 @@ public class PeerAuthorizerTest {
}
@Test
- public void auth_context_contains_union_of_granted_capabilities_from_policies() {
+ void auth_context_contains_union_of_granted_capabilities_from_policies() {
RequiredPeerCredential cnRequirement = createRequiredCredential(CN, "*.matching.cn");
RequiredPeerCredential sanRequirement = createRequiredCredential(SAN_DNS, "*.matching.san");
diff --git a/security-utils/src/test/java/com/yahoo/security/tls/TransportSecurityOptionsJsonSerializerTest.java b/security-utils/src/test/java/com/yahoo/security/tls/TransportSecurityOptionsJsonSerializerTest.java
index 476ab689903..895428037ed 100644
--- a/security-utils/src/test/java/com/yahoo/security/tls/TransportSecurityOptionsJsonSerializerTest.java
+++ b/security-utils/src/test/java/com/yahoo/security/tls/TransportSecurityOptionsJsonSerializerTest.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.security.tls;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@@ -21,20 +22,21 @@ import java.util.Optional;
import static com.yahoo.security.tls.RequiredPeerCredential.Field.CN;
import static com.yahoo.security.tls.RequiredPeerCredential.Field.SAN_DNS;
import static com.yahoo.security.tls.RequiredPeerCredential.Field.SAN_URI;
-import static com.yahoo.test.json.JsonTestHelper.assertJsonEquals;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bjorncs
*/
public class TransportSecurityOptionsJsonSerializerTest {
- @Rule public TemporaryFolder tempDirectory = new TemporaryFolder();
+ @TempDir
+ public File tempDirectory;
private static final Path TEST_CONFIG_FILE = Paths.get("src/test/resources/transport-security-options.json");
+ private static final ObjectMapper mapper = new ObjectMapper();
@Test
- public void can_serialize_and_deserialize_transport_security_options() throws IOException {
+ void can_serialize_and_deserialize_transport_security_options() throws IOException {
TransportSecurityOptions options = new TransportSecurityOptions.Builder()
.withCaCertificates(Paths.get("/path/to/ca-certs.pem"))
.withCertificates(Paths.get("/path/to/cert.pem"), Paths.get("/path/to/key.pem"))
@@ -61,15 +63,15 @@ public class TransportSecurityOptionsJsonSerializerTest {
}
@Test
- public void can_serialize_options_without_authorized_peers() throws IOException {
+ void can_serialize_options_without_authorized_peers() throws IOException {
TransportSecurityOptions options = new TransportSecurityOptions.Builder()
.withCertificates(Paths.get("certs.pem"), Paths.get("myhost.key"))
.withCaCertificates(Paths.get("my_cas.pem"))
- .withAcceptedCiphers(Arrays.asList("TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384" , "TLS_AES_256_GCM_SHA384"))
+ .withAcceptedCiphers(Arrays.asList("TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", "TLS_AES_256_GCM_SHA384"))
.withAcceptedProtocols(Collections.singletonList("TLSv1.2"))
.withHostnameValidationDisabled(true)
.build();
- File outputFile = tempDirectory.newFile();
+ File outputFile = File.createTempFile("junit", null, tempDirectory);
try (OutputStream out = Files.newOutputStream(outputFile.toPath())) {
new TransportSecurityOptionsJsonSerializer().serialize(out, options);
}
@@ -79,13 +81,13 @@ public class TransportSecurityOptionsJsonSerializerTest {
}
@Test
- public void disable_hostname_validation_is_not_serialized_if_false() throws IOException {
+ void disable_hostname_validation_is_not_serialized_if_false() throws IOException {
TransportSecurityOptions options = new TransportSecurityOptions.Builder()
.withCertificates(Paths.get("certs.pem"), Paths.get("myhost.key"))
.withCaCertificates(Paths.get("my_cas.pem"))
.withHostnameValidationDisabled(false)
.build();
- File outputFile = tempDirectory.newFile();
+ File outputFile = File.createTempFile("junit", null, tempDirectory);
try (OutputStream out = Files.newOutputStream(outputFile.toPath())) {
new TransportSecurityOptionsJsonSerializer().serialize(out, options);
}
@@ -96,4 +98,8 @@ public class TransportSecurityOptionsJsonSerializerTest {
assertJsonEquals(expectedOutput, actualOutput);
}
+ private static void assertJsonEquals(String inputJson, String expectedJson) throws JsonProcessingException {
+ assertEquals(mapper.readTree(expectedJson), mapper.readTree(inputJson));
+ }
+
}
diff --git a/security-utils/src/test/java/com/yahoo/security/tls/TransportSecurityOptionsTest.java b/security-utils/src/test/java/com/yahoo/security/tls/TransportSecurityOptionsTest.java
index 7d67c492170..089a4ca6de5 100644
--- a/security-utils/src/test/java/com/yahoo/security/tls/TransportSecurityOptionsTest.java
+++ b/security-utils/src/test/java/com/yahoo/security/tls/TransportSecurityOptionsTest.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.security.tls;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@@ -11,7 +11,7 @@ import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bjorncs
@@ -28,13 +28,13 @@ public class TransportSecurityOptionsTest {
.build();
@Test
- public void can_read_options_from_json_file() {
+ void can_read_options_from_json_file() {
TransportSecurityOptions actualOptions = TransportSecurityOptions.fromJsonFile(TEST_CONFIG_FILE);
assertEquals(OPTIONS, actualOptions);
}
@Test
- public void can_read_options_from_json() throws IOException {
+ void can_read_options_from_json() throws IOException {
String tlsJson = new String(Files.readAllBytes(TEST_CONFIG_FILE), StandardCharsets.UTF_8);
TransportSecurityOptions actualOptions = TransportSecurityOptions.fromJson(tlsJson);
assertEquals(OPTIONS, actualOptions);
diff --git a/standalone-container/pom.xml b/standalone-container/pom.xml
index 3776743cbd8..590872282ca 100644
--- a/standalone-container/pom.xml
+++ b/standalone-container/pom.xml
@@ -99,7 +99,14 @@
config-bundle-jar-with-dependencies.jar,
config-model-api-jar-with-dependencies.jar,
config-model-jar-with-dependencies.jar,
+
container-disc-jar-with-dependencies.jar,
+
+ <!-- START bundles that can be moved to config-model when all standalone containers are set up via the model -->
+ container-spifly.jar, <!-- Aries SPIFly repackaged -->
+ javax.servlet-api-3.1.0.jar, <!-- Needed by vespa-athenz. TODO Vespa 9: remove the need for servlet-api -->
+ <!-- END bundles that can be moved to config-model -->
+
<!-- START config-model dependencies -->
container-search-and-docproc-jar-with-dependencies.jar,
linguistics-components-jar-with-dependencies.jar,
diff --git a/testutil/src/main/java/com/yahoo/test/JunitCompat.java b/testutil/src/main/java/com/yahoo/test/JunitCompat.java
new file mode 100644
index 00000000000..b771ffa0e22
--- /dev/null
+++ b/testutil/src/main/java/com/yahoo/test/JunitCompat.java
@@ -0,0 +1,65 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package com.yahoo.test;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.util.List;
+
+/**
+ * Hack to support both junit4 and junit5
+ *
+ * @author bjorncs
+ */
+public class JunitCompat {
+ private JunitCompat() {}
+
+ public static <T> void assertEquals(T l, T r) {
+ List<Class<?>> argTypes = List.of(Object.class, Object.class);
+ List<Object> argValues = List.of(l, r);
+ invokeAssert("assertEquals", argTypes, argValues, argTypes, argValues);
+ }
+
+ public static void assertEquals(String msg, long l, long r) {
+ List<Class<?>> junit4ArgTypes = List.of(String.class, long.class, long.class);
+ List<Object> junit4ArgValues = List.of(msg, l, r);
+ List<Class<?>> junit5ArgTypes = List.of(long.class, long.class, String.class);
+ List<Object> junit5ArgValues = List.of(l, r, msg);
+ invokeAssert("assertEquals", junit4ArgTypes, junit4ArgValues, junit5ArgTypes, junit5ArgValues);
+ }
+
+ public static void assertTrue(String msg, boolean b) {
+ List<Class<?>> junit4ArgTypes = List.of(String.class, boolean.class);
+ List<Object> junit4ArgValues = List.of(msg, b);
+ List<Class<?>> junit5ArgTypes = List.of(boolean.class, String.class);
+ List<Object> junit5ArgValues = List.of(b, msg);
+ invokeAssert("assertTrue", junit4ArgTypes, junit4ArgValues, junit5ArgTypes, junit5ArgValues);
+ }
+
+ private static void invokeAssert(String method, List<Class<?>> junit4ArgTypes, List<Object> junit4ArgValues,
+ List<Class<?>> junit5ArgTypes, List<Object> junit5ArgValues) {
+ try {
+ invokeAssert("org.junit.jupiter.api.Assertions", method, junit5ArgTypes, junit5ArgValues);
+ } catch (ReflectiveOperationException e) {
+ try {
+ invokeAssert("org.junit.Assert", method, junit4ArgTypes, junit4ArgValues);
+ } catch (ReflectiveOperationException ex) {
+ throw new RuntimeException("Unable to find junit4 or junit5 on test classpath", ex);
+ }
+ }
+ }
+
+ private static void invokeAssert(String clazz, String method, List<Class<?>> argTypes, List<Object> argValues)
+ throws ReflectiveOperationException {
+ try {
+ Class<?> c = Class.forName(clazz);
+ Method m = c.getMethod(method, argTypes.toArray(new Class<?>[0]));
+ m.invoke(null, argValues.toArray());
+ } catch (InvocationTargetException e) {
+ if (e.getCause() instanceof AssertionError ae) {
+ throw ae;
+ } else {
+ throw new RuntimeException(e.getCause());
+ }
+ }
+ }
+}
diff --git a/testutil/src/main/java/com/yahoo/test/PartialOrderTester.java b/testutil/src/main/java/com/yahoo/test/PartialOrderTester.java
index ed92171542c..0917355c50c 100644
--- a/testutil/src/main/java/com/yahoo/test/PartialOrderTester.java
+++ b/testutil/src/main/java/com/yahoo/test/PartialOrderTester.java
@@ -1,9 +1,6 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
/**
* PartialOrderTester implements a partial order test for OrderTester
*
@@ -14,14 +11,14 @@ import static org.junit.Assert.assertTrue;
public class PartialOrderTester<T extends Comparable<T>> extends OrderTester<T> {
protected void lessTest(T a, T b) throws AssertionError {
- assertTrue(a + " must be less than or equal to " + b, a.compareTo(b) <= 0);
+ JunitCompat.assertTrue(a + " must be less than or equal to " + b, a.compareTo(b) <= 0);
}
protected void greaterTest(T a, T b) throws AssertionError {
- assertTrue(a + " must be greater than or equal to " + b, a.compareTo(b) >= 0);
+ JunitCompat.assertTrue(a + " must be greater than or equal to " + b, a.compareTo(b) >= 0);
}
protected void equalTest(T a, T b) throws AssertionError {
- assertEquals(a + " must be compared equal to " + b, 0, a.compareTo(b));
+ JunitCompat.assertEquals(a + " must be compared equal to " + b, 0, a.compareTo(b));
}
}
diff --git a/testutil/src/main/java/com/yahoo/test/TotalOrderTester.java b/testutil/src/main/java/com/yahoo/test/TotalOrderTester.java
index e95bc056ba8..2b5f100ca50 100644
--- a/testutil/src/main/java/com/yahoo/test/TotalOrderTester.java
+++ b/testutil/src/main/java/com/yahoo/test/TotalOrderTester.java
@@ -1,9 +1,6 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.test;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
/**
* TotalOrderTester implements a total order test for OrderTester
*
@@ -22,14 +19,14 @@ import static org.junit.Assert.assertTrue;
public class TotalOrderTester<T extends Comparable<? super T>> extends OrderTester<T> {
protected void lessTest(T a, T b) throws AssertionError {
- assertTrue(a + " must be less than " + b, a.compareTo(b) <= -1);
+ JunitCompat.assertTrue(a + " must be less than " + b, a.compareTo(b) <= -1);
}
protected void greaterTest(T a, T b) throws AssertionError {
- assertTrue(a + " must be greater than " + b, a.compareTo(b) >= 1);
+ JunitCompat.assertTrue(a + " must be greater than " + b, a.compareTo(b) >= 1);
}
protected void equalTest(T a, T b) throws AssertionError {
- assertEquals(a + " must be compared equal to " + b, 0, a.compareTo(b));
+ JunitCompat.assertEquals(a + " must be compared equal to " + b, 0, a.compareTo(b));
}
}
diff --git a/testutil/src/main/java/com/yahoo/test/json/JsonTestHelper.java b/testutil/src/main/java/com/yahoo/test/json/JsonTestHelper.java
index 05532d2a504..f7112ee9379 100644
--- a/testutil/src/main/java/com/yahoo/test/json/JsonTestHelper.java
+++ b/testutil/src/main/java/com/yahoo/test/json/JsonTestHelper.java
@@ -5,11 +5,10 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Joiner;
+import com.yahoo.test.JunitCompat;
import java.io.UncheckedIOException;
-import static org.junit.Assert.assertEquals;
-
/**
* @author Vegard Sjonfjell
*/
@@ -31,7 +30,7 @@ public class JsonTestHelper {
try {
JsonNode expected = mapper.readTree(expectedJson);
JsonNode actual = mapper.readTree(inputJson);
- assertEquals(expected, actual);
+ JunitCompat.assertEquals(expected, actual);
} catch (JsonProcessingException e) {
throw new RuntimeException("Exception when comparing json strings." , e);
}
@@ -57,4 +56,5 @@ public class JsonTestHelper {
throw new UncheckedIOException(e);
}
}
+
}
diff --git a/vespa-athenz/pom.xml b/vespa-athenz/pom.xml
index 580910799c1..55482dd1fed 100644
--- a/vespa-athenz/pom.xml
+++ b/vespa-athenz/pom.xml
@@ -22,6 +22,12 @@
<artifactId>container-dev</artifactId>
<version>${project.version}</version>
<scope>provided</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<groupId>com.yahoo.vespa</groupId>
@@ -38,11 +44,6 @@
<!-- test -->
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
@@ -52,6 +53,30 @@
<artifactId>testutil</artifactId>
<version>${project.version}</version>
<scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-core</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-library</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
+ <scope>test</scope>
</dependency>
<!-- compile -->
@@ -90,6 +115,10 @@
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</exclusion>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
</exclusions>
</dependency>
<dependency> <!-- needed by auth-core -->
diff --git a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/api/AthenzDomainTest.java b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/api/AthenzDomainTest.java
index ff3d8d20797..d7d5428c11b 100644
--- a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/api/AthenzDomainTest.java
+++ b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/api/AthenzDomainTest.java
@@ -1,14 +1,11 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.athenz.api;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.function.Supplier;
-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 bjorncs
@@ -16,28 +13,28 @@ import static org.junit.Assert.fail;
public class AthenzDomainTest {
@Test
- public void domain_can_be_constructed_from_valid_string() {
+ void domain_can_be_constructed_from_valid_string() {
new AthenzDomain("home.john.my-app");
}
@Test
- public void invalid_domain_throws_exception() {
+ void invalid_domain_throws_exception() {
assertInvalid(() -> new AthenzDomain("endswithdot."));
assertInvalid(() -> new AthenzDomain(".startswithdot"));
}
@Test
- public void parent_domain_is_without_name_suffix() {
+ void parent_domain_is_without_name_suffix() {
assertEquals(new AthenzDomain("home.john"), new AthenzDomain("home.john.myapp").getParent());
}
@Test
- public void domain_name_suffix_is_the_suffix_after_last_dot() {
+ void domain_name_suffix_is_the_suffix_after_last_dot() {
assertEquals("myapp", new AthenzDomain("home.john.myapp").getNameSuffix());
}
@Test
- public void domain_without_dot_is_toplevel() {
+ void domain_without_dot_is_toplevel() {
assertTrue(new AthenzDomain("toplevel").isTopLevelDomain());
assertFalse(new AthenzDomain("not.toplevel").isTopLevelDomain());
}
diff --git a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/api/AthenzResourceNameTest.java b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/api/AthenzResourceNameTest.java
index ececa45d5fb..a2de235906c 100644
--- a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/api/AthenzResourceNameTest.java
+++ b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/api/AthenzResourceNameTest.java
@@ -1,9 +1,9 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.athenz.api;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bjorncs
@@ -11,7 +11,7 @@ import static org.junit.Assert.*;
public class AthenzResourceNameTest {
@Test
- public void can_serialize_and_deserialize_to_string() {
+ void can_serialize_and_deserialize_to_string() {
AthenzResourceName resourceName = new AthenzResourceName(new AthenzDomain("domain"), "entity");
String resourceNameString = resourceName.toResourceNameString();
assertEquals("domain:entity", resourceNameString);
diff --git a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/api/NTokenGeneratorTest.java b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/api/NTokenGeneratorTest.java
index 7c4ee36926f..dd12bca03f3 100644
--- a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/api/NTokenGeneratorTest.java
+++ b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/api/NTokenGeneratorTest.java
@@ -3,13 +3,13 @@ package com.yahoo.vespa.athenz.api;
import com.yahoo.athenz.auth.util.CryptoException;
import com.yahoo.test.ManualClock;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.security.PrivateKey;
import java.time.Instant;
-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;
import static org.mockito.Mockito.mock;
/**
@@ -19,14 +19,14 @@ public class NTokenGeneratorTest {
private final PrivateKey key = mock(PrivateKey.class);
@Test
- public void ntoken() {
+ void ntoken() {
var signer = new Signer("signature");
NTokenGenerator generator = new NTokenGenerator(signer, new ManualClock(Instant.ofEpochSecond(12L)), () -> 3L);
AthenzIdentity identity = new AthenzService("domain", "service");
NToken token = generator.setIdentity(identity)
- .setKeyVersion("0")
- .sign(key);
+ .setKeyVersion("0")
+ .sign(key);
assertEquals("v=S1;d=domain;n=service;k=0;a=3;t=12;e=612", signer.message);
assertSame(key, signer.key);
diff --git a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/aws/AwsCredentialsTest.java b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/aws/AwsCredentialsTest.java
index 39ab8294409..48ff3ab651a 100644
--- a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/aws/AwsCredentialsTest.java
+++ b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/aws/AwsCredentialsTest.java
@@ -2,14 +2,14 @@
package com.yahoo.vespa.athenz.aws;
import com.yahoo.vespa.athenz.api.AwsTemporaryCredentials;
-import org.junit.Assert;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
-import static org.junit.Assert.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author tokle
@@ -17,19 +17,19 @@ import static org.junit.Assert.assertFalse;
public class AwsCredentialsTest {
@Test
- public void refreshes_correctly() {
+ void refreshes_correctly() {
Clock clock = Clock.systemUTC();
// Does not require refresh when expires in 10 minutes
assertFalse(AwsCredentials.shouldRefresh(getCredentials(clock.instant().plus(Duration.ofMinutes(10)))));
// Requires refresh when expires in 3 minutes
- Assert.assertTrue(AwsCredentials.shouldRefresh(getCredentials(clock.instant().plus(Duration.ofMinutes(3)))));
+ assertTrue(AwsCredentials.shouldRefresh(getCredentials(clock.instant().plus(Duration.ofMinutes(3)))));
// Requires refresh when expired
- Assert.assertTrue(AwsCredentials.shouldRefresh(getCredentials(clock.instant().minus(Duration.ofMinutes(1)))));
+ assertTrue(AwsCredentials.shouldRefresh(getCredentials(clock.instant().minus(Duration.ofMinutes(1)))));
// Refreshes when no credentials provided
- Assert.assertTrue(AwsCredentials.shouldRefresh(null));
+ assertTrue(AwsCredentials.shouldRefresh(null));
}
private AwsTemporaryCredentials getCredentials(Instant expiration) {
diff --git a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identity/SiaIdentityProviderTest.java b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identity/SiaIdentityProviderTest.java
index f502951572c..764b2d26006 100644
--- a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identity/SiaIdentityProviderTest.java
+++ b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identity/SiaIdentityProviderTest.java
@@ -7,9 +7,8 @@ import com.yahoo.security.SignatureAlgorithm;
import com.yahoo.security.X509CertificateBuilder;
import com.yahoo.security.X509CertificateUtils;
import com.yahoo.vespa.athenz.api.AthenzService;
-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 javax.security.auth.x500.X500Principal;
import java.io.File;
@@ -22,27 +21,27 @@ import java.time.Duration;
import java.time.Instant;
import static com.yahoo.yolean.Exceptions.uncheck;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
/**
* @author bjorncs
*/
public class SiaIdentityProviderTest {
- @Rule
- public TemporaryFolder tempDirectory = new TemporaryFolder();
+ @TempDir
+ public File tempDirectory;
@Test
- public void constructs_ssl_context_from_file() throws IOException {
- File keyFile = tempDirectory.newFile();
+ void constructs_ssl_context_from_file() throws IOException {
+ File keyFile = File.createTempFile("junit", null, tempDirectory);
KeyPair keypair = KeyUtils.generateKeypair(KeyAlgorithm.RSA);
createPrivateKeyFile(keyFile, keypair);
X509Certificate certificate = createCertificate(keypair);
- File certificateFile = tempDirectory.newFile();
+ File certificateFile = File.createTempFile("junit", null, tempDirectory);
createCertificateFile(certificate, certificateFile);
- File trustStoreFile = tempDirectory.newFile();
+ File trustStoreFile = File.createTempFile("junit", null, tempDirectory);
createTrustStoreFile(certificate, trustStoreFile);
SiaIdentityProvider provider =
@@ -56,16 +55,16 @@ public class SiaIdentityProviderTest {
}
@Test
- public void constructs_ssl_context_with_pem_trust_store() throws IOException {
- File keyFile = tempDirectory.newFile();
+ void constructs_ssl_context_with_pem_trust_store() throws IOException {
+ File keyFile = File.createTempFile("junit", null, tempDirectory);
KeyPair keypair = KeyUtils.generateKeypair(KeyAlgorithm.RSA);
createPrivateKeyFile(keyFile, keypair);
X509Certificate certificate = createCertificate(keypair);
- File certificateFile = tempDirectory.newFile();
+ File certificateFile = File.createTempFile("junit", null, tempDirectory);
createCertificateFile(certificate, certificateFile);
- File trustStoreFile = tempDirectory.newFile();
+ File trustStoreFile = File.createTempFile("junit", null, tempDirectory);
createPemTrustStoreFile(certificate, trustStoreFile);
SiaIdentityProvider provider =
diff --git a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/api/VespaUniqueInstanceIdTest.java b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/api/VespaUniqueInstanceIdTest.java
index 81f2d2a08cb..d22a791fa60 100644
--- a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/api/VespaUniqueInstanceIdTest.java
+++ b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/api/VespaUniqueInstanceIdTest.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.athenz.identityprovider.api;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import static com.yahoo.vespa.athenz.identityprovider.api.IdentityType.*;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bjorncs
@@ -12,7 +12,7 @@ import static org.junit.Assert.*;
public class VespaUniqueInstanceIdTest {
@Test
- public void can_serialize_to_and_deserialize_from_string() {
+ void can_serialize_to_and_deserialize_from_string() {
VespaUniqueInstanceId id =
new VespaUniqueInstanceId(1, "cluster-id", "instance", "application", "tenant", "region", "environment", TENANT);
String stringRepresentation = id.asDottedString();
diff --git a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/client/AthenzIdentityProviderImplTest.java b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/client/AthenzIdentityProviderImplTest.java
index 21f2c84710a..c9d2ea581bb 100644
--- a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/client/AthenzIdentityProviderImplTest.java
+++ b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/client/AthenzIdentityProviderImplTest.java
@@ -14,12 +14,13 @@ import com.yahoo.security.Pkcs10CsrBuilder;
import com.yahoo.security.SignatureAlgorithm;
import com.yahoo.security.X509CertificateBuilder;
import com.yahoo.test.ManualClock;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.TemporaryFolder;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
import javax.security.auth.x500.X500Principal;
+
+import java.io.File;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Path;
@@ -32,6 +33,7 @@ import java.util.Date;
import java.util.concurrent.ScheduledExecutorService;
import java.util.function.Supplier;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
@@ -44,8 +46,8 @@ import static org.mockito.Mockito.when;
*/
public class AthenzIdentityProviderImplTest {
- @Rule
- public TemporaryFolder tempDir = new TemporaryFolder();
+ @TempDir
+ public File tempDir;
public static final Duration certificateValidity = Duration.ofDays(30);
@@ -63,7 +65,7 @@ public class AthenzIdentityProviderImplTest {
private Path trustStoreFile;
private X509Certificate caCertificate;
- @Before
+ @BeforeEach
public void createTrustStoreFile() throws IOException {
caCertificate = X509CertificateBuilder
.fromKeypair(
@@ -74,7 +76,7 @@ public class AthenzIdentityProviderImplTest {
SignatureAlgorithm.SHA256_WITH_ECDSA,
BigInteger.ONE)
.build();
- trustStoreFile = tempDir.newFile().toPath();
+ trustStoreFile = File.createTempFile("junit", null, tempDir).toPath();
KeyStoreUtils.writeKeyStoreToFile(
KeyStoreBuilder.withType(KeyStoreType.JKS)
.withKeyEntry("default", caKeypair.getPrivate(), caCertificate)
@@ -82,17 +84,19 @@ public class AthenzIdentityProviderImplTest {
trustStoreFile);
}
- @Test(expected = AthenzIdentityProviderException.class)
- public void component_creation_fails_when_credentials_not_found() {
- AthenzCredentialsService credentialService = mock(AthenzCredentialsService.class);
- when(credentialService.registerInstance())
- .thenThrow(new RuntimeException("athenz unavailable"));
-
- new AthenzIdentityProviderImpl(IDENTITY_CONFIG, mock(Metric.class), trustStoreFile ,credentialService, mock(ScheduledExecutorService.class), new ManualClock(Instant.EPOCH));
+ @Test
+ void component_creation_fails_when_credentials_not_found() {
+ assertThrows(AthenzIdentityProviderException.class, () -> {
+ AthenzCredentialsService credentialService = mock(AthenzCredentialsService.class);
+ when(credentialService.registerInstance())
+ .thenThrow(new RuntimeException("athenz unavailable"));
+
+ new AthenzIdentityProviderImpl(IDENTITY_CONFIG, mock(Metric.class), trustStoreFile, credentialService, mock(ScheduledExecutorService.class), new ManualClock(Instant.EPOCH));
+ });
}
@Test
- public void metrics_updated_on_refresh() {
+ void metrics_updated_on_refresh() {
ManualClock clock = new ManualClock(Instant.EPOCH);
Metric metric = mock(Metric.class);
diff --git a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/client/IdentityDocumentSignerTest.java b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/client/IdentityDocumentSignerTest.java
index 5a3099aff76..5253fee0802 100644
--- a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/client/IdentityDocumentSignerTest.java
+++ b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/client/IdentityDocumentSignerTest.java
@@ -7,7 +7,7 @@ import com.yahoo.vespa.athenz.api.AthenzService;
import com.yahoo.vespa.athenz.identityprovider.api.IdentityType;
import com.yahoo.vespa.athenz.identityprovider.api.SignedIdentityDocument;
import com.yahoo.vespa.athenz.identityprovider.api.VespaUniqueInstanceId;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.security.KeyPair;
import java.time.Instant;
@@ -16,7 +16,7 @@ import java.util.HashSet;
import static com.yahoo.vespa.athenz.identityprovider.api.IdentityType.TENANT;
import static com.yahoo.vespa.athenz.identityprovider.api.SignedIdentityDocument.DEFAULT_DOCUMENT_VERSION;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* @author bjorncs
@@ -25,7 +25,7 @@ public class IdentityDocumentSignerTest {
public static final int KEY_VERSION = 0;
@Test
- public void generates_and_validates_signature() {
+ void generates_and_validates_signature() {
IdentityDocumentSigner signer = new IdentityDocumentSigner();
IdentityType identityType = TENANT;
VespaUniqueInstanceId id =
diff --git a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/client/InstanceCsrGeneratorTest.java b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/client/InstanceCsrGeneratorTest.java
index fc0b0a9c85f..3e4f8541aaa 100644
--- a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/client/InstanceCsrGeneratorTest.java
+++ b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/identityprovider/client/InstanceCsrGeneratorTest.java
@@ -6,13 +6,13 @@ import com.yahoo.security.KeyUtils;
import com.yahoo.vespa.athenz.api.AthenzService;
import com.yahoo.vespa.athenz.identityprovider.api.VespaUniqueInstanceId;
import com.yahoo.security.Pkcs10Csr;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.security.auth.x500.X500Principal;
import java.security.KeyPair;
import java.util.Collections;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author mortent
@@ -24,7 +24,7 @@ public class InstanceCsrGeneratorTest {
private static final String ATHENZ_SERVICE = "foo.bar";
@Test
- public void it_generates_csr_with_correct_subject() {
+ void it_generates_csr_with_correct_subject() {
CsrGenerator csrGenerator = new CsrGenerator(DNS_SUFFIX, PROVIDER_SERVICE);
AthenzService service = new AthenzService(ATHENZ_SERVICE);
diff --git a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/utils/AthenzIdentitiesTest.java b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/utils/AthenzIdentitiesTest.java
index 1b5dc3b7a71..262bac012b8 100644
--- a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/utils/AthenzIdentitiesTest.java
+++ b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/utils/AthenzIdentitiesTest.java
@@ -4,9 +4,9 @@ package com.yahoo.vespa.athenz.utils;
import com.yahoo.vespa.athenz.api.AthenzDomain;
import com.yahoo.vespa.athenz.api.AthenzIdentity;
import com.yahoo.vespa.athenz.api.AthenzService;
-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 bjorncs
@@ -14,7 +14,7 @@ import static org.junit.Assert.assertEquals;
public class AthenzIdentitiesTest {
@Test
- public void athenz_identity_is_parsed_from_dot_separated_string() {
+ void athenz_identity_is_parsed_from_dot_separated_string() {
AthenzIdentity expectedIdentity = new AthenzService(new AthenzDomain("my.subdomain"), "myservicename");
String fullName = expectedIdentity.getFullName();
AthenzIdentity actualIdentity = AthenzIdentities.from(fullName);
diff --git a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/utils/AthenzIdentityVerifierTest.java b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/utils/AthenzIdentityVerifierTest.java
index 5b699be4088..e59d9998170 100644
--- a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/utils/AthenzIdentityVerifierTest.java
+++ b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/utils/AthenzIdentityVerifierTest.java
@@ -7,7 +7,7 @@ import com.yahoo.security.X509CertificateBuilder;
import com.yahoo.vespa.athenz.api.AthenzIdentity;
import com.yahoo.vespa.athenz.api.AthenzService;
import com.yahoo.vespa.athenz.tls.AthenzIdentityVerifier;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
@@ -21,8 +21,8 @@ import java.time.Instant;
import static com.yahoo.security.SignatureAlgorithm.SHA256_WITH_ECDSA;
import static java.util.Collections.singleton;
-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;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -32,7 +32,7 @@ import static org.mockito.Mockito.when;
public class AthenzIdentityVerifierTest {
@Test
- public void verifies_certificate_with_athenz_service_as_common_name() throws Exception {
+ void verifies_certificate_with_athenz_service_as_common_name() throws Exception {
AthenzIdentity trustedIdentity = new AthenzService("mydomain", "alice");
AthenzIdentity unknownIdentity = new AthenzService("mydomain", "mallory");
KeyPair keyPair = KeyUtils.generateKeypair(KeyAlgorithm.EC);
diff --git a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/utils/SiaUtilsTest.java b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/utils/SiaUtilsTest.java
index 62c187b8c2c..7be55ec18a8 100644
--- a/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/utils/SiaUtilsTest.java
+++ b/vespa-athenz/src/test/java/com/yahoo/vespa/athenz/utils/SiaUtilsTest.java
@@ -3,29 +3,29 @@ package com.yahoo.vespa.athenz.utils;
import com.yahoo.vespa.athenz.api.AthenzIdentity;
import com.yahoo.vespa.athenz.api.AthenzService;
-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;
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;
/**
* @author bjorncs
*/
public class SiaUtilsTest {
- @Rule
- public TemporaryFolder tempDirectory = new TemporaryFolder();
+ @TempDir
+ public File tempDirectory;
@Test
- public void it_finds_all_identity_names_from_files_in_sia_keys_directory() throws IOException {
- Path siaRoot = tempDirectory.getRoot().toPath();
+ void it_finds_all_identity_names_from_files_in_sia_keys_directory() throws IOException {
+ Path siaRoot = tempDirectory.toPath();
assertTrue(SiaUtils.findSiaServices(siaRoot).isEmpty());
Files.createDirectory(siaRoot.resolve("keys"));
AthenzService fooService = new AthenzService("my.domain.foo");
diff --git a/vespaclient-java/pom.xml b/vespaclient-java/pom.xml
index d0e04d1e692..3e5e7ca8025 100644
--- a/vespaclient-java/pom.xml
+++ b/vespaclient-java/pom.xml
@@ -13,11 +13,6 @@
<version>8-SNAPSHOT</version>
<dependencies>
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
@@ -43,6 +38,12 @@
<groupId>com.yahoo.vespa</groupId>
<artifactId>container-dev</artifactId>
<version>${project.version}</version>
+ <exclusions>
+ <exclusion>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </exclusion>
+ </exclusions>
</dependency>
<dependency>
<!-- Added explicitly to get commons-collections, which is excluded from container-dev -->
@@ -69,6 +70,11 @@
<groupId>commons-cli</groupId>
<artifactId>commons-cli</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter</artifactId>
+ <scope>test</scope>
+ </dependency>
</dependencies>
<build>
<plugins>
diff --git a/vespaclient-java/src/test/java/com/yahoo/vespafeeder/BenchmarkProgressPrinterTest.java b/vespaclient-java/src/test/java/com/yahoo/vespafeeder/BenchmarkProgressPrinterTest.java
index 5edc9429c74..7268e892c7d 100644
--- a/vespaclient-java/src/test/java/com/yahoo/vespafeeder/BenchmarkProgressPrinterTest.java
+++ b/vespaclient-java/src/test/java/com/yahoo/vespafeeder/BenchmarkProgressPrinterTest.java
@@ -6,12 +6,12 @@ import com.yahoo.concurrent.Timer;
import com.yahoo.documentapi.messagebus.protocol.PutDocumentMessage;
import com.yahoo.documentapi.messagebus.protocol.UpdateDocumentMessage;
import com.yahoo.messagebus.EmptyReply;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
public class BenchmarkProgressPrinterTest {
@@ -22,7 +22,7 @@ public class BenchmarkProgressPrinterTest {
}
@Test
- public void testSimple() {
+ void testSimple() {
ByteArrayOutputStream output = new ByteArrayOutputStream();
DummyTimer timer = new DummyTimer();
timer.ms = 0;
@@ -72,7 +72,7 @@ public class BenchmarkProgressPrinterTest {
String val = output.toString().split("\n")[1];
String correctPattern = "62000, \\d+, \\d+, \\d+, \\d+, \\d+$";
- assertTrue("Value '" + val + "' does not match pattern '" + correctPattern + "'", val.matches(correctPattern));
+ assertTrue(val.matches(correctPattern), "Value '" + val + "' does not match pattern '" + correctPattern + "'");
}
}
diff --git a/vespaclient-java/src/test/java/com/yahoo/vespafeeder/ProgressPrinterTest.java b/vespaclient-java/src/test/java/com/yahoo/vespafeeder/ProgressPrinterTest.java
index f1e81fdd3c6..495367ff4c3 100644
--- a/vespaclient-java/src/test/java/com/yahoo/vespafeeder/ProgressPrinterTest.java
+++ b/vespaclient-java/src/test/java/com/yahoo/vespafeeder/ProgressPrinterTest.java
@@ -7,12 +7,12 @@ import com.yahoo.documentapi.messagebus.protocol.DocumentIgnoredReply;
import com.yahoo.documentapi.messagebus.protocol.PutDocumentMessage;
import com.yahoo.documentapi.messagebus.protocol.UpdateDocumentMessage;
import com.yahoo.messagebus.EmptyReply;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
public class ProgressPrinterTest {
@@ -23,7 +23,7 @@ public class ProgressPrinterTest {
}
@Test
- public void testSimple() {
+ void testSimple() {
ByteArrayOutputStream output = new ByteArrayOutputStream();
DummyTimer timer = new DummyTimer();
timer.ms = 0;
@@ -78,12 +78,12 @@ public class ProgressPrinterTest {
String correct =
"\rSuccessfully sent 2 messages so far" +
- "\rSuccessfully sent 3 messages so far" +
- "\n\n" +
- "Messages sent to vespa (route foobar) :\n" +
- "---------------------------------------\n" +
- "PutDocument:\tok: 2 msgs/sec: 0.03 failed: 0 ignored: 1 latency(min, max, avg): 0, 0, 0\n" +
- "UpdateDocument:\tok: 1 msgs/sec: 0.02 failed: 2 ignored: 0 latency(min, max, avg): 0, 0, 0\n";
+ "\rSuccessfully sent 3 messages so far" +
+ "\n\n" +
+ "Messages sent to vespa (route foobar) :\n" +
+ "---------------------------------------\n" +
+ "PutDocument:\tok: 2 msgs/sec: 0.03 failed: 0 ignored: 1 latency(min, max, avg): 0, 0, 0\n" +
+ "UpdateDocument:\tok: 1 msgs/sec: 0.02 failed: 2 ignored: 0 latency(min, max, avg): 0, 0, 0\n";
assertEquals(correct, val);
}
diff --git a/vespaclient-java/src/test/java/com/yahoo/vespafeeder/VespaFeederTestCase.java b/vespaclient-java/src/test/java/com/yahoo/vespafeeder/VespaFeederTestCase.java
index d6e55a26a39..a26672c5f26 100644
--- a/vespaclient-java/src/test/java/com/yahoo/vespafeeder/VespaFeederTestCase.java
+++ b/vespaclient-java/src/test/java/com/yahoo/vespafeeder/VespaFeederTestCase.java
@@ -22,23 +22,15 @@ import com.yahoo.feedhandler.VespaFeedHandler;
import com.yahoo.text.Utf8;
import com.yahoo.vespaclient.config.FeederConfig;
-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.assertTrue;
+import static org.junit.jupiter.api.Assertions.*;
public class VespaFeederTestCase {
- @SuppressWarnings("deprecation")
- @Rule
- public ExpectedException exception = ExpectedException.none();
-
@Test
- public void testParseArgs() throws Exception {
- String argsS="--abortondataerror false --abortonsenderror false --file foo.xml --maxpending 10" +
+ void testParseArgs() throws Exception {
+ String argsS = "--abortondataerror false --abortonsenderror false --file foo.xml --maxpending 10" +
" --maxfeedrate 29 --mode benchmark --noretry --route e6 --timeout 13 --trace 4" +
" --validate -v bar.xml --priority LOW_1";
@@ -63,23 +55,23 @@ public class VespaFeederTestCase {
}
@Test
- public void requireThatCreateIfNonExistentArgumentCanBeParsed() throws Exception {
- String argsS="--create-if-non-existent --file foo.xml";
+ void requireThatCreateIfNonExistentArgumentCanBeParsed() throws Exception {
+ String argsS = "--create-if-non-existent --file foo.xml";
Arguments arguments = new Arguments(argsS.split(" "), DummySessionFactory.createWithAutoReply());
assertTrue(arguments.getFeederConfig().createifnonexistent());
}
@Test
- public void requireThatnumThreadsBeParsed() throws Exception {
- String argsS="--numthreads 5";
+ void requireThatnumThreadsBeParsed() throws Exception {
+ String argsS = "--numthreads 5";
Arguments arguments = new Arguments(argsS.split(" "), DummySessionFactory.createWithAutoReply());
assertEquals(5, arguments.getNumThreads());
assertEquals(1, new Arguments("".split(" "), DummySessionFactory.createWithAutoReply()).getNumThreads());
}
@Test
- public void testHelp() throws Exception {
- String argsS="-h";
+ void testHelp() throws Exception {
+ String argsS = "-h";
try {
new Arguments(argsS.split(" "), null);
@@ -90,7 +82,7 @@ public class VespaFeederTestCase {
}
@Test
- public void requireCorrectInputTypeDetection() throws IOException {
+ void requireCorrectInputTypeDetection() throws IOException {
{
BufferedInputStream b = new BufferedInputStream(
new ByteArrayInputStream(Utf8.toBytes("[]")));
@@ -114,16 +106,16 @@ public class VespaFeederTestCase {
}
@Test
- public void testRenderErrors() {
+ void testRenderErrors() {
{
- String[] errors = { "foo" };
+ String[] errors = {"foo"};
assertRenderErrorOutput("Errors:\n" +
- "-------\n" +
- " foo\n", errors);
+ "-------\n" +
+ " foo\n", errors);
}
{
- String[] errors = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"};
+ String[] errors = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11"};
assertRenderErrorOutput("First 10 errors (of 11):\n" +
"------------------------\n" +
" 1\n 2\n 3\n 4\n 5\n 6\n 7\n 8\n 9\n 10\n", errors);
@@ -136,7 +128,7 @@ public class VespaFeederTestCase {
}
@Test
- public void testCreateProgressPrinter() throws Exception {
+ void testCreateProgressPrinter() throws Exception {
assert(getProgressPrinter("--mode benchmark") instanceof BenchmarkProgressPrinter);
assert(getProgressPrinter("") instanceof ProgressPrinter);
}
@@ -151,15 +143,16 @@ public class VespaFeederTestCase {
}
}
+ // TODO: Remove on Vespa 9
@Test
- @SuppressWarnings("removal") // TODO: Remove on Vespa 9
- public void feedFile() throws Exception {
+ @SuppressWarnings("removal")
+ void feedFile() throws Exception {
FeedFixture f = new FeedFixture();
Arguments arguments = new Arguments("--file src/test/files/myfeed.xml --priority LOW_1".split(" "), f.sessionFactory);
new VespaFeeder(arguments, f.typeManager).parseFiles(System.in, f.printStream);
assertEquals(3, f.sessionFactory.messages.size());
- assertEquals(DocumentProtocol.Priority.LOW_1, ((PutDocumentMessage)f.sessionFactory.messages.get(0)).getPriority()); // TODO: Remove on Vespa 9
+ assertEquals(DocumentProtocol.Priority.LOW_1, ((PutDocumentMessage) f.sessionFactory.messages.get(0)).getPriority()); // TODO: Remove on Vespa 9
assertEquals("id:test:news::foo", ((PutDocumentMessage) f.sessionFactory.messages.get(0)).getDocumentPut().getDocument().getId().toString());
DocumentUpdate update = ((UpdateDocumentMessage) f.sessionFactory.messages.get(1)).getDocumentUpdate();
assertEquals("id:test:news::foo", update.getId().toString());
@@ -170,7 +163,7 @@ public class VespaFeederTestCase {
}
@Test
- public void feedJson() throws Exception {
+ void feedJson() throws Exception {
FeedFixture feedFixture = feed("src/test/files/myfeed.json", true);
assertJsonFeedState(feedFixture);
@@ -190,7 +183,7 @@ public class VespaFeederTestCase {
}
@Test
- public void requireThatCreateIfNonExistentArgumentIsUsed() throws Exception {
+ void requireThatCreateIfNonExistentArgumentIsUsed() throws Exception {
FeedFixture f = new FeedFixture();
Arguments arguments = new Arguments("--file src/test/files/myfeed.xml --create-if-non-existent".split(" "), f.sessionFactory);
new VespaFeeder(arguments, f.typeManager).parseFiles(System.in, f.printStream);
@@ -201,10 +194,11 @@ public class VespaFeederTestCase {
}
@Test
- public void feedMalformedJson() throws Exception {
- exception.expect(VespaFeeder.FeedErrorException.class);
- exception.expectMessage("JsonParseException");
- feed("src/test/files/malformedfeed.json", false);
+ void feedMalformedJson() throws Exception {
+ Throwable exception = assertThrows(VespaFeeder.FeedErrorException.class, () -> {
+ feed("src/test/files/malformedfeed.json", false);
+ });
+ assertTrue(exception.getMessage().contains("JsonParseException"));
}
protected FeedFixture feed(String feed, boolean abortOnDataError) throws Exception {
diff --git a/vespaclient-java/src/test/java/com/yahoo/vespaget/CommandLineOptionsTest.java b/vespaclient-java/src/test/java/com/yahoo/vespaget/CommandLineOptionsTest.java
index 0b828c91f91..c448e5d55f5 100644
--- a/vespaclient-java/src/test/java/com/yahoo/vespaget/CommandLineOptionsTest.java
+++ b/vespaclient-java/src/test/java/com/yahoo/vespaget/CommandLineOptionsTest.java
@@ -5,9 +5,7 @@ import com.yahoo.document.fieldset.AllFields;
import com.yahoo.document.fieldset.DocumentOnly;
import com.yahoo.document.fieldset.DocIdOnly;
import com.yahoo.documentapi.messagebus.protocol.DocumentProtocol;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@@ -17,9 +15,7 @@ import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
-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 class for {@link CommandLineOptions}
@@ -37,10 +33,6 @@ public class CommandLineOptionsTest {
}
};
- @SuppressWarnings("deprecation")
- @Rule
- public final ExpectedException exception = ExpectedException.none();
-
private ClientParameters getParsedOptions(InputStream in, String... args) {
CommandLineOptions options = new CommandLineOptions(in);
return options.parseCommandLineArguments(args);
@@ -51,7 +43,7 @@ public class CommandLineOptionsTest {
}
@Test
- public void testDefaultOptions() {
+ void testDefaultOptions() {
ClientParameters params = getParsedOptions();
assertFalse(params.help);
assertFalse(params.documentIds.hasNext());
@@ -68,7 +60,7 @@ public class CommandLineOptionsTest {
}
@Test
- public void testValidOptions() {
+ void testValidOptions() {
ClientParameters params = getParsedOptions(
"--fieldset", "[fieldset]",
"--route", "dummyroute",
@@ -97,73 +89,78 @@ public class CommandLineOptionsTest {
}
@Test
- public void testInvalidCombination3() {
- exception.expect(IllegalArgumentException.class);
- exception.expectMessage("Field set option can not be used in combination with print ids option.");
- getParsedOptions("--printids", "--fieldset", AllFields.NAME);
+ void testInvalidCombination3() {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ getParsedOptions("--printids", "--fieldset", AllFields.NAME);
+ });
+ assertTrue(exception.getMessage().contains("Field set option can not be used in combination with print ids option."));
}
@Test
- public void testInvalidCombination4() {
- exception.expect(IllegalArgumentException.class);
- exception.expectMessage("Cluster and route options are mutually exclusive.");
- getParsedOptions("--route", "dummyroute", "--cluster", "dummycluster");
+ void testInvalidCombination4() {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ getParsedOptions("--route", "dummyroute", "--cluster", "dummycluster");
+ });
+ assertTrue(exception.getMessage().contains("Cluster and route options are mutually exclusive."));
}
@Test
- public void testInvalidPriority() {
- exception.expect(IllegalArgumentException.class);
- exception.expectMessage("Invalid priority: 16");
- getParsedOptions("--priority", "16");
+ void testInvalidPriority() {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ getParsedOptions("--priority", "16");
+ });
+ assertTrue(exception.getMessage().contains("Invalid priority: 16"));
}
@Test
- public void TestHighestPriority() {
+ void TestHighestPriority() {
ClientParameters params = getParsedOptions("--priority", "HIGHEST");
assertEquals(DocumentProtocol.Priority.HIGHEST, params.priority);
}
@Test
- public void TestHigh1PriorityAsNumber() {
+ void TestHigh1PriorityAsNumber() {
ClientParameters params = getParsedOptions("--priority", "2");
assertEquals(DocumentProtocol.Priority.HIGH_1, params.priority);
}
@Test
- public void testInvalidTraceLevel1() {
- exception.expect(IllegalArgumentException.class);
- exception.expectMessage("Invalid tracelevel: -1");
- getParsedOptions("--trace", "-1");
+ void testInvalidTraceLevel1() {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ getParsedOptions("--trace", "-1");
+ });
+ assertTrue(exception.getMessage().contains("Invalid tracelevel: -1"));
}
@Test
- public void testInvalidTraceLevel2() {
- exception.expect(IllegalArgumentException.class);
- exception.expectMessage("Invalid tracelevel: 10");
- getParsedOptions("--trace", "10");
+ void testInvalidTraceLevel2() {
+ Throwable exception = assertThrows(IllegalArgumentException.class, () -> {
+ getParsedOptions("--trace", "10");
+ });
+ assertTrue(exception.getMessage().contains("Invalid tracelevel: 10"));
}
@Test
- public void testPrintids() {
+ void testPrintids() {
ClientParameters params = getParsedOptions("--printids");
assertEquals(DocIdOnly.NAME, params.fieldSet);
}
@Test
- public void testCluster() {
+ void testCluster() {
ClientParameters params = getParsedOptions("--cluster", "dummycluster");
assertEquals("dummycluster", params.cluster);
assertTrue(params.route.isEmpty());
}
@Test
- public void testHelp() {
+ void testHelp() {
ClientParameters params = getParsedOptions("--help");
assertTrue(params.help);
}
@Test
- public void testDocumentIdsFromInputStream() throws UnsupportedEncodingException {
+ void testDocumentIdsFromInputStream() throws UnsupportedEncodingException {
InputStream in = new ByteArrayInputStream("id:1 id:2 id:3".getBytes("UTF-8"));
ClientParameters params = getParsedOptions(in, "");
@@ -175,7 +172,7 @@ public class CommandLineOptionsTest {
}
@Test
- public void testPrintHelp() {
+ void testPrintHelp() {
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
PrintStream oldOut = System.out;
System.setOut(new PrintStream(outContent));
diff --git a/vespaclient-java/src/test/java/com/yahoo/vespaget/DocumentRetrieverTest.java b/vespaclient-java/src/test/java/com/yahoo/vespaget/DocumentRetrieverTest.java
index ce555e2c0f5..24e303d6fce 100644
--- a/vespaclient-java/src/test/java/com/yahoo/vespaget/DocumentRetrieverTest.java
+++ b/vespaclient-java/src/test/java/com/yahoo/vespaget/DocumentRetrieverTest.java
@@ -15,11 +15,9 @@ import com.yahoo.messagebus.Error;
import com.yahoo.messagebus.Reply;
import com.yahoo.vespaclient.ClusterDef;
import com.yahoo.vespaclient.ClusterList;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.mockito.ArgumentMatcher;
import java.io.ByteArrayOutputStream;
@@ -31,8 +29,7 @@ import java.util.Iterator;
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.*;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.mock;
@@ -60,11 +57,7 @@ public class DocumentRetrieverTest {
private PrintStream oldOut;
private PrintStream oldErr;
- @SuppressWarnings("deprecation")
- @Rule
- public final ExpectedException exception = ExpectedException.none();
-
- @Before
+ @BeforeEach
public void setUpStreams() {
oldOut = System.out;
oldErr = System.err;
@@ -72,7 +65,7 @@ public class DocumentRetrieverTest {
System.setErr(new PrintStream(errContent));
}
- @Before
+ @BeforeEach
public void prepareMessageBusMocks() {
this.mockedFactory = mock(DocumentAccessFactory.class);
this.mockedDocumentAccess = mock(MessageBusDocumentAccess.class);
@@ -81,7 +74,7 @@ public class DocumentRetrieverTest {
when(mockedDocumentAccess.createSyncSession(any())).thenReturn(mockedSession);
}
- @After
+ @AfterEach
public void cleanUpStreams() {
System.setOut(oldOut);
System.setErr(oldErr);
@@ -129,9 +122,10 @@ public class DocumentRetrieverTest {
params);
}
+ // TODO: Remove on Vespa 9
@Test
- @SuppressWarnings("removal") // TODO: Remove on Vespa 9
- public void testSendSingleMessage() throws DocumentRetrieverException {
+ @SuppressWarnings("removal")
+ void testSendSingleMessage() throws DocumentRetrieverException {
ClientParameters params = createParameters()
.setDocumentIds(asIterator(DOC_ID_1))
.setPriority(DocumentProtocol.Priority.HIGH_1)
@@ -148,12 +142,12 @@ public class DocumentRetrieverTest {
verify(mockedSession, times(1)).syncSend(argThat((ArgumentMatcher<GetDocumentMessage>) o ->
o.getPriority().equals(DocumentProtocol.Priority.HIGH_1) && // TODO remove on Vespa 9
- !o.getRetryEnabled()));
+ !o.getRetryEnabled()));
assertContainsDocument(DOC_ID_1);
}
@Test
- public void testMultipleMessages() throws DocumentRetrieverException {
+ void testMultipleMessages() throws DocumentRetrieverException {
ClientParameters params = createParameters()
.setDocumentIds(asIterator(DOC_ID_1, DOC_ID_2, DOC_ID_3))
.build();
@@ -173,7 +167,7 @@ public class DocumentRetrieverTest {
}
@Test
- public void testJsonOutput() throws DocumentRetrieverException, IOException {
+ void testJsonOutput() throws DocumentRetrieverException, IOException {
ClientParameters params = createParameters()
.setDocumentIds(asIterator(DOC_ID_1, DOC_ID_2, DOC_ID_3))
.setJsonOutput(true)
@@ -197,7 +191,7 @@ public class DocumentRetrieverTest {
}
@Test
- public void testShutdownHook() throws DocumentRetrieverException {
+ void testShutdownHook() throws DocumentRetrieverException {
ClientParameters params = createParameters()
.setDocumentIds(asIterator(DOC_ID_1))
.build();
@@ -213,7 +207,7 @@ public class DocumentRetrieverTest {
}
@Test
- public void testClusterLookup() throws DocumentRetrieverException {
+ void testClusterLookup() throws DocumentRetrieverException {
final String cluster = "storage",
expectedRoute = "[Content:cluster=storage]";
@@ -230,35 +224,37 @@ public class DocumentRetrieverTest {
}
@Test
- public void testInvalidClusterName() throws DocumentRetrieverException {
- exception.expect(DocumentRetrieverException.class);
- exception.expectMessage("The Vespa cluster contains the content clusters storage, not invalidclustername. Please select a valid vespa cluster.");
+ void testInvalidClusterName() throws DocumentRetrieverException {
+ Throwable exception = assertThrows(DocumentRetrieverException.class, () -> {
- ClientParameters params = createParameters()
- .setCluster("invalidclustername")
- .build();
+ ClientParameters params = createParameters()
+ .setCluster("invalidclustername")
+ .build();
- ClusterList clusterList = new ClusterList(Collections.singletonList(new ClusterDef("storage")));
+ ClusterList clusterList = new ClusterList(Collections.singletonList(new ClusterDef("storage")));
- DocumentRetriever documentRetriever = createDocumentRetriever(params, clusterList);
- documentRetriever.retrieveDocuments();
+ DocumentRetriever documentRetriever = createDocumentRetriever(params, clusterList);
+ documentRetriever.retrieveDocuments();
+ });
+ assertTrue(exception.getMessage().contains("The Vespa cluster contains the content clusters storage, not invalidclustername. Please select a valid vespa cluster."));
}
@Test
- public void testEmtpyClusterList() throws DocumentRetrieverException {
- exception.expect(DocumentRetrieverException.class);
- exception.expectMessage("The Vespa cluster does not have any content clusters declared.");
+ void testEmtpyClusterList() throws DocumentRetrieverException {
+ Throwable exception = assertThrows(DocumentRetrieverException.class, () -> {
- ClientParameters params = createParameters()
- .setCluster("invalidclustername")
- .build();
+ ClientParameters params = createParameters()
+ .setCluster("invalidclustername")
+ .build();
- DocumentRetriever documentRetriever = createDocumentRetriever(params);
- documentRetriever.retrieveDocuments();
+ DocumentRetriever documentRetriever = createDocumentRetriever(params);
+ documentRetriever.retrieveDocuments();
+ });
+ assertTrue(exception.getMessage().contains("The Vespa cluster does not have any content clusters declared."));
}
@Test
- public void testHandlingErrorFromMessageBus() throws DocumentRetrieverException {
+ void testHandlingErrorFromMessageBus() throws DocumentRetrieverException {
ClientParameters params = createParameters()
.setDocumentIds(asIterator(DOC_ID_1))
.build();
@@ -274,7 +270,7 @@ public class DocumentRetrieverTest {
}
@Test
- public void testShowDocSize() throws DocumentRetrieverException {
+ void testShowDocSize() throws DocumentRetrieverException {
ClientParameters params = createParameters()
.setDocumentIds(asIterator(DOC_ID_1))
.setShowDocSize(true)
@@ -290,7 +286,7 @@ public class DocumentRetrieverTest {
}
@Test
- public void testPrintIdOnly() throws DocumentRetrieverException {
+ void testPrintIdOnly() throws DocumentRetrieverException {
ClientParameters params = createParameters()
.setDocumentIds(asIterator(DOC_ID_1))
.setPrintIdsOnly(true)
@@ -305,7 +301,7 @@ public class DocumentRetrieverTest {
}
@Test
- public void testDocumentNotFound() throws DocumentRetrieverException {
+ void testDocumentNotFound() throws DocumentRetrieverException {
ClientParameters params = createParameters()
.setDocumentIds(asIterator(DOC_ID_1))
.setPrintIdsOnly(true)
@@ -321,7 +317,7 @@ public class DocumentRetrieverTest {
}
@Test
- public void testTrace() throws DocumentRetrieverException {
+ void testTrace() throws DocumentRetrieverException {
final int traceLevel = 9;
ClientParameters params = createParameters()
.setDocumentIds(asIterator(DOC_ID_1))
diff --git a/vespaclient-java/src/test/java/com/yahoo/vespastat/BucketStatsPrinterTest.java b/vespaclient-java/src/test/java/com/yahoo/vespastat/BucketStatsPrinterTest.java
index 8120e2f1d77..0a0bca8af0e 100644
--- a/vespaclient-java/src/test/java/com/yahoo/vespastat/BucketStatsPrinterTest.java
+++ b/vespaclient-java/src/test/java/com/yahoo/vespastat/BucketStatsPrinterTest.java
@@ -3,9 +3,9 @@ package com.yahoo.vespastat;
import com.yahoo.document.BucketId;
import com.yahoo.documentapi.messagebus.protocol.GetBucketListReply;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
@@ -13,7 +13,7 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -24,7 +24,7 @@ public class BucketStatsPrinterTest {
private final ByteArrayOutputStream out = new ByteArrayOutputStream();
private final String bucketSpace = "default";
- @Before
+ @BeforeEach
public void mockBucketStatsRetriever() throws BucketStatsException {
retriever = mock(BucketStatsRetriever.class);
when(retriever.getBucketIdForType(any(), any())).thenReturn(new BucketId(0x42));
@@ -32,7 +32,7 @@ public class BucketStatsPrinterTest {
when(retriever.retrieveBucketStats(any(), any(), any(), any())).thenReturn("");
}
- @After
+ @AfterEach
public void resetOutputMock() {
out.reset();
}
@@ -50,7 +50,7 @@ public class BucketStatsPrinterTest {
}
@Test
- public void testShouldPrintBucketIdForUserAndGroup() throws BucketStatsException {
+ void testShouldPrintBucketIdForUserAndGroup() throws BucketStatsException {
String output = retreiveAndPrintBucketStats(ClientParameters.SelectionType.USER, "1234", false);
assertTrue(output.contains("Generated 32-bit bucket id"));
@@ -59,13 +59,13 @@ public class BucketStatsPrinterTest {
}
@Test
- public void testShouldPrintWarningIfBucketListEmpty() throws BucketStatsException {
+ void testShouldPrintWarningIfBucketListEmpty() throws BucketStatsException {
String output = retreiveAndPrintBucketStats(ClientParameters.SelectionType.USER, "1234", false);
assertTrue(output.contains("No actual files were stored for this bucket"));
}
@Test
- public void testShouldPrintBucketList() throws BucketStatsException {
+ void testShouldPrintBucketList() throws BucketStatsException {
List<GetBucketListReply.BucketInfo> bucketList = new ArrayList<>();
String dummyInfoString = "dummyinformation";
bucketList.add(new GetBucketListReply.BucketInfo(new BucketId(0), dummyInfoString));
@@ -76,7 +76,7 @@ public class BucketStatsPrinterTest {
}
@Test
- public void testShouldPrintBucketStats() throws BucketStatsException {
+ void testShouldPrintBucketStats() throws BucketStatsException {
String dummyBucketStats = "dummystats";
GetBucketListReply.BucketInfo bucketInfo = new GetBucketListReply.BucketInfo(new BucketId(0), "dummy");
when(retriever.retrieveBucketList(any(), any())).thenReturn(Collections.singletonList(bucketInfo));
diff --git a/vespaclient-java/src/test/java/com/yahoo/vespastat/BucketStatsRetrieverTest.java b/vespaclient-java/src/test/java/com/yahoo/vespastat/BucketStatsRetrieverTest.java
index 39f8968d209..426c316027a 100644
--- a/vespaclient-java/src/test/java/com/yahoo/vespastat/BucketStatsRetrieverTest.java
+++ b/vespaclient-java/src/test/java/com/yahoo/vespastat/BucketStatsRetrieverTest.java
@@ -9,12 +9,13 @@ import com.yahoo.documentapi.messagebus.MessageBusSyncSession;
import com.yahoo.documentapi.messagebus.protocol.GetBucketListReply;
import com.yahoo.documentapi.messagebus.protocol.StatBucketReply;
import com.yahoo.messagebus.Error;
-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 static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
@@ -31,7 +32,7 @@ public class BucketStatsRetrieverTest {
private final String bucketSpace = "default";
- @Before
+ @BeforeEach
public void prepareMessageBusMocks() {
this.mockedFactory = mock(DocumentAccessFactory.class);
this.mockedDocumentAccess = mock(MessageBusDocumentAccess.class);
@@ -41,7 +42,7 @@ public class BucketStatsRetrieverTest {
}
@Test
- public void testGetBucketId() throws BucketStatsException {
+ void testGetBucketId() throws BucketStatsException {
BucketStatsRetriever retriever = createRetriever();
assertEquals("BucketId(0x80000000000004d2)",
@@ -57,7 +58,7 @@ public class BucketStatsRetrieverTest {
}
@Test
- public void testRetrieveBucketList() throws BucketStatsException {
+ void testRetrieveBucketList() throws BucketStatsException {
String bucketInfo = "I like turtles!";
BucketId bucketId = bucketIdFactory.getBucketId(new DocumentId("id:ns:type::another"));
@@ -73,7 +74,7 @@ public class BucketStatsRetrieverTest {
}
@Test
- public void testRetrieveBucketStats() throws BucketStatsException {
+ void testRetrieveBucketStats() throws BucketStatsException {
String docId = "id:ns:type::another";
String bucketInfo = "I like turtles!";
BucketId bucketId = bucketIdFactory.getBucketId(new DocumentId(docId));
@@ -88,9 +89,10 @@ public class BucketStatsRetrieverTest {
}
@Test
- public void testShutdownHook() {
+ void testShutdownHook() {
class MockShutdownRegistrar implements BucketStatsRetriever.ShutdownHookRegistrar {
public Runnable shutdownRunnable;
+
@Override
public void registerShutdownHook(Runnable runnable) {
shutdownRunnable = runnable;
@@ -104,24 +106,27 @@ public class BucketStatsRetrieverTest {
verify(mockedDocumentAccess, times(1)).shutdown();
}
- @Test(expected = BucketStatsException.class)
- public void testShouldFailOnReplyError() throws BucketStatsException {
- GetBucketListReply reply = new GetBucketListReply();
- reply.addError(new Error(0, "errormsg"));
- when(mockedSession.syncSend(any())).thenReturn(reply);
-
- createRetriever().retrieveBucketList(new BucketId(1), bucketSpace);
+ @Test
+ void testShouldFailOnReplyError() throws BucketStatsException {
+ assertThrows(BucketStatsException.class, () -> {
+ GetBucketListReply reply = new GetBucketListReply();
+ reply.addError(new Error(0, "errormsg"));
+ when(mockedSession.syncSend(any())).thenReturn(reply);
+
+ createRetriever().retrieveBucketList(new BucketId(1), bucketSpace);
+ });
}
@Test
- public void testRoute() throws BucketStatsException {
+ void testRoute() throws BucketStatsException {
String route = "default";
BucketId bucketId = bucketIdFactory.getBucketId(new DocumentId("id:ns:type::another"));
GetBucketListReply reply = new GetBucketListReply();
reply.getBuckets().add(new GetBucketListReply.BucketInfo(bucketId, "I like turtles!"));
when(mockedSession.syncSend(any())).thenReturn(reply);
- BucketStatsRetriever retriever = new BucketStatsRetriever(mockedFactory, route, t -> {});
+ BucketStatsRetriever retriever = new BucketStatsRetriever(mockedFactory, route, t -> {
+ });
retriever.retrieveBucketList(new BucketId(0), bucketSpace);
// Route is set at session-level, not per message sent.
diff --git a/vespaclient-java/src/test/java/com/yahoo/vespastat/CommandLineOptionsTest.java b/vespaclient-java/src/test/java/com/yahoo/vespastat/CommandLineOptionsTest.java
index 4bfe9b68b65..b030120ac52 100644
--- a/vespaclient-java/src/test/java/com/yahoo/vespastat/CommandLineOptionsTest.java
+++ b/vespaclient-java/src/test/java/com/yahoo/vespastat/CommandLineOptionsTest.java
@@ -1,12 +1,12 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespastat;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.*;
public class CommandLineOptionsTest {
@@ -16,12 +16,12 @@ public class CommandLineOptionsTest {
}
@Test
- public void testHelp() {
+ void testHelp() {
assertTrue(getParsedOptions("--help").help);
}
@Test
- public void testMultipleOptions() {
+ void testMultipleOptions() {
ClientParameters params = getParsedOptions("--dump", "--route", "dummyroute", "--user", "userid");
assertTrue(params.dumpData);
assertEquals("dummyroute", params.route);
@@ -30,7 +30,7 @@ public class CommandLineOptionsTest {
}
@Test
- public void testSelectionTypes() {
+ void testSelectionTypes() {
assertEquals(ClientParameters.SelectionType.USER, getParsedOptions("--user", "id").selectionType);
assertEquals(ClientParameters.SelectionType.DOCUMENT, getParsedOptions("--document", "id").selectionType);
assertEquals(ClientParameters.SelectionType.BUCKET, getParsedOptions("--bucket", "id").selectionType);
@@ -38,24 +38,28 @@ public class CommandLineOptionsTest {
assertEquals(ClientParameters.SelectionType.GID, getParsedOptions("--gid", "id").selectionType);
}
- @Test(expected = IllegalArgumentException.class)
- public void testMissingSelectionType() {
- getParsedOptions();
+ @Test
+ void testMissingSelectionType() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ getParsedOptions();
+ });
}
- @Test(expected = IllegalArgumentException.class)
- public void testFailOnMultipleDumpTypes() {
- getParsedOptions("--user", "id", "--document", "id", "--group", "id", "--gid", "id");
+ @Test
+ void testFailOnMultipleDumpTypes() {
+ assertThrows(IllegalArgumentException.class, () -> {
+ getParsedOptions("--user", "id", "--document", "id", "--group", "id", "--gid", "id");
+ });
}
@Test
- public void testForceDumpOnDocumentOrGid() {
+ void testForceDumpOnDocumentOrGid() {
assertTrue(getParsedOptions("--document", "docid").dumpData);
assertTrue(getParsedOptions("--gid", "gid").dumpData);
}
@Test
- public void testPrintHelp() {
+ void testPrintHelp() {
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
PrintStream oldOut = System.out;
System.setOut(new PrintStream(outContent));
@@ -71,17 +75,17 @@ public class CommandLineOptionsTest {
}
@Test
- public void bucket_space_is_default_unless_specified() {
+ void bucket_space_is_default_unless_specified() {
assertEquals("default", getParsedOptions("--user", "id").bucketSpace);
}
@Test
- public void can_specify_explicit_bucket_space() {
+ void can_specify_explicit_bucket_space() {
assertEquals("global", getParsedOptions("--user", "id", "--bucketspace", "global").bucketSpace);
}
@Test
- public void testDefaultRoute() {
+ void testDefaultRoute() {
assertEquals("default", getParsedOptions("--user", "dummyuser").route);
}
diff --git a/vespaclient-java/src/test/java/com/yahoo/vespavisit/StdOutVisitorHandlerTest.java b/vespaclient-java/src/test/java/com/yahoo/vespavisit/StdOutVisitorHandlerTest.java
index 854d7ae9ad3..f109b0ad56b 100644
--- a/vespaclient-java/src/test/java/com/yahoo/vespavisit/StdOutVisitorHandlerTest.java
+++ b/vespaclient-java/src/test/java/com/yahoo/vespavisit/StdOutVisitorHandlerTest.java
@@ -2,33 +2,32 @@
package com.yahoo.vespavisit;
import com.yahoo.documentapi.VisitorDataHandler;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.MethodSource;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author bjorncs
*/
-@RunWith(Parameterized.class)
public class StdOutVisitorHandlerTest {
- private final boolean jsonOutput;
+ private boolean jsonOutput;
- public StdOutVisitorHandlerTest(boolean jsonOutput) {
+ public void initStdOutVisitorHandlerTest(boolean jsonOutput) {
this.jsonOutput = jsonOutput;
}
- @Parameterized.Parameters(name = "jsonOutput={0}")
public static Object[] data() {
- return new Object[] { true, false};
+ return new Object[]{true, false};
}
- @Test
- public void printing_ids_for_zero_documents_produces_empty_output() {
+ @MethodSource("data")
+ @ParameterizedTest(name = "jsonOutput={0}")
+ void printing_ids_for_zero_documents_produces_empty_output(boolean jsonOutput) {
+ initStdOutVisitorHandlerTest(jsonOutput);
ByteArrayOutputStream out = new ByteArrayOutputStream();
StdOutVisitorHandler visitorHandler =
new StdOutVisitorHandler(/*printIds*/true, false, false, false, false, false, 0, jsonOutput, new PrintStream(out, true));
@@ -38,8 +37,10 @@ public class StdOutVisitorHandlerTest {
assertEquals("", output.trim());
}
- @Test
- public void printing_zero_documents_produces_empty_output() {
+ @MethodSource("data")
+ @ParameterizedTest(name = "jsonOutput={0}")
+ void printing_zero_documents_produces_empty_output(boolean jsonOutput) {
+ initStdOutVisitorHandlerTest(jsonOutput);
ByteArrayOutputStream out = new ByteArrayOutputStream();
StdOutVisitorHandler visitorHandler =
new StdOutVisitorHandler(/*printIds*/false, false, false, false, false, false, 0, jsonOutput, new PrintStream(out, true));
diff --git a/vespaclient-java/src/test/java/com/yahoo/vespavisit/VdsVisitTargetTestCase.java b/vespaclient-java/src/test/java/com/yahoo/vespavisit/VdsVisitTargetTestCase.java
index 42526a38df5..3a74ac39f43 100644
--- a/vespaclient-java/src/test/java/com/yahoo/vespavisit/VdsVisitTargetTestCase.java
+++ b/vespaclient-java/src/test/java/com/yahoo/vespavisit/VdsVisitTargetTestCase.java
@@ -1,13 +1,14 @@
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespavisit;
-import org.junit.Test;
-import static org.junit.Assert.*;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.*;
public class VdsVisitTargetTestCase {
@Test
- public void testParametersSlobrok() throws Exception {
+ void testParametersSlobrok() throws Exception {
VdsVisitTarget target = new VdsVisitTarget();
target.parseArguments(new String[]{
"--bindtoslobrok", "myname",
@@ -30,11 +31,11 @@ public class VdsVisitTargetTestCase {
}
@Test
- public void testParametersPort() throws Exception {
+ void testParametersPort() throws Exception {
VdsVisitTarget target = new VdsVisitTarget();
target.parseArguments("--bindtosocket 1234".split(" "));
assertEquals(1234, target.getPort());
- assertEquals(null, target.getSlobrokAddress());
+ assertNull(target.getSlobrokAddress());
}
public void assertException(String params) {
@@ -48,7 +49,7 @@ public class VdsVisitTargetTestCase {
}
@Test
- public void testPortAndSlobrok() {
+ void testPortAndSlobrok() {
assertException("--bindtoslobrok foo --bindtosocket 1234");
assertException("--bindtoport foo");
}
diff --git a/vespaclient-java/src/test/java/com/yahoo/vespavisit/VdsVisitTestCase.java b/vespaclient-java/src/test/java/com/yahoo/vespavisit/VdsVisitTestCase.java
index 55ac7761da3..a67fee0c0d6 100644
--- a/vespaclient-java/src/test/java/com/yahoo/vespavisit/VdsVisitTestCase.java
+++ b/vespaclient-java/src/test/java/com/yahoo/vespavisit/VdsVisitTestCase.java
@@ -3,22 +3,31 @@ package com.yahoo.vespavisit;
import com.yahoo.document.fieldset.DocIdOnly;
import com.yahoo.document.select.parser.ParseException;
-import com.yahoo.documentapi.*;
+import com.yahoo.documentapi.AckToken;
+import com.yahoo.documentapi.ProgressToken;
+import com.yahoo.documentapi.VisitorControlHandler;
+import com.yahoo.documentapi.VisitorParameters;
+import com.yahoo.documentapi.VisitorResponse;
+import com.yahoo.documentapi.VisitorSession;
import com.yahoo.documentapi.messagebus.protocol.DocumentProtocol;
import com.yahoo.messagebus.StaticThrottlePolicy;
import com.yahoo.messagebus.Trace;
import com.yahoo.vespaclient.ClusterDef;
import com.yahoo.vespaclient.ClusterList;
import org.apache.commons.cli.Options;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
-import java.util.Arrays;
import java.util.List;
-import static org.junit.Assert.*;
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
public class VdsVisitTestCase {
@@ -28,9 +37,9 @@ public class VdsVisitTestCase {
}
@Test
- public void testCommandLineShortOptions() throws Exception {
+ void testCommandLineShortOptions() throws Exception {
// short options testing (for options that do not collide with each other)
- String[] args = new String[] {
+ String[] args = new String[]{
"-d", "foo.remote",
"-s", "'id.user=1234'",
"-f", "5678",
@@ -70,9 +79,9 @@ public class VdsVisitTestCase {
* @throws Exception
*/
@Test
- public void testCommandLineShortOptions2() throws Exception {
+ void testCommandLineShortOptions2() throws Exception {
// Short options testing (for options that do not collide with each other)
- String[] args = new String[] {
+ String[] args = new String[]{
"-o", "654321",
"-i"
};
@@ -88,9 +97,9 @@ public class VdsVisitTestCase {
}
@Test
- public void testCommandLineShortOptionsPrintIdsOnly() throws Exception {
+ void testCommandLineShortOptionsPrintIdsOnly() throws Exception {
// Short options testing (for options that do not collide with each other)
- String[] args = new String[] {
+ String[] args = new String[]{
"-i"
};
VdsVisit.ArgumentParser parser = createMockArgumentParser();
@@ -104,9 +113,9 @@ public class VdsVisitTestCase {
}
@Test
- public void testCommandLineLongOptions() throws Exception {
+ void testCommandLineLongOptions() throws Exception {
// short options testing (for options that do not collide with each other)
- String[] args = new String[] {
+ String[] args = new String[]{
"--datahandler", "foo.remote",
"--selection", "'id.user=1234'",
"--from", "5678",
@@ -151,12 +160,12 @@ public class VdsVisitTestCase {
assertEquals("kittens", allParams.getCluster());
assertTrue(params.getThrottlePolicy() instanceof StaticThrottlePolicy);
- assertEquals(3, ((StaticThrottlePolicy)params.getThrottlePolicy()).getMaxPendingCount());
+ assertEquals(3, ((StaticThrottlePolicy) params.getThrottlePolicy()).getMaxPendingCount());
assertTrue(params.visitInconsistentBuckets());
assertEquals("fnord", params.getVisitorLibrary());
// TODO: FIXME? multiple library params doesn't work
- assertTrue(Arrays.equals("rargh".getBytes(), params.getLibraryParameters().get("asdf")));
+ assertArrayEquals("rargh".getBytes(), params.getLibraryParameters().get("asdf"));
//assertTrue(Arrays.equals("pie".getBytes(), params.getLibraryParameters().get("pinkie")));
assertEquals(555, allParams.getProcessTime());
assertEquals(2002, params.getMaxTotalHits());
@@ -171,7 +180,7 @@ public class VdsVisitTestCase {
printStream.flush();
String nl = System.getProperty("line.separator"); // the joys of running tests on windows
assertEquals(
- "Time out visitor after 123456789 ms." + nl +
+ "Time out visitor after 123456789 ms." + nl +
"Visiting documents matching: 'id.user=1234'" + nl +
"Visiting bucket space: outerspace" + nl +
"Visiting in the inclusive timestamp range 5678 - 9012." + nl +
@@ -193,7 +202,7 @@ public class VdsVisitTestCase {
private static String[] emptyArgList() { return new String[]{}; }
@Test
- public void visitor_priority_is_low1_by_default() throws Exception {
+ void visitor_priority_is_low1_by_default() throws Exception {
VdsVisit.VdsVisitParameters allParams = createMockArgumentParser().parse(emptyArgList());
VisitorParameters params = allParams.getVisitorParameters();
@@ -201,8 +210,8 @@ public class VdsVisitTestCase {
}
@Test
- public void testBadPriorityValue() throws Exception {
- String[] args = new String[] {
+ void testBadPriorityValue() throws Exception {
+ String[] args = new String[]{
"--priority", "super_hyper_important"
};
VdsVisit.ArgumentParser parser = createMockArgumentParser();
@@ -215,9 +224,9 @@ public class VdsVisitTestCase {
}
@Test
- public void testCommandLineShortOptionsInvokeHelp() throws Exception {
+ void testCommandLineShortOptionsInvokeHelp() throws Exception {
// Short options testing (for options that do not collide with each other)
- String[] args = new String[] {
+ String[] args = new String[]{
"-h"
};
VdsVisit.ArgumentParser parser = createMockArgumentParser();
@@ -226,7 +235,7 @@ public class VdsVisitTestCase {
}
@Test
- public void testAutoSelectClusterRoute() throws Exception {
+ void testAutoSelectClusterRoute() throws Exception {
List<ClusterDef> clusterDefs = new ArrayList<>();
clusterDefs.add(new ClusterDef("storage"));
ClusterList clusterList = new ClusterList(clusterDefs);
@@ -236,7 +245,7 @@ public class VdsVisitTestCase {
}
@Test
- public void testBadClusterName() throws Exception {
+ void testBadClusterName() throws Exception {
List<ClusterDef> clusterDefs = new ArrayList<>();
clusterDefs.add(new ClusterDef("storage"));
ClusterList clusterList = new ClusterList(clusterDefs);
@@ -244,13 +253,13 @@ public class VdsVisitTestCase {
VdsVisit.resolveClusterRoute(clusterList, "borkbork");
} catch (IllegalArgumentException e) {
assertEquals("Your vespa cluster contains the content clusters 'storage', not 'borkbork'. " +
- "Please select a valid vespa cluster.",
- e.getMessage());
+ "Please select a valid vespa cluster.",
+ e.getMessage());
}
}
@Test
- public void testRequireClusterOptionIfMultipleClusters() {
+ void testRequireClusterOptionIfMultipleClusters() {
List<ClusterDef> clusterDefs = new ArrayList<>();
clusterDefs.add(new ClusterDef("storage"));
clusterDefs.add(new ClusterDef("storage2"));
@@ -263,7 +272,7 @@ public class VdsVisitTestCase {
}
@Test
- public void testExplicitClusterOptionWithMultipleClusters() {
+ void testExplicitClusterOptionWithMultipleClusters() {
List<ClusterDef> clusterDefs = new ArrayList<>();
clusterDefs.add(new ClusterDef("storage"));
clusterDefs.add(new ClusterDef("storage2"));
@@ -274,7 +283,7 @@ public class VdsVisitTestCase {
}
@Test
- public void testFailIfNoContentClustersAvailable() {
+ void testFailIfNoContentClustersAvailable() {
List<ClusterDef> clusterDefs = new ArrayList<>();
ClusterList clusterList = new ClusterList(clusterDefs);
try {
@@ -285,8 +294,8 @@ public class VdsVisitTestCase {
}
@Test
- public void testStatistics() throws Exception {
- String[] args = new String[] {
+ void testStatistics() throws Exception {
+ String[] args = new String[]{
"--statistics", "foo"
};
VdsVisit.ArgumentParser parser = createMockArgumentParser();
@@ -400,7 +409,7 @@ public class VdsVisitTestCase {
}
@Test
- public void testVdsVisitRunLogic() {
+ void testVdsVisitRunLogic() {
MockVisitorSessionAccessorFactory accessorFactory = new MockVisitorSessionAccessorFactory();
MockShutdownHookRegistrar shutdownHookRegistrar = new MockShutdownHookRegistrar();
VdsVisit vdsVisit = new VdsVisit(accessorFactory, shutdownHookRegistrar);
@@ -429,7 +438,7 @@ public class VdsVisitTestCase {
}
@Test
- public void testVdsVisitRunLogicProgressFileNotYetCreated() {
+ void testVdsVisitRunLogicProgressFileNotYetCreated() {
MockVisitorSessionAccessorFactory accessorFactory = new MockVisitorSessionAccessorFactory();
MockShutdownHookRegistrar shutdownHookRegistrar = new MockShutdownHookRegistrar();
VdsVisit vdsVisit = new VdsVisit(accessorFactory, shutdownHookRegistrar);
diff --git a/vespajlib/src/main/java/com/yahoo/concurrent/Threads.java b/vespajlib/src/main/java/com/yahoo/concurrent/Threads.java
new file mode 100644
index 00000000000..d30750692e9
--- /dev/null
+++ b/vespajlib/src/main/java/com/yahoo/concurrent/Threads.java
@@ -0,0 +1,30 @@
+// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
+package com.yahoo.concurrent;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.List;
+
+/**
+ * @author bjorncs
+ */
+public class Threads {
+
+ private Threads() {}
+
+ /** Returns all threads in JVM */
+ public static Collection<Thread> getAllThreads() {
+ ThreadGroup root = Thread.currentThread().getThreadGroup();
+ ThreadGroup parent;
+ while ((parent = root.getParent()) != null) {
+ root = parent;
+ }
+ // The number of threads may increase between activeCount() and enumerate()
+ Thread[] threads = new Thread[root.activeCount() + 100];
+ int count;
+ while ((count = root.enumerate(threads, true)) == threads.length) {
+ threads = new Thread[threads.length + 1000];
+ }
+ return List.of(Arrays.copyOf(threads, count));
+ }
+}
diff --git a/zookeeper-client-common/pom.xml b/zookeeper-client-common/pom.xml
index 5eafd040e79..c3dc4629702 100644
--- a/zookeeper-client-common/pom.xml
+++ b/zookeeper-client-common/pom.xml
@@ -40,8 +40,13 @@
<!-- compile scope -->
<!-- test scope -->
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
diff --git a/zookeeper-client-common/src/test/java/com/yahoo/vespa/zookeeper/client/ZkClientConfigBuilderTest.java b/zookeeper-client-common/src/test/java/com/yahoo/vespa/zookeeper/client/ZkClientConfigBuilderTest.java
index 7ffce79b67a..6248424d8da 100644
--- a/zookeeper-client-common/src/test/java/com/yahoo/vespa/zookeeper/client/ZkClientConfigBuilderTest.java
+++ b/zookeeper-client-common/src/test/java/com/yahoo/vespa/zookeeper/client/ZkClientConfigBuilderTest.java
@@ -3,7 +3,7 @@ package com.yahoo.vespa.zookeeper.client;
import com.yahoo.security.tls.TlsContext;
import org.apache.zookeeper.client.ZKClientConfig;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
@@ -17,8 +17,8 @@ import static com.yahoo.vespa.zookeeper.client.ZkClientConfigBuilder.SSL_CLIENTA
import static com.yahoo.vespa.zookeeper.client.ZkClientConfigBuilder.SSL_CONTEXT_SUPPLIER_CLASS_PROPERTY;
import static com.yahoo.vespa.zookeeper.client.ZkClientConfigBuilder.SSL_ENABLED_CIPHERSUITES_PROPERTY;
import static com.yahoo.vespa.zookeeper.client.ZkClientConfigBuilder.SSL_ENABLED_PROTOCOLS_PROPERTY;
-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;
/**
* Tests the zookeeper client config builder.
@@ -26,7 +26,7 @@ import static org.junit.Assert.assertNull;
public class ZkClientConfigBuilderTest {
@Test
- public void config_when_not_using_tls_context() {
+ void config_when_not_using_tls_context() {
ZkClientConfigBuilder builder = new ZkClientConfigBuilder(null);
ZKClientConfig config = builder.toConfig();
assertEquals("false", config.getProperty(CLIENT_SECURE_PROPERTY));
@@ -36,7 +36,7 @@ public class ZkClientConfigBuilderTest {
}
@Test
- public void config_when_using_system_tls_context() {
+ void config_when_using_system_tls_context() {
ZkClientConfigBuilder builder = new ZkClientConfigBuilder(new MockTlsContext());
ZKClientConfig config = builder.toConfig();
assertEquals("true", config.getProperty(CLIENT_SECURE_PROPERTY));