chai#should TypeScript Examples
The following examples show how to use
chai#should.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: warnings.tests.ts From sixpg with MIT License | 6 votes |
describe.skip('commands/warnings', () => {
it('null channel, throws error', () =>
{
const ctx = mock<CommandContext>();
const result = () => new WarningsCommand().execute(ctx, '1');
result().should.eventually.throw();
});
});
Example #2
Source File: accountant.ts From polkadot-payouts with Apache License 2.0 | 6 votes |
async function checkRestriction(cfg: checkReceiverInput): Promise<void> {
const txs = defaultTransactions();
txs.pop();
txs[0].restriction = {
remaining: cfg.remaining,
desired: cfg.desired,
};
const subject = new Accountant({transactions:txs, claims:[], minimumSenderBalance:MinimumSenderBalance}, client, logger);
const sendStub = sandbox.stub(client, 'send');
const balanceOfKeystoreStub = sandbox.stub(client, 'balanceOfKeystore');
const balanceOfStub = sandbox.stub(client, 'balanceOf');
const senderBalance = new BN(cfg.senderBalance) as Balance;
const receiverBalance = new BN(cfg.receiverBalance) as Balance;
balanceOfKeystoreStub.onFirstCall().resolves(senderBalance);
balanceOfStub.onFirstCall().resolves(receiverBalance);
await subject.run();
const expectedSent = new BN(cfg.expectedSent) as Balance;
sendStub.calledWith(keystore1, receiverAddr1, expectedSent).should.be.true;
}
Example #3
Source File: any.spec.ts From dyngoose with ISC License | 6 votes |
describe('AttributeType/Any', () => {
let record: TestableTable
beforeEach(() => {
record = new TestableTable()
})
it('should store objects into JSON', async () => {
record.id = 30
record.title = 'json test'
const value = {
dogs: 'good',
cats: 'okay',
ferrets: 'stinky',
}
expect(record.generic).eq(null, 'starts as null')
record.generic = value
expect(record.generic).to.deep.eq(value, 'accepts a javascript object')
expect(record.getAttributeDynamoValue('generic')).deep.eq({ S: JSON.stringify(value) }, 'stores in json')
try {
await record.save()
} catch (ex) {
should().not.exist(ex)
}
const loaded = await TestableTable.primaryKey.get(30, 'json test')
expect(loaded).to.be.instanceof(TestableTable)
if (loaded != null) {
expect(loaded.generic).to.deep.eq(value, 'after loading record from dynamo')
}
})
})
Example #4
Source File: play.tests.ts From sixpg with MIT License | 6 votes |
describe.skip('commands/play', () => {
it('null query, throws error', () =>
{
const ctx = mock<CommandContext>();
ctx.member = { voice: { channel: null }} as any;
const result = () => new PlayCommand().execute(ctx);
result().should.eventually.throw();
});
it('null channel, throws error', () =>
{
const ctx = mock<CommandContext>();
ctx.member = { voice: { channel: null }} as any;
const result = () => new PlayCommand().execute(ctx, 'a');
result().should.eventually.throw();
});
});
Example #5
Source File: pause.tests.ts From sixpg with MIT License | 5 votes |
should();
Example #6
Source File: leveling.tests.ts From sixpg with MIT License | 5 votes |
should();
Example #7
Source File: announce.tests.ts From sixpg with MIT License | 5 votes |
should();
Example #8
Source File: warnings.tests.ts From sixpg with MIT License | 5 votes |
should();
Example #9
Source File: stop.tests.ts From sixpg with MIT License | 5 votes |
should();
Example #10
Source File: resume.tests.ts From sixpg with MIT License | 5 votes |
should();
Example #11
Source File: play.tests.ts From sixpg with MIT License | 5 votes |
should();
Example #12
Source File: accountant.ts From polkadot-payouts with Apache License 2.0 | 5 votes |
should();
Example #13
Source File: accountant.ts From polkadot-payouts with Apache License 2.0 | 5 votes |
describe('E2E', () => {
before(async () => {
await testRPC.start();
keyring = new Keyring({ type: 'sr25519' });
});
after(async () => {
await testRPC.stop();
});
it('should send the transactions with remaining and desired restrictions', async () => {
const alice = keyring.addFromUri('//Alice');
const bob = keyring.addFromUri('//Bob');
const charlie = keyring.addFromUri('//Charlie');
const ferdie = keyring.addFromUri('//Ferdie');
const pass = 'pass';
const passFile = tmp.fileSync();
fs.writeSync(passFile.fd, pass);
const aliceKeypairJson = keyring.toJson(alice.address, pass);
const aliceKsFile = tmp.fileSync();
fs.writeSync(aliceKsFile.fd, JSON.stringify(aliceKeypairJson));
const charlieKeypairJson = keyring.toJson(charlie.address, pass);
const charlieKsFile = tmp.fileSync();
fs.writeSync(charlieKsFile.fd, JSON.stringify(charlieKeypairJson));
const aliceInitBalance = await client.balanceOf(alice.address);
const bobInitBalance = await client.balanceOf(bob.address);
const remaining = new BN("5000000000000");
const desired = new BN("1500000000000000000");
const cfgContent = `
logLevel: info
wsEndpoint: ${testRPC.endpoint()}
transactions:
- sender:
alias: alice
address: ${alice.address}
keystore:
filePath: ${aliceKsFile.name}
passwordPath: ${passFile.name}
receiver:
alias: bob
address: ${bob.address}
restriction:
remaining: "${remaining}"
- sender:
alias: charlie
address: ${charlie.address}
keystore:
filePath: ${charlieKsFile.name}
passwordPath: ${passFile.name}
receiver:
alias: ferdie
address: ${ferdie.address}
restriction:
desired: "${desired}"
claims: []
`;
const cfgFile = tmp.fileSync();
fs.writeSync(cfgFile.fd, cfgContent);
await startAction({ config: cfgFile.name });
const bobFinalBalance = await client.balanceOf(bob.address);
const expectedOneSend = aliceInitBalance.sub(new BN(remaining) as Balance);
const expectedOne = bobInitBalance.add(expectedOneSend);
bobFinalBalance.eq(expectedOne).should.be.true;
const ferdieFinalBalance = await client.balanceOf(ferdie.address);
ferdieFinalBalance.eq(desired).should.be.true;
});
});
Example #14
Source File: client.ts From polkadot-payouts with Apache License 2.0 | 5 votes |
should();
Example #15
Source File: index.ts From rollup-plugin-swc with MIT License | 5 votes |
should();
Example #16
Source File: accountant.ts From polkadot-payouts with Apache License 2.0 | 5 votes |
should();
Example #17
Source File: 4_serviceApi.test.ts From Designer-Server with GNU General Public License v3.0 | 5 votes |
describe('4-service Api', () => {
it('token exist', (done) => {
should().exist(token);
done();
});
describe('Post /', () => {
it('Create service', (done) => {
const newService: ServiceParams = {
metaId: metas[0].id,
method: "GET",
entityName: "test-service2",
description: "테스트를 위한 service 입니다."
}
chai.request(application.app)
.post(`/api/services`)
.set('Authorization', `Bearer ${token}`)
.send(newService)
.end((err, res) => {
expect(res).to.have.status(201).and.have.property('body').and.have.keys(["method", "entityName", "description", "userId", "meta", "id", "createdAt", "updatedAt"]);;
expect(res.body.meta.id).to.equal(metas[0].id);
done();
});
})
it('Create service2', (done) => {
const newService: ServiceParams = {
metaId: metas[1].id,
method: "GET",
entityName: "test-service3",
description: "테스트를 위한 service 입니다."
}
chai.request(application.app)
.post(`/api/services`)
.set('Authorization', `Bearer ${token}`)
.send(newService)
.end((err, res) => {
expect(res).to.have.status(201).and.have.property('body').and.have.keys(["method", "entityName", "description", "userId", "meta", "id", "createdAt", "updatedAt"]);;
expect(res.body.meta.id).to.equal(metas[1].id);
done();
});
})
it('Create service2', (done) => {
const newService: ServiceParams = {
metaId: metas[2].id,
method: "GET",
entityName: "test-service4",
description: "테스트를 위한 service 입니다."
}
chai.request(application.app)
.post(`/api/services`)
.set('Authorization', `Bearer ${token}`)
.send(newService)
.end((err, res) => {
expect(res).to.have.status(201).and.have.property('body').and.have.keys(["method", "entityName", "description", "userId", "meta", "id", "createdAt", "updatedAt"]);;
expect(res.body.meta.id).to.equal(metas[2].id);
done();
});
})
})
});
Example #18
Source File: accountant.ts From polkadot-payouts with Apache License 2.0 | 4 votes |
describe('Accountant', () => {
beforeEach(() => {
logger = createLogger();
client = new ClientMock();
});
describe('transactions', () => {
afterEach(() => {
sandbox.restore();
});
it('should process all the transactions in the config', async () => {
const txs = defaultTransactions();
const subject = new Accountant({transactions:txs, claims:[], minimumSenderBalance:MinimumSenderBalance}, client, logger);
const stub = sandbox.stub(client, 'send');
await subject.run();
stub.callCount.should.eq(txs.length);
});
it('should allow undefined claims', async () => {
const txs = defaultTransactions();
const subject = new Accountant({transactions:txs, claims:undefined, minimumSenderBalance:MinimumSenderBalance}, client, logger);
const stub = sandbox.stub(client, 'send');
await subject.run();
stub.callCount.should.eq(txs.length);
});
describe('restrictions', () => {
it('should implement remaining', async () => {
await checkRestriction({
senderBalance: 250000000000000,
remaining: 100000000000000,
desired: 0,
expectedSent: 150000000000000
});
});
it('should implement remaining with undefined desired', async () => {
await checkRestriction({
senderBalance: 250000000000000,
remaining: 100000000000000,
desired: undefined,
expectedSent: 150000000000000
});
});
it('should return 0 if sender balance is less than minimum', async () => {
const senderBalance = MinimumSenderBalance - 100;
await checkRestriction({
senderBalance,
remaining: 0,
desired: 0,
expectedSent: 0
});
});
it('should return 0 if remaining is less than minimum', async () => {
const remaining = MinimumSenderBalance - 100;
await checkRestriction({
senderBalance: 200000000000000,
remaining,
desired: 0,
expectedSent: 0
});
});
it('should return 0 if sender balance is less than remaining', async () => {
await checkRestriction({
senderBalance: 9000000000000,
remaining: 10000000000000,
desired: 0,
expectedSent: 0
});
});
it('should implement desired', async () => {
await checkRestriction({
senderBalance: 200000000000000,
receiverBalance: 50000000000000,
remaining: 0,
desired: 100000000000000,
expectedSent: 50000000000000
});
});
it('should implement desired with undefined remaining', async () => {
await checkRestriction({
senderBalance: 200000000000000,
receiverBalance: 50000000000000,
remaining: undefined,
desired: 100000000000000,
expectedSent: 50000000000000
});
});
it('should return 0 if receiver balance is >= desired', async () => {
await checkRestriction({
senderBalance: 200000000000000,
receiverBalance: 300000000000000,
remaining: 0,
desired: 100000000000000,
expectedSent: 0
});
});
it('should send desired on best effort', async () => {
const senderBalance = 10000000000000;
const expectedSent = senderBalance - MinimumSenderBalance;
await checkRestriction({
senderBalance,
receiverBalance: 50000000000000,
remaining: 0,
desired: 100000000000000,
expectedSent: expectedSent
});
});
it('should return 0 if both remaining and desired are present', async () => {
await checkRestriction({
senderBalance: 1000000000000000,
receiverBalance: 50000000000000,
remaining: 100000000000000,
desired: 100000000000000,
expectedSent: 0
});
});
});
describe('empty actors', () => {
it('should not try to send when receciver address is empty', async () => {
const txs = defaultTransactions();
txs.pop();
delete txs[0].receiver.address;
const subject = new Accountant({transactions:txs, claims:[], minimumSenderBalance:MinimumSenderBalance}, client, logger);
const stub = sandbox.stub(client, 'send');
await subject.run();
stub.notCalled.should.be.true;
});
it('should get the sender address from the keystore', async () => {
const senderAddress = 'sender-address-from-keystore';
const receiverAddress = 'receciver-address-not-from-keystore';
const fileContent = `{"address":"${senderAddress}","encoded":"encoded-content","encoding":{"content":["pkcs8","ed25519"],"type":"xsalsa20-poly1305","version":"2"},"meta":{}}`;
const tmpobj = tmp.fileSync();
fs.writeSync(tmpobj.fd, fileContent);
const txs = defaultTransactions();
txs.pop();
txs[0].sender.keystore = {
filePath: tmpobj.name,
passwordPath: 'passwordpath'
};
txs[0].receiver.address = receiverAddress;
sandbox.stub(client, 'send');
const balanceOfStub = sandbox.stub(client, 'balanceOf');
const balanceOfKeystoreStub = sandbox.stub(client, 'balanceOfKeystore');
const senderBalance = new BN(100) as Balance;
const receiverBalance = new BN(100) as Balance;
balanceOfKeystoreStub.onFirstCall().resolves(senderBalance);
balanceOfStub.onFirstCall().resolves(receiverBalance);
const subject = new Accountant({transactions:txs, claims:[], minimumSenderBalance:MinimumSenderBalance}, client, logger);
await subject.run();
balanceOfKeystoreStub.calledWith(txs[0].sender.keystore).should.be.true;
});
});
});
describe('claims', () => {
afterEach(() => {
sandbox.restore();
});
it('should process all the claims in the config', async () => {
const claims = defaultClaims();
const subject = new Accountant({transactions:[], claims, minimumSenderBalance:MinimumSenderBalance}, client, logger);
const stub = sandbox.stub(client, 'claim');
await subject.run();
stub.callCount.should.eq(claims.length);
});
it('should allow undefined transactions', async () => {
const claims = defaultClaims();
const subject = new Accountant({transactions:undefined, claims, minimumSenderBalance:MinimumSenderBalance}, client, logger);
const stub = sandbox.stub(client, 'claim');
await subject.run();
stub.callCount.should.eq(claims.length);
});
});
});
Example #19
Source File: leveling.tests.ts From sixpg with MIT License | 4 votes |
describe('modules/leveling', () => {
let leveling: Leveling;
beforeEach(() => {
leveling = new Leveling();
});
describe('validateXPMsg', () => {
it('null message member throws exception', () => {
const client = mock<BotDocument>();
let msg: any = { member: null };
const result = () => leveling.validateXPMsg(msg, guild);
result().should.eventually.throw();
});
it('member with ignored role throws exception', () => {
const client = mock<BotDocument>();
let msg: any = { member: { roles: { cache: [{ name: '123' }] }}};
guild.leveling.ignoredRoleNames = ['123'];
const result = () => leveling.validateXPMsg(msg, guild);
result().should.eventually.throw();
});
});
describe('getLevel', () => {
it('0 returns level 1', () => {
const result = new Leveling().getLevel(0);
expect(result).to.deep.equal(1);
});
it('floored level returned, min level messages', () => {
const result = new Leveling().getLevel(300);
expect(result).to.equal(2);
});
it('floored level returned, greater than min level messages', () => {
const result = new Leveling().getLevel(400);
expect(result).to.equal(2);
});
});
describe('getLevel', () => {
it('0 returns level 1', () => {
const result = Leveling.xpInfo(0).level;
expect(result).to.deep.equal(1);
});
it('floored level returned, min level messages', () => {
const result = Leveling.xpInfo(300).level;
expect(result).to.equal(2);
});
it('floored level returned, greater than min level messages', () => {
const result = Leveling.xpInfo(400).level;
expect(result).to.equal(2);
});
});
describe('xpForNextLevel', () => {
it('0 xp returns max xp for next level', () => {
const result = Leveling.xpInfo(0).xpForNextLevel;
expect(result).to.equal(300);
});
it('minimum level xp returns max xp for next level', () => {
const result = Leveling.xpInfo(300).xpForNextLevel;
expect(result).to.equal(450);
});
it('250XP returns 50XP for next level', () => {
const result = Leveling.xpInfo(250).xpForNextLevel;
expect(result).to.equal(50);
});
});
describe('levelCompletion', () => {
it('no level completion, returns 0', () => {
const result = Leveling.xpInfo(0).levelCompletion;
expect(result).to.equal(0);
});
it('250/300 level completion, returns 0.83333...', () => {
const result = Leveling.xpInfo(250).levelCompletion;
expect(result).to.be.approximately(0.833, 0.05);
});
});
});
Example #20
Source File: 2_applicationApi.test.ts From Designer-Server with GNU General Public License v3.0 | 4 votes |
describe('2-application Api', () => {
it('token exist', (done) => {
should().exist(token);
done();
});
it('application exist', (done) => {
should().exist(application.app);
done();
})
let applicationEntity;
describe('POST /', () => {
it('create application', (done) => {
const applicationParams: ApplicationParams = {
nameSpace: "test-api",
title: "테스트를 위한 API 입니다.",
description: "test를 하기 위한 API 입니다.",
dailyMaxCount: 1000,
monthlyMaxCount: 10000
}
chai.request(application.app)
.post('/api/applications')
.set('Authorization', `Bearer ${token}`)
.send(applicationParams)
.end((err, res) => {
expect(res).to.have.status(201).and.have.property('body').and.have.keys(['id', 'nameSpace', 'title', 'description', 'createdAt', 'updatedAt', 'userId', 'trafficConfigs', 'stages', 'lastStageVersion']);
applicationEntity = res.body
done();
})
})
it('shoud have daily & monthly traffic configs', (done) => {
const typeList = applicationEntity.trafficConfigs.map(el => el.type);
expect(typeList).includes(TrafficConfigType.DAY).and.includes(TrafficConfigType.MONTH);
done();
})
it('shoud have stages with length 1', (done) => {
const stages = applicationEntity.stages;
expect(stages).to.have.length(1);
done();
})
it('lastVersion should be same as stage name', (done) => {
expect(applicationEntity.stages[0].name).equal(`${applicationEntity.lastStageVersion}`);
done();
})
})
describe('GET /{id}', () => {
it('GET application by id', (done) => {
chai.request(application.app)
.get(`/api/applications/${applicationEntity.id}`)
.set('Authorization', `Bearer ${token}`)
.end((err, res) => {
expect(res).to.have.status(200).and.have.property('body').and.have.keys(['id', 'nameSpace', 'title', 'description', 'createdAt', 'updatedAt', 'userId', 'trafficConfigs', 'stages', 'lastStageVersion']);
done();
})
})
it('Status should be 404', (done) => {
chai.request(application.app)
.get(`/api/applications/999`)
.set('Authorization', `Bearer ${token}`)
.end((err, res) => {
expect(res).to.have.status(404);
done();
})
})
})
describe('POST /{id}/stages', () => {
it('GET application by id', (done) => {
chai.request(application.app)
.post(`/api/applications/${applicationEntity.id}/stages`)
.set('Authorization', `Bearer ${token}`)
.end((err, res) => {
expect(res).to.have.status(201);
expect(res.body.name).to.equal('2');
done();
})
})
})
});
Example #21
Source File: auto-mod.tests.ts From sixpg with MIT License | 4 votes |
describe('modules/auto-mod', () => {
let autoMod: AutoMod;
beforeEach(() => {
const members = mock<Members>();
members.get = (): any => new SavedMember();
autoMod = new AutoMod(members);
});
describe('validateMsg', () => {
it('contains ban word, has filter, error thrown', async() => {
const client = mock<BotDocument>();
const msg = mock<Message>();
guild.autoMod.filters = [MessageFilter.Words];
guild.autoMod.banWords = ['a'];
msg.content = 'a';
const result = () => autoMod.validateMsg(msg, guild);
result().should.eventually.throw();
});
it('contains ban word, has filter, auto deleted, error thrown', async() => {
const client = mock<BotDocument>();
const msg = mock<Message>();
guild.autoMod.filters = [MessageFilter.Words];
guild.autoMod.banWords = ['a'];
msg.content = 'a';
msg.delete = () => { throw new TypeError('deleted'); }
const result = () => autoMod.validateMsg(msg, guild);
result().should.eventually.throw('deleted');
});
it('contains ban word, no filter, ignored', async() => {
const client = mock<BotDocument>();
const msg = mock<Message>();
guild.autoMod.filters = [];
guild.autoMod.banWords = [];
msg.content = 'a';
const result = () => autoMod.validateMsg(msg, guild);
result().should.not.eventually.throw();
});
it('contains ban link, has filter, error thrown', async() => {
const client = mock<BotDocument>();
const msg = mock<Message>();
guild.autoMod.filters = [MessageFilter.Links];
guild.autoMod.banLinks = ['a'];
msg.content = 'a';
const result = () => autoMod.validateMsg(msg, guild);
result().should.eventually.throw();
});
it('contains ban link, no filter, ignored', async() => {
const client = mock<BotDocument>();
const msg = mock<Message>();
guild.autoMod.filters = [];
guild.autoMod.banLinks = ['a'];
msg.content = 'a';
const result = () => autoMod.validateMsg(msg, guild);
result().should.not.eventually.throw();
});
});
describe('warnMember', () => {
it('warn member, message sent to user', async() => {
const member: any = { id: '123', send: () => { throw new TypeError() }, user: { bot: false }};
const instigator: any = { id: '321' };
const result = () => autoMod.warn(member, instigator);
result().should.eventually.throw();
});
it('warn self member, error thrown', async() => {
const member: any = { id: '123', user: { bot: false } };
const instigator: any = { id: '123' };
const result = () => autoMod.warn(member, instigator);
result().should.eventually.throw();
});
it('warn bot member, error thrown', async() => {
const member: any = { id: '123', user: { bot: true }};
const instigator: any = { id: '321' };
const result = () => autoMod.warn(member, instigator);
result().should.eventually.throw();
});
});
});
Example #22
Source File: announce.tests.ts From sixpg with MIT License | 4 votes |
describe('modules/announce', () => {
let guilds: Bots;
beforeEach(() => {
guilds = mock<Bots>();
guilds.get = (): any => new SavedBot();
});
describe('member join handler', () =>
{
let member: GuildMember;
beforeEach(() => {
member = {
id: '123',
guild: {
name: 'Guild',
channels: { cache: {
get: (id: string) => {
const channel = mock<TextChannel>();
channel.send = (message: any): any => {
throw new TypeError(message);
}
return (id === '123') ? channel : null;
}
}},
memberCount: 2
}
} as any;
});
it('member join, member undefined, returns', () => {
const result = () => new MemberJoinHandler(guilds).invoke(member);
result().should.eventually.not.throw();
});
it('member join, event not active, returns', () => {
const result = () => new MemberJoinHandler(guilds).invoke(member);
result().should.eventually.not.throw();
});
it('member join, channel not found, returns', () => {
guilds.get = (): any => {
const client = new SavedBot();
guild.announce.events.push({
event: EventType.MemberJoin,
message: 'test',
channelName: '321'
});
}
const result = () => new MemberJoinHandler(guilds).invoke(member);
result().should.eventually.not.throw();
});
it('member join, event active, message is sent', () => {
guilds.get = (): any => {
const client = new SavedBot();
guild.announce.events.push({
event: EventType.MemberJoin,
message: 'test',
channelName: '123'
});
}
const result = () => new MemberJoinHandler(guilds).invoke(member);
result().should.eventually.throw('test');
});
it('member join, event active, message is sent with applied guild variables', () => {
guilds.get = (): any => {
const client = new SavedBot();
guild.announce.events.push({
event: EventType.MemberJoin,
message: '[USER] joined!',
channelName: '123'
});
}
const result = () => new MemberJoinHandler(guilds).invoke(member);
result().should.eventually.throws(new TypeError('<@!123> joined!'));
});
});
describe('message deleted handler', () => {
it('')
});
});
Example #23
Source File: transaction.spec.ts From dyngoose with ISC License | 4 votes |
describe('Transaction', () => {
@TableDecorator({ name: 'TransactionTestCardTable' })
class Card extends Table {
@PrimaryKeyDecorator('id', 'title')
public static readonly primaryKey: PrimaryKey<Card, number, string>
@AttributeDecorator.Number()
public id: number
@AttributeDecorator.String()
public title: string
@AttributeDecorator.Number()
public count: number
}
before(async () => {
await Card.createTable()
})
after(async () => {
await Card.deleteTable()
})
beforeEach(async () => {
await Card.documentClient.batchPut([
Card.new({ id: 10, title: 'a', count: 4 }),
Card.new({ id: 10, title: 'b', count: 3 }),
Card.new({ id: 10, title: 'c', count: 2 }),
Card.new({ id: 11, title: 'd', count: 1 }),
])
})
it('should operate a successful commit', async () => {
const transaction = new Transaction()
// add a new record
transaction.save(Card.new({ id: 42, title: 'new record', count: 1 }))
// perform an update without loading the record
transaction.update(Card.primaryKey.fromKey(10, 'a').set('count', 5))
// delete a few records
transaction.delete(Card.primaryKey.fromKey(10, 'b'), { count: 3 })
transaction.delete(Card.primaryKey.fromKey(10, 'c'))
// add a condition
transaction.conditionCheck(Card.primaryKey.fromKey(11, 'd'), { count: 1 })
// commit the transaction
await transaction.commit()
// now verify the results
const results = await Card.primaryKey.scan()
const records = sortBy(results.records, 'id')
expect(results.count).eq(3)
expect(records[0].id).eq(10)
expect(records[1].id).eq(11)
expect(records[2].id).eq(42)
})
it('should fail with a ConditionalCheckFailed error', async () => {
const transaction = new Transaction()
// add a new record
transaction.save(Card.new({ id: 42, title: 'new record', count: 1 }))
// add a condition
transaction.conditionCheck(Card.primaryKey.fromKey(11, 'd'), { count: 3 }) // note: 3 is not the right number
let error: Error | undefined
try {
await transaction.commit()
} catch (ex) {
error = ex
}
expect(error).to.be.instanceOf(Error)
.with.property('name', 'TransactionCanceledException')
should().exist((error as any).cancellationReasons)
})
})
Example #24
Source File: global-secondary-index.spec.ts From dyngoose with ISC License | 4 votes |
describe('Query/GlobalSecondaryIndex', () => {
beforeEach(async () => {
await Card.createTable()
})
afterEach(async () => {
await Card.deleteTable()
})
describe('hash only index', () => {
describe('#get', () => {
it('should throw error when no range key is specified', async () => {
let exception
try {
await Card.filterableTitleIndex.get({ id: 10 })
} catch (ex) {
exception = ex
}
should().exist(exception)
})
it('should find item', async () => {
await Card.new({ id: 10, title: 'abc', count: 1 }).save()
// this .get() will perform a query with a limit of 1,
// so it will get the first matching record
const card = await Card.filterableTitleIndex.get({ id: 10, title: 'abc' })
should().exist(card)
if (card != null) {
expect(card.id).to.eq(10)
expect(card.title).to.eq('abc')
expect(card.count).to.eq(1)
}
})
})
describe('#query', () => {
it('should find items', async () => {
await Card.new({ id: 10, title: 'abc' }).save()
await Card.new({ id: 11, title: 'abd' }).save()
await Card.new({ id: 12, title: 'abd' }).save()
const res = await Card.hashTitleIndex.query({ title: 'abd' })
expect(res.records.length).to.eq(2)
expect(res.records[0].id).to.eq(12)
expect(res.records[1].id).to.eq(11)
})
it('should return an empty array when no items match', async () => {
const res = await Card.hashTitleIndex.query({ title: '404' })
expect(res[0]).to.not.eq(null)
expect(res.records.length).to.eq(0)
expect(res.length).to.eq(0)
expect(res.count).to.eq(0)
expect(res.map(i => i)[0]).to.eq(undefined)
for (const card of res.records) {
expect(card).to.eq('does not exist')
}
for (const card of res) {
expect(card).to.eq('does not exist')
}
})
it('should complain when HASH key is not provided', async () => {
await Card.hashTitleIndex.query({ id: 10 }).then(
() => {
expect(true).to.be.eq('false')
},
(err) => {
expect(err).to.be.instanceOf(QueryError)
expect(err.message).to.contain('Cannot perform')
},
)
})
it('should complain when HASH key attempts to use unsupported operator', async () => {
await Card.hashTitleIndex.query({ title: ['<>', 'abd'] }).then(
() => {
expect(true).to.be.eq('false')
},
(err) => {
expect(err).to.be.instanceOf(QueryError)
expect(err.message).to.contain('DynamoDB only supports')
},
)
})
it('should allow use of query operators for RANGE', async () => {
await Card.new({ id: 10, title: 'prefix/abc' }).save()
await Card.new({ id: 10, title: 'prefix/123' }).save()
await Card.new({ id: 10, title: 'prefix/xyz' }).save()
const res = await Card.filterableTitleIndex.query({ id: 10, title: ['beginsWith', 'prefix/'] })
expect(res.records.length).to.eq(3)
expect(res.records[0].id).to.eq(10)
expect(res.records[1].id).to.eq(10)
expect(res.records[2].id).to.eq(10)
})
it('should complain when using unsupported query operators for RANGE', async () => {
await Card.filterableTitleIndex.query({ id: 10, title: ['contains', 'prefix/'] }).then(
() => {
expect(true).to.be.eq('false')
},
(err) => {
expect(err).to.be.instanceOf(QueryError)
expect(err.message).to.contain('Cannot use')
},
)
})
})
describe('#scan', () => {
const cardIds = [111, 222, 333, 444, 555]
beforeEach(async () => {
for (const cardId of cardIds) {
await Card.new({ id: cardId, title: cardId.toString() }).save()
}
})
it('should return results', async () => {
const res1 = await Card.hashTitleIndex.scan()
const res2 = await Card.hashTitleIndex.scan(null, { limit: 2 })
const res3 = await Card.hashTitleIndex.scan(null, { limit: 2, exclusiveStartKey: res2.lastEvaluatedKey })
expect(res1.records.map((r) => r.id)).to.have.all.members(cardIds)
expect(cardIds).to.include.members(res2.records.map((r) => r.id))
expect(cardIds).to.include.members(res3.records.map((r) => r.id))
})
})
})
describe('hash and range index', () => {
describe('#query', () => {
it('should find items', async () => {
await Card.new({ id: 10, title: 'abc' }).save()
await Card.new({ id: 11, title: 'abd' }).save()
await Card.new({ id: 12, title: 'abd' }).save()
await Card.new({ id: 13, title: 'abd' }).save()
const res = await Card.fullTitleIndex.query({
title: 'abd',
id: ['>=', 12],
}, {
rangeOrder: 'DESC',
})
expect(res.records.length).to.eq(2)
expect(res.records[0].id).to.eq(13)
expect(res.records[1].id).to.eq(12)
})
})
describe('#scan', () => {
const cardIds = [111, 222, 333, 444, 555]
beforeEach(async () => {
for (const cardId of cardIds) {
await Card.new({ id: cardId, title: cardId.toString() }).save()
}
})
it('should support filters', async () => {
const search = await Card.fullTitleIndex.scan({
id: ['includes', cardIds],
})
expect(search.records.map((r) => r.id)).to.have.all.members(cardIds)
})
it('should work without filters', async () => {
const res1 = await Card.fullTitleIndex.scan()
const res2 = await Card.fullTitleIndex.scan(null, { limit: 2 })
const res3 = await Card.fullTitleIndex.scan(null, { limit: 2, exclusiveStartKey: res2.lastEvaluatedKey })
expect(res1.records.map((r) => r.id)).to.have.all.members(cardIds)
expect(cardIds).to.include.members(res2.records.map((r) => r.id))
expect(cardIds).to.include.members(res3.records.map((r) => r.id))
})
})
})
describe('include projection index', () => {
it('allows you to query and returns the nonKeyAttributes', async () => {
const newCard = Card.new({ id: 10, title: 'abc' })
newCard.count = 10
await newCard.save()
const card = await Card.includeTestIndex.get({ id: 10 })
should().exist(card)
if (card != null) {
expect(card.id).to.eq(10)
expect(card.title).to.eq('abc')
should().not.exist(card.count)
}
})
})
})
Example #25
Source File: map.spec.ts From dyngoose with ISC License | 4 votes |
describe('AttributeType/Map', () => {
before(async () => {
await MapTestTable.createTable()
})
after(async () => {
await MapTestTable.deleteTable()
})
it('should store the object as a map', async () => {
const record = MapTestTable.new({
id: 1,
person: {
first: 'John',
middle: 'Jacobs',
last: 'Smith',
level: 1,
// nick is left empty to ensure optional properties work
},
})
await record.save()
const loaded = await MapTestTable.primaryKey.get(1)
expect(loaded?.getAttributeDynamoValue('person')).to.deep.eq({
M: {
first: { S: 'John' },
middle: { S: 'Jacobs' },
last: { S: 'Smith' },
level: { N: '1' },
},
})
expect(loaded?.person.first).to.eq('John')
expect(loaded?.getAttributeDynamoValue('person')).to.deep.eq({
M: {
first: { S: 'John' },
middle: { S: 'Jacobs' },
last: { S: 'Smith' },
level: { N: '1' },
},
})
expect(loaded?.toJSON()).to.deep.eq({
id: 1,
person: {
first: 'John',
middle: 'Jacobs',
last: 'Smith',
level: 1,
},
})
})
it('should allow you to query using child attributes', async () => {
const record = MapTestTable.new({
id: 2,
person: {
first: 'Sally',
middle: 'Shelly',
last: 'Samuel',
level: 1,
// nick is left empty to ensure optional properties work
},
})
await record.save()
const result = await MapTestTable.search({
'person.first': 'Sally',
} as any).exec()
expect(result.count).to.eq(1)
expect(result[0].person.first).to.eq('Sally')
expect(result.records[0].person.first).to.eq('Sally')
// ensure you can look through the result as an array
for (const doc of result) {
expect(doc.person.first).to.eq('Sally')
}
const searchOutput = await MapTestTable.search()
.filter('person', 'first').eq('Sally')
.exec()
expect(searchOutput.count).to.eq(1)
expect(searchOutput[0].person.first).to.eq('Sally')
})
it('should allow maps within maps', async () => {
const record = MapTestTable.new({
id: 3,
contact: {
name: {
first: 'Homer',
last: 'Simpson',
},
address: {
line1: '742 Evergreen Terrace',
city: 'Springfield',
state: 'Simpcity',
},
dob: new Date(1956, 4, 12), // May 12, 1956
},
})
expect(record.contact?.name.first).to.eq('homer')
expect(record.contact?.name.last).to.eq('SIMPSON')
await record.save()
const loaded = await MapTestTable.primaryKey.get(3)
should().exist(loaded)
if (loaded != null) {
expect(loaded.getAttributeDynamoValue('contact')).to.deep.eq({
M: {
name: {
M: {
first: { S: 'homer' },
last: { S: 'SIMPSON' },
},
},
address: {
M: {
line1: { S: '742 Evergreen Terrace' },
city: { S: 'Springfield' },
state: { S: 'Simpcity' },
},
},
dob: {
S: '1956-05-12',
},
},
})
expect(loaded.contact.name.first).to.eq('homer')
expect(loaded.contact.name.last).to.eq('SIMPSON')
expect(loaded.toJSON()).to.deep.eq({
id: 3,
contact: {
name: {
first: 'homer',
last: 'SIMPSON',
},
address: {
line1: '742 Evergreen Terrace',
city: 'Springfield',
state: 'Simpcity',
},
dob: '1956-05-12',
},
})
}
})
it('should allow you to query using deep child attributes', async () => {
const record = MapTestTable.new({
id: 4,
contact: {
name: {
first: 'Marge',
last: 'Simpson',
},
},
})
await record.save()
const result = await MapTestTable.search({
'contact.name.first': 'Marge',
} as any).exec()
expect(result.count).to.eq(1)
expect(result.length).to.eq(1)
expect(result[0].contact.name.first).to.eq('marge')
const searchOutput = await MapTestTable.search()
.filter('contact', 'name', 'first').eq('marge')
.exec()
expect(searchOutput.count).to.eq(1)
expect(searchOutput.length).to.eq(1)
expect(searchOutput[0].contact.name.first).to.eq('marge')
})
it('should support use of fromJSON to support REST APIs and DB Seeding', async () => {
const record = MapTestTable.fromJSON({
id: 3,
contact: {
name: {
first: 'Homer',
last: 'Simpson',
},
address: {
line1: '742 Evergreen Terrace',
city: 'Springfield',
state: 'Simpcity',
},
dob: '1956-05-12',
},
})
expect(record.contact.address?.line1).to.eq('742 Evergreen Terrace')
expect(record.contact.dob).to.be.instanceOf(Date)
expect(record.contact.dob?.toISOString()).to.eq('1956-05-12T00:00:00.000Z')
})
})
Example #26
Source File: index.ts From rollup-plugin-swc with MIT License | 4 votes |
describe('swc', () => {
before(() => {
if (fs.existsSync(tmpDir)) {
fs.rmSync(tmpDir, { recursive: true });
}
});
it('simple', async () => {
const dir = realFs(getTestName(), {
'./fixture/index.js': `
import Foo from './foo'
console.log(Foo)
import bar from './bar'
console.log(bar)
`,
'./fixture/foo.tsx': `
export default class Foo {
render() {
return <div className="hehe">hello there!!!</div>
}
}
`,
'./fixture/bar.mjs': `
const bar = 'baz'
export default bar
`
});
const output = await build({}, { dir });
output[0].code.should.equal(`class Foo {
render() {
return /*#__PURE__*/ React.createElement("div", {
className: "hehe"
}, "hello there!!!");
}
}
const bar = 'baz';
console.log(Foo);
console.log(bar);
`);
});
it('minify', async () => {
const dir = realFs(getTestName(), {
'./fixture/index.js': `
import Foo from './foo'
console.log(Foo)
`,
'./fixture/foo.tsx': `
export default class Foo {
render() {
return <div className="hehe">hello there!!!</div>
}
}
`
});
const output = await build({ minify: true, jsc: { target: 'es2022' } }, { dir });
output[0].code.should.equal(`class Foo{render(){return React.createElement("div",{className:"hehe"},"hello there!!!")}}console.log(Foo)
`);
});
it('standalone minify', async () => {
const dir = realFs(getTestName(), {
'./fixture/index.js': `
console.log(10000);
console.log('b' + 'c');
`
});
const output = await runMinify({}, { dir });
output[0].code.should.equal(`console.log(1e4);console.log("b"+"c")
`);
});
it('load index.(x)', async () => {
const dir = realFs(getTestName(), {
'./fixture/index.js': `
import Foo from './foo'
console.log(Foo)
`,
'./fixture/foo/index.tsx': `
export default class Foo {
render() {
return <div className="hehe">hello there!!!</div>
}
}
`
});
const output = await build({}, { dir });
output[0].code.should.equal(`class Foo {
render() {
return /*#__PURE__*/ React.createElement("div", {
className: "hehe"
}, "hello there!!!");
}
}
console.log(Foo);
`);
});
it('load json', async () => {
const dir = realFs(getTestName(), {
'./fixture/index.js': `
import foo from './foo.json'
console.log(foo)
`,
'./fixture/foo.json': `
{
"foo": true
}
`
});
const output = await build(
{},
{ otherRollupPlugins: [json()], dir }
);
output[0].code.should.equal(`var foo = true;
var foo$1 = {
\tfoo: foo
};
console.log(foo$1);
`);
});
it('support rollup virtual module (e.g. commonjs plugin)', async () => {
const dir = realFs(getTestName(), {
'./fixture/index.js': `
const Foo = require('./foo')
const { Bar } = require('./bar')
console.log(Foo, Bar)
`,
'./fixture/foo.js': `
module.exports = 'foo'
`,
'./fixture/bar.js': `
exports.Bar = 'bar'
`
});
const output = await build(
{},
{ otherRollupPlugins: [commonjs()], dir }
);
output[0].code.should.equal(`var fixture = {};
var foo = 'foo';
var bar = {};
bar.Bar = 'bar';
const Foo = foo;
const { Bar } = bar;
console.log(Foo, Bar);
export { fixture as default };
`);
});
it('use custom jsxFactory (h) from tsconfig', async () => {
const dir = realFs(getTestName(), {
'./fixture/index.tsx': `
export const foo = <div>foo</div>
`,
'./fixture/tsconfig.json': `
{
"compilerOptions": {
"jsxFactory": "h"
}
}
`
});
const output = await build({}, { input: './fixture/index.tsx', dir });
output[0].code.should.equal(`var foo = /*#__PURE__*/ h("div", null, "foo");
export { foo };
`);
});
it('use custom jsxFactory (h) from jsconfig.json', async () => {
const dir = realFs(getTestName(), {
'./fixture/index.tsx': `
export const foo = <div>foo</div>
`,
'./fixture/jsconfig.json': `
{
"compilerOptions": {
"jsxFactory": "h"
}
}
`
});
const output = await build({}, { input: './fixture/index.tsx', dir });
output[0].code.should.equal(`var foo = /*#__PURE__*/ h("div", null, "foo");
export { foo };
`);
});
it('use tsconfig.json when tsconfig.json & jsconfig.json both exists', async () => {
const dir = realFs(getTestName(), {
'./fixture/index.tsx': `
export const foo = <><div>foo</div></>
`,
'./fixture/jsconfig.json': `
{
"compilerOptions": {
"jsxFactory": "m",
"jsxFragmentFactory": "React.Fragment"
}
}
`,
'./fixture/tsconfig.json': `
{
"compilerOptions": {
}
}
`
});
const output = await build({}, { input: './fixture/index.tsx', dir });
output[0].code.should.equal(`var foo = /*#__PURE__*/ React.createElement(React.Fragment, null, /*#__PURE__*/ React.createElement("div", null, "foo"));
export { foo };
`);
});
it('use custom tsconfig.json', async () => {
const dir = realFs(getTestName(), {
'./fixture/index.jsx': `
export const foo = <div>foo</div>
`,
'./fixture/tsconfig.json': `
{
"compilerOptions": {
"jsxFactory": "h"
}
}
`,
'./fixture/tsconfig.build.json': `
{
"compilerOptions": {
"jsxFactory": "custom"
}
}
`
});
const output = await build(
{ tsconfig: 'tsconfig.build.json' },
{ input: './fixture/index.jsx', dir }
);
output[0].code.should.equal(`var foo = /*#__PURE__*/ custom("div", null, "foo");
export { foo };
`);
});
});
Example #27
Source File: 5_stageApi.test.ts From Designer-Server with GNU General Public License v3.0 | 4 votes |
describe('5-stage Api', () => {
it('token exist', (done) => {
should().exist(token);
done();
});
describe('Get /', () => {
let stageEntity;
it('should have at least one stage and pagination info', (done) => {
chai.request(application.app)
.get('/api/stages')
.set('Authorization', `Bearer ${token}`)
.end((err, res) => {
if(err) console.log(err);
expect(res).to.have.status(200).and.have.property('body').and.have.keys(["items", "page", "perPage", "totalCount"]);
stageEntity = res.body;
done();
})
})
it('item shoud have metas', (done) => {
expect(stageEntity.items[0]).to.have.keys(["applicationId", "createdAt", "id", "metas", "name", "status", "updatedAt", "userId", "application"]);
done();
})
it('should have NO stage', (done) => {
chai.request(application.app)
.get('/api/stages?page=100')
.set('Authorization', `Bearer ${token}`)
.end((err, res) => {
if(err) console.log(err);
expect(res).to.have.status(200).and.have.property('body').and.have.keys(["items", "page", "perPage", "totalCount"]);
expect(res.body.items.length).to.equal(0);
done();
})
})
})
describe('Get /{id}', () => {
it('should have stage', (done) => {
chai.request(application.app)
.get('/api/stages/1')
.set('Authorization', `Bearer ${token}`)
.end((err, res) => {
if(err) console.log(err);
expect(res).to.have.status(200).and.have.property('body').and.have.keys(["metas", "id", "status", "applicationId", "name", "createdAt", "updatedAt", "userId", "application"]);
done();
})
})
})
describe('POST /{id}/load-data', () => {
it('Should have return 400 because of Service Not yet ready', (done) => {
chai.request(application.app)
.post('/api/stages/1/load-data')
.set('Authorization', `Bearer ${token}`)
.end((err, res) => {
expect(res).to.have.status(400);
expect(res.body.code).to.equal(ERROR_CODE.STAGE.ALL_METAS_SHOULD_HAVE_SERVICE)
done();
});
})
describe('... save sample data ...', () => {
let stage: Stage;
before((done) => {
const newService: ServiceParams = {
metaId: metas[3].id,
method: "GET",
entityName: "test-service",
description: "테스트를 위한 service 입니다."
}
chai.request(application.app)
.post(`/api/services`)
.set('Authorization', `Bearer ${token}`)
.send(newService)
.end((err, res) => {
expect(res).to.have.status(201).and.have.property('body').and.have.keys(["method", "entityName", "description", "userId", "meta", "id", "createdAt", "updatedAt"]);;
expect(res.body.meta.id).to.equal(metas[3].id);
done();
});
})
it('Should have return 201', (done) => {
chai.request(application.app)
.post('/api/stages/1/load-data')
.set('Authorization', `Bearer ${token}`)
.end((err, res) => {
expect(res).to.have.status(201);
stage = res.body;
done();
});
})
it('Data loaded stage shoud have data-load-scheduled metas', (done) => {
const haveScheduledMeta = stage.metas.every( meta => meta.status === MetaStatus.DATA_LOAD_SCHEDULED)
expect(haveScheduledMeta).to.true;
done();
})
it('should wait til Data loaded', (done) => {
setTimeout(() => {
done();
}, 4500)
}).timeout(5000);
it('Should have return 200 and loaded', (done) => {
chai.request(application.app)
.get('/api/stages/1')
.set('Authorization', `Bearer ${token}`)
.end((err, res) => {
expect(res).to.have.status(200);
stage = res.body;
expect(stage.status).to.equal(StageStatus.LOADED);
done();
});
})
/**
* Auth 서버와 통신을 하는 코드이므로,
* Local에서 test하는 경우 정상적으로 동작하지 않을 수 있습니다.
*/
// it('Stage can be deployed', (done) => {
// chai.request(application.app)
// .post('/api/stages/1/deploy')
// .set('Authorization', `Bearer ${token}`)
// .end((err, res) => {
// expect(res).to.have.status(201);
// expect(res.body.status).to.equal(StageStatus.DEPLOYED);
// done();
// });
// })
// it('Stage can be undeployed', (done) => {
// chai.request(application.app)
// .post('/api/stages/1/undeploy')
// .set('Authorization', `Bearer ${token}`)
// .end((err, res) => {
// expect(res).to.have.status(201);
// expect(res.body.status).to.equal(StageStatus.LOADED);
// done();
// });
// })
})
})
describe("Delete /{id}", () => {
let stage;
it('Create new Stage', (done) => {
chai.request(application.app)
.post(`/api/applications/1/stages`)
.set('Authorization', `Bearer ${token}`)
.end((err, res) => {
expect(res).to.have.status(201);
stage = res.body;
done();
})
})
it('Delete stage', (done) => {
chai.request(application.app)
.delete(`/api/stages/${stage.id}`)
.set('Authorization', `Bearer ${token}`)
.end((err, res) => {
expect(res).to.have.status(200);
done();
})
})
})
});
Example #28
Source File: 3_metaApi.test.ts From Designer-Server with GNU General Public License v3.0 | 4 votes |
describe('3-meta Api', () => {
let applicationEntity;
let fileUrlMeta;
before((done) => {
chai.request(application.app)
.get('/api/applications/1')
.set('Authorization', `Bearer ${token}`)
.end((err, res) => {
if(err || res.error) throw err ? err : res.error;
applicationEntity = res.body;
done();
})
})
it('token exist', (done) => {
should().exist(token);
done();
});
describe('Post /', () => {
it('create new Meta with DBMS info', (done) => {
const newMeta: DbmsParams = {
stageId: applicationEntity.stages[0].id,
title: "Database test data",
dbms: "mysql",
host: "localhost",
port: "3306",
database: "api-manager",
user: "root",
password: "",
table: "application"
}
chai.request(application.app)
.post(`/api/metas/dbms`)
.set('Authorization', `Bearer ${token}`)
.send(newMeta)
.end((err, res) => {
expect(res).to.have.status(201).and.have.property('body').and.have.keys(["samples", "status", "columns", "createdAt", "dataType", "db", "dbUser", "dbms", "encoding", "extension", "filePath", "host", "id", "originalFileName", "port", "pwd", "remoteFilePath", "rowCounts", "sheet", "skip", "stage", "stageId", "table", "title", "updatedAt", "userId"]);
should().exist(res.body.dbms);
should().exist(res.body.host);
should().exist(res.body.port);
should().exist(res.body.pwd);
should().exist(res.body.table);
expect(res.body.status).equal(MetaStatus.METALOADED)
metas.push(res.body);
done();
})
})
it('create new Meta with CSV File info', (done) => {
const newMeta: FileParams = {
stageId: applicationEntity.stages[0].id,
dataType: "file",
ext: "csv",
title: "CSV File test data",
skip: 0,
sheet: 0,
filePath: "./test/filesForTest/폐기물.csv",
originalFileName: "폐기물.csv"
}
chai.request(application.app)
.post(`/api/metas/file`)
.set('Authorization', `Bearer ${token}`)
.send(newMeta)
.end((err, res) => {
expect(res).to.have.status(201).and.have.property('body').and.have.keys(["samples", "status", "createdAt", "dataType", "db", "dbUser", "dbms", "encoding", "extension", "filePath", "host", "id", "originalFileName", "port", "pwd", "remoteFilePath", "rowCounts", "sheet", "skip", "stageId", "table", "title", "updatedAt", "userId"]);
should().exist(res.body.dataType);
should().exist(res.body.encoding);
should().exist(res.body.extension);
should().exist(res.body.filePath);
should().exist(res.body.originalFileName);
should().exist(res.body.sheet);
should().exist(res.body.skip);
should().exist(res.body.samples);
expect(res.body.status).equal(MetaStatus.METALOADED)
metas.push(res.body);
done();
})
})
it('create new Meta with XLSX File info', (done) => {
const newMeta: FileParams = {
stageId: applicationEntity.stages[0].id,
dataType: "file",
ext: "xlsx",
title: "XLSX File test data",
skip: 0,
sheet: 0,
filePath: "./test/filesForTest/그늘막설치현황.xlsx",
originalFileName: "그늘막설치현황.xlsx"
}
chai.request(application.app)
.post(`/api/metas/file`)
.set('Authorization', `Bearer ${token}`)
.send(newMeta)
.end((err, res) => {
expect(res).to.have.status(201).and.have.property('body').and.have.keys(["samples", "status", "createdAt", "dataType", "db", "dbUser", "dbms", "encoding", "extension", "filePath", "host", "id", "originalFileName", "port", "pwd", "remoteFilePath", "rowCounts", "sheet", "skip", "stageId", "table", "title", "updatedAt", "userId"]);
should().exist(res.body.dataType);
should().exist(res.body.extension);
should().exist(res.body.filePath);
should().exist(res.body.originalFileName);
should().exist(res.body.sheet);
should().exist(res.body.skip);
should().exist(res.body.samples);
expect(res.body.status).equal(MetaStatus.METALOADED)
metas.push(res.body);
done();
})
})
it('create new Meta with File-url info', (done) => {
const newMeta: FileParams = {
stageId: applicationEntity.stages[0].id,
dataType: "file-url",
ext: "csv",
title: "File test data",
skip: 0,
sheet: 0,
url: "https://raw.githubusercontent.com/uiuc-cse/data-fa14/gh-pages/data/iris.csv"
}
chai.request(application.app)
.post(`/api/metas/file`)
.set('Authorization', `Bearer ${token}`)
.send(newMeta)
.end((err, res) => {
fileUrlMeta = res.body;
expect(res).to.have.status(201).and.have.property('body').and.have.keys(["samples", "status", "createdAt", "dataType", "db", "dbUser", "dbms", "encoding", "extension", "filePath", "host", "id", "originalFileName", "port", "pwd", "remoteFilePath", "rowCounts", "sheet", "skip", "stageId", "table", "title", "updatedAt", "userId"]);
should().exist(res.body.dataType);
should().exist(res.body.extension);
should().exist(res.body.remoteFilePath);
should().exist(res.body.sheet);
should().exist(res.body.skip);
expect(res.body.status).equal(MetaStatus.DOWNLOAD_SCHEDULED)
setTimeout(() => {
done();
}, 1500)
})
})
})
let metaEntity;
describe('GET /{id}', () => {
it('File-url Meta Should be loaded', (done) => {
chai.request(application.app)
.get(`/api/metas/${fileUrlMeta.id}`)
.set('Authorization', `Bearer ${token}`)
.end((err, res) => {
expect(res).to.have.status(200).and.have.property('body').and.have.property('status').to.satisfy((status) => {
return status == MetaStatus.DOWNLOAD_DONE || status == MetaStatus.METALOADED
})
metaEntity = res.body
metas.push(res.body);
done();
})
})
it('Sholud return 404 Error', (done) => {
chai.request(application.app)
.get(`/api/metas/100`)
.set('Authorization', `Bearer ${token}`)
.end((err, res) => {
expect(res).to.have.status(404);
done();
})
})
})
describe('PUT /{metaId}/columns', () => {
it('Shoud meta column updated', (done) => {
metaEntity.columns.forEach(column => {
column.columnName = `${column.id}-column-${column.originalColumnName}`
if(column.type === AcceptableType.DOUBLE) {
column.size = '16, 4';
} else {
column.size = '100';
}
column.isSearchable = true;
column.isNullable = true;
});
chai.request(application.app)
.put(`/api/metas/${metaEntity.id}/columns`)
.set('Authorization', `Bearer ${token}`)
.send({
columns: metaEntity.columns
})
.end((err, res) => {
expect(res).to.have.status(201);
done();
})
})
})
describe('PUT /{metaId}', () => {
it('Shoud meta column & service updated', (done) => {
metaEntity.columns.forEach(column => {
column.columnName = `${column.id}-column-${column.originalColumnName}-test2`
if(column.type === AcceptableType.DOUBLE) {
column.size = '16, 4';
} else {
column.size = '100';
}
column.isSearchable = true;
column.isNullable = true;
column["params"] = [{
metaColumnId: column.id,
operator: "lt",
description: "description",
isRequired: false
}]
});
const service = {
method: 'GET',
entityName: 'test-service',
description: '테스트를 위한 서비스입니다.\n서비스가 생성되어야 합니다.',
}
chai.request(application.app)
.put(`/api/metas/${metaEntity.id}`)
.set('Authorization', `Bearer ${token}`)
.send({
service: service,
columns: metaEntity.columns
})
.end((err, res) => {
expect(res).to.have.status(201);
metaEntity = res.body;
done();
})
})
it('Shoud meta column & service updated2', (done) => {
metaEntity.columns.forEach(column => {
column.columnName = `${column.id}-column-${column.originalColumnName}-test2`
if(column.type === AcceptableType.DOUBLE) {
column.size = '16, 4';
} else {
column.size = '100';
}
column.isSearchable = true;
column.isNullable = true;
column["params"].push({
metaColumnId: column.id,
operator: "eq",
description: "description",
isRequired: false
})
});
const service = {
method: 'GET',
entityName: 'test-service',
description: '테스트를 위한 서비스입니다.\n서비스가 생성되어야 합니다.',
}
chai.request(application.app)
.put(`/api/metas/${metaEntity.id}`)
.set('Authorization', `Bearer ${token}`)
.send({
service: service,
columns: metaEntity.columns
})
.end((err, res) => {
expect(res).to.have.status(201);
done();
})
})
})
describe('DELETE /{metaId}/service', () => {
it('Meta should have null service', (done) => {
chai.request(application.app)
.delete(`/api/metas/${metaEntity.id}/service`)
.set('Authorization', `Bearer ${token}`)
.end((err, res) => {
expect(res).to.have.status(201);
done();
})
})
})
describe('Get /', () => {
it('should have at least one stage and pagination info', (done) => {
chai.request(application.app)
.get('/api/metas')
.set('Authorization', `Bearer ${token}`)
.end((err, res) => {
if(err) console.log(err);
expect(res).to.have.status(200).and.have.property('body').and.have.keys(["items", "page", "perPage", "totalCount"]);
done();
})
})
it('should have NO stage', (done) => {
chai.request(application.app)
.get('/api/metas?page=100')
.set('Authorization', `Bearer ${token}`)
.end((err, res) => {
if(err) console.log(err);
expect(res).to.have.status(200).and.have.property('body').and.have.keys(["items", "page", "perPage", "totalCount"]);
expect(res.body.items.length).to.equal(0);
done();
})
})
})
});