Skip to content

Commit

Permalink
Test initialization refactor (#254)
Browse files Browse the repository at this point in the history
  • Loading branch information
schmidt-sebastian committed Jul 12, 2018
1 parent a3d91e1 commit 9552c32
Show file tree
Hide file tree
Showing 13 changed files with 2,101 additions and 1,746 deletions.
124 changes: 64 additions & 60 deletions conformance/runner.js
Expand Up @@ -32,20 +32,20 @@ const document = require('../src/document')(reference.DocumentReference);
const DocumentSnapshot = document.DocumentSnapshot;
const convert = require('../src/convert');
const ResourcePath = require('../src/path').ResourcePath;

const firestore = new Firestore({
projectId: 'projectID',
sslCreds: grpc.credentials.createInsecure(),
timestampsInSnapshots: true,
keyFilename: './test/fake-certificate.json',
});
const createInstanceHelper = require('../test/util/helpers').createInstance;

/** List of test cases that are ignored. */
const ignoredRe = [];

/** If non-empty, list the test cases to run exclusively. */
const exclusiveRe = [];

// The project ID used in the conformance test protos.
const CONFORMANCE_TEST_PROJECT_ID = 'projectID';

// Firestore instance initialized by the test runner.
let firestore;

const docRef = function(path) {
const relativePath = ResourcePath.fromSlashSeparatedString(path).relativeName;
return firestore.doc(relativePath);
Expand All @@ -56,8 +56,18 @@ const collRef = function(path) {
return firestore.collection(relativePath);
};

const watchQuery =
collRef('projects/projectID/databases/(default)/documents/C').orderBy('a');
const watchQuery = function() {
return firestore.collection('C').orderBy('a');
};

const createInstance = function(overrides) {
return createInstanceHelper(
overrides, {projectId: CONFORMANCE_TEST_PROJECT_ID})
.then(firestoreClient => {
firestore = firestoreClient;
});
};


/** Converts JSON test data into JavaScript types suitable for the Node API. */
const convertInput = {
Expand Down Expand Up @@ -154,7 +164,7 @@ const convertInput = {
}

return new Firestore.QuerySnapshot(
watchQuery, readTime, docs.length, () => docs, () => changes);
watchQuery(), readTime, docs.length, () => docs, () => changes);
},
};

