Skip to content

Commit

Permalink
upd gha test
Browse files Browse the repository at this point in the history
  • Loading branch information
ikethecoder committed Mar 5, 2024
1 parent 0ace2ab commit 0dbb826
Show file tree
Hide file tree
Showing 8 changed files with 216 additions and 144 deletions.
7 changes: 6 additions & 1 deletion .github/workflows/ci-feat-sonar.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ name: Sonar Scanner

on:
push:
branches: [dev, feat/*]
branches: [dev, feature/*]

env:
REGISTRY: ghcr.io
Expand All @@ -25,8 +25,13 @@ jobs:
run: |
cd src
npm i
docker compose up kong-db -d
npm test
docker compose down
- name: SonarCloud Scan
uses: sonarsource/sonarcloud-github-action@master
with:
Expand Down
2 changes: 1 addition & 1 deletion src/jest.config.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
module.exports = {
verbose: true,
testEnvironment: 'node',
testMatch: ['**/?(*.)+(test.{ts,js,jsx})'],
testMatch: ['**/?(*.)+(test.{js,jsx})'],
collectCoverageFrom: ['services/**/*.js', 'services/**/*.ts'],
coveragePathIgnorePatterns: ['.*/__mocks__/.*', '.*/@types/.*'],
coverageDirectory: '__coverage__',
Expand Down
28 changes: 20 additions & 8 deletions src/lists/Product.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const {
DeleteProductValidate,
DeleteProductEnvironments,
} = require('../services/workflow/delete-product');
const { strict: assert } = require('assert');
const { strict: assert, AssertionError } = require('assert');
const { StructuredActivityService } = require('../services/workflow');
const { regExprValidation } = require('../services/utils');

Expand Down Expand Up @@ -47,7 +47,11 @@ module.exports = {
access: EnforcementPoint,
hooks: {
resolveInput: ({ context, operation, resolvedData }) => {
logger.debug('[List.Product] Auth %j', context['authedItem']);
logger.debug(
'[List.Product] Auth %s %j',
operation,
context['authedItem']
);
if (operation == 'create') {
if ('appId' in resolvedData && isProductID(resolvedData['appId'])) {
} else {
Expand All @@ -60,12 +64,20 @@ module.exports = {
logger.debug('[List.Product] Resolved %j', resolvedData);
return resolvedData;
},
validateInput: ({ resolvedData }) => {
regExprValidation(
'^[a-zA-Z0-9 ()&-]{3,100}$',
resolvedData['name'],
"Product name must be between 3 and 100 alpha-numeric characters (including special characters ' {}&-')"
);
validateInput: ({ resolvedData, addValidationError }) => {
try {
regExprValidation(
'^[a-zA-Z0-9 ()&-]{3,100}$',
resolvedData['name'],
"Product name must be between 3 and 100 alpha-numeric characters (including special characters ' ()&-')"
);
} catch (ex) {
if (ex instanceof AssertionError) {
addValidationError(ex.message);
} else {
throw ex;
}
}
},
validateDelete: async function ({ existingItem, context }) {
await DeleteProductValidate(
Expand Down
3 changes: 2 additions & 1 deletion src/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"x-prestart": "npm run build",
"x-dev": "nodemon",
"batch": "cross-env NODE_ENV=development node dist/server-batch.js",
"intg-build": "cross-env NODE_ENV=development NODE_OPTIONS='--openssl-legacy-provider --no-experimental-fetch --dns-result-order=ipv4first' npm-run-all delete-assets copy-assets ts-build",
"dev": "cross-env NODE_ENV=development NODE_OPTIONS='--openssl-legacy-provider --no-experimental-fetch --dns-result-order=ipv4first' npm-run-all delete-assets copy-assets tsoa-gen-types tsoa-build-v1 tsoa-build-v2 ts-build ks-dev",
"ks-dev": "cross-env NODE_ENV=development DISABLE_LOGGING=true keystone dev --entry=dist/server.js",
"dev2": "cross-env NODE_ENV=development DISABLE_LOGGING=true keystone --entry=dist/index.js",
Expand All @@ -44,7 +45,7 @@
"create-tables": "cross-env CREATE_TABLES=true keystone create-tables --entry=dist/server.js",
"lint": "eslint ./nextapp --ext .ts,.tsx --quiet",
"lint:ts": "tsc -p ./nextapp/tsconfig.json --noEmit",
"test": "cross-env NODE_ENV=test jest --config ./jest.config.js --coverage --detectOpenHandles",
"test": "cross-env NODE_ENV=test NODE_OPTIONS='--openssl-legacy-provider --no-experimental-fetch --dns-result-order=ipv4first' jest --config ./jest.config.js --coverage --detectOpenHandles",
"test:next": "jest --config ./nextapp/jest.config.js --coverage",
"test:next-watch": "jest --watch --config ./nextapp/jest.config.js",
"test:watch": "jest -w --coverage",
Expand Down
119 changes: 0 additions & 119 deletions src/test/integrated/batchworker/testsuite/run.ts

This file was deleted.

23 changes: 20 additions & 3 deletions src/test/integrated/keystonejs/init.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
/*
node dist/test/integrated/keystonejs/test.js
*/
import { syncRecords } from '../../../batch/feed-worker';

import { loadRulesAndWatch } from '../../../authz/enforcement';

loadRulesAndWatch(false);
Expand All @@ -17,15 +15,34 @@ export default async function InitKeystone(
const session = require('express-session');
//const MongoStore = require('connect-mongo')(session);

const { KnexAdapter } = require('@keystonejs/adapter-knex');
const knexAdapterConfig = {
knexOptions: {
debug: process.env.LOG_LEVEL === 'debug' ? false : false,
connection: {
host: process.env.KNEX_HOST,
port: process.env.KNEX_PORT,
user: process.env.KNEX_USER,
password: process.env.KNEX_PASSWORD,
database: process.env.KNEX_DATABASE,
},
},
};

const { MongooseAdapter } = require('@keystonejs/adapter-mongoose');
const mongooseAdapterConfig = {
mongoUri: process.env.MONGO_URL,
user: process.env.MONGO_USER,
pass: process.env.MONGO_PASSWORD,
};

const adapter = process.env.ADAPTER ? process.env.ADAPTER : 'mongoose';

const keystone = new Keystone({
adapter: new MongooseAdapter(mongooseAdapterConfig),
adapter:
adapter == 'knex'
? new KnexAdapter(knexAdapterConfig)
: new MongooseAdapter(mongooseAdapterConfig),
cookieSecret: process.env.COOKIE_SECRET,
cookie: {
secure: process.env.COOKIE_SECURE === 'true', // Default to true in production
Expand Down
108 changes: 108 additions & 0 deletions src/test/services/batch/integrated-batch.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
/*
Wire up directly with Keycloak and use the Services
To run:
npm run intg-build
npm run ts-watch
node dist/test/integrated/batchworker/testsuite/run.js
*/

import InitKeystone from '../../integrated/keystonejs/init';
import {
removeKeys,
syncRecords,
getRecords,
} from '../../../batch/feed-worker';
import yaml from 'js-yaml';
import { strict as assert } from 'assert';

import testdata from './testdata';
import { Logger } from '../../../logger';
import { BatchWhereClause } from '@/services/keystone/batch-service';

const logger = Logger('testsuite');

function equalPayload(a: any, e: any) {
assert.strictEqual(
yaml.dump(a, { indent: 2, lineWidth: 100 }),
yaml.dump(e, { indent: 2, lineWidth: 100 })
);
}

function testHeading(index: number, name: string) {
console.log('\x1b[33m --------------------------------------------- \x1b[0m');
console.log('\x1b[33m ' + index + ' ' + name + ' \x1b[0m');
console.log('\x1b[33m --------------------------------------------- \x1b[0m');
}

describe('Batch Tests', function () {
it(`should pass all tests`, async function () {
await (async () => {
const keystone = await InitKeystone();
console.log('K = ' + keystone);

const ns = 'refactortime';
const skipAccessControl = true;

const identity = {
id: null,
username: 'sample_username',
namespace: ns,
roles: JSON.stringify(['api-owner']),
scopes: [],
userId: null,
} as any;

const ctx = keystone.createContext({
skipAccessControl,
authentication: { item: identity },
});

//await cleanupDatabase();

let index = 1;
for (const test of testdata.tests) {
const json: any = test.data;
testHeading(index++, test.name);
try {
if ((test.method || 'PUT') === 'PUT') {
const res = await syncRecords(
ctx,
test.entity,
json[test.refKey],
json
);
equalPayload(
removeKeys(res, ['id', 'ownedBy']),
test.expected.payload
);
} else {
const where: BatchWhereClause = test.whereClause;
const records: any[] = await getRecords(
ctx,
test.entity,
null,
test.responseFields,
where
);
const payload = records.map((o) => removeKeys(o, ['id', 'appId']));
equalPayload(payload, test.expected.payload);
}
} catch (e) {
logger.error(e.message);
if (
!test.expected?.exception ||
test.expected?.exception != `${e.message}`
) {
await keystone.disconnect();

throw e;
}
}
}

testHeading(index, 'DONE');

await keystone.disconnect();
})();
});
});
Loading

0 comments on commit 0dbb826

Please sign in to comment.