@mojaloop/ml-testing-toolkit-client-lib 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/.circleci/config.yml +502 -0
  2. package/.dockerignore +10 -0
  3. package/.nvmrc +1 -0
  4. package/CHANGELOG.md +5 -0
  5. package/Dockerfile +25 -0
  6. package/LICENSE.md +10 -0
  7. package/README.md +213 -0
  8. package/audit-resolve.json +14 -0
  9. package/bin/cli.js +2 -0
  10. package/jest.config.js +16 -0
  11. package/native-app-generation/assets/macos/start.sh +7 -0
  12. package/native-app-generation/build-native-app.sh +57 -0
  13. package/package.json +132 -0
  14. package/src/client.js +49 -0
  15. package/src/extras/s3-upload.js +69 -0
  16. package/src/extras/slack-broadcast.js +149 -0
  17. package/src/modes/monitoring.js +32 -0
  18. package/src/modes/outbound.js +179 -0
  19. package/src/modes/testcaseDefinitionReport.js +53 -0
  20. package/src/objectStore.js +39 -0
  21. package/src/router.js +110 -0
  22. package/src/sample-config.json +11 -0
  23. package/src/utils/file-utils.js +53 -0
  24. package/src/utils/listeners.js +46 -0
  25. package/src/utils/logger.js +93 -0
  26. package/src/utils/report.js +127 -0
  27. package/src/utils/templateGenerator.js +65 -0
  28. package/test/lib/mockRequest.js +38 -0
  29. package/test/lib/mockResponse.js +53 -0
  30. package/test/unit/client.test.js +36 -0
  31. package/test/unit/extras/s3-upload.test.js +99 -0
  32. package/test/unit/extras/slack-broadcast.test.js +125 -0
  33. package/test/unit/listener.test.js +58 -0
  34. package/test/unit/logger.test.js +259 -0
  35. package/test/unit/monitoring-mode.test.js +38 -0
  36. package/test/unit/outbound-mode.test.js +192 -0
  37. package/test/unit/report.test.js +258 -0
  38. package/test/unit/router.test.js +110 -0
  39. package/test/unit/templateGenerator.test.js +119 -0
  40. package/test/unit/testcaseDefinitionReport-mode.test.js +72 -0
  41. package/test/util/testConfig.js +38 -0
