Skip to content

Commit

Permalink
updating subscription tests for auth_model default
Browse files Browse the repository at this point in the history
  • Loading branch information
dalehille committed May 28, 2020
1 parent 27ef05a commit f27a95e
Show file tree
Hide file tree
Showing 9 changed files with 98 additions and 146 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -70,3 +70,5 @@ dev/
# vscode settings
.vscode
.DS_Store

.nvmrc
1 change: 1 addition & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ script:
- if [ "${TRAVIS_PULL_REQUEST}" != "false" ]; then npx audit-ci --low; else npx audit-ci --low || true; fi
- npm run lint
- npm test
- npm run test:apollo:default
- npm run test:apollo:local
- npm run test:apollo:passport.local
- docker build --rm -t "quay.io/razee/razeedash-api:${TRAVIS_COMMIT}" .
Expand Down
4 changes: 2 additions & 2 deletions app/apollo/models/user.default.schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,6 @@ UserDefaultSchema.statics.userTokenIsAuthorized = async function(me, orgId, acti

UserDefaultSchema.statics.isAuthorized = async function(me, orgId, action, type, attributes, req_id) {
logger.debug({ req_id: req_id },`default isAuthorized ${action} ${type} ${attributes}`);
logger.debug('default isAuthorized me', me);

if (AUTH_MODEL === AUTH_MODELS.DEFAULT) {
const user = await this.findOne({ apiKey: me.apiKey }).lean();
Expand All @@ -114,14 +113,15 @@ UserDefaultSchema.statics.isAuthorized = async function(me, orgId, action, type,
};

UserDefaultSchema.statics.isValidOrgKey = async function(models, me) {
logger.debug('default isValidOrgKey', me);
logger.debug('default isValidOrgKey');
if (AUTH_MODEL === AUTH_MODELS.DEFAULT) {

const org = await models.Organization.findOne({ orgKeys: me.orgKey }).lean();
if(!org) {
logger.error('An org was not found for this razee-org-key');
throw new ForbiddenError('org id was not found');
}
logger.debug('org found using orgKey');
return org;
}
return false;
Expand Down
1 change: 0 additions & 1 deletion app/apollo/resolvers/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ const whoIs = me => {
// Throw exception if not.
const validAuth = async (me, org_id, action, type, queryName, context) => {
const {req_id, models, logger} = context;
logger.debug('validAuth', me);

// razeedash users (x-api-key)
if(me && me.type == 'userToken'){
Expand Down
4 changes: 4 additions & 0 deletions app/apollo/test/data/default/cluster.spec.org_01.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"type": "local",
"name": "org_01"
}
201 changes: 60 additions & 141 deletions app/apollo/test/subscriptions.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,35 +19,24 @@ const fs = require('fs');
const { MongoMemoryServer } = require('mongodb-memory-server');

const { models } = require('../models');
const apiFunc = require('./api');
const subscriptionsFunc = require('./subscriptionsApi');

const apollo = require('../index');
const { AUTH_MODEL } = require('../models/const');
const { GraphqlPubSub } = require('../subscription');

const { prepareUser, prepareOrganization, signInUser } = require(`./testHelper.${AUTH_MODEL}`);
const { prepareOrganization } = require(`./testHelper.${AUTH_MODEL}`);
let mongoServer;
let myApollo;
const graphqlPort = 18000;
const graphqlUrl = `http://localhost:${graphqlPort}/graphql`;
const api = apiFunc(graphqlUrl);
const subscriptionsApi = subscriptionsFunc(graphqlUrl);
let token;
let orgKey;

let org01Data;
let org01;

let user01Data;
let user77Data;
let userRootData;

let presetOrgs;
let presetUsers;
let presetClusters;
let presetSubs;

const channel_01_name = 'fake_channel_01';
const channel_01_uuid = 'fake_ch_01_uuid';

Expand All @@ -73,67 +62,6 @@ const createOrganizations = async () => {
org01 = await prepareOrganization(models, org01Data);
};

const createUsers = async () => {
user01Data = JSON.parse(
fs.readFileSync(
`./app/apollo/test/data/${AUTH_MODEL}/cluster.spec.user01.json`,
'utf8',
),
);
await prepareUser(models, user01Data);
user77Data = JSON.parse(
fs.readFileSync(
`./app/apollo/test/data/${AUTH_MODEL}/cluster.spec.user77.json`,
'utf8',
),
);
await prepareUser(models, user77Data);
userRootData = JSON.parse(
fs.readFileSync(
`./app/apollo/test/data/${AUTH_MODEL}/cluster.spec.root.json`,
'utf8',
),
);
await prepareUser(models, userRootData);
return {};
};

// eslint-disable-next-line no-unused-vars
const getPresetOrgs = async () => {
presetOrgs = await models.Organization.find();
presetOrgs = presetOrgs.map(user => {
return user.toJSON();
});
console.log(`presetOrgs=${JSON.stringify(presetOrgs)}`);
};

// eslint-disable-next-line no-unused-vars
const getPresetUsers = async () => {
presetUsers = await models.User.find();
presetUsers = presetUsers.map(user => {
return user.toJSON();
});
console.log(`presetUsers=${JSON.stringify(presetUsers)}`);
};

// eslint-disable-next-line no-unused-vars
const getPresetClusters = async () => {
presetClusters = await models.Cluster.find();
presetClusters = presetClusters.map(cluster => {
return cluster.toJSON();
});
console.log(`presetClusters=${JSON.stringify(presetClusters)}`);
};

// eslint-disable-next-line no-unused-vars
const getPresetSubs= async () => {
presetSubs = await models.Subscription.find();
presetSubs = presetSubs.map(sub=> {
return sub.toJSON();
});
console.log(`presetSubs=${JSON.stringify(presetSubs)}`);
};

const createChannels = async () => {
await models.Channel.create({
_id: 'fake_ch_id_1',
Expand Down Expand Up @@ -191,77 +119,68 @@ const getOrgKey = async () => {
return presetOrgs[0].orgKeys[0];
};

describe('subscriptions graphql test suite', () => {
before(async () => {
process.env.NODE_ENV = 'test';
mongoServer = new MongoMemoryServer();
const mongoUrl = await mongoServer.getConnectionString();
console.log(` cluster.js in memory test mongodb url is ${mongoUrl}`);

myApollo = await apollo({ mongo_url: mongoUrl, graphql_port: graphqlPort, });

await createOrganizations();
await createUsers();
await createChannels();
await createSubscriptions();
if(AUTH_MODEL === 'default') {
describe('subscriptions graphql test suite', () => {
before(async () => {
process.env.NODE_ENV = 'test';
mongoServer = new MongoMemoryServer();
const mongoUrl = await mongoServer.getConnectionString();
console.log(` cluster.js in memory test mongodb url is ${mongoUrl}`);

// Can be uncommented if you want to see the test data that was added to the DB
// await getPresetOrgs();
// await getPresetUsers();
// await getPresetClusters();
// await getPresetSubs();
myApollo = await apollo({ mongo_url: mongoUrl, graphql_port: graphqlPort, });

token = await signInUser(models, api, user01Data);
orgKey = await getOrgKey();
}); // before
await createOrganizations();
await createChannels();
await createSubscriptions();
orgKey = await getOrgKey();
}); // before

after(async () => {
await myApollo.stop(myApollo);
GraphqlPubSub.deleteInstance();
await mongoServer.stop();
}); // after

it('get should return a subscription with a matching tag', async () => {
try {
const {
data: {
data: { subscriptionsByTag },
},
} = await subscriptionsApi.subscriptionsByTag(token, {
org_id: org01._id,
tags: sub_01_tags
}, orgKey);

expect(subscriptionsByTag).to.have.length(1);
} catch (error) {
if (error.response) {
console.error('error encountered: ', error.response.data);
} else {
console.error('error encountered: ', error);
after(async () => {
await myApollo.stop(myApollo);
GraphqlPubSub.deleteInstance();
await mongoServer.stop();
}); // after

it('get should return a subscription with a matching tag', async () => {
try {
const {
data: {
data: { subscriptionsByTag },
},
} = await subscriptionsApi.subscriptionsByTag(token, {
tags: sub_01_tags
}, orgKey);

expect(subscriptionsByTag).to.have.length(1);
} catch (error) {
if (error.response) {
console.error('error encountered: ', error.response.data);
} else {
console.error('error encountered: ', error);
}
throw error;
}
throw error;
}
});

it('get should return an empty array when there are no matching tags', async () => {
try {
const {
data: {
data: { subscriptionsByTag },
},
} = await subscriptionsApi.subscriptionsByTag(token, {
org_id: org01._id,
tags: ''
}, orgKey);
expect(subscriptionsByTag).to.have.length(0);
} catch (error) {
if (error.response) {
console.error('error encountered: ', error.response.data);
} else {
console.error('error encountered: ', error);
});

it('get should return an empty array when there are no matching tags', async () => {
try {
const {
data: {
data: { subscriptionsByTag },
},
} = await subscriptionsApi.subscriptionsByTag(token, {
tags: ''
}, orgKey);
expect(subscriptionsByTag).to.have.length(0);
} catch (error) {
if (error.response) {
console.error('error encountered: ', error.response.data);
} else {
console.error('error encountered: ', error);
}
throw error;
}
throw error;
}
});
});

});
});
}
4 changes: 2 additions & 2 deletions app/apollo/test/subscriptionsApi.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ const subscriptionsFunc = grahqlUrl => {
grahqlUrl,
{
query: `
query($org_id: String!, $tags: String) {
subscriptionsByTag( org_id: $org_id, tags: $tags) {
query($tags: String) {
subscriptionsByTag( tags: $tags) {
subscription_name
subscription_channel
subscription_uuid
Expand Down
26 changes: 26 additions & 0 deletions app/apollo/test/testHelper.default.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/**
* Copyright 2020 IBM Corp. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is 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.
*/

const { AUTH_MODELS, AUTH_MODEL } = require('../models/const');

async function prepareOrganization(models, orgData) {
if (AUTH_MODEL === AUTH_MODELS.DEFAULT) {
return await models.Organization.createLocalOrg(orgData);
}
return null;
}

module.exports = { prepareOrganization };
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"start:debug": "node --inspect-brk app/index.js",
"test": "nyc --all --exclude=**/*.tests.js --exclude=**/*.spec.js --exclude=app/apollo/**/*.js --exclude=coverage/* --reporter=html --reporter=text mocha -r dotenv/config **/*.tests.js",
"test:apollo": "export NODE_ENV=test; nyc --exclude=**/*.spec.js --reporter=html --reporter=text mocha --timeout 5000 --exit 'app/apollo/test/*.spec.js'",
"test:apollo:default": "export AUTH_MODEL=default; export NODE_ENV=test; nyc --exclude=**/*.spec.js --reporter=html --reporter=text mocha --timeout 5000 'app/apollo/test/*.spec.js'",
"test:apollo:local": "export AUTH_MODEL=local; export NODE_ENV=test; nyc --exclude=**/*.spec.js --reporter=html --reporter=text mocha --timeout 5000 'app/apollo/test/*.spec.js'",
"test:apollo:passport.local": "export AUTH_MODEL=passport.local; export NODE_ENV=test; nyc --exclude=**/*.spec.js --reporter=html --reporter=text mocha --timeout 5000 'app/apollo/test/*.spec.js'",
"wait-mongo": "node app/wait-mongo.js",
Expand Down

0 comments on commit f27a95e

Please sign in to comment.