Expand Down Expand Up @@ -279,9 +289,9 @@ function runTest(spec) {
console.log(`Running Spec:\n${JSON.stringify(spec, null, 2)}\n`);

const updateTest = function(spec) {
firestore._firestoreClient._innerApiCalls.commit = commitHandler(spec);
const overrides = {commit: commitHandler(spec)};

return Promise.resolve().then(() => {
return createInstance(overrides).then(() => {
let varargs = [];

if (spec.jsonData) {
Expand All @@ -305,7 +315,7 @@ function runTest(spec) {
};

const queryTest = function(spec) {
firestore._firestoreClient._innerApiCalls.runQuery = queryHandler(spec);
const overrides = {runQuery: queryHandler(spec)};

const applyClause = function(query, clause) {
if (clause.select) {
Expand Down Expand Up @@ -337,9 +347,8 @@ function runTest(spec) {
return query;
};

let query = collRef(spec.collPath);

return Promise.resolve().then(() => {
return createInstance(overrides).then(() => {
let query = collRef(spec.collPath);
for (let clause of spec.clauses) {
query = applyClause(query, clause);
}
Expand All @@ -348,9 +357,9 @@ function runTest(spec) {
};

const deleteTest = function(spec) {
firestore._firestoreClient._innerApiCalls.commit = commitHandler(spec);
const overrides = {commit: commitHandler(spec)};

return Promise.resolve().then(() => {
return createInstance(overrides).then(() => {
if (spec.precondition) {
const precondition = convertInput.precondition(deleteSpec.precondition);
return docRef(spec.docRefPath).delete(precondition);
Expand All @@ -361,9 +370,9 @@ function runTest(spec) {
};

const setTest = function(spec) {
firestore._firestoreClient._innerApiCalls.commit = commitHandler(spec);
const overrides = {commit: commitHandler(spec)};

return Promise.resolve().then(() => {
return createInstance(overrides).then(() => {
const setOption = {};

if (spec.option && spec.option.all) {
Expand All @@ -381,19 +390,18 @@ function runTest(spec) {
};

const createTest = function(spec) {
firestore._firestoreClient._innerApiCalls.commit = commitHandler(spec);
const overrides = {commit: commitHandler(spec)};

return Promise.resolve().then(() => {
return createInstance(overrides).then(() => {
return docRef(spec.docRefPath)
.create(convertInput.argument(spec.jsonData));
});
};

const getTest = function(spec) {
firestore._firestoreClient._innerApiCalls.batchGetDocuments =
getHandler(spec);
const overrides = {batchGetDocuments: getHandler(spec)};

return Promise.resolve().then(() => {
return createInstance(overrides).then(() => {
return docRef(spec.docRefPath).get();
});
};
Expand All @@ -403,38 +411,38 @@ function runTest(spec) {

const writeStream = through.obj();

firestore._firestoreClient._innerApiCalls.listen = () => {
return duplexify.obj(through.obj(), writeStream);
};

return new Promise((resolve, reject) => {
const unlisten = watchQuery.onSnapshot(
actualSnap => {
const expectedSnapshot = expectedSnapshots.shift();
if (expectedSnapshot) {
if (!actualSnap.isEqual(
convertInput.snapshot(expectedSnapshot))) {
reject(
new Error('Expected and actual snapshots do not match.'));
}

if (expectedSnapshots.length === 0 || !spec.isError) {
unlisten();
resolve();
const overrides = {listen: () => duplexify.obj(through.obj(), writeStream)};

return createInstance(overrides).then(() => {
return new Promise((resolve, reject) => {
const unlisten = watchQuery().onSnapshot(
actualSnap => {
const expectedSnapshot = expectedSnapshots.shift();
if (expectedSnapshot) {
if (!actualSnap.isEqual(
convertInput.snapshot(expectedSnapshot))) {
reject(
new Error('Expected and actual snapshots do not match.'));
}

if (expectedSnapshots.length === 0 || !spec.isError) {
unlisten();
resolve();
}
} else {
reject(new Error('Received unexpected snapshot'));
}
} else {
reject(new Error('Received unexpected snapshot'));
}
},
err => {
assert.equal(expectedSnapshots.length, 0);
unlisten();
reject(err);
});

for (const response of spec.responses) {
writeStream.write(convertProto.listenRequest(response));
}
},
err => {
assert.equal(expectedSnapshots.length, 0);
unlisten();
reject(err);
});

for (const response of spec.responses) {
writeStream.write(convertProto.listenRequest(response));
}
});
});
};

Expand Down Expand Up @@ -509,10 +517,6 @@ describe('Conformance Tests', function() {
return testSuite.tests;
};

before(() => {
firestore._ensureClient();
});

for (let testCase of loadTestCases()) {
const isIgnored = ignoredRe.find(re => re.test(testCase.description));
const isExclusive = exclusiveRe.find(re => re.test(testCase.description));
Expand Down
7 changes: 1 addition & 6 deletions src/path.ts
Expand Up @@ -57,7 +57,6 @@ const FIELD_PATH_RE = /^[^*~/[\]]+$/;
* @class
*/
abstract class Path<T> {
private _formattedName: string|undefined = undefined;
/**
* Creates a new Path with the given segments.
*
Expand All @@ -74,11 +73,7 @@ abstract class Path<T> {
* @type {string}
*/
get formattedName(): string {
if (this._formattedName === undefined) {
this._formattedName = this.canonicalString();
}

return this._formattedName!;
return this.canonicalString()!;
}

abstract construct(segments: string[]|string): T;
Expand Down
101 changes: 47 additions & 54 deletions test/collection.js
Expand Up @@ -24,23 +24,13 @@ const is = require('is');
const Firestore = require('../src');
const DocumentReference =
require('../src/reference')(Firestore).DocumentReference;
const createInstance = require('../test/util/helpers').createInstance;

// Change the argument to 'console.log' to enable debug output.
Firestore.setLogFunction(() => {});

const PROJECT_ID = 'test-project';

function createInstance() {
let firestore = new Firestore({
projectId: PROJECT_ID,
sslCreds: grpc.credentials.createInsecure(),
timestampsInSnapshots: true,
keyFilename: './test/fake-certificate.json',
});

return firestore._ensureClient().then(() => firestore);
}

describe('Collection interface', function() {
let firestore;

Expand Down Expand Up @@ -101,54 +91,57 @@ describe('Collection interface', function() {
it('has add() method', function() {
const dbPrefix = `projects/${PROJECT_ID}/databases`;

firestore._firestoreClient._innerApiCalls.commit = function(
request, options, callback) {
// Verify that the document name uses an auto-generated id.
let docIdRe = new RegExp(
`${dbPrefix}/\\(default\\)/documents/collectionId/[a-zA-Z0-9]{20}`);
assert.ok(docIdRe.test(request.writes[0].update.name));
delete request.writes[0].update.name;

// Verify that the rest of the protobuf matches.
assert.deepEqual(request, {
database: dbPrefix + '/(default)',
writes: [
{
update: {
fields: {},
const overrides = {
commit: (request, options, callback) => {
// Verify that the document name uses an auto-generated id.
let docIdRe = new RegExp(
`${dbPrefix}/\\(default\\)/documents/collectionId/[a-zA-Z0-9]{20}`);
assert.ok(docIdRe.test(request.writes[0].update.name));
delete request.writes[0].update.name;

// Verify that the rest of the protobuf matches.
assert.deepEqual(request, {
database: dbPrefix + '/(default)',
writes: [
{
update: {
fields: {},
},
currentDocument: {
exists: false,
},
},
currentDocument: {
exists: false,
},
},
],
});
],
});

callback(null, {
commitTime: {
nanos: 0,
seconds: 0,
},
writeResults: [
{
updateTime: {
nanos: 0,
seconds: 0,
},
callback(null, {
commitTime: {
nanos: 0,
seconds: 0,
},
],
});
writeResults: [
{
updateTime: {
nanos: 0,
seconds: 0,
},
},
],
});
}
};

let collectionRef = firestore.collection('collectionId');
assert.ok(collectionRef.add);
let promise = collectionRef.add({});
assert.ok(is.instance(promise, Promise));

return promise.then(documentRef => {
assert.ok(is.instance(documentRef, DocumentReference));
assert.equal(collectionRef.id, 'collectionId');
assert.ok(documentRef.id.length, 20);
return createInstance(overrides).then(firestore => {
let collectionRef = firestore.collection('collectionId');
assert.ok(collectionRef.add);
let promise = collectionRef.add({});
assert.ok(is.instance(promise, Promise));

return promise.then(documentRef => {
assert.ok(is.instance(documentRef, DocumentReference));
assert.equal(collectionRef.id, 'collectionId');
assert.ok(documentRef.id.length, 20);
});
});
});

Expand Down

0 comments on commit 9552c32

Please sign in to comment.