Skip to content

Commit

Permalink
fix: tests
Browse files Browse the repository at this point in the history
  • Loading branch information
bastiandoetsch committed Jan 8, 2024
1 parent fd94ca7 commit adff7aa
Show file tree
Hide file tree
Showing 20 changed files with 78 additions and 120 deletions.
6 changes: 6 additions & 0 deletions src/main/kotlin/io/snyk/plugin/ui/settings/ScanTypesPanel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ class ScanTypesPanel(
val panel = com.intellij.ui.dsl.builder.panel {
row {
checkBox(ProductType.OSS.productSelectionName).applyToComponent {
name = text
cliScanComments?.let { comment(it) }
label("").component.convertIntoHelpHintLabel(ProductType.OSS.description)
isSelected = settings.ossScanEnable
Expand All @@ -75,6 +76,7 @@ class ScanTypesPanel(
}
row {
checkBox(ProductType.ADVISOR.productSelectionName).applyToComponent {
name = text
label("").component.convertIntoHelpHintLabel(ProductType.ADVISOR.description)
isSelected = settings.advisorEnable
this.addItemListener {
Expand All @@ -85,6 +87,7 @@ class ScanTypesPanel(
}
row {
checkBox(ProductType.IAC.productSelectionName).applyToComponent {
name = text
label("").component.convertIntoHelpHintLabel(ProductType.IAC.description)
isSelected = settings.iacScanEnabled
this.addItemListener {
Expand All @@ -95,6 +98,7 @@ class ScanTypesPanel(
}
row {
checkBox(ProductType.CONTAINER.productSelectionName).applyToComponent {
name = text
label("").component.convertIntoHelpHintLabel(ProductType.CONTAINER.description)
isSelected = settings.containerScanEnabled
this.addItemListener {
Expand All @@ -107,6 +111,7 @@ class ScanTypesPanel(
}
row {
checkBox(ProductType.CODE_SECURITY.productSelectionName).applyToComponent {
name = text
codeSecurityCheckbox = this
isSelected = settings.snykCodeSecurityIssuesScanEnable
label("").component.convertIntoHelpHintLabel(ProductType.CODE_SECURITY.description)
Expand All @@ -117,6 +122,7 @@ class ScanTypesPanel(
}
}
checkBox(ProductType.CODE_QUALITY.productSelectionName).applyToComponent {
name = text
codeQualityCheckbox = this
isSelected = settings.snykCodeQualityIssuesScanEnable
label("").component.convertIntoHelpHintLabel(ProductType.CODE_QUALITY.description)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -859,7 +859,7 @@ class SnykToolWindowPanel(val project: Project) : JPanel(), Disposable {
rootContainerIssuesTreeNode.removeAllChildren()

fun navigateToImage(issuesForImage: ContainerIssuesForImage?, virtualFile: VirtualFile?): () -> Unit = {
val image = issuesForImage?.workloadImages?.get(0)
val image = issuesForImage?.workloadImages?.getOrNull(0)

var file = virtualFile
if (image != null) {
Expand All @@ -874,7 +874,8 @@ class SnykToolWindowPanel(val project: Project) : JPanel(), Disposable {
val settings = pluginSettings()
if (settings.containerScanEnabled && settings.treeFiltering.containerResults) {
containerResult.allCliIssues?.forEach { issuesForImage ->
val virtualFile = issuesForImage.workloadImages[0].virtualFile
val image = issuesForImage.workloadImages.getOrNull(0)
val virtualFile = image?.virtualFile
if (issuesForImage.vulnerabilities.isNotEmpty()) {
val imageTreeNode =
ContainerImageTreeNode(
Expand Down
4 changes: 2 additions & 2 deletions src/main/kotlin/snyk/advisor/AdvisorScoreProvider.kt
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,15 @@ class AdvisorScoreProvider(private val editor: Editor, private val psiFile: PsiF
private var currentBalloon: Balloon? = null
private var currentCursor: Cursor? = null
private var editorListener: AdvisorEditorListener? = null
private var packageNameProvider: PackageNameProvider? = null
var packageNameProvider: PackageNameProvider? = null

fun getLineExtensions(lineNumber: Int): Collection<LineExtensionInfo> {
val settings = pluginSettings()
if (settings.pluginFirstRun || !settings.advisorEnable) {
return resetAndReturnEmptyList()
}

val (packageName, packageManager) = packageNameProvider?.getPackageName(psiFile, lineNumber)
val (packageName, packageManager) = packageNameProvider?.getPackageName(lineNumber)
?: return resetAndReturnEmptyList()

val info = packageName?.let {
Expand Down
5 changes: 2 additions & 3 deletions src/main/kotlin/snyk/advisor/PackageNameProvider.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,12 @@ package snyk.advisor

import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiFile
import snyk.advisor.buildsystems.NpmSupport
import snyk.advisor.buildsystems.PythonSupport

class PackageNameProvider(private val editor: Editor, private val packageManager: AdvisorPackageManager) {

fun getPackageName(psiFile: PsiFile, lineNumber: Int): Pair<String?, AdvisorPackageManager>? {
fun getPackageName(lineNumber: Int): Pair<String?, AdvisorPackageManager>? {
// sanity checks, examples taken from ImageOrColorPreviewManager.registerListeners
val project = editor.project
if (project == null || project.isDisposed) {
Expand All @@ -18,7 +17,7 @@ class PackageNameProvider(private val editor: Editor, private val packageManager
if (lineNumber < 0 || (editor.document.lineCount - 1) < lineNumber) {
log.warn(
"Line number $lineNumber is out of range " +
"[0:${editor.document.lineCount - 1}] at ${psiFile.virtualFile.path}"
"[0:${editor.document.lineCount - 1}] at ${editor.virtualFile.path}"
)
return Pair(null, packageManager)
}
Expand Down
6 changes: 5 additions & 1 deletion src/main/kotlin/snyk/common/SnykError.kt
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,11 @@ data class SnykError(

init {
if (path.isNotEmpty()) {
virtualFile = LocalFileSystem.getInstance().findFileByPath(this.path)
try {
virtualFile = LocalFileSystem.getInstance().findFileByPath(this.path)
} catch (ignore: RuntimeException) {
// ignore because this file is optional
}
}
}
}
1 change: 1 addition & 0 deletions src/main/kotlin/snyk/common/lsp/LanguageServerWrapper.kt
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ class LanguageServerWrapper(private val lsPath: String = getCliFile().absolutePa
val cmd = listOf(lsPath, "language-server", "-l", logLevel)

val processBuilder = ProcessBuilder(cmd)

process = processBuilder.start()
launcher = LSPLauncher.createClientLauncher(languageClient, process.inputStream, process.outputStream)
languageServer = launcher.remoteProxy
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ class ConsoleCommandRunnerTest : LightPlatformTestCase() {
assertEquals("JETBRAINS_IDE", generalCommandLine.environment["SNYK_INTEGRATION_NAME"])
assertEquals(snykPluginVersion, generalCommandLine.environment["SNYK_INTEGRATION_VERSION"])
assertEquals("INTELLIJ IDEA IC", generalCommandLine.environment["SNYK_INTEGRATION_ENVIRONMENT"])
assertEquals("2023.1", generalCommandLine.environment["SNYK_INTEGRATION_ENVIRONMENT_VERSION"])
assertEquals("2023.1".length, generalCommandLine.environment["SNYK_INTEGRATION_ENVIRONMENT_VERSION"]?.length)
}

@Suppress("SwallowedException")
Expand Down
4 changes: 2 additions & 2 deletions src/test/kotlin/io/snyk/plugin/ui/UIUtilsTest.kt
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
package io.snyk.plugin.ui

import com.intellij.ui.components.ActionLink
import org.junit.Test
import javax.swing.JLabel

class UIUtilsTest {

@Test
fun `descriptionHeaderPanel should not fail with customLabels`() {
descriptionHeaderPanel(
issueNaming = "test naming",
customLabels = (1..10).toList().map { JLabel(it.toString()) }
customLabels = (1..10).toList().map { ActionLink(it.toString()) }
)
}
}
66 changes: 10 additions & 56 deletions src/test/kotlin/io/snyk/plugin/ui/toolwindow/LabelProviderTest.kt
Original file line number Diff line number Diff line change
@@ -1,96 +1,65 @@
package io.snyk.plugin.ui.toolwindow

import com.intellij.ui.components.labels.LinkLabel
import io.mockk.mockkStatic
import io.mockk.slot
import io.mockk.unmockkAll
import io.mockk.verify
import com.intellij.ui.components.ActionLink
import junit.framework.TestCase.assertEquals
import junit.framework.TestCase.assertTrue
import org.junit.After
import org.junit.Before
import org.junit.Test
import java.net.URL
import javax.swing.JLabel

class LabelProviderTest {
@Before
fun setUp() {
unmockkAll()
// test URL - unfortunately, LinkLabel does not provide an easy way to verify
// the link action, so we're using a static mock of the create method to check the action
mockkStatic(LinkLabel::class)
}

@After
fun tearDown() {
unmockkAll()
}

@Test
fun `getDependencyLabel should provide a label with a clickable link to package at npmBaseUrl for npm packages`() {
val packageName = "packageName"

val label: JLabel = LabelProvider().getDependencyLabel("npm", packageName)
val label: ActionLink = LabelProvider().getDependencyLabel("npm", packageName)

assertTrue("Expected LinkLabel, but got ${label::class}", label is LinkLabel<*>)
assertEquals(packageName, label.text)
verifyLinkLabelCreated(LabelProvider.npmBaseUrl + "/$packageName")
}

@Test
fun `getDependencyLabel should provide a plain text label for non-npm packages`() {
val packageName = "package"

val output: JLabel = LabelProvider().getDependencyLabel("maven", packageName)
val output: ActionLink = LabelProvider().getDependencyLabel("maven", packageName)

assertEquals(JLabel::class, output::class)
assertEquals(packageName, output.text)
}

@Test
fun `getCWELabel should provide a label with a clickable link to the CWE info at cweBaseUrl`() {
val cwe = "CWE-400"

val output: JLabel = LabelProvider().getCWELabel(cwe)
val output: ActionLink = LabelProvider().getCWELabel(cwe)

assertEquals(LinkLabel::class, output::class)
assertEquals(cwe, output.text)
verifyLinkLabelCreated(LabelProvider.CWE_BASE_URL + "/${cwe.removePrefix("CWE-")}.html")
}

@Test
fun `getCVELabel should provide a label with a clickable link to the CVE info at cveBaseUrl`() {
val cve = "CVE123"

val output: JLabel = LabelProvider().getCVELabel(cve)
val output: ActionLink = LabelProvider().getCVELabel(cve)

assertEquals(LinkLabel::class, output::class)
assertEquals(cve, output.text)
verifyLinkLabelCreated(LabelProvider.CVE_BASE_URL + "=$cve")
}

@Test
fun `getVulnerability should provide a label with a clickable link to the vulnerability at vulnerabilityBaseUrl`() {
val id = "VULN123"

val output: JLabel = LabelProvider().getVulnerabilityLabel(id)
val output: ActionLink = LabelProvider().getVulnerabilityLabel(id)

assertEquals(LinkLabel::class, output::class)
assertEquals(id, output.text)
verifyLinkLabelCreated(LabelProvider.VULNERABILITY_BASE_URL + "/$id")
}

@Test
fun `getVulnerability should provide a label with a explicit link if provided`() {
val id = "VULN123"
val url = "https://some.link"

val output: JLabel = LabelProvider().getVulnerabilityLabel(id, url)
val output: ActionLink = LabelProvider().getVulnerabilityLabel(id, url)

assertEquals(LinkLabel::class, output::class)
assertEquals(id, output.text)
verifyLinkLabelCreated(url)
}

@Test
Expand All @@ -99,40 +68,25 @@ class LabelProviderTest {

val output = LabelProvider().getVulnerabilityLabel(id)

assertEquals(LinkLabel::class, output::class)
assertEquals(id.toUpperCase(), output.text)
verifyLinkLabelCreated(LabelProvider.VULNERABILITY_BASE_URL + "/$id")
assertEquals(id.uppercase(), output.text)
}

@Test
fun `getCVSSLabel should provide a label with a clickable link to the CVSS scoring calculator for this score`() {
val cvssText = "package"
val cvssId = "1"
val output: JLabel = LabelProvider().getCVSSLabel(cvssText, cvssId)
val output: ActionLink = LabelProvider().getCVSSLabel(cvssText, cvssId)

assertEquals(LinkLabel::class, output::class)
assertEquals(cvssText, output.text)

verifyLinkLabelCreated(LabelProvider.CVSS_BASE_URL + "#$cvssId")
}

@Test
fun `getLinkLabel should provide a label with a clickable link`() {
val url = "https://snyk.io/reference"
val text = "reference"

val label: JLabel = LabelProvider().createActionLink(URL(url), text)
val label: ActionLink = LabelProvider().createActionLink(URL(url), text)

assertEquals(text, label.text)
verifyLinkLabelCreated(url)
}

private fun verifyLinkLabelCreated(expectedUrl: String) {
val actionSlot = slot<Runnable>()
verify {
LinkLabel.create(any(), capture(actionSlot))
}
val actualUrl = (actionSlot.captured as LabelProvider.OpenLinkAction).url.toExternalForm()
assertEquals(expectedUrl, actualUrl)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ import snyk.iac.ui.toolwindow.IacFileTreeNode
import snyk.iac.ui.toolwindow.IacIssueTreeNode
import snyk.oss.Vulnerability
import snyk.trust.confirmScanningAndSetWorkspaceTrustedStateIfNeeded
import java.nio.charset.Charset
import javax.swing.JButton
import javax.swing.JEditorPane
import javax.swing.JLabel
Expand Down Expand Up @@ -172,10 +173,11 @@ class SnykToolWindowPanelIntegTest : HeavyPlatformTestCase() {
}

private fun prepareTreeWithFakeCodeResults() {
val virtualFile = super.createTempVirtualFile("test.js", null, "test", Charset.defaultCharset())
val codeResults = SnykCodeResults(
mapOf(
Pair(
SnykCodeFile(project, mockk(relaxed = true)),
SnykCodeFile(project, virtualFile),
listOf(fakeSuggestionForFile)
)
)
Expand Down Expand Up @@ -368,7 +370,7 @@ class SnykToolWindowPanelIntegTest : HeavyPlatformTestCase() {
impact = ""
)
val iacIssuesForFile =
IacIssuesForFile(listOf(iacIssue), "k8s-deployment.yaml", "src/k8s-deployment.yaml", "npm")
IacIssuesForFile(listOf(iacIssue), "k8s-deployment.yaml", "src/k8s-deployment.yaml", "npm", null, project)
val jsonError = SnykError("Failed to parse JSON file", project.basePath.toString(), 1021)
val iacResult = IacResult(listOf(iacIssuesForFile), listOf(jsonError))
scanPublisher.scanningIacFinished(iacResult)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
package io.snyk.plugin.ui.toolwindow

import com.google.gson.Gson
import com.intellij.ui.components.labels.LinkLabel
import com.intellij.ui.components.ActionLink
import io.snyk.plugin.ui.toolwindow.panels.VulnerabilityDescriptionPanel
import junit.framework.TestCase.assertEquals
import junit.framework.TestCase.assertNotNull
import org.junit.Before
import org.junit.Test
import snyk.UIComponentFinder.getJLabelByText
import snyk.UIComponentFinder.getJButtonByText
import snyk.oss.Vulnerability
import java.io.FileReader
import javax.swing.JLabel

class VulnerabilityDescriptionPanelTest {
private lateinit var cut: VulnerabilityDescriptionPanel
Expand All @@ -27,26 +26,26 @@ class VulnerabilityDescriptionPanelTest {
@Test
fun `constructor should build panel with npm introduced-from info as link label`() {
val introducingDependency = vulnerability.from[1]
val actual = getJLabelByText(cut, introducingDependency)
val actual = getJButtonByText(cut, introducingDependency)
assertNotNull(actual)
assertEquals(LinkLabel::class, actual!!::class)
assertEquals(ActionLink::class, actual!!::class)
}

@Test
fun `constructor should build panel with non-npm introduced-from info as plain text label`() {
val introducingDependency = vulnerability.from[1]
vulnerability = vulnerability.copy(packageManager = "not npm!")
cut = VulnerabilityDescriptionPanel(listOf(vulnerability))
val actual = getJLabelByText(cut, introducingDependency)
val actual = getJButtonByText(cut, introducingDependency)
assertNotNull(actual)
assertEquals(JLabel::class, actual!!::class)
assertEquals(ActionLink::class, actual!!::class)
}

@Test
fun `constructor should build panel with all CWEs as link labels`() {
val cwes = vulnerability.identifiers!!.cwe
cwes.forEach { cwe ->
val actual = getJLabelByText(cut, cwe)
val actual = getJButtonByText(cut, cwe)
assertNotNull("Expected to find label for $cwe, but was null", actual)
}
}
Expand Down
Loading

0 comments on commit adff7aa

Please sign in to comment.