github.com/ouraigua/jenkins-library@v0.0.0-20231028010029-fbeaf2f3aa9b/test/groovy/MailSendNotificationTest.groovy (about)

     1  import org.junit.After
     2  import org.junit.Before
     3  import org.junit.Rule
     4  import org.junit.Test
     5  import org.junit.rules.RuleChain
     6  import util.*
     7  import com.sap.piper.Utils
     8  
     9  import static org.hamcrest.Matchers.*
    10  import static org.junit.Assert.assertThat
    11  
    12  class MailSendNotificationTest extends BasePiperTest {
    13      private JenkinsLoggingRule loggingRule = new JenkinsLoggingRule(this)
    14      private JenkinsStepRule stepRule = new JenkinsStepRule(this)
    15      private JenkinsShellCallRule shellRule = new JenkinsShellCallRule(this)
    16  
    17      @Rule
    18      public RuleChain ruleChain = Rules
    19          .getCommonRules(this)
    20          .around(new JenkinsReadYamlRule(this))
    21          .around(loggingRule)
    22          .around(shellRule)
    23          .around(stepRule)
    24  
    25      @Before
    26      void init() throws Exception {
    27          // register Jenkins commands with mock values
    28          helper.registerAllowedMethod("deleteDir", [], null)
    29          helper.registerAllowedMethod("sshagent", [Map.class, Closure.class], null)
    30  
    31          nullScript.commonPipelineEnvironment.configuration = nullScript.commonPipelineEnvironment.configuration ?: [:]
    32          nullScript.commonPipelineEnvironment.configuration['general'] = nullScript.commonPipelineEnvironment.configuration['general'] ?: [:]
    33          nullScript.commonPipelineEnvironment.configuration['steps'] = nullScript.commonPipelineEnvironment.configuration['steps'] ?: [:]
    34          nullScript.commonPipelineEnvironment.configuration['steps']['mailSendNotification'] = nullScript.commonPipelineEnvironment.configuration['steps']['mailSendNotification'] ?: [:]
    35  
    36          helper.registerAllowedMethod('requestor', [], { -> return [$class: 'RequesterRecipientProvider']})
    37  
    38          Utils.metaClass.echo = { def m -> }
    39      }
    40  
    41      @After
    42      public void tearDown() {
    43          Utils.metaClass = null
    44      }
    45  
    46      @Test
    47      void testGetDistinctRecipients() throws Exception {
    48          // git log -10 --pretty=format:"%ae %ce"
    49          def input = '''user1@domain.com noreply+github@domain.com
    50  user1@domain.com noreply+github@domain.com
    51  user3@domain.com noreply+github@domain.com
    52  user2@domain.com user1@domain.com
    53  user1@noreply.domain.com
    54  user1@domain.com noreply+github@domain.com
    55  user3@domain.com noreply+github@domain.com
    56  user3@domain.com noreply+github@domain.com
    57  user3@domain.com noreply+github@domain.com
    58  user3@domain.com noreply+github@domain.com
    59  user3@domain.com noreply+github@domain.com'''
    60  
    61          def result = stepRule.step.getDistinctRecipients(input)
    62          // asserts
    63          assertThat(result.split(' '), arrayWithSize(3))
    64          assertThat(result, containsString('user1@domain.com'))
    65          assertThat(result, containsString('user2@domain.com'))
    66          assertThat(result, containsString('user3@domain.com'))
    67      }
    68  
    69      @Test
    70      void testCulpritsFromGitCommit() throws Exception {
    71          def gitCommand = "git log -2 --first-parent --pretty=format:'%ae %ce'"
    72          def expected = "user2@domain.com user3@domain.com"
    73  
    74          shellRule.setReturnValue("git log -2 --first-parent --pretty=format:'%ae %ce'", 'user2@domain.com user3@domain.com')
    75  
    76          def result = stepRule.step.getCulprits(
    77              [
    78                  gitSSHCredentialsId: '',
    79                  gitUrl: 'git@github.domain.com:IndustryCloudFoundation/pipeline-test-node.git',
    80                  gitCommitId: 'f0973368a35a2b973612acb86f932c61f2635f6e'
    81              ],
    82              'master',
    83              2)
    84          // asserts
    85          assertThat(result, containsString('user2@domain.com'))
    86          assertThat(result, containsString('user3@domain.com'))
    87      }
    88  
    89      @Test
    90      void testCulpritsWithEmptyGitCommit() throws Exception {
    91  
    92          shellRule.setReturnValue('git log > /dev/null 2>&1',1)
    93  
    94          stepRule.step.getCulprits(
    95              [
    96                  gitSSHCredentialsId: '',
    97                  gitUrl: 'git@github.domain.com:IndustryCloudFoundation/pipeline-test-node.git',
    98                  gitCommitId: ''
    99              ],
   100              'master',
   101              2)
   102          // asserts
   103          assertThat(loggingRule.log, containsString('[mailSendNotification] No git context available to retrieve culprits'))
   104      }
   105  
   106      @Test
   107      void testCulpritsWithoutGitCommit() throws Exception {
   108  
   109          shellRule.setReturnValue('git log > /dev/null 2>&1',1)
   110  
   111          stepRule.step.getCulprits(
   112              [
   113                  gitSSHCredentialsId: '',
   114                  gitUrl: 'git@github.domain.com:IndustryCloudFoundation/pipeline-test-node.git',
   115                  gitCommitId: null
   116              ],
   117              'master',
   118              2)
   119          // asserts
   120          assertThat(loggingRule.log, containsString('[mailSendNotification] No git context available to retrieve culprits'))
   121      }
   122  
   123      @Test
   124      void testCulpritsWithoutBranch() throws Exception {
   125  
   126          shellRule.setReturnValue('git log > /dev/null 2>&1',1)
   127  
   128          stepRule.step.getCulprits(
   129              [
   130                  gitSSHCredentialsId: '',
   131                  gitUrl: 'git@github.domain.com:IndustryCloudFoundation/pipeline-test-node.git',
   132                  gitCommitId: ''
   133              ],
   134              null,
   135              2)
   136          // asserts
   137          assertThat(loggingRule.log, containsString('[mailSendNotification] No git context available to retrieve culprits'))
   138      }
   139  
   140      @Test
   141      void testSendNotificationMail() throws Exception {
   142          def emailParameters = [:]
   143          def buildMock = [
   144              fullProjectName: 'testProjectName',
   145              displayName: 'testDisplayName',
   146              result: 'FAILURE',
   147              rawBuild: [
   148                  getLog: { cnt -> return ['Setting http proxy: proxy.domain.com:8080',
   149  ' > git fetch --no-tags --progress https://github.com/SAP/jenkins-library.git +refs/heads/*:refs/remotes/origin/*',
   150  'Checking out Revision myUniqueCommitId (master)',
   151  ' > git config core.sparsecheckout # timeout=10',
   152  ' > git checkout -f myUniqueCommitId',
   153  'Commit message: "Merge pull request #147 from marcusholl/pr/useGitRevParseForInsideGitRepoCheck"',
   154  ' > git rev-list --no-walk myUniqueCommitId # timeout=10',
   155  '[Pipeline] node',
   156  'Running on Jenkins in /var/jenkins_home/workspace/Test/UserId/ECHO',
   157  '[Pipeline] {',
   158  '[Pipeline] stage',
   159  '[Pipeline] { (A)',
   160  '[Pipeline] script',
   161  '[Pipeline] {']
   162                  }
   163              ],
   164              getPreviousBuild: {
   165                  return null
   166              }
   167          ]
   168          nullScript.currentBuild = buildMock
   169          nullScript.commonPipelineEnvironment.configuration['steps']['mailSendNotification']['notificationRecipients'] = 'piper@domain.com'
   170          helper.registerAllowedMethod('emailext', [Map.class], { map ->
   171              emailParameters = map
   172              return ''
   173          })
   174  
   175          stepRule.step.mailSendNotification(
   176              script: nullScript,
   177              notifyCulprits: false,
   178              gitUrl: 'git@github.domain.com:IndustryCloudFoundation/pipeline-test-node.git'
   179          )
   180          // asserts
   181          assertThat(emailParameters.to, is('piper@domain.com'))
   182          assertThat(emailParameters.subject, is('FAILURE: Build testProjectName testDisplayName'))
   183          assertThat(emailParameters.body, startsWith('<a href="http://build.url">http://build.url</a>\n<br>\nTo have a detailed look at the different pipeline stages: <a href="null">null</a>\n<br>\n<h3>Last lines of output</h3>'))
   184          assertThat(emailParameters.body, containsString(' > git fetch --no-tags --progress https://github.com/SAP/jenkins-library.git +refs/heads/*:refs/remotes/origin/*'))
   185          assertJobStatusSuccess()
   186      }
   187  
   188      @Test
   189      void testSendNotificationMailWithGeneralConfig() throws Exception {
   190          def credentials
   191          nullScript.currentBuild = [
   192              fullProjectName: 'testProjectName',
   193              displayName: 'testDisplayName',
   194              result: 'FAILURE',
   195              rawBuild: [ getLog: { cnt -> return ['empty'] } ],
   196              getChangeSets: { return null },
   197              getPreviousBuild: { return null }
   198          ]
   199          nullScript.commonPipelineEnvironment.configuration['general']['gitSshKeyCredentialsId'] = 'myCredentialsId'
   200          helper.registerAllowedMethod('emailext', [Map.class], null)
   201          helper.registerAllowedMethod("sshagent", [Map.class, Closure.class], { map, closure ->
   202              credentials = map.credentials
   203              return null
   204          })
   205  
   206          shellRule.setReturnValue("git log -0 --pretty=format:'%ae %ce'", 'user2@domain.com user3@domain.com')
   207  
   208          stepRule.step.mailSendNotification(
   209              script: nullScript,
   210              gitCommitId: 'abcd1234',
   211              //notifyCulprits: true,
   212              gitUrl: 'git@github.domain.com:IndustryCloudFoundation/pipeline-test-node.git'
   213          )
   214          // asserts
   215          assertThat(credentials, hasItem('myCredentialsId'))
   216          assertJobStatusSuccess()
   217      }
   218  
   219      @Test
   220      void testSendNotificationMailWithEmptySshKey() throws Exception {
   221          def credentials
   222          nullScript.currentBuild = [
   223              fullProjectName: 'testProjectName',
   224              displayName: 'testDisplayName',
   225              result: 'FAILURE',
   226              rawBuild: [ getLog: { cnt -> return ['empty'] } ],
   227              getChangeSets: { return null },
   228              getPreviousBuild: { return null }
   229          ]
   230          helper.registerAllowedMethod('emailext', [Map.class], null)
   231          helper.registerAllowedMethod("sshagent", [Map.class, Closure.class], { map, closure ->
   232              credentials = map.credentials
   233              return null
   234          })
   235  
   236          shellRule.setReturnValue("git log -0 --pretty=format:'%ae %ce'", 'user2@domain.com user3@domain.com')
   237  
   238          stepRule.step.mailSendNotification(
   239              script: nullScript,
   240              gitCommitId: 'abcd1234',
   241              gitUrl: 'git@github.domain.com:IndustryCloudFoundation/pipeline-test-node.git'
   242          )
   243          // asserts
   244          assertThat(credentials, hasItem(''))
   245          assertJobStatusSuccess()
   246      }
   247  
   248      @Test
   249      void testSendNotificationMailOnFirstBuild() throws Exception {
   250          def emailExtCalls = []
   251          def buildMock = [
   252              fullProjectName: 'testProjectName',
   253              displayName: 'testDisplayName',
   254              result: 'SUCCESS',
   255              getPreviousBuild: {
   256                  return null
   257              }
   258          ]
   259          nullScript.currentBuild = buildMock
   260          helper.registerAllowedMethod('emailext', [Map.class], { map ->
   261              emailExtCalls.add(map)
   262              return ''
   263          })
   264  
   265          stepRule.step.mailSendNotification(
   266              script: nullScript,
   267              notifyCulprits: false,
   268              gitUrl: 'git@github.domain.com:IndustryCloudFoundation/pipeline-test-node.git'
   269          )
   270  
   271          assertThat(emailExtCalls, hasSize(0))
   272      }
   273  
   274      @Test
   275      void testSendNotificationMailOnRecovery() throws Exception {
   276          def emailExtCalls = []
   277          def buildMock = [
   278              fullProjectName: 'testProjectName',
   279              displayName: 'testDisplayName',
   280              result: 'SUCCESS',
   281              getPreviousBuild: {
   282                  return [result: 'FAILURE']
   283              }
   284          ]
   285          nullScript.currentBuild = buildMock
   286          helper.registerAllowedMethod('emailext', [Map.class], { map ->
   287              emailExtCalls.add(map)
   288              return ''
   289          })
   290  
   291          stepRule.step.mailSendNotification(
   292              script: nullScript,
   293              notifyCulprits: false,
   294              gitUrl: 'git@github.domain.com:IndustryCloudFoundation/pipeline-test-node.git'
   295          )
   296  
   297          assertThat(emailExtCalls, hasSize(1))
   298          assertThat(emailExtCalls[0].subject, is("SUCCESS: Build testProjectName testDisplayName is back to normal"))
   299      }
   300  }