diff --git a/gradle.properties b/gradle.properties index 91d0be009..8901ab96c 100644 --- a/gradle.properties +++ b/gradle.properties @@ -4,7 +4,7 @@ pluginName=Snyk Security # for insight into build numbers and IntelliJ Platform versions # see https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html pluginSinceBuild=233 -pluginUntilBuild=233.* +pluginUntilBuild=241.* platformVersion=2023.3 platformDownloadSources=true @@ -13,7 +13,7 @@ platformDownloadSources=true # see https://plugins.jetbrains.com/docs/intellij/plugin-dependencies.html platformPlugins=org.intellij.plugins.hcl:233.11799.172,org.jetbrains.plugins.yaml,org.jetbrains.kotlin,com.intellij.java,org.intellij.groovy # list of versions for which to check the plugin for api compatibility -pluginVerifierIdeVersions=2023.3 +pluginVerifierIdeVersions=2023.3,2024.1 localIdeDirectory= # opt-out flag for bundling Kotlin standard library # see https://plugins.jetbrains.com/docs/intellij/kotlin.html#kotlin-standard-library diff --git a/src/main/kotlin/io/snyk/plugin/services/SnykCliAuthenticationService.kt b/src/main/kotlin/io/snyk/plugin/services/SnykCliAuthenticationService.kt index 4ba98d5e1..33739f5fd 100644 --- a/src/main/kotlin/io/snyk/plugin/services/SnykCliAuthenticationService.kt +++ b/src/main/kotlin/io/snyk/plugin/services/SnykCliAuthenticationService.kt @@ -23,6 +23,7 @@ import io.snyk.plugin.ui.getReadOnlyClickableHtmlJEditorPane import org.apache.commons.text.StringEscapeUtils.escapeHtml4 import snyk.common.getEndpointUrl import snyk.common.isOauth +import snyk.common.lsp.LanguageServerWrapper import java.awt.BorderLayout import java.awt.Dimension import java.awt.datatransfer.StringSelection @@ -47,7 +48,7 @@ class SnykCliAuthenticationService(val project: Project) { downloadCliIfNeeded() if (getCliFile().exists()) executeAuthCommand() if (isAuthenticated) executeGetConfigApiCommand() - + LanguageServerWrapper.getInstance().updateConfiguration() return token } diff --git a/src/main/kotlin/io/snyk/plugin/ui/SnykSettingsDialog.kt b/src/main/kotlin/io/snyk/plugin/ui/SnykSettingsDialog.kt index 5f22933c4..d1736e73a 100644 --- a/src/main/kotlin/io/snyk/plugin/ui/SnykSettingsDialog.kt +++ b/src/main/kotlin/io/snyk/plugin/ui/SnykSettingsDialog.kt @@ -15,12 +15,14 @@ import com.intellij.ui.ContextHelpLabel import com.intellij.ui.DocumentAdapter import com.intellij.ui.IdeBorderFactory import com.intellij.ui.components.JBPasswordField +import com.intellij.ui.components.JBTextField import com.intellij.ui.components.fields.ExpandableTextField +import com.intellij.ui.dsl.builder.AlignX +import com.intellij.ui.dsl.builder.panel import com.intellij.uiDesigner.core.Spacer import com.intellij.util.Alarm import com.intellij.util.FontUtil import com.intellij.util.ui.GridBag -import com.intellij.util.ui.UI import io.snyk.plugin.events.SnykCliDownloadListener import io.snyk.plugin.getCliFile import io.snyk.plugin.getSnykCliAuthenticationService @@ -84,7 +86,7 @@ class SnykSettingsDialog( private val manageBinariesAutomatically: JCheckBox = JCheckBox() private val cliPathTextBoxWithFileBrowser = TextFieldWithBrowseButton() - private val cliBaseDownloadUrlTextField = JTextField() + private val cliBaseDownloadUrlTextField = JBTextField() private val logger = Logger.getInstance(this::class.java) @@ -522,33 +524,44 @@ class SnykSettingsDialog( cliBaseDownloadUrlTextField.toolTipText = "The default URL is https://static.snyk.io. " + "for FIPS-enabled CLIs (only available for Windows and Linux), please use https://static.snyk.io/fips" - executableSettingsPanel.add( - UI.PanelFactory - .panel(cliBaseDownloadUrlTextField) - .withLabel("Base URL to download the CLI: ").createPanel(), - gb.nextLine() - ) + val cliBaseDownloadPanel = panel { + row { + label("Base URL to download the CLI: ") + cell(cliBaseDownloadUrlTextField).align(AlignX.FILL) + } + } + executableSettingsPanel.add(cliBaseDownloadPanel, gb.nextLine()) cliPathTextBoxWithFileBrowser.toolTipText = "The default path is ${getCliFile().canonicalPath}." val descriptor = FileChooserDescriptor(true, false, false, false, false, false) cliPathTextBoxWithFileBrowser.addBrowseFolderListener( - "", "Please choose the Snyk CLI you want to use:", null, + "", + "Please choose the Snyk CLI you want to use:", + null, descriptor, TextComponentAccessor.TEXT_FIELD_WHOLE_TEXT ) executableSettingsPanel.add( - UI.PanelFactory - .panel(cliPathTextBoxWithFileBrowser) - .withLabel("Path to Snyk CLI: ").createPanel(), + panel { + row { + label("Path to Snyk CLI: ") + cell(cliPathTextBoxWithFileBrowser).align(AlignX.FILL) + } + }, gb.nextLine() ) - manageBinariesAutomatically.text = "Automatically manage needed binaries" executableSettingsPanel.add( - manageBinariesAutomatically, + panel { + row { + label("Automatically manage needed binaries: ") + cell(manageBinariesAutomatically).align(AlignX.FILL) + } + }, gb.nextLine() ) + val descriptionLabelManageBinaries = JLabel( "These options allow you to customize the handling, where and how plugin " + @@ -598,14 +611,16 @@ class SnykSettingsDialog( } private fun setupValidation(textField: JTextField, message: String, isValidText: (sourceStr: String?) -> Boolean) { - ComponentValidator(rootPanel).withValidator(Supplier { - val validationInfo: ValidationInfo = if (!isValidText(textField.text)) { - ValidationInfo(message, textField) - } else { - ValidationInfo("") + ComponentValidator(rootPanel).withValidator( + Supplier { + val validationInfo: ValidationInfo = if (!isValidText(textField.text)) { + ValidationInfo(message, textField) + } else { + ValidationInfo("") + } + validationInfo } - validationInfo - }).installOn(textField) + ).installOn(textField) textField.document.addDocumentListener(object : DocumentAdapter() { override fun textChanged(event: DocumentEvent) { diff --git a/src/main/kotlin/io/snyk/plugin/ui/settings/IssueViewOptionsPanel.kt b/src/main/kotlin/io/snyk/plugin/ui/settings/IssueViewOptionsPanel.kt index 7998ccac4..97ba345b9 100644 --- a/src/main/kotlin/io/snyk/plugin/ui/settings/IssueViewOptionsPanel.kt +++ b/src/main/kotlin/io/snyk/plugin/ui/settings/IssueViewOptionsPanel.kt @@ -2,7 +2,6 @@ package io.snyk.plugin.ui.settings import com.intellij.openapi.project.Project import com.intellij.ui.components.JBCheckBox -import com.intellij.ui.layout.panel import com.intellij.util.ui.JBUI import io.snyk.plugin.getSnykTaskQueueService import io.snyk.plugin.pluginSettings @@ -14,45 +13,34 @@ class IssueViewOptionsPanel( private val settings get() = pluginSettings() - private var currentOpenIssuesEnabled = settings.openIssuesEnabled - private var currentIgnoredIssuesEnabled = settings.ignoredIssuesEnabled - - val panel = panel { + val panel = com.intellij.ui.dsl.builder.panel { row { - cell { - checkBox( - text = "Open issues", - getter = { settings.openIssuesEnabled }, - setter = { settings.openIssuesEnabled = it } - ).component.apply { - this.addItemListener { - if (canOptionChange(this, currentOpenIssuesEnabled)) { - currentOpenIssuesEnabled = this.isSelected - settings.openIssuesEnabled = currentOpenIssuesEnabled - getSnykTaskQueueService(project)?.scan() - } + checkBox( + text = "Open issues", + ).component.apply { + isSelected = settings.openIssuesEnabled + this.addItemListener { + if (canOptionChange(this, settings.openIssuesEnabled)) { + settings.openIssuesEnabled = this.isSelected + getSnykTaskQueueService(project)?.scan() } - name = "Open issues" } + name = "Open issues" } } row { - cell { checkBox( text = "Ignored issues", - getter = { settings.ignoredIssuesEnabled }, - setter = { settings.ignoredIssuesEnabled = it } ).component.apply { + isSelected = settings.ignoredIssuesEnabled this.addItemListener { - if (canOptionChange(this, currentIgnoredIssuesEnabled)) { - currentIgnoredIssuesEnabled = this.isSelected - settings.ignoredIssuesEnabled =currentIgnoredIssuesEnabled + if (canOptionChange(this, settings.ignoredIssuesEnabled)) { + settings.ignoredIssuesEnabled = this.isSelected getSnykTaskQueueService(project)?.scan() } } name = "Ignored issues" } - } } }.apply { name = "issueViewPanel" @@ -61,8 +49,8 @@ class IssueViewOptionsPanel( private fun canOptionChange(component: JBCheckBox, wasEnabled: Boolean): Boolean { val onlyOneEnabled = arrayOf( - currentOpenIssuesEnabled, - currentIgnoredIssuesEnabled, + settings.openIssuesEnabled, + settings.ignoredIssuesEnabled, ).count { it } == 1 if (onlyOneEnabled && wasEnabled) { diff --git a/src/main/kotlin/io/snyk/plugin/ui/settings/SeveritiesEnablementPanel.kt b/src/main/kotlin/io/snyk/plugin/ui/settings/SeveritiesEnablementPanel.kt index d2a8a565c..34f9240f9 100644 --- a/src/main/kotlin/io/snyk/plugin/ui/settings/SeveritiesEnablementPanel.kt +++ b/src/main/kotlin/io/snyk/plugin/ui/settings/SeveritiesEnablementPanel.kt @@ -1,11 +1,12 @@ package io.snyk.plugin.ui.settings import com.intellij.ui.components.JBCheckBox -import com.intellij.ui.layout.panel +import com.intellij.ui.dsl.builder.panel import com.intellij.util.ui.JBUI import io.snyk.plugin.Severity import io.snyk.plugin.pluginSettings import io.snyk.plugin.ui.SnykBalloonNotificationHelper +import java.awt.event.ItemEvent class SeveritiesEnablementPanel { private val settings @@ -18,62 +19,42 @@ class SeveritiesEnablementPanel { val panel = panel { row { - cell { - checkBox( - text = Severity.CRITICAL.toPresentableString(), - getter = { settings.criticalSeverityEnabled }, - setter = { settings.criticalSeverityEnabled = it } - ).component.apply { - this.addItemListener { - isLastSeverityDisabling(this, currentCriticalSeverityEnabled) - currentCriticalSeverityEnabled = this.isSelected - } - name = Severity.CRITICAL.toPresentableString() + checkBox(Severity.CRITICAL.toPresentableString()).applyToComponent { + name = text + isSelected = settings.criticalSeverityEnabled + this.addItemListener { + correctLastSeverityDisabled(it) + settings.criticalSeverityEnabled = this.isSelected } } } row { - cell { - checkBox( - text = Severity.HIGH.toPresentableString(), - getter = { settings.highSeverityEnabled }, - setter = { settings.highSeverityEnabled = it } - ).component.apply { - this.addItemListener { - isLastSeverityDisabling(this, currentHighSeverityEnabled) - currentHighSeverityEnabled = this.isSelected - } - name = Severity.HIGH.toPresentableString() + checkBox(Severity.HIGH.toPresentableString()).applyToComponent { + name = text + isSelected = settings.highSeverityEnabled + this.addItemListener { + correctLastSeverityDisabled(it) + settings.highSeverityEnabled = this.isSelected } } } row { - cell { - checkBox( - text = Severity.MEDIUM.toPresentableString(), - getter = { settings.mediumSeverityEnabled }, - setter = { settings.mediumSeverityEnabled = it } - ).component.apply { - this.addItemListener { - isLastSeverityDisabling(this, currentMediumSeverityEnabled) - currentMediumSeverityEnabled = this.isSelected - } - name = Severity.MEDIUM.toPresentableString() + checkBox(Severity.MEDIUM.toPresentableString()).applyToComponent { + name = text + isSelected = settings.mediumSeverityEnabled + this.addItemListener { + correctLastSeverityDisabled(it) + settings.mediumSeverityEnabled = this.isSelected } } } row { - cell { - checkBox( - text = Severity.LOW.toPresentableString(), - getter = { settings.lowSeverityEnabled }, - setter = { settings.lowSeverityEnabled = it } - ).component.apply { - this.addItemListener { - isLastSeverityDisabling(this, currentLowSeverityEnabled) - currentLowSeverityEnabled = this.isSelected - } - name = Severity.LOW.toPresentableString() + checkBox(Severity.LOW.toPresentableString()).applyToComponent { + name = text + isSelected = settings.lowSeverityEnabled + this.addItemListener { + correctLastSeverityDisabled(it) + settings.lowSeverityEnabled = this.isSelected } } } @@ -82,6 +63,11 @@ class SeveritiesEnablementPanel { border = JBUI.Borders.empty(2) } + private fun JBCheckBox.correctLastSeverityDisabled(it: ItemEvent) { + val deselected = it.stateChange == ItemEvent.DESELECTED + isLastSeverityDisabling(this, deselected) + } + private fun isLastSeverityDisabling(component: JBCheckBox, wasEnabled: Boolean): Boolean { val onlyOneEnabled = arrayOf( currentCriticalSeverityEnabled, diff --git a/src/main/kotlin/io/snyk/plugin/ui/toolwindow/SnykPluginDisposable.kt b/src/main/kotlin/io/snyk/plugin/ui/toolwindow/SnykPluginDisposable.kt new file mode 100644 index 000000000..a1eef35a9 --- /dev/null +++ b/src/main/kotlin/io/snyk/plugin/ui/toolwindow/SnykPluginDisposable.kt @@ -0,0 +1,28 @@ +package io.snyk.plugin.ui.toolwindow + +import com.intellij.openapi.Disposable +import com.intellij.openapi.application.ApplicationManager +import com.intellij.openapi.components.Service +import com.intellij.openapi.project.Project +import org.jetbrains.annotations.NotNull + + +/** + * Top-Level disposable for the Snyk plugin. + */ +@Service(Service.Level.APP, Service.Level.PROJECT) +class SnykPluginDisposable : Disposable { + companion object { + @NotNull + fun getInstance(): Disposable { + return ApplicationManager.getApplication().getService(SnykPluginDisposable::class.java) + } + + @NotNull + fun getInstance(@NotNull project: Project): Disposable { + return project.getService(SnykPluginDisposable::class.java) + } + } + + override fun dispose() = Unit +} diff --git a/src/main/kotlin/io/snyk/plugin/ui/toolwindow/SnykToolWindow.kt b/src/main/kotlin/io/snyk/plugin/ui/toolwindow/SnykToolWindow.kt index 1b9ef3598..a28a2f9a3 100644 --- a/src/main/kotlin/io/snyk/plugin/ui/toolwindow/SnykToolWindow.kt +++ b/src/main/kotlin/io/snyk/plugin/ui/toolwindow/SnykToolWindow.kt @@ -101,7 +101,10 @@ class SnykToolWindow(private val project: Project) : SimpleToolWindowPanel(false private fun updateActionsPresentation() = ApplicationManager.getApplication().invokeLater { actionToolbar.updateActionsImmediately() } - override fun dispose() = Unit + var isDisposed = false + override fun dispose() { + isDisposed = true + } inner class ExpandNodeChildAction( val tree: JTree diff --git a/src/main/kotlin/io/snyk/plugin/ui/toolwindow/SnykToolWindowFactory.kt b/src/main/kotlin/io/snyk/plugin/ui/toolwindow/SnykToolWindowFactory.kt index 21fa47c81..412922cfd 100644 --- a/src/main/kotlin/io/snyk/plugin/ui/toolwindow/SnykToolWindowFactory.kt +++ b/src/main/kotlin/io/snyk/plugin/ui/toolwindow/SnykToolWindowFactory.kt @@ -5,6 +5,7 @@ import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.ToolWindowFactory +import io.snyk.plugin.pluginSettings /** * IntelliJ ToolWindowFactory for Snyk plugin. @@ -13,11 +14,10 @@ class SnykToolWindowFactory : ToolWindowFactory, DumbAware { override fun createToolWindowContent(project: Project, toolWindow: ToolWindow) { val toolWindowPanel = SnykToolWindow(project) + Disposer.register(SnykPluginDisposable.getInstance(), toolWindowPanel) val contentManager = toolWindow.contentManager val content = contentManager.factory.createContent(toolWindowPanel, null, false) contentManager.addContent(content) - - Disposer.register(project, toolWindowPanel) } companion object { diff --git a/src/main/kotlin/io/snyk/plugin/ui/toolwindow/SnykToolWindowPanel.kt b/src/main/kotlin/io/snyk/plugin/ui/toolwindow/SnykToolWindowPanel.kt index 83207e65d..b35a4828f 100644 --- a/src/main/kotlin/io/snyk/plugin/ui/toolwindow/SnykToolWindowPanel.kt +++ b/src/main/kotlin/io/snyk/plugin/ui/toolwindow/SnykToolWindowPanel.kt @@ -15,7 +15,9 @@ import com.intellij.openapi.vfs.VirtualFileManager import com.intellij.psi.PsiManager import com.intellij.ui.OnePixelSplitter import com.intellij.ui.TreeSpeedSearch +import com.intellij.ui.TreeUIHelper import com.intellij.ui.treeStructure.Tree +import com.intellij.util.containers.Convertor import com.intellij.util.ui.tree.TreeUtil import io.snyk.plugin.Severity import io.snyk.plugin.analytics.getSelectedProducts @@ -110,7 +112,7 @@ import javax.swing.tree.TreePath /** * Main panel for Snyk tool window. */ -@Service +@Service(Service.Level.PROJECT) class SnykToolWindowPanel(val project: Project) : JPanel(), Disposable { private val descriptionPanel = SimpleToolWindowPanel(true, true).apply { name = "descriptionPanel" } private val logger = Logger.getInstance(this::class.java) @@ -147,10 +149,14 @@ class SnykToolWindowPanel(val project: Project) : JPanel(), Disposable { init { vulnerabilitiesTree.cellRenderer = SnykTreeCellRenderer() layout = BorderLayout() - TreeSpeedSearch(vulnerabilitiesTree, TreeSpeedSearch.NODE_DESCRIPTOR_TOSTRING, true) - createTreeAndDescriptionPanel() + // convertor interface seems to be still used in TreeSpeedSearch, although it's marked obsolete + val convertor = Convertor { + TreeSpeedSearch.NODE_PRESENTATION_FUNCTION.apply(it) + } + TreeUIHelper.getInstance().installTreeSpeedSearch(vulnerabilitiesTree, convertor, true) + createTreeAndDescriptionPanel() chooseMainPanelToDisplay() vulnerabilitiesTree.selectionModel.addTreeSelectionListener { @@ -428,7 +434,10 @@ class SnykToolWindowPanel(val project: Project) : JPanel(), Disposable { } } - override fun dispose() {} + var isDisposed: Boolean = false + override fun dispose() { + isDisposed = true + } fun cleanUiAndCaches() { getSnykCachedResults(project)?.cleanCaches() @@ -516,7 +525,7 @@ class SnykToolWindowPanel(val project: Project) : JPanel(), Disposable { } fun displayAuthPanel() { - if (Disposer.isDisposed(this)) return + if (isDisposed) return doCleanUi(false) descriptionPanel.removeAll() val authPanel = SnykAuthPanel(project) @@ -1102,6 +1111,7 @@ class SnykToolWindowPanel(val project: Project) : JPanel(), Disposable { } } + @Suppress("UNCHECKED_CAST") fun selectNodeAndDisplayDescription(vulnerability: Vulnerability) = selectAndDisplayNodeWithIssueDescription { treeNode -> treeNode is VulnerabilityTreeNode && @@ -1122,6 +1132,7 @@ class SnykToolWindowPanel(val project: Project) : JPanel(), Disposable { (treeNode.userObject as ContainerIssuesForImage) == issuesForImage } + @Suppress("UNCHECKED_CAST") fun selectNodeAndDisplayDescription(suggestionForFile: SuggestionForFile, textRange: MyTextRange) = selectAndDisplayNodeWithIssueDescription { treeNode -> treeNode is SuggestionTreeNode && diff --git a/src/main/kotlin/io/snyk/plugin/ui/toolwindow/panels/StatePanel.kt b/src/main/kotlin/io/snyk/plugin/ui/toolwindow/panels/StatePanel.kt index 822263459..f256d5520 100644 --- a/src/main/kotlin/io/snyk/plugin/ui/toolwindow/panels/StatePanel.kt +++ b/src/main/kotlin/io/snyk/plugin/ui/toolwindow/panels/StatePanel.kt @@ -1,16 +1,17 @@ package io.snyk.plugin.ui.toolwindow.panels -import com.intellij.ui.components.labels.LinkLabel +import com.intellij.ui.components.ActionLink import com.intellij.uiDesigner.core.GridLayoutManager +import com.intellij.util.ui.JBUI import io.snyk.plugin.ui.addSpacer import io.snyk.plugin.ui.baseGridConstraints import io.snyk.plugin.ui.getReadOnlyClickableHtmlJEditorPaneFixedSize -import java.awt.Insets +import java.awt.event.ActionEvent import javax.swing.JPanel -class StatePanel(messageHtmlText: String, actionText: String? = null, action: (() -> Unit)? = null) : JPanel() { +class StatePanel(messageHtmlText: String, actionText: String? = null, action: ((e: ActionEvent) -> Unit)? = null) : JPanel() { init { - layout = GridLayoutManager(4, 1, Insets(20, 100, 20, 100), -1, -1) + layout = GridLayoutManager(4, 1, JBUI.insets(20, 100), -1, -1) add( getReadOnlyClickableHtmlJEditorPaneFixedSize(messageHtmlText), @@ -19,7 +20,7 @@ class StatePanel(messageHtmlText: String, actionText: String? = null, action: (( if (actionText != null && action != null) { add( - LinkLabel.create(actionText, action), + ActionLink(actionText, action), baseGridConstraints(row = 2, indent = 0) ) } diff --git a/src/main/kotlin/io/snyk/plugin/ui/toolwindow/panels/SuggestionDescriptionPanel.kt b/src/main/kotlin/io/snyk/plugin/ui/toolwindow/panels/SuggestionDescriptionPanel.kt index e6d83aa27..973bfe38f 100644 --- a/src/main/kotlin/io/snyk/plugin/ui/toolwindow/panels/SuggestionDescriptionPanel.kt +++ b/src/main/kotlin/io/snyk/plugin/ui/toolwindow/panels/SuggestionDescriptionPanel.kt @@ -94,6 +94,7 @@ class SuggestionDescriptionPanel( } } + @Suppress("DuplicatedCode") // ok, as we'll delete this class soon private fun linkLabel( beforeLinkText: String = "", linkText: String, @@ -103,7 +104,7 @@ class SuggestionDescriptionPanel( onClick: (HyperlinkEvent) -> Unit ): HyperlinkLabel { return HyperlinkLabel().apply { - this.setHyperlinkText(beforeLinkText, linkText, afterLinkText) + this.setTextWithHyperlink("$beforeLinkText$linkText$afterLinkText") this.toolTipText = toolTipText this.font = io.snyk.plugin.ui.getFont(-1, 14, customFont ?: font) addHyperlinkListener { diff --git a/src/main/kotlin/io/snyk/plugin/ui/toolwindow/panels/VulnerabilityDescriptionPanel.kt b/src/main/kotlin/io/snyk/plugin/ui/toolwindow/panels/VulnerabilityDescriptionPanel.kt index 9ec35659b..02e0d7b2d 100644 --- a/src/main/kotlin/io/snyk/plugin/ui/toolwindow/panels/VulnerabilityDescriptionPanel.kt +++ b/src/main/kotlin/io/snyk/plugin/ui/toolwindow/panels/VulnerabilityDescriptionPanel.kt @@ -1,7 +1,8 @@ package io.snyk.plugin.ui.toolwindow.panels -import com.intellij.ui.components.labels.LinkLabel +import com.intellij.ui.components.ActionLink import com.intellij.uiDesigner.core.GridLayoutManager +import com.intellij.util.ui.JBUI import io.snyk.plugin.ui.DescriptionHeaderPanel import io.snyk.plugin.ui.addRowOfItemsToPanel import io.snyk.plugin.ui.baseGridConstraintsAnchorWest @@ -14,7 +15,6 @@ import io.snyk.plugin.ui.toolwindow.LabelProvider import org.commonmark.parser.Parser import org.commonmark.renderer.html.HtmlRenderer import snyk.oss.Vulnerability -import java.awt.Insets import javax.swing.JLabel import javax.swing.JPanel @@ -32,7 +32,7 @@ class VulnerabilityDescriptionPanel( override fun createMainBodyPanel(): Pair { val lastRowToAddSpacer = 4 val panel = JPanel( - GridLayoutManager(lastRowToAddSpacer + 1, 1, Insets(0, 10, 20, 20), -1, 10) + GridLayoutManager(lastRowToAddSpacer + 1, 1, JBUI.insets(0, 10, 20, 20), -1, 10) ).apply { this.add( getMainBodyPanel(), @@ -52,7 +52,7 @@ class VulnerabilityDescriptionPanel( private fun getMainBodyPanel(): JPanel { val panel = JPanel() - panel.layout = GridLayoutManager(11, 2, Insets(10, 0, 20, 0), 30, -1) + panel.layout = GridLayoutManager(11, 2, JBUI.insets(10, 0, 20, 0), 30, -1) panel.add( boldLabel("Vulnerable module:"), @@ -118,7 +118,7 @@ class VulnerabilityDescriptionPanel( val panel = JPanel() val packageManager = groupedVulns.first().packageManager - panel.layout = GridLayoutManager(1, intros.size * 2, Insets(0, 0, 0, 0), 0, 0) + panel.layout = GridLayoutManager(1, intros.size * 2, JBUI.emptyInsets(), 0, 0) addRowOfItemsToPanel( panel = panel, @@ -133,7 +133,7 @@ class VulnerabilityDescriptionPanel( private fun getDetailedPathsPanel(): JPanel { val detailsPanel = JPanel() - detailsPanel.layout = GridLayoutManager(2, 2, Insets(0, 0, 0, 0), -1, -1) + detailsPanel.layout = GridLayoutManager(2, 2, JBUI.emptyInsets(), -1, -1) detailsPanel.add( boldLabel("Detailed paths").apply { @@ -156,13 +156,13 @@ class VulnerabilityDescriptionPanel( private fun getInnerDetailedPathsPanel(itemsToShow: Int? = null): JPanel { val detailsPanel = JPanel() - detailsPanel.layout = GridLayoutManager(groupedVulns.size + 2, 2, Insets(0, 0, 0, 0), -1, -1) + detailsPanel.layout = GridLayoutManager(groupedVulns.size + 2, 2, JBUI.emptyInsets(), -1, -1) groupedVulns .take(itemsToShow ?: groupedVulns.size) .forEachIndexed { index, vuln -> val detailPanel = JPanel() - detailPanel.layout = GridLayoutManager(2, 2, Insets(0, 0, 0, 0), 30, 0) + detailPanel.layout = GridLayoutManager(2, 2, JBUI.emptyInsets(), 30, 0) insertTitleAndResizableTextIntoPanelColumns( panel = detailPanel, @@ -191,7 +191,7 @@ class VulnerabilityDescriptionPanel( } if (itemsToShow != null && itemsToShow < groupedVulns.size) { - val showMoreLabel = LinkLabel.create("...and ${groupedVulns.size - itemsToShow} more") { + val showMoreLabel = ActionLink("...and ${groupedVulns.size - itemsToShow} more") { detailsPanel.removeAll() detailsPanel.add( getInnerDetailedPathsPanel(), @@ -211,7 +211,7 @@ class VulnerabilityDescriptionPanel( private fun getOverviewPanel(): JPanel { val overviewPanel = JPanel() - overviewPanel.layout = GridLayoutManager(2, 1, Insets(0, 5, 0, 0), -1, 0) + overviewPanel.layout = GridLayoutManager(2, 1, JBUI.insetsLeft(5), -1, 0) val descriptionPane = getReadOnlyClickableHtmlJEditorPane(getDescriptionAsHtml()) diff --git a/src/main/kotlin/snyk/container/ui/ContainerIssueDetailPanel.kt b/src/main/kotlin/snyk/container/ui/ContainerIssueDetailPanel.kt index aa5ca7e0b..d8ffa1951 100644 --- a/src/main/kotlin/snyk/container/ui/ContainerIssueDetailPanel.kt +++ b/src/main/kotlin/snyk/container/ui/ContainerIssueDetailPanel.kt @@ -1,7 +1,8 @@ package snyk.container.ui -import com.intellij.ui.components.labels.LinkLabel +import com.intellij.ui.components.ActionLink import com.intellij.uiDesigner.core.GridLayoutManager +import com.intellij.util.ui.JBUI import io.snyk.plugin.ui.DescriptionHeaderPanel import io.snyk.plugin.ui.baseGridConstraintsAnchorWest import io.snyk.plugin.ui.boldLabel @@ -13,7 +14,6 @@ import io.snyk.plugin.ui.toolwindow.panels.IssueDescriptionPanelBase import org.commonmark.parser.Parser import org.commonmark.renderer.html.HtmlRenderer import snyk.container.ContainerIssue -import java.awt.Insets import javax.swing.JPanel class ContainerIssueDetailPanel( @@ -29,7 +29,7 @@ class ContainerIssueDetailPanel( override fun createMainBodyPanel(): Pair { val lastRowToAddSpacer = 4 val panel = JPanel( - GridLayoutManager(lastRowToAddSpacer + 1, 1, Insets(10, 10, 20, 20), -1, 10) + GridLayoutManager(lastRowToAddSpacer + 1, 1, JBUI.insets(10, 10, 20, 20), -1, 10) ) panel.add( @@ -61,7 +61,7 @@ class ContainerIssueDetailPanel( private fun mainPanel(): JPanel { val panel = JPanel( - GridLayoutManager(2, 2, Insets(0, 0, 0, 0), 30, -1) + GridLayoutManager(2, 2, JBUI.emptyInsets(), 30, -1) ) val introducedThrough = groupedVulns @@ -91,7 +91,7 @@ class ContainerIssueDetailPanel( private fun getDetailedPathsPanel(): JPanel { val detailsPanel = JPanel() - detailsPanel.layout = GridLayoutManager(2, 2, Insets(20, 0, 0, 0), -1, -1) + detailsPanel.layout = GridLayoutManager(2, 2, JBUI.insetsTop(20), -1, -1) detailsPanel.add( boldLabel("Detailed paths").apply { @@ -114,13 +114,13 @@ class ContainerIssueDetailPanel( private fun getInnerDetailedPathsPanel(itemsToShow: Int? = null): JPanel { val detailsPanel = JPanel() - detailsPanel.layout = GridLayoutManager(groupedVulns.size + 2, 2, Insets(0, 0, 0, 0), -1, -1) + detailsPanel.layout = GridLayoutManager(groupedVulns.size + 2, 2, JBUI.emptyInsets(), -1, -1) groupedVulns .take(itemsToShow ?: groupedVulns.size) .forEachIndexed { index, vuln -> val detailPanel = JPanel() - detailPanel.layout = GridLayoutManager(2, 2, Insets(0, 0, 0, 0), 30, 5) + detailPanel.layout = GridLayoutManager(2, 2, JBUI.emptyInsets(), 30, 5) insertTitleAndResizableTextIntoPanelColumns( panel = detailPanel, @@ -145,7 +145,7 @@ class ContainerIssueDetailPanel( } if (itemsToShow != null && itemsToShow < groupedVulns.size) { - val showMoreLabel = LinkLabel.create("...and ${groupedVulns.size - itemsToShow} more") { + val showMoreLabel = ActionLink("...and ${groupedVulns.size - itemsToShow} more") { detailsPanel.removeAll() detailsPanel.add( getInnerDetailedPathsPanel(), @@ -164,7 +164,7 @@ class ContainerIssueDetailPanel( } private fun overviewPanel(): JPanel { - val panel = JPanel(GridLayoutManager(2, 2, Insets(10, 5, 0, 0), -1, 0)) + val panel = JPanel(GridLayoutManager(2, 2, JBUI.insets(10, 5, 0, 0), -1, 0)) val descriptionMarkdown = issue.description.replaceFirst("## NVD Description", "## Description") val document = Parser.builder().build().parse(descriptionMarkdown) diff --git a/src/main/kotlin/snyk/tree/IssuesTree.kt b/src/main/kotlin/snyk/tree/IssuesTree.kt deleted file mode 100644 index 763b2de92..000000000 --- a/src/main/kotlin/snyk/tree/IssuesTree.kt +++ /dev/null @@ -1,25 +0,0 @@ -package snyk.tree - -import com.intellij.openapi.project.Project -import com.intellij.ui.treeStructure.Tree -import javax.swing.tree.DefaultMutableTreeNode - -class IssuesTree(project: Project) : Tree() { - private val root = DefaultMutableTreeNode("") - private val ossIssuesNode = IssueTreeNode("Open Source Security", project) - private val snykCodeSecurityIssuesNode = IssueTreeNode("Code Security", project) - private val snykCodeQualityIssuesNode = IssueTreeNode("Code Quality", project) - private val iacIssuesNode = IssueTreeNode("Configuration Issues", project) - //private val containerIssuesNode = IssueTreeNode("Container", project) - - init { - rootVisible = false - - root.add(ossIssuesNode) - root.add(snykCodeSecurityIssuesNode) - root.add(snykCodeQualityIssuesNode) - root.add(iacIssuesNode) - } -} - -class IssueTreeNode(value: String, project: Project) : DefaultMutableTreeNode() diff --git a/src/test/java/ai/deepcode/javaclient/core/Base64EncodeRequestInterceptorTest.java b/src/test/java/ai/deepcode/javaclient/core/Base64EncodeRequestInterceptorTest.java index 84283e484..0745e6458 100644 --- a/src/test/java/ai/deepcode/javaclient/core/Base64EncodeRequestInterceptorTest.java +++ b/src/test/java/ai/deepcode/javaclient/core/Base64EncodeRequestInterceptorTest.java @@ -5,6 +5,7 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.util.zip.GZIPInputStream; import static org.junit.Assert.assertEquals; @@ -18,7 +19,8 @@ public void encodesCorrectly() { byte[] encodedBytes = interceptor.encodeToBase64(jsonStr.getBytes()); - assertEquals("eyJzcmMvYXBwLnRzIn06eyJjb25zb2xlLmxvZyhcImhlbGxvXCJ9Igo=", new String(encodedBytes)); + assertEquals("eyJzcmMvYXBwLnRzIn06eyJjb25zb2xlLmxvZyhcImhlbGxvXCJ9Igo=", + new String(encodedBytes, StandardCharsets.UTF_8)); } @Test diff --git a/src/test/kotlin/io/snyk/plugin/net/RetrofitAuthenticatorTest.kt b/src/test/kotlin/io/snyk/plugin/net/RetrofitAuthenticatorTest.kt index a75903d01..03b35a18f 100644 --- a/src/test/kotlin/io/snyk/plugin/net/RetrofitAuthenticatorTest.kt +++ b/src/test/kotlin/io/snyk/plugin/net/RetrofitAuthenticatorTest.kt @@ -1,6 +1,5 @@ package io.snyk.plugin.net -import com.intellij.util.Base64 import com.intellij.util.net.HttpConfigurable import io.mockk.every import io.mockk.mockk @@ -11,6 +10,7 @@ import okhttp3.Response import okhttp3.Route import org.junit.Test import java.net.PasswordAuthentication +import java.util.Base64 class RetrofitAuthenticatorTest { @@ -37,7 +37,7 @@ class RetrofitAuthenticatorTest { val authHeader = request.headers[PROXY_AUTHORIZATION_HEADER_NAME] assertNotNull(authHeader) assertEquals("Basic dXNlcm5hbWU6cHc=", authHeader) - assertEquals("dXNlcm5hbWU6cHc=", Base64.encode("username:pw".toByteArray())) + assertEquals("dXNlcm5hbWU6cHc=", String(Base64.getEncoder().encode("username:pw".toByteArray()))) } @Test @@ -56,7 +56,7 @@ class RetrofitAuthenticatorTest { val request = cut.authenticate(route, response) - val authHeader = request!!.headers[PROXY_AUTHORIZATION_HEADER_NAME] + val authHeader = request.headers[PROXY_AUTHORIZATION_HEADER_NAME] assertNull(authHeader) } } diff --git a/src/test/kotlin/io/snyk/plugin/services/download/CliDownloaderTest.kt b/src/test/kotlin/io/snyk/plugin/services/download/CliDownloaderTest.kt index a63ae32d7..0efa5f421 100644 --- a/src/test/kotlin/io/snyk/plugin/services/download/CliDownloaderTest.kt +++ b/src/test/kotlin/io/snyk/plugin/services/download/CliDownloaderTest.kt @@ -67,7 +67,7 @@ class CliDownloaderTest { @Test fun `should not delete file if checksum verification fails`() { - val testFile = createTempFile() + val testFile = Files.createTempFile("test", "test").toFile() testFile.deleteOnExit() val dummyContent = "test test test".toByteArray() Files.write(testFile.toPath(), dummyContent) diff --git a/src/test/kotlin/io/snyk/plugin/ui/toolwindow/SnykToolWindowPanelIntegTest.kt b/src/test/kotlin/io/snyk/plugin/ui/toolwindow/SnykToolWindowPanelIntegTest.kt index 8e8108595..a58cfd388 100644 --- a/src/test/kotlin/io/snyk/plugin/ui/toolwindow/SnykToolWindowPanelIntegTest.kt +++ b/src/test/kotlin/io/snyk/plugin/ui/toolwindow/SnykToolWindowPanelIntegTest.kt @@ -1,3 +1,5 @@ +@file:Suppress("UNCHECKED_CAST") + package io.snyk.plugin.ui.toolwindow import ai.deepcode.javaclient.core.SuggestionForFile @@ -889,7 +891,7 @@ class SnykToolWindowPanelIntegTest : HeavyPlatformTestCase() { val rootContainerNode = toolWindowPanel.getRootContainerIssuesTreeNode() val expectedIssuesCount = containerResult.issuesCount - val actualIssueNodesCount = rootContainerNode.children().asSequence().sumBy { + val actualIssueNodesCount = rootContainerNode.children().asSequence().sumOf { (it as TreeNode).childCount } assertEquals(expectedIssuesCount, actualIssueNodesCount) diff --git a/src/test/kotlin/snyk/amplitude/api/AmplitudeExperimentApiClientTest.kt b/src/test/kotlin/snyk/amplitude/api/AmplitudeExperimentApiClientTest.kt index 317cf3637..c739a19f5 100644 --- a/src/test/kotlin/snyk/amplitude/api/AmplitudeExperimentApiClientTest.kt +++ b/src/test/kotlin/snyk/amplitude/api/AmplitudeExperimentApiClientTest.kt @@ -10,12 +10,10 @@ import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer import okio.buffer import okio.source -import org.hamcrest.collection.IsMapWithSize.aMapWithSize -import org.hamcrest.collection.IsMapWithSize.anEmptyMap -import org.hamcrest.core.IsEqual.equalTo -import org.hamcrest.core.IsNull.notNullValue import org.junit.After -import org.junit.Assert.assertThat +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Rule import org.junit.Test @@ -64,21 +62,21 @@ class AmplitudeExperimentApiClientTest { val response = amplitudeVariantService.sdkVardata(ExperimentUser("random-user-id")).execute() // asserts - assertThat(response.code(), equalTo(200)) + assertEquals(200, response.code()) val variants = response.body() - assertThat(variants, notNullValue()) - assertThat(variants, aMapWithSize(2)) + assertNotNull(variants) + assertEquals(2, variants?.size) val expectedFirstVariant = Variant(value = "on", payload = mapOf("message" to "random message")) val actualFirstVariant = variants?.entries?.first() - assertThat(actualFirstVariant?.key, equalTo("first-experiment")) - assertThat(actualFirstVariant?.value, equalTo(expectedFirstVariant)) + assertEquals("first-experiment", actualFirstVariant?.key) + assertEquals(expectedFirstVariant, actualFirstVariant?.value) val expectedLastVariant = Variant(value = "off") val actualLastVariant = variants?.entries?.last() - assertThat(actualLastVariant?.key, equalTo("second-experiment")) - assertThat(actualLastVariant?.value, equalTo(expectedLastVariant)) + assertEquals("second-experiment", actualLastVariant?.key) + assertEquals(expectedLastVariant, actualLastVariant?.value) } @Test @@ -90,7 +88,7 @@ class AmplitudeExperimentApiClientTest { val response = amplitudeVariantService.sdkVardata(ExperimentUser("")).execute() - assertThat(response.code(), equalTo(200)) + assertEquals(200, response.code()) } @Test @@ -101,8 +99,8 @@ class AmplitudeExperimentApiClientTest { val actualVariants = clientUnderTest.allVariants(ExperimentUser("random-user-id")) - assertThat(actualVariants, notNullValue()) - assertThat(actualVariants, aMapWithSize(2)) + assertNotNull(actualVariants) + assertEquals(2, actualVariants.size) } @Test @@ -111,7 +109,7 @@ class AmplitudeExperimentApiClientTest { val variants = clientUnderTest.allVariants(ExperimentUser("")) - assertThat(variants, anEmptyMap()) + assertTrue(variants.isEmpty()) } } diff --git a/src/test/kotlin/snyk/container/BaseImageRemediationExtractorTest.kt b/src/test/kotlin/snyk/container/BaseImageRemediationExtractorTest.kt index 02f3234e3..fee67a49c 100644 --- a/src/test/kotlin/snyk/container/BaseImageRemediationExtractorTest.kt +++ b/src/test/kotlin/snyk/container/BaseImageRemediationExtractorTest.kt @@ -1,8 +1,7 @@ package snyk.container -import org.hamcrest.core.IsEqual.equalTo -import org.hamcrest.core.IsNull.notNullValue -import org.junit.Assert.assertThat +import junit.framework.TestCase.assertEquals +import junit.framework.TestCase.assertNotNull import org.junit.Test class BaseImageRemediationExtractorTest { @@ -42,21 +41,18 @@ postgres:14.1 50 0 critical, 0 high, 0 medium, 50 low ) { val currentImage = BaseImageRemediationExtractor.extractImageInfo(input) - assertThat(currentImage, notNullValue()) - assertThat( - currentImage, - equalTo( - BaseImageInfo( - name = expectedImage, - vulnerabilities = BaseImageVulnerabilities( - critical = expectedCritical, - high = expectedHigh, - medium = expectedMedium, - low = expectedLow - ) + assertNotNull(currentImage) + assertEquals( + BaseImageInfo( + name = expectedImage, + vulnerabilities = BaseImageVulnerabilities( + critical = expectedCritical, + high = expectedHigh, + medium = expectedMedium, + low = expectedLow ) - ) + ), + currentImage ) } - } diff --git a/src/test/kotlin/snyk/iac/annotator/IacBaseAnnotatorCase.kt b/src/test/kotlin/snyk/iac/annotator/IacBaseAnnotatorCase.kt index f71714b6f..ac0593190 100644 --- a/src/test/kotlin/snyk/iac/annotator/IacBaseAnnotatorCase.kt +++ b/src/test/kotlin/snyk/iac/annotator/IacBaseAnnotatorCase.kt @@ -6,7 +6,6 @@ import io.mockk.mockk import io.mockk.unmockkAll import io.snyk.plugin.pluginSettings import io.snyk.plugin.resetSettings -import org.junit.Before import snyk.common.SnykCachedResults import java.nio.file.Paths @@ -22,7 +21,6 @@ abstract class IacBaseAnnotatorCase : BasePlatformTestCase() { override fun isWriteActionRequired(): Boolean = true - @Before override fun setUp() { super.setUp() unmockkAll() diff --git a/src/test/kotlin/snyk/iac/annotator/IacHclAnnotatorTest.kt b/src/test/kotlin/snyk/iac/annotator/IacHclAnnotatorTest.kt index 24f6a3de6..463842446 100644 --- a/src/test/kotlin/snyk/iac/annotator/IacHclAnnotatorTest.kt +++ b/src/test/kotlin/snyk/iac/annotator/IacHclAnnotatorTest.kt @@ -8,11 +8,7 @@ import com.intellij.psi.PsiFile import io.mockk.every import io.mockk.mockk import io.mockk.verify -import org.hamcrest.collection.IsCollectionWithSize.hasSize -import org.hamcrest.core.IsEqual.equalTo -import org.junit.Assert.assertThat -import org.junit.Before -import org.junit.Test +import junit.framework.TestCase import snyk.iac.IacIssue import snyk.iac.IacIssuesForFile import snyk.iac.IacResult @@ -24,32 +20,28 @@ class IacHclAnnotatorTest : IacBaseAnnotatorCase() { lateinit var file: VirtualFile private lateinit var psiFile: PsiFile - @Before override fun setUp() { super.setUp() file = myFixture.copyFileToProject(terraformManifestFile) psiFile = WriteAction.computeAndWait { psiManager.findFile(file)!! } } - @Test fun `test doAnnotation should not return any annotations if no iac issue exists`() { every { snykCachedResults.currentIacResult } returns null val annotations = IacHclAnnotator().getIssues(psiFile) - assertThat(annotations, hasSize(0)) + assertEquals(0, annotations.size) } - @Test fun `test getIssues should return one annotation if only one iac issue exists`() { every { snykCachedResults.currentIacResult } returns createIacResultWithIssueOnLine1() val annotations = IacHclAnnotator().getIssues(psiFile) - assertThat(annotations, hasSize(1)) + TestCase.assertEquals(1, annotations.size) } - @Test fun `test apply should trigger newAnnotation call`() { every { snykCachedResults.currentIacResult } returns createIacResultWithIssueOnLine1() @@ -58,7 +50,6 @@ class IacHclAnnotatorTest : IacBaseAnnotatorCase() { verify { annotationHolderMock.newAnnotation(any(), any()) } } - @Test fun `test textRange without leading whitespace for HCLIdentifier`() { every { snykCachedResults.currentIacResult } returns createIacResultWithIssueOnLine1() @@ -68,10 +59,9 @@ class IacHclAnnotatorTest : IacBaseAnnotatorCase() { snykCachedResults.currentIacResult?.allCliIssues!!.first().infrastructureAsCodeIssues.first() ) - assertThat(actualRange, equalTo(expectedRange)) + assertEquals(expectedRange, actualRange) } - @Test fun `test textRange with leading whitespace for HCLIdentifier`() { every { snykCachedResults.currentIacResult } returns createIacResultWithIssueOnLine8() @@ -81,10 +71,9 @@ class IacHclAnnotatorTest : IacBaseAnnotatorCase() { snykCachedResults.currentIacResult?.allCliIssues!!.first().infrastructureAsCodeIssues.first() ) - assertThat(actualRange, equalTo(expectedRange)) + assertEquals(expectedRange, actualRange) } - @Test fun `test textRange for leading whitespace for HCLProperty`() { every { snykCachedResults.currentIacResult } returns createIacResultWithIssueOnLine18() @@ -94,7 +83,7 @@ class IacHclAnnotatorTest : IacBaseAnnotatorCase() { snykCachedResults.currentIacResult?.allCliIssues!!.first().infrastructureAsCodeIssues.first() ) - assertThat(actualRange, equalTo(expectedRange)) + assertEquals(expectedRange, actualRange) } private fun createIacResultWithIssueOnLine1(): IacResult { diff --git a/src/test/kotlin/snyk/iac/annotator/IacJsonAnnotatorTest.kt b/src/test/kotlin/snyk/iac/annotator/IacJsonAnnotatorTest.kt index 80f12f416..b56ab51e6 100644 --- a/src/test/kotlin/snyk/iac/annotator/IacJsonAnnotatorTest.kt +++ b/src/test/kotlin/snyk/iac/annotator/IacJsonAnnotatorTest.kt @@ -9,10 +9,6 @@ import io.mockk.every import io.mockk.mockk import io.mockk.verify import io.snyk.plugin.pluginSettings -import org.hamcrest.collection.IsCollectionWithSize.hasSize -import org.junit.Assert.assertThat -import org.junit.Before -import org.junit.Test import snyk.iac.IacIssue import snyk.iac.IacIssuesForFile import snyk.iac.IacResult @@ -25,32 +21,28 @@ class IacJsonAnnotatorTest : IacBaseAnnotatorCase() { lateinit var file: VirtualFile private lateinit var psiFile: PsiFile - @Before override fun setUp() { super.setUp() file = myFixture.copyFileToProject(cloudformationManifestFile) psiFile = WriteAction.computeAndWait { psiManager.findFile(file)!! } } - @Test fun `test getIssues should not return any annotations if no iac issue exists`() { every { snykCachedResults.currentIacResult } returns null val issues = IacJsonAnnotator().getIssues(psiFile) - assertThat(issues, hasSize(0)) + assertEquals(0, issues.size) } - @Test fun `test getIssues should return one annotations if only one iac issue exists`() { every { snykCachedResults.currentIacResult } returns createIacResultWithIssueOnLine2() val issues = IacJsonAnnotator().getIssues(psiFile) - assertThat(issues, hasSize(1)) + assertEquals(1, issues.size) } - @Test fun `test apply should trigger newAnnotation call`() { every { snykCachedResults.currentIacResult } returns createIacResultWithIssueOnLine2() @@ -59,7 +51,6 @@ class IacJsonAnnotatorTest : IacBaseAnnotatorCase() { verify { annotationHolderMock.newAnnotation(any(), any()) } } - @Test fun `test apply for disabled Severity should not trigger newAnnotation call`() { every { snykCachedResults.currentIacResult } returns createIacResultWithIssueOnLine2() pluginSettings().mediumSeverityEnabled = false diff --git a/src/test/kotlin/snyk/iac/annotator/IacYamlAnnotatorTest.kt b/src/test/kotlin/snyk/iac/annotator/IacYamlAnnotatorTest.kt index 229ae2d3c..845115dca 100644 --- a/src/test/kotlin/snyk/iac/annotator/IacYamlAnnotatorTest.kt +++ b/src/test/kotlin/snyk/iac/annotator/IacYamlAnnotatorTest.kt @@ -8,11 +8,6 @@ import com.intellij.psi.PsiFile import io.mockk.every import io.mockk.mockk import io.mockk.verify -import org.hamcrest.collection.IsCollectionWithSize.hasSize -import org.hamcrest.core.IsEqual.equalTo -import org.junit.Assert.assertThat -import org.junit.Before -import org.junit.Test import snyk.iac.IacIssue import snyk.iac.IacIssuesForFile import snyk.iac.IacResult @@ -24,32 +19,28 @@ class IacYamlAnnotatorTest : IacBaseAnnotatorCase() { lateinit var file: VirtualFile private lateinit var psiFile: PsiFile - @Before override fun setUp() { super.setUp() file = myFixture.copyFileToProject(kubernetesManifestFile) psiFile = WriteAction.computeAndWait { psiManager.findFile(file)!! } } - @Test fun `test getIssues should not return any annotations if no iac issue exists`() { every { snykCachedResults.currentIacResult } returns null val issues = IacYamlAnnotator().getIssues(psiFile) - assertThat(issues, hasSize(0)) + assertEquals(0, issues.size) } - @Test fun `test getIssues should return one annotations if only one iac issue exists`() { every { snykCachedResults.currentIacResult } returns createIacResultWithIssueOnLine18() val issues = IacYamlAnnotator().getIssues(psiFile) - assertThat(issues, hasSize(1)) + assertEquals(1, issues.size) } - @Test fun `test apply should trigger newAnnotation call`() { every { snykCachedResults.currentIacResult } returns createIacResultWithIssueOnLine18() @@ -58,7 +49,6 @@ class IacYamlAnnotatorTest : IacBaseAnnotatorCase() { verify { annotationHolderMock.newAnnotation(any(), any()) } } - @Test fun `test textRange with leading space`() { every { snykCachedResults.currentIacResult } returns createIacResultWithIssueOnLine18() @@ -68,10 +58,9 @@ class IacYamlAnnotatorTest : IacBaseAnnotatorCase() { snykCachedResults.currentIacResult?.allCliIssues!!.first().infrastructureAsCodeIssues.first() ) - assertThat(actualRange, equalTo(expectedRange)) + assertEquals(expectedRange, actualRange) } - @Test fun `test textRange with dash at the begin`() { every { snykCachedResults.currentIacResult } returns createIacResultWithIssueOnLine20() @@ -81,7 +70,7 @@ class IacYamlAnnotatorTest : IacBaseAnnotatorCase() { snykCachedResults.currentIacResult?.allCliIssues!!.first().infrastructureAsCodeIssues.first() ) - assertThat(actualRange, equalTo(expectedRange)) + assertEquals(expectedRange, actualRange) } private fun createIacResultWithIssueOnLine18(): IacResult { diff --git a/src/test/kotlin/snyk/oss/annotator/OSSGoModAnnotatorTest.kt b/src/test/kotlin/snyk/oss/annotator/OSSGoModAnnotatorTest.kt index 90488cdb8..ebb743683 100644 --- a/src/test/kotlin/snyk/oss/annotator/OSSGoModAnnotatorTest.kt +++ b/src/test/kotlin/snyk/oss/annotator/OSSGoModAnnotatorTest.kt @@ -14,17 +14,15 @@ import io.mockk.mockk import io.mockk.unmockkAll import io.mockk.verify import io.snyk.plugin.pluginSettings -import org.hamcrest.collection.IsCollectionWithSize import org.junit.Assert import org.junit.Assert.assertNotEquals -import org.junit.Assert.assertThat import snyk.common.SnykCachedResults import snyk.common.intentionactions.AlwaysAvailableReplacementIntentionAction import snyk.oss.OssResult import snyk.oss.OssVulnerabilitiesForFile import java.nio.file.Paths -@Suppress("DuplicatedCode", "FunctionName") +@Suppress("DuplicatedCode") class OSSGoModAnnotatorTest : BasePlatformTestCase() { private val cut by lazy { OSSGoModAnnotator() } private val annotationHolderMock = mockk(relaxed = true) @@ -81,7 +79,7 @@ class OSSGoModAnnotatorTest : BasePlatformTestCase() { val issues = cut.getIssuesForFile(psiFile) assertNotEquals(null, issues) - assertThat(issues!!.vulnerabilities, IsCollectionWithSize.hasSize(11)) + assertEquals(11, issues!!.vulnerabilities.size) } fun `test apply should trigger newAnnotation call`() { diff --git a/src/test/kotlin/snyk/oss/annotator/OSSMavenAnnotatorTest.kt b/src/test/kotlin/snyk/oss/annotator/OSSMavenAnnotatorTest.kt index 70652e834..1acee03e1 100644 --- a/src/test/kotlin/snyk/oss/annotator/OSSMavenAnnotatorTest.kt +++ b/src/test/kotlin/snyk/oss/annotator/OSSMavenAnnotatorTest.kt @@ -15,18 +15,14 @@ import io.mockk.slot import io.mockk.unmockkAll import io.mockk.verify import io.snyk.plugin.pluginSettings -import org.hamcrest.collection.IsCollectionWithSize import org.junit.Assert.assertNotEquals -import org.junit.Assert.assertThat -import org.junit.Before -import org.junit.Test import snyk.common.SnykCachedResults import snyk.common.intentionactions.AlwaysAvailableReplacementIntentionAction import snyk.oss.OssResult import snyk.oss.OssVulnerabilitiesForFile import java.nio.file.Paths -@Suppress("DuplicatedCode", "FunctionName") +@Suppress("DuplicatedCode") class OSSMavenAnnotatorTest : BasePlatformTestCase() { private val cut by lazy { OSSMavenAnnotator() } private val annotationHolderMock = mockk(relaxed = true) @@ -47,7 +43,6 @@ class OSSMavenAnnotatorTest : BasePlatformTestCase() { override fun isWriteActionRequired(): Boolean = true - @Before override fun setUp() { super.setUp() unmockkAll() @@ -64,7 +59,6 @@ class OSSMavenAnnotatorTest : BasePlatformTestCase() { super.tearDown() } - @Test fun `test getIssues should not return any issue if no oss issue exists`() { every { snykCachedResults.currentOssResults } returns null @@ -73,17 +67,15 @@ class OSSMavenAnnotatorTest : BasePlatformTestCase() { assertEquals(null, issues) } - @Test fun `test getIssues should return issues if they exist`() { every { snykCachedResults.currentOssResults } returns createOssResultWithIssues() val issues = cut.getIssuesForFile(psiFile) assertNotEquals(null, issues) - assertThat(issues!!.vulnerabilities, IsCollectionWithSize.hasSize(4)) + assertEquals(4, issues!!.vulnerabilities.size) } - @Test fun `test apply should trigger newAnnotation call`() { every { snykCachedResults.currentOssResults } returns createOssResultWithIssues() @@ -92,7 +84,6 @@ class OSSMavenAnnotatorTest : BasePlatformTestCase() { verify { annotationHolderMock.newAnnotation(any(), any()) } } - @Test fun `test textRange for maven pom`() { val ossResult = createOssResultWithIssues() val issue = ossResult.allCliIssues!!.first().vulnerabilities[0] @@ -105,7 +96,6 @@ class OSSMavenAnnotatorTest : BasePlatformTestCase() { assertEquals(expectedRange, actualRange) } - @Test fun `test annotation message should contain issue title`() { val vulnerability = createOssResultWithIssues().allCliIssues!!.first().vulnerabilities[0] @@ -114,7 +104,6 @@ class OSSMavenAnnotatorTest : BasePlatformTestCase() { assertTrue(actual.contains(vulnerability.title) && actual.contains(vulnerability.name)) } - @Test fun `test apply should add a quickfix if upgradePath available and introducing dep is in pom`() { val builderMock = mockk(relaxed = true) val result = createOssResultWithIssues() diff --git a/src/test/kotlin/snyk/oss/annotator/OSSNpmAnnotatorTest.kt b/src/test/kotlin/snyk/oss/annotator/OSSNpmAnnotatorTest.kt index 0a9a550ef..6a9f5eb2f 100644 --- a/src/test/kotlin/snyk/oss/annotator/OSSNpmAnnotatorTest.kt +++ b/src/test/kotlin/snyk/oss/annotator/OSSNpmAnnotatorTest.kt @@ -17,18 +17,14 @@ import io.mockk.unmockkAll import io.mockk.verify import io.snyk.plugin.pluginSettings import io.snyk.plugin.resetSettings -import org.hamcrest.collection.IsCollectionWithSize import org.junit.Assert.assertNotEquals -import org.junit.Assert.assertThat -import org.junit.Before -import org.junit.Test import snyk.common.SnykCachedResults import snyk.common.intentionactions.AlwaysAvailableReplacementIntentionAction import snyk.oss.OssResult import snyk.oss.OssVulnerabilitiesForFile import java.nio.file.Paths -@Suppress("DuplicatedCode", "FunctionName") +@Suppress("DuplicatedCode") class OSSNpmAnnotatorTest : BasePlatformTestCase() { private val cut by lazy { OSSNpmAnnotator() } private val annotationHolderMock = mockk(relaxed = true) @@ -36,7 +32,8 @@ class OSSNpmAnnotatorTest : BasePlatformTestCase() { private val ossResult = javaClass.classLoader.getResource("oss-test-results/oss-result-package.json")!!.readText(Charsets.UTF_8) private val ossResultNoRemediation = - javaClass.classLoader.getResource("oss-test-results/oss-result-package-no-remediation.json")!!.readText(Charsets.UTF_8) + javaClass.classLoader.getResource("oss-test-results/oss-result-package-no-remediation.json")!! + .readText(Charsets.UTF_8) private lateinit var file: VirtualFile private lateinit var psiFile: PsiFile @@ -51,7 +48,6 @@ class OSSNpmAnnotatorTest : BasePlatformTestCase() { override fun isWriteActionRequired(): Boolean = true - @Before override fun setUp() { super.setUp() unmockkAll() @@ -69,7 +65,6 @@ class OSSNpmAnnotatorTest : BasePlatformTestCase() { super.tearDown() } - @Test fun `test getIssues should not return any issue if no oss issue exists`() { every { snykCachedResults.currentOssResults } returns null @@ -78,17 +73,15 @@ class OSSNpmAnnotatorTest : BasePlatformTestCase() { assertEquals(null, issues) } - @Test fun `test getIssues should return issues if they exist`() { every { snykCachedResults.currentOssResults } returns createOssResultWithIssues() val issues = cut.getIssuesForFile(psiFile) assertNotEquals(null, issues) - assertThat(issues!!.vulnerabilities.distinctBy { it.id }, IsCollectionWithSize.hasSize(1)) + assertEquals(1, issues!!.vulnerabilities.distinctBy { it.id }.size) } - @Test fun `test apply should trigger newAnnotation call`() { every { snykCachedResults.currentOssResults } returns createOssResultWithIssues() @@ -97,7 +90,6 @@ class OSSNpmAnnotatorTest : BasePlatformTestCase() { verify { annotationHolderMock.newAnnotation(any(), any()) } } - @Test fun `test apply for disabled Severity should not trigger newAnnotation call`() { every { snykCachedResults.currentOssResults } returns createOssResultWithIssues() pluginSettings().mediumSeverityEnabled = false @@ -107,7 +99,6 @@ class OSSNpmAnnotatorTest : BasePlatformTestCase() { verify(exactly = 0) { annotationHolderMock.newAnnotation(HighlightSeverity.WEAK_WARNING, any()) } } - @Test fun `test textRange`() { val ossResult = createOssResultWithIssues() val issue = ossResult.allCliIssues!!.first().vulnerabilities[0] @@ -120,7 +111,6 @@ class OSSNpmAnnotatorTest : BasePlatformTestCase() { assertEquals(expectedRange, actualRange) } - @Test fun `test annotation message should contain issue title`() { val vulnerability = createOssResultWithIssues().allCliIssues!!.first().vulnerabilities[0] @@ -129,7 +119,6 @@ class OSSNpmAnnotatorTest : BasePlatformTestCase() { assertTrue(actual.contains(vulnerability.title) && actual.contains(vulnerability.name)) } - @Test fun `test apply should not add a quickfix when upgrade empty`() { val builderMock = mockk(relaxed = true) val result = createOssResultWithIssuesNoRemediation() @@ -142,7 +131,6 @@ class OSSNpmAnnotatorTest : BasePlatformTestCase() { verify(exactly = 0) { builderMock.withFix(ofType(AlwaysAvailableReplacementIntentionAction::class)) } } - @Test fun `test apply should add a quickfix with message`() { val builderMock = mockk(relaxed = true) val result = createOssResultWithIssues() diff --git a/src/test/kotlin/snyk/trust/WorkspaceTrustServiceIntegrationTest.kt b/src/test/kotlin/snyk/trust/WorkspaceTrustServiceIntegrationTest.kt index 03dbf5b7e..b645f11fa 100644 --- a/src/test/kotlin/snyk/trust/WorkspaceTrustServiceIntegrationTest.kt +++ b/src/test/kotlin/snyk/trust/WorkspaceTrustServiceIntegrationTest.kt @@ -9,10 +9,6 @@ import com.intellij.testFramework.replaceService import io.mockk.every import io.mockk.mockk import io.mockk.unmockkAll -import org.hamcrest.core.IsEqual.equalTo -import org.junit.Assert.assertThat -import org.junit.Before -import org.junit.Test import java.nio.file.Paths class WorkspaceTrustServiceIntegrationTest : BasePlatformTestCase() { @@ -21,10 +17,9 @@ class WorkspaceTrustServiceIntegrationTest : BasePlatformTestCase() { private lateinit var cut: WorkspaceTrustService private class IntegTestDisposable : Disposable { - override fun dispose() {} + override fun dispose() = Unit } - @Before public override fun setUp() { super.setUp() unmockkAll() @@ -39,21 +34,19 @@ class WorkspaceTrustServiceIntegrationTest : BasePlatformTestCase() { cut = WorkspaceTrustService() } - @Test fun `test isPathTrusted should return false if no trusted path in settings available`() { every { workspaceTrustSettingsMock.getTrustedPaths() } returns listOf() val path = Paths.get("/project") - assertThat(cut.isPathTrusted(path), equalTo(false)) + assertFalse(cut.isPathTrusted(path)) } - @Test fun `test isPathTrusted should return true if trusted path in settings available`() { every { workspaceTrustSettingsMock.getTrustedPaths() } returns listOf("/project") val path = Paths.get("/project") - assertThat(cut.isPathTrusted(path), equalTo(true)) + assertTrue(cut.isPathTrusted(path)) } } diff --git a/src/test/kotlin/snyk/trust/WorkspaceTrustServiceTest.kt b/src/test/kotlin/snyk/trust/WorkspaceTrustServiceTest.kt index 574c64d06..85ea2c2d3 100644 --- a/src/test/kotlin/snyk/trust/WorkspaceTrustServiceTest.kt +++ b/src/test/kotlin/snyk/trust/WorkspaceTrustServiceTest.kt @@ -1,7 +1,7 @@ package snyk.trust -import org.hamcrest.core.IsEqual.equalTo -import org.junit.Assert.assertThat +import junit.framework.TestCase.assertFalse +import junit.framework.TestCase.assertTrue import org.junit.Rule import org.junit.Test import snyk.InMemoryFsRule @@ -17,8 +17,8 @@ class WorkspaceTrustServiceTest { val absoluteSimpleDir = memoryFs.fs.getPath("/opt/projects/simple") val relativeSimpleDir = memoryFs.fs.getPath("projects/simple") - assertThat(absoluteSimpleDir.isAncestor(absoluteSimpleDir), equalTo(true)) - assertThat(relativeSimpleDir.isAncestor(relativeSimpleDir), equalTo(true)) + assertTrue(absoluteSimpleDir.isAncestor(absoluteSimpleDir)) + assertTrue(relativeSimpleDir.isAncestor(relativeSimpleDir)) } @Test @@ -28,8 +28,8 @@ class WorkspaceTrustServiceTest { val relativeOuterDir = memoryFs.fs.getPath("projects/outer") val relativeInnerDir = memoryFs.fs.getPath("projects/outer/inner") - assertThat(absoluteOuterDir.isAncestor(absoluteInnerDir), equalTo(true)) - assertThat(relativeOuterDir.isAncestor(relativeInnerDir), equalTo(true)) + assertTrue(absoluteOuterDir.isAncestor(absoluteInnerDir)) + assertTrue(relativeOuterDir.isAncestor(relativeInnerDir)) } @Test @@ -39,8 +39,8 @@ class WorkspaceTrustServiceTest { val relativeOuterDir = memoryFs.fs.getPath("projects/outer") val relativeInnerDir = memoryFs.fs.getPath("projects/outer/level1/level2/level3/inner") - assertThat(absoluteOuterDir.isAncestor(absoluteInnerDir), equalTo(true)) - assertThat(relativeOuterDir.isAncestor(relativeInnerDir), equalTo(true)) + assertTrue(absoluteOuterDir.isAncestor(absoluteInnerDir)) + assertTrue(relativeOuterDir.isAncestor(relativeInnerDir)) } @Test @@ -50,8 +50,8 @@ class WorkspaceTrustServiceTest { val relativeOuterDir = memoryFs.fs.getPath("projects/outer") val relativeInnerDir = memoryFs.fs.getPath("projects/outer/inner") - assertThat(absoluteInnerDir.isAncestor(absoluteOuterDir), equalTo(false)) - assertThat(relativeInnerDir.isAncestor(relativeOuterDir), equalTo(false)) + assertFalse(absoluteInnerDir.isAncestor(absoluteOuterDir)) + assertFalse(relativeInnerDir.isAncestor(relativeOuterDir)) } @Test @@ -61,9 +61,9 @@ class WorkspaceTrustServiceTest { val relativeFirstDir = memoryFs.fs.getPath("projects/first") val relativeSecondDir = memoryFs.fs.getPath("projects/second") - assertThat(absoluteFirstDir.isAncestor(absoluteSecondDir), equalTo(false)) - assertThat(absoluteSecondDir.isAncestor(absoluteFirstDir), equalTo(false)) - assertThat(relativeFirstDir.isAncestor(relativeSecondDir), equalTo(false)) - assertThat(relativeSecondDir.isAncestor(relativeFirstDir), equalTo(false)) + assertFalse(absoluteFirstDir.isAncestor(absoluteSecondDir)) + assertFalse(absoluteSecondDir.isAncestor(absoluteFirstDir)) + assertFalse(relativeFirstDir.isAncestor(relativeSecondDir)) + assertFalse(relativeSecondDir.isAncestor(relativeFirstDir)) } }