azure-cosmos-js/test/functional/trigger.spec.ts

198 строки
6.8 KiB
TypeScript
Исходник Обычный вид История

import assert from "assert";
import { TriggerOperation, TriggerType } from "../../dist-esm";
import { TriggerDefinition, Container } from "../../dist-esm/client";
import { getTestContainer, removeAllDatabases } from "../common/TestHelpers";
Feature/object model refactor (#26) * Move foreach to async iterator * Mock out new APIs * remove legacy tests * remove old ntvs stuff for samples * Add shimmed implemention + bug fixes * Update (some) samples to use new OM * refactor interfaces into their own files * refactor om into new directory structure * small tweak to lib in gitignore * renamed document to item * update tests * Move Item/Permission/User tests * Remove Attachment from OM * Update item, container, database, and database account tests * Permission tests * User tests * Aggregate query tests moved to new OM * collectionNaming tests obsolete due to attachment/media * Update crosspartition test * Add encoding test * Update incremental feed tests * update proxy test * Update query test * update ruPerMind test * Update session tests * Update session container tests (moved to unit test) * Update SSL tests * Update UriFactory tests (moved to unit) * Update document client tests * Update authorization tests * Fix lint * Refactor of UDF test * Refactor trigger test * Refactor functional TTL test * Remove UriFactory * Type assertion due to intermediate implementation details * Query needs to support string * Support any overload * Query e2e tests * Spatial e2e test updated * Refactor functional sproc test * Add await to fix TS errors * Type assertion on container def for now * Remove offer tests for now * authorization tests updated * bug in test * Comment out and skip HashPartitionResolver test * Use UriFactory for urls * rids make me sad * types are fun * bugs in permission test * Symbol Shim for forEach * Fix user test * stringify the funciton bodys to avoid TypeScript weirdness * Support string body for UDF * Small bug in TTL test * Fix Authorization tests * remove bad options object * One more sproc fix * Need a blank object for parition key (if none specified) * One tests is broken still for now * Expose ErrorResponse * Handle undefined in forEach * Better error handling * Better error handling for crossParititon tests * Update tslint to catch dangling promises * Port over existing docs to TS files * Fix Mock toArray to promise based * Include tests in lint and fix errors * No assignment to Symbol.asyncIterator in node 10 * tslint fix * Remove unnecessary test (forEach is an iterable now) * no more generic database names in test * Index kind mistake * Missing promise * Shorten timeout (flakey test) * rename \w+s\.read to \w+s\.readAll * Move all #.get\w+ to #.get * Remove rid test. Pick up global timeout in auth test * Fix tslint * Fix test timeouts against production, except for TTL. Run TS tests directly * Add files * remove some collection/document mentions * fix sproc mistake from rename * Add CosmosClientOptions to export
2018-06-30 02:51:57 +03:00
const notFoundErrorCode = 404;
Feature/object model refactor (#26) * Move foreach to async iterator * Mock out new APIs * remove legacy tests * remove old ntvs stuff for samples * Add shimmed implemention + bug fixes * Update (some) samples to use new OM * refactor interfaces into their own files * refactor om into new directory structure * small tweak to lib in gitignore * renamed document to item * update tests * Move Item/Permission/User tests * Remove Attachment from OM * Update item, container, database, and database account tests * Permission tests * User tests * Aggregate query tests moved to new OM * collectionNaming tests obsolete due to attachment/media * Update crosspartition test * Add encoding test * Update incremental feed tests * update proxy test * Update query test * update ruPerMind test * Update session tests * Update session container tests (moved to unit test) * Update SSL tests * Update UriFactory tests (moved to unit) * Update document client tests * Update authorization tests * Fix lint * Refactor of UDF test * Refactor trigger test * Refactor functional TTL test * Remove UriFactory * Type assertion due to intermediate implementation details * Query needs to support string * Support any overload * Query e2e tests * Spatial e2e test updated * Refactor functional sproc test * Add await to fix TS errors * Type assertion on container def for now * Remove offer tests for now * authorization tests updated * bug in test * Comment out and skip HashPartitionResolver test * Use UriFactory for urls * rids make me sad * types are fun * bugs in permission test * Symbol Shim for forEach * Fix user test * stringify the funciton bodys to avoid TypeScript weirdness * Support string body for UDF * Small bug in TTL test * Fix Authorization tests * remove bad options object * One more sproc fix * Need a blank object for parition key (if none specified) * One tests is broken still for now * Expose ErrorResponse * Handle undefined in forEach * Better error handling * Better error handling for crossParititon tests * Update tslint to catch dangling promises * Port over existing docs to TS files * Fix Mock toArray to promise based * Include tests in lint and fix errors * No assignment to Symbol.asyncIterator in node 10 * tslint fix * Remove unnecessary test (forEach is an iterable now) * no more generic database names in test * Index kind mistake * Missing promise * Shorten timeout (flakey test) * rename \w+s\.read to \w+s\.readAll * Move all #.get\w+ to #.get * Remove rid test. Pick up global timeout in auth test * Fix tslint * Fix test timeouts against production, except for TTL. Run TS tests directly * Add files * remove some collection/document mentions * fix sproc mistake from rename * Add CosmosClientOptions to export
2018-06-30 02:51:57 +03:00
// Mock for trigger function bodies
declare var getContext: any;
describe("NodeJS CRUD Tests", function() {
this.timeout(process.env.MOCHA_TIMEOUT || 10000);
let container: Container;
Feature/object model refactor (#26) * Move foreach to async iterator * Mock out new APIs * remove legacy tests * remove old ntvs stuff for samples * Add shimmed implemention + bug fixes * Update (some) samples to use new OM * refactor interfaces into their own files * refactor om into new directory structure * small tweak to lib in gitignore * renamed document to item * update tests * Move Item/Permission/User tests * Remove Attachment from OM * Update item, container, database, and database account tests * Permission tests * User tests * Aggregate query tests moved to new OM * collectionNaming tests obsolete due to attachment/media * Update crosspartition test * Add encoding test * Update incremental feed tests * update proxy test * Update query test * update ruPerMind test * Update session tests * Update session container tests (moved to unit test) * Update SSL tests * Update UriFactory tests (moved to unit) * Update document client tests * Update authorization tests * Fix lint * Refactor of UDF test * Refactor trigger test * Refactor functional TTL test * Remove UriFactory * Type assertion due to intermediate implementation details * Query needs to support string * Support any overload * Query e2e tests * Spatial e2e test updated * Refactor functional sproc test * Add await to fix TS errors * Type assertion on container def for now * Remove offer tests for now * authorization tests updated * bug in test * Comment out and skip HashPartitionResolver test * Use UriFactory for urls * rids make me sad * types are fun * bugs in permission test * Symbol Shim for forEach * Fix user test * stringify the funciton bodys to avoid TypeScript weirdness * Support string body for UDF * Small bug in TTL test * Fix Authorization tests * remove bad options object * One more sproc fix * Need a blank object for parition key (if none specified) * One tests is broken still for now * Expose ErrorResponse * Handle undefined in forEach * Better error handling * Better error handling for crossParititon tests * Update tslint to catch dangling promises * Port over existing docs to TS files * Fix Mock toArray to promise based * Include tests in lint and fix errors * No assignment to Symbol.asyncIterator in node 10 * tslint fix * Remove unnecessary test (forEach is an iterable now) * no more generic database names in test * Index kind mistake * Missing promise * Shorten timeout (flakey test) * rename \w+s\.read to \w+s\.readAll * Move all #.get\w+ to #.get * Remove rid test. Pick up global timeout in auth test * Fix tslint * Fix test timeouts against production, except for TTL. Run TS tests directly * Add files * remove some collection/document mentions * fix sproc mistake from rename * Add CosmosClientOptions to export
2018-06-30 02:51:57 +03:00
beforeEach(async function() {
await removeAllDatabases();
container = await getTestContainer("trigger container");
});
describe("Validate Trigger CRUD", function() {
it("nativeApi Should do trigger CRUD operations successfully name based", async function() {
// read triggers
const { resources: triggers } = await container.scripts.triggers.readAll().fetchAll();
assert.equal(Array.isArray(triggers), true);
// create a trigger
const beforeCreateTriggersCount = triggers.length;
// tslint:disable:no-var-keyword
// tslint:disable:prefer-const
const triggerDefinition: TriggerDefinition = {
id: "sample trigger",
body: "serverScript() { var x = 10; }",
triggerType: TriggerType.Pre,
triggerOperation: TriggerOperation.All
};
// tslint:enable:no-var-keyword
// tslint:enable:prefer-const
const { resource: trigger } = await container.scripts.triggers.create(triggerDefinition);
assert.equal(trigger.id, triggerDefinition.id);
assert.equal(trigger.body, "serverScript() { var x = 10; }");
// read triggers after creation
const { resources: triggersAfterCreation } = await container.scripts.triggers.readAll().fetchAll();
assert.equal(
triggersAfterCreation.length,
beforeCreateTriggersCount + 1,
"create should increase the number of triggers"
);
// query triggers
const querySpec = {
query: "SELECT * FROM root r WHERE r.id=@id",
parameters: [
{
name: "@id",
value: triggerDefinition.id
}
]
};
const { resources: results } = await container.scripts.triggers.query(querySpec).fetchAll();
assert(results.length > 0, "number of results for the query should be > 0");
// replace trigger
// prettier-ignore
2019-03-07 23:32:56 +03:00
trigger.body = function () { const x = 20; };
const { resource: replacedTrigger } = await container.scripts.trigger(trigger.id).replace(trigger);
assert.equal(replacedTrigger.id, trigger.id);
assert.equal(replacedTrigger.body, "function () { const x = 20; }");
// read trigger
const { resource: triggerAfterReplace } = await container.scripts.trigger(replacedTrigger.id).read();
assert.equal(replacedTrigger.id, triggerAfterReplace.id);
// delete trigger
await await container.scripts.trigger(replacedTrigger.id).delete();
// read triggers after deletion
try {
await container.scripts.trigger(replacedTrigger.id).read();
assert.fail("Must fail to read after deletion");
} catch (err) {
assert.equal(err.code, notFoundErrorCode, "response should return error code 404");
}
Feature/object model refactor (#26) * Move foreach to async iterator * Mock out new APIs * remove legacy tests * remove old ntvs stuff for samples * Add shimmed implemention + bug fixes * Update (some) samples to use new OM * refactor interfaces into their own files * refactor om into new directory structure * small tweak to lib in gitignore * renamed document to item * update tests * Move Item/Permission/User tests * Remove Attachment from OM * Update item, container, database, and database account tests * Permission tests * User tests * Aggregate query tests moved to new OM * collectionNaming tests obsolete due to attachment/media * Update crosspartition test * Add encoding test * Update incremental feed tests * update proxy test * Update query test * update ruPerMind test * Update session tests * Update session container tests (moved to unit test) * Update SSL tests * Update UriFactory tests (moved to unit) * Update document client tests * Update authorization tests * Fix lint * Refactor of UDF test * Refactor trigger test * Refactor functional TTL test * Remove UriFactory * Type assertion due to intermediate implementation details * Query needs to support string * Support any overload * Query e2e tests * Spatial e2e test updated * Refactor functional sproc test * Add await to fix TS errors * Type assertion on container def for now * Remove offer tests for now * authorization tests updated * bug in test * Comment out and skip HashPartitionResolver test * Use UriFactory for urls * rids make me sad * types are fun * bugs in permission test * Symbol Shim for forEach * Fix user test * stringify the funciton bodys to avoid TypeScript weirdness * Support string body for UDF * Small bug in TTL test * Fix Authorization tests * remove bad options object * One more sproc fix * Need a blank object for parition key (if none specified) * One tests is broken still for now * Expose ErrorResponse * Handle undefined in forEach * Better error handling * Better error handling for crossParititon tests * Update tslint to catch dangling promises * Port over existing docs to TS files * Fix Mock toArray to promise based * Include tests in lint and fix errors * No assignment to Symbol.asyncIterator in node 10 * tslint fix * Remove unnecessary test (forEach is an iterable now) * no more generic database names in test * Index kind mistake * Missing promise * Shorten timeout (flakey test) * rename \w+s\.read to \w+s\.readAll * Move all #.get\w+ to #.get * Remove rid test. Pick up global timeout in auth test * Fix tslint * Fix test timeouts against production, except for TTL. Run TS tests directly * Add files * remove some collection/document mentions * fix sproc mistake from rename * Add CosmosClientOptions to export
2018-06-30 02:51:57 +03:00
});
});
describe("validate trigger functionality", function() {
const triggers: TriggerDefinition[] = [
{
id: "t1",
// tslint:disable:no-var-keyword
// tslint:disable:prefer-const
// tslint:disable:curly
// tslint:disable:no-string-throw
// tslint:disable:object-literal-shorthand
body: function() {
var item = getContext()
.getRequest()
.getBody();
item.id = item.id.toUpperCase() + "t1";
getContext()
.getRequest()
.setBody(item);
},
triggerType: TriggerType.Pre,
triggerOperation: TriggerOperation.All
},
{
id: "t2",
body: "function() { }", // trigger already stringified
triggerType: TriggerType.Pre,
triggerOperation: TriggerOperation.All
},
{
id: "t3",
body: function() {
const item = getContext()
.getRequest()
.getBody();
item.id = item.id.toLowerCase() + "t3";
getContext()
.getRequest()
.setBody(item);
},
triggerType: TriggerType.Pre,
triggerOperation: TriggerOperation.All
},
{
id: "response1",
body: function() {
const prebody = getContext()
.getRequest()
.getBody();
if (prebody.id !== "TESTING POST TRIGGERt1") throw "name mismatch";
const postbody = getContext()
.getResponse()
.getBody();
if (postbody.id !== "TESTING POST TRIGGERt1") throw "name mismatch";
},
triggerType: TriggerType.Post,
triggerOperation: TriggerOperation.All
},
{
id: "triggerOpType",
body: "function() { }",
triggerType: TriggerType.Post,
triggerOperation: TriggerOperation.Delete
}
];
// tslint:enable:no-var-keyword
// tslint:enable:prefer-const
// tslint:enable:curly
// tslint:enable:no-string-throw
// tslint:enable:object-literal-shorthand
it("should do trigger operations successfully with create", async function() {
for (const trigger of triggers) {
await container.scripts.triggers.create(trigger);
}
// create document
2019-03-07 23:32:56 +03:00
const { resource: document } = await container.items.create(
{ id: "doc1", key: "value" },
{ preTriggerInclude: "t1" }
);
assert.equal(document.id, "DOC1t1", "name should be capitalized");
2019-03-07 23:32:56 +03:00
const { resource: document2 } = await container.items.create(
{ id: "doc2", key2: "value2" },
{ preTriggerInclude: "t2" }
);
assert.equal(document2.id, "doc2", "name shouldn't change");
2019-03-07 23:32:56 +03:00
const { resource: document3 } = await container.items.create(
{ id: "Doc3", prop: "empty" },
{ preTriggerInclude: "t3" }
);
assert.equal(document3.id, "doc3t3");
2019-03-07 23:32:56 +03:00
const { resource: document4 } = await container.items.create(
{ id: "testing post trigger" },
{ postTriggerInclude: "response1", preTriggerInclude: "t1" }
);
assert.equal(document4.id, "TESTING POST TRIGGERt1");
2019-03-07 23:32:56 +03:00
const { resource: document5, headers } = await container.items.create(
{ id: "responseheaders" },
{ preTriggerInclude: "t1" }
);
assert.equal(document5.id, "RESPONSEHEADERSt1");
try {
await container.items.create({ id: "Docoptype" }, { postTriggerInclude: "triggerOpType" });
assert.fail("Must fail");
} catch (err) {
assert.equal(err.code, 400, "Must throw when using a DELETE trigger on a CREATE operation");
}
});
});
});