Skip to content

Commit

Permalink
Merge pull request #78 from cap-js/test-checkout
Browse files Browse the repository at this point in the history
Test setup
  • Loading branch information
danjoa authored Dec 3, 2024
2 parents 043b1b4 + 5ce58ea commit d8ece8c
Show file tree
Hide file tree
Showing 27 changed files with 597 additions and 658 deletions.
102 changes: 27 additions & 75 deletions .github/workflows/checkout
Original file line number Diff line number Diff line change
@@ -1,81 +1,33 @@
#!/usr/bin/env node
/* eslint-disable no-console */

const [,,$1] = process.argv
const { exec } = require('child_process')
const path = require('path')
const { readFile, writeFile } = require("fs").promises;
const { join } = require("path");

async function remoteService () {
const TARGET_DIR = "xmpls/remote-service"
const levelUP = "../../"
const INCLUDES = ["srv", "test"]
const paths = INCLUDES.map(pattern => join(__dirname, levelUP, TARGET_DIR, pattern))
const cmd = `cp -r ${paths.join(' ')} ${join(__dirname, levelUP)}`
await run(cmd);

const packageJson = JSON.parse(await readFile(join(__dirname, levelUP ,"package.json"), "utf-8"));
const delta = JSON.parse(await readFile(join(__dirname, levelUP, TARGET_DIR, "package.json"), "utf-8"));
packageJson.cds.requires["API_BUSINESS_PARTNER"] = delta.cds.requires["API_BUSINESS_PARTNER"]
await writeFile(join(__dirname, levelUP, "package.json"), JSON.stringify(packageJson, null, 2), "utf-8");

// dependencies
const deps = [
"@sap-cloud-sdk/connectivity",
"@sap-cloud-sdk/http-client",
"@sap-cloud-sdk/resilience",
"@sap-cloud-sdk/util"
]
return await run(`npm add ${deps.join(" ")}`)
const { fs, path, exists, copy, read, write, append=_append } = require("@sap/cds").utils

async function checkout (xmpl, ...requires) {
// copy content from xmpl to incidents...
await Promise.all (['app','srv','db','test'] .map (async each => {
let src = `xmpls/${xmpl}/${each}`
if (exists(src)) return await copy(src).to(each)
}))
// enhance package.json
let xmpls = await read (`xmpls/${xmpl}/package.json`)
let base = await read ('package.json')
for (let each of requires) base.cds.requires[each] = xmpls.cds.requires[each]
if (append === _append) base = _formatted(base) //> for older cds versions only
await write (base) .to ('package.json')
}

async function messaging () {
const TARGET_DIR = "xmpls/messaging"
const levelUP = "../../"
const INCLUDES = ["app", "srv", "test"]
const paths = INCLUDES.map(pattern => join(__dirname, levelUP, TARGET_DIR, pattern))
const cmd = `cp -r ${paths.join(' ')} ${join(__dirname, levelUP)}`
await run(cmd);
exports['remote-service'] = ()=>
checkout ('remote-service', 'API_BUSINESS_PARTNER')

const packageJson = JSON.parse(await readFile(join(__dirname, levelUP, "package.json"), "utf-8"));
const delta = JSON.parse(await readFile(join(__dirname, levelUP, TARGET_DIR, "package.json"), "utf-8"));
packageJson.cds.requires["API_BUSINESS_PARTNER"] = delta.cds.requires["API_BUSINESS_PARTNER"]
packageJson.cds.requires["messaging"] = delta.cds.requires["messaging"]
await writeFile(join(__dirname, levelUP, "package.json"), JSON.stringify(packageJson, null, 2), "utf-8");
exports['messaging'] = ()=> Promise.all([
checkout ('messaging', 'messaging', 'API_BUSINESS_PARTNER'),
append ('\n'+`using from './incidents/field';`+'\n') .to ('app/services.cds') // add email fields to UI
])

// dependencies
const deps = [
"@sap-cloud-sdk/connectivity",
"@sap-cloud-sdk/http-client",
"@sap-cloud-sdk/resilience",
"@sap-cloud-sdk/util",
"@sap/xb-msg-amqp-v100"
]
return await run(`npm add ${deps.join(" ")}`)
}

function run (cmd, silent) {
if (cmd.raw) return run (String.raw(...arguments))
if (cmd.endsWith('--silent')) silent = cmd = cmd.slice(0,-9)
if (typeof cmd === 'string') cmd = new Promise ((done,failed) => {
const cp = exec (cmd, (e,stdout) => e ? failed(e) : done(stdout))
if (!silent) {
cp.stdout.on ('data', d => process.stdout.write(d))
cp.stderr.on ('data', d => process.stderr.write(d))
}
})
return cmd
}
if (!module.parent) exports[process.argv[2]]?.().catch(console.error) || console.log (
`Usage: ${path.relative(process.cwd(),__filename)} ${Object.keys(exports).join('|')}`
)

switch ($1) {

case 'remote-service':
remoteService();
break;
case 'messaging':
messaging();
break;
default:
console.log('Usage: ./checkout <command>');
}
// ------------------------------------------------------------------------
// fixes for missing features in older cds versions
function _append (str) { return { to: file => fs.promises.appendFile(path.join(cds.root,file), str) }}
function _formatted (json) { return JSON.stringify(json,null,2) }
6 changes: 3 additions & 3 deletions .github/workflows/create-test-branch.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@ jobs:
run: |
npm run add-all-xmpls
rm -rf xmpls
- name: Test
run: |
npm i
npm test
npm test -- --colors
- name: Extract last commit author email and name
id: extract_commit_info
run: |
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/node.js.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ jobs:
with:
node-version: ${{ matrix.node-version }}
- run: npm i
- run: npm test
- run: npm test -- --colors

push:
name: Push to CDS Test branch
Expand Down
2 changes: 1 addition & 1 deletion cds-plugin.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const cds = require("@sap/cds");
const cds = require("@sap/cds")
cds.once('bootstrap', (app) => {
app.serve('/incidents/app').from(__dirname,'/app/incidents/webapp')
})
25 changes: 15 additions & 10 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,12 @@
"express": "^4"
},
"devDependencies": {
"@cap-js/sqlite": "^1.7.3",
"@sap/ux-specification": "^1.120.16",
"axios": "^1.7.3",
"@cap-js/audit-logging": "^0.8.0",
"@cap-js/change-tracking": "^1.0.6",
"@cap-js/attachments": "^1.1.6",
"@cap-js/sqlite": "^1.0.1",
"@sap/ux-specification": "^1.108.4",
"axios": "^1.4.0",
"chai": "^4.3.7",
"chai-as-promised": "^7.1.1",
"chai-subset": "^1.6.0"
Expand All @@ -27,18 +30,20 @@
"watch": "cds watch",
"start": "cds-serve",
"test": "npx jest --silent",
"add-attachments": "npm add @cap-js/attachments && cp -r xmpls/attachments.cds ./db && cp xmpls/attachments.test.js ./test",
"add-change-tracking": "npm add @cap-js/change-tracking && cp xmpls/change-tracking.cds ./srv && cp xmpls/change-tracking.test.js ./test",
"add-change-tracking": "npm add @cap-js/change-tracking && cp xmpls/change-tracking.cds ./srv",
"add-telemetry": "npm add @cap-js/telemetry",
"add-attachments": "npm add @cap-js/attachments && cp -r xmpls/attachments.cds ./srv",
"add-notifications": "npm add @cap-js/notifications && cp xmpls/alert-notifications.js ./srv && cp xmpls/notification-types.json ./srv",
"add-audit-log": "npm add @cap-js/audit-logging && cp xmpls/data-privacy.cds ./srv && cp xmpls/audit-log.test.js ./test",
"add-remote-service": "./.github/workflows/checkout remote-service",
"add-messaging": "./.github/workflows/checkout messaging",
"add-audit-log": "npm add @cap-js/audit-logging && cp xmpls/data-privacy.cds ./srv",
"add-remote-service": ".github/workflows/checkout remote-service",
"add-messaging": ".github/workflows/checkout messaging",
"add-all-xmpls": "npm run add-remote-service && npm run add-messaging && npm run add-change-tracking && npm run add-audit-log",
"reset": "read -p 'This will irreversibly reset your working directory including ALL files in this git repo. Continue?' -n 1 -r && echo && if [[ $REPLY =~ ^[Yy]$ ]]; then git clean -fd && git reset --hard && npm i; fi"
},
"jest": {
"modulePathIgnorePatterns": ["<rootDir>/xmpls/"]
"modulePathIgnorePatterns": [
"<rootDir>/xmpls/"
]
},
"sapux": [
"app/incidents"
Expand All @@ -65,4 +70,4 @@
}
},
"private": true
}
}
73 changes: 73 additions & 0 deletions test/attachments.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
const cds = require('@sap/cds')