@@ -0,0 +1,93 @@
1
+ /*****
2
+ License
3
+ --------------
4
+ Copyright © 2017 Bill & Melinda Gates Foundation
5
+ The Mojaloop files are made available by the Bill & Melinda Gates Foundation under the Apache License, Version 2.0 (the "License") and you may not use these files except in compliance with the License. You may obtain a copy of the License at
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+ Unless required by applicable law or agreed to in writing, the Mojaloop files are distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
8
+ Contributors
9
+ --------------
10
+ This is the official list of the Mojaloop project contributors for this file.
11
+ Names of the original copyright holders (individuals or organizations)
12
+ should be listed with a '*' in the first column. People who have
13
+ contributed from an organization can be listed under the organization
14
+ that actually holds the copyright for their contributions (see the
15
+ Gates Foundation organization for an example). Those individuals should have
16
+ their names indented and be marked with a '-'. Email address can be added
17
+ optionally within square brackets <email>.
18
+ * Gates Foundation
19
+
20
+ * ModusBox
21
+ * Georgi Logodazhki <georgi.logodazhki@modusbox.com> (Original Author)
22
+ --------------
23
+ ******/
24
+ const fStr = require('node-strings')
25
+ const Table = require('cli-table3')
26
+ const objectStore = require('../objectStore')
27
+
28
+ const outbound = (progress) => {
29
+ let totalAssertionsCount = 0
30
+ let totalPassedAssertionsCount = 0
31
+ let totalRequestsCount = 0
32
+ const testCasesTag = '--------------------FINAL REPORT--------------------'
33
+ console.log('\n' + fStr.yellow(testCasesTag))
34
+ progress.test_cases.forEach(testCase => {
35
+ console.log(fStr.yellow(testCase.name))
36
+ totalRequestsCount += testCase.requests.length
37
+ testCase.requests.forEach(req => {
38
+ const passedAssertionsCount = (req.request.tests && req.request.tests.passedAssertionsCount) ? req.request.tests.passedAssertionsCount : 0
39
+ const assertionsCount = (req.request.tests && req.request.tests.assertions) ? req.request.tests.assertions.length : 0
40
+ totalAssertionsCount += assertionsCount
41
+ totalPassedAssertionsCount += passedAssertionsCount
42
+ const logMessage = `\t${
43
+ req.request.description} - ${
44
+ req.request.method.toUpperCase()} - ${
45
+ req.request.operationPath} - [${
46
+ passedAssertionsCount}/${
47
+ assertionsCount}]`
48
+ const passed = passedAssertionsCount === assertionsCount
49
+ console.log(passed ? fStr.green(logMessage) : fStr.red(logMessage))
50
+ })
51
+ })
52
+ console.log(fStr.yellow(testCasesTag) + '\n')
53
+ const config = objectStore.get('config')
54
+ if (config.extraSummaryInformation) {
55
+ const extraSummaryInformationArr = config.extraSummaryInformation.split(',')
56
+ extraSummaryInformationArr.forEach(info => {
57
+ const infoArr = info.split(':')
58
+ console.log(infoArr[0] + ':' + fStr.yellow(infoArr[1]))
59
+ })
60
+ }
61
+ const summary = new Table()
62
+ summary.push(
63
+ [{ colSpan: 2, content: 'SUMMARY', hAlign: 'center' }],
64
+ { 'Total assertions': totalAssertionsCount },
65
+ { 'Passed assertions': totalPassedAssertionsCount },
66
+ { 'Failed assertions': totalAssertionsCount - totalPassedAssertionsCount },
67
+ { 'Total requests': totalRequestsCount },
68
+ { 'Total test cases': progress.test_cases.length },
69
+ { 'Passed percentage': `${(100 * (totalPassedAssertionsCount / totalAssertionsCount)).toFixed(2)}%` },
70
+ { 'Started time': progress.runtimeInformation.startedTime },
71
+ { 'Completed time': progress.runtimeInformation.completedTime },
72
+ { 'Runtime duration': `${progress.runtimeInformation.runDurationMs} ms` }
73
+ )
74
+ console.log(summary.toString())
75
+
76
+ const passed = totalPassedAssertionsCount === totalAssertionsCount
77
+ return passed
78
+ }
79
+
80
+ const monitoring = (progress) => {
81
+ console.log(
82
+ fStr.red(`\n${progress.logTime}`) +
83
+ fStr.blue(` ${progress.verbosity.toUpperCase()}`) +
84
+ (progress.uniqueId ? fStr.yellow(`\t(${progress.uniqueId})`) : '\t') +
85
+ fStr.green(`\t${progress.message}`) +
86
+ (progress.additionalData ? ('\n' + JSON.stringify(progress.additionalData, null, 2)) : '\n')
87
+ )
88
+ }
89
+
90
+ module.exports = {
91
+ outbound,
92
+ monitoring
93
+ }
@@ -0,0 +1,127 @@
1
+ /*****
2
+ License
3
+ --------------
4
+ Copyright © 2017 Bill & Melinda Gates Foundation
5
+ The Mojaloop files are made available by the Bill & Melinda Gates Foundation under the Apache License, Version 2.0 (the "License") and you may not use these files except in compliance with the License. You may obtain a copy of the License at
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+ Unless required by applicable law or agreed to in writing, the Mojaloop files are distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
8
+ Contributors
9
+ --------------
10
+ This is the official list of the Mojaloop project contributors for this file.
11
+ Names of the original copyright holders (individuals or organizations)
12
+ should be listed with a '*' in the first column. People who have
13
+ contributed from an organization can be listed under the organization
14
+ that actually holds the copyright for their contributions (see the
15
+ Gates Foundation organization for an example). Those individuals should have
16
+ their names indented and be marked with a '-'. Email address can be added
17
+ optionally within square brackets <email>.
18
+ * Gates Foundation
19
+
20
+ * ModusBox
21
+ * Vijay Kumar Guthi <vijaya.guthi@modusbox.com>
22
+ * Georgi Logodazhki <georgi.logodazhki@modusbox.com> (Original Author)
23
+ --------------
24
+ ******/
25
+ const axios = require('axios').default
26
+ const fs = require('fs')
27
+ const { promisify } = require('util')
28
+ const objectStore = require('../objectStore')
29
+ const s3Upload = require('../extras/s3-upload')
30
+
31
+ const outbound = async (data) => {
32
+ const testcaseReport = await report(data, 'testcase')
33
+ return testcaseReport
34
+ }
35
+
36
+ const testcaseDefinition = async (template) => {
37
+ const testcaseDefinitionReport = await report(template, 'testcase_definition')
38
+ return testcaseDefinitionReport
39
+ }
40
+
41
+ const report = async (data, reportType) => {
42
+ const returnInfo = {}
43
+ const config = objectStore.get('config')
44
+ let reportData
45
+ let reportFilename
46
+ switch (config.reportFormat) {
47
+ case 'json':
48
+ reportData = JSON.stringify(data, null, 2)
49
+ reportFilename = `${data.name}-${data.runtimeInformation.completedTimeISO}.json`
50
+ break
51
+ case 'html':
52
+ case 'printhtml': {
53
+ if (config.extraSummaryInformation) {
54
+ const extraSummaryInformationArr = config.extraSummaryInformation.split(',')
55
+ data.extraRuntimeInformation = extraSummaryInformationArr.map(info => {
56
+ const infoArr = info.split(':')
57
+ return {
58
+ key: infoArr[0],
59
+ value: infoArr[1]
60
+ }
61
+ })
62
+ }
63
+ const response = await axios.post(`${config.baseURL}/api/reports/${reportType}/${config.reportFormat}`, data, { headers: { 'Content-Type': 'application/json' } })
64
+ reportData = response.data
65
+ const disposition = response.headers['content-disposition']
66
+ if (disposition && disposition.indexOf('attachment') !== -1) {
67
+ const filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/
68
+ const matches = filenameRegex.exec(disposition)
69
+ if (matches != null && matches[1]) {
70
+ reportFilename = matches[1].replace(/['"]/g, '')
71
+ }
72
+ }
73
+ if (!reportFilename) {
74
+ reportFilename = 'report.html'
75
+ }
76
+ break
77
+ }
78
+ default:
79
+ console.log('reportFormat is not supported')
80
+ return
81
+ }
82
+ if (config.reportTarget) {
83
+ const reportTargetRe = /(.*):\/\/(.*)/g
84
+ const reportTargetArr = reportTargetRe.exec(config.reportTarget)
85
+ let writeFileName = reportTargetArr[2]
86
+ if (config.reportAutoFilenameEnable) {
87
+ // Replace the last part with auto generated file name
88
+ writeFileName = replaceFileName(writeFileName, reportFilename)
89
+ }
90
+ switch (reportTargetArr[1]) {
91
+ case 'file': {
92
+ const writeFileAsync = promisify(fs.writeFile)
93
+ await writeFileAsync(writeFileName, reportData)
94
+ console.log(`${writeFileName} was generated`)
95
+ break
96
+ }
97
+ case 's3': {
98
+ const uploadedReportURL = await s3Upload.uploadFileDataToS3('s3://' + writeFileName, reportData)
99
+ returnInfo.uploadedReportURL = uploadedReportURL
100
+ break
101
+ }
102
+ default:
103
+ console.log('reportTarget is not supported')
104
+ return
105
+ }
106
+ } else {
107
+ // Store the file
108
+ const writeFileAsync = promisify(fs.writeFile)
109
+ await writeFileAsync(reportFilename, reportData)
110
+ console.log(`${reportFilename} was generated`)
111
+ }
112
+ return returnInfo
113
+ }
114
+
115
+ const replaceFileName = (fullPath, fileName) => {
116
+ const fullPathArr = fullPath.split('/')
117
+ if (fullPathArr.length > 1) {
118
+ return fullPath.split('/').slice(0, -1).join('/') + '/' + fileName
119
+ } else {
120
+ return fileName
121
+ }
122
+ }
123
+
124
+ module.exports = {
125
+ testcaseDefinition,
126
+ outbound
127
+ }
@@ -0,0 +1,65 @@
1
+ const { FolderParser } = require('@mojaloop/ml-testing-toolkit-shared-lib')
2
+ const { readFileAsync, readRecursiveAsync, fileStatAsync } = require('../utils/file-utils')
3
+ const path = require('path')
4
+
5
+ const getFileData = async (fileToRead, fileStat) => {
6
+ try {
7
+ const content = await readFileAsync(fileToRead, 'utf8')
8
+ const fileContent = JSON.parse(content)
9
+ return {
10
+ name: path.basename(fileToRead),
11
+ path: fileToRead.replace(/\\/g, '/'),
12
+ size: fileStat.size,
13
+ modified: '' + fileStat.mtime,
14
+ content: fileContent
15
+ }
16
+ } catch (err) {
17
+ console.log(err.message)
18
+ return null
19
+ }
20
+ }
21
+ const getFolderRawData = async (folderItem) => {
22
+ const importFolderRawData = []
23
+ const stat = await fileStatAsync(folderItem)
24
+ if (stat.isFile() && folderItem.endsWith('.json')) {
25
+ const fileItemData = await getFileData(folderItem, stat)
26
+ if (fileItemData) {
27
+ importFolderRawData.push(fileItemData)
28
+ }
29
+ } else if (stat.isDirectory()) {
30
+ const fileList = await readRecursiveAsync(folderItem)
31
+ for (let j = 0; j < fileList.length; j++) {
32
+ const fileItemData = await getFileData(fileList[j], stat)
33
+ if (fileItemData) {
34
+ importFolderRawData.push(fileItemData)
35
+ }
36
+ }
37
+ }
38
+ importFolderRawData.sort((a, b) => a.path.localeCompare(b.path))
39
+ return importFolderRawData
40
+ }
41
+
42
+ const generateTemplate = async (inputFiles, selectedLabels = null) => {
43
+ try {
44
+ const folderRawDataArray = []
45
+ for (let i = 0; i < inputFiles.length; i++) {
46
+ const inputFile = inputFiles[i]
47
+ const folderRawData = await getFolderRawData(inputFile)
48
+ folderRawDataArray.push(...folderRawData)
49
+ }
50
+ const folderData = FolderParser.getFolderData(folderRawDataArray)
51
+ const testCases = FolderParser.getTestCases(folderData, null, selectedLabels)
52
+ FolderParser.sequenceTestCases(testCases)
53
+ const template = {}
54
+ template.test_cases = testCases
55
+ template.name = 'multi'
56
+ return template
57
+ } catch (err) {
58
+ console.log(err)
59
+ return null
60
+ }
61
+ }
62
+
63
+ module.exports = {
64
+ generateTemplate
65
+ }
@@ -0,0 +1,38 @@
1
+ /*****
2
+ License
3
+ --------------
4
+ Copyright © 2017 Bill & Melinda Gates Foundation
5
+ The Mojaloop files are made available by the Bill & Melinda Gates Foundation under the Apache License, Version 2.0 (the "License") and you may not use these files except in compliance with the License. You may obtain a copy of the License at
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+ Unless required by applicable law or agreed to in writing, the Mojaloop files are distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
8
+ Contributors
9
+ --------------
10
+ This is the official list of the Mojaloop project contributors for this file.
11
+ Names of the original copyright holders (individuals or organizations)
12
+ should be listed with a '*' in the first column. People who have
13
+ contributed from an organization can be listed under the organization
14
+ that actually holds the copyright for their contributions (see the
15
+ Gates Foundation organization for an example). Those individuals should have
16
+ their names indented and be marked with a '-'. Email address can be added
17
+ optionally within square brackets <email>.
18
+ * Gates Foundation
19
+
20
+ * ModusBox
21
+ * Vijaya Kumar Guthi <vijaya.guthi@modusbox.com> (Original Author)
22
+ --------------
23
+ ******/
24
+
25
+ const { stub } = require('sinon')
26
+
27
+ const mockRequest = (options = {}) => ({
28
+ body: {},
29
+ cookies: {},
30
+ query: {},
31
+ params: {},
32
+ headers: {},
33
+ customInfo: {},
34
+ get: stub(),
35
+ ...options
36
+ })
37
+
38
+ module.exports = mockRequest
@@ -0,0 +1,53 @@
1
+ /*****
2
+ License
3
+ --------------
4
+ Copyright © 2017 Bill & Melinda Gates Foundation
5
+ The Mojaloop files are made available by the Bill & Melinda Gates Foundation under the Apache License, Version 2.0 (the "License") and you may not use these files except in compliance with the License. You may obtain a copy of the License at
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+ Unless required by applicable law or agreed to in writing, the Mojaloop files are distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
8
+ Contributors
9
+ --------------
10
+ This is the official list of the Mojaloop project contributors for this file.
11
+ Names of the original copyright holders (individuals or organizations)
12
+ should be listed with a '*' in the first column. People who have
13
+ contributed from an organization can be listed under the organization
14
+ that actually holds the copyright for their contributions (see the
15
+ Gates Foundation organization for an example). Those individuals should have
16
+ their names indented and be marked with a '-'. Email address can be added
17
+ optionally within square brackets <email>.
18
+ * Gates Foundation
19
+
20
+ * ModusBox
21
+ * Vijaya Kumar Guthi <vijaya.guthi@modusbox.com> (Original Author)
22
+ --------------
23
+ ******/
24
+
25
+ const { spy, stub } = require('sinon')
26
+
27
+ const mockResponse = (options = {}) => {
28
+ const res = {
29
+ cookie: spy(),
30
+ clearCookie: spy(),
31
+ download: spy(),
32
+ format: spy(),
33
+ getHeader: spy(),
34
+ json: spy(),
35
+ jsonp: spy(),
36
+ send: spy(),
37
+ sendFile: spy(),
38
+ sendStatus: spy(),
39
+ setHeader: spy(),
40
+ redirect: spy(),
41
+ render: spy(),
42
+ end: spy(),
43
+ set: spy(),
44
+ type: spy(),
45
+ get: stub(),
46
+ ...options
47
+ }
48
+ res.status = stub().returns(res)
49
+ res.vary = stub().returns(res)
50
+ return res
51
+ }
52
+
53
+ module.exports = mockResponse
@@ -0,0 +1,36 @@
1
+ /*****
2
+ License
3
+ --------------
4
+ Copyright © 2017 Bill & Melinda Gates Foundation
5
+ The Mojaloop files are made available by the Bill & Melinda Gates Foundation under the Apache License, Version 2.0 (the "License") and you may not use these files except in compliance with the License. You may obtain a copy of the License at
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+ Unless required by applicable law or agreed to in writing, the Mojaloop files are distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
8
+ Contributors
9
+ --------------
10
+ This is the official list of the Mojaloop project contributors for this file.
11
+ Names of the original copyright holders (individuals or organizations)
12
+ should be listed with a '*' in the first column. People who have
13
+ contributed from an organization can be listed under the organization
14
+ that actually holds the copyright for their contributions (see the
15
+ Gates Foundation organization for an example). Those individuals should have
16
+ their names indented and be marked with a '-'. Email address can be added
17
+ optionally within square brackets <email>.
18
+ * Gates Foundation
19
+
20
+ * ModusBox
21
+ * Georgi Logodazhki <georgi.logodazhki@modusbox.com> (Original Author)
22
+ --------------
23
+ ******/
24
+ 'use strict'
25
+
26
+ const spyRouter = jest.spyOn(require('../../src/router'), 'cli')
27
+
28
+ describe('Cli client', () => {
29
+ it('running the client should not throw an error', async () => {
30
+ process.argv = ['', '']
31
+ spyRouter.mockReturnValueOnce({})
32
+ expect(() => {
33
+ require('../../src/client')
34
+ }).not.toThrowError();
35
+ })
36
+ })
@@ -0,0 +1,99 @@
1
+ /*****
2
+ License
3
+ --------------
4
+ Copyright © 2017 Bill & Melinda Gates Foundation
5
+ The Mojaloop files are made available by the Bill & Melinda Gates Foundation under the Apache License, Version 2.0 (the "License") and you may not use these files except in compliance with the License. You may obtain a copy of the License at
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+ Unless required by applicable law or agreed to in writing, the Mojaloop files are distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
8
+ Contributors
9
+ --------------
10
+ This is the official list of the Mojaloop project contributors for this file.
11
+ Names of the original copyright holders (individuals or organizations)
12
+ should be listed with a '*' in the first column. People who have
13
+ contributed from an organization can be listed under the organization
14
+ that actually holds the copyright for their contributions (see the
15
+ Gates Foundation organization for an example). Those individuals should have
16
+ their names indented and be marked with a '-'. Email address can be added
17
+ optionally within square brackets <email>.
18
+ * Gates Foundation
19
+
20
+ * ModusBox
21
+ * Vijay Kumar Guthi <vijaya.guthi@modusbox.com> (Original Author)
22
+ --------------
23
+ ******/
24
+ 'use strict'
25
+
26
+ const AWS = require('aws-sdk')
27
+ jest.mock('aws-sdk')
28
+ AWS.config.update.mockReturnValueOnce()
29
+ const s3UploadMockResolve = {
30
+ upload: () => {
31
+ return {
32
+ promise: async () => {
33
+ return {
34
+ Location: 'some_url'
35
+ }
36
+ }
37
+ }
38
+ }
39
+ }
40
+ const s3UploadMockReject = {
41
+ upload: () => {
42
+ throw new Error()
43
+ }
44
+ }
45
+
46
+ const s3Upload = require('../../../src/extras/s3-upload')
47
+
48
+ const s3SampleURL = 's3://some_bucket/file_key.html'
49
+ const sampleFileData = 'asdf'
50
+
51
+ describe('Cli client', () => {
52
+ describe('uploadFileDataToS3', () => {
53
+ it('when there are no AWS credentials, it should return undefined', async () => {
54
+ AWS.config.credentials = null
55
+ AWS.config.region = 'asdf'
56
+ await expect(s3Upload.uploadFileDataToS3(s3SampleURL, sampleFileData)).resolves.toBe(undefined)
57
+ })
58
+ it('when there are some AWS credentials, and no AWS region set it should return undefined', async () => {
59
+ AWS.config.credentials = {
60
+ asdf: 'asdf'
61
+ }
62
+ AWS.config.region = null
63
+ await expect(s3Upload.uploadFileDataToS3(s3SampleURL, sampleFileData)).resolves.toBe(undefined)
64
+ })
65
+ it('when the url is in wrong format it should return undefined', async () => {
66
+ AWS.config.credentials = {
67
+ asdf: 'asdf'
68
+ }
69
+ AWS.config.region = 'asdf'
70
+ await expect(s3Upload.uploadFileDataToS3('wrong://asdf/', sampleFileData)).resolves.toBe(undefined)
71
+ })
72
+ it('when there are some AWS credentials, and AWS region it should return some_url', async () => {
73
+ AWS.config.credentials = {
74
+ asdf: 'asdf'
75
+ }
76
+ AWS.config.region = 'asdf'
77
+ AWS.S3.mockReturnValueOnce(s3UploadMockResolve)
78
+ await expect(s3Upload.uploadFileDataToS3(s3SampleURL, sampleFileData)).resolves.toBe('some_url')
79
+ })
80
+ it('when there are some AWS credentials, and AWS region, and sample url not ends with html or htm it should return some_url', async () => {
81
+ AWS.config.credentials = {
82
+ asdf: 'asdf'
83
+ }
84
+ AWS.config.region = 'asdf'
85
+ AWS.S3.mockReturnValueOnce(s3UploadMockResolve)
86
+ const s3SampleURL = 's3://some_bucket/file_key.ht'
87
+ await expect(s3Upload.uploadFileDataToS3(s3SampleURL, sampleFileData)).resolves.toBe('some_url')
88
+ })
89
+ it('when there are some AWS credentials, and AWS region, and s3 upload fails, it should return null', async () => {
90
+ AWS.config.credentials = {
91
+ asdf: 'asdf'
92
+ }
93
+ AWS.config.region = 'asdf'
94
+ AWS.S3.mockReturnValueOnce(s3UploadMockReject)
95
+ await expect(s3Upload.uploadFileDataToS3(s3SampleURL, sampleFileData)).resolves.toBe(null)
96
+ })
97
+
98
+ })
99
+ })
@@ -0,0 +1,125 @@
1
+ /*****
2
+ License
3
+ --------------
4
+ Copyright © 2017 Bill & Melinda Gates Foundation
5
+ The Mojaloop files are made available by the Bill & Melinda Gates Foundation under the Apache License, Version 2.0 (the "License") and you may not use these files except in compliance with the License. You may obtain a copy of the License at
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+ Unless required by applicable law or agreed to in writing, the Mojaloop files are distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
8
+ Contributors
9
+ --------------
10
+ This is the official list of the Mojaloop project contributors for this file.
11
+ Names of the original copyright holders (individuals or organizations)
12
+ should be listed with a '*' in the first column. People who have
13
+ contributed from an organization can be listed under the organization
14
+ that actually holds the copyright for their contributions (see the
15
+ Gates Foundation organization for an example). Those individuals should have
16
+ their names indented and be marked with a '-'. Email address can be added
17
+ optionally within square brackets <email>.
18
+ * Gates Foundation
19
+
20
+ * ModusBox
21
+ * Vijay Kumar Guthi <vijaya.guthi@modusbox.com> (Original Author)
22
+ --------------
23
+ ******/
24
+ 'use strict'
25
+
26
+ const { IncomingWebhook } = require('@slack/webhook')
27
+ jest.mock('@slack/webhook')
28
+ const webhook = {
29
+ send: async () => {}
30
+ }
31
+ IncomingWebhook.mockImplementationOnce(() => {
32
+ return webhook
33
+ })
34
+ const SpySlackSend = jest.spyOn(webhook, 'send')
35
+
36
+ const objectStore = require('../../../src/objectStore')
37
+ jest.mock('../../../src/objectStore')
38
+ const config = {
39
+ slackPassedImage: 'asdf',
40
+ slackFailedImage: 'asdf',
41
+ extraSummaryInformation: "info1:value1,info2:value2"
42
+ }
43
+ objectStore.get.mockReturnValue(config)
44
+
45
+ const slackBroadCast = require('../../../src/extras/slack-broadcast')
46
+
47
+ const sampleProgress = {
48
+ test_cases: [],
49
+ runtimeInformation: {}
50
+ }
51
+ const sampleReportURL = 'asdf'
52
+
53
+ describe('Cli client', () => {
54
+ describe('sendSlackNotification', () => {
55
+ it('When slackWebhookUrl config is null, it should do nothing', async () => {
56
+ config.slackWebhookUrl = null
57
+ SpySlackSend.mockResolvedValueOnce(null)
58
+ await expect(slackBroadCast.sendSlackNotification(sampleProgress)).resolves.toBe(undefined)
59
+ })
60
+ it('When slackWebhookUrl config is set, it should call slack send function', async () => {
61
+ config.slackWebhookUrl = 'http://some_url'
62
+ SpySlackSend.mockResolvedValueOnce(null)
63
+ await expect(slackBroadCast.sendSlackNotification(sampleProgress)).resolves.toBe(undefined)
64
+ expect(SpySlackSend).toHaveBeenCalledWith(expect.objectContaining({
65
+ text: expect.any(String),
66
+ blocks: expect.any(Array)
67
+ }))
68
+ })
69
+ it('When reportURL is set, it should call slack send function', async () => {
70
+ config.slackWebhookUrl = 'http://some_url'
71
+ SpySlackSend.mockResolvedValueOnce(null)
72
+ await expect(slackBroadCast.sendSlackNotification(sampleProgress, sampleReportURL)).resolves.toBe(undefined)
73
+ expect(SpySlackSend).toHaveBeenCalledWith(expect.objectContaining({
74
+ text: expect.any(String),
75
+ blocks: expect.any(Array)
76
+ }))
77
+ })
78
+ it('When the progress contains testCases, it should call slack send function', async () => {
79
+ config.slackWebhookUrl = 'http://some_url'
80
+ sampleProgress.test_cases = [
81
+ {
82
+ requests: [
83
+ {
84
+ request: {
85
+ tests: {
86
+ assertions: [],
87
+ passedAssertionsCount: 0
88
+ }
89
+ }
90
+ }
91
+ ]
92
+ }
93
+ ]
94
+ SpySlackSend.mockResolvedValueOnce(null)
95
+ await expect(slackBroadCast.sendSlackNotification(sampleProgress)).resolves.toBe(undefined)
96
+ expect(SpySlackSend).toHaveBeenCalledWith(expect.objectContaining({
97
+ text: expect.any(String),
98
+ blocks: expect.any(Array)
99
+ }))
100
+ })
101
+ it('When failed case, it should call slack send function', async () => {
102
+ config.slackWebhookUrl = 'http://some_url'
103
+ sampleProgress.test_cases = [
104
+ {
105
+ requests: [
106
+ {
107
+ request: {
108
+ tests: {
109
+ assertions: [{}],
110
+ passedAssertionsCount: 0
111
+ }
112
+ }
113
+ }
114
+ ]
115
+ }
116
+ ]
117
+ SpySlackSend.mockResolvedValueOnce(null)
118
+ await expect(slackBroadCast.sendSlackNotification(sampleProgress)).resolves.toBe(undefined)
119
+ expect(SpySlackSend).toHaveBeenCalledWith(expect.objectContaining({
120
+ text: expect.any(String),
121
+ blocks: expect.any(Array)
122
+ }))
123
+ })
124
+ })
125
+ })