From 266d4d1bc043a67b9439249424022424073d4d2f Mon Sep 17 00:00:00 2001 From: Tim Jacomb <21194782+timja@users.noreply.github.com> Date: Tue, 10 Sep 2024 21:34:50 +0100 Subject: [PATCH] Remove unneeded code (#4081) --- Jenkinsfile | 7 +- README.md | 4 +- permissions/plugin-repository.yml | 2 +- .../ArtifactoryPermissionsUpdater.groovy | 12 +- .../Definition.java | 37 +-- .../JiraAPI.java | 20 -- .../JiraImpl.java | 147 ------------ .../KnownUsers.java | 4 +- .../JiraAPITest.java | 218 ------------------ 9 files changed, 23 insertions(+), 428 deletions(-) delete mode 100644 src/main/java/io/jenkins/infra/repository_permissions_updater/JiraAPI.java delete mode 100644 src/main/java/io/jenkins/infra/repository_permissions_updater/JiraImpl.java delete mode 100644 src/test/java/io/jenkins/infra/repository_permissions_updater/JiraAPITest.java diff --git a/Jenkinsfile b/Jenkinsfile index ad63e0b028..60ff10d9d3 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -55,11 +55,7 @@ node('maven-21 || (java&&linux)') { if (dryRun) { try { - withCredentials([ - usernamePassword(credentialsId: 'jiraUser', passwordVariable: 'JIRA_PASSWORD', usernameVariable: 'JIRA_USERNAME') - ]) { - sh 'java -DdryRun=true' + javaArgs - } + sh 'java -DdryRun=true' + javaArgs } catch(ignored) { if (fileExists('checks-title.txt')) { def title = readFile file: 'checks-title.txt', encoding: 'utf-8' @@ -76,7 +72,6 @@ node('maven-21 || (java&&linux)') { title: 'All checks passed' } else { withCredentials([ - usernamePassword(credentialsId: 'jiraUser', passwordVariable: 'JIRA_PASSWORD', usernameVariable: 'JIRA_USERNAME'), string(credentialsId: 'artifactoryAdminToken', variable: 'ARTIFACTORY_TOKEN'), usernamePassword(credentialsId: 'jenkins-infra-bot-github-token', passwordVariable: 'GITHUB_TOKEN', usernameVariable: 'GITHUB_USERNAME') ]) { diff --git a/README.md b/README.md index e55ed67443..74f576cf94 100644 --- a/README.md +++ b/README.md @@ -166,10 +166,12 @@ A complete example with two trackers: ```yaml issues: - github: 'jenkinsci/configuration-as-code-plugin' # The preferred issue tracker - - jira: 'configuration-as-code-plugin' # A secondary issue tracker is the Jira component 'configuration-as-code-plugin' + - jira: '23170' # A secondary issue tracker is the Jira component id 23170 for 'configuration-as-code-plugin' report: false # No new issues should be reported here ``` +Jira component id can be found at: https://issues.jenkins.io/rest/api/2/project/JENKINS/components + When GitHub Issues is used, there would be some duplicated content in the file (between `github` and `issues` entries) which can be resolved by using a YAML reference. Example: diff --git a/permissions/plugin-repository.yml b/permissions/plugin-repository.yml index ed245fccd0..38c8f09510 100644 --- a/permissions/plugin-repository.yml +++ b/permissions/plugin-repository.yml @@ -2,7 +2,7 @@ name: "repository" github: "jenkinsci/maven-repository-plugin" issues: - - jira: "maven-repository-plugin" + - jira: '15802' # maven-repository-plugin paths: - "jenkins/repository" developers: diff --git a/src/main/groovy/io/jenkins/infra/repository_permissions_updater/ArtifactoryPermissionsUpdater.groovy b/src/main/groovy/io/jenkins/infra/repository_permissions_updater/ArtifactoryPermissionsUpdater.groovy index cc9c42c0bb..0b8dfe6bf0 100644 --- a/src/main/groovy/io/jenkins/infra/repository_permissions_updater/ArtifactoryPermissionsUpdater.groovy +++ b/src/main/groovy/io/jenkins/infra/repository_permissions_updater/ArtifactoryPermissionsUpdater.groovy @@ -120,8 +120,8 @@ class ArtifactoryPermissionsUpdater { Map> teamsByName = loadTeams() - Map> pathsByGithub = new TreeMap() - Map issueTrackersByPlugin = new TreeMap() + Map> pathsByGithub = new TreeMap<>() + Map issueTrackersByPlugin = new TreeMap<>() Map> cdEnabledComponentsByGitHub = new TreeMap<>() Map> maintainersByComponent = new HashMap<>() @@ -176,11 +176,11 @@ class ArtifactoryPermissionsUpdater { issueTrackersByPlugin.put(definition.name, definition.issues.collect { tracker -> if (tracker.isJira() || tracker.isGitHubIssues()) { def ret = [type: tracker.getType(), reference: tracker.getReference()] - def viewUrl = tracker.getViewUrl(JiraAPI.getInstance()) + def viewUrl = tracker.getViewUrl() if (viewUrl) { ret += [ viewUrl: viewUrl ] } - def reportUrl = tracker.getReportUrl(JiraAPI.getInstance()) + def reportUrl = tracker.getReportUrl() if (reportUrl) { ret += [ reportUrl: reportUrl ] } @@ -243,7 +243,7 @@ class ArtifactoryPermissionsUpdater { if (!definition.cd?.exclusive) { users definition.developers.collectEntries { developer -> def existsInArtifactory = KnownUsers.existsInArtifactory(developer) - def existsInJira = KnownUsers.existsInJira(developer) || JiraAPI.getInstance().isUserPresent(developer) + def existsInJira = KnownUsers.existsInJira(developer) if (!existsInArtifactory && !existsInJira) { reportChecksApiDetails(developer + " needs to log in to Artifactory and Jira", @@ -287,7 +287,7 @@ class ArtifactoryPermissionsUpdater { } } else { definition.developers.each { developer -> - def existsInJira = KnownUsers.existsInJira(developer) || JiraAPI.getInstance().isUserPresent(developer) + def existsInJira = KnownUsers.existsInJira(developer) if (!existsInJira) { reportChecksApiDetails(developer + " needs to log in to Jira", diff --git a/src/main/java/io/jenkins/infra/repository_permissions_updater/Definition.java b/src/main/java/io/jenkins/infra/repository_permissions_updater/Definition.java index b40f88a990..69b4fb6300 100644 --- a/src/main/java/io/jenkins/infra/repository_permissions_updater/Definition.java +++ b/src/main/java/io/jenkins/infra/repository_permissions_updater/Definition.java @@ -2,7 +2,6 @@ import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; @@ -32,10 +31,6 @@ public static class SecurityContacts { * Some invalid input may result in both returning {@code false}, in that case other methods will throw exceptions. */ public static class IssueTracker { - public interface JiraComponentSource { - String getComponentId(String componentName) throws IOException; - } - private static final Logger LOGGER = Logger.getLogger(IssueTracker.class.getName()); public String jira; @@ -50,6 +45,9 @@ public boolean isJira() { LOGGER.log(Level.INFO, "Unexpected Jira component name, skipping: " + jira); return false; } + + assertJiraIdFormatValid(); + return true; } @@ -65,27 +63,16 @@ public boolean isGitHubIssues() { } @SuppressFBWarnings(value = "NP_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", - justification = "All calls are guarded by jira null check in isJira()") - private String loadComponentId(JiraComponentSource source) throws IOException { - String jiraComponentId = jira; + justification = "All calls are guarded by jira null check in isJira()") + private void assertJiraIdFormatValid() { if (!jira.matches("[0-9]+")) { - // CreateIssueDetails needs the numeric Jira component ID - jiraComponentId = source.getComponentId(jira); - if (jiraComponentId == null) { - LOGGER.warning("Failed to determine Jira component ID for '" + jira + "', the component may not exist"); - return null; - } + throw new IllegalArgumentException("Jira component ID must be numeric, but got: " + jira); } - return jiraComponentId; } - public String getViewUrl(JiraComponentSource source) throws IOException { + public String getViewUrl() { if (isJira()) { - final String id = loadComponentId(source); - if (id != null) { - return "https://issues.jenkins.io/issues/?jql=component=" + id; - } - return null; + return "https://issues.jenkins.io/issues/?jql=component=" + jira; } if (isGitHubIssues()) { return "https://github.com/" + github + "/issues"; @@ -93,16 +80,12 @@ public String getViewUrl(JiraComponentSource source) throws IOException { throw new IllegalStateException("Invalid issue tracker: " + github + " / " + jira); } - public String getReportUrl(JiraComponentSource source) throws IOException { + public String getReportUrl() { if (!report) { return null; } if (isJira()) { - final String id = loadComponentId(source); - if (id != null) { - return "https://www.jenkins.io/participate/report-issue/redirect/#" + id; - } - return null; + return "https://www.jenkins.io/participate/report-issue/redirect/#" + jira; } if (isGitHubIssues()) { return "https://github.com/" + github + "/issues/new/choose"; // The 'choose' URL works even when there are no issue templates diff --git a/src/main/java/io/jenkins/infra/repository_permissions_updater/JiraAPI.java b/src/main/java/io/jenkins/infra/repository_permissions_updater/JiraAPI.java deleted file mode 100644 index 9d962901de..0000000000 --- a/src/main/java/io/jenkins/infra/repository_permissions_updater/JiraAPI.java +++ /dev/null @@ -1,20 +0,0 @@ -package io.jenkins.infra.repository_permissions_updater; - -import java.io.IOException; - -public abstract class JiraAPI implements Definition.IssueTracker.JiraComponentSource { - - static JiraAPI INSTANCE = null; - - public abstract String getComponentId(String componentName) throws IOException; - - abstract boolean isUserPresent(String username); - - /* Singleton support */ - public static synchronized JiraAPI getInstance() { - if (INSTANCE == null) { - INSTANCE = new JiraImpl(System.getProperty("jiraUrl", "https://issues.jenkins.io")); - } - return INSTANCE; - } -} diff --git a/src/main/java/io/jenkins/infra/repository_permissions_updater/JiraImpl.java b/src/main/java/io/jenkins/infra/repository_permissions_updater/JiraImpl.java deleted file mode 100644 index e4762d5dab..0000000000 --- a/src/main/java/io/jenkins/infra/repository_permissions_updater/JiraImpl.java +++ /dev/null @@ -1,147 +0,0 @@ -package io.jenkins.infra.repository_permissions_updater; - -import com.google.gson.Gson; -import com.google.gson.JsonArray; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.ProtocolException; -import java.net.URI; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.Base64; -import java.util.HashMap; -import java.util.Map; -import java.util.regex.Pattern; -import java.util.stream.Collectors; - -class JiraImpl extends JiraAPI { - private static final Logger LOGGER = LoggerFactory.getLogger(JiraImpl.class); - private static final Gson gson = new Gson(); - private static final Pattern USERNAME_REGEX = Pattern.compile("[a-zA-Z0-9_]+"); - private static final String JIRA_USERNAME = System.getenv("JIRA_USERNAME"); - private static final String JIRA_PASSWORD = System.getenv("JIRA_PASSWORD"); - private static final String JIRA_BASIC_AUTH_VALUE = Base64.getEncoder().encodeToString((JIRA_USERNAME + ":" + JIRA_PASSWORD).getBytes(StandardCharsets.UTF_8)); - private static final String JIRA_BASIC_AUTH_HEADER = "Basic %s"; - - /** - * URL to Jira components API - */ - private final String JIRA_COMPONENTS_URL; - private final String JIRA_USE_URL; - /** - * URL to Jira user API - */ - private final String JIRA_USER_QUERY; - private Map componentNamesToIds; - private final Map userMapping = new HashMap<>(); - - - JiraImpl(String jiraUrl) { - JIRA_COMPONENTS_URL = jiraUrl + "/rest/api/2/project/JENKINS/components"; - JIRA_USE_URL = jiraUrl + "/rest/api/2/user"; - JIRA_USER_QUERY = JIRA_USE_URL + "?username=%s"; - } - - @SuppressFBWarnings({"SE_NO_SERIALVERSIONID", "URLCONNECTION_SSRF_FD"}) - private void ensureDataLoaded() throws IOException { - if (componentNamesToIds == null) { - componentNamesToIds = new HashMap<>(); - - LOGGER.info("Retrieving components from Jira..."); - final URL url; - try { - url = URI.create(JIRA_COMPONENTS_URL).toURL(); - } catch (final MalformedURLException e) { - throw new IOException("Failed to construct Jira URL", e); - } - final HttpURLConnection conn; - try { - conn = (HttpURLConnection) url.openConnection(); - } catch (final IOException e) { - throw new IOException("Failed to open connection for Jira URL", e); - } - - try { - conn.setRequestMethod("GET"); - } catch (final ProtocolException e) { - throw new IOException("Failed to set request method", e); - } - try { - conn.connect(); - } catch (IOException e) { - throw new IOException("Failed to connect to Jira URL", e); - } - try (final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) { - final String text = bufferedReader.lines().collect(Collectors.joining()); - final JsonArray jsonElements = gson.fromJson(text, JsonArray.class); - jsonElements.forEach(jsonElement -> { - final var object = jsonElement.getAsJsonObject(); - final var id = object.get("id").getAsString(); - final var name = object.get("name").getAsString(); - LOGGER.trace("Identified Jira component with ID {} and name {}", id, name); - componentNamesToIds.put(name, id); - }); - } catch (final IOException e) { - throw new IOException("Failed to parse Jira response", e); - } - } - } - @Override - public String getComponentId(final String componentName) throws IOException { - ensureDataLoaded(); - return componentNamesToIds.get(componentName); - } - - @Override - boolean isUserPresent(final String username) { - return userMapping.computeIfAbsent(username, this::isUserPresentInternal); - } - @SuppressFBWarnings({"URLCONNECTION_SSRF_FD"}) - private boolean isUserPresentInternal(final String username) throws RuntimeException { - if (!USERNAME_REGEX.matcher(username).matches()) { - throw new RuntimeException(String.format("Rejecting user name for Jira lookup: %s", username)); - } - - LOGGER.info("Checking whether user exists in Jira: {}", username); - - final URL url; - try { - url = URI.create(String.format(JIRA_USER_QUERY, username)).toURL(); - } catch (final MalformedURLException e) { - throw new RuntimeException("Failed to construct Jira URL", e); - } - final HttpURLConnection conn; - try { - conn = (HttpURLConnection) url.openConnection(); - } catch (final IOException e) { - throw new RuntimeException("Failed to open connection for Jira URL", e); - } - - try { - conn.setRequestMethod("GET"); - } catch (final ProtocolException e) { - throw new RuntimeException("Failed to set request method", e); - } - conn.setRequestProperty("Authorization", String.format(JIRA_BASIC_AUTH_HEADER, JIRA_BASIC_AUTH_VALUE)); - try { - conn.connect(); - } catch (final IOException e) { - throw new RuntimeException("Failed to connect to Jira URL", e); - } - - final int code; - try { - code = conn.getResponseCode(); - } catch (final IOException e) { - return false; - } - return code == 200; - } -} diff --git a/src/main/java/io/jenkins/infra/repository_permissions_updater/KnownUsers.java b/src/main/java/io/jenkins/infra/repository_permissions_updater/KnownUsers.java index 107eeaa0c7..a2f1a7da89 100644 --- a/src/main/java/io/jenkins/infra/repository_permissions_updater/KnownUsers.java +++ b/src/main/java/io/jenkins/infra/repository_permissions_updater/KnownUsers.java @@ -15,8 +15,8 @@ public class KnownUsers { private static final String ARTIFACTORY_USER_NAMES_URL = System.getProperty("artifactoryUserNamesJsonListUrl", "https://reports.jenkins.io/artifactory-ldap-users-report.json"); private static final String JIRA_USER_NAMES_URL = System.getProperty("jiraUserNamesJsonListUrl", "https://reports.jenkins.io/jira-users-report.json"); - private static Set knownArtifactoryUsers = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); - private static Set knownJiraUsers = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); + private static final Set knownArtifactoryUsers = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); + private static final Set knownJiraUsers = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); static { try { diff --git a/src/test/java/io/jenkins/infra/repository_permissions_updater/JiraAPITest.java b/src/test/java/io/jenkins/infra/repository_permissions_updater/JiraAPITest.java deleted file mode 100644 index acfc768207..0000000000 --- a/src/test/java/io/jenkins/infra/repository_permissions_updater/JiraAPITest.java +++ /dev/null @@ -1,218 +0,0 @@ -package io.jenkins.infra.repository_permissions_updater; - -import io.jenkins.infra.repository_permissions_updater.helper.URLHelper; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.ProtocolException; -import java.net.URI; -import java.net.URL; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.Properties; -import java.util.function.Supplier; - -import static org.junit.Assert.assertThrows; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; -class JiraAPITest { - - private static final Supplier JIRA_USER_QUERY = JiraAPITest::createUserQuery; - private static final Supplier JIRA_COMPONENTS_URL = JiraAPITest::createComponentsURL; - - private Properties backup; - - private static String createUserQuery() { - return System.getProperty("jiraUrl", "https://issues.jenkins.io") +"/rest/api/2/user?username=%s"; - } - - private static String createComponentsURL() { - return System.getProperty("jiraUrl", "https://issues.jenkins.io") + "/rest/api/2/project/JENKINS/components"; - } - - @BeforeEach - public void reset() { - backup = new Properties(); - backup.putAll(System.getProperties()); - JiraAPI.INSTANCE = null; - URLHelper.instance().getURLStreamHandler().resetConnections(); - } - - @AfterEach - void restore() { - System.setProperties(backup); - } - - @Test - void testEnsureLoadedWrongBaseUrl() { - System.setProperty("jiraUrl", "xx://issues.jenkins.io"); - Exception exception = assertThrows(IOException.class, () -> { - JiraAPI.getInstance().getComponentId("FakeData"); - }); - String expectedMessage = "Failed to construct Jira URL"; - String actualMessage = exception.getMessage(); - Assertions.assertTrue(actualMessage.contains(expectedMessage)); - } - - @Test - void testEnsureLoadedFailedToOpenConnection() throws IOException { - URL fakeUrl = spy(URI.create(JIRA_COMPONENTS_URL.get()).toURL()); - URLHelper.instance().getURLStreamHandler().addConnection(fakeUrl, new IOException()); - Exception exception = assertThrows(IOException.class, () -> { - JiraAPI.getInstance().getComponentId("FakeData"); - }); - String expectedMessage = "Failed to open connection for Jira URL"; - String actualMessage = exception.getMessage(); - Assertions.assertTrue(actualMessage.contains(expectedMessage)); - } - - @Test - void testEnsureLoadedFailedToGetConnection() throws IOException { - URL fakeUrl = spy(URI.create(JIRA_COMPONENTS_URL.get()).toURL()); - var fakeHttpConnection = mock(HttpURLConnection.class); - doThrow(ProtocolException.class).when(fakeHttpConnection).setRequestMethod(anyString()); - URLHelper.instance().getURLStreamHandler().addConnection(fakeUrl, fakeHttpConnection); - Exception exception = assertThrows(IOException.class, () -> { - JiraAPI.getInstance().getComponentId("FakeData"); - }); - String expectedMessage = "Failed to set request method"; - String actualMessage = exception.getMessage(); - Assertions.assertTrue(actualMessage.contains(expectedMessage)); - } - - @Test - void testEnsureLoadedFailedToConnect() throws IOException { - URL fakeUrl = spy(URI.create(JIRA_COMPONENTS_URL.get()).toURL()); - var fakeHttpConnection = mock(HttpURLConnection.class); - doThrow(IOException.class).when(fakeHttpConnection).connect(); - URLHelper.instance().getURLStreamHandler().addConnection(fakeUrl, fakeHttpConnection); - Exception exception = assertThrows(IOException.class, () -> { - JiraAPI.getInstance().getComponentId("FakeData"); - }); - String expectedMessage = "Failed to connect to Jira URL"; - String actualMessage = exception.getMessage(); - Assertions.assertTrue(actualMessage.contains(expectedMessage)); - } - - @Test - void testEnsureLoadedFailedToParse() throws IOException { - URL fakeUrl = spy(URI.create(JIRA_COMPONENTS_URL.get()).toURL()); - var fakeHttpConnection = mock(HttpURLConnection.class); - when(fakeHttpConnection.getInputStream()).thenThrow(IOException.class); - URLHelper.instance().getURLStreamHandler().addConnection(fakeUrl, fakeHttpConnection); - Exception exception = assertThrows(IOException.class, () -> { - JiraAPI.getInstance().getComponentId("FakeData"); - }); - String expectedMessage = "Failed to parse Jira response"; - String actualMessage = exception.getMessage(); - Assertions.assertTrue(actualMessage.contains(expectedMessage)); - } - - @Test - void testEnsureLoadedSuccessToParse() throws IOException { - URL fakeUrl = spy(URI.create(JIRA_COMPONENTS_URL.get()).toURL()); - var fakeHttpConnection = mock(HttpURLConnection.class); - when(fakeHttpConnection.getInputStream()).thenReturn(Files.newInputStream(Path.of("src","test","resources", "components_12_07_2024.json"))); - URLHelper.instance().getURLStreamHandler().addConnection(fakeUrl, fakeHttpConnection); - var id = JiraAPI.getInstance().getComponentId("42crunch-security-audit-plugin"); - Assertions.assertEquals("27235", id); - } - - @Test - void testIsUserPresentInternalRegexDontMatch() { - Exception exception = assertThrows(RuntimeException.class, () -> { - Assertions.assertFalse(JiraAPI.getInstance().isUserPresent("FakeUser**")); - }); - String expectedMessage = "Rejecting user name for Jira lookup"; - String actualMessage = exception.getMessage(); - Assertions.assertTrue(actualMessage.contains(expectedMessage)); - } - - @Test - void testIsUserPresentInternalMalformedUrlException() { - System.setProperty("jiraUrl", "xx://issues.jenkins.io"); - Exception exception = assertThrows(RuntimeException.class, () -> { - Assertions.assertFalse(JiraAPI.getInstance().isUserPresent("FakeUser")); - }); - String expectedMessage = "Failed to construct Jira URL"; - String actualMessage = exception.getMessage(); - Assertions.assertTrue(actualMessage.contains(expectedMessage)); - } - - - @Test - void testIsUserPresentInternalFailedToOpenConnection() throws IOException { - URL fakeUrl = spy(URI.create(String.format(JIRA_USER_QUERY.get(), "FakeUser")).toURL()); - URLHelper.instance().getURLStreamHandler().addConnection(fakeUrl, new IOException()); - Exception exception = assertThrows(RuntimeException.class, () -> { - Assertions.assertFalse(JiraAPI.getInstance().isUserPresent("FakeUser")); - }); - String expectedMessage = "Failed to open connection for Jira URL"; - String actualMessage = exception.getMessage(); - Assertions.assertTrue(actualMessage.contains(expectedMessage)); - } - - @Test - void testIsUserPresentInternalFailedToGetConnection() throws IOException { - URL fakeUrl = spy(URI.create(String.format(JIRA_USER_QUERY.get(), "FakeUser")).toURL()); - var fakeHttpConnection = mock(HttpURLConnection.class); - doThrow(ProtocolException.class).when(fakeHttpConnection).setRequestMethod(anyString()); - URLHelper.instance().getURLStreamHandler().addConnection(fakeUrl, fakeHttpConnection); - Exception exception = assertThrows(RuntimeException.class, () -> { - Assertions.assertFalse(JiraAPI.getInstance().isUserPresent("FakeUser")); - }); - String expectedMessage = "Failed to set request method"; - String actualMessage = exception.getMessage(); - Assertions.assertTrue(actualMessage.contains(expectedMessage)); - } - - @Test - void testIsUserPresentInternalFailedToConnect() throws IOException { - URL fakeUrl = spy(URI.create(String.format(JIRA_USER_QUERY.get(), "FakeUser")).toURL()); - var fakeHttpConnection = mock(HttpURLConnection.class); - doThrow(IOException.class).when(fakeHttpConnection).connect(); - URLHelper.instance().getURLStreamHandler().addConnection(fakeUrl, fakeHttpConnection); - Exception exception = assertThrows(RuntimeException.class, () -> { - Assertions.assertFalse(JiraAPI.getInstance().isUserPresent("FakeUser")); - }); - String expectedMessage = "Failed to connect to Jira URL"; - String actualMessage = exception.getMessage(); - Assertions.assertTrue(actualMessage.contains(expectedMessage)); - } - - @Test - void testIsUserPresentInternalNotExistsException() throws IOException { - URL fakeUrl = spy(URI.create(String.format(JIRA_USER_QUERY.get(), "FakeUser")).toURL()); - var fakeHttpConnection = mock(HttpURLConnection.class); - when(fakeHttpConnection.getResponseCode()).thenThrow(IOException.class); - URLHelper.instance().getURLStreamHandler().addConnection(fakeUrl, fakeHttpConnection); - Assertions.assertFalse(JiraAPI.getInstance().isUserPresent("FakeUser")); - } - - @Test - void testIsUserPresentInternalNotExists() throws IOException { - URL fakeUrl = spy(URI.create(String.format(JIRA_USER_QUERY.get(), "FakeUser")).toURL()); - var fakeHttpConnection = mock(HttpURLConnection.class); - when(fakeHttpConnection.getResponseCode()).thenReturn(404); - URLHelper.instance().getURLStreamHandler().addConnection(fakeUrl, fakeHttpConnection); - Assertions.assertFalse(JiraAPI.getInstance().isUserPresent("FakeUser")); - } - - @Test - void testIsUserPresentInternalExists() throws IOException { - URL fakeUrl = spy(URI.create(String.format(JIRA_USER_QUERY.get(), "FakeUser")).toURL()); - var fakeHttpConnection = mock(HttpURLConnection.class); - when(fakeHttpConnection.getResponseCode()).thenReturn(200); - URLHelper.instance().getURLStreamHandler().addConnection(fakeUrl, fakeHttpConnection); - var result = JiraAPI.getInstance().isUserPresent("FakeUser"); - Assertions.assertTrue(result); - } - -}