describe('Test attachments service', () => {

const { copy, rm, exists, path } = cds.utils; cds.root = path.resolve(__dirname,'..')
beforeAll (()=> copy('xmpls/attachments.cds').to('srv/attachments.cds'))
afterAll (() => rm('srv/attachments.cds'))

it('should have the srv/attachments.cds file in place', () => {
expect(exists('srv/attachments.cds')).to.be.true
})

const { GET, POST, PUT, DELETE , expect, axios} = cds.test()
axios.defaults.auth = { username: 'alice' }

const Incidents = '/odata/v4/processor/Incidents'
const edit = 'ProcessorService.draftEdit'
const activate = 'ProcessorService.draftActivate'
const active = 'IsActiveEntity=true'
const draft = 'IsActiveEntity=false'
let ID = null, id = null

it('should create a new incident ', async () => {
const { status, data } = await POST(`${Incidents}`, {
title: 'Urgent attention required !',
status_code: 'N'
})
expect(status).to.equal(201)
ID = `ID=${data.ID}` //> captures the newly created Incident's ID for subsequent use...
})

it('should activate the draft', async () => {
const response = await POST `${Incidents}(${ID},${draft})/${activate}`
expect(response.status).to.eql(201)
})

it(`should edit the incident to add an attachment`, async () => {
await POST `${Incidents}(${ID},${active})/${edit}`

// Add an attachment entry
const created = await POST (`${Incidents}(${ID},${draft})/attachments`, {
up__ID: ID,
filename: "SolarPanelReport.pdf",
mimeType: "application/pdf",
status: "Clean",
}, { headers: { 'Content-Type': 'application/json' }})
expect(created.status).to.equal(201)
id = `ID=${created.data.ID}` //> captures the newly created Attachments's ID for subsequent use...

// Upload the file
const uploaded = await PUT (`${Incidents}_attachments(up__${ID},${id},${draft})/content`,
require('fs').createReadStream (cds.root+'/xmpls/SolarPanelReport.pdf'),
{ headers: { 'Content-Type': 'application/pdf' }}
)
expect(uploaded.status).to.equal(204)

// Activate the draft
const activated = await POST `${Incidents}(${ID},${draft})/${activate}`
expect(activated.status).to.eql(200)
})


it('should check the uploaded file', async () => {
const { status, data} = await GET `${Incidents}(${ID},${active})/attachments(up__${ID},${id})/content`
expect(status).to.equal(200)
expect(data).to.not.be.undefined
})

it('should delete the incident', async () => {
const { status } = await DELETE `${Incidents}(${ID},${active})`
expect(status).to.eql(204)
})
})
61 changes: 61 additions & 0 deletions test/audit-log.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
const cds = require("@sap/cds")
const e = require("express")


