diff options
author | Bjørn Christian Seime <bjorncs@yahooinc.com> | 2022-07-28 15:18:41 +0200 |
---|---|---|
committer | Bjørn Christian Seime <bjorncs@yahooinc.com> | 2022-07-28 15:18:41 +0200 |
commit | 038ccba9ff0b90d6d6b78825c6e34ba116003fa5 (patch) | |
tree | 20fc060bb344afca2d5239c6491b2bee8e5e63c8 /node-admin | |
parent | 4514585fe9e66260809f20ef92252a29ff987d67 (diff) |
Convert node-admin to junit5
Diffstat (limited to 'node-admin')
65 files changed, 972 insertions, 943 deletions
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(); |