describe("Integration Test for AuditLog", () => {

const { copy, rm, exists, path } = cds.utils; cds.root = path.resolve(__dirname,'..')
beforeAll (()=> copy('xmpls/data-privacy.cds').to('srv/data-privacy.cds'))
afterAll (() => rm('srv/data-privacy.cds'))

it('should have the srv/data-privacy.cds file in place', () => {
expect(exists('srv/data-privacy.cds')).to.be.true
})

const { GET, POST, PATCH , expect, axios} = cds.test()
axios.defaults.auth = { username: 'alice' }

let ID
let audit; beforeAll (async () => {
audit = await cds.connect.to('audit-log')
audit.on('PersonalDataModified', req => expect(req.event).to.include('PersonalDataModified'))
audit.on('SensitiveDataRead', req => expect(req.event).to.include("SensitiveDataRead"))
})

it("Should return list of Customers", async () => {
const {status} = await GET `/odata/v4/processor/Customers`
expect(status).to.eql(200)
})


it("Should return list of Customers data by explicitly selecting the fields", async () => {
const {status} = await GET `/odata/v4/processor/Customers?$select=name`
expect(status).to.eql(200)
})


it('Creating a customer with personal data', async () => {
const { status, data } = await POST (`/odata/v4/admin/Customers`, {
ID: "{{$guid}}",
firstName: "Bob",
lastName: "Builder",
email: "[email protected]"
})
expect(status).to.equal(201)
ID = data.ID
})

it('Updating a customer with personal data details', async () => {
const {status} = await PATCH (`/odata/v4/admin/Customers('${ID}')`, {
"addresses": [
{
"city": "Walldorf",
"postCode": "69190",
"streetAddress": "Dietmar-Hopp-Allee 16"
}
]
})
expect(status).to.equal(200)
})

})
24 changes: 13 additions & 11 deletions test/basics.test.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,25 @@
const cds = require('@sap/cds/lib')
const { GET, expect, axios } = cds.test(__dirname + '/..', '--with-mocks')

axios.defaults.auth = { username: 'alice' }
const cds = require('@sap/cds')

describe('Test The GET Endpoints', () => {
const { GET, expect, axios } = cds.test(__dirname+'/..')
axios.defaults.auth = { username: 'alice' }

it('Should check Processor Service', async () => {
const processorService = await cds.connect.to('ProcessorService')
const { Incidents } = processorService.entities
expect(await SELECT.from(Incidents)).to.have.length(4)
let srv = await cds.connect.to('ProcessorService')
let {Incidents} = srv.entities
let incidents = await SELECT.from(Incidents)
expect(incidents).to.have.length(4)
})

it('Should check Customers', async () => {
const processorService = await cds.connect.to('ProcessorService')
const { Customers } = processorService.entities
expect(await SELECT.from(Customers)).to.have.length(3)
let srv = await cds.connect.to('ProcessorService')
let {Customers} = srv.entities
let customers = await SELECT.from(Customers)
expect(customers).to.have.length(3)
})

it('Test Expand Entity Endpoint', async () => {
const { data } = await GET`/odata/v4/processor/Customers?$select=firstName&$expand=incidents`
let {data} = await GET `/odata/v4/processor/Customers?$select=firstName&$expand=incidents`
expect(data).to.be.an('object')
})
})
Loading

0 comments on commit d8ece8c

Please sign in to comment.